🖋️ feat: Seal Code Environment Choices Per Conversation (#15868)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions

* feat: lock code environments per conversation

* style: Sort code environment imports

* fix: Harden code environment decisions

* fix: Preserve code environment rollout compatibility

* fix: Harden code environment boundaries

* refactor: Centralize code environment policy

* test: Restore partial disconnect policy mock

* fix: Close code environment edge paths

* fix: Preserve implicit stateful code routes

* fix: Stabilize implicit code routing

* test: Align remote workspace contract

* chore: Sort code route import
This commit is contained in:
Danny Avila 2026-09-12 20:45:00 -04:00 • committed by GitHub
parent 19eb24921e
commit 1163045cef
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
60 changed files with 1843 additions and 300 deletions

View file

@ -444,6 +444,39 @@ describe('resolveCodeExecutionWorkspaceContext', () => {
});
});
it('accepts an equivalent retry regardless of selection order', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue(workspaceStatus([{ id: 'project-a' }]));
const personal = { environmentId: 'personal', workspaceId: 'project-a' };
const team = { environmentId: 'team', workspaceId: 'project-b' };
await expect(
resolveCodeExecutionWorkspaceContext({
context,
requestedSelections: [team, personal],
persistedSelections: [personal, team],
environments,
getAppConfig,
}),
).resolves.toMatchObject({ codeWorkspace: personal });
});
it('rejects a request that changes a persisted workspace before contacting Code API', async () => {
const fetchSpy = jest
.spyOn(globalThis, 'fetch')
.mockRejectedValue(new Error('Unexpected status request'));
await expect(
resolveCodeExecutionWorkspaceContext({
context,
requestedSelections: [{ environmentId: 'personal', workspaceId: 'project-b' }],
persistedSelections: [{ environmentId: 'personal', workspaceId: 'project-a' }],
environments,
getAppConfig,
}),
).rejects.toMatchObject({ reason: 'locked' });
expect(fetchSpy).not.toHaveBeenCalled();
});
it('fails when the saved workspace disappears instead of selecting another', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue(workspaceStatus([{ id: 'replacement' }]));

View file

@ -29,7 +29,9 @@ function codeWorkspaceSelectionErrorMessage(reason: CodeWorkspaceSelectionErrorR
case 'unsupported':
return 'The attached code environment does not advertise selectable workspaces. Update the LibreChat Code worker and try again.';
case 'missing':
return 'The selected workspace is no longer registered on this machine. Choose another workspace explicitly or restore the previous registration.';
return 'The selected workspace is no longer registered on this machine. Restore the previous registration or start a new conversation.';
case 'locked':
return 'This conversation already has a different code environment decision.';
}
}
@ -44,6 +46,28 @@ export class CodeWorkspaceSelectionError extends Error {
}
}
function canonicalWorkspaceSelections(
selections: CodeWorkspaceSelection[],
): CodeWorkspaceSelection[] {
return [...selections].sort((left, right) => {
if (left.environmentId < right.environmentId) return -1;
if (left.environmentId > right.environmentId) return 1;
if (left.workspaceId < right.workspaceId) return -1;
if (left.workspaceId > right.workspaceId) return 1;
return 0;
});
}
function sameWorkspaceSelections(
left: CodeWorkspaceSelection[],
right: CodeWorkspaceSelection[],
): boolean {
return (
JSON.stringify(canonicalWorkspaceSelections(left)) ===
JSON.stringify(canonicalWorkspaceSelections(right))
);
}
async function readAuthorizedAttachedWorkerStatus(
context: CodeExecutionContext,
environments: readonly CodeEnvironmentConfig[] | undefined,
@ -91,12 +115,7 @@ async function readAuthorizedAttachedWorkerStatus(
});
}
/**
* Resolves a conversation preference into a live worker capability. Request
* state wins so a user can deliberately change directories on this turn;
* persisted state supplies reconnect and non-browser clients. Neither path is
* trusted until the worker confirms the exact environment/workspace pair.
*/
/** Resolves an immutable conversation selection into a live worker capability. */
export async function resolveCodeExecutionWorkspaceContext({
context,
requestedSelections,
@ -111,8 +130,16 @@ export async function resolveCodeExecutionWorkspaceContext({
getAppConfig?: CodeCapabilityConfigLoader;
}): Promise<CodeExecutionContext> {
if (context.environmentType !== 'attached') return context;
const rawSelections =
requestedSelections === undefined ? persistedSelections : requestedSelections;
if (
persistedSelections !== undefined &&
requestedSelections !== undefined &&
(!isCodeWorkspaceSelections(persistedSelections) ||
!isCodeWorkspaceSelections(requestedSelections) ||
!sameWorkspaceSelections(persistedSelections, requestedSelections))
) {
throw new CodeWorkspaceSelectionError('locked');
}
const rawSelections = persistedSelections ?? requestedSelections;
if (rawSelections == null) {
throw new CodeWorkspaceSelectionError('required');
}

View file

@ -1,6 +1,31 @@
import { EModelEndpoint } from 'librechat-data-provider';
import type { AppConfig } from '@librechat/data-schemas';
import { mergeAccessibleCodeEnvironments } from './config';
import {
isImplicitStatefulCodeRouteAvailable,
mergeAccessibleCodeEnvironments,
resolveCodeEnvironmentDecisionVersion,
} from './config';
describe('resolveCodeEnvironmentDecisionVersion', () => {
it('advertises the exact supported protocol version', () => {
expect(resolveCodeEnvironmentDecisionVersion('1')).toBe(1);
});
it.each([undefined, '0', '2', '1.0', 'true'])(
'keeps unsupported configured version %s on the legacy-safe path',
(version) => {
expect(resolveCodeEnvironmentDecisionVersion(version)).toBeUndefined();
},
);
});
describe('isImplicitStatefulCodeRouteAvailable', () => {
it('requires both the deployed protocol version and a non-empty managed base URL', () => {
expect(isImplicitStatefulCodeRouteAvailable('1', 'https://code.example/v1')).toBe(true);
expect(isImplicitStatefulCodeRouteAvailable(undefined, 'https://code.example/v1')).toBe(false);
expect(isImplicitStatefulCodeRouteAvailable('1', ' ')).toBe(false);
});
});
describe('mergeAccessibleCodeEnvironments', () => {
test('adds principal environments without allowing them to shadow deployment entries', async () => {

View file

@ -1,5 +1,5 @@
import { logger } from '@librechat/data-schemas';
import { EModelEndpoint } from 'librechat-data-provider';
import { CODE_ENVIRONMENT_DECISION_VERSION, EModelEndpoint } from 'librechat-data-provider';
import type { AppConfig } from '@librechat/data-schemas';
import type {
AccessibleCodeEnvironmentConfiguration,
@ -18,6 +18,29 @@ type StatefulCodeConfig = NonNullable<
>['statefulCodeSessions'];
type CodeEnvironmentConfig = NonNullable<NonNullable<StatefulCodeConfig>['environments']>[number];
/**
* Resolves the deployment-wide browser protocol gate. The exact version match
* keeps older and future wire shapes on the legacy-safe path.
*/
export function resolveCodeEnvironmentDecisionVersion(
configuredVersion?: string,
): typeof CODE_ENVIRONMENT_DECISION_VERSION | undefined {
return configuredVersion === String(CODE_ENVIRONMENT_DECISION_VERSION)
? CODE_ENVIRONMENT_DECISION_VERSION
: undefined;
}
/** Enables the implicit managed route only after the versioned rollout is complete. */
export function isImplicitStatefulCodeRouteAvailable(
configuredVersion?: string,
statefulBaseURL?: string,
): boolean {
return (
resolveCodeEnvironmentDecisionVersion(configuredVersion) != null &&
(statefulBaseURL?.trim().length ?? 0) > 0
);
}
function isExecutableCodeEnvironment(environment: CodeEnvironmentConfig): boolean {
return !(
environment.pairing?.allowPrincipalWorkers === true &&

View file

@ -0,0 +1,123 @@
import { resolveConversationCodeEnvironmentDecision } from './decision';
import { CodeWorkspaceSelectionError } from './capabilities';
const selection = { environmentId: 'personal-vm', workspaceId: 'project-a' };
describe('resolveConversationCodeEnvironmentDecision', () => {
it('defaults a new conversation without a selection to no attached environment', () => {
expect(resolveConversationCodeEnvironmentDecision({ conversationId: 'new' })).toEqual({
mode: 'without_attached',
});
});
it('accepts and canonicalizes a new attached decision', () => {
expect(
resolveConversationCodeEnvironmentDecision({
conversationId: 'new',
requestedMode: 'attached',
requestedSelections: [{ environmentId: 'team-vm', workspaceId: 'project-b' }, selection],
}),
).toEqual({
mode: 'attached',
codeWorkspaces: [selection, { environmentId: 'team-vm', workspaceId: 'project-b' }],
});
});
it('infers legacy persisted decisions', () => {
expect(
resolveConversationCodeEnvironmentDecision({
conversationId: 'conversation-1',
conversation: { conversationId: 'conversation-1', codeWorkspaces: [selection] },
}),
).toEqual({ mode: 'attached', codeWorkspaces: [selection] });
expect(
resolveConversationCodeEnvironmentDecision({
conversationId: 'conversation-1',
conversation: { conversationId: 'conversation-1' },
}),
).toEqual({ mode: 'without_attached' });
});
it('allows an identical retry of a persisted decision', () => {
expect(
resolveConversationCodeEnvironmentDecision({
conversationId: 'conversation-1',
requestedMode: 'attached',
requestedSelections: [selection],
conversation: {
conversationId: 'conversation-1',
codeEnvironmentMode: 'attached',
codeWorkspaces: [selection],
},
}),
).toEqual({ mode: 'attached', codeWorkspaces: [selection] });
});
it.each([
{
requestedMode: 'without_attached',
requestedSelections: undefined,
},
{
requestedMode: 'attached',
requestedSelections: [{ environmentId: 'personal-vm', workspaceId: 'project-b' }],
},
])('rejects a conflicting change to a persisted attached decision', (requested) => {
expect(() =>
resolveConversationCodeEnvironmentDecision({
conversationId: 'conversation-1',
...requested,
conversation: {
conversationId: 'conversation-1',
codeEnvironmentMode: 'attached',
codeWorkspaces: [selection],
},
}),
).toThrow(expect.objectContaining<Partial<CodeWorkspaceSelectionError>>({ reason: 'locked' }));
});
it('rejects attaching a workspace to a conversation locked without one', () => {
expect(() =>
resolveConversationCodeEnvironmentDecision({
conversationId: 'conversation-1',
requestedMode: 'attached',
requestedSelections: [selection],
conversation: {
conversationId: 'conversation-1',
codeEnvironmentMode: 'without_attached',
},
}),
).toThrow(expect.objectContaining<Partial<CodeWorkspaceSelectionError>>({ reason: 'locked' }));
});
it('rejects contradictory decision fields', () => {
expect(() =>
resolveConversationCodeEnvironmentDecision({
conversationId: 'new',
requestedMode: 'without_attached',
requestedSelections: [selection],
}),
).toThrow(expect.objectContaining<Partial<CodeWorkspaceSelectionError>>({ reason: 'invalid' }));
expect(() =>
resolveConversationCodeEnvironmentDecision({
conversationId: 'new',
requestedMode: 'attached',
}),
).toThrow(
expect.objectContaining<Partial<CodeWorkspaceSelectionError>>({ reason: 'required' }),
);
});
it('rejects an invalid persisted mode instead of treating it as attached', () => {
expect(() =>
resolveConversationCodeEnvironmentDecision({
conversationId: 'conversation-1',
conversation: {
conversationId: 'conversation-1',
codeEnvironmentMode: 'future-mode' as never,
codeWorkspaces: [selection],
},
}),
).toThrow(expect.objectContaining<Partial<CodeWorkspaceSelectionError>>({ reason: 'invalid' }));
});
});

View file

@ -0,0 +1,104 @@
import { isCodeEnvironmentMode, isCodeWorkspaceSelections } from 'librechat-data-provider';
import type {
CodeEnvironmentMode,
CodeWorkspaceSelection,
TConversation,
} from 'librechat-data-provider';
import { CodeWorkspaceSelectionError } from './capabilities';
export interface ConversationCodeEnvironmentDecision {
mode: CodeEnvironmentMode;
codeWorkspaces?: CodeWorkspaceSelection[];
}
type StoredConversationDecision = Pick<
TConversation,
'conversationId' | 'codeEnvironmentMode' | 'codeWorkspaces'
>;
function canonicalSelections(selections: CodeWorkspaceSelection[]): CodeWorkspaceSelection[] {
return [...selections].sort((left, right) => {
if (left.environmentId < right.environmentId) return -1;
if (left.environmentId > right.environmentId) return 1;
if (left.workspaceId < right.workspaceId) return -1;
if (left.workspaceId > right.workspaceId) return 1;
return 0;
});
}
function sameSelections(left: CodeWorkspaceSelection[], right: CodeWorkspaceSelection[]): boolean {
return JSON.stringify(canonicalSelections(left)) === JSON.stringify(canonicalSelections(right));
}
function validateDecision(mode: unknown, selections: unknown): ConversationCodeEnvironmentDecision {
if (!isCodeEnvironmentMode(mode)) {
throw new CodeWorkspaceSelectionError('invalid');
}
if (mode === 'without_attached') {
if (
selections !== undefined &&
(!isCodeWorkspaceSelections(selections) || selections.length > 0)
) {
throw new CodeWorkspaceSelectionError('invalid');
}
return { mode };
}
if (!isCodeWorkspaceSelections(selections) || selections.length === 0) {
throw new CodeWorkspaceSelectionError('required');
}
return { mode, codeWorkspaces: canonicalSelections(selections) };
}
/** Resolves one immutable conversation choice before attached tools are registered. */
export function resolveConversationCodeEnvironmentDecision({
conversationId,
requestedMode,
requestedSelections,
conversation,
}: {
conversationId: string;
requestedMode?: unknown;
requestedSelections?: unknown;
conversation?: StoredConversationDecision | null;
}): ConversationCodeEnvironmentDecision {
const ownsConversation = conversation != null && conversation.conversationId === conversationId;
const persistedMode = ownsConversation ? conversation.codeEnvironmentMode : undefined;
const persistedSelections = ownsConversation ? conversation.codeWorkspaces : undefined;
let inferredPersistedMode: unknown = persistedMode;
if (inferredPersistedMode == null && ownsConversation) {
inferredPersistedMode = persistedSelections?.length ? 'attached' : 'without_attached';
}
if (inferredPersistedMode != null) {
const persisted = validateDecision(inferredPersistedMode, persistedSelections);
if (requestedMode !== undefined && requestedMode !== persisted.mode) {
throw new CodeWorkspaceSelectionError('locked');
}
if (
persisted.mode === 'attached' &&
requestedSelections !== undefined &&
(!isCodeWorkspaceSelections(requestedSelections) ||
!sameSelections(requestedSelections, persisted.codeWorkspaces ?? []))
) {
throw new CodeWorkspaceSelectionError('locked');
}
if (
persisted.mode === 'without_attached' &&
requestedSelections !== undefined &&
(!isCodeWorkspaceSelections(requestedSelections) || requestedSelections.length > 0)
) {
throw new CodeWorkspaceSelectionError('locked');
}
return persisted;
}
if (requestedMode !== undefined && !isCodeEnvironmentMode(requestedMode)) {
throw new CodeWorkspaceSelectionError('invalid');
}
const mode =
requestedMode ??
(isCodeWorkspaceSelections(requestedSelections) && requestedSelections.length > 0
? 'attached'
: 'without_attached');
return validateDecision(mode, requestedSelections);
}

View file

@ -1,5 +1,8 @@
import { ErrorTypes } from 'librechat-data-provider';
import { getCodeWorkspaceSelectionErrorDetails } from './errors';
import {
getCodeWorkspaceSelectionErrorDetails,
shouldPersistCodeWorkspaceInitializationError,
} from './errors';
describe('getCodeWorkspaceSelectionErrorDetails', () => {
it.each(['required', 'invalid', 'worker_unavailable', 'unsupported', 'missing'] as const)(
@ -23,3 +26,40 @@ describe('getCodeWorkspaceSelectionErrorDetails', () => {
expect(getCodeWorkspaceSelectionErrorDetails(error)).toEqual({});
});
});
describe('shouldPersistCodeWorkspaceInitializationError', () => {
it('keeps a rejected first-turn decision retryable', () => {
expect(
shouldPersistCodeWorkspaceInitializationError({
streamStarted: true,
isNewConversation: true,
failureCode: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,
hasValidatedDecision: false,
}),
).toBe(false);
});
it.each([
{ isNewConversation: false, hasValidatedDecision: false },
{ isNewConversation: true, hasValidatedDecision: true },
])('persists an initialized workspace failure for %o', (state) => {
expect(
shouldPersistCodeWorkspaceInitializationError({
streamStarted: true,
failureCode: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,
...state,
}),
).toBe(true);
});
it('does not persist any initialization error before the stream starts', () => {
expect(
shouldPersistCodeWorkspaceInitializationError({
streamStarted: false,
isNewConversation: false,
failureCode: 'MODEL_UNAVAILABLE',
hasValidatedDecision: true,
}),
).toBe(false);
});
});

View file

@ -21,3 +21,29 @@ export function getCodeWorkspaceSelectionErrorDetails(
}
return { reason: error.reason };
}
/**
* A rejected decision must remain retryable. Publishing the generation error
* is safe, but persisting a first-turn conversation without a validated
* decision would turn the retry into a locked legacy conversation.
*/
export function shouldPersistCodeWorkspaceInitializationError({
streamStarted,
isNewConversation,
failureCode,
hasValidatedDecision,
}: {
streamStarted: boolean;
isNewConversation: boolean;
failureCode?: string;
hasValidatedDecision: boolean;
}): boolean {
if (!streamStarted) {
return false;
}
return !(
isNewConversation &&
failureCode === ErrorTypes.CODE_WORKSPACE_UNAVAILABLE &&
!hasValidatedDecision
);
}

View file

@ -6,4 +6,5 @@ export * from './lifecycle';
export * from './workspace';
export * from './command';
export * from './capabilities';
export * from './decision';
export * from './errors';

View file

@ -4,29 +4,36 @@ import { validateRequest } from '../agents/openai/service';
const selections = [{ environmentId: 'machine', workspaceId: 'project' }];
describe('remote workspace selection envelopes', () => {
it.each([
[
'chat completions',
(code_workspaces: unknown) =>
validateRequest({
model: 'agent',
messages: [{ role: 'user', content: 'hello' }],
code_workspaces,
}),
],
[
'responses',
(code_workspaces: unknown) =>
validateResponseRequest({ model: 'agent', input: 'hello', code_workspaces }),
],
] as const)(
'validates %s selection identity without accepting duplicate environments',
(_name, validate) => {
expect(validate(selections).valid).toBe(true);
expect(validate([...selections, ...selections]).valid).toBe(false);
expect(validate([{ ...selections[0], path: '/secret' }]).valid).toBe(false);
},
);
it('rejects workspace extensions on chat completions, which cannot persist the decision', () => {
expect(
validateRequest({
model: 'agent',
messages: [{ role: 'user', content: 'hello' }],
code_workspaces: selections,
}).valid,
).toBe(false);
});
it('validates responses selection identity without accepting duplicate environments', () => {
expect(
validateResponseRequest({ model: 'agent', input: 'hello', code_workspaces: selections })
.valid,
).toBe(true);
expect(
validateResponseRequest({
model: 'agent',
input: 'hello',
code_workspaces: [...selections, ...selections],
}).valid,
).toBe(false);
expect(
validateResponseRequest({
model: 'agent',
input: 'hello',
code_workspaces: [{ ...selections[0], path: '/secret' }],
}).valid,
).toBe(false);
});
it('carries selections into the runtime envelope', () => {
expect(
createMCPRuntimeRequestBody({