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

🚛 fix: Move Sealed Chats to New Code Environments (#15902)

Danny Avila4216de41c29c
diff --git a/CONTEXT.md b/CONTEXT.md
index 061c21700b..b390f49505 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -3,7 +3,7 @@
- **Scheduled run admission**: The claimed-occurrence phase that rehydrates the owner, validates current schedule policy and agent reachability, resolves files and MCP readiness, and only then competes for durable generation capacity. It owns cancellation and lease revalidation until a generation slot is reserved; a slow or failed readiness check never occupies generation capacity.
- **Attached code environment**: A principal- or deployment-authorized stateful workspace owned by an outbound `librechat-code` worker on a user-chosen machine or VM. LibreChat selects it and enforces approval policy, Code API authenticates and dispatches to it, and the worker's local sandbox and capability flags remain the final execution ceiling. The environment interface is runtime-neutral: native SRT, WSL2, Docker/NsJail, and future adapters expose the same workspace operations without leaking host paths or runtime configuration into agent tools.
-- **Conversation code-environment decision**: The immutable choice established by a conversation's first accepted submission between validated attached workspaces and continuing without an attached environment. Agent defaults and recent workspace preferences may suggest a draft choice, but only the persisted conversation decision authorizes attached workspace tool registration; later turns, retries, resumes, and alternate ingresses cannot upgrade or replace it.
+- **Conversation code-environment decision**: The immutable choice established by a conversation's first accepted submission between validated attached workspaces and continuing without an attached environment. Agent defaults and recent workspace preferences may suggest a draft choice, but only the persisted conversation decision authorizes attached workspace tool registration; later turns, retries, resumes, and alternate ingresses cannot upgrade or replace it. Runs persist a decision only for a conversation that does not store one yet, so no run writes its run-start decision back over a stored one. The one exception to immutability is the owner's explicit move, available where `statefulCodeSessions.conversationMoves.enabled` allows it: when an agent is pointed at a different attached environment after the chat was sealed, the owner may replace the decision's environments with the ones the agents now use, validated against the live worker. A move never changes the workspace of an environment the decision already covers, never upgrades a conversation that continues without an attached environment, and is refused while a generation is running, awaiting approval, or saving its response.
- **Agent run envelope**: the versioned, JSON-safe request contract created after ingress authentication and protocol validation but before agent, provider, tool, or MCP initialization. It carries only the validated protocol payload and the minimum trusted principal identifiers. The execution host rehydrates all runtime state from those identifiers.
- **Agent execution context**: runtime-only, transport-free state rehydrated beside an Agent run envelope. It contains the authenticated user, application configuration, normalized request metadata, and resolved conversation facts needed by initialization, but never Express request/response objects or serialized credentials.
- **Agent execution host**: the protocol-neutral module that owns run admission, disconnect cancellation, provider-start fencing, and terminal settlement. Protocol implementations execute behind its callback interface; HTTP adapters retain validation and final stream rendering.
diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.js
index 1cbac69ccb..6f8372072b 100644
--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js
+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js
@@ -251,6 +251,8 @@ jest.mock('@librechat/api', () => ({
...(codeWorkspaces !== undefined && { codeWorkspaces }),
};
},
+ resolvePersistableCodeEnvironmentDecision: (...args) =>
+ jest.requireActual('@librechat/api').resolvePersistableCodeEnvironmentDecision(...args),
getCodeWorkspaceSelections: jest.fn(),
createMCPRuntimeRequestBody: ({
messageId,
@@ -660,6 +662,32 @@ describe('createResponse controller', () => {
},
);
+ it('keeps the stored decision when a continued conversation is saved', async () => {
+ const api = require('@librechat/api');
+ const db = require('~/models');
+ api.validateResponseRequest.mockReturnValueOnce({
+ request: {
+ model: 'agent-123',
+ input: 'Hello',
+ stream: false,
+ store: true,
+ previous_response_id: 'previous',
+ },
+ });
+ db.getConvo.mockResolvedValueOnce({
+ conversationId: 'previous',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [{ environmentId: 'vm', workspaceId: 'projects' }],
+ });
+
+ await createResponse(req, res);
+
+ const saved = db.saveConvo.mock.calls.at(-1)[1];
+ expect(saved).toEqual(expect.objectContaining({ conversationId: 'previous' }));
+ expect(saved).not.toHaveProperty('codeEnvironmentMode');
+ expect(saved).not.toHaveProperty('codeWorkspaces');
+ });
+
it('enrolls, starts, and settles the remote execution lifecycle', async () => {
await createResponse(req, res);
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index 5b9b955257..d491d259fe 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -176,6 +176,7 @@ const {
isAgentRunCancellation,
getSummaryPartText,
markCompactionOutcome,
+ resolvePersistableCodeEnvironmentDecision,
} = require('@librechat/api');
const {
Run,
@@ -1969,7 +1970,12 @@ class AgentClient extends BaseClient {
collectAttachedCodeEnvironmentPolicySettings(topLevelAgents),
agentsEConfig?.toolApproval?.enabled !== false,
);
- const codeEnvironmentDecision = this.options.req._codeEnvironmentDecision;
+ const persistedCodeEnvironmentDecision = resolvePersistableCodeEnvironmentDecision({
+ conversationId: this.conversationId,
+ decision: this.options.req._codeEnvironmentDecision,
+ conversation: this.options.req.resolvedConversation,
+ requested: this.options.req.body,
+ });
return removeNullishValues(
Object.assign(
@@ -1984,12 +1990,7 @@ class AgentClient extends BaseClient {
imageDetail: this.options.imageDetail,
maxContextTokens: this.maxContextTokens,
codeApprovalMode,
- codeEnvironmentMode:
- codeEnvironmentDecision?.mode ?? this.options.req.body.codeEnvironmentMode,
- codeWorkspaces:
- codeEnvironmentDecision != null
- ? codeEnvironmentDecision.codeWorkspaces
- : this.options.req.body.codeWorkspaces,
+ ...persistedCodeEnvironmentDecision,
},
// TODO: PARSE OPTIONS BY PROVIDER, MAY CONTAIN SENSITIVE DATA
runOptions,
diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.js
index 8e63b061b1..1b0aa9c33c 100644
--- a/api/server/controllers/agents/client.test.js
+++ b/api/server/controllers/agents/client.test.js
@@ -99,6 +99,54 @@ describe('AgentClient code approval persistence', () => {
});
});
+ it('never writes its run-start decision over a stored one a move replaced', () => {
+ const client = Object.create(AgentClient.prototype);
+ client.agentConfigs = new Map();
+ client.conversationId = 'convo-1';
+ client.options = {
+ endpoint: EModelEndpoint.agents,
+ agent: { id: 'attached-agent' },
+ req: {
+ body: {},
+ _codeEnvironmentDecision: {
+ mode: 'attached',
+ codeWorkspaces: [{ environmentId: 'mac', workspaceId: 'primary' }],
+ },
+ resolvedConversation: {
+ conversationId: 'convo-1',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [{ environmentId: 'vm', workspaceId: 'projects' }],
+ },
+ config: { endpoints: { [EModelEndpoint.agents]: {} } },
+ },
+ };
+
+ const saveOptions = client.getSaveOptions();
+ expect(saveOptions).not.toHaveProperty('codeEnvironmentMode');
+ expect(saveOptions).not.toHaveProperty('codeWorkspaces');
+ });
+
+ it('records only the mode a legacy conversation inferred', () => {
+ const client = Object.create(AgentClient.prototype);
+ client.agentConfigs = new Map();
+ client.conversationId = 'convo-1';
+ const codeWorkspaces = [{ environmentId: 'mac', workspaceId: 'primary' }];
+ client.options = {
+ endpoint: EModelEndpoint.agents,
+ agent: { id: 'attached-agent' },
+ req: {
+ body: {},
+ _codeEnvironmentDecision: { mode: 'attached', codeWorkspaces },
+ resolvedConversation: { conversationId: 'convo-1', codeWorkspaces },
+ config: { endpoints: { [EModelEndpoint.agents]: {} } },
+ },
+ };
+
+ const saveOptions = client.getSaveOptions();
+ expect(saveOptions.codeEnvironmentMode).toBe('attached');
+ expect(saveOptions).not.toHaveProperty('codeWorkspaces');
+ });
+
it('does not combine a normalized no-attached mode with stale request selections', () => {
const client = Object.create(AgentClient.prototype);
client.agentConfigs = new Map();
diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js
index b5da862f9c..8d8612238a 100644
--- a/api/server/controllers/agents/responses.js
+++ b/api/server/controllers/agents/responses.js
@@ -83,6 +83,7 @@ const {
waitForAgentExecutionWrites,
resolveToolRoleGrants,
resolveConversationCodeEnvironmentDecision,
+ resolvePersistableCodeEnvironmentDecision,
createTerminalRunErrorObserver,
} = require('@librechat/api');
const {
@@ -446,16 +447,10 @@ async function saveResponseOutput(
* @param {string} conversationId
* @param {string} agentId
* @param {object} agent
+ * @param {import('@librechat/api').ConversationCodeEnvironmentDecision} codeEnvironmentDecision
* @returns {Promise<void>}
*/
-async function saveConversation(
- req,
- conversationId,
- agentId,
- agent,
- codeEnvironmentMode,
- codeWorkspaces,
-) {
+async function saveConversation(req, conversationId, agentId, agent, codeEnvironmentDecision) {
const title = resolveConversationTitle(req, agent?.name || 'Open Responses Conversation');
await db.saveConvo(
{
@@ -468,8 +463,11 @@ async function saveConversation(
conversationId,
endpoint: EModelEndpoint.agents,
agent_id: agentId,
- codeEnvironmentMode,
- ...(codeWorkspaces !== undefined && { codeWorkspaces }),
+ ...resolvePersistableCodeEnvironmentDecision({
+ conversationId,
+ decision: codeEnvironmentDecision,
+ conversation: req.resolvedConversation,
+ }),
...(title != null && { title }),
model: agent?.model,
},
@@ -1360,14 +1358,7 @@ const executeResponse = async (envelope, { req, res }) => {
if (request.store === true) {
try {
// Save conversation
- await saveConversation(
- req,
- conversationId,
- agentId,
- agent,
- codeEnvironmentDecision.mode,
- codeEnvironmentDecision.codeWorkspaces,
- );
+ await saveConversation(req, conversationId, agentId, agent, codeEnvironmentDecision);
// Save input messages
await saveInputMessages(req, conversationId, inputMessages, agentId);
@@ -1599,14 +1590,7 @@ const executeResponse = async (envelope, { req, res }) => {
if (request.store === true) {
try {
- await saveConversation(
- req,
- conversationId,
- agentId,
- agent,
- codeEnvironmentDecision.mode,
- codeEnvironmentDecision.codeWorkspaces,
- );
+ await saveConversation(req, conversationId, agentId, agent, codeEnvironmentDecision);
await saveInputMessages(req, conversationId, inputMessages, agentId);
diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.js
index 0ef6122842..59f58772a5 100644
--- a/api/server/routes/__tests__/config.spec.js
+++ b/api/server/routes/__tests__/config.spec.js
@@ -354,6 +354,36 @@ describe('GET /api/config', () => {
expect(response.body.codeEnvironmentDecisionVersion).toBeUndefined();
});
+ it('does not advertise conversation moves unless the effective policy enables them', async () => {
+ mockGetAppConfig.mockResolvedValue(baseAppConfig);
+ const app = createApp(mockUser);
+
+ const response = await request(app).get('/api/config');
+
+ expect(response.body.codeEnvironmentMoveVersion).toBeUndefined();
+ });
+
+ it('advertises enabled conversation moves regardless of decision activation', async () => {
+ mockGetAppConfig.mockResolvedValue({
+ ...baseAppConfig,
+ endpoints: {
+ agents: {
+ statefulCodeSessions: {
+ allowedEnvironments: ['user'],
+ conversationMoves: { enabled: true },
+ },
+ },
+ },
+ });
+ delete process.env.CODE_ENVIRONMENT_DECISION_VERSION;
+ const app = createApp(mockUser);
+
+ const response = await request(app).get('/api/config');
+
+ expect(response.body.codeEnvironmentDecisionVersion).toBeUndefined();
+ expect(response.body.codeEnvironmentMoveVersion).toBe(1);
+ });
+
it('advertises code environment decisions only after deployment-wide activation', async () => {
mockGetAppConfig.mockResolvedValue(baseAppConfig);
process.env.CODE_ENVIRONMENT_DECISION_VERSION = '1';
diff --git a/api/server/routes/code-environments.js b/api/server/routes/code-environments.js
index 8f885091e3..c771b98dcf 100644
--- a/api/server/routes/code-environments.js
+++ b/api/server/routes/code-environments.js
@@ -1,5 +1,6 @@
const express = require('express');
const {
+ GenerationJobManager,
createCodeEnvironmentHttpHandlers,
codeEnvironmentPairingLimiter,
codeEnvironmentStatusIpLimiter,
@@ -19,6 +20,11 @@ function getHandlers() {
getAppConfig,
registry: getCodeEnvironmentRegistry(),
principalIsActive: db.isAgentTriggerPrincipalActive,
+ conversations: {
+ get: db.getConvo,
+ replaceDecision: db.replaceConvoCodeEnvironmentDecision,
+ },
+ generations: GenerationJobManager,
});
}
return handlers;
@@ -43,5 +49,11 @@ router.patch('/:environmentId/settings', (req, res, next) =>
getHandlers().updateSettings(req, res, next),
);
router.delete('/:environmentId', (req, res, next) => getHandlers().remove(req, res, next));
+router.patch(
+ '/conversations/:conversationId/decision',
+ codeEnvironmentStatusIpLimiter,
+ codeEnvironmentStatusLimiter,
+ (req, res, next) => getHandlers().moveConversationDecision(req, res, next),
+);
module.exports = router;
diff --git a/api/server/routes/code-environments.test.js b/api/server/routes/code-environments.test.js
index a9525dd602..c236a0ddb2 100644
--- a/api/server/routes/code-environments.test.js
+++ b/api/server/routes/code-environments.test.js
@@ -34,6 +34,19 @@ const mockHandlers = {
),
updateSettings: jest.fn((_req, res) => res.status(200).json({ environment: { id: 'code-1' } })),
remove: jest.fn((_req, res) => res.status(200).json({ environment: { id: 'code-1' } })),
+ moveConversationDecision: jest.fn((_req, res) =>
+ res.status(200).json({ conversationId: 'convo-1' }),
+ ),
+};
+const mockGenerationJobManager = {
+ getJob: jest.fn(),
+ getCleanupBlockingJobIdsForConversations: jest.fn(),
+};
+let mockHandlerDeps;
+const mockModels = {
+ isAgentTriggerPrincipalActive: jest.fn(),
+ getConvo: jest.fn(),
+ replaceConvoCodeEnvironmentDecision: jest.fn(),
};
jest.mock('@librechat/data-schemas', () => ({
@@ -41,8 +54,12 @@ jest.mock('@librechat/data-schemas', () => ({
}));
jest.mock('@librechat/api', () => ({
+ GenerationJobManager: mockGenerationJobManager,
createCodeEnvironmentRegistry: jest.fn(() => mockRegistry),
- createCodeEnvironmentHttpHandlers: jest.fn(() => mockHandlers),
+ createCodeEnvironmentHttpHandlers: jest.fn((deps) => {
+ mockHandlerDeps = deps;
+ return mockHandlers;
+ }),
codeEnvironmentPairingLimiter: mockCodeEnvironmentPairingLimiter,
codeEnvironmentStatusIpLimiter: mockCodeEnvironmentStatusIpLimiter,
codeEnvironmentStatusLimiter: mockCodeEnvironmentStatusLimiter,
@@ -56,7 +73,7 @@ jest.mock('~/server/services/Config', () => ({
getAppConfig: jest.fn(),
getCodeEnvironmentRegistry: mockGetCodeEnvironmentRegistry,
}));
-jest.mock('~/models', () => ({ isAgentTriggerPrincipalActive: jest.fn() }));
+jest.mock('~/models', () => mockModels);
function createApp() {
delete require.cache[require.resolve('./code-environments')];
@@ -132,4 +149,23 @@ describe('code environment routes', () => {
expect(middlewareCalls).toEqual(['jwt']);
expect(mockHandlers.updateSettings).toHaveBeenCalledTimes(1);
});
+
+ it('rate-limits an authenticated owner moving a conversation code environment', async () => {
+ await request(createApp())
+ .patch('/api/code-environments/conversations/convo-1/decision')
+ .send({ from: [], to: [] })
+ .expect(200, { conversationId: 'convo-1' });
+
+ expect(middlewareCalls).toEqual(['jwt', 'status-ip-limit', 'status-limit']);
+ expect(mockHandlers.moveConversationDecision).toHaveBeenCalledTimes(1);
+ });
+
+ it('gives the handlers owner-scoped conversation reads and conversation-scoped generations', async () => {
+ await request(createApp()).get('/api/code-environments').expect(200);
+
+ const { conversations, generations } = mockHandlerDeps;
+ expect(conversations.get).toBe(mockModels.getConvo);
+ expect(conversations.replaceDecision).toBe(mockModels.replaceConvoCodeEnvironmentDecision);
+ expect(generations).toBe(mockGenerationJobManager);
+ });
});
diff --git a/api/server/routes/config.js b/api/server/routes/config.js
index 99ab46ad4e..b5ebdb9d61 100644
--- a/api/server/routes/config.js
+++ b/api/server/routes/config.js
@@ -13,6 +13,7 @@ const {
isFileSnapshotEnabled,
getEndpointsDropParamsMap,
resolveCodeEnvironmentDecisionVersion,
+ resolveCodeEnvironmentMoveVersion,
} = require('@librechat/api');
const { EModelEndpoint, defaultSocialLogins } = require('librechat-data-provider');
const { logger, getTenantId, SystemCapabilities } = require('@librechat/data-schemas');
@@ -253,6 +254,7 @@ router.get('/', async function (req, res) {
const codeEnvironmentDecisionVersion = resolveCodeEnvironmentDecisionVersion(
process.env.CODE_ENVIRONMENT_DECISION_VERSION,
);
+ const codeEnvironmentMoveVersion = resolveCodeEnvironmentMoveVersion(appConfig);
const endpointsDropParamsMap = getEndpointsDropParamsMap(appConfig?.endpoints);
@@ -314,6 +316,7 @@ router.get('/', async function (req, res) {
insightsEnabled: isEnabled(process.env.ENABLE_INSIGHTS),
compactionEnabled: appConfig?.summarization?.enabled !== false,
...(codeEnvironmentDecisionVersion != null ? { codeEnvironmentDecisionVersion } : {}),
+ ...(codeEnvironmentMoveVersion != null ? { codeEnvironmentMoveVersion } : {}),
...(cloudFront ? { cloudFront } : {}),
...(rum ? { rum } : {}),
fileUploadSseEnabled: isEnabled(process.env.FILE_UPLOAD_SSE_ENABLED),
diff --git a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx
index e7f0560f27..d71265f96c 100644
--- a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx
+++ b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx
@@ -1,11 +1,23 @@
+import { useState } from 'react';
import * as Ariakit from '@ariakit/react';
-import { Check, ChevronDown, Folder, FolderX } from 'lucide-react';
-import { TooltipAnchor, composerControlClasses } from '@librechat/client';
+import { Check, ChevronDown, Folder, FolderSync, FolderX } from 'lucide-react';
+import { TooltipAnchor, composerControlClasses, useToastContext } from '@librechat/client';
import type { CodeWorkspaceSelection, TConversation } from 'librechat-data-provider';
import type { SetterOrUpdater } from 'recoil';
-import type { CodeWorkspaceResult, TranslationKeys } from '~/hooks';
+import type {
+ CodeWorkspaceEnvironmentResult,
+ CodeWorkspaceRelocation,
+ CodeWorkspaceResult,
+ TranslationKeys,
+} from '~/hooks';
+import {
+ cn,
+ codeWorkspaceErrorKeys,
+ getCodeWorkspaceErrorReason,
+ getResponseStatus,
+} from '~/utils';
+import { useMoveConversationCodeEnvironmentMutation } from '~/data-provider';
import { useLocalize } from '~/hooks';
-import { cn } from '~/utils';
const stateLabels: Partial<Record<CodeWorkspaceResult['state'], TranslationKeys>> = {
loading: 'com_ui_code_workspace_loading',
@@ -16,6 +28,112 @@ const stateLabels: Partial<Record<CodeWorkspaceResult['state'], TranslationKeys>
without_attached: 'com_ui_code_workspace_without_attached',
};
+const headingClasses = 'px-2.5 py-1.5 text-xs font-medium text-text-secondary';
+
+const menuItemClasses = (selected = false) =>
+ cn(
+ 'group flex w-full cursor-pointer items-start gap-3 rounded-lg px-2.5 py-2',
+ 'outline-none transition-colors duration-theme-fast',
+ 'hover:bg-surface-hover data-[active-item]:bg-surface-hover',
+ selected && 'bg-surface-active-alt',
+ );
+
+/** A stale view of the decision recovers on reload; the other reasons explain themselves. */
+function moveErrorKey(error: unknown): TranslationKeys {
+ const reason = getCodeWorkspaceErrorReason(error);
+ if (reason === 'locked') return 'com_ui_code_workspace_move_stale';
+ if (reason != null) return codeWorkspaceErrorKeys[reason];
+ if (getResponseStatus(error) === 409) return 'com_ui_code_workspace_move_busy';
+ return 'com_ui_code_workspace_move_error';
+}
+
+function describeRelocation(
+ relocation: CodeWorkspaceRelocation,
+ localize: ReturnType<typeof useLocalize>,
+): { label: string; info: string } {
+ const targetNames = relocation.targets
+ .map(({ environment }) => environment.name ?? environment.id)
+ .join(', ');
+ const previousNames = relocation.previous.map(({ id, name }) => name ?? id).join(', ');
+ let info = localize('com_ui_code_workspace_move_info', { 0: previousNames, 1: targetNames });
+ if (relocation.targets.length === 0) {
+ info = localize('com_ui_code_workspace_move_info_removed', { 0: previousNames });
+ } else if (!previousNames) {
+ info = localize('com_ui_code_workspace_move_info_added', { 0: targetNames });
+ }
+ return {
+ label:
+ relocation.targets.length === 1
+ ? localize('com_ui_code_workspace_move_to', { 0: targetNames })
+ : localize('com_ui_code_workspace_move'),
+ info,
+ };
+}
+
+/** A sole advertised workspace is the only valid pick, so it counts as chosen until changed. */
+function chosenWorkspaceId(
+ target: CodeWorkspaceEnvironmentResult,
+ choices: Record<string, string>,
+): string | undefined {
+ const choice = choices[target.environment.id];
+ if (choice != null && target.workspaces.some(({ id }) => id === choice)) return choice;
+ return target.workspaces.length === 1 ? target.workspaces[0].id : undefined;
+}
+
+function EnvironmentWorkspaces({
+ environment,
+ workspaces,
+ emptyLabel,
+ hideOnClick,
+ isSelected,
+ onSelect,
+}: {
+ environment: CodeWorkspaceEnvironmentResult['environment'];
+ workspaces: CodeWorkspaceEnvironmentResult['workspaces'];
+ emptyLabel: string;
+ hideOnClick: boolean;
+ isSelected: (workspaceId: string) => boolean;
+ onSelect: (selection: CodeWorkspaceSelection) => void;
+}) {
+ return (
+ <div>
+ <Ariakit.MenuHeading render={<div />} className={headingClasses}>
+ {environment.name ?? environment.id}
+ </Ariakit.MenuHeading>
+ {workspaces.length === 0 && (
+ <div className="px-2.5 py-2 text-sm text-text-secondary">{emptyLabel}</div>
+ )}
+ {workspaces.map((descriptor) => {
+ const selected = isSelected(descriptor.id);
+ return (
+ <Ariakit.MenuItemRadio
+ key={descriptor.id}
+ name={`codeWorkspace:${environment.id}`}
+ value={descriptor.id}
+ checked={selected}
+ hideOnClick={hideOnClick}
+ onChange={() => onSelect({ environmentId: environment.id, workspaceId: descriptor.id })}
+ className={menuItemClasses(selected)}
+ >
+ <Folder className="mt-0.5 size-4 shrink-0 text-text-secondary" aria-hidden="true" />
+ <div className="min-w-0 flex-1 text-left">
+ <div className="truncate text-sm font-medium text-text-primary">
+ {descriptor.name ?? descriptor.id}
+ </div>
+ {descriptor.name && (
+ <p className="truncate text-xs text-text-secondary">{descriptor.id}</p>
+ )}
+ </div>
+ {selected && (
+ <Check className="mt-0.5 size-4 shrink-0 text-text-primary" aria-hidden="true" />
+ )}
+ </Ariakit.MenuItemRadio>
+ );
+ })}
+ </div>
+ );
+}
+
export default function CodeWorkspaceMenu({
setConversation,
workspace,
@@ -26,11 +144,18 @@ export default function CodeWorkspaceMenu({
disabled: boolean;
}) {
const localize = useLocalize();
+ const { showToast } = useToastContext();
const menuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' });
const isOpen = menuStore.useState('open');
+ const moveMutation = useMoveConversationCodeEnvironmentMutation();
+ const [moveDraft, setMoveDraft] = useState<{
+ conversationId: string;
+ workspaces: Record<string, string>;
+ } | null>(null);
if (!workspace.required) return null;
+ const { relocation } = workspace;
const environmentIds = new Set(workspace.environments.map(({ environment }) => environment.id));
const selectWorkspace = (selection: CodeWorkspaceSelection) => {
workspace.rememberSelection(selection);
@@ -83,7 +208,7 @@ export default function CodeWorkspaceMenu({
? FolderX
: Folder;
- if (workspace.locked) {
+ if (workspace.locked && relocation == null) {
if (workspace.canSubmit) return null;
const recovery = localize('com_ui_code_workspace_locked_recovery');
return (
@@ -104,27 +229,71 @@ export default function CodeWorkspaceMenu({
);
}
+ const relocationText = relocation == null ? null : describeRelocation(relocation, localize);
+ /** Choices belong to the chat they were made in; another relocatable chat starts undecided. */
+ const moveChoices =
+ relocation != null && moveDraft?.conversationId === relocation.conversationId
+ ? moveDraft.workspaces
+ : {};
+ /** Every target needs a workspace, so the whole move lands in one validated write. */
+ const chosenTargets =
+ relocation?.targets.flatMap((target) => {
+ const workspaceId = chosenWorkspaceId(target, moveChoices);
+ return workspaceId == null ? [] : [{ environmentId: target.environment.id, workspaceId }];
+ }) ?? [];
+ const moveReady = relocation != null && chosenTargets.length === relocation.targets.length;
+ const confirmMove = () => {
+ if (relocation == null || !moveReady) return;
+ moveMutation.mutate(
+ {
+ conversationId: relocation.conversationId,
+ from: relocation.from,
+ to: [...relocation.retained, ...chosenTargets],
+ },
+ {
+ onSuccess: ({ conversationId, codeEnvironmentMode, codeWorkspaces }) => {
+ chosenTargets.forEach((selection) => workspace.rememberSelection(selection));
+ setMoveDraft(null);
+ setConversation((current) =>
+ current?.conversationId === conversationId
+ ? { ...current, codeEnvironmentMode, codeWorkspaces }
+ : current,
+ );
+ },
+ onError: (error) => {
+ showToast({ message: localize(moveErrorKey(error)), status: 'error' });
+ },
+ },
+ );
+ };
+ const buttonDisabled = disabled || moveMutation.isLoading;
+ const ButtonIcon = relocationText == null ? Icon : FolderSync;
+
return (
<Ariakit.MenuProvider store={menuStore}>
<TooltipAnchor
- description={localize('com_ui_code_workspace')}
+ description={relocationText?.info ?? localize('com_ui_code_workspace')}
disabled={isOpen}
render={
<Ariakit.MenuButton
- disabled={disabled}
- data-testid="code-workspace"
- aria-label={`${localize('com_ui_code_workspace')}: ${label}`}
+ disabled={buttonDisabled}
+ data-testid={relocationText == null ? 'code-workspace' : 'code-workspace-move'}
+ aria-label={
+ relocationText == null
+ ? `${localize('com_ui_code_workspace')}: ${label}`
+ : `${relocationText.label}. ${relocationText.info}`
+ }
className={cn(
composerControlClasses(),
'min-w-0 max-w-full px-2.5 md:px-theme-normal',
isOpen && 'bg-surface-hover',
- disabled && 'cursor-not-allowed opacity-50',
+ buttonDisabled && 'cursor-not-allowed opacity-50',
)}
/>
}
>
- <Icon className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
- <span className="min-w-0 max-w-[12rem] truncate">{label}</span>
+ <ButtonIcon className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
+ <span className="min-w-0 max-w-[12rem] truncate">{relocationText?.label ?? label}</span>
<ChevronDown
className={cn(
'size-3 shrink-0 text-text-secondary transition-transform',
@@ -145,96 +314,90 @@ export default function CodeWorkspaceMenu({
'scale-95 data-[leave]:scale-95 data-[leave]:opacity-0',
)}
>
- <Ariakit.MenuHeading
- render={<div />}
- className="px-2.5 py-1.5 text-xs font-medium text-text-secondary"
- >
- {localize('com_ui_code_environment')}
- </Ariakit.MenuHeading>
- {workspace.supportsEnvironmentDecisions && (
- <Ariakit.MenuItemRadio
- name="codeEnvironmentMode"
- value="without_attached"
- checked={workspace.mode === 'without_attached'}
- hideOnClick={true}
- onChange={selectWithoutAttached}
- className={cn(
- 'group flex w-full cursor-pointer items-start gap-3 rounded-lg px-2.5 py-2',
- 'outline-none transition-colors duration-theme-fast',
- 'hover:bg-surface-hover data-[active-item]:bg-surface-hover',
- workspace.mode === 'without_attached' && 'bg-surface-active-alt',
- )}
- >
- <FolderX className="mt-0.5 size-4 shrink-0 text-text-secondary" aria-hidden="true" />
- <div className="min-w-0 flex-1 text-left">
- <div className="truncate text-sm font-medium text-text-primary">
- {localize('com_ui_code_workspace_without_attached')}
- </div>
- <p className="text-xs text-text-secondary">
- {localize('com_ui_code_workspace_without_attached_info')}
- </p>
- </div>
- {workspace.mode === 'without_attached' && (
- <Check className="mt-0.5 size-4 shrink-0 text-text-primary" aria-hidden="true" />
- )}
- </Ariakit.MenuItemRadio>
- )}
- {workspace.environments.map(({ environment, state, workspaces, selected }) => (
- <div key={environment.id}>
- <Ariakit.MenuHeading
- render={<div />}
- className="px-2.5 py-1.5 text-xs font-medium text-text-secondary"
+ {relocation != null && relocationText != null ? (
+ <>
+ <Ariakit.MenuHeading render={<div />} className={headingClasses}>
+ {localize('com_ui_code_workspace_move')}
+ </Ariakit.MenuHeading>
+ <p className="px-2.5 pb-2 text-xs text-text-secondary">{relocationText.info}</p>
+ {relocation.targets.map((target) => (
+ <EnvironmentWorkspaces
+ key={target.environment.id}
+ environment={target.environment}
+ workspaces={target.workspaces}
+ emptyLabel={localize('com_ui_code_workspace_unavailable')}
+ hideOnClick={false}
+ isSelected={(workspaceId) => chosenWorkspaceId(target, moveChoices) === workspaceId}
+ onSelect={({ environmentId, workspaceId }) =>
+ setMoveDraft({
+ conversationId: relocation.conversationId,
+ workspaces: { ...moveChoices, [environmentId]: workspaceId },
+ })
+ }
+ />
+ ))}
+ <Ariakit.MenuSeparator className="my-1 h-0 w-full border-t border-border-light" />
+ <Ariakit.MenuItem
+ disabled={!moveReady || moveMutation.isLoading}
+ hideOnClick={true}
+ onClick={confirmMove}
+ className={cn(
+ menuItemClasses(),
+ 'items-center aria-disabled:cursor-not-allowed aria-disabled:opacity-50',
+ )}
>
- {environment.name ?? environment.id}
+ <FolderSync className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
+ <span className="min-w-0 flex-1 truncate text-left text-sm font-medium text-text-primary">
+ {relocationText.label}
+ </span>
+ </Ariakit.MenuItem>
+ </>
+ ) : (
+ <>
+ <Ariakit.MenuHeading render={<div />} className={headingClasses}>
+ {localize('com_ui_code_environment')}
</Ariakit.MenuHeading>
- {workspaces.length === 0 && (
- <div className="px-2.5 py-2 text-sm text-text-secondary">
- {localize(stateLabels[state] ?? 'com_ui_code_workspace_unavailable')}
- </div>
- )}
- {workspaces.map((descriptor) => {
- const isSelected =
- workspace.mode === 'attached' && descriptor.id === selected?.workspaceId;
- return (
- <Ariakit.MenuItemRadio
- key={descriptor.id}
- name={`codeWorkspace:${environment.id}`}
- value={descriptor.id}
- checked={isSelected}
- hideOnClick={true}
- onChange={() =>
- selectWorkspace({ environmentId: environment.id, workspaceId: descriptor.id })
- }
- className={cn(
- 'group flex w-full cursor-pointer items-start gap-3 rounded-lg px-2.5 py-2',
- 'outline-none transition-colors duration-theme-fast',
- 'hover:bg-surface-hover data-[active-item]:bg-surface-hover',
- isSelected && 'bg-surface-active-alt',
- )}
- >
- <Folder
- className="mt-0.5 size-4 shrink-0 text-text-secondary"
- aria-hidden="true"
- />
- <div className="min-w-0 flex-1 text-left">
- <div className="truncate text-sm font-medium text-text-primary">
- {descriptor.name ?? descriptor.id}
- </div>
- {descriptor.name && (
- <p className="truncate text-xs text-text-secondary">{descriptor.id}</p>
- )}
+ {workspace.supportsEnvironmentDecisions && (
+ <Ariakit.MenuItemRadio
+ name="codeEnvironmentMode"
+ value="without_attached"
+ checked={workspace.mode === 'without_attached'}
+ hideOnClick={true}
+ onChange={selectWithoutAttached}
+ className={menuItemClasses(workspace.mode === 'without_attached')}
+ >
+ <FolderX
+ className="mt-0.5 size-4 shrink-0 text-text-secondary"
+ aria-hidden="true"
+ />
+ <div className="min-w-0 flex-1 text-left">
+ <div className="truncate text-sm font-medium text-text-primary">
+ {localize('com_ui_code_workspace_without_attached')}
</div>
- {isSelected && (
- <Check
- className="mt-0.5 size-4 shrink-0 text-text-primary"
- aria-hidden="true"
- />
- )}
- </Ariakit.MenuItemRadio>
- );
- })}
- </div>
- ))}
+ <p className="text-xs text-text-secondary">
+ {localize('com_ui_code_workspace_without_attached_info')}
+ </p>
+ </div>
+ {workspace.mode === 'without_attached' && (
+ <Check className="mt-0.5 size-4 shrink-0 text-text-primary" aria-hidden="true" />
+ )}
+ </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}
+ />
+ ))}
+ </>
+ )}
</Ariakit.Menu>
</Ariakit.MenuProvider>
);
diff --git a/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx b/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx
index f6fd8cc580..29b31609f0 100644
--- a/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx
@@ -1,9 +1,21 @@
+import { AxiosError } from 'axios';
import userEvent from '@testing-library/user-event';
-import { render, screen } from '@testing-library/react';
+import { dataService } from 'librechat-data-provider';
+import { render, screen, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TConversation } from 'librechat-data-provider';
+import type { AxiosResponse } from 'axios';
import type { CodeWorkspaceResult } from '~/hooks';
import CodeWorkspaceMenu from '../CodeWorkspaceMenu';
+const mockShowToast = jest.fn();
+
+jest.mock('librechat-data-provider', () => {
+ const actual =
+ jest.requireActual<typeof import('librechat-data-provider')>('librechat-data-provider');
+ return { ...actual, dataService: { ...actual.dataService } };
+});
+
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
}));
@@ -12,6 +24,7 @@ jest.mock('@librechat/client', () => {
const { cloneElement } = jest.requireActual('react');
return {
composerControlClasses: () => 'composer-control',
+ useToastContext: () => ({ showToast: mockShowToast }),
TooltipAnchor: ({
render,
children,
@@ -60,10 +73,24 @@ function workspace(overrides: Partial<CodeWorkspaceResult> = {}): CodeWorkspaceR
};
}
+function renderMenu(ui: React.ReactElement) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const wrap = (element: React.ReactElement) => (
+ <QueryClientProvider client={queryClient}>{element}</QueryClientProvider>
+ );
+ const result = render(wrap(ui));
+ return {
+ ...result,
+ rerenderMenu: (element: React.ReactElement) => result.rerender(wrap(element)),
+ };
+}
+
describe('CodeWorkspaceMenu', () => {
test('shows a suggested workspace without committing the conversation decision', () => {
const setConversation = jest.fn();
- render(
+ renderMenu(
<CodeWorkspaceMenu
setConversation={setConversation}
workspace={workspace()}
@@ -77,7 +104,7 @@ describe('CodeWorkspaceMenu', () => {
test('allows working without an attached workspace even while the worker is unavailable', async () => {
const setConversation = jest.fn();
- render(
+ renderMenu(
<CodeWorkspaceMenu
setConversation={setConversation}
workspace={workspace({
@@ -109,7 +136,7 @@ describe('CodeWorkspaceMenu', () => {
});
test('does not offer selection-less decisions before the API advertises support', async () => {
- render(
+ renderMenu(
<CodeWorkspaceMenu
setConversation={jest.fn()}
workspace={workspace({ supportsEnvironmentDecisions: false })}
@@ -128,7 +155,7 @@ describe('CodeWorkspaceMenu', () => {
test('commits an explicit attached-workspace choice only when the user selects it', async () => {
const setConversation = jest.fn();
const rememberSelection = jest.fn();
- render(
+ renderMenu(
<CodeWorkspaceMenu
setConversation={setConversation}
workspace={workspace({ mode: undefined, state: 'choose', rememberSelection })}
@@ -152,7 +179,7 @@ describe('CodeWorkspaceMenu', () => {
});
test('does not mark a suggested workspace selected in no-attached mode', async () => {
- render(
+ renderMenu(
<CodeWorkspaceMenu
setConversation={jest.fn()}
workspace={workspace({ mode: 'without_attached', state: 'without_attached' })}
@@ -172,7 +199,7 @@ describe('CodeWorkspaceMenu', () => {
});
test('hides the chooser after the conversation decision is locked', () => {
- render(
+ renderMenu(
<CodeWorkspaceMenu
setConversation={jest.fn()}
workspace={workspace({ locked: true })}
@@ -184,7 +211,7 @@ describe('CodeWorkspaceMenu', () => {
});
test('shows recovery status when a locked workspace is unavailable', () => {
- render(
+ renderMenu(
<CodeWorkspaceMenu
setConversation={jest.fn()}
workspace={workspace({
@@ -204,4 +231,262 @@ describe('CodeWorkspaceMenu', () => {
'com_ui_code_workspace_unavailable. com_ui_code_workspace_locked_recovery',
);
});
+
+ describe('a chat sealed to a machine its agent no longer uses', () => {
+ const mac = { environmentId: 'mac', workspaceId: 'primary' };
+ const moved = { environmentId: environment.id, workspaceId: 'project-a' };
+ const sealed = { ...conversation, conversationId: 'existing' } as TConversation;
+ const teamVm = {
+ id: 'team-vm',
+ name: 'Team VM',
+ type: 'attached' as const,
+ baseURL: 'https://team.example.com',
+ };
+
+ type Target = NonNullable<CodeWorkspaceResult['relocation']>['targets'][number];
+ const target = (
+ targetEnvironment: Target['environment'],
+ workspaces: Target['workspaces'],
+ ): Target => ({
+ environment: targetEnvironment,
+ state: 'choose',
+ workspaces,
+ selected: undefined,
+ });
+
+ const relocatable = (targets: Target[], rememberSelection = jest.fn()) =>
+ workspace({
+ locked: true,
+ canSubmit: false,
+ state: 'relocatable',
+ selections: undefined,
+ rememberSelection,
+ environments: targets,
+ relocation: {
+ conversationId: 'existing',
+ from: [mac],
+ previous: [{ id: 'mac', name: 'Danny Mac' }],
+ retained: [],
+ targets,
+ },
+ });
+
+ const confirmItem = () => screen.findByRole('menuitem', { name: /com_ui_code_workspace_move/ });
+
+ beforeEach(() => {
+ mockShowToast.mockReset();
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ test('moves the chat onto the sole workspace its agent now uses', async () => {
+ const moveSpy = jest.spyOn(dataService, 'moveConversationCodeEnvironment').mockResolvedValue({
+ conversationId: 'existing',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [moved],
+ });
+ const setConversation = jest.fn();
+ const rememberSelection = jest.fn();
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={setConversation}
+ workspace={relocatable(
+ [target(environment, [{ id: 'project-a', name: 'Project A' }])],
+ rememberSelection,
+ )}
+ disabled={false}
+ />,
+ );
+
+ expect(screen.queryByTestId('code-workspace-locked-status')).not.toBeInTheDocument();
+ await userEvent.click(screen.getByTestId('code-workspace-move'));
+ expect(screen.getByRole('menuitemradio', { name: /Project A/ })).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ await userEvent.click(await confirmItem());
+
+ await waitFor(() => expect(setConversation).toHaveBeenCalledTimes(1));
+ expect(moveSpy).toHaveBeenCalledTimes(1);
+ expect(moveSpy).toHaveBeenCalledWith({
+ conversationId: 'existing',
+ from: [mac],
+ to: [moved],
+ });
+ expect(rememberSelection).toHaveBeenCalledWith(moved);
+ const update = setConversation.mock.calls[0][0];
+ expect(update(sealed)).toEqual({
+ ...sealed,
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [moved],
+ });
+ expect(update(conversation)).toBe(conversation);
+ expect(mockShowToast).not.toHaveBeenCalled();
+ });
+
+ test('moves every new environment in one request once each has a workspace', async () => {
+ const moveSpy = jest.spyOn(dataService, 'moveConversationCodeEnvironment').mockResolvedValue({
+ conversationId: 'existing',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [],
+ });
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={jest.fn()}
+ workspace={relocatable([
+ target(environment, [{ id: 'project-a', name: 'Project A' }]),
+ target(teamVm, [
+ { id: 'shared', name: 'Shared' },
+ { id: 'scratch', name: 'Scratch' },
+ ]),
+ ])}
+ disabled={false}
+ />,
+ );
+
+ await userEvent.click(screen.getByTestId('code-workspace-move'));
+ expect(await confirmItem()).toHaveAttribute('aria-disabled', 'true');
+ await userEvent.click(screen.getByRole('menuitemradio', { name: /Scratch/ }));
+ await userEvent.click(await confirmItem());
+
+ await waitFor(() => expect(moveSpy).toHaveBeenCalledTimes(1));
+ expect(moveSpy).toHaveBeenCalledWith({
+ conversationId: 'existing',
+ from: [mac],
+ to: [moved, { environmentId: 'team-vm', workspaceId: 'scratch' }],
+ });
+ });
+
+ test('starts another relocatable chat undecided even when it targets the same machine', async () => {
+ const targets = [
+ target(teamVm, [
+ { id: 'shared', name: 'Shared' },
+ { id: 'scratch', name: 'Scratch' },
+ ]),
+ ];
+ const firstChat = relocatable(targets);
+ const { rerenderMenu } = renderMenu(
+ <CodeWorkspaceMenu setConversation={jest.fn()} workspace={firstChat} disabled={false} />,
+ );
+
+ await userEvent.click(screen.getByTestId('code-workspace-move'));
+ await userEvent.click(screen.getByRole('menuitemradio', { name: /Scratch/ }));
+ expect(await confirmItem()).not.toHaveAttribute('aria-disabled', 'true');
+
+ rerenderMenu(
+ <CodeWorkspaceMenu
+ setConversation={jest.fn()}
+ workspace={{
+ ...firstChat,
+ relocation: { ...firstChat.relocation!, conversationId: 'another-chat' },
+ }}
+ disabled={false}
+ />,
+ );
+
+ expect(screen.getByRole('menuitemradio', { name: /Scratch/ })).toHaveAttribute(
+ 'aria-checked',
+ 'false',
+ );
+ expect(await confirmItem()).toHaveAttribute('aria-disabled', 'true');
+ });
+
+ test('drops a machine the agents stopped using with a single confirm', async () => {
+ const moveSpy = jest.spyOn(dataService, 'moveConversationCodeEnvironment').mockResolvedValue({
+ conversationId: 'existing',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [moved],
+ });
+ const setConversation = jest.fn();
+ const base = relocatable([]);
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={setConversation}
+ workspace={{
+ ...base,
+ relocation: {
+ ...base.relocation!,
+ from: [mac, moved],
+ previous: [{ id: 'mac', name: 'Danny Mac' }],
+ retained: [moved],
+ },
+ }}
+ disabled={false}
+ />,
+ );
+
+ await userEvent.click(screen.getByTestId('code-workspace-move'));
+ expect(screen.getByText('com_ui_code_workspace_move_info_removed')).toBeInTheDocument();
+ await userEvent.click(await confirmItem());
+
+ await waitFor(() => expect(setConversation).toHaveBeenCalledTimes(1));
+ expect(moveSpy).toHaveBeenCalledWith({
+ conversationId: 'existing',
+ from: [mac, moved],
+ to: [moved],
+ });
+ });
+
+ test('explains a new machine that advertises no workspace and cannot be moved to', async () => {
+ const moveSpy = jest.spyOn(dataService, 'moveConversationCodeEnvironment');
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={jest.fn()}
+ workspace={relocatable([target(environment, [])])}
+ disabled={false}
+ />,
+ );
+
+ await userEvent.click(screen.getByTestId('code-workspace-move'));
+
+ expect(screen.getByText('com_ui_code_workspace_unavailable')).toBeInTheDocument();
+ const confirm = await confirmItem();
+ expect(confirm).toHaveAttribute('aria-disabled', 'true');
+ await userEvent.setup({ pointerEventsCheck: 0 }).click(confirm);
+ expect(moveSpy).not.toHaveBeenCalled();
+ });
+
+ test.each([
+ {
+ name: 'the new machine rejected the workspace',
+ data: { reason: 'missing' },
+ key: 'com_error_code_workspace_missing',
+ },
+ {
+ name: 'the decision changed elsewhere first',
+ data: { reason: 'locked' },
+ key: 'com_ui_code_workspace_move_stale',
+ },
+ {
+ name: 'a response is still generating',
+ data: { error: 'busy' },
+ key: 'com_ui_code_workspace_move_busy',
+ },
+ ])('explains a refused move when $name and keeps the chat as it was', async ({ data, key }) => {
+ jest.spyOn(dataService, 'moveConversationCodeEnvironment').mockRejectedValue(
+ new AxiosError('Conflict', 'ERR_BAD_REQUEST', undefined, undefined, {
+ status: 409,
+ data,
+ } as AxiosResponse),
+ );
+ const setConversation = jest.fn();
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={setConversation}
+ workspace={relocatable([target(environment, [{ id: 'project-a', name: 'Project A' }])])}
+ disabled={false}
+ />,
+ );
+
+ await userEvent.click(screen.getByTestId('code-workspace-move'));
+ await userEvent.click(await confirmItem());
+
+ await waitFor(() =>
+ expect(mockShowToast).toHaveBeenCalledWith({ message: key, status: 'error' }),
+ );
+ expect(setConversation).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/client/src/components/Messages/Content/Error.tsx b/client/src/components/Messages/Content/Error.tsx
index 7577eef186..0d5edf0cb3 100644
--- a/client/src/components/Messages/Content/Error.tsx
+++ b/client/src/components/Messages/Content/Error.tsx
@@ -7,10 +7,10 @@ import {
parseLangChainErrorCode,
stripLangChainTroubleshootingUrl,
} from 'librechat-data-provider';
-import type { CodeWorkspaceSelectionErrorReason } from 'librechat-data-provider';
import type { LocalizeFunction } from '~/common';
import type { TranslationKeys } from '~/hooks';
import { formatJSON, extractJson, isJson } from '~/utils/json';
+import { codeWorkspaceErrorKeys } from '~/utils/errors';
import { useLocalize } from '~/hooks';
import CodeBlock from './CodeBlock';
@@ -79,15 +79,6 @@ type TUpstreamModelError = {
status?: number;
};
-const codeWorkspaceErrorKeys: Record<CodeWorkspaceSelectionErrorReason, TranslationKeys> = {
- required: 'com_error_code_workspace_required',
- invalid: 'com_error_code_workspace_invalid',
- worker_unavailable: 'com_error_code_workspace_worker_unavailable',
- unsupported: 'com_error_code_workspace_unsupported',
- missing: 'com_error_code_workspace_missing',
- locked: 'com_error_code_workspace_locked',
-};
-
/** Why a manual compaction could not run, keyed by the SDK's skip reason. */
const compactionSkippedKeys: Record<string, TranslationKeys> = {
disabled: 'com_error_compaction_disabled',
diff --git a/client/src/data-provider/CodeEnvironments.ts b/client/src/data-provider/CodeEnvironments.ts
index 153c78655c..6dad49dab8 100644
--- a/client/src/data-provider/CodeEnvironments.ts
+++ b/client/src/data-provider/CodeEnvironments.ts
@@ -1,11 +1,15 @@
import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
import { DynamicQueryKeys, MutationKeys, QueryKeys, dataService } from 'librechat-data-provider';
import type {
+ TConversation,
CodeEnvironmentUserSettings,
+ TCodeEnvironmentMoveRequest,
+ TCodeEnvironmentMoveResponse,
TCodeEnvironmentPairingResponse,
TCodeEnvironmentStatusResponse,
TCodeEnvironmentsResponse,
} from 'librechat-data-provider';
+import { CONVERSATION_LIST_KEYS, updateConvoInAllQueries } from '~/utils';
export type CodeEnvironmentPairingResponse = TCodeEnvironmentPairingResponse;
@@ -84,3 +88,32 @@ export function useUpdateCodeEnvironmentSettingsMutation() {
},
});
}
+
+/** Keeps every cached copy of the conversation on the decision the server just persisted. */
+export function useMoveConversationCodeEnvironmentMutation() {
+ const queryClient = useQueryClient();
+ return useMutation<TCodeEnvironmentMoveResponse, Error, TCodeEnvironmentMoveRequest>(
+ [MutationKeys.moveConversationCodeEnvironment],
+ dataService.moveConversationCodeEnvironment,
+ {
+ onSuccess: async ({ conversationId, codeEnvironmentMode, codeWorkspaces }) => {
+ /** A read already in flight could land after this write and restore the replaced decision. */
+ await Promise.all(
+ [[QueryKeys.conversation, conversationId], [QueryKeys.pinnedConversations]]
+ .concat(CONVERSATION_LIST_KEYS.map((listKey) => [listKey]))
+ .map((queryKey) => queryClient.cancelQueries({ queryKey })),
+ );
+ const applyDecision = (conversation: TConversation): TConversation => ({
+ ...conversation,
+ codeEnvironmentMode,
+ codeWorkspaces,
+ });
+ updateConvoInAllQueries(queryClient, conversationId, applyDecision);
+ queryClient.setQueryData<TConversation | undefined>(
+ [QueryKeys.conversation, conversationId],
+ (conversation) => (conversation == null ? conversation : applyDecision(conversation)),
+ );
+ },
+ },
+ );
+}
diff --git a/client/src/data-provider/__tests__/moveCodeEnvironment.test.tsx b/client/src/data-provider/__tests__/moveCodeEnvironment.test.tsx
new file mode 100644
index 0000000000..2fbc1eb17d
--- /dev/null
+++ b/client/src/data-provider/__tests__/moveCodeEnvironment.test.tsx
@@ -0,0 +1,67 @@
+import { createElement } from 'react';
+import { dataService, QueryKeys } from 'librechat-data-provider';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
+import type { TConversation } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import { useMoveConversationCodeEnvironmentMutation } from '../CodeEnvironments';
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: { ...actual.dataService, moveConversationCodeEnvironment: jest.fn() },
+ };
+});
+
+const mac = { environmentId: 'mac', workspaceId: 'primary' };
+const vm = { environmentId: 'vm', workspaceId: 'projects' };
+
+describe('useMoveConversationCodeEnvironmentMutation', () => {
+ it('keeps the moved decision when a conversation read from before the move resolves later', async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const stored = {
+ conversationId: 'convo-1',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac],
+ } as TConversation;
+ queryClient.setQueryData([QueryKeys.conversation, 'convo-1'], stored);
+ jest.mocked(dataService.moveConversationCodeEnvironment).mockResolvedValue({
+ conversationId: 'convo-1',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [vm],
+ });
+ let resolveStaleRead: (conversation: TConversation) => void = () => undefined;
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(QueryClientProvider, { client: queryClient }, children);
+
+ const { result } = renderHook(
+ () => ({
+ conversation: useQuery(
+ [QueryKeys.conversation, 'convo-1'],
+ () =>
+ new Promise<TConversation>((resolve) => {
+ resolveStaleRead = resolve;
+ }),
+ { staleTime: 0 },
+ ),
+ move: useMoveConversationCodeEnvironmentMutation(),
+ }),
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.conversation.isFetching).toBe(true));
+
+ await act(async () => {
+ await result.current.move.mutateAsync({ conversationId: 'convo-1', from: [mac], to: [vm] });
+ });
+ await act(async () => {
+ resolveStaleRead(stored);
+ });
+
+ expect(queryClient.getQueryData([QueryKeys.conversation, 'convo-1'])).toEqual(
+ expect.objectContaining({ codeEnvironmentMode: 'attached', codeWorkspaces: [vm] }),
+ );
+ });
+});
diff --git a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx
index 94308e44d8..3121d292c9 100644
--- a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx
+++ b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx
@@ -464,6 +464,212 @@ describe('useCodeWorkspace', () => {
expect(result.current.state).toBe('choose');
expect(result.current.canSubmit).toBe(false);
expect(result.current.selections).toBeUndefined();
+ expect(result.current.relocation).toBeUndefined();
+ });
+
+ describe('a saved chat sealed to a machine its agent no longer uses', () => {
+ const sealed = (codeWorkspaces: TConversation['codeWorkspaces']): TConversation =>
+ ({
+ ...conversation(codeWorkspaces),
+ conversationId: 'existing',
+ codeEnvironmentMode: 'attached',
+ }) as TConversation;
+ const mac = { environmentId: 'mac', workspaceId: 'primary' };
+
+ beforeEach(() => {
+ mockStartupConfig.mockReturnValue({
+ codeEnvironmentDecisionVersion: 1,
+ codeEnvironmentMoveVersion: 1,
+ });
+ });
+
+ it('keeps the recovery status for an API that cannot move chats', () => {
+ mockStartupConfig.mockReturnValue({ codeEnvironmentDecisionVersion: 1 });
+
+ const { result } = renderHook(() => useCodeWorkspace(sealed([mac])));
+
+ expect(result.current.state).toBe('choose');
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.relocation).toBeUndefined();
+ });
+
+ it('offers to move the chat instead of an unusable workspace choice', () => {
+ mockAgentsConfig().agentsConfig.statefulCodeSessions.environments.push({
+ id: 'mac',
+ name: 'Danny Mac',
+ type: 'attached',
+ baseURL: 'https://code.example.com',
+ });
+
+ const { result } = renderHook(() => useCodeWorkspace(sealed([mac])));
+
+ expect(result.current.locked).toBe(true);
+ expect(result.current.state).toBe('relocatable');
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.relocation).toEqual({
+ conversationId: 'existing',
+ from: [mac],
+ previous: [{ id: 'mac', name: 'Danny Mac' }],
+ retained: [],
+ targets: [
+ expect.objectContaining({
+ environment: expect.objectContaining({ id: 'personal-vm' }),
+ state: 'choose',
+ workspaces: [{ id: 'project-a', name: 'Project A' }],
+ }),
+ ],
+ });
+ });
+
+ it('offers to drop a machine the agents stopped using instead of trimming the seal', () => {
+ const kept = { environmentId: 'personal-vm', workspaceId: 'project-a' };
+ const gone = { environmentId: 'gone-vm', workspaceId: 'root' };
+
+ const { result } = renderHook(() => useCodeWorkspace(sealed([gone, kept])));
+
+ expect(result.current.state).toBe('relocatable');
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.relocation).toEqual({
+ conversationId: 'existing',
+ from: [gone, kept],
+ previous: [{ id: 'gone-vm', name: undefined }],
+ retained: [kept],
+ targets: [],
+ });
+ });
+
+ it('never submits a trimmed seal when the API cannot move chats', () => {
+ mockStartupConfig.mockReturnValue({ codeEnvironmentDecisionVersion: 1 });
+ const kept = { environmentId: 'personal-vm', workspaceId: 'project-a' };
+ const gone = { environmentId: 'gone-vm', workspaceId: 'root' };
+
+ const { result } = renderHook(() => useCodeWorkspace(sealed([gone, kept])));
+
+ expect(result.current.state).toBe('choose');
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.resolveSubmission([gone, kept], 'attached')).toBeUndefined();
+ });
+
+ it('treats a legacy selection-only seal the same way', () => {
+ const { result } = renderHook(() =>
+ useCodeWorkspace({ ...conversation([mac]), conversationId: 'existing' }),
+ );
+
+ expect(result.current.state).toBe('relocatable');
+ expect(result.current.relocation?.previous).toEqual([{ id: 'mac', name: undefined }]);
+ });
+
+ it.each([
+ { codeEnvironmentDecisionVersion: 1, codeEnvironmentMoveVersion: 1 },
+ { codeEnvironmentMoveVersion: 1 },
+ ])('carries over a sealed workspace the agents still use: %j', (startupConfig) => {
+ mockStartupConfig.mockReturnValue(startupConfig);
+ const primary = {
+ id: 'agent_primary',
+ stateful_code_sessions: true,
+ code_environment_id: 'personal-vm',
+ tools: [Tools.execute_code],
+ subagents: { enabled: true, agent_ids: ['child'] },
+ };
+ mockAgentPermissions.mockImplementation((id?: string) => ({
+ agent: id === 'agent_primary' ? primary : undefined,
+ tools: id === 'agent_primary' ? primary.tools : undefined,
+ }));
+ mockAgentsMap.mockReturnValue({
+ child: {
+ id: 'child',
+ stateful_code_sessions: true,
+ code_environment_id: 'team-vm',
+ tools: [Tools.execute_code],
+ },
+ });
+ mockAgentsConfig().agentsConfig.statefulCodeSessions.environments.push({
+ id: 'team-vm',
+ name: 'Team VM',
+ type: 'attached',
+ baseURL: 'https://two.example.com',
+ });
+ mockStatus.mockReturnValue([
+ mockStatus()[0],
+ {
+ data: {
+ environmentId: 'team-vm',
+ status: 'ready',
+ statefulWorkspace: true,
+ workspaces: [{ id: 'project-b' }],
+ },
+ isLoading: false,
+ isError: false,
+ },
+ ]);
+ const kept = { environmentId: 'personal-vm', workspaceId: 'project-a' };
+
+ const { result } = renderHook(() => useCodeWorkspace(sealed([kept])));
+
+ expect(result.current.state).toBe('relocatable');
+ expect(result.current.relocation?.previous).toEqual([]);
+ expect(result.current.relocation?.retained).toEqual([kept]);
+ expect(result.current.relocation?.targets.map(({ environment }) => environment.id)).toEqual([
+ 'team-vm',
+ ]);
+ });
+
+ it('waits for the new machine before offering a move', () => {
+ mockStatus.mockReturnValue([{ isLoading: true, isError: false }]);
+
+ const { result } = renderHook(() => useCodeWorkspace(sealed([mac])));
+
+ expect(result.current.state).toBe('loading');
+ expect(result.current.relocation).toBeUndefined();
+ });
+
+ it('does not offer a move when the sealed machine lost its workspace', () => {
+ const removed = { environmentId: 'personal-vm', workspaceId: 'removed-project' };
+
+ const { result } = renderHook(() => useCodeWorkspace(sealed([removed])));
+
+ expect(result.current.state).toBe('missing');
+ expect(result.current.relocation).toBeUndefined();
+ });
+
+ it('does not offer an attached machine to a chat that continues without one', () => {
+ const { result } = renderHook(() =>
+ useCodeWorkspace({
+ ...conversation(),
+ conversationId: 'existing',
+ codeEnvironmentMode: 'without_attached',
+ } as TConversation),
+ );
+
+ expect(result.current.state).toBe('without_attached');
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.relocation).toBeUndefined();
+ });
+
+ it('does not auto-select a sole workspace the saved decision never covered', () => {
+ const { result } = renderHook(() =>
+ useCodeWorkspace({ ...conversation(), conversationId: 'existing' } as TConversation),
+ );
+
+ expect(result.current.state).toBe('without_attached');
+ expect(result.current.selections).toBeUndefined();
+ expect(result.current.resolveSubmission()).toEqual({
+ codeEnvironmentMode: 'without_attached',
+ });
+ });
+
+ it('keeps auto-selecting for an API that does not seal decisions', () => {
+ mockStartupConfig.mockReturnValue({});
+
+ const { result } = renderHook(() =>
+ useCodeWorkspace({ ...conversation(), conversationId: 'existing' } as TConversation),
+ );
+
+ expect(result.current.state).toBe('ready');
+ expect(result.current.selections).toEqual([
+ { environmentId: 'personal-vm', workspaceId: 'project-a' },
+ ]);
+ });
});
it('invalidates readiness when current agent metadata changes environments', () => {
diff --git a/client/src/hooks/Agents/index.ts b/client/src/hooks/Agents/index.ts
index 02687456cf..38fde48357 100644
--- a/client/src/hooks/Agents/index.ts
+++ b/client/src/hooks/Agents/index.ts
@@ -11,6 +11,11 @@ export type { AgentUploadTarget } from './useAgentUploadTarget';
export { default as useAgentToolPermissions } from './useAgentToolPermissions';
export { default as useCodeApprovalMode } from './useCodeApprovalMode';
export { default as useCodeWorkspace } from './useCodeWorkspace';
-export type { CodeWorkspaceResult, CodeWorkspaceState } from './useCodeWorkspace';
+export type {
+ CodeWorkspaceEnvironmentResult,
+ CodeWorkspaceRelocation,
+ CodeWorkspaceResult,
+ CodeWorkspaceState,
+} from './useCodeWorkspace';
export { default as useMCPToolOptions } from './useMCPToolOptions';
export * from './useApplyModelSpecAgents';
diff --git a/client/src/hooks/Agents/useCodeWorkspace.ts b/client/src/hooks/Agents/useCodeWorkspace.ts
index 2c36cf3fde..d862cfffa8 100644
--- a/client/src/hooks/Agents/useCodeWorkspace.ts
+++ b/client/src/hooks/Agents/useCodeWorkspace.ts
@@ -8,6 +8,7 @@ import {
import {
AgentCapabilities,
CODE_ENVIRONMENT_DECISION_VERSION,
+ CODE_ENVIRONMENT_MOVE_VERSION,
PermissionTypes,
Permissions,
} from 'librechat-data-provider';
@@ -33,6 +34,7 @@ export type CodeWorkspaceState =
| 'without_attached'
| 'loading'
| 'choose'
+ | 'relocatable'
| 'ready'
| 'missing'
| 'unavailable'
@@ -40,11 +42,30 @@ export type CodeWorkspaceState =
export interface CodeWorkspaceEnvironmentResult {
environment: TPublicCodeEnvironment;
- state: Exclude<CodeWorkspaceState, 'not_required'>;
+ state: Exclude<CodeWorkspaceState, 'not_required' | 'relocatable'>;
workspaces: CodeWorkspaceDescriptor[];
selected?: CodeWorkspaceSelection;
}
+/**
+ * A saved chat whose attached decision no longer covers every environment its agents use, most
+ * often because an agent was pointed at a different machine after the chat was created. The
+ * decision stays sealed against implicit changes; only its owner's explicit move replaces it.
+ */
+export interface CodeWorkspaceRelocation {
+ conversationId: string;
+ /** The persisted selections a move replaces, exactly as the conversation stores them. */
+ from: CodeWorkspaceSelection[];
+ /** Environments the decision covered that the agents no longer use. */
+ previous: Array<
+ Pick<TPublicCodeEnvironment, 'id'> & Partial<Pick<TPublicCodeEnvironment, 'name'>>
+ >;
+ /** Sealed selections the agents still use; a move carries them over unchanged. */
+ retained: CodeWorkspaceSelection[];
+ /** Environments the agents now use that the decision does not cover. */
+ targets: CodeWorkspaceEnvironmentResult[];
+}
+
export interface CodeWorkspaceResult {
required: boolean;
supportsEnvironmentDecisions: boolean;
@@ -53,6 +74,7 @@ export interface CodeWorkspaceResult {
state: CodeWorkspaceState;
canSubmit: boolean;
environments: CodeWorkspaceEnvironmentResult[];
+ relocation?: CodeWorkspaceRelocation;
selections?: CodeWorkspaceSelection[];
resolveSelections: (
selections?: CodeWorkspaceSelection[],
@@ -111,6 +133,8 @@ export default function useCodeWorkspace(
const { data: startupConfig } = useGetStartupConfig();
const supportsEnvironmentDecisions =
startupConfig?.codeEnvironmentDecisionVersion === CODE_ENVIRONMENT_DECISION_VERSION;
+ const supportsEnvironmentMoves =
+ startupConfig?.codeEnvironmentMoveVersion === CODE_ENVIRONMENT_MOVE_VERSION;
const preferences = useWorkspacePreferences(conversation?.agent_id);
const { agentsConfig, endpointsConfig } = useGetAgentsConfig();
const canRunCode = useHasAccess({
@@ -208,7 +232,10 @@ export default function useCodeWorkspace(
required && selectionMetadataComplete,
);
const storedSelections = conversation?.codeWorkspaces;
- const attachedEnvironmentIds = new Set(attachedEnvironments.map(({ id }) => id));
+ const attachedEnvironmentIds = useMemo(
+ () => new Set(attachedEnvironments.map(({ id }) => id)),
+ [attachedEnvironments],
+ );
const hasForeignStoredSelection = storedSelections?.some(
({ environmentId }) => !attachedEnvironmentIds.has(environmentId),
);
@@ -243,8 +270,14 @@ export default function useCodeWorkspace(
status: status?.data,
workspaces,
stored,
+ /** A saved chat already holds the server's decision, so a sole workspace is not a draft
+ * choice there: auto-selecting it would submit a selection its persisted decision rejects.
+ * Attached selections are sealed whether or not selection-less decisions are advertised. */
hasStoredSelections:
- stored != null || conflictingDefaults || hasForeignStoredSelection === true,
+ (locked && (supportsEnvironmentDecisions || (storedSelections?.length ?? 0) > 0)) ||
+ stored != null ||
+ conflictingDefaults ||
+ hasForeignStoredSelection === true,
});
let state: CodeWorkspaceEnvironmentResult['state'] = 'choose';
if (status == null || status.isLoading) state = 'loading';
@@ -265,6 +298,14 @@ 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))
+ ) {
+ return undefined;
+ }
const resolved: CodeWorkspaceSelection[] = [];
for (const result of environmentResults) {
const requested = selections?.find(
@@ -291,7 +332,7 @@ export default function useCodeWorkspace(
}
return resolved.sort((a, b) => a.environmentId.localeCompare(b.environmentId));
},
- [environmentResults, required, selectionMetadataComplete],
+ [attachedEnvironmentIds, environmentResults, locked, required, selectionMetadataComplete],
);
const selections = resolveSelections(storedSelections);
@@ -314,6 +355,33 @@ export default function useCodeWorkspace(
} else {
state = aggregateState(required, metadataComplete, environmentResults, selections);
}
+ let relocation: CodeWorkspaceRelocation | undefined;
+ if (
+ supportsEnvironmentMoves &&
+ locked &&
+ state === 'choose' &&
+ inferredMode === 'attached' &&
+ conversation?.conversationId != null &&
+ storedSelections != null &&
+ storedSelections.length > 0
+ ) {
+ const configuredEnvironments = statefulCodeSessions?.environments;
+ relocation = {
+ conversationId: conversation.conversationId,
+ from: storedSelections,
+ previous: storedSelections
+ .filter(({ environmentId }) => !attachedEnvironmentIds.has(environmentId))
+ .map(({ environmentId }) => ({
+ id: environmentId,
+ name: configuredEnvironments?.find(({ id }) => id === environmentId)?.name,
+ })),
+ retained: environmentResults.flatMap((result) =>
+ result.state === 'ready' && result.selected != null ? [result.selected] : [],
+ ),
+ targets: environmentResults.filter((result) => result.state === 'choose'),
+ };
+ state = 'relocatable';
+ }
const resolveSubmission = useCallback(
(
candidateSelections?: CodeWorkspaceSelection[],
@@ -360,6 +428,7 @@ export default function useCodeWorkspace(
state,
canSubmit,
environments: environmentResults,
+ relocation,
selections,
resolveSelections,
resolveSubmission,
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 2c8142cc60..9e558487e8 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -21,6 +21,14 @@
"com_ui_code_workspace_without_attached": "No attached workspace",
"com_ui_code_workspace_without_attached_info": "Chat without using files or commands on an attached machine.",
"com_ui_code_workspace_locked_recovery": "Reconnect or restore this workspace, or start a new chat.",
+ "com_ui_code_workspace_move": "Move chat",
+ "com_ui_code_workspace_move_to": "Move chat to {{0}}",
+ "com_ui_code_workspace_move_info": "This chat used {{0}}, but its agent now uses {{1}}. Files from earlier turns stay on the previous machine.",
+ "com_ui_code_workspace_move_info_removed": "This chat's agent no longer uses {{0}}. Move the chat to continue without it.",
+ "com_ui_code_workspace_move_info_added": "This chat's agent now also uses {{0}}. Choose a workspace there to continue.",
+ "com_ui_code_workspace_move_stale": "This chat's workspace changed in another window. Reload and try again.",
+ "com_ui_code_workspace_move_busy": "Wait for the current response to finish, then move this chat.",
+ "com_ui_code_workspace_move_error": "Couldn't move this chat. Try again.",
"com_ui_code_workspaces_selected": "{{0}} code workspaces",
"com_ui_code_approval_ask": "Ask before changes",
"com_ui_code_approval_ask_description": "Ask before editing files or running commands",
diff --git a/client/src/utils/errors.ts b/client/src/utils/errors.ts
index 04666c5313..62beaa6079 100644
--- a/client/src/utils/errors.ts
+++ b/client/src/utils/errors.ts
@@ -1,4 +1,7 @@
import axios from 'axios';
+import { isCodeWorkspaceSelectionErrorReason } from 'librechat-data-provider';
+import type { CodeWorkspaceSelectionErrorReason } from 'librechat-data-provider';
+import type { TranslationKeys } from '~/hooks';
/**
* Returns the HTTP response status code from an error, regardless of the
@@ -19,3 +22,24 @@ export const getResponseStatus = (error: unknown): number | undefined => {
};
export const isNotFoundError = (error: unknown): boolean => getResponseStatus(error) === 404;
+
+export const codeWorkspaceErrorKeys: Record<CodeWorkspaceSelectionErrorReason, TranslationKeys> = {
+ required: 'com_error_code_workspace_required',
+ invalid: 'com_error_code_workspace_invalid',
+ worker_unavailable: 'com_error_code_workspace_worker_unavailable',
+ unsupported: 'com_error_code_workspace_unsupported',
+ missing: 'com_error_code_workspace_missing',
+ locked: 'com_error_code_workspace_locked',
+};
+
+/** Reads the workspace rejection reason a failed request carried, when the server sent one. */
+export const getCodeWorkspaceErrorReason = (
+ error: unknown,
+): CodeWorkspaceSelectionErrorReason | undefined => {
+ if (!axios.isAxiosError(error)) {
+ return undefined;
+ }
+ const data: unknown = error.response?.data;
+ const reason = data != null && typeof data === 'object' && 'reason' in data ? data.reason : null;
+ return isCodeWorkspaceSelectionErrorReason(reason) ? reason : undefined;
+};
diff --git a/packages/api/src/code/config.spec.ts b/packages/api/src/code/config.spec.ts
index c6a4c0608c..7c556669e3 100644
--- a/packages/api/src/code/config.spec.ts
+++ b/packages/api/src/code/config.spec.ts
@@ -4,6 +4,7 @@ import {
isImplicitStatefulCodeRouteAvailable,
mergeAccessibleCodeEnvironments,
resolveCodeEnvironmentDecisionVersion,
+ resolveCodeEnvironmentMoveVersion,
} from './config';
describe('resolveCodeEnvironmentDecisionVersion', () => {
@@ -19,6 +20,33 @@ describe('resolveCodeEnvironmentDecisionVersion', () => {
);
});
+describe('resolveCodeEnvironmentMoveVersion', () => {
+ const withMoves = (conversationMoves?: { enabled?: boolean }) =>
+ ({
+ endpoints: {
+ [EModelEndpoint.agents]: {
+ statefulCodeSessions: { allowedEnvironments: ['user'], conversationMoves },
+ },
+ },
+ }) as unknown as AppConfig;
+
+ it('advertises moves only where the effective policy enables them', () => {
+ expect(resolveCodeEnvironmentMoveVersion(withMoves({ enabled: true }))).toBe(1);
+ });
+
+ it.each([undefined, {}, { enabled: false }])(
+ 'keeps sealed decisions immovable by default: %j',
+ (conversationMoves) => {
+ expect(resolveCodeEnvironmentMoveVersion(withMoves(conversationMoves))).toBeUndefined();
+ },
+ );
+
+ it('keeps moves off without any stateful code configuration', () => {
+ expect(resolveCodeEnvironmentMoveVersion({} as AppConfig)).toBeUndefined();
+ expect(resolveCodeEnvironmentMoveVersion(undefined)).toBeUndefined();
+ });
+});
+
describe('isImplicitStatefulCodeRouteAvailable', () => {
it('requires both the deployed protocol version and a non-empty managed base URL', () => {
expect(isImplicitStatefulCodeRouteAvailable('1', 'https://code.example/v1')).toBe(true);
diff --git a/packages/api/src/code/config.ts b/packages/api/src/code/config.ts
index 922263cfe8..7904fe756d 100644
--- a/packages/api/src/code/config.ts
+++ b/packages/api/src/code/config.ts
@@ -1,5 +1,9 @@
import { logger } from '@librechat/data-schemas';
-import { CODE_ENVIRONMENT_DECISION_VERSION, EModelEndpoint } from 'librechat-data-provider';
+import {
+ CODE_ENVIRONMENT_DECISION_VERSION,
+ CODE_ENVIRONMENT_MOVE_VERSION,
+ EModelEndpoint,
+} from 'librechat-data-provider';
import type { AppConfig } from '@librechat/data-schemas';
import type {
AccessibleCodeEnvironmentConfiguration,
@@ -30,6 +34,16 @@ export function resolveCodeEnvironmentDecisionVersion(
: undefined;
}
+/** Advertises owner moves of a sealed decision only where the effective policy enables them. */
+export function resolveCodeEnvironmentMoveVersion(
+ appConfig?: Pick<AppConfig, 'endpoints'> | null,
+): typeof CODE_ENVIRONMENT_MOVE_VERSION | undefined {
+ return appConfig?.endpoints?.[EModelEndpoint.agents]?.statefulCodeSessions?.conversationMoves
+ ?.enabled === true
+ ? CODE_ENVIRONMENT_MOVE_VERSION
+ : undefined;
+}
+
/** Enables the implicit managed route only after the versioned rollout is complete. */
export function isImplicitStatefulCodeRouteAvailable(
configuredVersion?: string,
diff --git a/packages/api/src/code/decision.spec.ts b/packages/api/src/code/decision.spec.ts
index 1a145ba76d..cd3a96e5d1 100644
--- a/packages/api/src/code/decision.spec.ts
+++ b/packages/api/src/code/decision.spec.ts
@@ -1,4 +1,8 @@
-import { resolveConversationCodeEnvironmentDecision } from './decision';
+import {
+ resolveConversationCodeEnvironmentDecision,
+ resolveConversationCodeEnvironmentMove,
+ resolvePersistableCodeEnvironmentDecision,
+} from './decision';
import { CodeWorkspaceSelectionError } from './capabilities';
const selection = { environmentId: 'personal-vm', workspaceId: 'project-a' };
@@ -121,3 +125,208 @@ describe('resolveConversationCodeEnvironmentDecision', () => {
).toThrow(expect.objectContaining<Partial<CodeWorkspaceSelectionError>>({ reason: 'invalid' }));
});
});
+
+describe('resolveConversationCodeEnvironmentMove', () => {
+ const mac = { environmentId: 'mac', workspaceId: 'primary' };
+ const vm = { environmentId: 'vm', workspaceId: 'projects' };
+ const locked = expect.objectContaining<Partial<CodeWorkspaceSelectionError>>({
+ reason: 'locked',
+ });
+ const sealedOn = (...codeWorkspaces: (typeof mac)[]) => ({
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'attached' as const,
+ codeWorkspaces,
+ });
+
+ it('replaces an environment the agents stopped using with the one they use now', () => {
+ expect(
+ resolveConversationCodeEnvironmentMove({
+ conversation: sealedOn(mac),
+ from: [mac],
+ to: [vm],
+ }),
+ ).toEqual({ codeWorkspaces: [vm] });
+ });
+
+ it('carries a covered environment over unchanged while adding a new one', () => {
+ const team = { environmentId: 'team', workspaceId: 'shared' };
+ expect(
+ resolveConversationCodeEnvironmentMove({
+ conversation: sealedOn(team),
+ from: [team],
+ to: [vm, team],
+ }),
+ ).toEqual({ codeWorkspaces: [team, vm] });
+ });
+
+ it('moves a legacy decision inferred from its selections', () => {
+ expect(
+ resolveConversationCodeEnvironmentMove({
+ conversation: { conversationId: 'conversation-1', codeWorkspaces: [mac] },
+ from: [mac],
+ to: [vm],
+ }),
+ ).toEqual({ codeWorkspaces: [vm] });
+ });
+
+ it('never switches the workspace of an environment the decision already covers', () => {
+ expect(() =>
+ resolveConversationCodeEnvironmentMove({
+ conversation: sealedOn(mac),
+ from: [mac],
+ to: [{ environmentId: 'mac', workspaceId: 'canary' }],
+ }),
+ ).toThrow(locked);
+ expect(() =>
+ resolveConversationCodeEnvironmentMove({
+ conversation: sealedOn(mac),
+ from: [mac],
+ to: [{ environmentId: 'mac', workspaceId: 'canary' }, vm],
+ }),
+ ).toThrow(locked);
+ });
+
+ it('drops an environment the agents stopped using without adding one', () => {
+ const team = { environmentId: 'team', workspaceId: 'shared' };
+ expect(
+ resolveConversationCodeEnvironmentMove({
+ conversation: sealedOn(mac, team),
+ from: [mac, team],
+ to: [team],
+ }),
+ ).toEqual({ codeWorkspaces: [team] });
+ });
+
+ it('rejects a move that changes nothing', () => {
+ expect(() =>
+ resolveConversationCodeEnvironmentMove({
+ conversation: sealedOn(mac),
+ from: [mac],
+ to: [mac],
+ }),
+ ).toThrow(locked);
+ });
+
+ it.each([
+ { conversationId: 'conversation-1', codeEnvironmentMode: 'without_attached' as const },
+ { conversationId: 'conversation-1' },
+ ])('never upgrades a conversation that continues without an attached environment', (stored) => {
+ expect(() =>
+ resolveConversationCodeEnvironmentMove({ conversation: stored, from: [], to: [vm] }),
+ ).toThrow(locked);
+ });
+
+ it('rejects a client acting on a decision it has not seen', () => {
+ expect(() =>
+ resolveConversationCodeEnvironmentMove({ conversation: sealedOn(vm), from: [mac], to: [vm] }),
+ ).toThrow(locked);
+ });
+
+ it.each([[], undefined, [vm, { ...vm, workspaceId: 'other' }], [{ environmentId: 'vm' }]])(
+ 'rejects a malformed target: %j',
+ (to) => {
+ expect(() =>
+ resolveConversationCodeEnvironmentMove({ conversation: sealedOn(mac), from: [mac], to }),
+ ).toThrow(
+ expect.objectContaining<Partial<CodeWorkspaceSelectionError>>({ reason: 'invalid' }),
+ );
+ },
+ );
+});
+
+describe('resolvePersistableCodeEnvironmentDecision', () => {
+ const mac = { environmentId: 'mac', workspaceId: 'primary' };
+ const vm = { environmentId: 'vm', workspaceId: 'projects' };
+
+ it('persists the decision a new conversation establishes', () => {
+ expect(
+ resolvePersistableCodeEnvironmentDecision({
+ conversationId: 'conversation-1',
+ decision: { mode: 'attached', codeWorkspaces: [mac] },
+ }),
+ ).toEqual({ codeEnvironmentMode: 'attached', codeWorkspaces: [mac] });
+ expect(
+ resolvePersistableCodeEnvironmentDecision({
+ conversationId: 'conversation-1',
+ decision: { mode: 'without_attached' },
+ }),
+ ).toEqual({ codeEnvironmentMode: 'without_attached' });
+ });
+
+ it('never writes a run-start decision over a stored one that a move replaced', () => {
+ expect(
+ resolvePersistableCodeEnvironmentDecision({
+ conversationId: 'conversation-1',
+ decision: { mode: 'attached', codeWorkspaces: [mac] },
+ conversation: {
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [vm],
+ },
+ }),
+ ).toEqual({});
+ });
+
+ it('records the mode a legacy row inferred without rewriting its selections', () => {
+ expect(
+ resolvePersistableCodeEnvironmentDecision({
+ conversationId: 'conversation-1',
+ decision: { mode: 'attached', codeWorkspaces: [mac] },
+ conversation: { conversationId: 'conversation-1', codeWorkspaces: [vm] },
+ }),
+ ).toEqual({ codeEnvironmentMode: 'attached' });
+ });
+
+ it('treats a resolved conversation for another id as a new conversation', () => {
+ expect(
+ resolvePersistableCodeEnvironmentDecision({
+ conversationId: 'conversation-1',
+ decision: { mode: 'attached', codeWorkspaces: [mac] },
+ conversation: {
+ conversationId: 'another-conversation',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [vm],
+ },
+ }),
+ ).toEqual({ codeEnvironmentMode: 'attached', codeWorkspaces: [mac] });
+ });
+
+ it('falls back to request fields for a caller that never resolved a decision', () => {
+ expect(
+ resolvePersistableCodeEnvironmentDecision({
+ conversationId: 'conversation-1',
+ requested: { codeEnvironmentMode: 'attached', codeWorkspaces: [mac] },
+ }),
+ ).toEqual({ codeEnvironmentMode: 'attached', codeWorkspaces: [mac] });
+ });
+
+ it('never writes a request fallback over a stored decision', () => {
+ expect(
+ resolvePersistableCodeEnvironmentDecision({
+ conversationId: 'conversation-1',
+ requested: { codeEnvironmentMode: 'attached', codeWorkspaces: [mac] },
+ conversation: {
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [vm],
+ },
+ }),
+ ).toEqual({});
+ });
+
+ it('prefers the validated decision over request fields', () => {
+ expect(
+ resolvePersistableCodeEnvironmentDecision({
+ conversationId: 'conversation-1',
+ decision: { mode: 'without_attached' },
+ requested: { codeEnvironmentMode: 'attached', codeWorkspaces: [mac] },
+ }),
+ ).toEqual({ codeEnvironmentMode: 'without_attached' });
+ });
+
+ it('persists nothing without a validated decision', () => {
+ expect(resolvePersistableCodeEnvironmentDecision({ conversationId: 'conversation-1' })).toEqual(
+ {},
+ );
+ });
+});
diff --git a/packages/api/src/code/decision.ts b/packages/api/src/code/decision.ts
index 01f54ffbcc..f120032620 100644
--- a/packages/api/src/code/decision.ts
+++ b/packages/api/src/code/decision.ts
@@ -11,7 +11,7 @@ export interface ConversationCodeEnvironmentDecision {
codeWorkspaces?: CodeWorkspaceSelection[];
}
-type StoredConversationDecision = Pick<
+export type StoredConversationDecision = Pick<
TConversation,
'conversationId' | 'codeEnvironmentMode' | 'codeWorkspaces'
>;
@@ -49,6 +49,16 @@ function validateDecision(mode: unknown, selections: unknown): ConversationCodeE
return { mode, codeWorkspaces: canonicalSelections(selections) };
}
+/** A stored conversation always carries a decision; legacy rows infer it from their selections. */
+function readPersistedDecision(
+ conversation: StoredConversationDecision,
+): ConversationCodeEnvironmentDecision {
+ const mode =
+ conversation.codeEnvironmentMode ??
+ (conversation.codeWorkspaces?.length ? 'attached' : 'without_attached');
+ return validateDecision(mode, conversation.codeWorkspaces);
+}
+
/** Resolves one immutable conversation choice before attached tools are registered. */
export function resolveConversationCodeEnvironmentDecision({
conversationId,
@@ -61,16 +71,8 @@ export function resolveConversationCodeEnvironmentDecision({
requestedSelections?: unknown;
conversation?: StoredConversationDecision | null;
}): ConversationCodeEnvironmentDecision {
- const ownsConversation = conversation != null && conversation.conversationId === conversationId;
- const persistedMode = ownsConversation ? conversation.codeEnvironmentMode : undefined;
- const persistedSelections = ownsConversation ? conversation.codeWorkspaces : undefined;
- let inferredPersistedMode: unknown = persistedMode;
- if (inferredPersistedMode == null && ownsConversation) {
- inferredPersistedMode = persistedSelections?.length ? 'attached' : 'without_attached';
- }
-
- if (inferredPersistedMode != null) {
- const persisted = validateDecision(inferredPersistedMode, persistedSelections);
+ if (conversation != null && conversation.conversationId === conversationId) {
+ const persisted = readPersistedDecision(conversation);
if (requestedMode !== undefined && requestedMode !== persisted.mode) {
throw new CodeWorkspaceSelectionError('locked');
}
@@ -102,3 +104,95 @@ export function resolveConversationCodeEnvironmentDecision({
: 'without_attached');
return validateDecision(mode, requestedSelections);
}
+
+export interface ConversationCodeEnvironmentMove {
+ codeWorkspaces: CodeWorkspaceSelection[];
+}
+
+/**
+ * Validates an owner's explicit move of a sealed attached decision onto the environments its
+ * agents now use. A move may drop environments the agents stopped using and add ones they now use,
+ * but never changes the workspace of an environment the decision already covers and never upgrades
+ * a conversation that continues without an attached environment. `from` must repeat the persisted selections, so a client acting
+ * on a stale view of the conversation cannot replace a decision it has not seen.
+ */
+export function resolveConversationCodeEnvironmentMove({
+ conversation,
+ from,
+ to,
+}: {
+ conversation: StoredConversationDecision;
+ from: unknown;
+ to: unknown;
+}): ConversationCodeEnvironmentMove {
+ const persisted = readPersistedDecision(conversation);
+ if (persisted.mode !== 'attached' || persisted.codeWorkspaces == null) {
+ throw new CodeWorkspaceSelectionError('locked');
+ }
+ if (!isCodeWorkspaceSelections(from) || !sameSelections(from, persisted.codeWorkspaces)) {
+ throw new CodeWorkspaceSelectionError('locked');
+ }
+ if (!isCodeWorkspaceSelections(to) || to.length === 0) {
+ throw new CodeWorkspaceSelectionError('invalid');
+ }
+ const sealed = new Map(
+ persisted.codeWorkspaces.map(({ environmentId, workspaceId }) => [environmentId, workspaceId]),
+ );
+ let adds = false;
+ for (const selection of to) {
+ const sealedWorkspaceId = sealed.get(selection.environmentId);
+ if (sealedWorkspaceId == null) {
+ adds = true;
+ } else if (sealedWorkspaceId !== selection.workspaceId) {
+ throw new CodeWorkspaceSelectionError('locked');
+ }
+ }
+ if (!adds && to.length === sealed.size) {
+ throw new CodeWorkspaceSelectionError('locked');
+ }
+ return { codeWorkspaces: canonicalSelections(to) };
+}
+
+type PersistableDecisionFields = Pick<
+ StoredConversationDecision,
+ 'codeEnvironmentMode' | 'codeWorkspaces'
+>;
+
+/**
+ * Returns the decision fields a run may persist. A stored conversation keeps the decision it
+ * already holds, because only its owner's explicit move replaces one: a run from any ingress that
+ * settles after a move would otherwise write its run-start decision back over it. A legacy row
+ * records the mode it inferred without touching the selections it already stores. A caller that
+ * never resolved a decision falls back to the fields its request carried, under the same rule.
+ */
+export function resolvePersistableCodeEnvironmentDecision({
+ conversationId,
+ decision,
+ conversation,
+ requested,
+}: {
+ conversationId: string;
+ decision?: ConversationCodeEnvironmentDecision | null;
+ conversation?: StoredConversationDecision | null;
+ requested?: PersistableDecisionFields | null;
+}): PersistableDecisionFields {
+ const candidate: PersistableDecisionFields =
+ decision != null
+ ? {
+ codeEnvironmentMode: decision.mode,
+ ...(decision.codeWorkspaces != null && { codeWorkspaces: decision.codeWorkspaces }),
+ }
+ : {
+ ...(requested?.codeEnvironmentMode != null && {
+ codeEnvironmentMode: requested.codeEnvironmentMode,
+ }),
+ ...(requested?.codeWorkspaces != null && { codeWorkspaces: requested.codeWorkspaces }),
+ };
+ if (conversation == null || conversation.conversationId !== conversationId) {
+ return candidate;
+ }
+ if (conversation.codeEnvironmentMode != null || candidate.codeEnvironmentMode == null) {
+ return {};
+ }
+ return { codeEnvironmentMode: candidate.codeEnvironmentMode };
+}
diff --git a/packages/api/src/code/http.spec.ts b/packages/api/src/code/http.spec.ts
index 22a1edade0..268cbca842 100644
--- a/packages/api/src/code/http.spec.ts
+++ b/packages/api/src/code/http.spec.ts
@@ -1,5 +1,6 @@
import { EModelEndpoint } from 'librechat-data-provider';
import type { AppConfig } from '@librechat/data-schemas';
+import type { CodeEnvironmentGenerationJob } from './http';
import { CodeEnvironmentLimitError, CodeEnvironmentValidationError } from './environments';
import { createCodeEnvironmentHttpHandlers } from './http';
@@ -1501,3 +1502,362 @@ describe('code environment HTTP handlers', () => {
expect(res.body).toEqual(body);
});
});
+
+describe('moving a sealed conversation code-environment decision', () => {
+ type Selection = { environmentId: string; workspaceId: string };
+ type StoredDecision = {
+ conversationId: string;
+ codeEnvironmentMode?: 'attached' | 'without_attached';
+ codeWorkspaces?: Selection[];
+ };
+
+ const userId = '68b2f0c498f24c1e78fa0001';
+ const mac: Selection = { environmentId: 'mac', workspaceId: 'primary' };
+ const vm: Selection = { environmentId: 'personal-vm', workspaceId: 'project-a' };
+ const controlPlane = {
+ id: 'self-service',
+ name: 'Self service',
+ type: 'attached' as const,
+ baseURL: 'https://code.example.com/v1',
+ owner: 'deployment' as const,
+ pairing: { allowPrincipalWorkers: true, tokenEnv: 'CODE_ADMIN_TOKEN' },
+ };
+
+ function workerStatusResponse({
+ ready = true,
+ workspaces = [{ id: 'project-a', name: 'Project A' }],
+ }: { ready?: boolean; workspaces?: Array<{ id: string; name?: string }> } = {}) {
+ return new Response(
+ JSON.stringify({
+ protocolVersion: 1,
+ workerId: 'personal-vm',
+ online: true,
+ ready,
+ leaseExpiresInMs: 50_000,
+ capabilities: {
+ sandboxProfile: 'native-srt',
+ runtimes: ['bash'],
+ workspaceTools: { protocolVersion: 1, operations: ['read_file'], workspaces },
+ },
+ }),
+ );
+ }
+
+ function setup({
+ movesEnabled = true,
+ stored = {
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac],
+ },
+ job,
+ conversationRunIds = [],
+ fetchImpl = jest.fn().mockImplementation(async () => workerStatusResponse()),
+ }: {
+ movesEnabled?: boolean;
+ stored?: StoredDecision;
+ job?: CodeEnvironmentGenerationJob;
+ conversationRunIds?: string[];
+ fetchImpl?: jest.Mock;
+ } = {}) {
+ const conversations = new Map<string, StoredDecision>([[stored.conversationId, stored]]);
+ const listConversationRuns = jest.fn(async () => conversationRunIds);
+ const getConversation = jest.fn(async (user: string, conversationId: string) =>
+ user === userId ? (conversations.get(conversationId) ?? null) : null,
+ );
+ /** Mirrors the data-schemas compare-and-swap: the write lands only on the decision it read. */
+ const replaceDecision = jest.fn(
+ async ({
+ conversationId,
+ expected,
+ codeWorkspaces,
+ }: {
+ conversationId: string;
+ expected: Pick<StoredDecision, 'codeEnvironmentMode' | 'codeWorkspaces'>;
+ codeWorkspaces: Selection[];
+ }) => {
+ const current = conversations.get(conversationId);
+ const decisionOf = (decision: Partial<StoredDecision> | undefined) =>
+ JSON.stringify([decision?.codeEnvironmentMode ?? null, decision?.codeWorkspaces ?? null]);
+ if (current == null || decisionOf(current) !== decisionOf(expected)) {
+ return null;
+ }
+ const moved: StoredDecision = {
+ ...current,
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces,
+ };
+ conversations.set(conversationId, moved);
+ return moved;
+ },
+ );
+ const handlers = createCodeEnvironmentHttpHandlers({
+ getAppConfig: jest.fn().mockResolvedValue({
+ endpoints: {
+ [EModelEndpoint.agents]: {
+ statefulCodeSessions: {
+ environments: [controlPlane],
+ conversationMoves: { enabled: movesEnabled },
+ },
+ },
+ },
+ } as unknown as AppConfig),
+ registry: {
+ register: jest.fn(),
+ listAccessible: jest.fn(),
+ listAccessibleConfigurations: jest.fn().mockResolvedValue([
+ {
+ id: 'personal-vm',
+ name: 'Personal VM',
+ type: 'attached',
+ baseURL: 'https://stale.example.com/v1',
+ controlPlaneId: 'self-service',
+ owner: 'principal',
+ workerId: 'personal-vm',
+ },
+ ]),
+ remove: jest.fn(),
+ },
+ readSecret: jest.fn(() => 'administrator-token'),
+ fetchImpl,
+ conversations: {
+ get: getConversation,
+ replaceDecision,
+ },
+ generations: {
+ getJob: async () => job ?? null,
+ getCleanupBlockingJobIdsForConversations: listConversationRuns,
+ },
+ });
+ const move = async (
+ body: { from?: unknown; to?: unknown },
+ conversationId = 'conversation-1',
+ ) => {
+ const res = response();
+ await handlers.moveConversationDecision(
+ { user: { id: userId, role: 'USER' }, params: { conversationId }, body } as never,
+ res as never,
+ );
+ return res;
+ };
+ return {
+ move,
+ conversations,
+ getConversation,
+ listConversationRuns,
+ replaceDecision,
+ fetchImpl,
+ };
+ }
+
+ test('moves a sealed decision onto a workspace the new machine registers', async () => {
+ const { move, conversations, fetchImpl } = setup();
+
+ const res = await move({ from: [mac], to: [vm] });
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual({
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [vm],
+ });
+ expect(conversations.get('conversation-1')?.codeWorkspaces).toEqual([vm]);
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ expect(fetchImpl).toHaveBeenCalledWith(
+ 'https://code.example.com/v1/bridge/workers/personal-vm/status',
+ expect.objectContaining({ headers: { Authorization: 'Bearer administrator-token' } }),
+ );
+ });
+
+ test('moves a legacy decision that only stored its selections', async () => {
+ const { move, conversations } = setup({
+ stored: { conversationId: 'conversation-1', codeWorkspaces: [mac] },
+ });
+
+ const res = await move({ from: [mac], to: [vm] });
+
+ expect(res.statusCode).toBe(200);
+ expect(conversations.get('conversation-1')).toEqual({
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [vm],
+ });
+ });
+
+ test.each([
+ { name: 'running', job: { status: 'running' as const } },
+ { name: 'awaiting approval', job: { status: 'requires_action' as const } },
+ {
+ name: 'settled but still saving its response',
+ job: { status: 'complete' as const, metadata: { terminalPersistencePending: true } },
+ },
+ ])(
+ 'refuses while a generation is $name, since it saves the decision it started with',
+ async ({ job }) => {
+ const { move, replaceDecision, fetchImpl } = setup({ job });
+
+ const res = await move({ from: [mac], to: [vm] });
+
+ expect(res.statusCode).toBe(409);
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect(replaceDecision).not.toHaveBeenCalled();
+ },
+ );
+
+ test('refuses while a remote run keyed by its response id still works on the conversation', async () => {
+ const { move, listConversationRuns, replaceDecision, fetchImpl } = setup({
+ conversationRunIds: ['resp_remote-run'],
+ });
+
+ const res = await move({ from: [mac], to: [vm] });
+
+ expect(res.statusCode).toBe(409);
+ expect(listConversationRuns).toHaveBeenCalledWith(userId, ['conversation-1'], undefined);
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect(replaceDecision).not.toHaveBeenCalled();
+ });
+
+ test('drops an environment the agents stopped using after revalidating the one it keeps', async () => {
+ const gone = { environmentId: 'gone-vm', workspaceId: 'root' };
+ const { move, conversations, fetchImpl } = setup({
+ stored: {
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [gone, vm],
+ },
+ });
+
+ const res = await move({ from: [gone, vm], to: [vm] });
+
+ expect(res.statusCode).toBe(200);
+ expect(conversations.get('conversation-1')?.codeWorkspaces).toEqual([vm]);
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ });
+
+ test('rejects a move whose kept workspace is no longer registered', async () => {
+ const gone = { environmentId: 'gone-vm', workspaceId: 'root' };
+ const { move, conversations, replaceDecision } = setup({
+ stored: {
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [gone, vm],
+ },
+ fetchImpl: jest
+ .fn()
+ .mockImplementation(async () =>
+ workerStatusResponse({ workspaces: [{ id: 'another-project' }] }),
+ ),
+ });
+
+ const res = await move({ from: [gone, vm], to: [vm] });
+
+ expect(res.statusCode).toBe(409);
+ expect(res.body).toEqual(expect.objectContaining({ reason: 'missing' }));
+ expect(replaceDecision).not.toHaveBeenCalled();
+ expect(conversations.get('conversation-1')?.codeWorkspaces).toEqual([gone, vm]);
+ });
+
+ test('moves once the previous generation has settled and saved', async () => {
+ const { move } = setup({
+ job: { status: 'complete', metadata: { terminalPersistencePending: false } },
+ });
+
+ expect((await move({ from: [mac], to: [vm] })).statusCode).toBe(200);
+ });
+
+ test.each([
+ {
+ name: 'a workspace the machine does not register',
+ fetchImpl: jest
+ .fn()
+ .mockImplementation(async () =>
+ workerStatusResponse({ workspaces: [{ id: 'another-project' }] }),
+ ),
+ reason: 'missing',
+ },
+ {
+ name: 'a machine that is not ready',
+ fetchImpl: jest.fn().mockImplementation(async () => workerStatusResponse({ ready: false })),
+ reason: 'worker_unavailable',
+ },
+ ])('rejects $name without persisting', async ({ fetchImpl, reason }) => {
+ const { move, conversations, replaceDecision } = setup({ fetchImpl });
+
+ const res = await move({ from: [mac], to: [vm] });
+
+ expect(res.statusCode).toBe(409);
+ expect(res.body).toEqual(expect.objectContaining({ reason }));
+ expect(replaceDecision).not.toHaveBeenCalled();
+ expect(conversations.get('conversation-1')?.codeWorkspaces).toEqual([mac]);
+ });
+
+ test.each([
+ {
+ name: 'an environment the caller cannot access',
+ body: { from: [mac], to: [{ environmentId: 'another-users-vm', workspaceId: 'root' }] },
+ reason: 'invalid',
+ polls: 0,
+ },
+ {
+ name: 'a stale view of the decision',
+ body: { from: [{ environmentId: 'old-vm', workspaceId: 'primary' }], to: [vm] },
+ reason: 'locked',
+ polls: 0,
+ },
+ {
+ name: 'a workspace switch inside a sealed environment',
+ body: { from: [mac], to: [{ environmentId: 'mac', workspaceId: 'canary' }] },
+ reason: 'locked',
+ polls: 0,
+ },
+ ])('rejects $name without polling any worker', async ({ body, reason, polls }) => {
+ const { move, replaceDecision, fetchImpl } = setup();
+
+ const res = await move(body);
+
+ expect(res.statusCode).toBe(409);
+ expect(res.body).toEqual(expect.objectContaining({ reason }));
+ expect(fetchImpl).toHaveBeenCalledTimes(polls);
+ expect(replaceDecision).not.toHaveBeenCalled();
+ });
+
+ test('keeps a decision another writer replaced while the worker was checked', async () => {
+ const concurrent: StoredDecision = {
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'without_attached',
+ };
+ const holder: { conversations?: Map<string, StoredDecision> } = {};
+ const fetchImpl = jest.fn().mockImplementation(async () => {
+ holder.conversations?.set('conversation-1', concurrent);
+ return workerStatusResponse();
+ });
+ const context = setup({ fetchImpl });
+ holder.conversations = context.conversations;
+
+ const res = await context.move({ from: [mac], to: [vm] });
+
+ expect(res.statusCode).toBe(409);
+ expect(res.body).toEqual(expect.objectContaining({ reason: 'locked' }));
+ expect(context.conversations.get('conversation-1')).toEqual(concurrent);
+ });
+
+ test('refuses every move when the effective policy does not enable them', async () => {
+ const { move, getConversation, replaceDecision, fetchImpl } = setup({ movesEnabled: false });
+
+ const res = await move({ from: [mac], to: [vm] });
+
+ expect(res.statusCode).toBe(403);
+ expect(getConversation).not.toHaveBeenCalled();
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect(replaceDecision).not.toHaveBeenCalled();
+ });
+
+ test('reports a conversation the caller does not own as not found', async () => {
+ const { move, fetchImpl } = setup();
+
+ const res = await move({ from: [mac], to: [vm] }, 'someone-elses-conversation');
+
+ expect(res.statusCode).toBe(404);
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/api/src/code/http.ts b/packages/api/src/code/http.ts
index f90f3d6236..ab6d229905 100644
--- a/packages/api/src/code/http.ts
+++ b/packages/api/src/code/http.ts
@@ -1,6 +1,7 @@
import { nanoid } from 'nanoid';
import { EModelEndpoint } from 'librechat-data-provider';
import { logger, type AppConfig } from '@librechat/data-schemas';
+import type { CodeWorkspaceSelection } from 'librechat-data-provider';
import type { Response } from 'express';
import type {
CodeEnvironmentLifecycleTarget,
@@ -10,9 +11,11 @@ import type {
AccessibleCodeEnvironmentDetails,
AccessibleCodeEnvironmentConfiguration,
} from './environments';
+import type { ConversationCodeEnvironmentMove, StoredConversationDecision } from './decision';
+import type { CodeBridgeFetch, CodeBridgeWorkerStatus } from './bridge';
+import type { JobStatus } from '~/stream/interfaces/IJobStore';
import type { GetAppConfigOptions } from '~/app/service';
import type { ServerRequest } from '~/types/http';
-import type { CodeBridgeFetch } from './bridge';
import {
CodeBridgeLifecycleError,
CodeBridgePairingError,
@@ -37,7 +40,10 @@ import {
CodeEnvironmentSettingsValidationError,
validateCodeEnvironmentUserSettings,
} from './settings';
+import { resolveConversationCodeEnvironmentMove } from './decision';
import { resolveCodeWorkerEnrollmentLimit } from './enrollment';
+import { resolveCodeEnvironmentMoveVersion } from './config';
+import { CodeWorkspaceSelectionError } from './capabilities';
import { getAppConfigOptionsFromUser } from '~/app/service';
type Registry = {
@@ -76,9 +82,40 @@ type ConfiguredCodeEnvironment = NonNullable<
NonNullable<StatefulCodeConfig>['environments']
>[number];
+/** Owner-scoped conversation access for moving a sealed code-environment decision. */
+export interface CodeEnvironmentConversationDeps {
+ get: (userId: string, conversationId: string) => Promise<StoredConversationDecision | null>;
+ replaceDecision: (params: {
+ user: string;
+ conversationId: string;
+ expected: Pick<StoredConversationDecision, 'codeEnvironmentMode' | 'codeWorkspaces'>;
+ codeWorkspaces: CodeWorkspaceSelection[];
+ }) => Promise<StoredConversationDecision | null>;
+}
+
+/** Generation lookups a move needs to tell whether any run can still act for a conversation. */
+export interface CodeEnvironmentGenerationDeps {
+ getJob: (streamId: string) => Promise<CodeEnvironmentGenerationJob | null | undefined>;
+ /** Remote API runs use response IDs as stream identities, so the conversation's own stream
+ * is not the only generation that can still act in its environment. */
+ getCleanupBlockingJobIdsForConversations: (
+ userId: string,
+ conversationIds: readonly string[],
+ tenantId?: string,
+ ) => Promise<string[]>;
+}
+
+/** The generation state a move reads to tell whether a run can still save its own decision. */
+export type CodeEnvironmentGenerationJob = {
+ status: JobStatus;
+ metadata?: { terminalPersistencePending?: boolean };
+};
+
export interface CodeEnvironmentHttpDeps {
getAppConfig: (options: GetAppConfigOptions) => Promise<AppConfig>;
registry: Registry;
+ conversations?: CodeEnvironmentConversationDeps;
+ generations?: CodeEnvironmentGenerationDeps;
createEnvironmentId?: () => string;
readSecret?: (name: string) => string | undefined;
resolveTenantId?: (req: ServerRequest) => string;
@@ -153,6 +190,60 @@ function configuredAttachedControlPlane(
);
}
+type WorkerPolicy = {
+ configurations: AccessibleCodeEnvironmentConfiguration[];
+ effectiveConfig: AppConfig;
+ deploymentConfig: AppConfig;
+};
+
+type WorkerTarget = { controlPlane: ConfiguredCodeEnvironment; workerId: string };
+
+/** Resolves the deployment control plane and worker a principal may poll for one environment. */
+function selectWorkerTarget(policy: WorkerPolicy, environmentId: string): WorkerTarget | undefined {
+ const { configurations, effectiveConfig, deploymentConfig } = policy;
+ const configuration = configurations.find(({ id }) => id === environmentId);
+ if (configuration == null) {
+ const effectiveEnvironment = configuredControlPlane(effectiveConfig, environmentId);
+ const deploymentEnvironment = configuredControlPlane(deploymentConfig, environmentId);
+ const workerId = deploymentEnvironment?.pairing?.workerId;
+ if (
+ effectiveEnvironment == null ||
+ deploymentEnvironment == null ||
+ workerId == null ||
+ effectiveEnvironment.pairing?.workerId !== workerId
+ ) {
+ return undefined;
+ }
+ return { controlPlane: deploymentEnvironment, workerId };
+ }
+ const { controlPlaneId, workerId } = configuration;
+ if (
+ controlPlaneId == null ||
+ workerId == null ||
+ configuredAttachedControlPlane(effectiveConfig, controlPlaneId) == null
+ ) {
+ return undefined;
+ }
+ const controlPlane = configuredAttachedControlPlane(deploymentConfig, controlPlaneId);
+ return controlPlane == null ? undefined : { controlPlane, workerId };
+}
+
+/** A terminal claim marks the job settled before its response save lands, so that save still
+ * writes the decision the run started with until `terminalPersistencePending` clears. */
+function isGenerationActive(job: CodeEnvironmentGenerationJob | null | undefined): boolean {
+ return (
+ job?.status === 'running' ||
+ job?.status === 'requires_action' ||
+ job?.metadata?.terminalPersistencePending === true
+ );
+}
+
+function selectionErrorResponse(error: CodeWorkspaceSelectionError, res: Response): Response {
+ return res
+ .status(error.status)
+ .json({ error: error.message, code: error.code, reason: error.reason });
+}
+
class CodeEnvironmentLifecycleHttpError extends Error {
constructor(
public readonly status: number,
@@ -196,6 +287,7 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps)
status: (req: ServerRequest, res: Response) => Promise<Response>;
updateSettings: (req: ServerRequest, res: Response) => Promise<Response>;
remove: (req: ServerRequest, res: Response) => Promise<Response>;
+ moveConversationDecision: (req: ServerRequest, res: Response) => Promise<Response>;
} {
const createEnvironmentId = deps.createEnvironmentId ?? (() => `code-${nanoid(20)}`);
const readSecret = deps.readSecret ?? readCodeBridgeSecret;
@@ -205,6 +297,158 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps)
const principalIsActive = deps.principalIsActive ?? (async () => true);
const workerStatus = createCodeBridgeStatusPoller({ fetchImpl: deps.fetchImpl });
+ async function loadWorkerPolicy(
+ req: ServerRequest,
+ principal: CodeEnvironmentPrincipalContext,
+ ): Promise<WorkerPolicy> {
+ const principals = await deps.registry.resolvePrincipals?.(principal);
+ const resolvedPrincipal = principals == null ? principal : { ...principal, principals };
+ const [configurations, effectiveConfig, deploymentConfig] = await Promise.all([
+ deps.registry.listAccessibleConfigurations?.(resolvedPrincipal) ?? Promise.resolve([]),
+ deps.getAppConfig({
+ ...getAppConfigOptionsFromUser(req.user),
+ ...(principals == null ? {} : { resolvedPrincipals: principals }),
+ failClosed: true,
+ skipRuntimeAugmentation: true,
+ }),
+ deps.getAppConfig({ baseOnly: true }),
+ ]);
+ return { configurations, effectiveConfig, deploymentConfig };
+ }
+
+ function readControlPlaneToken(controlPlane: ConfiguredCodeEnvironment): string | undefined {
+ const tokenEnv = controlPlane.pairing?.tokenEnv;
+ return tokenEnv == null ? undefined : readSecret(tokenEnv)?.trim();
+ }
+
+ /** Applies the run path's live workspace checks to a selection before it is persisted. */
+ async function assertWorkspaceRegistered(
+ policy: WorkerPolicy,
+ selection: CodeWorkspaceSelection,
+ ): Promise<void> {
+ const target = selectWorkerTarget(policy, selection.environmentId);
+ if (target == null) {
+ throw new CodeWorkspaceSelectionError('invalid');
+ }
+ const token = readControlPlaneToken(target.controlPlane);
+ if (!token) {
+ throw new CodeWorkspaceSelectionError('worker_unavailable');
+ }
+ let current: CodeBridgeWorkerStatus;
+ try {
+ current = await workerStatus({
+ baseURL: target.controlPlane.baseURL,
+ token,
+ workerId: target.workerId,
+ });
+ } catch (error) {
+ if (error instanceof CodeBridgeStatusError) {
+ throw new CodeWorkspaceSelectionError('worker_unavailable');
+ }
+ throw error;
+ }
+ if (current.status !== 'ready') {
+ throw new CodeWorkspaceSelectionError('worker_unavailable');
+ }
+ if (!current.workspaces || !current.operations) {
+ throw new CodeWorkspaceSelectionError('unsupported');
+ }
+ if (!current.workspaces.some(({ id }) => id === selection.workspaceId)) {
+ throw new CodeWorkspaceSelectionError('missing');
+ }
+ }
+
+ /**
+ * Moves a sealed attached decision onto the environments a conversation's agents now use, when
+ * the effective policy enables moves. Runs never rewrite a stored decision, so no run from any
+ * ingress can write its run-start decision back over a move. A move is still refused while a
+ * generation is running, awaiting approval, or saving its response, so that generation does not
+ * keep working in the previous environment after the conversation has left it.
+ */
+ async function moveConversationDecision(req: ServerRequest, res: Response): Promise<Response> {
+ const principal = actor(req);
+ if (principal == null) {
+ return res.status(401).json({ error: 'Authentication required' });
+ }
+ const { conversations, generations } = deps;
+ if (conversations == null || generations == null) {
+ return res.status(503).json({ error: 'Conversation code environments are not configured' });
+ }
+ const conversationId = (
+ req.params as { conversationId?: string } | undefined
+ )?.conversationId?.trim();
+ if (!conversationId) {
+ return res.status(400).json({ error: 'Conversation id is required' });
+ }
+ let policy: WorkerPolicy;
+ try {
+ policy = await loadWorkerPolicy(req, principal);
+ } catch (error) {
+ logger.error('[codeEnvironments] move policy resolution failed:', error);
+ return res.status(503).json({ error: 'Code environment policy is unavailable' });
+ }
+ if (resolveCodeEnvironmentMoveVersion(policy.effectiveConfig) == null) {
+ return res.status(403).json({ error: 'Conversation code environment moves are disabled' });
+ }
+ const { from, to } = (req.body ?? {}) as { from?: unknown; to?: unknown };
+ const userId = principal.userId.toString();
+ const tenantId =
+ typeof req.user?.tenantId === 'string' && req.user.tenantId !== ''
+ ? req.user.tenantId
+ : undefined;
+ const [conversation, job, conversationRunIds] = await Promise.all([
+ conversations.get(userId, conversationId),
+ generations.getJob(conversationId),
+ generations.getCleanupBlockingJobIdsForConversations(userId, [conversationId], tenantId),
+ ]);
+ if (conversation == null) {
+ return res.status(404).json({ error: 'Conversation was not found' });
+ }
+ if (isGenerationActive(job) || conversationRunIds.length > 0) {
+ return res
+ .status(409)
+ .json({ error: 'Wait for the current response to finish before moving this conversation' });
+ }
+
+ let move: ConversationCodeEnvironmentMove;
+ try {
+ move = resolveConversationCodeEnvironmentMove({ conversation, from, to });
+ } catch (error) {
+ if (error instanceof CodeWorkspaceSelectionError) {
+ return selectionErrorResponse(error, res);
+ }
+ throw error;
+ }
+ try {
+ await Promise.all(
+ move.codeWorkspaces.map((selection) => assertWorkspaceRegistered(policy, selection)),
+ );
+ } catch (error) {
+ if (error instanceof CodeWorkspaceSelectionError) {
+ return selectionErrorResponse(error, res);
+ }
+ throw error;
+ }
+
+ const moved = await conversations.replaceDecision({
+ user: userId,
+ conversationId,
+ expected: {
+ codeEnvironmentMode: conversation.codeEnvironmentMode,
+ codeWorkspaces: conversation.codeWorkspaces,
+ },
+ codeWorkspaces: move.codeWorkspaces,
+ });
+ if (moved == null) {
+ return selectionErrorResponse(new CodeWorkspaceSelectionError('locked'), res);
+ }
+ return res.status(200).json({
+ conversationId,
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: move.codeWorkspaces,
+ });
+ }
+
async function list(req: ServerRequest, res: Response): Promise<Response> {
const principal = actor(req);
if (principal == null) {
@@ -659,62 +903,25 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps)
return res.status(400).json({ error: 'Code environment id is required' });
}
- let configuration: AccessibleCodeEnvironmentConfiguration | undefined;
- let controlPlane: ConfiguredCodeEnvironment | undefined;
- let workerId: string | undefined;
+ let target: WorkerTarget | undefined;
try {
- const principals = await deps.registry.resolvePrincipals?.(principal);
- const resolvedPrincipal = principals == null ? principal : { ...principal, principals };
- const [configurations, effectiveConfig, deploymentConfig] = await Promise.all([
- deps.registry.listAccessibleConfigurations?.(resolvedPrincipal) ?? Promise.resolve([]),
- deps.getAppConfig({
- ...getAppConfigOptionsFromUser(req.user),
- ...(principals == null ? {} : { resolvedPrincipals: principals }),
- failClosed: true,
- skipRuntimeAugmentation: true,
- }),
- deps.getAppConfig({ baseOnly: true }),
- ]);
- configuration = configurations.find(({ id }) => id === environmentId);
- const controlPlaneId = configuration?.controlPlaneId;
- const effectiveControlPlane =
- controlPlaneId == null
- ? undefined
- : configuredAttachedControlPlane(effectiveConfig, controlPlaneId);
- controlPlane =
- effectiveControlPlane == null || controlPlaneId == null
- ? undefined
- : configuredAttachedControlPlane(deploymentConfig, controlPlaneId);
- workerId = configuration?.workerId;
- if (configuration == null) {
- const effectiveEnvironment = configuredControlPlane(effectiveConfig, environmentId);
- const deploymentEnvironment = configuredControlPlane(deploymentConfig, environmentId);
- if (
- effectiveEnvironment != null &&
- deploymentEnvironment != null &&
- effectiveEnvironment.pairing?.workerId === deploymentEnvironment.pairing?.workerId
- ) {
- controlPlane = deploymentEnvironment;
- workerId = deploymentEnvironment.pairing?.workerId;
- }
- }
+ target = selectWorkerTarget(await loadWorkerPolicy(req, principal), environmentId);
} catch (error) {
logger.error('[codeEnvironments] status policy resolution failed:', error);
return res.status(503).json({ error: 'Code environment policy is unavailable' });
}
- if (workerId == null || controlPlane == null) {
+ if (target == null) {
return res.status(404).json({ error: 'Code environment was not found' });
}
- const tokenEnv = controlPlane.pairing?.tokenEnv;
- const token = tokenEnv == null ? undefined : readSecret(tokenEnv)?.trim();
+ const token = readControlPlaneToken(target.controlPlane);
if (!token) {
return res.status(503).json({ error: 'Code environment status is not configured' });
}
try {
const currentStatus = await workerStatus({
- baseURL: controlPlane.baseURL,
+ baseURL: target.controlPlane.baseURL,
token,
- workerId,
+ workerId: target.workerId,
});
return res.status(200).json({ environmentId, ...currentStatus });
} catch (error) {
@@ -781,5 +988,5 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps)
}
}
- return { list, register, pair, status, updateSettings, remove };
+ return { list, register, pair, status, updateSettings, remove, moveConversationDecision };
}
diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts
index cddee914fe..da19a4476c 100644
--- a/packages/data-provider/src/api-endpoints.ts
+++ b/packages/data-provider/src/api-endpoints.ts
@@ -55,6 +55,8 @@ export const codeEnvironmentById = (id: string) =>
`${codeEnvironments()}/${encodeURIComponent(id)}`;
export const codeEnvironmentSettings = (id: string) => `${codeEnvironmentById(id)}/settings`;
export const codeEnvironmentStatus = (id: string) => `${codeEnvironmentById(id)}/status`;
+export const codeEnvironmentConversationDecision = (conversationId: string) =>
+ `${codeEnvironments()}/conversations/${encodeURIComponent(conversationId)}/decision`;
const messagesRoot = `${BASE_URL}/api/messages`;
diff --git a/packages/data-provider/src/code/workspace.ts b/packages/data-provider/src/code/workspace.ts
index 532c6c0592..2bc3f2bc6e 100644
--- a/packages/data-provider/src/code/workspace.ts
+++ b/packages/data-provider/src/code/workspace.ts
@@ -3,6 +3,8 @@ export const CODE_WORKSPACE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
export const CODE_WORKSPACE_MAX_COUNT = 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. */
+export const CODE_ENVIRONMENT_MOVE_VERSION = 1 as const;
export const CODE_WORKSPACE_OPERATIONS = [
'read_file',
'search_text',
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index fcba1ab79a..8cfcbd03a3 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -27,8 +27,8 @@ import {
MAX_SUBAGENTS_CEILING,
DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,
} from './limits';
+import { CODE_ENVIRONMENT_DECISION_VERSION, CODE_ENVIRONMENT_MOVE_VERSION } from './code/workspace';
import { ComponentTypes, SettingTypes, OptionTypes } from './generate';
-import { CODE_ENVIRONMENT_DECISION_VERSION } from './code/workspace';
import { STATEFUL_CODE_ENVIRONMENTS } from './stateful-code';
import { specsConfigSchema, TSpecsConfig } from './models';
import { isActionTool } from './types/assistants';
@@ -1266,6 +1266,13 @@ export const agentsEndpointSchema = baseEndpointSchema
maxPerUser: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),
})
.optional(),
+ /** Server-only policy letting a conversation's owner move its sealed attached decision
+ * onto the environments its agents now use. Omit to keep sealed decisions immovable. */
+ conversationMoves: z
+ .object({
+ enabled: z.boolean().optional(),
+ })
+ .optional(),
/** Operator-managed execution environments. Attached entries route to a
* Code API deployment backed by an outbound librechat-code worker. */
environments: z
@@ -2220,6 +2227,9 @@ export type TStartupConfig = {
/** Conversation-owned code-environment decision protocol supported by the API.
* Clients must not emit selection-less decisions unless this is advertised. */
codeEnvironmentDecisionVersion?: typeof CODE_ENVIRONMENT_DECISION_VERSION;
+ /** Owner moves of a sealed code-environment decision supported by the API. Clients must not
+ * offer to move a conversation unless this is advertised. */
+ codeEnvironmentMoveVersion?: typeof CODE_ENVIRONMENT_MOVE_VERSION;
interface?: TInterfaceConfig;
turnstile?: TTurnstileConfig;
balance?: TBalanceConfig;
diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts
index 4684f67961..60e2832b52 100644
--- a/packages/data-provider/src/data-service.ts
+++ b/packages/data-provider/src/data-service.ts
@@ -111,6 +111,17 @@ export function getCodeEnvironmentStatus(id: string): Promise<t.TCodeEnvironment
return request.get(endpoints.codeEnvironmentStatus(id));
}
+export function moveConversationCodeEnvironment({
+ conversationId,
+ from,
+ to,
+}: t.TCodeEnvironmentMoveRequest): Promise<t.TCodeEnvironmentMoveResponse> {
+ return request.patch(endpoints.codeEnvironmentConversationDecision(conversationId), {
+ from,
+ to,
+ });
+}
+
export function pairCodeEnvironment(payload: {
name: string;
controlPlaneId: string;
diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.ts
index 01c8455f6b..d6e773d331 100644
--- a/packages/data-provider/src/keys.ts
+++ b/packages/data-provider/src/keys.ts
@@ -166,4 +166,5 @@ export enum MutationKeys {
pairCodeEnvironment = 'pairCodeEnvironment',
updateCodeEnvironmentSettings = 'updateCodeEnvironmentSettings',
deleteCodeEnvironment = 'deleteCodeEnvironment',
+ moveConversationCodeEnvironment = 'moveConversationCodeEnvironment',
}
diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts
index 22eb5cce7f..e619f933c0 100644
--- a/packages/data-provider/src/types.ts
+++ b/packages/data-provider/src/types.ts
@@ -612,6 +612,20 @@ export type TCodeEnvironmentStatusResponse = {
workspaces?: CodeWorkspaceDescriptor[];
};
+/** Moves a sealed attached decision onto the environments a conversation's agents now use. */
+export type TCodeEnvironmentMoveRequest = {
+ conversationId: string;
+ /** The persisted selections being replaced; a mismatch rejects the move as stale. */
+ from: CodeWorkspaceSelection[];
+ to: CodeWorkspaceSelection[];
+};
+
+export type TCodeEnvironmentMoveResponse = {
+ conversationId: string;
+ codeEnvironmentMode: 'attached';
+ codeWorkspaces: CodeWorkspaceSelection[];
+};
+
export type TConfig = {
order: number;
type?: EModelEndpoint;
diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.ts
index 273c32e14c..00e3dae652 100644
--- a/packages/data-schemas/src/methods/conversation.spec.ts
+++ b/packages/data-schemas/src/methods/conversation.spec.ts
@@ -1079,6 +1079,146 @@ describe('Conversation Operations', () => {
});
});
+ describe('replaceConvoCodeEnvironmentDecision', () => {
+ const anchor = new Date('2026-09-12T11:22:22.976Z');
+ const mac = { environmentId: 'code-mac', workspaceId: 'primary' };
+ const team = { environmentId: 'code-team', workspaceId: 'shared' };
+ const vm = { environmentId: 'code-vm', workspaceId: 'projects' };
+
+ /** Raw inserts bypass Mongoose casting, the way legacy rows and operator repairs are stored. */
+ const seedDecision = async (decision: Record<string, unknown>, user = 'user123') => {
+ const conversationId = uuidv4();
+ await Conversation.collection.insertOne({
+ conversationId,
+ user,
+ title: 'Mortgage analysis',
+ endpoint: EModelEndpoint.agents,
+ messages: [],
+ createdAt: anchor,
+ updatedAt: anchor,
+ ...decision,
+ });
+ return conversationId;
+ };
+
+ const moveFromStored = async (
+ conversationId: string,
+ codeWorkspaces: NonNullable<IConversation['codeWorkspaces']>,
+ user = 'user123',
+ ) => {
+ const stored = await getConvo('user123', conversationId);
+ return methods.replaceConvoCodeEnvironmentDecision({
+ user,
+ conversationId,
+ expected: {
+ codeEnvironmentMode: stored?.codeEnvironmentMode,
+ codeWorkspaces: stored?.codeWorkspaces,
+ },
+ codeWorkspaces,
+ });
+ };
+
+ it('replaces the decision it read without disturbing timestamps', async () => {
+ const conversationId = await seedDecision({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac, team],
+ });
+
+ const result = await moveFromStored(conversationId, [team, vm]);
+
+ expect(result?.codeEnvironmentMode).toBe('attached');
+ expect(result?.codeWorkspaces).toEqual([team, vm]);
+ expect(new Date(result?.updatedAt ?? 0).toISOString()).toBe(anchor.toISOString());
+ });
+
+ it('replaces a legacy decision stored without a mode', async () => {
+ const conversationId = await seedDecision({ codeWorkspaces: [mac] });
+
+ const result = await moveFromStored(conversationId, [vm]);
+
+ expect(result?.codeEnvironmentMode).toBe('attached');
+ expect(result?.codeWorkspaces).toEqual([vm]);
+ });
+
+ it('replaces a decision that saveConvo persisted', async () => {
+ const conversationId = uuidv4();
+ await saveConvo(
+ { userId: 'user123' },
+ {
+ conversationId,
+ endpoint: EModelEndpoint.agents,
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac, team],
+ },
+ );
+ expect((await getConvo('user123', conversationId))?.codeWorkspaces).toEqual([mac, team]);
+
+ const result = await moveFromStored(conversationId, [vm]);
+
+ expect(result?.codeWorkspaces).toEqual([vm]);
+ });
+
+ it('leaves a decision that changed after it was read untouched', async () => {
+ const conversationId = await seedDecision({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac],
+ });
+ const stored = await getConvo('user123', conversationId);
+ await Conversation.collection.updateOne(
+ { conversationId },
+ { $set: { codeWorkspaces: [team] } },
+ );
+
+ const result = await methods.replaceConvoCodeEnvironmentDecision({
+ user: 'user123',
+ conversationId,
+ expected: {
+ codeEnvironmentMode: stored?.codeEnvironmentMode,
+ codeWorkspaces: stored?.codeWorkspaces,
+ },
+ codeWorkspaces: [vm],
+ });
+
+ expect(result).toBeNull();
+ const current = await getConvo('user123', conversationId);
+ expect(current?.codeWorkspaces).toEqual([team]);
+ });
+
+ it('does not treat a reordered selection list as the decision it read', async () => {
+ const conversationId = await seedDecision({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac, team],
+ });
+
+ const result = await methods.replaceConvoCodeEnvironmentDecision({
+ user: 'user123',
+ conversationId,
+ expected: { codeEnvironmentMode: 'attached', codeWorkspaces: [team, mac] },
+ codeWorkspaces: [vm],
+ });
+
+ expect(result).toBeNull();
+ });
+
+ it('cannot move another user’s conversation', async () => {
+ const conversationId = await seedDecision(
+ { codeEnvironmentMode: 'attached', codeWorkspaces: [mac] },
+ 'other-user',
+ );
+
+ const result = await methods.replaceConvoCodeEnvironmentDecision({
+ user: 'user123',
+ conversationId,
+ expected: { codeEnvironmentMode: 'attached', codeWorkspaces: [mac] },
+ codeWorkspaces: [vm],
+ });
+
+ expect(result).toBeNull();
+ const stored = await Conversation.findOne({ conversationId }).lean<IConversation>();
+ expect(stored?.codeWorkspaces).toEqual([mac]);
+ });
+ });
+
describe('saveConvo appendMessageIds', () => {
const ctx = { userId: 'append-user' };
const conversationId = 'append-conversation';
diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.ts
index 50acbccead..10ad260b8d 100644
--- a/packages/data-schemas/src/methods/conversation.ts
+++ b/packages/data-schemas/src/methods/conversation.ts
@@ -285,6 +285,12 @@ export interface ConversationMethods {
conversationId: string,
pinned: boolean,
): Promise<IConversation | null>;
+ replaceConvoCodeEnvironmentDecision(params: {
+ user: string;
+ conversationId: string;
+ expected: Pick<IConversation, 'codeEnvironmentMode' | 'codeWorkspaces'>;
+ codeWorkspaces: NonNullable<IConversation['codeWorkspaces']>;
+ }): Promise<IConversation | null>;
bulkSaveConvos(conversations: Array<Record<string, unknown>>): Promise<unknown>;
getConvosByCursor(
user: string,
@@ -2531,6 +2537,41 @@ export function createConversationMethods(
}
}
+ /**
+ * Compare-and-swap for an owner's explicit move of an attached code-environment decision.
+ * The filter repeats the stored decision being replaced, so a writer that changed it first
+ * leaves this update unmatched rather than overwritten. A missing and a null mode both
+ * describe a legacy decision inferred from its selections.
+ */
+ async function replaceConvoCodeEnvironmentDecision({
+ user,
+ conversationId,
+ expected,
+ codeWorkspaces,
+ }: {
+ user: string;
+ conversationId: string;
+ expected: Pick<IConversation, 'codeEnvironmentMode' | 'codeWorkspaces'>;
+ codeWorkspaces: NonNullable<IConversation['codeWorkspaces']>;
+ }) {
+ try {
+ const Conversation = mongoose.models.Conversation as Model<IConversation>;
+ return await Conversation.findOneAndUpdate(
+ {
+ conversationId,
+ user,
+ codeEnvironmentMode: expected.codeEnvironmentMode ?? { $in: [null] },
+ codeWorkspaces: expected.codeWorkspaces ?? { $in: [null] },
+ },
+ { $set: { codeEnvironmentMode: 'attached', codeWorkspaces } },
+ { new: true, timestamps: false },
+ ).lean<IConversation>();
+ } catch (error) {
+ logger.error('[replaceConvoCodeEnvironmentDecision] Error moving code environment', error);
+ throw new Error('Error moving code environment');
+ }
+ }
+
/**
* Saves multiple conversations in bulk.
*/
@@ -3348,6 +3389,7 @@ export function createConversationMethods(
deleteNullOrEmptyConversations,
saveConvo,
setConvoPinned,
+ replaceConvoCodeEnvironmentDecision,
bulkSaveConvos,
getConvosByCursor,
getConvosQueried,