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): own provider tab lifetime (#1423)

Call Whitec72f7ce6263c
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.test.ts b/ui/src/components/settings/models/OAuthConnectDialog.test.ts
index 916678010..8c88316c7 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.test.ts
+++ b/ui/src/components/settings/models/OAuthConnectDialog.test.ts
@@ -8,7 +8,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { ToastProvider } from '@/context/ToastProvider';
import i18n from '@/i18n';
import { OAuthConnectDialog } from './OAuthConnectDialog';
-import { ApiCallError, modelsApi } from './modelsApi';
+import { ApiCallError, modelsApi, type OAuthResult } from './modelsApi';
+import { disposeProviderTab } from './providerTab';
import {
initialSubscriptionChannel,
nativeSubscriptionSlotTaken,
@@ -19,6 +20,8 @@ import type { Source } from './types';
afterEach(() => {
cleanup();
+ disposeProviderTab('cleanup');
+ disposeProviderTab('cleanup');
vi.useRealTimers();
vi.restoreAllMocks();
});
@@ -58,6 +61,29 @@ const dialog = (props: Partial<React.ComponentProps<typeof OAuthConnectDialog>>
const renderDialog = (props: Partial<React.ComponentProps<typeof OAuthConnectDialog>> = {}) =>
render(dialog(props));
+const providerTab = () => {
+ const tab = {
+ closed: false,
+ close: vi.fn(),
+ opener: {} as unknown,
+ location: { href: '' },
+ };
+ tab.close.mockImplementation(() => {
+ tab.closed = true;
+ });
+ return tab;
+};
+
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (reason: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+};
+
describe('add-subscription channel choice', () => {
it('flips the recommendation and visible order by vendor', () => {
expect(recommendedSubscriptionChannel('anthropic')).toBe('native_cli');
@@ -111,6 +137,73 @@ describe('add-subscription start recovery', () => {
expect(start.mock.calls[1]).toEqual(start.mock.calls[0]);
expect(start.mock.calls[0][2]).toMatch(/^ofn_[a-z0-9]{16,64}$/);
});
+
+ it('keeps the Retry tab across effect cleanup and navigates the replacement flow', async () => {
+ const authUrl = 'https://provider.example/retry';
+ const tab = providerTab();
+ vi.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);
+ const reauth = vi
+ .spyOn(modelsApi, 'reauthSource')
+ .mockRejectedValueOnce(new ApiCallError('engine_down'))
+ .mockResolvedValueOnce({
+ flow_id: 'oaf_retry',
+ intent: 'reauth',
+ vendor: 'anthropic',
+ channel: 'native_cli',
+ state: 'awaiting_action',
+ presentation: { expects: 'paste_code', auth_url: authUrl },
+ expires_at: '2099-01-01T00:00:00Z',
+ });
+ renderDialog({ reauth: subscription() });
+
+ await userEvent.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));
+
+ await waitFor(() => expect(reauth).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(tab.location.href).toBe(authUrl));
+ expect(tab.close).not.toHaveBeenCalled();
+ });
+
+ it('disposes the blank tab when acquisition is refused', async () => {
+ const tab = providerTab();
+ vi.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);
+ vi.spyOn(modelsApi, 'startOAuth').mockRejectedValue(new ApiCallError('engine_down'));
+ renderDialog();
+
+ await userEvent.click(screen.getByRole('button', { name: /Sign in|去登录/i }));
+ await screen.findByRole('button', { name: /^Retry$|^重试$/i });
+
+ expect(tab.close).toHaveBeenCalledOnce();
+ expect(tab.location.href).toBe('');
+ });
+
+ it('disposes without navigating an already-terminal nonce replay', async () => {
+ const authUrl = 'https://provider.example/stale';
+ const tab = providerTab();
+ vi.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);
+ const terminal = {
+ flow_id: 'oaf_terminal',
+ client_nonce: 'ofn_terminal',
+ vendor: 'anthropic',
+ channel: 'native_cli' as const,
+ state: 'failed' as const,
+ presentation: { expects: 'paste_code' as const, auth_url: authUrl },
+ error_key: 'settings.models.oauth.error.generic',
+ expires_at: '2099-01-01T00:00:00Z',
+ };
+ vi.spyOn(modelsApi, 'startOAuth').mockResolvedValue(terminal);
+ const status = vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue({
+ flow: terminal,
+ created: null,
+ repaired: null,
+ });
+ renderDialog();
+
+ await userEvent.click(screen.getByRole('button', { name: /Sign in|去登录/i }));
+ await waitFor(() => expect(status).toHaveBeenCalledWith(terminal.flow_id));
+
+ expect(tab.close).toHaveBeenCalledOnce();
+ expect(tab.location.href).toBe('');
+ });
});
describe('OAuth failure class behavior', () => {
@@ -150,6 +243,70 @@ describe('OAuth failure class behavior', () => {
expect(providerTab.close).toHaveBeenCalledOnce();
});
+ it.each([
+ {
+ label: 'failure',
+ finish: (pending: ReturnType<typeof deferred<OAuthResult>>, _flow: OAuthResult['flow']) =>
+ pending.reject(new ApiCallError('engine_down')),
+ },
+ {
+ label: 'terminal response',
+ finish: (pending: ReturnType<typeof deferred<OAuthResult>>, flow: OAuthResult['flow']) =>
+ pending.resolve({ flow: { ...flow, state: 'failed' }, created: null, repaired: null }),
+ },
+ ])('keeps Retry\'s tab when the timed-out flow ignores a late submit $label', async ({ finish }) => {
+ vi.useFakeTimers();
+ const tab = providerTab();
+ vi.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);
+ const expiredFlow: OAuthResult['flow'] = {
+ flow_id: 'oaf_late_submit',
+ intent: 'reauth',
+ vendor: 'anthropic',
+ channel: 'native_cli',
+ state: 'awaiting_action',
+ presentation: { expects: 'paste_code' },
+ expires_at: new Date(Date.now() - 61_000).toISOString(),
+ };
+ const replacementUrl = 'https://provider.example/late-submit-retry';
+ const replacementFlow: OAuthResult['flow'] = {
+ ...expiredFlow,
+ flow_id: 'oaf_late_submit_replacement',
+ presentation: { expects: 'paste_code', auth_url: replacementUrl },
+ expires_at: '2099-01-01T00:00:00Z',
+ };
+ const reauth = vi.spyOn(modelsApi, 'reauthSource')
+ .mockResolvedValueOnce(expiredFlow)
+ .mockResolvedValueOnce(replacementFlow);
+ const submit = deferred<OAuthResult>();
+ vi.spyOn(modelsApi, 'submitOAuth').mockReturnValue(submit.promise);
+ const reread = deferred<OAuthResult>();
+ vi.spyOn(modelsApi, 'getOAuthStatus').mockReturnValue(reread.promise);
+ vi.spyOn(modelsApi, 'cancelOAuth').mockResolvedValue(undefined);
+ renderDialog({ reauth: subscription() });
+
+ await act(async () => Promise.resolve());
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'auth-code' } });
+ fireEvent.click(screen.getByRole('button', { name: /^Submit$|^提交$/i }));
+ expect(modelsApi.submitOAuth).toHaveBeenCalledWith(expiredFlow.flow_id, 'auth-code');
+ await act(async () => vi.advanceTimersByTime(2_000));
+
+ fireEvent.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));
+ expect(modelsApi.getOAuthStatus).toHaveBeenCalledWith(expiredFlow.flow_id);
+ await act(async () => {
+ finish(submit, expiredFlow);
+ await Promise.resolve();
+ });
+ expect(tab.close).not.toHaveBeenCalled();
+
+ await act(async () => {
+ reread.resolve({ flow: expiredFlow, created: null, repaired: null });
+ await Promise.resolve();
+ });
+ expect(reauth).toHaveBeenCalledTimes(2);
+ expect(tab.location.href).toBe(replacementUrl);
+ expect(tab.close).not.toHaveBeenCalled();
+ });
+
it('ignores a held-flow reread rejection after its journey is retired', async () => {
vi.useFakeTimers();
let rejectStatus!: (reason: unknown) => void;
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsx
index c8f03fb19..c6aab3f48 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx
+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx
@@ -38,7 +38,12 @@ import {
type FlowView,
} from './asyncLifetime';
import { apiFailure, modelsApi, type Adoption, type OAuthResult } from './modelsApi';
-import { preopenProviderTab, takeHandedProviderTab } from './providerTab';
+import {
+ commitProviderTabRetry,
+ disposeProviderTab,
+ preopenProviderTab,
+ takeProviderTabForNavigation,
+} from './providerTab';
import { REPAIR_LINE_KEY, REPAIR_TOAST, repairOutcome, repairSettles, type RepairOutcome } from './repair';
import { NATIVE_SUBSCRIPTION_EXISTS_FAILURE, oauthFailureKey, oauthStartFailureKey, serverText, type OAuthJourney } from './serverCopy';
import {
@@ -139,29 +144,9 @@ export const OAuthConnectDialog: React.FC<{
onCloseRef.current = onClose;
const initializedOpenSubject = React.useRef<string | null>(null);
const clientNonce = React.useRef<string | null>(null);
- const providerWindow = React.useRef<Window | null>(null);
const heldFlowId = React.useRef<string | null>(null);
const rereadHeldFlow = React.useRef<(() => Promise<boolean>) | null>(null);
- const preopenProviderWindow = React.useCallback(() => {
- if (providerWindow.current && !providerWindow.current.closed) return;
- providerWindow.current = preopenProviderTab();
- }, []);
-
- const closeProviderWindow = React.useCallback(() => {
- // Also the tab a gesture outside this dialog handed over: an unused handoff
- // is an unused tab, and this is already the owner that closes one.
- const target = providerWindow.current ?? takeHandedProviderTab();
- providerWindow.current = null;
- if (!target || target.closed) return;
- try {
- target.close();
- } catch {
- // Cross-origin or already-closing windows can reject access; clearing the
- // ref above is still the important ownership transition.
- }
- }, []);
-
const createClientNonce = React.useCallback(() => {
const uuid = globalThis.crypto?.randomUUID?.();
if (uuid) return `ofn_${uuid.replaceAll('-', '').toLowerCase()}`;
@@ -382,7 +367,11 @@ export const OAuthConnectDialog: React.FC<{
// the guard above already makes that poll harmless, but there is no reason
// to let it fire.
if (isDone(step.action)) stop();
- if (isDone(step.action)) closeProviderWindow();
+ if (terminalArrivalMovedRows(step.action)) {
+ disposeProviderTab(
+ step.view.failureClass ?? (step.action === 'succeed' ? 'success' : undefined),
+ );
+ }
return isDone(step.action);
};
settleRef.current = settle;
@@ -412,11 +401,11 @@ export const OAuthConnectDialog: React.FC<{
// 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);
+ // This reread did not start a provider journey, so the tab opened
+ // by the Retry gesture has no URL to receive.
+ disposeProviderTab(failureClass);
// 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;
@@ -471,6 +460,7 @@ export const OAuthConnectDialog: React.FC<{
pollTimer = window.setTimeout(() => void poll(flowId), POLL_MS);
return;
}
+ disposeProviderTab(failureClass);
// 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.
@@ -574,7 +564,7 @@ export const OAuthConnectDialog: React.FC<{
failureClass,
});
if (!isReauth) setStartFailureCode(failure?.detail ?? failure?.code ?? 'start_failed');
- closeProviderWindow();
+ disposeProviderTab(failureClass);
rowsBehindAreStale(failure, failureLanded(step.action));
}
})();
@@ -609,7 +599,7 @@ export const OAuthConnectDialog: React.FC<{
// first, and by then the attempt it belongs to is not merely settled but
// GONE. Whatever gap report is on screen when it returns is somebody else's.
const opened = openedFlowId;
- closeProviderWindow();
+ disposeProviderTab('cleanup');
if (heldFlowId.current === opened) heldFlowId.current = null;
rereadHeldFlow.current = null;
void releaseFlow(authority, owner, {
@@ -675,6 +665,7 @@ export const OAuthConnectDialog: React.FC<{
errorKey: oauthFailureKey(failure?.code, journey),
failureClass,
});
+ if (failureLanded(step.action)) disposeProviderTab(failureClass);
rowsBehindAreStale(failure, failureLanded(step.action));
} finally {
if (isCurrent()) setSubmitting(false);
@@ -688,7 +679,7 @@ export const OAuthConnectDialog: React.FC<{
setNativeSlotTaken(true);
setChannel('hub');
setStartFailureCode(null);
- closeProviderWindow();
+ disposeProviderTab(view.failureClass ?? 'retryable-provider');
setPhase('choose');
return;
}
@@ -699,6 +690,7 @@ export const OAuthConnectDialog: React.FC<{
const freshAcquisition = startFailureCode === null;
setStartFailureCode(null);
if (freshAcquisition) clientNonce.current = null;
+ commitProviderTabRetry();
setStartAttempt((attempt) => attempt + 1);
setPhase('flow');
};
@@ -742,7 +734,7 @@ export const OAuthConnectDialog: React.FC<{
// claim taken at mount is stranded by anything that remounts (StrictMode
// replays effects in development) with the tab still open and unreachable.
// Claiming here also means a run with nothing to navigate keeps the handoff.
- const target = providerWindow.current ?? takeHandedProviderTab();
+ const target = takeProviderTabForNavigation();
if (!target || target.closed) return;
try {
target.location.href = presentation.auth_url;
@@ -750,7 +742,6 @@ export const OAuthConnectDialog: React.FC<{
// A popup may become inaccessible after opening; the visible link remains
// the fallback in that case.
}
- providerWindow.current = null;
}, [flowActive, presentation?.auth_url]);
const choosing = !isReauth && phase === 'choose';
@@ -892,7 +883,7 @@ export const OAuthConnectDialog: React.FC<{
size="sm"
className="model-hub-dialog-action"
onClick={() => {
- preopenProviderWindow();
+ preopenProviderTab();
setPhase('flow');
}}
>
@@ -1058,7 +1049,7 @@ export const OAuthConnectDialog: React.FC<{
size="sm"
className="h-10 sm:h-9"
onClick={() => {
- preopenProviderWindow();
+ preopenProviderTab('retry');
void retryStart();
}}
>
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 4a3e05900..24230091d 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -124,6 +124,43 @@ describe('SettingsModelsPage surface branches', () => {
expect((callback.match(/void refresh\(\)/g) ?? []).length).toBe(2);
});
+ it('issues exactly one surface refresh for a successful subscription create', async () => {
+ const created = {
+ ...nativeSubscription,
+ id: 'src_created_subscription',
+ display_name: 'Created subscription',
+ };
+ const terminal = {
+ flow_id: 'flow_created_subscription',
+ client_nonce: 'ofn_created_subscription',
+ vendor: 'anthropic',
+ channel: 'native_cli' as const,
+ state: 'success' as const,
+ presentation: { expects: 'none' as const },
+ expires_at: '2099-01-01T00:00:00Z',
+ };
+ vi.spyOn(modelsApi, 'startOAuth').mockResolvedValue(terminal);
+ const status = vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue({
+ flow: terminal,
+ created: { source: created, added_to: [], adopted_by: [] },
+ repaired: null,
+ });
+ renderPage([retainedSource]);
+
+ await screen.findByText('Retained source');
+ const listSources = vi.mocked(modelsApi.listSources);
+ const refreshesBeforeCreate = listSources.mock.calls.length;
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: /Add subscription|添加订阅/i }));
+ await user.click(await screen.findByRole('menuitem', { name: /Claude subscription|Claude 订阅/i }));
+ await user.click(screen.getByRole('button', { name: /Sign in|去登录/i }));
+
+ await waitFor(() => expect(status).toHaveBeenCalledWith(terminal.flow_id));
+ await waitFor(() => expect(listSources).toHaveBeenCalledTimes(refreshesBeforeCreate + 1));
+ await act(async () => Promise.resolve());
+ expect(listSources).toHaveBeenCalledTimes(refreshesBeforeCreate + 1);
+ });
+
it('renders Frame 09 without tabs when every backend is direct and no source exists', async () => {
renderPage([]);
diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.ts
index 1eadac932..ae649be6a 100644
--- a/ui/src/components/settings/models/asyncLifetime.test.ts
+++ b/ui/src/components/settings/models/asyncLifetime.test.ts
@@ -983,7 +983,7 @@ describe('failureLanded — whose account of the rows is the one on screen', ()
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.
- expect(dialog).not.toMatch(/if \(failureLanded\(/);
+ expect(dialog).not.toMatch(/if \(failureLanded\([^)]*\)\)\s*rowsBehindAreStale/);
});
it('makes silence the default, and lets exactly one arrival opt out of it', () => {
diff --git a/ui/src/components/settings/models/providerTab.test.ts b/ui/src/components/settings/models/providerTab.test.ts
index 3eae3abce..3216499f3 100644
--- a/ui/src/components/settings/models/providerTab.test.ts
+++ b/ui/src/components/settings/models/providerTab.test.ts
@@ -7,12 +7,33 @@ import { fileURLToPath } from 'node:url';
import * as ts from 'typescript';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { handOffProviderTab, preopenProviderTab, takeHandedProviderTab } from './providerTab';
+import {
+ commitProviderTabRetry,
+ disposeProviderTab,
+ handOffProviderTab,
+ preopenProviderTab,
+ takeHandedProviderTab,
+ takeProviderTabForNavigation,
+} from './providerTab';
-type FakeTab = { closed: boolean; opener: unknown };
+type FakeTab = {
+ closed: boolean;
+ opener: unknown;
+ location: { href: string };
+ close: ReturnType<typeof vi.fn>;
+};
function fakeTab(closed = false): FakeTab {
- return { closed, opener: {} };
+ const tab = {
+ closed,
+ opener: {},
+ location: { href: '' },
+ close: vi.fn(),
+ };
+ tab.close.mockImplementation(() => {
+ tab.closed = true;
+ });
+ return tab;
}
/** Install a `window.open` and report what it was asked for. */
@@ -35,6 +56,38 @@ function sourceFiles(directory: URL): URL[] {
});
}
+function providerTabConsumerFiles(directory: URL): URL[] {
+ return sourceFiles(directory).filter((url) => {
+ const path = fileURLToPath(url);
+ return path.endsWith('/providerTab.ts') || readFileSync(url, 'utf8').includes("from './providerTab'");
+ });
+}
+
+function directCloseSites(url: URL): string[] {
+ const path = fileURLToPath(url);
+ const source = ts.createSourceFile(
+ path,
+ readFileSync(url, 'utf8'),
+ ts.ScriptTarget.Latest,
+ true,
+ path.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
+ );
+ const found: string[] = [];
+ const visit = (node: ts.Node) => {
+ if (
+ ts.isCallExpression(node)
+ && ts.isPropertyAccessExpression(node.expression)
+ && node.expression.name.text === 'close'
+ ) {
+ const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
+ found.push(path.slice(path.lastIndexOf('/') + 1) + ':' + line);
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ return found;
+}
+
/** Names a call by its identifier, so `foo()` and `obj.foo()` read the same. */
function calledNames(node: ts.Node): Set<string> {
const names = new Set<string>();
@@ -78,7 +131,7 @@ function journeyStartHandlers(url: URL): { site: string; allocates: boolean }[]
path.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
);
const starts = ['retryStart', 'onReauth', 'setPhase:flow'];
- const allocators = ['preopenProviderWindow', 'preopenProviderTab', 'handOffProviderTab'];
+ const allocators = ['preopenProviderTab', 'handOffProviderTab'];
const found: { site: string; allocates: boolean }[] = [];
const visit = (node: ts.Node) => {
if (
@@ -106,7 +159,10 @@ function journeyStartHandlers(url: URL): { site: string; allocates: boolean }[]
afterEach(() => {
vi.unstubAllGlobals();
- takeHandedProviderTab();
+ // A committed retry intentionally survives one disposal, so two calls make
+ // cleanup independent of the state a failed assertion stopped at.
+ disposeProviderTab('cleanup');
+ disposeProviderTab('cleanup');
});
describe('provider tab', () => {
@@ -153,6 +209,52 @@ describe('provider tab', () => {
expect(takeHandedProviderTab()).toBeNull();
});
+ it('retains a committed Retry tab across cleanup for the replacement journey', () => {
+ const tab = fakeTab();
+ stubWindowOpen(() => tab as unknown as Window);
+
+ expect(preopenProviderTab('retry')).toBe(tab);
+ commitProviderTabRetry();
+ disposeProviderTab('cleanup');
+
+ expect(tab.close).not.toHaveBeenCalled();
+ expect(takeHandedProviderTab()).toBe(tab);
+ });
+
+ it('does not turn an initial tab into a Retry handoff', () => {
+ const tab = fakeTab();
+ stubWindowOpen(() => tab as unknown as Window);
+
+ preopenProviderTab();
+ commitProviderTabRetry();
+ disposeProviderTab('cleanup');
+
+ expect(tab.close).toHaveBeenCalledOnce();
+ expect(takeHandedProviderTab()).toBeNull();
+ });
+
+ it('disposes a Retry tab when no replacement journey was committed', () => {
+ const tab = fakeTab();
+ stubWindowOpen(() => tab as unknown as Window);
+
+ preopenProviderTab('retry');
+ disposeProviderTab('inconclusive');
+
+ expect(tab.close).toHaveBeenCalledOnce();
+ expect(takeHandedProviderTab()).toBeNull();
+ });
+
+ it('ends ownership when the provider tab is taken for navigation', () => {
+ const tab = fakeTab();
+ stubWindowOpen(() => tab as unknown as Window);
+
+ preopenProviderTab();
+ expect(takeProviderTabForNavigation()).toBe(tab);
+ disposeProviderTab('success');
+
+ expect(tab.close).not.toHaveBeenCalled();
+ });
+
// The invariant behind both re-auth findings on b594ef986: a journey's provider
// tab must be allocated by the gesture that starts it. The create journey's
// gesture is inside the dialog, the re-auth journey's is the confirm outside it,
@@ -164,4 +266,12 @@ describe('provider tab', () => {
expect(handlers.length).toBeGreaterThan(0);
expect(handlers.filter(({ allocates }) => !allocates)).toEqual([]);
});
+
+ it('keeps every direct provider-tab close inside the lifetime owner', () => {
+ const closes = providerTabConsumerFiles(new URL('./', import.meta.url)).flatMap(directCloseSites);
+
+ // The owner must actually close a tab, or this invariant would prove nothing.
+ expect(closes.length).toBeGreaterThan(0);
+ expect(closes.filter((site) => !site.startsWith('providerTab.ts:'))).toEqual([]);
+ });
});
diff --git a/ui/src/components/settings/models/providerTab.ts b/ui/src/components/settings/models/providerTab.ts
index dd8bd7c50..5c02ad071 100644
--- a/ui/src/components/settings/models/providerTab.ts
+++ b/ui/src/components/settings/models/providerTab.ts
@@ -13,18 +13,44 @@
* lifetime that spans the gesture → mount boundary, which is exactly what a
* component ref cannot hold; threading a live `Window` through page state and a
* prop would model that lifetime as data and copy it. One module owns the
- * allocation, and whichever journey opens next claims it.
+ * allocation, handoff, claim, navigation, retention and disposal.
*/
-/** Allocated by a gesture, not yet claimed by the journey it was opened for. */
-let handedTab: Window | null = null;
+import type { OAuthFailureClass } from './asyncLifetime';
+
+type ProviderTabState = 'handed' | 'claimed' | 'retry-pending' | 'retry-committed';
+type ProviderTabPurpose = 'initial' | 'retry';
+type ProviderTabRecord = { tab: Window; state: ProviderTabState };
+
+/** The one browser tab this feature owns, from allocation through disposal. */
+let providerTab: ProviderTabRecord | null = null;
+
+/** Reasons are carried from the shared OAuth classifier to the one disposer. */
+export type ProviderTabDisposalReason = OAuthFailureClass | 'success' | 'cleanup';
+
+const closeTab = (tab: Window) => {
+ if (tab.closed) return;
+ try {
+ tab.close();
+ } catch {
+ // Cross-origin or already-closing windows can reject access.
+ }
+};
+
+/** Drop an old record before a new gesture allocates the single owned tab. */
+const discardOwnedTab = () => {
+ if (!providerTab) return;
+ closeTab(providerTab.tab);
+ providerTab = null;
+};
/**
* The single `window.open` for provider handoffs: blank, and with `opener`
* severed, because the provider page is navigated into it later and would
* otherwise be able to drive this window (reverse tabnabbing).
*/
-export function preopenProviderTab(): Window | null {
+export function preopenProviderTab(purpose: ProviderTabPurpose = 'initial'): Window | null {
+ discardOwnedTab();
try {
const tab = window.open('about:blank', '_blank');
if (tab) {
@@ -33,6 +59,7 @@ export function preopenProviderTab(): Window | null {
} catch {
// Some browser WindowProxy implementations expose a read-only opener.
}
+ providerTab = { tab, state: purpose === 'retry' ? 'retry-pending' : 'claimed' };
}
return tab;
} catch {
@@ -45,7 +72,8 @@ export function preopenProviderTab(): Window | null {
* it. Called from the gesture; claimed by the dialog as it opens.
*/
export function handOffProviderTab(): void {
- handedTab = preopenProviderTab();
+ const tab = preopenProviderTab();
+ if (tab && providerTab) providerTab.state = 'handed';
}
/**
@@ -57,8 +85,43 @@ export function handOffProviderTab(): void {
* a handoff whose journey never opened cannot survive into a later one.
*/
export function takeHandedProviderTab(): Window | null {
- const tab = handedTab;
- handedTab = null;
- if (!tab || tab.closed) return null;
+ if (!providerTab || providerTab.state !== 'handed') return null;
+ if (providerTab.tab.closed) {
+ providerTab = null;
+ return null;
+ }
+ providerTab.state = 'claimed';
+ return providerTab.tab;
+}
+
+/** Commit the retry handoff only once the next flow is definitely starting. */
+export function commitProviderTabRetry(): void {
+ if (providerTab?.state === 'retry-pending') providerTab.state = 'retry-committed';
+}
+
+/**
+ * Take the owned tab for navigation and end this module's ownership. A settled
+ * flow therefore cannot navigate a tab later, even if its auth URL is present.
+ */
+export function takeProviderTabForNavigation(): Window | null {
+ if (!providerTab) return null;
+ const tab = providerTab.tab;
+ providerTab = null;
+ if (tab.closed) return null;
return tab;
}
+
+/**
+ * Dispose the owned tab, or retain a committed Retry tab across effect cleanup.
+ * The caller supplies the shared classifier's value; no second terminal
+ * predicate is allowed in this owner or its callers.
+ */
+export function disposeProviderTab(reason?: ProviderTabDisposalReason): void {
+ if (!providerTab) return;
+ if (providerTab.state === 'retry-committed' && reason === 'cleanup') {
+ providerTab.state = 'handed';
+ return;
+ }
+ closeTab(providerTab.tab);
+ providerTab = null;
+}