From 4216de41c29cb078c44f2d155a2b5ff7e591cb74 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Mon, 14 Sep 2026 00:58:08 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=9B=20fix:=20Move=20Sealed=20Chats=20t?= =?UTF-8?q?o=20New=20Code=20Environments=20(#15902)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🧭 fix: Let a Sealed Chat Follow Its Agent to a New Machine A conversation's code-environment decision is sealed on its first turn, but the environment an agent uses stays editable. Pointing an agent at a different attached machine left every chat sealed to the old one with no valid move: the client showed an unusable workspace chooser, and any other selection was rejected by the server as locked. Forking copied the stale seal. The owner can now move such a chat explicitly. The composer names the machine the chat used and the one its agent uses now, and moving it goes through an owner-scoped endpoint that compare-and-swaps the persisted decision after validating the new workspace against the live worker. A move never switches the workspace of an environment the decision already covers, never upgrades a chat that continues without an attached environment, and is refused while a generation is in flight. A saved chat also no longer auto-selects a sole workspace for an environment its decision never covered, which submitted a selection the server always rejected. * fix: Hold Moves Through Terminal Saves and Move Every Target at Once A terminal claim marks a generation complete before its response save lands, and that save still writes the decision the run started with, so a move is now refused until terminalPersistencePending clears. The API advertises codeEnvironmentMoveVersion, and the client offers a move only when it is present, so a new client never exposes an endpoint an older API lacks. The move menu picks one workspace per new environment, with a sole workspace preselected, and a single confirm sends the complete target set in one request, so a partial move can no longer leave a half-migrated decision. A new machine that advertises no workspace shows its unavailable state instead of an empty section, and the confirm stays disabled. * fix: Keep Runs From Rewriting Moved Decisions and Gate Moves by Policy Every agent turn used to persist the decision it started with, so a run from any ingress that settled after a move could write the old decision back: the chat controller reads the conversation before its generation job exists, and Responses API runs never enroll one. Runs now persist a decision only for a conversation that does not store one yet, and a legacy row records only the mode it inferred, so no admission or persistence order can revert a move. Moves are now an operator setting, statefulCodeSessions.conversationMoves.enabled, off by default. The API advertises codeEnvironmentMoveVersion and accepts moves only where the effective policy enables them. A saved chat carrying attached selections no longer auto-selects a sole workspace even when selection-less decisions are not advertised, because the server seals those selections either way. * fix: Fence Moves Across Remote Runs and Let Moves Drop Unused Machines A Responses API run is keyed by its response id, so the conversation stream alone could not show it still working on a chat. A move is now refused while any generation that can still act for the conversation exists, using the same conversation-scoped enumeration conversation deletion drains. A move now validates every workspace it persists, not only the added ones, so a successful move never hands back a decision whose kept workspace is gone. A chat sealed to machines its agents no longer all use could not be sent or moved: the client trimmed the unused selection and the server rejected the trimmed set as locked. A saved chat now treats that seal as unresolvable, offers a move that drops the unused machine, and the server accepts drop-only moves. * fix: Own the Decision Fallback in TypeScript and Settle Move Caches The fields a run may persist when it never resolved a decision were chosen by a branch in AgentClient; resolvePersistableCodeEnvironmentDecision now owns that fallback too, under the same never-overwrite rule, and the CJS method only wires the request into it. Workspace choices made in the move menu belong to the chat they were made in, so another relocatable chat targeting the same machine starts undecided. A successful move cancels conversation, pinned, and list reads already in flight before writing the moved decision, so a response from before the move cannot restore the replaced decision in the cache. --- CONTEXT.md | 2 +- .../agents/__tests__/responses.unit.spec.js | 28 ++ api/server/controllers/agents/client.js | 15 +- api/server/controllers/agents/client.test.js | 48 +++ api/server/controllers/agents/responses.js | 36 +- api/server/routes/__tests__/config.spec.js | 30 ++ api/server/routes/code-environments.js | 12 + api/server/routes/code-environments.test.js | 40 +- api/server/routes/config.js | 3 + .../Chat/Input/CodeWorkspaceMenu.tsx | 363 +++++++++++++----- .../__tests__/CodeWorkspaceMenu.spec.tsx | 301 ++++++++++++++- .../src/components/Messages/Content/Error.tsx | 11 +- client/src/data-provider/CodeEnvironments.ts | 33 ++ .../__tests__/moveCodeEnvironment.test.tsx | 67 ++++ .../__tests__/useCodeWorkspace.test.tsx | 206 ++++++++++ client/src/hooks/Agents/index.ts | 7 +- client/src/hooks/Agents/useCodeWorkspace.ts | 77 +++- client/src/locales/en/translation.json | 8 + client/src/utils/errors.ts | 24 ++ packages/api/src/code/config.spec.ts | 28 ++ packages/api/src/code/config.ts | 16 +- packages/api/src/code/decision.spec.ts | 211 +++++++++- packages/api/src/code/decision.ts | 116 +++++- packages/api/src/code/http.spec.ts | 360 +++++++++++++++++ packages/api/src/code/http.ts | 297 +++++++++++--- packages/data-provider/src/api-endpoints.ts | 2 + packages/data-provider/src/code/workspace.ts | 2 + packages/data-provider/src/config.ts | 12 +- packages/data-provider/src/data-service.ts | 11 + packages/data-provider/src/keys.ts | 1 + packages/data-provider/src/types.ts | 14 + .../src/methods/conversation.spec.ts | 140 +++++++ .../data-schemas/src/methods/conversation.ts | 42 ++ 33 files changed, 2345 insertions(+), 218 deletions(-) create mode 100644 client/src/data-provider/__tests__/moveCodeEnvironment.test.tsx 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 ( } > -