Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🌳 fix: Guard Ambiguous BYOM Workspace Selection (#15785)
Danny Avila6cb049931948
diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.jsindex 19c65c775b..654e0ec24f 100644--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js@@ -273,6 +273,8 @@ jest.mock('@librechat/api', () => ({buildMessageFiles: jest.fn(() => []),resolveTitleTiming: jest.fn(() => 'immediate'),resolveConversationAnchor: jest.requireActual('@librechat/api').resolveConversationAnchor,+ getCodeWorkspaceSelectionErrorDetails:+ jest.requireActual('@librechat/api').getCodeWorkspaceSelectionErrorDetails,GenerationJobManager: mockGenerationJobManager,getReferencedQuotes: jest.fn((quotes) => {if (!Array.isArray(quotes)) {@@ -2667,6 +2669,45 @@ describe('ResumableAgentController resume metadata', () => {);});+ it.each([+ ['required', 'required'],+ ['future_reason', undefined],+ ])('serializes only allowlisted workspace reason %s', async (reason, expectedReason) => {+ const workspaceError = Object.assign(new Error('Choose an attached workspace'), {+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ reason,+ status: 409,+ statusCode: 409,+ });+ const initializeClient = jest.fn().mockRejectedValue(workspaceError);+ const req = {+ user: { id: 'user-123' },+ body: {+ text: 'Edit the project.',+ messageId: 'user-msg',+ clientRequestId: 'req-abc',+ conversationId: 'conversation-123',+ endpointOption: { endpoint: 'agents', modelOptions: { model: 'gpt-4.1' } },+ },+ config: {},+ };+ const res = createResumableResponse();++ await AgentController(req, res, jest.fn(), initializeClient, null);++ expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith(+ 'conversation-123',+ JSON.stringify({+ status: 409,+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ ...(expectedReason == null ? {} : { reason: expectedReason }),+ error: 'Choose an attached workspace',+ }),+ 1000,+ expect.objectContaining({ beforeErrorPublication: expect.any(Function) }),+ );+ });+it('preserves a stateful scope policy denial in the durable initialization error', async () => {const policyError = Object.assign(new Error('Stateful code environment is not allowed by this deployment: conversation'),diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.jsindex a9fa0de429..4ea5ba8892 100644--- a/api/server/controllers/agents/request.js+++ b/api/server/controllers/agents/request.js@@ -41,6 +41,7 @@ const {agentRequestsAskUserQuestion,resolveAgentTurnExecutionPlan,logAgentMemorySnapshot,+ getCodeWorkspaceSelectionErrorDetails,} = require('@librechat/api');const { disposeClient } = require('~/server/cleanup');const {@@ -110,6 +111,7 @@ function getInitializationFailure(error) {return {status: candidateStatus,...(typeof error?.code === 'string' ? { code: error.code } : {}),+ ...getCodeWorkspaceSelectionErrorDetails(error),error: error?.message || 'Failed to start generation',};}diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsxindex 819d67a42d..f13756b854 100644--- a/client/src/components/Chat/Input/ChatForm.tsx+++ b/client/src/components/Chat/Input/ChatForm.tsx@@ -843,7 +843,7 @@ const ChatForm = memo(function ChatForm({disabled={filesLoading ||disableInputs ||- (codeWorkspace.required && codeWorkspace.state !== 'ready') ||+ !codeWorkspace.canSubmit ||isNotAppendable ||answerMode.composerLocked ||(isSubmitting && !answerMode.composerAnswers)diff --git a/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx b/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsxindex 4a72f34d75..383ca7cac7 100644--- a/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx+++ b/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx@@ -40,6 +40,7 @@ function workspace(overrides: Partial<CodeWorkspaceResult> = {}): CodeWorkspaceRreturn {required: true,state: 'ready',+ canSubmit: true,environments: [{environment,@@ -50,6 +51,7 @@ function workspace(overrides: Partial<CodeWorkspaceResult> = {}): CodeWorkspaceR],selections: [selected],resolveSelections: () => [selected],+ resolveSubmission: () => ({ codeWorkspaces: [selected] }),...overrides,};}diff --git a/client/src/components/Messages/Content/Error.tsx b/client/src/components/Messages/Content/Error.tsxindex fceb06ab1c..3f9f50bc4c 100644--- a/client/src/components/Messages/Content/Error.tsx+++ b/client/src/components/Messages/Content/Error.tsx@@ -3,9 +3,11 @@ import {ErrorTypes,alternateName,ViolationTypes,+ isCodeWorkspaceSelectionErrorReason,parseLangChainErrorCode,stripLangChainTroubleshootingUrl,} from 'librechat-data-provider';+import type { CodeWorkspaceSelectionErrorReason } from 'librechat-data-provider';import type { LocalizeFunction } from '~/common';import type { TranslationKeys } from '~/hooks';import { formatJSON, extractJson, isJson } from '~/utils/json';@@ -69,6 +71,18 @@ type TCompactionSkipped = {reason?: string;};+type TCodeWorkspaceError = {+ reason?: string;+};++const codeWorkspaceErrorKeys: Record<CodeWorkspaceSelectionErrorReason, TranslationKeys> = {+ required: 'com_error_code_workspace_required',+ invalid: 'com_error_code_workspace_invalid',+ worker_unavailable: 'com_error_code_workspace_worker_unavailable',+ unsupported: 'com_error_code_workspace_unsupported',+ missing: 'com_error_code_workspace_missing',+};+/** Why a manual compaction could not run, keyed by the SDK's skip reason. */const compactionSkippedKeys: Record<string, TranslationKeys> = {disabled: 'com_error_compaction_disabled',@@ -126,7 +140,15 @@ 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.CODE_WORKSPACE_UNAVAILABLE]: (+ json: TCodeWorkspaceError,+ localize: LocalizeFunction,+ ) => {+ if (!isCodeWorkspaceSelectionErrorReason(json.reason)) {+ return localize('com_error_code_workspace_unavailable');+ }+ return localize(codeWorkspaceErrorKeys[json.reason]);+ },[ErrorTypes.STREAM_EXPIRED]: 'com_error_stream_expired',[ErrorTypes.MODEL_NOT_FOUND]: langChainErrorKeys.MODEL_NOT_FOUND,[ErrorTypes.MODEL_RATE_LIMIT]: langChainErrorKeys.MODEL_RATE_LIMIT,@@ -237,14 +259,14 @@ const Error = ({ text }: { text: string }) => {const json = JSON.parse(jsonString);const errorKey = json.code || json.type;- const keyExists = errorKey && errorMessages[errorKey];-- if (keyExists && typeof errorMessages[errorKey] === 'function') {- return errorMessages[errorKey](json, localize);- } else if (keyExists && keyExists.startsWith(localizedErrorPrefix)) {- return localize(errorMessages[errorKey]);- } else if (keyExists) {- return errorMessages[errorKey];+ const mappedError = errorKey && errorMessages[errorKey];++ if (typeof mappedError === 'function') {+ return mappedError(json, localize);+ } else if (mappedError && mappedError.startsWith(localizedErrorPrefix)) {+ return localize(mappedError);+ } else if (mappedError) {+ return mappedError;} else {return defaultResponse;}diff --git a/client/src/components/Messages/Content/__tests__/Error.spec.tsx b/client/src/components/Messages/Content/__tests__/Error.spec.tsxindex 8a246597c7..25f47f4826 100644--- a/client/src/components/Messages/Content/__tests__/Error.spec.tsx+++ b/client/src/components/Messages/Content/__tests__/Error.spec.tsx@@ -59,6 +59,33 @@ describe('Error — typed provider errors', () => {expect(screen.getByText(catalog[key])).toBeInTheDocument();});+ it.each([+ ['required', 'com_error_code_workspace_required'],+ ['invalid', 'com_error_code_workspace_invalid'],+ ['worker_unavailable', 'com_error_code_workspace_worker_unavailable'],+ ['unsupported', 'com_error_code_workspace_unsupported'],+ ['missing', 'com_error_code_workspace_missing'],+ ])('localizes a workspace rejection with reason %s', (reason, key) => {+ render(+ <Error text={JSON.stringify({ type: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, reason })} />,+ );++ expect(screen.getByText(catalog[key])).toBeInTheDocument();+ });++ it.each([{ reason: 'future_reason' }, {}])(+ 'uses safe workspace fallback copy for an unknown or legacy payload',+ (payload) => {+ render(+ <Error+ text={JSON.stringify({ type: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, ...payload })}+ />,+ );++ expect(screen.getByText(catalog.com_error_code_workspace_unavailable)).toBeInTheDocument();+ },+ );+it('keeps the provider message for a LangChain code without localized copy, minus the URL', () => {const raw ='An error occurred while processing the request: could not parse output\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/OUTPUT_PARSING_FAILURE/\n';diff --git a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsxindex 5ef93d4913..194894603c 100644--- a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx+++ b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx@@ -26,7 +26,7 @@ const conversation = (codeWorkspaces?: TConversation['codeWorkspaces']): TConver({conversationId: 'conversation-1',endpoint: EModelEndpoint.agents,- agent_id: 'agent-1',+ agent_id: 'agent_primary',codeWorkspaces,}) as TConversation;@@ -36,7 +36,7 @@ describe('useCodeWorkspace', () => {mockAgentPermissions.mockReturnValue({tools: [Tools.execute_code],agent: {- id: 'agent-1',+ id: 'agent_primary',stateful_code_sessions: true,code_environment_id: 'personal-vm',tools: [Tools.execute_code],@@ -93,6 +93,7 @@ describe('useCodeWorkspace', () => {const { result } = renderHook(() => useCodeWorkspace(conversation()));expect(result.current.state).toBe('ready');+ expect(result.current.canSubmit).toBe(true);expect(result.current.selections).toEqual([{ environmentId: 'personal-vm', workspaceId: 'project-a' },]);@@ -162,7 +163,7 @@ describe('useCodeWorkspace', () => {environmentId: 'personal-vm',status: 'ready',statefulWorkspace: true,- workspaces: [{ id: 'project-a' }, { id: 'project-b' }],+ workspaces: [{ id: 'primary' }, { id: 'canary-a' }, { id: 'canary-b' }],},isLoading: false,isError: false,@@ -172,7 +173,54 @@ describe('useCodeWorkspace', () => {const { result } = renderHook(() => useCodeWorkspace(conversation()));expect(result.current.state).toBe('choose');+ expect(result.current.canSubmit).toBe(false);expect(result.current.selections).toBeUndefined();+ expect(result.current.resolveSubmission()).toBeUndefined();+ });++ it('submits an explicit selection from several advertised workspaces', () => {+ const selection = { environmentId: 'personal-vm', workspaceId: 'canary-a' };+ mockStatus.mockReturnValue([+ {+ data: {+ environmentId: 'personal-vm',+ status: 'ready',+ workspaces: [{ id: 'primary' }, { id: 'canary-a' }, { id: 'canary-b' }],+ },+ isLoading: false,+ isError: false,+ },+ ]);++ const { result } = renderHook(() => useCodeWorkspace(conversation([selection])));++ expect(result.current.canSubmit).toBe(true);+ expect(result.current.resolveSubmission([selection])).toEqual({+ codeWorkspaces: [selection],+ });+ });++ it('blocks submission while the required worker status is loading', () => {+ mockStatus.mockReturnValue([{ data: undefined, isLoading: true, isError: false }]);++ const { result } = renderHook(() => useCodeWorkspace(conversation()));++ expect(result.current.required).toBe(true);+ expect(result.current.state).toBe('loading');+ expect(result.current.canSubmit).toBe(false);+ expect(result.current.resolveSubmission()).toBeUndefined();+ });++ it('blocks submission while endpoint capabilities are loading', () => {+ mockAgentsConfig.mockReturnValue({ agentsConfig: null, endpointsConfig: undefined });++ const { result } = renderHook(() => useCodeWorkspace(conversation()));++ expect(result.current.required).toBe(true);+ expect(result.current.state).toBe('loading');+ expect(result.current.canSubmit).toBe(false);+ expect(result.current.resolveSubmission()).toBeUndefined();+ expect(mockStatus).toHaveBeenLastCalledWith([], false);});it('does not replace a saved workspace that disappeared', () => {@@ -180,6 +228,7 @@ describe('useCodeWorkspace', () => {const { result } = renderHook(() => useCodeWorkspace(conversation([saved])));expect(result.current.state).toBe('missing');+ expect(result.current.canSubmit).toBe(false);expect(result.current.selections).toBeUndefined();expect(result.current.resolveSelections([saved])).toBeUndefined();});@@ -189,9 +238,59 @@ describe('useCodeWorkspace', () => {const { result } = renderHook(() => useCodeWorkspace(conversation([saved])));expect(result.current.state).toBe('choose');+ expect(result.current.canSubmit).toBe(false);expect(result.current.selections).toBeUndefined();});+ it('invalidates readiness when current agent metadata changes environments', () => {+ let environmentId = 'personal-vm';+ mockAgentPermissions.mockImplementation((agentId?: string) =>+ agentId == null+ ? {}+ : {+ tools: [Tools.execute_code],+ agent: {+ id: agentId,+ stateful_code_sessions: true,+ code_environment_id: environmentId,+ tools: [Tools.execute_code],+ },+ },+ );+ mockAgentsConfig.mockReturnValue({+ agentsConfig: {+ capabilities: ['execute_code', 'stateful_code_sessions'],+ statefulCodeSessions: {+ environments: [+ { id: 'personal-vm', type: 'attached' },+ { id: 'team-vm', type: 'attached' },+ ],+ },+ },+ });+ mockStatus.mockImplementation((ids: string[]) =>+ ids.map((id) => ({+ data: {+ environmentId: id,+ status: 'ready',+ workspaces: [{ id: id === 'personal-vm' ? 'project-a' : 'project-b' }],+ },+ isLoading: false,+ isError: false,+ })),+ );+ const saved = { environmentId: 'personal-vm', workspaceId: 'project-a' };+ const { result, rerender } = renderHook(() => useCodeWorkspace(conversation([saved])));+ expect(result.current.canSubmit).toBe(true);++ environmentId = 'team-vm';+ rerender();++ expect(result.current.state).toBe('choose');+ expect(result.current.canSubmit).toBe(false);+ expect(result.current.resolveSubmission([saved])).toBeUndefined();+ });+it('rejects a status response for a different environment', () => {mockStatus.mockReturnValue([{@@ -228,9 +327,20 @@ describe('useCodeWorkspace', () => {expect(mockStatus).toHaveBeenCalledWith([], false);});+ it('does not gate a non-agent conversation', () => {+ const { result } = renderHook(() =>+ useCodeWorkspace({ ...conversation(), endpoint: EModelEndpoint.openAI }),+ );++ expect(result.current.required).toBe(false);+ expect(result.current.state).toBe('not_required');+ expect(result.current.canSubmit).toBe(true);+ expect(result.current.resolveSubmission()).toEqual({});+ });+it.each(['subagent', 'handoff'])('collects every attached environment through %s', (kind) => {const primary = {- id: 'agent-1',+ id: 'agent_primary',stateful_code_sessions: true,code_environment_id: 'personal-vm',tools: [Tools.execute_code],@@ -238,13 +348,13 @@ describe('useCodeWorkspace', () => {...(kind === 'handoff'? {subagents: { enabled: false, agent_ids: [] },- edges: [{ from: 'agent-1', to: 'child', edgeType: 'handoff' }],+ edges: [{ from: 'agent_primary', to: 'child', edgeType: 'handoff' }],}: {}),};mockAgentPermissions.mockImplementation((id?: string) => ({- agent: id === 'agent-1' ? primary : undefined,- tools: id === 'agent-1' ? primary.tools : undefined,+ agent: id === 'agent_primary' ? primary : undefined,+ tools: id === 'agent_primary' ? primary.tools : undefined,}));mockAgentsMap.mockReturnValue({child: {diff --git a/client/src/hooks/Agents/useCodeWorkspace.ts b/client/src/hooks/Agents/useCodeWorkspace.tsindex 2a987c4d54..a860a47ffe 100644--- a/client/src/hooks/Agents/useCodeWorkspace.ts+++ b/client/src/hooks/Agents/useCodeWorkspace.ts@@ -1,6 +1,11 @@import { useCallback, useMemo } from 'react';import { AgentCapabilities, PermissionTypes, Permissions } from 'librechat-data-provider';-import { EModelEndpoint, Tools, isCodeWorkspaceSelections } from 'librechat-data-provider';+import {+ EModelEndpoint,+ Tools,+ isEphemeralAgentId,+ isCodeWorkspaceSelections,+} from 'librechat-data-provider';import type {CodeWorkspaceDescriptor,CodeWorkspaceSelection,@@ -35,11 +40,15 @@ export interface CodeWorkspaceEnvironmentResult {export interface CodeWorkspaceResult {required: boolean;state: CodeWorkspaceState;+ canSubmit: boolean;environments: CodeWorkspaceEnvironmentResult[];selections?: CodeWorkspaceSelection[];resolveSelections: (selections?: CodeWorkspaceSelection[],) => CodeWorkspaceSelection[] | undefined;+ resolveSubmission: (+ selections?: CodeWorkspaceSelection[],+ ) => { codeWorkspaces?: CodeWorkspaceSelection[] } | undefined;}function aggregateState(@@ -84,7 +93,7 @@ export default function useCodeWorkspace(conversation: TConversation | null,addedConversation?: TConversation | null,): CodeWorkspaceResult {- const { agentsConfig } = useGetAgentsConfig();+ const { agentsConfig, endpointsConfig } = useGetAgentsConfig();const canRunCode = useHasAccess({permissionType: PermissionTypes.RUN_CODE,permission: Permissions.USE,@@ -126,14 +135,22 @@ export default function useCodeWorkspace(const isAgentsConversation =(conversation?.endpointType ?? conversation?.endpoint) === EModelEndpoint.agents;const expectedRoot = conversation?.agent_id != null || addedConversation?.agent_id != null;+ const expectedSavedAgent = [conversation?.agent_id, addedConversation?.agent_id].some(+ (agentId) => agentId != null && !isEphemeralAgentId(agentId),+ );+ const configurationLoaded = endpointsConfig !== undefined || agentsConfig != null;+ const configurationPending =+ canRunCode && isAgentsConversation && expectedSavedAgent && !configurationLoaded;const attachedEnvironments = workspaceMetadata.environments;const metadataComplete =!isAgentsConversation || !expectedRoot || (reachable.complete && workspaceMetadata.complete);const required =- codeEnabled && isAgentsConversation && (!metadataComplete || attachedEnvironments.length > 0);+ configurationPending ||+ (codeEnabled && isAgentsConversation && (!metadataComplete || attachedEnvironments.length > 0));+ const selectionMetadataComplete = !configurationPending && metadataComplete;const statuses = useCodeEnvironmentStatusQueries(attachedEnvironments.map(({ id }) => id),- required && metadataComplete,+ required && selectionMetadataComplete,);const storedSelections = conversation?.codeWorkspaces;const environmentResults = attachedEnvironments.map((environment, index) => {@@ -166,7 +183,7 @@ export default function useCodeWorkspace(const resolveSelections = useCallback((selections?: CodeWorkspaceSelection[]): CodeWorkspaceSelection[] | undefined => {- if (!required || !metadataComplete || !isCodeWorkspaceSelections(selections ?? [])) {+ if (!required || !selectionMetadataComplete || !isCodeWorkspaceSelections(selections ?? [])) {return undefined;}const resolved: CodeWorkspaceSelection[] = [];@@ -198,10 +215,31 @@ export default function useCodeWorkspace(}return resolved.sort((a, b) => a.environmentId.localeCompare(b.environmentId));},- [environmentResults, metadataComplete, required],+ [environmentResults, required, selectionMetadataComplete],);const selections = resolveSelections(storedSelections);- const state = aggregateState(required, metadataComplete, environmentResults, selections);- return { required, state, environments: environmentResults, selections, resolveSelections };+ const state = configurationPending+ ? 'loading'+ : aggregateState(required, metadataComplete, environmentResults, selections);+ const resolveSubmission = useCallback(+ (+ candidateSelections?: CodeWorkspaceSelection[],+ ): { codeWorkspaces?: CodeWorkspaceSelection[] } | undefined => {+ if (!required) return {};+ const codeWorkspaces = resolveSelections(candidateSelections);+ return codeWorkspaces == null ? undefined : { codeWorkspaces };+ },+ [required, resolveSelections],+ );+ const canSubmit = resolveSubmission(storedSelections) != null;+ return {+ required,+ state,+ canSubmit,+ environments: environmentResults,+ selections,+ resolveSelections,+ resolveSubmission,+ };}diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsxindex 3a3dcde848..d44fa9b7d8 100644--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx@@ -19,13 +19,12 @@ 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,+const mockResolveCodeWorkspaceSubmission = jest.fn<+ { codeWorkspaces?: CodeWorkspaceSelection[] } | undefined,[CodeWorkspaceSelection[]?]->(() => undefined);+>(() => ({}));const mockCodeWorkspace = {- required: false,- resolveSelections: mockResolveCodeWorkspace,+ resolveSubmission: mockResolveCodeWorkspaceSubmission,};jest.mock('react-router-dom', () => ({@@ -150,8 +149,7 @@ describe('useChatFunctions ask', () => {jest.clearAllMocks();mockGetQueryData.mockReturnValue({});mockGetLatestConversation.mockReturnValue(null);- mockCodeWorkspace.required = false;- mockResolveCodeWorkspace.mockReturnValue(undefined);+ mockResolveCodeWorkspaceSubmission.mockReturnValue({});});it('reads an approval-mode selection made immediately before send', () => {@@ -171,8 +169,7 @@ describe('useChatFunctions ask', () => {it('submits the latest validated workspace selection', () => {const selection = { environmentId: 'personal-vm', workspaceId: 'project-a' };- mockCodeWorkspace.required = true;- mockResolveCodeWorkspace.mockReturnValue([selection]);+ mockResolveCodeWorkspaceSubmission.mockReturnValue({ codeWorkspaces: [selection] });mockGetLatestConversation.mockReturnValue({...conversation('conversation-1'),codeWorkspaces: [selection],@@ -184,13 +181,12 @@ describe('useChatFunctions ask', () => {});const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;- expect(mockResolveCodeWorkspace).toHaveBeenCalledWith([selection]);+ expect(mockResolveCodeWorkspaceSubmission).toHaveBeenCalledWith([selection]);expect(submission.codeWorkspaces).toEqual([selection]);});- it('refuses to send while the required workspace is unavailable', () => {- mockCodeWorkspace.required = true;- mockResolveCodeWorkspace.mockReturnValue(undefined);+ it('refuses to send when workspace submission resolution is not ready', () => {+ mockResolveCodeWorkspaceSubmission.mockReturnValue(undefined);const { result, setSubmission } = renderAsk([]);expect(result.current.ask({ text: 'Edit the file', conversationId: 'conversation-1' })).toBe(diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.tsindex 950d4eb3e6..eb918117b8 100644--- a/client/src/hooks/Chat/useChatFunctions.ts+++ b/client/src/hooks/Chat/useChatFunctions.ts@@ -332,11 +332,12 @@ export default function useChatFunctions({? latestCodeApprovalMode: fallbackCodeApprovalMode;const latestCodeWorkspaces = getConversation()?.codeWorkspaces ?? conversation?.codeWorkspaces;- const codeWorkspaces = codeWorkspaceState.resolveSelections(latestCodeWorkspaces);- if (codeWorkspaceState.required && codeWorkspaces == null) {+ const workspaceSubmission = codeWorkspaceState.resolveSubmission(latestCodeWorkspaces);+ if (workspaceSubmission == null) {logger.warn('[useChatFunctions] Refusing to send without an available code workspace');return false;}+ const { codeWorkspaces } = workspaceSubmission;const endpoint = conversation?.endpoint;if (endpoint === null) {diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex f3d904c689..2a8f7a7c8b 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -412,6 +412,11 @@"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_code_workspace_required": "Choose an attached workspace before sending.",+ "com_error_code_workspace_invalid": "The workspace selection is invalid; select an available workspace.",+ "com_error_code_workspace_worker_unavailable": "The machine is unavailable; reconnect or choose another environment.",+ "com_error_code_workspace_unsupported": "The worker does not support workspace selection.",+ "com_error_code_workspace_missing": "The selected workspace is no longer registered; choose an available workspace.","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/code/capabilities.ts b/packages/api/src/code/capabilities.tsindex 1b02553a8b..9014784efd 100644--- a/packages/api/src/code/capabilities.ts+++ b/packages/api/src/code/capabilities.ts@@ -1,9 +1,13 @@import { logger } from '@librechat/data-schemas';import { ErrorTypes, isCodeWorkspaceSelections } from 'librechat-data-provider';-import type { CodeWorkspaceSelection } from 'librechat-data-provider';+import type {+ CodeWorkspaceSelection,+ CodeWorkspaceSelectionErrorReason,+} from 'librechat-data-provider';import type { CodeEnvironmentConfig, CodeExecutionContext } from '~/agents/execution';import type { createAppConfigService } from '~/app/service';import type { CodeBridgeWorkerStatus } from './bridge';+export type { CodeWorkspaceSelectionErrorReason } from 'librechat-data-provider';import {CodeBridgeStatusError,createCodeBridgeStatusPoller,@@ -14,13 +18,6 @@ export type CodeCapabilityConfigLoader = ReturnType<typeof createAppConfigServicconst pollWorkerStatus = createCodeBridgeStatusPoller();-export type CodeWorkspaceSelectionErrorReason =- | 'required'- | 'invalid'- | 'worker_unavailable'- | 'unsupported'- | 'missing';-function codeWorkspaceSelectionErrorMessage(reason: CodeWorkspaceSelectionErrorReason): string {switch (reason) {case 'required':diff --git a/packages/api/src/code/errors.spec.ts b/packages/api/src/code/errors.spec.tsnew file mode 100644index 0000000000..a0945f04cf--- /dev/null+++ b/packages/api/src/code/errors.spec.ts@@ -0,0 +1,25 @@+import { ErrorTypes } from 'librechat-data-provider';+import { getCodeWorkspaceSelectionErrorDetails } from './errors';++describe('getCodeWorkspaceSelectionErrorDetails', () => {+ it.each(['required', 'invalid', 'worker_unavailable', 'unsupported', 'missing'] as const)(+ 'preserves the allowlisted workspace reason %s',+ (reason) => {+ expect(+ getCodeWorkspaceSelectionErrorDetails({+ code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,+ reason,+ }),+ ).toEqual({ reason });+ },+ );++ it.each([+ { code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE, reason: 'future_reason' },+ { code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE },+ { code: 'ANOTHER_ERROR', reason: 'required' },+ null,+ ])('omits unrecognized or unrelated error details', (error) => {+ expect(getCodeWorkspaceSelectionErrorDetails(error)).toEqual({});+ });+});diff --git a/packages/api/src/code/errors.ts b/packages/api/src/code/errors.tsnew file mode 100644index 0000000000..ff71e8c1fc--- /dev/null+++ b/packages/api/src/code/errors.ts@@ -0,0 +1,23 @@+import { ErrorTypes, isCodeWorkspaceSelectionErrorReason } from 'librechat-data-provider';+import type { CodeWorkspaceSelectionErrorReason } from 'librechat-data-provider';++interface CodeWorkspaceErrorLike {+ code?: string;+ reason?: string;+}++interface CodeWorkspaceSelectionErrorDetails {+ reason?: CodeWorkspaceSelectionErrorReason;+}++export function getCodeWorkspaceSelectionErrorDetails(+ error?: CodeWorkspaceErrorLike | null,+): CodeWorkspaceSelectionErrorDetails {+ if (+ error?.code !== ErrorTypes.CODE_WORKSPACE_UNAVAILABLE ||+ !isCodeWorkspaceSelectionErrorReason(error.reason)+ ) {+ return {};+ }+ return { reason: error.reason };+}diff --git a/packages/api/src/code/index.ts b/packages/api/src/code/index.tsindex c45f48eb77..4006a47405 100644--- a/packages/api/src/code/index.ts+++ b/packages/api/src/code/index.ts@@ -6,3 +6,4 @@ export * from './lifecycle';export * from './workspace';export * from './command';export * from './capabilities';+export * from './errors';diff --git a/packages/data-provider/src/code/workspace.ts b/packages/data-provider/src/code/workspace.tsindex e9183accad..9b352156ea 100644--- a/packages/data-provider/src/code/workspace.ts+++ b/packages/data-provider/src/code/workspace.ts@@ -10,8 +10,17 @@ export const CODE_WORKSPACE_OPERATIONS = ['edit_file','execute_command',] as const;+export const CODE_WORKSPACE_SELECTION_ERROR_REASONS = [+ 'required',+ 'invalid',+ 'worker_unavailable',+ 'unsupported',+ 'missing',+] as const;export type CodeWorkspaceOperation = (typeof CODE_WORKSPACE_OPERATIONS)[number];+export type CodeWorkspaceSelectionErrorReason =+ (typeof CODE_WORKSPACE_SELECTION_ERROR_REASONS)[number];/** Public, path-free description of one root registered by an attached worker. */export interface CodeWorkspaceDescriptor {@@ -27,6 +36,12 @@ export interface CodeWorkspaceSelection {workspaceId: string;}+export function isCodeWorkspaceSelectionErrorReason(+ value: unknown,+): value is CodeWorkspaceSelectionErrorReason {+ return CODE_WORKSPACE_SELECTION_ERROR_REASONS.some((reason) => reason === value);+}+export function isCodeWorkspaceSelection(value: unknown): value is CodeWorkspaceSelection {if (value == null || typeof value !== 'object' || Array.isArray(value)) {return false;