From a8087ce4544d340a47d23b0aae48a6b124c1f855 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Wed, 9 Sep 2026 02:14:50 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=8F=95=EF=B8=8F=20feat:=20Select=20Attach?= =?UTF-8?q?ed=20Code=20Workspaces=20(#15768)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Select Attached Code Workspaces * fix: Preserve Workspace Boundaries Across Agent Graphs * fix: Validate Lazy Agent Workspace Bindings Before Persistence * fix: Include Handoff Environments in Workspace Selection * fix: Close Workspace Admission and Remote Ingress Gaps * fix: Preserve Workspace Selection In Chat Runtime Envelopes * fix: Authorize Deployment Workspace Status And Match Readiness * fix: Preserve Ephemeral Chats And Pin Runtime Worker Identity * test: Complete Deployment Pairing Fixtures --- .../agents/__tests__/openai.spec.js | 37 ++- .../__tests__/request.resumeMetadata.spec.js | 93 +++--- .../agents/__tests__/responses.unit.spec.js | 38 ++- api/server/controllers/agents/client.js | 10 + api/server/controllers/agents/client.test.js | 32 +- api/server/controllers/agents/openai.js | 5 +- api/server/controllers/agents/request.js | 1 + api/server/controllers/agents/responses.js | 27 +- api/server/controllers/agents/resume.js | 1 + .../services/Endpoints/agents/initialize.js | 13 +- .../Endpoints/agents/initialize.spec.js | 157 ++++++---- api/server/services/ToolService.js | 40 ++- .../services/__tests__/ToolService.spec.js | 47 ++- client/src/components/Chat/Input/ChatForm.tsx | 11 + .../Chat/Input/CodeWorkspaceMenu.tsx | 184 ++++++++++++ .../__tests__/CodeWorkspaceMenu.spec.tsx | 114 ++++++++ .../src/components/Messages/Content/Error.tsx | 1 + .../Messages/Content/__tests__/Error.spec.tsx | 1 + client/src/data-provider/CodeEnvironments.ts | 15 +- .../__tests__/useCodeApprovalMode.test.ts | 22 +- .../__tests__/useCodeWorkspace.test.tsx | 273 ++++++++++++++++++ client/src/hooks/Agents/index.ts | 2 + .../src/hooks/Agents/useCodeApprovalMode.ts | 21 +- client/src/hooks/Agents/useCodeWorkspace.ts | 213 ++++++++++++++ .../useChatFunctions.regenerate.spec.tsx | 48 ++- client/src/hooks/Chat/useChatFunctions.ts | 9 + client/src/locales/en/translation.json | 8 + .../src/agents/__tests__/initialize.test.ts | 82 ++++++ packages/api/src/agents/errors.spec.ts | 1 + packages/api/src/agents/errors.ts | 1 + packages/api/src/agents/execution.spec.ts | 51 +++- packages/api/src/agents/execution.ts | 39 +++ packages/api/src/agents/handlers.spec.ts | 44 ++- packages/api/src/agents/handlers.ts | 55 +++- packages/api/src/agents/hitl/policy.spec.ts | 38 +++ packages/api/src/agents/hitl/policy.ts | 8 + packages/api/src/agents/initialize.ts | 25 +- packages/api/src/agents/openai/service.ts | 11 + packages/api/src/agents/openai/types.ts | 2 + packages/api/src/agents/responses/service.ts | 10 + packages/api/src/agents/responses/types.ts | 2 + packages/api/src/agents/skills.ts | 6 +- packages/api/src/agents/tools.spec.ts | 59 +++- packages/api/src/agents/tools.ts | 57 +++- packages/api/src/code/bridge.spec.ts | 94 +++++- packages/api/src/code/bridge.ts | 107 ++++++- packages/api/src/code/capabilities.spec.ts | 254 +++++++++++++++- packages/api/src/code/capabilities.ts | 187 ++++++++++-- packages/api/src/code/command.spec.ts | 19 +- packages/api/src/code/command.ts | 23 +- packages/api/src/code/http.spec.ts | 104 ++++++- packages/api/src/code/http.ts | 17 +- packages/api/src/code/remoteWorkspace.spec.ts | 39 +++ packages/api/src/mcp/request.ts | 3 + packages/api/src/mcp/types/index.ts | 2 +- packages/api/src/tools/classification.spec.ts | 4 +- packages/api/src/tools/classification.ts | 1 + packages/api/src/types/http.ts | 7 +- .../data-provider/specs/codeWorkspace.spec.ts | 38 +++ .../data-provider/specs/createPayload.spec.ts | 9 + packages/data-provider/src/code/workspace.ts | 55 ++++ packages/data-provider/src/config.ts | 4 + packages/data-provider/src/createPayload.ts | 2 + packages/data-provider/src/index.ts | 1 + packages/data-provider/src/schemas.ts | 11 + packages/data-provider/src/types.ts | 13 +- packages/data-schemas/src/schema/defaults.ts | 18 ++ packages/data-schemas/src/types/convo.ts | 7 +- 68 files changed, 2704 insertions(+), 229 deletions(-) create mode 100644 client/src/components/Chat/Input/CodeWorkspaceMenu.tsx create mode 100644 client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx create mode 100644 client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx create mode 100644 client/src/hooks/Agents/useCodeWorkspace.ts create mode 100644 packages/api/src/code/remoteWorkspace.spec.ts create mode 100644 packages/data-provider/specs/codeWorkspace.spec.ts create mode 100644 packages/data-provider/src/code/workspace.ts diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.js index 9986276e20..2a3bde6ec6 100644 --- a/api/server/controllers/agents/__tests__/openai.spec.js +++ b/api/server/controllers/agents/__tests__/openai.spec.js @@ -214,9 +214,15 @@ jest.mock('@librechat/api', () => ({ buildInitialToolSessions: jest.fn().mockReturnValue(mockInitialSessions), AgentRunEnvelopeError: MockAgentRunEnvelopeError, createAgentRunEnvelope: (...args) => mockCreateAgentRunEnvelope(...args), - createMCPRuntimeRequestBody: ({ messageId, conversationId, parentMessageId }) => ({ + createMCPRuntimeRequestBody: ({ messageId, conversationId, + parentMessageId, + codeWorkspaces, + }) => ({ + messageId, + conversationId, + ...(codeWorkspaces !== undefined && { codeWorkspaces }), ...(parentMessageId !== undefined && { parentMessageId: parentMessageId ?? '00000000-0000-0000-0000-000000000000', }), @@ -1170,6 +1176,35 @@ describe('OpenAIChatCompletionController', () => { }); describe('conversation ownership validation', () => { + it.each([false, true])( + 'propagates explicit or owned persisted workspaces: continuation=%s', + async (continuation) => { + const api = require('@librechat/api'); + const selections = [{ environmentId: 'machine', workspaceId: 'project' }]; + api.validateRequest.mockReturnValueOnce({ + request: { + model: 'agent-123', + messages: [], + stream: false, + ...(continuation ? { conversation_id: 'convo-abc' } : { code_workspaces: selections }), + }, + }); + if (continuation) + require('~/models').getConvo.mockResolvedValueOnce({ + conversationId: 'convo-abc', + codeWorkspaces: selections, + }); + await OpenAIChatCompletionController(req, res); + expect(api.initializeAgent).toHaveBeenCalledWith( + expect.objectContaining({ + requestBody: expect.objectContaining({ codeWorkspaces: selections }), + }), + expect.anything(), + ); + if (continuation) + expect(require('~/models').getConvo).toHaveBeenCalledWith('user-123', 'convo-abc'); + }, + ); it('should skip ownership check when conversation_id is not provided', async () => { const { getConvo } = require('~/models'); await OpenAIChatCompletionController(req, res); diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js index 1fc795a5cd..2f001ca790 100644 --- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js +++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js @@ -326,10 +326,16 @@ jest.mock('@librechat/api', () => ({ agent?.toolDefinitions?.some((tool) => tool?.name === 'ask_user_question') === true, isAgentEventRetentionActive: (expiredAt) => expiredAt == null || new Date(expiredAt).getTime() > Date.now(), - createMCPRuntimeRequestBody: ({ messageId, conversationId, parentMessageId }) => ({ + createMCPRuntimeRequestBody: ({ messageId, conversationId, parentMessageId, + codeWorkspaces, + }) => ({ + messageId, + conversationId, + parentMessageId, + ...(codeWorkspaces !== undefined ? { codeWorkspaces } : {}), }), })); @@ -4201,45 +4207,56 @@ describe('ResumableAgentController resume metadata', () => { ); }); - it('proceeds to create the job when it wins the idempotency claim', async () => { - mockGenerationJobManager.claimGeneration.mockResolvedValue(wonGenerationClaim()); - const initializeClient = jest.fn().mockRejectedValue(new Error('stop before tool loading')); - const req = { - user: { id: 'user-123' }, - body: { - text: 'Fresh submission.', - messageId: 'user-msg', - clientRequestId: 'req-abc', - conversationId: 'conversation-123', - endpointOption: { endpoint: 'agents', modelOptions: { model: 'gpt-4.1' } }, - }, - config: {}, - }; - const res = { - headersSent: true, - json: jest.fn(() => { - res.headersSent = true; - }), - status: jest.fn(() => res), - set: jest.fn(), - }; - - await AgentController(req, res, jest.fn(), initializeClient, null); - - expect(mockCheckAndIncrementPendingRequest).toHaveBeenCalledWith('user-123'); - expect(mockGenerationJobManager.createJob).toHaveBeenCalledWith( - 'conversation-123', - 'user-123', - 'conversation-123', - expect.objectContaining({ - startupTelemetry: mockStartupTelemetry, - initialMetadata: expect.objectContaining({ + it.each(['submitted', 'persisted'])( + 'preserves %s workspace selections in the runtime envelope', + async (source) => { + mockGenerationJobManager.claimGeneration.mockResolvedValue(wonGenerationClaim()); + const initializeClient = jest.fn().mockRejectedValue(new Error('stop before tool loading')); + const codeWorkspaces = [{ environmentId: 'machine-a', workspaceId: 'project-b' }]; + const req = { + user: { id: 'user-123' }, + ...(source === 'persisted' ? { resolvedConversation: { codeWorkspaces } } : {}), + body: { + ...(source === 'submitted' ? { codeWorkspaces } : {}), + text: 'Fresh submission.', + messageId: 'user-msg', + clientRequestId: 'req-abc', conversationId: 'conversation-123', - endpoint: 'agents', + endpointOption: { endpoint: 'agents', modelOptions: { model: 'gpt-4.1' } }, + }, + config: {}, + }; + const res = { + headersSent: true, + json: jest.fn(() => { + res.headersSent = true; }), - }), - ); - }); + status: jest.fn(() => res), + set: jest.fn(), + }; + + await AgentController(req, res, jest.fn(), initializeClient, null); + + expect(initializeClient).toHaveBeenCalledWith( + expect.objectContaining({ + requestBody: expect.objectContaining({ codeWorkspaces }), + }), + ); + expect(mockCheckAndIncrementPendingRequest).toHaveBeenCalledWith('user-123'); + expect(mockGenerationJobManager.createJob).toHaveBeenCalledWith( + 'conversation-123', + 'user-123', + 'conversation-123', + expect.objectContaining({ + startupTelemetry: mockStartupTelemetry, + initialMetadata: expect.objectContaining({ + conversationId: 'conversation-123', + endpoint: 'agents', + }), + }), + ); + }, + ); it('retains terminal metadata for the first event in an empty bound actor thread', async () => { const expiredAt = new Date(Date.now() + 60_000); diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.js index a088e484bd..0bbf27b8f5 100644 --- a/api/server/controllers/agents/__tests__/responses.unit.spec.js +++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js @@ -233,9 +233,16 @@ jest.mock('@librechat/api', () => ({ buildRunToolSet: jest.fn().mockReturnValue(new Set()), AgentRunEnvelopeError: MockAgentRunEnvelopeError, createAgentRunEnvelope: (...args) => mockCreateAgentRunEnvelope(...args), - createMCPRuntimeRequestBody: ({ messageId, conversationId, parentMessageId }) => ({ + getCodeWorkspaceSelections: jest.fn(), + createMCPRuntimeRequestBody: ({ messageId, conversationId, + parentMessageId, + codeWorkspaces, + }) => ({ + messageId, + conversationId, + ...(codeWorkspaces !== undefined && { codeWorkspaces }), ...(parentMessageId !== undefined && { parentMessageId: parentMessageId ?? '00000000-0000-0000-0000-000000000000', }), @@ -572,6 +579,35 @@ describe('createResponse controller', () => { }; }); + it.each([false, true])( + 'passes explicit or owner-loaded workspace selections to runtime: continuation=%s', + async (continuation) => { + const api = require('@librechat/api'); + const selections = [{ environmentId: 'machine', workspaceId: 'project' }]; + const request = { + model: 'agent-123', + input: 'Hello', + stream: false, + ...(continuation ? { previous_response_id: 'previous' } : { code_workspaces: selections }), + }; + api.validateResponseRequest.mockReturnValueOnce({ request }); + if (continuation) + require('~/models').getConvo.mockResolvedValueOnce({ + conversationId: 'previous', + codeWorkspaces: selections, + }); + await createResponse(req, res); + expect(api.initializeAgent).toHaveBeenCalledWith( + expect.objectContaining({ + requestBody: expect.objectContaining({ codeWorkspaces: selections }), + }), + expect.anything(), + ); + if (continuation) + expect(require('~/models').getConvo).toHaveBeenCalledWith('user-123', 'previous'); + }, + ); + 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 44b57ce0d4..71dd0ffb19 100644 --- a/api/server/controllers/agents/client.js +++ b/api/server/controllers/agents/client.js @@ -43,6 +43,7 @@ const { buildPendingAction, toClientPendingAction, captureCodeExecutionApprovalBinding, + getCodeWorkspaceSelections, computeAgentRequestFingerprint, getRunDiscoveredTools, captureResumeModelParameters, @@ -2005,6 +2006,9 @@ class AgentClient extends BaseClient { imageDetail: this.options.imageDetail, maxContextTokens: this.maxContextTokens, codeApprovalMode, + codeWorkspaces: getCodeWorkspaceSelections( + collectReachableAgents(topLevelAgents).map((agent) => agent?.codeExecutionContext), + ), }, // TODO: PARSE OPTIONS BY PROVIDER, MAY CONTAIN SENSITIVE DATA runOptions, @@ -4492,6 +4496,9 @@ class AgentClient extends BaseClient { messageId: this.responseMessageId, conversationId: this.conversationId, parentMessageId: this.parentMessageId, + codeWorkspaces: + this.options.req.body.codeWorkspaces ?? + this.options.req.resolvedConversation?.codeWorkspaces, }), user: createSafeUser(this.options.req.user), }, @@ -5264,6 +5271,9 @@ class AgentClient extends BaseClient { messageId: this.responseMessageId, conversationId: this.conversationId, parentMessageId: this.parentMessageId, + codeWorkspaces: + this.options.req.body.codeWorkspaces ?? + this.options.req.resolvedConversation?.codeWorkspaces, }), user: createSafeUser(this.options.req.user), }, diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.js index 634590b888..040af6c629 100644 --- a/api/server/controllers/agents/client.test.js +++ b/api/server/controllers/agents/client.test.js @@ -37,13 +37,37 @@ const { resolveConfigServers } = require('~/server/services/MCP'); describe('AgentClient code approval persistence', () => { it('persists a validated mode in agent conversation options', () => { const client = Object.create(AgentClient.prototype); + client.agentConfigs = new Map([ + [ + 'secondary', + { + codeExecutionContext: { + environmentId: 'team-vm', + environmentType: 'attached', + codeWorkspace: { + environmentId: 'team-vm', + workspaceId: 'project-b', + operations: ['read_file'], + }, + }, + }, + ], + ]); + const secondary = client.agentConfigs.get('secondary'); client.agentConfigs = new Map(); client.options = { endpoint: EModelEndpoint.agents, agent: { id: 'attached-agent', + subagentAgentConfigs: [secondary], codeExecutionContext: { + environmentId: 'attached-vm', environmentType: 'attached', + codeWorkspace: { + environmentId: 'attached-vm', + workspaceId: 'project-a', + operations: ['read_file', 'execute_command'], + }, codeEnvironmentConfigSchema: { permissions: { fileWrite: { allowed: ['ask', 'allow'], default: 'ask' }, @@ -58,7 +82,13 @@ describe('AgentClient code approval persistence', () => { }, }; - expect(client.getSaveOptions()).toMatchObject({ codeApprovalMode: 'acceptEdits' }); + expect(client.getSaveOptions()).toMatchObject({ + codeApprovalMode: 'acceptEdits', + codeWorkspaces: [ + { environmentId: 'attached-vm', workspaceId: 'project-a' }, + { environmentId: 'team-vm', workspaceId: 'project-b' }, + ], + }); }); }); diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js index 3fb6a213da..12cd8f126e 100644 --- a/api/server/controllers/agents/openai.js +++ b/api/server/controllers/agents/openai.js @@ -440,9 +440,11 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => { 'invalid_request_error', ); } - if (!(await db.getConvo(principal.userId, request.conversation_id))) { + const conversation = await db.getConvo(principal.userId, request.conversation_id); + if (!conversation) { return sendErrorResponse(res, 404, 'Conversation not found', 'invalid_request_error'); } + req.resolvedConversation = conversation; } const parentMessageId = request.parent_message_id ?? null; @@ -458,6 +460,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => { const mcpRequestBody = createMCPRuntimeRequestBody({ messageId: responseId, conversationId, + codeWorkspaces: request.code_workspaces ?? req.resolvedConversation?.codeWorkspaces, parentMessageId: mcpParentMessageId, }); diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.js index 38cff1a1aa..3198859a27 100644 --- a/api/server/controllers/agents/request.js +++ b/api/server/controllers/agents/request.js @@ -1483,6 +1483,7 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit const mcpRequestBody = createMCPRuntimeRequestBody({ messageId: preallocatedResponseMessageId, conversationId: effectiveConversationId, + codeWorkspaces: req.body.codeWorkspaces ?? req.resolvedConversation?.codeWorkspaces, parentMessageId: editedContent != null ? preallocatedResponseMessageId : preallocatedUserMessageId, }); diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js index fdcd93a372..02b7ea8dbd 100644 --- a/api/server/controllers/agents/responses.js +++ b/api/server/controllers/agents/responses.js @@ -18,6 +18,8 @@ const { createAgentRunEnvelope, createAgentExecutionContext, createMCPRuntimeRequestBody, + getCodeWorkspaceSelections, + collectReachableAgents, buildAgentScopedContext, buildInlineMemoryContext, buildAgentContextAttachmentsByAgentId, @@ -446,7 +448,7 @@ async function saveResponseOutput( * @param {object} agent * @returns {Promise} */ -async function saveConversation(req, conversationId, agentId, agent) { +async function saveConversation(req, conversationId, agentId, agent, codeWorkspaces) { const title = resolveConversationTitle(req, agent?.name || 'Open Responses Conversation'); await db.saveConvo( { @@ -459,6 +461,7 @@ async function saveConversation(req, conversationId, agentId, agent) { conversationId, endpoint: EModelEndpoint.agents, agent_id: agentId, + ...(codeWorkspaces !== undefined && { codeWorkspaces }), ...(title != null && { title }), model: agent?.model, }, @@ -681,6 +684,7 @@ const executeResponse = async (envelope, { req, res }) => { if (!previousConversation) { return sendResponsesErrorResponse(res, 404, 'Conversation not found', 'not_found'); } + req.resolvedConversation = previousConversation; if (previousConversation.subagentThread != null) { return sendResponsesErrorResponse( res, @@ -696,6 +700,7 @@ const executeResponse = async (envelope, { req, res }) => { const mcpRequestBody = createMCPRuntimeRequestBody({ messageId: responseId, conversationId, + codeWorkspaces: request.code_workspaces ?? req.resolvedConversation?.codeWorkspaces, }); const agentsEConfig = appConfig?.endpoints?.[EModelEndpoint.agents]; const previousMessages = request.previous_response_id @@ -1308,7 +1313,15 @@ const executeResponse = async (envelope, { req, res }) => { if (request.store === true) { try { // Save conversation - await saveConversation(req, conversationId, agentId, agent); + await saveConversation( + req, + conversationId, + agentId, + agent, + getCodeWorkspaceSelections( + collectReachableAgents(runAgents).map((config) => config.codeExecutionContext), + ), + ); // Save input messages await saveInputMessages(req, conversationId, inputMessages, agentId); @@ -1530,7 +1543,15 @@ const executeResponse = async (envelope, { req, res }) => { if (request.store === true) { try { - await saveConversation(req, conversationId, agentId, agent); + await saveConversation( + req, + conversationId, + agentId, + agent, + getCodeWorkspaceSelections( + collectReachableAgents(runAgents).map((config) => config.codeExecutionContext), + ), + ); await saveInputMessages(req, conversationId, inputMessages, agentId); diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.js index dbdf2d24a1..f679ab98b6 100644 --- a/api/server/controllers/agents/resume.js +++ b/api/server/controllers/agents/resume.js @@ -1827,6 +1827,7 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) createMCPRuntimeRequestBody({ messageId: job.metadata.responseMessageId, conversationId: streamId, + codeWorkspaces: req.body.codeWorkspaces ?? req.resolvedConversation?.codeWorkspaces, parentMessageId: job.metadata.userMessage?.messageId ?? Constants.NO_PARENT, }), }); diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js index 053f809e4a..c8ee09b130 100644 --- a/api/server/services/Endpoints/agents/initialize.js +++ b/api/server/services/Endpoints/agents/initialize.js @@ -21,6 +21,7 @@ const { collectCodeExecutionProfileRoutes, getLazySubagentConfigId, resolveCodeExecutionContext, + resolveCodeExecutionWorkspaceContext, createStatefulCodeEnvironmentPolicyError, buildSubagentThreadTaskConfig, backgroundCompletionWakeupsEnabled, @@ -83,6 +84,7 @@ const { } = require('./backgroundCompletion'); const { logViolation } = require('~/cache'); const db = require('~/models'); +const { getAppConfig } = require('~/server/services/Config'); const SUBAGENT_GRAPH_LOAD_CONCURRENCY = 4; @@ -1010,7 +1012,7 @@ const initializeClient = async ({ const hasConfiguredCodeEnvironment = agent.code_environment_id != null || configuredCodeEnvironments?.some((environment) => environment.default === true) === true; - const codeExecutionContext = + const baseCodeExecutionContext = lazyCodeEnvAvailable && (!statefulCodeSessions || hasConfiguredCodeEnvironment) ? resolveCodeExecutionContext({ statefulSessions: statefulCodeSessions, @@ -1022,6 +1024,15 @@ const initializeClient = async ({ conversationId, }) : undefined; + const codeExecutionContext = baseCodeExecutionContext + ? await resolveCodeExecutionWorkspaceContext({ + context: baseCodeExecutionContext, + requestedSelections: runtimeRequestBody?.codeWorkspaces, + persistedSelections: req.resolvedConversation?.codeWorkspaces, + environments: configuredCodeEnvironments, + getAppConfig, + }) + : undefined; const { alwaysApplySkillPrimes, historicalToolNames, diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.js index e6ca1f5e92..b4eb93311d 100644 --- a/api/server/services/Endpoints/agents/initialize.spec.js +++ b/api/server/services/Endpoints/agents/initialize.spec.js @@ -14,6 +14,11 @@ const { MongoMemoryServer } = require('mongodb-memory-server'); const mockInitializeAgent = jest.fn(); const mockValidateAgentModel = jest.fn(); +const mockGetAppConfig = jest.fn(); +jest.mock('~/server/services/Config', () => ({ + ...jest.requireActual('~/server/services/Config'), + getAppConfig: (...args) => mockGetAppConfig(...args), +})); function deferred() { let resolve; @@ -69,6 +74,7 @@ jest.mock('~/server/services/ToolService', () => ({ 'AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE', 'resource_recovery_required', 'stateful_code_environment_not_allowed', + 'code_workspace_unavailable', ].includes(error?.code), })); @@ -1426,59 +1432,106 @@ describe('initializeClient — subagent loading', () => { expect(mockInitializeAgent).toHaveBeenCalledTimes(1); }); - it('retains a configured Code API route on lazy subagent descriptors', async () => { - const subAgent = await createAgent({ - id: SUBAGENT_ID, - name: 'Attached Stateful Subagent', - provider: 'openai', - model: 'gpt-4', - author: new mongoose.Types.ObjectId(), - tools: ['execute_code'], - stateful_code_sessions: true, - stateful_code_environment: 'agent-user', - code_environment_id: 'attached-vm', - }); - await grantView(subAgent); - mockInitializeAgent.mockResolvedValue( - makePrimaryConfig({ - subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] }, - }), - ); - const req = makeSubagentReq(); - req.config.endpoints.agents.capabilities.push('execute_code', 'stateful_code_sessions'); - req.config.endpoints.agents.statefulCodeSessions = { - allowedEnvironments: ['agent-user'], - environments: [ - { - id: 'attached-vm', - name: 'Attached VM', - type: 'attached', - baseURL: 'https://bridge.example.com/v1/', - default: true, - }, - ], - }; - - await initializeClient({ - req, - res: {}, - signal: new AbortController().signal, - endpointOption: makeEndpointOption(), - }); - - expect(agentClientArgs.agent.lazySubagentConfigs[0]).toEqual( - expect.objectContaining({ - codeSessionKey: expect.stringMatching(/^execute_code:stateful:[a-f0-9]{32}:v3:/), - codeExecutionContext: expect.objectContaining({ - baseUrl: 'https://bridge.example.com/v1', - environmentId: 'attached-vm', - environmentType: 'attached', - executionProfile: 'stateful', - executionRouteKey: expect.stringMatching(/^stateful:[a-f0-9]{32}$/), + it.each([true, false])( + 'validates the lazy subagent workspace before exposure: registered=%s', + async (registered) => { + const subAgent = await createAgent({ + id: SUBAGENT_ID, + name: 'Attached Stateful Subagent', + provider: 'openai', + model: 'gpt-4', + author: new mongoose.Types.ObjectId(), + tools: ['execute_code'], + stateful_code_sessions: true, + stateful_code_environment: 'agent-user', + code_environment_id: 'attached-vm', + }); + await grantView(subAgent); + mockInitializeAgent.mockResolvedValue( + makePrimaryConfig({ + subagents: { enabled: true, allowSelf: false, agent_ids: [SUBAGENT_ID] }, }), - }), - ); - }); + ); + const req = makeSubagentReq(); + req.config.endpoints.agents.capabilities.push('execute_code', 'stateful_code_sessions'); + req.config.endpoints.agents.statefulCodeSessions = { + allowedEnvironments: ['agent-user'], + environments: [ + { + id: 'attached-vm', + name: 'Attached VM', + type: 'attached', + owner: 'deployment', + pairing: { workerId: 'lazy-worker', tokenEnv: 'TEST_LAZY_WORKSPACE_TOKEN' }, + baseURL: 'https://bridge.example.com/v1/', + default: true, + }, + ], + }; + req.body.codeWorkspaces = [{ environmentId: 'attached-vm', workspaceId: 'project-b' }]; + if (!registered) req.body.codeWorkspaces[0].workspaceId = 'removed-project'; + mockGetAppConfig.mockResolvedValue(req.config); + process.env.TEST_LAZY_WORKSPACE_TOKEN = 'test-token'; + const fetchSpy = jest.spyOn(globalThis, 'fetch').mockResolvedValue( + new Response( + JSON.stringify({ + protocolVersion: 1, + workerId: 'lazy-worker', + online: true, + ready: true, + leaseExpiresInMs: 45000, + capabilities: { + statefulWorkspace: true, + sandboxProfile: 'native-srt', + runtimes: ['bash'], + workspaceTools: { + protocolVersion: 1, + operations: ['read_file'], + workspaces: [{ id: 'project-b' }], + }, + }, + }), + ), + ); + try { + const initialization = initializeClient({ + req, + res: {}, + signal: new AbortController().signal, + endpointOption: makeEndpointOption(), + }); + if (!registered) { + await expect(initialization).rejects.toMatchObject({ + code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, + }); + expect(agentClientArgs).toBeUndefined(); + return; + } + await initialization; + } finally { + fetchSpy.mockRestore(); + delete process.env.TEST_LAZY_WORKSPACE_TOKEN; + } + + expect(agentClientArgs.agent.lazySubagentConfigs[0]).toEqual( + expect.objectContaining({ + codeSessionKey: expect.stringMatching(/^execute_code:stateful:[a-f0-9]{32}:v3:/), + codeExecutionContext: expect.objectContaining({ + baseUrl: 'https://bridge.example.com/v1', + environmentId: 'attached-vm', + environmentType: 'attached', + codeWorkspace: { + environmentId: 'attached-vm', + workspaceId: 'project-b', + operations: ['read_file'], + }, + executionProfile: 'stateful', + executionRouteKey: expect.stringMatching(/^stateful:[a-f0-9]{32}$/), + }), + }), + ); + }, + ); it('omits a descriptor when its metadata lookup fails without aborting the primary run', async () => { const primaryConfig = makePrimaryConfig({ diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js index e7b121da11..34b762e997 100644 --- a/api/server/services/ToolService.js +++ b/api/server/services/ToolService.js @@ -49,6 +49,7 @@ const { createAttachedWorkspaceBashTool, createGitIdentityProgrammaticBashTool, resolveCodeExecutionContext, + resolveCodeExecutionWorkspaceContext, resolveCallerCapabilityProjectionSnapshot, CREATE_FILE_TOOL_NAME, EDIT_FILE_TOOL_NAME, @@ -820,7 +821,7 @@ async function loadToolDefinitionsWrapper({ agent.tools?.includes(Tools.execute_code) === true && enabledCapabilities.has(AgentCapabilities.execute_code) && canUseTool(Tools.execute_code); - const resolvedCodeExecutionContext = + const baseCodeExecutionContext = codeExecutionContext ?? resolveCodeExecutionContext({ statefulSessions: @@ -834,6 +835,13 @@ async function loadToolDefinitionsWrapper({ agentId: agent.id, conversationId: runtimeRequestBody?.conversationId, }); + const resolvedCodeExecutionContext = await resolveCodeExecutionWorkspaceContext({ + context: baseCodeExecutionContext, + requestedSelections: runtimeRequestBody?.codeWorkspaces, + persistedSelections: req.resolvedConversation?.codeWorkspaces, + environments: req.config?.endpoints?.agents?.statefulCodeSessions?.environments, + getAppConfig, + }); const hasMCPTools = agent.tools?.some((tool) => tool?.includes(Constants.mcp_delimiter)); const mcpPermissionContext = createMCPPermissionContext(req); const canUseMCP = hasMCPTools ? await mcpPermissionContext.canUseServers(req.user) : true; @@ -1523,6 +1531,7 @@ async function loadToolDefinitionsWrapper({ actionsEnabled, primedCodeFiles, oauthActionToolNames, + codeExecutionContext: resolvedCodeExecutionContext, }; } @@ -1688,11 +1697,12 @@ async function loadAgentTools({ agent.tools?.includes(Tools.execute_code) === true && enabledCapabilities.has(AgentCapabilities.execute_code) && canUseTool(Tools.execute_code); + const runtimeRequestBody = requestBody ?? req.body; const statefulCodeSessions = codeExecutionEnabled && enabledCapabilities.has(AgentCapabilities.stateful_code_sessions) && agent.stateful_code_sessions === true; - const codeExecutionContext = + const baseCodeExecutionContext = providedCodeExecutionContext ?? resolveCodeExecutionContext({ statefulSessions: statefulCodeSessions, @@ -1701,8 +1711,15 @@ async function loadAgentTools({ environments: req.config?.endpoints?.agents?.statefulCodeSessions?.environments, userId: req.user.id, agentId: agent.id, - conversationId: requestBody?.conversationId ?? req.body?.conversationId, + conversationId: runtimeRequestBody?.conversationId, }); + const codeExecutionContext = await resolveCodeExecutionWorkspaceContext({ + context: baseCodeExecutionContext, + requestedSelections: runtimeRequestBody?.codeWorkspaces, + persistedSelections: req.resolvedConversation?.codeWorkspaces, + environments: req.config?.endpoints?.agents?.statefulCodeSessions?.environments, + getAppConfig, + }); const { loadedTools, toolContextMap, dynamicToolContextMap, primedCodeFiles } = await loadTools({ agent, @@ -1815,6 +1832,7 @@ async function loadAgentTools({ actionsEnabled, tools: agentTools, primedCodeFiles, + codeExecutionContext, }; } @@ -1835,6 +1853,7 @@ async function loadAgentTools({ actionsEnabled, tools: agentTools, primedCodeFiles, + codeExecutionContext, }; } // See registerActionTools for the key-shape rationale. @@ -1963,6 +1982,7 @@ async function loadAgentTools({ actionsEnabled, tools: agentTools, primedCodeFiles, + codeExecutionContext, }; } @@ -2097,7 +2117,7 @@ async function loadToolsForExecution({ codeExecutionEnabled && enabledCapabilities?.has(AgentCapabilities.stateful_code_sessions) === true && agent?.stateful_code_sessions === true; - const codeExecutionContext = resolveCodeExecutionContext({ + const baseCodeExecutionContext = resolveCodeExecutionContext({ statefulSessions: statefulCodeSessions, environment: agent?.stateful_code_environment, environmentId: agent?.code_environment_id, @@ -2106,6 +2126,13 @@ async function loadToolsForExecution({ agentId: agent?.id, conversationId: conversationId ?? runtimeRequestBody?.conversationId, }); + const codeExecutionContext = await resolveCodeExecutionWorkspaceContext({ + context: baseCodeExecutionContext, + requestedSelections: runtimeRequestBody?.codeWorkspaces, + persistedSelections: req.resolvedConversation?.codeWorkspaces, + environments: req.config?.endpoints?.agents?.statefulCodeSessions?.environments, + getAppConfig, + }); configurable.codeExecutionContext = codeExecutionContext; const isPTC = @@ -2184,7 +2211,9 @@ async function loadToolsForExecution({ const isBashTool = isBashToolRequested && codeExecutionEnabled && - toolRegistry?.has(AgentConstants.BASH_TOOL) === true; + toolRegistry?.has(AgentConstants.BASH_TOOL) === true && + (codeExecutionContext.environmentType !== 'attached' || + codeExecutionContext.codeWorkspace?.operations.includes('execute_command') === true); if (isBashToolRequested && !isBashTool) { logger.warn( `[loadToolsForExecution] Skipping unregistered or unauthorized ${AgentConstants.BASH_TOOL}. ` + @@ -2203,6 +2232,7 @@ async function loadToolsForExecution({ ? createAttachedWorkspaceBashTool({ authHeaders, baseUrl: codeExecutionContext.baseUrl, + workspaceId: codeExecutionContext.codeWorkspace.workspaceId, gitIdentity: agent?.git_identity, }) : createBashExecutionTool({ diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.js index fede6125f5..5235a65441 100644 --- a/api/server/services/__tests__/ToolService.spec.js +++ b/api/server/services/__tests__/ToolService.spec.js @@ -22,6 +22,15 @@ const mockGetCachedTools = jest.fn(); const mockSendEvent = jest.fn(); const mockEmitChunk = jest.fn(); const mockCreateAttachedWorkspaceBashTool = jest.fn(() => ({ name: AgentConstants.BASH_TOOL })); +const attachedWorkspaceOperations = [ + 'read_file', + 'search_text', + 'list_files', + 'write_file', + 'preview_edit', + 'edit_file', + 'execute_command', +]; const mockResolveCodeExecutionContext = jest.fn( ({ statefulSessions, environment, userId, agentId, conversationId }) => { if (!statefulSessions) { @@ -56,6 +65,21 @@ const mockResolveCodeExecutionContext = jest.fn( }; }, ); +const mockResolveCodeExecutionWorkspaceContext = jest.fn(async ({ context }) => { + if (context.environmentType !== 'attached') { + return context; + } + const environmentId = context.environmentId ?? 'personal-machine'; + return { + ...context, + environmentId, + codeWorkspace: { + environmentId, + workspaceId: 'project-a', + operations: attachedWorkspaceOperations, + }, + }; +}); const mockPrimeSearchFiles = jest.fn().mockResolvedValue({}); const mockPrimeCodeFiles = jest.fn().mockResolvedValue({}); jest.mock('~/server/services/Config', () => ({ @@ -85,6 +109,8 @@ jest.mock('@librechat/api', () => ({ emitChunk: (...args) => mockEmitChunk(...args), }, resolveCodeExecutionContext: (...args) => mockResolveCodeExecutionContext(...args), + resolveCodeExecutionWorkspaceContext: (...args) => + mockResolveCodeExecutionWorkspaceContext(...args), createAttachedWorkspaceBashTool: (...args) => mockCreateAttachedWorkspaceBashTool(...args), })); @@ -2712,6 +2738,9 @@ describe('ToolService - Action Capability Gating', () => { AgentCapabilities.stateful_code_sessions, ]; const req = createMockReq(capabilities); + req.body = { + codeWorkspaces: [{ environmentId: 'personal-machine', workspaceId: 'project-a' }], + }; mockGetEndpointsConfig.mockResolvedValue(createEndpointsConfig(capabilities)); mockResolveCodeExecutionContext.mockReturnValueOnce({ baseUrl: 'http://attached-code.test/v1', @@ -2719,6 +2748,7 @@ describe('ToolService - Action Capability Gating', () => { executionProfile: 'stateful', statefulSessions: true, environmentType: 'attached', + environmentId: 'personal-machine', bridgeWorkerId: 'worker-abc', }); const toolRegistry = new Map([ @@ -2743,8 +2773,12 @@ describe('ToolService - Action Capability Gating', () => { expect(mockCreateAttachedWorkspaceBashTool).toHaveBeenCalledWith({ authHeaders: expect.any(Function), baseUrl: 'http://attached-code.test/v1', + workspaceId: 'project-a', gitIdentity: { name: 'LibreChat Agent', email: 'agent@example.com' }, }); + expect(mockResolveCodeExecutionWorkspaceContext).toHaveBeenCalledWith( + expect.objectContaining({ requestedSelections: req.body.codeWorkspaces }), + ); expect(result.loadedTools).toContainEqual({ name: AgentConstants.BASH_TOOL }); }); @@ -3060,9 +3094,9 @@ describe('ToolService - Action Capability Gating', () => { it.each([ { statefulWorkspace: false, runtimes: ['bash'], supported: false }, { statefulWorkspace: true, runtimes: ['py'], supported: false }, - { statefulWorkspace: true, runtimes: ['bash'], supported: true }, + { statefulWorkspace: true, runtimes: ['bash'], supported: false }, ])( - 'loads attached PTC using deployment credentials: stateful=$statefulWorkspace runtimes=$runtimes', + 'suppresses workspace-unaware attached PTC: stateful=$statefulWorkspace runtimes=$runtimes', async ({ statefulWorkspace, runtimes, supported }) => { const capabilities = [ AgentCapabilities.tools, @@ -3123,13 +3157,8 @@ describe('ToolService - Action Capability Gating', () => { (tool) => tool.name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING, ), ).toBe(supported); - expect(mockGetAppConfig).toHaveBeenCalledWith({ baseOnly: true }); - expect(fetchSpy).toHaveBeenCalledWith( - `https://attached.example/bridge/workers/${environment.workerId}/status`, - expect.objectContaining({ - headers: { Authorization: `Bearer deployment-token-${statefulWorkspace}` }, - }), - ); + expect(mockGetAppConfig).not.toHaveBeenCalled(); + expect(fetchSpy).not.toHaveBeenCalled(); } finally { fetchSpy.mockRestore(); delete process.env.TEST_PTC_DEPLOYMENT_TOKEN; diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx index bcee4fa0f5..819d67a42d 100644 --- a/client/src/components/Chat/Input/ChatForm.tsx +++ b/client/src/components/Chat/Input/ChatForm.tsx @@ -16,6 +16,7 @@ import { useQueryParams, useSubmitMessage, useFocusChatEffect, + useCodeWorkspace, } from '~/hooks'; import { cn, @@ -49,6 +50,7 @@ import { mainTextareaId, BadgeItem } from '~/common'; import PendingSteerChips from './PendingSteerChips'; import PendingQuoteChips from './PendingQuoteChips'; import AttachFileChat from './Files/AttachFileChat'; +import CodeWorkspaceMenu from './CodeWorkspaceMenu'; import useSteering from '~/hooks/Chat/useSteering'; import CodeApprovalMenu from './CodeApprovalMenu'; import FileFormChat from './Files/FileFormChat'; @@ -282,6 +284,7 @@ const ChatForm = memo(function ChatForm({ ); const { submitMessage, submitPrompt } = useSubmitMessage(); + const codeWorkspace = useCodeWorkspace(conversation, addedConvo); /** Queued/steered sends carry their FULL submission context: explicit * (possibly empty) overrides stop `ask` from vacuuming quotes or skill @@ -796,6 +799,12 @@ const ChatForm = memo(function ChatForm({ setConversation={setConversation} disabled={disableInputs || isSubmitting} /> + {index === 0 && conversationId != null && ( )} @@ -834,6 +843,7 @@ const ChatForm = memo(function ChatForm({ disabled={ filesLoading || disableInputs || + (codeWorkspace.required && codeWorkspace.state !== 'ready') || isNotAppendable || answerMode.composerLocked || (isSubmitting && !answerMode.composerAnswers) @@ -897,6 +907,7 @@ function ChatFormWrapper({ conversation?.model, conversation?.maxContextTokens, conversation?.codeApprovalMode, + conversation?.codeWorkspaces, hasMessages, ], ); diff --git a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx new file mode 100644 index 0000000000..2054fea0d3 --- /dev/null +++ b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx @@ -0,0 +1,184 @@ +import { useEffect } from 'react'; +import * as Ariakit from '@ariakit/react'; +import { Check, ChevronDown, Folder, FolderX } from 'lucide-react'; +import { TooltipAnchor, composerControlClasses } from '@librechat/client'; +import type { CodeWorkspaceSelection, TConversation } from 'librechat-data-provider'; +import type { SetterOrUpdater } from 'recoil'; +import type { CodeWorkspaceResult, TranslationKeys } from '~/hooks'; +import { useLocalize } from '~/hooks'; +import { cn } from '~/utils'; + +const stateLabels: Partial> = { + loading: 'com_ui_code_workspace_loading', + choose: 'com_ui_code_workspace_choose', + missing: 'com_ui_code_workspace_missing', + unavailable: 'com_ui_code_workspace_unavailable', + unsupported: 'com_ui_code_workspace_unsupported', +}; + +export default function CodeWorkspaceMenu({ + conversation, + setConversation, + workspace, + disabled, +}: { + conversation: TConversation | null; + setConversation: SetterOrUpdater; + workspace: CodeWorkspaceResult; + disabled: boolean; +}) { + const localize = useLocalize(); + const menuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' }); + const isOpen = menuStore.useState('open'); + + /** A single advertised root per reachable environment is an unambiguous + * initial choice. Once a conversation owns any binding, even a partial or + * stale set, only explicit user actions may replace or complete it. */ + useEffect(() => { + if (conversation?.codeWorkspaces != null || workspace.selections == null) return; + setConversation((current) => + current == null || current.codeWorkspaces != null + ? current + : { ...current, codeWorkspaces: workspace.selections }, + ); + }, [conversation?.codeWorkspaces, setConversation, workspace.selections]); + + if (!workspace.required) return null; + + const environmentIds = new Set(workspace.environments.map(({ environment }) => environment.id)); + const selectWorkspace = (selection: CodeWorkspaceSelection) => { + setConversation((current) => { + if (current == null) return current; + const retained = (current.codeWorkspaces ?? []).filter( + ({ environmentId }) => + environmentIds.has(environmentId) && environmentId !== selection.environmentId, + ); + return { + ...current, + codeWorkspaces: [...retained, selection].sort((a, b) => + a.environmentId.localeCompare(b.environmentId), + ), + }; + }); + }; + 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; + if (label == null && workspace.state === 'ready') { + label = localize('com_ui_code_workspaces_selected', { + 0: workspace.selections?.length ?? 0, + }); + } 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; + + return ( + + + } + > + + {canChoose && ( + + {workspace.environments.map(({ environment, state, workspaces, selected }) => ( +
+ } + className="px-2.5 py-1.5 text-xs font-medium text-text-secondary" + > + {environment.name ?? environment.id} + + {workspaces.length === 0 && ( +
+ {localize(stateLabels[state] ?? 'com_ui_code_workspace_unavailable')} +
+ )} + {workspaces.map((descriptor) => { + const isSelected = descriptor.id === selected?.workspaceId; + return ( + + selectWorkspace({ environmentId: environment.id, workspaceId: descriptor.id }) + } + className={cn( + 'group flex w-full cursor-pointer items-start gap-3 rounded-lg px-2.5 py-2', + 'outline-none transition-colors duration-theme-fast', + 'hover:bg-surface-hover data-[active-item]:bg-surface-hover', + isSelected && 'bg-surface-active-alt', + )} + > + + ); + })} +
+ ))} +
+ )} +
+ ); +} diff --git a/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx b/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx new file mode 100644 index 0000000000..4a72f34d75 --- /dev/null +++ b/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx @@ -0,0 +1,114 @@ +import userEvent from '@testing-library/user-event'; +import { render, screen } from '@testing-library/react'; +import type { TConversation } from 'librechat-data-provider'; +import type { CodeWorkspaceResult } from '~/hooks'; +import CodeWorkspaceMenu from '../CodeWorkspaceMenu'; + +jest.mock('~/hooks', () => ({ + useLocalize: () => (key: string) => key, +})); + +jest.mock('@librechat/client', () => { + const { cloneElement } = jest.requireActual('react'); + return { + composerControlClasses: () => 'composer-control', + TooltipAnchor: ({ + render, + children, + }: { + render: React.ReactElement; + children: React.ReactNode; + }) => cloneElement(render, {}, children), + }; +}); + +const conversation = { + conversationId: 'conversation-1', + endpoint: 'agents', + agent_id: 'agent-1', + title: 'Code', +} as TConversation; +const environment = { + id: 'personal-vm', + name: 'Personal VM', + type: 'attached' as const, + baseURL: 'https://code.example.com', +}; + +function workspace(overrides: Partial = {}): CodeWorkspaceResult { + const selected = { environmentId: environment.id, workspaceId: 'project-a' }; + return { + required: true, + state: 'ready', + environments: [ + { + environment, + state: 'ready', + workspaces: [{ id: 'project-a', name: 'Project A' }], + selected, + }, + ], + selections: [selected], + resolveSelections: () => [selected], + ...overrides, + }; +} + +describe('CodeWorkspaceMenu', () => { + test('stores one unambiguous initial workspace on the conversation', () => { + const setConversation = jest.fn(); + render( + , + ); + + const update = setConversation.mock.calls[0][0]; + expect(update(conversation)).toEqual({ + ...conversation, + codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }], + }); + expect(screen.getByTestId('code-workspace')).toHaveTextContent('Project A'); + }); + + test('keeps a missing binding until the user explicitly selects a replacement', async () => { + const savedConversation = { + ...conversation, + codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'removed-project' }], + }; + const setConversation = jest.fn(); + render( + , + ); + + expect(setConversation).not.toHaveBeenCalled(); + expect(screen.getByTestId('code-workspace')).toHaveTextContent('com_ui_code_workspace_missing'); + await userEvent.click(screen.getByTestId('code-workspace')); + await userEvent.click(await screen.findByText('Project A')); + + const update = setConversation.mock.calls[0][0]; + expect(update(savedConversation)).toEqual({ + ...savedConversation, + codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }], + }); + }); +}); diff --git a/client/src/components/Messages/Content/Error.tsx b/client/src/components/Messages/Content/Error.tsx index 2723d380ca..fceb06ab1c 100644 --- a/client/src/components/Messages/Content/Error.tsx +++ b/client/src/components/Messages/Content/Error.tsx @@ -126,6 +126,7 @@ const errorMessages = { [ErrorTypes.GOOGLE_TOOL_CONFLICT]: 'com_error_google_tool_conflict', [ErrorTypes.GOOGLE_VIDEO_UNPROCESSABLE]: 'com_error_google_video_unprocessable', [ErrorTypes.RESOURCE_RECOVERY_REQUIRED]: 'com_error_resource_recovery_required', + [ErrorTypes.CODE_WORKSPACE_UNAVAILABLE]: 'com_error_code_workspace_unavailable', [ErrorTypes.STREAM_EXPIRED]: 'com_error_stream_expired', [ErrorTypes.MODEL_NOT_FOUND]: langChainErrorKeys.MODEL_NOT_FOUND, [ErrorTypes.MODEL_RATE_LIMIT]: langChainErrorKeys.MODEL_RATE_LIMIT, diff --git a/client/src/components/Messages/Content/__tests__/Error.spec.tsx b/client/src/components/Messages/Content/__tests__/Error.spec.tsx index 9baa4bff5f..8a246597c7 100644 --- a/client/src/components/Messages/Content/__tests__/Error.spec.tsx +++ b/client/src/components/Messages/Content/__tests__/Error.spec.tsx @@ -52,6 +52,7 @@ describe('Error — typed provider errors', () => { it.each([ [ErrorTypes.MODEL_NOT_FOUND, 'com_error_model_not_found'], [ErrorTypes.MODEL_RATE_LIMIT, 'com_error_model_rate_limit'], + [ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, 'com_error_code_workspace_unavailable'], ])('localizes the typed %s payload the server now emits', (type, key) => { render(); diff --git a/client/src/data-provider/CodeEnvironments.ts b/client/src/data-provider/CodeEnvironments.ts index 957a28b971..153c78655c 100644 --- a/client/src/data-provider/CodeEnvironments.ts +++ b/client/src/data-provider/CodeEnvironments.ts @@ -1,4 +1,4 @@ -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query'; import { DynamicQueryKeys, MutationKeys, QueryKeys, dataService } from 'librechat-data-provider'; import type { CodeEnvironmentUserSettings, @@ -30,6 +30,19 @@ export function useCodeEnvironmentStatusQuery(id: string, enabled = true) { ); } +export function useCodeEnvironmentStatusQueries(ids: string[], enabled = true) { + return useQueries({ + queries: ids.map((id) => ({ + queryKey: DynamicQueryKeys.codeEnvironmentStatus(id), + queryFn: () => dataService.getCodeEnvironmentStatus(id), + enabled: enabled && id.length > 0, + refetchInterval: 10_000, + refetchIntervalInBackground: false, + retry: false, + })), + }); +} + export function usePairCodeEnvironmentMutation() { const queryClient = useQueryClient(); return useMutation< diff --git a/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts b/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts index 115d96d2f9..35d58e3f7f 100644 --- a/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts +++ b/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts @@ -16,7 +16,7 @@ jest.mock('~/Providers', () => ({ useAgentsMapContext: () => mockUseAgentsMapCon const conversation = { conversationId: 'conversation-1', endpoint: 'agents', - agent_id: 'agent-1', + agent_id: 'agent_1', title: 'Code', createdAt: '2026-09-01T00:00:00.000Z', updatedAt: '2026-09-01T00:00:00.000Z', @@ -29,7 +29,7 @@ describe('useCodeApprovalMode', () => { mockUseAgentsMapContext.mockReturnValue({}); mockUseAgentToolPermissions.mockReturnValue({ agent: { - id: 'agent-1', + id: 'agent_1', tools: ['execute_code'], stateful_code_sessions: true, code_environment_id: 'mac', @@ -77,7 +77,7 @@ describe('useCodeApprovalMode', () => { }; mockUseAgentToolPermissions.mockReturnValue({ agent: { - id: 'agent-1', + id: 'agent_1', tools: ['execute_code'], stateful_code_sessions: true, code_environment_id: 'mac', @@ -120,7 +120,7 @@ describe('useCodeApprovalMode', () => { }, ); - test.each(['agent-1', 'agent-2'])( + test.each(['agent_1', 'agent_2'])( 'waits for unresolved root %s before full access', (missingId) => { const permissions = { @@ -151,7 +151,7 @@ describe('useCodeApprovalMode', () => { const { result, rerender } = renderHook(() => useCodeApprovalMode( { ...conversation, codeApprovalMode: 'fullAccess' }, - { ...conversation, agent_id: 'agent-2' }, + { ...conversation, agent_id: 'agent_2' }, ), ); expect(result.current.modes).not.toContain('fullAccess'); @@ -244,7 +244,7 @@ describe('useCodeApprovalMode', () => { test('includes attached subagents while preserving their mandatory asks', () => { const primary = { - id: 'agent-1', + id: 'agent_1', tools: [], stateful_code_sessions: false, subagents: { enabled: true, agent_ids: ['child-1', 'child-2'] }, @@ -299,20 +299,20 @@ describe('useCodeApprovalMode', () => { test('includes the active parallel conversation agent', () => { const primary = { - id: 'agent-1', + id: 'agent_1', tools: [], stateful_code_sessions: false, }; const addedAgent = { - id: 'agent-2', + id: 'agent_2', tools: ['execute_code'], stateful_code_sessions: true, code_environment_id: 'mac', }; mockUseAgentToolPermissions.mockImplementation((agentId?: string) => ({ - agent: agentId === 'agent-2' ? addedAgent : primary, + agent: agentId === 'agent_2' ? addedAgent : primary, })); - const addedConversation = { endpoint: 'agents', agent_id: 'agent-2' } as TConversation; + const addedConversation = { endpoint: 'agents', agent_id: 'agent_2' } as TConversation; const { result } = renderHook(() => useCodeApprovalMode(conversation, addedConversation)); @@ -323,7 +323,7 @@ describe('useCodeApprovalMode', () => { test('does not traverse disabled subagent configurations', () => { mockUseAgentToolPermissions.mockReturnValue({ agent: { - id: 'agent-1', + id: 'agent_1', tools: ['execute_code'], stateful_code_sessions: true, code_environment_id: 'restricted', diff --git a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx new file mode 100644 index 0000000000..fe80485cda --- /dev/null +++ b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx @@ -0,0 +1,273 @@ +import { renderHook } from '@testing-library/react'; +import { EModelEndpoint, Tools } from 'librechat-data-provider'; +import type { TConversation } from 'librechat-data-provider'; +import useCodeWorkspace from '../useCodeWorkspace'; + +const mockAgentPermissions = jest.fn(); +const mockAgentsConfig = jest.fn(); +const mockStatus = jest.fn(); +const mockAgentsMap = jest.fn(); +const mockAccess = jest.fn(); +jest.mock('~/hooks/Roles/useHasAccess', () => () => mockAccess()); + +jest.mock( + '../useAgentToolPermissions', + () => + (...args: unknown[]) => + mockAgentPermissions(...args), +); +jest.mock('../useGetAgentsConfig', () => () => mockAgentsConfig()); +jest.mock('~/Providers', () => ({ useAgentsMapContext: () => mockAgentsMap() })); +jest.mock('~/data-provider', () => ({ + useCodeEnvironmentStatusQueries: (...args: unknown[]) => mockStatus(...args), +})); + +const conversation = (codeWorkspaces?: TConversation['codeWorkspaces']): TConversation => + ({ + conversationId: 'conversation-1', + endpoint: EModelEndpoint.agents, + agent_id: 'agent-1', + codeWorkspaces, + }) as TConversation; + +describe('useCodeWorkspace', () => { + beforeEach(() => { + mockAccess.mockReturnValue(true); + mockAgentPermissions.mockReturnValue({ + tools: [Tools.execute_code], + agent: { + id: 'agent-1', + stateful_code_sessions: true, + code_environment_id: 'personal-vm', + tools: [Tools.execute_code], + }, + }); + mockAgentsMap.mockReturnValue({}); + mockAgentsConfig.mockReturnValue({ + agentsConfig: { + capabilities: ['execute_code', 'stateful_code_sessions'], + statefulCodeSessions: { + environments: [ + { + id: 'personal-vm', + name: 'Personal VM', + type: 'attached', + baseURL: 'https://code.example.com', + }, + ], + }, + }, + }); + mockStatus.mockReturnValue([ + { + data: { + environmentId: 'personal-vm', + status: 'ready', + statefulWorkspace: true, + workspaces: [{ id: 'project-a', name: 'Project A' }], + }, + isLoading: false, + isError: false, + }, + ]); + }); + + it.each(['role', 'execute_code', 'stateful_code_sessions'])( + 'does not require a workspace when %s permission is disabled', + (gate) => { + if (gate === 'role') mockAccess.mockReturnValue(false); + else { + const config = mockAgentsConfig(); + config.agentsConfig.capabilities = config.agentsConfig.capabilities.filter( + (value: string) => value !== gate, + ); + } + const { result } = renderHook(() => useCodeWorkspace(conversation())); + expect(result.current.required).toBe(false); + expect(result.current.state).toBe('not_required'); + expect(mockStatus).toHaveBeenLastCalledWith(['personal-vm'], false); + }, + ); + + it('selects one unambiguous initial workspace', () => { + const { result } = renderHook(() => useCodeWorkspace(conversation())); + + expect(result.current.state).toBe('ready'); + expect(result.current.selections).toEqual([ + { environmentId: 'personal-vm', workspaceId: 'project-a' }, + ]); + expect(mockStatus).toHaveBeenCalledWith(['personal-vm'], true); + }); + + it.each(['ephemeral', 'openAI__gpt-4o'])('does not block ephemeral agent %s', (agent_id) => { + mockAgentPermissions.mockReturnValue({}); + const { result } = renderHook(() => useCodeWorkspace({ ...conversation(), agent_id })); + expect(result.current.required).toBe(false); + expect(result.current.state).toBe('not_required'); + expect(mockStatus).toHaveBeenLastCalledWith([], false); + }); + + it('still blocks missing saved-agent metadata alongside an ephemeral agent', () => { + mockAgentPermissions.mockReturnValue({}); + const { result } = renderHook(() => + useCodeWorkspace( + { ...conversation(), agent_id: 'ephemeral' }, + { ...conversation(), agent_id: 'agent_missing' }, + ), + ); + expect(result.current.required).toBe(true); + expect(result.current.state).toBe('unavailable'); + }); + + it.each([false, undefined])('rejects non-stateful worker support: %s', (statefulWorkspace) => { + const statuses = mockStatus(); + statuses[0].data.statefulWorkspace = statefulWorkspace; + const selection = { environmentId: 'personal-vm', workspaceId: 'project-a' }; + const { result } = renderHook(() => useCodeWorkspace(conversation([selection]))); + expect(result.current.state).toBe('unavailable'); + expect(result.current.selections).toBeUndefined(); + expect(result.current.resolveSelections([selection])).toBeUndefined(); + }); + + it('requires an explicit choice when several workspaces are advertised', () => { + mockStatus.mockReturnValue([ + { + data: { + environmentId: 'personal-vm', + status: 'ready', + statefulWorkspace: true, + workspaces: [{ id: 'project-a' }, { id: 'project-b' }], + }, + isLoading: false, + isError: false, + }, + ]); + + const { result } = renderHook(() => useCodeWorkspace(conversation())); + + expect(result.current.state).toBe('choose'); + expect(result.current.selections).toBeUndefined(); + }); + + it('does not replace a saved workspace that disappeared', () => { + const saved = { environmentId: 'personal-vm', workspaceId: 'removed-project' }; + const { result } = renderHook(() => useCodeWorkspace(conversation([saved]))); + + expect(result.current.state).toBe('missing'); + expect(result.current.selections).toBeUndefined(); + expect(result.current.resolveSelections([saved])).toBeUndefined(); + }); + + it('does not reuse a workspace selection after the environment changes', () => { + const saved = { environmentId: 'old-vm', workspaceId: 'project-a' }; + const { result } = renderHook(() => useCodeWorkspace(conversation([saved]))); + + expect(result.current.state).toBe('choose'); + expect(result.current.selections).toBeUndefined(); + }); + + it('rejects a status response for a different environment', () => { + mockStatus.mockReturnValue([ + { + data: { + environmentId: 'another-vm', + status: 'ready', + statefulWorkspace: true, + workspaces: [{ id: 'project-a' }], + }, + isLoading: false, + isError: false, + }, + ]); + + const { result } = renderHook(() => useCodeWorkspace(conversation())); + + expect(result.current.state).toBe('unavailable'); + expect(result.current.selections).toBeUndefined(); + }); + + it('blocks sending when the agent-selected environment is not accessible', () => { + mockAgentsConfig.mockReturnValue({ + agentsConfig: { + capabilities: ['execute_code', 'stateful_code_sessions'], + statefulCodeSessions: { environments: [] }, + }, + }); + + const { result } = renderHook(() => useCodeWorkspace(conversation())); + + expect(result.current.required).toBe(true); + expect(result.current.state).toBe('unavailable'); + expect(result.current.selections).toBeUndefined(); + expect(mockStatus).toHaveBeenCalledWith([], false); + }); + + it.each(['subagent', 'handoff'])('collects every attached environment through %s', (kind) => { + const primary = { + id: 'agent-1', + stateful_code_sessions: true, + code_environment_id: 'personal-vm', + tools: [Tools.execute_code], + subagents: { enabled: true, agent_ids: ['child'] }, + ...(kind === 'handoff' + ? { + subagents: { enabled: false, agent_ids: [] }, + edges: [{ from: 'agent-1', to: 'child', edgeType: 'handoff' }], + } + : {}), + }; + mockAgentPermissions.mockImplementation((id?: string) => ({ + agent: id === 'agent-1' ? primary : undefined, + tools: id === 'agent-1' ? primary.tools : undefined, + })); + mockAgentsMap.mockReturnValue({ + child: { + id: 'child', + stateful_code_sessions: true, + code_environment_id: 'team-vm', + tools: [Tools.execute_code], + }, + }); + mockAgentsConfig.mockReturnValue({ + agentsConfig: { + capabilities: ['execute_code', 'stateful_code_sessions'], + statefulCodeSessions: { + environments: [ + { id: 'personal-vm', type: 'attached', baseURL: 'https://one.example.com' }, + { id: 'team-vm', type: 'attached', baseURL: 'https://two.example.com' }, + ], + }, + }, + }); + mockStatus.mockReturnValue([ + { + data: { + environmentId: 'personal-vm', + status: 'ready', + statefulWorkspace: true, + workspaces: [{ id: 'project-a' }], + }, + isLoading: false, + isError: false, + }, + { + data: { + environmentId: 'team-vm', + status: 'ready', + statefulWorkspace: true, + workspaces: [{ id: 'project-b' }], + }, + isLoading: false, + isError: false, + }, + ]); + + const { result } = renderHook(() => useCodeWorkspace(conversation())); + + expect(result.current.state).toBe('ready'); + expect(result.current.selections).toEqual([ + { environmentId: 'personal-vm', workspaceId: 'project-a' }, + { environmentId: 'team-vm', workspaceId: 'project-b' }, + ]); + }); +}); diff --git a/client/src/hooks/Agents/index.ts b/client/src/hooks/Agents/index.ts index 639ac2ade3..02687456cf 100644 --- a/client/src/hooks/Agents/index.ts +++ b/client/src/hooks/Agents/index.ts @@ -10,5 +10,7 @@ export { default as useAgentUploadTarget } from './useAgentUploadTarget'; export type { AgentUploadTarget } from './useAgentUploadTarget'; export { default as useAgentToolPermissions } from './useAgentToolPermissions'; export { default as useCodeApprovalMode } from './useCodeApprovalMode'; +export { default as useCodeWorkspace } from './useCodeWorkspace'; +export type { CodeWorkspaceResult, CodeWorkspaceState } from './useCodeWorkspace'; export { default as useMCPToolOptions } from './useMCPToolOptions'; export * from './useApplyModelSpecAgents'; diff --git a/client/src/hooks/Agents/useCodeApprovalMode.ts b/client/src/hooks/Agents/useCodeApprovalMode.ts index 677ead68be..3ee381cd14 100644 --- a/client/src/hooks/Agents/useCodeApprovalMode.ts +++ b/client/src/hooks/Agents/useCodeApprovalMode.ts @@ -2,6 +2,7 @@ import { useMemo } from 'react'; import { EModelEndpoint, Tools, + isEphemeralAgentId, getAllowedCodeApprovalModes, CODE_APPROVAL_MODES, } from 'librechat-data-provider'; @@ -95,7 +96,7 @@ export default function useCodeApprovalMode( return { available, modes, selected }; } -function findExecutionEnvironment( +export function findExecutionEnvironment( agent: Agent, environments?: TPublicCodeEnvironment[], ): TPublicCodeEnvironment | undefined { @@ -104,7 +105,7 @@ function findExecutionEnvironment( : environments?.find((candidate) => candidate.default === true); } -function collectReachableAgents( +export function collectReachableAgents( roots: Array, agentsMap: TAgentsMap | undefined, expectedRootIds: Array, @@ -113,24 +114,28 @@ function collectReachableAgents( const visited = new Set(); const agents: Agent[] = []; let complete = expectedRootIds.every( - (id) => id == null || roots.some((agent) => agent?.id === id), + (id) => isEphemeralAgentId(id) || roots.some((agent) => agent?.id === id), ); while (pending.length > 0) { const agent = pending.pop(); if (agent == null || visited.has(agent.id)) continue; visited.add(agent.id); agents.push(agent); - if (agent.subagents?.enabled !== true) continue; - const edgeIds = agent.edges?.flatMap((edge) => (Array.isArray(edge.to) ? edge.to : [edge.to])); - const graphIds = agent.subagents.graphs?.flatMap((graph) => graph.agent_ids); + const edgeIds = agent.edges?.flatMap((edge) => [ + ...(Array.isArray(edge.from) ? edge.from : [edge.from]), + ...(Array.isArray(edge.to) ? edge.to : [edge.to]), + ]); + const subagents = agent.subagents?.enabled === true ? agent.subagents : undefined; + const graphIds = subagents?.graphs?.flatMap((graph) => graph.agent_ids); const ids = [ ...(agent.agent_ids ?? []), - ...(agent.subagents?.agent_ids ?? []), + ...(subagents?.agent_ids ?? []), ...(edgeIds ?? []), ...(graphIds ?? []), ]; for (const id of ids) { - const candidate = agentsMap?.[id]; + if (visited.has(id)) continue; + const candidate = roots.find((root) => root?.id === id) ?? agentsMap?.[id]; if (candidate != null) pending.push(candidate); else complete = false; } diff --git a/client/src/hooks/Agents/useCodeWorkspace.ts b/client/src/hooks/Agents/useCodeWorkspace.ts new file mode 100644 index 0000000000..91315bf40c --- /dev/null +++ b/client/src/hooks/Agents/useCodeWorkspace.ts @@ -0,0 +1,213 @@ +import { useCallback, useMemo } from 'react'; +import { AgentCapabilities, PermissionTypes, Permissions } from 'librechat-data-provider'; +import { EModelEndpoint, Tools, isCodeWorkspaceSelections } from 'librechat-data-provider'; +import type { + CodeWorkspaceDescriptor, + CodeWorkspaceSelection, + TConfig, + TCodeEnvironmentStatusResponse, + TConversation, + TPublicCodeEnvironment, +} from 'librechat-data-provider'; +import { collectReachableAgents, findExecutionEnvironment } from './useCodeApprovalMode'; +import { useCodeEnvironmentStatusQueries } from '~/data-provider'; +import useAgentToolPermissions from './useAgentToolPermissions'; +import useHasAccess from '~/hooks/Roles/useHasAccess'; +import useGetAgentsConfig from './useGetAgentsConfig'; +import { useAgentsMapContext } from '~/Providers'; + +export type CodeWorkspaceState = + | 'not_required' + | 'loading' + | 'choose' + | 'ready' + | 'missing' + | 'unavailable' + | 'unsupported'; + +export interface CodeWorkspaceEnvironmentResult { + environment: TPublicCodeEnvironment; + state: Exclude; + workspaces: CodeWorkspaceDescriptor[]; + selected?: CodeWorkspaceSelection; +} + +export interface CodeWorkspaceResult { + required: boolean; + state: CodeWorkspaceState; + environments: CodeWorkspaceEnvironmentResult[]; + selections?: CodeWorkspaceSelection[]; + resolveSelections: ( + selections?: CodeWorkspaceSelection[], + ) => CodeWorkspaceSelection[] | undefined; +} + +function aggregateState( + required: boolean, + complete: boolean, + environments: CodeWorkspaceEnvironmentResult[], + selections: CodeWorkspaceSelection[] | undefined, +): CodeWorkspaceState { + if (!required) return 'not_required'; + if (!complete || environments.some(({ state }) => state === 'unavailable')) return 'unavailable'; + if (environments.some(({ state }) => state === 'unsupported')) return 'unsupported'; + if (environments.some(({ state }) => state === 'missing')) return 'missing'; + if (environments.some(({ state }) => state === 'loading')) return 'loading'; + if (selections == null) return 'choose'; + return 'ready'; +} + +function resolveEnvironmentSelection({ + environment, + status, + workspaces, + stored, + hasStoredSelections, +}: { + environment: TPublicCodeEnvironment; + status?: TCodeEnvironmentStatusResponse; + workspaces: CodeWorkspaceDescriptor[]; + stored?: CodeWorkspaceSelection; + hasStoredSelections: boolean; +}): CodeWorkspaceSelection | undefined { + if ( + status?.status !== 'ready' || + status.statefulWorkspace !== true || + status.environmentId !== environment.id + ) + return undefined; + if (stored != null && workspaces.some(({ id }) => id === stored.workspaceId)) { + return { environmentId: environment.id, workspaceId: stored.workspaceId }; + } + if (!hasStoredSelections && workspaces.length === 1) { + return { environmentId: environment.id, workspaceId: workspaces[0].id }; + } + return undefined; +} + +export default function useCodeWorkspace( + conversation: TConversation | null, + addedConversation?: TConversation | null, +): CodeWorkspaceResult { + const { agentsConfig } = useGetAgentsConfig(); + const canRunCode = useHasAccess({ + permissionType: PermissionTypes.RUN_CODE, + permission: Permissions.USE, + }); + const codeEnabled = + canRunCode && + agentsConfig?.capabilities?.includes(AgentCapabilities.execute_code) === true && + agentsConfig.capabilities.includes(AgentCapabilities.stateful_code_sessions); + const agentsMap = useAgentsMapContext(); + const { agent: primaryAgent } = useAgentToolPermissions(conversation?.agent_id); + const { agent: addedAgent } = useAgentToolPermissions(addedConversation?.agent_id); + const statefulCodeSessions = agentsConfig?.statefulCodeSessions as + | TConfig['statefulCodeSessions'] + | undefined; + const reachable = useMemo( + () => + collectReachableAgents([primaryAgent, addedAgent], agentsMap, [ + conversation?.agent_id, + addedConversation?.agent_id, + ]), + [addedAgent, agentsMap, primaryAgent, conversation?.agent_id, addedConversation?.agent_id], + ); + const workspaceMetadata = useMemo(() => { + const unique = new Map(); + let complete = true; + for (const agent of reachable.agents) { + if (agent.stateful_code_sessions !== true || !agent.tools?.includes(Tools.execute_code)) { + continue; + } + const environment = findExecutionEnvironment(agent, statefulCodeSessions?.environments); + if (agent.code_environment_id && environment == null) complete = false; + if (environment?.type === 'attached') unique.set(environment.id, environment); + } + return { + complete, + environments: [...unique.values()].sort((a, b) => a.id.localeCompare(b.id)), + }; + }, [reachable.agents, statefulCodeSessions?.environments]); + const isAgentsConversation = + (conversation?.endpointType ?? conversation?.endpoint) === EModelEndpoint.agents; + const expectedRoot = conversation?.agent_id != null || addedConversation?.agent_id != null; + const attachedEnvironments = workspaceMetadata.environments; + const metadataComplete = + !isAgentsConversation || !expectedRoot || (reachable.complete && workspaceMetadata.complete); + const required = + codeEnabled && isAgentsConversation && (!metadataComplete || attachedEnvironments.length > 0); + const statuses = useCodeEnvironmentStatusQueries( + attachedEnvironments.map(({ id }) => id), + required && metadataComplete, + ); + const storedSelections = conversation?.codeWorkspaces; + const environmentResults = attachedEnvironments.map((environment, index) => { + const status = statuses[index]; + const workspaces = + status?.data?.status === 'ready' && Array.isArray(status.data.workspaces) + ? status.data.workspaces + : []; + const stored = storedSelections?.find(({ environmentId }) => environmentId === environment.id); + const selected = resolveEnvironmentSelection({ + environment, + status: status?.data, + workspaces, + stored, + hasStoredSelections: storedSelections != null, + }); + let state: CodeWorkspaceEnvironmentResult['state'] = 'choose'; + if (status == null || status.isLoading) state = 'loading'; + else if ( + status.isError || + status.data?.status !== 'ready' || + status.data.statefulWorkspace !== true || + status.data.environmentId !== environment.id + ) { + state = 'unavailable'; + } else if (status.data.workspaces == null) state = 'unsupported'; + else if (selected != null) state = 'ready'; + else if (stored != null) state = 'missing'; + return { environment, state, workspaces, selected }; + }); + + const resolveSelections = useCallback( + (selections?: CodeWorkspaceSelection[]): CodeWorkspaceSelection[] | undefined => { + if (!required || !metadataComplete || !isCodeWorkspaceSelections(selections ?? [])) { + return undefined; + } + const resolved: CodeWorkspaceSelection[] = []; + for (const result of environmentResults) { + const requested = selections?.find( + ({ environmentId }) => environmentId === result.environment.id, + ); + if ( + requested != null && + result.state !== 'loading' && + result.state !== 'unavailable' && + result.state !== 'unsupported' && + result.workspaces.some(({ id }) => id === requested.workspaceId) + ) { + resolved.push({ + environmentId: result.environment.id, + workspaceId: requested.workspaceId, + }); + continue; + } + if (selections == null && result.workspaces.length === 1 && result.state === 'ready') { + resolved.push({ + environmentId: result.environment.id, + workspaceId: result.workspaces[0].id, + }); + continue; + } + return undefined; + } + return resolved.sort((a, b) => a.environmentId.localeCompare(b.environmentId)); + }, + [environmentResults, metadataComplete, required], + ); + + const selections = resolveSelections(storedSelections); + const state = aggregateState(required, metadataComplete, environmentResults, selections); + return { required, state, environments: environmentResults, selections, resolveSelections }; +} diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx index 0a2b8c83c5..3a3dcde848 100644 --- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx +++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx @@ -1,6 +1,11 @@ import { renderHook, act } from '@testing-library/react'; import { Constants, EModelEndpoint } from 'librechat-data-provider'; -import type { TConversation, TMessage, TSubmission } from 'librechat-data-provider'; +import type { + CodeWorkspaceSelection, + TConversation, + TMessage, + TSubmission, +} from 'librechat-data-provider'; import useChatFunctions from '../useChatFunctions'; import { isPasteSubmitted } from '~/utils'; @@ -14,6 +19,14 @@ const mockGetExpiry = jest.fn(() => 'expiry-key'); const mockGetQueryData = jest.fn(() => ({})); const mockLoggerWarn = jest.fn(); const mockGetLatestConversation = jest.fn(() => null as TConversation | null); +const mockResolveCodeWorkspace = jest.fn< + CodeWorkspaceSelection[] | undefined, + [CodeWorkspaceSelection[]?] +>(() => undefined); +const mockCodeWorkspace = { + required: false, + resolveSelections: mockResolveCodeWorkspace, +}; jest.mock('react-router-dom', () => ({ useNavigate: () => mockNavigate, @@ -45,6 +58,7 @@ jest.mock('~/hooks/Agents/useCodeApprovalMode', () => () => ({ modes: ['ask', 'acceptEdits'], selected: 'ask', })); +jest.mock('~/hooks/Agents/useCodeWorkspace', () => () => mockCodeWorkspace); jest.mock('~/hooks/Conversations/useGetConversation', () => () => mockGetLatestConversation); jest.mock('~/hooks/Conversations/useGetSender', () => () => mockGetSender); jest.mock('~/hooks/Input/useUserKey', () => () => ({ getExpiry: mockGetExpiry })); @@ -136,6 +150,8 @@ describe('useChatFunctions ask', () => { jest.clearAllMocks(); mockGetQueryData.mockReturnValue({}); mockGetLatestConversation.mockReturnValue(null); + mockCodeWorkspace.required = false; + mockResolveCodeWorkspace.mockReturnValue(undefined); }); it('reads an approval-mode selection made immediately before send', () => { @@ -153,6 +169,36 @@ describe('useChatFunctions ask', () => { expect(submission.codeApprovalMode).toBe('acceptEdits'); }); + it('submits the latest validated workspace selection', () => { + const selection = { environmentId: 'personal-vm', workspaceId: 'project-a' }; + mockCodeWorkspace.required = true; + mockResolveCodeWorkspace.mockReturnValue([selection]); + mockGetLatestConversation.mockReturnValue({ + ...conversation('conversation-1'), + codeWorkspaces: [selection], + }); + const { result, setSubmission } = renderAsk([]); + + act(() => { + result.current.ask({ text: 'Edit the file', conversationId: 'conversation-1' }); + }); + + const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission; + expect(mockResolveCodeWorkspace).toHaveBeenCalledWith([selection]); + expect(submission.codeWorkspaces).toEqual([selection]); + }); + + it('refuses to send while the required workspace is unavailable', () => { + mockCodeWorkspace.required = true; + mockResolveCodeWorkspace.mockReturnValue(undefined); + const { result, setSubmission } = renderAsk([]); + + expect(result.current.ask({ text: 'Edit the file', conversationId: 'conversation-1' })).toBe( + false, + ); + expect(setSubmission).not.toHaveBeenCalled(); + }); + it('refuses to send to an existing conversation before its history loads', () => { const { result, getMessages, setMessages, setSubmission } = renderAsk(undefined); diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts index 3cf5da92ba..950d4eb3e6 100644 --- a/client/src/hooks/Chat/useChatFunctions.ts +++ b/client/src/hooks/Chat/useChatFunctions.ts @@ -40,6 +40,7 @@ import useFocusRegeneratedResponse from '~/hooks/Chat/useFocusRegeneratedRespons import useGetConversation from '~/hooks/Conversations/useGetConversation'; import useCodeApprovalMode from '~/hooks/Agents/useCodeApprovalMode'; import useSetFilesToDelete from '~/hooks/Files/useSetFilesToDelete'; +import useCodeWorkspace from '~/hooks/Agents/useCodeWorkspace'; import useGetSender from '~/hooks/Conversations/useGetSender'; import store, { useGetEphemeralAgent } from '~/store'; import { startupConfigKey } from '~/data-provider'; @@ -232,6 +233,7 @@ export default function useChatFunctions({ immutableConversation, addedConversation, ); + const codeWorkspaceState = useCodeWorkspace(immutableConversation, addedConversation); /** * Atomically read + reset the per-conversation queue of manually-invoked @@ -329,6 +331,12 @@ export default function useChatFunctions({ latestCodeApprovalMode != null && codeApprovalModes.includes(latestCodeApprovalMode) ? latestCodeApprovalMode : fallbackCodeApprovalMode; + const latestCodeWorkspaces = getConversation()?.codeWorkspaces ?? conversation?.codeWorkspaces; + const codeWorkspaces = codeWorkspaceState.resolveSelections(latestCodeWorkspaces); + if (codeWorkspaceState.required && codeWorkspaces == null) { + logger.warn('[useChatFunctions] Refusing to send without an available code workspace'); + return false; + } const endpoint = conversation?.endpoint; if (endpoint === null) { @@ -743,6 +751,7 @@ export default function useChatFunctions({ addedConvo, manualSkills: manualSkills.length > 0 ? manualSkills : undefined, codeApprovalMode, + codeWorkspaces, clientRequestId, recoverySteerId: overrideRecoverySteerId, expectedPredecessorCreatedAt: overrideExpectedPredecessorCreatedAt, diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index ba47c2b815..f3d904c689 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -1,5 +1,12 @@ { "com_ui_code_approval_mode": "Code approval mode", + "com_ui_code_workspace": "Code workspace", + "com_ui_code_workspace_choose": "Choose workspace", + "com_ui_code_workspace_loading": "Loading workspace…", + "com_ui_code_workspace_missing": "Workspace missing", + "com_ui_code_workspace_unavailable": "Workspace unavailable", + "com_ui_code_workspace_unsupported": "Update worker for workspaces", + "com_ui_code_workspaces_selected": "{{0}} code workspaces", "com_ui_code_approval_ask": "Ask before changes", "com_ui_code_approval_ask_description": "Ask before editing files or running commands", "com_ui_code_approval_accept_edits": "Accept edits", @@ -404,6 +411,7 @@ "com_error_compaction_disabled": "Context compaction is not available for this agent because summarization is disabled.", "com_error_compaction_failed": "Could not compact the context: the summarizer produced no summary. Nothing was changed.", "com_error_compaction_nothing": "Nothing to compact: the retained recent turns already cover the whole conversation.", + "com_error_code_workspace_unavailable": "The selected code workspace is unavailable. Reconnect its machine or choose an available workspace, then try again.", "com_error_context_tokens_detail": "Your messages need {{0}} tokens, but only {{1}} are available.", "com_error_empty_messages": "Your messages do not fit in the current context window, so there was nothing left to send to the model. Increase the max context size from the conversation parameters, shorten your message, or start a new conversation.", "com_error_files_process": "An error occurred while processing the file.", diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.ts index 6c528e004d..1feffdf41b 100644 --- a/packages/api/src/agents/__tests__/initialize.test.ts +++ b/packages/api/src/agents/__tests__/initialize.test.ts @@ -44,6 +44,7 @@ import type { IMongoFile } from '@librechat/data-schemas'; import type { Agent } from 'librechat-data-provider'; import type { ServerRequest, InitializeResultBase, EndpointTokenConfig } from '~/types'; import type { InitializeAgentDbMethods } from '../initialize'; +import type { CodeExecutionContext } from '../execution'; import { DEFAULT_MAX_CONTEXT_TOKENS } from '../initialize'; // Mock logger — `format` must be a callable factory so @librechat/data-schemas @@ -2500,6 +2501,87 @@ describe('initializeAgent — execute_code capability expansion', () => { } }); + it.each([false, true])( + 'uses the validated attached workspace operation ceiling: protectedEdit=%s', + async (protectedEdit) => { + const { agent, req, res, loadTools, db } = createMocks(); + agent.tools = ['execute_code']; + agent.stateful_code_sessions = true; + agent.code_environment_id = 'personal-vm'; + req.config = { + endpoints: { + [EModelEndpoint.agents]: { + statefulCodeSessions: { + environments: [ + { + id: 'personal-vm', + name: 'Personal VM', + type: 'attached', + baseURL: 'https://code.example.com/v1', + owner: 'deployment', + workerId: 'worker-a', + }, + ], + }, + }, + }, + } as NonNullable; + if (protectedEdit) + req.config.filters = { + files: { + pii: { + customPatterns: [{ id: 'test', label: 'test', regex: 'secret' }], + fields: ['content'], + }, + }, + }; + const codeExecutionContext: CodeExecutionContext = { + baseUrl: 'https://code.example.com/v1', + codeSessionKey: 'execute_code:stateful:route:session', + executionProfile: 'stateful', + statefulSessions: true, + environmentId: 'personal-vm', + environmentType: 'attached', + bridgeWorkerId: 'worker-a', + codeWorkspace: { + environmentId: 'personal-vm', + workspaceId: 'project-a', + operations: ['read_file', 'list_files'], + }, + }; + if (protectedEdit) codeExecutionContext.codeWorkspace!.operations.push('edit_file'); + loadTools.mockResolvedValue({ + tools: [], + toolContextMap: {}, + dynamicToolContextMap: {}, + toolDefinitions: [], + hasDeferredTools: false, + codeExecutionContext, + }); + + const result = await initializeAgent( + { + req, + res, + agent, + loadTools, + endpointOption: { endpoint: EModelEndpoint.agents }, + allowedProviders: new Set([Providers.OPENAI]), + isInitialAgent: true, + codeEnvAvailable: true, + statefulSessionsAvailable: true, + }, + db, + ); + + expect(result.codeExecutionContext).toBe(codeExecutionContext); + expect(result.toolDefinitions?.map(({ name }) => name).sort()).toEqual([ + 'list_workspace_files', + 'read_file', + ]); + }, + ); + it('rejects a stateful environment excluded by deployment policy', async () => { const { agent, req, res, loadTools, db } = createMocks(); agent.tools = ['execute_code']; diff --git a/packages/api/src/agents/errors.spec.ts b/packages/api/src/agents/errors.spec.ts index 9c1130d4fa..ebf4a317e1 100644 --- a/packages/api/src/agents/errors.spec.ts +++ b/packages/api/src/agents/errors.spec.ts @@ -15,6 +15,7 @@ describe('isFatalAgentInitializationError', () => { it.each([ ErrorTypes.RESOURCE_RECOVERY_REQUIRED, ErrorTypes.STATEFUL_CODE_ENVIRONMENT_NOT_ALLOWED, + ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, AGENT_ATTACHMENT_LIMIT_EXCEEDED, AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE, ])('classifies %s as fatal', (code) => { diff --git a/packages/api/src/agents/errors.ts b/packages/api/src/agents/errors.ts index d3b05d20fe..8a58b5b0e8 100644 --- a/packages/api/src/agents/errors.ts +++ b/packages/api/src/agents/errors.ts @@ -49,6 +49,7 @@ export function isFatalAgentInitializationError( code === AGENT_ATTACHMENT_LIMIT_EXCEEDED || code === ErrorTypes.RESOURCE_RECOVERY_REQUIRED || code === ErrorTypes.STATEFUL_CODE_ENVIRONMENT_NOT_ALLOWED || + code === ErrorTypes.CODE_WORKSPACE_UNAVAILABLE || (code === AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE && options.allowExpectedMCPFallback !== true) ); } diff --git a/packages/api/src/agents/execution.spec.ts b/packages/api/src/agents/execution.spec.ts index 5adc8e43d5..d281dbd4d2 100644 --- a/packages/api/src/agents/execution.spec.ts +++ b/packages/api/src/agents/execution.spec.ts @@ -1,11 +1,13 @@ import winston from 'winston'; import { Writable } from 'node:stream'; import { logger } from '@librechat/data-schemas'; +import type { CodeExecutionContext } from './execution'; import { assertCodeExecutionApprovalBinding, captureCodeExecutionApprovalBinding, codeExecutionAuthHeaders, codeExecutionHeaders, + getCodeWorkspaceSelections, resolveCodeExecutionContext, } from './execution'; @@ -350,7 +352,7 @@ describe('resolveCodeExecutionContext', () => { }); describe('stateful code approval target binding', () => { - const context = (overrides: Record = {}) => ({ + const context = (overrides: Partial = {}): CodeExecutionContext => ({ baseUrl: 'https://bridge.example/v1', codeSessionKey: 'execute_code:stateful:route-a:session-a', executionProfile: 'stateful' as const, @@ -360,9 +362,35 @@ describe('stateful code approval target binding', () => { environmentId: 'environment-a', environmentType: 'attached' as const, bridgeWorkerId: 'worker-a', + codeWorkspace: { + environmentId: 'environment-a', + workspaceId: 'project-a', + operations: ['read_file', 'execute_command'], + }, ...overrides, }); + it('ignores operation ordering but binds actual permission changes', () => { + const original = context(); + const binding = (ctx: CodeExecutionContext) => + captureCodeExecutionApprovalBinding([{ id: 'a', codeExecutionContext: ctx }]); + expect( + binding( + context({ + codeWorkspace: { + ...original.codeWorkspace!, + operations: ['execute_command', 'read_file'], + }, + }), + ), + ).toEqual(binding(original)); + expect( + binding( + context({ codeWorkspace: { ...original.codeWorkspace!, operations: ['read_file'] } }), + ), + ).not.toEqual(binding(original)); + }); + it('captures only opaque, canonical identities for stateful targets', () => { const binding = captureCodeExecutionApprovalBinding([ { @@ -431,6 +459,16 @@ describe('stateful code approval target binding', () => { ['route', { executionRouteKey: 'stateful:route-b' }], ['worker', { bridgeWorkerId: 'worker-b' }], ['workspace session', { runtimeSessionHint: 'v3:environment-a:agent-user:session-b' }], + [ + 'selected directory', + { + codeWorkspace: { + environmentId: 'environment-a', + workspaceId: 'project-b', + operations: ['read_file', 'execute_command'], + }, + }, + ], ['base URL', { baseUrl: 'https://replacement.example/v1' }], ])('rejects a changed %s before execution', (_label, overrides) => { const binding = captureCodeExecutionApprovalBinding([ @@ -439,7 +477,10 @@ describe('stateful code approval target binding', () => { expect(() => assertCodeExecutionApprovalBinding(binding, [ - { id: 'agent-a', codeExecutionContext: context(overrides) }, + { + id: 'agent-a', + codeExecutionContext: context(overrides as Partial), + }, ]), ).toThrow('Retry the request and review the action again'); }); @@ -460,6 +501,12 @@ describe('stateful code approval target binding', () => { ]), ).not.toThrow(); }); + + it('persists only the environment/workspace pair, not live capabilities', () => { + expect(getCodeWorkspaceSelections([context()])).toEqual([ + { environmentId: 'environment-a', workspaceId: 'project-a' }, + ]); + }); }); describe('codeExecutionAuthHeaders', () => { diff --git a/packages/api/src/agents/execution.ts b/packages/api/src/agents/execution.ts index 989d0c3003..3447393540 100644 --- a/packages/api/src/agents/execution.ts +++ b/packages/api/src/agents/execution.ts @@ -3,6 +3,8 @@ import { logger } from '@librechat/data-schemas'; import { Constants, getCodeBaseURL } from '@librechat/agents'; import type { Agents, + CodeWorkspaceOperation, + CodeWorkspaceSelection, CodeEnvironmentUserConfigSchema, CodeEnvironmentUserSettings, StatefulCodeEnvironment, @@ -35,6 +37,36 @@ export interface CodeExecutionContext { bridgeWorkerId?: string; codeEnvironmentConfigSchema?: CodeEnvironmentUserConfigSchema; codeEnvironmentSettings?: CodeEnvironmentUserSettings; + /** Live, server-validated directory selection. Never derive session reuse from this field. */ + codeWorkspace?: CodeWorkspaceSelection & { operations: CodeWorkspaceOperation[] }; +} + +/** Removes live capability data before a workspace binding is persisted. */ +export function getCodeWorkspaceSelections( + contexts: Array< + | Pick + | null + | undefined + >, +): CodeWorkspaceSelection[] | undefined { + const selections = new Map(); + for (const context of contexts) { + const workspace = context?.codeWorkspace; + if ( + context?.environmentType !== 'attached' || + context.environmentId == null || + workspace == null || + workspace.environmentId !== context.environmentId + ) { + continue; + } + selections.set(workspace.environmentId, { + environmentId: workspace.environmentId, + workspaceId: workspace.workspaceId, + }); + } + if (selections.size === 0) return undefined; + return [...selections.values()].sort((a, b) => a.environmentId.localeCompare(b.environmentId)); } type CodeExecutionApprovalAgent = { @@ -71,6 +103,13 @@ export function captureCodeExecutionApprovalBinding( context.environmentId ?? null, context.environmentType ?? null, context.bridgeWorkerId ?? null, + context.codeWorkspace == null + ? null + : { + environmentId: context.codeWorkspace.environmentId, + workspaceId: context.codeWorkspace.workspaceId, + operations: [...new Set(context.codeWorkspace.operations)].sort(), + }, ]), ) .digest('hex'); diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.ts index f8a0fc19c7..afaef8b574 100644 --- a/packages/api/src/agents/handlers.spec.ts +++ b/packages/api/src/agents/handlers.spec.ts @@ -10,7 +10,7 @@ import type { ToolExecuteResult, ToolCallRequest, } from '@librechat/agents'; -import type { PtcToolCallEvent } from 'librechat-data-provider'; +import type { CodeWorkspaceOperation, PtcToolCallEvent } from 'librechat-data-provider'; import type { CodeExecutionContext } from './execution'; import { createOwnedToolEndHandler, @@ -105,6 +105,32 @@ function skillsInScope(): unknown[] { return [new Types.ObjectId()]; } +const TEST_ATTACHED_WORKSPACE_OPERATIONS: CodeWorkspaceOperation[] = [ + 'read_file', + 'search_text', + 'list_files', + 'write_file', + 'preview_edit', + 'edit_file', + 'execute_command', +]; + +function withTestAttachedWorkspace( + context: CodeExecutionContext | undefined, +): CodeExecutionContext | undefined { + if (context?.environmentType !== 'attached' || context.codeWorkspace != null) return context; + const environmentId = context.environmentId ?? 'personal-machine'; + return { + ...context, + environmentId, + codeWorkspace: { + environmentId, + workspaceId: 'project-a', + operations: TEST_ATTACHED_WORKSPACE_OPERATIONS, + }, + }; +} + function protectedToolOutputRequest() { return { user: { id: 'user-1' }, @@ -3920,6 +3946,9 @@ describe('createToolExecuteHandler', () => { params: Partial, configurable?: Record, ) { + const codeExecutionContext = withTestAttachedWorkspace( + configurable?.codeExecutionContext as CodeExecutionContext | undefined, + ); const loadTools: ToolExecuteOptions['loadTools'] = jest.fn(async () => ({ loadedTools: [], configurable: { @@ -3929,6 +3958,7 @@ describe('createToolExecuteHandler', () => { skillAuthoringAvailable: false, fileAuthoringToolNames: new Set(['create_file', 'edit_file']), ...(configurable ?? {}), + ...(codeExecutionContext == null ? {} : { codeExecutionContext }), }, })); return createToolExecuteHandler({ @@ -4210,7 +4240,7 @@ describe('createToolExecuteHandler', () => { file_path: 'src/new.ts', content: 'export const ok = 1;', overwrite: false, - workspace_id: 'primary', + workspace_id: 'project-a', codeApiBaseUrl: 'https://code.example.com', executionProfile: 'stateful', bridgeWorkerId: 'user-worker', @@ -4330,7 +4360,7 @@ describe('createToolExecuteHandler', () => { { oldText: 'draft', newText: 'ready' }, { oldText: 'false', newText: 'true' }, ], - workspace_id: 'primary', + workspace_id: 'project-a', codeApiBaseUrl: 'https://code.example.com', executionProfile: 'stateful', bridgeWorkerId: 'user-worker', @@ -5122,7 +5152,7 @@ describe('createToolExecuteHandler', () => { activeSkillNames: params.activeSkillNames, skillPrimedIdsByName: params.skillPrimedIdsByName, skillAuthoringAvailable: params.skillAuthoringAvailable === true, - codeExecutionContext: params.codeExecutionContext, + codeExecutionContext: withTestAttachedWorkspace(params.codeExecutionContext), }, })); return createToolExecuteHandler({ @@ -5174,7 +5204,7 @@ describe('createToolExecuteHandler', () => { expect(readWorkspaceFile).toHaveBeenCalledWith({ file_path: 'src/app.ts', - workspace_id: 'primary', + workspace_id: 'project-a', start_line: 1, max_lines: 200, codeApiBaseUrl: 'https://code.example.com/v1', @@ -5480,7 +5510,7 @@ describe('createToolExecuteHandler', () => { expect(searchWorkspace).toHaveBeenCalledWith({ query: 'needle', - workspace_id: 'primary', + workspace_id: 'project-a', path: 'src', max_results: 20, codeApiBaseUrl: 'https://code.example.com/v1', @@ -5632,7 +5662,7 @@ describe('createToolExecuteHandler', () => { }); expect(listWorkspaceFiles).toHaveBeenCalledWith({ - workspace_id: 'primary', + workspace_id: 'project-a', path: 'src', after_path: 'src/app.ts', max_results: 20, diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.ts index 67ac39725d..62b4dba530 100644 --- a/packages/api/src/agents/handlers.ts +++ b/packages/api/src/agents/handlers.ts @@ -17,9 +17,9 @@ import type { StreamEventData, ToolEndCallback as SdkToolEndCallback, } from '@librechat/agents'; +import type { CodeEnvRef, CodeWorkspaceOperation, PtcToolCallEvent } from 'librechat-data-provider'; import type { BackgroundToolResultClaim, ValidationIssue } from '@librechat/data-schemas'; import type { StructuredToolInterface } from '@librechat/agents/langchain/tools'; -import type { CodeEnvRef, PtcToolCallEvent } from 'librechat-data-provider'; import type { CodeEnvFile, CodeSessionContext } from '@librechat/agents'; import type { WorkspaceEditResult, @@ -708,6 +708,31 @@ function getCodeExecutionContext( return candidate as CodeExecutionContext; } +function selectedWorkspaceId( + context: CodeExecutionContext, + operation: CodeWorkspaceOperation, +): string | undefined { + const workspace = context.codeWorkspace; + if ( + workspace == null || + workspace.environmentId !== context.environmentId || + !workspace.operations.includes(operation) + ) { + return undefined; + } + return workspace.workspaceId; +} + +function unavailableWorkspaceOperation( + tc: ToolCallRequest, + operation: CodeWorkspaceOperation, +): ToolExecuteResult { + return errorResult( + tc, + `The selected attached workspace is unavailable or does not permit ${operation}. Choose an available workspace and retry.`, + ); +} + function codeExecutionRequestParams(context?: CodeExecutionContext): { codeApiBaseUrl?: string; executionProfile?: CodeExecutionContext['executionProfile']; @@ -2311,6 +2336,8 @@ async function handleWorkspaceFileRead( errorMessage: 'Attached workspace reading is not configured.', }; } + const workspaceId = selectedWorkspaceId(codeExecutionContext, 'read_file'); + if (!workspaceId) return unavailableWorkspaceOperation(tc, 'read_file'); const args = tc.args as { start_line?: number; max_lines?: number }; const startLine = args.start_line ?? 1; const maxLines = args.max_lines ?? 200; @@ -2344,7 +2371,7 @@ async function handleWorkspaceFileRead( try { const result = await readWorkspaceFile({ file_path: filePath, - workspace_id: 'primary', + workspace_id: workspaceId, start_line: startLine, max_lines: maxLines, codeApiBaseUrl: codeExecutionContext.baseUrl, @@ -2426,6 +2453,8 @@ async function handleWorkspaceSearchCall( if (!options.searchWorkspace) { return errorResult(tc, 'Attached workspace search is not configured.'); } + const workspaceId = selectedWorkspaceId(codeExecutionContext, 'search_text'); + if (!workspaceId) return unavailableWorkspaceOperation(tc, 'search_text'); const args = tc.args as { query?: unknown; path?: unknown; max_results?: unknown }; const maxResults = args.max_results ?? 50; @@ -2444,7 +2473,7 @@ async function handleWorkspaceSearchCall( try { const result = await options.searchWorkspace({ query: args.query, - workspace_id: 'primary', + workspace_id: workspaceId, ...(typeof args.path === 'string' && args.path.length > 0 ? { path: args.path } : {}), max_results: Number(maxResults), codeApiBaseUrl: codeExecutionContext.baseUrl, @@ -2508,6 +2537,8 @@ async function handleWorkspaceListCall( if (!options.listWorkspaceFiles) { return errorResult(tc, 'Attached workspace file listing is not configured.'); } + const workspaceId = selectedWorkspaceId(codeExecutionContext, 'list_files'); + if (!workspaceId) return unavailableWorkspaceOperation(tc, 'list_files'); const args = tc.args as { path?: unknown; after_path?: unknown; max_results?: unknown }; const maxResults = args.max_results ?? 100; @@ -2526,7 +2557,7 @@ async function handleWorkspaceListCall( try { const result = await options.listWorkspaceFiles({ - workspace_id: 'primary', + workspace_id: workspaceId, ...(typeof args.path === 'string' && args.path.length > 0 ? { path: args.path } : {}), ...(typeof args.after_path === 'string' && args.after_path.length > 0 ? { after_path: args.after_path } @@ -3677,6 +3708,7 @@ function attachedWorkspaceAuthoringPath( function attachedWorkspaceMutationParams( codeExecutionContext: CodeExecutionContext, + workspaceId: string, req: ServerRequest | undefined, signal: AbortSignal | undefined, ): { @@ -3688,7 +3720,7 @@ function attachedWorkspaceMutationParams( signal?: AbortSignal; } { return { - workspace_id: 'primary', + workspace_id: workspaceId, codeApiBaseUrl: codeExecutionContext.baseUrl, executionProfile: codeExecutionContext.executionProfile, ...(codeExecutionContext.bridgeWorkerId @@ -3728,13 +3760,15 @@ async function handleAttachedWorkspaceCreateFileCall({ } const filtered = filteredFileResult(tc, req, path.filePath, content); if (filtered != null) return filtered; + const workspaceId = selectedWorkspaceId(codeExecutionContext, 'write_file'); + if (!workspaceId) return unavailableWorkspaceOperation(tc, 'write_file'); try { const result = await options.writeWorkspaceFile({ file_path: path.filePath, content, overwrite, - ...attachedWorkspaceMutationParams(codeExecutionContext, req, signal), + ...attachedWorkspaceMutationParams(codeExecutionContext, workspaceId, req, signal), }); const action = result.created ? 'Created' : 'Updated'; return successResult(tc, `${action} workspace/${path.filePath} (${content.length} chars).`, { @@ -3796,6 +3830,8 @@ async function handleAttachedWorkspaceEditFileCall({ } const filteredName = filteredFileNameResult(tc, req, path.filePath); if (filteredName != null) return filteredName; + const workspaceId = selectedWorkspaceId(codeExecutionContext, 'edit_file'); + if (!workspaceId) return unavailableWorkspaceOperation(tc, 'edit_file'); try { const workspaceEdits = edits.map((edit) => ({ @@ -3810,12 +3846,15 @@ async function handleAttachedWorkspaceEditFileCall({ 'Attached workspace editing requires an updated BYOM worker while file-content protections are enabled.', ); } + if (!selectedWorkspaceId(codeExecutionContext, 'preview_edit')) { + return unavailableWorkspaceOperation(tc, 'preview_edit'); + } let preview: WorkspacePreviewEditResult; try { preview = await options.previewWorkspaceEdit({ file_path: path.filePath, edits: workspaceEdits, - ...attachedWorkspaceMutationParams(codeExecutionContext, req, signal), + ...attachedWorkspaceMutationParams(codeExecutionContext, workspaceId, req, signal), }); } catch (error) { if (signal?.aborted === true && isAbortError(error)) throw error; @@ -3833,7 +3872,7 @@ async function handleAttachedWorkspaceEditFileCall({ file_path: path.filePath, edits: workspaceEdits, ...(expectedBaseSha256 ? { expected_base_sha256: expectedBaseSha256 } : {}), - ...attachedWorkspaceMutationParams(codeExecutionContext, req, signal), + ...attachedWorkspaceMutationParams(codeExecutionContext, workspaceId, req, signal), }); return successResult( tc, diff --git a/packages/api/src/agents/hitl/policy.spec.ts b/packages/api/src/agents/hitl/policy.spec.ts index 50ee848763..e971a83032 100644 --- a/packages/api/src/agents/hitl/policy.spec.ts +++ b/packages/api/src/agents/hitl/policy.spec.ts @@ -662,6 +662,23 @@ describe('computeAgentRequestFingerprint', () => { expect(computeAgentRequestFingerprint(base)).not.toBe( computeAgentRequestFingerprint({ ...base, codeApprovalMode: null }), ); + expect(computeAgentRequestFingerprint(base)).not.toBe( + computeAgentRequestFingerprint({ + ...base, + codeWorkspaces: [{ environmentId: 'env-a', workspaceId: 'project-a' }], + }), + ); + expect( + computeAgentRequestFingerprint({ + ...base, + codeWorkspaces: [{ environmentId: 'env-a', workspaceId: 'project-a' }], + }), + ).not.toBe( + computeAgentRequestFingerprint({ + ...base, + codeWorkspaces: [{ environmentId: 'env-a', workspaceId: 'project-b' }], + }), + ); }); it('differs when promptPrefix changes (ephemeral instructions)', () => { @@ -716,6 +733,7 @@ describe('pickResumeContext / applyResumeContext', () => { // Graph-determining: feeds the ephemeral agent id / checkpoint namespace (#14253). modelLabel: 'My Opus', codeApprovalMode: 'acceptEdits', + codeWorkspaces: [{ environmentId: 'env-a', workspaceId: 'project-a' }], conversationId: 'c', decisions: [], actionId: 'x', @@ -731,6 +749,7 @@ describe('pickResumeContext / applyResumeContext', () => { manualSkills: ['code-reviewer'], modelLabel: 'My Opus', codeApprovalMode: 'acceptEdits', + codeWorkspaces: [{ environmentId: 'env-a', workspaceId: 'project-a' }], }); }); @@ -750,6 +769,25 @@ describe('pickResumeContext / applyResumeContext', () => { expect('codeApprovalMode' in injected).toBe(false); }); + it('pins the attached workspace across resume and removes a forged selection', () => { + const restored: Record = { + conversationId: 'c', + codeWorkspaces: [{ environmentId: 'env-a', workspaceId: 'project-b' }], + }; + applyResumeContext(restored, { + endpoint: 'agents', + codeWorkspaces: [{ environmentId: 'env-a', workspaceId: 'project-a' }], + }); + expect(restored.codeWorkspaces).toEqual([{ environmentId: 'env-a', workspaceId: 'project-a' }]); + + const injected: Record = { + conversationId: 'c', + codeWorkspaces: [{ environmentId: 'env-a', workspaceId: 'project-b' }], + }; + applyResumeContext(injected, { endpoint: 'agents' }); + expect('codeWorkspaces' in injected).toBe(false); + }); + it('replays a dropped modelLabel so the ephemeral agent id stays stable (#14253)', () => { // Resume/reload case: the resolved llmConfig stripped modelLabel; the server restores // the original top-level value so parseCompactConvo re-derives the same sender/id. diff --git a/packages/api/src/agents/hitl/policy.ts b/packages/api/src/agents/hitl/policy.ts index 1647a6a7d3..b0b4c2ceac 100644 --- a/packages/api/src/agents/hitl/policy.ts +++ b/packages/api/src/agents/hitl/policy.ts @@ -361,6 +361,7 @@ export interface AgentRequestFingerprintFields { promptPrefix?: string | null; ephemeralAgent?: Record | null; codeApprovalMode?: string | null; + codeWorkspaces?: unknown; } /** Stable, order-independent serialization of the ephemeral capability config. */ @@ -399,6 +400,10 @@ export const RESUME_CONTEXT_KEYS = [ 'promptPrefix', 'ephemeralAgent', 'codeApprovalMode', + // The selected attached workspace determines the code tools' execution root and + // operation ceiling. Pin it across every pause type so a reload or crafted resume + // cannot rebuild the graph against a different directory. + 'codeWorkspaces', // The agents build reads addedConvo into endpointOption to add parallel/secondary // agents; the resume POST can't reconstruct it, so replay it from the paused request. 'addedConvo', @@ -736,6 +741,9 @@ export function computeAgentRequestFingerprint(fields: AgentRequestFingerprintFi ...(Object.prototype.hasOwnProperty.call(fields, 'codeApprovalMode') ? { codeApprovalMode: fields.codeApprovalMode ?? null } : {}), + ...(Object.prototype.hasOwnProperty.call(fields, 'codeWorkspaces') + ? { codeWorkspaces: fields.codeWorkspaces ?? null } + : {}), }); return createHash('sha256').update(canonical).digest('hex'); } diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.ts index 582d723848..5254a6b88f 100644 --- a/packages/api/src/agents/initialize.ts +++ b/packages/api/src/agents/initialize.ts @@ -109,6 +109,7 @@ import { applyIntentLabels, sanitizeIntentLabels } from './intent'; import { ContentFilterError } from '../middleware/contentFilter'; import { createRequestAgentExecutionContext } from './runtime'; import { filterFilesByEndpointRuntimeConfig } from '~/files'; +import { hasActiveFileFieldPolicy } from '~/protection'; import { PARTIAL_RESOLVED_CONVERSATION } from './guard'; import { applyBackgroundToolCalls } from './background'; import { generateArtifactsPrompt } from '~/prompts'; @@ -689,6 +690,8 @@ export interface InitializeAgentParams { * artifacts don't reach the sandbox. */ primedCodeFiles?: import('@librechat/agents').CodeEnvFile[]; + /** Live workspace binding resolved by the execution-side loader. */ + codeExecutionContext?: CodeExecutionContext; } | null>; /** Endpoint option (contains model_parameters and endpoint info) */ endpointOption?: Partial; @@ -1645,6 +1648,7 @@ export async function initializeAgent( oauthActionToolNames, tools: structuredTools, primedCodeFiles, + codeExecutionContext: loadedCodeExecutionContext, } = loadToolsResult ?? { tools: [], toolContextMap: {}, @@ -1659,7 +1663,20 @@ export async function initializeAgent( actionsEnabled: undefined, oauthActionToolNames: undefined, primedCodeFiles: undefined, + codeExecutionContext: undefined, }; + const trustedCodeExecutionContext = loadedCodeExecutionContext ?? codeExecutionContext; + const attachedWorkspaceOperations = + trustedCodeExecutionContext.environmentType === 'attached' + ? new Set(trustedCodeExecutionContext.codeWorkspace?.operations ?? []) + : undefined; + if ( + attachedWorkspaceOperations && + !attachedWorkspaceOperations.has('preview_edit') && + hasActiveFileFieldPolicy(appConfig?.filters, ['content', 'extracted_text']) + ) { + attachedWorkspaceOperations.delete('edit_file'); + } let toolDefinitions = loadedToolDefinitions; @@ -1787,6 +1804,7 @@ export async function initializeAgent( enableToolOutputReferences: effectiveCodeEnvAvailable, statefulSessions: effectiveStatefulSessions, workspaceTools: attachedWorkspaceTools, + workspaceOperations: attachedWorkspaceOperations, }); toolDefinitions = codeExecResult.toolDefinitions; recordCapabilityToolNames(AgentCapabilities.execute_code, codeExecResult.toolNames); @@ -1836,6 +1854,7 @@ export async function initializeAgent( includeSkillFileInstructions: true, enableToolOutputReferences: effectiveCodeEnvAvailable, workspaceTools: attachedWorkspaceTools, + workspaceOperations: attachedWorkspaceOperations, }); toolDefinitions = skillReadResult.toolDefinitions; recordCapabilityToolNames(AgentCapabilities.skills, skillReadResult.toolNames); @@ -1847,6 +1866,7 @@ export async function initializeAgent( toolDefinitions, includeSkillFileInstructions: skillAuthoringAvailable, workspaceTools: attachedWorkspaceTools, + workspaceOperations: attachedWorkspaceOperations, }); toolDefinitions = fileAuthoringResult.toolDefinitions; /** File authoring is owned by whichever capability switched it on — @@ -1998,6 +2018,7 @@ export async function initializeAgent( codeEnvAvailable: effectiveCodeEnvAvailable, statefulSessions: effectiveStatefulSessions, workspaceTools: attachedWorkspaceTools, + workspaceOperations: attachedWorkspaceOperations, userId: user?.id, skillStates: params.skillStates, defaultActiveOnShare: params.defaultActiveOnShare, @@ -2122,8 +2143,8 @@ export async function initializeAgent( codeEnvAvailable: effectiveCodeEnvAvailable, statefulCodeSessions: effectiveStatefulSessions, statefulCodeEnvironment, - codeSessionKey: codeExecutionContext.codeSessionKey, - codeExecutionContext, + codeSessionKey: trustedCodeExecutionContext.codeSessionKey, + codeExecutionContext: trustedCodeExecutionContext, reasoningKey: customEndpointConfig?.customParams?.reasoningKey, includeReasoningHistory: customEndpointConfig?.customParams?.includeReasoningHistory, skillAuthoringAvailable, diff --git a/packages/api/src/agents/openai/service.ts b/packages/api/src/agents/openai/service.ts index c03023c4c5..508967e5b6 100644 --- a/packages/api/src/agents/openai/service.ts +++ b/packages/api/src/agents/openai/service.ts @@ -19,6 +19,7 @@ * ``` */ import { nanoid } from 'nanoid'; +import { isCodeWorkspaceSelections } from 'librechat-data-provider'; import { AgentCapabilities, EModelEndpoint } from 'librechat-data-provider'; import type { FiltersConfig, @@ -535,6 +536,15 @@ export function validateRequest(body: unknown): ChatCompletionValidationResult { if (request.conversation_id !== undefined && typeof request.conversation_id !== 'string') { return { valid: false, error: 'conversation_id must be a string' }; } + if ( + request.code_workspaces !== undefined && + !isCodeWorkspaceSelections(request.code_workspaces) + ) { + return { + valid: false, + error: 'code_workspaces must contain unique environment/workspace selections', + }; + } if (request.parent_message_id !== undefined && typeof request.parent_message_id !== 'string') { return { valid: false, error: 'parent_message_id must be a string' }; @@ -643,6 +653,7 @@ export async function createAgentChatCompletion( const mcpRequestBody = createMCPRuntimeRequestBody({ messageId: requestId, conversationId, + codeWorkspaces: request.code_workspaces, parentMessageId: mcpParentMessageId, }); const created = Math.floor(Date.now() / 1000); diff --git a/packages/api/src/agents/openai/types.ts b/packages/api/src/agents/openai/types.ts index 623f7de9c0..c1b36b9287 100644 --- a/packages/api/src/agents/openai/types.ts +++ b/packages/api/src/agents/openai/types.ts @@ -73,6 +73,8 @@ export interface ChatCompletionRequest { user?: string; /** Conversation ID (LibreChat extension) */ conversation_id?: string; + /** Explicit registered workspaces for attached agents (LibreChat extension). */ + code_workspaces?: import('librechat-data-provider').CodeWorkspaceSelection[]; /** Parent message ID (LibreChat extension) */ parent_message_id?: string; } diff --git a/packages/api/src/agents/responses/service.ts b/packages/api/src/agents/responses/service.ts index 508083b809..0b538b6f4f 100644 --- a/packages/api/src/agents/responses/service.ts +++ b/packages/api/src/agents/responses/service.ts @@ -4,6 +4,7 @@ * Core service for processing Open Responses API requests. * Handles input conversion, message formatting, and request validation. */ +import { isCodeWorkspaceSelections } from 'librechat-data-provider'; import type { Response as ServerResponse } from 'express'; import type { RequestValidationResult, @@ -80,6 +81,15 @@ export function validateResponseRequest(body: unknown): RequestValidationResult } const request = body as Record; + if ( + request.code_workspaces !== undefined && + !isCodeWorkspaceSelections(request.code_workspaces) + ) { + return { + valid: false, + error: 'code_workspaces must contain unique environment/workspace selections', + }; + } // Required: model if (!request.model || typeof request.model !== 'string') { diff --git a/packages/api/src/agents/responses/types.ts b/packages/api/src/agents/responses/types.ts index 02e8100166..d5bf1dbcb7 100644 --- a/packages/api/src/agents/responses/types.ts +++ b/packages/api/src/agents/responses/types.ts @@ -326,6 +326,8 @@ export type Metadata = Record; /** Open Responses API Request */ export interface ResponseRequest { + /** Explicit registered workspaces for attached agents (LibreChat extension). */ + code_workspaces?: import('librechat-data-provider').CodeWorkspaceSelection[]; /** Model/agent ID to use */ model: string; diff --git a/packages/api/src/agents/skills.ts b/packages/api/src/agents/skills.ts index a495d39c9f..970d836e01 100644 --- a/packages/api/src/agents/skills.ts +++ b/packages/api/src/agents/skills.ts @@ -3,8 +3,8 @@ import { HumanMessage } from '@librechat/agents/langchain/messages'; import { SkillsScope, isEphemeralAgentId, resolveAgentSkillsScope } from 'librechat-data-provider'; import { formatSkillCatalog, SkillToolDefinition, ReadFileToolDefinition } from '@librechat/agents'; import type { LCToolRegistry, LCTool, InjectedMessage } from '@librechat/agents'; +import type { Agent, CodeWorkspaceOperation } from 'librechat-data-provider'; import type { BaseMessage } from '@librechat/agents/langchain/messages'; -import type { Agent } from 'librechat-data-provider'; import type { Types } from 'mongoose'; import { createSkillContentDigest } from './compatibility'; import { registerCodeExecutionTools } from './tools'; @@ -432,6 +432,8 @@ export interface InjectSkillCatalogParams { statefulSessions?: boolean; /** When true, read_file exposes the attached worker's workspace namespace. */ workspaceTools?: boolean; + /** Live operation ceiling for the selected attached workspace. */ + workspaceOperations?: ReadonlySet; /** Current user ID — used to determine skill ownership for active-state resolution. */ userId?: string; /** Per-user skill overrides: `{ [skillId]: boolean }`. Missing entries use the default. */ @@ -659,6 +661,7 @@ export async function injectSkillCatalog( codeEnvAvailable, statefulSessions, workspaceTools, + workspaceOperations, userId, skillStates, defaultActiveOnShare = false, @@ -817,6 +820,7 @@ export async function injectSkillCatalog( enableToolOutputReferences: codeEnvAvailable === true, statefulSessions: statefulSessions === true, workspaceTools: workspaceTools === true, + workspaceOperations, }); workingDefs = codeExecResult.toolDefinitions; diff --git a/packages/api/src/agents/tools.spec.ts b/packages/api/src/agents/tools.spec.ts index 4ba738e040..8afd0a524a 100644 --- a/packages/api/src/agents/tools.spec.ts +++ b/packages/api/src/agents/tools.spec.ts @@ -49,7 +49,7 @@ jest.mock('@librechat/agents', () => ({ import { CODE_EXECUTION_TOOLS } from '@librechat/agents'; import type { LCTool, LCToolRegistry } from '@librechat/agents'; -import { Constants } from 'librechat-data-provider'; +import { CODE_WORKSPACE_OPERATIONS, Constants } from 'librechat-data-provider'; import { buildToolSet, buildRunToolSet, @@ -492,6 +492,7 @@ describe('registerCodeExecutionTools', () => { includeBash: true, includeSkillFileInstructions: false, workspaceTools: true, + workspaceOperations: new Set(CODE_WORKSPACE_OPERATIONS), }); const readFile = result.toolDefinitions.find((definition) => definition.name === 'read_file'); @@ -518,6 +519,7 @@ describe('registerCodeExecutionTools', () => { properties: { command: { type: 'string' }, args: { type: 'array' }, + cwd: { type: 'string', maxLength: 4096 }, }, required: ['command'], }); @@ -548,6 +550,34 @@ describe('registerCodeExecutionTools', () => { expect(filePathDescription(listWorkspaceFiles)).toContain('canonical relative'); }); + it('registers only operations advertised by the selected workspace', () => { + const result = registerCodeExecutionTools({ + toolRegistry: makeRegistry(), + toolDefinitions: [], + includeBash: true, + includeSkillFileInstructions: false, + workspaceTools: true, + workspaceOperations: new Set(['read_file', 'list_files']), + }); + + expect(result.toolDefinitions.map(({ name }) => name).sort()).toEqual([ + 'list_workspace_files', + 'read_file', + ]); + }); + + it('fails closed when attached workspace operations were not validated', () => { + const result = registerCodeExecutionTools({ + toolRegistry: makeRegistry(), + toolDefinitions: [], + includeBash: true, + includeSkillFileInstructions: false, + workspaceTools: true, + }); + + expect(result.toolDefinitions).toEqual([]); + }); + it('upgrades a code-only read_file definition when skills are enabled later in the run', () => { const toolRegistry = makeRegistry(); const codeOnly = registerCodeExecutionTools({ @@ -579,6 +609,7 @@ describe('registerCodeExecutionTools', () => { includeBash: true, includeSkillFileInstructions: false, workspaceTools: true, + workspaceOperations: new Set(CODE_WORKSPACE_OPERATIONS), }); const upgraded = registerCodeExecutionTools({ toolRegistry, @@ -586,6 +617,7 @@ describe('registerCodeExecutionTools', () => { includeBash: false, includeSkillFileInstructions: true, workspaceTools: true, + workspaceOperations: new Set(CODE_WORKSPACE_OPERATIONS), }); const readFile = upgraded.toolDefinitions.find( @@ -877,6 +909,7 @@ describe('registerFileAuthoringTools', () => { toolDefinitions: [], includeSkillFileInstructions: false, workspaceTools: true, + workspaceOperations: new Set(CODE_WORKSPACE_OPERATIONS), }); const createFile = result.toolDefinitions.find((d) => d.name === 'create_file'); const editFile = result.toolDefinitions.find((d) => d.name === 'edit_file'); @@ -890,6 +923,29 @@ describe('registerFileAuthoringTools', () => { expect(isFileAuthoringToolDefinition(editFile)).toBe(true); }); + it('registers only authoring operations advertised by the selected workspace', () => { + const result = registerFileAuthoringTools({ + toolRegistry: makeRegistry(), + toolDefinitions: [], + includeSkillFileInstructions: false, + workspaceTools: true, + workspaceOperations: new Set(['edit_file']), + }); + + expect(result.toolDefinitions.map(({ name }) => name)).toEqual(['edit_file']); + }); + + it('fails closed when attached authoring operations were not validated', () => { + const result = registerFileAuthoringTools({ + toolRegistry: makeRegistry(), + toolDefinitions: [], + includeSkillFileInstructions: false, + workspaceTools: true, + }); + + expect(result.toolDefinitions).toEqual([]); + }); + it('is idempotent across repeated registration calls', () => { const toolRegistry = makeRegistry(); const first = registerFileAuthoringTools({ @@ -946,6 +1002,7 @@ describe('registerFileAuthoringTools', () => { toolDefinitions: [], includeSkillFileInstructions: true, workspaceTools: true, + workspaceOperations: new Set(CODE_WORKSPACE_OPERATIONS), }); expect( diff --git a/packages/api/src/agents/tools.ts b/packages/api/src/agents/tools.ts index e02879e83c..ce8af5002f 100644 --- a/packages/api/src/agents/tools.ts +++ b/packages/api/src/agents/tools.ts @@ -11,7 +11,7 @@ import { ReadFileToolDefinition, buildBashExecutionToolDescription, } from '@librechat/agents'; -import type { AgentToolOptions, GraphEdge } from 'librechat-data-provider'; +import type { AgentToolOptions, CodeWorkspaceOperation, GraphEdge } from 'librechat-data-provider'; import type { LCTool, LCToolRegistry } from '@librechat/agents'; import type { ReachableAgent } from './traversal'; import { @@ -377,6 +377,8 @@ export interface RegisterCodeExecutionToolsParams { * backed by the selected attached worker, including bounded line pagination. */ workspaceTools?: boolean; + /** Live operation ceiling for the selected workspace. Omitted for managed runtimes. */ + workspaceOperations?: ReadonlySet; /** * When `true`, the registered `bash_tool` description includes the * LLM-facing `{{toolturn}}` reference syntax guide so the @@ -420,6 +422,8 @@ export interface RegisterFileAuthoringToolsParams { includeSkillFileInstructions?: boolean; /** When true, non-skill paths use the attached worker's workspace/ namespace. */ workspaceTools?: boolean; + /** Live operation ceiling for the selected workspace. Omitted for managed runtimes. */ + workspaceOperations?: ReadonlySet; } /** @@ -946,20 +950,30 @@ export function registerCodeExecutionTools( includeBash, includeSkillFileInstructions = true, workspaceTools = false, + workspaceOperations, enableToolOutputReferences = false, statefulSessions = false, } = params; - const readFileDef = buildReadFileDef(includeSkillFileInstructions, workspaceTools); - const codeTools: LCTool[] = includeBash - ? [ - readFileDef, - buildBashToolDef({ enableToolOutputReferences, statefulSessions, workspaceTools }), - ] - : [readFileDef]; - const candidates = workspaceTools - ? [...codeTools, SEARCH_WORKSPACE_TOOL_DEF, LIST_WORKSPACE_FILES_TOOL_DEF] - : codeTools; + const supportsWorkspaceOperation = (operation: CodeWorkspaceOperation): boolean => + !workspaceTools || workspaceOperations?.has(operation) === true; + const candidates: LCTool[] = []; + if (!workspaceTools || supportsWorkspaceOperation('read_file')) { + candidates.push(buildReadFileDef(includeSkillFileInstructions, workspaceTools)); + } else if (includeSkillFileInstructions) { + candidates.push(buildReadFileDef(true, false)); + } + if (includeBash && supportsWorkspaceOperation('execute_command')) { + candidates.push( + buildBashToolDef({ enableToolOutputReferences, statefulSessions, workspaceTools }), + ); + } + if (workspaceTools && supportsWorkspaceOperation('search_text')) { + candidates.push(SEARCH_WORKSPACE_TOOL_DEF); + } + if (workspaceTools && supportsWorkspaceOperation('list_files')) { + candidates.push(LIST_WORKSPACE_FILES_TOOL_DEF); + } const toolNames = candidates.map((def) => def.name); const inputDefinitions = toolDefinitions ?? []; @@ -1020,9 +1034,28 @@ export function registerFileAuthoringTools( toolDefinitions, includeSkillFileInstructions = true, workspaceTools = false, + workspaceOperations, } = params; - const candidates = buildFileAuthoringDefs(includeSkillFileInstructions, workspaceTools); + const supportsWorkspaceOperation = (operation: CodeWorkspaceOperation): boolean => + !workspaceTools || workspaceOperations?.has(operation) === true; + let candidates = buildFileAuthoringDefs(includeSkillFileInstructions, false); + if (workspaceTools) { + candidates = []; + if (includeSkillFileInstructions) { + candidates.push( + supportsWorkspaceOperation('write_file') + ? ATTACHED_SKILL_CREATE_FILE_DEF + : SKILL_CREATE_FILE_DEF, + supportsWorkspaceOperation('edit_file') + ? ATTACHED_SKILL_EDIT_FILE_DEF + : SKILL_EDIT_FILE_DEF, + ); + } else { + if (supportsWorkspaceOperation('write_file')) candidates.push(ATTACHED_CODE_CREATE_FILE_DEF); + if (supportsWorkspaceOperation('edit_file')) candidates.push(ATTACHED_CODE_EDIT_FILE_DEF); + } + } const toolNames = candidates.map((def) => def.name); const inputDefinitions = toolDefinitions ?? []; let workingDefinitions = inputDefinitions; diff --git a/packages/api/src/code/bridge.spec.ts b/packages/api/src/code/bridge.spec.ts index 0db156062d..1e7e78c9ff 100644 --- a/packages/api/src/code/bridge.spec.ts +++ b/packages/api/src/code/bridge.spec.ts @@ -18,7 +18,14 @@ describe('getCodeBridgeWorkerStatus', () => { statefulWorkspace: true, sandboxProfile: 'native-srt', runtimes: ['bash'], - workspaceTools: { operations: ['read_file', 'execute_command'] }, + workspaceTools: { + protocolVersion: 1, + operations: ['read_file', 'execute_command'], + workspaces: [ + { id: 'project-a', name: 'Project A' }, + { id: 'docs', operations: ['read_file'] }, + ], + }, identityId: 'must-not-cross-the-boundary', }, binding: { tenantId: 'tenant-1', principal: { type: 'user', id: 'user-1' } }, @@ -40,6 +47,10 @@ describe('getCodeBridgeWorkerStatus', () => { sandboxProfile: 'native-srt', runtimes: ['bash'], operations: ['read_file', 'execute_command'], + workspaces: [ + { id: 'project-a', name: 'Project A' }, + { id: 'docs', operations: ['read_file'] }, + ], }); expect(fetchImpl).toHaveBeenCalledWith( 'https://code.example.com/v1/bridge/workers/personal-vm/status', @@ -50,6 +61,42 @@ describe('getCodeBridgeWorkerStatus', () => { ); }); + test('keeps legacy worker status readable without inventing a primary workspace', async () => { + const fetchImpl = jest.fn().mockResolvedValue( + new Response( + JSON.stringify({ + protocolVersion: 1, + workerId: 'personal-vm', + online: true, + ready: true, + leaseExpiresInMs: 45_000, + capabilities: { + statefulWorkspace: true, + sandboxProfile: 'native-srt', + runtimes: ['bash'], + workspaceTools: { operations: ['read_file', 'execute_command'] }, + }, + }), + ), + ); + + await expect( + getCodeBridgeWorkerStatus({ + baseURL: 'https://code.example.com/v1', + token: 'administrator-token', + workerId: 'personal-vm', + fetchImpl, + }), + ).resolves.toEqual({ + status: 'ready', + statefulWorkspace: true, + leaseExpiresInMs: 45_000, + sandboxProfile: 'native-srt', + runtimes: ['bash'], + operations: ['read_file', 'execute_command'], + }); + }); + test.each([ { online: false, ready: true }, { online: true, ready: false }, @@ -60,6 +107,51 @@ describe('getCodeBridgeWorkerStatus', () => { ready: true, capabilities: { sandboxProfile: 'native-srt', runtimes: Array(33).fill('bash') }, }, + { + online: true, + ready: true, + leaseExpiresInMs: 5_000, + capabilities: { + statefulWorkspace: true, + sandboxProfile: 'native-srt', + runtimes: ['bash'], + workspaceTools: { + protocolVersion: 1, + operations: ['read_file'], + workspaces: [{ id: '../escape' }], + }, + }, + }, + { + online: true, + ready: true, + leaseExpiresInMs: 5_000, + capabilities: { + statefulWorkspace: true, + sandboxProfile: 'native-srt', + runtimes: ['bash'], + workspaceTools: { + protocolVersion: 1, + operations: ['read_file'], + workspaces: [{ id: 'project-a', operations: ['execute_command'] }], + }, + }, + }, + { + online: true, + ready: true, + leaseExpiresInMs: 5_000, + capabilities: { + statefulWorkspace: true, + sandboxProfile: 'native-srt', + runtimes: ['bash'], + workspaceTools: { + protocolVersion: 1, + operations: ['read_file'], + workspaces: [{ id: 'project-a', operations: null }], + }, + }, + }, ])('rejects an invalid upstream status response: %p', async (invalid) => { const fetchImpl = jest .fn() diff --git a/packages/api/src/code/bridge.ts b/packages/api/src/code/bridge.ts index 7d4aea1022..0ad24ad4cb 100644 --- a/packages/api/src/code/bridge.ts +++ b/packages/api/src/code/bridge.ts @@ -1,4 +1,10 @@ import { createHash } from 'node:crypto'; +import { + CODE_WORKSPACE_ID_PATTERN, + CODE_WORKSPACE_MAX_COUNT, + CODE_WORKSPACE_OPERATIONS, +} from 'librechat-data-provider'; +import type { CodeWorkspaceDescriptor, CodeWorkspaceOperation } from 'librechat-data-provider'; const CODE_BRIDGE_REQUEST_TIMEOUT_MS = 10_000; const CODE_BRIDGE_STATUS_RESPONSE_MAX_BYTES = 64 * 1024; @@ -26,7 +32,8 @@ export type CodeBridgeWorkerStatus = { statefulWorkspace?: boolean; sandboxProfile?: string; runtimes?: string[]; - operations?: string[]; + operations?: CodeWorkspaceOperation[]; + workspaces?: CodeWorkspaceDescriptor[]; }; export type CodeBridgeFetch = ( @@ -141,6 +148,77 @@ function validStatusStringArray(value: unknown): value is string[] { ); } +function validWorkspaceOperations(value: unknown): value is CodeWorkspaceOperation[] { + return ( + Array.isArray(value) && + value.length > 0 && + value.length <= CODE_WORKSPACE_OPERATIONS.length && + value.every((operation) => + CODE_WORKSPACE_OPERATIONS.includes(operation as CodeWorkspaceOperation), + ) && + new Set(value).size === value.length + ); +} + +function validWorkspaceCapabilities(value: unknown): value is { + protocolVersion: 1; + operations: CodeWorkspaceOperation[]; + workspaces: CodeWorkspaceDescriptor[]; +} { + if (value == null || typeof value !== 'object' || Array.isArray(value)) return false; + const capabilities = value as Record; + if ( + capabilities.protocolVersion !== 1 || + !validWorkspaceOperations(capabilities.operations) || + !Array.isArray(capabilities.workspaces) || + capabilities.workspaces.length < 1 || + capabilities.workspaces.length > CODE_WORKSPACE_MAX_COUNT + ) { + return false; + } + const operations = capabilities.operations; + const ids = new Set(); + return capabilities.workspaces.every((value) => { + if (value == null || typeof value !== 'object' || Array.isArray(value)) return false; + const workspace = value as Record; + if ( + Object.keys(workspace).some( + (key) => key !== 'id' && key !== 'name' && key !== 'operations', + ) || + typeof workspace.id !== 'string' || + !CODE_WORKSPACE_ID_PATTERN.test(workspace.id) || + ids.has(workspace.id) || + (workspace.name !== undefined && + (typeof workspace.name !== 'string' || + workspace.name.trim().length === 0 || + workspace.name.length > 128)) || + (workspace.operations !== undefined && + (!validWorkspaceOperations(workspace.operations) || + workspace.operations.length > operations.length || + workspace.operations.some((operation) => !operations.includes(operation)))) + ) { + return false; + } + ids.add(workspace.id); + return true; + }); +} + +/** Keep the status endpoint readable during worker-first rolling upgrades. + * Legacy capabilities remain non-selectable and are surfaced as an explicit + * update-required state; they never regain an implicit `primary` binding. */ +function validLegacyWorkspaceCapabilities(value: unknown): value is { + operations: CodeWorkspaceOperation[]; +} { + if (value == null || typeof value !== 'object' || Array.isArray(value)) return false; + const capabilities = value as Record; + return ( + capabilities.protocolVersion === undefined && + capabilities.workspaces === undefined && + validWorkspaceOperations(capabilities.operations) + ); +} + async function readBoundedStatusJson(response: Response): Promise { const reader = response.body?.getReader(); if (reader == null) throw new CodeBridgeStatusError('invalid'); @@ -203,7 +281,7 @@ export async function getCodeBridgeWorkerStatus({ statefulWorkspace?: unknown; sandboxProfile?: unknown; runtimes?: unknown; - workspaceTools?: { operations?: unknown }; + workspaceTools?: unknown; }; }; const capabilities = status.capabilities; @@ -216,9 +294,10 @@ export async function getCodeBridgeWorkerStatus({ const validCapabilities = capabilities == null || validStatusString(capabilities.sandboxProfile); const validRuntimes = capabilities == null || validStatusStringArray(capabilities.runtimes); - const validOperations = - capabilities?.workspaceTools?.operations == null || - validStatusStringArray(capabilities.workspaceTools.operations); + const validWorkspaceTools = + capabilities?.workspaceTools == null || + validWorkspaceCapabilities(capabilities.workspaceTools) || + validLegacyWorkspaceCapabilities(capabilities.workspaceTools); if ( status.protocolVersion !== 1 || status.workerId !== workerId || @@ -230,7 +309,7 @@ export async function getCodeBridgeWorkerStatus({ !validLease || !validCapabilities || !validRuntimes || - !validOperations || + !validWorkspaceTools || (capabilities?.statefulWorkspace != null && typeof capabilities.statefulWorkspace !== 'boolean') ) { @@ -240,6 +319,18 @@ export async function getCodeBridgeWorkerStatus({ if (status.online) { workerStatus = status.ready ? 'ready' : 'starting'; } + let workspaceStatus: Pick = {}; + if (validWorkspaceCapabilities(capabilities?.workspaceTools)) { + workspaceStatus = { + operations: [...capabilities.workspaceTools.operations], + workspaces: capabilities.workspaceTools.workspaces.map((workspace) => ({ + ...workspace, + ...(workspace.operations ? { operations: [...workspace.operations] } : {}), + })), + }; + } else if (validLegacyWorkspaceCapabilities(capabilities?.workspaceTools)) { + workspaceStatus = { operations: [...capabilities.workspaceTools.operations] }; + } return { status: workerStatus, ...(typeof capabilities?.statefulWorkspace === 'boolean' @@ -254,9 +345,7 @@ export async function getCodeBridgeWorkerStatus({ ...(validStatusStringArray(capabilities?.runtimes) ? { runtimes: capabilities.runtimes } : {}), - ...(validStatusStringArray(capabilities?.workspaceTools?.operations) - ? { operations: capabilities.workspaceTools.operations } - : {}), + ...workspaceStatus, }; } catch (error) { if (error instanceof CodeBridgeStatusError) throw error; diff --git a/packages/api/src/code/capabilities.spec.ts b/packages/api/src/code/capabilities.spec.ts index ffb6ded5f9..14b6d9902d 100644 --- a/packages/api/src/code/capabilities.spec.ts +++ b/packages/api/src/code/capabilities.spec.ts @@ -1,6 +1,11 @@ +import { ErrorTypes } from 'librechat-data-provider'; import type { AppConfig } from '@librechat/data-schemas'; import type { CodeExecutionContext, CodeEnvironmentConfig } from '~/agents/execution'; -import { supportsProgrammaticCodeExecution } from './capabilities'; +import { + CodeWorkspaceSelectionError, + resolveCodeExecutionWorkspaceContext, + supportsProgrammaticCodeExecution, +} from './capabilities'; const context: CodeExecutionContext = { baseUrl: 'https://bridge.example', @@ -145,6 +150,28 @@ describe('supportsProgrammaticCodeExecution', () => { expect(fetchSpy).not.toHaveBeenCalled(); }); + it('suppresses generic programmatic Bash after an attached workspace is selected', async () => { + const fetchSpy = jest + .spyOn(globalThis, 'fetch') + .mockRejectedValue(new Error('Unexpected status request')); + + expect( + await supportsProgrammaticCodeExecution( + { + ...context, + codeWorkspace: { + environmentId: 'personal', + workspaceId: 'project-a', + operations: ['read_file', 'execute_command'], + }, + }, + environments, + getAppConfig, + ), + ).toBe(false); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + it('does not send credentials to a different execution route', async () => { process.env.TEST_CODE_CAPABILITY_TOKEN = 'route-token'; const fetchSpy = jest @@ -245,3 +272,228 @@ describe('supportsProgrammaticCodeExecution', () => { expect(fetchSpy).not.toHaveBeenCalled(); }); }); + +describe('resolveCodeExecutionWorkspaceContext', () => { + beforeEach(() => { + getAppConfig.mockClear(); + process.env.TEST_CODE_CAPABILITY_TOKEN = `workspace-${Math.random()}`; + }); + + afterEach(() => { + delete process.env.TEST_CODE_CAPABILITY_TOKEN; + }); + + function workspaceStatus(workspaces: unknown[]): Response { + return new Response( + JSON.stringify({ + protocolVersion: 1, + workerId: 'worker', + online: true, + ready: true, + leaseExpiresInMs: 45_000, + capabilities: { + statefulWorkspace: true, + sandboxProfile: 'native-srt', + runtimes: ['bash'], + workspaceTools: { + protocolVersion: 1, + operations: ['read_file', 'list_files', 'execute_command'], + workspaces, + }, + }, + }), + ); + } + + it('binds the exact advertised workspace and its operation ceiling', async () => { + jest.spyOn(globalThis, 'fetch').mockResolvedValue( + workspaceStatus([ + { id: 'project-a', name: 'Project A' }, + { id: 'docs', operations: ['read_file', 'list_files'] }, + ]), + ); + + await expect( + resolveCodeExecutionWorkspaceContext({ + context, + requestedSelections: [ + { environmentId: 'another-machine', workspaceId: 'other-project' }, + { environmentId: 'personal', workspaceId: 'docs' }, + ], + environments, + getAppConfig, + }), + ).resolves.toMatchObject({ + codeSessionKey: 'session', + codeWorkspace: { + environmentId: 'personal', + workspaceId: 'docs', + operations: ['read_file', 'list_files'], + }, + }); + }); + + it.each(['worker', 'replacement', undefined])( + 'pins deployment worker identity: %s', + async (workerId) => { + const fetch = jest + .spyOn(globalThis, 'fetch') + .mockResolvedValue(workspaceStatus([{ id: 'project-a' }])); + const deploymentEnvironment: CodeEnvironmentConfig = { + id: 'fixed', + name: 'Fixed VM', + type: 'attached', + owner: 'deployment', + baseURL: context.baseUrl, + pairing: { workerId, tokenEnv: 'TEST_CODE_CAPABILITY_TOKEN', allowPrincipalWorkers: false }, + }; + const pending = resolveCodeExecutionWorkspaceContext({ + context: { ...context, environmentId: 'fixed' }, + requestedSelections: [{ environmentId: 'fixed', workspaceId: 'project-a' }], + environments: [ + { + ...deploymentEnvironment, + pairing: { + workerId: 'worker', + tokenEnv: 'TEST_CODE_CAPABILITY_TOKEN', + allowPrincipalWorkers: false, + }, + }, + ], + getAppConfig: jest.fn( + async () => + ({ + endpoints: { + agents: { statefulCodeSessions: { environments: [deploymentEnvironment] } }, + }, + }) as AppConfig, + ), + }); + if (workerId === 'worker') { + await expect(pending).resolves.toMatchObject({ + codeWorkspace: { workspaceId: 'project-a' }, + }); + } else { + await expect(pending).rejects.toMatchObject({ reason: 'worker_unavailable' }); + expect(fetch).not.toHaveBeenCalled(); + } + }, + ); + + it('uses the persisted binding when the request omits one', async () => { + jest.spyOn(globalThis, 'fetch').mockResolvedValue(workspaceStatus([{ id: 'project-a' }])); + + await expect( + resolveCodeExecutionWorkspaceContext({ + context, + persistedSelections: [{ environmentId: 'personal', workspaceId: 'project-a' }], + environments, + getAppConfig, + }), + ).resolves.toMatchObject({ + codeWorkspace: { environmentId: 'personal', workspaceId: 'project-a' }, + }); + }); + + it('fails when the saved workspace disappears instead of selecting another', async () => { + jest.spyOn(globalThis, 'fetch').mockResolvedValue(workspaceStatus([{ id: 'replacement' }])); + + await expect( + resolveCodeExecutionWorkspaceContext({ + context, + requestedSelections: [{ environmentId: 'personal', workspaceId: 'project-a' }], + environments, + getAppConfig, + }), + ).rejects.toEqual( + expect.objectContaining>({ + reason: 'missing', + code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, + status: 409, + statusCode: 409, + }), + ); + }); + + it('requires a binding for the executing environment before contacting Code API', async () => { + const fetchSpy = jest + .spyOn(globalThis, 'fetch') + .mockRejectedValue(new Error('Unexpected status request')); + + await expect( + resolveCodeExecutionWorkspaceContext({ + context, + requestedSelections: [{ environmentId: 'another-machine', workspaceId: 'project-a' }], + environments, + getAppConfig, + }), + ).rejects.toEqual( + expect.objectContaining>({ + reason: 'required', + }), + ); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('rejects malformed selections before contacting Code API', async () => { + const fetchSpy = jest + .spyOn(globalThis, 'fetch') + .mockRejectedValue(new Error('Unexpected status request')); + + await expect( + resolveCodeExecutionWorkspaceContext({ + context, + requestedSelections: [ + { + environmentId: 'personal', + workspaceId: 'project-a', + operations: ['execute_command'], + }, + ], + environments, + getAppConfig, + }), + ).rejects.toEqual( + expect.objectContaining>({ reason: 'invalid' }), + ); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('rejects duplicate environment bindings before contacting Code API', async () => { + const fetchSpy = jest + .spyOn(globalThis, 'fetch') + .mockRejectedValue(new Error('Unexpected status request')); + + await expect( + resolveCodeExecutionWorkspaceContext({ + context, + requestedSelections: [ + { environmentId: 'personal', workspaceId: 'project-a' }, + { environmentId: 'personal', workspaceId: 'project-b' }, + ], + environments, + getAppConfig, + }), + ).rejects.toEqual( + expect.objectContaining>({ reason: 'invalid' }), + ); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('returns an explicit unavailable error when deployment configuration cannot be loaded', async () => { + await expect( + resolveCodeExecutionWorkspaceContext({ + context, + requestedSelections: [{ environmentId: 'personal', workspaceId: 'project-a' }], + environments, + getAppConfig: async () => { + throw new Error('configuration unavailable'); + }, + }), + ).rejects.toEqual( + expect.objectContaining>({ + reason: 'worker_unavailable', + }), + ); + }); +}); diff --git a/packages/api/src/code/capabilities.ts b/packages/api/src/code/capabilities.ts index 8221140bff..34722ed40d 100644 --- a/packages/api/src/code/capabilities.ts +++ b/packages/api/src/code/capabilities.ts @@ -1,20 +1,60 @@ import { logger } from '@librechat/data-schemas'; +import { ErrorTypes, isCodeWorkspaceSelections } from 'librechat-data-provider'; +import type { CodeWorkspaceSelection } from 'librechat-data-provider'; import type { CodeEnvironmentConfig, CodeExecutionContext } from '~/agents/execution'; import type { createAppConfigService } from '~/app/service'; -import { createCodeBridgeStatusPoller, readCodeBridgeSecret } from './bridge'; +import type { CodeBridgeWorkerStatus } from './bridge'; +import { + CodeBridgeStatusError, + createCodeBridgeStatusPoller, + readCodeBridgeSecret, +} from './bridge'; export type CodeCapabilityConfigLoader = ReturnType['getAppConfig']; const pollWorkerStatus = createCodeBridgeStatusPoller(); -/** Attached workers must confirm both a stateful workspace and the Bash runtime. */ -export async function supportsProgrammaticCodeExecution( - context?: CodeExecutionContext, - environments?: readonly CodeEnvironmentConfig[], - getAppConfig?: CodeCapabilityConfigLoader, -): Promise { - if (context?.environmentType !== 'attached') return true; - if (!context.bridgeWorkerId) return false; +export type CodeWorkspaceSelectionErrorReason = + | 'required' + | 'invalid' + | 'worker_unavailable' + | 'unsupported' + | 'missing'; + +function codeWorkspaceSelectionErrorMessage(reason: CodeWorkspaceSelectionErrorReason): string { + switch (reason) { + case 'required': + return 'Choose an attached workspace before using this agent.'; + case 'invalid': + return 'The selected attached workspace is invalid.'; + case 'worker_unavailable': + return 'The attached code environment is unavailable. Reconnect the machine and try again.'; + case 'unsupported': + return 'The attached code environment does not advertise selectable workspaces. Update the LibreChat Code worker and try again.'; + case 'missing': + return 'The selected workspace is no longer registered on this machine. Choose another workspace explicitly or restore the previous registration.'; + } +} + +export class CodeWorkspaceSelectionError extends Error { + readonly code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE = ErrorTypes.CODE_WORKSPACE_UNAVAILABLE; + readonly status: number = 409; + readonly statusCode: number = 409; + + constructor(public readonly reason: CodeWorkspaceSelectionErrorReason) { + super(codeWorkspaceSelectionErrorMessage(reason)); + this.name = 'CodeWorkspaceSelectionError'; + } +} + +async function readAuthorizedAttachedWorkerStatus( + context: CodeExecutionContext, + environments: readonly CodeEnvironmentConfig[] | undefined, + getAppConfig: CodeCapabilityConfigLoader | undefined, +): Promise { + if (context.environmentType !== 'attached' || !context.bridgeWorkerId) { + throw new CodeWorkspaceSelectionError('worker_unavailable'); + } const selected = environments?.find((environment) => environment.id === context.environmentId); const controlPlaneId = selected?.controlPlaneId ?? selected?.id; const effectiveControlPlane = environments?.find( @@ -23,30 +63,113 @@ export async function supportsProgrammaticCodeExecution( environment.type === 'attached' && environment.owner === 'deployment', ); - if (!effectiveControlPlane || !getAppConfig) return false; + if (!effectiveControlPlane || !getAppConfig) { + throw new CodeWorkspaceSelectionError('worker_unavailable'); + } + const deploymentConfig = await getAppConfig({ baseOnly: true }); + const controlPlane = deploymentConfig.endpoints?.agents?.statefulCodeSessions?.environments?.find( + (environment) => + environment.id === controlPlaneId && + environment.type === 'attached' && + environment.owner === 'deployment', + ); + if ( + !controlPlane || + (selected?.workerId ?? selected?.pairing?.workerId) !== context.bridgeWorkerId || + (selected?.owner === 'deployment' && + controlPlane.pairing?.workerId !== context.bridgeWorkerId) || + controlPlane.baseURL.replace(/\/+$/, '') !== context.baseUrl.replace(/\/+$/, '') + ) { + throw new CodeWorkspaceSelectionError('worker_unavailable'); + } + const tokenEnv = controlPlane.pairing?.tokenEnv; + const token = tokenEnv == null ? undefined : readCodeBridgeSecret(tokenEnv)?.trim(); + if (!token) { + throw new CodeWorkspaceSelectionError('worker_unavailable'); + } + return await pollWorkerStatus({ + baseURL: controlPlane.baseURL, + workerId: context.bridgeWorkerId, + token, + }); +} + +/** + * Resolves a conversation preference into a live worker capability. Request + * state wins so a user can deliberately change directories on this turn; + * persisted state supplies reconnect and non-browser clients. Neither path is + * trusted until the worker confirms the exact environment/workspace pair. + */ +export async function resolveCodeExecutionWorkspaceContext({ + context, + requestedSelections, + persistedSelections, + environments, + getAppConfig, +}: { + context: CodeExecutionContext; + requestedSelections?: unknown; + persistedSelections?: unknown; + environments?: readonly CodeEnvironmentConfig[]; + getAppConfig?: CodeCapabilityConfigLoader; +}): Promise { + if (context.environmentType !== 'attached') return context; + const rawSelections = + requestedSelections === undefined ? persistedSelections : requestedSelections; + if (rawSelections == null) { + throw new CodeWorkspaceSelectionError('required'); + } + if (!isCodeWorkspaceSelections(rawSelections)) { + throw new CodeWorkspaceSelectionError('invalid'); + } + const selection: CodeWorkspaceSelection | undefined = rawSelections.find( + ({ environmentId }) => environmentId === context.environmentId, + ); + if (selection == null) throw new CodeWorkspaceSelectionError('required'); + + let status: CodeBridgeWorkerStatus; try { - const deploymentConfig = await getAppConfig({ baseOnly: true }); - const controlPlane = - deploymentConfig.endpoints?.agents?.statefulCodeSessions?.environments?.find( - (environment) => - environment.id === controlPlaneId && - environment.type === 'attached' && - environment.owner === 'deployment', - ); - if ( - !controlPlane || - controlPlane.baseURL.replace(/\/+$/, '') !== context.baseUrl.replace(/\/+$/, '') - ) { - return false; - } - const tokenEnv = controlPlane.pairing?.tokenEnv; - const token = tokenEnv == null ? undefined : readCodeBridgeSecret(tokenEnv)?.trim(); - if (!token) return false; - const status = await pollWorkerStatus({ - baseURL: controlPlane.baseURL, - workerId: context.bridgeWorkerId, - token, - }); + status = await readAuthorizedAttachedWorkerStatus(context, environments, getAppConfig); + } catch (error) { + if (error instanceof CodeWorkspaceSelectionError) throw error; + logger.warn( + '[codeCapabilities] Worker workspace capabilities unavailable; workspace selection rejected', + error instanceof CodeBridgeStatusError ? { reason: error.reason } : undefined, + ); + throw new CodeWorkspaceSelectionError('worker_unavailable'); + } + if (status.status !== 'ready' || status.statefulWorkspace !== true) { + throw new CodeWorkspaceSelectionError('worker_unavailable'); + } + if (!status.workspaces || !status.operations) { + throw new CodeWorkspaceSelectionError('unsupported'); + } + const workspace = status.workspaces.find(({ id }) => id === selection.workspaceId); + if (!workspace) { + throw new CodeWorkspaceSelectionError('missing'); + } + return { + ...context, + codeWorkspace: { + ...selection, + operations: [...(workspace.operations ?? status.operations)], + }, + }; +} + +/** Attached workers must confirm both a stateful workspace and the Bash runtime. */ +export async function supportsProgrammaticCodeExecution( + context?: CodeExecutionContext, + environments?: readonly CodeEnvironmentConfig[], + getAppConfig?: CodeCapabilityConfigLoader, +): Promise { + if (context?.environmentType !== 'attached') return true; + /** Programmatic Bash uses Code API's generic exec endpoint, which has no + * workspace identifier. A fully resolved attached context therefore cannot + * use it until that protocol can preserve the selected-root boundary. */ + if (context.codeWorkspace != null) return false; + try { + const status = await readAuthorizedAttachedWorkerStatus(context, environments, getAppConfig); return ( status.status === 'ready' && status.statefulWorkspace === true && diff --git a/packages/api/src/code/command.spec.ts b/packages/api/src/code/command.spec.ts index 3247e18240..7c56c10207 100644 --- a/packages/api/src/code/command.spec.ts +++ b/packages/api/src/code/command.spec.ts @@ -51,7 +51,7 @@ function commandResponse(overrides: Record = {}): Response { JSON.stringify({ protocolVersion: 1, operation: 'execute_command', - workspaceId: 'primary', + workspaceId: 'project-a', exitCode: 0, stdout: 'ready\n', stderr: '', @@ -64,7 +64,7 @@ function commandResponse(overrides: Record = {}): Response { } describe('createAttachedWorkspaceBashTool', () => { - test('executes in the attached default workspace with per-user bridge authentication', async () => { + test('executes in the selected workspace and relative working directory', async () => { const fetchImpl: CodeBridgeFetch = jest.fn(async () => commandResponse()); const authHeaders = jest.fn().mockResolvedValue({ Authorization: 'Bearer jwt', @@ -73,13 +73,13 @@ describe('createAttachedWorkspaceBashTool', () => { const bashTool = createAttachedWorkspaceBashTool({ baseUrl: 'https://code.example.com/v1/', authHeaders, + workspaceId: 'project-a', fetchImpl, }); - await expect(bashTool.func({ command: 'pwd' }, undefined, {})).resolves.toEqual([ - 'stdout:\nready\n\n[exit code: 0]', - {}, - ]); + await expect( + bashTool.func({ command: 'pwd', cwd: 'packages/api' }, undefined, {}), + ).resolves.toEqual(['stdout:\nready\n\n[exit code: 0]', {}]); expect(authHeaders).toHaveBeenCalledTimes(1); expect(fetchImpl).toHaveBeenCalledWith( @@ -95,8 +95,9 @@ describe('createAttachedWorkspaceBashTool', () => { expect(request).toEqual({ protocolVersion: 1, operation: 'execute_command', - workspaceId: 'primary', + workspaceId: 'project-a', command: 'pwd', + cwd: 'packages/api', maxOutputBytes: 256 * 1024, }); }); @@ -106,6 +107,7 @@ describe('createAttachedWorkspaceBashTool', () => { const bashTool = createAttachedWorkspaceBashTool({ baseUrl: 'https://code.example.com/v1', authHeaders: () => ({}), + workspaceId: 'project-a', fetchImpl, }); @@ -122,6 +124,7 @@ describe('createAttachedWorkspaceBashTool', () => { const bashTool = createAttachedWorkspaceBashTool({ baseUrl: 'https://code.example.com/v1', authHeaders: () => ({}), + workspaceId: 'project-a', fetchImpl, }); @@ -136,6 +139,7 @@ describe('createAttachedWorkspaceBashTool', () => { const bashTool = createAttachedWorkspaceBashTool({ baseUrl: 'https://code.example.com/v1', authHeaders: () => ({}), + workspaceId: 'project-a', gitIdentity: { name: "Agent O'Brien", email: 'agent@example.com' }, fetchImpl, }); @@ -163,6 +167,7 @@ describe('createAttachedWorkspaceBashTool', () => { const bashTool = createAttachedWorkspaceBashTool({ baseUrl: 'https://code.example.com/v1', authHeaders: () => ({}), + workspaceId: 'project-a', fetchImpl, }); diff --git a/packages/api/src/code/command.ts b/packages/api/src/code/command.ts index b6afc18953..ecb16e3e1e 100644 --- a/packages/api/src/code/command.ts +++ b/packages/api/src/code/command.ts @@ -11,7 +11,6 @@ import type { WorkspaceExecuteCommandResult } from './workspace'; import type { CodeBridgeFetch } from './bridge'; import { executeWorkspaceTool } from './workspace'; -const DEFAULT_WORKSPACE_ID = 'primary'; const DEFAULT_OUTPUT_BYTES = 256 * 1024; export const ATTACHED_WORKSPACE_BASH_DESCRIPTION = `Runs bash commands inside the selected attached environment and returns stdout/stderr. The workspace may be an existing project, a Git repository, or an empty directory; Git is not required. @@ -35,6 +34,20 @@ const attachedCommandSchema: NonNullable = { 'The bash command or script to execute from the attached workspace root. Files written in the workspace persist between calls, but each call starts a fresh process.', }; +/** `maxLength` is valid JSON Schema, but the SDK's schema type omits it. */ +interface BoundedWorkingDirectorySchema { + type: 'string'; + maxLength: number; + description: string; +} + +const attachedWorkingDirectorySchema: BoundedWorkingDirectorySchema = { + type: 'string', + maxLength: 4096, + description: + 'Optional working directory relative to the selected workspace root, such as "packages/api". Absolute paths and parent traversal are rejected.', +}; + /** * This definition is shared with agent metadata. LangChain's JSON Schema * dereferencer annotates schemas during validation, so each tool receives an @@ -45,6 +58,7 @@ export const ATTACHED_WORKSPACE_BASH_SCHEMA: NonNullable = properties: { ...bashSchema.properties, command: attachedCommandSchema, + cwd: attachedWorkingDirectorySchema, }, required: ['command'], }); @@ -114,19 +128,19 @@ function formatCommandResult(result: WorkspaceExecuteCommandResult): string { export function createAttachedWorkspaceBashTool({ baseUrl, authHeaders, - workspaceId = DEFAULT_WORKSPACE_ID, + workspaceId, gitIdentity, fetchImpl, }: { baseUrl: string; authHeaders: () => Promise> | Record; - workspaceId?: string; + workspaceId: string; gitIdentity?: AgentGitIdentity | null; fetchImpl?: CodeBridgeFetch; }): DynamicStructuredTool { return tool( async ( - rawInput: { command: string; args?: string[]; intent?: string }, + rawInput: { command: string; args?: string[]; cwd?: string; intent?: string }, config, ): Promise<[string, Record]> => { const command = commandWithGitIdentity( @@ -141,6 +155,7 @@ export function createAttachedWorkspaceBashTool({ operation: 'execute_command', workspaceId, command, + ...(rawInput.cwd ? { cwd: rawInput.cwd } : {}), maxOutputBytes: DEFAULT_OUTPUT_BYTES, }, signal: config?.signal, diff --git a/packages/api/src/code/http.spec.ts b/packages/api/src/code/http.spec.ts index 41da6a663b..22a1edade0 100644 --- a/packages/api/src/code/http.spec.ts +++ b/packages/api/src/code/http.spec.ts @@ -20,6 +20,86 @@ function response() { } describe('code environment HTTP handlers', () => { + test.each(['allowed', 'denied', 'unpaired', 'changed-worker'])( + 'resolves deployment worker status only through effective authorization: %s', + async (policy) => { + const deploymentEnvironment = { + id: 'deployment-vm', + name: 'Deployment VM', + type: 'attached' as const, + owner: 'deployment' as const, + baseURL: 'https://code.example.com/v1', + pairing: { workerId: 'configured-worker', tokenEnv: 'CODE_ADMIN_TOKEN' }, + }; + let effectiveWorkerId: string | undefined = 'configured-worker'; + if (policy === 'unpaired') effectiveWorkerId = undefined; + if (policy === 'changed-worker') effectiveWorkerId = 'replacement'; + const effectiveEnvironment = { + ...deploymentEnvironment, + pairing: { + ...deploymentEnvironment.pairing, + workerId: effectiveWorkerId, + }, + }; + const fetchImpl = jest.fn().mockResolvedValue( + new Response( + JSON.stringify({ + protocolVersion: 1, + workerId: 'configured-worker', + online: true, + ready: true, + leaseExpiresInMs: 50_000, + capabilities: { + statefulWorkspace: true, + sandboxProfile: 'native-srt', + runtimes: ['bash'], + }, + }), + ), + ); + const effectiveEnvironments = policy === 'denied' ? [] : [effectiveEnvironment]; + const handlers = createCodeEnvironmentHttpHandlers({ + getAppConfig: jest.fn().mockImplementation(async ({ baseOnly }) => ({ + endpoints: { + [EModelEndpoint.agents]: { + statefulCodeSessions: { + environments: baseOnly ? [deploymentEnvironment] : effectiveEnvironments, + }, + }, + }, + })), + registry: { + register: jest.fn(), + listAccessible: jest.fn(), + remove: jest.fn(), + listAccessibleConfigurations: jest.fn().mockResolvedValue([]), + }, + readSecret: () => 'administrator-token', + fetchImpl, + }); + const res = response(); + await handlers.status( + { + user: { id: 'user-1', role: 'USER' }, + params: { environmentId: 'deployment-vm' }, + } as never, + res as never, + ); + expect(res.statusCode).toBe(policy === 'allowed' ? 200 : 404); + if (policy !== 'allowed') { + expect(fetchImpl).not.toHaveBeenCalled(); + return; + } + expect(res.body).toEqual( + expect.objectContaining({ environmentId: 'deployment-vm', statefulWorkspace: true }), + ); + expect(fetchImpl).toHaveBeenCalledWith( + 'https://code.example.com/v1/bridge/workers/configured-worker/status', + expect.any(Object), + ); + }, + ); + test('reports status only for an accessible worker through its current control plane', async () => { const fetchImpl = jest.fn().mockResolvedValue( new Response( @@ -29,7 +109,21 @@ describe('code environment HTTP handlers', () => { online: true, ready: true, leaseExpiresInMs: 50_000, - capabilities: { sandboxProfile: 'native-srt', runtimes: ['bash'] }, + capabilities: { + sandboxProfile: 'native-srt', + runtimes: ['bash'], + workspaceTools: { + protocolVersion: 1, + operations: ['read_file', 'execute_command'], + workspaces: [ + { + id: 'project-a', + name: 'Project A', + operations: ['read_file', 'execute_command'], + }, + ], + }, + }, }), ), ); @@ -93,6 +187,14 @@ describe('code environment HTTP handlers', () => { leaseExpiresInMs: 50_000, sandboxProfile: 'native-srt', runtimes: ['bash'], + operations: ['read_file', 'execute_command'], + workspaces: [ + { + id: 'project-a', + name: 'Project A', + operations: ['read_file', 'execute_command'], + }, + ], }); expect(coalescedRes.body).toEqual(res.body); expect(fetchImpl).toHaveBeenCalledTimes(1); diff --git a/packages/api/src/code/http.ts b/packages/api/src/code/http.ts index 2cf7db489a..f90f3d6236 100644 --- a/packages/api/src/code/http.ts +++ b/packages/api/src/code/http.ts @@ -661,6 +661,7 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps) let configuration: AccessibleCodeEnvironmentConfiguration | undefined; let controlPlane: ConfiguredCodeEnvironment | undefined; + let workerId: string | undefined; try { const principals = await deps.registry.resolvePrincipals?.(principal); const resolvedPrincipal = principals == null ? principal : { ...principal, principals }; @@ -684,14 +685,26 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps) effectiveControlPlane == null || controlPlaneId == null ? undefined : configuredAttachedControlPlane(deploymentConfig, controlPlaneId); + workerId = configuration?.workerId; + if (configuration == null) { + const effectiveEnvironment = configuredControlPlane(effectiveConfig, environmentId); + const deploymentEnvironment = configuredControlPlane(deploymentConfig, environmentId); + if ( + effectiveEnvironment != null && + deploymentEnvironment != null && + effectiveEnvironment.pairing?.workerId === deploymentEnvironment.pairing?.workerId + ) { + controlPlane = deploymentEnvironment; + workerId = deploymentEnvironment.pairing?.workerId; + } + } } catch (error) { logger.error('[codeEnvironments] status policy resolution failed:', error); return res.status(503).json({ error: 'Code environment policy is unavailable' }); } - if (configuration?.workerId == null || controlPlane == null) { + if (workerId == null || controlPlane == null) { return res.status(404).json({ error: 'Code environment was not found' }); } - const workerId = configuration.workerId; const tokenEnv = controlPlane.pairing?.tokenEnv; const token = tokenEnv == null ? undefined : readSecret(tokenEnv)?.trim(); if (!token) { diff --git a/packages/api/src/code/remoteWorkspace.spec.ts b/packages/api/src/code/remoteWorkspace.spec.ts new file mode 100644 index 0000000000..4333837b0e --- /dev/null +++ b/packages/api/src/code/remoteWorkspace.spec.ts @@ -0,0 +1,39 @@ +import { validateResponseRequest } from '../agents/responses/service'; +import { createMCPRuntimeRequestBody } from '../mcp/request'; +import { validateRequest } from '../agents/openai/service'; + +const selections = [{ environmentId: 'machine', workspaceId: 'project' }]; +describe('remote workspace selection envelopes', () => { + it.each([ + [ + 'chat completions', + (code_workspaces: unknown) => + validateRequest({ + model: 'agent', + messages: [{ role: 'user', content: 'hello' }], + code_workspaces, + }), + ], + [ + 'responses', + (code_workspaces: unknown) => + validateResponseRequest({ model: 'agent', input: 'hello', code_workspaces }), + ], + ] as const)( + 'validates %s selection identity without accepting duplicate environments', + (_name, validate) => { + expect(validate(selections).valid).toBe(true); + expect(validate([...selections, ...selections]).valid).toBe(false); + expect(validate([{ ...selections[0], path: '/secret' }]).valid).toBe(false); + }, + ); + it('carries selections into the runtime envelope', () => { + expect( + createMCPRuntimeRequestBody({ + messageId: 'm', + conversationId: 'c', + codeWorkspaces: selections, + }), + ).toEqual({ messageId: 'm', conversationId: 'c', codeWorkspaces: selections }); + }); +}); diff --git a/packages/api/src/mcp/request.ts b/packages/api/src/mcp/request.ts index 8f24f7719e..93a9aa749a 100644 --- a/packages/api/src/mcp/request.ts +++ b/packages/api/src/mcp/request.ts @@ -15,14 +15,17 @@ export function createMCPRuntimeRequestBody({ messageId, conversationId, parentMessageId, + codeWorkspaces, }: { messageId: string; conversationId: string; parentMessageId?: string | null; + codeWorkspaces?: MCPRuntimeRequestBody['codeWorkspaces']; }): MCPRuntimeRequestBody { return { messageId, conversationId, + ...(codeWorkspaces !== undefined && { codeWorkspaces }), ...(parentMessageId !== undefined && { parentMessageId: parentMessageId ?? Constants.NO_PARENT, }), diff --git a/packages/api/src/mcp/types/index.ts b/packages/api/src/mcp/types/index.ts index eb7c21a0ac..3d3bcabe34 100644 --- a/packages/api/src/mcp/types/index.ts +++ b/packages/api/src/mcp/types/index.ts @@ -28,7 +28,7 @@ import type { RequestBody } from '~/types/http'; import type * as o from '~/mcp/oauth/types'; export type MCPRuntimeRequestBody = Required> & - Pick; + Pick; export type StdioOptions = z.infer; export type WebSocketOptions = z.infer; diff --git a/packages/api/src/tools/classification.spec.ts b/packages/api/src/tools/classification.spec.ts index f2aa5d9414..c7740db824 100644 --- a/packages/api/src/tools/classification.spec.ts +++ b/packages/api/src/tools/classification.spec.ts @@ -545,7 +545,7 @@ describe('classification.ts', () => { [false, true].flatMap((definitionsOnly) => [ { definitionsOnly, statefulWorkspace: false, runtimes: ['bash'], supported: false }, { definitionsOnly, statefulWorkspace: true, runtimes: ['py'], supported: false }, - { definitionsOnly, statefulWorkspace: true, runtimes: ['bash'], supported: true }, + { definitionsOnly, statefulWorkspace: true, runtimes: ['bash'], supported: false }, ]), )( 'gates attached PTC: definitionsOnly=$definitionsOnly stateful=$statefulWorkspace runtimes=$runtimes', @@ -620,7 +620,7 @@ describe('classification.ts', () => { 'direct', 'code_execution', ]); - expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(fetchSpy).not.toHaveBeenCalled(); } finally { fetchSpy.mockRestore(); delete process.env.TEST_CODE_CAPABILITY_TOKEN; diff --git a/packages/api/src/tools/classification.ts b/packages/api/src/tools/classification.ts index c99190d2f6..1123e1e5b3 100644 --- a/packages/api/src/tools/classification.ts +++ b/packages/api/src/tools/classification.ts @@ -389,6 +389,7 @@ export async function buildToolClassification( programmaticToolsEnabled && codeExecutionEnabled && agentHasProgrammaticTools(toolRegistry) && + codeExecutionContext?.environmentType !== 'attached' && (await supportsProgrammaticCodeExecution(codeExecutionContext, codeEnvironments, getAppConfig)); const hasDeferredTools = deferredToolsEnabled && agentHasDeferredTools(toolRegistry); diff --git a/packages/api/src/types/http.ts b/packages/api/src/types/http.ts index 1618b6e7a4..3c077ace54 100644 --- a/packages/api/src/types/http.ts +++ b/packages/api/src/types/http.ts @@ -1,4 +1,8 @@ -import type { CodeApprovalMode, TEndpointOption } from 'librechat-data-provider'; +import type { + CodeApprovalMode, + CodeWorkspaceSelection, + TEndpointOption, +} from 'librechat-data-provider'; import type { IUser, AppConfig, IConversation } from '@librechat/data-schemas'; import type { Request } from 'express'; @@ -19,6 +23,7 @@ export type RequestBody = { /** Browser IANA timezone used to resolve local-time prompt variables (e.g. `{{current_datetime}}`). */ timezone?: string; codeApprovalMode?: CodeApprovalMode; + codeWorkspaces?: CodeWorkspaceSelection[]; }; export type ServerRequest = Request & { diff --git a/packages/data-provider/specs/codeWorkspace.spec.ts b/packages/data-provider/specs/codeWorkspace.spec.ts new file mode 100644 index 0000000000..ae5786c8bb --- /dev/null +++ b/packages/data-provider/specs/codeWorkspace.spec.ts @@ -0,0 +1,38 @@ +import { isCodeWorkspaceSelection, isCodeWorkspaceSelections } from '../src/code/workspace'; + +describe('isCodeWorkspaceSelection', () => { + it('accepts an exact environment/workspace binding', () => { + expect( + isCodeWorkspaceSelection({ environmentId: 'personal-vm', workspaceId: 'project:a' }), + ).toBe(true); + }); + + it.each([ + { environmentId: 1, workspaceId: 'project-a' }, + { environmentId: 'personal-vm', workspaceId: 1 }, + { environmentId: 'personal-vm', workspaceId: '../escape' }, + { environmentId: 'personal-vm', workspaceId: 'project-a', operations: ['execute_command'] }, + ])('rejects a malformed or capability-bearing binding: %p', (selection) => { + expect(isCodeWorkspaceSelection(selection)).toBe(false); + }); +}); + +describe('isCodeWorkspaceSelections', () => { + it('accepts one exact binding per environment', () => { + expect( + isCodeWorkspaceSelections([ + { environmentId: 'personal-vm', workspaceId: 'project-a' }, + { environmentId: 'team-vm', workspaceId: 'project-b' }, + ]), + ).toBe(true); + }); + + it('rejects duplicate environment bindings', () => { + expect( + isCodeWorkspaceSelections([ + { environmentId: 'personal-vm', workspaceId: 'project-a' }, + { environmentId: 'personal-vm', workspaceId: 'project-b' }, + ]), + ).toBe(false); + }); +}); diff --git a/packages/data-provider/specs/createPayload.spec.ts b/packages/data-provider/specs/createPayload.spec.ts index 61cfdf17f9..7d8de11e8b 100644 --- a/packages/data-provider/specs/createPayload.spec.ts +++ b/packages/data-provider/specs/createPayload.spec.ts @@ -47,6 +47,15 @@ describe('createPayload server URL', () => { expect(payload.endpoint).toBe('Company/API'); }); + it('forwards the conversation-selected code workspace to agents', () => { + const submission = makeSubmission('agents'); + submission.codeWorkspaces = [{ environmentId: 'personal-vm', workspaceId: 'project-a' }]; + + expect(createPayload(submission).payload.codeWorkspaces).toEqual([ + { environmentId: 'personal-vm', workspaceId: 'project-a' }, + ]); + }); + it('does not touch the assistants URL, which carries no endpoint segment', () => { const { server } = createPayload(makeSubmission(EModelEndpoint.assistants)); diff --git a/packages/data-provider/src/code/workspace.ts b/packages/data-provider/src/code/workspace.ts new file mode 100644 index 0000000000..e9183accad --- /dev/null +++ b/packages/data-provider/src/code/workspace.ts @@ -0,0 +1,55 @@ +export const CODE_WORKSPACE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; +/** Protocol-v1 ceiling enforced by the worker and Code API. */ +export const CODE_WORKSPACE_MAX_COUNT = 32; +export const CODE_WORKSPACE_OPERATIONS = [ + 'read_file', + 'search_text', + 'list_files', + 'write_file', + 'preview_edit', + 'edit_file', + 'execute_command', +] as const; + +export type CodeWorkspaceOperation = (typeof CODE_WORKSPACE_OPERATIONS)[number]; + +/** Public, path-free description of one root registered by an attached worker. */ +export interface CodeWorkspaceDescriptor { + id: string; + name?: string; + /** Omitted when every worker-level operation applies to this workspace. */ + operations?: CodeWorkspaceOperation[]; +} + +/** Conversation-owned selection, bound to the environment that advertised it. */ +export interface CodeWorkspaceSelection { + environmentId: string; + workspaceId: string; +} + +export function isCodeWorkspaceSelection(value: unknown): value is CodeWorkspaceSelection { + if (value == null || typeof value !== 'object' || Array.isArray(value)) { + return false; + } + const selection = value as Record; + return ( + Object.keys(selection).every((key) => key === 'environmentId' || key === 'workspaceId') && + typeof selection.environmentId === 'string' && + CODE_WORKSPACE_ID_PATTERN.test(selection.environmentId) && + typeof selection.workspaceId === 'string' && + CODE_WORKSPACE_ID_PATTERN.test(selection.workspaceId) + ); +} + +/** One exact workspace per attached environment used by a conversation. */ +export function isCodeWorkspaceSelections(value: unknown): value is CodeWorkspaceSelection[] { + if (!Array.isArray(value)) return false; + const environmentIds = new Set(); + return value.every((selection) => { + if (!isCodeWorkspaceSelection(selection) || environmentIds.has(selection.environmentId)) { + return false; + } + environmentIds.add(selection.environmentId); + return true; + }); +} diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts index 1ce166acd6..e735aeaa76 100644 --- a/packages/data-provider/src/config.ts +++ b/packages/data-provider/src/config.ts @@ -3384,6 +3384,10 @@ export enum ErrorTypes { * Agent selected a stateful Code API workspace scope disabled by the deployment. */ STATEFUL_CODE_ENVIRONMENT_NOT_ALLOWED = 'stateful_code_environment_not_allowed', + /** + * A conversation's selected attached workspace cannot be used as requested. + */ + CODE_WORKSPACE_UNAVAILABLE = 'code_workspace_unavailable', /** * Invalid Agent Provider (excluded by Admin) */ diff --git a/packages/data-provider/src/createPayload.ts b/packages/data-provider/src/createPayload.ts index ca197f6c30..dcad9ff5ae 100644 --- a/packages/data-provider/src/createPayload.ts +++ b/packages/data-provider/src/createPayload.ts @@ -26,6 +26,7 @@ export default function createPayload(submission: t.TSubmission) { endpointOption, manualSkills, codeApprovalMode, + codeWorkspaces, clientRequestId, recoverySteerId, expectedPredecessorCreatedAt, @@ -62,6 +63,7 @@ export default function createPayload(submission: t.TSubmission) { ephemeralAgent: s.isAssistantsEndpoint(endpoint) ? undefined : ephemeralAgent, manualSkills: s.isAssistantsEndpoint(endpoint) ? undefined : manualSkills, codeApprovalMode: s.isAssistantsEndpoint(endpoint) ? undefined : codeApprovalMode, + codeWorkspaces: s.isAssistantsEndpoint(endpoint) ? undefined : codeWorkspaces, timezone: getUserTimezone(), clientRequestId, recoverySteerId, diff --git a/packages/data-provider/src/index.ts b/packages/data-provider/src/index.ts index 6812446ab3..5505b6d0e7 100644 --- a/packages/data-provider/src/index.ts +++ b/packages/data-provider/src/index.ts @@ -74,3 +74,4 @@ export * from './agentToolOptions'; export * from './codeEnvRef'; export * from './code/worker'; export * from './code/approval'; +export * from './code/workspace'; diff --git a/packages/data-provider/src/schemas.ts b/packages/data-provider/src/schemas.ts index 583e0225ee..7dc914837e 100644 --- a/packages/data-provider/src/schemas.ts +++ b/packages/data-provider/src/schemas.ts @@ -3,6 +3,7 @@ import type { TMessageContentParts, AgentSubagentGraph, FunctionTool } from './t import type { SearchResultData } from './types/web'; import type { TFile } from './types/files'; import { userSubmittedMessageFieldPathSchema } from './filters'; +import { CODE_WORKSPACE_ID_PATTERN } from './code/workspace'; import { TFeedback, feedbackSchema } from './feedback'; import { CODE_APPROVAL_MODES } from './code/approval'; import { Tools } from './types/assistants'; @@ -1116,6 +1117,16 @@ export const tConversationSchema = z.object({ /** Server-derived: an active shared link exists for this conversation. Not persisted. */ isShared: z.boolean().optional(), codeApprovalMode: z.enum(CODE_APPROVAL_MODES).optional(), + codeWorkspaces: z + .array( + z + .object({ + environmentId: z.string().regex(CODE_WORKSPACE_ID_PATTERN), + workspaceId: z.string().regex(CODE_WORKSPACE_ID_PATTERN), + }) + .strict(), + ) + .optional(), title: z.string().nullable().or(z.literal('New Chat')).default('New Chat'), user: z.string().optional(), messages: z.array(z.string()).optional(), diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts index 36757fa8ea..798b12237a 100644 --- a/packages/data-provider/src/types.ts +++ b/packages/data-provider/src/types.ts @@ -10,6 +10,11 @@ import type { ReasoningResponseKey, ReasoningParameterFormat, } from './schemas'; +import type { + CodeWorkspaceDescriptor, + CodeWorkspaceOperation, + CodeWorkspaceSelection, +} from './code/workspace'; import type { CodeEnvironmentUserConfigSchema, CodeEnvironmentUserSettings } from './config'; import type { Agent, EToolResources, StatefulCodeEnvironment } from './types/assistants'; import type { CodeApprovalMode } from './code/approval'; @@ -152,6 +157,8 @@ export type TPayload = Partial & manualSkills?: string[]; /** Conversation-scoped preference for code tool approval behavior. */ codeApprovalMode?: CodeApprovalMode; + /** Conversation-selected workspaces, with at most one binding per environment. */ + codeWorkspaces?: CodeWorkspaceSelection[]; /** Browser IANA timezone (e.g. `America/New_York`) used to resolve local-time prompt variables server-side. */ timezone?: string; /** @@ -233,6 +240,8 @@ export type TSubmission = { manualSkills?: string[]; /** Conversation-scoped preference for code tool approval behavior. */ codeApprovalMode?: CodeApprovalMode; + /** Conversation-selected workspaces, with at most one binding per environment. */ + codeWorkspaces?: CodeWorkspaceSelection[]; /** Stable per-submission idempotency key (uuid) forwarded to the server to dedup retried start-generation requests. */ clientRequestId?: string; /** Client-only carry-through for a receipt-bound queued recovery. */ @@ -583,10 +592,12 @@ export type TCodeEnvironmentPairingResponse = { export type TCodeEnvironmentStatusResponse = { environmentId: string; status: 'offline' | 'starting' | 'ready'; + statefulWorkspace?: boolean; leaseExpiresInMs?: number; sandboxProfile?: string; runtimes?: string[]; - operations?: string[]; + operations?: CodeWorkspaceOperation[]; + workspaces?: CodeWorkspaceDescriptor[]; }; export type TConfig = { diff --git a/packages/data-schemas/src/schema/defaults.ts b/packages/data-schemas/src/schema/defaults.ts index 9d390ea2d6..9aee90dcdc 100644 --- a/packages/data-schemas/src/schema/defaults.ts +++ b/packages/data-schemas/src/schema/defaults.ts @@ -121,6 +121,14 @@ export const conversationPreset: { type: StringConstructor; enum: string[]; }; + codeWorkspaces: { + type: { + environmentId: { type: StringConstructor; required: boolean }; + workspaceId: { type: StringConstructor; required: boolean }; + _id: boolean; + }[]; + default: undefined; + }; /* assistants */ assistant_id: { type: StringConstructor; @@ -308,6 +316,16 @@ export const conversationPreset: { type: String, enum: [...CODE_APPROVAL_MODES], }, + codeWorkspaces: { + type: [ + { + environmentId: { type: String, required: true }, + workspaceId: { type: String, required: true }, + _id: false, + }, + ], + default: undefined, + }, /* assistants */ assistant_id: { type: String, diff --git a/packages/data-schemas/src/types/convo.ts b/packages/data-schemas/src/types/convo.ts index 80b1199cb4..4b89956e8d 100644 --- a/packages/data-schemas/src/types/convo.ts +++ b/packages/data-schemas/src/types/convo.ts @@ -1,4 +1,8 @@ -import type { CodeApprovalMode, TSubagentThreadLineage } from 'librechat-data-provider'; +import type { + CodeApprovalMode, + CodeWorkspaceSelection, + TSubagentThreadLineage, +} from 'librechat-data-provider'; import type { Document, Types } from 'mongoose'; import type { ICompactionSemanticIndexProjection } from './compaction'; @@ -266,6 +270,7 @@ export interface IConversation extends Document { imageDetail?: string; agent_id?: string; codeApprovalMode?: CodeApprovalMode; + codeWorkspaces?: CodeWorkspaceSelection[]; /** Immutable primary persisted-agent attribution for Insights. */ initial_agent_id?: string | null; subagentThread?: TSubagentThreadLineage;