Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(settings): preserve actionable apply and usage errors (#1984, #1907)

Bingxi Zhao (Frank)df7621d3acda
diff --git a/web/features/settings/sections/UsageSettingsSection.tsx b/web/features/settings/sections/UsageSettingsSection.tsx
index 8cf7bfd79..793210779 100644
--- a/web/features/settings/sections/UsageSettingsSection.tsx
+++ b/web/features/settings/sections/UsageSettingsSection.tsx
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next'
import { SettingsPageHeader } from '@/components/settings/shared'
import { fetchUsageStatistics, usageYear, type UsageStatistics } from '@/lib/usage-statistics'
import UsageActivity from '../components/UsageActivity'
+import { isApiError } from '@/shared/api/errors'
export default function UsageSettingsSection() {
const { t, i18n } = useTranslation()
@@ -17,7 +18,7 @@ export default function UsageSettingsSection() {
const [snapshot, setSnapshot] = useState<{
key: string
data: UsageStatistics | null
- error: boolean
+ error: string | null
} | null>(null)
const [revision, setRevision] = useState(0)
const requestKey = `${year}:${revision}`
@@ -28,11 +29,17 @@ export default function UsageSettingsSection() {
const controller = new AbortController()
fetchUsageStatistics(year, controller.signal)
.then(value => {
- if (!controller.signal.aborted) setSnapshot({ key: requestKey, data: value, error: false })
+ if (!controller.signal.aborted) setSnapshot({ key: requestKey, data: value, error: null })
})
- .catch(() => {
+ .catch((failure: unknown) => {
if (!controller.signal.aborted)
- setSnapshot(previous => ({ key: requestKey, data: previous?.data ?? null, error: true }))
+ setSnapshot(previous => ({
+ key: requestKey,
+ data: previous?.data ?? null,
+ error: failure instanceof Error
+ ? `${failure.message}${isApiError(failure) && failure.status ? ` (HTTP ${failure.status})` : ''}`
+ : 'Unable to load usage statistics.',
+ }))
})
return () => controller.abort()
}, [year, requestKey])
@@ -90,7 +97,10 @@ export default function UsageSettingsSection() {
role="alert"
className="mb-5 flex items-center justify-between rounded-lg bg-[var(--destructive)]/5 px-3 py-2 text-xs text-[var(--destructive)]"
>
- <span>{t('Unable to load usage statistics.')}</span>
+ <span>
+ {t('Unable to load usage statistics.')}
+ {snapshot?.error && <span className="mt-1 block break-words">{t(snapshot.error)}</span>}
+ </span>
<button
type="button"
onClick={() => setRevision(value => value + 1)}
diff --git a/web/features/settings/store/SettingsStore.tsx b/web/features/settings/store/SettingsStore.tsx
index aebcb74e8..60dec4425 100644
--- a/web/features/settings/store/SettingsStore.tsx
+++ b/web/features/settings/store/SettingsStore.tsx
@@ -25,6 +25,7 @@ import {
} from "@/context/app-shell-storage";
import { useAppShell } from "@/context/AppShellContext";
import { apiFetch, apiUrl } from "@/lib/api";
+import { asJsonOrThrow } from "@/shared/api/client";
import { invalidateLLMOptionsCache } from "@/lib/llm-options";
import { setModelReasoningEffort } from "@/lib/reasoning-effort";
import { applyExtensionPayload } from "@/lib/settings-extensions";
@@ -1763,7 +1764,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
body: JSON.stringify(draftEnvelope()),
});
- if (!draftResponse.ok) throw new Error(`HTTP ${draftResponse.status}`);
+ await asJsonOrThrow(draftResponse);
// Pages still on screen save themselves — they refresh their own local
// state and surface their own errors. Everything else pending is
@@ -1779,8 +1780,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
method: "POST",
headers: { "Content-Type": "application/json" },
});
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
- const payload = await response.json();
+ const payload = await asJsonOrThrow(response);
if (!payload.catalog)
throw new Error("Missing catalog in apply response");
setCatalog(payload.catalog);
diff --git a/web/lib/usage-statistics.ts b/web/lib/usage-statistics.ts
index 052373707..1cb0aa20e 100644
--- a/web/lib/usage-statistics.ts
+++ b/web/lib/usage-statistics.ts
@@ -1,5 +1,5 @@
import type { components } from '@/contracts/generated/api'
-import { apiFetch, apiUrl } from '@/lib/api'
+import { requestJson } from '@/shared/api/client'
export type UsageStatistics = components['schemas']['UsageStatistics']
export type DailyUsage = components['schemas']['DailyUsage']
@@ -10,9 +10,7 @@ export async function fetchUsageStatistics(
): Promise<UsageStatistics> {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
const query = new URLSearchParams({ year: String(year), timezone })
- const response = await apiFetch(apiUrl(`/api/settings/usage?${query}`), { signal })
- if (!response.ok) throw new Error(`Usage request failed (${response.status})`)
- return response.json()
+ return requestJson<UsageStatistics>(`/api/settings/usage?${query}`, { signal, scope: 'settings' })
}
export function usageYear(value: string | null, current: number): number {
diff --git a/web/tests/settings-unified-draft.spec.tsx b/web/tests/settings-unified-draft.spec.tsx
index 84f31c6bd..05fca370d 100644
--- a/web/tests/settings-unified-draft.spec.tsx
+++ b/web/tests/settings-unified-draft.spec.tsx
@@ -26,7 +26,7 @@ vi.mock("@/lib/api", () => ({
apiFetch: (...args: unknown[]) => mocks.fetch(...args),
}));
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) }));
-const t = (key: string) => key;
+const t = (key: string, values?: Record<string, unknown>) => key.replace(/{{(.*?)}}/g, (_, name) => String(values?.[name] ?? name));
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t, i18n: { language: "en" } }),
}));
@@ -199,6 +199,27 @@ it("keeps failed changes pending and allows retry", async () => {
expect(settings.draftState).toBe("clean");
});
+it.each(["/api/settings/draft", "/api/settings/apply"])("shows a denied %s write without losing the editable draft", async endpoint => {
+ live.services.llm.profiles.push({ id: "saved", name: "Saved profile", binding: "custom", base_url: "", api_key: "", api_version: "", models: [] });
+ render(<App page="" />);
+ await ready();
+ await act(async () => settings.mutateCatalog(next => {
+ next.services.llm.profiles[0].name = "Retained draft";
+ }));
+ const original = mocks.fetch.getMockImplementation()!;
+ mocks.fetch.mockImplementation((url, init) => url === endpoint && init?.method !== "GET"
+ ? { ...reply({ detail: "Check the service account write permissions; your draft was retained." }, false), status: 503 }
+ : original(url, init));
+ await act(() => settings.applyCatalog());
+ expect(settings.toast).toContain("service account write permissions");
+ expect(settings.draft.services.llm.profiles[0].name).toBe("Retained draft");
+ expect(live.services.llm.profiles[0].name).not.toBe("Retained draft");
+ mocks.fetch.mockImplementation(original);
+ await act(() => settings.applyCatalog());
+ expect(settings.draftState).toBe("clean");
+ expect(live.services.llm.profiles[0].name).toBe("Retained draft");
+});
+
it("stages language and appearance without changing browser preferences until Apply", async () => {
render(<App page="appearance" />);
await ready();
diff --git a/web/tests/usage-statistics-http.spec.ts b/web/tests/usage-statistics-http.spec.ts
new file mode 100644
index 000000000..645dcfe23
--- /dev/null
+++ b/web/tests/usage-statistics-http.spec.ts
@@ -0,0 +1,22 @@
+import { afterEach, expect, it, vi } from 'vitest'
+import { fetchUsageStatistics } from '@/lib/usage-statistics'
+
+afterEach(() => vi.unstubAllGlobals())
+
+it('keeps actionable HTTP refusal details from the actual usage request', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ detail: 'Workspace access was revoked. Select an accessible workspace.',
+ }), { status: 403, headers: { 'x-request-id': 'usage-refused' } })))
+ await expect(fetchUsageStatistics(2026)).rejects.toMatchObject({
+ message: 'Workspace access was revoked. Select an accessible workspace.',
+ status: 403,
+ correlationId: 'usage-refused',
+ })
+})
+
+it('reports non-JSON proxy failures without exposing the proxy page as usage data', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('<html>private proxy diagnostic</html>', {
+ status: 502, statusText: 'Bad Gateway',
+ })))
+ await expect(fetchUsageStatistics(2026)).rejects.toMatchObject({ message: 'Bad Gateway', status: 502 })
+})
diff --git a/web/tests/usage-statistics.spec.tsx b/web/tests/usage-statistics.spec.tsx
index 62f741eb3..66c951bc8 100644
--- a/web/tests/usage-statistics.spec.tsx
+++ b/web/tests/usage-statistics.spec.tsx
@@ -42,6 +42,7 @@ it('shows errors and retries instead of presenting failure as zero usage', async
mocks.fetch.mockRejectedValueOnce(new Error('offline')).mockResolvedValue(data)
render(<UsageSettingsSection />)
expect(await screen.findByRole('alert')).toHaveTextContent('Unable to load usage statistics.')
+ expect(screen.getByRole('alert')).toHaveTextContent('offline')
expect(screen.queryByText('No recorded model usage for this year.')).toBeNull()
fireEvent.click(screen.getByRole('button', {name: 'Retry'}))
expect(await screen.findByText('glm-test')).toBeVisible()