From 1163045cef65e3acae3c7f7aeab9061cb0da76e5 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Sat, 12 Sep 2026 20:45:00 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=96=8B=EF=B8=8F=20feat:=20Seal=20Code=20E?= =?UTF-8?q?nvironment=20Choices=20Per=20Conversation=20(#15868)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: lock code environments per conversation * style: Sort code environment imports * fix: Harden code environment decisions * fix: Preserve code environment rollout compatibility * fix: Harden code environment boundaries * refactor: Centralize code environment policy * test: Restore partial disconnect policy mock * fix: Close code environment edge paths * fix: Preserve implicit stateful code routes * fix: Stabilize implicit code routing * test: Align remote workspace contract * chore: Sort code route import --- .env.example | 4 + CONTEXT.md | 1 + .../agents/__tests__/openai.spec.js | 17 ++ .../request.partialDisconnect.spec.js | 2 + .../__tests__/request.resumeMetadata.spec.js | 100 ++++++- .../agents/__tests__/responses.unit.spec.js | 46 +++ .../agents/__tests__/resume.spec.js | 27 ++ api/server/controllers/agents/client.js | 24 +- api/server/controllers/agents/client.test.js | 28 ++ api/server/controllers/agents/openai.js | 10 +- api/server/controllers/agents/request.js | 33 ++- api/server/controllers/agents/responses.js | 32 ++- api/server/controllers/agents/resume.js | 11 +- api/server/routes/__tests__/config.spec.js | 25 ++ api/server/routes/config.js | 5 + .../services/Endpoints/agents/initialize.js | 67 +++-- .../Endpoints/agents/initialize.spec.js | 104 ++++++- client/src/components/Chat/Input/ChatForm.tsx | 44 +-- .../Chat/Input/CodeWorkspaceMenu.tsx | 253 ++++++++++------- .../__tests__/CodeWorkspaceMenu.spec.tsx | 138 +++++++-- .../src/components/Messages/Content/Error.tsx | 1 + .../__tests__/useCodeWorkspace.test.tsx | 69 +++-- client/src/hooks/Agents/useCodeWorkspace.ts | 75 ++++- client/src/hooks/Agents/useSelectAgent.ts | 3 + .../useChatFunctions.regenerate.spec.tsx | 9 +- client/src/hooks/Chat/useChatFunctions.ts | 10 +- client/src/hooks/useNewConvo.ts | 4 +- client/src/locales/en/translation.json | 6 +- .../src/agents/__tests__/initialize.test.ts | 268 ++++++++++++++++++ packages/api/src/agents/hitl/policy.spec.ts | 47 +++ packages/api/src/agents/hitl/policy.ts | 35 +++ packages/api/src/agents/initialize.ts | 56 +++- .../api/src/agents/openai/service.spec.ts | 26 ++ packages/api/src/agents/openai/service.ts | 10 +- packages/api/src/agents/openai/types.ts | 2 - packages/api/src/agents/responses/service.ts | 8 +- packages/api/src/agents/responses/types.ts | 2 + packages/api/src/code/capabilities.spec.ts | 33 +++ packages/api/src/code/capabilities.ts | 45 ++- packages/api/src/code/config.spec.ts | 27 +- packages/api/src/code/config.ts | 25 +- packages/api/src/code/decision.spec.ts | 123 ++++++++ packages/api/src/code/decision.ts | 104 +++++++ packages/api/src/code/errors.spec.ts | 42 ++- packages/api/src/code/errors.ts | 26 ++ packages/api/src/code/index.ts | 1 + packages/api/src/code/remoteWorkspace.spec.ts | 53 ++-- packages/api/src/mcp/request.ts | 3 + packages/api/src/mcp/types/index.ts | 2 +- packages/api/src/types/http.ts | 2 + .../data-provider/specs/codeWorkspace.spec.ts | 16 +- .../data-provider/specs/createPayload.spec.ts | 2 + packages/data-provider/src/code/workspace.ts | 9 + packages/data-provider/src/config.ts | 4 + packages/data-provider/src/createPayload.ts | 2 + packages/data-provider/src/schemas.ts | 3 +- packages/data-provider/src/types.ts | 5 + packages/data-provider/src/types/agents.ts | 2 + packages/data-schemas/src/schema/defaults.ts | 10 +- packages/data-schemas/src/types/convo.ts | 2 + 60 files changed, 1843 insertions(+), 300 deletions(-) create mode 100644 packages/api/src/code/decision.spec.ts create mode 100644 packages/api/src/code/decision.ts diff --git a/.env.example b/.env.example index 1a6a27ee35..42b88f61bc 100644 --- a/.env.example +++ b/.env.example @@ -729,6 +729,10 @@ TTS_API_KEY= #==================================================# # LIBRECHAT_CODE_API_KEY= + +# Advertise the immutable per-conversation code-environment decision protocol. +# Enable only after every LibreChat API replica runs a version that supports protocol v1. +# CODE_ENVIRONMENT_DECISION_VERSION=1 # LIBRECHAT_CODE_BASEURL= # Current self-hosted Code Interpreter deployments use per-user LibreChat JWTs outside local mode. # Configure the matching public verifier on Code Interpreter; see: diff --git a/CONTEXT.md b/CONTEXT.md index 1fa1202774..061c21700b 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -3,6 +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. - **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__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.js index c82c0ac51b..ff2b5235bb 100644 --- a/api/server/controllers/agents/__tests__/openai.spec.js +++ b/api/server/controllers/agents/__tests__/openai.spec.js @@ -217,14 +217,27 @@ jest.mock('@librechat/api', () => ({ buildInitialToolSessions: jest.fn().mockReturnValue(mockInitialSessions), AgentRunEnvelopeError: MockAgentRunEnvelopeError, createAgentRunEnvelope: (...args) => mockCreateAgentRunEnvelope(...args), + resolveConversationCodeEnvironmentDecision: ({ + requestedMode, + requestedSelections, + conversation, + }) => { + const codeWorkspaces = requestedSelections ?? conversation?.codeWorkspaces; + return { + mode: requestedMode ?? (codeWorkspaces?.length ? 'attached' : 'without_attached'), + ...(codeWorkspaces !== undefined && { codeWorkspaces }), + }; + }, createMCPRuntimeRequestBody: ({ messageId, conversationId, parentMessageId, + codeEnvironmentMode, codeWorkspaces, }) => ({ messageId, conversationId, + ...(codeEnvironmentMode !== undefined && { codeEnvironmentMode }), ...(codeWorkspaces !== undefined && { codeWorkspaces }), ...(parentMessageId !== undefined && { parentMessageId: parentMessageId ?? '00000000-0000-0000-0000-000000000000', @@ -1608,6 +1621,7 @@ describe('OpenAIChatCompletionController', () => { messageId: 'chatcmpl-mock-nanoid-123', conversationId: 'conversation-123', parentMessageId: 'parent-123', + codeEnvironmentMode: 'without_attached', }, }), expect.anything(), @@ -1618,6 +1632,7 @@ describe('OpenAIChatCompletionController', () => { messageId: 'chatcmpl-mock-nanoid-123', conversationId: 'conversation-123', parentMessageId: 'parent-123', + codeEnvironmentMode: 'without_attached', }, }), ); @@ -1629,6 +1644,7 @@ describe('OpenAIChatCompletionController', () => { messageId: 'chatcmpl-mock-nanoid-123', conversationId: 'conversation-123', parentMessageId: 'parent-123', + codeEnvironmentMode: 'without_attached', }, }), }), @@ -1655,6 +1671,7 @@ describe('OpenAIChatCompletionController', () => { expect(requestBody).toEqual({ messageId: 'chatcmpl-mock-nanoid-123', conversationId: 'conversation-123', + codeEnvironmentMode: 'without_attached', }); expect(requestBody).not.toHaveProperty('parentMessageId'); }); diff --git a/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js b/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js index 742917090c..90b9c89a33 100644 --- a/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js +++ b/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js @@ -65,6 +65,8 @@ jest.mock('@librechat/api', () => ({ resolveTitleTiming: jest.fn(() => 'immediate'), resolveConversationAnchor: jest.requireActual('@librechat/api').resolveConversationAnchor, resolveRunCodeWorkspaces: jest.requireActual('@librechat/api').resolveRunCodeWorkspaces, + shouldPersistCodeWorkspaceInitializationError: + jest.requireActual('@librechat/api').shouldPersistCodeWorkspaceInitializationError, getSafeErrorMetadata: jest.requireActual('@librechat/api').getSafeErrorMetadata, getSafeErrorText: jest.requireActual('@librechat/api').getSafeErrorText, GenerationJobManager: mockGenerationJobManager, diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js index 3d8d74b261..b6f2dcba01 100644 --- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js +++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js @@ -278,6 +278,8 @@ jest.mock('@librechat/api', () => ({ encodeAndFormatImages: jest.requireActual('@librechat/api').encodeAndFormatImages, getCodeWorkspaceSelectionErrorDetails: jest.requireActual('@librechat/api').getCodeWorkspaceSelectionErrorDetails, + shouldPersistCodeWorkspaceInitializationError: + jest.requireActual('@librechat/api').shouldPersistCodeWorkspaceInitializationError, getSafeErrorMetadata: jest.requireActual('@librechat/api').getSafeErrorMetadata, getSafeErrorText: jest.requireActual('@librechat/api').getSafeErrorText, GenerationJobManager: mockGenerationJobManager, @@ -337,11 +339,13 @@ jest.mock('@librechat/api', () => ({ messageId, conversationId, parentMessageId, + codeEnvironmentMode, codeWorkspaces, }) => ({ messageId, conversationId, parentMessageId, + ...(codeEnvironmentMode !== undefined ? { codeEnvironmentMode } : {}), ...(codeWorkspaces !== undefined ? { codeWorkspaces } : {}), }), })); @@ -1430,6 +1434,53 @@ describe('ResumableAgentController resume metadata', () => { expect(requestBody.messageId).not.toBe(req.body.messageId); }); + it('pins a normalized code-environment decision before provider execution', async () => { + let signalProviderStarted; + const providerStarted = new Promise((resolve) => { + signalProviderStarted = resolve; + }); + const sendMessage = jest.fn(() => { + signalProviderStarted(); + return new Promise(() => {}); + }); + const initializeClient = jest.fn(async ({ req }) => { + req.body.codeEnvironmentMode = 'without_attached'; + delete req.body.codeWorkspaces; + return { client: { options: {}, sendMessage } }; + }); + const req = { + user: { id: 'user-123' }, + body: { + text: 'Continue without my attached machine.', + messageId: 'incoming-client-message', + parentMessageId: 'previous-response', + conversationId: 'conversation-123', + endpointOption: { endpoint: 'agents', modelOptions: { model: 'gpt-4.1' } }, + }, + config: {}, + }; + + await AgentController(req, createResumableResponse(), jest.fn(), initializeClient, null); + await providerStarted; + + const initialRequestBody = + mockGenerationJobManager.createJob.mock.calls[0][3].initialMetadata.mcpRequestBody; + expect(initialRequestBody).not.toHaveProperty('codeEnvironmentMode'); + expect(mockGenerationJobManager.updateMetadata).toHaveBeenCalledWith( + 'conversation-123', + { + mcpRequestBody: { + ...initialRequestBody, + codeEnvironmentMode: 'without_attached', + }, + }, + 1000, + ); + expect(mockGenerationJobManager.updateMetadata.mock.invocationCallOrder[0]).toBeLessThan( + sendMessage.mock.invocationCallOrder[0], + ); + }); + it('uses the effective overridden conversation in the MCP request body', async () => { const initializeClient = jest.fn().mockRejectedValue(new Error('stop after MCP discovery')); const req = { @@ -3786,6 +3837,36 @@ describe('ResumableAgentController resume metadata', () => { expect(mockSaveConvo).not.toHaveBeenCalled(); }); + it('does not persist a first turn whose code environment decision was rejected', async () => { + const res = createResumableResponse(); + mockGenerationJobManager.claimGeneration.mockImplementation( + async (_userId, _clientRequestId, streamId, claimedConversationId) => + wonGenerationClaim({ streamId, conversationId: claimedConversationId }), + ); + const req = createFailedRequest({ + conversationId: undefined, + clientRequestId: 'invalid-code-decision', + codeEnvironmentMode: 'attached', + codeWorkspaces: undefined, + }); + const workspaceError = Object.assign(new Error('Choose an attached workspace'), { + code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, + reason: 'required', + status: 409, + statusCode: 409, + }); + + await AgentController(req, res, jest.fn(), jest.fn().mockRejectedValue(workspaceError), null); + + expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith( + expect.any(String), + expect.stringContaining(ErrorTypes.CODE_WORKSPACE_UNAVAILABLE), + 1000, + ); + expect(mockSaveMessage).not.toHaveBeenCalled(); + expect(mockSaveConvo).not.toHaveBeenCalled(); + }); + it('creates the conversation row for a failed first turn', async () => { const res = createResumableResponse(); mockGenerationJobManager.claimGeneration.mockImplementation( @@ -3803,15 +3884,18 @@ describe('ResumableAgentController resume metadata', () => { modelOptions: { model: 'gpt-4o' }, chatProjectId: '507f1f77bcf86cd799439011', }, + codeEnvironmentMode: 'attached', + codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }], + }); + const initializeClient = jest.fn().mockImplementation(async ({ req: request }) => { + request._codeEnvironmentDecision = { + mode: 'attached', + codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }], + }; + throw new Error('model unavailable'); }); - await AgentController( - req, - res, - jest.fn(), - jest.fn().mockRejectedValue(new Error('model unavailable')), - null, - ); + await AgentController(req, res, jest.fn(), initializeClient, null); const mintedConversationId = res.json.mock.calls[0][0].conversationId; expect(mockSaveMessage).toHaveBeenCalledWith( @@ -3829,6 +3913,8 @@ describe('ResumableAgentController resume metadata', () => { endpoint: 'azureOpenAI', model: 'gpt-4o', chatProjectId: '507f1f77bcf86cd799439011', + codeEnvironmentMode: 'attached', + codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }], }), expect.objectContaining({ initialAgentId: null }), ); diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.js index e639f015e5..41e07fffb5 100644 --- a/api/server/controllers/agents/__tests__/responses.unit.spec.js +++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js @@ -236,15 +236,28 @@ jest.mock('@librechat/api', () => ({ buildRunToolSet: jest.fn().mockReturnValue(new Set()), AgentRunEnvelopeError: MockAgentRunEnvelopeError, createAgentRunEnvelope: (...args) => mockCreateAgentRunEnvelope(...args), + resolveConversationCodeEnvironmentDecision: ({ + requestedMode, + requestedSelections, + conversation, + }) => { + const codeWorkspaces = requestedSelections ?? conversation?.codeWorkspaces; + return { + mode: requestedMode ?? (codeWorkspaces?.length ? 'attached' : 'without_attached'), + ...(codeWorkspaces !== undefined && { codeWorkspaces }), + }; + }, getCodeWorkspaceSelections: jest.fn(), createMCPRuntimeRequestBody: ({ messageId, conversationId, parentMessageId, + codeEnvironmentMode, codeWorkspaces, }) => ({ messageId, conversationId, + ...(codeEnvironmentMode !== undefined && { codeEnvironmentMode }), ...(codeWorkspaces !== undefined && { codeWorkspaces }), ...(parentMessageId !== undefined && { parentMessageId: parentMessageId ?? '00000000-0000-0000-0000-000000000000', @@ -611,6 +624,38 @@ describe('createResponse controller', () => { }, ); + it.each([false, true])( + 'persists the normalized no-attached decision atomically: stream=%s', + async (stream) => { + const api = require('@librechat/api'); + const db = require('~/models'); + api.getCodeWorkspaceSelections.mockReturnValueOnce([ + { environmentId: 'machine', workspaceId: 'stale-project' }, + ]); + api.validateResponseRequest.mockReturnValueOnce({ + request: { + model: 'agent-123', + input: 'Hello', + stream, + store: true, + code_environment_mode: 'without_attached', + }, + }); + + await createResponse(req, res); + + expect(db.saveConvo).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + codeEnvironmentMode: 'without_attached', + }), + expect.anything(), + ); + expect(db.saveConvo.mock.calls.at(-1)[1]).not.toHaveProperty('codeWorkspaces'); + expect(api.getCodeWorkspaceSelections).not.toHaveBeenCalled(); + }, + ); + it('enrolls, starts, and settles the remote execution lifecycle', async () => { await createResponse(req, res); @@ -905,6 +950,7 @@ describe('createResponse controller', () => { requestBody: { messageId: 'resp_mock-123', conversationId: expect.any(String), + codeEnvironmentMode: 'without_attached', }, }), expect.anything(), diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.js index dde2514f66..d83ef745ed 100644 --- a/api/server/controllers/agents/__tests__/resume.spec.js +++ b/api/server/controllers/agents/__tests__/resume.spec.js @@ -2461,6 +2461,33 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { await flush(); }); + it('enforces the current fingerprint while retaining the rolling-deploy digest', async () => { + const { computeAgentRequestFingerprint, computeLegacyAgentRequestFingerprint } = + jest.requireActual('@librechat/api'); + const pausedBody = { + endpoint: 'agents', + agent_id: AGENT_ID, + codeEnvironmentMode: 'attached', + codeWorkspaces: [{ environmentId: 'machine-a', workspaceId: 'project-a' }], + }; + const job = makeToolApprovalJob(); + job.metadata.pendingAction.requestFingerprint = + computeLegacyAgentRequestFingerprint(pausedBody); + job.metadata.pendingAction.requestFingerprintV2 = computeAgentRequestFingerprint(pausedBody); + mockGenerationJobManager.getJob.mockResolvedValue(job); + + const res = await post( + approveBody({ + codeEnvironmentMode: 'attached', + codeWorkspaces: [{ environmentId: 'machine-a', workspaceId: 'project-b' }], + }), + ); + + expect(res.status).toBe(403); + expect(res.body.error).toMatch(/different agent configuration/i); + expect(mockGenerationJobManager.approvals.resolve).not.toHaveBeenCalled(); + }); + it('403 when the resume sends a different promptPrefix than the paused config', async () => { const { computeAgentRequestFingerprint } = jest.requireActual('@librechat/api'); const job = makeToolApprovalJob(); diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js index f9370fdabc..fc61f61c58 100644 --- a/api/server/controllers/agents/client.js +++ b/api/server/controllers/agents/client.js @@ -43,8 +43,8 @@ const { buildPendingAction, toClientPendingAction, captureCodeExecutionApprovalBinding, - getCodeWorkspaceSelections, computeAgentRequestFingerprint, + computeLegacyAgentRequestFingerprint, getRunDiscoveredTools, captureResumeModelParameters, pickResumeContext, @@ -1999,6 +1999,7 @@ class AgentClient extends BaseClient { collectAttachedCodeEnvironmentPolicySettings(topLevelAgents), agentsEConfig?.toolApproval?.enabled !== false, ); + const codeEnvironmentDecision = this.options.req._codeEnvironmentDecision; return removeNullishValues( Object.assign( @@ -2013,9 +2014,12 @@ class AgentClient extends BaseClient { imageDetail: this.options.imageDetail, maxContextTokens: this.maxContextTokens, codeApprovalMode, - codeWorkspaces: getCodeWorkspaceSelections( - collectReachableAgents(topLevelAgents).map((agent) => agent?.codeExecutionContext), - ), + codeEnvironmentMode: + codeEnvironmentDecision?.mode ?? this.options.req.body.codeEnvironmentMode, + codeWorkspaces: + codeEnvironmentDecision != null + ? codeEnvironmentDecision.codeWorkspaces + : this.options.req.body.codeWorkspaces, }, // TODO: PARSE OPTIONS BY PROVIDER, MAY CONTAIN SENSITIVE DATA runOptions, @@ -4310,7 +4314,11 @@ class AgentClient extends BaseClient { // Pin the graph-determining request fields so resume can't rebuild this paused // run on a different agent/tool set (esp. ephemeral agents, whose agent_id is // undefined so the id guard can't tell two configs apart). - requestFingerprint: computeAgentRequestFingerprint(this.options.req?.body ?? {}), + // Keep the legacy digest in its established field so an old replica can + // resume pauses written during a rolling deploy; current replicas also + // enforce the stricter code-environment-aware digest below. + requestFingerprint: computeLegacyAgentRequestFingerprint(this.options.req?.body ?? {}), + requestFingerprintV2: computeAgentRequestFingerprint(this.options.req?.body ?? {}), // Persist those same fields verbatim so the resume route can REPLAY them — a // reload/cross-replica resume can't reconstruct the ephemeral config client-side, // so the server restores it and rebuilds the same graph (and the fingerprint matches). @@ -4516,6 +4524,9 @@ class AgentClient extends BaseClient { messageId: this.responseMessageId, conversationId: this.conversationId, parentMessageId: this.parentMessageId, + codeEnvironmentMode: + this.options.req.body.codeEnvironmentMode ?? + this.options.req.resolvedConversation?.codeEnvironmentMode, codeWorkspaces: this.options.req.body.codeWorkspaces ?? this.options.req.resolvedConversation?.codeWorkspaces, @@ -5300,6 +5311,9 @@ class AgentClient extends BaseClient { messageId: this.responseMessageId, conversationId: this.conversationId, parentMessageId: this.parentMessageId, + codeEnvironmentMode: + this.options.req.body.codeEnvironmentMode ?? + this.options.req.resolvedConversation?.codeEnvironmentMode, codeWorkspaces: this.options.req.body.codeWorkspaces ?? this.options.req.resolvedConversation?.codeWorkspaces, diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.js index 9cc76615c5..54b869ca88 100644 --- a/api/server/controllers/agents/client.test.js +++ b/api/server/controllers/agents/client.test.js @@ -78,18 +78,46 @@ describe('AgentClient code approval persistence', () => { }, req: { body: { codeApprovalMode: 'acceptEdits' }, + _codeEnvironmentDecision: { + mode: 'attached', + codeWorkspaces: [ + { environmentId: 'attached-vm', workspaceId: 'project-a' }, + { environmentId: 'team-vm', workspaceId: 'project-b' }, + ], + }, config: { endpoints: { [EModelEndpoint.agents]: {} } }, }, }; expect(client.getSaveOptions()).toMatchObject({ codeApprovalMode: 'acceptEdits', + codeEnvironmentMode: 'attached', codeWorkspaces: [ { environmentId: 'attached-vm', workspaceId: 'project-a' }, { environmentId: 'team-vm', workspaceId: 'project-b' }, ], }); }); + + it('does not combine a normalized no-attached mode with stale request selections', () => { + const client = Object.create(AgentClient.prototype); + client.agentConfigs = new Map(); + client.options = { + endpoint: EModelEndpoint.agents, + agent: { id: 'attached-agent' }, + req: { + body: { + codeWorkspaces: [{ environmentId: 'attached-vm', workspaceId: 'stale-project' }], + }, + _codeEnvironmentDecision: { mode: 'without_attached' }, + config: { endpoints: { [EModelEndpoint.agents]: {} } }, + }, + }; + + const saveOptions = client.getSaveOptions(); + expect(saveOptions.codeEnvironmentMode).toBe('without_attached'); + expect(saveOptions).not.toHaveProperty('codeWorkspaces'); + }); }); function deferred() { diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js index 36713ee168..c7659fb526 100644 --- a/api/server/controllers/agents/openai.js +++ b/api/server/controllers/agents/openai.js @@ -67,6 +67,7 @@ const { executeAgentRun, waitForAgentExecutionWrites, resolveToolRoleGrants, + resolveConversationCodeEnvironmentDecision, createTerminalRunErrorObserver, } = require('@librechat/api'); const { @@ -456,6 +457,12 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => { req.resolvedConversation = conversation; } + const codeEnvironmentDecision = resolveConversationCodeEnvironmentDecision({ + conversationId, + requestedMode: request.code_environment_mode, + requestedSelections: request.code_workspaces, + conversation: req.resolvedConversation, + }); const parentMessageId = request.parent_message_id ?? null; let mcpParentMessageId; if ( @@ -469,7 +476,8 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => { const mcpRequestBody = createMCPRuntimeRequestBody({ messageId: responseId, conversationId, - codeWorkspaces: request.code_workspaces ?? req.resolvedConversation?.codeWorkspaces, + codeEnvironmentMode: codeEnvironmentDecision.mode, + codeWorkspaces: codeEnvironmentDecision.codeWorkspaces, parentMessageId: mcpParentMessageId, }); diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.js index b2e3904d20..d4ea75e173 100644 --- a/api/server/controllers/agents/request.js +++ b/api/server/controllers/agents/request.js @@ -44,6 +44,7 @@ const { resolveAgentTurnExecutionPlan, logAgentMemorySnapshot, getCodeWorkspaceSelectionErrorDetails, + shouldPersistCodeWorkspaceInitializationError, } = require('@librechat/api'); const { disposeClient } = require('~/server/cleanup'); const { @@ -491,6 +492,7 @@ async function saveErrorTurn( const agentId = endpointOption?.agent_id ?? req.body?.agent_id; const chatProjectId = endpointOption?.chatProjectId ?? req.body?.chatProjectId; const seedConvo = isNewConvo || req.resolvedConversation === null; + const codeEnvironmentDecision = req._codeEnvironmentDecision; const convoFields = seedConvo ? { ...(endpoint != null && { endpoint }), @@ -502,6 +504,12 @@ async function saveErrorTurn( ...(endpointOption?.spec != null && { spec: endpointOption.spec }), ...(agentId != null && { agent_id: agentId }), ...(typeof chatProjectId === 'string' && chatProjectId.length > 0 && { chatProjectId }), + ...(codeEnvironmentDecision?.mode != null && { + codeEnvironmentMode: codeEnvironmentDecision.mode, + ...(codeEnvironmentDecision.codeWorkspaces != null && { + codeWorkspaces: codeEnvironmentDecision.codeWorkspaces, + }), + }), } : {}; await saveConvo( @@ -1487,6 +1495,7 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit const mcpRequestBody = createMCPRuntimeRequestBody({ messageId: preallocatedResponseMessageId, conversationId: effectiveConversationId, + codeEnvironmentMode: req.body.codeEnvironmentMode, codeWorkspaces: resolveRunCodeWorkspaces({ conversationId: effectiveConversationId, requestedSelections: req.body.codeWorkspaces, @@ -1920,6 +1929,22 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit }); startupTelemetry?.mark('client_initialized'); client = result.client; + const normalizedMCPRequestBody = createMCPRuntimeRequestBody({ + messageId: mcpRequestBody.messageId, + conversationId: mcpRequestBody.conversationId, + codeEnvironmentMode: req.body.codeEnvironmentMode, + codeWorkspaces: req.body.codeWorkspaces, + ...(Object.prototype.hasOwnProperty.call(mcpRequestBody, 'parentMessageId') && { + parentMessageId: mcpRequestBody.parentMessageId, + }), + }); + if (JSON.stringify(normalizedMCPRequestBody) !== JSON.stringify(mcpRequestBody)) { + await GenerationJobManager.updateMetadata( + streamId, + { mcpRequestBody: normalizedMCPRequestBody }, + jobCreatedAt, + ); + } if ( typeof client?.options?.agent?.id === 'string' && !isEphemeralAgentId(client.options.agent.id) @@ -3384,7 +3409,13 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit const initializationError = initializationFailure ? JSON.stringify(initializationFailure) : error.message || 'Failed to start generation'; - const completionPromise = streamStarted + const persistInitializationError = shouldPersistCodeWorkspaceInitializationError({ + streamStarted, + isNewConversation: isNewConvo, + failureCode: initializationFailure?.code, + hasValidatedDecision: req._codeEnvironmentDecision != null, + }); + const completionPromise = persistInitializationError ? GenerationJobManager.completeJob(streamId, initializationError, jobCreatedAt, { beforeErrorPublication: () => saveErrorTurn(req, { diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js index 367fd04bc0..328052fe04 100644 --- a/api/server/controllers/agents/responses.js +++ b/api/server/controllers/agents/responses.js @@ -18,8 +18,6 @@ const { createAgentRunEnvelope, createAgentExecutionContext, createMCPRuntimeRequestBody, - getCodeWorkspaceSelections, - collectReachableAgents, buildAgentScopedContext, buildInlineMemoryContext, buildAgentContextAttachmentsByAgentId, @@ -84,6 +82,7 @@ const { executeAgentRun, waitForAgentExecutionWrites, resolveToolRoleGrants, + resolveConversationCodeEnvironmentDecision, createTerminalRunErrorObserver, } = require('@librechat/api'); const { @@ -449,7 +448,14 @@ async function saveResponseOutput( * @param {object} agent * @returns {Promise} */ -async function saveConversation(req, conversationId, agentId, agent, codeWorkspaces) { +async function saveConversation( + req, + conversationId, + agentId, + agent, + codeEnvironmentMode, + codeWorkspaces, +) { const title = resolveConversationTitle(req, agent?.name || 'Open Responses Conversation'); await db.saveConvo( { @@ -462,6 +468,7 @@ async function saveConversation(req, conversationId, agentId, agent, codeWorkspa conversationId, endpoint: EModelEndpoint.agents, agent_id: agentId, + codeEnvironmentMode, ...(codeWorkspaces !== undefined && { codeWorkspaces }), ...(title != null && { title }), model: agent?.model, @@ -705,11 +712,18 @@ const executeResponse = async (envelope, { req, res }) => { } } + const codeEnvironmentDecision = resolveConversationCodeEnvironmentDecision({ + conversationId, + requestedMode: request.code_environment_mode, + requestedSelections: request.code_workspaces, + conversation: req.resolvedConversation, + }); const parentMessageId = null; const mcpRequestBody = createMCPRuntimeRequestBody({ messageId: responseId, conversationId, - codeWorkspaces: request.code_workspaces ?? req.resolvedConversation?.codeWorkspaces, + codeEnvironmentMode: codeEnvironmentDecision.mode, + codeWorkspaces: codeEnvironmentDecision.codeWorkspaces, }); const agentsEConfig = appConfig?.endpoints?.[EModelEndpoint.agents]; const ordinaryToolCancellationEnabled = @@ -1342,9 +1356,8 @@ const executeResponse = async (envelope, { req, res }) => { conversationId, agentId, agent, - getCodeWorkspaceSelections( - collectReachableAgents(runAgents).map((config) => config.codeExecutionContext), - ), + codeEnvironmentDecision.mode, + codeEnvironmentDecision.codeWorkspaces, ); // Save input messages @@ -1582,9 +1595,8 @@ const executeResponse = async (envelope, { req, res }) => { conversationId, agentId, agent, - getCodeWorkspaceSelections( - collectReachableAgents(runAgents).map((config) => config.codeExecutionContext), - ), + codeEnvironmentDecision.mode, + codeEnvironmentDecision.codeWorkspaces, ); await saveInputMessages(req, conversationId, inputMessages, agentId); diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.js index 793e89568b..284027e51d 100644 --- a/api/server/controllers/agents/resume.js +++ b/api/server/controllers/agents/resume.js @@ -23,6 +23,7 @@ const { findDisallowedDecisions, findIncompleteDecisions, computeAgentRequestFingerprint, + computeLegacyAgentRequestFingerprint, captureAgentCheckpointGeneration, deleteAgentCheckpoint, buildAbortedResponseMetadata, @@ -917,7 +918,13 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) // when the paused action carries a fingerprint (in-flight pauses from before this // change won't), and recomputed from the resume body's graph-determining fields. const pinnedFingerprint = pendingAction.requestFingerprint; - if (pinnedFingerprint && pinnedFingerprint !== computeAgentRequestFingerprint(req.body ?? {})) { + const pinnedFingerprintV2 = pendingAction.requestFingerprintV2; + const legacyFingerprint = computeLegacyAgentRequestFingerprint(req.body ?? {}); + const currentFingerprint = computeAgentRequestFingerprint(req.body ?? {}); + if ( + (pinnedFingerprint && pinnedFingerprint !== legacyFingerprint) || + (pinnedFingerprintV2 && pinnedFingerprintV2 !== currentFingerprint) + ) { return sendGenerationJson( res, 403, @@ -1822,6 +1829,8 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) createMCPRuntimeRequestBody({ messageId: job.metadata.responseMessageId, conversationId: streamId, + codeEnvironmentMode: + req.body.codeEnvironmentMode ?? req.resolvedConversation?.codeEnvironmentMode, codeWorkspaces: req.body.codeWorkspaces ?? req.resolvedConversation?.codeWorkspaces, parentMessageId: job.metadata.userMessage?.messageId ?? Constants.NO_PARENT, }); diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.js index 529879ce9a..0ef6122842 100644 --- a/api/server/routes/__tests__/config.spec.js +++ b/api/server/routes/__tests__/config.spec.js @@ -116,6 +116,7 @@ afterEach(() => { delete process.env.LANGFUSE_TRACING_ENABLED; delete process.env.LANGFUSE_SAMPLE_RATE; delete process.env.TENANT_ISOLATION_STRICT; + delete process.env.CODE_ENVIRONMENT_DECISION_VERSION; }); describe('GET /api/config', () => { @@ -350,8 +351,32 @@ describe('GET /api/config', () => { expect(response.body.modelSpecs).toEqual({ list: [{ name: 'test-spec' }] }); expect(response.body.balance).toEqual({ enabled: true, startBalance: 10000 }); expect(response.body.webSearch).toEqual({ searchProvider: 'tavily' }); + expect(response.body.codeEnvironmentDecisionVersion).toBeUndefined(); }); + it('advertises code environment decisions only after deployment-wide activation', async () => { + mockGetAppConfig.mockResolvedValue(baseAppConfig); + process.env.CODE_ENVIRONMENT_DECISION_VERSION = '1'; + const app = createApp(mockUser); + + const response = await request(app).get('/api/config'); + + expect(response.body.codeEnvironmentDecisionVersion).toBe(1); + }); + + it.each(['0', '2', '1.0', 'true'])( + 'does not advertise unsupported code environment decision version %s', + async (version) => { + mockGetAppConfig.mockResolvedValue(baseAppConfig); + process.env.CODE_ENVIRONMENT_DECISION_VERSION = version; + const app = createApp(mockUser); + + const response = await request(app).get('/api/config'); + + expect(response.body.codeEnvironmentDecisionVersion).toBeUndefined(); + }, + ); + it('should strip private prompt fields from model spec presets', async () => { mockGetAppConfig.mockResolvedValue({ ...baseAppConfig, diff --git a/api/server/routes/config.js b/api/server/routes/config.js index 4f584b40c5..99ab46ad4e 100644 --- a/api/server/routes/config.js +++ b/api/server/routes/config.js @@ -12,6 +12,7 @@ const { excludeHiddenModelSpecs, isFileSnapshotEnabled, getEndpointsDropParamsMap, + resolveCodeEnvironmentDecisionVersion, } = require('@librechat/api'); const { EModelEndpoint, defaultSocialLogins } = require('librechat-data-provider'); const { logger, getTenantId, SystemCapabilities } = require('@librechat/data-schemas'); @@ -249,6 +250,9 @@ router.get('/', async function (req, res) { } const appConfig = await getAppConfig(getAppConfigOptionsFromUser(req.user)); + const codeEnvironmentDecisionVersion = resolveCodeEnvironmentDecisionVersion( + process.env.CODE_ENVIRONMENT_DECISION_VERSION, + ); const endpointsDropParamsMap = getEndpointsDropParamsMap(appConfig?.endpoints); @@ -309,6 +313,7 @@ router.get('/', async function (req, res) { langfuseConnectionAccess, insightsEnabled: isEnabled(process.env.ENABLE_INSIGHTS), compactionEnabled: appConfig?.summarization?.enabled !== false, + ...(codeEnvironmentDecisionVersion != null ? { codeEnvironmentDecisionVersion } : {}), ...(cloudFront ? { cloudFront } : {}), ...(rum ? { rum } : {}), fileUploadSseEnabled: isEnabled(process.env.FILE_UPLOAD_SSE_ENABLED), diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js index 286b0b412f..aad58efc5e 100644 --- a/api/server/services/Endpoints/agents/initialize.js +++ b/api/server/services/Endpoints/agents/initialize.js @@ -3,6 +3,7 @@ const { createContentAggregator, GraphNodeKeys } = require('@librechat/agents'); const { resolveSender, resolveRunConversation, + resolveConversationCodeEnvironmentDecision, createConcurrencyLimiter, loadSkillStates, initializeAgent, @@ -23,6 +24,8 @@ const { getLazySubagentConfigId, resolveCodeExecutionContext, resolveCodeExecutionWorkspaceContext, + optsOutOfAttachedCodeEnvironment, + isImplicitStatefulCodeRouteAvailable, createStatefulCodeEnvironmentPolicyError, buildSubagentThreadTaskConfig, backgroundCompletionWakeupsEnabled, @@ -206,7 +209,7 @@ const initializeClient = async ({ /** The normal controller resolves this once for timestamp anchoring. Reuse * that trusted document for child-thread execution policy; resume and direct * callers fall back to the same owner-scoped lookup. */ - const runtimeRequestBody = requestBody ?? req.body; + let runtimeRequestBody = requestBody ?? req.body; const conversationId = runtimeRequestBody?.conversationId; const requestConversationPromise = resolveRunConversation({ request: req, @@ -584,6 +587,25 @@ const initializeClient = async ({ ]); /** Preserve the owner-scoped fallback for loaders that share this request. */ req.resolvedConversation = requestConversation; + const codeEnvironmentDecision = resolveConversationCodeEnvironmentDecision({ + conversationId, + requestedMode: runtimeRequestBody?.codeEnvironmentMode, + requestedSelections: runtimeRequestBody?.codeWorkspaces, + conversation: requestConversation, + }); + /** Trusted, normalized pair used by every persistence path, including init failures. */ + req._codeEnvironmentDecision = codeEnvironmentDecision; + runtimeRequestBody = { + ...runtimeRequestBody, + codeEnvironmentMode: codeEnvironmentDecision.mode, + codeWorkspaces: codeEnvironmentDecision.codeWorkspaces, + }; + req.body.codeEnvironmentMode = codeEnvironmentDecision.mode; + if (codeEnvironmentDecision.codeWorkspaces == null) { + delete req.body.codeWorkspaces; + } else { + req.body.codeWorkspaces = codeEnvironmentDecision.codeWorkspaces; + } delete endpointOption.agent; /** The deployment switch AND the role grant. `initializeAgent` rebuilds @@ -1032,8 +1054,21 @@ const initializeClient = async ({ }); const toLazySubagentMetadata = async (agent) => { + const configuredCodeEnvironments = + appConfig?.endpoints?.[EModelEndpoint.agents]?.statefulCodeSessions?.environments; + const attachedEnvironmentOptOut = optsOutOfAttachedCodeEnvironment( + agent, + runtimeRequestBody, + configuredCodeEnvironments, + isImplicitStatefulCodeRouteAvailable( + process.env.CODE_ENVIRONMENT_DECISION_VERSION, + process.env.LIBRECHAT_CODE_BASEURL_STATEFUL, + ), + ); const lazyCodeEnvAvailable = - codeEnvAvailable === true && agent.tools?.includes(Tools.execute_code) === true; + codeEnvAvailable === true && + agent.tools?.includes(Tools.execute_code) === true && + !attachedEnvironmentOptOut; const statefulCodeSessions = statefulSessionsAvailable === true && lazyCodeEnvAvailable && @@ -1046,23 +1081,17 @@ const initializeClient = async ({ ) { throw createStatefulCodeEnvironmentPolicyError(statefulCodeEnvironment); } - const configuredCodeEnvironments = - appConfig?.endpoints?.[EModelEndpoint.agents]?.statefulCodeSessions?.environments; - const hasConfiguredCodeEnvironment = - agent.code_environment_id != null || - configuredCodeEnvironments?.some((environment) => environment.default === true) === true; - const baseCodeExecutionContext = - lazyCodeEnvAvailable && (!statefulCodeSessions || hasConfiguredCodeEnvironment) - ? resolveCodeExecutionContext({ - statefulSessions: statefulCodeSessions, - environment: statefulCodeEnvironment, - environmentId: agent.code_environment_id, - environments: configuredCodeEnvironments, - userId, - agentId: agent.id, - conversationId, - }) - : undefined; + const baseCodeExecutionContext = lazyCodeEnvAvailable + ? resolveCodeExecutionContext({ + statefulSessions: statefulCodeSessions, + environment: statefulCodeEnvironment, + environmentId: agent.code_environment_id, + environments: configuredCodeEnvironments, + userId, + agentId: agent.id, + conversationId, + }) + : undefined; const codeExecutionContext = baseCodeExecutionContext ? await resolveCodeExecutionWorkspaceContext({ context: baseCodeExecutionContext, diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.js index 836268ab19..52241abda3 100644 --- a/api/server/services/Endpoints/agents/initialize.spec.js +++ b/api/server/services/Endpoints/agents/initialize.spec.js @@ -896,12 +896,17 @@ describe('initializeClient — subagent loading', () => { requestBody, }); - expect(mockInitializeAgent.mock.calls[0][0].requestBody).toBe(requestBody); - expect(agentClientArgs.mcpRequestBody).toBe(requestBody); + const normalizedRequestBody = mockInitializeAgent.mock.calls[0][0].requestBody; + expect(normalizedRequestBody).toEqual({ + ...requestBody, + codeEnvironmentMode: 'without_attached', + codeWorkspaces: undefined, + }); + expect(agentClientArgs.mcpRequestBody).toBe(normalizedRequestBody); await capturedToolExecuteOptions.loadTools([], PRIMARY_ID); expect(mockLoadToolsForExecution).toHaveBeenCalledWith( - expect.objectContaining({ requestBody }), + expect.objectContaining({ requestBody: normalizedRequestBody }), ); }); @@ -1460,20 +1465,74 @@ describe('initializeClient — subagent loading', () => { const req = makeSubagentReq(); req.config.endpoints.agents.capabilities.push('execute_code', 'stateful_code_sessions'); req.config.endpoints.agents.statefulCodeSessions = { allowedEnvironments: ['user'] }; + process.env.CODE_ENVIRONMENT_DECISION_VERSION = '1'; + process.env.LIBRECHAT_CODE_BASEURL_STATEFUL = 'https://stateful-code.example.com/v1/'; - await expect( - initializeClient({ + try { + await expect( + initializeClient({ + req, + res: {}, + signal: new AbortController().signal, + endpointOption: makeEndpointOption(), + }), + ).rejects.toMatchObject({ + code: ErrorTypes.STATEFUL_CODE_ENVIRONMENT_NOT_ALLOWED, + }); + + expect(agentClientArgs).toBeUndefined(); + expect(mockInitializeAgent).toHaveBeenCalledTimes(1); + } finally { + delete process.env.CODE_ENVIRONMENT_DECISION_VERSION; + delete process.env.LIBRECHAT_CODE_BASEURL_STATEFUL; + } + }); + + it('binds a versioned implicit stateful route into lazy subagent metadata', async () => { + const subAgent = await createAgent({ + id: SUBAGENT_ID, + name: 'Implicit Stateful Subagent', + provider: 'openai', + model: 'gpt-4', + author: new mongoose.Types.ObjectId(), + tools: ['execute_code'], + stateful_code_sessions: true, + stateful_code_environment: 'user', + }); + await grantView(subAgent); + mockInitializeAgent.mockResolvedValue( + makePrimaryConfig({ + subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] }, + }), + ); + const req = makeSubagentReq(); + req.body.codeEnvironmentMode = 'without_attached'; + req.config.endpoints.agents.capabilities.push('execute_code', 'stateful_code_sessions'); + req.config.endpoints.agents.statefulCodeSessions = { allowedEnvironments: ['user'] }; + process.env.CODE_ENVIRONMENT_DECISION_VERSION = '1'; + process.env.LIBRECHAT_CODE_BASEURL_STATEFUL = 'https://stateful-code.example.com/v1/'; + + try { + await initializeClient({ req, res: {}, signal: new AbortController().signal, endpointOption: makeEndpointOption(), - }), - ).rejects.toMatchObject({ - code: ErrorTypes.STATEFUL_CODE_ENVIRONMENT_NOT_ALLOWED, - }); + }); - expect(agentClientArgs).toBeUndefined(); - expect(mockInitializeAgent).toHaveBeenCalledTimes(1); + expect(agentClientArgs.agent.lazySubagentConfigs[0]).toEqual( + expect.objectContaining({ + codeExecutionContext: expect.objectContaining({ + baseUrl: 'https://stateful-code.example.com/v1', + executionProfile: 'stateful', + statefulSessions: true, + }), + }), + ); + } finally { + delete process.env.CODE_ENVIRONMENT_DECISION_VERSION; + delete process.env.LIBRECHAT_CODE_BASEURL_STATEFUL; + } }); it.each([ @@ -1582,7 +1641,8 @@ describe('initializeClient — subagent loading', () => { signal: new AbortController().signal, endpointOption: makeEndpointOption(), }); - if (!registered) { + const defaultsWithoutAttached = source === 'resolved-null' || source === 'other-owner'; + if (!registered && !defaultsWithoutAttached) { await expect(initialization).rejects.toMatchObject({ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, }); @@ -1590,6 +1650,13 @@ describe('initializeClient — subagent loading', () => { return; } await initialization; + if (defaultsWithoutAttached) { + expect(fetchSpy).not.toHaveBeenCalled(); + expect(agentClientArgs.mcpRequestBody).toEqual( + expect.objectContaining({ codeEnvironmentMode: 'without_attached' }), + ); + return; + } if (source === 'fallback' || source.startsWith('override')) { mockInitializeAgent.mockImplementationOnce(async (params) => { expect(params.req.resolvedConversation.codeWorkspaces).toEqual([ @@ -2019,6 +2086,19 @@ describe('initializeClient — subagent loading', () => { 'tool_intents', 'stateful_code_sessions', ); + req.config.endpoints.agents.statefulCodeSessions = { + allowedEnvironments: ['user'], + environments: [ + { + id: 'managed-code', + name: 'Managed code', + type: 'managed', + baseURL: 'https://stateful-code.example.com/v1', + default: true, + }, + ], + }; + mockGetAppConfig.mockResolvedValue(req.config); const { userMCPAuthMap } = await initializeClient({ req, res: {}, diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx index f7e640a21a..6bc3a9715b 100644 --- a/client/src/components/Chat/Input/ChatForm.tsx +++ b/client/src/components/Chat/Input/ChatForm.tsx @@ -650,6 +650,28 @@ const ChatForm = memo(function ChatForm({ onRestoreToComposer={restoreReclaimedSteer} /> )} + {(project || + (codeWorkspace.required && (!codeWorkspace.locked || !codeWorkspace.canSubmit))) && ( +
+ {project ? : null} + {codeWorkspace.required && (!codeWorkspace.locked || !codeWorkspace.canSubmit) ? ( +
+ +
+ ) : null} +
+ )}
- {project ? : null} {quotesEnabled && ( @@ -782,11 +803,6 @@ const ChatForm = memo(function ChatForm({ onFocus={handleTextareaFocus} onBlur={handleTextareaBlur} aria-label={localize('com_ui_message_input')} - aria-describedby={ - codeWorkspace.state === 'choose' || codeWorkspace.state === 'missing' - ? `code-workspace-hint-${index}` - : undefined - } onClick={handleFocusOrClick} style={{ height: 44, overflowY: 'auto' }} className={cn( @@ -805,15 +821,6 @@ const ChatForm = memo(function ChatForm({
)} - {(codeWorkspace.state === 'choose' || codeWorkspace.state === 'missing') && ( -

- {localize('com_error_code_workspace_required')} -

- )}
- {index === 0 && conversationId != null && ( )} @@ -964,6 +965,7 @@ function ChatFormWrapper({ conversation?.model, conversation?.maxContextTokens, conversation?.codeApprovalMode, + conversation?.codeEnvironmentMode, conversation?.codeWorkspaces, hasMessages, ], diff --git a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx index 36ae9f01e6..e7f0560f27 100644 --- a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx +++ b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx @@ -1,4 +1,3 @@ -import { useEffect } from 'react'; import * as Ariakit from '@ariakit/react'; import { Check, ChevronDown, Folder, FolderX } from 'lucide-react'; import { TooltipAnchor, composerControlClasses } from '@librechat/client'; @@ -14,15 +13,14 @@ const stateLabels: Partial missing: 'com_ui_code_workspace_missing', unavailable: 'com_ui_code_workspace_unavailable', unsupported: 'com_ui_code_workspace_unsupported', + without_attached: 'com_ui_code_workspace_without_attached', }; export default function CodeWorkspaceMenu({ - conversation, setConversation, workspace, disabled, }: { - conversation: TConversation | null; setConversation: SetterOrUpdater; workspace: CodeWorkspaceResult; disabled: boolean; @@ -31,25 +29,6 @@ export default function CodeWorkspaceMenu({ const menuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' }); const isOpen = menuStore.useState('open'); - /** Pin resolved defaults to this chat; later preference changes cannot move it. */ - useEffect(() => { - if (conversation?.codeWorkspaces != null || workspace.selections == null) return; - setConversation((current) => - current == null || - current.codeWorkspaces != null || - current.conversationId !== conversation?.conversationId || - current.agent_id !== conversation?.agent_id - ? current - : { ...current, codeWorkspaces: workspace.selections }, - ); - }, [ - conversation?.codeWorkspaces, - conversation?.conversationId, - conversation?.agent_id, - setConversation, - workspace.selections, - ]); - if (!workspace.required) return null; const environmentIds = new Set(workspace.environments.map(({ environment }) => environment.id)); @@ -57,24 +36,39 @@ export default function CodeWorkspaceMenu({ workspace.rememberSelection(selection); setConversation((current) => { if (current == null) return current; - const retained = (current.codeWorkspaces ?? []).filter( + const retained = (current.codeWorkspaces ?? workspace.selections ?? []).filter( ({ environmentId }) => environmentIds.has(environmentId) && environmentId !== selection.environmentId, ); return { ...current, + codeEnvironmentMode: 'attached', codeWorkspaces: [...retained, selection].sort((a, b) => a.environmentId.localeCompare(b.environmentId), ), }; }); }; + const selectWithoutAttached = () => { + setConversation((current) => + current == null + ? current + : { + ...current, + codeEnvironmentMode: 'without_attached', + codeWorkspaces: undefined, + }, + ); + }; const onlyEnvironment = workspace.environments.length === 1 ? workspace.environments[0] : null; const onlyDescriptor = onlyEnvironment?.workspaces.find( ({ id }) => id === onlyEnvironment.selected?.workspaceId, ); const labelKey = stateLabels[workspace.state]; - let label = onlyDescriptor?.name ?? onlyDescriptor?.id; + let label = + workspace.mode === 'without_attached' + ? localize('com_ui_code_workspace_without_attached') + : (onlyDescriptor?.name ?? onlyDescriptor?.id); if (label == null && workspace.state === 'ready') { label = localize('com_ui_code_workspaces_selected', { 0: workspace.selections?.length ?? 0, @@ -82,9 +76,33 @@ export default function CodeWorkspaceMenu({ } else if (label == null) { label = labelKey ? localize(labelKey) : localize('com_ui_code_workspace_choose'); } - const canChoose = workspace.environments.some(({ workspaces }) => workspaces.length > 0); const Icon = - workspace.state === 'missing' || workspace.state === 'unavailable' ? FolderX : Folder; + workspace.mode === 'without_attached' || + workspace.state === 'missing' || + workspace.state === 'unavailable' + ? FolderX + : Folder; + + if (workspace.locked) { + if (workspace.canSubmit) return null; + const recovery = localize('com_ui_code_workspace_locked_recovery'); + return ( + + } + > + + ); + } return ( @@ -93,100 +111,131 @@ export default function CodeWorkspaceMenu({ disabled={isOpen} render={ } >