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
63 changes: 63 additions & 0 deletions apps/api/tests/unit/routes/ai-proxy-usage-limit-markers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* The VM agent tells a SAM AI usage-limit refusal from a provider overload by the refusal's
* message (packages/vm-agent/internal/acp/sam_usage_limit.go, samUsageLimitMarkers). Both are
* 429s, so if a message here drifts away from those markers, users see "Provider overloaded"
* again (idea 01M89JXTFHW4W3PQ65GTED6D0K). The markers are read from the Go source itself.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';

import { monthlyCostCapMessage } from '@simple-agent-manager/ai-proxy';
import { describe, expect, it } from 'vitest';

import { anthropicUsageGateError as anthropicSupportError } from '../../../src/routes/ai-proxy-anthropic-support';
import {
anthropicUsageGateError,
openaiUsageGateError,
} from '../../../src/routes/ai-proxy-passthrough-errors';

/** The marker list as the VM agent compiles it, read from its source rather than copied. */
function goMarkers(): string[] {
const source = readFileSync(
resolve(__dirname, '../../../../../packages/vm-agent/internal/acp/sam_usage_limit.go'),
'utf8'
);
const block = /var samUsageLimitMarkers = \[\]string\{([^}]*)\}/.exec(source)?.[1] ?? '';
return [...block.matchAll(/"([^"]+)"/g)].map((m) => m[1]!);
}
const GO_MARKERS = goMarkers();

it('reads the VM agent marker list (a broken parse cannot pass as an empty list)', () => {
expect(GO_MARKERS).toHaveLength(3);
expect(GO_MARKERS.every((m) => m === m.toLowerCase())).toBe(true);
});

const administrator = { allowed: false, limitSource: 'administrator' } as Parameters<
typeof monthlyCostCapMessage
>[0];

describe('SAM AI usage-limit refusals carry a marker the VM agent recognizes', () => {
it.each([
['administrator ceiling', monthlyCostCapMessage(administrator)],
['personal cap', monthlyCostCapMessage(undefined)],
])('monthly message: %s', (_name, message) => {
expect(GO_MARKERS.some((marker) => message.toLowerCase().includes(marker))).toBe(true);
});

it.each([
['anthropic passthrough', anthropicUsageGateError],
['anthropic support', anthropicSupportError],
['openai passthrough', openaiUsageGateError],
])('%s: every refusal is a 429 whose message has a marker', async (_name, build) => {
for (const response of [
build('daily-token-budget'),
build('monthly-cost-cap', administrator),
build('monthly-cost-cap'),
]) {
expect(response.status).toBe(429);
const body = (await response.json()) as { error: { message: string } };
const message = body.error.message.toLowerCase();
expect(GO_MARKERS.some((marker) => message.includes(marker))).toBe(true);
}
});
});
12 changes: 12 additions & 0 deletions apps/api/tests/unit/services/inbox-system-errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,18 @@ describe('failed tasks file one error item for their owner', () => {
expect(errorAsks()[0]!.failure_count).toBe(1);
});

// Idea 01M89JXTFHW4W3PQ65GTED6D0K: a task that stops on SAM's AI usage limit has failed, and its
// owner must hear about it, without being told to retry.
it('files a task stopped by the SAM AI usage limit, with the limit sentence', async () => {
task('t-limit', { status: 'in_progress', started_at: new Date().toISOString() });
await markTaskFailedIfNonTerminal(env.DATABASE, 't-limit', 'sam_ai_usage_limit_reached');
expect((await runInboxSystemErrorSweep(env)).filed).toBe(1);
const [item] = (await listInbox(ctx('owner'), { projectId: P1 })).items;
expect(item?.taskId).toBe('t-limit');
expect(item?.body).toMatch(/AI usage limit was reached/);
expect(edges.createNotification).toHaveBeenCalledTimes(1);
});

