From 02492bdb6c579f3fa64516a837567d31cf8a0f69 Mon Sep 17 00:00:00 2001 From: "lia-by-librechat[bot]" <328778573+lia-by-librechat[bot]@users.noreply.github.com> Date: Thu, 24 Sep 2026 06:03:23 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=8F=9A=EF=B8=8F=20feat:=20Recover=20Codin?= =?UTF-8?q?g=20Chats=20With=20Missing=20Workspaces=20(#16273)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🏚️ feat: Recover Coding Chats With Missing Workspaces * fix: Revalidate Workspace Recovery and Preserve V1 Usage --------- Co-authored-by: Lia --- api/server/routes/__tests__/config.spec.js | 3 + api/server/routes/config.js | 6 +- .../Chat/Input/CodeWorkspaceMenu.tsx | 12 +- .../__tests__/CodeWorkspaceMenu.spec.tsx | 188 ++++++++++++++++++ .../__tests__/moveCodeEnvironment.test.tsx | 93 +++++---- .../__tests__/useCodeWorkspace.test.tsx | 116 ++++++++++- client/src/hooks/Agents/useCodeWorkspace.ts | 20 +- client/src/locales/en/translation.json | 10 +- packages/api/src/code/bridge.spec.ts | 91 +++++++++ packages/api/src/code/bridge.ts | 10 + packages/api/src/code/config.spec.ts | 8 + packages/api/src/code/config.ts | 14 ++ packages/api/src/code/decision.spec.ts | 20 +- packages/api/src/code/decision.ts | 23 +-- packages/api/src/code/http.spec.ts | 130 +++++++++++- packages/api/src/code/http.ts | 19 +- packages/data-provider/src/code/workspace.ts | 2 + packages/data-provider/src/config.ts | 12 +- 18 files changed, 680 insertions(+), 97 deletions(-) diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.js index 59f58772a5..78a09b7a7a 100644 --- a/api/server/routes/__tests__/config.spec.js +++ b/api/server/routes/__tests__/config.spec.js @@ -361,6 +361,7 @@ describe('GET /api/config', () => { const response = await request(app).get('/api/config'); expect(response.body.codeEnvironmentMoveVersion).toBeUndefined(); + expect(response.body.codeWorkspaceRecoveryVersion).toBeUndefined(); }); it('advertises enabled conversation moves regardless of decision activation', async () => { @@ -381,7 +382,9 @@ describe('GET /api/config', () => { const response = await request(app).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); + expect(response.body.codeWorkspaceRecoveryVersion).toBe(1); }); it('advertises code environment decisions only after deployment-wide activation', async () => { diff --git a/api/server/routes/config.js b/api/server/routes/config.js index b5ebdb9d61..fd7359d285 100644 --- a/api/server/routes/config.js +++ b/api/server/routes/config.js @@ -13,7 +13,7 @@ const { isFileSnapshotEnabled, getEndpointsDropParamsMap, resolveCodeEnvironmentDecisionVersion, - resolveCodeEnvironmentMoveVersion, + resolveCodeEnvironmentMoveCapabilities, } = require('@librechat/api'); const { EModelEndpoint, defaultSocialLogins } = require('librechat-data-provider'); const { logger, getTenantId, SystemCapabilities } = require('@librechat/data-schemas'); @@ -254,7 +254,7 @@ router.get('/', async function (req, res) { const codeEnvironmentDecisionVersion = resolveCodeEnvironmentDecisionVersion( process.env.CODE_ENVIRONMENT_DECISION_VERSION, ); - const codeEnvironmentMoveVersion = resolveCodeEnvironmentMoveVersion(appConfig); + const codeEnvironmentMoveCapabilities = resolveCodeEnvironmentMoveCapabilities(appConfig); const endpointsDropParamsMap = getEndpointsDropParamsMap(appConfig?.endpoints); @@ -316,7 +316,7 @@ router.get('/', async function (req, res) { insightsEnabled: isEnabled(process.env.ENABLE_INSIGHTS), compactionEnabled: appConfig?.summarization?.enabled !== false, ...(codeEnvironmentDecisionVersion != null ? { codeEnvironmentDecisionVersion } : {}), - ...(codeEnvironmentMoveVersion != null ? { codeEnvironmentMoveVersion } : {}), + ...codeEnvironmentMoveCapabilities, ...(cloudFront ? { cloudFront } : {}), ...(rum ? { rum } : {}), fileUploadSseEnabled: isEnabled(process.env.FILE_UPLOAD_SSE_ENABLED), diff --git a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx index be03a3da89..dbbcdf9188 100644 --- a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx +++ b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx @@ -51,6 +51,12 @@ function describeRelocation( relocation: CodeWorkspaceRelocation, localize: ReturnType, ): { label: string; info: string } { + if (relocation.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 .map(({ environment }) => environment.name ?? environment.id) .join(', '); @@ -263,7 +269,7 @@ export default function CodeWorkspaceMenu({ }) ?? []; const moveReady = relocation != null && chosenTargets.length === relocation.targets.length; const confirmMove = () => { - if (relocation == null || !moveReady) return; + if (relocation == null || !moveReady || disabled || moveMutation.isLoading) return; moveMutation.mutate( { conversationId: relocation.conversationId, @@ -337,7 +343,7 @@ export default function CodeWorkspaceMenu({ {relocation != null && relocationText != null ? ( <> } className={headingClasses}> - {localize('com_ui_code_workspace_move')} + {relocationText.label}

{relocationText.info}

{relocation.targets.map((target) => ( @@ -358,7 +364,7 @@ export default function CodeWorkspaceMenu({ ))} { jest.restoreAllMocks(); }); + test('recovers in the same chat only after confirmation, preserving healthy environments', async () => { + const missing = { ...moved, workspaceId: 'deleted-project' }; + const kept = { environmentId: 'team-vm', workspaceId: 'shared' }; + const replacement = { ...moved, workspaceId: 'project-b' }; + const moveSpy = jest.spyOn(dataService, 'moveConversationCodeEnvironment').mockResolvedValue({ + conversationId: 'existing', + codeEnvironmentMode: 'attached', + codeWorkspaces: [replacement, kept], + }); + const setConversation = jest.fn(); + const rememberSelection = jest.fn(); + const base = relocatable( + [ + { + ...target(environment, [ + { id: 'project-a', name: 'Project A' }, + { id: 'project-b', name: 'Project B' }, + ]), + state: 'missing', + }, + ], + rememberSelection, + ); + renderMenu( + , + ); + + expect(screen.getByTestId('code-workspace-move')).toHaveAccessibleName( + 'com_ui_code_workspace_recover. com_ui_code_workspace_recover_info', + ); + await userEvent.click(screen.getByTestId('code-workspace-move')); + const confirm = await screen.findByRole('menuitem', { + name: 'com_ui_code_workspace_recover', + }); + expect(confirm).toHaveAttribute('aria-disabled', 'true'); + await userEvent.click(screen.getByRole('menuitemradio', { name: /Project B/ })); + expect(moveSpy).not.toHaveBeenCalled(); + expect(setConversation).not.toHaveBeenCalled(); + expect(rememberSelection).not.toHaveBeenCalled(); + await userEvent.keyboard('{Escape}'); + expect(moveSpy).not.toHaveBeenCalled(); + await userEvent.click(screen.getByTestId('code-workspace-move')); + await userEvent.click( + await screen.findByRole('menuitem', { name: 'com_ui_code_workspace_recover' }), + ); + + await waitFor(() => expect(setConversation).toHaveBeenCalledTimes(1)); + expect(moveSpy).toHaveBeenCalledWith({ + conversationId: 'existing', + from: [missing, kept], + to: [kept, replacement], + }); + expect(rememberSelection).toHaveBeenCalledWith(replacement); + const current = { ...sealed, codeWorkspaces: [missing, kept] }; + expect(setConversation.mock.calls[0][0](current)).toEqual({ + ...current, + codeEnvironmentMode: 'attached', + codeWorkspaces: [replacement, kept], + }); + }); + + test('keeps a failed recovery retryable without changing the chat or preferences', async () => { + const missing = { ...moved, workspaceId: 'deleted-project' }; + const moveSpy = jest + .spyOn(dataService, 'moveConversationCodeEnvironment') + .mockRejectedValueOnce(new Error('offline')) + .mockResolvedValueOnce({ + conversationId: 'existing', + codeEnvironmentMode: 'attached', + codeWorkspaces: [moved], + }); + const setConversation = jest.fn(); + const rememberSelection = jest.fn(); + const base = relocatable( + [{ ...target(environment, [{ id: 'project-a' }]), state: 'missing' }], + rememberSelection, + ); + renderMenu( + , + ); + await userEvent.click(screen.getByTestId('code-workspace-move')); + await userEvent.click( + await screen.findByRole('menuitem', { name: 'com_ui_code_workspace_recover' }), + ); + await waitFor(() => + expect(mockShowToast).toHaveBeenCalledWith({ + message: 'com_ui_code_workspace_move_error', + status: 'error', + }), + ); + expect(setConversation).not.toHaveBeenCalled(); + expect(rememberSelection).not.toHaveBeenCalled(); + + await userEvent.click(screen.getByTestId('code-workspace-move')); + await userEvent.click( + await screen.findByRole('menuitem', { name: 'com_ui_code_workspace_recover' }), + ); + await waitFor(() => expect(setConversation).toHaveBeenCalledTimes(1)); + expect(moveSpy).toHaveBeenCalledTimes(2); + expect(rememberSelection).toHaveBeenCalledTimes(1); + }); + + test('disables recovery while its request is pending and applies only the acknowledged result', async () => { + const missing = { ...moved, workspaceId: 'deleted-project' }; + let finish: (() => void) | undefined; + jest.spyOn(dataService, 'moveConversationCodeEnvironment').mockImplementation( + () => + new Promise((resolve) => { + finish = () => + resolve({ + conversationId: 'existing', + codeEnvironmentMode: 'attached', + codeWorkspaces: [moved], + }); + }), + ); + const setConversation = jest.fn(); + const base = relocatable([ + { ...target(environment, [{ id: 'project-a' }]), state: 'missing' }, + ]); + renderMenu( + , + ); + await userEvent.click(screen.getByTestId('code-workspace-move')); + await userEvent.click( + await screen.findByRole('menuitem', { name: 'com_ui_code_workspace_recover' }), + ); + await waitFor(() => expect(screen.getByTestId('code-workspace-move')).toBeDisabled()); + expect(setConversation).not.toHaveBeenCalled(); + finish?.(); + await waitFor(() => expect(setConversation).toHaveBeenCalledTimes(1)); + expect(screen.getByTestId('code-workspace-move')).not.toBeDisabled(); + }); + + test('prevents confirmation if a generation starts while the recovery menu is open', async () => { + const moveSpy = jest.spyOn(dataService, 'moveConversationCodeEnvironment'); + const base = relocatable([ + { ...target(environment, [{ id: 'project-a' }]), state: 'missing' }, + ]); + const state = { + ...base, + relocation: { + ...base.relocation!, + from: [{ ...moved, workspaceId: 'deleted-project' }], + previous: [], + }, + }; + const { rerenderMenu } = renderMenu( + , + ); + await userEvent.click(screen.getByTestId('code-workspace-move')); + rerenderMenu( + , + ); + const confirm = await screen.findByRole('menuitem', { + name: 'com_ui_code_workspace_recover', + }); + expect(confirm).toHaveAttribute('aria-disabled', 'true'); + await userEvent.setup({ pointerEventsCheck: 0 }).click(confirm); + expect(moveSpy).not.toHaveBeenCalled(); + }); + test('moves the chat onto the sole workspace its agent now uses', async () => { const moveSpy = jest.spyOn(dataService, 'moveConversationCodeEnvironment').mockResolvedValue({ conversationId: 'existing', diff --git a/client/src/data-provider/__tests__/moveCodeEnvironment.test.tsx b/client/src/data-provider/__tests__/moveCodeEnvironment.test.tsx index 2fbc1eb17d..f56b71a518 100644 --- a/client/src/data-provider/__tests__/moveCodeEnvironment.test.tsx +++ b/client/src/data-provider/__tests__/moveCodeEnvironment.test.tsx @@ -18,50 +18,57 @@ const mac = { environmentId: 'mac', workspaceId: 'primary' }; const vm = { environmentId: 'vm', workspaceId: 'projects' }; describe('useMoveConversationCodeEnvironmentMutation', () => { - it('keeps the moved decision when a conversation read from before the move resolves later', async () => { - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, - }); - const stored = { - conversationId: 'convo-1', - codeEnvironmentMode: 'attached', - codeWorkspaces: [mac], - } as TConversation; - queryClient.setQueryData([QueryKeys.conversation, 'convo-1'], stored); - jest.mocked(dataService.moveConversationCodeEnvironment).mockResolvedValue({ - conversationId: 'convo-1', - codeEnvironmentMode: 'attached', - codeWorkspaces: [vm], - }); - let resolveStaleRead: (conversation: TConversation) => void = () => undefined; - const wrapper = ({ children }: { children: ReactNode }) => - createElement(QueryClientProvider, { client: queryClient }, children); + it.each([vm, { ...mac, workspaceId: 'replacement' }])( + 'keeps the moved decision %j when a pre-move conversation read resolves later', + async (target) => { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, + }); + const stored = { + conversationId: 'convo-1', + codeEnvironmentMode: 'attached', + codeWorkspaces: [mac], + } as TConversation; + queryClient.setQueryData([QueryKeys.conversation, 'convo-1'], stored); + jest.mocked(dataService.moveConversationCodeEnvironment).mockResolvedValue({ + conversationId: 'convo-1', + codeEnvironmentMode: 'attached', + codeWorkspaces: [target], + }); + let resolveStaleRead: (conversation: TConversation) => void = () => undefined; + const wrapper = ({ children }: { children: ReactNode }) => + createElement(QueryClientProvider, { client: queryClient }, children); - const { result } = renderHook( - () => ({ - conversation: useQuery( - [QueryKeys.conversation, 'convo-1'], - () => - new Promise((resolve) => { - resolveStaleRead = resolve; - }), - { staleTime: 0 }, - ), - move: useMoveConversationCodeEnvironmentMutation(), - }), - { wrapper }, - ); - await waitFor(() => expect(result.current.conversation.isFetching).toBe(true)); + const { result } = renderHook( + () => ({ + conversation: useQuery( + [QueryKeys.conversation, 'convo-1'], + () => + new Promise((resolve) => { + resolveStaleRead = resolve; + }), + { staleTime: 0 }, + ), + move: useMoveConversationCodeEnvironmentMutation(), + }), + { wrapper }, + ); + await waitFor(() => expect(result.current.conversation.isFetching).toBe(true)); - await act(async () => { - await result.current.move.mutateAsync({ conversationId: 'convo-1', from: [mac], to: [vm] }); - }); - await act(async () => { - resolveStaleRead(stored); - }); + await act(async () => { + await result.current.move.mutateAsync({ + conversationId: 'convo-1', + from: [mac], + to: [target], + }); + }); + await act(async () => { + resolveStaleRead(stored); + }); - expect(queryClient.getQueryData([QueryKeys.conversation, 'convo-1'])).toEqual( - expect.objectContaining({ codeEnvironmentMode: 'attached', codeWorkspaces: [vm] }), - ); - }); + expect(queryClient.getQueryData([QueryKeys.conversation, 'convo-1'])).toEqual( + expect.objectContaining({ codeEnvironmentMode: 'attached', codeWorkspaces: [target] }), + ); + }, + ); }); diff --git a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx index b7ce0bf74a..bc63cbfdcf 100644 --- a/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx +++ b/client/src/hooks/Agents/__tests__/useCodeWorkspace.test.tsx @@ -627,7 +627,7 @@ describe('useCodeWorkspace', () => { expect(result.current.relocation).toBeUndefined(); }); - it('does not offer a move when the sealed machine lost its workspace', () => { + it('does not offer recovery to an API that only supports environment moves', () => { const removed = { environmentId: 'personal-vm', workspaceId: 'removed-project' }; const { result } = renderHook(() => useCodeWorkspace(sealed([removed]))); @@ -636,6 +636,120 @@ describe('useCodeWorkspace', () => { expect(result.current.relocation).toBeUndefined(); }); + describe('missing workspace recovery', () => { + const missing = { environmentId: 'personal-vm', workspaceId: 'deleted-project' }; + const replacement = { environmentId: 'personal-vm', workspaceId: 'project-a' }; + + beforeEach(() => { + mockStartupConfig.mockReturnValue({ + codeEnvironmentMoveVersion: 1, + codeWorkspaceRecoveryVersion: 1, + }); + }); + + it.each(['attached', undefined] as const)( + 'offers explicit recovery without silently selecting a replacement for mode %s', + (codeEnvironmentMode) => { + const { result, rerender } = renderHook( + ({ codeWorkspaces }) => + useCodeWorkspace({ ...sealed(codeWorkspaces), codeEnvironmentMode }), + { initialProps: { codeWorkspaces: [missing] } }, + ); + + expect(result.current.state).toBe('relocatable'); + expect(result.current.canSubmit).toBe(false); + expect(result.current.selections).toBeUndefined(); + expect(result.current.resolveSubmission([missing], 'attached')).toBeUndefined(); + expect(result.current.relocation).toEqual({ + conversationId: 'existing', + from: [missing], + previous: [], + retained: [], + targets: [expect.objectContaining({ state: 'missing', selected: undefined })], + }); + + rerender({ codeWorkspaces: [replacement] }); + expect(result.current.state).toBe('ready'); + expect(result.current.locked).toBe(true); + expect(result.current.canSubmit).toBe(true); + expect(result.current.relocation).toBeUndefined(); + }, + ); + + it.each([ + { codeEnvironmentMoveVersion: 1 }, + { codeEnvironmentMoveVersion: 1, codeWorkspaceRecoveryVersion: 2 }, + { codeWorkspaceRecoveryVersion: 1 }, + { codeEnvironmentMoveVersion: 2, codeWorkspaceRecoveryVersion: 1 }, + ])('never offers recovery without both supported capabilities: %j', (config) => { + mockStartupConfig.mockReturnValue(config); + const { result } = renderHook(() => useCodeWorkspace(sealed([missing]))); + expect(result.current.state).toBe('missing'); + expect(result.current.relocation).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'); + }); + + 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.canSubmit).toBe(false); + }); + + it.each(['ready', 'loading', 'unavailable', 'unsupported', 'choose', 'missing'] as const)( + 'handles a second environment in state %s without dropping its sealed selection', + (state) => { + mockAgentPermissions().agent.subagents = { enabled: true, agent_ids: ['child'] }; + 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://team.example.com', + }); + const kept = { environmentId: 'team-vm', workspaceId: 'shared' }; + mockStatus().push({ + data: { + environmentId: 'team-vm', + status: state === 'unavailable' ? 'unavailable' : 'ready', + workspaces: + state === 'unsupported' + ? undefined + : [{ id: state === 'missing' ? 'replacement' : 'shared' }], + }, + isLoading: state === 'loading', + isError: false, + }); + const from = state === 'choose' ? [missing] : [missing, kept]; + const { result } = renderHook(() => useCodeWorkspace(sealed(from))); + + expect(result.current.canSubmit).toBe(false); + if (['loading', 'unavailable', 'unsupported'].includes(state)) { + expect(result.current.relocation).toBeUndefined(); + return; + } + expect(result.current.relocation?.from).toEqual(from); + expect(result.current.relocation?.retained).toEqual(state === 'ready' ? [kept] : []); + expect( + result.current.relocation?.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', () => { const { result } = renderHook(() => useCodeWorkspace({ diff --git a/client/src/hooks/Agents/useCodeWorkspace.ts b/client/src/hooks/Agents/useCodeWorkspace.ts index a104c5f44a..07a4d1f4ae 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_WORKSPACE_RECOVERY_VERSION, PermissionTypes, Permissions, } from 'librechat-data-provider'; @@ -48,9 +49,8 @@ export interface CodeWorkspaceEnvironmentResult { } /** - * A saved chat whose attached decision no longer covers every environment its agents use, most - * often because an agent was pointed at a different machine after the chat was created. The - * decision stays sealed against implicit changes; only its owner's explicit move replaces it. + * 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. */ export interface CodeWorkspaceRelocation { conversationId: string; @@ -60,9 +60,9 @@ export interface CodeWorkspaceRelocation { previous: Array< Pick & Partial> >; - /** Sealed selections the agents still use; a move carries them over unchanged. */ + /** Registered sealed selections the agents still use; a move carries them over unchanged. */ retained: CodeWorkspaceSelection[]; - /** Environments the agents now use that the decision does not cover. */ + /** Environments needing a new selection, including those whose workspace disappeared. */ targets: CodeWorkspaceEnvironmentResult[]; } @@ -135,6 +135,9 @@ export default function useCodeWorkspace( startupConfig?.codeEnvironmentDecisionVersion === CODE_ENVIRONMENT_DECISION_VERSION; const supportsEnvironmentMoves = startupConfig?.codeEnvironmentMoveVersion === CODE_ENVIRONMENT_MOVE_VERSION; + const supportsWorkspaceRecovery = + supportsEnvironmentMoves && + startupConfig?.codeWorkspaceRecoveryVersion === CODE_WORKSPACE_RECOVERY_VERSION; const preferences = useWorkspacePreferences(conversation?.agent_id); const { agentsConfig, endpointsConfig } = useGetAgentsConfig(); const canRunCode = useHasAccess({ @@ -374,7 +377,8 @@ export default function useCodeWorkspace( if ( supportsEnvironmentMoves && locked && - state === 'choose' && + (state === 'choose' || (supportsWorkspaceRecovery && state === 'missing')) && + environmentResults.every(({ state }) => ['ready', 'choose', 'missing'].includes(state)) && inferredMode === 'attached' && conversation?.conversationId != null && storedSelections != null && @@ -393,7 +397,9 @@ export default function useCodeWorkspace( retained: environmentResults.flatMap((result) => result.state === 'ready' && result.selected != null ? [result.selected] : [], ), - targets: environmentResults.filter((result) => result.state === 'choose'), + targets: environmentResults.filter( + (result) => result.state === 'choose' || result.state === 'missing', + ), }; state = 'relocatable'; } diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index db1d8a3aed..9df188df8a 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -28,14 +28,16 @@ "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_locked_recovery": "Reconnect or restore this workspace, or start a new chat.", + "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", "com_ui_code_workspace_move_to": "Move chat to {{0}}", "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 changed in another window. Reload and try again.", - "com_ui_code_workspace_move_busy": "Wait for the current response to finish, then move this chat.", - "com_ui_code_workspace_move_error": "Couldn't move this chat. Try again.", + "com_ui_code_workspace_move_stale": "This chat's workspace selection is no longer current. Reload 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_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", "com_ui_code_approval_ask_description": "Ask before editing files or running commands", @@ -442,7 +444,7 @@ "com_error_ban": "Your account is temporarily banned for violating the terms of service.", "com_error_code_workspace_invalid": "The workspace selection is invalid; select an available workspace.", "com_error_code_workspace_locked": "This chat already uses a different code environment. Continue with its original environment or start a new chat.", - "com_error_code_workspace_missing": "The selected workspace is no longer registered. Restore it on the attached machine or start a new chat.", + "com_error_code_workspace_missing": "The selected workspace is no longer registered. Restore it on the attached machine, choose a replacement if recovery is available, or start a new chat.", "com_error_code_workspace_required": "Choose an attached workspace before sending.", "com_error_code_workspace_unavailable": "The selected code workspace is unavailable. Reconnect its machine or choose an available workspace, then try again.", "com_error_code_workspace_unsupported": "The worker does not support workspace selection.", diff --git a/packages/api/src/code/bridge.spec.ts b/packages/api/src/code/bridge.spec.ts index 778129d1e4..faf724de7f 100644 --- a/packages/api/src/code/bridge.spec.ts +++ b/packages/api/src/code/bridge.spec.ts @@ -319,6 +319,97 @@ describe('getCodeBridgeWorkerStatus', () => { expect(fetchImpl).toHaveBeenCalledTimes(1); }); + test('bypasses cached status without falling back on failure or changing normal polling', async () => { + jest.spyOn(Date, 'now').mockReturnValue(1_000); + const offline = () => + new Response( + JSON.stringify({ + protocolVersion: 1, + workerId: 'personal-vm', + online: false, + ready: false, + }), + ); + const fetchImpl = jest + .fn() + .mockImplementationOnce(async () => offline()) + .mockRejectedValueOnce(new Error('offline')) + .mockImplementation(async () => offline()); + const poll = createCodeBridgeStatusPoller({ fetchImpl, maxConcurrent: 1 }); + const params = { + baseURL: 'https://code.example.com/v1', + token: 'administrator-token', + workerId: 'personal-vm', + }; + await expect(poll(params)).resolves.toEqual({ status: 'offline' }); + await expect(poll({ ...params, bypassCache: true })).rejects.toEqual( + expect.objectContaining({ reason: 'failed' }), + ); + await expect(poll({ ...params, bypassCache: true })).resolves.toEqual({ status: 'offline' }); + expect(fetchImpl).toHaveBeenCalledTimes(3); + await expect(poll(params)).resolves.toEqual({ status: 'offline' }); + expect(fetchImpl).toHaveBeenCalledTimes(3); + }); + + test('never joins an older in-flight poll and shares its upstream concurrency limit', async () => { + const responses: Array<(response: Response) => void> = []; + const fetchImpl = jest.fn(() => new Promise((resolve) => responses.push(resolve))); + const poll = createCodeBridgeStatusPoller({ fetchImpl, maxConcurrent: 2 }); + const params = { + baseURL: 'https://code.example.com/v1', + token: 'administrator-token', + workerId: 'personal-vm', + }; + const previous = poll(params); + const current = poll({ ...params, bypassCache: true }); + expect(current).not.toBe(previous); + expect(poll(params)).toBe(previous); + expect(fetchImpl).toHaveBeenCalledTimes(2); + await expect(poll({ ...params, bypassCache: true })).rejects.toEqual( + expect.objectContaining({ reason: 'busy' }), + ); + await expect(poll({ ...params, workerId: 'second-vm' })).rejects.toEqual( + expect.objectContaining({ reason: 'busy' }), + ); + responses[1]( + new Response( + JSON.stringify({ + protocolVersion: 1, + workerId: 'personal-vm', + online: true, + ready: true, + leaseExpiresInMs: 50_000, + capabilities: { sandboxProfile: 'native-srt', runtimes: ['bash'] }, + }), + ), + ); + await expect(current).resolves.toEqual(expect.objectContaining({ status: 'ready' })); + responses[0]( + new Response( + JSON.stringify({ + protocolVersion: 1, + workerId: 'personal-vm', + online: false, + ready: false, + }), + ), + ); + await expect(previous).resolves.toEqual({ status: 'offline' }); + const next = poll({ ...params, bypassCache: true }); + expect(fetchImpl).toHaveBeenCalledTimes(3); + responses[2]( + new Response( + JSON.stringify({ + protocolVersion: 1, + workerId: 'personal-vm', + online: false, + ready: false, + }), + ), + ); + await next; + }); + test('does not coalesce status requests across credential rotations', async () => { const fetchImpl = jest.fn().mockImplementation((_input, init) => Promise.resolve( diff --git a/packages/api/src/code/bridge.ts b/packages/api/src/code/bridge.ts index 99b732335e..c3cb7af0e5 100644 --- a/packages/api/src/code/bridge.ts +++ b/packages/api/src/code/bridge.ts @@ -91,6 +91,8 @@ export function createCodeBridgeStatusPoller({ baseURL: string; token: string; workerId: string; + /** Force a new upstream request, bypassing cached results and older in-flight polls. */ + bypassCache?: boolean; }) => Promise { const requests = new Map< string, @@ -98,6 +100,14 @@ export function createCodeBridgeStatusPoller({ >(); let active = 0; return (params) => { + if (params.bypassCache) { + if (active >= maxConcurrent) return Promise.reject(new CodeBridgeStatusError('busy')); + active += 1; + // Mutation validation needs its own observation, but still shares the polling capacity. + return getCodeBridgeWorkerStatus({ ...params, fetchImpl }).finally(() => { + active -= 1; + }); + } const credentialId = createHash('sha256').update(params.token).digest('base64url'); const normalizedBaseURL = params.baseURL.trim().replace(/\/+$/, ''); const key = `${normalizedBaseURL}\u0000${params.workerId}\u0000${credentialId}`; diff --git a/packages/api/src/code/config.spec.ts b/packages/api/src/code/config.spec.ts index 7c556669e3..4b0749f3eb 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, + resolveCodeEnvironmentMoveCapabilities, } from './config'; describe('resolveCodeEnvironmentDecisionVersion', () => { @@ -32,18 +33,25 @@ describe('resolveCodeEnvironmentMoveVersion', () => { it('advertises moves only where the effective policy enables them', () => { expect(resolveCodeEnvironmentMoveVersion(withMoves({ enabled: true }))).toBe(1); + expect(resolveCodeEnvironmentMoveCapabilities(withMoves({ enabled: true }))).toEqual({ + codeEnvironmentMoveVersion: 1, + codeWorkspaceRecoveryVersion: 1, + }); }); it.each([undefined, {}, { enabled: false }])( 'keeps sealed decisions immovable by default: %j', (conversationMoves) => { expect(resolveCodeEnvironmentMoveVersion(withMoves(conversationMoves))).toBeUndefined(); + expect(resolveCodeEnvironmentMoveCapabilities(withMoves(conversationMoves))).toEqual({}); }, ); it('keeps moves off without any stateful code configuration', () => { expect(resolveCodeEnvironmentMoveVersion({} as AppConfig)).toBeUndefined(); expect(resolveCodeEnvironmentMoveVersion(undefined)).toBeUndefined(); + expect(resolveCodeEnvironmentMoveCapabilities({} as AppConfig)).toEqual({}); + expect(resolveCodeEnvironmentMoveCapabilities(undefined)).toEqual({}); }); }); diff --git a/packages/api/src/code/config.ts b/packages/api/src/code/config.ts index 7904fe756d..3996fea913 100644 --- a/packages/api/src/code/config.ts +++ b/packages/api/src/code/config.ts @@ -2,8 +2,10 @@ import { logger } from '@librechat/data-schemas'; import { CODE_ENVIRONMENT_DECISION_VERSION, CODE_ENVIRONMENT_MOVE_VERSION, + CODE_WORKSPACE_RECOVERY_VERSION, EModelEndpoint, } from 'librechat-data-provider'; +import type { TStartupConfig } from 'librechat-data-provider'; import type { AppConfig } from '@librechat/data-schemas'; import type { AccessibleCodeEnvironmentConfiguration, @@ -44,6 +46,18 @@ export function resolveCodeEnvironmentMoveVersion( : undefined; } +/** Advertises recovery separately so already-open V1 clients retain ordinary environment moves. */ +export function resolveCodeEnvironmentMoveCapabilities( + appConfig?: Pick | null, +): Pick { + const codeEnvironmentMoveVersion = resolveCodeEnvironmentMoveVersion(appConfig); + if (codeEnvironmentMoveVersion == null) return {}; + return { + codeEnvironmentMoveVersion, + codeWorkspaceRecoveryVersion: CODE_WORKSPACE_RECOVERY_VERSION, + }; +} + /** Enables the implicit managed route only after the versioned rollout is complete. */ export function isImplicitStatefulCodeRouteAvailable( configuredVersion?: string, diff --git a/packages/api/src/code/decision.spec.ts b/packages/api/src/code/decision.spec.ts index 42d29df8f8..01d1798e93 100644 --- a/packages/api/src/code/decision.spec.ts +++ b/packages/api/src/code/decision.spec.ts @@ -190,21 +190,15 @@ describe('resolveConversationCodeEnvironmentMove', () => { ).toEqual({ codeWorkspaces: [vm] }); }); - it('never switches the workspace of an environment the decision already covers', () => { - expect(() => + it('accepts an explicit workspace replacement for the caller to verify against live status', () => { + const replacement = { environmentId: 'mac', workspaceId: 'canary' }; + expect( resolveConversationCodeEnvironmentMove({ - conversation: sealedOn(mac), - from: [mac], - to: [{ environmentId: 'mac', workspaceId: 'canary' }], + conversation: sealedOn(mac, vm), + from: [mac, vm], + to: [replacement, vm], }), - ).toThrow(locked); - expect(() => - resolveConversationCodeEnvironmentMove({ - conversation: sealedOn(mac), - from: [mac], - to: [{ environmentId: 'mac', workspaceId: 'canary' }, vm], - }), - ).toThrow(locked); + ).toEqual({ codeWorkspaces: [replacement, vm] }); }); it('drops an environment the agents stopped using without adding one', () => { diff --git a/packages/api/src/code/decision.ts b/packages/api/src/code/decision.ts index 8c3880b496..ff1346c9e0 100644 --- a/packages/api/src/code/decision.ts +++ b/packages/api/src/code/decision.ts @@ -124,11 +124,10 @@ export interface ConversationCodeEnvironmentMove { } /** - * Validates an owner's explicit move of a sealed attached decision onto the environments its - * agents now use. A move may drop environments the agents stopped using and add ones they now use, - * but never changes the workspace of an environment the decision already covers and never upgrades - * a conversation that continues without an attached environment. `from` must repeat the persisted selections, so a client acting - * on a stale view of the conversation cannot replace a decision it has not seen. + * 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. */ export function resolveConversationCodeEnvironmentMove({ conversation, @@ -149,19 +148,7 @@ export function resolveConversationCodeEnvironmentMove({ if (!isCodeWorkspaceSelections(to) || to.length === 0) { throw new CodeWorkspaceSelectionError('invalid'); } - const sealed = new Map( - persisted.codeWorkspaces.map(({ environmentId, workspaceId }) => [environmentId, workspaceId]), - ); - let adds = false; - for (const selection of to) { - const sealedWorkspaceId = sealed.get(selection.environmentId); - if (sealedWorkspaceId == null) { - adds = true; - } else if (sealedWorkspaceId !== selection.workspaceId) { - throw new CodeWorkspaceSelectionError('locked'); - } - } - if (!adds && to.length === sealed.size) { + if (sameSelections(to, persisted.codeWorkspaces)) { throw new CodeWorkspaceSelectionError('locked'); } return { codeWorkspaces: canonicalSelections(to) }; diff --git a/packages/api/src/code/http.spec.ts b/packages/api/src/code/http.spec.ts index 268cbca842..9bc6872003 100644 --- a/packages/api/src/code/http.spec.ts +++ b/packages/api/src/code/http.spec.ts @@ -1640,8 +1640,20 @@ describe('moving a sealed conversation code-environment decision', () => { ); return res; }; + const status = async () => { + const res = response(); + await handlers.status( + { + user: { id: userId, role: 'USER' }, + params: { environmentId: vm.environmentId }, + } as never, + res as never, + ); + return res; + }; return { move, + status, conversations, getConversation, listConversationRuns, @@ -1669,6 +1681,120 @@ describe('moving a sealed conversation code-environment decision', () => { ); }); + test.each(['attached', undefined] as const)( + 'recovers a missing workspace on the same machine with mode %s and keeps the new decision sealed', + async (codeEnvironmentMode) => { + const missing = { ...vm, workspaceId: 'deleted-project' }; + const { move, conversations, fetchImpl } = setup({ + stored: { + conversationId: 'conversation-1', + codeEnvironmentMode, + codeWorkspaces: [missing], + }, + }); + + const res = await move({ from: [missing], to: [vm] }); + + expect(res.statusCode).toBe(200); + expect(conversations.get('conversation-1')).toEqual({ + conversationId: 'conversation-1', + codeEnvironmentMode: 'attached', + codeWorkspaces: [vm], + }); + expect(fetchImpl).toHaveBeenCalledTimes(1); + expect((await move({ from: [missing], to: [vm] })).statusCode).toBe(409); + expect(fetchImpl).toHaveBeenCalledTimes(1); + }, + ); + + test.each([ + { + name: 'old workspace restored', + workspaces: ['deleted-project', 'project-a'], + ready: true, + reason: 'locked', + }, + { name: 'replacement removed', workspaces: ['unrelated'], ready: true, reason: 'missing' }, + { + name: 'worker unavailable', + workspaces: ['project-a'], + ready: false, + reason: 'worker_unavailable', + }, + { name: 'workspace still missing', workspaces: ['project-a'], ready: true, reason: undefined }, + ])( + 'revalidates recovery after a cached status poll: $name', + async ({ workspaces, ready, reason }) => { + jest.spyOn(Date, 'now').mockReturnValue(1_000); + const old = { ...vm, workspaceId: 'deleted-project' }; + const fetchImpl = jest + .fn() + .mockImplementationOnce(async () => workerStatusResponse()) + .mockImplementation(async () => + workerStatusResponse({ workspaces: workspaces.map((id) => ({ id })), ready }), + ); + const { move, status, conversations, replaceDecision } = setup({ + stored: { conversationId: 'conversation-1', codeWorkspaces: [old] }, + fetchImpl, + }); + expect((await status()).statusCode).toBe(200); + expect((await status()).statusCode).toBe(200); + expect(fetchImpl).toHaveBeenCalledTimes(1); + + const res = await move({ from: [old], to: [vm] }); + + expect(fetchImpl).toHaveBeenCalledTimes(2); + expect(res.statusCode).toBe(reason == null ? 200 : 409); + if (reason != null) { + expect(res.body).toEqual(expect.objectContaining({ reason })); + expect(replaceDecision).not.toHaveBeenCalled(); + } + expect(conversations.get('conversation-1')?.codeWorkspaces).toEqual( + reason == null ? [vm] : [old], + ); + }, + ); + + test('refuses replacement if the old workspace is still registered or was restored', async () => { + const old = { ...vm, workspaceId: 'old-project' }; + const { move, conversations, replaceDecision, fetchImpl } = setup({ + stored: { conversationId: 'conversation-1', codeWorkspaces: [old] }, + fetchImpl: jest.fn(async () => + workerStatusResponse({ workspaces: [{ id: old.workspaceId }, { id: vm.workspaceId }] }), + ), + }); + + const res = await move({ from: [old], to: [vm] }); + + expect(res.statusCode).toBe(409); + expect(res.body).toEqual(expect.objectContaining({ reason: 'locked' })); + expect(fetchImpl).toHaveBeenCalledTimes(1); + expect(replaceDecision).not.toHaveBeenCalled(); + expect(conversations.get('conversation-1')?.codeWorkspaces).toEqual([old]); + }); + + test.each([ + { ready: false, workspaces: [{ id: vm.workspaceId }], reason: 'worker_unavailable' }, + { ready: true, workspaces: [{ id: 'unrelated' }], reason: 'missing' }, + { ready: true, workspaces: [], reason: 'worker_unavailable' }, + ])( + 'leaves a missing decision untouched when recovery fails: $reason', + async ({ reason, ...status }) => { + const old = { ...vm, workspaceId: 'deleted-project' }; + const { move, conversations, replaceDecision } = setup({ + stored: { conversationId: 'conversation-1', codeWorkspaces: [old] }, + fetchImpl: jest.fn(async () => workerStatusResponse(status)), + }); + + const res = await move({ from: [old], to: [vm] }); + + expect(res.statusCode).toBe(409); + expect(res.body).toEqual(expect.objectContaining({ reason })); + expect(replaceDecision).not.toHaveBeenCalled(); + expect(conversations.get('conversation-1')?.codeWorkspaces).toEqual([old]); + }, + ); + test('moves a legacy decision that only stored its selections', async () => { const { move, conversations } = setup({ stored: { conversationId: 'conversation-1', codeWorkspaces: [mac] }, @@ -1805,9 +1931,9 @@ describe('moving a sealed conversation code-environment decision', () => { polls: 0, }, { - name: 'a workspace switch inside a sealed environment', + name: 'a replacement on an environment the caller cannot access', body: { from: [mac], to: [{ environmentId: 'mac', workspaceId: 'canary' }] }, - reason: 'locked', + reason: 'invalid', polls: 0, }, ])('rejects $name without polling any worker', async ({ body, reason, polls }) => { diff --git a/packages/api/src/code/http.ts b/packages/api/src/code/http.ts index ab6d229905..ec02903105 100644 --- a/packages/api/src/code/http.ts +++ b/packages/api/src/code/http.ts @@ -325,6 +325,7 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps) async function assertWorkspaceRegistered( policy: WorkerPolicy, selection: CodeWorkspaceSelection, + previousWorkspaceId?: string, ): Promise { const target = selectWorkerTarget(policy, selection.environmentId); if (target == null) { @@ -340,6 +341,7 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps) baseURL: target.controlPlane.baseURL, token, workerId: target.workerId, + bypassCache: true, }); } catch (error) { if (error instanceof CodeBridgeStatusError) { @@ -356,6 +358,13 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps) if (!current.workspaces.some(({ id }) => id === selection.workspaceId)) { throw new CodeWorkspaceSelectionError('missing'); } + if ( + previousWorkspaceId != null && + previousWorkspaceId !== selection.workspaceId && + current.workspaces.some(({ id }) => id === previousWorkspaceId) + ) { + throw new CodeWorkspaceSelectionError('locked'); + } } /** @@ -421,7 +430,15 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps) } try { await Promise.all( - move.codeWorkspaces.map((selection) => assertWorkspaceRegistered(policy, selection)), + move.codeWorkspaces.map((selection) => + assertWorkspaceRegistered( + policy, + selection, + conversation.codeWorkspaces?.find( + ({ environmentId }) => environmentId === selection.environmentId, + )?.workspaceId, + ), + ), ); } catch (error) { if (error instanceof CodeWorkspaceSelectionError) { diff --git a/packages/data-provider/src/code/workspace.ts b/packages/data-provider/src/code/workspace.ts index b431232d96..52beb3c6f6 100644 --- a/packages/data-provider/src/code/workspace.ts +++ b/packages/data-provider/src/code/workspace.ts @@ -5,6 +5,8 @@ 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; +/** 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 = [ 'read_file', 'search_text', diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts index 521863b2d4..691b48ac1e 100644 --- a/packages/data-provider/src/config.ts +++ b/packages/data-provider/src/config.ts @@ -30,7 +30,11 @@ import { MAX_SUBAGENTS_CEILING, DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS, } from './limits'; -import { CODE_ENVIRONMENT_DECISION_VERSION, CODE_ENVIRONMENT_MOVE_VERSION } from './code/workspace'; +import { + CODE_ENVIRONMENT_DECISION_VERSION, + CODE_ENVIRONMENT_MOVE_VERSION, + CODE_WORKSPACE_RECOVERY_VERSION, +} from './code/workspace'; import { ComponentTypes, SettingTypes, OptionTypes } from './generate'; import { STATEFUL_CODE_ENVIRONMENTS } from './stateful-code'; import { specsConfigSchema, TSpecsConfig } from './models'; @@ -1374,7 +1378,8 @@ export const agentsEndpointSchema = baseEndpointSchema }) .optional(), /** Server-only policy letting a conversation's owner move its sealed attached decision - * onto the environments its agents now use. Omit to keep sealed decisions immovable. */ + * onto the environments its agents now use, or recover a missing workspace. Omit to keep + * sealed decisions immovable. */ conversationMoves: z .object({ enabled: z.boolean().optional(), @@ -2390,6 +2395,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; + /** 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; interface?: TInterfaceConfig; turnstile?: TTurnstileConfig; balance?: TBalanceConfig;