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} */ -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> = { loading: 'com_ui_code_workspace_loading', @@ -16,6 +28,112 @@ const stateLabels: Partial 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, +): { 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 | 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 ( +
+ } className={headingClasses}> + {environment.name ?? environment.id} + + {workspaces.length === 0 && ( +
{emptyLabel}
+ )} + {workspaces.map((descriptor) => { + const selected = isSelected(descriptor.id); + return ( + onSelect({ environmentId: environment.id, workspaceId: descriptor.id })} + className={menuItemClasses(selected)} + > + + ); + })} +
+ ); +} + 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; + } | 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 ( } > -