it('does not offer Retry to a task owner who cannot run the project owner’s retry', async () => {
task('t-colleague', { user_id: 'colleague' });
await markTaskFailedIfNonTerminal(env.DATABASE, 't-colleague', 'Session creation failed');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ function BudgetBar({
}) {
const pct = limit > 0 ? Math.min(100, (used / limit) * 100) : 0;
const format = unit === '$' ? formatCost : formatTokens;
const barColor = pct >= 100 ? 'bg-danger' : pct >= 80 ? 'bg-warning' : 'bg-accent-emphasis';
const barColor = pct >= 100 ? 'bg-danger' : pct >= 80 ? 'bg-warning' : 'bg-accent';

return (
<div className="space-y-1">
Expand Down
10 changes: 5 additions & 5 deletions apps/web/src/components/ai-usage/AiUsageSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export function AiUsageSection() {
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div>
<SectionHeading>LLM Usage</SectionHeading>
<Body className="text-fg-muted text-sm">SAM-managed AI Gateway traffic only</Body>
<Body className="text-fg-muted text-sm">Model calls made through SAM only</Body>
</div>
<div className="flex gap-1 flex-wrap">
{AI_PERIODS.map((opt) => (
Expand All @@ -60,7 +60,7 @@ export function AiUsageSection() {
onClick={() => handlePeriodChange(opt.value)}
className={`px-3 py-2.5 rounded-md text-sm font-medium transition-colors min-h-[44px] ${
period === opt.value
? 'bg-accent-emphasis text-fg-on-accent'
? 'bg-accent text-fg-on-accent'
: 'bg-surface text-fg-muted hover:bg-surface-hover border border-border-default'
}`}
>
Expand All @@ -87,8 +87,8 @@ export function AiUsageSection() {
<Bot className="w-10 h-10 mx-auto mb-3 text-fg-muted" aria-hidden="true" />
<Body className="text-fg-muted font-medium">No LLM usage yet</Body>
<Body className="text-fg-muted text-sm mt-1">
Usage from SAM-managed AI Gateway requests will appear here. Direct BYOK or non-Gateway
usage is not tracked.
Usage from model calls made through SAM will appear here. Calls made directly to a
provider, outside SAM, are not tracked.
</Body>
</Card>
)}
Expand Down Expand Up @@ -176,7 +176,7 @@ export function AiUsageSection() {
role="presentation"
>
<div
className="h-full bg-accent-emphasis rounded"
className="h-full bg-accent rounded"
style={{ width: `${Math.max(1, (d.costUsd / maxCost) * 100)}%` }}
/>
</div>
Expand Down
13 changes: 11 additions & 2 deletions apps/web/src/components/debug/FailureCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ export function FailureCard({
);

const style = useMemo(() => getClassificationStyle(classification), [classification]);
// The session can continue, but "send another message to retry" is wrong when retrying
// cannot help (for example SAM's AI usage limit).
const retryInSession = recoverable && classification.retryable;
const settingsAction = isSessionCreator ? authSettingsAction(classification.code) : null;

const handleCopyReport = useCallback(async () => {
Expand Down Expand Up @@ -165,7 +168,7 @@ export function FailureCard({
<span className="text-xs font-semibold" style={{ color: style.label }}>
{classification.label}
</span>
{recoverable && (
{retryInSession && (
<span className="text-[10px] px-1.5 py-0.5 rounded-full bg-warning-tint text-warning-fg font-medium">
Recoverable
</span>
Expand Down Expand Up @@ -327,12 +330,18 @@ export function FailureCard({
)}

{/* Recoverable guidance */}
{recoverable && (
{retryInSession && (
<p className="text-[11px] m-0 leading-snug text-fg-muted italic">
This session is still active. Send another message to retry — your workspace is
preserved.
</p>
)}
{recoverable && !classification.retryable && (
<p className="text-[11px] m-0 leading-snug text-fg-muted italic">
This session is still open. Fix the cause above, then send a message — your workspace
is preserved.
</p>
)}
</div>
)}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ function AttachmentItem({ attachment: a, onOpen, onRemove, disabled }: ItemProps
</span>
{(a.status === 'uploading' || a.status === 'pending') && (
<span
className="absolute bottom-0 left-0 h-0.5 bg-accent-emphasis transition-all"
className="absolute bottom-0 left-0 h-0.5 bg-accent transition-all"
style={{ width: `${a.progress}%` }}
/>
)}
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/components/task/TaskSubmitForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ export const TaskSubmitForm: FC<TaskSubmitFormProps> = ({
</button>
{att.status === 'uploading' && (
<div
className="absolute bottom-0 left-0 h-0.5 bg-accent-emphasis rounded-full transition-all"
className="absolute bottom-0 left-0 h-0.5 bg-accent rounded-full transition-all"
style={{ width: `${att.progress}%` }}
/>
)}
Expand Down
58 changes: 55 additions & 3 deletions apps/web/tests/playwright/ai-usage-audit.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { expect, type Page, type Route, test } from '@playwright/test';

import { assertNoOverflow as assertNoClippedOrDocumentOverflow, seedTheme } from './audit-helpers';

// ---------------------------------------------------------------------------
// Mock Data
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -138,6 +140,10 @@ type MockOptions = {

async function setupMocks(page: Page, options: MockOptions = {}) {
const aiUsageData = options.aiUsage ?? makeAiUsageResponse();
// Without this the first-run setup dialog covers the page and screenshots show the dialog.
await page.addInitScript(() => {
localStorage.setItem('sam-onboarding-wizard-dismissed-user-test-1', 'true');
});

await page.route('**/api/**', async (route: Route) => {
const url = new URL(route.request().url());
Expand All @@ -156,6 +162,25 @@ async function setupMocks(page: Page, options: MockOptions = {}) {
if (path === '/api/projects') return respond(200, { projects: [] });
if (path.endsWith('/health')) return respond(200, { status: 'ok' });

// Budget settings (AiBudgetSettingsSection), the shape GET /api/usage/ai/budget returns.
if (path === '/api/usage/ai/budget') {
return respond(200, {
settings: {
dailyInputTokenLimit: null,
dailyOutputTokenLimit: null,
monthlyCostCapUsd: 10,
alertThresholdPercent: 80,
},
isCustom: true,
dailyUsage: { inputTokens: 120_000, outputTokens: 40_000 },
effectiveLimits: { dailyInputTokenLimit: 500_000, dailyOutputTokenLimit: 200_000 },
monthCostUsd: 4.2,
monthlyCostCap: { available: true, ceilingUsd: null, effectiveCapUsd: 10 },
utilization: { dailyInputPercent: 24, dailyOutputPercent: 20, monthlyCostPercent: 42 },
exceeded: false,
});
}

// AI usage endpoint
if (path === '/api/usage/ai') {
if (options.aiUsageError) return respond(500, { error: 'Gateway error' });
Expand Down Expand Up @@ -332,7 +357,10 @@ test.describe('AI Usage — Mobile (375x667)', () => {
test('disclaimer text visible', async ({ page }) => {
await setupMocks(page);
await goToUsage(page);
await expect(page.locator('text=SAM-managed AI Gateway traffic only')).toBeVisible();
await expect(
page.getByText('Model calls made through SAM only', { exact: true })
).toBeVisible();
await expect(page.getByText('AI Gateway', { exact: false })).toHaveCount(0);
await screenshot(page, 'ai-usage-disclaimer-mobile');
await assertNoOverflow(page);
});
Expand All @@ -350,8 +378,8 @@ test.describe('AI Usage — Desktop (1280x800)', () => {
await goToUsage(page);
await expect(page.locator('text=LLM Usage')).toBeVisible();
await expect(page.locator('text=Total Cost')).toBeVisible();
await expect(page.locator('text=Input Tokens')).toBeVisible();
await expect(page.locator('text=Output Tokens')).toBeVisible();
await expect(page.getByText('Input Tokens', { exact: true })).toBeVisible();
await expect(page.getByText('Output Tokens', { exact: true })).toBeVisible();
await screenshot(page, 'ai-usage-normal-desktop');
await assertNoOverflow(page);
});
Expand Down Expand Up @@ -384,3 +412,27 @@ test.describe('AI Usage — Desktop (1280x800)', () => {
await assertNoOverflow(page);
});
});

// Idea 01M89JXTFHW4W3PQ65GTED6D0K: the selected period button used `bg-accent-emphasis`, which is
// not a defined token, so its white label sat on no background (invisible in the light theme).
for (const theme of ['light', 'dark'] as const) {
test(`selected period button is readable (${theme} theme)`, async ({ page }, testInfo) => {
await seedTheme(page, theme);
await setupMocks(page);
await goToUsage(page);
const selected = page.getByRole('button', { name: 'This Month', pressed: true });
await expect(selected).toBeVisible();
const colors = await selected.evaluate((el) => {
const style = getComputedStyle(el);
return { bg: style.backgroundColor, fg: style.color };
});
// A painted background, distinct from the label colour.
expect(colors.bg).not.toBe('rgba(0, 0, 0, 0)');
expect(colors.bg).not.toBe(colors.fg);
await page.getByRole('button', { name: '7 Days' }).click();
await expect(page.getByRole('button', { name: '7 Days', pressed: true })).toBeVisible();
await assertNoClippedOrDocumentOverflow(page);
const viewport = testInfo.project.name.includes('Desktop') ? 'desktop' : 'mobile';
await screenshot(page, `ai-usage-period-${theme}-${viewport}`);
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,27 @@ async function assertNoHorizontalOverflow(page: Page) {
}

test.describe('Project chat recoverable error banner', () => {
// Idea 01M89JXTFHW4W3PQ65GTED6D0K: SAM's own AI usage limit read as "Provider overloaded".
for (const [code, label, recoverable] of [
['sam_ai_usage_limit_reached', 'AI usage limit reached', false],
['provider_overloaded', 'Provider overloaded', true],
] as const) {
test(`failure card for ${code}`, async ({ page }, testInfo) => {
await setupApiMocks(
page,
{ ...MOCK_TASK, errorMessage: code, executionStep: code },
true,
MOCK_MESSAGES
);
await page.goto('/projects/proj-test-1/chat/session-recoverable-1');
await expect(page.getByText(label, { exact: true })).toBeVisible();
await expect(page.getByText('Recoverable', { exact: true })).toHaveCount(recoverable ? 1 : 0);
await assertNoHorizontalOverflow(page);
const viewport = testInfo.project.name.includes('Desktop') ? 'desktop' : 'mobile';
await screenshot(page, `chat-failure-${code}-${viewport}`);
});
}

test('startup missing credential reaches existing agent connections', async ({ page }, testInfo) => {
const systemMessage = {
...MOCK_MESSAGES[0],
Expand Down
1 change: 0 additions & 1 deletion apps/web/tests/playwright/visual-audit-quarantine.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ admin-users-signup-approval-audit.spec.ts
agent-context-audit.spec.ts
agent-crash-report-audit.spec.ts
agent-guided-connect-audit.spec.ts
ai-usage-audit.spec.ts
auth-flows-audit.spec.ts
chat-dom-bound-audit.spec.ts
chat-file-viewer-audit.spec.ts
Expand Down
45 changes: 45 additions & 0 deletions apps/web/tests/unit/debug-failure-card.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,51 @@ describe('FailureCard', () => {
expect(screen.getByText('Recoverable')).toBeInTheDocument();
});

// Idea 01M89JXTFHW4W3PQ65GTED6D0K: SAM's own usage limit is not a provider overload, and
// retrying in the same conversation cannot help until the limit changes.
it('shows the AI usage limit without a Recoverable badge or retry advice', async () => {
renderWithQuery(
<FailureCard
projectId="proj-1"
taskEmbed={makeTaskEmbed({
status: 'in_progress',
taskMode: 'conversation',
errorMessage: 'sam_ai_usage_limit_reached',
executionStep: 'sam_ai_usage_limit_reached',
})}
recoverable={true}
/>
);

expect(screen.getByText('AI usage limit reached')).toBeInTheDocument();
expect(screen.queryByText('Provider overloaded')).not.toBeInTheDocument();
expect(screen.queryByText('Recoverable')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { expanded: false }));
expect(await screen.findByText(/Settings > Usage/)).toBeInTheDocument();
expect(screen.queryByText(/Send another message to retry/)).not.toBeInTheDocument();
expect(screen.getByText(/This session is still open. Fix the cause above/)).toBeInTheDocument();
});

it('control: a real provider overload still reads as recoverable', async () => {
renderWithQuery(
<FailureCard
projectId="proj-1"
taskEmbed={makeTaskEmbed({
status: 'in_progress',
taskMode: 'conversation',
errorMessage: 'provider_overloaded',
executionStep: 'provider_overloaded',
})}
recoverable={true}
/>
);

expect(screen.getByText('Provider overloaded')).toBeInTheDocument();
expect(screen.getByText('Recoverable')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { expanded: false }));
expect(await screen.findByText(/Send another message to retry/)).toBeInTheDocument();
});

it('expands detail on click', async () => {
renderWithQuery(
<FailureCard
Expand Down
6 changes: 6 additions & 0 deletions apps/web/tests/unit/lib/chat-session-utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,12 @@ describe('getAttentionState', () => {

it.each([
['task failed', { task: { id: 't-1', status: 'failed' } }, 'failed'],
// SAM's AI usage limit ended the task: a failure the owner must see, not a normal stop.
[
'task failed on the SAM AI usage limit',
{ task: { id: 't-1', status: 'failed', errorMessage: 'sam_ai_usage_limit_reached' } },
'failed',
],
['task completed', { task: { id: 't-1', status: 'completed' } }, 'completed'],
['task cancelled', { task: { id: 't-1', status: 'cancelled' } }, 'stopped'],
['session failed', { status: 'failed' }, 'error'],
Expand Down
4 changes: 4 additions & 0 deletions apps/www/src/content/docs/docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -2273,6 +2273,10 @@ logged as `ai_proxy.monthly_cost_ceiling_unreadable`. The same protection applie
isolate; no extra last-known ceiling is reused during an outage (`services/ai-proxy-ports.ts`).
Gateway calls and locally own-funded calls do not read this ceiling. A failed monthly-spend read
also refuses inference with a retryable 503, without reporting that the cap has been reached.
A call refused by the monthly cap or the daily token budget is a 429 whose message names that
limit. The VM agent reports it as `sam_ai_usage_limit_reached`, not `provider_overloaded`, so the
chat shows "AI usage limit reached" without a retry suggestion
(`packages/vm-agent/internal/acp/sam_usage_limit.go`, `packages/shared/src/failure-classification.ts`).
Once a ceiling is set, every gated call on such an installation reads the month's
priced total (one Durable Object call), not only calls by users with their own cap. Passthrough
calls served by a platform-owned credential are priced too; a user's or project's own credential
Expand Down
Loading
Loading