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: Stop Sealing a Code Environment Decision a Chat Never Made (#16056)

lia-by-librechat[bot]1080f90bed06
diff --git a/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js b/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js
index 90b9c89a33..e4524db39a 100644
--- a/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js
+++ b/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js
@@ -67,6 +67,8 @@ jest.mock('@librechat/api', () => ({
resolveRunCodeWorkspaces: jest.requireActual('@librechat/api').resolveRunCodeWorkspaces,
shouldPersistCodeWorkspaceInitializationError:
jest.requireActual('@librechat/api').shouldPersistCodeWorkspaceInitializationError,
+ resolvePersistableCodeEnvironmentDecision: (...args) =>
+ jest.requireActual('@librechat/api').resolvePersistableCodeEnvironmentDecision(...args),
getSafeErrorMetadata: jest.requireActual('@librechat/api').getSafeErrorMetadata,
getSafeErrorText: jest.requireActual('@librechat/api').getSafeErrorText,
GenerationJobManager: mockGenerationJobManager,
diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
index d778f6b2e5..eebe5f3518 100644
--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
@@ -281,6 +281,8 @@ jest.mock('@librechat/api', () => ({
jest.requireActual('@librechat/api').getCodeWorkspaceSelectionErrorDetails,
shouldPersistCodeWorkspaceInitializationError:
jest.requireActual('@librechat/api').shouldPersistCodeWorkspaceInitializationError,
+ resolvePersistableCodeEnvironmentDecision: (...args) =>
+ jest.requireActual('@librechat/api').resolvePersistableCodeEnvironmentDecision(...args),
getSafeErrorMetadata: jest.requireActual('@librechat/api').getSafeErrorMetadata,
getSafeErrorText: jest.requireActual('@librechat/api').getSafeErrorText,
resolveFailedTurnContent: jest.requireActual('@librechat/api').resolveFailedTurnContent,
@@ -3999,6 +4001,68 @@ describe('ResumableAgentController resume metadata', () => {
expect.objectContaining({ initialAgentId: null }),
);
});
+
+ it('records the decision a failed turn of a saved chat ran under', async () => {
+ const codeWorkspaces = [{ environmentId: 'personal-vm', workspaceId: 'project-a' }];
+ const initializeClient = jest.fn().mockImplementation(async ({ req: request }) => {
+ request._codeEnvironmentDecision = { mode: 'attached', codeWorkspaces };
+ throw new Error('model unavailable');
+ });
+
+ await AgentController(
+ createFailedRequest(),
+ createResumableResponse(),
+ jest.fn(),
+ initializeClient,
+ null,
+ );
+
+ expect(mockSaveConvo).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: 'user-123' }),
+ { conversationId, codeEnvironmentMode: 'attached', codeWorkspaces },
+ expect.objectContaining({ noUpsert: true }),
+ );
+ });
+
+ it('does not rewrite the decision a chat already holds', async () => {
+ const req = createFailedRequest();
+ req.resolvedConversation = {
+ conversationId,
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }],
+ };
+ const initializeClient = jest.fn().mockImplementation(async ({ req: request }) => {
+ request._codeEnvironmentDecision = {
+ mode: 'attached',
+ codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-b' }],
+ };
+ throw new Error('model unavailable');
+ });
+
+ await AgentController(req, createResumableResponse(), jest.fn(), initializeClient, null);
+
+ expect(mockSaveConvo).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: 'user-123' }),
+ { conversationId },
+ expect.objectContaining({ noUpsert: true }),
+ );
+ });
+
+ it('leaves a saved chat undecided when the turn resolved no decision', async () => {
+ await AgentController(
+ createFailedRequest(),
+ createResumableResponse(),
+ jest.fn(),
+ jest.fn().mockRejectedValue(new Error('model unavailable')),
+ null,
+ );
+
+ expect(mockSaveConvo).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: 'user-123' }),
+ { conversationId },
+ expect.objectContaining({ noUpsert: true }),
+ );
+ });
});
it('finalizes the failed job before releasing the idempotency claim', async () => {
diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.js
index 9f9b5935d7..c1a4cfb389 100644
--- a/api/server/controllers/agents/request.js
+++ b/api/server/controllers/agents/request.js
@@ -45,6 +45,7 @@ const {
logAgentMemorySnapshot,
getCodeWorkspaceSelectionErrorDetails,
shouldPersistCodeWorkspaceInitializationError,
+ resolvePersistableCodeEnvironmentDecision,
getFailedTurnTraceFields,
resolveFailedTurnContent,
} = require('@librechat/api');
@@ -502,7 +503,16 @@ async function saveErrorTurn(
const agentId = endpointOption?.agent_id ?? req.body?.agent_id;
const chatProjectId = endpointOption?.chatProjectId ?? req.body?.chatProjectId;
const seedConvo = isNewConvo || req.resolvedConversation === null;
- const codeEnvironmentDecision = req._codeEnvironmentDecision;
+ /** A stored turn seals the decision it ran under, on a saved chat as much as on a new one: the
+ * error turn below enters the conversation, so leaving its validated decision out would let a
+ * retry choose a different workspace than the failure already recorded. The resolver the
+ * streaming saves already use decides what this turn may write, so an error turn and a
+ * completed one record a decision under one rule. */
+ const decisionFields = resolvePersistableCodeEnvironmentDecision({
+ conversationId,
+ decision: req._codeEnvironmentDecision,
+ conversation: req.resolvedConversation,
+ });
const convoFields = seedConvo
? {
...(endpoint != null && { endpoint }),
@@ -514,14 +524,9 @@ async function saveErrorTurn(
...(endpointOption?.spec != null && { spec: endpointOption.spec }),
...(agentId != null && { agent_id: agentId }),
...(typeof chatProjectId === 'string' && chatProjectId.length > 0 && { chatProjectId }),
- ...(codeEnvironmentDecision?.mode != null && {
- codeEnvironmentMode: codeEnvironmentDecision.mode,
- ...(codeEnvironmentDecision.codeWorkspaces != null && {
- codeWorkspaces: codeEnvironmentDecision.codeWorkspaces,
- }),
- }),
+ ...decisionFields,
}
- : {};
+ : decisionFields;
await saveConvo(
reqCtx,
{ conversationId, ...convoFields },
diff --git a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx
index 3121d292c9..b7ce0bf74a 100644
--- a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx
+++ b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx
@@ -126,7 +126,7 @@ describe('useCodeWorkspace', () => {
expect(result.current.resolveSubmission(undefined, 'without_attached')).toBeUndefined();
});
- it('uses an agent default ahead of the last used workspace only for new chats', () => {
+ it('uses an agent default ahead of the last used workspace while a chat is undecided', () => {
mockStatus()[0].data.workspaces.push({ id: 'project-b', name: 'Project B' });
mockAgentPermissions().agent.code_workspace_id = 'project-b';
mockPreference.mockReturnValue('project-a');
@@ -137,8 +137,12 @@ describe('useCodeWorkspace', () => {
},
);
expect(result.current.selections?.[0].workspaceId).toBe('project-b');
+ /* Saving the chat does not seal a decision it never recorded, so the default still applies and
+ * the composer still offers the choice. */
rerender({ id: 'existing' });
- expect(result.current.mode).toBe('without_attached');
+ expect(result.current.locked).toBe(false);
+ expect(result.current.mode).toBe('attached');
+ expect(result.current.selections?.[0].workspaceId).toBe('project-b');
expect(result.current.canSubmit).toBe(true);
});
@@ -646,18 +650,66 @@ describe('useCodeWorkspace', () => {
expect(result.current.relocation).toBeUndefined();
});
- it('does not auto-select a sole workspace the saved decision never covered', () => {
+ it('attaches a sole workspace to a saved chat that never recorded a decision', () => {
const { result } = renderHook(() =>
useCodeWorkspace({ ...conversation(), conversationId: 'existing' } as TConversation),
);
- expect(result.current.state).toBe('without_attached');
- expect(result.current.selections).toBeUndefined();
+ expect(result.current.locked).toBe(false);
+ expect(result.current.state).toBe('ready');
+ expect(result.current.selections).toEqual([
+ { environmentId: 'personal-vm', workspaceId: 'project-a' },
+ ]);
expect(result.current.resolveSubmission()).toEqual({
- codeEnvironmentMode: 'without_attached',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }],
});
});
+ /* Switching an existing chat to a coding agent used to leave the composer with a sealed
+ * decision its owner never made: nothing to select, and Send disabled. */
+ it.each([
+ { support: { codeEnvironmentDecisionVersion: 1 } },
+ { support: { codeEnvironmentDecisionVersion: 1, codeEnvironmentMoveVersion: 1 } },
+ ])('lets a saved chat with several workspaces choose one', ({ support }) => {
+ mockStartupConfig.mockReturnValue(support);
+ mockStatus()[0].data.workspaces.push({ id: 'project-b', name: 'Project B' });
+ const chosen = { environmentId: 'personal-vm', workspaceId: 'project-b' };
+
+ const { result } = renderHook(() =>
+ useCodeWorkspace({ ...conversation(), conversationId: 'existing' } as TConversation),
+ );
+
+ expect(result.current.locked).toBe(false);
+ expect(result.current.state).toBe('choose');
+ expect(result.current.relocation).toBeUndefined();
+ /* `useChatFunctions` submits the conversation's latest selections and mode together, the way
+ * the menu writes both when a workspace is picked. */
+ expect(result.current.resolveSubmission([chosen], 'attached')).toEqual({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [chosen],
+ });
+ });
+
+ /* A replica that predates the protocol reads a field-less row as sealed `without_attached`, so
+ * attaching an agent default here would submit a choice it rejects as `locked`. The rollout
+ * window keeps the legacy lock, which is what an unadvertised protocol means. */
+ it('keeps the legacy lock until the deployment advertises the protocol', () => {
+ mockStartupConfig.mockReturnValue({});
+ mockStatus()[0].data.workspaces.push({ id: 'project-b', name: 'Project B' });
+ mockAgentPermissions().agent.code_workspace_id = 'project-b';
+
+ const { result } = renderHook(() =>
+ useCodeWorkspace({ ...conversation(), conversationId: 'existing' } as TConversation),
+ );
+
+ expect(result.current.locked).toBe(true);
+ expect(result.current.mode).toBeUndefined();
+ expect(result.current.selections).toBeUndefined();
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.resolveSubmission()).toBeUndefined();
+ });
+
it('keeps auto-selecting for an API that does not seal decisions', () => {
mockStartupConfig.mockReturnValue({});
diff --git a/client/src/hooks/Agents/useCodeWorkspace.ts b/client/src/hooks/Agents/useCodeWorkspace.ts
index d862cfffa8..a104c5f44a 100644
--- a/client/src/hooks/Agents/useCodeWorkspace.ts
+++ b/client/src/hooks/Agents/useCodeWorkspace.ts
@@ -242,7 +242,22 @@ export default function useCodeWorkspace(
const isNewChat =
conversation != null &&
(conversation.conversationId == null || conversation.conversationId === 'new');
- const locked = conversation != null && !isNewChat;
+ /** Only a recorded decision is sealed. A saved chat whose turns never involved a code-capable
+ * agent stores none, so switching one to a coding agent still gets to choose; treating it as
+ * sealed leaves the composer showing a decision its owner never made, with no workspace to
+ * select and no way to submit.
+ *
+ * Until the deployment advertises the decision protocol, a replica that still reads a
+ * field-less row as a sealed `without_attached` may serve the next turn and reject an attached
+ * choice as `locked`, so the legacy lock stays for the whole rollout window. Nothing is lost by
+ * waiting: the composer only reports that unmade decision once the same flag is on. */
+ const holdsDecision =
+ conversation?.codeEnvironmentMode != null || (storedSelections?.length ?? 0) > 0;
+ const locked =
+ conversation != null && !isNewChat && (holdsDecision || !supportsEnvironmentDecisions);
+ /** A new chat and a saved chat that never decided are both still choosing, so agent defaults, a
+ * remembered selection, and a sole workspace apply to each. */
+ const undecided = conversation != null && !locked;
const environmentResults = attachedEnvironments.map((environment, index) => {
const status = statuses[index];
const workspaces =
@@ -251,7 +266,7 @@ export default function useCodeWorkspace(
: [];
let stored = storedSelections?.find(({ environmentId }) => environmentId === environment.id);
let conflictingDefaults = false;
- if (stored == null && isNewChat && !hasForeignStoredSelection) {
+ if (stored == null && undecided && !hasForeignStoredSelection) {
const defaults = workspaceMetadata.defaults.get(environment.id) ?? new Set<string>();
let preferred: string | undefined;
if (defaults.size === 1) preferred = [...defaults][0];
diff --git a/packages/api/src/code/decision.spec.ts b/packages/api/src/code/decision.spec.ts
index cd3a96e5d1..42d29df8f8 100644
--- a/packages/api/src/code/decision.spec.ts
+++ b/packages/api/src/code/decision.spec.ts
@@ -42,6 +42,27 @@ describe('resolveConversationCodeEnvironmentDecision', () => {
).toEqual({ mode: 'without_attached' });
});
+ /* A chat started by an agent that never ran code stores neither field. Sealing that state made
+ * switching it to a coding agent reject the first workspace its owner picked. */
+ it('lets a saved conversation that never decided establish a decision', () => {
+ expect(
+ resolveConversationCodeEnvironmentDecision({
+ conversationId: 'conversation-1',
+ requestedMode: 'attached',
+ requestedSelections: [selection],
+ conversation: { conversationId: 'conversation-1' },
+ }),
+ ).toEqual({ mode: 'attached', codeWorkspaces: [selection] });
+ expect(
+ resolveConversationCodeEnvironmentDecision({
+ conversationId: 'conversation-1',
+ requestedMode: 'attached',
+ requestedSelections: [selection],
+ conversation: { conversationId: 'conversation-1', codeWorkspaces: [] },
+ }),
+ ).toEqual({ mode: 'attached', codeWorkspaces: [selection] });
+ });
+
it('allows an identical retry of a persisted decision', () => {
expect(
resolveConversationCodeEnvironmentDecision({
@@ -253,6 +274,18 @@ describe('resolvePersistableCodeEnvironmentDecision', () => {
).toEqual({ codeEnvironmentMode: 'without_attached' });
});
+ it('records the whole decision a saved conversation establishes for the first time', () => {
+ /* Selections included: an `attached` mode stored without them fails the next turn's
+ * validation, which requires a non-empty selection set. */
+ expect(
+ resolvePersistableCodeEnvironmentDecision({
+ conversationId: 'conversation-1',
+ decision: { mode: 'attached', codeWorkspaces: [mac] },
+ conversation: { conversationId: 'conversation-1' },
+ }),
+ ).toEqual({ codeEnvironmentMode: 'attached', codeWorkspaces: [mac] });
+ });
+
it('never writes a run-start decision over a stored one that a move replaced', () => {
expect(
resolvePersistableCodeEnvironmentDecision({
diff --git a/packages/api/src/code/decision.ts b/packages/api/src/code/decision.ts
index f120032620..8c3880b496 100644
--- a/packages/api/src/code/decision.ts
+++ b/packages/api/src/code/decision.ts
@@ -49,7 +49,17 @@ function validateDecision(mode: unknown, selections: unknown): ConversationCodeE
return { mode, codeWorkspaces: canonicalSelections(selections) };
}
-/** A stored conversation always carries a decision; legacy rows infer it from their selections. */
+/**
+ * Whether the conversation already recorded a decision. A chat whose turns never involved a
+ * code-capable agent stores neither field, so it has nothing to seal: switching one to a coding
+ * agent still gets to decide. Sealing that state instead would report `without_attached` for a
+ * choice its owner never made, and reject the selection they go on to make.
+ */
+function holdsDecision(conversation: StoredConversationDecision): boolean {
+ return conversation.codeEnvironmentMode != null || (conversation.codeWorkspaces?.length ?? 0) > 0;
+}
+
+/** Reads the decision a conversation holds; legacy rows infer it from their selections. */
function readPersistedDecision(
conversation: StoredConversationDecision,
): ConversationCodeEnvironmentDecision {
@@ -71,7 +81,11 @@ export function resolveConversationCodeEnvironmentDecision({
requestedSelections?: unknown;
conversation?: StoredConversationDecision | null;
}): ConversationCodeEnvironmentDecision {
- if (conversation != null && conversation.conversationId === conversationId) {
+ if (
+ conversation != null &&
+ conversation.conversationId === conversationId &&
+ holdsDecision(conversation)
+ ) {
const persisted = readPersistedDecision(conversation);
if (requestedMode !== undefined && requestedMode !== persisted.mode) {
throw new CodeWorkspaceSelectionError('locked');
@@ -191,6 +205,11 @@ export function resolvePersistableCodeEnvironmentDecision({
if (conversation == null || conversation.conversationId !== conversationId) {
return candidate;
}
+ /* A saved chat that held no decision records the one this run establishes, selections included:
+ * writing the mode alone would leave `attached` without the selections the next turn validates. */
+ if (!holdsDecision(conversation)) {
+ return candidate;
+ }
if (conversation.codeEnvironmentMode != null || candidate.codeEnvironmentMode == null) {
return {};
}
diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.ts
index 5fa9ae689f..86c370d375 100644
--- a/packages/data-schemas/src/methods/conversation.spec.ts
+++ b/packages/data-schemas/src/methods/conversation.spec.ts
@@ -1144,21 +1144,70 @@ describe('Conversation Operations', () => {
expect(stored?.codeWorkspaces).toEqual([vm]);
});
- it.each([{}, { codeWorkspaces: [mac] }])(
- 'preserves a legacy decision: %j',
- async (decision) => {
- const conversationId = uuidv4();
- await Conversation.collection.insertOne({ conversationId, user: userId, ...decision });
- await saveConvo(
- { userId },
- { conversationId, codeEnvironmentMode: 'attached', codeWorkspaces: [vm] },
- { unsetFields },
- );
- const stored = await getConvo(userId, conversationId);
- expect(stored?.codeEnvironmentMode).toBeUndefined();
- expect(stored?.codeWorkspaces).toEqual(decision.codeWorkspaces);
- },
- );
+ it('preserves a legacy decision', async () => {
+ const conversationId = uuidv4();
+ await Conversation.collection.insertOne({
+ conversationId,
+ user: userId,
+ codeWorkspaces: [mac],
+ });
+ await saveConvo(
+ { userId },
+ { conversationId, codeEnvironmentMode: 'attached', codeWorkspaces: [vm] },
+ { unsetFields },
+ );
+ const stored = await getConvo(userId, conversationId);
+ expect(stored?.codeEnvironmentMode).toBeUndefined();
+ expect(stored?.codeWorkspaces).toEqual([mac]);
+ });
+
+ it('records the first decision of a saved chat that holds none', async () => {
+ const conversationId = uuidv4();
+ await Conversation.collection.insertOne({ conversationId, user: userId, title: 'Saved' });
+
+ const saved = await saveConvo(
+ { userId },
+ { conversationId, codeEnvironmentMode: 'attached', codeWorkspaces: [mac] },
+ { unsetFields },
+ );
+
+ expect(saved?.codeEnvironmentMode).toBe('attached');
+ expect(saved?.codeWorkspaces).toEqual([mac]);
+ const stored = await getConvo(userId, conversationId);
+ expect(stored?.codeEnvironmentMode).toBe('attached');
+ expect(stored?.codeWorkspaces).toEqual([mac]);
+ });
+
+ it('keeps the decision it recorded when a later turn resolves another', async () => {
+ const conversationId = uuidv4();
+ await Conversation.collection.insertOne({ conversationId, user: userId, title: 'Saved' });
+ await saveConvo(
+ { userId },
+ { conversationId, codeEnvironmentMode: 'attached', codeWorkspaces: [mac] },
+ { unsetFields },
+ );
+
+ await saveConvo(
+ { userId },
+ { conversationId, codeEnvironmentMode: 'without_attached', codeWorkspaces: [vm] },
+ { unsetFields },
+ );
+
+ const stored = await getConvo(userId, conversationId);
+ expect(stored?.codeEnvironmentMode).toBe('attached');
+ expect(stored?.codeWorkspaces).toEqual([mac]);
+ });
+
+ it('leaves a chat undecided when a save carries selections without a mode', async () => {
+ const conversationId = uuidv4();
+ await Conversation.collection.insertOne({ conversationId, user: userId, title: 'Saved' });
+
+ await saveConvo({ userId }, { conversationId, codeWorkspaces: [vm] }, { unsetFields });
+
+ const stored = await getConvo(userId, conversationId);
+ expect(stored?.codeEnvironmentMode).toBeUndefined();
+ expect(stored?.codeWorkspaces).toBeUndefined();
+ });
});
describe('replaceConvoCodeEnvironmentDecision', () => {
diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.ts
index 36b7f365f2..ec719499cb 100644
--- a/packages/data-schemas/src/methods/conversation.ts
+++ b/packages/data-schemas/src/methods/conversation.ts
@@ -2417,6 +2417,31 @@ export function createConversationMethods(
return null;
}
+ /** `$setOnInsert` only reaches a chat this save creates, yet a chat whose earlier turns never
+ * involved a code-capable agent holds no decision either: without this fill its first
+ * workspace choice is dropped and the next turn starts undecided again. The filter repeats
+ * that absence, so a concurrent writer that decided first keeps its decision and a chat that
+ * already holds one is never touched. Only a whole decision seeds a row, never bare
+ * selections. */
+ if (
+ decisionOnInsert.codeEnvironmentMode != null &&
+ conversation.codeEnvironmentMode == null &&
+ (conversation.codeWorkspaces?.length ?? 0) === 0
+ ) {
+ const seeded = await Conversation.updateOne(
+ {
+ _id: conversation._id,
+ codeEnvironmentMode: { $in: [null] },
+ $or: [{ codeWorkspaces: { $in: [null] } }, { codeWorkspaces: { $size: 0 } }],
+ },
+ { $set: decisionOnInsert },
+ { timestamps: false },
+ );
+ if (seeded.modifiedCount > 0) {
+ Object.assign(conversation, decisionOnInsert);
+ }
+ }
+
/** Reuse the saved row's chat type when callers omit it, preserving existing deadlines. */
if (
interfaceConfig?.retentionMode === RetentionMode.ALL &&