The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(dashboard): add Filestore controls and lifecycle E2E (#2701)
Lhfcws04841765526e
diff --git a/apps/dashboard/README.md b/apps/dashboard/README.mdindex ef12c2080..ed175acd3 100644--- a/apps/dashboard/README.md+++ b/apps/dashboard/README.md@@ -131,6 +131,13 @@ Queries and dialogs stay scoped to the selected organization, so old results canAPI, SDK and CLI recovery remain separate. The mock preview supports capture, restoration and deletion.See [Checkpoint controls and recovery](#checkpoint-controls-and-recovery) for request states.+## Managed volumes++**Volumes → New Volume** selects Standard storage by default. Performance storage is offered only when the+API advertises `filestore_enabled`; unsupported deployments keep the option disabled. The API+assigns the underlying Filestore instance. Creation and Box failures retain the server reason plus non-sensitive+HTTP status, error code and Box ID when available.+## SSH access**Connect via SSH**, beside start/stop, opens a static local-terminal guide.diff --git a/apps/dashboard/src/api/apiClient.test.ts b/apps/dashboard/src/api/apiClient.test.tsindex 2364f952b..aca1224c3 100644--- a/apps/dashboard/src/api/apiClient.test.ts+++ b/apps/dashboard/src/api/apiClient.test.ts@@ -144,6 +144,24 @@ it('sends the dashboard activity source without inventing an SDK version', async}})+it('keeps usage and telemetry requests on the configured Analytics API', async () => {+ const requests: any[] = []+ const analyticsApiUrl = 'http://analytics.test/analytics'+ const api = await makeClient(vi.fn(), 200, {}, requests, {}, { ...config, analyticsApiUrl } as never)+ const from = '2026-11-01T00:00:00.000Z'+ const to = '2026-11-02T00:00:00.000Z'++ await api.analyticsUsageApi!.organizationOrganizationIdUsageAggregatedGet('org-1', from, to)+ await api.analyticsTelemetryApi!.organizationOrganizationIdBoxBoxIdTelemetryTracesGet('org-1', 'box-1', from, to)++ expect(requests).toHaveLength(2)+ expect(requests.map((request) => request.baseURL)).toEqual([analyticsApiUrl, analyticsApiUrl])+ expect(requests.map((request) => request.url)).toEqual([+ '/organization/org-1/usage/aggregated?from=2026-11-01T00%3A00%3A00.000Z&to=2026-11-02T00%3A00%3A00.000Z',+ '/organization/org-1/box/box-1/telemetry/traces?from=2026-11-01T00%3A00%3A00.000Z&to=2026-11-02T00%3A00%3A00.000Z',+ ])+}, 30_000)+// Each client starts with fresh reauthentication state and uses the real response interceptor.async function makeClient(onUnauthorized: () => Promise<void> | void,@@ -151,6 +169,7 @@ async function makeClient(body: unknown = {},requests: any[] = [],headers: Record<string, string> = {},+ clientConfig = config,) {vi.resetModules()const axios = (await import('axios')).default@@ -171,7 +190,7 @@ async function makeClient(throw new axios.AxiosError(`Request failed with status code ${status}`, undefined, cfg, undefined, response)}const { ApiClient } = await import('./apiClient')- return new ApiClient(config, 'tok', onUnauthorized)+ return new ApiClient(clientConfig, 'tok', onUnauthorized)}it('uses the renewed token for billing requests', async () => {@@ -187,6 +206,74 @@ it.each([204, 401, 403, 503])('preserves HTTP %i when eligibility has no decisioawait expect(api.billingApi.getPlanTrialEligibility('org')).rejects.toMatchObject({ cause: { response: { status } } })})+describe('ApiClient Box API errors', () => {+ it('uses the current access token for Box API requests', async () => {+ const requests: any[] = []+ const api = await makeClient(vi.fn(), 201, { box_id: 'box-1' }, requests)+ api.setAccessToken('renewed-token')+ const cloud = await import('../lib/cloudBox')++ await cloud.createBoxViaBoxApi(api, 'org-1', {})++ expect(requests[0].headers.Authorization).toBe('Bearer renewed-token')+ })++ it('preserves structured metadata and the specialized type for suspended organizations', async () => {+ const api = await makeClient(vi.fn(), 403, {+ message: 'Organization is suspended',+ statusCode: 403,+ code: 'ORGANIZATION_SUSPENDED',+ boxId: 'box-1',+ })+ const cloud = await import('../lib/cloudBox')+ const { OrganizationSuspendedError } = await import('./errors')++ const error = await cloud.createBoxViaBoxApi(api, 'org-1', {}).catch((failure) => failure)++ expect(error).toBeInstanceOf(OrganizationSuspendedError)+ expect(error).toMatchObject({+ message: 'Organization is suspended',+ statusCode: 403,+ code: 'ORGANIZATION_SUSPENDED',+ boxId: 'box-1',+ })+ })++ it('preserves the server reason, status, code and Box ID for create-box failures', async () => {+ const api = await makeClient(vi.fn(), 400, {+ message: 'runner has not declared filestore',+ statusCode: 400,+ code: 'BOX_STATE_TRANSITION_FAILED',+ boxId: 'box-1',+ })+ const cloud = await import('../lib/cloudBox')+ const { BoxliteError } = await import('./errors')++ const error = await cloud.createBoxViaBoxApi(api, 'org-1', {}).catch((failure) => failure)++ expect(error).toBeInstanceOf(BoxliteError)+ expect(error).toMatchObject({+ message: 'runner has not declared filestore',+ statusCode: 400,+ code: 'BOX_STATE_TRANSITION_FAILED',+ boxId: 'box-1',+ })+ })++ it('preserves a nested Box API message for SSH setup classification', async () => {+ const api = await makeClient(vi.fn(), 409, { error: { message: 'SSH configuration is required' } })+ const { BoxliteError } = await import('./errors')+ const { requestSsh } = await import('../lib/ssh')+ const { sshFailureReason } = await import('../lib/ssh-connection-ui')++ const error = await requestSsh(api, 'org-1', 'box-1', 'enable').catch((failure) => failure)++ expect(error).toBeInstanceOf(BoxliteError)+ expect(error).toMatchObject({ message: 'SSH configuration is required', statusCode: 409 })+ expect(sshFailureReason(error)).toBe('missing-config')+ })+})+describe('ApiClient registration deadline', () => {let api: import('./apiClient').ApiClientlet send: ReturnType<typeof vi.fn<import('axios').AxiosAdapter>>@@ -414,7 +501,7 @@ describe('ApiClient 401 -> bounded re-login recovery', () => {const error = await api.organizationsApi.listOrganizations().catch((caught: unknown) => caught)- expect(error).toMatchObject({ code, message: 'Account creation refused' })+ expect(error).toMatchObject({ code, message: 'Account creation refused', statusCode: status })expect(onUnauthorized).not.toHaveBeenCalled()expect(window.sessionStorage.getItem('boxlite.reauth-attempted')).toBeNull()})@@ -530,6 +617,17 @@ describe('ApiClient checkpoints', () => {})})+describe('ApiClient volume storage capabilities', () => {+ it('discovers volume backend capabilities using the authenticated REST client', async () => {+ const requests: any[] = []+ const capabilities = { object_storage_enabled: true, filestore_enabled: false }+ const api = await makeClient(vi.fn(), 200, { capabilities }, requests)++ await expect(api.getVolumeStorageCapabilities()).resolves.toEqual(capabilities)+ expect(requests[0]).toMatchObject({ method: 'get', url: '/v1/config' })+ })+})+describe('ApiClient.setBoxInboundMode', () => {it('sends the mode to the /v1 inbound route of the selected organization', async () => {vi.resetModules()@@ -614,7 +712,8 @@ describe('ApiClient terminal session', () => {const url = await api.terminalAttachUrl('org-1', 'box-1', 'exec-1')expect(requests[0].method).toBe('post')- expect(requests[0].url).toBe('http://api.test/api/box/box-1/attach-tickets')+ expect(requests[0].url).toBe('/box/box-1/attach-tickets')+ expect(requests[0].baseURL).toBe('http://api.test/api')expect(JSON.parse(requests[0].data ?? '')).toEqual({ executionId: 'exec-1' })expect(url).toBe('ws://api.test/api/v1/org-1/boxes/box-1/executions/exec-1/attach?ticket=tkt-1')expect(url).not.toContain('tok')diff --git a/apps/dashboard/src/api/apiClient.ts b/apps/dashboard/src/api/apiClient.tsindex 52752890f..83f9acdbe 100644--- a/apps/dashboard/src/api/apiClient.ts+++ b/apps/dashboard/src/api/apiClient.ts@@ -44,6 +44,11 @@ import type { DomainList, HeldDomain, CustomDomain, CustomDomainList } from './dimport type { Checkpoint, CheckpointPage } from './checkpoint-types'import { readTunnelDescriptor, tunnelOperationError, TunnelRequestError, type TunnelDescriptor } from './tunnel'+export interface VolumeStorageCapabilities {+ object_storage_enabled?: boolean+ filestore_enabled?: boolean+}+// A burst of in-flight requests can all 401 at once when the access token goes// invalid; this in-page guard ensures at most one re-login redirect per page// load. It is reset if onUnauthorized throws (a failed handler must not wedge@@ -280,6 +285,10 @@ export class ApiClient {return (await this.http.get('/v1/config', this.v1Config())).data.capabilities}+ public async getVolumeStorageCapabilities(): Promise<VolumeStorageCapabilities> {+ return (await this.http.get('/v1/config', this.v1Config())).data.capabilities+ }+public async listCheckpoints(org: string): Promise<Checkpoint[]> {const checkpoints: Checkpoint[] = []const seen = new Set<string>()@@ -394,7 +403,8 @@ export class ApiClient {accessToken: accessToken,})- const axiosInstance = axios.create({ headers: activityHeaders })+ const axiosInstance = axios.create({ baseURL: config.apiUrl, headers: activityHeaders })+ axiosInstance.defaults.headers.common.Authorization = `Bearer ${accessToken}`axiosInstance.interceptors.request.use((request) => {request.headers?.delete?.('User-Agent')if (request.headers) {@@ -425,19 +435,33 @@ export class ApiClient {if (error instanceof AxiosError && error.message.includes('timeout of')) {errorMessage = 'Operation timed out'} else {- errorMessage = error.response?.data?.message || error.response?.data || error.message || String(error)+ errorMessage =+ error.response?.data?.message ||+ error.response?.data?.error?.message ||+ error.response?.data ||+ error.message ||+ String(error)}// The envelope's machine-readable `code` is what the UI branches on; the// message is only for display. A rejection the API describes (say, an// unverified email) must not be flattened into an anonymous error here.const responseCode = error?.response?.data?.code+ const responseBoxId = error?.response?.data?.boxId+ const responseStatus = error?.response?.data?.statusCodeconst retryAfter = Number(error?.response?.headers?.['retry-after'])throw BoxliteError.fromString(String(errorMessage), {cause: error instanceof Error ? error : undefined,code: typeof responseCode === 'string' ? responseCode : undefined,retryAfterSeconds: Number.isSafeInteger(retryAfter) && retryAfter > 0 ? retryAfter : undefined,+ statusCode:+ typeof responseStatus === 'number'+ ? responseStatus+ : typeof error?.response?.status === 'number'+ ? error.response.status+ : undefined,+ boxId: typeof responseBoxId === 'string' && responseBoxId.length > 0 ? responseBoxId : undefined,})},)@@ -464,6 +488,7 @@ export class ApiClient {basePath: config.analyticsApiUrl,accessToken: accessToken,baseOptions: {+ baseURL: config.analyticsApiUrl,headers: {Authorization: `Bearer ${accessToken}`,},@@ -695,6 +720,7 @@ export class ApiClient {public setAccessToken(accessToken: string) {this.config.accessToken = accessTokenthis._billingApi.setAccessToken(accessToken)+ this.http.defaults.headers.common.Authorization = `Bearer ${accessToken}`}public get boxApi() {@@ -775,12 +801,6 @@ export class ApiClient {}public get axiosInstance() {- return axios.create({- baseURL: this.config.basePath,- headers: {- ...activityHeaders,- Authorization: `Bearer ${this.config.accessToken}`,- },- })+ return this.http}}diff --git a/apps/dashboard/src/api/errors.ts b/apps/dashboard/src/api/errors.tsindex be39ce058..7c45fa337 100644--- a/apps/dashboard/src/api/errors.ts+++ b/apps/dashboard/src/api/errors.ts@@ -4,36 +4,46 @@* SPDX-License-Identifier: AGPL-3.0*/+export type BoxliteErrorOptions = ErrorOptions & {+ code?: string+ retryAfterSeconds?: number+ statusCode?: number+ boxId?: string+}+export class BoxliteError extends Error {- public static fromError(error: Error, code?: string, retryAfterSeconds?: number): BoxliteError {+ public readonly code?: string+ public readonly retryAfterSeconds?: number+ public readonly statusCode?: number+ public readonly boxId?: string++ constructor(message: string, options: BoxliteErrorOptions = {}) {+ super(message, options)+ this.code = options.code+ this.retryAfterSeconds = options.retryAfterSeconds+ this.statusCode = options.statusCode+ this.boxId = options.boxId+ }++ public static fromError(error: Error, options: BoxliteErrorOptions = {}): BoxliteError {+ const { code, retryAfterSeconds } = optionsif (code === 'disposable_email' || code === 'email_required' || code === 'invalid_email') {- return new RegistrationEmailError(error.message, code, { cause: error.cause })+ return new RegistrationEmailError(error.message, code, { ...options, cause: error.cause })}if (code && registrationCodes.includes(code)) {- return new RegistrationError(error.message, code, retryAfterSeconds, { cause: error.cause })+ return new RegistrationError(error.message, code, retryAfterSeconds, { ...options, cause: error.cause })}if (String(error).includes('Organization is suspended')) {- return new OrganizationSuspendedError(error.message, {- cause: error.cause,- })+ return new OrganizationSuspendedError(error.message, { ...options, cause: error.cause })}- return new BoxliteError(error.message, {- cause: error.cause,- })+ return new BoxliteError(error.message, options)}- public static fromString(- error: string,- options?: { cause?: Error; code?: string; retryAfterSeconds?: number },- ): BoxliteError {- return BoxliteError.fromError(- new Error(error, { cause: options?.cause }),- options?.code,- options?.retryAfterSeconds,- )+ public static fromString(error: string, options: BoxliteErrorOptions = {}): BoxliteError {+ return BoxliteError.fromError(new Error(error, { cause: options.cause }), options)}}diff --git a/apps/dashboard/src/components/VolumeTable.tsx b/apps/dashboard/src/components/VolumeTable.tsxindex 2446303fa..01e0eb1b5 100644--- a/apps/dashboard/src/components/VolumeTable.tsx+++ b/apps/dashboard/src/components/VolumeTable.tsx@@ -179,6 +179,11 @@ export function VolumeTable({ data, loading, processingVolumeAction, onDelete, o<div className="space-y-2"><p>Create a volume, then mount it when creating a Box. Its data survives Box deletion.</p><p>+ Volumes are shared, persistent directories with Standard or Performance storage, perfect for+ reusing datasets, caching dependencies, or passing files across boxes.+ </p>+ <p>+ Create one via the SDK or CLI. <br /><ahref={BOXLITE_VOLUMES_DOCS_URL}target="_blank"diff --git a/apps/dashboard/src/hooks/mutations/useCreateBoxMutation.test.tsx b/apps/dashboard/src/hooks/mutations/useCreateBoxMutation.test.tsxindex 550672f9c..2c8b38905 100644--- a/apps/dashboard/src/hooks/mutations/useCreateBoxMutation.test.tsx+++ b/apps/dashboard/src/hooks/mutations/useCreateBoxMutation.test.tsx@@ -8,7 +8,9 @@ import { createRoot, type Root } from 'react-dom/client'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'import { ApiClient } from '@/api/apiClient'+import * as cloudBox from '@/lib/cloudBox'import type { DashboardConfig } from '@/types/DashboardConfig'+import { AxiosError, AxiosHeaders } from 'axios'import { getBoxesQueryKey } from '../useBoxes'import { useCreateBoxMutation } from './useCreateBoxMutation'@@ -21,6 +23,16 @@ vi.mock('../useSelectedOrganization', () => ({useSelectedOrganization: () => ({ selectedOrganization: context.organization }),}))+function axiosFailure(status: number, boxId: string): AxiosError {+ return new AxiosError(`Request failed with status code ${status}`, String(status), undefined, undefined, {+ status,+ data: { boxId },+ statusText: '',+ headers: {},+ config: { headers: new AxiosHeaders() },+ })+}+describe('useCreateBoxMutation startup timeout recovery', () => {let server: Serverlet apiUrl: string@@ -77,6 +89,7 @@ describe('useCreateBoxMutation startup timeout recovery', () => {afterEach(() => {act(() => root.unmount())client.clear()+ vi.restoreAllMocks()})async function submit() {@@ -127,13 +140,13 @@ describe('useCreateBoxMutation startup timeout recovery', () => {it.each([undefined, '', 123, { id: 'box-1' }])('does not recover a 408 without a valid Box ID: %p', async (boxId) => {postBody = { message: 'Timed out waiting for box box-1 to reach started', boxId }- await expect(submit()).rejects.toMatchObject({ response: { status: 408 } })+ await expect(submit()).rejects.toMatchObject({ statusCode: 408 })expect(requests.map(({ method }) => method)).toEqual(['POST'])})it.each([400, 403, 409, 429, 502, 504])('preserves HTTP %s failures even if an ID is present', async (status) => {postStatus = status- await expect(submit()).rejects.toMatchObject({ response: { status } })+ await expect(submit()).rejects.toMatchObject({ statusCode: status })expect(requests.map(({ method }) => method)).toEqual(['POST'])})@@ -144,6 +157,26 @@ describe('useCreateBoxMutation startup timeout recovery', () => {expect(client.getQueryState(getBoxesQueryKey('org-1'))?.isInvalidated).toBe(false)})+ it('recovers a raw Axios 408 through the returned Box ID', async () => {+ const create = vi.spyOn(cloudBox, 'createBoxViaBoxApi').mockRejectedValueOnce(axiosFailure(408, 'box-1'))++ await expect(submit()).resolves.toEqual(box)++ expect(create).toHaveBeenCalledOnce()+ expect(requests.map(({ method, url }) => [method, url])).toEqual([['GET', '/api/box/box-1']])+ })++ it.each([+ ['a raw Axios non-408 response', axiosFailure(409, 'box-1')],+ ['a non-Axios failure', new Error('Connection closed')],+ ])('preserves %s without a follow-up read', async (_name, error) => {+ vi.spyOn(cloudBox, 'createBoxViaBoxApi').mockRejectedValueOnce(error)++ await expect(submit()).rejects.toBe(error)++ expect(requests).toEqual([])+ })+it('sends no request without an organization', async () => {context.organization = nullawait expect(submit()).rejects.toThrow('Missing organization')diff --git a/apps/dashboard/src/hooks/mutations/useCreateBoxMutation.tsx b/apps/dashboard/src/hooks/mutations/useCreateBoxMutation.tsxindex ad9b8ba4e..dbd874e7b 100644--- a/apps/dashboard/src/hooks/mutations/useCreateBoxMutation.tsx+++ b/apps/dashboard/src/hooks/mutations/useCreateBoxMutation.tsx@@ -3,6 +3,7 @@* SPDX-License-Identifier: AGPL-3.0*/+import { BoxliteError } from '@/api/errors'import { useApi } from '@/hooks/useApi'import { CreateBoxParams, createBoxViaBoxApi } from '@/lib/cloudBox'import type { Box } from '@boxlite-ai/api-client'@@ -27,8 +28,12 @@ export const useCreateBoxMutation = () => {} catch (error) {// The server may finish waiting before a cold image finishes pulling.// Only its explicit identity proves a box exists; never repeat POST.- if (!isAxiosError(error) || error.response?.status !== 408) throw error- const pendingBoxId = error.response.data?.boxId+ if (error instanceof BoxliteError) {+ if (error.statusCode !== 408) throw error+ } else if (!isAxiosError(error) || error.response?.status !== 408) {+ throw error+ }+ const pendingBoxId = error instanceof BoxliteError ? error.boxId : error.response?.data?.boxIdif (typeof pendingBoxId !== 'string' || pendingBoxId.length === 0) throw errorboxId = pendingBoxId}diff --git a/apps/dashboard/src/hooks/queries/useVolumeStorageCapabilities.test.tsx b/apps/dashboard/src/hooks/queries/useVolumeStorageCapabilities.test.tsxnew file mode 100644index 000000000..a188775b7--- /dev/null+++ b/apps/dashboard/src/hooks/queries/useVolumeStorageCapabilities.test.tsx@@ -0,0 +1,81 @@+// @vitest-environment jsdom+/* Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0 */++import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { useVolumeStorageCapabilities } from './useVolumeStorageCapabilities'++const state = vi.hoisted(() => ({ organization: { id: 'org-1' } as { id: string } | null }))+const getVolumeStorageCapabilities = vi.hoisted(() => vi.fn())+vi.mock('../useApi', () => ({ useApi: () => ({ getVolumeStorageCapabilities }) }))+vi.mock('../useSelectedOrganization', () => ({+ useSelectedOrganization: () => ({ selectedOrganization: state.organization }),+}))++describe('useVolumeStorageCapabilities', () => {+ let client: QueryClient+ let root: ReturnType<typeof createRoot>+ let query: ReturnType<typeof useVolumeStorageCapabilities>++ function Probe() {+ query = useVolumeStorageCapabilities()+ return null+ }++ async function render() {+ await act(async () =>+ root.render(+ <QueryClientProvider client={client}>+ <Probe />+ </QueryClientProvider>,+ ),+ )+ }++ beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ state.organization = { id: 'org-1' }+ getVolumeStorageCapabilities.mockReset()+ client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } })+ root = createRoot(document.createElement('div'))+ })++ afterEach(() => {+ act(() => root.unmount())+ client.clear()+ })++ it('loads capabilities and isolates them by selected organization', async () => {+ const standardOnly = { object_storage_enabled: true, filestore_enabled: false }+ const filestoreEnabled = { object_storage_enabled: true, filestore_enabled: true }+ getVolumeStorageCapabilities.mockResolvedValueOnce(standardOnly).mockResolvedValueOnce(filestoreEnabled)++ await render()+ await act(async () => {+ await vi.waitFor(() => expect(query.isSuccess).toBe(true))+ })+ expect(query.data).toEqual(standardOnly)++ state.organization = { id: 'org-2' }+ await render()+ await act(async () => {+ await vi.waitFor(() => expect(query.data).toEqual(filestoreEnabled))+ })++ expect(getVolumeStorageCapabilities).toHaveBeenCalledTimes(2)+ expect(client.getQueryData(['volume-storage-capabilities', 'org-1'])).toEqual(standardOnly)+ expect(client.getQueryData(['volume-storage-capabilities', 'org-2'])).toEqual(filestoreEnabled)+ })++ it('does not request capabilities without a selected organization', async () => {+ state.organization = null+ await render()++ expect(query.fetchStatus).toBe('idle')+ expect(query.data).toBeUndefined()+ expect(getVolumeStorageCapabilities).not.toHaveBeenCalled()+ })+})diff --git a/apps/dashboard/src/hooks/queries/useVolumeStorageCapabilities.ts b/apps/dashboard/src/hooks/queries/useVolumeStorageCapabilities.tsnew file mode 100644index 000000000..4b80474c6--- /dev/null+++ b/apps/dashboard/src/hooks/queries/useVolumeStorageCapabilities.ts@@ -0,0 +1,16 @@+/* Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0 */++import { useQuery } from '@tanstack/react-query'+import { useApi } from '../useApi'+import { useSelectedOrganization } from '../useSelectedOrganization'++export function useVolumeStorageCapabilities() {+ const api = useApi()+ const { selectedOrganization } = useSelectedOrganization()+ return useQuery({+ queryKey: ['volume-storage-capabilities', selectedOrganization?.id],+ queryFn: () => api.getVolumeStorageCapabilities(),+ enabled: !!selectedOrganization,+ })+}diff --git a/apps/dashboard/src/lib/error-handling.test.ts b/apps/dashboard/src/lib/error-handling.test.tsnew file mode 100644index 000000000..dd33a6620--- /dev/null+++ b/apps/dashboard/src/lib/error-handling.test.ts@@ -0,0 +1,26 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { toast } from 'sonner'+import { BoxliteError } from '@/api/errors'+import { handleApiError } from './error-handling'++vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))++describe('handleApiError', () => {+ beforeEach(() => vi.clearAllMocks())++ it('shows the server reason and non-sensitive diagnostics', () => {+ const error = BoxliteError.fromString('runner has not declared filestore', {+ statusCode: 400,+ code: 'BOX_STATE_TRANSITION_FAILED',+ boxId: 'box-1',+ })++ handleApiError(error, 'Failed to create box')++ expect(toast.error).toHaveBeenCalledWith('Failed to create box', {+ description:+ 'runner has not declared filestore · HTTP 400 · Code: BOX_STATE_TRANSITION_FAILED · Box ID: box-1',+ action: undefined,+ })+ })+})diff --git a/apps/dashboard/src/lib/error-handling.ts b/apps/dashboard/src/lib/error-handling.tsindex 0eb2a6a04..1dba693b4 100644--- a/apps/dashboard/src/lib/error-handling.ts+++ b/apps/dashboard/src/lib/error-handling.ts@@ -14,10 +14,18 @@ interface HandleApiErrorOptions {export function handleApiError(error: unknown, message: string, options?: HandleApiErrorOptions) {const isBoxliteError = error instanceof BoxliteError+ const description = isBoxliteError+ ? [+ error.message,+ ...(error.statusCode ? [`HTTP ${error.statusCode}`] : []),+ ...(error.code ? [`Code: ${error.code}`] : []),+ ...(error.boxId ? [`Box ID: ${error.boxId}`] : []),+ ].join(' · ')+ : 'Please try again or check the console for more details'toast.error(message, {...(options?.toastId ? { id: options.toastId } : {}),- description: isBoxliteError ? error.message : 'Please try again or check the console for more details',+ description,action: options?.action,})diff --git a/apps/dashboard/src/lib/ssh-connection-ui.test.ts b/apps/dashboard/src/lib/ssh-connection-ui.test.tsnew file mode 100644index 000000000..fda2240a4--- /dev/null+++ b/apps/dashboard/src/lib/ssh-connection-ui.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest'+import { BoxliteError } from '@/api/errors'+import { sshFailureReason } from './ssh-connection-ui'++describe('sshFailureReason', () => {+ it.each([+ [401, 'authentication'],+ [403, 'permission'],+ ] as const)('preserves HTTP %i as %s after API error normalization', (statusCode, expected) => {+ expect(sshFailureReason(BoxliteError.fromString('request failed', { statusCode }))).toBe(expected)+ })++ it('still recognizes a missing configuration after API error normalization', () => {+ const error = BoxliteError.fromString('SSH configuration is required', { statusCode: 400 })+ expect(sshFailureReason(error)).toBe('missing-config')+ })+})diff --git a/apps/dashboard/src/lib/ssh-connection-ui.ts b/apps/dashboard/src/lib/ssh-connection-ui.tsindex 5aa6e7b76..d16841736 100644--- a/apps/dashboard/src/lib/ssh-connection-ui.ts+++ b/apps/dashboard/src/lib/ssh-connection-ui.ts@@ -1,13 +1,22 @@/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */+import { BoxliteError } from '@/api/errors'import { isAxiosError } from 'axios'/** Keep missing configuration distinct from authentication, permission and transport failures. */export function sshFailureReason(error: unknown): 'missing-config' | 'authentication' | 'permission' | 'unknown' {- if (!isAxiosError(error)) return 'unknown'- if (error.response?.status === 401) return 'authentication'- if (error.response?.status === 403) return 'permission'- const data = error.response?.data+ let status: number | undefined+ let data: any+ if (error instanceof BoxliteError) {+ status = error.statusCode+ data = { message: error.message }+ } else {+ if (!isAxiosError(error)) return 'unknown'+ status = error.response?.status+ data = error.response?.data+ }+ if (status === 401) return 'authentication'+ if (status === 403) return 'permission'let message = data?.error?.message ?? data?.messageif (typeof message !== 'string') return 'unknown'// map_tonic_err adds the operation and tonic's Display envelope to guest errors.diff --git a/apps/dashboard/src/mocks/checkpoint-handlers.test.ts b/apps/dashboard/src/mocks/checkpoint-handlers.test.tsindex b810437ad..62cda039b 100644--- a/apps/dashboard/src/mocks/checkpoint-handlers.test.ts+++ b/apps/dashboard/src/mocks/checkpoint-handlers.test.ts@@ -8,6 +8,15 @@ const server = setupServer(...checkpointHandlers)beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))afterAll(() => server.close())+it('advertises the volume backends supported by the mock preview', async () => {+ const response = await fetch('https://checkpoint-preview.test/v1/config')++ expect(response.status).toBe(200)+ expect(await response.json()).toMatchObject({+ capabilities: { object_storage_enabled: true, filestore_enabled: true },+ })+})+it('checkpoint preview captures only a source owned by the requested organization', async () => {const source = buildBox({id: 'foreign-capture-source',diff --git a/apps/dashboard/src/mocks/checkpoint-handlers.ts b/apps/dashboard/src/mocks/checkpoint-handlers.tsindex a21e52df9..f45effc9f 100644--- a/apps/dashboard/src/mocks/checkpoint-handlers.ts+++ b/apps/dashboard/src/mocks/checkpoint-handlers.ts@@ -74,7 +74,14 @@ export function createMockCheckpointBox(org: string, key: string, name?: string)export const checkpointHandlers = [http.get('*/v1/config', () =>- HttpResponse.json({ capabilities: { checkpoints_enabled: true, private_tunnels_enabled: true } }),+ HttpResponse.json({+ capabilities: {+ checkpoints_enabled: true,+ private_tunnels_enabled: true,+ object_storage_enabled: true,+ filestore_enabled: true,+ },+ }),),http.get('*/v1/:organizationId/checkpoints', ({ params }) => {const rows = [...recordsFor(String(params.organizationId)).values()]diff --git a/apps/dashboard/src/mocks/fixtures.ts b/apps/dashboard/src/mocks/fixtures.tsindex c7daf9e6c..2b3fd1ed5 100644--- a/apps/dashboard/src/mocks/fixtures.ts+++ b/apps/dashboard/src/mocks/fixtures.ts@@ -267,6 +267,7 @@ export const MOCK_PAGINATED_BOXES: PaginatedBoxes = {function buildVolume(overrides: Partial<VolumeDto> & Pick<VolumeDto, 'id' | 'name' | 'state'>): VolumeDto {return {organizationId: MOCK_ORGANIZATION_ID,+ storageBackend: 'standard',createdAt: daysAgo(31),updatedAt: now,lastUsedAt: undefined,@@ -303,6 +304,15 @@ export const MOCK_VOLUMES: VolumeDto[] = [createdAt: daysAgo(31),lastUsedAt: daysAgo(31),}),+ buildVolume({+ id: 'vol-k5l6m7n8',+ name: 'shared-training-data',+ state: VolumeState.READY,+ createdAt: daysAgo(3),+ lastUsedAt: hoursAgo(1),+ storageBackend: 'performance',+ instance: 'boxlite-dev-shared',+ }),buildVolume({id: 'vol-m3n4o5p6',name: 'tmp-debug',@@ -337,6 +347,7 @@ export const MOCK_VOLUME_USAGE: Record<string, { boxId: string; boxName: string;{ boxId: 'mock-box-stopped', boxName: 'batch-worker', mountPath: '/models' },],'vol-e5f6g7h8': [{ boxId: 'mock-box-running', boxName: 'web-api', mountPath: '/data' }],+ 'vol-k5l6m7n8': [{ boxId: 'mock-box-running', boxName: 'web-api', mountPath: '/training' }],}// --- Billing history depth -------------------------------------------------diff --git a/apps/dashboard/src/mocks/handlers.ts b/apps/dashboard/src/mocks/handlers.tsindex 363b19c0e..a4ae220a5 100644--- a/apps/dashboard/src/mocks/handlers.ts+++ b/apps/dashboard/src/mocks/handlers.ts@@ -307,12 +307,17 @@ export const handlers = [HttpResponse.json(globalThis.localStorage?.getItem('desktop-review-empty') === '1' ? [] : MOCK_VOLUMES),),http.post(`${API_URL}/volumes`, async ({ request }) => {- const body = (await request.json()) as { name?: string }+ const body = (await request.json()) as {+ name?: string+ storageBackend?: 'standard' | 'performance'+ }const created = {id: `vol-${Math.abs(Date.now() % 100000000)}`,name: body?.name || 'unnamed-volume',organizationId: MOCK_ORGANIZATION.id,- state: 'creating',+ storageBackend: body?.storageBackend || 'standard',+ instance: body?.storageBackend === 'performance' ? 'boxlite-dev-shared' : undefined,+ state: body?.storageBackend === 'performance' ? 'ready' : 'creating',createdAt: new Date().toISOString(),updatedAt: new Date().toISOString(),}diff --git a/apps/dashboard/src/mocks/resource-state-handlers.ts b/apps/dashboard/src/mocks/resource-state-handlers.tsindex e0f29542e..4eb283538 100644--- a/apps/dashboard/src/mocks/resource-state-handlers.ts+++ b/apps/dashboard/src/mocks/resource-state-handlers.ts@@ -12,7 +12,17 @@ export function resourceStateHandlers(apiUrl: string) {[`${apiUrl}/volumes`, []],[`${apiUrl}/api-keys`, []],[`${apiUrl}/box/paginated`, { items: [], total: 0, totalPages: 0, page: 1, pageSize: 25 }],- ['*/v1/config', { capabilities: { checkpoints_enabled: true, private_tunnels_enabled: true } }],+ [+ '*/v1/config',+ {+ capabilities: {+ checkpoints_enabled: true,+ private_tunnels_enabled: true,+ object_storage_enabled: true,+ filestore_enabled: true,+ },+ },+ ],['*/v1/:organizationId/checkpoints', { checkpoints: [] }],['*/v1/:organizationId/domains',diff --git a/apps/dashboard/src/pages/Volumes.test.tsx b/apps/dashboard/src/pages/Volumes.test.tsxindex c232c89c1..25857ed86 100644--- a/apps/dashboard/src/pages/Volumes.test.tsx+++ b/apps/dashboard/src/pages/Volumes.test.tsx@@ -5,6 +5,7 @@*/import { OrganizationRolePermissionsEnum } from '@boxlite-ai/api-client'+import { BoxliteError } from '@/api/errors'import { act } from 'react'import { createRoot, type Root } from 'react-dom/client'import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'@@ -17,6 +18,7 @@ const READY_VOLUME = {state: 'ready',createdAt: new Date().toISOString(),lastUsedAt: null,+ storageBackend: 'standard',}// Stands in for the real form so the assertions can read what the page decided@@ -38,6 +40,18 @@ const state = vi.hoisted(() => ({refetch: vi.fn(),volumeState: 'ready',errorReason: undefined as string | undefined,+ storageBackend: 'standard',+ instance: undefined as string | undefined,+ capabilities: undefined as+ | { object_storage_enabled?: boolean; filestore_enabled?: boolean }+ | undefined,+ capabilitiesLoading: false,+ capabilitiesFetching: false,+ capabilitiesError: false,+ capabilitiesRefetch: vi.fn(),+ createdVolume: undefined as Record<string, unknown> | undefined,+ createError: undefined as Error | undefined,+ createPending: false,}))vi.mock('@/hooks/useSelectedOrganization', () => ({@@ -53,7 +67,15 @@ vi.mock('@/hooks/queries/useVolumesQuery', () => ({? undefined: state.empty? []- : [{ ...READY_VOLUME, state: state.volumeState, errorReason: state.errorReason }],+ : [+ {+ ...READY_VOLUME,+ state: state.volumeState,+ errorReason: state.errorReason,+ storageBackend: state.storageBackend,+ instance: state.instance,+ },+ ],isLoading: state.loading,error: state.error,refetch: state.refetch,@@ -61,7 +83,22 @@ vi.mock('@/hooks/queries/useVolumesQuery', () => ({}),}))vi.mock('@/hooks/mutations/useCreateVolumeMutation', () => ({- useCreateVolumeMutation: () => ({ mutateAsync: vi.fn(), isPending: false }),+ useCreateVolumeMutation: () => ({+ mutateAsync: vi.fn(async (variables: { volume: Record<string, unknown> }) => {+ if (state.createError) throw state.createError+ state.createdVolume = variables.volume+ }),+ isPending: state.createPending,+ }),+}))+vi.mock('@/hooks/queries/useVolumeStorageCapabilities', () => ({+ useVolumeStorageCapabilities: () => ({+ data: state.capabilities,+ isLoading: state.capabilitiesLoading,+ isFetching: state.capabilitiesFetching,+ isError: state.capabilitiesError,+ refetch: state.capabilitiesRefetch,+ }),}))vi.mock('@/hooks/mutations/useDeleteVolumeMutation', () => ({useDeleteVolumeMutation: () => ({ mutateAsync: vi.fn() }),@@ -82,6 +119,29 @@ function rowAction(label: string): HTMLElement | undefined {)}+function inputText(label: string, value: string) {+ const input = document.querySelector<HTMLInputElement>(`input[aria-label="${label}"]`)!+ act(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value)+ input.dispatchEvent(new Event('input', { bubbles: true }))+ })+}++async function submitWithEnter() {+ const input = document.querySelector<HTMLInputElement>('input[aria-label="Volume name"]')!+ await act(async () => {+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))+ })+}++function selectStorage(value: string) {+ const select = document.querySelector<HTMLSelectElement>('[aria-label="Volume storage"]')!+ act(() => {+ Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!.call(select, value)+ select.dispatchEvent(new Event('change', { bubbles: true }))+ })+}+describe('Volumes row action "New Box"', () => {let root: Root | null = null@@ -98,6 +158,15 @@ describe('Volumes row action "New Box"', () => {state.empty = falsestate.volumeState = 'ready'state.errorReason = undefined+ state.storageBackend = 'standard'+ state.instance = undefined+ state.capabilities = { object_storage_enabled: true, filestore_enabled: false }+ state.capabilitiesLoading = false+ state.capabilitiesFetching = false+ state.capabilitiesError = false+ state.createdVolume = undefined+ state.createError = undefined+ state.createPending = falsestate.permissions = [OrganizationRolePermissionsEnum.WRITE_VOLUMES, OrganizationRolePermissionsEnum.WRITE_BOXES]})@@ -311,3 +380,215 @@ describe('Volumes row action "New Box"', () => {expect(rowAction('New Volume')).toBeDefined()})})++describe('Volumes storage selection', () => {+ let root: Root | null = null++ beforeAll(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ })++ beforeEach(() => {+ vi.clearAllMocks()+ state.empty = false+ state.volumeState = 'ready'+ state.errorReason = undefined+ state.storageBackend = 'standard'+ state.instance = undefined+ state.capabilities = { object_storage_enabled: true, filestore_enabled: false }+ state.capabilitiesLoading = false+ state.capabilitiesFetching = false+ state.capabilitiesError = false+ state.createdVolume = undefined+ state.createError = undefined+ state.createPending = false+ state.permissions = [OrganizationRolePermissionsEnum.WRITE_VOLUMES]+ })++ afterEach(() => {+ act(() => root?.unmount())+ root = null+ document.body.innerHTML = ''+ vi.unstubAllGlobals()+ })++ function renderPage() {+ const host = document.createElement('div')+ document.body.appendChild(host)+ act(() => {+ root = createRoot(host)+ root.render(<Volumes />)+ })+ }++ it('defaults to standard storage and sends no implicit Filestore instance', async () => {+ renderPage()+ await act(async () => rowAction('New Volume')!.click())+ expect(document.querySelector<HTMLSelectElement>('[aria-label="Volume storage"]')!.value).toBe('standard')+ inputText('Volume name', 'shared-data')+ await act(async () => rowAction('Create')!.click())++ expect(state.createdVolume).toEqual({ name: 'shared-data', storageBackend: 'standard' })+ expect(toast.success).toHaveBeenCalledWith('Creating volume shared-data')+ })++ it('keeps unconfigured Performance storage visible but disabled', () => {+ renderPage()+ act(() => rowAction('New Volume')?.click())++ expect(document.querySelector<HTMLOptionElement>('option[value="performance"]')!.disabled).toBe(true)+ expect(document.body.textContent).toContain('Performance storage is not configured on this deployment.')+ })++ it('creates a Performance volume through server assignment and immediate-ready copy', async () => {+ state.capabilities = { object_storage_enabled: true, filestore_enabled: true }+ renderPage()+ await act(async () => rowAction('New Volume')!.click())+ expect(document.querySelector<HTMLSelectElement>('[aria-label="Volume storage"]')!.value).toBe('standard')+ selectStorage('performance')+ inputText('Volume name', 'nfs-data')+ await act(async () => rowAction('Create')!.click())++ expect(state.createdVolume).toEqual({ name: 'nfs-data', storageBackend: 'performance' })+ expect(Object.hasOwn(state.createdVolume!, 'instance')).toBe(false)+ expect(toast.success).toHaveBeenCalledWith('Created volume nfs-data')+ expect(document.body.textContent).not.toContain('It takes a few seconds to become ready.')+ })++ it('shows the detailed Filestore lookup error returned by the API', async () => {+ state.capabilities = { object_storage_enabled: true, filestore_enabled: true }+ state.createError = new BoxliteError(+ "Could not look up Filestore instance 'projects/boxlite-dev-project/locations/us-east5-a/instances/boxlite-dev-shared': GCP PERMISSION_DENIED: file.instances.get denied",+ )+ renderPage()+ await act(async () => rowAction('New Volume')!.click())+ selectStorage('performance')+ inputText('Volume name', 'nfs-data')+ await act(async () => rowAction('Create')!.click())++ expect(toast.error).toHaveBeenCalledWith('Failed to create volume', {+ description: state.createError.message,+ action: undefined,+ })+ })++ it('starts with the only configured backend and disables creation without one', async () => {+ state.capabilities = { object_storage_enabled: false, filestore_enabled: true }+ renderPage()+ await act(async () => rowAction('New Volume')!.click())++ expect(document.querySelector<HTMLSelectElement>('[aria-label="Volume storage"]')!.value).toBe('performance')+ inputText('Volume name', 'nfs-data')+ await act(async () => rowAction('Create')!.click())+ expect(state.createdVolume).toEqual({ name: 'nfs-data', storageBackend: 'performance' })++ act(() => root?.unmount())+ root = null+ document.body.innerHTML = ''++ state.capabilities = { object_storage_enabled: false, filestore_enabled: false }+ renderPage()+ await act(async () => rowAction('New Volume')!.click())+ inputText('Volume name', 'unused')+ expect(rowAction('Create')!.hasAttribute('disabled')).toBe(true)+ })++ it('waits for backend capabilities before submitting', () => {+ state.capabilitiesLoading = true+ renderPage()+ act(() => rowAction('New Volume')?.click())+ inputText('Volume name', 'shared-data')++ expect(rowAction('Create')!.hasAttribute('disabled')).toBe(true)+ })++ it('resets storage to the default each time the dialog opens', () => {+ state.capabilities = { object_storage_enabled: true, filestore_enabled: true }+ renderPage()+ act(() => rowAction('New Volume')?.click())+ selectStorage('performance')+ act(() => rowAction('Cancel')?.click())++ act(() => rowAction('New Volume')?.click())+ expect(document.querySelector<HTMLSelectElement>('[aria-label="Volume storage"]')!.value).toBe('standard')+ })++ it('keeps Standard available when an older config omits the new capability fields', async () => {+ state.capabilities = { filestore_enabled: false }+ renderPage()+ await act(async () => rowAction('New Volume')!.click())+ inputText('Volume name', 'legacy-standard')+ await act(async () => rowAction('Create')!.click())++ expect(state.createdVolume).toEqual({ name: 'legacy-standard', storageBackend: 'standard' })+ })++ it.each([+ {+ name: 'capabilities are loading',+ arrange: () => {+ state.capabilitiesLoading = true+ },+ },+ {+ name: 'no backend is available',+ arrange: () => {+ state.capabilities = { object_storage_enabled: false, filestore_enabled: false }+ },+ },+ {+ name: 'capability discovery failed',+ arrange: () => {+ state.capabilities = undefined+ state.capabilitiesError = true+ },+ },+ ])('does not submit with Enter while $name', async ({ arrange }) => {+ arrange()+ renderPage()+ await act(async () => rowAction('New Volume')!.click())+ inputText('Volume name', 'must-not-create')+ await submitWithEnter()++ expect(state.createdVolume).toBeUndefined()+ })++ it('does not submit with Enter while creation is pending', async () => {+ state.createPending = true+ renderPage()+ await act(async () => rowAction('New Volume')!.click())+ inputText('Volume name', 'must-not-create')+ await submitWithEnter()++ expect(state.createdVolume).toBeUndefined()+ }, 30_000)++ it('distinguishes capability discovery failure from a disabled backend and retries it', async () => {+ state.capabilities = undefined+ state.capabilitiesError = true+ renderPage()+ await act(async () => rowAction('New Volume')!.click())++ expect(document.body.textContent).toContain('Could not load volume storage options')+ expect(document.body.textContent).not.toContain('Performance storage is not configured')+ await act(async () => rowAction('Retry')!.click())+ expect(state.capabilitiesRefetch).toHaveBeenCalledTimes(1)+ })++ it('does not label an unknown response storage backend as Standard', () => {+ state.storageBackend = '11184809'+ renderPage()++ expect(document.querySelector('.resource-list-row')?.textContent).toContain('Unknown')+ expect(document.querySelector('.resource-list-row')?.textContent).not.toContain('Standard')+ })++ it('shows only the storage backend', () => {+ state.storageBackend = 'performance'+ state.instance = 'boxlite-dev-shared'+ renderPage()++ expect(document.body.textContent).toContain('Performance')+ expect(document.body.textContent).not.toContain('boxlite-dev-shared')+ })+})diff --git a/apps/dashboard/src/pages/Volumes.tsx b/apps/dashboard/src/pages/Volumes.tsxindex 7b748b1fb..26e988027 100644--- a/apps/dashboard/src/pages/Volumes.tsx+++ b/apps/dashboard/src/pages/Volumes.tsx@@ -37,6 +37,7 @@ import { HardDrive, Plus, Trash } from '@/components/ui/icon'import { useCreateVolumeMutation } from '@/hooks/mutations/useCreateVolumeMutation'import { useDeleteVolumeMutation } from '@/hooks/mutations/useDeleteVolumeMutation'import { queryKeys } from '@/hooks/queries/queryKeys'+import { useVolumeStorageCapabilities } from '@/hooks/queries/useVolumeStorageCapabilities'import { useVolumesQuery } from '@/hooks/queries/useVolumesQuery'import { useSelectedOrganization } from '@/hooks/useSelectedOrganization'import { useVolumeWsSync } from '@/hooks/useVolumeWsSync'@@ -44,7 +45,13 @@ import { copyToClipboard } from '@/lib/copy-text'import { handleApiError } from '@/lib/error-handling'import { timeAgo } from '@/lib/format'import { cn } from '@/lib/utils'-import { OrganizationRolePermissionsEnum, VolumeDto, VolumeState } from '@boxlite-ai/api-client'+import {+ CreateVolumeStorageBackendEnum,+ OrganizationRolePermissionsEnum,+ VolumeDto,+ VolumeDtoStorageBackendEnum,+ VolumeState,+} from '@boxlite-ai/api-client'import { useQueryClient } from '@tanstack/react-query'import React, { useCallback, useMemo, useState } from 'react'import { toast } from 'sonner'@@ -62,8 +69,9 @@ const NAME_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9._-]+$/// buttons under it — and every `fr` column drifted further apart the further// right it sat. The last column is therefore fixed, and this string exists// once so the two can no longer diverge.-const ROW_GRID =- 'grid min-w-[760px] grid-cols-[minmax(0,1.4fr)_minmax(0,1.5fr)_120px_100px_100px_104px] items-center gap-4'+// `min-w` keeps every column readable on a phone: the list scrolls sideways inside its own+// box instead of squeezing names down to a letter.+const ROW_GRID = 'grid min-w-[840px] grid-cols-[1.6fr_1.2fr_1fr_1fr_0.8fr_0.85fr_104px] items-center gap-3'// Transitional states read as `warn` rather than blending in with the healthy// ones: a volume stuck in `pending_delete` is exactly the leak this page exists@@ -100,6 +108,13 @@ const Volumes: React.FC = () => {const queryKey = useMemo(() => queryKeys.volumes.list(selectedOrganization?.id ?? ''), [selectedOrganization?.id])const { data: inventory, error: volumesError, isFetching, refetch } = useVolumesQuery()const volumes = inventory ?? []+ const {+ data: storageCapabilities,+ isLoading: storageCapabilitiesLoading,+ isFetching: storageCapabilitiesFetching,+ isError: storageCapabilitiesError,+ refetch: refetchStorageCapabilities,+ } = useVolumeStorageCapabilities()const createVolume = useCreateVolumeMutation()const deleteVolume = useDeleteVolumeMutation({ invalidateOnSuccess: false })@@ -110,6 +125,9 @@ const Volumes: React.FC = () => {const [filter, setFilter] = useState('')const [createOpen, setCreateOpen] = useState(false)const [newName, setNewName] = useState('')+ const [newStorageBackend, setNewStorageBackend] = useState<CreateVolumeStorageBackendEnum>(+ CreateVolumeStorageBackendEnum.STANDARD,+ )const [pendingDelete, setPendingDelete] = useState<VolumeDto | null>(null)const [boxVolumeId, setBoxVolumeId] = useState<string | null>(null)const [deleteConfirmText, setDeleteConfirmText] = useState('')@@ -131,6 +149,17 @@ const Volumes: React.FC = () => {}, [volumes, filter])const nameValid = !newName || NAME_REGEX.test(newName)+ const objectStorageAvailable = storageCapabilities?.object_storage_enabled !== false+ const filestoreAvailable = storageCapabilities?.filestore_enabled === true+ // The server assigns the Filestore instance; the dashboard deliberately does+ // not ask users to know one. Falling back to the only available backend+ // avoids opening with a choice that is guaranteed to fail.+ const selectedStorageBackend = objectStorageAvailable+ ? newStorageBackend === CreateVolumeStorageBackendEnum.PERFORMANCE && !filestoreAvailable+ ? CreateVolumeStorageBackendEnum.STANDARD+ : newStorageBackend+ : CreateVolumeStorageBackendEnum.PERFORMANCE+ const storageUnavailable = !objectStorageAvailable && !filestoreAvailable// Exact match, untrimmed: a pasted name with a stray space is exactly the// half-attention this gate exists to catch.@@ -146,11 +175,19 @@ const Volumes: React.FC = () => {toast.error('Only letters, digits, dots, underscores and dashes are allowed in the name.')return}+ if (createVolume.isPending || storageCapabilitiesLoading || storageCapabilitiesError || storageUnavailable) returntry {- await createVolume.mutateAsync({ volume: { name }, organizationId: selectedOrganization?.id })+ await createVolume.mutateAsync({+ volume: { name, storageBackend: selectedStorageBackend },+ organizationId: selectedOrganization?.id,+ })setCreateOpen(false)setNewName('')- toast.success(`Creating volume ${name}`)+ toast.success(+ selectedStorageBackend === CreateVolumeStorageBackendEnum.PERFORMANCE+ ? `Created volume ${name}`+ : `Creating volume ${name}`,+ )} catch (error) {handleApiError(error, 'Failed to create volume')}@@ -202,7 +239,16 @@ const Volumes: React.FC = () => {/><div className="flex-1" />{canWrite && (- <AsciiButton variant="primary" className="h-11 sm:h-9" type="button" onClick={() => setCreateOpen(true)}>+ <AsciiButton+ variant="primary"+ className="h-11 sm:h-9"+ type="button"+ onClick={() => {+ setNewName('')+ setNewStorageBackend(CreateVolumeStorageBackendEnum.STANDARD)+ setCreateOpen(true)+ }}+ ><Plus className="size-3.5" strokeWidth={2.4} />New Volume</AsciiButton>@@ -221,6 +267,7 @@ const Volumes: React.FC = () => {<span>Name</span><span>Volume ID</span><span>Status</span>+ <span>Storage</span><span>Created</span>{/* `lastUsedAt` is written only when a box that mounts the volume iscreated (volume.service.ts:254-272), never on read or write — so it@@ -268,6 +315,13 @@ const Volumes: React.FC = () => {<span title={statusDetail} className={statusDetail ? 'cursor-help' : undefined}><StatusMark tone={STATE_TONE[volume.state] ?? 'idle'}>{volume.state}</StatusMark></span>+ <span className="font-mono text-meta text-muted-foreground">+ {volume.storageBackend === VolumeDtoStorageBackendEnum.PERFORMANCE+ ? 'Performance'+ : volume.storageBackend === VolumeDtoStorageBackendEnum.STANDARD+ ? 'Standard'+ : 'Unknown'}+ </span><span className="font-mono text-meta text-muted-foreground">{timeAgo(volume.createdAt)}</span><span className="font-mono text-meta text-muted-foreground">{timeAgo(volume.lastUsedAt)}</span>{/* Space is tight, so only the promoted action keeps a@@ -330,8 +384,8 @@ const Volumes: React.FC = () => {<DialogTitle>New Volume</DialogTitle></DialogHeader><FormDialogBody>- {/* Nothing else here says what a volume is — the payload is just a- name — and this dialog is where someone meets the concept. */}+ {/* This dialog is where someone meets the concept. The backend is+ explicit; the instance is server scheduling, not user input. */}<p className="mb-[5px] font-sans text-meta leading-relaxed text-muted-foreground">Storage that outlives a box. Mount it into a box to read and write; the data stays once that box is gone,and another box can mount it later.@@ -346,10 +400,37 @@ const Volumes: React.FC = () => {aria-invalid={!nameValid}className="form-field-input font-mono"/>- {/* Name is the entire create payload — the API accepts nothing else- — and a mount takes a name in place of an id, so this is the- handle the user will type later. */}- <PanelNote>Used to mount this volume into a box. It takes a few seconds to become ready.</PanelNote>+ <div className="mt-4">+ <div className="form-field-label">Volume storage</div>+ <select+ value={selectedStorageBackend}+ onChange={(event) => setNewStorageBackend(event.target.value as CreateVolumeStorageBackendEnum)}+ aria-label="Volume storage"+ className="form-field-input"+ >+ <option value={CreateVolumeStorageBackendEnum.STANDARD} disabled={!objectStorageAvailable}>+ Standard+ </option>+ <option value={CreateVolumeStorageBackendEnum.PERFORMANCE} disabled={!filestoreAvailable}>+ Performance+ </option>+ </select>+ </div>+ {storageCapabilitiesError ? (+ <ResourceErrorNotice+ title="Could not load volume storage options."+ retrying={storageCapabilitiesFetching}+ onRetry={() => void refetchStorageCapabilities()}+ />+ ) : !objectStorageAvailable && !filestoreAvailable ? (+ <PanelNote>This deployment has no volume storage configured.</PanelNote>+ ) : !filestoreAvailable ? (+ <PanelNote>Performance storage is not configured on this deployment.</PanelNote>+ ) : selectedStorageBackend === CreateVolumeStorageBackendEnum.PERFORMANCE ? (+ <PanelNote>Used to mount this volume into a box. It is ready immediately after creation.</PanelNote>+ ) : (+ <PanelNote>Used to mount this volume into a box. It takes a few seconds to become ready.</PanelNote>+ )}</FormDialogBody><DialogFooter><AsciiButton type="button" onClick={() => setCreateOpen(false)}>@@ -359,7 +440,14 @@ const Volumes: React.FC = () => {variant="primary"type="button"onClick={handleCreate}- disabled={createVolume.isPending || !newName.trim() || !nameValid}+ disabled={+ createVolume.isPending ||+ storageCapabilitiesLoading ||+ storageCapabilitiesError ||+ storageUnavailable ||+ !newName.trim() ||+ !nameValid+ }>{createVolume.isPending ? 'Creating…' : 'Create'}</AsciiButton>diff --git a/apps/e2e/README.md b/apps/e2e/README.mdindex 5581cb676..9eb84b610 100644--- a/apps/e2e/README.md+++ b/apps/e2e/README.md@@ -296,6 +296,11 @@ export BOXLITE_E2E_ALLOW_MISSING_CATALOG=1export BOXLITE_E2E_EXPANDED_DISK_RUNNER_ID=<runner-id>export BOXLITE_E2E_EXPANDED_DISK_TARGET_GIB=<new-size-in-gib>+# The filestore case normally asks the API to auto-assign one of its+# configured instances; exporting this pins one name for an API+# compatibility check (see the Filestore section):+# export FILESTORE_E2E_INSTANCE=other-instance-name+# The private image case runs only with a real private image and its login,# written with its host and a tag or digest. The prefix defaults to the# image's namespace. It adds its own login and refuses to start while the@@ -392,6 +397,50 @@ after confirming that the target is from the interrupted test, recover with`boxlite domain unbind "$BOXLITE_E2E_DOMAIN"` before rerunning. A binding thatmoves to another target during the test is left intact and reported as a failure.+## Filestore volume cases++`cases/test_filestore.py` covers **Filestore volumes** — Volume rows whose+data directory lives on a Filestore NFS instance, created through+`POST /volumes` with `storageBackend: "performance"` and an optional+`instance` field. They mount by box volume references that carry only+`managed_volume`, exactly like bucket-backed volumes. Instances themselves are+**ops-provisioned API env config** (`FILESTORE_INSTANCES`, a JSON object list+of GCP instances the API resolves through Filestore), not API objects the suite+can create.++A module gate probes for an instance ONCE before any test runs (the config+is deployment env with no listing API, so one volume create attempt is the+only honest probe). The gate's outcome decides the whole file:++- **Configured instance** → the probe box and volume are deleted and+ four cases run: the unknown-instance refusal is pinned, the happy path+ (write → stop → start → read back) runs on the proven instance, two boxes+ prove data sharing (write in one, read in the other, read again after the+ first is destroyed), and the lifecycle rules are pinned (in-use refusal →+ 409, free removal → 204, force re-delete → 204).+- **No configured instance** → one warning —+ `GCP FileStore instance=[auto-assignment] not available. Skip+ test_filestore.py .` — and the entire module skips.++An explicitly exported `FILESTORE_E2E_INSTANCE` only pins which name the+gate probes; a missing or unknown instance skips the module the same way —+the test instance can be recycled at any time, so its absence is never a+broken run.++Only unprovisioned-environment refusals skip: an instance that IS configured+but unusable ("is not ready") fails the gate loudly instead, because that is a+defect signal, not a precondition — keep the two classes apart when touching+the gate's skip conditions.++All cases skip when the API key cannot attach volumes (403 without+READ_VOLUMES + WRITE_VOLUMES), like the managed-volume cases. None is marked+`smoke` because a real GCP instance and mount are deployment dependencies, not+unit-test fixtures.++The gate normally omits `instance` and lets the API hash-assign one of its+configured names; set `FILESTORE_E2E_INSTANCE` only when a run must exercise+one particular instance name.+## The cloud legs (CI)`.github/workflows/e2e-cloud.yml` runs this suite against a deployed@@ -642,6 +691,7 @@ apps/e2e/├── test_box_lifecycle_policy.py # auto_stop / auto_delete reaping├── test_box_metrics.py # Per-box metrics through the runner├── test_volumes.py # Managed volumes: CRUD + data reuse+ ├── test_filestore.py # Filestore volumes: loud refusal, data across stop/start, cross-box sharing, lifecycle├── test_network_egress.py # Outbound policy: block-all, allow_net├── test_exec_*.py # Exec stdout, attach, timeout├── test_copy_roundtrip.py # Copy in/outdiff --git a/apps/e2e/cases/test_filestore.py b/apps/e2e/cases/test_filestore.pynew file mode 100644index 000000000..97f87f28e--- /dev/null+++ b/apps/e2e/cases/test_filestore.py@@ -0,0 +1,540 @@+"""Filestore volumes over the unified volume API — data that survives+stop/start, cross-box sharing, and lifecycle rules.++A Filestore volume is a Volume row like any other (volume.service): created+through `POST /volumes` with `storageBackend: "performance"` and an optional+`instance` naming the NFS instance that holds its data directory, mounted by+box volume references that carry only `managed_volume` — the same selector+form as bucket-backed volumes. The API resolves the instance address at+dispatch time from GCP Filestore, validates the name at volume create, and+hands the runner the resolved server and export inside the internal dispatch+DTO — the public request and the persisted row carry only the logical name.++Data semantics (volumes.go filestoreDataDir): a volume's data directory is+named by the volume id, so boxes sharing a volume share data, and a destroyed+box's data stays reachable by mounting the volume into a new box. Volume+removal this release tombstones the row (the NFS directory is left in place+for ops cleanup), and refuses while any live box still mounts it+(volume.service delete).++Raw REST rather than the SDK throughout, matching test_volumes' read-only+case: the Python SDK's volume dicts predate Filestore and reject unknown keys+(sdks/python/src/options.rs), and the wire shape used here+(`{"managed_volume": ...}`) is the volume-create + box-create flow+test_volumes already exercises for buckets — so the REST form is the honest+wire-level proof. Exec, stop and start still go through the SDK —+`rt.get(box_id)` hands back a full handle once the id is known.++How a runner-side failure reaches a REST caller: POST /boxes inserts a pending+box and the endpoint then waits up to 30s for STARTED+(boxlite-box.controller.ts:139); the failed CREATE_BOX job marks the box ERROR+carrying the runner's words (job-state-handler.service.ts), and the waiter+rejects with "Box state transition failed: <runner's error>" as HTTP 400. So+the create answer itself carries the failure — but the box row it inserted is+still there in ERROR state, and the case deletes it (a 4xx create is not proof+no box was created; same note as test_quota_enforcement's `_post_box`). A 2xx+is likewise more than acceptance: the endpoint answers only once the box+reached STARTED, so no separate wait is needed.++Filestore volumes skip the object-storage machinery entirely — creating one+succeeds on an API with no object storage configured, and `validateVolumes`+gets the full selector list (volume.service.ts) — so there is no 503+precondition here the way test_volumes has. The permission precondition is+real though: attaching any volume requires the key to hold volume permissions+(boxlite-box.controller.ts::assertCanAttachVolumes), and that 403 names a+skip, mirroring test_volumes.++Deployment reality, so nobody mistakes a green local run for coverage: the+FILESTORE_INSTANCES configuration is deployment runtime state. A local+single-machine stack must set it empty to opt out of the temporary default, so+its normal skip path only proves the gate works — the four cases need an+environment whose API config declares an instance and whose runner can reach it.+"""++from __future__ import annotations++import asyncio+import json+import os+import time+import uuid+import warnings+from typing import Any++import pytest++from conftest import (+ DEFAULT_IMAGE,+ drain,+ wait_for_box_state,+ wait_until_unlisted,+ with_bounded_lifetime,+)+from e2e_auth import auth_context, request_json+++GUEST_PATH = "/filestore"++# The API's words for an instance name its configuration does not know,+# pinned verbatim so a softened or reworded refusal cannot pass silently+# (apps/api/src/box/services/filestore-instance.resolver.ts).+UNKNOWN_INSTANCE_MARKER = "unknown Filestore instance"++# The API's words for a deployment that cannot accept a Filestore create at+# all (empty FILESTORE_INSTANCES), pinned verbatim from+# apps/api/src/box/services/volume.service.ts:134.+NO_INSTANCE_MARKER = "Filestore is not configured"+VOLUME_PERMISSION_MARKER = "Attaching a volume requires: read:volumes, write:volumes"++[email protected](scope="module")+def filestore_instance():+ """Module gate: prove the stage runner holds a Filestore instance BEFORE+ any test runs.++ The configuration is deployment-side env config with no listing API, so+ the only honest probe is one create attempt: the volume create IS the+ probe, and the box create proves the runner mount chain behind it. An+ empty instance list, an explicitly requested missing instance, or a+ configured-but-missing auto-selected instance means the environment is+ not provisioned — the+ whole module skips with a warning naming what was tried. Anything else+ that fails is a defect, not a precondition. On success the probe box is+ deleted immediately and the proven instance name is returned for the+ tests to reuse.+ """+ # FILESTORE_E2E_INSTANCE pins one configured instance for API+ # compatibility checks. When unset, let the API's early deterministic+ # hash assignment choose from its configured instances.+ candidate = os.environ.get("FILESTORE_E2E_INSTANCE")+ # An unavailable instance always skips, never fails — including an+ # explicitly exported name: the test instance can be recycled at any+ # time, so its absence is an unprovisioned environment, not a broken+ # run. The env var only pins WHICH name the gate probes.+ probe_volume_name = f"e2e-fs-probe-{uuid.uuid4().hex[:10]}"+ probe_box_name = f"e2e-fs-probe-box-{uuid.uuid4().hex[:10]}"++ volume_id = None+ try:+ status, body = request_json(+ "POST",+ auth_context().v1("volumes"),+ with_bounded_lifetime(+ {+ "name": probe_volume_name,+ "storageBackend": "performance",+ **({"instance": candidate} if candidate else {}),+ }+ ),+ )+ _skip_when_key_cannot_attach_volumes(status, body)+ body_str = json.dumps(body) if body else ""+ expected_refusal = status in (400, 503)+ not_configured = expected_refusal and NO_INSTANCE_MARKER in body_str+ unknown_instance = expected_refusal and UNKNOWN_INSTANCE_MARKER in body_str+ not_found = expected_refusal and "was not found" in body_str+ # Only unprovisioned-environment refusals skip; a configured instance+ # that is present but unusable ("is not ready") is a real defect and+ # must fail loudly below. Keep the two classes apart.+ environment_not_provisioned = unknown_instance or not_configured or not_found+ if not (200 <= status < 300) and environment_not_provisioned:+ warnings.warn(+ "GCP FileStore "+ f"instance=[{candidate or 'auto-assignment'}] not available. "+ "Skip test_filestore.py ."+ )+ pytest.skip(+ f"GCP FileStore instance=[{candidate or 'auto-assignment'}] not existed — add it to the "+ "API's FILESTORE_INSTANCES configuration to enable"+ )+ assert 200 <= status < 300, (+ f"filestore volume create failed: HTTP {status}: {body}"+ )+ assert body is not None and body.get("id"), (+ f"volume create response has no id: {body}"+ )+ volume_id = body["id"]+ assert body.get("state") == "ready", (+ f"a filestore volume must be ready at once (the runner provisions the data "+ f"directory lazily at first mount), got {body}"+ )+ candidate = body.get("instance")+ assert candidate, f"volume response lost the instance: {body}"+ if os.environ.get("FILESTORE_E2E_INSTANCE"):+ assert candidate == os.environ["FILESTORE_E2E_INSTANCE"], (+ f"API returned {candidate}; requested {os.environ['FILESTORE_E2E_INSTANCE']}"+ )++ status, body = _create_box_with_volume(volume_id, name=probe_box_name)+ _skip_when_key_cannot_attach_volumes(status, body)++ assert 200 <= status < 300, (+ f"filestore probe box create failed: HTTP {status}: {body}"+ )+ finally:+ _cleanup_probe(probe_box_name, volume_id)++ return candidate+++def _boxes_path(suffix: str = "") -> str:+ return auth_context().v1(f"boxes{suffix}")+++def _volumes_path(suffix: str = "") -> str:+ return auth_context().v1(f"volumes{suffix}")+++def _create_filestore_volume(+ instance: str | None = None, name: str | None = None+) -> tuple[int, dict[str, Any] | None]:+ """POST a filestore volume: a Volume row whose data directory will live on+ the named NFS instance."""+ body: dict[str, Any] = {"storageBackend": "performance"}+ if instance is not None:+ body["instance"] = instance+ if name is not None:+ body["name"] = name+ return request_json("POST", _volumes_path(), with_bounded_lifetime(body))+++def _create_box_with_volume(+ volume_selector: str, name: str | None = None+) -> tuple[int, dict[str, Any] | None]:+ """POST a box mounting the volume by selector — the same `managed_volume`+ form a bucket-backed volume uses."""+ body: dict[str, Any] = {+ "image": DEFAULT_IMAGE,+ "volumes": [{"managed_volume": volume_selector, "guest_path": GUEST_PATH}],+ }+ if name is not None:+ body["name"] = name+ return request_json("POST", _boxes_path(), with_bounded_lifetime(body))+++def _skip_when_key_cannot_attach_volumes(status: int, body: Any) -> None:+ """Skip only the API's explicit volume-permission refusal."""+ body_str = json.dumps(body) if body else ""+ if status == 403 and VOLUME_PERMISSION_MARKER in body_str:+ pytest.skip(+ "API key lacks volume attach permissions (READ_VOLUMES, WRITE_VOLUMES)"+ )+++def _delete_box_by_name(name: str) -> None:+ """Remove a Box returned by either a successful or a refused create."""+ status, body = request_json("GET", _boxes_path(f"/{name}"))+ if status == 404:+ return+ assert status == 200 and body and body.get("box_id"), (+ f"GET box {name} for cleanup failed: HTTP {status}: {body}"+ )+ status, body = request_json("DELETE", _boxes_path(f"/{body['box_id']}?force=true"))+ assert 200 <= status < 300 or status == 404, (+ f"DELETE box {body['box_id']} failed: HTTP {status}: {body}"+ )+++def _delete_volume_by_id(volume_id: str, force: bool = False) -> None:+ suffix = f"/{volume_id}" + ("?force=true" if force else "")+ status, body = request_json("DELETE", _volumes_path(suffix))+ assert 200 <= status < 300 or status == 404, (+ f"DELETE volume {volume_id} failed: HTTP {status}: {body}"+ )+++def _cleanup_probe(box_name: str, volume_id: str | None) -> None:+ errors = []+ try:+ _delete_box_by_name(box_name)+ except Exception as exc:+ errors.append(f"box {box_name}: {exc}")+ if volume_id:+ try:+ _delete_volume_by_id(volume_id, force=True)+ except Exception as exc:+ errors.append(f"volume {volume_id}: {exc}")+ if errors:+ raise AssertionError("Filestore cleanup failed: " + "; ".join(errors))+++async def _cleanup_resources(+ rt,+ *,+ box_ids: list[str] | None = None,+ box_names: list[str] | None = None,+ volume_id: str | None = None,+) -> None:+ errors = []+ for box_id in box_ids or []:+ try:+ await rt.remove(box_id, force=True)+ except Exception as exc:+ errors.append(f"box {box_id}: {exc}")+ for name in box_names or []:+ try:+ _delete_box_by_name(name)+ except Exception as exc:+ errors.append(f"box {name}: {exc}")+ if volume_id:+ try:+ _delete_volume_by_id(volume_id, force=True)+ except Exception as exc:+ errors.append(f"volume {volume_id}: {exc}")+ if errors:+ raise AssertionError("Filestore cleanup failed: " + "; ".join(errors))+++def _wait_for_volume_deleted(volume_id: str, timeout: float = 60) -> None:+ deadline = time.monotonic() + timeout+ last_state = "not observed"+ while True:+ status, body = request_json("GET", _volumes_path(f"/{volume_id}"))+ assert status == 200 and body is not None, (+ f"GET volume {volume_id} while waiting for deletion failed: HTTP {status}: {body}"+ )+ last_state = body.get("state")+ if last_state == "deleted":+ return+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ break+ time.sleep(min(1, remaining))+ raise AssertionError(+ f"volume {volume_id} did not reach deleted within {timeout}s; last state: {last_state}"+ )+++async def _exec_ok(box, script: str) -> str:+ async def collect():+ ex = await box.exec("sh", ["-c", script], None)+ out, err = await drain(ex)+ rc = await ex.wait()+ return out, err, rc++ try:+ out, err, rc = await asyncio.wait_for(collect(), timeout=60)+ except asyncio.TimeoutError as exc:+ raise AssertionError(f"{script!r} timed out after 60s") from exc+ assert rc.exit_code == 0, f"{script!r} failed ({rc.exit_code}): {err!r}"+ return out+++async def test_create_with_unregistered_instance_fails_loudly(filestore_instance):+ """A volume create naming an instance outside the API configuration fails loudly.++ The configuration is deployment-side env config an API caller cannot+ inspect, so the only honest outcomes are an accepted name or a refusal+ that names the instance. A create that swallowed the unknown name —+ accepting the row and deferring the failure to box create — would leave+ the caller believing the volume is backed by storage it is not.++ Behind the module gate: on a deployment without a configured instance the+ whole file skips, so this case only runs where an instance was proven to+ exist.+ """+ instance = f"e2e-no-such-instance-{uuid.uuid4().hex[:8]}"+ volume_name = f"e2e-fs-bad-{uuid.uuid4().hex[:10]}"++ volume_id = None+ try:+ status, body = _create_filestore_volume(instance, name=volume_name)+ volume_id = body.get("id") if body else None+ body_str = json.dumps(body) if body else ""+ assert 400 <= status < 500, (+ f"an unknown Filestore instance must fail the volume create with 4xx, "+ f"got HTTP {status}: {body_str}"+ )+ assert UNKNOWN_INSTANCE_MARKER in body_str, (+ f"the refusal must carry the API's words ({UNKNOWN_INSTANCE_MARKER!r}), "+ f"got HTTP {status}: {body_str}"+ )+ finally:+ if volume_id:+ _delete_volume_by_id(volume_id, force=True)+++async def test_filestore_volume_data_survives_stop_start(rt, filestore_instance):+ """Bytes written through a filestore volume survive stop → start.++ The mount is real NFS on the runner, bind-mounted into the box; stop+ unbinds but keeps the data directory, and start rebuilds the mount from+ the metadata saved at create time (volumes.go), so the same volume derives+ the same data directory. That is what separates a volume from the box's+ own disk, and it had no coverage outside the runner's own tests.+ """+ volume_name = f"e2e-fs-keep-{uuid.uuid4().hex[:10]}"+ box_name = f"e2e-fs-keep-box-{uuid.uuid4().hex[:10]}"+ volume_id = None+ box_id = None++ try:+ status, body = _create_filestore_volume(filestore_instance, name=volume_name)+ volume_id = body.get("id") if body else None+ assert 200 <= status < 300, f"filestore volume create failed: HTTP {status}: {body}"+ assert volume_id, f"volume create response has no id: {body}"+ status, body = _create_box_with_volume(volume_name, name=box_name)+ box_id = body.get("box_id") if body else None+ assert 200 <= status < 300, f"filestore box create failed: HTTP {status}: {body}"+ assert box_id, f"create response has no box_id: {body}"+ # The create's 2xx already means STARTED (the endpoint waits for it), so+ # the handle is usable for exec right away.+ box = await rt.get(box_id)+ assert box is not None, f"box {box_id} missing right after create"++ payload = f"filestore-e2e-{uuid.uuid4().hex[:8]}"+ await _exec_ok(box, f"printf %s {payload} > {GUEST_PATH}/probe.txt")++ await box.stop()+ await wait_for_box_state(rt, box_id, "stopped")+ await box.start()+ await wait_for_box_state(rt, box_id, "running")+ # A freshly started box gets the same short grace before its first+ # exec as in test_lifecycle_comprehensive; mirror it rather than race it.+ await asyncio.sleep(2)++ out = await _exec_ok(box, f"cat {GUEST_PATH}/probe.txt")+ assert out.strip() == payload, (+ f"filestore content did not survive stop/start: {out!r}"+ )+ finally:+ await _cleanup_resources(+ rt,+ box_ids=[box_id] if box_id else [],+ box_names=[] if box_id else [box_name],+ volume_id=volume_id,+ )+++async def test_filestore_volume_shares_data_across_boxes(rt, filestore_instance):+ """Two boxes mounting the same volume see the same bytes.++ The data directory is named by the volume id (filestoreDataDir), so the+ second box's mount lands in the first box's directory. This is the+ bucket-alignment contract — a destroyed box's data stays reachable by+ mounting the volume into a new box — and it had no coverage anywhere.+ """+ volume_name = f"e2e-fs-share-{uuid.uuid4().hex[:10]}"+ box1_name = f"e2e-fs-share-a-{uuid.uuid4().hex[:8]}"+ box2_name = f"e2e-fs-share-b-{uuid.uuid4().hex[:8]}"+ volume_id = None+ box1_id = None+ box2_id = None++ try:+ status, body = _create_filestore_volume(filestore_instance, name=volume_name)+ volume_id = body.get("id") if body else None+ assert 200 <= status < 300, f"filestore volume create failed: HTTP {status}: {body}"+ assert volume_id, f"volume create response has no id: {body}"++ status, body = _create_box_with_volume(volume_id, name=box1_name)+ box1_id = body.get("box_id") if body else None+ assert 200 <= status < 300, f"box1 create failed: HTTP {status}: {body}"+ assert box1_id, f"box1 create response has no box_id: {body}"+ box1 = await rt.get(box1_id)++ payload = f"shared-e2e-{uuid.uuid4().hex[:8]}"+ await _exec_ok(box1, f"printf %s {payload} > {GUEST_PATH}/shared.txt")++ status, body = _create_box_with_volume(volume_name, name=box2_name)+ box2_id = body.get("box_id") if body else None+ assert 200 <= status < 300, f"box2 create failed: HTTP {status}: {body}"+ assert box2_id, f"box2 create response has no box_id: {body}"+ box2 = await rt.get(box2_id)++ out = await _exec_ok(box2, f"cat {GUEST_PATH}/shared.txt")+ assert out.strip() == payload, (+ f"box2 must see box1's bytes through the shared volume: {out!r}"+ )++ # A destroyed box's data stays reachable: destroy box1, box2 still+ # reads what box1 wrote.+ await rt.remove(box1_id, force=True)+ leaked = await wait_until_unlisted(rt, [box1_id])+ assert not leaked, f"box1 was not destroyed before the readback: {leaked}"+ box1_id = None+ box1_name = None+ out = await _exec_ok(box2, f"cat {GUEST_PATH}/shared.txt")+ assert out.strip() == payload, f"data must survive box1's destroy: {out!r}"+ finally:+ await _cleanup_resources(+ rt,+ box_ids=[box_id for box_id in (box1_id, box2_id) if box_id],+ box_names=[+ name+ for box_id, name in ((box1_id, box1_name), (box2_id, box2_name))+ if not box_id and name+ ],+ volume_id=volume_id,+ )+++async def test_filestore_volume_lifecycle_rules(rt, filestore_instance):+ """Volume removal follows the same rules as bucket volumes: in-use refusal,+ removal once free.++ volume.service delete refuses while any non-destroyed box's volumes JSON+ carries the volume id, and tombstones the row once free (the NFS data+ directory is left in place for ops cleanup this release — documented in+ apps/runner/README.md). Force-deleting a missing volume is accepted.+ """+ volume_name = f"e2e-fs-del-{uuid.uuid4().hex[:10]}"+ box_name = f"e2e-fs-del-box-{uuid.uuid4().hex[:10]}"+ volume_id = None+ box_id = None++ try:+ status, body = _create_filestore_volume(filestore_instance, name=volume_name)+ volume_id = body.get("id") if body else None+ assert 200 <= status < 300, f"filestore volume create failed: HTTP {status}: {body}"+ assert volume_id, f"volume create response has no id: {body}"++ # In-use refusal: the delete arrives while a box mounts the volume.+ status, body = _create_box_with_volume(volume_id, name=box_name)+ box_id = body.get("box_id") if body else None+ assert 200 <= status < 300, f"box create failed: HTTP {status}: {body}"+ assert box_id, f"box create response has no box_id: {body}"++ status, body = request_json("DELETE", _volumes_path(f"/{volume_id}"))+ assert status == 409, (+ f"deleting a volume a live box mounts must be refused with 409, "+ f"got HTTP {status}: {body}"+ )++ # Free, then removed: destroy the box, delete succeeds.+ await (await rt.get(box_id)).remove(force=True)+ leaked = await wait_until_unlisted(rt, [box_id])+ assert not leaked, f"box was not destroyed before volume deletion: {leaked}"+ box_id = None+ box_name = None++ status, body = request_json("DELETE", _volumes_path(f"/{volume_id}"))+ assert status == 204, (+ f"deleting a free volume must answer 204, got HTTP {status}: {body}"+ )+ await asyncio.to_thread(_wait_for_volume_deleted, volume_id)++ status, body = request_json("GET", _volumes_path())+ assert status == 200 and body is not None, (+ f"listing volumes after deletion failed: HTTP {status}: {body}"+ )+ assert volume_id not in {volume.get("id") for volume in body}, (+ f"deleted volume {volume_id} remains in the default list"+ )++ # A second delete with force is accepted as already-deleted.+ status, body = request_json("DELETE", _volumes_path(f"/{volume_id}?force=true"))+ assert status == 204, (+ f"force-deleting an already-deleted volume must answer 204, got HTTP {status}: {body}"+ )+ finally:+ await _cleanup_resources(+ rt,+ box_ids=[box_id] if box_id else [],+ box_names=[] if box_id or box_name is None else [box_name],+ volume_id=volume_id,+ )diff --git a/apps/go.work.sum b/apps/go.work.sumindex 1831e8e88..513c8f6f3 100644--- a/apps/go.work.sum+++ b/apps/go.work.sum@@ -229,7 +229,6 @@ go.opentelemetry.io/contrib/detectors/gcp v1.43.0/go.mod h1:RyaZMFY7yi1kAs45S6mbgo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.54.0 h1:r6I7RJCN86bpD/FQwedZ0vSixDpwuWREjW9oRMsmqDc=go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.54.0/go.mod h1:B9yO6b04uB80CzjedvewuqDhxJxi11s7/GtiGa8bAjI=go.opentelemetry.io/otel v1.36.0/go.mod h1:/TcFMXYjyRNh8khOAO9ybYkqaDBb/70aVwkNML4pP8E=-go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0/go.mod h1:mBFWu/WOVDkWWsR7Tx7h6EpQB8wsv7P0Yrh0Pb7othc=go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw=@@ -240,11 +239,8 @@ go.opentelemetry.io/otel/metric v1.36.0/go.mod h1:zC7Ks+yeyJt4xig9DEw9kuUFe5C3zLgo.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=go.opentelemetry.io/otel/metric/x v0.68.0/go.mod h1:agudOmvWhwUTjgibWDzxD2PoWYnpw5Ht5jISYOD2Hd4=go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=-go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=-go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=go.opentelemetry.io/otel/trace v1.36.0/go.mod h1:gQ+OnDZzrybY4k4seLzPAWNwVBBVlF2szhehOBB/tGA=-go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=@@ -257,11 +253,13 @@ golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY=golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=+golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=+golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=@@ -270,6 +268,7 @@ golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=+golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=@@ -285,6 +284,7 @@ golang.org/x/telemetry v0.0.0-20260625142307-59b4966ccb57/go.mod h1:3AWMyWHS+caVgolang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=+golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=@@ -319,8 +319,8 @@ google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b/go.google.golang.org/genproto/googleapis/api v0.0.0-20251029180050-ab9386a59fda/go.mod h1:fDMmzKV90WSg1NbozdqrE64fkuTv6mlq2zxo9ad+3yo=google.golang.org/genproto/googleapis/api v0.0.0-20260120221211-b8f7ae30c516/go.mod h1:p3MLuOwURrGBRoEyFHBT3GjUwaCQVKeNqqWxlcISGdw=google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:kSJwQxqmFXeo79zOmbrALdflXQeAYcUbgS7PbpMknCY=-google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=+google.golang.org/genproto/googleapis/rpc v0.0.0-20250804133106-a7a43d27e69b/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=google.golang.org/genproto/googleapis/rpc v0.0.0-20260120221211-b8f7ae30c516/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=@@ -339,6 +339,7 @@ google.golang.org/grpc/stats/opentelemetry v0.0.0-20240907200651-3ffb98b2c93a h1google.golang.org/grpc/stats/opentelemetry v0.0.0-20240907200651-3ffb98b2c93a/go.mod h1:9i1T9n4ZinTUZGgzENMi8MDDgbGC5mqTS75JAv6xN3A=google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=+google.golang.org/protobuf v1.36.7/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc=