diff --git a/services/platform/app/features/settings/sandboxes/sandbox-quota-editor.test.tsx b/services/platform/app/features/settings/sandboxes/sandbox-quota-editor.test.tsx index 2a461be6eb..45dea51ff3 100644 --- a/services/platform/app/features/settings/sandboxes/sandbox-quota-editor.test.tsx +++ b/services/platform/app/features/settings/sandboxes/sandbox-quota-editor.test.tsx @@ -19,11 +19,15 @@ import { import { SandboxQuotaEditor } from './sandbox-quota-editor'; -const { state, save, refresh, toast } = vi.hoisted(() => ({ +const { state, save, refresh, toast, refetch } = vi.hoisted(() => ({ state: { canEdit: true, usage: { isLoading: false, + isError: false, + isFetching: false, + error: null as Error | null, + refetch: vi.fn(), data: undefined as | Array<{ budget: string; used: number; cap: number }> | undefined, @@ -32,6 +36,7 @@ const { state, save, refresh, toast } = vi.hoisted(() => ({ save: vi.fn(), refresh: vi.fn(), toast: vi.fn(), + refetch: vi.fn(), })); vi.mock('@/app/hooks/use-ability', () => ({ @@ -70,6 +75,11 @@ function EditorView(props: Partial>) { beforeEach(() => { state.canEdit = true; state.usage.isLoading = false; + state.usage.isError = false; + state.usage.isFetching = false; + state.usage.error = null; + state.usage.refetch = refetch; + refetch.mockReset().mockResolvedValue(undefined); state.usage.data = [ { budget: 'project', used: 1, cap: 2 }, { budget: 'workflow', used: 1, cap: 2 }, @@ -465,20 +475,164 @@ describe('SandboxQuotaEditor', () => { expect(screen.queryByText(/waiting for a free worker/)).toBeNull(); }); - it('shows unavailable allocation data without substituting defaults or a zero total', () => { - state.usage.data = undefined; - render(); - expect(screen.getAllByText('Allocation data unavailable')).toHaveLength(3); + it.each([ + new BackendApiError(503, 'Internal allocation reader payload'), + new Error('Allocation service is temporarily offline.'), + ])( + 'shows a safe allocation-read error and retries before recovering: %s', + async (error) => { + const recovered = [ + { budget: 'project', used: 1, cap: 3 }, + { budget: 'workflow', used: 0, cap: 4 }, + { budget: 'render', used: 0, cap: 2 }, + ]; + state.usage.data = undefined; + state.usage.isError = true; + state.usage.error = error; + const { user, rerender } = render(); + const alert = screen.getByRole('alert'); + expect(alert).toHaveTextContent("Couldn't load sandbox allocation data"); + if (error instanceof BackendApiError) { + expect(alert).not.toHaveTextContent( + 'Internal allocation reader payload', + ); + } else { + expect(alert).toHaveTextContent( + 'Allocation service is temporarily offline.', + ); + } + expect( + screen.queryByText('Allocation data unavailable'), + ).not.toBeInTheDocument(); + expect( + screen.queryByText(/Deployment capacity is unavailable/), + ).not.toBeInTheDocument(); + expect( + screen.queryByRole('button', { name: 'Save' }), + ).not.toBeInTheDocument(); + for (const input of screen.getAllByRole('spinbutton')) { + expect(input).toBeDisabled(); + expect(input).toHaveValue(null); + } + + let finishRetry = () => {}; + refetch.mockImplementationOnce(() => { + state.usage.isFetching = true; + state.usage.isLoading = true; + state.usage.isError = false; + state.usage.error = null; + return new Promise((resolve) => { + finishRetry = resolve; + }); + }); + const retry = screen.getByRole('button', { name: 'Retry' }); + await user.click(retry); + rerender(); + expect(refetch).toHaveBeenCalledOnce(); + expect(refresh).not.toHaveBeenCalled(); + expect(retry).toBeDisabled(); + expect(retry).toHaveAttribute('aria-busy', 'true'); + expect(screen.getByRole('alert')).toBe(alert); + if (!(error instanceof BackendApiError)) { + expect(alert).toHaveTextContent( + 'Allocation service is temporarily offline.', + ); + } + for (const input of screen.getAllByRole('spinbutton')) { + expect(input).toBeDisabled(); + } + await user.click(retry); + expect(refetch).toHaveBeenCalledOnce(); + expect( + screen.queryByRole('button', { name: 'Save' }), + ).not.toBeInTheDocument(); + + state.usage.data = recovered; + state.usage.isError = false; + state.usage.isFetching = false; + state.usage.isLoading = false; + state.usage.error = null; + finishRetry(); + rerender(); + await waitFor(() => + expect(screen.queryByRole('alert')).not.toBeInTheDocument(), + ); + expect( + screen.queryByRole('button', { name: 'Retry' }), + ).not.toBeInTheDocument(); + const workflow = screen.getByRole('spinbutton', { + name: 'Workflow sessions', + }); + await waitFor(() => expect(workflow).toHaveValue(4)); + for (const input of screen.getAllByRole('spinbutton')) + expect(input).toBeEnabled(); + expect( + screen.getByRole('status', { name: 'Total organization sessions' }), + ).toHaveTextContent('9 / 16'); + await user.clear(workflow); + await user.type(workflow, '5'); + await user.tab(); + await user.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => + expect(save).toHaveBeenCalledWith({ + organizationId: 'org-1', + policyType: 'sandbox_quota', + config: { + maxSessionsPerOrg: 3, + maxWorkflowSessionsPerOrg: 5, + maxRenderSessionsPerOrg: 2, + }, + }), + ); + }, + ); + + it('blocks editing and saving cached limits after an allocation refresh fails', async () => { + const { user, rerender } = render(); + const workflow = screen.getByRole('spinbutton', { + name: 'Workflow sessions', + }); + await user.clear(workflow); + await user.type(workflow, '3'); + await user.tab(); + expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled(); + state.usage.isError = true; + state.usage.error = new BackendApiError(503, 'Reader failed'); + rerender(); + expect(screen.getByRole('alert')).toHaveTextContent( + "Couldn't load sandbox allocation data", + ); expect(screen.queryByText(/Allocated:/)).not.toBeInTheDocument(); expect( screen.queryByRole('button', { name: 'Save' }), ).not.toBeInTheDocument(); - expect( - screen.getByRole('status', { name: 'Total organization sessions' }), - ).toHaveTextContent('Unavailable / 16'); - for (const input of screen.getAllByRole('spinbutton')) { + for (const input of screen.getAllByRole('spinbutton')) expect(input).toBeDisabled(); - expect(input).toHaveValue(null); - } + expect(save).not.toHaveBeenCalled(); }); + + it.each([undefined, [{ budget: 'project', used: 1, cap: 2 }]])( + 'shows successful incomplete allocation data without substituting defaults or a zero total: %j', + (data) => { + state.usage.data = data; + render(); + expect(screen.getAllByText('Allocation data unavailable')).toHaveLength( + data ? 2 : 3, + ); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + expect( + screen.queryByRole('button', { name: 'Retry' }), + ).not.toBeInTheDocument(); + expect( + screen.queryByRole('button', { name: 'Save' }), + ).not.toBeInTheDocument(); + expect( + screen.getByRole('status', { name: 'Total organization sessions' }), + ).toHaveTextContent('Unavailable / 16'); + for (const input of screen.getAllByRole('spinbutton')) { + expect(input).toBeDisabled(); + expect(input).toHaveValue(null); + } + }, + ); }); diff --git a/services/platform/app/features/settings/sandboxes/sandbox-quota-editor.tsx b/services/platform/app/features/settings/sandboxes/sandbox-quota-editor.tsx index 1f7b3acc4e..656ac33fec 100644 --- a/services/platform/app/features/settings/sandboxes/sandbox-quota-editor.tsx +++ b/services/platform/app/features/settings/sandboxes/sandbox-quota-editor.tsx @@ -4,11 +4,13 @@ import { sandboxQuotaTotal, type SandboxQuotaConfig, } from '@tale/shared/schemas/governance'; +import { Alert } from '@tale/ui/alert'; import { Badge } from '@tale/ui/badge'; +import { Button } from '@tale/ui/button'; import { useFormEditor, useRegisterGroupedEditor } from '@tale/ui/editor'; import { Input } from '@tale/ui/input'; import { Skeletonize } from '@tale/ui/skeleton-context'; -import { useCallback, useMemo } from 'react'; +import { useCallback, useMemo, useState } from 'react'; import { useWatch } from 'react-hook-form'; import { z } from 'zod'; @@ -19,6 +21,7 @@ import { import { SettingsSection } from '@/app/features/settings/components/settings-section'; import { useAbility } from '@/app/hooks/use-ability'; import { useBackendQuery } from '@/app/hooks/use-backend-query'; +import { failureDetail } from '@/app/lib/backend/adapters'; import { BackendApiError } from '@/app/lib/backend/api-client'; import type { ReturnsOf } from '@/app/lib/backend/contract'; import { useT } from '@/lib/i18n/client'; @@ -66,9 +69,27 @@ export function SandboxQuotaEditor({ { organizationId }, ); + // An initial failed query becomes pending again during refetch. Retain its + // failure until this retry settles so the recovery control stays visible. + const [retryFailure, setRetryFailure] = useState<{ + detail: string | undefined; + } | null>(null); + const readFailed = usage.isError || retryFailure !== null; + const retrying = usage.isFetching || retryFailure !== null; + const retryUsage = async () => { + if (retrying) return; + setRetryFailure({ detail: failureDetail(usage.error) }); + try { + await usage.refetch({ throwOnError: false }); + } finally { + setRetryFailure(null); + } + }; + // The usage endpoint exposes the same saved limits to readers and editors. // A missing response never becomes an editable set of schema defaults. const savedConfig = useMemo(() => { + if (readFailed) return undefined; const project = usage.data?.find((row) => row.budget === 'project'); const workflow = usage.data?.find((row) => row.budget === 'workflow'); const render = usage.data?.find((row) => row.budget === 'render'); @@ -78,7 +99,7 @@ export function SandboxQuotaEditor({ maxWorkflowSessionsPerOrg: workflow.cap, maxRenderSessionsPerOrg: render.cap, }; - }, [usage.data]); + }, [usage.data, readFailed]); const cannotManage = ability.cannot('write', 'orgSettings'); const canEdit = !cannotManage; // The organization's connected devices add their own slots: the server @@ -129,6 +150,9 @@ export function SandboxQuotaEditor({ async (values: SandboxQuotaConfig) => { // The grouped controller disables Save immediately, and this guard also // covers native form submission and a capacity update during editing. + if (savedConfig === undefined) { + throw new Error(t('limits.usageLoadFailed')); + } const total = sandboxQuotaTotal(values); if (maxSessions === undefined) { // No readable ceiling: only a total that does not grow may be saved. @@ -202,7 +226,10 @@ export function SandboxQuotaEditor({ }); const values = useWatch({ control: editor.form.control }); const parsed = schema.safeParse(values); - const total = parsed.success ? sandboxQuotaTotal(parsed.data) : undefined; + const total = + savedConfig !== undefined && parsed.success + ? sandboxQuotaTotal(parsed.data) + : undefined; const exceedsDeployment = total !== undefined && maxSessions !== undefined && total > maxSessions; // Without a readable ceiling, a total that does not grow beyond the saved @@ -239,21 +266,44 @@ export function SandboxQuotaEditor({ } = editor.form; return ( - + + {readFailed && ( + + + + )}
{QUOTA_FIELDS.map(({ field, budget }) => { - const current = usage.data?.find( - (row) => row.budget === budget, - ); + const current = + !readFailed && + usage.data?.find((row) => row.budget === budget); return ( - ) : ( + ) : !readFailed ? (

{t('limits.usageUnavailable')}

- )} + ) : null} {budget === 'project' && waitingForWorkers !== undefined && waitingForWorkers > 0 ? ( diff --git a/services/platform/app/hooks/use-backend-query.sandbox-quota.test.tsx b/services/platform/app/hooks/use-backend-query.sandbox-quota.test.tsx new file mode 100644 index 0000000000..a8f4a29168 --- /dev/null +++ b/services/platform/app/hooks/use-backend-query.sandbox-quota.test.tsx @@ -0,0 +1,103 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { act, renderHook, waitFor } from '@testing-library/react'; +import type { ReactNode } from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { useBackendQuery } from './use-backend-query'; + +beforeEach(() => { + window.__ENV__ = { BASE_PATH: '' }; +}); +afterEach(() => { + vi.restoreAllMocks(); + delete window.__ENV__; +}); + +function mountUsage() { + const client = new QueryClient({ + defaultOptions: { queries: { retryDelay: 0 } }, + }); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const hook = renderHook( + () => + useBackendQuery('sandbox/session_queries_public:getSandboxQuotaUsage', { + organizationId: 'org-a', + }), + { wrapper }, + ); + return { ...hook, client }; +} + +describe('sandbox allocation reads through the real backend query', () => { + it('surfaces failures, waits during retry, and recovers after repeated failure', async () => { + const fetch = vi + .spyOn(window, 'fetch') + .mockImplementation(async () => Response.json({}, { status: 503 })); + const { result, unmount, client } = mountUsage(); + try { + await waitFor(() => expect(result.current.isError).toBe(true)); + expect(result.current.data).toBeUndefined(); + expect(fetch).toHaveBeenCalledTimes(4); + expect(fetch.mock.calls[0]?.[0]).toBe( + '/api/app/sandbox/quota-usage?orgId=org-a', + ); + let finishRetry!: (response: Response) => void; + fetch.mockImplementationOnce( + () => + new Promise((resolve) => { + finishRetry = resolve; + }), + ); + let retry!: ReturnType; + act(() => { + retry = result.current.refetch(); + }); + await waitFor(() => expect(result.current.isFetching).toBe(true)); + expect(result.current.data).toBeUndefined(); + await act(async () => { + finishRetry(Response.json({}, { status: 503 })); + await retry; + }); + await waitFor(() => expect(result.current.isFetching).toBe(false)); + expect(result.current.isError).toBe(true); + expect(fetch).toHaveBeenCalledTimes(8); + const usage = [ + { + budget: 'project', + used: 1, + cap: 5, + atLimit: false, + nearLimit: false, + }, + ]; + fetch.mockResolvedValue(Response.json({ usage })); + await act(async () => { + await result.current.refetch(); + }); + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + expect(result.current.data).toEqual(usage); + expect(result.current.error).toBeNull(); + } finally { + unmount(); + client.clear(); + } + }); + + it.each([null, {}, { usage: null }])( + 'keeps successful absent allocations unavailable: %j', + async (body) => { + vi.spyOn(window, 'fetch').mockResolvedValue(Response.json(body)); + const { result, unmount, client } = mountUsage(); + try { + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + expect(result.current.data).toBeNull(); + expect(result.current.isError).toBe(false); + } finally { + unmount(); + client.clear(); + } + }, + ); +}); diff --git a/services/platform/app/lib/backend/settings.ts b/services/platform/app/lib/backend/settings.ts index 4446b8ba90..59265b1d60 100644 --- a/services/platform/app/lib/backend/settings.ts +++ b/services/platform/app/lib/backend/settings.ts @@ -590,10 +590,7 @@ export const settingsReadAdapters: Record = { queryFn: () => backendFetch<{ usage: QuotaUsageResult }>('/sandbox/quota-usage', { orgId, - }).then( - (body) => body.usage, - () => null, - ), + }).then((body) => body?.usage ?? null), refetchInterval: 15_000, }; }, diff --git a/services/platform/messages/de/sandboxes.yml b/services/platform/messages/de/sandboxes.yml index 9314a68cf7..16b3ff91c0 100644 --- a/services/platform/messages/de/sandboxes.yml +++ b/services/platform/messages/de/sandboxes.yml @@ -21,6 +21,8 @@ limits: usageUnavailable: Kontingentbelegung nicht verfügbar # Unter dem Limit der Agenten-Worker: die Läufe, die ein höheres Limit sofort starten würde. waitingForWorkers: '{count, plural, one {# Agentenlauf wartet auf einen freien Worker.} other {# Agentenläufe warten auf einen freien Worker.}}' + usageLoadFailed: Kontingentbelegung konnte nicht geladen werden + usageRetry: Erneut versuchen invalidSessions: Gib eine ganze Zahl zwischen 1 und 500 ein. total: Sitzungen deiner Organisation insgesamt totalValue: '{total} / {maxSessions}' diff --git a/services/platform/messages/en/sandboxes.yml b/services/platform/messages/en/sandboxes.yml index a696c5175b..0e232d5464 100644 --- a/services/platform/messages/en/sandboxes.yml +++ b/services/platform/messages/en/sandboxes.yml @@ -18,6 +18,8 @@ limits: usageUnavailable: Allocation data unavailable # Under the agent workers limit: the runs a higher limit would start now. waitingForWorkers: '{count, plural, one {# agent run is waiting for a free worker.} other {# agent runs are waiting for a free worker.}}' + usageLoadFailed: Couldn't load sandbox allocation data + usageRetry: Retry invalidSessions: Must be a whole number between 1 and 500. total: Total organization sessions totalValue: '{total} / {maxSessions}' diff --git a/services/platform/messages/fr/sandboxes.yml b/services/platform/messages/fr/sandboxes.yml index 6d42d6037a..f0bd66ee67 100644 --- a/services/platform/messages/fr/sandboxes.yml +++ b/services/platform/messages/fr/sandboxes.yml @@ -20,6 +20,8 @@ limits: usageUnavailable: Allocation indisponible # Sous la limite des workers d'agent : les exécutions qu'une limite plus haute démarrerait tout de suite. waitingForWorkers: '{count, plural, one {# exécution d’agent attend un worker libre.} other {# exécutions d’agent attendent un worker libre.}}' + usageLoadFailed: Impossible de charger les données d'allocation des sandboxes + usageRetry: Réessayer invalidSessions: Saisis un nombre entier entre 1 et 500. total: Total des sessions de ton organisation totalValue: '{total} / {maxSessions}' diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index c0113828c2..8d44a60eca 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -134,6 +134,13 @@ the real ContactsTable selection and failure-only retry are covered by `app/features/contacts/components/contact-table.bulk-delete.test.tsx`. Real-browser focus, layout and visual transitions remain manual. +Sandbox quota allocation reads show an accessible error with Retry when they fail, +keep quota editing and grouped Save disabled through retry, and recover to the +fetched limits before saving. Failed cached reads cannot enable edits; successful +missing or incomplete allocation responses remain a separate unavailable state. +`app/features/settings/sandboxes/sandbox-quota-editor.test.tsx` owns these controls. +Real-browser layout and screen-reader announcements remain manual. + Website content search clears submitted results when the input changes to a different query, without issuing another request until Enter. Whitespace-only edits retain results; clearing the input and late responses after edits are diff --git a/tools/cli/scripts/cli-workflow.test.ts b/tools/cli/scripts/cli-workflow.test.ts index 1c7b3c0148..a1b386b169 100644 --- a/tools/cli/scripts/cli-workflow.test.ts +++ b/tools/cli/scripts/cli-workflow.test.ts @@ -492,6 +492,7 @@ describe('CLI command test targets', () => { 'deployment.test.ts', 'doctor.test.ts', 'hash-password.test.ts', + 'observation.test.ts', 'platform-configuration.test.ts', 'provision.test.ts', ]);