Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(model-hub): classify OAuth failures once (#1419)

Call White21afaed7b05e
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.test.ts b/ui/src/components/settings/models/OAuthConnectDialog.test.ts
index bf94843c4..916678010 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.test.ts
+++ b/ui/src/components/settings/models/OAuthConnectDialog.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { I18nextProvider } from 'react-i18next';
import * as React from 'react';
@@ -19,6 +19,7 @@ import type { Source } from './types';
afterEach(() => {
cleanup();
+ vi.useRealTimers();
vi.restoreAllMocks();
});
@@ -36,6 +37,27 @@ const subscription = (over: Partial<Source> = {}): Source => ({
...over,
});
+const dialog = (props: Partial<React.ComponentProps<typeof OAuthConnectDialog>> = {}) =>
+ React.createElement(
+ ToastProvider,
+ null,
+ React.createElement(
+ I18nextProvider,
+ { i18n },
+ React.createElement(OAuthConnectDialog, {
+ open: true,
+ vendor: 'anthropic',
+ sources: [],
+ onClose: vi.fn(),
+ onConnected: vi.fn(),
+ ...props,
+ }),
+ ),
+ );
+
+const renderDialog = (props: Partial<React.ComponentProps<typeof OAuthConnectDialog>> = {}) =>
+ render(dialog(props));
+
describe('add-subscription channel choice', () => {
it('flips the recommendation and visible order by vendor', () => {
expect(recommendedSubscriptionChannel('anthropic')).toBe('native_cli');
@@ -78,21 +100,7 @@ describe('add-subscription start recovery', () => {
expires_at: '2099-01-01T00:00:00Z',
});
- render(React.createElement(
- ToastProvider,
- null,
- React.createElement(
- I18nextProvider,
- { i18n },
- React.createElement(OAuthConnectDialog, {
- open: true,
- vendor: 'anthropic',
- sources: [],
- onClose: vi.fn(),
- onConnected: vi.fn(),
- }),
- ),
- ));
+ renderDialog();
const user = userEvent.setup();
await user.click(screen.getByRole('button', { name: /Sign in|去登录/i }));
@@ -104,3 +112,106 @@ describe('add-subscription start recovery', () => {
expect(start.mock.calls[0][2]).toMatch(/^ofn_[a-z0-9]{16,64}$/);
});
});
+
+describe('OAuth failure class behavior', () => {
+ it('keeps a held flow when its timeout reread is inconclusive', async () => {
+ vi.useFakeTimers();
+ const providerTab = {
+ closed: false,
+ close: vi.fn(),
+ opener: {},
+ };
+ vi.spyOn(window, 'open').mockReturnValue(providerTab as unknown as Window);
+ const reauth = vi.spyOn(modelsApi, 'reauthSource').mockResolvedValue({
+ flow_id: 'oaf_timeout',
+ intent: 'reauth',
+ vendor: 'anthropic',
+ channel: 'native_cli',
+ state: 'awaiting_action',
+ presentation: { expects: 'none' },
+ expires_at: new Date(Date.now() - 61_000).toISOString(),
+ });
+ const status = vi
+ .spyOn(modelsApi, 'getOAuthStatus')
+ .mockRejectedValue(new TypeError('Failed to fetch'));
+ renderDialog({ reauth: subscription() });
+
+ await act(async () => Promise.resolve());
+ expect(reauth).toHaveBeenCalledTimes(1);
+ await act(async () => vi.advanceTimersByTime(2_000));
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));
+ await Promise.resolve();
+ });
+
+ expect(status).toHaveBeenCalledWith('oaf_timeout');
+ expect(reauth).toHaveBeenCalledTimes(1);
+ expect(providerTab.close).toHaveBeenCalledOnce();
+ });
+
+ it('ignores a held-flow reread rejection after its journey is retired', async () => {
+ vi.useFakeTimers();
+ let rejectStatus!: (reason: unknown) => void;
+ const pendingStatus = new Promise<never>((_resolve, reject) => {
+ rejectStatus = reject;
+ });
+ const reauth = vi
+ .spyOn(modelsApi, 'reauthSource')
+ .mockResolvedValueOnce({
+ flow_id: 'oaf_retired',
+ intent: 'reauth',
+ vendor: 'anthropic',
+ channel: 'native_cli',
+ state: 'awaiting_action',
+ presentation: { expects: 'none' },
+ expires_at: new Date(Date.now() - 61_000).toISOString(),
+ })
+ .mockResolvedValueOnce({
+ flow_id: 'oaf_replacement',
+ intent: 'reauth',
+ vendor: 'anthropic',
+ channel: 'native_cli',
+ state: 'awaiting_action',
+ presentation: { expects: 'none' },
+ expires_at: '2099-01-01T00:00:00Z',
+ });
+ vi.spyOn(modelsApi, 'getOAuthStatus').mockReturnValue(pendingStatus);
+ vi.spyOn(modelsApi, 'cancelOAuth').mockResolvedValue(undefined);
+ const retiredSource = subscription({ id: 'src_retired' });
+ const replacementSource = subscription({ id: 'src_replacement' });
+ const rendered = renderDialog({ reauth: retiredSource });
+
+ await act(async () => Promise.resolve());
+ await act(async () => vi.advanceTimersByTime(2_000));
+ fireEvent.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));
+ expect(modelsApi.getOAuthStatus).toHaveBeenCalledWith('oaf_retired');
+
+ rendered.rerender(dialog({ open: false, reauth: retiredSource }));
+ rendered.rerender(dialog({ reauth: replacementSource }));
+ await act(async () => Promise.resolve());
+ expect(reauth).toHaveBeenCalledTimes(2);
+
+ await act(async () => {
+ rejectStatus(new ApiCallError('source_not_found'));
+ await Promise.resolve();
+ });
+
+ expect(screen.getByRole('button', { name: /^Cancel$|^取消$/i })).toBeTruthy();
+ });
+
+ it('does not offer Retry for an authoritative terminal failure', async () => {
+ vi.spyOn(modelsApi, 'reauthSource').mockRejectedValue(new ApiCallError('source_not_found'));
+ renderDialog({ reauth: subscription() });
+
+ await screen.findByRole('button', { name: /^Close$|^关闭$/i });
+ expect(screen.queryByRole('button', { name: /^Retry$|^重试$/i })).toBeNull();
+ });
+
+ it('offers Retry when the engine is unavailable', async () => {
+ vi.spyOn(modelsApi, 'reauthSource').mockRejectedValue(new ApiCallError('engine_down'));
+ renderDialog({ reauth: subscription() });
+
+ expect(await screen.findByRole('button', { name: /^Retry$|^重试$/i })).toBeTruthy();
+ });
+});
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsx
index 8b88b3e8a..c8f03fb19 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx
+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx
@@ -25,6 +25,7 @@ import { useToast } from '@/context/ToastContext';
import { OAuthDeviceCodeRow, OAuthLinkRow, OAuthSubmitRow } from '../oauth/OAuthFlowParts';
import { AdoptionNote } from './AdoptionNote';
import {
+ classifyOAuthFailure,
createFlowAuthority,
failureLanded,
initialFlowView,
@@ -406,8 +407,29 @@ export const OAuthConnectDialog: React.FC<{
// fresh acquisition; this status read was the required last chance
// to observe a near-deadline terminal result.
return false;
- } catch {
- return false;
+ } catch (err) {
+ // The success and rejection paths belong to the same read. Once
+ // this authority is retired, neither outcome may update the view
+ // or dispose a provider tab owned by its replacement.
+ if (cancelled || flowAuthorityRef.current !== authority) return true;
+ // This reread did not start a provider journey, so the tab opened
+ // by the Retry gesture has no URL to receive.
+ closeProviderWindow();
+ const failure = apiFailure(err);
+ const failureClass = classifyOAuthFailure(failure);
+ // An unread flow is still held. Retry may ask again, but it may not
+ // turn missing evidence into permission to mint a replacement.
+ if (failureClass === 'inconclusive') return true;
+ // A named failure replaces the local timeout so the same class can
+ // decide whether another Retry is meaningful.
+ transition({ kind: 'reset' });
+ const step = transition({
+ kind: 'error',
+ errorKey: oauthFailureKey(failure?.code, journey),
+ failureClass,
+ });
+ rowsBehindAreStale(failure, failureLanded(step.action));
+ return true;
}
};
}
@@ -444,14 +466,19 @@ export const OAuthConnectDialog: React.FC<{
// about the flow at all — that same read is what materializes a
// just-succeeded one. Keep reading instead of stopping; the deadline check
// at the top of each poll bounds either.
- if (!pollFailureSettles(submittingRef.current, failure?.serverNamed ?? false, failure?.code ?? failure?.detail)) {
+ const failureClass = classifyOAuthFailure(failure);
+ if (!pollFailureSettles(submittingRef.current, failureClass)) {
pollTimer = window.setTimeout(() => void poll(flowId), POLL_MS);
return;
}
// The authority goes first because its answer is what decides whether these
// pairs are the ones on screen — see `failureLanded`. The refetch below is
// owed whatever it answers.
- const step = transition({ kind: 'error', errorKey: oauthFailureKey(failure?.code, journey) });
+ const step = transition({
+ kind: 'error',
+ errorKey: oauthFailureKey(failure?.code, journey),
+ failureClass,
+ });
rowsBehindAreStale(failure, failureLanded(step.action));
}
};
@@ -524,6 +551,7 @@ export const OAuthConnectDialog: React.FC<{
pollTimer = window.setTimeout(() => void poll(started.flow_id), POLL_MS);
} catch (err) {
const failure = apiFailure(err);
+ const failureClass = classifyOAuthFailure(failure);
// A reauth that fails to START can still have written the row: the
// irreversible marking is rolled back only for a login that fails to
// spawn, not for the flow-binding failures after it. Which is why this
@@ -543,6 +571,7 @@ export const OAuthConnectDialog: React.FC<{
const step = transition({
kind: 'error',
errorKey: isReauth ? 'settings.models.oauth.error.start' : oauthStartFailureKey(failure?.detail ?? failure?.code),
+ failureClass,
});
if (!isReauth) setStartFailureCode(failure?.detail ?? failure?.code ?? 'start_failed');
closeProviderWindow();
@@ -640,9 +669,11 @@ export const OAuthConnectDialog: React.FC<{
// the flow id, so a submit rejecting afterwards is still current and still
// ignored. `failureLanded` is the part that knows.
const failure = apiFailure(err);
+ const failureClass = classifyOAuthFailure(failure);
const step = authority.transition({
kind: 'error',
errorKey: oauthFailureKey(failure?.code, journey),
+ failureClass,
});
rowsBehindAreStale(failure, failureLanded(step.action));
} finally {
@@ -661,7 +692,7 @@ export const OAuthConnectDialog: React.FC<{
setPhase('choose');
return;
}
- const timedOutFlow = view.errorKey === 'settings.models.oauth.error.timeout' ? heldFlowId.current : null;
+ const timedOutFlow = view.failureClass === 'inconclusive' ? heldFlowId.current : null;
if (timedOutFlow && rereadHeldFlow.current) {
if (await rereadHeldFlow.current()) return;
}
@@ -672,7 +703,7 @@ export const OAuthConnectDialog: React.FC<{
setPhase('flow');
};
- const { flow, errorKey } = view;
+ const { flow, errorKey, failureClass } = view;
const presentation = flow?.presentation;
const expects = presentation?.expects;
const isDevice = expects === 'none';
@@ -681,7 +712,6 @@ export const OAuthConnectDialog: React.FC<{
// the same call, so there is no in-between to hold the banner for. The complete
// rendered state comes from the authority's landed view.
const success = view.settled && flow?.state === 'success';
- const failed = view.settled && Boolean(errorKey);
const active = !view.settled;
const remainingMs = flow?.expires_at ? Math.max(0, new Date(flow.expires_at).getTime() - Date.now()) : null;
@@ -893,7 +923,7 @@ export const OAuthConnectDialog: React.FC<{
</DialogTitle>
</DialogHeader>
- {failed && (
+ {failureClass && (
<div className="flex flex-col gap-2">
<div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/[0.08] px-4 py-3 text-[13px] text-destructive-ink">
<TriangleAlert className="mt-0.5 size-4 shrink-0" />
@@ -1022,7 +1052,7 @@ export const OAuthConnectDialog: React.FC<{
siblings are already marked — so sending the user back to the row
to confirm it a second time asks them to agree to a cost they have
already paid, for the only gesture that can undo it. */}
- {failed && (
+ {failureClass && failureClass !== 'authoritative-terminal' && (
<Button
variant="brand"
size="sm"
diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.ts
index a505109e3..1eadac932 100644
--- a/ui/src/components/settings/models/asyncLifetime.test.ts
+++ b/ui/src/components/settings/models/asyncLifetime.test.ts
@@ -63,6 +63,7 @@ import { describe, expect, it } from 'vitest';
import {
agentsWithEcho,
+ classifyOAuthFailure,
createFlowAuthority,
createLatestAsyncAuthority,
createLatestAsyncAuthorityByKey,
@@ -610,7 +611,12 @@ describe('seedStep', () => {
});
describe('flowStep', () => {
- const fresh: FlowView = { flow: null, errorKey: null, settled: false };
+ const fresh: FlowView = {
+ flow: null,
+ errorKey: null,
+ failureClass: null,
+ settled: false,
+ };
it('keeps polling while the flow is running', () => {
const step = flowStep(fresh, { kind: 'response', flow: flow('awaiting_action') });
@@ -663,6 +669,7 @@ describe('flowStep', () => {
expect(tick.action).toBe('timeout');
expect(tick.view.flow?.state).toBe('failed');
expect(tick.view.errorKey).toBe('settings.models.oauth.error.timeout');
+ expect(tick.view.failureClass).toBe('inconclusive');
expect(isDone(tick.action)).toBe(true);
});
@@ -675,6 +682,7 @@ describe('flowStep', () => {
const failed = flowStep(fresh, { kind: 'response', flow: flow('cancelled') });
expect(failed.action).toBe('fail');
expect(failed.view.errorKey).toBe('settings.models.oauth.error.generic');
+ expect(failed.view.failureClass).toBe('retryable-provider');
expect(failed.view.settled).toBe(true);
expect(flowStep(failed.view, { kind: 'response', flow: flow('success') }).action).toBe('ignore');
});
@@ -689,12 +697,14 @@ describe('flow authority', () => {
const latePoll = authority.transition({
kind: 'error',
errorKey: 'settings.models.oauth.error.generic',
+ failureClass: 'retryable-provider',
});
expect(latePoll.action).toBe('ignore');
expect(authority.current()).toEqual({
flow: expect.objectContaining({ state: 'success' }),
errorKey: null,
+ failureClass: null,
settled: true,
});
});
@@ -707,12 +717,14 @@ describe('flow authority', () => {
const latePaste = authority.transition({
kind: 'error',
errorKey: 'settings.models.oauth.error.finalize',
+ failureClass: 'retryable-provider',
});
expect(latePaste.action).toBe('ignore');
expect(authority.current()).toEqual({
flow: expect.objectContaining({ state: 'success' }),
errorKey: null,
+ failureClass: null,
settled: true,
});
});
@@ -735,24 +747,46 @@ describe('flow authority', () => {
expect(authority.current()).toEqual({
flow: expect.objectContaining({ state: 'failed' }),
errorKey: 'settings.models.oauth.error.timeout',
+ failureClass: 'inconclusive',
settled: true,
});
expect(landed.at(-1)).toEqual(authority.current());
});
});
-describe('pollFailureSettles — who speaks for a journey whose submit is outstanding', () => {
+describe('OAuth failure classification', () => {
+ const named = (code: string) => ({ serverNamed: true, code });
+
+ it('keeps transport failures and engine outages inconclusive', () => {
+ expect(classifyOAuthFailure(null)).toBe('inconclusive');
+ expect(classifyOAuthFailure({ serverNamed: false, code: 'bad_response' })).toBe('inconclusive');
+ expect(classifyOAuthFailure(named('engine_down'))).toBe('inconclusive');
+ expect(classifyOAuthFailure(named('modelHub.errors.engine_down'))).toBe('inconclusive');
+ });
+
+ it.each(['source_not_found', 'flow_settled', 'already_connected'])(
+ 'treats %s as an authoritative terminal',
+ (code) => {
+ expect(classifyOAuthFailure(named(code))).toBe('authoritative-terminal');
+ },
+ );
+
+ it('defaults other server-named failures to retryable provider failures', () => {
+ expect(classifyOAuthFailure(named('discovery_failed'))).toBe('retryable-provider');
+ });
+
it('lets a failed poll settle the journey when it is the only authority', () => {
// A status read is also the call that materializes a just-succeeded flow, so on
// a device-code login its failure can be the one thing that knows the login
// produced nothing usable — when the route is what said so.
- expect(pollFailureSettles(false, true)).toBe(true);
+ expect(pollFailureSettles(false, 'retryable-provider')).toBe(true);
+ expect(pollFailureSettles(false, 'authoritative-terminal')).toBe(true);
});
it('does not let it settle one while the user’s own submit is outstanding', () => {
// The submit is the writer of record; a read failing beside it says nothing
// about whether that write committed.
- expect(pollFailureSettles(true, true)).toBe(false);
+ expect(pollFailureSettles(true, 'retryable-provider')).toBe(false);
});
it('does not let a failure the route never named settle one either', () => {
@@ -762,14 +796,9 @@ describe('pollFailureSettles — who speaks for a journey whose submit is outsta
// source may exist while the dialog declares a terminal nobody reported — and
// an ordinary connect retried from that sentence mints a second source. Same
// `serverNamed` bit `mayHaveWritten` reads for the refetch, asked about speech.
- expect(pollFailureSettles(false, false)).toBe(false);
+ expect(pollFailureSettles(false, 'inconclusive')).toBe(false);
// …and the submit's precedence does not depend on it.
- expect(pollFailureSettles(true, false)).toBe(false);
- });
-
- it('keeps a named engine outage inconclusive so the held flow is polled again', () => {
- expect(pollFailureSettles(false, true, 'engine_down')).toBe(false);
- expect(pollFailureSettles(false, true, 'modelHub.errors.engine_down')).toBe(false);
+ expect(pollFailureSettles(true, 'inconclusive')).toBe(false);
});
it('shows what latching one costs: the success right behind it is ignored', () => {
@@ -778,7 +807,11 @@ describe('pollFailureSettles — who speaks for a journey whose submit is outsta
const authority = createFlowAuthority(() => {}, null);
authority.transition({ kind: 'response', flow: flow('awaiting_action') });
- authority.transition({ kind: 'error', errorKey: 'settings.models.oauth.error.generic' });
+ authority.transition({
+ kind: 'error',
+ errorKey: 'settings.models.oauth.error.generic',
+ failureClass: 'retryable-provider',
+ });
const submitSucceeded = authority.transition({ kind: 'response', flow: flow('success') });
expect(submitSucceeded.action).toBe('ignore');
@@ -791,14 +824,12 @@ describe('pollFailureSettles — who speaks for a journey whose submit is outsta
// read the submit's in-flight state through a ref or it reads `false` forever.
const dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');
- expect(dialog).toMatch(
- /pollFailureSettles\(submittingRef\.current, failure\?\.serverNamed \?\? false, failure\?\.code \?\? failure\?\.detail\)/,
- );
+ expect(dialog).toMatch(/pollFailureSettles\(submittingRef\.current, failureClass\)/);
expect(dialog).toMatch(/submittingRef\.current = submitting;/);
// The second argument only exists if the failure is read BEFORE the question is
// asked — reading it after the settle branch is how this reverts silently.
expect(dialog.indexOf('const failure = apiFailure(err);')).toBeLessThan(
- dialog.indexOf('if (!pollFailureSettles('),
+ dialog.indexOf('const failureClass = classifyOAuthFailure(failure);'),
);
});
});
@@ -947,10 +978,8 @@ describe('failureLanded — whose account of the rows is the one on screen', ()
const dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');
const carrying = [...dialog.matchAll(/rowsBehindAreStale\(failure[^)]*\)/g)].map((m) => m[0]);
- // Three: the start rejection, the status poll's, and the paste submit's. The
- // start one cannot reach a settled view today and asks regardless — a site that
- // is right because of where it sits stops being right when it is moved.
- expect(carrying.length).toBe(3);
+ // The pattern must exist somewhere, or the sweep proves nothing.
+ expect(carrying.length).toBeGreaterThan(0);
for (const call of carrying) expect(call).toMatch(/failureLanded\(step\.action\)/);
// And the refetch is still owed on the ignored path: the gate is the second
// argument, never a reason to skip the call.
diff --git a/ui/src/components/settings/models/asyncLifetime.ts b/ui/src/components/settings/models/asyncLifetime.ts
index 5bfb3f915..5ea46b803 100644
--- a/ui/src/components/settings/models/asyncLifetime.ts
+++ b/ui/src/components/settings/models/asyncLifetime.ts
@@ -342,7 +342,7 @@ export const seedStep = (state: SeedState, authoritative: string): { state: Seed
*/
export type FlowEvent =
| { kind: 'reset' }
- | { kind: 'error'; errorKey: string }
+ | { kind: 'error'; errorKey: string; failureClass: OAuthFailureClass }
| { kind: 'response'; flow: OAuthFlow }
| { kind: 'tick'; overdue: boolean };
@@ -358,10 +358,49 @@ export type FlowEvent =
*/
export type FlowAction = 'continue' | 'succeed' | 'fail' | 'timeout' | 'ignore';
+export type OAuthFailureClass =
+ | 'authoritative-terminal'
+ | 'inconclusive'
+ | 'retryable-provider';
+
+type OAuthFailureEvidence = {
+ serverNamed: boolean;
+ code?: string;
+ detail?: string;
+} | null;
+
+const AUTHORITATIVE_TERMINAL_CODES = new Set([
+ 'source_not_found',
+ 'flow_settled',
+ 'already_connected',
+]);
+
+/** One classification shared by polling, timeout recovery, and Retry. */
+export const classifyOAuthFailure = (failure: OAuthFailureEvidence): OAuthFailureClass => {
+ const rawCode = failure?.code ?? failure?.detail;
+ const code = rawCode?.startsWith('modelHub.errors.')
+ ? rawCode.slice('modelHub.errors.'.length)
+ : rawCode;
+ if (!failure?.serverNamed || code === 'engine_down') return 'inconclusive';
+ return code && AUTHORITATIVE_TERMINAL_CODES.has(code)
+ ? 'authoritative-terminal'
+ : 'retryable-provider';
+};
+
/** Everything that decides what the dialog shows, including its terminal latch. */
-export type FlowView = { flow: OAuthFlow | null; errorKey: string | null; settled: boolean };
+export type FlowView = {
+ flow: OAuthFlow | null;
+ errorKey: string | null;
+ failureClass: OAuthFailureClass | null;
+ settled: boolean;
+};
-export const initialFlowView: FlowView = { flow: null, errorKey: null, settled: false };
+export const initialFlowView: FlowView = {
+ flow: null,
+ errorKey: null,
+ failureClass: null,
+ settled: false,
+};
/**
* The states in which the SERVER has reported a flow finished — one list, because
@@ -383,7 +422,15 @@ export const flowStep = (view: FlowView, event: FlowEvent): { view: FlowView; ac
// source).
if (view.settled) return { view, action: 'ignore' };
if (event.kind === 'error') {
- return { view: { flow: view.flow, errorKey: event.errorKey, settled: true }, action: 'fail' };
+ return {
+ view: {
+ flow: view.flow,
+ errorKey: event.errorKey,
+ failureClass: event.failureClass,
+ settled: true,
+ },
+ action: 'fail',
+ };
}
if (event.kind === 'tick') {
if (!event.overdue) return { view, action: 'continue' };
@@ -391,13 +438,19 @@ export const flowStep = (view: FlowView, event: FlowEvent): { view: FlowView; ac
view: {
flow: view.flow ? { ...view.flow, state: 'failed' } : null,
errorKey: 'settings.models.oauth.error.timeout',
+ failureClass: classifyOAuthFailure(null),
settled: true,
},
action: 'timeout',
};
}
const flow = event.flow;
- if (flow.state === 'success') return { view: { flow, errorKey: null, settled: true }, action: 'succeed' };
+ if (flow.state === 'success') {
+ return {
+ view: { flow, errorKey: null, failureClass: null, settled: true },
+ action: 'succeed',
+ };
+ }
// `settled` means terminal, not successful: a failed flow is just as finished,
// and a later arrival has just as little business reopening it. Which states
// those are is `flowStateTerminal`'s to say — success has already returned, so
@@ -407,12 +460,16 @@ export const flowStep = (view: FlowView, event: FlowEvent): { view: FlowView; ac
view: {
flow,
errorKey: flow.error_key ?? 'settings.models.oauth.error.generic',
+ failureClass: classifyOAuthFailure({ serverNamed: true }),
settled: true,
},
action: 'fail',
};
}
- return { view: { flow, errorKey: null, settled: false }, action: 'continue' };
+ return {
+ view: { flow, errorKey: null, failureClass: null, settled: false },
+ action: 'continue',
+ };
};
/**
@@ -529,19 +586,16 @@ export const terminalArrivalMovedRows = (action: FlowAction): boolean =>
* not one the server named. Settling on it declares a terminal nobody reported, over
* an operation that may have committed — the dialog says 授权失败 on a source the
* server did create, and an ordinary connect retried from there mints a second one.
- * `serverNamed` is the same discriminator `mayHaveWritten` reads for the refetch,
- * asked here about speech instead of writes: a refusal that named itself knows the
- * login went nowhere; a transport failure knows nothing at all.
+ * `classifyOAuthFailure` owns that discriminator: a refusal that named itself can
+ * answer about the flow, while an inconclusive class cannot.
*
* Dropping it is bounded either way — the caller keeps polling, and the deadline at
* the top of each tick is the dialog's own verdict when nothing ever answers.
*/
export const pollFailureSettles = (
submitOutstanding: boolean,
- serverNamed: boolean,
- code?: string,
-): boolean =>
- !submitOutstanding && serverNamed && code !== 'engine_down' && code !== 'modelHub.errors.engine_down';
+ failureClass: OAuthFailureClass,
+): boolean => !submitOutstanding && failureClass !== 'inconclusive';
/**
* Whether the failure that just arrived is the one now ON SCREEN.
diff --git a/ui/src/components/settings/models/oauthFailureClass.test.ts b/ui/src/components/settings/models/oauthFailureClass.test.ts
new file mode 100644
index 000000000..6eb81859d
--- /dev/null
+++ b/ui/src/components/settings/models/oauthFailureClass.test.ts
@@ -0,0 +1,66 @@
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+import * as ts from 'typescript';
+import { describe, expect, it } from 'vitest';
+
+type FailureConsumer = { site: string; classifies: boolean };
+
+function isCallTo(node: ts.Node | undefined, name: string): node is ts.CallExpression {
+ return Boolean(
+ node
+ && ts.isCallExpression(node)
+ && ts.isIdentifier(node.expression)
+ && node.expression.text === name,
+ );
+}
+
+/** Every normalized API failure in the dialog, found rather than listed. */
+function failureConsumers(url: URL): FailureConsumer[] {
+ const path = fileURLToPath(url);
+ const source = ts.createSourceFile(
+ path,
+ readFileSync(url, 'utf8'),
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const found: FailureConsumer[] = [];
+ const visit = (node: ts.Node) => {
+ if (
+ ts.isVariableDeclaration(node)
+ && ts.isIdentifier(node.name)
+ && isCallTo(node.initializer, 'apiFailure')
+ ) {
+ let scope: ts.Node | undefined = node.parent;
+ while (scope && !ts.isBlock(scope)) scope = scope.parent;
+ let classifies = false;
+ const inspect = (child: ts.Node) => {
+ if (
+ isCallTo(child, 'classifyOAuthFailure')
+ && child.arguments.some(
+ (argument) => ts.isIdentifier(argument) && argument.text === node.name.text,
+ )
+ ) {
+ classifies = true;
+ }
+ ts.forEachChild(child, inspect);
+ };
+ if (scope) inspect(scope);
+ const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
+ found.push({ site: `${path.slice(path.lastIndexOf('/') + 1)}:${line}`, classifies });
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ return found;
+}
+
+describe('OAuth failure classification invariant', () => {
+ it('classifies every API failure consumed by the dialog', () => {
+ const consumers = failureConsumers(new URL('./OAuthConnectDialog.tsx', import.meta.url));
+
+ expect(consumers.length).toBeGreaterThan(0);
+ expect(consumers.filter(({ classifies }) => !classifies)).toEqual([]);
+ });
+});