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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🛰️ feat: Show BYOM Worker Readiness (#15618)
Danny Avila3d085b227d65
diff --git a/api/server/routes/code-environments.js b/api/server/routes/code-environments.jsindex 7e3bea328c..3c17c4bced 100644--- a/api/server/routes/code-environments.js+++ b/api/server/routes/code-environments.js@@ -34,6 +34,7 @@ router.post('/pairings', codeEnvironmentPairingLimiter, (req, res, next) =>router.post('/', requireCodeEnvironmentManage, (req, res, next) =>getHandlers().register(req, res, next),);+router.get('/:environmentId/status', (req, res, next) => getHandlers().status(req, res, next));router.patch('/:environmentId/settings', (req, res, next) =>getHandlers().updateSettings(req, res, next),);diff --git a/api/server/routes/code-environments.test.js b/api/server/routes/code-environments.test.jsindex 16e02f7de0..c1e504dd17 100644--- a/api/server/routes/code-environments.test.js+++ b/api/server/routes/code-environments.test.js@@ -21,6 +21,9 @@ const mockHandlers = {list: jest.fn((_req, res) => res.status(200).json({ environments: [] })),register: jest.fn((_req, res) => res.status(201).json({ environment: { id: 'code-1' } })),pair: jest.fn((_req, res) => res.status(201).json({ environment: { id: 'code-1' } })),+ status: jest.fn((_req, res) =>+ res.status(200).json({ environmentId: 'code-1', status: 'ready' }),+ ),updateSettings: jest.fn((_req, res) => res.status(200).json({ environment: { id: 'code-1' } })),remove: jest.fn((_req, res) => res.status(200).json({ environment: { id: 'code-1' } })),};@@ -104,6 +107,16 @@ describe('code environment routes', () => {expect(mockHandlers.remove).toHaveBeenCalledTimes(1);});+ it('allows an authenticated principal to read environment status', async () => {+ await request(createApp()).get('/api/code-environments/code-1/status').expect(200, {+ environmentId: 'code-1',+ status: 'ready',+ });++ expect(middlewareCalls).toEqual(['jwt']);+ expect(mockHandlers.status).toHaveBeenCalledTimes(1);+ });+it('allows an authenticated owner to update exposed environment settings', async () => {await request(createApp()).patch('/api/code-environments/code-1/settings')diff --git a/client/src/components/Nav/Settings/CodeEnvironments.tsx b/client/src/components/Nav/Settings/CodeEnvironments.tsxindex fcc3feb9a9..79cad08317 100644--- a/client/src/components/Nav/Settings/CodeEnvironments.tsx+++ b/client/src/components/Nav/Settings/CodeEnvironments.tsx@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';import { createCodeWorkerSetupCommand, isCodeWorkerShell } from 'librechat-data-provider';import {Button,+ Chip,Input,Label,OGDialog,@@ -23,12 +24,41 @@ import type {import type { CodeEnvironmentPairingResponse } from '~/data-provider/CodeEnvironments';import {useCodeEnvironmentsQuery,+ useCodeEnvironmentStatusQuery,useDeleteCodeEnvironmentMutation,usePairCodeEnvironmentMutation,useUpdateCodeEnvironmentSettingsMutation,} from '~/data-provider';import { useLocalize } from '~/hooks';+const statusPresentation = {+ offline: { label: 'com_ui_code_environment_status_offline', tone: 'error' },+ starting: { label: 'com_ui_code_environment_status_starting', tone: 'warning' },+ ready: { label: 'com_ui_code_environment_status_ready', tone: 'success' },+} as const;++function EnvironmentStatus({ environmentId }: { environmentId: string }) {+ const localize = useLocalize();+ const query = useCodeEnvironmentStatusQuery(environmentId);+ if (query.isLoading) {+ return <Chip tone="neutral">{localize('com_ui_code_environment_status_checking')}</Chip>;+ }+ if (query.isError || query.data == null) {+ return <Chip tone="warning">{localize('com_ui_code_environment_status_unavailable')}</Chip>;+ }+ const presentation = statusPresentation[query.data.status];+ return (+ <div className="flex min-w-0 flex-col items-end gap-1">+ <Chip tone={presentation.tone}>{localize(presentation.label)}</Chip>+ {query.data.sandboxProfile != null && (+ <span className="max-w-48 truncate text-xs text-text-tertiary">+ {[query.data.sandboxProfile, ...(query.data.runtimes ?? [])].join(' · ')}+ </span>+ )}+ </div>+ );+}+function WorkerCommand({ pairing }: { pairing: CodeEnvironmentPairingResponse['pairing'] }) {const { showToast } = useToastContext();const localize = useLocalize();@@ -289,42 +319,45 @@ export default function CodeEnvironments() {<p className="truncate text-sm font-medium text-text-primary">{environment.name}</p><p className="truncate text-xs text-text-secondary">{environment.id}</p></div>- {environment.canDelete && (- <OGDialog>- <OGDialogTrigger asChild>- <Button type="button" variant="outline" size="sm">- {localize('com_ui_delete')}- </Button>- </OGDialogTrigger>- <OGDialogTemplate- showCloseButton={false}- title={localize('com_ui_code_environment_remove_title')}- main={- <p className="text-sm text-text-secondary">- {localize('com_ui_code_environment_remove_description')}- </p>- }- selection={{- selectHandler: () =>- deleteMutation.mutate(environment.id, {- onSuccess: () =>- showToast({- message: localize('com_ui_code_environment_removed'),- status: 'success',- }),- onError: () =>- showToast({- message: localize('com_ui_code_environment_remove_error'),- status: 'error',- }),- }),- selectClasses:- 'bg-surface-destructive text-text-on-status transition-all duration-200 hover:bg-surface-destructive-hover',- selectText: localize('com_ui_delete'),- }}- />- </OGDialog>- )}+ <div className="flex shrink-0 items-center gap-2">+ <EnvironmentStatus environmentId={environment.id} />+ {environment.canDelete && (+ <OGDialog>+ <OGDialogTrigger asChild>+ <Button type="button" variant="outline" size="sm">+ {localize('com_ui_delete')}+ </Button>+ </OGDialogTrigger>+ <OGDialogTemplate+ showCloseButton={false}+ title={localize('com_ui_code_environment_remove_title')}+ main={+ <p className="text-sm text-text-secondary">+ {localize('com_ui_code_environment_remove_description')}+ </p>+ }+ selection={{+ selectHandler: () =>+ deleteMutation.mutate(environment.id, {+ onSuccess: () =>+ showToast({+ message: localize('com_ui_code_environment_removed'),+ status: 'success',+ }),+ onError: () =>+ showToast({+ message: localize('com_ui_code_environment_remove_error'),+ status: 'error',+ }),+ }),+ selectClasses:+ 'bg-surface-destructive text-text-on-status transition-all duration-200 hover:bg-surface-destructive-hover',+ selectText: localize('com_ui_delete'),+ }}+ />+ </OGDialog>+ )}+ </div></div><EnvironmentPermissions environment={environment} /></div>diff --git a/client/src/components/Nav/Settings/__tests__/CodeEnvironments.spec.tsx b/client/src/components/Nav/Settings/__tests__/CodeEnvironments.spec.tsxnew file mode 100644index 0000000000..3fff72fa08--- /dev/null+++ b/client/src/components/Nav/Settings/__tests__/CodeEnvironments.spec.tsx@@ -0,0 +1,90 @@+import { render, screen } from '@testing-library/react';+import CodeEnvironments from '../CodeEnvironments';++const mockMutate = jest.fn();+let mockStatusQuery: {+ isLoading: boolean;+ isError: boolean;+ data?: {+ environmentId: string;+ status: 'offline' | 'starting' | 'ready';+ sandboxProfile?: string;+ runtimes?: string[];+ };+};++jest.mock('@librechat/client', () => ({+ ...jest.requireActual('@librechat/client'),+ useToastContext: () => ({ showToast: jest.fn() }),+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++jest.mock('~/data-provider', () => ({+ useCodeEnvironmentsQuery: () => ({+ isLoading: false,+ isError: false,+ data: {+ controlPlanes: [],+ environments: [+ {+ resourceId: 'resource-1',+ id: 'personal-vm',+ name: 'Personal VM',+ type: 'attached',+ canDelete: false,+ },+ ],+ },+ }),+ useCodeEnvironmentStatusQuery: () => mockStatusQuery,+ usePairCodeEnvironmentMutation: () => ({ mutate: mockMutate, isLoading: false }),+ useDeleteCodeEnvironmentMutation: () => ({ mutate: mockMutate, isLoading: false }),+ useUpdateCodeEnvironmentSettingsMutation: () => ({ mutate: mockMutate, isLoading: false }),+}));++describe('CodeEnvironments status', () => {+ beforeEach(() => {+ mockStatusQuery = { isLoading: true, isError: false };+ });++ test('shows status discovery while the worker is being checked', () => {+ render(<CodeEnvironments />);++ expect(screen.getByText('com_ui_code_environment_status_checking')).toBeInTheDocument();+ });++ test('shows ready sandbox and runtime metadata', () => {+ mockStatusQuery = {+ isLoading: false,+ isError: false,+ data: {+ environmentId: 'personal-vm',+ status: 'ready',+ sandboxProfile: 'native-srt',+ runtimes: ['bash'],+ },+ };++ render(<CodeEnvironments />);++ expect(screen.getByText('com_ui_code_environment_status_ready')).toBeInTheDocument();+ expect(screen.getByText('native-srt · bash')).toBeInTheDocument();+ });++ test('distinguishes status transport failure from an offline worker', () => {+ mockStatusQuery = { isLoading: false, isError: true };+ const { rerender } = render(<CodeEnvironments />);+ expect(screen.getByText('com_ui_code_environment_status_unavailable')).toBeInTheDocument();++ mockStatusQuery = {+ isLoading: false,+ isError: false,+ data: { environmentId: 'personal-vm', status: 'offline' },+ };+ rerender(<CodeEnvironments />);+ expect(screen.getByText('com_ui_code_environment_status_offline')).toBeInTheDocument();+ });+});diff --git a/client/src/data-provider/CodeEnvironments.ts b/client/src/data-provider/CodeEnvironments.tsindex 21779496eb..957a28b971 100644--- a/client/src/data-provider/CodeEnvironments.ts+++ b/client/src/data-provider/CodeEnvironments.ts@@ -1,8 +1,9 @@import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';-import { MutationKeys, QueryKeys, dataService } from 'librechat-data-provider';+import { DynamicQueryKeys, MutationKeys, QueryKeys, dataService } from 'librechat-data-provider';import type {CodeEnvironmentUserSettings,TCodeEnvironmentPairingResponse,+ TCodeEnvironmentStatusResponse,TCodeEnvironmentsResponse,} from 'librechat-data-provider';@@ -16,6 +17,19 @@ export function useCodeEnvironmentsQuery(enabled = true) {);}+export function useCodeEnvironmentStatusQuery(id: string, enabled = true) {+ return useQuery<TCodeEnvironmentStatusResponse>(+ DynamicQueryKeys.codeEnvironmentStatus(id),+ () => dataService.getCodeEnvironmentStatus(id),+ {+ enabled: enabled && id.length > 0,+ refetchInterval: 10_000,+ refetchIntervalInBackground: false,+ retry: false,+ },+ );+}+export function usePairCodeEnvironmentMutation() {const queryClient = useQueryClient();return useMutation<diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 6323b2ed3f..da18254b50 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -2199,6 +2199,11 @@"com_ui_code_environment_shell_posix": "macOS / Linux / WSL2","com_ui_code_environment_shell_powershell": "Windows PowerShell","com_ui_code_environment_pairing_created": "Code environment created",+ "com_ui_code_environment_status_checking": "Checking",+ "com_ui_code_environment_status_offline": "Offline",+ "com_ui_code_environment_status_starting": "Starting",+ "com_ui_code_environment_status_ready": "Ready",+ "com_ui_code_environment_status_unavailable": "Status unavailable","com_ui_code_environment_pairing_error": "Could not create the code environment","com_ui_code_environment_remove_title": "Remove code environment?","com_ui_code_environment_remove_description": "This revokes the worker before removing it from LibreChat. Its sandbox files remain on your VM.",diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.jsindex a804535d2e..84c89658f3 100644--- a/e2e/setup/fake-model.js+++ b/e2e/setup/fake-model.js@@ -1657,8 +1657,8 @@ function statefulCodeResponses(operation, toolNames) {}const commands = {- write: `printf ${STATEFUL_CODE_VALUE} > /mnt/data/librechat-bridge-state.txt && cat /mnt/data/librechat-bridge-state.txt`,- read: 'cat /mnt/data/librechat-bridge-state.txt',+ write: `printf ${STATEFUL_CODE_VALUE} > librechat-bridge-state.txt && cat librechat-bridge-state.txt`,+ read: 'cat librechat-bridge-state.txt',};const command = commands[operation];if (!command) {diff --git a/e2e/specs/mock/stateful-code-bridge.spec.ts b/e2e/specs/mock/stateful-code-bridge.spec.tsindex 9144f98379..9704560928 100644--- a/e2e/specs/mock/stateful-code-bridge.spec.ts+++ b/e2e/specs/mock/stateful-code-bridge.spec.ts@@ -1,4 +1,5 @@import { expect, request as playwrightRequest, test } from '@playwright/test';+import type { Page } from '@playwright/test';import type { AgentDetail } from './agents.helpers';import cleanupUser from '../../setup/cleanupUser';import { cleanupAgent, openAgentBuilder, uniqueAgentName } from './agents.helpers';@@ -8,7 +9,7 @@ import {getAccessToken,messagesView,requestJson,- sendMessageAndWaitForCompletion,+ sendMessage,} from './helpers';const CODE_VALUE = 'librechat-bridge-persisted';@@ -36,6 +37,66 @@ interface RegisteredEnvironment {};}+interface EnvironmentStatus {+ environmentId: string;+ status: 'offline' | 'starting' | 'ready';+ leaseExpiresInMs?: number;+ sandboxProfile?: string;+ runtimes?: string[];+ operations?: string[];+}++interface PersistedMessage {+ messageId?: string;+ isCreatedByUser?: boolean;+ unfinished?: boolean;+ text?: string;+}++async function sendApprovedCommand(page: Page, prompt: string) {+ const token = await getAccessToken(page);+ const commandOutputs = messagesView(page).getByText(`stdout: ${CODE_VALUE}`, { exact: false });+ const existingOutputCount = await commandOutputs.count();+ const existingConversationId = new URL(page.url()).pathname.match(/^\/c\/([^/]+)$/)?.[1];+ const existingMessages = existingConversationId+ ? await requestJson<PersistedMessage[]>(page, {+ path: `/api/messages/${encodeURIComponent(existingConversationId)}`,+ token,+ })+ : [];+ const existingMessageIds = new Set(existingMessages.map(({ messageId }) => messageId));+ const response = await sendMessage(page, prompt);+ expect(response.ok()).toBe(true);+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });++ const approval = messagesView(page).getByTestId('tool-approval').last();+ await expect(approval).toBeVisible({ timeout: 30000 });+ await approval.getByRole('button', { name: 'Approve' }).click();+ const submit = approval.getByRole('button', { name: 'Submit' });+ await expect(submit).toBeEnabled();+ await submit.click();++ await expect(commandOutputs).toHaveCount(existingOutputCount + 1, { timeout: 30000 });+ const conversationId = new URL(page.url()).pathname.replace(/^\/c\//, '');+ await expect+ .poll(+ async () => {+ const messages = await requestJson<PersistedMessage[]>(page, {+ path: `/api/messages/${encodeURIComponent(conversationId)}`,+ token,+ });+ return messages.some(+ (message) =>+ !existingMessageIds.has(message.messageId) &&+ message.isCreatedByUser === false &&+ message.unfinished === false,+ );+ },+ { timeout: 30000, intervals: [250, 500, 1000] },+ )+ .toBe(true);+}+test.describe('attached stateful code environment', () => {test.skip(!process.env.E2E_CODE_BRIDGE_URL, 'E2E_CODE_BRIDGE_URL is required');@@ -172,7 +233,34 @@ test.describe('attached stateful code environment', () => {path: '/api/code-environments',token,});- expect(ownerList.environments).toContainEqual(registration.environment);+ expect(ownerList.environments).toContainEqual(+ expect.objectContaining(registration.environment),+ );++ let workerStatus: EnvironmentStatus | undefined;+ await expect+ .poll(+ async () => {+ workerStatus = await requestJson<EnvironmentStatus>(page, {+ path: `/api/code-environments/${registration.environment.id}/status`,+ token,+ });+ return workerStatus.status;+ },+ {+ message: 'BYOM worker should become ready before workspace commands run',+ timeout: 30_000,+ intervals: [250, 500, 1_000],+ },+ )+ .toBe('ready');+ expect(workerStatus).toMatchObject({+ environmentId: registration.environment.id,+ status: 'ready',+ leaseExpiresInMs: expect.any(Number),+ sandboxProfile: expect.any(String),+ runtimes: expect.any(Array),+ });await cleanupUser(stranger);const strangerApi = await playwrightRequest.newContext({@@ -202,7 +290,7 @@ test.describe('attached stateful code environment', () => {headers: { Authorization: `Bearer ${strangerToken}` },});expect(strangerList.ok()).toBe(true);- expect(await strangerList.json()).toEqual({ environments: [] });+ expect(await strangerList.json()).toMatchObject({ environments: [] });} finally {await strangerApi.dispose();await cleanupUser(stranger);@@ -232,15 +320,8 @@ test.describe('attached stateful code environment', () => {await expect(form.getByLabel('Agent name')).toHaveValue(name);await form.getByRole('button', { name: 'Select Agent' }).click();- await sendMessageAndWaitForCompletion(page, 'E2E_STATEFUL_CODE:write');- await expect(- messagesView(page).getByText(`E2E stateful code write observed ${CODE_VALUE}`),- ).toBeVisible({ timeout: 30000 });-- await sendMessageAndWaitForCompletion(page, 'E2E_STATEFUL_CODE:read');- await expect(- messagesView(page).getByText(`E2E stateful code read observed ${CODE_VALUE}`),- ).toBeVisible({ timeout: 30000 });+ await sendApprovedCommand(page, 'E2E_STATEFUL_CODE:write');+ await sendApprovedCommand(page, 'E2E_STATEFUL_CODE:read');} finally {await cleanupAgent(page, agentId);}diff --git a/packages/api/src/code/bridge.spec.ts b/packages/api/src/code/bridge.spec.tsnew file mode 100644index 0000000000..9365cc0324--- /dev/null+++ b/packages/api/src/code/bridge.spec.ts@@ -0,0 +1,78 @@+import { CodeBridgeStatusError, getCodeBridgeWorkerStatus } from './bridge';++describe('getCodeBridgeWorkerStatus', () => {+ test('normalizes a ready worker while exposing only bounded capability metadata', async () => {+ const fetchImpl = jest.fn().mockResolvedValue({+ ok: true,+ json: jest.fn().mockResolvedValue({+ protocolVersion: 1,+ workerId: 'personal-vm',+ online: true,+ ready: true,+ leaseExpiresInMs: 45_000,+ capabilities: {+ statefulWorkspace: true,+ sandboxProfile: 'native-srt',+ runtimes: ['bash'],+ workspaceTools: { operations: ['read_file', 'execute_command'] },+ identityId: 'must-not-cross-the-boundary',+ },+ binding: { tenantId: 'tenant-1', principal: { type: 'user', id: 'user-1' } },+ }),+ });++ await expect(+ getCodeBridgeWorkerStatus({+ baseURL: 'https://code.example.com/v1/',+ token: 'administrator-token',+ workerId: 'personal-vm',+ fetchImpl,+ }),+ ).resolves.toEqual({+ status: 'ready',+ leaseExpiresInMs: 45_000,+ sandboxProfile: 'native-srt',+ runtimes: ['bash'],+ operations: ['read_file', 'execute_command'],+ });+ expect(fetchImpl).toHaveBeenCalledWith(+ 'https://code.example.com/v1/bridge/workers/personal-vm/status',+ expect.objectContaining({+ headers: { Authorization: 'Bearer administrator-token' },+ redirect: 'error',+ }),+ );+ });++ test.each([+ { online: false, ready: true },+ { online: true, ready: false },+ { online: false, ready: false, leaseExpiresInMs: 5_000 },+ { online: true, ready: true, leaseExpiresInMs: 60_001 },+ {+ online: true,+ ready: true,+ capabilities: { sandboxProfile: 'native-srt', runtimes: Array(33).fill('bash') },+ },+ ])('rejects an invalid upstream status response: %p', async (invalid) => {+ const fetchImpl = jest.fn().mockResolvedValue({+ ok: true,+ json: jest.fn().mockResolvedValue({+ protocolVersion: 1,+ workerId: 'personal-vm',+ ...invalid,+ }),+ });++ await expect(+ getCodeBridgeWorkerStatus({+ baseURL: 'https://code.example.com/v1',+ token: 'administrator-token',+ workerId: 'personal-vm',+ fetchImpl,+ }),+ ).rejects.toEqual(+ expect.objectContaining<Partial<CodeBridgeStatusError>>({ reason: 'invalid' }),+ );+ });+});diff --git a/packages/api/src/code/bridge.ts b/packages/api/src/code/bridge.tsindex ff476cdee3..e5af0d97e1 100644--- a/packages/api/src/code/bridge.ts+++ b/packages/api/src/code/bridge.ts@@ -17,6 +17,14 @@ export type CodeBridgePairing = {expiresAt: string;};+export type CodeBridgeWorkerStatus = {+ status: 'offline' | 'starting' | 'ready';+ leaseExpiresInMs?: number;+ sandboxProfile?: string;+ runtimes?: string[];+ operations?: string[];+};+export type CodeBridgeFetch = (input: Parameters<typeof fetch>[0],init?: Parameters<typeof fetch>[1],@@ -42,6 +50,121 @@ export class CodeBridgeLifecycleError extends Error {}}+export class CodeBridgeStatusError extends Error {+ constructor(+ public readonly reason: 'rejected' | 'invalid' | 'timeout' | 'failed',+ public readonly upstreamStatus?: number,+ ) {+ super(`Code bridge status request ${reason}`);+ this.name = 'CodeBridgeStatusError';+ }+}++function validStatusString(value: unknown): value is string {+ return typeof value === 'string' && value.length > 0 && value.length <= 128;+}++function validStatusStringArray(value: unknown): value is string[] {+ return (+ Array.isArray(value) && value.length <= 32 && value.every((item) => validStatusString(item))+ );+}++export async function getCodeBridgeWorkerStatus({+ baseURL,+ token,+ workerId,+ fetchImpl = fetch,+}: {+ baseURL: string;+ token: string;+ workerId: string;+ fetchImpl?: CodeBridgeFetch;+}): Promise<CodeBridgeWorkerStatus> {+ try {+ const response = await fetchImpl(+ `${baseURL.trim().replace(/\/+$/, '')}/bridge/workers/${encodeURIComponent(workerId)}/status`,+ {+ headers: { Authorization: `Bearer ${token}` },+ redirect: 'error',+ signal: AbortSignal.timeout(CODE_BRIDGE_REQUEST_TIMEOUT_MS),+ },+ );+ if (!response.ok) {+ throw new CodeBridgeStatusError('rejected', response.status);+ }+ const payload = (await response.json()) as unknown;+ if (typeof payload !== 'object' || payload == null) {+ throw new CodeBridgeStatusError('invalid');+ }+ const status = payload as {+ protocolVersion?: unknown;+ workerId?: unknown;+ online?: unknown;+ ready?: unknown;+ leaseExpiresInMs?: unknown;+ capabilities?: {+ sandboxProfile?: unknown;+ runtimes?: unknown;+ workspaceTools?: { operations?: unknown };+ };+ };+ const capabilities = status.capabilities;+ const validLease =+ status.leaseExpiresInMs == null ||+ (typeof status.leaseExpiresInMs === 'number' &&+ Number.isSafeInteger(status.leaseExpiresInMs) &&+ status.leaseExpiresInMs > 0 &&+ status.leaseExpiresInMs <= 60_000);+ const validCapabilities =+ capabilities == null || validStatusString(capabilities.sandboxProfile);+ const validRuntimes = capabilities == null || validStatusStringArray(capabilities.runtimes);+ const validOperations =+ capabilities?.workspaceTools?.operations == null ||+ validStatusStringArray(capabilities.workspaceTools.operations);+ if (+ status.protocolVersion !== 1 ||+ status.workerId !== workerId ||+ typeof status.online !== 'boolean' ||+ typeof status.ready !== 'boolean' ||+ (status.ready && !status.online) ||+ (status.online && (status.leaseExpiresInMs == null || capabilities == null)) ||+ (!status.online && (status.leaseExpiresInMs != null || capabilities != null)) ||+ !validLease ||+ !validCapabilities ||+ !validRuntimes ||+ !validOperations+ ) {+ throw new CodeBridgeStatusError('invalid');+ }+ let workerStatus: CodeBridgeWorkerStatus['status'] = 'offline';+ if (status.online) {+ workerStatus = status.ready ? 'ready' : 'starting';+ }+ return {+ status: workerStatus,+ ...(typeof status.leaseExpiresInMs !== 'number'+ ? {}+ : { leaseExpiresInMs: status.leaseExpiresInMs }),+ ...(typeof capabilities?.sandboxProfile !== 'string'+ ? {}+ : { sandboxProfile: capabilities.sandboxProfile }),+ ...(validStatusStringArray(capabilities?.runtimes)+ ? { runtimes: capabilities.runtimes }+ : {}),+ ...(validStatusStringArray(capabilities?.workspaceTools?.operations)+ ? { operations: capabilities.workspaceTools.operations }+ : {}),+ };+ } catch (error) {+ if (error instanceof CodeBridgeStatusError) throw error;+ if (error instanceof Error && error.name === 'TimeoutError') {+ throw new CodeBridgeStatusError('timeout');+ }+ throw new CodeBridgeStatusError('failed');+ }+}+function validPairing(value: unknown, workerId: string): value is CodeBridgePairing {if (typeof value !== 'object' || value == null) return false;const pairing = value as Partial<CodeBridgePairing>;diff --git a/packages/api/src/code/http.spec.ts b/packages/api/src/code/http.spec.tsindex 9382a9ec18..b0a16caffe 100644--- a/packages/api/src/code/http.spec.ts+++ b/packages/api/src/code/http.spec.ts@@ -20,6 +20,103 @@ function response() {}describe('code environment HTTP handlers', () => {+ test('reports status only for an accessible worker through its current control plane', async () => {+ const fetchImpl = jest.fn().mockResolvedValue({+ ok: true,+ json: jest.fn().mockResolvedValue({+ protocolVersion: 1,+ workerId: 'personal-vm',+ online: true,+ ready: true,+ leaseExpiresInMs: 50_000,+ capabilities: { sandboxProfile: 'native-srt', runtimes: ['bash'] },+ }),+ });+ const controlPlane = {+ id: 'self-service',+ name: 'Self service',+ type: 'attached' as const,+ baseURL: 'https://code.example.com/v1',+ owner: 'deployment' as const,+ pairing: { allowPrincipalWorkers: true, tokenEnv: 'CODE_ADMIN_TOKEN' },+ };+ const handlers = createCodeEnvironmentHttpHandlers({+ getAppConfig: jest.fn().mockResolvedValue({+ endpoints: {+ [EModelEndpoint.agents]: { statefulCodeSessions: { environments: [controlPlane] } },+ },+ } as unknown as AppConfig),+ registry: {+ register: jest.fn(),+ listAccessible: jest.fn(),+ listAccessibleConfigurations: jest.fn().mockResolvedValue([+ {+ id: 'personal-vm',+ name: 'Personal VM',+ type: 'attached',+ baseURL: 'https://stale.example.com/v1',+ controlPlaneId: 'self-service',+ owner: 'principal',+ workerId: 'personal-vm',+ },+ ]),+ remove: jest.fn(),+ },+ readSecret: jest.fn(() => 'administrator-token'),+ fetchImpl,+ });+ const res = response();++ await handlers.status(+ {+ user: { id: '68b2f0c498f24c1e78fa0001', role: 'USER' },+ params: { environmentId: 'personal-vm' },+ } as never,+ res as never,+ );++ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual({+ environmentId: 'personal-vm',+ status: 'ready',+ leaseExpiresInMs: 50_000,+ sandboxProfile: 'native-srt',+ runtimes: ['bash'],+ });+ expect(fetchImpl).toHaveBeenCalledWith(+ 'https://code.example.com/v1/bridge/workers/personal-vm/status',+ expect.objectContaining({ headers: { Authorization: 'Bearer administrator-token' } }),+ );+ });++ test('does not query status for an inaccessible environment', async () => {+ const fetchImpl = jest.fn();+ const handlers = createCodeEnvironmentHttpHandlers({+ getAppConfig: jest.fn().mockResolvedValue({+ endpoints: { [EModelEndpoint.agents]: { statefulCodeSessions: { environments: [] } } },+ } as unknown as AppConfig),+ registry: {+ register: jest.fn(),+ listAccessible: jest.fn(),+ listAccessibleConfigurations: jest.fn().mockResolvedValue([]),+ remove: jest.fn(),+ },+ fetchImpl,+ });+ const res = response();++ await handlers.status(+ {+ user: { id: '68b2f0c498f24c1e78fa0001', role: 'USER' },+ params: { environmentId: 'another-users-vm' },+ } as never,+ res as never,+ );++ expect(res.statusCode).toBe(404);+ expect(fetchImpl).not.toHaveBeenCalled();+ });+test('does not advertise principal pairing when Code API principal auth is disabled', async () => {const listAccessible = jest.fn();const listAccessibleConfigurations = jest.fn();diff --git a/packages/api/src/code/http.ts b/packages/api/src/code/http.tsindex a278993197..3c99ed3364 100644--- a/packages/api/src/code/http.ts+++ b/packages/api/src/code/http.ts@@ -13,19 +13,21 @@ import type {import type { GetAppConfigOptions } from '~/app/service';import type { ServerRequest } from '~/types/http';import type { CodeBridgeFetch } from './bridge';-import {- CodeEnvironmentInUseError,- CodeEnvironmentLimitError,- CodeEnvironmentValidationError,- normalizeCodeEnvironmentName,-} from './environments';import {CodeBridgeLifecycleError,CodeBridgePairingError,+ CodeBridgeStatusError,createCodeBridgePairing,+ getCodeBridgeWorkerStatus,readCodeBridgeSecret,revokeCodeBridgeWorker,} from './bridge';+import {+ CodeEnvironmentInUseError,+ CodeEnvironmentLimitError,+ CodeEnvironmentValidationError,+ normalizeCodeEnvironmentName,+} from './environments';import {assertCodeApiJwtSigningReady,getCodeApiTenantId,@@ -184,6 +186,7 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps)list: (req: ServerRequest, res: Response) => Promise<Response>;register: (req: ServerRequest, res: Response) => Promise<Response>;pair: (req: ServerRequest, res: Response) => Promise<Response>;+ status: (req: ServerRequest, res: Response) => Promise<Response>;updateSettings: (req: ServerRequest, res: Response) => Promise<Response>;remove: (req: ServerRequest, res: Response) => Promise<Response>;} {@@ -619,6 +622,75 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps)});}+ async function status(req: ServerRequest, res: Response): Promise<Response> {+ const principal = actor(req);+ if (principal == null) {+ return res.status(401).json({ error: 'Authentication required' });+ }+ const environmentId = (+ req.params as { environmentId?: string } | undefined+ )?.environmentId?.trim();+ if (!environmentId) {+ return res.status(400).json({ error: 'Code environment id is required' });+ }++ let configuration: AccessibleCodeEnvironmentConfiguration | undefined;+ let controlPlane: ConfiguredCodeEnvironment | undefined;+ try {+ const principals = await deps.registry.resolvePrincipals?.(principal);+ const resolvedPrincipal = principals == null ? principal : { ...principal, principals };+ const [configurations, effectiveConfig, deploymentConfig] = await Promise.all([+ deps.registry.listAccessibleConfigurations?.(resolvedPrincipal) ?? Promise.resolve([]),+ deps.getAppConfig({+ ...getAppConfigOptionsFromUser(req.user),+ ...(principals == null ? {} : { resolvedPrincipals: principals }),+ failClosed: true,+ skipRuntimeAugmentation: true,+ }),+ deps.getAppConfig({ baseOnly: true }),+ ]);+ configuration = configurations.find(({ id }) => id === environmentId);+ const controlPlaneId = configuration?.controlPlaneId;+ const effectiveControlPlane =+ controlPlaneId == null+ ? undefined+ : configuredAttachedControlPlane(effectiveConfig, controlPlaneId);+ controlPlane =+ effectiveControlPlane == null || controlPlaneId == null+ ? undefined+ : configuredAttachedControlPlane(deploymentConfig, controlPlaneId);+ } catch (error) {+ logger.error('[codeEnvironments] status policy resolution failed:', error);+ return res.status(503).json({ error: 'Code environment policy is unavailable' });+ }+ if (configuration?.workerId == null || controlPlane == null) {+ return res.status(404).json({ error: 'Code environment was not found' });+ }+ const workerId = configuration.workerId;+ const tokenEnv = controlPlane.pairing?.tokenEnv;+ const token = tokenEnv == null ? undefined : readSecret(tokenEnv)?.trim();+ if (!token) {+ return res.status(503).json({ error: 'Code environment status is not configured' });+ }+ try {+ const workerStatus = await getCodeBridgeWorkerStatus({+ baseURL: controlPlane.baseURL,+ token,+ workerId,+ fetchImpl: deps.fetchImpl,+ });+ return res.status(200).json({ environmentId, ...workerStatus });+ } catch (error) {+ if (error instanceof CodeBridgeStatusError) {+ return res.status(error.reason === 'timeout' ? 504 : 502).json({+ error: 'Code environment status is unavailable',+ ...(error.upstreamStatus == null ? {} : { upstreamStatus: error.upstreamStatus }),+ });+ }+ throw error;+ }+ }+async function remove(req: ServerRequest, res: Response): Promise<Response> {const principal = actor(req);if (principal == null) {@@ -672,5 +744,5 @@ export function createCodeEnvironmentHttpHandlers(deps: CodeEnvironmentHttpDeps)}}- return { list, register, pair, updateSettings, remove };+ return { list, register, pair, status, updateSettings, remove };}diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.tsindex a329c4265a..77087f53bc 100644--- a/packages/data-provider/src/api-endpoints.ts+++ b/packages/data-provider/src/api-endpoints.ts@@ -54,6 +54,7 @@ export const codeEnvironmentPairings = () => `${codeEnvironments()}/pairings`;export const codeEnvironmentById = (id: string) =>`${codeEnvironments()}/${encodeURIComponent(id)}`;export const codeEnvironmentSettings = (id: string) => `${codeEnvironmentById(id)}/settings`;+export const codeEnvironmentStatus = (id: string) => `${codeEnvironmentById(id)}/status`;const messagesRoot = `${BASE_URL}/api/messages`;diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex 62e692cf10..933570aaf8 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -72,6 +72,10 @@ export function getCodeEnvironments(): Promise<t.TCodeEnvironmentsResponse> {return request.get(endpoints.codeEnvironments());}+export function getCodeEnvironmentStatus(id: string): Promise<t.TCodeEnvironmentStatusResponse> {+ return request.get(endpoints.codeEnvironmentStatus(id));+}+export function pairCodeEnvironment(payload: {name: string;controlPlaneId: string;diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex 3ceaf1e5c1..5cdfd3397c 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -102,6 +102,7 @@ export enum QueryKeys {// Dynamic query keys that require parametersexport const DynamicQueryKeys = {agentFiles: (agentId: string) => ['agentFiles', agentId] as const,+ codeEnvironmentStatus: (id: string) => [QueryKeys.codeEnvironments, id, 'status'] as const,} as const;export enum MutationKeys {diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.tsindex 6223f438f7..fa0c9fe33d 100644--- a/packages/data-provider/src/types.ts+++ b/packages/data-provider/src/types.ts@@ -569,6 +569,15 @@ export type TCodeEnvironmentPairingResponse = {};};+export type TCodeEnvironmentStatusResponse = {+ environmentId: string;+ status: 'offline' | 'starting' | 'ready';+ leaseExpiresInMs?: number;+ sandboxProfile?: string;+ runtimes?: string[];+ operations?: string[];+};+export type TConfig = {order: number;type?: EModelEndpoint;