Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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', () => ({
Expand Down Expand Up @@ -70,6 +75,11 @@ function EditorView(props: Partial<ComponentProps<typeof SandboxQuotaEditor>>) {
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 },
Expand Down Expand Up @@ -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(<EditorView />);
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(<EditorView />);
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<void>((resolve) => {
finishRetry = resolve;
});
});
const retry = screen.getByRole('button', { name: 'Retry' });
await user.click(retry);
rerender(<EditorView />);
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(<EditorView />);
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(<EditorView />);
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(<EditorView />);
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(<EditorView />);
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);
}
},
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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';
Expand Down Expand Up @@ -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<SandboxQuotaConfig | undefined>(() => {
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');
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -239,21 +266,44 @@ export function SandboxQuotaEditor({
} = editor.form;

return (
<Skeletonize loading={usage.isLoading} label={t('limits.title')}>
<Skeletonize
loading={usage.isLoading && !readFailed}
label={t('limits.title')}
>
<SettingsSection
title={t('limits.title')}
description={t('limits.description')}
>
{readFailed && (
<Alert
variant="destructive"
title={t('limits.usageLoadFailed')}
description={
usage.isError ? failureDetail(usage.error) : retryFailure?.detail
}
>
<Button
type="button"
variant="secondary"
className="mt-3"
isLoading={retrying}
disabled={retrying}
onClick={() => void retryUsage()}
>
{t('limits.usageRetry')}
</Button>
</Alert>
)}
<form id={FORM_ID} onSubmit={editor.submit}>
<fieldset
disabled={!canEdit || editor.isLoading}
disabled={!canEdit || editor.isLoading || savedConfig === undefined}
className="contents"
>
<SettingsFieldList>
{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 (
<SettingsFieldRow
key={field}
Expand Down Expand Up @@ -292,11 +342,11 @@ export function SandboxQuotaEditor({
limit: current.cap,
})}
</Badge>
) : (
) : !readFailed ? (
<p className="text-muted-foreground text-xs">
{t('limits.usageUnavailable')}
</p>
)}
) : null}
{budget === 'project' &&
waitingForWorkers !== undefined &&
waitingForWorkers > 0 ? (
Expand Down
Loading