Skip to content

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

🏝️ fix: Let a No-Workspace Turn Carry a Remembered Approval Mode (#16763)

Danny Avila3a32d8b0d3d7
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index adb65f6cff..746cb5b7e4 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -65,6 +65,8 @@ const {
collectAttachedCodeRoutePolicies,
buildAttachedCodeEnvironmentAdmissionHooks,
resolveAttachedCodeApprovalMode,
+ resolvePersistedCodeApprovalMode,
+ getCodeApprovalPreservedFields,
markNativeCodeToolApprovalRequests,
markToolApprovalAllowAlways,
resolveRunToolApprovalAllows,
@@ -1986,11 +1988,11 @@ class AgentClient extends BaseClient {
const agentsEConfig = this.options.req.config?.endpoints?.[EModelEndpoint.agents];
const topLevelAgents = [this.options.agent, ...(this.agentConfigs?.values() ?? [])];
- const codeApprovalMode = resolveAttachedCodeApprovalMode(
- this.options.req.body.codeApprovalMode,
- collectAttachedCodeApprovalPolicies(topLevelAgents),
- agentsEConfig?.toolApproval?.enabled !== false,
- );
+ const codeApprovalMode = resolvePersistedCodeApprovalMode({
+ requested: this.options.req.body.codeApprovalMode,
+ policies: collectAttachedCodeApprovalPolicies(topLevelAgents),
+ approvalsEnabled: agentsEConfig?.toolApproval?.enabled !== false,
+ });
const persistedCodeEnvironmentDecision = resolvePersistableCodeEnvironmentDecision({
conversationId: this.options.req.body.conversationId,
decision: this.options.req._codeEnvironmentDecision,
@@ -2019,6 +2021,17 @@ class AgentClient extends BaseClient {
);
}
+ getTurnConversationFields(options, conversationId, endpointOptions, context) {
+ const topLevelAgents = [options.agent, ...(this.agentConfigs?.values() ?? [])];
+ return {
+ ...super.getTurnConversationFields(options, conversationId, endpointOptions, context),
+ preservedFields: getCodeApprovalPreservedFields(
+ collectAttachedCodeApprovalPolicies(topLevelAgents),
+ options.req?.config?.endpoints?.[EModelEndpoint.agents]?.toolApproval?.enabled !== false,
+ ),
+ };
+ }
+
/**
* Returns build message options. For AgentClient, agent-specific instructions
* are retrieved directly from agent objects in buildMessages, so this returns empty.
diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.js
index 2491cb2281..3d30076aef 100644
--- a/api/server/controllers/agents/client.test.js
+++ b/api/server/controllers/agents/client.test.js
@@ -99,6 +99,94 @@ describe('AgentClient code approval persistence', () => {
});
});
+ /** Reproduces the "no workspace" failure: no agent has an attached execution context, yet the
+ * request still carries the mode the reader picked for a workspace. */
+ const noWorkspaceClient = ({ requested, stored, agent = { id: 'terra' } }) => {
+ const client = Object.create(AgentClient.prototype);
+ client.agentConfigs = new Map();
+ client.conversationId = 'convo-1';
+ client.options = {
+ endpoint: EModelEndpoint.agents,
+ agent,
+ req: {
+ body: { conversationId: 'convo-1', codeApprovalMode: requested },
+ _codeEnvironmentDecision: { mode: 'without_attached' },
+ resolvedConversation: {
+ conversationId: 'convo-1',
+ codeEnvironmentMode: 'without_attached',
+ ...(stored != null && { codeApprovalMode: stored }),
+ },
+ config: { endpoints: { [EModelEndpoint.agents]: {} } },
+ },
+ };
+ return client;
+ };
+
+ /** The write `BaseClient` performs with these options: an omitted key is `$unset` from the
+ * stored row unless the write preserves it. */
+ const turnWrite = (client) =>
+ client.getTurnConversationFields(
+ client.options,
+ 'convo-1',
+ client.getSaveOptions(),
+ 'client.test approval mode',
+ );
+
+ it.each(['fullAccess', 'acceptEdits', 'ask', undefined])(
+ 'saves a turn without a workspace that carries %s, keeping the stored mode as it is',
+ (requested) => {
+ const write = turnWrite(noWorkspaceClient({ requested, stored: 'acceptEdits' }));
+ expect(write.endpointOptions).not.toHaveProperty('codeApprovalMode');
+ expect(write.preservedFields).toEqual(['codeApprovalMode']);
+ },
+ );
+
+ it('preserves nothing once the turn runs on an attached machine', () => {
+ const agent = {
+ id: 'terra',
+ codeExecutionContext: {
+ environmentId: 'terra-vm',
+ environmentType: 'attached',
+ codeEnvironmentConfigSchema: {
+ permissions: { fileWrite: { allowed: ['allow', 'ask'], default: 'ask' } },
+ },
+ },
+ };
+ const write = turnWrite(noWorkspaceClient({ requested: 'acceptEdits', agent }));
+ expect(write.endpointOptions).toMatchObject({ codeApprovalMode: 'acceptEdits' });
+ expect(write.preservedFields).toEqual([]);
+ });
+
+ it('still rejects a value that is not an approval mode without a workspace', () => {
+ expect(() =>
+ noWorkspaceClient({ requested: 'unrestricted', stored: 'fullAccess' }).getSaveOptions(),
+ ).toThrow('not permitted');
+ });
+
+ it('validates the mode against a subagent machine when the parent has no workspace', () => {
+ const agent = {
+ id: 'terra',
+ lazySubagentConfigs: [
+ {
+ id: 'builder',
+ codeExecutionContext: {
+ environmentId: 'builder-vm',
+ environmentType: 'attached',
+ codeEnvironmentConfigSchema: {
+ permissions: { fileWrite: { allowed: ['ask'], default: 'ask' } },
+ },
+ },
+ },
+ ],
+ };
+ expect(() =>
+ noWorkspaceClient({ requested: 'fullAccess', stored: 'fullAccess', agent }).getSaveOptions(),
+ ).toThrow('not permitted');
+ expect(
+ noWorkspaceClient({ requested: 'ask', stored: 'fullAccess', agent }).getSaveOptions(),
+ ).toMatchObject({ codeApprovalMode: 'ask' });
+ });
+
it('never writes its run-start decision over a stored one a move replaced', () => {
const client = Object.create(AgentClient.prototype);
client.agentConfigs = new Map();
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index f8e60a6e62..3e6acabdb3 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -430,6 +430,7 @@ const ChatForm = memo(function ChatForm({
index,
conversationId,
conversation,
+ codeEnvironmentMode: codeWorkspace.mode,
isSubmitting,
answerModeActive: composerReserved,
composerDisabled: isPreparingFromUrl,
@@ -1025,6 +1026,7 @@ const ChatForm = memo(function ChatForm({
<CodeApprovalMenu
conversation={conversation}
addedConversation={addedConvo}
+ codeEnvironmentMode={codeWorkspace.mode}
setConversation={setConversation}
disabled={disableInputs}
/>
diff --git a/client/src/components/Chat/Input/CodeApprovalMenu.tsx b/client/src/components/Chat/Input/CodeApprovalMenu.tsx
index 946eb2b4d9..5b7c3827e4 100644
--- a/client/src/components/Chat/Input/CodeApprovalMenu.tsx
+++ b/client/src/components/Chat/Input/CodeApprovalMenu.tsx
@@ -3,7 +3,7 @@ import { TooltipAnchor } from '@librechat/client';
import { useQueryClient } from '@tanstack/react-query';
import { QueryKeys, Constants } from 'librechat-data-provider';
import { Check, ChevronDown, FilePen, FileQuestionMark, FileTerminal } from 'lucide-react';
-import type { CodeApprovalMode, TConversation } from 'librechat-data-provider';
+import type { TConversation, CodeApprovalMode, CodeEnvironmentMode } from 'librechat-data-provider';
import type { LucideIcon } from 'lucide-react';
import type { SetterOrUpdater } from 'recoil';
import type { TranslationKeys } from '~/hooks';
@@ -42,17 +42,24 @@ const modeOptions: Record<
export default function CodeApprovalMenu({
conversation,
addedConversation,
+ codeEnvironmentMode,
setConversation,
disabled,
}: {
conversation: TConversation | null;
addedConversation?: TConversation | null;
+ /** The workspace mode the composer resolved for the next turn. */
+ codeEnvironmentMode?: CodeEnvironmentMode;
setConversation: SetterOrUpdater<TConversation | null>;
disabled: boolean;
}) {
const localize = useLocalize();
const queryClient = useQueryClient();
- const { available, modes, selected } = useCodeApprovalMode(conversation, addedConversation);
+ const { available, modes, selected } = useCodeApprovalMode(
+ conversation,
+ addedConversation,
+ codeEnvironmentMode,
+ );
const preference = useCodeApprovalModePreference();
const menuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' });
const isOpen = menuStore.useState('open');
diff --git a/client/src/hooks/Agents/__tests__/codeDecision.test.ts b/client/src/hooks/Agents/__tests__/codeDecision.test.ts
index 007182464d..433452339b 100644
--- a/client/src/hooks/Agents/__tests__/codeDecision.test.ts
+++ b/client/src/hooks/Agents/__tests__/codeDecision.test.ts
@@ -1,5 +1,9 @@
import type { TConversation } from 'librechat-data-provider';
-import { withSubmittedCodeDecision, hasSameCodeDecision } from '../codeDecision';
+import {
+ hasSameCodeDecision,
+ withSubmittedCodeDecision,
+ resolveSubmittedCodeApprovalMode,
+} from '../codeDecision';
const selection = { environmentId: 'personal-vm', workspaceId: 'project-a' };
const conversation = (overrides: Partial<TConversation> = {}): TConversation =>
@@ -104,3 +108,51 @@ it('treats empty and absent selections alike without treating an undecided chat
).toBe(true);
expect(hasSameCodeDecision({}, { codeEnvironmentMode: 'without_attached' })).toBe(false);
});
+
+describe('resolveSubmittedCodeApprovalMode', () => {
+ const modes = ['ask', 'acceptEdits', 'fullAccess'] as const;
+
+ it('sends the gated ask for a turn resolved without a workspace', () => {
+ for (const requested of modes) {
+ expect(
+ resolveSubmittedCodeApprovalMode({
+ requested,
+ modes,
+ fallback: requested,
+ codeEnvironmentMode: 'without_attached',
+ }),
+ ).toBe('ask');
+ }
+ });
+
+ it('keeps the policy-offered pick for an attached turn and falls back otherwise', () => {
+ expect(
+ resolveSubmittedCodeApprovalMode({
+ requested: 'fullAccess',
+ modes,
+ fallback: 'ask',
+ codeEnvironmentMode: 'attached',
+ }),
+ ).toBe('fullAccess');
+ expect(
+ resolveSubmittedCodeApprovalMode({
+ requested: 'fullAccess',
+ modes: ['ask'],
+ fallback: 'ask',
+ }),
+ ).toBe('ask');
+ expect(resolveSubmittedCodeApprovalMode({ modes, fallback: 'acceptEdits' })).toBe(
+ 'acceptEdits',
+ );
+ });
+
+ it('sends nothing when approvals are unsupported', () => {
+ expect(
+ resolveSubmittedCodeApprovalMode({
+ requested: 'fullAccess',
+ modes: [],
+ codeEnvironmentMode: 'without_attached',
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts b/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts
index ee73eca9cc..3d049aa136 100644
--- a/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts
+++ b/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts
@@ -70,6 +70,38 @@ describe('useCodeApprovalMode', () => {
});
});
+ test('offers no attached mode once the chat runs without a workspace, and submits ask', () => {
+ const { result, rerender } = renderHook(
+ ({ codeEnvironmentMode }: Pick<TConversation, 'codeEnvironmentMode'>) =>
+ useCodeApprovalMode({ ...conversation, codeEnvironmentMode }),
+ { initialProps: { codeEnvironmentMode: 'without_attached' } },
+ );
+
+ expect(result.current).toEqual({ available: false, modes: [], selected: 'ask' });
+ rerender({ codeEnvironmentMode: 'attached' });
+ expect(result.current).toEqual({
+ available: true,
+ modes: ['ask', 'acceptEdits'],
+ selected: 'acceptEdits',
+ });
+ });
+
+ test('follows the composer-resolved mode for a chat that records no decision', () => {
+ const { result, rerender } = renderHook(
+ ({ resolved }: { resolved?: TConversation['codeEnvironmentMode'] }) =>
+ useCodeApprovalMode(conversation, undefined, resolved),
+ { initialProps: { resolved: 'without_attached' } },
+ );
+
+ expect(result.current).toEqual({ available: false, modes: [], selected: 'ask' });
+ rerender({ resolved: 'attached' });
+ expect(result.current).toEqual({
+ available: true,
+ modes: ['ask', 'acceptEdits'],
+ selected: 'acceptEdits',
+ });
+ });
+
test('uses the chosen machine policy without inheriting full access from the default', () => {
mockUseAgentToolPermissions.mockReturnValue({
agent: {
diff --git a/client/src/hooks/Agents/codeDecision.ts b/client/src/hooks/Agents/codeDecision.ts
index 6897a28e36..1b544093d6 100644
--- a/client/src/hooks/Agents/codeDecision.ts
+++ b/client/src/hooks/Agents/codeDecision.ts
@@ -1,5 +1,6 @@
import { Constants, canonicalizeCodeWorkspaceSelections } from 'librechat-data-provider';
import type {
+ CodeApprovalMode,
CodeEnvironmentMode,
EventSubmission,
CodeWorkspaceSelection,
@@ -88,3 +89,24 @@ export function getFailedCodeDecisionRequest(submission: EventSubmission, resolv
},
};
}
+
+/**
+ * The mode a submission carries: the conversation's pick when current policy offers it, else the
+ * gated fallback. A turn sent without attached workspaces has no target for a stronger mode to
+ * govern, so it carries `ask` even when the composer resolved the decision only at send time.
+ */
+export function resolveSubmittedCodeApprovalMode({
+ requested,
+ modes,
+ fallback,
+ codeEnvironmentMode,
+}: {
+ requested?: CodeApprovalMode;
+ modes: readonly CodeApprovalMode[];
+ fallback?: CodeApprovalMode;
+ codeEnvironmentMode?: CodeEnvironmentMode;
+}): CodeApprovalMode | undefined {
+ if (fallback == null) return undefined;
+ if (codeEnvironmentMode === 'without_attached') return 'ask';
+ return requested != null && modes.includes(requested) ? requested : fallback;
+}
diff --git a/client/src/hooks/Agents/useCodeApprovalMode.ts b/client/src/hooks/Agents/useCodeApprovalMode.ts
index 336dba54db..80c56b1d25 100644
--- a/client/src/hooks/Agents/useCodeApprovalMode.ts
+++ b/client/src/hooks/Agents/useCodeApprovalMode.ts
@@ -10,21 +10,28 @@ import {
} from 'librechat-data-provider';
import type {
Agent,
- TAgentsMap,
TConfig,
+ TAgentsMap,
+ TConversation,
+ CodeApprovalMode,
+ CodeEnvironmentMode,
TPublicCodeEnvironment,
CodeWorkspaceSelection,
CodeWorkspaceRoutingAgent,
} from 'librechat-data-provider';
-import type { CodeApprovalMode, TConversation } from 'librechat-data-provider';
import { useCodeApprovalModePreference } from './codeApprovalPreference';
import useAgentToolPermissions from './useAgentToolPermissions';
import useGetAgentsConfig from './useGetAgentsConfig';
import { useAgentsMapContext } from '~/Providers';
+/**
+ * `codeEnvironmentMode` is the mode the composer resolved for the next turn (`useCodeWorkspace`'s
+ * `mode`), which also covers a saved chat with no recorded decision and a draft still choosing.
+ */
export default function useCodeApprovalMode(
conversation: TConversation | null,
addedConversation?: TConversation | null,
+ codeEnvironmentMode?: CodeEnvironmentMode,
): {
available: boolean;
modes: CodeApprovalMode[];
@@ -71,12 +78,19 @@ export default function useCodeApprovalMode(
conversation?.codeWorkspaces,
],
);
+ /** A turn sent without attached workspaces opts every agent out of its attached machine on the
+ * server, so no attached mode applies to it, whatever the agents' defaults are. */
+ const withoutAttached =
+ (codeEnvironmentMode ?? conversation?.codeEnvironmentMode) === 'without_attached';
const attachedEnvironments = useMemo(
() =>
- codeEnvironments.filter(
- (environment): environment is TPublicCodeEnvironment => environment?.type === 'attached',
- ),
- [codeEnvironments],
+ withoutAttached
+ ? []
+ : codeEnvironments.filter(
+ (environment): environment is TPublicCodeEnvironment =>
+ environment?.type === 'attached',
+ ),
+ [codeEnvironments, withoutAttached],
);
const supported =
(conversation?.endpointType ?? conversation?.endpoint) === EModelEndpoint.agents &&
@@ -115,8 +129,9 @@ export default function useCodeApprovalMode(
/**
* Fail closed while agent/environment metadata is incomplete. An affirmative
* server capability means `ask` is safe to submit even before an attached
- * environment is discoverable; the server ignores it when no BYOM tool is
- * active. Never preserve `acceptEdits` until current policy authorizes it.
+ * environment is discoverable; a turn with no attached target accepts it and
+ * keeps the conversation's stored mode. Never preserve `acceptEdits` until
+ * current policy authorizes it.
*/
let selected: CodeApprovalMode | undefined;
if (supported) {
diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
index c2cc2a8215..3ee1911413 100644
--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
@@ -302,6 +302,26 @@ describe('useChatFunctions ask', () => {
expect(submission.conversation.codeApprovalMode).toBe('acceptEdits');
});
+ it('sends the gated ask for a turn without a workspace while keeping the chat pick', () => {
+ mockResolveCodeWorkspaceSubmission.mockReturnValue({ codeEnvironmentMode: 'without_attached' });
+ mockGetLatestConversation.mockReturnValue({
+ ...conversation('conversation-1'),
+ codeApprovalMode: 'acceptEdits',
+ codeEnvironmentMode: 'without_attached',
+ });
+ const { result, setSubmission } = renderAsk([]);
+
+ act(() => {
+ result.current.ask({ text: 'Just chat', conversationId: 'conversation-1' });
+ });
+
+ const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;
+ expect(submission.codeEnvironmentMode).toBe('without_attached');
+ expect(submission.codeApprovalMode).toBe('ask');
+ expect(createPayload(submission).payload.codeApprovalMode).toBe('ask');
+ expect(submission.conversation.codeApprovalMode).toBe('acceptEdits');
+ });
+
it('preallocates a durable Agents user id for the optimistic response anchor', () => {
const { result, setSubmission } = renderAsk([]);
diff --git a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
index a7a0dce725..e3cb075c53 100644
--- a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
@@ -660,6 +660,7 @@ describe('useSteering', () => {
function setupServerQueue(
initializer = withActiveGeneration(),
addedConversation?: TConversation,
+ codeEnvironmentMode?: TConversation['codeEnvironmentMode'],
) {
const sendNow = jest.fn();
const wrapper = ({ children }: { children: React.ReactNode }) => (
@@ -673,6 +674,7 @@ describe('useSteering', () => {
conversationId: CONVO_ID,
conversation: agentsConversation,
addedConversation,
+ codeEnvironmentMode,
isSubmitting: true,
answerModeActive: false,
sendNow,
@@ -720,10 +722,23 @@ describe('useSteering', () => {
result.current.steering.queueFromComposer('run later');
await Promise.resolve();
});
- expect(mockCodeApprovalMode).toHaveBeenLastCalledWith(agentsConversation, addedConversation);
+ expect(mockCodeApprovalMode).toHaveBeenLastCalledWith(
+ agentsConversation,
+ addedConversation,
+ undefined,
+ );
expect(mockEnqueueQueuedTurn.mock.calls[0]?.[0].codeApprovalMode).toBe('ask');
});
+ it('gates the queued mode on the workspace mode the composer resolved', () => {
+ setupServerQueue(withActiveGeneration(), undefined, 'without_attached');
+ expect(mockCodeApprovalMode).toHaveBeenLastCalledWith(
+ agentsConversation,
+ undefined,
+ 'without_attached',
+ );
+ });
+
it('keeps startup turns local until the server generation epoch exists', async () => {
const { result } = setupServerQueue(
withActiveGeneration(({ set }) => {
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index a60131535a..57d6c7891e 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -46,9 +46,12 @@ import {
getReasoningStateKey,
pendingReasoningOverrideFamily,
} from '~/components/Chat/Input/Composer/state';
+import {
+ withSubmittedCodeDecision,
+ resolveSubmittedCodeApprovalMode,
+} from '~/hooks/Agents/codeDecision';
import useFocusRegeneratedResponse from '~/hooks/Chat/useFocusRegeneratedResponse';
import useGetConversation from '~/hooks/Conversations/useGetConversation';
-import { withSubmittedCodeDecision } from '~/hooks/Agents/codeDecision';
import useCodeApprovalMode from '~/hooks/Agents/useCodeApprovalMode';
import useSetFilesToDelete from '~/hooks/Files/useSetFilesToDelete';
import { useAgentsMapContext } from '~/Providers/AgentsMapContext';
@@ -258,11 +261,12 @@ export default function useChatFunctions({
const jotaiStore = useStore();
const getConversation = useGetConversation(index);
const addedConversation = useRecoilValue(store.conversationByKeySelector(1));
+ const codeWorkspaceState = useCodeWorkspace(immutableConversation, addedConversation);
const { modes: codeApprovalModes, selected: fallbackCodeApprovalMode } = useCodeApprovalMode(
immutableConversation,
addedConversation,
+ codeWorkspaceState.mode,
);
- const codeWorkspaceState = useCodeWorkspace(immutableConversation, addedConversation);
/**
* `ask` refuses while `isSubmitting`, but that Recoil value only reads true
@@ -391,10 +395,6 @@ export default function useChatFunctions({
const conversation = cloneDeep(immutableConversation);
const latestCodeApprovalMode = getConversation()?.codeApprovalMode;
- const codeApprovalMode =
- latestCodeApprovalMode != null && codeApprovalModes.includes(latestCodeApprovalMode)
- ? latestCodeApprovalMode
- : fallbackCodeApprovalMode;
const latestCodeWorkspaces = getConversation()?.codeWorkspaces ?? conversation?.codeWorkspaces;
const latestCodeEnvironmentMode =
getConversation()?.codeEnvironmentMode ?? conversation?.codeEnvironmentMode;
@@ -407,6 +407,12 @@ export default function useChatFunctions({
return false;
}
const { codeEnvironmentMode, codeWorkspaces } = workspaceSubmission;
+ const codeApprovalMode = resolveSubmittedCodeApprovalMode({
+ requested: latestCodeApprovalMode,
+ modes: codeApprovalModes,
+ fallback: fallbackCodeApprovalMode,
+ codeEnvironmentMode,
+ });
const endpoint = conversation?.endpoint;
if (endpoint === null) {
diff --git a/client/src/hooks/Chat/useSteering.ts b/client/src/hooks/Chat/useSteering.ts
index 5cd1bf15b8..d1e909cf73 100644
--- a/client/src/hooks/Chat/useSteering.ts
+++ b/client/src/hooks/Chat/useSteering.ts
@@ -15,6 +15,7 @@ import type {
TAgentQueuedTurnFileRef,
TMessage,
TConversation,
+ CodeEnvironmentMode,
TMessageContentParts,
} from 'librechat-data-provider';
import type { CallbackInterface } from 'recoil';
@@ -544,6 +545,8 @@ export interface UseSteeringParams {
conversationId: string;
conversation: TConversation | null;
addedConversation?: TConversation | null;
+ /** The workspace mode the composer resolved for the next turn. */
+ codeEnvironmentMode?: CodeEnvironmentMode;
isSubmitting: boolean;
answerModeActive: boolean;
/** Host-owned preparation hold; existing queued-message and Stop actions remain independent. */
@@ -581,6 +584,7 @@ export default function useSteering({
conversationId,
conversation,
addedConversation,
+ codeEnvironmentMode,
isSubmitting,
answerModeActive,
composerDisabled = false,
@@ -612,7 +616,11 @@ export default function useSteering({
const { duringRunDefaultAction: defaultAction, setDuringRunDefaultAction: setDefaultAction } =
useChatSettings();
- const { selected: codeApprovalMode } = useCodeApprovalMode(conversation, addedConversation);
+ const { selected: codeApprovalMode } = useCodeApprovalMode(
+ conversation,
+ addedConversation,
+ codeEnvironmentMode,
+ );
const endpoint = conversation?.endpointType ?? conversation?.endpoint;
const steerable = !isAssistantsEndpoint(endpoint);
const hasRealConvoId =
diff --git a/packages/api/src/agents/hitl/byom.spec.ts b/packages/api/src/agents/hitl/byom.spec.ts
index 567dcbac08..5e23574558 100644
--- a/packages/api/src/agents/hitl/byom.spec.ts
+++ b/packages/api/src/agents/hitl/byom.spec.ts
@@ -10,6 +10,8 @@ import {
isStatefulCodeEnvironmentToolName,
markNativeCodeToolApprovalRequests,
resolveAttachedCodeApprovalMode,
+ resolvePersistedCodeApprovalMode,
+ getCodeApprovalPreservedFields,
} from './byom';
import { canAgentGraphPause } from './admission';
@@ -618,12 +620,13 @@ describe('collectAttachedCodeApprovalPolicies', () => {
},
];
- expect(() =>
+ /** Default routes alone see no attached target, so the mode would only gate at `ask`. */
+ expect(
resolveAttachedCodeApprovalMode(
'acceptEdits',
collectAttachedCodeEnvironmentPolicySettings(agents).values(),
),
- ).toThrow('not permitted');
+ ).toBe('ask');
expect(
resolveAttachedCodeApprovalMode('acceptEdits', collectAttachedCodeApprovalPolicies(agents)),
).toBe('acceptEdits');
@@ -815,3 +818,113 @@ for (const placement of ['lazySubagentConfigs', 'subagentGraphMemberMetadata'] a
},
);
}
+
+describe('approval mode without attached targets', () => {
+ const restrictedSettings: AttachedCodeEnvironmentPolicySettings = {
+ configSchema: { permissions: { fileWrite: { allowed: ['ask'], default: 'ask' } } },
+ };
+ const attachedContext = (settings: AttachedCodeEnvironmentPolicySettings) => ({
+ environmentType: 'attached',
+ codeEnvironmentConfigSchema: settings.configSchema,
+ codeEnvironmentSettings: settings.settings,
+ });
+
+ test.each(['ask', 'acceptEdits', 'fullAccess'] as const)(
+ 'accepts a remembered %s mode for a turn that has nothing attached, resolving it to ask',
+ (requested) => {
+ const policies = collectAttachedCodeApprovalPolicies([
+ { id: 'terra', codeExecutionContext: { environmentType: 'managed' } },
+ ]);
+ expect(policies).toEqual([]);
+ expect(resolveAttachedCodeApprovalMode(requested, policies)).toBe('ask');
+ },
+ );
+
+ test('still rejects values that are not approval modes and treats an absent mode as none', () => {
+ for (const requested of ['unrestricted', 'FULLACCESS', 1, {}]) {
+ expect(() => resolveAttachedCodeApprovalMode(requested, [])).toThrow('not permitted');
+ }
+ expect(resolveAttachedCodeApprovalMode(undefined, [])).toBeUndefined();
+ expect(resolveAttachedCodeApprovalMode(null, [])).toBeUndefined();
+ });
+
+ test('keeps strict validation once any attached target exists', () => {
+ const unconfigured: AttachedCodeEnvironmentPolicySettings[] = [{}];
+ expect(resolveAttachedCodeApprovalMode('ask', unconfigured)).toBe('ask');
+ expect(() => resolveAttachedCodeApprovalMode('acceptEdits', unconfigured)).toThrow(
+ 'not permitted',
+ );
+ expect(() => resolveAttachedCodeApprovalMode('fullAccess', unconfigured)).toThrow(
+ 'not permitted',
+ );
+ });
+
+ test('validates against a subagent machine when the parent runs without a workspace', () => {
+ type PolicyAgent = Parameters<typeof collectAttachedCodeApprovalPolicies>[0][number];
+ const parent = (child: PolicyAgent) =>
+ collectAttachedCodeApprovalPolicies([{ id: 'parent', lazySubagentConfigs: [child] }]);
+ const restricted = parent({
+ id: 'child',
+ codeExecutionContext: attachedContext(restrictedSettings),
+ });
+ expect(restricted).toHaveLength(1);
+ expect(() => resolveAttachedCodeApprovalMode('fullAccess', restricted)).toThrow(
+ 'not permitted',
+ );
+ const permissive = parent({
+ id: 'child',
+ codeExecutionContext: attachedContext(fullAccessSettings),
+ });
+ expect(resolveAttachedCodeApprovalMode('fullAccess', permissive)).toBe('fullAccess');
+ const routable = parent({
+ id: 'child',
+ codeExecutionContext: { environmentType: 'managed' },
+ codeExecutionChoices: [attachedContext(restrictedSettings)],
+ });
+ expect(() => resolveAttachedCodeApprovalMode('fullAccess', routable)).toThrow('not permitted');
+ const graphMember = collectAttachedCodeApprovalPolicies([
+ {
+ id: 'parent',
+ subagentGraphConfigs: [
+ {
+ memberConfigs: [
+ { id: 'member', codeExecutionContext: attachedContext(restrictedSettings) },
+ ],
+ },
+ ],
+ },
+ ]);
+ expect(() => resolveAttachedCodeApprovalMode('fullAccess', graphMember)).toThrow(
+ 'not permitted',
+ );
+ });
+
+ test('leaves the approvals-disabled contract unchanged', () => {
+ expect(() => resolveAttachedCodeApprovalMode('fullAccess', [], false)).toThrow('not permitted');
+ expect(
+ resolvePersistedCodeApprovalMode({ requested: 'ask', policies: [], approvalsEnabled: false }),
+ ).toBeUndefined();
+ expect(getCodeApprovalPreservedFields([], false)).toEqual([]);
+ });
+
+ describe('persisted mode', () => {
+ const permissive = [fullAccessSettings];
+ const persist = (requested: unknown, policies: AttachedCodeEnvironmentPolicySettings[] = []) =>
+ resolvePersistedCodeApprovalMode({ requested, policies });
+
+ test('records nothing and keeps the stored mode through a turn with nothing attached', () => {
+ for (const requested of ['ask', 'acceptEdits', 'fullAccess', undefined]) {
+ expect(persist(requested)).toBeUndefined();
+ }
+ expect(getCodeApprovalPreservedFields([])).toEqual(['codeApprovalMode']);
+ expect(() => persist('unrestricted')).toThrow('not permitted');
+ });
+
+ test('records exactly the validated mode once a target is attached', () => {
+ expect(persist('acceptEdits', permissive)).toBe('acceptEdits');
+ expect(persist(undefined, permissive)).toBeUndefined();
+ expect(getCodeApprovalPreservedFields(permissive)).toEqual([]);
+ expect(() => persist('fullAccess', [restrictedSettings])).toThrow('not permitted');
+ });
+ });
+});
diff --git a/packages/api/src/agents/hitl/byom.ts b/packages/api/src/agents/hitl/byom.ts
index ca9fd569b8..12bc7e0191 100644
--- a/packages/api/src/agents/hitl/byom.ts
+++ b/packages/api/src/agents/hitl/byom.ts
@@ -1,6 +1,7 @@
import { Constants } from '@librechat/agents';
import {
CODE_APPROVAL_MODES,
+ CodeApprovalModeError,
getAllowedCodeApprovalModes,
resolveCodeApprovalMode,
resolveCodePermissionDecision,
@@ -274,6 +275,16 @@ function permissionDecision(
return resolveCodePermissionDecision({ mode: effectiveMode, category, decision });
}
+function isCodeApprovalMode(value: unknown): value is CodeApprovalMode {
+ return CODE_APPROVAL_MODES.some((mode) => mode === value);
+}
+
+/**
+ * Validates a requested approval mode against every attached target the turn can run on.
+ * A turn with no attached target has nothing for the mode to govern, so any known mode is
+ * accepted there and resolves to `ask`: a target discovered later still starts gated, and a
+ * stale preference from another workspace never fails a turn that cannot use it.
+ */
export function resolveAttachedCodeApprovalMode(
requested: unknown,
policies: Iterable<AttachedCodeEnvironmentPolicySettings>,
@@ -289,9 +300,15 @@ export function resolveAttachedCodeApprovalMode(
enabled: false,
});
}
+ const targets = [...policies];
+ if (targets.length === 0) {
+ if (requested == null) return undefined;
+ if (!isCodeApprovalMode(requested)) throw new CodeApprovalModeError();
+ return 'ask';
+ }
let resolved: CodeApprovalMode | undefined;
let rejection: Error | undefined;
- for (const policy of policies) {
+ for (const policy of targets) {
try {
resolved = resolveCodeApprovalMode(requested, {
environment: 'attached',
@@ -306,13 +323,50 @@ export function resolveAttachedCodeApprovalMode(
}
}
if (resolved == null && rejection != null) throw rejection;
- return (
- resolved ??
- resolveCodeApprovalMode(requested, {
- environment: 'attached',
- allowedModes: CODE_APPROVAL_MODES,
- })
- );
+ return resolved;
+}
+
+/** Approvals are on and no agent the turn can reach runs, or may be routed, on an attached
+ * machine. */
+function makesNoCodeApprovalDecision(
+ policies: readonly AttachedCodeEnvironmentPolicySettings[],
+ approvalsEnabled: boolean,
+): boolean {
+ return approvalsEnabled && policies.length === 0;
+}
+
+/**
+ * The approval mode a turn records on its conversation: the mode it validated against its
+ * attached targets. A turn without one still rejects a value that is not an approval mode, but
+ * records nothing; `getCodeApprovalPreservedFields` keeps the stored mode through its writes.
+ */
+export function resolvePersistedCodeApprovalMode({
+ requested,
+ policies,
+ approvalsEnabled = true,
+}: {
+ requested: unknown;
+ /** Every attached-machine policy the run may execute under (`collectAttachedCodeApprovalPolicies`). */
+ policies: readonly AttachedCodeEnvironmentPolicySettings[];
+ approvalsEnabled?: boolean;
+}): CodeApprovalMode | undefined {
+ const effective = resolveAttachedCodeApprovalMode(requested, policies, approvalsEnabled);
+ return makesNoCodeApprovalDecision(policies, approvalsEnabled) ? undefined : effective;
+}
+
+/**
+ * Conversation fields a turn's writes keep as stored although its save options omit them. A turn
+ * with no attached target makes no approval decision, so the mode stored on whichever
+ * conversation it is saved under, including an `overrideConvoId` target, stays as it is: leaving
+ * a workspace for a turn and returning keeps the reader's pick, and a chat that stores none keeps
+ * offering the remembered one. A kept mode grants nothing on its own and is validated again
+ * against the targets of whichever later turn uses it.
+ */
+export function getCodeApprovalPreservedFields(
+ policies: readonly AttachedCodeEnvironmentPolicySettings[],
+ approvalsEnabled = true,
+): Array<'codeApprovalMode'> {
+ return makesNoCodeApprovalDecision(policies, approvalsEnabled) ? ['codeApprovalMode'] : [];
}
function exactToolMatcher(toolNames: ReadonlySet<string>): string {
diff --git a/packages/api/src/conversations/save.spec.ts b/packages/api/src/conversations/save.spec.ts
index e510117d17..8d2afa07f6 100644
--- a/packages/api/src/conversations/save.spec.ts
+++ b/packages/api/src/conversations/save.spec.ts
@@ -3,6 +3,7 @@ import { randomUUID } from 'crypto';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { createMethods, createModels } from '@librechat/data-schemas';
import type { ConversationMethods, MessageMethods } from '@librechat/data-schemas';
+import type { AttachedCodeEnvironmentPolicySettings } from '~/agents/hitl/byom';
import type { TurnConversationRequest } from './save';
import {
runAfterSeed,
@@ -11,6 +12,10 @@ import {
getConversationWriteContext,
recoverTurnMessageReference,
} from './save';
+import {
+ getCodeApprovalPreservedFields,
+ resolvePersistedCodeApprovalMode,
+} from '~/agents/hitl/byom';
type Store = Pick<ConversationMethods, 'getConvo' | 'saveConvo' | 'appendConvoMessageReference'> &
Pick<MessageMethods, 'saveMessage'>;
@@ -182,6 +187,99 @@ describe('seedTurnConversation', () => {
});
});
+describe('code approval mode across workspace choices', () => {
+ const permissive: AttachedCodeEnvironmentPolicySettings = {
+ configSchema: {
+ permissions: {
+ fileWrite: { allowed: ['allow', 'ask'], default: 'ask' },
+ commandExecution: { allowed: ['allow', 'ask'], default: 'ask' },
+ },
+ },
+ };
+ const restricted: AttachedCodeEnvironmentPolicySettings = {
+ configSchema: { permissions: { fileWrite: { allowed: ['ask'], default: 'ask' } } },
+ };
+
+ /** One turn's save as `AgentClient` and `BaseClient` perform it: the row admission loaded is
+ * the existing one, and a key the options omit is `$unset` from it unless the write keeps it.
+ * `loadedId` names the row admission loaded when the turn is saved under another id. */
+ const saveTurn = async (
+ userId: string,
+ conversationId: string,
+ requested: unknown,
+ targets: Array<[string, AttachedCodeEnvironmentPolicySettings]>,
+ loadedId = conversationId,
+ ) => {
+ const req = createRequest(userId);
+ req.resolvedConversation = await store.getConvo(userId, loadedId);
+ const policies = targets.map(([, policy]) => policy);
+ const codeApprovalMode = resolvePersistedCodeApprovalMode({ requested, policies });
+ await saveTurnConversation(store, {
+ ...seedFields(req, conversationId),
+ endpointOptions: {
+ ...endpointOptions,
+ ...(codeApprovalMode != null && { codeApprovalMode }),
+ },
+ preservedFields: getCodeApprovalPreservedFields(policies),
+ context: 'save.spec approval mode',
+ ctx: getConversationWriteContext(req),
+ });
+ return (await store.getConvo(userId, conversationId))?.codeApprovalMode;
+ };
+
+ it('keeps the pick through a turn without a workspace and revalidates it on return', async () => {
+ const userId = new mongoose.Types.ObjectId().toString();
+ const conversationId = randomUUID();
+ const attached: Array<[string, AttachedCodeEnvironmentPolicySettings]> = [
+ ['terra', permissive],
+ ];
+
+ expect(await saveTurn(userId, conversationId, 'fullAccess', attached)).toBe('fullAccess');
+ /** A current client sends the gated `ask`; an older one still sends the remembered pick. */
+ expect(await saveTurn(userId, conversationId, 'ask', [])).toBe('fullAccess');
+ expect(await saveTurn(userId, conversationId, 'fullAccess', [])).toBe('fullAccess');
+ await expect(saveTurn(userId, conversationId, 'unrestricted', [])).rejects.toThrow(
+ 'not permitted',
+ );
+
+ expect(await saveTurn(userId, conversationId, 'fullAccess', attached)).toBe('fullAccess');
+ await expect(
+ saveTurn(userId, conversationId, 'fullAccess', [['terra', restricted]]),
+ ).rejects.toThrow('not permitted');
+ expect(await saveTurn(userId, conversationId, 'ask', attached)).toBe('ask');
+ expect(await saveTurn(userId, conversationId, undefined, attached)).toBeUndefined();
+ });
+
+ it('leaves a new chat without a mode until a turn with a workspace validates one', async () => {
+ const userId = new mongoose.Types.ObjectId().toString();
+ const conversationId = randomUUID();
+
+ /** The gated `ask` a current client sends must not replace the remembered pick the composer
+ * offers a chat that stores no mode of its own. */
+ expect(await saveTurn(userId, conversationId, 'ask', [])).toBeUndefined();
+ expect(await saveTurn(userId, conversationId, 'fullAccess', [])).toBeUndefined();
+ expect(await saveTurn(userId, randomUUID(), undefined, [])).toBeUndefined();
+ expect(await saveTurn(userId, conversationId, 'acceptEdits', [['terra', permissive]])).toBe(
+ 'acceptEdits',
+ );
+ expect(await saveTurn(userId, conversationId, 'ask', [])).toBe('acceptEdits');
+ });
+
+ it('keeps the mode of a conversation the turn is saved under instead of the loaded one', async () => {
+ const userId = new mongoose.Types.ObjectId().toString();
+ const source = randomUUID();
+ const target = randomUUID();
+ const attached: Array<[string, AttachedCodeEnvironmentPolicySettings]> = [
+ ['terra', permissive],
+ ];
+
+ expect(await saveTurn(userId, source, 'fullAccess', attached)).toBe('fullAccess');
+ expect(await saveTurn(userId, target, 'acceptEdits', attached)).toBe('acceptEdits');
+ expect(await saveTurn(userId, target, 'ask', [], source)).toBe('acceptEdits');
+ expect((await store.getConvo(userId, source))?.codeApprovalMode).toBe('fullAccess');
+ });
+});
+
describe('saveTurnConversation reply stamp', () => {
const saveReply = async (reply: { content?: unknown; text?: string }) => {
const userId = new mongoose.Types.ObjectId().toString();
diff --git a/packages/api/src/conversations/save.ts b/packages/api/src/conversations/save.ts
index 6ba8cde2cb..df0c9a9827 100644
--- a/packages/api/src/conversations/save.ts
+++ b/packages/api/src/conversations/save.ts
@@ -36,6 +36,9 @@ export interface TurnConversationFields {
endpointOptions?: Partial<TConversation>;
/** The agent running the turn, recorded as the conversation's initial agent when persisted. */
agentId?: string;
+ /** Stored fields this write leaves as they are when `endpointOptions` omits them, instead of
+ * unsetting them: the turn made no decision about them. */
+ preservedFields?: ReadonlyArray<keyof TConversation>;
/** Logged by `saveConvo` to name the write. */
context: string;
}
@@ -105,14 +108,16 @@ function getUnsetFields(
existing: Partial<IConversation>,
endpointOptions: Partial<TConversation>,
agentOwned: boolean,
+ preservedFields: ReadonlyArray<keyof TConversation> = [],
): Record<string, number> {
const kept = new Set(['spec', 'iconURL']);
if (agentOwned) {
kept.add('model');
}
+ const preserved = new Set<string>(preservedFields);
const unsetFields: Record<string, number> = {};
for (const key of Object.keys(existing)) {
- if (excludedKeys.has(key) && !kept.has(key)) {
+ if ((excludedKeys.has(key) && !kept.has(key)) || preserved.has(key)) {
continue;
}
if (endpointOptions[key as keyof TConversation] === undefined) {
@@ -182,7 +187,10 @@ async function writeConversation(
},
{
context: write.context,
- unsetFields: existing != null ? getUnsetFields(existing, endpointOptions, agentOwned) : {},
+ unsetFields:
+ existing != null
+ ? getUnsetFields(existing, endpointOptions, agentOwned, write.preservedFields)
+ : {},
noUpsert: req?._agentEventBindingParentConversationId != null,
initialAgentId: agentOwned ? (write.agentId ?? null) : null,
createdAtOnInsert: inserting ? getCreatedAtOnInsert(req) : undefined,