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

🧲 feat: Attach or Leave a Workspace on a Saved Chat (#16124)

lia-by-librechat[bot]7b2362d7a7c6
diff --git a/.github/workflows/workspace-acceptance.yml b/.github/workflows/workspace-acceptance.yml
new file mode 100644
index 0000000000..bd1c0a7aaf
--- /dev/null
+++ b/.github/workflows/workspace-acceptance.yml
@@ -0,0 +1,90 @@
+name: Native Workspace Acceptance
+
+on:
+ pull_request:
+ branches: [dev]
+ paths:
+ - 'e2e/byom/**'
+ - '.github/workflows/workspace-acceptance.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: workspace-acceptance-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ workspace:
+ name: Saved chat attach and offline detach (macOS)
+ runs-on: macos-latest
+ timeout-minutes: 25
+ env:
+ PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1'
+ HOMEBREW_NO_AUTO_UPDATE: '1'
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ persist-credentials: false
+
+ # Run the native worker unchanged, with Seatbelt and its real ownership checks.
+ # Pin the external fixture so this acceptance result has a reproducible worker revision.
+ - uses: actions/checkout@v5
+ with:
+ repository: LibreChat-AI/code-interpreter
+ ref: 67d75d859aee891923c40cde1db073489d74a424
+ path: .native-code
+ persist-credentials: false
+
+ - uses: actions/setup-node@v5
+ with:
+ node-version: '24.16.0'
+ cache: npm
+
+ - name: Install native prerequisites
+ run: |
+ brew list redis >/dev/null 2>&1 || brew install redis
+ brew list ripgrep >/dev/null 2>&1 || brew install ripgrep
+ command -v sandbox-exec
+ command -v redis-server
+ command -v rg
+
+ - name: Install and build LibreChat
+ env:
+ VITE_ENABLE_LOGGER: 'true'
+ VITE_LOGGER_FILTER: conversation,ResumableSSE
+ run: |
+ npm ci
+ npm run e2e:prepare
+ npx playwright install chromium
+
+ - name: Build the real Code API and worker
+ run: |
+ npm ci --prefix .native-code/packages/code
+ npm run build --prefix .native-code/packages/code
+ npm install --prefix .native-code/service --no-audit --no-fund
+ npm run build --prefix .native-code/service
+ cp .native-code/service/src/matplotlib-async.py .native-code/service/.build-service/src/matplotlib-async.py
+
+ - name: Exercise saved-chat workspace transitions
+ env:
+ BYOM_WORKSPACE_TRANSITIONS: 'true'
+ BYOM_CODE_REPO: ${{ github.workspace }}/.native-code
+ run: node e2e/byom/run.mjs
+
+ # The native harness retains private identities and cookies for local debugging.
+ # Never upload its run directory, raw logs, or browser storage state from CI.
+ - name: Record acceptance scope
+ if: always()
+ env:
+ RESULT: ${{ job.status }}
+ HEAD: ${{ github.event.pull_request.head.sha || github.sha }}
+ run: |
+ {
+ echo '### Native workspace acceptance'
+ echo "Head: \`$HEAD\`"
+ echo "Result: $RESULT"
+ echo 'Scope: saved chat, agent switch without implicit access, no-workspace send/reload, explicit attach, approved native command, offline detach, continued chat/reload.'
+ echo 'Worker: `67d75d859aee891923c40cde1db073489d74a424`. Platform: macOS Seatbelt. No Linux/WSL certification.'
+ } >> "$GITHUB_STEP_SUMMARY"
diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.js
index 8659082215..96e9b463bd 100644
--- a/api/server/controllers/agents/__tests__/openai.spec.js
+++ b/api/server/controllers/agents/__tests__/openai.spec.js
@@ -230,17 +230,8 @@ jest.mock('@librechat/api', () => ({
buildInitialToolSessions: jest.fn().mockReturnValue(mockInitialSessions),
AgentRunEnvelopeError: MockAgentRunEnvelopeError,
createAgentRunEnvelope: (...args) => mockCreateAgentRunEnvelope(...args),
- resolveConversationCodeEnvironmentDecision: ({
- requestedMode,
- requestedSelections,
- conversation,
- }) => {
- const codeWorkspaces = requestedSelections ?? conversation?.codeWorkspaces;
- return {
- mode: requestedMode ?? (codeWorkspaces?.length ? 'attached' : 'without_attached'),
- ...(codeWorkspaces !== undefined && { codeWorkspaces }),
- };
- },
+ resolveAdmittedCodeEnvironmentDecision: (...args) =>
+ jest.requireActual('@librechat/api').resolveAdmittedCodeEnvironmentDecision(...args),
createMCPRuntimeRequestBody: ({
messageId,
conversationId,
@@ -485,6 +476,7 @@ jest.mock('~/models', () => ({
getConvoFiles: jest.fn().mockResolvedValue([]),
getFormattedMemories: jest.fn().mockResolvedValue({ withKeys: '', withoutKeys: '' }),
getConvo: jest.fn().mockResolvedValue(null),
+ readAdmittedConvoCodeEnvironmentDecision: jest.fn().mockResolvedValue(null),
isSubagentOwnerAdmissible: jest.fn().mockResolvedValue(true),
}));
@@ -1508,11 +1500,19 @@ describe('OpenAIChatCompletionController', () => {
});
describe('conversation ownership validation', () => {
- it.each([false, true])(
- 'propagates explicit or owned persisted workspaces: continuation=%s',
- async (continuation) => {
+ it.each([
+ [false, false],
+ [true, false],
+ [false, true],
+ [true, true],
+ ])(
+ 'propagates explicit or owned persisted workspaces: continuation=%s moves=%s',
+ async (continuation, movesEnabled) => {
const api = require('@librechat/api');
const selections = [{ environmentId: 'machine', workspaceId: 'project' }];
+ req.config.endpoints.agents.statefulCodeSessions = {
+ conversationMoves: { enabled: movesEnabled },
+ };
api.validateRequest.mockReturnValueOnce({
request: {
model: 'agent-123',
@@ -1526,7 +1526,15 @@ describe('OpenAIChatCompletionController', () => {
conversationId: 'convo-abc',
codeWorkspaces: selections,
});
+ if (continuation && movesEnabled)
+ require('~/models').readAdmittedConvoCodeEnvironmentDecision.mockResolvedValueOnce({
+ conversationId: 'convo-abc',
+ codeWorkspaces: selections,
+ });
await OpenAIChatCompletionController(req, res);
+ const fencedRead = require('~/models').readAdmittedConvoCodeEnvironmentDecision;
+ if (movesEnabled) expect(fencedRead).toHaveBeenCalledTimes(1);
+ else expect(fencedRead).not.toHaveBeenCalled();
expect(api.initializeAgent).toHaveBeenCalledWith(
expect.objectContaining({
requestBody: expect.objectContaining({ codeWorkspaces: selections }),
diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.js
index 1eb14ff974..e8b1f2e7ab 100644
--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js
+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js
@@ -252,17 +252,8 @@ jest.mock('@librechat/api', () => ({
})),
AgentRunEnvelopeError: MockAgentRunEnvelopeError,
createAgentRunEnvelope: (...args) => mockCreateAgentRunEnvelope(...args),
- resolveConversationCodeEnvironmentDecision: ({
- requestedMode,
- requestedSelections,
- conversation,
- }) => {
- const codeWorkspaces = requestedSelections ?? conversation?.codeWorkspaces;
- return {
- mode: requestedMode ?? (codeWorkspaces?.length ? 'attached' : 'without_attached'),
- ...(codeWorkspaces !== undefined && { codeWorkspaces }),
- };
- },
+ resolveAdmittedCodeEnvironmentDecision: (...args) =>
+ jest.requireActual('@librechat/api').resolveAdmittedCodeEnvironmentDecision(...args),
resolvePersistableCodeEnvironmentDecision: (...args) =>
jest.requireActual('@librechat/api').resolvePersistableCodeEnvironmentDecision(...args),
getCodeWorkspaceSelections: jest.fn(),
@@ -568,6 +559,7 @@ jest.mock('~/models', () => ({
getFormattedMemories: jest.fn().mockResolvedValue({ withKeys: '', withoutKeys: '' }),
saveConvo: jest.fn().mockResolvedValue({}),
getConvo: jest.fn().mockResolvedValue(null),
+ readAdmittedConvoCodeEnvironmentDecision: jest.fn().mockResolvedValue(null),
isSubagentOwnerAdmissible: jest.fn().mockResolvedValue(true),
}));
@@ -614,11 +606,19 @@ describe('createResponse controller', () => {
};
});
- it.each([false, true])(
- 'passes explicit or owner-loaded workspace selections to runtime: continuation=%s',
- async (continuation) => {
+ it.each([
+ [false, false],
+ [true, false],
+ [false, true],
+ [true, true],
+ ])(
+ 'passes explicit or owner-loaded workspace selections to runtime: continuation=%s moves=%s',
+ async (continuation, movesEnabled) => {
const api = require('@librechat/api');
const selections = [{ environmentId: 'machine', workspaceId: 'project' }];
+ req.config.endpoints.agents.statefulCodeSessions = {
+ conversationMoves: { enabled: movesEnabled },
+ };
const request = {
model: 'agent-123',
input: 'Hello',
@@ -631,7 +631,15 @@ describe('createResponse controller', () => {
conversationId: 'previous',
codeWorkspaces: selections,
});
+ if (continuation && movesEnabled)
+ require('~/models').readAdmittedConvoCodeEnvironmentDecision.mockResolvedValueOnce({
+ conversationId: 'previous',
+ codeWorkspaces: selections,
+ });
await createResponse(req, res);
+ const fencedRead = require('~/models').readAdmittedConvoCodeEnvironmentDecision;
+ if (movesEnabled) expect(fencedRead).toHaveBeenCalledTimes(1);
+ else expect(fencedRead).not.toHaveBeenCalled();
expect(api.initializeAgent).toHaveBeenCalledWith(
expect.objectContaining({
requestBody: expect.objectContaining({ codeWorkspaces: selections }),
diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js
index 23fa533a1d..0aa760bcc4 100644
--- a/api/server/controllers/agents/openai.js
+++ b/api/server/controllers/agents/openai.js
@@ -72,7 +72,7 @@ const {
executeAgentRun,
waitForAgentExecutionWrites,
resolveToolRoleGrants,
- resolveConversationCodeEnvironmentDecision,
+ resolveAdmittedCodeEnvironmentDecision,
createTerminalRunErrorObserver,
} = require('@librechat/api');
const {
@@ -465,12 +465,16 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {
req.resolvedConversation = conversation;
}
- const codeEnvironmentDecision = resolveConversationCodeEnvironmentDecision({
- conversationId,
- requestedMode: request.code_environment_mode,
- requestedSelections: request.code_workspaces,
- conversation: req.resolvedConversation,
- });
+ const { decision: codeEnvironmentDecision, conversation: admittedConversation } =
+ await resolveAdmittedCodeEnvironmentDecision({
+ appConfig,
+ conversation: req.resolvedConversation,
+ conversationId,
+ requestedMode: request.code_environment_mode,
+ requestedSelections: request.code_workspaces,
+ readDecision: (id) => db.readAdmittedConvoCodeEnvironmentDecision(principal.userId, id),
+ });
+ req.resolvedConversation = admittedConversation;
const parentMessageId = request.parent_message_id ?? null;
let mcpParentMessageId;
if (
diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js
index f09f292dd6..64f64237a0 100644
--- a/api/server/controllers/agents/responses.js
+++ b/api/server/controllers/agents/responses.js
@@ -85,7 +85,7 @@ const {
executeAgentRun,
waitForAgentExecutionWrites,
resolveToolRoleGrants,
- resolveConversationCodeEnvironmentDecision,
+ resolveAdmittedCodeEnvironmentDecision,
resolvePersistableCodeEnvironmentDecision,
createTerminalRunErrorObserver,
} = require('@librechat/api');
@@ -716,12 +716,16 @@ const executeResponse = async (envelope, { req, res }) => {
}
}
- const codeEnvironmentDecision = resolveConversationCodeEnvironmentDecision({
- conversationId,
- requestedMode: request.code_environment_mode,
- requestedSelections: request.code_workspaces,
- conversation: req.resolvedConversation,
- });
+ const { decision: codeEnvironmentDecision, conversation: admittedConversation } =
+ await resolveAdmittedCodeEnvironmentDecision({
+ appConfig,
+ conversation: req.resolvedConversation,
+ conversationId,
+ requestedMode: request.code_environment_mode,
+ requestedSelections: request.code_workspaces,
+ readDecision: (id) => db.readAdmittedConvoCodeEnvironmentDecision(principal.userId, id),
+ });
+ req.resolvedConversation = admittedConversation;
const parentMessageId = null;
const mcpRequestBody = createMCPRuntimeRequestBody({
messageId: responseId,
diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.js
index 78a09b7a7a..82c714873b 100644
--- a/api/server/routes/__tests__/config.spec.js
+++ b/api/server/routes/__tests__/config.spec.js
@@ -371,7 +371,7 @@ describe('GET /api/config', () => {
agents: {
statefulCodeSessions: {
allowedEnvironments: ['user'],
- conversationMoves: { enabled: true },
+ conversationMoves: { enabled: true, allowAttachDetach: true },
},
},
},
@@ -384,6 +384,8 @@ describe('GET /api/config', () => {
expect(response.body.codeEnvironmentDecisionVersion).toBeUndefined();
// An already-open V1 client compares this value against its compiled literal 1.
expect(response.body.codeEnvironmentMoveVersion).toBe(1);
+ /** Attach and detach ride the same policy on their own number. */
+ expect(response.body.codeEnvironmentTransitionVersion).toBe(2);
expect(response.body.codeWorkspaceRecoveryVersion).toBe(1);
});
diff --git a/api/server/routes/code-environments.js b/api/server/routes/code-environments.js
index c771b98dcf..3cc88e6d6a 100644
--- a/api/server/routes/code-environments.js
+++ b/api/server/routes/code-environments.js
@@ -21,7 +21,7 @@ function getHandlers() {
registry: getCodeEnvironmentRegistry(),
principalIsActive: db.isAgentTriggerPrincipalActive,
conversations: {
- get: db.getConvo,
+ get: db.getConvoCodeEnvironmentDecision,
replaceDecision: db.replaceConvoCodeEnvironmentDecision,
},
generations: GenerationJobManager,
diff --git a/api/server/routes/code-environments.test.js b/api/server/routes/code-environments.test.js
index c236a0ddb2..d6029cc964 100644
--- a/api/server/routes/code-environments.test.js
+++ b/api/server/routes/code-environments.test.js
@@ -45,7 +45,7 @@ const mockGenerationJobManager = {
let mockHandlerDeps;
const mockModels = {
isAgentTriggerPrincipalActive: jest.fn(),
- getConvo: jest.fn(),
+ getConvoCodeEnvironmentDecision: jest.fn(),
replaceConvoCodeEnvironmentDecision: jest.fn(),
};
@@ -164,7 +164,7 @@ describe('code environment routes', () => {
await request(createApp()).get('/api/code-environments').expect(200);
const { conversations, generations } = mockHandlerDeps;
- expect(conversations.get).toBe(mockModels.getConvo);
+ expect(conversations.get).toBe(mockModels.getConvoCodeEnvironmentDecision);
expect(conversations.replaceDecision).toBe(mockModels.replaceConvoCodeEnvironmentDecision);
expect(generations).toBe(mockGenerationJobManager);
});
diff --git a/api/server/routes/config.js b/api/server/routes/config.js
index fd7359d285..d3e3682ab4 100644
--- a/api/server/routes/config.js
+++ b/api/server/routes/config.js
@@ -14,6 +14,7 @@ const {
getEndpointsDropParamsMap,
resolveCodeEnvironmentDecisionVersion,
resolveCodeEnvironmentMoveCapabilities,
+ resolveCodeEnvironmentTransitionVersion,
} = require('@librechat/api');
const { EModelEndpoint, defaultSocialLogins } = require('librechat-data-provider');
const { logger, getTenantId, SystemCapabilities } = require('@librechat/data-schemas');
@@ -255,6 +256,7 @@ router.get('/', async function (req, res) {
process.env.CODE_ENVIRONMENT_DECISION_VERSION,
);
const codeEnvironmentMoveCapabilities = resolveCodeEnvironmentMoveCapabilities(appConfig);
+ const codeEnvironmentTransitionVersion = resolveCodeEnvironmentTransitionVersion(appConfig);
const endpointsDropParamsMap = getEndpointsDropParamsMap(appConfig?.endpoints);
@@ -317,6 +319,7 @@ router.get('/', async function (req, res) {
compactionEnabled: appConfig?.summarization?.enabled !== false,
...(codeEnvironmentDecisionVersion != null ? { codeEnvironmentDecisionVersion } : {}),
...codeEnvironmentMoveCapabilities,
+ ...(codeEnvironmentTransitionVersion != null ? { codeEnvironmentTransitionVersion } : {}),
...(cloudFront ? { cloudFront } : {}),
...(rum ? { rum } : {}),
fileUploadSseEnabled: isEnabled(process.env.FILE_UPLOAD_SSE_ENABLED),
diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js
index 31782af1b0..94dc2e5b33 100644
--- a/api/server/services/Endpoints/agents/initialize.js
+++ b/api/server/services/Endpoints/agents/initialize.js
@@ -3,7 +3,7 @@ const { createContentAggregator, GraphNodeKeys } = require('@librechat/agents');
const {
resolveSender,
resolveRunConversation,
- resolveConversationCodeEnvironmentDecision,
+ resolveAdmittedCodeEnvironmentDecision,
createConcurrencyLimiter,
loadSkillStates,
initializeAgent,
@@ -607,12 +607,16 @@ const initializeClientWithProvider = async ({
]);
/** Preserve the owner-scoped fallback for loaders that share this request. */
req.resolvedConversation = requestConversation;
- const codeEnvironmentDecision = resolveConversationCodeEnvironmentDecision({
- conversationId,
- requestedMode: runtimeRequestBody?.codeEnvironmentMode,
- requestedSelections: runtimeRequestBody?.codeWorkspaces,
- conversation: requestConversation,
- });
+ const { decision: codeEnvironmentDecision, conversation: admittedConversation } =
+ await resolveAdmittedCodeEnvironmentDecision({
+ appConfig,
+ conversation: requestConversation,
+ conversationId,
+ requestedMode: runtimeRequestBody?.codeEnvironmentMode,
+ requestedSelections: runtimeRequestBody?.codeWorkspaces,
+ readDecision: (id) => db.readAdmittedConvoCodeEnvironmentDecision(req.user.id, id),
+ });
+ req.resolvedConversation = admittedConversation;
/** Trusted, normalized pair used by every persistence path, including init failures. */
req._codeEnvironmentDecision = codeEnvironmentDecision;
runtimeRequestBody = {
@@ -1130,7 +1134,7 @@ const initializeClientWithProvider = async ({
? await resolveCodeExecutionWorkspaceContext({
context: baseCodeExecutionContext,
requestedSelections: runtimeRequestBody?.codeWorkspaces,
- persistedSelections: requestConversation?.codeWorkspaces,
+ persistedSelections: admittedConversation?.codeWorkspaces,
environments: configuredCodeEnvironments,
getAppConfig,
})
diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.js
index b93442123f..b68966d1b8 100644
--- a/api/server/services/Endpoints/agents/initialize.spec.js
+++ b/api/server/services/Endpoints/agents/initialize.spec.js
@@ -1637,17 +1637,19 @@ describe('initializeClient — subagent loading', () => {
});
it.each([
- [true, 'request'],
- [false, 'request'],
- [true, 'fallback'],
- [true, 'override'],
- [true, 'override-resolved'],
- [true, 'resolved'],
- [false, 'resolved-null'],
- [false, 'other-owner'],
+ [true, 'request', false],
+ [false, 'request', false],
+ [true, 'fallback', false],
+ [true, 'override', false],
+ [true, 'override-resolved', false],
+ [true, 'resolved', false],
+ [true, 'moved', true],
+ [false, 'resolved-null', false],
+ [true, 'resolved-null', true],
+ [false, 'other-owner', false],
])(
- 'validates the lazy subagent workspace before exposure: registered=%s source=%s',
- async (registered, source) => {
+ 'validates the lazy subagent workspace before exposure: registered=%s source=%s moves=%s',
+ async (registered, source, movesEnabled) => {
const subAgent = await createAgent({
id: SUBAGENT_ID,
name: 'Attached Stateful Subagent',
@@ -1669,6 +1671,7 @@ describe('initializeClient — subagent loading', () => {
req.config.endpoints.agents.capabilities.push('execute_code', 'stateful_code_sessions');
req.config.endpoints.agents.statefulCodeSessions = {
allowedEnvironments: ['agent-user'],
+ conversationMoves: { enabled: movesEnabled },
environments: [
{
id: 'attached-vm',
@@ -1694,7 +1697,12 @@ describe('initializeClient — subagent loading', () => {
codeWorkspaces: req.body.codeWorkspaces,
});
delete req.body.codeWorkspaces;
- if (source === 'resolved') req.resolvedConversation = conversation.toObject();
+ if (source === 'moved') {
+ req.resolvedConversation = {
+ ...conversation.toObject(),
+ codeWorkspaces: [{ environmentId: 'old-machine', workspaceId: 'old-project' }],
+ };
+ } else if (source === 'resolved') req.resolvedConversation = conversation.toObject();
else if (source !== 'resolved-null') delete req.resolvedConversation;
if (source.startsWith('override')) {
conversation.codeWorkspaces = [
@@ -1734,6 +1742,7 @@ describe('initializeClient — subagent loading', () => {
}),
),
);
+ const readSpy = jest.spyOn(db, 'readAdmittedConvoCodeEnvironmentDecision');
try {
const initialization = initializeClient({
req,
@@ -1742,7 +1751,8 @@ describe('initializeClient — subagent loading', () => {
signal: new AbortController().signal,
endpointOption: makeEndpointOption(),
});
- const defaultsWithoutAttached = source === 'resolved-null' || source === 'other-owner';
+ const defaultsWithoutAttached =
+ source === 'other-owner' || (source === 'resolved-null' && !movesEnabled);
if (!registered && !defaultsWithoutAttached) {
await expect(initialization).rejects.toMatchObject({
code: ErrorTypes.CODE_WORKSPACE_UNAVAILABLE,
@@ -1751,6 +1761,12 @@ describe('initializeClient — subagent loading', () => {
return;
}
await initialization;
+ if (movesEnabled)
+ expect(readSpy).toHaveBeenCalledWith(
+ req.user.id,
+ requestBody?.conversationId ?? req.body.conversationId,
+ );
+ else expect(readSpy).not.toHaveBeenCalled();
if (defaultsWithoutAttached) {
expect(fetchSpy).not.toHaveBeenCalled();
expect(agentClientArgs.mcpRequestBody).toEqual(
@@ -1781,6 +1797,7 @@ describe('initializeClient — subagent loading', () => {
}
} finally {
fetchSpy.mockRestore();
+ readSpy.mockRestore();
delete process.env.TEST_LAZY_WORKSPACE_TOKEN;
}
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index cba6cc5e49..f23fb61ffa 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -666,8 +666,7 @@ const ChatForm = memo(function ChatForm({
onRestoreToComposer={restoreReclaimedSteer}
/>
)}
- {(project ||
- (codeWorkspace.required && (!codeWorkspace.locked || !codeWorkspace.canSubmit))) && (
+ {(project || codeWorkspace.visible) && (
<div
data-testid="composer-context-rail"
className={cn(
@@ -677,7 +676,7 @@ const ChatForm = memo(function ChatForm({
)}
>
{project ? <ProjectLandingChip project={project} /> : null}
- {codeWorkspace.required && (!codeWorkspace.locked || !codeWorkspace.canSubmit) ? (
+ {codeWorkspace.visible ? (
<div className="min-w-0 px-1 pt-1">
<CodeWorkspaceMenu
setConversation={setConversation}
diff --git a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx
index 6646ef5a5f..bee6dcc538 100644
--- a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx
+++ b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx
@@ -6,13 +6,14 @@ import type { CodeWorkspaceSelection, TConversation } from 'librechat-data-provi
import type { SetterOrUpdater } from 'recoil';
import type {
CodeWorkspaceEnvironmentResult,
- CodeWorkspaceRelocation,
CodeWorkspaceResult,
+ CodeWorkspaceTransition,
TranslationKeys,
} from '~/hooks';
import {
useCodeWorkspaceRefresh,
useMoveConversationCodeEnvironmentMutation,
+ useReconcileConversationCodeEnvironmentMutation,
} from '~/data-provider';
import {
cn,
@@ -23,6 +24,7 @@ import {
import { useLocalize } from '~/hooks';
const stateLabels: Partial<Record<CodeWorkspaceResult['state'], TranslationKeys>> = {
+ not_required: 'com_ui_code_workspace',
loading: 'com_ui_code_workspace_loading',
choose: 'com_ui_code_workspace_choose',
missing: 'com_ui_code_workspace_missing',
@@ -41,8 +43,8 @@ const menuItemClasses = (selected = false) =>
selected && 'bg-surface-active-alt',
);
-/** A stale view of the decision recovers on reload; the other reasons explain themselves. */
-function moveErrorKey(error: unknown): TranslationKeys {
+/** Conflicts refresh the decision; definitive rejections keep their specific explanation. */
+function transitionErrorKey(error: unknown): TranslationKeys {
const reason = getCodeWorkspaceErrorReason(error);
if (reason === 'locked') return 'com_ui_code_workspace_move_stale';
if (reason != null) return codeWorkspaceErrorKeys[reason];
@@ -50,29 +52,41 @@ function moveErrorKey(error: unknown): TranslationKeys {
return 'com_ui_code_workspace_move_error';
}
-function describeRelocation(
- relocation: CodeWorkspaceRelocation,
+function describeTransition(
+ transition: CodeWorkspaceTransition,
localize: ReturnType<typeof useLocalize>,
): { label: string; info: string } {
- if (relocation.targets.some(({ state }) => state === 'missing')) {
+ if (transition.targets.some(({ state }) => state === 'missing')) {
return {
label: localize('com_ui_code_workspace_recover'),
info: localize('com_ui_code_workspace_recover_info'),
};
}
- const targetNames = relocation.targets
+ const targetNames = transition.targets
.map(({ environment }) => environment.name ?? environment.id)
.join(', ');
- const previousNames = relocation.previous.map(({ id, name }) => name ?? id).join(', ');
+ if (transition.kind === 'attach') {
+ return {
+ label:
+ transition.targets.length === 1
+ ? localize('com_ui_code_workspace_attach_to', { 0: targetNames })
+ : localize('com_ui_code_workspace_attach'),
+ info: localize('com_ui_code_workspace_attach_info'),
+ };
+ }
+ const previousNames = transition.previous.map(({ id, name }) => name ?? id).join(', ');
let info = localize('com_ui_code_workspace_move_info', { 0: previousNames, 1: targetNames });
- if (relocation.targets.length === 0) {
+ if (transition.targets.length === 0 && !previousNames) {
+ /** Nothing to move onto and nothing the agents dropped: the machine itself is the problem. */
+ info = localize('com_ui_code_workspace_detach_prompt');
+ } else if (transition.targets.length === 0) {
info = localize('com_ui_code_workspace_move_info_removed', { 0: previousNames });
} else if (!previousNames) {
info = localize('com_ui_code_workspace_move_info_added', { 0: targetNames });
}
return {
label:
- relocation.targets.length === 1
+ transition.targets.length === 1
? localize('com_ui_code_workspace_move_to', { 0: targetNames })
: localize('com_ui_code_workspace_move'),
info,
@@ -176,16 +190,41 @@ export default function CodeWorkspaceMenu({
const { showToast } = useToastContext();
const menuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' });
const isOpen = menuStore.useState('open');
- const moveMutation = useMoveConversationCodeEnvironmentMutation();
+ const moveMutation = useMoveConversationCodeEnvironmentMutation(setConversation);
+ const reconcileMutation = useReconcileConversationCodeEnvironmentMutation(setConversation);
const { refresh, isRefreshing } = useCodeWorkspaceRefresh();
const [moveDraft, setMoveDraft] = useState<{
conversationId: string;
workspaces: Record<string, string>;
} | null>(null);
- if (!workspace.required) return null;
+ if (!workspace.visible) return null;
- const { relocation } = workspace;
+ if (workspace.recovery != null) {
+ const { request, status } = workspace.recovery;
+ const pending = status === 'pending';
+ return (
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <span role="status" className="text-xs text-text-secondary">
+ {localize(
+ pending
+ ? 'com_ui_code_workspace_reconciling'
+ : 'com_ui_code_workspace_reconcile_failed',
+ )}
+ </span>
+ <button
+ type="button"
+ className={composerControlClasses()}
+ disabled={disabled || pending || reconcileMutation.isLoading}
+ onClick={() => reconcileMutation.mutate(request)}
+ >
+ {localize('com_ui_code_workspace_reconcile_retry')}
+ </button>
+ </div>
+ );
+ }
+
+ const { transition } = workspace;
const environmentIds = new Set(workspace.environments.map(({ environment }) => environment.id));
const selectWorkspace = (selection: CodeWorkspaceSelection) => {
workspace.rememberSelection(selection);
@@ -215,6 +254,47 @@ export default function CodeWorkspaceMenu({
},
);
};
+ const transitionText = transition == null ? null : describeTransition(transition, localize);
+ /** Choices belong to the chat they were made in; another transitionable chat starts undecided. */
+ const moveChoices =
+ transition != null && moveDraft?.conversationId === transition.conversationId
+ ? moveDraft.workspaces
+ : {};
+ /** Every target needs a workspace, so the whole transition lands in one validated write. */
+ const chosenTargets =
+ transition?.targets.flatMap((target) => {
+ const workspaceId = chosenWorkspaceId(target, moveChoices);
+ return workspaceId == null ? [] : [{ environmentId: target.environment.id, workspaceId }];
+ }) ?? [];
+ /** A transition replaces the whole decision, so an empty target set is the detach and gets its
+ * own item: this one only confirms a decision that still names at least one workspace. */
+ const proposed = transition == null ? [] : [...transition.retained, ...chosenTargets];
+ const offersMove =
+ transition != null && (transition.targets.length > 0 || transition.retained.length > 0);
+ const moveReady =
+ transition != null && chosenTargets.length === transition.targets.length && proposed.length > 0;
+ const applyTransition = (to: CodeWorkspaceSelection[]) => {
+ if (transition == null || disabled || moveMutation.isLoading) return;
+ moveMutation.mutate(
+ { conversationId: transition.conversationId, from: transition.from, to },
+ {
+ onSuccess: () => {
+ to.forEach((selection) => workspace.rememberSelection(selection));
+ setMoveDraft(null);
+ },
+ onError: (error) => {
+ showToast({ message: localize(transitionErrorKey(error)), status: 'error' });
+ },
+ },
+ );
+ };
+ const confirmMove = () => {
+ if (!moveReady) return;
+ applyTransition(proposed);
+ };
+ /** An empty target set is the detach: the chat keeps its history and continues without a
+ * workspace, instead of waiting on a machine it cannot reach. */
+ const confirmDetach = () => applyTransition([]);
const onlyEnvironment = workspace.environments.length === 1 ? workspace.environments[0] : null;
const onlyDescriptor = onlyEnvironment?.workspaces.find(
({ id }) => id === onlyEnvironment.selected?.workspaceId,
@@ -238,9 +318,14 @@ export default function CodeWorkspaceMenu({
? FolderX
: Folder;
- if (workspace.locked && relocation == null) {
- if (workspace.canSubmit) return null;
- const recovery = localize('com_ui_code_workspace_locked_recovery');
+ if (workspace.locked && transition == null) {
+ /** A sealed decision with no transition on offer only reports where this chat runs: without a
+ * workspace by its own recorded choice, or on a machine that needs attention. Whether that is
+ * worth showing at all is `visible`, above. */
+ const recovery =
+ workspace.mode === 'without_attached'
+ ? localize('com_ui_code_workspace_without_attached_info')
+ : localize('com_ui_code_workspace_locked_recovery');
return (
<TooltipAnchor
description={recovery}
@@ -265,59 +350,27 @@ export default function CodeWorkspaceMenu({
);
}
- const relocationText = relocation == null ? null : describeRelocation(relocation, localize);
- /** Choices belong to the chat they were made in; another relocatable chat starts undecided. */
- const moveChoices =
- relocation != null && moveDraft?.conversationId === relocation.conversationId
- ? moveDraft.workspaces
- : {};
- /** Every target needs a workspace, so the whole move lands in one validated write. */
- const chosenTargets =
- relocation?.targets.flatMap((target) => {
- const workspaceId = chosenWorkspaceId(target, moveChoices);
- return workspaceId == null ? [] : [{ environmentId: target.environment.id, workspaceId }];
- }) ?? [];
- const moveReady = relocation != null && chosenTargets.length === relocation.targets.length;
- const confirmMove = () => {
- if (relocation == null || !moveReady || disabled || moveMutation.isLoading) return;
- moveMutation.mutate(
- {
- conversationId: relocation.conversationId,
- from: relocation.from,
- to: [...relocation.retained, ...chosenTargets],
- },
- {
- onSuccess: ({ conversationId, codeEnvironmentMode, codeWorkspaces }) => {
- chosenTargets.forEach((selection) => workspace.rememberSelection(selection));
- setMoveDraft(null);
- setConversation((current) =>
- current?.conversationId === conversationId
- ? { ...current, codeEnvironmentMode, codeWorkspaces }
- : current,
- );
- },
- onError: (error) => {
- showToast({ message: localize(moveErrorKey(error)), status: 'error' });
- },
- },
- );
- };
const buttonDisabled = disabled || moveMutation.isLoading;
- const ButtonIcon = relocationText == null ? Icon : FolderSync;
+ /** Only a move renames the control, because it replaces the machine the chat already runs on.
+ * Attaching and detaching keep naming the current state, which is what their menu changes. */
+ const renamesForMove = transition?.kind === 'move' && offersMove && transitionText != null;
+ const ButtonIcon = renamesForMove ? FolderSync : Icon;
+ const ConfirmIcon = transition?.kind === 'attach' ? Folder : FolderSync;
+ const buttonLabel = renamesForMove ? transitionText.label : label;
return (
<Ariakit.MenuProvider store={menuStore}>
<TooltipAnchor
- description={relocationText?.info ?? localize('com_ui_code_workspace')}
+ description={transitionText?.info ?? localize('com_ui_code_workspace')}
disabled={isOpen}
render={
<Ariakit.MenuButton
disabled={buttonDisabled}
- data-testid={relocationText == null ? 'code-workspace' : 'code-workspace-move'}
+ data-testid={renamesForMove ? 'code-workspace-move' : 'code-workspace'}
aria-label={
- relocationText == null
+ transitionText == null
? `${localize('com_ui_code_workspace')}: ${label}`
- : `${relocationText.label}. ${relocationText.info}`
+ : `${buttonLabel}. ${transitionText.info}`
}
className={cn(
composerControlClasses(),
@@ -329,7 +382,7 @@ export default function CodeWorkspaceMenu({
}
>
<ButtonIcon className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
- <span className="min-w-0 max-w-[12rem] truncate">{relocationText?.label ?? label}</span>
+ <span className="min-w-0 max-w-[12rem] truncate">{buttonLabel}</span>
<ChevronDown
className={cn(
'size-3 shrink-0 text-text-secondary transition-transform',
@@ -350,13 +403,13 @@ export default function CodeWorkspaceMenu({
'scale-95 data-[leave]:scale-95 data-[leave]:opacity-0',
)}
>
- {relocation != null && relocationText != null ? (
+ {transition != null && transitionText != null ? (
<>
<Ariakit.MenuHeading render={<div />} className={headingClasses}>
- {relocationText.label}
+ {transitionText.label}
</Ariakit.MenuHeading>
- <p className="px-2.5 pb-2 text-xs text-text-secondary">{relocationText.info}</p>
- {relocation.targets.map((target) => (
+ <p className="px-2.5 pb-2 text-xs text-text-secondary">{transitionText.info}</p>
+ {transition.targets.map((target) => (
<EnvironmentWorkspaces
key={target.environment.id}
environment={target.environment}
@@ -366,27 +419,54 @@ export default function CodeWorkspaceMenu({
isSelected={(workspaceId) => chosenWorkspaceId(target, moveChoices) === workspaceId}
onSelect={({ environmentId, workspaceId }) =>
setMoveDraft({
- conversationId: relocation.conversationId,
+ conversationId: transition.conversationId,
workspaces: { ...moveChoices, [environmentId]: workspaceId },
})
}
/>
))}
<Ariakit.MenuSeparator className="my-1 h-0 w-full border-t border-border-light" />
- <Ariakit.MenuItem
- disabled={disabled || !moveReady || moveMutation.isLoading}
- hideOnClick={true}
- onClick={confirmMove}
- className={cn(
- menuItemClasses(),
- 'items-center aria-disabled:cursor-not-allowed aria-disabled:opacity-50',
- )}
- >
- <FolderSync className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
- <span className="min-w-0 flex-1 truncate text-left text-sm font-medium text-text-primary">
- {relocationText.label}
- </span>
- </Ariakit.MenuItem>
+ {offersMove && (
+ <Ariakit.MenuItem
+ disabled={disabled || !moveReady || moveMutation.isLoading}
+ hideOnClick={true}
+ onClick={confirmMove}
+ className={cn(
+ menuItemClasses(),
+ 'items-center aria-disabled:cursor-not-allowed aria-disabled:opacity-50',
+ )}
+ >
+ <ConfirmIcon className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
+ <span className="min-w-0 flex-1 truncate text-left text-sm font-medium text-text-primary">
+ {transitionText.label}
+ </span>
+ </Ariakit.MenuItem>
+ )}
+ {transition.detachable && (
+ <Ariakit.MenuItem
+ data-testid="code-workspace-detach"
+ disabled={disabled || moveMutation.isLoading}
+ hideOnClick={true}
+ onClick={confirmDetach}
+ className={cn(
+ menuItemClasses(),
+ 'aria-disabled:cursor-not-allowed aria-disabled:opacity-50',
+ )}
+ >
+ <FolderX
+ className="mt-0.5 size-4 shrink-0 text-text-secondary"
+ aria-hidden="true"
+ />
+ <div className="min-w-0 flex-1 text-left">
+ <div className="truncate text-sm font-medium text-text-primary">
+ {localize('com_ui_code_workspace_detach')}
+ </div>
+ <p className="text-xs text-text-secondary">
+ {localize('com_ui_code_workspace_detach_info')}
+ </p>
+ </div>
+ </Ariakit.MenuItem>
+ )}
</>
) : (
<>
diff --git a/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx b/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx
index 2765297bc4..c4a96b70ea 100644
--- a/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx
@@ -1,4 +1,5 @@
import { AxiosError } from 'axios';
+import { Provider, createStore } from 'jotai';
import userEvent from '@testing-library/user-event';
import { dataService } from 'librechat-data-provider';
import { render, screen, waitFor } from '@testing-library/react';
@@ -6,6 +7,8 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TConversation } from 'librechat-data-provider';
import type { AxiosResponse } from 'axios';
import type { CodeWorkspaceResult } from '~/hooks';
+import { codeEnvironmentReconciliationsAtom } from '~/store/codeEnvironmentReconciliation';
+import { useConversationCodeEnvironmentRecovery } from '~/data-provider';
import CodeWorkspaceMenu from '../CodeWorkspaceMenu';
const mockShowToast = jest.fn();
@@ -57,6 +60,7 @@ function workspace(overrides: Partial<CodeWorkspaceResult> = {}): CodeWorkspaceR
mode: 'attached',
state: 'ready',
canSubmit: true,
+ visible: true,
environments: [
{
environment,
@@ -88,6 +92,62 @@ function renderMenu(ui: React.ReactElement) {
}
describe('CodeWorkspaceMenu', () => {
+ test('explains a failed reconciliation and retries without permitting workspace changes', async () => {
+ const store = createStore();
+ const request = {
+ conversationId: 'existing',
+ attempted: {
+ codeEnvironmentMode: 'attached' as const,
+ codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }],
+ },
+ };
+ store.set(
+ codeEnvironmentReconciliationsAtom,
+ new Map([['existing', { request, status: 'error', token: Symbol() }]]),
+ );
+ let resolveRead!: (value: TConversation) => void;
+ const read = jest.spyOn(dataService, 'getConversationById').mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveRead = resolve;
+ }),
+ );
+ const setter = jest.fn();
+ function RecoveryMenu() {
+ const recovery = useConversationCodeEnvironmentRecovery('existing');
+ return (
+ <CodeWorkspaceMenu
+ setConversation={setter}
+ workspace={workspace({ visible: recovery != null, recovery })}
+ disabled={false}
+ />
+ );
+ }
+ renderMenu(
+ <Provider store={store}>
+ <RecoveryMenu />
+ </Provider>,
+ );
+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_code_workspace_reconcile_failed');
+ expect(screen.queryByTestId('code-workspace')).not.toBeInTheDocument();
+ await userEvent.click(
+ screen.getByRole('button', { name: 'com_ui_code_workspace_reconcile_retry' }),
+ );
+ await waitFor(() => expect(read).toHaveBeenCalledWith('existing'));
+ expect(
+ screen.getByRole('button', { name: 'com_ui_code_workspace_reconcile_retry' }),
+ ).toBeDisabled();
+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_code_workspace_reconciling');
+ resolveRead({
+ ...conversation,
+ conversationId: 'existing',
+ codeEnvironmentMode: 'without_attached',
+ });
+ await waitFor(() => expect(screen.queryByRole('status')).not.toBeInTheDocument());
+ expect(setter).toHaveBeenCalledTimes(1);
+ read.mockRestore();
+ });
+
test('shows loading rather than the inferred no-workspace fallback on first load', () => {
renderMenu(
<CodeWorkspaceMenu
@@ -265,12 +325,13 @@ describe('CodeWorkspaceMenu', () => {
renderMenu(
<CodeWorkspaceMenu
setConversation={jest.fn()}
- workspace={workspace({ locked: true })}
+ workspace={workspace({ locked: true, visible: false })}
disabled={false}
/>,
);
expect(screen.queryByTestId('code-workspace')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('code-workspace-locked-status')).not.toBeInTheDocument();
});
test('shows recovery status when a locked workspace is unavailable', () => {
@@ -295,6 +356,173 @@ describe('CodeWorkspaceMenu', () => {
);
});
+ test('explains a chat that recorded running without a workspace and cannot attach one', () => {
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={jest.fn()}
+ workspace={workspace({
+ locked: true,
+ mode: 'without_attached',
+ state: 'without_attached',
+ selections: undefined,
+ })}
+ disabled={false}
+ />,
+ );
+
+ expect(screen.getByTestId('code-workspace-locked-status')).toHaveAccessibleName(
+ 'com_ui_code_workspace_without_attached. com_ui_code_workspace_without_attached_info. com_ui_retry',
+ );
+ });
+
+ describe('a saved chat that has been running without a workspace', () => {
+ const attached = { environmentId: environment.id, workspaceId: 'project-a' };
+ const sealed = { ...conversation, conversationId: 'existing' } as TConversation;
+ const attachable = (rememberSelection = jest.fn()) =>
+ workspace({
+ locked: true,
+ mode: 'without_attached',
+ state: 'without_attached',
+ selections: undefined,
+ rememberSelection,
+ environments: [
+ {
+ environment,
+ state: 'choose',
+ workspaces: [{ id: 'project-a', name: 'Project A' }],
+ selected: undefined,
+ },
+ ],
+ transition: {
+ kind: 'attach',
+ conversationId: 'existing',
+ from: [],
+ previous: [],
+ retained: [],
+ detachable: false,
+ targets: [
+ {
+ environment,
+ state: 'choose',
+ workspaces: [{ id: 'project-a', name: 'Project A' }],
+ selected: undefined,
+ },
+ ],
+ },
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ test('attaches a workspace while still naming where the chat runs', async () => {
+ const moveSpy = jest.spyOn(dataService, 'moveConversationCodeEnvironment').mockResolvedValue({
+ conversationId: 'existing',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [attached],
+ });
+ const setConversation = jest.fn();
+ const rememberSelection = jest.fn();
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={setConversation}
+ workspace={attachable(rememberSelection)}
+ disabled={false}
+ />,
+ );
+
+ /** The control keeps reading "no attached workspace"; attaching one is what it offers. */
+ const chip = screen.getByTestId('code-workspace');
+ expect(chip).toHaveTextContent('com_ui_code_workspace_without_attached');
+ await userEvent.click(chip);
+ expect(screen.getByText('com_ui_code_workspace_attach_info')).toBeInTheDocument();
+ expect(
+ screen.queryByRole('menuitem', { name: /com_ui_code_workspace_detach/ }),
+ ).not.toBeInTheDocument();
+ await userEvent.click(
+ await screen.findByRole('menuitem', { name: /com_ui_code_workspace_attach/ }),
+ );
+
+ await waitFor(() => expect(moveSpy).toHaveBeenCalledTimes(1));
+ expect(moveSpy).toHaveBeenCalledWith({
+ conversationId: 'existing',
+ from: [],
+ to: [attached],
+ });
+ expect(rememberSelection).toHaveBeenCalledWith(attached);
+ const update = setConversation.mock.calls[0][0];
+ expect(update(sealed)).toEqual({
+ ...sealed,
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [attached],
+ });
+ });
+ });
+
+ describe('a chat sealed to a machine it can no longer reach', () => {
+ const mac = { environmentId: 'mac', workspaceId: 'primary' };
+ const sealed = { ...conversation, conversationId: 'existing' } as TConversation;
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ test.each(['offline', 'no-longer-used'])(
+ 'continues without the %s workspace',
+ async (scenario) => {
+ const moveSpy = jest
+ .spyOn(dataService, 'moveConversationCodeEnvironment')
+ .mockResolvedValue({
+ conversationId: 'existing',
+ codeEnvironmentMode: 'without_attached',
+ });
+ const setConversation = jest.fn();
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={setConversation}
+ workspace={workspace({
+ locked: true,
+ required: scenario === 'offline',
+ canSubmit: scenario !== 'offline',
+ state: scenario === 'offline' ? 'unavailable' : 'not_required',
+ selections: undefined,
+ environments:
+ scenario === 'offline'
+ ? [{ environment, state: 'unavailable', workspaces: [], selected: undefined }]
+ : [],
+ transition: {
+ kind: 'move',
+ conversationId: 'existing',
+ from: [mac],
+ previous: scenario === 'offline' ? [] : [{ id: 'mac', name: 'Danny Mac' }],
+ retained: [],
+ targets: [],
+ detachable: true,
+ },
+ })}
+ disabled={false}
+ />,
+ );
+
+ await userEvent.click(screen.getByTestId('code-workspace'));
+ /** Nothing to move onto, so the only decision left is to stop waiting for the machine. */
+ expect(
+ screen.queryByRole('menuitem', { name: /com_ui_code_workspace_move/ }),
+ ).not.toBeInTheDocument();
+ await userEvent.click(screen.getByTestId('code-workspace-detach'));
+
+ await waitFor(() => expect(moveSpy).toHaveBeenCalledTimes(1));
+ expect(moveSpy).toHaveBeenCalledWith({ conversationId: 'existing', from: [mac], to: [] });
+ const update = setConversation.mock.calls[0][0];
+ expect(update(sealed)).toEqual({
+ ...sealed,
+ codeEnvironmentMode: 'without_attached',
+ codeWorkspaces: undefined,
+ });
+ },
+ );
+ });
+
describe('a chat sealed to a machine its agent no longer uses', () => {
const mac = { environmentId: 'mac', workspaceId: 'primary' };
const moved = { environmentId: environment.id, workspaceId: 'project-a' };
@@ -306,7 +534,7 @@ describe('CodeWorkspaceMenu', () => {
baseURL: 'https://team.example.com',
};
- type Target = NonNullable<CodeWorkspaceResult['relocation']>['targets'][number];
+ type Target = NonNullable<CodeWorkspaceResult['transition']>['targets'][number];
const target = (
targetEnvironment: Target['environment'],
workspaces: Target['workspaces'],
@@ -325,12 +553,14 @@ describe('CodeWorkspaceMenu', () => {
selections: undefined,
rememberSelection,
environments: targets,
- relocation: {
+ transition: {
+ kind: 'move',
conversationId: 'existing',
from: [mac],
previous: [{ id: 'mac', name: 'Danny Mac' }],
retained: [],
targets,
+ detachable: true,
},
});
@@ -372,8 +602,8 @@ describe('CodeWorkspaceMenu', () => {
setConversation={setConversation}
workspace={{
...base,
- relocation: {
- ...base.relocation!,
+ transition: {
+ ...base.transition!,
from: [missing, kept],
previous: [],
retained: [kept],
@@ -438,7 +668,7 @@ describe('CodeWorkspaceMenu', () => {
setConversation={setConversation}
workspace={{
...base,
- relocation: { ...base.relocation!, from: [missing], previous: [] },
+ transition: { ...base.transition!, from: [missing], previous: [] },
}}
disabled={false}
/>,
@@ -488,7 +718,7 @@ describe('CodeWorkspaceMenu', () => {
setConversation={setConversation}
workspace={{
...base,
- relocation: { ...base.relocation!, from: [missing], previous: [] },
+ transition: { ...base.transition!, from: [missing], previous: [] },
}}
disabled={false}
/>,
@@ -511,8 +741,8 @@ describe('CodeWorkspaceMenu', () => {
]);
const state = {
...base,
- relocation: {
- ...base.relocation!,
+ transition: {
+ ...base.transition!,
from: [{ ...moved, workspaceId: 'deleted-project' }],
previous: [],
},
@@ -631,7 +861,7 @@ describe('CodeWorkspaceMenu', () => {
setConversation={jest.fn()}
workspace={{
...firstChat,
- relocation: { ...firstChat.relocation!, conversationId: 'another-chat' },
+ transition: { ...firstChat.transition!, conversationId: 'another-chat' },
}}
disabled={false}
/>,
@@ -657,8 +887,8 @@ describe('CodeWorkspaceMenu', () => {
setConversation={setConversation}
workspace={{
...base,
- relocation: {
- ...base.relocation!,
+ transition: {
+ ...base.transition!,
from: [mac, moved],
previous: [{ id: 'mac', name: 'Danny Mac' }],
retained: [moved],
@@ -715,29 +945,43 @@ describe('CodeWorkspaceMenu', () => {
data: { error: 'busy' },
key: 'com_ui_code_workspace_move_busy',
},
- ])('explains a refused move when $name and keeps the chat as it was', async ({ data, key }) => {
- jest.spyOn(dataService, 'moveConversationCodeEnvironment').mockRejectedValue(
- new AxiosError('Conflict', 'ERR_BAD_REQUEST', undefined, undefined, {
- status: 409,
- data,
- } as AxiosResponse),
- );
- const setConversation = jest.fn();
- renderMenu(
- <CodeWorkspaceMenu
- setConversation={setConversation}
- workspace={relocatable([target(environment, [{ id: 'project-a', name: 'Project A' }])])}
- disabled={false}
- />,
- );
-
- await userEvent.click(screen.getByTestId('code-workspace-move'));
- await userEvent.click(await confirmItem());
-
- await waitFor(() =>
- expect(mockShowToast).toHaveBeenCalledWith({ message: key, status: 'error' }),
- );
- expect(setConversation).not.toHaveBeenCalled();
- });
+ ])(
+ 'explains a refused move when $name and reconciles only stale decisions',
+ async ({ data, key }) => {
+ jest.spyOn(dataService, 'moveConversationCodeEnvironment').mockRejectedValue(
+ new AxiosError('Conflict', 'ERR_BAD_REQUEST', undefined, undefined, {
+ status: 409,
+ data,
+ } as AxiosResponse),
+ );
+ const persisted = { ...sealed, codeEnvironmentMode: 'without_attached' } as TConversation;
+ const read = jest.spyOn(dataService, 'getConversationById').mockResolvedValue(persisted);
+ const setConversation = jest.fn();
+ renderMenu(
+ <CodeWorkspaceMenu
+ setConversation={setConversation}
+ workspace={relocatable([target(environment, [{ id: 'project-a', name: 'Project A' }])])}
+ disabled={false}
+ />,
+ );
+
+ await userEvent.click(screen.getByTestId('code-workspace-move'));
+ await userEvent.click(await confirmItem());
+
+ await waitFor(() =>
+ expect(mockShowToast).toHaveBeenCalledWith({ message: key, status: 'error' }),
+ );
+ if (data.reason === 'locked') {
+ expect(read).toHaveBeenCalledWith('existing');
+ const update = setConversation.mock.calls[0][0];
+ expect(
+ update({ ...sealed, codeEnvironmentMode: 'attached', codeWorkspaces: [mac] }),
+ ).toEqual(persisted);
+ } else {
+ expect(read).not.toHaveBeenCalled();
+ expect(setConversation).not.toHaveBeenCalled();
+ }
+ },
+ );
});
});
diff --git a/client/src/data-provider/CodeEnvironments.ts b/client/src/data-provider/CodeEnvironments.ts
index 3213accea3..b552f58b3a 100644
--- a/client/src/data-provider/CodeEnvironments.ts
+++ b/client/src/data-provider/CodeEnvironments.ts
@@ -1,6 +1,8 @@
+import { useAtomValue, useStore } from 'jotai';
import { DynamicQueryKeys, MutationKeys, QueryKeys, dataService } from 'librechat-data-provider';
import {
useIsFetching,
+ useIsMutating,
useMutation,
useQueries,
useQuery,
@@ -16,7 +18,16 @@ import type {
TCodeEnvironmentsResponse,
} from 'librechat-data-provider';
import type { QueryFilters } from '@tanstack/react-query';
-import { CONVERSATION_LIST_KEYS, updateConvoInAllQueries } from '~/utils';
+import type { SetterOrUpdater } from 'recoil';
+import type { CodeEnvironmentReconciliationRequest } from '~/store/codeEnvironmentReconciliation';
+import {
+ CONVERSATION_LIST_KEYS,
+ updateConvoInAllQueries,
+ getCodeWorkspaceErrorReason,
+ getResponseStatus,
+} from '~/utils';
+import { codeEnvironmentReconciliationsAtom } from '~/store/codeEnvironmentReconciliation';
+import { hasSameCodeDecision } from '~/hooks/Agents/codeDecision';
import { retryTransientQuery } from './retry';
export type CodeEnvironmentPairingResponse = TCodeEnvironmentPairingResponse;
@@ -108,13 +119,59 @@ export function useUpdateCodeEnvironmentSettingsMutation() {
});
}
+/** Pending and failed authoritative reads both leave the local decision unconfirmed. */
+export function useConversationCodeEnvironmentRecovery(conversationId?: string | null) {
+ const reconciliations = useAtomValue(codeEnvironmentReconciliationsAtom);
+ return conversationId == null ? undefined : reconciliations.get(conversationId);
+}
+
+/** Block pending transitions and unresolved decision reads for this conversation only. */
+export function useIsReplacingConversationCodeEnvironment(conversationId?: string | null): boolean {
+ const recovery = useConversationCodeEnvironmentRecovery(conversationId);
+ const pending =
+ useIsMutating({
+ predicate: (mutation) =>
+ [
+ MutationKeys.moveConversationCodeEnvironment,
+ 'reconcileConversationCodeEnvironment',
+ ].includes(String(mutation.options.mutationKey?.[0])) &&
+ conversationId != null &&
+ (mutation.state.variables as TCodeEnvironmentMoveRequest | undefined)?.conversationId ===
+ conversationId,
+ }) > 0;
+ return recovery != null || pending;
+}
+
/** Keeps every cached copy of the conversation on the decision the server just persisted. */
-export function useMoveConversationCodeEnvironmentMutation() {
+export function useMoveConversationCodeEnvironmentMutation(
+ setConversation?: SetterOrUpdater<TConversation | null>,
+) {
const queryClient = useQueryClient();
+ const { mutateAsync: reconcile } =
+ useReconcileConversationCodeEnvironmentMutation(setConversation);
return useMutation<TCodeEnvironmentMoveResponse, Error, TCodeEnvironmentMoveRequest>(
[MutationKeys.moveConversationCodeEnvironment],
dataService.moveConversationCodeEnvironment,
{
+ onError: async (error, { conversationId, from }) => {
+ const status = getResponseStatus(error);
+ if (getCodeWorkspaceErrorReason(error) !== 'locked' && status != null && status < 500) {
+ return;
+ }
+ // A conflict or lost response does not establish which decision the server holds.
+ // Keep this in the mutation, not a component callback that navigation can discard.
+ try {
+ await reconcile({
+ conversationId,
+ attempted: {
+ codeEnvironmentMode: from.length > 0 ? 'attached' : 'without_attached',
+ codeWorkspaces: from.length > 0 ? from : undefined,
+ },
+ });
+ } catch {
+ // The conversation-scoped recovery state retains the failed read and offers retry.
+ }
+ },
onSuccess: async ({ conversationId, codeEnvironmentMode, codeWorkspaces }) => {
/** A read already in flight could land after this write and restore the replaced decision. */
await Promise.all(
@@ -128,6 +185,9 @@ export function useMoveConversationCodeEnvironmentMutation() {
codeWorkspaces,
});
updateConvoInAllQueries(queryClient, conversationId, applyDecision);
+ setConversation?.((current) =>
+ current?.conversationId === conversationId ? applyDecision(current) : current,
+ );
queryClient.setQueryData<TConversation | undefined>(
[QueryKeys.conversation, conversationId],
(conversation) => (conversation == null ? conversation : applyDecision(conversation)),
@@ -136,3 +196,68 @@ export function useMoveConversationCodeEnvironmentMutation() {
},
);
}
+
+/** A terminal error does not say whether the server persisted the attempted decision. Read it,
+ * rather than rolling back a decision a failed turn may already have established. */
+export function useReconcileConversationCodeEnvironmentMutation(
+ setConversation?: SetterOrUpdater<TConversation | null>,
+) {
+ const queryClient = useQueryClient();
+ const store = useStore();
+ return useMutation({
+ mutationKey: ['reconcileConversationCodeEnvironment'],
+ onMutate: (request: CodeEnvironmentReconciliationRequest) => {
+ const token = Symbol();
+ store.set(codeEnvironmentReconciliationsAtom, (current) =>
+ new Map(current).set(request.conversationId, { request, token, status: 'pending' }),
+ );
+ return { token };
+ },
+ mutationFn: async ({ conversationId }: CodeEnvironmentReconciliationRequest) => {
+ const queryKey = [QueryKeys.conversation, conversationId];
+ await queryClient.cancelQueries({ queryKey });
+ return queryClient.fetchQuery(
+ queryKey,
+ async () => {
+ const persisted = await dataService.getConversationById(conversationId);
+ if (persisted?.conversationId !== conversationId) {
+ throw new Error(
+ 'Conversation decision reconciliation returned a different conversation',
+ );
+ }
+ return persisted;
+ },
+ { staleTime: 0 },
+ );
+ },
+ onSuccess: (persisted, { conversationId, attempted }, context) => {
+ if (
+ store.get(codeEnvironmentReconciliationsAtom).get(conversationId)?.token !== context?.token
+ ) {
+ return;
+ }
+ const apply = (current: TConversation): TConversation =>
+ current.conversationId === conversationId && hasSameCodeDecision(current, attempted)
+ ? {
+ ...current,
+ codeEnvironmentMode: persisted.codeEnvironmentMode,
+ codeWorkspaces: persisted.codeWorkspaces,
+ }
+ : current;
+ updateConvoInAllQueries(queryClient, conversationId, apply);
+ setConversation?.((current) => (current == null ? current : apply(current)));
+ store.set(codeEnvironmentReconciliationsAtom, (current) => {
+ const next = new Map(current);
+ next.delete(conversationId);
+ return next;
+ });
+ },
+ onError: (_error, { conversationId }, context) => {
+ store.set(codeEnvironmentReconciliationsAtom, (current) => {
+ const recovery = current.get(conversationId);
+ if (recovery == null || recovery.token !== context?.token) return current;
+ return new Map(current).set(conversationId, { ...recovery, status: 'error' });
+ });
+ },
+ });
+}
diff --git a/client/src/data-provider/__tests__/moveCodeEnvironment.test.tsx b/client/src/data-provider/__tests__/moveCodeEnvironment.test.tsx
index f56b71a518..59cb86090e 100644
--- a/client/src/data-provider/__tests__/moveCodeEnvironment.test.tsx
+++ b/client/src/data-provider/__tests__/moveCodeEnvironment.test.tsx
@@ -1,16 +1,28 @@
import { createElement } from 'react';
+import { AxiosError } from 'axios';
+import { Provider, createStore } from 'jotai';
import { dataService, QueryKeys } from 'librechat-data-provider';
import { act, renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
import type { TConversation } from 'librechat-data-provider';
+import type { AxiosResponse } from 'axios';
import type { ReactNode } from 'react';
-import { useMoveConversationCodeEnvironmentMutation } from '../CodeEnvironments';
+import {
+ useMoveConversationCodeEnvironmentMutation,
+ useIsReplacingConversationCodeEnvironment,
+ useConversationCodeEnvironmentRecovery,
+ useReconcileConversationCodeEnvironmentMutation,
+} from '../CodeEnvironments';
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return {
...actual,
- dataService: { ...actual.dataService, moveConversationCodeEnvironment: jest.fn() },
+ dataService: {
+ ...actual.dataService,
+ moveConversationCodeEnvironment: jest.fn(),
+ getConversationById: jest.fn(),
+ },
};
});
@@ -72,3 +84,393 @@ describe('useMoveConversationCodeEnvironmentMutation', () => {
},
);
});
+
+describe('conversation-scoped decision recovery', () => {
+ afterEach(() => jest.restoreAllMocks());
+ const setup = (setConversation = jest.fn()) => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const store = createStore();
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(
+ Provider,
+ { store },
+ createElement(QueryClientProvider, { client: queryClient }, children),
+ );
+ return renderHook(
+ () => ({
+ change: useMoveConversationCodeEnvironmentMutation(setConversation),
+ reconcile: useReconcileConversationCodeEnvironmentMutation(setConversation),
+ blocked: useIsReplacingConversationCodeEnvironment('convo-1'),
+ unrelated: useIsReplacingConversationCodeEnvironment('convo-2'),
+ recovery: useConversationCodeEnvironmentRecovery('convo-1'),
+ }),
+ { wrapper },
+ );
+ };
+
+ it('blocks only the conversation being changed and unblocks after settlement', async () => {
+ let finish!: (value: {
+ conversationId: string;
+ codeEnvironmentMode: 'attached';
+ codeWorkspaces: (typeof vm)[];
+ }) => void;
+ jest.mocked(dataService.moveConversationCodeEnvironment).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { result } = setup();
+ act(() => result.current.change.mutate({ conversationId: 'convo-1', from: [mac], to: [vm] }));
+ await waitFor(() => expect(result.current.blocked).toBe(true));
+ expect(result.current.unrelated).toBe(false);
+ await act(async () => {
+ finish({ conversationId: 'convo-1', codeEnvironmentMode: 'attached', codeWorkspaces: [vm] });
+ });
+ await waitFor(() => expect(result.current.blocked).toBe(false));
+ });
+
+ it.each([
+ { codeEnvironmentMode: undefined, codeWorkspaces: undefined },
+ { codeEnvironmentMode: 'attached' as const, codeWorkspaces: [mac] },
+ { codeEnvironmentMode: 'without_attached' as const, codeWorkspaces: undefined },
+ ])('reconciles both pre-persistence and persisted failures: %j', async (decision) => {
+ const attempted = { codeEnvironmentMode: 'attached' as const, codeWorkspaces: [vm] };
+ const current = {
+ conversationId: 'convo-1',
+ title: 'Keep title',
+ ...attempted,
+ } as TConversation;
+ const persisted = { ...current, ...decision };
+ jest.mocked(dataService.getConversationById).mockResolvedValueOnce(persisted);
+ const setter = jest.fn();
+ const { result } = setup(setter);
+ await act(async () => {
+ await result.current.reconcile.mutateAsync({ conversationId: 'convo-1', attempted });
+ });
+ const update = setter.mock.calls[0][0];
+ expect(update(current)).toEqual(persisted);
+ const other = { ...current, conversationId: 'convo-2' };
+ expect(update(other)).toBe(other);
+ const changed = {
+ ...current,
+ codeEnvironmentMode: 'without_attached',
+ codeWorkspaces: undefined,
+ };
+ expect(update(changed)).toBe(changed);
+ });
+
+ it('blocks retries while the authoritative decision is being read', async () => {
+ let finish!: (value: TConversation) => void;
+ jest.mocked(dataService.getConversationById).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { result } = setup();
+ act(() =>
+ result.current.reconcile.mutate({
+ conversationId: 'convo-1',
+ attempted: { codeEnvironmentMode: 'without_attached' },
+ }),
+ );
+ await waitFor(() => expect(result.current.blocked).toBe(true));
+ expect(result.current.unrelated).toBe(false);
+ await act(async () => {
+ finish({
+ conversationId: 'convo-1',
+ codeEnvironmentMode: 'without_attached',
+ } as TConversation);
+ });
+ await waitFor(() => expect(result.current.blocked).toBe(false));
+ });
+ it('keeps a failed read blocked across mutation resets until a successful retry', async () => {
+ jest.spyOn(console, 'error').mockImplementation(() => undefined);
+ const attempted = { codeEnvironmentMode: 'attached' as const, codeWorkspaces: [vm] };
+ const request = { conversationId: 'convo-1', attempted };
+ jest.mocked(dataService.getConversationById).mockRejectedValueOnce(new Error('offline'));
+ const setter = jest.fn();
+ const { result } = setup(setter);
+ await act(async () => {
+ await expect(result.current.reconcile.mutateAsync(request)).rejects.toThrow('offline');
+ });
+ expect(result.current.recovery?.status).toBe('error');
+ expect(result.current.blocked).toBe(true);
+ expect(result.current.unrelated).toBe(false);
+ expect(setter).not.toHaveBeenCalled();
+ act(() => result.current.reconcile.reset());
+ expect(result.current.blocked).toBe(true);
+
+ const persisted = {
+ conversationId: 'convo-1',
+ codeEnvironmentMode: 'without_attached',
+ } as TConversation;
+ jest.mocked(dataService.getConversationById).mockResolvedValueOnce(persisted);
+ await act(async () => {
+ await result.current.reconcile.mutateAsync(result.current.recovery!.request);
+ });
+ await waitFor(() => expect(result.current.blocked).toBe(false));
+ expect(result.current.recovery).toBeUndefined();
+ expect(setter.mock.calls[0][0]({ conversationId: 'convo-1', ...attempted })).toEqual(persisted);
+ });
+
+ it('preserves the failed guard when leaving and remounting the conversation', async () => {
+ jest.spyOn(console, 'error').mockImplementation(() => undefined);
+ const store = createStore();
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(
+ Provider,
+ { store },
+ createElement(QueryClientProvider, { client: queryClient }, children),
+ );
+ jest.mocked(dataService.getConversationById).mockRejectedValueOnce(new Error('offline'));
+ const first = renderHook(() => useReconcileConversationCodeEnvironmentMutation(), { wrapper });
+ await act(async () => {
+ await expect(
+ first.result.current.mutateAsync({ conversationId: 'convo-1', attempted: {} }),
+ ).rejects.toThrow('offline');
+ });
+ first.unmount();
+ const restored = renderHook(({ id }) => useIsReplacingConversationCodeEnvironment(id), {
+ wrapper,
+ initialProps: { id: 'convo-2' },
+ });
+ expect(restored.result.current).toBe(false);
+ restored.rerender({ id: 'convo-1' });
+ expect(restored.result.current).toBe(true);
+ });
+
+ it('treats a mismatched conversation response as failed reconciliation', async () => {
+ jest.spyOn(console, 'error').mockImplementation(() => undefined);
+ jest
+ .mocked(dataService.getConversationById)
+ .mockResolvedValueOnce({ conversationId: 'convo-2' } as TConversation);
+ const setter = jest.fn();
+ const { result } = setup(setter);
+ await act(async () => {
+ await expect(
+ result.current.reconcile.mutateAsync({ conversationId: 'convo-1', attempted: {} }),
+ ).rejects.toThrow('different conversation');
+ });
+ expect(result.current.recovery?.status).toBe('error');
+ expect(result.current.blocked).toBe(true);
+ expect(setter).not.toHaveBeenCalled();
+ });
+
+ it('does not let an older failed read replace a newer recovery attempt', async () => {
+ jest.spyOn(console, 'error').mockImplementation(() => undefined);
+ let failOld!: (reason: Error) => void;
+ let resolveNew!: (value: TConversation) => void;
+ jest
+ .mocked(dataService.getConversationById)
+ .mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ failOld = reject;
+ }),
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveNew = resolve;
+ }),
+ );
+ const { result } = setup();
+ const older = {
+ conversationId: 'convo-1',
+ attempted: { codeEnvironmentMode: 'attached' as const, codeWorkspaces: [mac] },
+ };
+ const newer = {
+ conversationId: 'convo-1',
+ attempted: { codeEnvironmentMode: 'attached' as const, codeWorkspaces: [vm] },
+ };
+ act(() => result.current.reconcile.mutate(older));
+ await waitFor(() => expect(failOld).toBeDefined());
+ act(() => result.current.reconcile.mutate(newer));
+ await waitFor(() => expect(resolveNew).toBeDefined());
+ await act(async () => failOld(new Error('late failure')));
+ expect(result.current.recovery?.request).toEqual(newer);
+ expect(result.current.recovery?.status).toBe('pending');
+ await act(async () =>
+ resolveNew({ conversationId: 'convo-1', ...newer.attempted } as TConversation),
+ );
+ await waitFor(() => expect(result.current.blocked).toBe(false));
+ expect(result.current.recovery).toBeUndefined();
+ });
+});
+
+describe('ambiguous workspace transitions', () => {
+ afterEach(() => jest.restoreAllMocks());
+
+ const conflict = new AxiosError('stale', 'ERR_BAD_REQUEST', undefined, undefined, {
+ status: 409,
+ data: { reason: 'locked' },
+ } as AxiosResponse);
+
+ it.each([
+ ['attach response lost', new Error('connection reset'), [], [vm]],
+ ['detach response lost', new Error('connection reset'), [mac], []],
+ ['competing tab', conflict, [mac], [vm]],
+ [
+ 'server failure',
+ new AxiosError('server', undefined, undefined, undefined, {
+ status: 503,
+ } as AxiosResponse),
+ [mac],
+ [vm],
+ ],
+ ] as const)(
+ 'recovers %s through the mutation even after its observer unmounts',
+ async (_label, error, from, to) => {
+ jest.spyOn(console, 'error').mockImplementation(() => undefined);
+ let fail!: (error: Error) => void;
+ let finishRead!: (value: TConversation) => void;
+ jest.mocked(dataService.moveConversationCodeEnvironment).mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ fail = reject;
+ }),
+ );
+ jest.mocked(dataService.getConversationById).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishRead = resolve;
+ }),
+ );
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const store = createStore();
+ const stored = {
+ conversationId: 'saved',
+ title: 'Preserved',
+ codeEnvironmentMode: from.length ? 'attached' : 'without_attached',
+ codeWorkspaces: from.length ? [...from] : undefined,
+ } as TConversation;
+ const persisted = {
+ ...stored,
+ codeEnvironmentMode: to.length ? 'attached' : 'without_attached',
+ codeWorkspaces: to.length ? [...to] : undefined,
+ } as TConversation;
+ queryClient.setQueryData([QueryKeys.conversation, 'saved'], stored);
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(
+ Provider,
+ { store },
+ createElement(QueryClientProvider, { client: queryClient }, children),
+ );
+ let current = stored;
+ const setter = jest.fn((update) => {
+ current = update(current);
+ });
+ const mutation = renderHook(() => useMoveConversationCodeEnvironmentMutation(setter), {
+ wrapper,
+ });
+ const guard = renderHook(
+ () => ({
+ blocked: useIsReplacingConversationCodeEnvironment('saved'),
+ unrelated: useIsReplacingConversationCodeEnvironment('other'),
+ }),
+ { wrapper },
+ );
+ act(() =>
+ mutation.result.current.mutate({ conversationId: 'saved', from: [...from], to: [...to] }),
+ );
+ await waitFor(() => expect(fail).toBeDefined());
+ mutation.unmount();
+ await act(async () => fail(error));
+ await waitFor(() => expect(finishRead).toBeDefined());
+ expect(guard.result.current.blocked).toBe(true);
+ expect(guard.result.current.unrelated).toBe(false);
+ await act(async () => finishRead(persisted));
+ await waitFor(() => expect(guard.result.current.blocked).toBe(false));
+ expect(current).toEqual(persisted);
+ expect(queryClient.getQueryData([QueryKeys.conversation, 'saved'])).toEqual(persisted);
+ },
+ );
+
+ it('keeps a failed transition read guarded until explicit retry, without changing another chat', async () => {
+ jest.spyOn(console, 'error').mockImplementation(() => undefined);
+ jest
+ .mocked(dataService.moveConversationCodeEnvironment)
+ .mockRejectedValueOnce(new Error('offline'));
+ jest.mocked(dataService.getConversationById).mockRejectedValueOnce(new Error('still offline'));
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const store = createStore();
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(
+ Provider,
+ { store },
+ createElement(QueryClientProvider, { client: queryClient }, children),
+ );
+ const other = {
+ conversationId: 'other',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac],
+ } as TConversation;
+ let current = other;
+ const setter = jest.fn((update) => {
+ current = update(current);
+ });
+ const { result } = renderHook(
+ () => ({
+ mutation: useMoveConversationCodeEnvironmentMutation(setter),
+ recovery: useConversationCodeEnvironmentRecovery('saved'),
+ retry: useReconcileConversationCodeEnvironmentMutation(setter),
+ blocked: useIsReplacingConversationCodeEnvironment('saved'),
+ }),
+ { wrapper },
+ );
+ await act(async () => {
+ await expect(
+ result.current.mutation.mutateAsync({ conversationId: 'saved', from: [mac], to: [] }),
+ ).rejects.toThrow('offline');
+ });
+ expect(result.current.blocked).toBe(true);
+ expect(result.current.recovery?.status).toBe('error');
+ const persisted = {
+ conversationId: 'saved',
+ codeEnvironmentMode: 'without_attached',
+ } as TConversation;
+ jest.mocked(dataService.getConversationById).mockResolvedValueOnce(persisted);
+ await act(async () => {
+ await result.current.retry.mutateAsync(result.current.recovery!.request);
+ });
+ await waitFor(() => expect(result.current.blocked).toBe(false));
+ expect(current).toBe(other);
+ });
+
+ it.each([400, 403, 409, 429])(
+ 'does not turn a definitive %s rejection into recovery',
+ async (status) => {
+ jest.spyOn(console, 'error').mockImplementation(() => undefined);
+ const read = jest.spyOn(dataService, 'getConversationById');
+ read.mockClear();
+ const error = new AxiosError('rejected', undefined, undefined, undefined, {
+ status,
+ data: {},
+ } as AxiosResponse);
+ jest.mocked(dataService.moveConversationCodeEnvironment).mockRejectedValueOnce(error);
+ const queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(QueryClientProvider, { client: queryClient }, children);
+ const { result } = renderHook(() => useMoveConversationCodeEnvironmentMutation(), {
+ wrapper,
+ });
+ await act(async () => {
+ await expect(
+ result.current.mutateAsync({ conversationId: 'saved', from: [mac], to: [] }),
+ ).rejects.toBe(error);
+ });
+ expect(read).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/client/src/hooks/Agents/__tests__/codeDecision.test.ts b/client/src/hooks/Agents/__tests__/codeDecision.test.ts
new file mode 100644
index 0000000000..1268c41264
--- /dev/null
+++ b/client/src/hooks/Agents/__tests__/codeDecision.test.ts
@@ -0,0 +1,92 @@
+import type { TConversation } from 'librechat-data-provider';
+import { withSubmittedCodeDecision, hasSameCodeDecision } from '../codeDecision';
+
+const selection = { environmentId: 'personal-vm', workspaceId: 'project-a' };
+const conversation = (overrides: Partial<TConversation> = {}): TConversation =>
+ ({ conversationId: 'existing', ...overrides }) as TConversation;
+
+describe('withSubmittedCodeDecision', () => {
+ it('records the mode and selections the run was submitted with', () => {
+ expect(
+ withSubmittedCodeDecision(conversation(), {
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [selection],
+ }),
+ ).toEqual({
+ conversationId: 'existing',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [selection],
+ });
+ });
+
+ it('records a run that continues without an attached environment', () => {
+ expect(
+ withSubmittedCodeDecision(conversation({ codeWorkspaces: [selection] }), {
+ codeEnvironmentMode: 'without_attached',
+ }),
+ ).toEqual({ conversationId: 'existing', codeEnvironmentMode: 'without_attached' });
+ });
+
+ /* A send that carries no decision belongs to a chat no attached environment applies to. */
+ it('leaves a conversation alone when the submission carries no decision', () => {
+ const current = conversation();
+ expect(withSubmittedCodeDecision(current, {})).toBe(current);
+ expect(withSubmittedCodeDecision(null, { codeEnvironmentMode: 'attached' })).toBeNull();
+ });
+
+ it('keeps the same conversation when it already holds the decision in another order', () => {
+ const other = { environmentId: 'team-vm', workspaceId: 'shared' };
+ const current = conversation({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [other, selection],
+ });
+
+ expect(
+ withSubmittedCodeDecision(current, {
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [selection, other],
+ }),
+ ).toBe(current);
+ });
+});
+
+it('does not confuse colons in environment and workspace identifiers', () => {
+ const current = conversation({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [{ environmentId: 'vm:repo', workspaceId: 'main' }],
+ });
+ const submitted = {
+ codeEnvironmentMode: 'attached' as const,
+ codeWorkspaces: [{ environmentId: 'vm', workspaceId: 'repo:main' }],
+ };
+ expect(withSubmittedCodeDecision(current, submitted)?.codeWorkspaces).toEqual(
+ submitted.codeWorkspaces,
+ );
+});
+
+it('records a legacy selection-only submission before the first saved-chat event', () => {
+ expect(withSubmittedCodeDecision(conversation(), { codeWorkspaces: [selection] })).toEqual({
+ conversationId: 'existing',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [selection],
+ });
+});
+
+it('matches legacy selection-only decisions when reconciling a transition', () => {
+ expect(
+ hasSameCodeDecision(
+ { codeWorkspaces: [selection] },
+ { codeEnvironmentMode: 'attached', codeWorkspaces: [selection] },
+ ),
+ ).toBe(true);
+});
+
+it('treats empty and absent selections alike without treating an undecided chat as sealed', () => {
+ expect(
+ hasSameCodeDecision(
+ { codeEnvironmentMode: 'without_attached', codeWorkspaces: [] },
+ { codeEnvironmentMode: 'without_attached' },
+ ),
+ ).toBe(true);
+ expect(hasSameCodeDecision({}, { codeEnvironmentMode: 'without_attached' })).toBe(false);
+});
diff --git a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx
index c2a98c1d12..3f2895e5e8 100644
--- a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx
+++ b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx
@@ -1,11 +1,14 @@
import { renderHook } from '@testing-library/react';
import { EModelEndpoint, Tools } from 'librechat-data-provider';
import type { TConversation } from 'librechat-data-provider';
+import { withSubmittedCodeDecision } from '../codeDecision';
import useCodeWorkspace from '../useCodeWorkspace';
const mockAgentPermissions = jest.fn();
const mockAgentsConfig = jest.fn();
const mockStatus = jest.fn();
+const mockReplacingDecision = jest.fn();
+const mockRecovery = jest.fn();
const mockStartupConfig = jest.fn();
const mockAgentsMap = jest.fn();
const mockAccess = jest.fn();
@@ -27,6 +30,8 @@ jest.mock('~/Providers', () => ({ useAgentsMapContext: () => mockAgentsMap() }))
jest.mock('~/data-provider', () => ({
useCodeEnvironmentStatusQueries: (...args: unknown[]) => mockStatus(...args),
useGetStartupConfig: () => ({ data: mockStartupConfig() }),
+ useIsReplacingConversationCodeEnvironment: () => mockReplacingDecision(),
+ useConversationCodeEnvironmentRecovery: () => mockRecovery(),
}));
const conversation = (codeWorkspaces?: TConversation['codeWorkspaces']): TConversation =>
@@ -42,6 +47,8 @@ describe('useCodeWorkspace', () => {
mockPreference.mockReset();
mockRememberPreference.mockReset();
mockAccess.mockReturnValue(true);
+ mockReplacingDecision.mockReturnValue(false);
+ mockRecovery.mockReturnValue(undefined);
mockStartupConfig.mockReturnValue({ codeEnvironmentDecisionVersion: 1 });
mockAgentPermissions.mockReturnValue({
tools: [Tools.execute_code],
@@ -99,6 +106,74 @@ describe('useCodeWorkspace', () => {
},
);
+ /* The server checks for active work before it polls the target workspace, so a turn submitted
+ * during that poll runs under the decision being replaced while the replacement still lands. */
+ it('withholds submission while a decision replacement is in flight', () => {
+ mockReplacingDecision.mockReturnValue(true);
+
+ const { result } = renderHook(() =>
+ useCodeWorkspace({ ...conversation(), conversationId: 'existing' } as TConversation),
+ );
+
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.resolveSubmission()).toBeUndefined();
+ /** The control stays reachable, so the reader sees where the chat runs while it settles. */
+ expect(result.current.visible).toBe(true);
+ });
+
+ it('keeps a saved chat without workspace access through first send and reload', () => {
+ mockStartupConfig.mockReturnValue({
+ codeEnvironmentDecisionVersion: 1,
+ codeEnvironmentMoveVersion: 1,
+ codeEnvironmentTransitionVersion: 2,
+ });
+ const existing = { ...conversation(), conversationId: 'existing' } as TConversation;
+ const { result, rerender } = renderHook(({ chat }) => useCodeWorkspace(chat), {
+ initialProps: { chat: existing },
+ });
+ expect(result.current.mode).toBe('without_attached');
+ expect(result.current.canSubmit).toBe(true);
+ const submission = result.current.resolveSubmission()!;
+ expect(submission).toEqual({ codeEnvironmentMode: 'without_attached' });
+ const persisted = JSON.parse(JSON.stringify(withSubmittedCodeDecision(existing, submission)));
+ rerender({ chat: persisted });
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.transition?.kind).toBe('attach');
+ const attached = {
+ ...persisted,
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }],
+ };
+ rerender({ chat: attached });
+ expect(result.current.resolveSubmission()).toEqual({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: attached.codeWorkspaces,
+ });
+ });
+
+ it.each(['pending', 'error'] as const)(
+ 'blocks every send while reconciliation is %s, even after switching to a non-coding agent',
+ (status) => {
+ mockRecovery.mockReturnValue({
+ request: { conversationId: 'existing', attempted: {} },
+ status,
+ token: Symbol(),
+ });
+ mockAgentPermissions.mockReturnValue({
+ tools: [],
+ agent: { id: 'agent_primary', tools: [] },
+ });
+ const { result } = renderHook(() =>
+ useCodeWorkspace({ ...conversation(), conversationId: 'existing' } as TConversation),
+ );
+ expect(result.current.required).toBe(false);
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.resolveSubmission()).toBeUndefined();
+ expect(result.current.visible).toBe(true);
+ expect(result.current.recovery?.status).toBe(status);
+ },
+ );
+
it('reports unavailable when a ready worker advertises no workspaces', () => {
mockStatus()[0].data.workspaces = [];
const { result } = renderHook(() => useCodeWorkspace(conversation()));
@@ -149,7 +224,8 @@ describe('useCodeWorkspace', () => {
* the composer still offers the choice. */
rerender({ id: 'existing' });
expect(result.current.locked).toBe(false);
- expect(result.current.mode).toBe('attached');
+ expect(result.current.mode).toBe('without_attached');
+ expect(result.current.resolveSubmission()).toEqual({ codeEnvironmentMode: 'without_attached' });
expect(result.current.selections?.[0].workspaceId).toBe('project-b');
expect(result.current.canSubmit).toBe(true);
});
@@ -476,7 +552,7 @@ describe('useCodeWorkspace', () => {
expect(result.current.state).toBe('choose');
expect(result.current.canSubmit).toBe(false);
expect(result.current.selections).toBeUndefined();
- expect(result.current.relocation).toBeUndefined();
+ expect(result.current.transition).toBeUndefined();
});
describe('a saved chat sealed to a machine its agent no longer uses', () => {
@@ -492,6 +568,7 @@ describe('useCodeWorkspace', () => {
mockStartupConfig.mockReturnValue({
codeEnvironmentDecisionVersion: 1,
codeEnvironmentMoveVersion: 1,
+ codeEnvironmentTransitionVersion: 2,
});
});
@@ -502,7 +579,65 @@ describe('useCodeWorkspace', () => {
expect(result.current.state).toBe('choose');
expect(result.current.canSubmit).toBe(false);
- expect(result.current.relocation).toBeUndefined();
+ expect(result.current.transition).toBeUndefined();
+ });
+
+ it.each(['non-coding', 'managed-only'])(
+ 'offers detach after switching to a %s agent',
+ (kind) => {
+ const previous = { environmentId: 'personal-vm', workspaceId: 'project-a' };
+ const agent = mockAgentPermissions().agent;
+ if (kind === 'non-coding') {
+ agent.tools = [];
+ agent.stateful_code_sessions = false;
+ } else {
+ agent.code_environment_id = 'managed';
+ mockAgentsConfig().agentsConfig.statefulCodeSessions.environments.push({
+ id: 'managed',
+ type: 'managed',
+ name: 'Managed',
+ });
+ }
+ const original = sealed([previous]);
+ const { result, rerender } = renderHook(({ chat }) => useCodeWorkspace(chat), {
+ initialProps: { chat: original },
+ });
+ expect(result.current.required).toBe(false);
+ expect(result.current.state).toBe('not_required');
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.visible).toBe(true);
+ expect(result.current.transition).toEqual(
+ expect.objectContaining({
+ kind: 'move',
+ from: [previous],
+ retained: [],
+ targets: [],
+ detachable: true,
+ }),
+ );
+ // Switching agents does not silently detach. Only a successful transition clears the seal.
+ expect(original.codeWorkspaces).toEqual([previous]);
+ rerender({
+ chat: { ...original, codeEnvironmentMode: 'without_attached', codeWorkspaces: undefined },
+ });
+ expect(result.current.transition).toBeUndefined();
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.visible).toBe(false);
+ },
+ );
+
+ it('keeps the no-environment detach hidden on a move-only deployment', () => {
+ mockStartupConfig.mockReturnValue({
+ codeEnvironmentDecisionVersion: 1,
+ codeEnvironmentMoveVersion: 1,
+ });
+ mockAgentPermissions().agent.tools = [];
+ mockAgentPermissions().agent.stateful_code_sessions = false;
+ const { result } = renderHook(() => useCodeWorkspace(sealed([mac])));
+ expect(result.current.required).toBe(false);
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.transition).toBeUndefined();
+ expect(result.current.visible).toBe(false);
});
it('offers to move the chat instead of an unusable workspace choice', () => {
@@ -518,7 +653,9 @@ describe('useCodeWorkspace', () => {
expect(result.current.locked).toBe(true);
expect(result.current.state).toBe('relocatable');
expect(result.current.canSubmit).toBe(false);
- expect(result.current.relocation).toEqual({
+ expect(result.current.transition).toEqual({
+ kind: 'move',
+ detachable: true,
conversationId: 'existing',
from: [mac],
previous: [{ id: 'mac', name: 'Danny Mac' }],
@@ -541,7 +678,9 @@ describe('useCodeWorkspace', () => {
expect(result.current.state).toBe('relocatable');
expect(result.current.canSubmit).toBe(false);
- expect(result.current.relocation).toEqual({
+ expect(result.current.transition).toEqual({
+ kind: 'move',
+ detachable: true,
conversationId: 'existing',
from: [gone, kept],
previous: [{ id: 'gone-vm', name: undefined }],
@@ -568,12 +707,16 @@ describe('useCodeWorkspace', () => {
);
expect(result.current.state).toBe('relocatable');
- expect(result.current.relocation?.previous).toEqual([{ id: 'mac', name: undefined }]);
+ expect(result.current.transition?.previous).toEqual([{ id: 'mac', name: undefined }]);
});
it.each([
- { codeEnvironmentDecisionVersion: 1, codeEnvironmentMoveVersion: 1 },
- { codeEnvironmentMoveVersion: 1 },
+ {
+ codeEnvironmentDecisionVersion: 1,
+ codeEnvironmentMoveVersion: 1,
+ codeEnvironmentTransitionVersion: 2,
+ },
+ { codeEnvironmentMoveVersion: 1, codeEnvironmentTransitionVersion: 2 },
])('carries over a sealed workspace the agents still use: %j', (startupConfig) => {
mockStartupConfig.mockReturnValue(startupConfig);
const primary = {
@@ -619,29 +762,184 @@ describe('useCodeWorkspace', () => {
const { result } = renderHook(() => useCodeWorkspace(sealed([kept])));
expect(result.current.state).toBe('relocatable');
- expect(result.current.relocation?.previous).toEqual([]);
- expect(result.current.relocation?.retained).toEqual([kept]);
- expect(result.current.relocation?.targets.map(({ environment }) => environment.id)).toEqual([
+ expect(result.current.transition?.previous).toEqual([]);
+ expect(result.current.transition?.retained).toEqual([kept]);
+ expect(result.current.transition?.targets.map(({ environment }) => environment.id)).toEqual([
'team-vm',
]);
});
+ /** A second machine the agents use that no set of picks can cover: unreachable, so it is
+ * neither carried over nor selectable. */
+ const withUnreachableSecondEnvironment = () => {
+ const primary = {
+ id: 'agent_primary',
+ stateful_code_sessions: true,
+ code_environment_id: 'personal-vm',
+ tools: [Tools.execute_code],
+ subagents: { enabled: true, agent_ids: ['child'] },
+ };
+ mockAgentPermissions.mockImplementation((id?: string) => ({
+ agent: id === 'agent_primary' ? primary : undefined,
+ tools: id === 'agent_primary' ? primary.tools : undefined,
+ }));
+ mockAgentsMap.mockReturnValue({
+ child: {
+ id: 'child',
+ stateful_code_sessions: true,
+ code_environment_id: 'team-vm',
+ tools: [Tools.execute_code],
+ },
+ });
+ mockAgentsConfig().agentsConfig.statefulCodeSessions.environments.push({
+ id: 'team-vm',
+ name: 'Team VM',
+ type: 'attached',
+ baseURL: 'https://two.example.com',
+ });
+ mockStatus.mockReturnValue([mockStatus()[0], { isLoading: false, isError: true }]);
+ };
+
+ /* A transition replaces the decision whole, so one that named only the reachable machines
+ * would seal a decision the next turn refuses, trading one dead end for a sealed one. */
+ it('refuses to attach while another machine the agents use is unreachable', () => {
+ withUnreachableSecondEnvironment();
+
+ const { result } = renderHook(() =>
+ useCodeWorkspace({
+ ...conversation(),
+ conversationId: 'existing',
+ codeEnvironmentMode: 'without_attached',
+ } as TConversation),
+ );
+
+ /** The chat keeps running without a workspace, which an unreachable machine does not change. */
+ expect(result.current.state).toBe('without_attached');
+ expect(result.current.canSubmit).toBe(true);
+ /** Already running without a workspace, so there is nothing to escape to. */
+ expect(result.current.transition).toBeUndefined();
+ expect(result.current.visible).toBe(true);
+ });
+
+ it('offers only to continue without a workspace when a machine cannot be covered', () => {
+ withUnreachableSecondEnvironment();
+ const kept = { environmentId: 'personal-vm', workspaceId: 'project-a' };
+
+ const { result } = renderHook(() => useCodeWorkspace(sealed([kept])));
+
+ expect(result.current.state).toBe('unavailable');
+ expect(result.current.canSubmit).toBe(false);
+ /** No partial decision on offer: an empty target set is the detach, and that is the escape. */
+ expect(result.current.transition).toEqual(
+ expect.objectContaining({
+ kind: 'move',
+ detachable: true,
+ from: [kept],
+ retained: [],
+ targets: [],
+ }),
+ );
+ });
+
+ /* A replica advertising the move-only protocol refuses an attach as `locked` and an empty
+ * target set as `invalid`, so those wait for v2 while the move it already serves keeps working
+ * — a mixed-version deployment must not lose the recovery path it had. */
+ describe('against a deployment that only supports moves', () => {
+ beforeEach(() => {
+ mockStartupConfig.mockReturnValue({
+ codeEnvironmentDecisionVersion: 1,
+ codeEnvironmentMoveVersion: 1,
+ });
+ });
+
+ it('keeps the move but withholds leaving attached execution', () => {
+ mockAgentsConfig().agentsConfig.statefulCodeSessions.environments.push({
+ id: 'mac',
+ name: 'Danny Mac',
+ type: 'attached',
+ baseURL: 'https://code.example.com',
+ });
+
+ const { result } = renderHook(() => useCodeWorkspace(sealed([mac])));
+
+ expect(result.current.state).toBe('relocatable');
+ expect(result.current.transition).toEqual(
+ expect.objectContaining({ kind: 'move', detachable: false }),
+ );
+ });
+
+ it('offers no attach to a chat that continues without a workspace', () => {
+ const { result } = renderHook(() =>
+ useCodeWorkspace({
+ ...conversation(),
+ conversationId: 'existing',
+ codeEnvironmentMode: 'without_attached',
+ } as TConversation),
+ );
+
+ expect(result.current.state).toBe('without_attached');
+ expect(result.current.transition).toBeUndefined();
+ });
+
+ /** Nothing to move onto and no detach to offer, so the composer reports the state instead. */
+ it('offers nothing when a machine the agents use cannot be covered', () => {
+ withUnreachableSecondEnvironment();
+ const kept = { environmentId: 'personal-vm', workspaceId: 'project-a' };
+
+ const { result } = renderHook(() => useCodeWorkspace(sealed([kept])));
+
+ expect(result.current.state).toBe('unavailable');
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.transition).toBeUndefined();
+ expect(result.current.visible).toBe(true);
+ });
+ });
+
it('waits for the new machine before offering a move', () => {
mockStatus.mockReturnValue([{ isLoading: true, isError: false }]);
const { result } = renderHook(() => useCodeWorkspace(sealed([mac])));
expect(result.current.state).toBe('loading');
- expect(result.current.relocation).toBeUndefined();
+ expect(result.current.transition).toBeUndefined();
+ });
+
+ /* The sealed workspace cannot be swapped for another on the same machine, so the only decision
+ * left is whether to keep waiting for it. */
+ it.each([
+ {
+ name: 'the sealed machine lost its workspace',
+ stored: { environmentId: 'personal-vm', workspaceId: 'removed-project' },
+ state: 'missing',
+ status: undefined,
+ },
+ {
+ name: 'the sealed machine is unreachable',
+ stored: { environmentId: 'personal-vm', workspaceId: 'project-a' },
+ state: 'unavailable',
+ status: { isLoading: false, isError: true },
+ },
+ ])('offers to continue without a workspace when $name', ({ stored, state, status }) => {
+ if (status != null) mockStatus.mockReturnValue([status]);
+
+ const { result } = renderHook(() => useCodeWorkspace(sealed([stored])));
+
+ expect(result.current.state).toBe(state);
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.visible).toBe(true);
+ expect(result.current.transition).toEqual(
+ expect.objectContaining({ kind: 'move', detachable: true, from: [stored], targets: [] }),
+ );
});
it('does not offer recovery to an API that only supports environment moves', () => {
+ mockStartupConfig.mockReturnValue({ codeEnvironmentMoveVersion: 1 });
const removed = { environmentId: 'personal-vm', workspaceId: 'removed-project' };
const { result } = renderHook(() => useCodeWorkspace(sealed([removed])));
expect(result.current.state).toBe('missing');
- expect(result.current.relocation).toBeUndefined();
+ expect(result.current.transition).toBeUndefined();
});
describe('missing workspace recovery', () => {
@@ -668,7 +966,9 @@ describe('useCodeWorkspace', () => {
expect(result.current.canSubmit).toBe(false);
expect(result.current.selections).toBeUndefined();
expect(result.current.resolveSubmission([missing], 'attached')).toBeUndefined();
- expect(result.current.relocation).toEqual({
+ expect(result.current.transition).toEqual({
+ kind: 'move',
+ detachable: false,
conversationId: 'existing',
from: [missing],
previous: [],
@@ -680,7 +980,7 @@ describe('useCodeWorkspace', () => {
expect(result.current.state).toBe('ready');
expect(result.current.locked).toBe(true);
expect(result.current.canSubmit).toBe(true);
- expect(result.current.relocation).toBeUndefined();
+ expect(result.current.transition).toBeUndefined();
},
);
@@ -693,20 +993,20 @@ describe('useCodeWorkspace', () => {
mockStartupConfig.mockReturnValue(config);
const { result } = renderHook(() => useCodeWorkspace(sealed([missing])));
expect(result.current.state).toBe('missing');
- expect(result.current.relocation).toBeUndefined();
+ expect(result.current.transition).toBeUndefined();
expect(result.current.canSubmit).toBe(false);
});
it('preserves ordinary environment moves on a recovery-capable API', () => {
const { result } = renderHook(() => useCodeWorkspace(sealed([mac])));
expect(result.current.state).toBe('relocatable');
- expect(result.current.relocation?.targets[0].state).toBe('choose');
+ expect(result.current.transition?.targets[0].state).toBe('choose');
});
it('offers the empty recovery picker without inventing a replacement', () => {
mockStatus()[0].data.workspaces = [];
const { result } = renderHook(() => useCodeWorkspace(sealed([missing])));
- expect(result.current.relocation?.targets[0].workspaces).toEqual([]);
+ expect(result.current.transition?.targets[0].workspaces).toEqual([]);
expect(result.current.canSubmit).toBe(false);
});
@@ -746,19 +1046,94 @@ describe('useCodeWorkspace', () => {
expect(result.current.canSubmit).toBe(false);
if (['loading', 'unavailable', 'unsupported'].includes(state)) {
- expect(result.current.relocation).toBeUndefined();
+ expect(result.current.transition).toBeUndefined();
return;
}
- expect(result.current.relocation?.from).toEqual(from);
- expect(result.current.relocation?.retained).toEqual(state === 'ready' ? [kept] : []);
+ expect(result.current.transition?.from).toEqual(from);
+ expect(result.current.transition?.retained).toEqual(state === 'ready' ? [kept] : []);
expect(
- result.current.relocation?.targets.map(({ environment }) => environment.id),
+ result.current.transition?.targets.map(({ environment }) => environment.id),
).toEqual(state === 'ready' ? ['personal-vm'] : ['personal-vm', 'team-vm']);
},
);
});
- it('does not offer an attached machine to a chat that continues without one', () => {
+ it('offers both missing-workspace replacement and explicit detach when both are advertised', () => {
+ mockStartupConfig.mockReturnValue({
+ codeEnvironmentDecisionVersion: 1,
+ codeEnvironmentMoveVersion: 1,
+ codeWorkspaceRecoveryVersion: 1,
+ codeEnvironmentTransitionVersion: 2,
+ });
+ const missing = { environmentId: 'personal-vm', workspaceId: 'removed-project' };
+ const { result } = renderHook(() => useCodeWorkspace(sealed([missing])));
+ expect(result.current.state).toBe('relocatable');
+ expect(result.current.canSubmit).toBe(false);
+ expect(result.current.transition).toMatchObject({
+ kind: 'move',
+ detachable: true,
+ from: [missing],
+ targets: [expect.objectContaining({ state: 'missing' })],
+ });
+ });
+
+ it('keeps a reachable sealed workspace out of the composer', () => {
+ const kept = { environmentId: 'personal-vm', workspaceId: 'project-a' };
+
+ const { result } = renderHook(() => useCodeWorkspace(sealed([kept])));
+
+ expect(result.current.state).toBe('ready');
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.transition).toBeUndefined();
+ expect(result.current.visible).toBe(false);
+ });
+
+ /* A chat that recorded running without a workspace keeps that decision until its owner attaches
+ * one; switching it to a coding agent is a transition, not a dead end. */
+ it('offers to attach a workspace to a chat that continues without one', () => {
+ const withoutAttached = {
+ ...conversation(),
+ conversationId: 'existing',
+ codeEnvironmentMode: 'without_attached',
+ } as TConversation;
+
+ const { result } = renderHook(() => useCodeWorkspace(withoutAttached));
+
+ expect(result.current.state).toBe('without_attached');
+ expect(result.current.canSubmit).toBe(true);
+ expect(result.current.visible).toBe(true);
+ expect(result.current.transition).toEqual({
+ kind: 'attach',
+ detachable: false,
+ conversationId: 'existing',
+ from: [],
+ previous: [],
+ retained: [],
+ targets: [
+ expect.objectContaining({
+ environment: expect.objectContaining({ id: 'personal-vm' }),
+ state: 'choose',
+ workspaces: [{ id: 'project-a', name: 'Project A' }],
+ }),
+ ],
+ });
+ });
+
+ it.each([
+ { name: 'the API cannot move chats', config: { codeEnvironmentDecisionVersion: 1 } },
+ {
+ name: 'no machine is reachable',
+ config: {
+ codeEnvironmentDecisionVersion: 1,
+ codeEnvironmentMoveVersion: 1,
+ codeEnvironmentTransitionVersion: 2,
+ },
+ status: { isLoading: false, isError: true },
+ },
+ ])('still reports a chat running without a workspace when $name', ({ config, status }) => {
+ mockStartupConfig.mockReturnValue(config);
+ if (status != null) mockStatus.mockReturnValue([status]);
+
const { result } = renderHook(() =>
useCodeWorkspace({
...conversation(),
@@ -769,10 +1144,11 @@ describe('useCodeWorkspace', () => {
expect(result.current.state).toBe('without_attached');
expect(result.current.canSubmit).toBe(true);
- expect(result.current.relocation).toBeUndefined();
+ expect(result.current.visible).toBe(true);
+ expect(result.current.transition).toBeUndefined();
});
- it('attaches a sole workspace to a saved chat that never recorded a decision', () => {
+ it('offers but does not automatically attach a sole workspace to an undecided saved chat', () => {
const { result } = renderHook(() =>
useCodeWorkspace({ ...conversation(), conversationId: 'existing' } as TConversation),
);
@@ -783,8 +1159,7 @@ describe('useCodeWorkspace', () => {
{ environmentId: 'personal-vm', workspaceId: 'project-a' },
]);
expect(result.current.resolveSubmission()).toEqual({
- codeEnvironmentMode: 'attached',
- codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }],
+ codeEnvironmentMode: 'without_attached',
});
});
@@ -792,7 +1167,13 @@ describe('useCodeWorkspace', () => {
* decision its owner never made: nothing to select, and Send disabled. */
it.each([
{ support: { codeEnvironmentDecisionVersion: 1 } },
- { support: { codeEnvironmentDecisionVersion: 1, codeEnvironmentMoveVersion: 1 } },
+ {
+ support: {
+ codeEnvironmentDecisionVersion: 1,
+ codeEnvironmentMoveVersion: 1,
+ codeEnvironmentTransitionVersion: 2,
+ },
+ },
])('lets a saved chat with several workspaces choose one', ({ support }) => {
mockStartupConfig.mockReturnValue(support);
mockStatus()[0].data.workspaces.push({ id: 'project-b', name: 'Project B' });
@@ -804,7 +1185,7 @@ describe('useCodeWorkspace', () => {
expect(result.current.locked).toBe(false);
expect(result.current.state).toBe('choose');
- expect(result.current.relocation).toBeUndefined();
+ expect(result.current.transition).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({
diff --git a/client/src/hooks/Agents/__tests__/workspaceLifecycle.spec.tsx b/client/src/hooks/Agents/__tests__/workspaceLifecycle.spec.tsx
index 5f4bf838d5..43685c7a13 100644
--- a/client/src/hooks/Agents/__tests__/workspaceLifecycle.spec.tsx
+++ b/client/src/hooks/Agents/__tests__/workspaceLifecycle.spec.tsx
@@ -12,8 +12,7 @@ jest.mock('librechat-data-provider', () => {
return { ...actual, dataService: { ...actual.dataService } };
});
jest.mock('~/data-provider', () => ({
- useCodeEnvironmentStatusQueries: jest.requireActual('~/data-provider/CodeEnvironments')
- .useCodeEnvironmentStatusQueries,
+ ...jest.requireActual('~/data-provider/CodeEnvironments'),
useGetStartupConfig: () => ({ data: { codeEnvironmentDecisionVersion: 1 } }),
}));
jest.mock('../workspacePreferences', () => ({
diff --git a/client/src/hooks/Agents/codeDecision.ts b/client/src/hooks/Agents/codeDecision.ts
new file mode 100644
index 0000000000..4b20cafba4
--- /dev/null
+++ b/client/src/hooks/Agents/codeDecision.ts
@@ -0,0 +1,90 @@
+import { Constants } from 'librechat-data-provider';
+import type {
+ CodeEnvironmentMode,
+ EventSubmission,
+ CodeWorkspaceSelection,
+ TConversation,
+} from 'librechat-data-provider';
+
+function sameSelections(
+ left?: CodeWorkspaceSelection[],
+ right?: CodeWorkspaceSelection[],
+): boolean {
+ if (!left?.length || !right?.length) return !left?.length && !right?.length;
+ if (left.length !== right.length) return false;
+ const key = ({ environmentId, workspaceId }: CodeWorkspaceSelection) =>
+ JSON.stringify([environmentId, workspaceId]);
+ const held = new Set(left.map(key));
+ return right.every((selection) => held.has(key(selection)));
+}
+
+/**
+ * Folds the decision a submitted run establishes into the conversation that run belongs to. The
+ * server seals this pair for the rest of the chat, so the conversation has to carry it from the
+ * moment it is sent: a chat that becomes saved mid-run would otherwise hold no decision while the
+ * stored one is already sealed, and the composer would re-derive an agent default or a remembered
+ * preference that the sealed decision refuses — reporting "choose a workspace", with Send
+ * disabled, for a workspace the run is already using. Returns the same conversation when it
+ * already holds the decision, so an unchanged send never re-renders the composer.
+ */
+export function withSubmittedCodeDecision(
+ conversation: TConversation | null,
+ submitted: {
+ codeEnvironmentMode?: CodeEnvironmentMode;
+ codeWorkspaces?: CodeWorkspaceSelection[];
+ },
+): TConversation | null {
+ const { codeWorkspaces } = submitted;
+ // Older replicas accept selections without a mode. Preserve that submitted selection locally
+ // too, or the first saved-chat event drops an implicit default back to "Choose workspace".
+ const codeEnvironmentMode =
+ submitted.codeEnvironmentMode ?? ((codeWorkspaces?.length ?? 0) > 0 ? 'attached' : undefined);
+ if (conversation == null || codeEnvironmentMode == null) return conversation;
+ if (
+ conversation.codeEnvironmentMode === codeEnvironmentMode &&
+ sameSelections(conversation.codeWorkspaces, codeWorkspaces)
+ ) {
+ return conversation;
+ }
+ return { ...conversation, codeEnvironmentMode, codeWorkspaces };
+}
+
+/** Compare the pair, including absence: a failed first send may leave no persisted decision. */
+export function hasSameCodeDecision(
+ left: Pick<TConversation, 'codeEnvironmentMode' | 'codeWorkspaces'>,
+ right: Pick<TConversation, 'codeEnvironmentMode' | 'codeWorkspaces'>,
+): boolean {
+ return (
+ (left.codeEnvironmentMode ?? (left.codeWorkspaces?.length ? 'attached' : undefined)) ===
+ (right.codeEnvironmentMode ?? (right.codeWorkspaces?.length ? 'attached' : undefined)) &&
+ sameSelections(left.codeWorkspaces, right.codeWorkspaces)
+ );
+}
+
+/** The submission snapshot may still be `new` after creation/streaming assigned a durable id. */
+export function getFailedCodeDecisionRequest(submission: EventSubmission, resolvedId?: string) {
+ const conversationId = [
+ resolvedId,
+ submission.userMessage?.conversationId,
+ submission.initialResponse?.conversationId,
+ submission.conversation?.conversationId,
+ ].find(
+ (id): id is string =>
+ typeof id === 'string' &&
+ id.length > 0 &&
+ id !== Constants.NEW_CONVO &&
+ id !== Constants.PENDING_CONVO &&
+ !id.startsWith('_'),
+ );
+ const codeEnvironmentMode =
+ submission.codeEnvironmentMode ??
+ ((submission.codeWorkspaces?.length ?? 0) > 0 ? 'attached' : undefined);
+ if (conversationId == null || codeEnvironmentMode == null) return undefined;
+ return {
+ conversationId,
+ attempted: {
+ codeEnvironmentMode,
+ codeWorkspaces: submission.codeWorkspaces,
+ },
+ };
+}
diff --git a/client/src/hooks/Agents/index.ts b/client/src/hooks/Agents/index.ts
index 38fde48357..ede4362973 100644
--- a/client/src/hooks/Agents/index.ts
+++ b/client/src/hooks/Agents/index.ts
@@ -9,13 +9,14 @@ export { default as useAgentFileConfig } from './useAgentFileConfig';
export { default as useAgentUploadTarget } from './useAgentUploadTarget';
export type { AgentUploadTarget } from './useAgentUploadTarget';
export { default as useAgentToolPermissions } from './useAgentToolPermissions';
+export { withSubmittedCodeDecision } from './codeDecision';
export { default as useCodeApprovalMode } from './useCodeApprovalMode';
export { default as useCodeWorkspace } from './useCodeWorkspace';
export type {
CodeWorkspaceEnvironmentResult,
- CodeWorkspaceRelocation,
CodeWorkspaceResult,
CodeWorkspaceState,
+ CodeWorkspaceTransition,
} from './useCodeWorkspace';
export { default as useMCPToolOptions } from './useMCPToolOptions';
export * from './useApplyModelSpecAgents';
diff --git a/client/src/hooks/Agents/useCodeWorkspace.ts b/client/src/hooks/Agents/useCodeWorkspace.ts
index 67c7c8f5a3..c06943e106 100644
--- a/client/src/hooks/Agents/useCodeWorkspace.ts
+++ b/client/src/hooks/Agents/useCodeWorkspace.ts
@@ -9,6 +9,7 @@ import {
AgentCapabilities,
CODE_ENVIRONMENT_DECISION_VERSION,
CODE_ENVIRONMENT_MOVE_VERSION,
+ CODE_ENVIRONMENT_TRANSITION_VERSION,
CODE_WORKSPACE_RECOVERY_VERSION,
PermissionTypes,
Permissions,
@@ -22,8 +23,14 @@ import type {
TConversation,
TPublicCodeEnvironment,
} from 'librechat-data-provider';
+import type { CodeEnvironmentReconciliation } from '~/store/codeEnvironmentReconciliation';
+import {
+ useCodeEnvironmentStatusQueries,
+ useGetStartupConfig,
+ useIsReplacingConversationCodeEnvironment,
+ useConversationCodeEnvironmentRecovery,
+} from '~/data-provider';
import { collectReachableAgents, findExecutionEnvironment } from './useCodeApprovalMode';
-import { useCodeEnvironmentStatusQueries, useGetStartupConfig } from '~/data-provider';
import { useWorkspacePreferences } from './workspacePreferences';
import useAgentToolPermissions from './useAgentToolPermissions';
import useHasAccess from '~/hooks/Roles/useHasAccess';
@@ -49,12 +56,20 @@ export interface CodeWorkspaceEnvironmentResult {
}
/**
- * A saved chat whose attached decision no longer covers its agents' environments or whose
- * selected workspace is missing. Only its owner's explicit move replaces the sealed decision.
+ * A change of a saved chat's sealed decision that its owner may make from the composer. The
+ * decision stays sealed against implicit changes; only this explicit transition replaces it, and
+ * it never touches the chat's messages or copies a file between machines.
+ *
+ * - `move`: the attached decision no longer covers every environment the chat's agents use, most
+ * often because an agent was pointed at a different machine or its saved workspace disappeared.
+ * - `attach`: the chat has been running without an attached environment and can now take one, so
+ * switching a saved chat to a coding agent is a transition rather than a dead end.
*/
-export interface CodeWorkspaceRelocation {
+export interface CodeWorkspaceTransition {
+ kind: 'move' | 'attach';
conversationId: string;
- /** The persisted selections a move replaces, exactly as the conversation stores them. */
+ /** The persisted selections this replaces, exactly as the conversation stores them; empty for a
+ * chat that has been running without an attached environment. */
from: CodeWorkspaceSelection[];
/** Environments the decision covered that the agents no longer use. */
previous: Array<
@@ -64,17 +79,25 @@ export interface CodeWorkspaceRelocation {
retained: CodeWorkspaceSelection[];
/** Environments needing a new selection, including those whose workspace disappeared. */
targets: CodeWorkspaceEnvironmentResult[];
+ /** Whether the chat may leave attached execution and continue without a workspace. Offered when
+ * the machine it sealed is no longer usable, so an unreachable worker never silently becomes a
+ * changed execution mode and never strands the composer either. */
+ detachable: boolean;
}
export interface CodeWorkspaceResult {
+ recovery?: CodeEnvironmentReconciliation;
required: boolean;
supportsEnvironmentDecisions: boolean;
locked: boolean;
mode?: CodeEnvironmentMode;
state: CodeWorkspaceState;
canSubmit: boolean;
+ /** Whether the composer shows the workspace control. A chat running without an attached
+ * environment keeps it, so the state it is in stays visible and reversible. */
+ visible: boolean;
environments: CodeWorkspaceEnvironmentResult[];
- relocation?: CodeWorkspaceRelocation;
+ transition?: CodeWorkspaceTransition;
selections?: CodeWorkspaceSelection[];
resolveSelections: (
selections?: CodeWorkspaceSelection[],
@@ -135,6 +158,15 @@ export default function useCodeWorkspace(
startupConfig?.codeEnvironmentDecisionVersion === CODE_ENVIRONMENT_DECISION_VERSION;
const supportsEnvironmentMoves =
startupConfig?.codeEnvironmentMoveVersion === CODE_ENVIRONMENT_MOVE_VERSION;
+ /** Attaching an environment and leaving attached execution are advertised beside the move rather
+ * than as a higher move version, so a deployment mid-rollout keeps serving the move to a client
+ * that predates them, and a client that has them never offers a replica an attach it refuses as
+ * `locked` or an empty target set it calls `invalid`. */
+ const supportsEnvironmentTransitions =
+ supportsEnvironmentDecisions &&
+ startupConfig?.codeEnvironmentTransitionVersion === CODE_ENVIRONMENT_TRANSITION_VERSION;
+ const recovery = useConversationCodeEnvironmentRecovery(conversation?.conversationId);
+ const replacingDecision = useIsReplacingConversationCodeEnvironment(conversation?.conversationId);
const supportsWorkspaceRecovery =
supportsEnvironmentMoves &&
startupConfig?.codeWorkspaceRecoveryVersion === CODE_WORKSPACE_RECOVERY_VERSION;
@@ -358,6 +390,10 @@ export default function useCodeWorkspace(
let inferredMode: CodeEnvironmentMode | undefined = conversation?.codeEnvironmentMode;
if (inferredMode == null && storedSelections != null) {
inferredMode = 'attached';
+ } else if (inferredMode == null && !isNewChat && supportsEnvironmentDecisions) {
+ // Suggestions are not consent. Existing non-coding chats start without workspace access;
+ // only an explicit selection in the composer may attach their first coding turn.
+ inferredMode = 'without_attached';
} else if (inferredMode == null && selections != null) {
inferredMode = 'attached';
} else if (inferredMode == null && required && supportsEnvironmentDecisions) {
@@ -374,36 +410,6 @@ export default function useCodeWorkspace(
} else {
state = aggregateState(required, metadataComplete, environmentResults, selections);
}
- let relocation: CodeWorkspaceRelocation | undefined;
- if (
- supportsEnvironmentMoves &&
- locked &&
- (state === 'choose' || (supportsWorkspaceRecovery && state === 'missing')) &&
- environmentResults.every(({ state }) => ['ready', 'choose', 'missing'].includes(state)) &&
- inferredMode === 'attached' &&
- conversation?.conversationId != null &&
- storedSelections != null &&
- storedSelections.length > 0
- ) {
- const configuredEnvironments = statefulCodeSessions?.environments;
- relocation = {
- conversationId: conversation.conversationId,
- from: storedSelections,
- previous: storedSelections
- .filter(({ environmentId }) => !attachedEnvironmentIds.has(environmentId))
- .map(({ environmentId }) => ({
- id: environmentId,
- name: configuredEnvironments?.find(({ id }) => id === environmentId)?.name,
- })),
- retained: environmentResults.flatMap((result) =>
- result.state === 'ready' && result.selected != null ? [result.selected] : [],
- ),
- targets: environmentResults.filter(
- (result) => result.state === 'choose' || result.state === 'missing',
- ),
- };
- state = 'relocatable';
- }
const resolveSubmission = useCallback(
(
candidateSelections?: CodeWorkspaceSelection[],
@@ -411,7 +417,16 @@ export default function useCodeWorkspace(
):
| { codeEnvironmentMode?: CodeEnvironmentMode; codeWorkspaces?: CodeWorkspaceSelection[] }
| undefined => {
+ if (recovery != null) return undefined;
if (!required) return {};
+ /**
+ * A replacement in flight has no decided answer yet. The server checks for active work
+ * before it polls the target workspace, so a turn submitted during that poll starts under
+ * the decision being replaced, runs without the workspace its owner just chose, and the
+ * replacement still lands afterwards because the stored decision it swaps is unchanged.
+ * Nothing reports that to the reader, so the send waits instead.
+ */
+ if (replacingDecision) return undefined;
const requestedMode =
candidateMode ??
inferredMode ??
@@ -431,9 +446,94 @@ export default function useCodeWorkspace(
? undefined
: { codeEnvironmentMode: 'attached', codeWorkspaces };
},
- [inferredMode, required, resolveSelections, supportsEnvironmentDecisions],
+ [
+ inferredMode,
+ recovery,
+ replacingDecision,
+ required,
+ resolveSelections,
+ supportsEnvironmentDecisions,
+ ],
);
const canSubmit = resolveSubmission(storedSelections, conversation?.codeEnvironmentMode) != null;
+ let transition: CodeWorkspaceTransition | undefined;
+ if (
+ supportsEnvironmentMoves &&
+ locked &&
+ selectionMetadataComplete &&
+ state !== 'loading' &&
+ conversation?.conversationId != null
+ ) {
+ const configuredEnvironments = statefulCodeSessions?.environments;
+ const base = {
+ conversationId: conversation.conversationId,
+ from: storedSelections ?? [],
+ previous: (storedSelections ?? [])
+ .filter(({ environmentId }) => !attachedEnvironmentIds.has(environmentId))
+ .map(({ environmentId }) => ({
+ id: environmentId,
+ name: configuredEnvironments?.find(({ id }) => id === environmentId)?.name,
+ })),
+ retained: environmentResults.flatMap((result) =>
+ result.state === 'ready' && result.selected != null ? [result.selected] : [],
+ ),
+ targets: environmentResults.filter(
+ (result) =>
+ result.state === 'choose' || (supportsWorkspaceRecovery && result.state === 'missing'),
+ ),
+ };
+ /**
+ * A transition replaces the decision whole, so one that named only some of the environments
+ * the agents use would seal a decision the next turn refuses: `resolveSelections` resolves
+ * every environment or none. An environment that is unreachable, missing its workspace or on
+ * an outdated worker is neither carried over nor selectable, so no set of picks covers it, and
+ * offering the transition anyway would trade one dead end for a sealed one that needs a second
+ * transition to escape. Leaving attached execution stays available, since that is the escape.
+ */
+ const coversEveryEnvironment =
+ base.retained.length + base.targets.length === environmentResults.length;
+ if (
+ supportsEnvironmentTransitions &&
+ state === 'without_attached' &&
+ conversation.codeEnvironmentMode === 'without_attached' &&
+ base.targets.length > 0 &&
+ coversEveryEnvironment
+ ) {
+ /** Only a decision this chat actually recorded is sealed, so a chat that merely lacks the
+ * fields still chooses in the composer and needs no transition. */
+ transition = { ...base, kind: 'attach', detachable: false };
+ } else if (
+ inferredMode === 'attached' &&
+ (storedSelections?.length ?? 0) > 0 &&
+ // Dropping the last attached agent makes ordinary chat sendable, but does not remove
+ // its persisted seal. Keep the explicit detach action available for that conversation.
+ (state === 'choose' || !canSubmit || attachedEnvironments.length === 0)
+ ) {
+ const move: CodeWorkspaceTransition = {
+ ...base,
+ kind: 'move',
+ detachable: supportsEnvironmentTransitions,
+ ...(coversEveryEnvironment ? {} : { retained: [], targets: [] }),
+ };
+ /** An uncoverable environment leaves nothing to move onto, so the transition is worth
+ * offering only where leaving attached execution is also served. */
+ if (move.targets.length > 0 || move.retained.length > 0 || move.detachable) {
+ transition = move;
+ if (
+ state === 'choose' ||
+ (supportsWorkspaceRecovery && state === 'missing' && coversEveryEnvironment)
+ )
+ state = 'relocatable';
+ }
+ }
+ }
+ /** A sealed chat hides the control once its decision needs nothing from its owner, except while
+ * it runs without a workspace: that state is worth naming, and attaching one starts here. */
+ const visible =
+ recovery != null ||
+ transition != null ||
+ (required &&
+ (!locked || !canSubmit || transition != null || inferredMode === 'without_attached'));
const rememberSelection = useCallback(
(selection: CodeWorkspaceSelection) => {
preferences.remember(selection.environmentId, selection.workspaceId, [
@@ -443,14 +543,16 @@ export default function useCodeWorkspace(
[preferences, workspaceMetadata.preferenceAgentIds],
);
return {
+ recovery,
required,
supportsEnvironmentDecisions,
locked,
mode: inferredMode,
state,
canSubmit,
+ visible,
environments: environmentResults,
- relocation,
+ transition,
selections,
resolveSelections,
resolveSubmission,
diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
index 2bce016518..4a66996cfb 100644
--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
@@ -22,6 +22,7 @@ const mockGetExpiry = jest.fn(() => 'expiry-key');
const mockGetQueryData = jest.fn(() => ({}));
const mockLoggerWarn = jest.fn();
const mockGetLatestConversation = jest.fn(() => null as TConversation | null);
+const mockSetConversation = jest.fn();
const mockResolveCodeWorkspaceSubmission = jest.fn<
| { codeEnvironmentMode?: CodeEnvironmentMode; codeWorkspaces?: CodeWorkspaceSelection[] }
| undefined,
@@ -143,6 +144,7 @@ function renderAsk(
getMessages,
setMessages,
setSubmission,
+ setConversation: mockSetConversation,
}),
);
@@ -210,6 +212,56 @@ describe('useChatFunctions ask', () => {
expect(submission.codeWorkspaces).toEqual([selection]);
});
+ /* The server seals the decision this run establishes. A chat that becomes saved mid-run must hold
+ * it too, or the composer re-derives an agent default the seal refuses and reports "choose a
+ * workspace" with Send disabled until the page reloads. */
+ it('records the decision the run establishes on the conversation it belongs to', () => {
+ const selection = { environmentId: 'personal-vm', workspaceId: 'project-a' };
+ mockResolveCodeWorkspaceSubmission.mockReturnValue({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [selection],
+ });
+ const { result } = renderAsk([]);
+
+ act(() => {
+ result.current.ask({ text: 'Edit the file', conversationId: 'conversation-1' });
+ });
+
+ expect(mockSetConversation).toHaveBeenCalledTimes(1);
+ const update = mockSetConversation.mock.calls[0][0];
+ const current = conversation('conversation-1');
+ expect(update(current)).toEqual({
+ ...current,
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [selection],
+ });
+ /** Another chat's conversation is never stamped with this run's decision. */
+ expect(update(conversation('conversation-2'))).toEqual(conversation('conversation-2'));
+ expect(update(null)).toBeNull();
+ });
+
+ it('leaves a conversation that already holds the decision untouched', () => {
+ const selection = { environmentId: 'personal-vm', workspaceId: 'project-a' };
+ mockResolveCodeWorkspaceSubmission.mockReturnValue({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [selection],
+ });
+ const sealed = {
+ ...conversation('conversation-1'),
+ codeEnvironmentMode: 'attached' as const,
+ codeWorkspaces: [selection],
+ };
+ mockGetLatestConversation.mockReturnValue(sealed);
+ const { result } = renderAsk([]);
+
+ act(() => {
+ result.current.ask({ text: 'Edit the file', conversationId: 'conversation-1' });
+ });
+
+ const update = mockSetConversation.mock.calls[0][0];
+ expect(update(sealed)).toBe(sealed);
+ });
+
it('refuses every direct send before consuming composer context during handoff', () => {
const family = revealedQueuedTurnFamily('conversation-1');
getDefaultStore().set(family, {
@@ -382,6 +434,7 @@ describe('useChatFunctions regenerate', () => {
getMessages: () => messages,
setMessages,
setSubmission,
+ setConversation: mockSetConversation,
}),
);
@@ -476,6 +529,7 @@ describe('useChatFunctions ask attachments', () => {
getMessages: () => [],
setMessages,
setSubmission,
+ setConversation: mockSetConversation,
files,
setFiles,
}),
@@ -514,6 +568,7 @@ describe('useChatFunctions ask attachments', () => {
getMessages: () => [],
setMessages,
setSubmission,
+ setConversation: mockSetConversation,
files: new Map(),
setFiles,
}),
@@ -614,6 +669,7 @@ describe('useChatFunctions ask compaction and the composer', () => {
getMessages: () => messages,
setMessages,
setSubmission,
+ setConversation: mockSetConversation,
files,
setFiles,
}),
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index d3b370da95..18bb4fa29f 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -39,6 +39,7 @@ import {
} from '~/utils';
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 useCodeWorkspace from '~/hooks/Agents/useCodeWorkspace';
@@ -204,6 +205,7 @@ export default function useChatFunctions({
isSubmitting,
latestMessage,
setSubmission,
+ setConversation,
conversation: immutableConversation,
}: {
index?: number;
@@ -216,6 +218,9 @@ export default function useChatFunctions({
files?: Map<string, ExtendedFile>;
setFiles?: SetterOrUpdater<Map<string, ExtendedFile>>;
setSubmission: SetterOrUpdater<TSubmission | null>;
+ /** Supplied by the host that owns the conversation atom, so a send records the decision it
+ * established without this hook becoming a second writer of that state. */
+ setConversation: SetterOrUpdater<TConversation | null>;
}) {
const navigate = useNavigate();
const getSender = useGetSender();
@@ -784,6 +789,14 @@ export default function useChatFunctions({
setMessages([...submissionMessages, currentMsg, initialResponse]);
}
+ /** Carry the submitted choice through the first saved-chat event instead of re-deriving it
+ * from agent defaults. This is optimistic: the SSE error path reconciles an existing chat
+ * with its authoritative server decision if admission fails. */
+ setConversation((current) =>
+ current == null || current.conversationId !== conversation?.conversationId
+ ? current
+ : withSubmittedCodeDecision(current, workspaceSubmission),
+ );
setSubmissionStart(Date.now());
setSubmission(submission);
logger.dir('message_stream', submission, { depth: null });
diff --git a/client/src/hooks/Chat/useChatHelpers.ts b/client/src/hooks/Chat/useChatHelpers.ts
index e99ede8eb0..46eb08bc29 100644
--- a/client/src/hooks/Chat/useChatHelpers.ts
+++ b/client/src/hooks/Chat/useChatHelpers.ts
@@ -161,6 +161,7 @@ export default function useChatHelpers(index = 0, paramId?: string) {
conversation,
latestMessage,
setSubmission,
+ setConversation,
});
const askRef = useRef(_ask);
diff --git a/client/src/hooks/SSE/__tests__/useAdaptiveSSE.spec.ts b/client/src/hooks/SSE/__tests__/useAdaptiveSSE.spec.ts
new file mode 100644
index 0000000000..099d3c936d
--- /dev/null
+++ b/client/src/hooks/SSE/__tests__/useAdaptiveSSE.spec.ts
@@ -0,0 +1,48 @@
+import { renderHook } from '@testing-library/react';
+import { EModelEndpoint } from 'librechat-data-provider';
+import type { TSubmission } from 'librechat-data-provider';
+import useResumableSSE from '../useResumableSSE';
+import useAdaptiveSSE from '../useAdaptiveSSE';
+import useSSE from '../useSSE';
+
+jest.mock('../useSSE', () => jest.fn());
+jest.mock('../useResumableSSE', () => jest.fn(() => ({ streamId: 'stream' })));
+
+const helpers = {
+ setMessages: jest.fn(),
+ getMessages: jest.fn(),
+ setConversation: jest.fn(),
+ setIsSubmitting: jest.fn(),
+ newConversation: jest.fn(),
+};
+
+beforeEach(() => jest.clearAllMocks());
+
+it.each([
+ { endpoint: EModelEndpoint.agents },
+ { endpoint: 'custom', endpointType: EModelEndpoint.agents },
+ { endpoint: EModelEndpoint.openAI },
+])(
+ 'routes $endpoint through resumable lifecycle, never legacy local cancellation',
+ (conversation) => {
+ const submission = {
+ conversation: { ...conversation, conversationId: 'saved' },
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [{ environmentId: 'vm', workspaceId: 'repo' }],
+ } as TSubmission;
+ const { rerender } = renderHook(({ value }) => useAdaptiveSSE(value, helpers), {
+ initialProps: { value: submission as TSubmission | null },
+ });
+ expect(useSSE).toHaveBeenLastCalledWith(null, helpers, false, 0);
+ expect(useResumableSSE).toHaveBeenLastCalledWith(submission, helpers, false, 0);
+ rerender({ value: null });
+ expect(useSSE).toHaveBeenLastCalledWith(null, helpers, false, 0);
+ },
+);
+
+it('preserves the Assistants transport and its server abort endpoint', () => {
+ const submission = { conversation: { endpoint: EModelEndpoint.assistants } } as TSubmission;
+ renderHook(() => useAdaptiveSSE(submission, helpers));
+ expect(useSSE).toHaveBeenLastCalledWith(submission, helpers, false, 0);
+ expect(useResumableSSE).toHaveBeenLastCalledWith(null, helpers, false, 0);
+});
diff --git a/client/src/hooks/SSE/__tests__/useEventHandlers.cancel.spec.tsx b/client/src/hooks/SSE/__tests__/useEventHandlers.cancel.spec.tsx
new file mode 100644
index 0000000000..24ab6732a1
--- /dev/null
+++ b/client/src/hooks/SSE/__tests__/useEventHandlers.cancel.spec.tsx
@@ -0,0 +1,159 @@
+import { createElement } from 'react';
+import { createStore, Provider } from 'jotai';
+import { act, renderHook } from '@testing-library/react';
+import { dataService, EModelEndpoint } from 'librechat-data-provider';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { EventSubmission, TConversation, TMessage } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import { useIsReplacingConversationCodeEnvironment } from '~/data-provider/CodeEnvironments';
+import useEventHandlers from '../useEventHandlers';
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return { ...actual, dataService: { ...actual.dataService, getConversationById: jest.fn() } };
+});
+jest.mock('recoil', () => ({
+ useSetRecoilState: () => jest.fn(),
+ useRecoilCallback: () => jest.fn(),
+}));
+jest.mock('react-router-dom', () => ({
+ useParams: () => ({ conversationId: 'saved' }),
+ useNavigate: () => jest.fn(),
+ useLocation: () => ({ pathname: '/c/saved' }),
+}));
+jest.mock('~/store', () => ({
+ __esModule: true,
+ default: { abortScroll: 'abortScroll', submissionStartFamily: () => 'start' },
+}));
+jest.mock('~/hooks/AuthContext', () => ({ useAuthContext: () => ({}) }));
+jest.mock('~/Providers', () => ({ useLiveAnnouncer: () => ({ announcePolite: jest.fn() }) }));
+jest.mock('~/hooks/Agents', () => ({ useApplyAgentTemplate: () => jest.fn() }));
+jest.mock('~/hooks/Chat/useFocusRegeneratedResponse', () => () => jest.fn());
+jest.mock('../useContentHandler', () => () => ({
+ contentHandler: jest.fn(),
+ resetContentHandler: jest.fn(),
+}));
+jest.mock('../useAttachmentHandler', () => () => jest.fn());
+jest.mock('../useStepHandler', () => () => ({
+ stepHandler: jest.fn(),
+ clearStepMaps: jest.fn(),
+ resetSubagentAtoms: jest.fn(),
+ resetPtcAtoms: jest.fn(),
+ prunePtcTraces: jest.fn(),
+ syncStepMessage: jest.fn(),
+ cancelPendingDeltaFlush: jest.fn(),
+ flushPendingDeltas: jest.fn(),
+}));
+jest.mock('~/data-provider', () => ({
+ ...jest.requireActual('~/data-provider/CodeEnvironments'),
+ startupConfigKey: ['startup'],
+ queueTitleGeneration: jest.fn(),
+ markTitleGenerationProcessed: jest.fn(),
+}));
+jest.mock('~/utils', () => ({
+ logger: { log: jest.fn(), info: jest.fn(), debug: jest.fn(), error: jest.fn() },
+ setDraft: jest.fn(),
+ scrollToEnd: jest.fn(),
+ getConversationDraftId: jest.fn(),
+ hasRealTitle: () => false,
+ withoutListFlags: (value: unknown) => value,
+ setDocumentTitle: jest.fn(),
+ requestChatFocus: jest.fn(),
+ getAllContentText: () => '',
+ upsertConvoInAllQueries: jest.fn(),
+ updateConvoInAllQueries: jest.fn(),
+ removeConvoFromAllQueries: jest.fn(),
+ findConversationInInfinite: () => undefined,
+ preserveStreamedContentIdentity: (_old: unknown, current: unknown) => current,
+ isEmptyContentPart: () => false,
+ getPartKeyIndex: jest.fn(),
+ CONVERSATION_LIST_KEYS: [],
+}));
+
+const attempted = {
+ codeEnvironmentMode: 'attached' as const,
+ codeWorkspaces: [{ environmentId: 'attempted', workspaceId: 'repo' }],
+};
+const user = {
+ conversationId: 'saved',
+ messageId: 'user',
+ parentMessageId: 'root',
+ text: 'run',
+ isCreatedByUser: true,
+} as TMessage;
+const response = {
+ conversationId: 'saved',
+ messageId: 'response',
+ parentMessageId: 'user',
+ text: '',
+ content: [],
+ isCreatedByUser: false,
+} as TMessage;
+const submission = {
+ isTemporary: false,
+ endpointOption: { endpoint: EModelEndpoint.agents },
+ conversation: { conversationId: 'saved', endpoint: EModelEndpoint.agents },
+ userMessage: user,
+ initialResponse: response,
+ messages: [],
+ ...attempted,
+} as EventSubmission;
+
+describe('local cancellation decision reconciliation', () => {
+ beforeEach(() => jest.clearAllMocks());
+ afterEach(() => jest.restoreAllMocks());
+
+ it.each(['streamed', 'minimal', 'navigated'])(
+ 'does not use a synthetic %s cancel as evidence that the server settled',
+ async (kind) => {
+ const read = jest.spyOn(dataService, 'getConversationById');
+ const store = createStore();
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(
+ Provider,
+ { store },
+ createElement(QueryClientProvider, { client: queryClient }, children),
+ );
+ const messages = kind === 'minimal' ? [] : [user, response];
+ let current = { ...submission.conversation, ...attempted } as TConversation;
+ const setConversation = jest.fn((update) => {
+ current = typeof update === 'function' ? update(current) : update;
+ });
+ const setIsSubmitting = jest.fn();
+ const newConversation = jest.fn();
+ const { result } = renderHook(
+ () => ({
+ handlers: useEventHandlers({
+ getMessages: () => (kind === 'navigated' ? [] : messages),
+ setMessages: jest.fn(),
+ setCompleted: jest.fn(),
+ setConversation,
+ setIsSubmitting,
+ setShowStopButton: jest.fn(),
+ newConversation,
+ }),
+ blocked: useIsReplacingConversationCodeEnvironment('saved'),
+ otherBlocked: useIsReplacingConversationCodeEnvironment('other'),
+ }),
+ { wrapper },
+ );
+ const currentOther = { conversationId: 'other', ...attempted } as TConversation;
+ if (kind === 'navigated') current = currentOther;
+
+ await act(async () => {
+ await result.current.handlers.abortConversation('saved', submission, messages);
+ });
+ expect(read).not.toHaveBeenCalled();
+ expect(result.current.blocked).toBe(false);
+ expect(result.current.otherBlocked).toBe(false);
+ if (kind === 'minimal') expect(newConversation).toHaveBeenCalled();
+ if (kind !== 'navigated') expect(setIsSubmitting).toHaveBeenCalledWith(false);
+
+ if (kind === 'navigated') expect(current).toBe(currentOther);
+ else expect(current.codeWorkspaces).toEqual(attempted.codeWorkspaces);
+ },
+ );
+});
diff --git a/client/src/hooks/SSE/__tests__/useEventHandlers.spec.ts b/client/src/hooks/SSE/__tests__/useEventHandlers.spec.ts
index d38e5b0dbb..058d8abbc9 100644
--- a/client/src/hooks/SSE/__tests__/useEventHandlers.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useEventHandlers.spec.ts
@@ -17,7 +17,9 @@ import {
resolveErrorTurn,
startedAsNewConversation,
} from '~/hooks/SSE/useEventHandlers';
+import { getFailedCodeDecisionRequest } from '~/hooks/Agents/codeDecision';
import { stripStreamedIndexStamps, getPartKeyIndex } from '~/utils';
+import buildDefaultConvo from '~/utils/buildDefaultConvo';
describe('buildCreatedInitialResponse', () => {
const userMessage = {
@@ -615,3 +617,66 @@ describe('resolveErrorTurn', () => {
expect(fromChat.errorResponse.parentMessageId).toBe('user-1');
});
});
+
+describe('first-send workspace error recovery', () => {
+ const selection = { environmentId: 'machine', workspaceId: 'repo' };
+ const submission = {
+ conversation: { conversationId: 'new', endpoint: 'agents', agent_id: 'agent' },
+ userMessage: { conversationId: 'generated-id', messageId: 'user' },
+ initialResponse: { conversationId: 'generated-id', messageId: 'response' },
+ codeWorkspaces: [selection],
+ } as EventSubmission;
+
+ it('preserves a legacy implicit choice in the recovery preset and reconciles its real id', () => {
+ const preset = buildRecoveryPreset(
+ submission.conversation,
+ undefined,
+ 'generated-id',
+ submission,
+ );
+ expect(preset.codeEnvironmentMode).toBe('attached');
+ expect(preset.codeWorkspaces).toEqual([selection]);
+ const rebuilt = buildDefaultConvo({
+ conversation: {
+ conversationId: 'generated-id',
+ codeEnvironmentMode: preset.codeEnvironmentMode,
+ codeWorkspaces: preset.codeWorkspaces,
+ } as TConversation,
+ lastConversationSetup: preset as TConversation,
+ endpoint: 'agents' as never,
+ models: [],
+ });
+ expect(rebuilt.codeEnvironmentMode).toBe('attached');
+ expect(rebuilt.codeWorkspaces).toEqual([selection]);
+ expect(getFailedCodeDecisionRequest(submission)).toEqual({
+ conversationId: 'generated-id',
+ attempted: { codeEnvironmentMode: 'attached', codeWorkspaces: [selection] },
+ });
+ });
+
+ it('uses a structured error conversation id when the snapshot and messages are still new', () => {
+ const first = {
+ ...submission,
+ userMessage: { ...submission.userMessage, conversationId: 'new' },
+ initialResponse: { ...submission.initialResponse, conversationId: 'new' },
+ } as EventSubmission;
+ expect(getFailedCodeDecisionRequest(first, 'server-id')?.conversationId).toBe('server-id');
+ expect(getFailedCodeDecisionRequest(first, '_local-error')).toBeUndefined();
+ expect(getFailedCodeDecisionRequest(first)).toBeUndefined();
+ });
+
+ it('preserves an explicit without-attached first send while the authoritative read runs', () => {
+ const unattached = {
+ ...submission,
+ codeEnvironmentMode: 'without_attached',
+ codeWorkspaces: undefined,
+ } as EventSubmission;
+ expect(
+ buildRecoveryPreset(unattached.conversation, undefined, 'generated-id', unattached)
+ .codeEnvironmentMode,
+ ).toBe('without_attached');
+ expect(getFailedCodeDecisionRequest(unattached)?.attempted.codeEnvironmentMode).toBe(
+ 'without_attached',
+ );
+ });
+});
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index d480fc74b1..b1d1bf6dec 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -504,6 +504,7 @@ describe('useResumableSSE', () => {
});
it('invalidates the stream conversation id on 404 for a new conversation', async () => {
+ mockGetConversationById.mockRejectedValueOnce({ response: { status: 404 } });
/* Key-aware: the conversation cache helpers now run a second, pinned-keyed pass,
and a fixed return value would attribute those writes to allConversations. */
mockFindAll.mockImplementation((queryKey?: unknown) => [
@@ -570,6 +571,82 @@ describe('useResumableSSE', () => {
unmount();
});
+ it('hydrates a first conversation when a fast run finishes before stream attachment', async () => {
+ const persisted = {
+ conversationId: 'stream-123',
+ endpoint: 'agents',
+ agent_id: 'ordinary',
+ codeEnvironmentMode: 'without_attached',
+ };
+ const messages = [{ messageId: 'saved-response', conversationId: 'stream-123', text: 'Done' }];
+ mockGetConversationById.mockResolvedValue(persisted);
+ mockFetchQuery.mockImplementation(({ queryFn }) => {
+ if (typeof queryFn !== 'function') throw new Error('Missing queryFn');
+ return Promise.resolve(messages);
+ });
+ const chatHelpers = buildChatHelpers();
+ const { unmount } = renderHook(() =>
+ useResumableSSE(
+ buildSubmission({
+ conversation: {},
+ userMessage: {
+ messageId: 'msg-1',
+ conversationId: null,
+ text: 'Hello',
+ isCreatedByUser: true,
+ sender: 'User',
+ parentMessageId: Constants.NO_PARENT,
+ },
+ }),
+ chatHelpers,
+ ),
+ );
+ await flushMicrotasks();
+ await act(async () => {
+ await getLastSSE()._emit('error', { responseCode: 404 });
+ });
+ expect(mockGetConversationById).toHaveBeenCalledWith('stream-123');
+ expect(chatHelpers.setMessages).toHaveBeenCalledWith(messages);
+ const update = chatHelpers.setConversation.mock.calls.at(-1)?.[0];
+ expect(update({ conversationId: 'new', codeApprovalMode: 'ask' })).toEqual({
+ ...persisted,
+ codeApprovalMode: 'ask',
+ });
+ const other = { conversationId: 'other', agent_id: 'different' };
+ expect(update(other)).toBe(other);
+ expect(mockSetRunEnd).toHaveBeenCalledWith(expect.objectContaining({ outcome: 'aborted' }));
+ unmount();
+ });
+
+ it('ignores a first-stream conversation lookup that returns after navigation', async () => {
+ let finish!: (value: unknown) => void;
+ mockGetConversationById.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const chatHelpers = buildChatHelpers();
+ const { unmount } = renderHook(() =>
+ useResumableSSE(buildSubmission({ conversation: {} }), chatHelpers),
+ );
+ await flushMicrotasks();
+ await act(async () => {
+ getLastSSE()._emit('error', { responseCode: 404 });
+ });
+ await waitFor(() => expect(finish).toBeDefined());
+ unmount();
+ mockSetQueryData.mockClear();
+ chatHelpers.setConversation.mockClear();
+ chatHelpers.setMessages.mockClear();
+ await act(async () =>
+ finish({ conversationId: 'stream-123', codeEnvironmentMode: 'without_attached' }),
+ );
+ expect(chatHelpers.setConversation).not.toHaveBeenCalled();
+ expect(chatHelpers.setMessages).not.toHaveBeenCalled();
+ expect(mockSetQueryData).not.toHaveBeenCalled();
+ });
+
it('reconciles conversations via refetch instead of removing them on a resume 404', async () => {
/* Key-aware: the conversation cache helpers now run a second, pinned-keyed pass,
and a fixed return value would attribute those writes to allConversations. */
@@ -4713,6 +4790,7 @@ describe('useResumableSSE', () => {
expect(mockFetchQuery).toHaveBeenCalledWith({
queryKey: [QueryKeys.messages, CONV_ID],
+ queryFn: expect.any(Function),
});
expect(mockSettleAppliedSteerParts).toHaveBeenCalledWith(CONV_ID, persisted);
unmount();
diff --git a/client/src/hooks/SSE/__tests__/workspace.spec.tsx b/client/src/hooks/SSE/__tests__/workspace.spec.tsx
index ca9cec3862..69f7f24db4 100644
--- a/client/src/hooks/SSE/__tests__/workspace.spec.tsx
+++ b/client/src/hooks/SSE/__tests__/workspace.spec.tsx
@@ -1,4 +1,5 @@
import { useState } from 'react';
+import { Provider } from 'jotai';
import { RecoilRoot } from 'recoil';
import { MemoryRouter } from 'react-router-dom';
import { act, renderHook } from '@testing-library/react';
@@ -48,6 +49,9 @@ jest.mock('~/hooks/Agents/useGetAgentsConfig', () => () => ({
}));
jest.mock('~/data-provider', () => ({
...jest.requireActual('~/data-provider'),
+ /** The barrel can be partially initialized through the hook imports above. Keep these
+ * real hooks rather than snapshotting missing exports or replacing recovery with a stub. */
+ ...jest.requireActual('~/data-provider/CodeEnvironments'),
useCodeEnvironmentStatusQueries: () => mockStatus(),
useGetStartupConfig: () => ({ data: mockStartupConfig() }),
}));
@@ -65,9 +69,11 @@ function setup(current = initialConversation, isAddedRequest = false) {
queryClient.setQueryData([QueryKeys.allConversations], { pages: [], pageParams: [] });
const wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>
- <RecoilRoot>
- <MemoryRouter initialEntries={['/c/new']}>{children}</MemoryRouter>
- </RecoilRoot>
+ <Provider>
+ <RecoilRoot>
+ <MemoryRouter initialEntries={['/c/new']}>{children}</MemoryRouter>
+ </RecoilRoot>
+ </Provider>
</QueryClientProvider>
);
const hook = renderHook(
@@ -224,15 +230,50 @@ describe('workspace decision at stream acknowledgement', () => {
expect(result.current.conversation?.codeWorkspaces).toBeUndefined();
});
- it('records a first decision on a saved conversation that has not used a workspace', () => {
+ it.each(['created', 'sync'] as const)(
+ 'records No workspace on %s for a saved chat that has not granted workspace access',
+ (event) => {
+ const { result, submission, createdData } = setup({
+ ...initialConversation,
+ conversationId: 'saved-chat',
+ });
+ expect(result.current.workspace.locked).toBe(false);
+ expect(submission.codeEnvironmentMode).toBe('without_attached');
+ expect(submission.codeWorkspaces).toBeUndefined();
+ act(() => {
+ if (event === 'created') result.current.createdHandler(createdData, submission);
+ else
+ result.current.syncHandler(
+ {
+ sync: true,
+ thread_id: 'thread',
+ conversationId: 'saved-chat',
+ requestMessage: submission.userMessage,
+ responseMessage: submission.initialResponse,
+ },
+ submission,
+ );
+ });
+ expect(result.current.conversation?.codeEnvironmentMode).toBe('without_attached');
+ expect(result.current.conversation?.codeWorkspaces).toBeUndefined();
+ expect(result.current.workspace).toMatchObject({ locked: true, canSubmit: true });
+ },
+ );
+
+ it('records an explicitly selected first workspace on a previously undecided saved chat', () => {
const { result, submission, createdData } = setup({
...initialConversation,
conversationId: 'saved-chat',
});
- expect(result.current.workspace.locked).toBe(false);
- act(() => result.current.createdHandler(createdData, submission));
+ act(() =>
+ result.current.createdHandler(createdData, {
+ ...submission,
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [selection],
+ }),
+ );
expect(result.current.conversation?.codeWorkspaces).toEqual([selection]);
- expect(result.current.workspace.locked).toBe(true);
+ expect(result.current.workspace).toMatchObject({ locked: true, canSubmit: true });
});
it('uses the submitted without-attached choice rather than a stale draft selection', () => {
diff --git a/client/src/hooks/SSE/useEventHandlers.ts b/client/src/hooks/SSE/useEventHandlers.ts
index 7894ca89e9..ebadfd8257 100644
--- a/client/src/hooks/SSE/useEventHandlers.ts
+++ b/client/src/hooks/SSE/useEventHandlers.ts
@@ -47,7 +47,12 @@ import {
startupConfigKey,
queueTitleGeneration,
markTitleGenerationProcessed,
+ useReconcileConversationCodeEnvironmentMutation,
} from '~/data-provider';
+import {
+ getFailedCodeDecisionRequest,
+ withSubmittedCodeDecision,
+} from '~/hooks/Agents/codeDecision';
import useFocusRegeneratedResponse from '~/hooks/Chat/useFocusRegeneratedResponse';
import { shouldResetSubagentAtomsOnConversationChange } from './cleanup';
import useAttachmentHandler from '~/hooks/SSE/useAttachmentHandler';
@@ -453,8 +458,17 @@ export const buildRecoveryPreset = (
submissionConvo: Partial<TConversation>,
cachedConvo: TConversation | null | undefined,
conversationId: string,
+ submittedDecision?: Pick<EventSubmission, 'codeEnvironmentMode' | 'codeWorkspaces'>,
): TPreset =>
- tPresetSchema.parse(keepLocalCodeApprovalMode(submissionConvo, cachedConvo, conversationId));
+ tPresetSchema.parse(
+ keepLocalCodeApprovalMode(
+ submittedDecision == null
+ ? submissionConvo
+ : withSubmittedCodeDecision(submissionConvo as TConversation, submittedDecision)!,
+ cachedConvo,
+ conversationId,
+ ),
+ );
export const getConvoTitle = ({
parentId,
@@ -507,6 +521,17 @@ export default function useEventHandlers({
* would inherit a stale baseline. Navigation teardown deliberately does not
* clear it — a reattach to a still-live run keeps its original start. */
const setSubmissionStart = useSetRecoilState(store.submissionStartFamily(runIndex));
+ const { mutate: reconcileCodeDecision } =
+ useReconcileConversationCodeEnvironmentMutation(setConversation);
+ const reconcileFailedCodeDecision = useCallback(
+ (submission: EventSubmission, conversationId?: string) => {
+ if (isAddedRequest) return;
+ const request = getFailedCodeDecisionRequest(submission, conversationId);
+ if (request != null) reconcileCodeDecision(request);
+ },
+ [isAddedRequest, reconcileCodeDecision],
+ );
+
const recoverConversation = useCallback(
(conversationId: string, submission: EventSubmission) => {
if (!newConversation) {
@@ -516,9 +541,21 @@ export default function useEventHandlers({
QueryKeys.conversation,
conversationId,
]);
+ const preset = buildRecoveryPreset(
+ submission.conversation,
+ cachedConvo,
+ conversationId,
+ submission,
+ );
newConversation({
- template: { conversationId },
- preset: buildRecoveryPreset(submission.conversation, cachedConvo, conversationId),
+ // Endpoint preset parsing omits code decisions. Carry them on the conversation template
+ // too, so rebuilding after a first-turn stream failure cannot discard the implicit pick.
+ template: {
+ conversationId,
+ codeEnvironmentMode: preset.codeEnvironmentMode,
+ codeWorkspaces: preset.codeWorkspaces,
+ },
+ preset,
});
},
[newConversation, queryClient],
@@ -943,6 +980,7 @@ export default function useEventHandlers({
const isExistingConvo =
currentConvoId && currentConvoId !== Constants.NEW_CONVO && !isInitialNewConvo;
if (isExistingConvo) {
+ reconcileFailedCodeDecision(submission, currentConvoId);
const abortMessages = getExistingConversationAbortMessages({
messages,
isRegenerate,
@@ -1187,6 +1225,7 @@ export default function useEventHandlers({
attachmentHandler,
setSubmissionStart,
restorePendingQuotes,
+ reconcileFailedCodeDecision,
],
);
@@ -1207,6 +1246,7 @@ export default function useEventHandlers({
if (recover) {
recoverConversation(conversationId, submission);
}
+ reconcileFailedCodeDecision(submission, conversationId);
setIsSubmitting(false);
},
[
@@ -1218,6 +1258,7 @@ export default function useEventHandlers({
getMessages,
queryClient,
recoverConversation,
+ reconcileFailedCodeDecision,
],
);
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index a2170f70f2..67dc162c26 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -3148,6 +3148,8 @@ export default function useResumableSSE(
}
const fetched = await queryClient.fetchQuery<TMessage[]>({
queryKey: messageQueryKey,
+ // The first stream can finish before CREATED mounts the saved-chat query.
+ queryFn: () => dataService.getMessagesByConvoId(convoId),
});
if (!isCurrentSubscription()) {
return;
@@ -3316,18 +3318,42 @@ export default function useResumableSSE(
!createdStreamIdsRef.current.has(currentStreamId) &&
optimisticStreamIdsRef.current.has(currentStreamId)
) {
- if (isResume) {
- // A resumed subscribe attaches to an already-adopted stream (e.g. a deduped
- // start request). A 404 means the job is gone — but the conversation may be
- // persisted (the original completed and was cleaned up) or may never have
- // existed (the winner died before persisting). Don't guess: reconcile against
- // the server so a real conversation stays and a phantom is dropped.
- invalidateConversationLists(queryClient);
- queryClient.invalidateQueries({ queryKey: [QueryKeys.pinnedConversations] });
- } else {
- // Fresh optimistic stream that never started: prune immediately.
- removeConvoFromAllQueries(queryClient, currentStreamId);
+ // Both fresh and resumed subscriptions can miss every event of a fast turn.
+ // A missing job proves neither that the conversation was saved nor that it failed.
+ try {
+ const persisted = await dataService.getConversationById(recoveryConvoId);
+ if (!isCurrentSubscription()) return;
+ if (persisted?.conversationId === recoveryConvoId) {
+ queryClient.setQueryData([QueryKeys.conversation, recoveryConvoId], persisted);
+ upsertConvoInAllQueries(queryClient, persisted);
+ if (!isAddedRequest) {
+ setConversation?.((current) => {
+ if (
+ current?.conversationId != null &&
+ current.conversationId !== Constants.NEW_CONVO &&
+ current.conversationId !== recoveryConvoId
+ )
+ return current;
+ return keepLocalCodeApprovalMode(
+ { ...current, ...persisted },
+ current,
+ current?.conversationId,
+ );
+ });
+ }
+ }
+ } catch (error) {
+ if (!isCurrentSubscription()) return;
+ if (toStartGenerationError(error)?.response?.status === 404) {
+ removeConvoFromAllQueries(queryClient, currentStreamId);
+ }
}
+ // An inconclusive read must not turn a saved chat into a phantom.
+ invalidateConversationLists(queryClient);
+ queryClient.invalidateQueries({ queryKey: [QueryKeys.pinnedConversations] });
+ }
+ if (persistedMessages) {
+ setMessages(persistedMessages);
}
subscriptionRetired = true;
setIsSubmitting(false);
@@ -3878,6 +3904,8 @@ export default function useResumableSSE(
}
},
[
+ isAddedRequest,
+ setConversation,
runIndex,
token,
setAbortScroll,
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index e6d28b9e67..f89b54d879 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -38,9 +38,15 @@
"com_ui_code_workspace_missing": "Workspace missing",
"com_ui_code_workspace_unavailable": "Workspace unavailable",
"com_ui_code_workspace_unsupported": "Update worker for workspaces",
- "com_ui_code_workspace_without_attached": "No attached workspace",
- "com_ui_code_workspace_without_attached_info": "Chat without using files or commands on an attached machine.",
+ "com_ui_code_workspace_without_attached": "No workspace",
+ "com_ui_code_workspace_without_attached_info": "You can chat and use available tools. Attach a workspace for files and commands.",
"com_ui_code_workspace_locked_recovery": "Reconnect or restore this workspace, or start a new chat.",
+ "com_ui_code_workspace_attach": "Attach workspace",
+ "com_ui_code_workspace_attach_info": "This chat runs without a workspace. Attach one to work with files and commands. Earlier messages stay, and no files are copied.",
+ "com_ui_code_workspace_attach_to": "Attach {{0}}",
+ "com_ui_code_workspace_detach": "Continue without workspace",
+ "com_ui_code_workspace_detach_info": "Keep chatting without files or commands on the attached machine.",
+ "com_ui_code_workspace_detach_prompt": "This chat's workspace is unavailable. Reconnect the machine, or continue without a workspace.",
"com_ui_code_workspace_recover": "Recover workspace",
"com_ui_code_workspace_recover_info": "A workspace saved with this chat is no longer registered. Choose an available workspace for each environment below to continue this chat. Chat history is kept, but previous workspace files are not restored or copied.",
"com_ui_code_workspace_move": "Move chat",
@@ -48,8 +54,11 @@
"com_ui_code_workspace_move_info": "This chat used {{0}}, but its agent now uses {{1}}. Files from earlier turns stay on the previous machine.",
"com_ui_code_workspace_move_info_removed": "This chat's agent no longer uses {{0}}. Move the chat to continue without it.",
"com_ui_code_workspace_move_info_added": "This chat's agent now also uses {{0}}. Choose a workspace there to continue.",
- "com_ui_code_workspace_move_stale": "This chat's workspace selection is no longer current. Reload and try again.",
+ "com_ui_code_workspace_move_stale": "This chat's workspace changed elsewhere. Review its current workspace and try again.",
"com_ui_code_workspace_move_busy": "Wait for the current response to finish before changing this chat's workspace.",
+ "com_ui_code_workspace_reconciling": "Confirming this chat's workspace decision…",
+ "com_ui_code_workspace_reconcile_failed": "Couldn't confirm this chat's workspace decision. Sending stays paused until you retry successfully or reload.",
+ "com_ui_code_workspace_reconcile_retry": "Retry workspace check",
"com_ui_code_workspace_move_error": "Couldn't update this chat's workspace. Try again.",
"com_ui_code_workspaces_selected": "{{0}} code workspaces",
"com_ui_code_approval_ask": "Ask before changes",
diff --git a/client/src/store/codeEnvironmentReconciliation.ts b/client/src/store/codeEnvironmentReconciliation.ts
new file mode 100644
index 0000000000..082e078214
--- /dev/null
+++ b/client/src/store/codeEnvironmentReconciliation.ts
@@ -0,0 +1,20 @@
+import { atom } from 'jotai';
+import type { TConversation } from 'librechat-data-provider';
+
+export type CodeEnvironmentReconciliationRequest = {
+ conversationId: string;
+ attempted: Pick<TConversation, 'codeEnvironmentMode' | 'codeWorkspaces'>;
+};
+
+export type CodeEnvironmentReconciliation = {
+ request: CodeEnvironmentReconciliationRequest;
+ status: 'pending' | 'error';
+ /** A late completion must not clear a newer reconciliation for the same chat. */
+ token: symbol;
+};
+
+/** An unconfirmed decision outlives the mutation observer, resets and navigation. It is cleared
+ * only after authoritative reconciliation succeeds, or when a full reload discards local state. */
+export const codeEnvironmentReconciliationsAtom = atom<
+ ReadonlyMap<string, CodeEnvironmentReconciliation>
+>(new Map());
diff --git a/client/src/utils/__tests__/workspaceSwitch.test.ts b/client/src/utils/__tests__/workspaceSwitch.test.ts
new file mode 100644
index 0000000000..b27564dcc5
--- /dev/null
+++ b/client/src/utils/__tests__/workspaceSwitch.test.ts
@@ -0,0 +1,68 @@
+import { EModelEndpoint } from 'librechat-data-provider';
+import type { TConversation } from 'librechat-data-provider';
+import buildDefaultConvo from '../buildDefaultConvo';
+import { getConvoSwitchLogic } from '../endpoints';
+
+const selection = { environmentId: 'old-machine', workspaceId: 'project' };
+
+function switchAgent(conversation: TConversation) {
+ const result = getConvoSwitchLogic({
+ conversation,
+ newEndpoint: EModelEndpoint.agents,
+ endpointsConfig: { agents: { order: 0 } },
+ modularChat: true,
+ });
+ return buildDefaultConvo({
+ conversation,
+ endpoint: EModelEndpoint.agents,
+ lastConversationSetup: { ...result.template, agent_id: 'agent_coding' } as TConversation,
+ models: [],
+ });
+}
+
+it.each([
+ {},
+ { codeEnvironmentMode: 'without_attached' as const },
+ { codeEnvironmentMode: 'attached' as const, codeWorkspaces: [selection] },
+ { codeWorkspaces: [selection] },
+])('keeps saved identity and workspace consent across a coding-agent selection: %j', (decision) => {
+ const conversation = {
+ conversationId: 'saved-chat',
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_ordinary',
+ title: 'History stays here',
+ ...decision,
+ } as TConversation;
+ const next = switchAgent(conversation);
+ expect(next.conversationId).toBe('saved-chat');
+ expect(next.agent_id).toBe('agent_coding');
+ expect(next.codeEnvironmentMode).toBe(conversation.codeEnvironmentMode);
+ expect(next.codeWorkspaces).toEqual(conversation.codeWorkspaces);
+ expect(conversation.agent_id).toBe('agent_ordinary');
+});
+
+it.each([
+ { endpoint: EModelEndpoint.openAI, modularChat: true, expected: true },
+ { endpoint: EModelEndpoint.openAI, modularChat: false, expected: false },
+ { endpoint: EModelEndpoint.assistants, modularChat: true, expected: false },
+])(
+ 'respects existing endpoint-switch rules: $endpoint, modular=$modularChat',
+ ({ endpoint, modularChat, expected }) => {
+ const result = getConvoSwitchLogic({
+ conversation: { conversationId: 'saved-chat', endpoint } as TConversation,
+ newEndpoint: EModelEndpoint.agents,
+ endpointsConfig: { agents: { order: 0 }, openAI: { order: 1 }, assistants: { order: 2 } },
+ modularChat,
+ });
+ expect(result.isCurrentModular && result.isNewModular && result.shouldSwitch).toBe(expected);
+ },
+);
+
+it('keeps a new-chat selection new', () => {
+ expect(
+ switchAgent({
+ conversationId: 'new',
+ endpoint: EModelEndpoint.agents,
+ } as TConversation).conversationId,
+ ).toBe('new');
+});
diff --git a/e2e/byom/README.md b/e2e/byom/README.md
index 05ce6e3bce..c263501d60 100644
--- a/e2e/byom/README.md
+++ b/e2e/byom/README.md
@@ -23,6 +23,21 @@ From the LibreChat root:
BYOM_CODE_REPO=/absolute/path/to/code-interpreter node e2e/byom/run.mjs
```
+To also exercise a saved non-coding chat switching to a coding agent without implicit access,
+sending and reloading in **No workspace** mode, attaching explicitly, and leaving an offline
+workspace before continuing the same chat:
+
+```sh
+BYOM_WORKSPACE_TRANSITIONS=true BYOM_CODE_REPO=/absolute/path/to/code-interpreter node e2e/byom/run.mjs
+```
+
+This enables the decision protocol and attach/detach policy only in the disposable test app.
+
+The `Native Workspace Acceptance` workflow runs this transition variant on a hosted macOS
+runner when the harness changes in a `dev` pull request. It pins the Code API/worker revision
+and uses the native Seatbelt policy unchanged. It does not upload identities, raw logs or
+browser state. This proves the macOS journey only; Linux and WSL2 require their own native run.
+
Optional: `BYOM_REDIS_BIN` selects an absolute Redis executable,
`BYOM_CODE_CLI` selects a separately built worker CLI, and
`E2E_CHROMIUM_CHANNEL=chrome` uses an installed Chrome instead of Playwright Chromium.
diff --git a/e2e/byom/native.spec.ts b/e2e/byom/native.spec.ts
index aa08936462..8d2a83070b 100644
--- a/e2e/byom/native.spec.ts
+++ b/e2e/byom/native.spec.ts
@@ -4,7 +4,12 @@ import { spawn } from 'node:child_process';
import { mkdir, open, readFile, readdir } from 'node:fs/promises';
import { expect, test } from '@playwright/test';
import type { ChildProcess } from 'node:child_process';
-import { getAccessToken, requestJson, sendMessage } from '../specs/mock/helpers';
+import {
+ getAccessToken,
+ requestJson,
+ sendMessage,
+ sendMessageAndWaitForCompletion,
+} from '../specs/mock/helpers';
interface Pairing {
environment: { id: string };
@@ -39,7 +44,34 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
}, testInfo) => {
const runDir = process.env.BYOM_ACCEPTANCE_DIR!;
const cli = process.env.BYOM_CODE_CLI!;
+ const workspaceTransitions = process.env.BYOM_WORKSPACE_TRANSITIONS === 'true';
const workers: Worker[] = [];
+ // Emit only conversation identifiers on failure, never raw browser arguments or worker logs.
+ const conversationEvents: unknown[] = [];
+ page.on('console', async (message) => {
+ if (!/^\[(conversation|ResumableSSE)\]/.test(message.text())) return;
+ const values = await Promise.all(
+ message.args().map((value, index) =>
+ value
+ .evaluate((item, position) => {
+ if (position < 2) return typeof item === 'string' ? item : undefined;
+ if (item == null || typeof item !== 'object') return undefined;
+ const record = item as Record<string, unknown>;
+ return {
+ conversationId: record.conversationId,
+ endpoint: record.endpoint,
+ agent_id: record.agent_id,
+ streamId: record.streamId,
+ isResume: record.isResume,
+ hasResponseMessage: record.hasResponseMessage,
+ };
+ }, index)
+ .catch(() => undefined),
+ ),
+ );
+ conversationEvents.push(values);
+ if (conversationEvents.length > 100) conversationEvents.shift();
+ });
let selectedWorker: Worker;
let selectedApprovalMode: 'ask' | 'acceptEdits' | 'fullAccess' = 'ask';
const password = `Acceptance-${randomUUID()}`;
@@ -161,6 +193,7 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
timeout: 30_000,
});
selectedApprovalMode = 'ask';
+ return agent;
}
async function turn(operation: string, decision?: 'Approve' | 'Reject') {
@@ -219,6 +252,36 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
return outputs.join('\n');
}
+ async function chat(text: string) {
+ const admitted = await sendMessageAndWaitForCompletion(page, text);
+ expect(admitted.ok()).toBe(true);
+ const { conversationId } = (await admitted.json()) as { conversationId: string };
+ await expect
+ .poll(
+ async () => {
+ const status = await requestJson<{ active: boolean }>(page, {
+ path: `/api/agents/chat/status/${conversationId}`,
+ token,
+ });
+ return status.active;
+ },
+ { timeout: 30_000 },
+ )
+ .toBe(false);
+ await expect(page.getByText(text, { exact: true }).last()).toBeVisible();
+ await expect(page.getByText('Acceptance model ready.', { exact: true }).last()).toBeVisible();
+ await expect(page.getByTestId('stop-generation-button')).toBeHidden();
+ await expect(page).toHaveURL(new RegExp(`/c/${conversationId}$`));
+ return conversationId;
+ }
+
+ async function readDecision(conversationId: string) {
+ return requestJson<{
+ codeEnvironmentMode?: string;
+ codeWorkspaces?: Array<{ environmentId: string; workspaceId: string }>;
+ }>(page, { path: `/api/convos/${conversationId}`, token });
+ }
+
async function selectApprovalMode(mode: 'Ask before changes' | 'Accept edits' | 'Full access') {
const selector = page.getByTestId('code-approval-mode');
await expect(selector).toBeVisible();
@@ -236,7 +299,121 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
try {
const a = await startWorker('a');
- await select(a);
+ const coding = await select(a);
+ if (workspaceTransitions) {
+ const ordinary = await requestJson<{ id: string }>(page, {
+ path: '/api/agents',
+ token,
+ method: 'POST',
+ body: {
+ name: 'Acceptance ordinary chat',
+ provider: 'Acceptance',
+ model: 'acceptance',
+ tools: [],
+ },
+ });
+ await page.goto(`/c/new?agent_id=${encodeURIComponent(ordinary.id)}`);
+ await expect(page.getByTestId('model-selector-button')).toContainText(
+ 'Acceptance ordinary chat',
+ );
+ await expect(page).toHaveURL(/\/c\/new$/);
+ // Reproduce a first turn that settles before the browser attaches. Do not rely on
+ // machine speed to cover the missing-stream recovery that must preserve saved identity.
+ const streamRoute = '**/api/agents/chat/stream/**';
+ await page.route(streamRoute, async (route) => {
+ const streamId = new URL(route.request().url()).pathname.split('/').pop();
+ await expect
+ .poll(
+ async () => {
+ const status = await requestJson<{ active: boolean }>(page, {
+ path: `/api/agents/chat/status/${streamId}`,
+ token,
+ });
+ return status.active;
+ },
+ { timeout: 30_000 },
+ )
+ .toBe(false);
+ await route.continue();
+ });
+ const conversationId = await chat('Keep this conversation and its history.');
+ await page.unroute(streamRoute);
+ const ordinaryDecision = await readDecision(conversationId);
+ expect(ordinaryDecision.codeEnvironmentMode).toBe('without_attached');
+ expect(ordinaryDecision.codeWorkspaces ?? []).toEqual([]);
+ await page.getByTestId('model-selector-button').click();
+ await page.locator('#model-search').fill(`Native ${a.environmentId}`);
+ await page.getByRole('option', { name: new RegExp(`Native ${a.environmentId}`) }).click();
+ await expect(page).toHaveURL(new RegExp(`/c/${conversationId}$`));
+ await expect(page.getByTestId('code-workspace')).toContainText('No workspace');
+ expect(await chat('Continue without granting workspace access.')).toBe(conversationId);
+ expect(await readDecision(conversationId)).toMatchObject({
+ codeEnvironmentMode: 'without_attached',
+ });
+ await page.reload();
+ await expect(page.getByTestId('model-selector-button')).toContainText(
+ `Native ${a.environmentId}`,
+ );
+ await expect(page.getByTestId('code-workspace')).toContainText('No workspace');
+ await page.getByTestId('code-workspace').click();
+ await page.getByRole('menuitem', { name: /^Attach / }).click();
+ await expect
+ .poll(async () => (await readDecision(conversationId)).codeEnvironmentMode)
+ .toBe('attached');
+ expect((await readDecision(conversationId)).codeWorkspaces).toEqual([
+ expect.objectContaining({ environmentId: a.environmentId }),
+ ]);
+ await expect(
+ page.getByText('Keep this conversation and its history.', { exact: true }),
+ ).toBeVisible();
+ expect(coding.id).toBeTruthy();
+ expect(await turn('command', 'Approve')).toContain('native-command-ok');
+ await stop(a.child);
+ // A stopped process stays online in the registry until its 60-second heartbeat lease
+ // expires. Observe that boundary rather than expecting the UI to contradict a live lease.
+ await expect
+ .poll(
+ async () => {
+ const status = await requestJson<{ status: string }>(page, {
+ path: `/api/code-environments/${a.environmentId}/status`,
+ token,
+ });
+ return status.status;
+ },
+ { timeout: 90_000 },
+ )
+ .toBe('offline');
+ await page.reload();
+ const workspace = page.getByTestId('code-workspace');
+ await expect(workspace).toBeVisible({ timeout: 30_000 });
+ await workspace.click();
+ await page.getByTestId('code-workspace-detach').click();
+ await expect
+ .poll(async () => (await readDecision(conversationId)).codeEnvironmentMode)
+ .toBe('without_attached');
+ expect((await readDecision(conversationId)).codeWorkspaces ?? []).toEqual([]);
+ expect(await chat('Continue chatting after leaving the offline workspace.')).toBe(
+ conversationId,
+ );
+ await page.reload();
+ await expect(
+ page.getByText('Keep this conversation and its history.', { exact: true }),
+ ).toBeVisible();
+ expect((await readDecision(conversationId)).codeEnvironmentMode).toBe('without_attached');
+ await testInfo.attach('workspace-transitions', {
+ body: JSON.stringify({
+ savedChatPreserved: true,
+ noImplicitWorkspaceAccess: true,
+ noWorkspaceSurvivesReload: true,
+ explicitAttach: true,
+ approvedNativeCommand: true,
+ offlineDetach: true,
+ detachedChatSurvivesReload: true,
+ }),
+ contentType: 'application/json',
+ });
+ return;
+ }
expect(await turn('create', 'Approve')).toContain('Created workspace/proof.txt');
expect(await readFile(path.join(a.root, 'proof.txt'), 'utf8')).toBe('native-original');
expect(await turn('read')).toContain('native-original');
@@ -288,6 +465,9 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
}),
contentType: 'application/json',
});
+ } catch (error) {
+ console.log('Native acceptance conversation metadata:', JSON.stringify(conversationEvents));
+ throw error;
} finally {
for (const worker of workers) await stop(worker.child);
}
diff --git a/e2e/byom/run.mjs b/e2e/byom/run.mjs
index 64afb4c7b3..7820b3d4b9 100644
--- a/e2e/byom/run.mjs
+++ b/e2e/byom/run.mjs
@@ -12,6 +12,7 @@ import { createLifecycle } from './lifecycle.mjs';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const require = createRequire(path.join(root, 'api/package.json'));
const codeRoot = process.env.BYOM_CODE_REPO;
+const workspaceTransitions = process.env.BYOM_WORKSPACE_TRANSITIONS === 'true';
if (!codeRoot)
throw new Error('Set BYOM_CODE_REPO to a built LibreChat-AI/code-interpreter checkout.');
if (!['darwin', 'linux'].includes(process.platform)) {
@@ -163,6 +164,9 @@ try {
toolApproval: { enabled: true, mode: 'bypass' },
statefulCodeSessions: {
allowedEnvironments: ['conversation'],
+ ...(workspaceTransitions && {
+ conversationMoves: { enabled: true, allowAttachDetach: true },
+ }),
principalWorkers: { enabled: true, maxPerUser: 2 },
environments: [
{
@@ -212,6 +216,7 @@ try {
CODEAPI_JWT_KID: 'acceptance',
CODEAPI_JWT_SINGLE_TENANT_ID: 'acceptance',
BYOM_ENROLLMENT_TOKEN: adminToken,
+ ...(workspaceTransitions && { CODE_ENVIRONMENT_DECISION_VERSION: '1' }),
/** Deliberately unusable: accidental default routing must fail, never hit production. */
LIBRECHAT_CODE_BASEURL: `${appURL}/forbidden-default-codeapi`,
LIBRECHAT_CODE_BASEURL_STATEFUL: codeURL,
@@ -267,7 +272,10 @@ try {
E2E_BASE_URL: appURL,
BYOM_ACCEPTANCE_DIR: runDir,
BYOM_CODE_CLI: cli,
+ BYOM_WORKSPACE_TRANSITIONS: String(workspaceTransitions),
E2E_CHROMIUM_CHANNEL: process.env.E2E_CHROMIUM_CHANNEL ?? '',
+ PLAYWRIGHT_BROWSERS_PATH: process.env.PLAYWRIGHT_BROWSERS_PATH ?? '',
+ ...(process.env.LD_LIBRARY_PATH && { LD_LIBRARY_PATH: process.env.LD_LIBRARY_PATH }),
},
},
),
diff --git a/librechat.example.yaml b/librechat.example.yaml
index 3f25483564..7836c55405 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -674,6 +674,12 @@ endpoints:
# # "stateful_code_sessions" is highly experimental and may change substantially.
# # (optional) Limit the workspace scopes users may select. Omit to allow all three.
# statefulCodeSessions:
+ # # Keep move-only behavior unless attach/detach is explicitly enabled.
+ # # Enable only after ALL API replicas run this build and advertise decision protocol 1
+ # # (CODE_ENVIRONMENT_DECISION_VERSION=1), then refresh clients.
+ # conversationMoves:
+ # enabled: true
+ # allowAttachDetach: false
# allowedEnvironments: ["user", "agent-user", "conversation"]
# # Personal BYOM enrollment. Requires allowPrincipalWorkers on a control plane.
# # Omitted values default to enabled and five registered environments per user.
diff --git a/packages/api/src/code/config.spec.ts b/packages/api/src/code/config.spec.ts
index 4b0749f3eb..cd3e7c6c38 100644
--- a/packages/api/src/code/config.spec.ts
+++ b/packages/api/src/code/config.spec.ts
@@ -5,6 +5,7 @@ import {
mergeAccessibleCodeEnvironments,
resolveCodeEnvironmentDecisionVersion,
resolveCodeEnvironmentMoveVersion,
+ resolveCodeEnvironmentTransitionVersion,
resolveCodeEnvironmentMoveCapabilities,
} from './config';
@@ -22,7 +23,7 @@ describe('resolveCodeEnvironmentDecisionVersion', () => {
});
describe('resolveCodeEnvironmentMoveVersion', () => {
- const withMoves = (conversationMoves?: { enabled?: boolean }) =>
+ const withMoves = (conversationMoves?: { enabled?: boolean; allowAttachDetach?: boolean }) =>
({
endpoints: {
[EModelEndpoint.agents]: {
@@ -39,6 +40,32 @@ describe('resolveCodeEnvironmentMoveVersion', () => {
});
});
+ /* Attaching and leaving ship under the same policy as the move but on their own number, so a
+ * client that predates them keeps reading a move version it understands. */
+ it.each([undefined, false])(
+ 'preserves enabled move-only policy with allowAttachDetach=%s',
+ (allowAttachDetach) => {
+ const config = withMoves({ enabled: true, allowAttachDetach });
+ expect(resolveCodeEnvironmentMoveVersion(config)).toBe(1);
+ expect(resolveCodeEnvironmentTransitionVersion(config)).toBeUndefined();
+ },
+ );
+
+ it('advertises attach and detach separately from the move', () => {
+ expect(
+ resolveCodeEnvironmentTransitionVersion(
+ withMoves({ enabled: true, allowAttachDetach: true }),
+ ),
+ ).toBe(2);
+ });
+
+ it.each([undefined, {}, { enabled: false }])(
+ 'keeps attach and detach off wherever moves are off: %j',
+ (conversationMoves) => {
+ expect(resolveCodeEnvironmentTransitionVersion(withMoves(conversationMoves))).toBeUndefined();
+ },
+ );
+
it.each([undefined, {}, { enabled: false }])(
'keeps sealed decisions immovable by default: %j',
(conversationMoves) => {
diff --git a/packages/api/src/code/config.ts b/packages/api/src/code/config.ts
index 3996fea913..619208ed0f 100644
--- a/packages/api/src/code/config.ts
+++ b/packages/api/src/code/config.ts
@@ -2,6 +2,7 @@ import { logger } from '@librechat/data-schemas';
import {
CODE_ENVIRONMENT_DECISION_VERSION,
CODE_ENVIRONMENT_MOVE_VERSION,
+ CODE_ENVIRONMENT_TRANSITION_VERSION,
CODE_WORKSPACE_RECOVERY_VERSION,
EModelEndpoint,
} from 'librechat-data-provider';
@@ -36,13 +37,31 @@ export function resolveCodeEnvironmentDecisionVersion(
: undefined;
}
+function conversationMovesEnabled(appConfig?: Pick<AppConfig, 'endpoints'> | null): boolean {
+ return (
+ appConfig?.endpoints?.[EModelEndpoint.agents]?.statefulCodeSessions?.conversationMoves
+ ?.enabled === true
+ );
+}
+
/** Advertises owner moves of a sealed decision only where the effective policy enables them. */
export function resolveCodeEnvironmentMoveVersion(
appConfig?: Pick<AppConfig, 'endpoints'> | null,
): typeof CODE_ENVIRONMENT_MOVE_VERSION | undefined {
- return appConfig?.endpoints?.[EModelEndpoint.agents]?.statefulCodeSessions?.conversationMoves
- ?.enabled === true
- ? CODE_ENVIRONMENT_MOVE_VERSION
+ return conversationMovesEnabled(appConfig) ? CODE_ENVIRONMENT_MOVE_VERSION : undefined;
+}
+
+/**
+ * Advertises attach/detach only after a deployment opts in. Keep the original move capability
+ * separate so older clients and move-only deployments retain their existing recovery path.
+ */
+export function resolveCodeEnvironmentTransitionVersion(
+ appConfig?: Pick<AppConfig, 'endpoints'> | null,
+): typeof CODE_ENVIRONMENT_TRANSITION_VERSION | undefined {
+ return conversationMovesEnabled(appConfig) &&
+ appConfig?.endpoints?.[EModelEndpoint.agents]?.statefulCodeSessions?.conversationMoves
+ ?.allowAttachDetach === true
+ ? CODE_ENVIRONMENT_TRANSITION_VERSION
: undefined;
}
diff --git a/packages/api/src/code/decision.spec.ts b/packages/api/src/code/decision.spec.ts
index 01d1798e93..90609892e6 100644
--- a/packages/api/src/code/decision.spec.ts
+++ b/packages/api/src/code/decision.spec.ts
@@ -1,5 +1,7 @@
+import type { AppConfig } from '@librechat/data-schemas';
import {
resolveConversationCodeEnvironmentDecision,
+ resolveAdmittedCodeEnvironmentDecision,
resolveConversationCodeEnvironmentMove,
resolvePersistableCodeEnvironmentDecision,
} from './decision';
@@ -166,7 +168,7 @@ describe('resolveConversationCodeEnvironmentMove', () => {
from: [mac],
to: [vm],
}),
- ).toEqual({ codeWorkspaces: [vm] });
+ ).toEqual({ mode: 'attached', codeWorkspaces: [vm] });
});
it('carries a covered environment over unchanged while adding a new one', () => {
@@ -177,7 +179,7 @@ describe('resolveConversationCodeEnvironmentMove', () => {
from: [team],
to: [vm, team],
}),
- ).toEqual({ codeWorkspaces: [team, vm] });
+ ).toEqual({ mode: 'attached', codeWorkspaces: [team, vm] });
});
it('moves a legacy decision inferred from its selections', () => {
@@ -187,7 +189,7 @@ describe('resolveConversationCodeEnvironmentMove', () => {
from: [mac],
to: [vm],
}),
- ).toEqual({ codeWorkspaces: [vm] });
+ ).toEqual({ mode: 'attached', codeWorkspaces: [vm] });
});
it('accepts an explicit workspace replacement for the caller to verify against live status', () => {
@@ -198,7 +200,7 @@ describe('resolveConversationCodeEnvironmentMove', () => {
from: [mac, vm],
to: [replacement, vm],
}),
- ).toEqual({ codeWorkspaces: [replacement, vm] });
+ ).toEqual({ mode: 'attached', codeWorkspaces: [replacement, vm] });
});
it('drops an environment the agents stopped using without adding one', () => {
@@ -209,7 +211,7 @@ describe('resolveConversationCodeEnvironmentMove', () => {
from: [mac, team],
to: [team],
}),
- ).toEqual({ codeWorkspaces: [team] });
+ ).toEqual({ mode: 'attached', codeWorkspaces: [team] });
});
it('rejects a move that changes nothing', () => {
@@ -222,12 +224,57 @@ describe('resolveConversationCodeEnvironmentMove', () => {
).toThrow(locked);
});
+ it('attaches an environment to a chat that recorded running without one', () => {
+ expect(
+ resolveConversationCodeEnvironmentMove({
+ conversation: {
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'without_attached',
+ },
+ from: [],
+ to: [vm, mac],
+ }),
+ ).toEqual({ mode: 'attached', codeWorkspaces: [mac, vm] });
+ });
+
+ /* An attach still replaces a decision the client has seen, and a chat that recorded none is not
+ * sealed at all: its next turn records one, so the composer selects instead of transitioning. */
+ it('rejects attaching against a decision the conversation does not hold', () => {
+ expect(() =>
+ resolveConversationCodeEnvironmentMove({
+ conversation: { conversationId: 'conversation-1' },
+ from: [],
+ to: [vm],
+ }),
+ ).toThrow(locked);
+ expect(() =>
+ resolveConversationCodeEnvironmentMove({
+ conversation: {
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'without_attached',
+ },
+ from: [mac],
+ to: [vm],
+ }),
+ ).toThrow(locked);
+ });
+
+ it('leaves every attached environment when the target set is empty', () => {
+ expect(
+ resolveConversationCodeEnvironmentMove({
+ conversation: sealedOn(mac, vm),
+ from: [mac, vm],
+ to: [],
+ }),
+ ).toEqual({ mode: 'without_attached' });
+ });
+
it.each([
{ conversationId: 'conversation-1', codeEnvironmentMode: 'without_attached' as const },
{ conversationId: 'conversation-1' },
- ])('never upgrades a conversation that continues without an attached environment', (stored) => {
+ ])('has nothing to detach without an attached decision: %j', (stored) => {
expect(() =>
- resolveConversationCodeEnvironmentMove({ conversation: stored, from: [], to: [vm] }),
+ resolveConversationCodeEnvironmentMove({ conversation: stored, from: [], to: [] }),
).toThrow(locked);
});
@@ -237,7 +284,7 @@ describe('resolveConversationCodeEnvironmentMove', () => {
).toThrow(locked);
});
- it.each([[], undefined, [vm, { ...vm, workspaceId: 'other' }], [{ environmentId: 'vm' }]])(
+ it.each([undefined, [vm, { ...vm, workspaceId: 'other' }], [{ environmentId: 'vm' }]])(
'rejects a malformed target: %j',
(to) => {
expect(() =>
@@ -357,3 +404,119 @@ describe('resolvePersistableCodeEnvironmentDecision', () => {
);
});
});
+
+describe('resolveAdmittedCodeEnvironmentDecision', () => {
+ const withMoves = (conversationMoves?: { enabled?: boolean; allowAttachDetach?: boolean }) =>
+ ({
+ endpoints: { agents: { statefulCodeSessions: { conversationMoves } } },
+ }) as AppConfig;
+
+ it.each([undefined, {}, { enabled: false }, { enabled: false, allowAttachDetach: true }])(
+ 'reuses the loaded decision without a database fence when moves are disabled: %j',
+ async (conversationMoves) => {
+ const readDecision = jest.fn();
+ const conversation = {
+ conversationId: 'saved',
+ codeEnvironmentMode: 'attached' as const,
+ codeWorkspaces: [selection],
+ };
+ expect(
+ await resolveAdmittedCodeEnvironmentDecision({
+ appConfig: withMoves(conversationMoves),
+ conversationId: 'saved',
+ conversation,
+ readDecision,
+ }),
+ ).toEqual({ decision: { mode: 'attached', codeWorkspaces: [selection] }, conversation });
+ expect(readDecision).not.toHaveBeenCalled();
+ },
+ );
+
+ it('does not read or write again without configuration or a persisted conversation', async () => {
+ const readDecision = jest.fn();
+ expect(
+ await resolveAdmittedCodeEnvironmentDecision({
+ appConfig: undefined,
+ conversationId: 'new-id',
+ conversation: null,
+ requestedMode: 'without_attached',
+ readDecision,
+ }),
+ ).toEqual({ decision: { mode: 'without_attached' }, conversation: null });
+ expect(readDecision).not.toHaveBeenCalled();
+ });
+
+ it('uses the authoritative admitted read', async () => {
+ const readDecision = jest.fn().mockResolvedValue({
+ conversationId: 'saved',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [selection],
+ });
+ expect(
+ await resolveAdmittedCodeEnvironmentDecision({
+ appConfig: withMoves({ enabled: true }),
+ conversationId: 'saved',
+ conversation: { conversationId: 'saved', codeEnvironmentMode: 'without_attached' },
+ readDecision,
+ }),
+ ).toEqual({
+ decision: { mode: 'attached', codeWorkspaces: [selection] },
+ conversation: {
+ conversationId: 'saved',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [selection],
+ },
+ });
+ expect(readDecision).toHaveBeenCalledWith('saved');
+ });
+ it('carries the authoritative selections rather than a cached machine into validation', async () => {
+ const old = { environmentId: 'old', workspaceId: 'repo' };
+ const conversation = {
+ conversationId: 'saved',
+ codeEnvironmentMode: 'attached' as const,
+ codeWorkspaces: [old],
+ };
+ const result = await resolveAdmittedCodeEnvironmentDecision({
+ appConfig: withMoves({ enabled: true }),
+ conversationId: 'saved',
+ conversation,
+ readDecision: async () => ({ ...conversation, codeWorkspaces: [selection] }),
+ });
+ expect(result.conversation?.codeWorkspaces).toEqual([selection]);
+ expect(result.decision.codeWorkspaces).toEqual(result.conversation?.codeWorkspaces);
+ });
+
+ it('keeps an unpersisted first choice separate from the admitted snapshot', async () => {
+ const result = await resolveAdmittedCodeEnvironmentDecision({
+ appConfig: withMoves({ enabled: true }),
+ conversationId: 'saved',
+ conversation: {
+ conversationId: 'saved',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [selection],
+ },
+ requestedMode: 'attached',
+ requestedSelections: [selection],
+ readDecision: async () => ({ conversationId: 'saved' }),
+ });
+ expect(result.decision.mode).toBe('attached');
+ expect(result.conversation?.codeEnvironmentMode).toBeUndefined();
+ expect(result.conversation?.codeWorkspaces).toBeUndefined();
+ });
+
+ it('rejects an old requested mode when the transition won first', async () => {
+ const readDecision = jest.fn().mockResolvedValue({
+ conversationId: 'saved',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [selection],
+ });
+ await expect(
+ resolveAdmittedCodeEnvironmentDecision({
+ appConfig: withMoves({ enabled: true, allowAttachDetach: true }),
+ conversationId: 'saved',
+ requestedMode: 'without_attached',
+ readDecision,
+ }),
+ ).rejects.toMatchObject({ reason: 'locked' });
+ });
+});
diff --git a/packages/api/src/code/decision.ts b/packages/api/src/code/decision.ts
index ff1346c9e0..2eec82ec84 100644
--- a/packages/api/src/code/decision.ts
+++ b/packages/api/src/code/decision.ts
@@ -4,7 +4,9 @@ import type {
CodeWorkspaceSelection,
TConversation,
} from 'librechat-data-provider';
+import type { AppConfig } from '@librechat/data-schemas';
import { CodeWorkspaceSelectionError } from './capabilities';
+import { resolveCodeEnvironmentMoveVersion } from './config';
export interface ConversationCodeEnvironmentDecision {
mode: CodeEnvironmentMode;
@@ -14,7 +16,7 @@ export interface ConversationCodeEnvironmentDecision {
export type StoredConversationDecision = Pick<
TConversation,
'conversationId' | 'codeEnvironmentMode' | 'codeWorkspaces'
->;
+> & { codeEnvironmentRevision?: number };
function canonicalSelections(selections: CodeWorkspaceSelection[]): CodeWorkspaceSelection[] {
return [...selections].sort((left, right) => {
@@ -120,14 +122,16 @@ export function resolveConversationCodeEnvironmentDecision({
}
export interface ConversationCodeEnvironmentMove {
- codeWorkspaces: CodeWorkspaceSelection[];
+ mode: CodeEnvironmentMode;
+ codeWorkspaces?: CodeWorkspaceSelection[];
}
/**
- * Validates the shape and expected decision of an owner's explicit move. The caller must verify
- * live registration of every target and, for same-environment replacements, absence of the old
- * workspace before persisting. `from` must repeat the persisted selections, so a stale client
- * cannot replace a decision it has not seen. A chat without an attached decision stays sealed.
+ * Validates an owner's explicit replacement of a sealed decision. Attach, detach, moves and
+ * missing-workspace recovery replace the whole decision without changing history or copying files.
+ * The caller must verify live registration of every target and, for same-environment replacements,
+ * absence of the previous workspace. `from` repeats the stored selections so stale clients cannot
+ * replace a decision they have not seen. Undecided chats record their first decision on submission.
*/
export function resolveConversationCodeEnvironmentMove({
conversation,
@@ -138,20 +142,30 @@ export function resolveConversationCodeEnvironmentMove({
from: unknown;
to: unknown;
}): ConversationCodeEnvironmentMove {
- const persisted = readPersistedDecision(conversation);
- if (persisted.mode !== 'attached' || persisted.codeWorkspaces == null) {
+ if (!holdsDecision(conversation)) {
throw new CodeWorkspaceSelectionError('locked');
}
- if (!isCodeWorkspaceSelections(from) || !sameSelections(from, persisted.codeWorkspaces)) {
+ const persisted = readPersistedDecision(conversation);
+ const sealed = persisted.codeWorkspaces ?? [];
+ if (!isCodeWorkspaceSelections(from) || !sameSelections(from, sealed)) {
throw new CodeWorkspaceSelectionError('locked');
}
- if (!isCodeWorkspaceSelections(to) || to.length === 0) {
+ if (!isCodeWorkspaceSelections(to)) {
throw new CodeWorkspaceSelectionError('invalid');
}
- if (sameSelections(to, persisted.codeWorkspaces)) {
+ if (to.length === 0) {
+ if (persisted.mode !== 'attached') {
+ throw new CodeWorkspaceSelectionError('locked');
+ }
+ return { mode: 'without_attached' };
+ }
+ if (persisted.mode === 'without_attached') {
+ return { mode: 'attached', codeWorkspaces: canonicalSelections(to) };
+ }
+ if (sameSelections(to, sealed)) {
throw new CodeWorkspaceSelectionError('locked');
}
- return { codeWorkspaces: canonicalSelections(to) };
+ return { mode: 'attached', codeWorkspaces: canonicalSelections(to) };
}
type PersistableDecisionFields = Pick<
@@ -202,3 +216,37 @@ export function resolvePersistableCodeEnvironmentDecision({
}
return { codeEnvironmentMode: candidate.codeEnvironmentMode };
}
+
+/** When moves are enabled, every ingress must publish its active job before calling this and
+ * keep it active through the fenced read. Otherwise no transition can race the decision, so reuse
+ * the owner-scoped conversation the ingress already loaded instead of writing an unused revision. */
+export async function resolveAdmittedCodeEnvironmentDecision({
+ appConfig,
+ readDecision,
+ ...request
+}: Parameters<typeof resolveConversationCodeEnvironmentDecision>[0] & {
+ appConfig: Pick<AppConfig, 'endpoints'> | undefined;
+ readDecision: (conversationId: string) => Promise<StoredConversationDecision | null | undefined>;
+}): Promise<{
+ decision: ConversationCodeEnvironmentDecision;
+ conversation: StoredConversationDecision | null | undefined;
+}> {
+ const conversation =
+ resolveCodeEnvironmentMoveVersion(appConfig) != null
+ ? await readDecision(request.conversationId)
+ : request.conversation;
+ return {
+ decision: resolveConversationCodeEnvironmentDecision({ ...request, conversation }),
+ // Keep owner-loaded metadata, but never the pre-admission environment fields. An absent
+ // stored decision must remain absent; the submitted first choice is not persisted yet.
+ conversation:
+ conversation == null
+ ? conversation
+ : {
+ ...request.conversation,
+ ...conversation,
+ codeEnvironmentMode: conversation.codeEnvironmentMode,
+ codeWorkspaces: conversation.codeWorkspaces,
+ },
+ };
+}
diff --git a/packages/api/src/code/http.spec.ts b/packages/api/src/code/http.spec.ts
index 9bc6872003..71bb7b131b 100644
--- a/packages/api/src/code/http.spec.ts
+++ b/packages/api/src/code/http.spec.ts
@@ -1507,6 +1507,7 @@ describe('moving a sealed conversation code-environment decision', () => {
type Selection = { environmentId: string; workspaceId: string };
type StoredDecision = {
conversationId: string;
+ codeEnvironmentRevision?: number;
codeEnvironmentMode?: 'attached' | 'without_attached';
codeWorkspaces?: Selection[];
};
@@ -1545,6 +1546,7 @@ describe('moving a sealed conversation code-environment decision', () => {
function setup({
movesEnabled = true,
+ allowAttachDetach = true,
stored = {
conversationId: 'conversation-1',
codeEnvironmentMode: 'attached',
@@ -1555,6 +1557,7 @@ describe('moving a sealed conversation code-environment decision', () => {
fetchImpl = jest.fn().mockImplementation(async () => workerStatusResponse()),
}: {
movesEnabled?: boolean;
+ allowAttachDetach?: boolean;
stored?: StoredDecision;
job?: CodeEnvironmentGenerationJob;
conversationRunIds?: string[];
@@ -1570,23 +1573,31 @@ describe('moving a sealed conversation code-environment decision', () => {
async ({
conversationId,
expected,
+ codeEnvironmentMode,
codeWorkspaces,
}: {
conversationId: string;
- expected: Pick<StoredDecision, 'codeEnvironmentMode' | 'codeWorkspaces'>;
- codeWorkspaces: Selection[];
+ expected: Pick<StoredDecision, 'codeEnvironmentMode' | 'codeWorkspaces'> & {
+ codeEnvironmentRevision?: number;
+ };
+ codeEnvironmentMode: StoredDecision['codeEnvironmentMode'];
+ codeWorkspaces?: Selection[];
}) => {
const current = conversations.get(conversationId);
const decisionOf = (decision: Partial<StoredDecision> | undefined) =>
- JSON.stringify([decision?.codeEnvironmentMode ?? null, decision?.codeWorkspaces ?? null]);
+ JSON.stringify([
+ decision?.codeEnvironmentMode ?? null,
+ decision?.codeWorkspaces ?? null,
+ (decision as { codeEnvironmentRevision?: number })?.codeEnvironmentRevision ?? null,
+ ]);
if (current == null || decisionOf(current) !== decisionOf(expected)) {
return null;
}
- const moved: StoredDecision = {
- ...current,
- codeEnvironmentMode: 'attached',
- codeWorkspaces,
- };
+ /** Mirrors the stored shape: leaving attached execution clears the selections. */
+ const moved: StoredDecision =
+ codeEnvironmentMode === 'attached'
+ ? { ...current, codeEnvironmentMode, codeWorkspaces }
+ : { conversationId: current.conversationId, codeEnvironmentMode };
conversations.set(conversationId, moved);
return moved;
},
@@ -1597,7 +1608,7 @@ describe('moving a sealed conversation code-environment decision', () => {
[EModelEndpoint.agents]: {
statefulCodeSessions: {
environments: [controlPlane],
- conversationMoves: { enabled: movesEnabled },
+ conversationMoves: { enabled: movesEnabled, allowAttachDetach },
},
},
},
@@ -1883,6 +1894,144 @@ describe('moving a sealed conversation code-environment decision', () => {
expect(conversations.get('conversation-1')?.codeWorkspaces).toEqual([gone, vm]);
});
+ test('attaches a workspace to a chat that recorded running without one', async () => {
+ const { move, conversations, fetchImpl } = setup({
+ stored: { conversationId: 'conversation-1', codeEnvironmentMode: 'without_attached' },
+ });
+
+ const res = await move({ from: [], to: [vm] });
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual({
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [vm],
+ });
+ expect(conversations.get('conversation-1')).toEqual({
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [vm],
+ });
+ /** The attached workspace is revalidated exactly like a move's target. */
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ });
+
+ test('rejects attaching a workspace the machine does not register', async () => {
+ const { move, conversations, replaceDecision } = setup({
+ stored: { conversationId: 'conversation-1', codeEnvironmentMode: 'without_attached' },
+ fetchImpl: jest
+ .fn()
+ .mockImplementation(async () =>
+ workerStatusResponse({ workspaces: [{ id: 'another-project' }] }),
+ ),
+ });
+
+ const res = await move({ from: [], to: [vm] });
+
+ expect(res.statusCode).toBe(409);
+ expect(res.body).toEqual(expect.objectContaining({ reason: 'missing' }));
+ expect(replaceDecision).not.toHaveBeenCalled();
+ expect(conversations.get('conversation-1')).toEqual({
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'without_attached',
+ });
+ });
+
+ test('leaves an attached machine without polling it and clears the selections', async () => {
+ const { move, conversations, fetchImpl } = setup();
+
+ const res = await move({ from: [mac], to: [] });
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual({
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'without_attached',
+ });
+ /** The machine a chat is leaving is usually the unreachable one; checking it would refuse the
+ * one transition that works while it is down. */
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect(conversations.get('conversation-1')).toEqual({
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'without_attached',
+ });
+ });
+
+ test('refuses to leave while a generation is still running', async () => {
+ const { move, replaceDecision } = setup({ job: { status: 'running' } });
+
+ expect((await move({ from: [mac], to: [] })).statusCode).toBe(409);
+ expect(replaceDecision).not.toHaveBeenCalled();
+ });
+
+ /* Revalidating the target is a round trip to the worker, so the earlier checks are stale when it
+ * returns. A turn that starts in that window would run in the previous environment while the
+ * conversation reports the new one, and the swap would still succeed: the stored decision it
+ * expects is unchanged, because a run never rewrites one the conversation already holds. */
+ test('refuses when a generation starts while the target worker is being checked', async () => {
+ const job: CodeEnvironmentGenerationJob = {
+ status: 'complete',
+ metadata: { terminalPersistencePending: false },
+ };
+ const fetchImpl = jest.fn().mockImplementation(async () => {
+ job.status = 'running';
+ return workerStatusResponse();
+ });
+ const { move, conversations, replaceDecision } = setup({ job, fetchImpl });
+
+ const res = await move({ from: [mac], to: [vm] });
+
+ expect(res.statusCode).toBe(409);
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ expect(replaceDecision).not.toHaveBeenCalled();
+ expect(conversations.get('conversation-1')?.codeWorkspaces).toEqual([mac]);
+ });
+
+ test('refuses when a remote run claims the conversation during that check', async () => {
+ const runIds: string[] = [];
+ const fetchImpl = jest.fn().mockImplementation(async () => {
+ runIds.push('resp_remote-run');
+ return workerStatusResponse();
+ });
+ const { move, replaceDecision } = setup({ conversationRunIds: runIds, fetchImpl });
+
+ expect((await move({ from: [mac], to: [vm] })).statusCode).toBe(409);
+ expect(replaceDecision).not.toHaveBeenCalled();
+ });
+
+ test('preserves moves but rejects attach and detach in a move-only deployment', async () => {
+ const context = setup({ allowAttachDetach: false });
+ expect((await context.move({ from: [mac], to: [] })).statusCode).toBe(403);
+ expect(context.replaceDecision).not.toHaveBeenCalled();
+ expect((await context.move({ from: [mac], to: [vm] })).statusCode).toBe(200);
+ const unattached = setup({
+ allowAttachDetach: false,
+ stored: {
+ conversationId: 'conversation-1',
+ codeEnvironmentMode: 'without_attached',
+ },
+ });
+ expect((await unattached.move({ from: [], to: [vm] })).statusCode).toBe(403);
+ expect(unattached.fetchImpl).not.toHaveBeenCalled();
+ expect(unattached.replaceDecision).not.toHaveBeenCalled();
+ });
+
+ test('rejects when an admitted read advances the revision after the final idle check', async () => {
+ const context = setup();
+ const swap = context.replaceDecision.getMockImplementation()!;
+ context.replaceDecision.mockImplementationOnce(async (args) => {
+ // The real readAdmittedConvoCodeEnvironmentDecision advances this in Mongo atomically.
+ context.conversations.set('conversation-1', {
+ ...context.conversations.get('conversation-1')!,
+ codeEnvironmentRevision: 1,
+ } as StoredDecision);
+ return swap(args);
+ });
+ const res = await context.move({ from: [mac], to: [vm] });
+ expect(res.statusCode).toBe(409);
+ expect(res.body).toEqual(expect.objectContaining({ reason: 'locked' }));
+ expect(context.conversations.get('conversation-1')?.codeWorkspaces).toEqual([mac]);
+ });
+
test('moves once the previous generation has settled and saved', async () => {
const { move } = setup({
job: { status: 'complete', metadata: { terminalPersistencePending: false } },
diff --git a/packages/api/src/code/http.ts b/packages/api/src/code/http.ts
index ec02903105..bd9e78e4d3 100644
--- a/packages/api/src/code/http.ts
+++ b/packages/api/src/code/http.ts
@@ -1,7 +1,7 @@
import { nanoid } from 'nanoid';
import { EModelEndpoint } from 'librechat-data-provider';
import { logger, type AppConfig } from '@librechat/data-schemas';
-import type { CodeWorkspaceSelection } from 'librechat-data-provider';
+import type { CodeEnvironmentMode, CodeWorkspaceSelection } from 'librechat-data-provider';
import type { Response } from 'express';
import type {
CodeEnvironmentLifecycleTarget,
@@ -40,9 +40,12 @@ import {
CodeEnvironmentSettingsValidationError,
validateCodeEnvironmentUserSettings,
} from './settings';
+import {
+ resolveCodeEnvironmentMoveVersion,
+ resolveCodeEnvironmentTransitionVersion,
+} from './config';
import { resolveConversationCodeEnvironmentMove } from './decision';
import { resolveCodeWorkerEnrollmentLimit } from './enrollment';
-import { resolveCodeEnvironmentMoveVersion } from './config';
import { CodeWorkspaceSelectionError } from './capabilities';
import { getAppConfigOptionsFromUser } from '~/app/service';
@@ -88,8 +91,13 @@ export interface CodeEnvironmentConversationDeps {
replaceDecision: (params: {
user: string;
conversationId: string;
- expected: Pick<StoredConversationDecision, 'codeEnvironmentMode' | 'codeWorkspaces'>;
- codeWorkspaces: CodeWorkspaceSelection[];
+ expected: Pick<
+ StoredConversationDecision,
+ 'codeEnvironmentMode' | 'codeWorkspaces' | 'codeEnvironmentRevision'
+ >;
+ codeEnvironmentMode: CodeEnvironmentMode;
+ /** Omitted by a detach, which leaves the conversation without any attached selection. */
+ codeWorkspaces?: CodeWorkspaceSelection[];
}) => Promise<StoredConversationDecision | null>;
}
@@ -368,11 +376,13 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps)
}
/**
- * Moves a sealed attached decision onto the environments a conversation's agents now use, when
- * the effective policy enables moves. Runs never rewrite a stored decision, so no run from any
- * ingress can write its run-start decision back over a move. A move is still refused while a
- * generation is running, awaiting approval, or saving its response, so that generation does not
- * keep working in the previous environment after the conversation has left it.
+ * Replaces a conversation's sealed code-environment decision with the one its owner chose: a
+ * move onto the environments its agents now use, an attach for a chat that has been running
+ * without one, or a detach off a machine it can no longer reach. Applies only when the effective
+ * policy enables moves. Runs never rewrite a stored decision, so no run from any ingress can
+ * write its run-start decision back over one of these. Each is still refused while a generation
+ * is running, awaiting approval, or saving its response, so that generation does not keep
+ * working in the previous environment after the conversation has left it.
*/
async function moveConversationDecision(req: ServerRequest, res: Response): Promise<Response> {
const principal = actor(req);
@@ -413,15 +423,26 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps)
if (conversation == null) {
return res.status(404).json({ error: 'Conversation was not found' });
}
- if (isGenerationActive(job) || conversationRunIds.length > 0) {
- return res
+ const busyResponse = () =>
+ res
.status(409)
.json({ error: 'Wait for the current response to finish before moving this conversation' });
+ if (isGenerationActive(job) || conversationRunIds.length > 0) {
+ return busyResponse();
}
let move: ConversationCodeEnvironmentMove;
try {
move = resolveConversationCodeEnvironmentMove({ conversation, from, to });
+ if (
+ (conversation.codeEnvironmentMode === 'without_attached' ||
+ move.mode === 'without_attached') &&
+ resolveCodeEnvironmentTransitionVersion(policy.effectiveConfig) == null
+ ) {
+ return res
+ .status(403)
+ .json({ error: 'Conversation code environment attach/detach is disabled' });
+ }
} catch (error) {
if (error instanceof CodeWorkspaceSelectionError) {
return selectionErrorResponse(error, res);
@@ -430,7 +451,7 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps)
}
try {
await Promise.all(
- move.codeWorkspaces.map((selection) =>
+ (move.codeWorkspaces ?? []).map((selection) =>
assertWorkspaceRegistered(
policy,
selection,
@@ -447,13 +468,27 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps)
throw error;
}
+ /** Worker checks are network round trips. Recheck long-lived work afterwards. Every admitted
+ * run advances the decision revision before reading, while its job remains active. The CAS
+ * below catches a run admitted after this final idle check; a run admitted after the CAS
+ * instead reads the new decision. */
+ const [pendingJob, pendingRunIds] = await Promise.all([
+ generations.getJob(conversationId),
+ generations.getCleanupBlockingJobIdsForConversations(userId, [conversationId], tenantId),
+ ]);
+ if (isGenerationActive(pendingJob) || pendingRunIds.length > 0) {
+ return busyResponse();
+ }
+
const moved = await conversations.replaceDecision({
user: userId,
conversationId,
expected: {
codeEnvironmentMode: conversation.codeEnvironmentMode,
codeWorkspaces: conversation.codeWorkspaces,
+ codeEnvironmentRevision: conversation.codeEnvironmentRevision,
},
+ codeEnvironmentMode: move.mode,
codeWorkspaces: move.codeWorkspaces,
});
if (moved == null) {
@@ -461,8 +496,8 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps)
}
return res.status(200).json({
conversationId,
- codeEnvironmentMode: 'attached',
- codeWorkspaces: move.codeWorkspaces,
+ codeEnvironmentMode: move.mode,
+ ...(move.codeWorkspaces != null && { codeWorkspaces: move.codeWorkspaces }),
});
}
diff --git a/packages/data-provider/src/code/workspace.ts b/packages/data-provider/src/code/workspace.ts
index 52beb3c6f6..33e0592fe4 100644
--- a/packages/data-provider/src/code/workspace.ts
+++ b/packages/data-provider/src/code/workspace.ts
@@ -5,6 +5,14 @@ export const CODE_WORKSPACE_MAX_COUNT = 32;
export const CODE_ENVIRONMENT_DECISION_VERSION = 1 as const;
/** API/client protocol for an owner's explicit move of a sealed environment decision. */
export const CODE_ENVIRONMENT_MOVE_VERSION = 1 as const;
+/**
+ * API/client protocol for the other two replacements of a sealed decision: attaching an
+ * environment to a chat that recorded running without one, and leaving attached execution behind.
+ * Advertised beside the move version rather than replacing it, so a client that predates this
+ * capability keeps the move it already had while a deployment rolls out, and a client that has it
+ * never offers an attach a replica would refuse as `locked` or a detach it would call `invalid`.
+ */
+export const CODE_ENVIRONMENT_TRANSITION_VERSION = 2 as const;
/** Additive capability for replacing a missing workspace without disabling moves in V1 clients. */
export const CODE_WORKSPACE_RECOVERY_VERSION = 1 as const;
export const CODE_WORKSPACE_OPERATIONS = [
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 3acf59cd6b..d5b8eb0185 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -33,6 +33,7 @@ import {
import {
CODE_ENVIRONMENT_DECISION_VERSION,
CODE_ENVIRONMENT_MOVE_VERSION,
+ CODE_ENVIRONMENT_TRANSITION_VERSION,
CODE_WORKSPACE_RECOVERY_VERSION,
} from './code/workspace';
import { ComponentTypes, SettingTypes, OptionTypes } from './generate';
@@ -1383,6 +1384,9 @@ export const agentsEndpointSchema = baseEndpointSchema
conversationMoves: z
.object({
enabled: z.boolean().optional(),
+ /** Opt in after every API replica supports attach/detach. Omitted or false keeps
+ * the existing move-only policy, including for already-enabled deployments. */
+ allowAttachDetach: z.boolean().optional(),
})
.optional(),
/** Operator-managed execution environments. Attached entries route to a
@@ -2432,6 +2436,9 @@ export type TStartupConfig = {
/** Owner moves of a sealed code-environment decision supported by the API. Clients must not
* offer to move a conversation unless this is advertised. */
codeEnvironmentMoveVersion?: typeof CODE_ENVIRONMENT_MOVE_VERSION;
+ /** Owner attach and detach of a sealed code-environment decision supported by the API. Clients
+ * must not offer either unless this is advertised, independently of the move version. */
+ codeEnvironmentTransitionVersion?: typeof CODE_ENVIRONMENT_TRANSITION_VERSION;
/** Additive recovery support. Clients require this and the move capability before replacing
* a missing workspace. Keeping it separate preserves exact-version checks in older clients. */
codeWorkspaceRecoveryVersion?: typeof CODE_WORKSPACE_RECOVERY_VERSION;
diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts
index f02fc87811..681188237e 100644
--- a/packages/data-provider/src/types.ts
+++ b/packages/data-provider/src/types.ts
@@ -615,18 +615,24 @@ export type TCodeEnvironmentStatusResponse = {
workspaces?: CodeWorkspaceDescriptor[];
};
-/** Moves a sealed attached decision onto the environments a conversation's agents now use. */
+/**
+ * Replaces a conversation's sealed code-environment decision: a move onto the environments its
+ * agents now use, an attach for a chat running without one, or a detach off an attached machine.
+ */
export type TCodeEnvironmentMoveRequest = {
conversationId: string;
- /** The persisted selections being replaced; a mismatch rejects the move as stale. */
+ /** The persisted selections being replaced, empty for a chat without an attached environment;
+ * a mismatch rejects the change as stale. */
from: CodeWorkspaceSelection[];
+ /** Empty to continue without an attached environment. */
to: CodeWorkspaceSelection[];
};
export type TCodeEnvironmentMoveResponse = {
conversationId: string;
- codeEnvironmentMode: 'attached';
- codeWorkspaces: CodeWorkspaceSelection[];
+ codeEnvironmentMode: CodeEnvironmentMode;
+ /** Absent once the conversation continues without an attached environment. */
+ codeWorkspaces?: CodeWorkspaceSelection[];
};
/** Sanitized results of server request shaping for each saved toggle state. */
diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.ts
index 704327518d..f3069b7e1a 100644
--- a/packages/data-schemas/src/methods/conversation.spec.ts
+++ b/packages/data-schemas/src/methods/conversation.spec.ts
@@ -1112,6 +1112,7 @@ describe('Conversation Operations', () => {
user: userId,
conversationId,
expected: decision,
+ codeEnvironmentMode: 'attached',
codeWorkspaces: [vm],
});
@@ -1136,6 +1137,7 @@ describe('Conversation Operations', () => {
user: userId,
conversationId,
expected: decision,
+ codeEnvironmentMode: 'attached',
codeWorkspaces: [vm],
});
await methods.bulkSaveConvos([imported]);
@@ -1237,14 +1239,16 @@ describe('Conversation Operations', () => {
codeWorkspaces: NonNullable<IConversation['codeWorkspaces']>,
user = 'user123',
) => {
- const stored = await getConvo('user123', conversationId);
+ const stored = await methods.getConvoCodeEnvironmentDecision('user123', conversationId);
return methods.replaceConvoCodeEnvironmentDecision({
user,
conversationId,
expected: {
codeEnvironmentMode: stored?.codeEnvironmentMode,
codeWorkspaces: stored?.codeWorkspaces,
+ codeEnvironmentRevision: stored?.codeEnvironmentRevision,
},
+ codeEnvironmentMode: 'attached',
codeWorkspaces,
});
};
@@ -1289,6 +1293,154 @@ describe('Conversation Operations', () => {
expect(result?.codeWorkspaces).toEqual([vm]);
});
+ it('advances the revision and returns the snapshot in one database round trip', async () => {
+ const conversationId = await seedDecision({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac],
+ });
+ const update = jest.spyOn(Conversation.collection, 'findOneAndUpdate');
+ const read = jest.spyOn(Conversation.collection, 'findOne');
+ try {
+ const result = await methods.readAdmittedConvoCodeEnvironmentDecision(
+ 'user123',
+ conversationId,
+ );
+ expect(result?.codeWorkspaces).toEqual([mac]);
+ expect(update).toHaveBeenCalledTimes(1);
+ expect(read).not.toHaveBeenCalled();
+ } finally {
+ update.mockRestore();
+ read.mockRestore();
+ }
+ });
+
+ it('rejects a transition when an admitted run reads after the idle check', async () => {
+ const conversationId = await seedDecision({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac],
+ });
+ const snapshot = await methods.getConvoCodeEnvironmentDecision('user123', conversationId);
+ const admitted = await methods.readAdmittedConvoCodeEnvironmentDecision(
+ 'user123',
+ conversationId,
+ );
+ expect(admitted?.codeWorkspaces).toEqual([mac]);
+ expect(
+ await methods.replaceConvoCodeEnvironmentDecision({
+ user: 'user123',
+ conversationId,
+ expected: snapshot!,
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [vm],
+ }),
+ ).toBeNull();
+ expect((await getConvo('user123', conversationId))?.codeWorkspaces).toEqual([mac]);
+ });
+
+ it('gives an admitted run the new decision when the transition wins first', async () => {
+ const conversationId = await seedDecision({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac],
+ });
+ const snapshot = await methods.getConvoCodeEnvironmentDecision('user123', conversationId);
+ expect(
+ await methods.replaceConvoCodeEnvironmentDecision({
+ user: 'user123',
+ conversationId,
+ expected: snapshot!,
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [vm],
+ }),
+ ).not.toBeNull();
+ const admitted = await methods.readAdmittedConvoCodeEnvironmentDecision(
+ 'user123',
+ conversationId,
+ );
+ expect(admitted?.codeWorkspaces).toEqual([vm]);
+ expect(admitted).not.toHaveProperty('codeEnvironmentRevision');
+ const current = await getConvo('user123', conversationId);
+ expect(current).not.toHaveProperty('codeEnvironmentRevision');
+ expect(new Date(current?.updatedAt ?? 0).toISOString()).toBe(anchor.toISOString());
+ });
+
+ it("does not advance another tenant's decision revision", async () => {
+ const conversationId = await seedDecision({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac],
+ tenantId: 'tenant-a',
+ });
+ const other = await tenantStorage.run({ tenantId: 'tenant-b' }, () =>
+ methods.readAdmittedConvoCodeEnvironmentDecision('user123', conversationId),
+ );
+ expect(other).toBeNull();
+ const own = await tenantStorage.run({ tenantId: 'tenant-a' }, () =>
+ methods.readAdmittedConvoCodeEnvironmentDecision('user123', conversationId),
+ );
+ expect(own?.codeWorkspaces).toEqual([mac]);
+ const raw = await Conversation.collection.findOne({ conversationId });
+ expect(raw?.codeEnvironmentRevision).toBe(1);
+ });
+
+ it('protects the revision from ordinary saves, imports and other users', async () => {
+ const conversationId = await seedDecision({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac],
+ });
+ await methods.readAdmittedConvoCodeEnvironmentDecision('user123', conversationId);
+ const before = await methods.getConvoCodeEnvironmentDecision('user123', conversationId);
+ await saveConvo(
+ { userId: 'user123' },
+ { conversationId, codeEnvironmentRevision: 999 },
+ { unsetFields: { codeEnvironmentRevision: 1 } },
+ );
+ await methods.bulkSaveConvos([
+ { conversationId, user: 'user123', codeEnvironmentRevision: 0 },
+ ]);
+ expect(
+ (await methods.getConvoCodeEnvironmentDecision('user123', conversationId))
+ ?.codeEnvironmentRevision,
+ ).toBe(before?.codeEnvironmentRevision);
+ expect(
+ await methods.readAdmittedConvoCodeEnvironmentDecision('someone-else', conversationId),
+ ).toBeNull();
+ });
+
+ it('attaches an environment to a chat stored without one', async () => {
+ const conversationId = await seedDecision({ codeEnvironmentMode: 'without_attached' });
+
+ const result = await methods.replaceConvoCodeEnvironmentDecision({
+ user: 'user123',
+ conversationId,
+ expected: { codeEnvironmentMode: 'without_attached' },
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [vm],
+ });
+
+ expect(result?.codeEnvironmentMode).toBe('attached');
+ expect(result?.codeWorkspaces).toEqual([vm]);
+ });
+
+ it('clears the selections when a chat leaves attached execution', async () => {
+ const conversationId = await seedDecision({
+ codeEnvironmentMode: 'attached',
+ codeWorkspaces: [mac, team],
+ });
+
+ const result = await methods.replaceConvoCodeEnvironmentDecision({
+ user: 'user123',
+ conversationId,
+ expected: { codeEnvironmentMode: 'attached', codeWorkspaces: [mac, team] },
+ codeEnvironmentMode: 'without_attached',
+ });
+
+ expect(result?.codeEnvironmentMode).toBe('without_attached');
+ /** Keeping them would read as an attached decision again on the next turn. */
+ expect(result?.codeWorkspaces).toBeUndefined();
+ const stored = await getConvo('user123', conversationId);
+ expect(stored?.codeWorkspaces).toBeUndefined();
+ expect(new Date(stored?.updatedAt ?? 0).toISOString()).toBe(anchor.toISOString());
+ });
+
it('leaves a decision that changed after it was read untouched', async () => {
const conversationId = await seedDecision({
codeEnvironmentMode: 'attached',
@@ -1306,7 +1458,9 @@ describe('Conversation Operations', () => {
expected: {
codeEnvironmentMode: stored?.codeEnvironmentMode,
codeWorkspaces: stored?.codeWorkspaces,
+ codeEnvironmentRevision: stored?.codeEnvironmentRevision,
},
+ codeEnvironmentMode: 'attached',
codeWorkspaces: [vm],
});
@@ -1325,6 +1479,7 @@ describe('Conversation Operations', () => {
user: 'user123',
conversationId,
expected: { codeEnvironmentMode: 'attached', codeWorkspaces: [team, mac] },
+ codeEnvironmentMode: 'attached',
codeWorkspaces: [vm],
});
@@ -1341,6 +1496,7 @@ describe('Conversation Operations', () => {
user: 'user123',
conversationId,
expected: { codeEnvironmentMode: 'attached', codeWorkspaces: [mac] },
+ codeEnvironmentMode: 'attached',
codeWorkspaces: [vm],
});
diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.ts
index 71811f2f44..9c2534d670 100644
--- a/packages/data-schemas/src/methods/conversation.ts
+++ b/packages/data-schemas/src/methods/conversation.ts
@@ -45,6 +45,7 @@ import {
import { createChatExpirationDate, createTempChatExpirationDate } from '~/utils/tempChatRetention';
import { isAgentFadingTier, isAgentFadingTierEntries } from '~/utils/fading';
import { isCompactionSemanticIndexProjection } from '~/types/compaction';
+import { withoutMeiliIndexing } from '~/models/plugins/mongoMeili';
import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';
import { isValidObjectIdString } from '~/utils/objectId';
import { decrementTagCounts } from './conversationTag';
@@ -290,12 +291,36 @@ export interface ConversationMethods {
conversationId: string,
messageId: string,
): Promise<IConversation | null>;
- replaceConvoCodeEnvironmentDecision(params: {
- user: string;
- conversationId: string;
- expected: Pick<IConversation, 'codeEnvironmentMode' | 'codeWorkspaces'>;
- codeWorkspaces: NonNullable<IConversation['codeWorkspaces']>;
- }): Promise<IConversation | null>;
+ getConvoCodeEnvironmentDecision(
+ user: string,
+ conversationId: string,
+ ): Promise<Pick<
+ IConversation,
+ 'conversationId' | 'codeEnvironmentMode' | 'codeWorkspaces' | 'codeEnvironmentRevision'
+ > | null>;
+ readAdmittedConvoCodeEnvironmentDecision(
+ user: string,
+ conversationId: string,
+ ): Promise<Pick<
+ IConversation,
+ 'conversationId' | 'codeEnvironmentMode' | 'codeWorkspaces'
+ > | null>;
+ replaceConvoCodeEnvironmentDecision(
+ params: {
+ user: string;
+ conversationId: string;
+ expected: Pick<
+ IConversation,
+ 'codeEnvironmentMode' | 'codeWorkspaces' | 'codeEnvironmentRevision'
+ >;
+ } & (
+ | {
+ codeEnvironmentMode: 'attached';
+ codeWorkspaces: NonNullable<IConversation['codeWorkspaces']>;
+ }
+ | { codeEnvironmentMode: 'without_attached'; codeWorkspaces?: undefined }
+ ),
+ ): Promise<IConversation | null>;
bulkSaveConvos(conversations: Array<Record<string, unknown>>): Promise<unknown>;
getConvosByCursor(
user: string,
@@ -2214,6 +2239,7 @@ export function createConversationMethods(
}),
...(convo.codeWorkspaces != null && { codeWorkspaces: convo.codeWorkspaces }),
};
+ delete update.codeEnvironmentRevision;
delete update.codeEnvironmentMode;
delete update.codeWorkspaces;
stripActorCheckpointFields(update);
@@ -2224,6 +2250,7 @@ export function createConversationMethods(
}
const unsetFields: Record<string, number> = { ...(metadata?.unsetFields ?? {}) };
delete unsetFields.initial_agent_id;
+ delete unsetFields.codeEnvironmentRevision;
delete unsetFields.codeEnvironmentMode;
delete unsetFields.codeWorkspaces;
stripActorCheckpointFields(unsetFields);
@@ -2636,23 +2663,60 @@ export function createConversationMethods(
}
}
+ /** Internal snapshot for a transition. The revision is never exposed in ordinary chat reads. */
+ async function getConvoCodeEnvironmentDecision(user: string, conversationId: string) {
+ const Conversation = mongoose.models.Conversation as Model<IConversation>;
+ return Conversation.findOne({ user, conversationId })
+ .select('conversationId codeEnvironmentMode codeWorkspaces +codeEnvironmentRevision')
+ .lean<IConversation>();
+ }
+
/**
- * Compare-and-swap for an owner's explicit move of an attached code-environment decision.
+ * Call only AFTER publishing the generation's active job. Atomically advance the fence and
+ * return the post-update decision in one round trip. A run that wins invalidates an in-flight
+ * transition's revision; a transition that wins is observed by this read.
+ */
+ async function readAdmittedConvoCodeEnvironmentDecision(user: string, conversationId: string) {
+ const Conversation = mongoose.models.Conversation as Model<IConversation>;
+ return withoutMeiliIndexing(
+ Conversation.findOneAndUpdate(
+ { user, conversationId },
+ { $inc: { codeEnvironmentRevision: 1 } },
+ { new: true, timestamps: false },
+ ),
+ )
+ .select('conversationId codeEnvironmentMode codeWorkspaces')
+ .lean<IConversation>();
+ }
+
+ /**
+ * Compare-and-swap for an owner's explicit replacement of a code-environment decision, whether
+ * that attaches an environment, moves to another, or leaves attached execution behind.
* The filter repeats the stored decision being replaced, so a writer that changed it first
* leaves this update unmatched rather than overwritten. A missing and a null mode both
- * describe a legacy decision inferred from its selections.
+ * describe a legacy decision inferred from its selections. Leaving attached execution clears
+ * the selections outright: a decision that kept them would read as attached again.
*/
async function replaceConvoCodeEnvironmentDecision({
user,
conversationId,
expected,
+ codeEnvironmentMode,
codeWorkspaces,
}: {
user: string;
conversationId: string;
- expected: Pick<IConversation, 'codeEnvironmentMode' | 'codeWorkspaces'>;
- codeWorkspaces: NonNullable<IConversation['codeWorkspaces']>;
- }) {
+ expected: Pick<
+ IConversation,
+ 'codeEnvironmentMode' | 'codeWorkspaces' | 'codeEnvironmentRevision'
+ >;
+ } & (
+ | {
+ codeEnvironmentMode: 'attached';
+ codeWorkspaces: NonNullable<IConversation['codeWorkspaces']>;
+ }
+ | { codeEnvironmentMode: 'without_attached'; codeWorkspaces?: undefined }
+ )) {
try {
const Conversation = mongoose.models.Conversation as Model<IConversation>;
return await Conversation.findOneAndUpdate(
@@ -2661,8 +2725,15 @@ export function createConversationMethods(
user,
codeEnvironmentMode: expected.codeEnvironmentMode ?? { $in: [null] },
codeWorkspaces: expected.codeWorkspaces ?? { $in: [null] },
+ codeEnvironmentRevision: expected.codeEnvironmentRevision ?? { $in: [null] },
},
- { $set: { codeEnvironmentMode: 'attached', codeWorkspaces } },
+ codeEnvironmentMode === 'attached'
+ ? { $set: { codeEnvironmentMode, codeWorkspaces }, $inc: { codeEnvironmentRevision: 1 } }
+ : {
+ $set: { codeEnvironmentMode },
+ $unset: { codeWorkspaces: 1 },
+ $inc: { codeEnvironmentRevision: 1 },
+ },
{ new: true, timestamps: false },
).lean<IConversation>();
} catch (error) {
@@ -2743,6 +2814,7 @@ export function createConversationMethods(
const bulkOps = conversations.map((convo) => {
const { codeEnvironmentMode, codeWorkspaces, ...sanitized } = convo;
delete sanitized.initial_agent_id;
+ delete sanitized.codeEnvironmentRevision;
stripActorCheckpointFields(sanitized);
if (typeof sanitized.user === 'string' && typeof sanitized.chatProjectId === 'string') {
if (ownedProjects.has(`${sanitized.user}:${sanitized.chatProjectId}`)) {
@@ -3509,6 +3581,8 @@ export function createConversationMethods(
saveConvo,
setConvoPinned,
appendConvoMessageReference,
+ getConvoCodeEnvironmentDecision,
+ readAdmittedConvoCodeEnvironmentDecision,
replaceConvoCodeEnvironmentDecision,
bulkSaveConvos,
getConvosByCursor,
diff --git a/packages/data-schemas/src/models/plugins/mongoMeili.findOneAndUpdate.spec.ts b/packages/data-schemas/src/models/plugins/mongoMeili.findOneAndUpdate.spec.ts
index 4b314d79cc..dbe0039efc 100644
--- a/packages/data-schemas/src/models/plugins/mongoMeili.findOneAndUpdate.spec.ts
+++ b/packages/data-schemas/src/models/plugins/mongoMeili.findOneAndUpdate.spec.ts
@@ -117,6 +117,43 @@ describe('mongoMeili findOneAndUpdate with includeResultMetadata (saveConvo path
}
};
+ test('skips indexing for an internal admission fence without disabling later content updates', async () => {
+ const { withoutMeiliIndexing } = await import('./mongoMeili');
+ const conversationId = new mongoose.Types.ObjectId().toString();
+ const user = new mongoose.Types.ObjectId().toString();
+ await conversationModel.create({
+ conversationId,
+ user,
+ title: 'Original Title',
+ endpoint: EModelEndpoint.openAI,
+ });
+ await waitForIndexAcknowledgment(conversationId);
+ const before = await conversationModel.collection.findOne({ conversationId });
+ mockAddDocuments.mockClear();
+ mockUpdateDocuments.mockClear();
+ const result = await withoutMeiliIndexing(
+ conversationModel.findOneAndUpdate(
+ { conversationId, user },
+ { $inc: { codeEnvironmentRevision: 1 } },
+ { new: true, timestamps: false },
+ ),
+ )
+ .select('conversationId codeWorkspaces')
+ .lean();
+ expect(result).toHaveProperty('conversationId', conversationId);
+ expect(result).not.toHaveProperty('codeEnvironmentRevision');
+ const after = await conversationModel.collection.findOne({ conversationId });
+ expect(after?.codeEnvironmentRevision).toBe(1);
+ expect(after?.updatedAt).toEqual(before?.updatedAt);
+ expect(after?._meiliIndexVersion).toEqual(before?._meiliIndexVersion);
+ expect(after?._meiliIndex).toBe(true);
+ expect(mockAddDocuments).not.toHaveBeenCalled();
+ expect(mockUpdateDocuments).not.toHaveBeenCalled();
+ await updateTitle(conversationId, user, 'New title');
+ await waitForMock(mockAddDocuments);
+ expect(mockAddDocuments).toHaveBeenCalledTimes(1);
+ });
+
test('re-indexes the updated title when the raw result wrapper is returned', async () => {
const conversationId = new mongoose.Types.ObjectId().toString();
const user = new mongoose.Types.ObjectId().toString();
diff --git a/packages/data-schemas/src/models/plugins/mongoMeili.ts b/packages/data-schemas/src/models/plugins/mongoMeili.ts
index 2adfda4444..20e4498a73 100644
--- a/packages/data-schemas/src/models/plugins/mongoMeili.ts
+++ b/packages/data-schemas/src/models/plugins/mongoMeili.ts
@@ -15,6 +15,14 @@ import type { IConversation, IMessage } from '~/types';
import { buildRetentionVisibilityFilter, legacyPermanentExpirationFilter } from '~/utils/retention';
import logger from '~/config/meiliLogger';
+/** Internal per-query bypass for writes to non-searchable bookkeeping fields. A WeakSet keeps
+ * this marker out of driver options and stored data. Other model middleware still runs. */
+const queriesWithoutMeiliIndexing = new WeakSet<object>();
+export function withoutMeiliIndexing<T extends object>(query: T): T {
+ queriesWithoutMeiliIndexing.add(query);
+ return query;
+}
+
interface MongoMeiliOptions {
host: string;
apiKey: string;
@@ -1146,6 +1154,10 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):
});
schema.pre('findOneAndUpdate', function (next) {
+ if (queriesWithoutMeiliIndexing.has(this)) {
+ next();
+ return;
+ }
const query = this as Query<unknown, unknown>;
if (meiliEnabled) {
const version = new mongoose.Types.ObjectId().toString();
diff --git a/packages/data-schemas/src/schema/convo.ts b/packages/data-schemas/src/schema/convo.ts
index db0946e7ae..2488964a68 100644
--- a/packages/data-schemas/src/schema/convo.ts
+++ b/packages/data-schemas/src/schema/convo.ts
@@ -41,6 +41,7 @@ const convoSchema: Schema<IConversation> = new Schema(
default: false,
},
...conversationPreset,
+ codeEnvironmentRevision: { type: Number, select: false },
agent_id: {
type: String,
},
diff --git a/packages/data-schemas/src/types/convo.ts b/packages/data-schemas/src/types/convo.ts
index 61cfc1bca8..62d9a9a718 100644
--- a/packages/data-schemas/src/types/convo.ts
+++ b/packages/data-schemas/src/types/convo.ts
@@ -282,6 +282,8 @@ export interface IConversation extends Document {
imageDetail?: string;
agent_id?: string;
codeApprovalMode?: CodeApprovalMode;
+ /** Private fence advanced when an admitted generation reads its decision. */
+ codeEnvironmentRevision?: number;
codeEnvironmentMode?: CodeEnvironmentMode;
codeWorkspaces?: CodeWorkspaceSelection[];
/** Immutable primary persisted-agent attribution for Insights. */