The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(onboarding): break the TinyHumans sign-in restart loop and repair the browser hand-off (#7030)
Cyrus Gray5b9abad92359
diff --git a/app/src/components/BootCheckGate/BootCheckGate.tsx b/app/src/components/BootCheckGate/BootCheckGate.tsxindex 066368d9b8..a017bea563 100644--- a/app/src/components/BootCheckGate/BootCheckGate.tsx+++ b/app/src/components/BootCheckGate/BootCheckGate.tsx@@ -37,7 +37,6 @@ import {} from '../../utils/configPersistence';import { isTauri } from '../../utils/tauriCommands/common';import AppBackground from '../AppBackground';-import LanguageSelect from '../LanguageSelect';import Button from '../ui/Button';const log = debug('boot-check');@@ -96,15 +95,6 @@ function Panel({ children }: PanelProps) {);}-function BootCheckLanguageSelect() {- const { t } = useT();- return (- <div className="absolute right-5 top-5">- <LanguageSelect id="boot-check-language" ariaLabel={t('settings.language')} />- </div>- );-}-// ---------------------------------------------------------------------------// Picker (first-ever launch)// ---------------------------------------------------------------------------@@ -242,7 +232,6 @@ function ModePicker({ onConfirm }: PickerProps) {picker by its heading text, so renaming the copy made the wait passvacuously for every spec. */}<div data-testid="boot-check-picker" hidden />- <BootCheckLanguageSelect /><h2 className="text-xl font-semibold text-content">{isDesktop ? t('bootCheck.chooseCoreMode') : t('bootCheck.connectToCore')}</h2>diff --git a/app/src/components/oauth/OAuthProviderButton.tsx b/app/src/components/oauth/OAuthProviderButton.tsxindex 719336f9e1..2a946578bb 100644--- a/app/src/components/oauth/OAuthProviderButton.tsx+++ b/app/src/components/oauth/OAuthProviderButton.tsx@@ -4,8 +4,10 @@ import { useEffect, useRef, useState } from 'react';import { useT } from '../../lib/i18n/I18nContext';import { checkBackendHealthy } from '../../services/backendHealth';import {+ beginAwaitingAuthCallback,beginDeepLinkAuthProcessing,completeDeepLinkAuthProcessing,+ endAwaitingAuthCallback,getDeepLinkAuthState,} from '../../store/deepLinkAuthState';import type { OAuthProviderConfig } from '../../types/oauth';@@ -190,8 +192,13 @@ const OAuthProviderButton = ({const timer = window.setTimeout(() => {log('[%s] timeout -> reset isLoading', provider.id);reset();- // 90s with no deep-link is a strong "something went wrong" signal even- // if the user never refocused the app. Probe so we can attribute it.+ // Stop holding the hand-off screen: after this long the browser is not+ // coming back on its own, and a spinner with no end is worse than a+ // screen that says so.+ endAwaitingAuthCallback();+ // Five minutes with no deep-link is a strong "something went wrong"+ // signal even if the user never refocused the app. Probe so we can+ // attribute it.probeBackendOnReturn('timeout');}, OAUTH_LOADING_TIMEOUT_MS);@@ -340,7 +347,12 @@ const OAuthProviderButton = ({window.location.href = loginUrl;}browserOpenedRef.current = true;+ // The launch step is done, but the sign-in is not: the user is now in+ // another window. Mark that explicitly so the UI can hold a hand-off+ // screen until the callback lands, instead of snapping back to the+ // sign-in buttons a second after the browser opens.completeDeepLinkAuthProcessing();+ beginAwaitingAuthCallback();} catch (error) {completeDeepLinkAuthProcessing();const message = getOAuthStartupFailureMessage(provider, error);diff --git a/app/src/components/oauth/__tests__/OAuthProviderButton.test.tsx b/app/src/components/oauth/__tests__/OAuthProviderButton.test.tsxindex 3663f49ff2..d95201ea5b 100644--- a/app/src/components/oauth/__tests__/OAuthProviderButton.test.tsx+++ b/app/src/components/oauth/__tests__/OAuthProviderButton.test.tsx@@ -3,8 +3,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { checkBackendHealthy } from '../../../services/backendHealth';import {+ beginAwaitingAuthCallback,beginDeepLinkAuthProcessing,completeDeepLinkAuthProcessing,+ endAwaitingAuthCallback,getDeepLinkAuthState,} from '../../../store/deepLinkAuthState';import { handleDeepLinkUrls } from '../../../utils/desktopDeepLinkListener';@@ -35,6 +37,8 @@ vi.mock('../../../utils/desktopDeepLinkListener', () => ({vi.mock('../../../store/deepLinkAuthState', () => ({beginDeepLinkAuthProcessing: vi.fn(),completeDeepLinkAuthProcessing: vi.fn(),+ beginAwaitingAuthCallback: vi.fn(),+ endAwaitingAuthCallback: vi.fn(),getDeepLinkAuthState: vi.fn(),}));@@ -67,6 +71,7 @@ describe('OAuthProviderButton', () => {vi.mocked(isTauri).mockReturnValue(true);vi.mocked(getDeepLinkAuthState).mockReturnValue({isProcessing: false,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -124,6 +129,7 @@ describe('OAuthProviderButton', () => {it('does NOT reset isLoading on focus when a deep-link auth round-trip is processing', async () => {vi.mocked(getDeepLinkAuthState).mockReturnValue({isProcessing: true,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -199,6 +205,29 @@ describe('OAuthProviderButton', () => {expect(screen.getByRole('button', { name: 'Google' })).toBeEnabled();});+ it('ends the awaiting-callback hand-off when the 300s timeout elapses, not before', async () => {+ render(<OAuthProviderButton provider={stubProvider} />);++ fireEvent.click(screen.getByRole('button', { name: 'Google' }));+ await act(async () => {+ for (let i = 0; i < 6; i++) await Promise.resolve();+ });++ // The browser is open: the hand-off flag was raised and not yet dropped.+ expect(beginAwaitingAuthCallback).toHaveBeenCalledTimes(1);+ expect(endAwaitingAuthCallback).not.toHaveBeenCalled();++ await act(async () => {+ vi.advanceTimersByTime(299_999);+ });+ expect(endAwaitingAuthCallback).not.toHaveBeenCalled();++ await act(async () => {+ vi.advanceTimersByTime(1);+ });+ expect(endAwaitingAuthCallback).toHaveBeenCalledTimes(1);+ });+it('honors onClickOverride and skips the OAuth flow', () => {const override = vi.fn();@@ -485,6 +514,7 @@ describe('OAuthProviderButton web dev redirect', () => {vi.mocked(isTauri).mockReturnValue(false);vi.mocked(getDeepLinkAuthState).mockReturnValue({isProcessing: false,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -543,6 +573,7 @@ describe('OAuthProviderButton — every configured provider reaches its own backvi.mocked(isTauri).mockReturnValue(true);vi.mocked(getDeepLinkAuthState).mockReturnValue({isProcessing: false,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,diff --git a/app/src/components/settings/panels/SearchPanelProviders.tsx b/app/src/components/settings/panels/SearchPanelProviders.tsxindex 7ec969011e..d4c023cd20 100644--- a/app/src/components/settings/panels/SearchPanelProviders.tsx+++ b/app/src/components/settings/panels/SearchPanelProviders.tsx@@ -29,6 +29,7 @@ import {canUseManaged,directNeedsSetup,hasBaseUrl,+ isStrandedManaged,rolesSummary,SearchProviderSwatch,STATUS_VARIANT,@@ -76,8 +77,14 @@ const SearchPanelProviders = ({t,}: Props) => {const [dialog, setDialog] = useState<DialogState | null>(null);- const connected = settings.providers.filter(p => p.enabled);- const available = settings.providers.filter(p => !p.enabled);+ // A provider enabled only over the managed route is not connected when this+ // session has no account behind that route — see `isStrandedManaged`.+ const connected = settings.providers.filter(+ p => p.enabled && !isStrandedManaged(p, managedUnavailable)+ );+ const available = settings.providers.filter(+ p => !p.enabled || isStrandedManaged(p, managedUnavailable)+ );const viaTinyHumans = available.filter(p => canUseManaged(p, managedUnavailable));const ownKey = available.filter(p => !canUseManaged(p, managedUnavailable));const dialogProvider = dialog ? settings.providers.find(p => p.id === dialog.id) : undefined;diff --git a/app/src/components/settings/panels/ai/ProviderAuthSection.tsx b/app/src/components/settings/panels/ai/ProviderAuthSection.tsxindex 57d1fd9085..db73b6bcca 100644--- a/app/src/components/settings/panels/ai/ProviderAuthSection.tsx+++ b/app/src/components/settings/panels/ai/ProviderAuthSection.tsx@@ -175,10 +175,19 @@ export const ProviderAuthSection = ({const bySlug = (slug: string) => draft.cloudProviders.find(cp => cp.slug === slug);const connectedCloud = BUILTIN_CLOUD_PROVIDER_SLUGS.filter(slug => bySlug(slug));+const connectedLocal = LOCAL_RUNTIME_SLUGS.filter(slug => bySlug(slug));const customProviders = draft.cloudProviders.filter(cp => !BUILTIN_RESERVED_SLUGS.includes(cp.slug));+ // An empty "Connected" card is a heading over nothing. It used to be+ // guaranteed non-empty by the always-on managed row; now that the row is+ // gated on a real session, a local user with no keys yet got a bare box.+ const hasConnected =+ managedAvailable ||+ connectedCloud.length > 0 ||+ customProviders.length > 0 ||+ connectedLocal.length > 0;// Three categories, each a different question rather than a slice of one:// cloud wants an API key, local wants an endpoint on this machine, CLI wants@@ -299,132 +308,136 @@ export const ProviderAuthSection = ({#3760: it renders a badge, not a disabled toggle — a locked switchreads as switchable-but-broken and invites a fight the user cannotwin. */}- <ProviderGroup- title={t('settings.ai.providers.groupConnected')}- /* The description says "Managed is always on as a fallback. Choose+ {hasConnected && (+ <ProviderGroup+ title={t('settings.ai.providers.groupConnected')}+ /* The description says "Managed is always on as a fallback. Choosewhich provider each task uses on the Routing tab." Both halves arewrong without a managed session: there is no managed fallback, andthe onboarding wizard hides the Routing tab. Shown only where bothare true. */- description={managedAvailable ? t('settings.ai.providers.connectedDesc') : undefined}- card- data-testid="provider-group-connected">- {managedAvailable && (- <ProviderListRow- slug="openhuman"- label={t('settings.ai.routing.managed')}- tone={BUILTIN_PROVIDER_META.openhuman?.tone ?? ''}- detail={t('settings.ai.providers.managedDetail')}- control={<Badge variant="success">{t('settings.ai.routing.managedAlwaysOn')}</Badge>}- data-testid="provider-row-openhuman"- />- )}-- {connectedCloud.map(slug => {- const existing = bySlug(slug)!;- const meta = BUILTIN_PROVIDER_META[slug];- const label = meta?.label ?? slug;- const actions: ProviderRowAction[] = [- {- label: t('settings.ai.providers.replaceKey'),- onSelect: () => onOpenKeyDialog(slug, null),- },- ];- return (+ description={managedAvailable ? t('settings.ai.providers.connectedDesc') : undefined}+ card+ data-testid="provider-group-connected">+ {managedAvailable && (<ProviderListRow- key={slug}- slug={slug}- label={label}- tone={meta?.tone ?? ''}- detail={existing.maskedKey || hostOf(existing.endpoint)}- detailMono+ slug="openhuman"+ label={t('settings.ai.routing.managed')}+ tone={BUILTIN_PROVIDER_META.openhuman?.tone ?? ''}+ detail={t('settings.ai.providers.managedDetail')}control={- <Switch- id={`provider-toggle-${slug}`}- checked- onCheckedChange={async () => await removeProvider(existing, false)}- disabled={busyAction === `toggle-${slug}`}- aria-label={providerToggleAriaLabel(t, true, label)}- />+ <Badge variant="success">{t('settings.ai.routing.managedAlwaysOn')}</Badge>}- actions={actions}- actionsLabel={formatI18n(t('settings.ai.providers.rowActions'), {- provider: label,- })}- data-testid={`provider-row-${slug}`}+ data-testid="provider-row-openhuman"/>- );- })}+ )}- {customProviders.map(existing => (- <ProviderListRow- key={existing.id}- slug={existing.slug}- label={existing.label}- tone={BUILTIN_PROVIDER_META.custom?.tone ?? ''}- detail={hostOf(existing.endpoint) || existing.maskedKey}- detailMono- badge={<Badge variant="primary">{t('settings.ai.providers.custom')}</Badge>}- control={- <Switch- id={`provider-toggle-${existing.slug}`}- checked- onCheckedChange={async () => await removeProvider(existing, false)}- disabled={busyAction === `toggle-${existing.slug}`}- aria-label={providerToggleAriaLabel(t, true, existing.label)}- />- }- actions={[- { label: t('common.edit'), onSelect: () => onEditCustomProvider(existing) },+ {connectedCloud.map(slug => {+ const existing = bySlug(slug)!;+ const meta = BUILTIN_PROVIDER_META[slug];+ const label = meta?.label ?? slug;+ const actions: ProviderRowAction[] = [{- label: t('common.remove'),- destructive: true,- onSelect: () => void removeProvider(existing, false),+ label: t('settings.ai.providers.replaceKey'),+ onSelect: () => onOpenKeyDialog(slug, null),},- ]}- actionsLabel={formatI18n(t('settings.ai.providers.rowActions'), {- provider: existing.label,- })}- data-testid={`provider-row-${existing.slug}`}- />- ))}+ ];+ return (+ <ProviderListRow+ key={slug}+ slug={slug}+ label={label}+ tone={meta?.tone ?? ''}+ detail={existing.maskedKey || hostOf(existing.endpoint)}+ detailMono+ control={+ <Switch+ id={`provider-toggle-${slug}`}+ checked+ onCheckedChange={async () => await removeProvider(existing, false)}+ disabled={busyAction === `toggle-${slug}`}+ aria-label={providerToggleAriaLabel(t, true, label)}+ />+ }+ actions={actions}+ actionsLabel={formatI18n(t('settings.ai.providers.rowActions'), {+ provider: label,+ })}+ data-testid={`provider-row-${slug}`}+ />+ );+ })}- {connectedLocal.map(slug => {- const existing = bySlug(slug)!;- const label = LOCAL_CHIP_LABEL[slug as LocalChipSlug];- return (+ {customProviders.map(existing => (<ProviderListRow- key={slug}- slug={slug}- label={label}- tone={LOCAL_CHIP_TONE[slug as LocalChipSlug]}- // The endpoint is the thing that breaks on a local runtime, so- // it is shown in full rather than reduced to a host.- detail={existing.endpoint || t('settings.ai.providers.connected')}+ key={existing.id}+ slug={existing.slug}+ label={existing.label}+ tone={BUILTIN_PROVIDER_META.custom?.tone ?? ''}+ detail={hostOf(existing.endpoint) || existing.maskedKey}detailMono+ badge={<Badge variant="primary">{t('settings.ai.providers.custom')}</Badge>}control={<Switch- id={`local-runtime-toggle-${slug}`}+ id={`provider-toggle-${existing.slug}`}checked- onCheckedChange={async () => await removeProvider(existing, true)}- disabled={busyAction === `toggle-${slug}`}- aria-label={providerToggleAriaLabel(t, true, label)}+ onCheckedChange={async () => await removeProvider(existing, false)}+ disabled={busyAction === `toggle-${existing.slug}`}+ aria-label={providerToggleAriaLabel(t, true, existing.label)}/>}actions={[+ { label: t('common.edit'), onSelect: () => onEditCustomProvider(existing) },{- label: t('settings.ai.editEndpoint'),- onSelect: () => onOpenKeyDialog(slug, label),+ label: t('common.remove'),+ destructive: true,+ onSelect: () => void removeProvider(existing, false),},]}actionsLabel={formatI18n(t('settings.ai.providers.rowActions'), {- provider: label,+ provider: existing.label,})}- data-testid={`provider-row-${slug}`}+ data-testid={`provider-row-${existing.slug}`}/>- );- })}- </ProviderGroup>+ ))}++ {connectedLocal.map(slug => {+ const existing = bySlug(slug)!;+ const label = LOCAL_CHIP_LABEL[slug as LocalChipSlug];+ return (+ <ProviderListRow+ key={slug}+ slug={slug}+ label={label}+ tone={LOCAL_CHIP_TONE[slug as LocalChipSlug]}+ // The endpoint is the thing that breaks on a local runtime, so+ // it is shown in full rather than reduced to a host.+ detail={existing.endpoint || t('settings.ai.providers.connected')}+ detailMono+ control={+ <Switch+ id={`local-runtime-toggle-${slug}`}+ checked+ onCheckedChange={async () => await removeProvider(existing, true)}+ disabled={busyAction === `toggle-${slug}`}+ aria-label={providerToggleAriaLabel(t, true, label)}+ />+ }+ actions={[+ {+ label: t('settings.ai.editEndpoint'),+ onSelect: () => onOpenKeyDialog(slug, label),+ },+ ]}+ actionsLabel={formatI18n(t('settings.ai.providers.rowActions'), {+ provider: label,+ })}+ data-testid={`provider-row-${slug}`}+ />+ );+ })}+ </ProviderGroup>+ )}{/* ─── CLI logins ────────────────────────────────────────────────Only Claude Code earns a row here, and only once connected: it owns adiff --git a/app/src/components/settings/panels/ai/__tests__/ProviderAuthSection.test.tsx b/app/src/components/settings/panels/ai/__tests__/ProviderAuthSection.test.tsxindex 6ddfba72ee..25e8a45886 100644--- a/app/src/components/settings/panels/ai/__tests__/ProviderAuthSection.test.tsx+++ b/app/src/components/settings/panels/ai/__tests__/ProviderAuthSection.test.tsx@@ -9,7 +9,7 @@ import type { Locale } from '../../../../../lib/i18n/types';import { CoreStateContext } from '../../../../../providers/coreStateContext';import localeReducer from '../../../../../store/localeSlice';import { createLocalSessionToken } from '../../../../../utils/localSession';-import { EMPTY_SETTINGS } from '../aiPanelTypes';+import { type CloudProvider, EMPTY_SETTINGS } from '../aiPanelTypes';import { ProviderAuthSection } from '../ProviderAuthSection';function renderSection(@@ -56,10 +56,17 @@ describe('ProviderAuthSection managed row', () => {it('hides the managed row for a local ("Continue Locally") session', () => {renderSection(createLocalSessionToken());- expect(screen.getByTestId('provider-group-connected')).toBeInTheDocument();expect(screen.queryByTestId('provider-row-openhuman')).not.toBeInTheDocument();});+ it('drops the whole Connected group when nothing is connected', () => {+ // The group used to be guaranteed non-empty by the always-on managed row.+ // With that row gated on a real session, a local user who has not added a+ // key yet was left with a "Connected" heading over an empty card.+ renderSection(createLocalSessionToken());+ expect(screen.queryByTestId('provider-group-connected')).not.toBeInTheDocument();+ });+it('hides the managed row when signed out', () => {renderSection(null);expect(screen.queryByTestId('provider-row-openhuman')).not.toBeInTheDocument();@@ -86,9 +93,85 @@ describe('ProviderAuthSection wizard affordances', () => {);managed.unmount();+ // A local session has nothing connected, so the group — and with it the+ // claim about a managed fallback and the Routing tab — is gone entirely.renderSection(createLocalSessionToken());- expect(screen.getByTestId('provider-group-connected')).not.toHaveTextContent(- 'Managed is always on as a fallback'- );+ expect(screen.queryByTestId('provider-group-connected')).not.toBeInTheDocument();+ expect(screen.queryByText(/Managed is always on as a fallback/)).not.toBeInTheDocument();+ });+});++/**+ * Rows inside the "Connected" group.+ *+ * The group is now gated on actually having something connected, so these rows+ * only render when the draft carries providers. Each shape has its own branch+ * (builtin cloud, user-defined custom, local runtime), and each is rendered+ * here so the gate cannot hide a broken row.+ */+describe('ProviderAuthSection connected rows', () => {+ const provider = (over: Partial<CloudProvider> = {}): CloudProvider => ({+ id: 'p1',+ slug: 'openai',+ label: 'OpenAI',+ endpoint: 'https://api.openai.com/v1',+ authStyle: 'bearer' as CloudProvider['authStyle'],+ maskedKey: 'sk-…4f2a',+ ...over,+ });++ it('renders a connected builtin cloud provider with its masked key', () => {+ renderSection('header.payload.signature', {+ draft: { ...EMPTY_SETTINGS, cloudProviders: [provider()] },+ });++ expect(screen.getByTestId('provider-group-connected')).toBeInTheDocument();+ expect(screen.getByTestId('provider-row-openai')).toHaveTextContent('sk-…4f2a');+ });++ it('renders a user-defined custom provider by host, with edit and remove', () => {+ renderSection('header.payload.signature', {+ draft: {+ ...EMPTY_SETTINGS,+ cloudProviders: [+ provider({ id: 'c1', slug: 'my-proxy', label: 'My Proxy', maskedKey: '' }),+ ],+ },+ });++ const row = screen.getByTestId('provider-row-my-proxy');+ expect(row).toBeInTheDocument();+ // A custom provider shows where it points rather than a key it may not have.+ expect(row).toHaveTextContent('api.openai.com');+ });++ it('renders a local runtime with its full endpoint, not just the host', () => {+ renderSection('header.payload.signature', {+ draft: {+ ...EMPTY_SETTINGS,+ cloudProviders: [+ provider({+ id: 'l1',+ slug: 'ollama',+ label: 'Ollama',+ endpoint: 'http://localhost:11434',+ maskedKey: '',+ }),+ ],+ },+ });++ expect(screen.getByTestId('provider-row-ollama')).toHaveTextContent('http://localhost:11434');+ });++ it('keeps the group for a local session once a provider is connected', () => {+ // The group disappears only while nothing is connected — a local user who+ // has added their own key still needs to see it.+ renderSection(createLocalSessionToken(), {+ draft: { ...EMPTY_SETTINGS, cloudProviders: [provider()] },+ });++ expect(screen.getByTestId('provider-group-connected')).toBeInTheDocument();+ expect(screen.queryByTestId('provider-row-openhuman')).not.toBeInTheDocument();});});diff --git a/app/src/components/settings/panels/searchPanelShared.tsx b/app/src/components/settings/panels/searchPanelShared.tsxindex 82626f762b..4b5a946bf3 100644--- a/app/src/components/settings/panels/searchPanelShared.tsx+++ b/app/src/components/settings/panels/searchPanelShared.tsx@@ -70,6 +70,30 @@ export function statusLabel(status: SearchProviderStatus, t: Translate): stringexport const canUseManaged = (provider: SearchProviderInfo, managedUnavailable: boolean) =>!managedUnavailable && provider.routes.includes('managed') && provider.managed_available;+/**+ * Enabled, but only over the managed route, with no account behind this+ * session.+ *+ * The core reports providers like Exa and Gemini as `enabled` with+ * `route: 'managed'` because they are on by default via TinyHumans. In a local+ * session that route is unreachable, so rendering them under "Connected" with+ * an on-toggle claimed a working provider the agent cannot actually call --+ * the row said "Connected", "via TinyHumans" and "Sign in required" all at+ * once. They belong with the providers you could connect with your own key.+ */+export const isStrandedManaged = (+ provider: SearchProviderInfo,+ managedUnavailable: boolean+): boolean =>+ managedUnavailable &&+ provider.enabled &&+ provider.route === 'managed' &&+ // Only move it if the catalogue can actually offer something: a provider+ // with no direct route would land in a blocked tile with no switch and no+ // action, leaving it enabled in core settings and uncontrollable from here.+ // Those keep their Connected row, where the toggle can still turn them off.+ provider.routes.includes('direct');+/** A provider that can be reached with the user's own key or instance. */export const canUseDirect = (provider: SearchProviderInfo) => provider.routes.includes('direct');diff --git a/app/src/pages/Welcome.tsx b/app/src/pages/Welcome.tsxindex 197035d88f..116184619f 100644--- a/app/src/pages/Welcome.tsx+++ b/app/src/pages/Welcome.tsx@@ -1,7 +1,8 @@import createDebug from 'debug';-import { useState } from 'react';+import { useEffect, useState } from 'react';import { useNavigate } from 'react-router-dom';+import LanguageSelect from '../components/LanguageSelect';import OAuthProviderButton from '../components/oauth/OAuthProviderButton';import { oauthProviderConfigs } from '../components/oauth/providerConfigs';import { Alert, AlertDescription, Button, Card } from '../components/ui';@@ -10,7 +11,11 @@ import { useCoreState } from '../providers/CoreStateProvider';import { clearBackendUrlCache } from '../services/backendUrl';import { clearCoreRpcTokenCache, clearCoreRpcUrlCache } from '../services/coreRpcClient';import { resetCoreMode } from '../store/coreModeSlice';-import { useDeepLinkAuthState } from '../store/deepLinkAuthState';+import {+ endAwaitingAuthCallback,+ getDeepLinkAuthState,+ useDeepLinkAuthState,+} from '../store/deepLinkAuthState';import { useAppDispatch, useAppSelector } from '../store/hooks';import { resolveTheme, setThemeMode, type ThemeMode } from '../store/themeSlice';import { clearAllAppData } from '../utils/clearAllAppData';@@ -36,12 +41,19 @@ const ProviderButtons = () => (</div>);+/**+ * How long a regained focus waits for a deep link before concluding there+ * isn't one. The callback is delivered after the OS focus event, so this has+ * to outlast that gap; it only ever delays *giving up*, never a success.+ */+const CALLBACK_GRACE_MS = 1_500;+const Welcome = () => {const { t } = useT();const navigate = useNavigate();const dispatch = useAppDispatch();const { storeSessionToken } = useCoreState();- const { isProcessing, errorMessage, errorMessageKey, requiresAppDataReset } =+ const { isProcessing, awaitingCallback, errorMessage, errorMessageKey, requiresAppDataReset } =useDeepLinkAuthState();// Deep-link auth runs outside React and cannot translate its own copy, so it// hands over a key for the failures whose copy is localized. Everything else@@ -53,7 +65,6 @@ const Welcome = () => {const [isClearingAppData, setIsClearingAppData] = useState(false);const [isLocalSigningIn, setIsLocalSigningIn] = useState(false);- const [showProviders, setShowProviders] = useState(false);const [resetError, setResetError] = useState<string | null>(null);const [localLoginError, setLocalLoginError] = useState<string | null>(null);@@ -105,6 +116,36 @@ const Welcome = () => {}};+ // Coming back to the app without a callback means the user cancelled, closed+ // the tab, or the redirect failed. End the wait so they get the cards back+ // instead of a spinner that only the 5-minute timeout would clear.+ //+ // The check cannot be synchronous. On a *successful* sign-in the OS focus+ // event arrives BEFORE the deep link does (see the same race documented at+ // `OAuthProviderButton`'s `skipDuringDeepLink`), so reading `isProcessing`+ // the instant focus fires would say "no callback" during a perfectly good+ // round-trip and flash the cards back mid-sign-in. Give the callback a grace+ // window to land, then decide.+ useEffect(() => {+ if (!awaitingCallback) return;+ let graceTimer: ReturnType<typeof setTimeout> | null = null;+ const onFocus = () => {+ if (graceTimer !== null) return;+ graceTimer = setTimeout(() => {+ graceTimer = null;+ const state = getDeepLinkAuthState();+ // Redeeming a callback, or something already ended the wait: leave it.+ if (state.isProcessing || !state.awaitingCallback) return;+ endAwaitingAuthCallback();+ }, CALLBACK_GRACE_MS);+ };+ window.addEventListener('focus', onFocus);+ return () => {+ if (graceTimer !== null) clearTimeout(graceTimer);+ window.removeEventListener('focus', onFocus);+ };+ }, [awaitingCallback]);+const toggleTheme = () => {dispatch(setThemeMode(isDark ? 'light' : 'dark'));};@@ -136,7 +177,11 @@ const Welcome = () => {return (<div className="min-h-full flex flex-col items-center justify-center p-4"><div className="w-full max-w-3xl animate-fade-up">- <div className="flex justify-end">+ <div className="flex items-center justify-end gap-2">+ {/* Language sits with the other presentation control rather than on+ the boot-check panel, which is now a failure-only fallback most+ people never see. */}+ <LanguageSelect id="welcome-language" ariaLabel={t('settings.language')} /><ButtoniconOnlyvariant="tertiary"@@ -201,9 +246,9 @@ const Welcome = () => {take the self-hosted path instead. */}{!requiresAppDataReset ? (<div className="mt-3 flex flex-wrap gap-2">- <div data-testid="welcome-handoff-retry">- <ProviderButtons />- </div>+ {/* No provider buttons here: the TinyHumans card below shows+ them permanently now, so repeating them put two Google+ buttons on screen. Retrying is clicking one of those. */}<Buttonvariant="secondary"size="sm"@@ -242,7 +287,12 @@ const Welcome = () => {</Alert>) : null}- {isProcessing ? (+ {/* `isProcessing` alone is wrong here: it covers an auth STEP, and the+ launch step ends the instant the browser opens — so the hand-off+ appeared for about a second and then dropped the user back to the+ sign-in buttons while they were still in the browser.+ `awaitingCallback` is the actual wait. */}+ {isProcessing || awaitingCallback ? (/* Screen B — the browser hand-off. Sign-in leaves the app entirely,so the window the user comes back to has to say where they are andgive them a way out. A bare spinner said neither. */@@ -257,20 +307,19 @@ const Welcome = () => {<p className="text-base font-semibold text-content">{t('welcome.handoff.title')}</p><p className="mt-1 text-sm text-content-muted">{t('welcome.handoff.body')}</p></div>- {/* The real action, not a button that sets state nothing reads:- the provider buttons only render in the non-processing branch,- so toggling `showProviders` from here did nothing at all. */}- <div data-testid="welcome-handoff-reopen">- <p className="mb-2 text-xs text-content-muted">{t('welcome.handoff.reopen')}</p>- <ProviderButtons />- </div>+ {/* No sign-in buttons here. By this point a provider has been+ picked and the browser is open; repeating the row just asks+ the same question twice. If the browser never comes back, the+ 90s timeout swaps this panel for the failure state, which is+ where the way out belongs. */}</div></Card>) : (<>- {/* Deliberately asymmetric: the TinyHumans card is wider and denser, and- neither card carries a "Recommended" badge. */}- <div className="mt-8 grid grid-cols-1 gap-4 sm:grid-cols-[3fr_2fr]">+ {/* Equal columns. The two paths are a genuine either/or, so neither+ card is sized to argue for itself; the TinyHumans one leads by+ being first and denser. Stacks to one column at phone width. */}+ <div className="mt-8 grid grid-cols-1 items-stretch gap-4 sm:grid-cols-2"><Carddata-testid="welcome-card-tinyhumans"padded@@ -292,7 +341,12 @@ const Welcome = () => {</li>))}</ul>- <div className="rounded-lg bg-primary-50 px-3 py-2 text-center text-sm font-medium text-primary-700">+ {/* A quiet highlight, not a second button. `bg-primary-50`+ alone rendered near-white in dark mode, because the accent+ ramps are identical in both themes and only the shade+ chosen changes — so the dark shade has to be picked+ explicitly. */}+ <div className="rounded-lg border border-primary-200 bg-primary-50 px-3 py-1.5 text-center text-xs font-medium text-primary-700 dark:border-primary-500/30 dark:bg-primary-500/10 dark:text-primary-300">{t('welcome.th.credit')}</div><div className="mt-auto space-y-3">@@ -301,31 +355,25 @@ const Welcome = () => {`openhuman://auth?token=...&state=...`. That hosted single-login pagedoes not exist yet, so for now the CTA reveals the three existingOAuth provider buttons (google, github, twitter). */}- <Button- data-testid="welcome-cta-tinyhumans"- variant="primary"- size="md"- onClick={() => setShowProviders(true)}- aria-expanded={showProviders}- className="w-full py-3">- {t('welcome.th.cta')}- </Button>- {showProviders ? (- <div className="flex flex-wrap items-center justify-center gap-3">- {oauthProviderConfigs- .filter(provider => provider.showOnWelcome)- .map(provider => (- <OAuthProviderButton- key={provider.id}- provider={provider}- className="rounded-full! px-4! py-2!"- />- ))}- </div>- ) : null}+ {/* The providers are the action, so they are on screen.+ A "Continue with TinyHumans" button used to sit here and+ reveal them on click, which was a tap that bought the+ user nothing.++ WHEN THE HOSTED LOGIN LANDS: put that single button back+ in place of this row and have it `openUrl` to the+ tinyhumans.ai login page with `redirectUri` +`state`;+ the page returns `openhuman://auth?token=…&state=…`,+ which `desktopDeepLinkListener` already redeems through+ `loginWithToken` → `POST /auth/login-token/consume`.+ Every piece of that exists except the page itself, which+ is why provider selection is still in the app. */}<p className="text-center text-xs text-content-muted">{t('welcome.th.providers')}</p>+ <div data-testid="welcome-cta-tinyhumans">+ <ProviderButtons />+ </div></div></div></Card>diff --git a/app/src/pages/__tests__/Welcome.test.tsx b/app/src/pages/__tests__/Welcome.test.tsxindex 5b4222a899..f4a86b2d8b 100644--- a/app/src/pages/__tests__/Welcome.test.tsx+++ b/app/src/pages/__tests__/Welcome.test.tsx@@ -1,9 +1,14 @@import { fireEvent, screen, waitFor } from '@testing-library/react';+import { act } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';import { clearBackendUrlCache } from '../../services/backendUrl';import { clearCoreRpcTokenCache, clearCoreRpcUrlCache } from '../../services/coreRpcClient';-import { useDeepLinkAuthState } from '../../store/deepLinkAuthState';+import {+ endAwaitingAuthCallback,+ getDeepLinkAuthState,+ useDeepLinkAuthState,+} from '../../store/deepLinkAuthState';import { renderWithProviders } from '../../test/test-utils';import {clearStoredCoreMode,@@ -54,7 +59,11 @@ vi.mock('../../components/oauth/providerConfigs', () => ({],}));-vi.mock('../../store/deepLinkAuthState', () => ({ useDeepLinkAuthState: vi.fn() }));+vi.mock('../../store/deepLinkAuthState', () => ({+ useDeepLinkAuthState: vi.fn(),+ getDeepLinkAuthState: vi.fn(),+ endAwaitingAuthCallback: vi.fn(),+}));const mockNavigate = vi.fn();vi.mock('react-router-dom', async () => {@@ -106,15 +115,20 @@ vi.mock('../../utils/configPersistence', () => ({normalizeRpcUrl: vi.fn((url: string) => url.trim().replace(/\/+$/, '')),}));-/** The TinyHumans CTA reveals the provider buttons inline; they are not there before. */+/**+ * The provider buttons are rendered unconditionally now, so there is nothing+ * to reveal. Kept as a no-op so the call sites below still read as "the+ * providers are available at this point" rather than being silently deleted.+ */function revealProviders() {- fireEvent.click(screen.getByTestId('welcome-cta-tinyhumans'));+ expect(screen.getByTestId('welcome-cta-tinyhumans')).toBeInTheDocument();}describe('Welcome — two-card layout', () => {beforeEach(() => {vi.mocked(useDeepLinkAuthState).mockReturnValue({isProcessing: false,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -126,25 +140,22 @@ describe('Welcome — two-card layout', () => {expect(screen.getByTestId('welcome-card-tinyhumans')).toBeInTheDocument();expect(screen.getByTestId('welcome-card-self')).toBeInTheDocument();- expect(screen.getByTestId('welcome-cta-tinyhumans')).toHaveTextContent(- 'Continue with TinyHumans'- );+ // The TinyHumans card's action IS the provider row — there is no+ // intermediate button to click through.+ expect(screen.getByTestId('welcome-cta-tinyhumans')).toBeInTheDocument();expect(screen.getByTestId('welcome-cta-self')).toHaveTextContent('Set it up myself');expect(screen.getByTestId('welcome-server-link')).toHaveTextContent('Connect to it.');});- it('keeps provider buttons hidden until the TinyHumans CTA is clicked', () => {+ it('shows the sign-in providers immediately, with no reveal step', () => {+ // A "Continue with TinyHumans" button used to gate these. It revealed the+ // buttons and did nothing else, so it was a tap that bought nothing.renderWithProviders(<Welcome />);- expect(screen.queryByRole('button', { name: 'google' })).not.toBeInTheDocument();- expect(screen.getByTestId('welcome-cta-tinyhumans')).toHaveAttribute('aria-expanded', 'false');-- revealProviders();-- expect(screen.getByTestId('welcome-cta-tinyhumans')).toHaveAttribute('aria-expanded', 'true');expect(screen.getByRole('button', { name: 'google' })).toBeInTheDocument();expect(screen.getByRole('button', { name: 'github' })).toBeInTheDocument();expect(screen.getByRole('button', { name: 'twitter' })).toBeInTheDocument();+ // `showOnWelcome: false` still keeps discord out.expect(screen.queryByRole('button', { name: 'discord' })).not.toBeInTheDocument();});});@@ -156,6 +167,7 @@ describe('Welcome auth entrypoint', () => {vi.mocked(openUrl).mockClear();vi.mocked(useDeepLinkAuthState).mockReturnValue({isProcessing: false,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -207,6 +219,7 @@ describe('Welcome auth entrypoint', () => {it('shows the deep-link processing state when auth is already in progress', () => {vi.mocked(useDeepLinkAuthState).mockReturnValue({isProcessing: true,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -216,14 +229,136 @@ describe('Welcome auth entrypoint', () => {expect(screen.getByTestId('welcome-handoff')).toBeInTheDocument();expect(screen.getByRole('status')).toHaveTextContent('Finishing sign-in in your browser');- expect(screen.getByTestId('welcome-handoff-reopen')).toBeInTheDocument();+ // No sign-in buttons on the hand-off: a provider has already been picked+ // and the browser is open, so repeating the row asks the same question+ // twice. The 90s timeout's failure state is where the way out lives.+ expect(screen.queryByTestId('welcome-handoff-reopen')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'google' })).not.toBeInTheDocument();// The two cards are replaced by the hand-off screen while auth is in flight.expect(screen.queryByTestId('welcome-card-tinyhumans')).not.toBeInTheDocument();});+ it('shows the hand-off panel while awaiting the browser callback, even though no auth step is running', () => {+ vi.mocked(useDeepLinkAuthState).mockReturnValue({+ isProcessing: false,+ awaitingCallback: true,+ errorMessage: null,+ errorMessageKey: null,+ requiresAppDataReset: false,+ });++ renderWithProviders(<Welcome />);++ expect(screen.getByTestId('welcome-handoff')).toBeInTheDocument();+ expect(screen.getByRole('status')).toHaveTextContent('Finishing sign-in in your browser');+ expect(screen.queryByTestId('welcome-card-tinyhumans')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'google' })).not.toBeInTheDocument();+ });++ it('ends the wait when the window regains focus with no callback (cancelled browser flow)', () => {+ vi.mocked(useDeepLinkAuthState).mockReturnValue({+ isProcessing: false,+ awaitingCallback: true,+ errorMessage: null,+ errorMessageKey: null,+ requiresAppDataReset: false,+ });+ vi.mocked(getDeepLinkAuthState).mockReturnValue({+ isProcessing: false,+ awaitingCallback: true,+ errorMessage: null,+ errorMessageKey: null,+ requiresAppDataReset: false,+ });+ vi.mocked(endAwaitingAuthCallback).mockClear();++ vi.useFakeTimers();+ renderWithProviders(<Welcome />);+ act(() => {+ window.dispatchEvent(new FocusEvent('focus'));+ });++ // The grace window has to elapse first: a successful callback arrives+ // after the focus event, so ending the wait on focus alone would cut a+ // good sign-in short.+ expect(endAwaitingAuthCallback).not.toHaveBeenCalled();+ act(() => {+ vi.advanceTimersByTime(1_500);+ });+ expect(endAwaitingAuthCallback).toHaveBeenCalledTimes(1);+ vi.useRealTimers();+ });++ it('keeps the hand-off when the callback lands during the grace window', () => {+ vi.mocked(useDeepLinkAuthState).mockReturnValue({+ isProcessing: false,+ awaitingCallback: true,+ errorMessage: null,+ errorMessageKey: null,+ requiresAppDataReset: false,+ });+ // The real ordering: focus fires while the store still says no auth step+ // is running, and the deep link lands a moment later. Reading the store+ // the instant focus arrives therefore says "cancelled" during a perfectly+ // good sign-in, which is why the decision is deferred.+ let storeProcessing = false;+ vi.mocked(getDeepLinkAuthState).mockImplementation(() => ({+ isProcessing: storeProcessing,+ awaitingCallback: true,+ errorMessage: null,+ errorMessageKey: null,+ requiresAppDataReset: false,+ }));+ vi.mocked(endAwaitingAuthCallback).mockClear();++ vi.useFakeTimers();+ renderWithProviders(<Welcome />);+ act(() => {+ window.dispatchEvent(new FocusEvent('focus'));+ });+ // The callback arrives inside the grace window.+ act(() => {+ vi.advanceTimersByTime(500);+ });+ storeProcessing = true;+ act(() => {+ vi.advanceTimersByTime(1_000);+ });++ expect(endAwaitingAuthCallback).not.toHaveBeenCalled();+ expect(screen.getByTestId('welcome-handoff')).toBeInTheDocument();+ vi.useRealTimers();+ });++ it('keeps waiting on focus when a callback is already being redeemed', () => {+ const redeeming = {+ isProcessing: true,+ awaitingCallback: true,+ errorMessage: null,+ errorMessageKey: null,+ requiresAppDataReset: false,+ };+ vi.mocked(useDeepLinkAuthState).mockReturnValue(redeeming);+ vi.mocked(getDeepLinkAuthState).mockReturnValue(redeeming);+ vi.mocked(endAwaitingAuthCallback).mockClear();++ vi.useFakeTimers();+ renderWithProviders(<Welcome />);+ act(() => {+ window.dispatchEvent(new FocusEvent('focus'));+ });+ act(() => {+ vi.advanceTimersByTime(1_500);+ });++ expect(endAwaitingAuthCallback).not.toHaveBeenCalled();+ vi.useRealTimers();+ });+it('offers retry and a self-hosted fallback when the browser hand-off fails', async () => {vi.mocked(useDeepLinkAuthState).mockReturnValue({isProcessing: false,+ awaitingCallback: false,errorMessage: 'OAuth failed',errorMessageKey: null,requiresAppDataReset: false,@@ -232,8 +367,16 @@ describe('Welcome auth entrypoint', () => {renderWithProviders(<Welcome />);expect(screen.getByRole('alert')).toHaveTextContent("Sign-in didn't come back");- fireEvent.click(screen.getByTestId('welcome-handoff-retry'));- expect(screen.getByRole('button', { name: 'google' })).toBeInTheDocument();+ // Retrying means clicking a provider again, and the card keeps them on+ // screen — the alert deliberately does not repeat them, which would put+ // two Google buttons in the document.+ expect(screen.getAllByRole('button', { name: 'google' })).toHaveLength(1);++ // The retry itself: clicking the provider starts a sign-in again.+ oauthButtonSpy.mockClear();+ fireEvent.click(screen.getByRole('button', { name: 'google' }));+ expect(oauthButtonSpy).toHaveBeenCalledTimes(1);+ expect(oauthButtonSpy).toHaveBeenCalledWith('google');fireEvent.click(screen.getByTestId('welcome-handoff-fallback-self'));await waitFor(() => expect(mockStoreSessionToken).toHaveBeenCalledTimes(1));@@ -243,6 +386,7 @@ describe('Welcome auth entrypoint', () => {it('renders deep-link auth errors', () => {vi.mocked(useDeepLinkAuthState).mockReturnValue({isProcessing: false,+ awaitingCallback: false,errorMessage: 'OAuth failed',errorMessageKey: null,requiresAppDataReset: false,@@ -262,6 +406,7 @@ describe('Welcome — decryption-failure recovery action', () => {mockClearAllAppData.mockReset().mockResolvedValue(undefined);vi.mocked(useDeepLinkAuthState).mockReturnValue({isProcessing: false,+ awaitingCallback: false,errorMessage: "Sign-in failed because OpenHuman couldn't decrypt locally stored data.",errorMessageKey: null,requiresAppDataReset: true,@@ -314,6 +459,7 @@ describe('Welcome — server link (Connect to it.)', () => {beforeEach(() => {vi.mocked(useDeepLinkAuthState).mockReturnValue({isProcessing: false,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -364,6 +510,7 @@ describe('Welcome — OAuth buttons presence', () => {beforeEach(() => {vi.mocked(useDeepLinkAuthState).mockReturnValue({isProcessing: false,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -389,6 +536,7 @@ describe('Welcome — OAuth buttons presence', () => {it('swaps the cards for the hand-off panel while auth is processing', () => {vi.mocked(useDeepLinkAuthState).mockReturnValue({isProcessing: true,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -399,11 +547,11 @@ describe('Welcome — OAuth buttons presence', () => {expect(screen.queryByTestId('welcome-card-tinyhumans')).not.toBeInTheDocument();expect(screen.getByTestId('welcome-handoff')).toBeInTheDocument();- // ...which keeps the sign-in buttons reachable on purpose. Sign-in happens- // in another window, so a user who closed it or never saw it open needs a- // way to reopen it. A control that cannot do that is a dead end.- expect(screen.getByTestId('welcome-handoff-reopen')).toBeInTheDocument();- expect(screen.getByRole('button', { name: 'google' })).toBeInTheDocument();+ // ...and carries no sign-in buttons of its own. A provider has already+ // been chosen and the browser is open; the row would just repeat the+ // question. Recovery lives in the 90s failure state, not here.+ expect(screen.queryByTestId('welcome-handoff-reopen')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'google' })).not.toBeInTheDocument();});});@@ -413,6 +561,7 @@ describe('Welcome — local login', () => {mockNavigate.mockReset();vi.mocked(useDeepLinkAuthState).mockReturnValue({isProcessing: false,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,diff --git a/app/src/providers/CoreStateProvider.tsx b/app/src/providers/CoreStateProvider.tsxindex 845ebad2fe..4870616095 100644--- a/app/src/providers/CoreStateProvider.tsx+++ b/app/src/providers/CoreStateProvider.tsx@@ -33,6 +33,7 @@ import { store } from '../store';import { resetUserScopedState } from '../store/resetActions';import { loadThreads, resetThreadCachesPreservingSelection } from '../store/threadSlice';import { getActiveUserId, setActiveUserId } from '../store/userScopedStorage';+import { markIdentityFlipSeed } from '../utils/bootstrapActiveUser';import { isLocalSessionToken } from '../utils/localSession';import {getSessionToken,@@ -210,6 +211,10 @@ async function handleIdentityFlip(opts: { reason: string; nextUserId: string }):const { reason, nextUserId } = opts;log('identity flip restart reason=%s nextUserId=%s', reason, `****${nextUserId.slice(-4)}`);setActiveUserId(nextUserId);+ // Survive the relaunch. In local core mode the next boot primes from the+ // core's `active_user.toml`, which still names the previous user and would+ // undo the line above -- restarting again, forever (#4545).+ markIdentityFlipSeed(nextUserId);store.dispatch(resetUserScopedState());socketService.disconnect();await restartApp();diff --git a/app/src/providers/__tests__/CoreStateProvider.identityFlip.test.tsx b/app/src/providers/__tests__/CoreStateProvider.identityFlip.test.tsxindex 50cae67d34..0dca980ca2 100644--- a/app/src/providers/__tests__/CoreStateProvider.identityFlip.test.tsx+++ b/app/src/providers/__tests__/CoreStateProvider.identityFlip.test.tsx@@ -11,6 +11,7 @@ import { socketService } from '../../services/socketService';import { store } from '../../store';import { addAccount } from '../../store/accountsSlice';import { resetUserScopedState } from '../../store/resetActions';+import { consumeIdentityFlipSeed } from '../../utils/bootstrapActiveUser';import CoreStateProvider, { useCoreState } from '../CoreStateProvider';vi.mock('../../services/coreStateApi');@@ -108,6 +109,8 @@ describe('CoreStateProvider — identity flip cleanup (#900)', () => {resetCoreStateStore();store.dispatch(resetUserScopedState());userScopedStorage.setActiveUserId(null);+ // Drop any flip marker a previous case left in localStorage.+ consumeIdentityFlipSeed();});it('cold bootstrap on a fresh device (seed=null, nextId=A): sets activeUserId without restart (#3107)', async () => {@@ -343,4 +346,40 @@ describe('CoreStateProvider — identity flip cleanup (#900)', () => {setActiveSpy.mockRestore();disconnectSpy.mockRestore();});++ it('records the identity-flip seed for the NEXT user before restartApp runs (#4545 loop guard)', async () => {+ userScopedStorage.setActiveUserId('A');+ fetchSnapshot.mockResolvedValue(makeSnapshot({ userId: 'A', sessionToken: 'tokA' }));+ const disconnectSpy = vi.spyOn(socketService, 'disconnect').mockImplementation(() => {});++ let ctx: CoreStateContextValue | undefined;+ render(+ <CoreStateProvider>+ <Consumer captureCtx={c => (ctx = c)} />+ </CoreStateProvider>+ );+ await act(async () => {+ await ctx!.refresh();+ });+ // Warm launch on A writes no marker.+ expect(consumeIdentityFlipSeed()).toBeNull();++ // The relaunched process reads the marker on boot, so what matters is+ // what is in storage at the moment the restart is requested.+ let seedAtRestart: string | null = null;+ restartApp.mockImplementation(async () => {+ seedAtRestart = consumeIdentityFlipSeed();+ });++ fetchSnapshot.mockResolvedValue(makeSnapshot({ userId: 'B', sessionToken: 'tokB' }));+ await act(async () => {+ await ctx!.refresh();+ await Promise.resolve();+ });++ expect(restartApp).toHaveBeenCalledTimes(1);+ expect(seedAtRestart).toBe('B');++ disconnectSpy.mockRestore();+ });});diff --git a/app/src/store/__tests__/deepLinkAuthState.test.ts b/app/src/store/__tests__/deepLinkAuthState.test.tsindex 3a639b0302..d9e5b4aeff 100644--- a/app/src/store/__tests__/deepLinkAuthState.test.ts+++ b/app/src/store/__tests__/deepLinkAuthState.test.ts@@ -2,8 +2,10 @@ import { act, renderHook } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';import {+ beginAwaitingAuthCallback,beginDeepLinkAuthProcessing,completeDeepLinkAuthProcessing,+ endAwaitingAuthCallback,failDeepLinkAuthProcessing,getDeepLinkAuthState,subscribeDeepLinkAuthState,@@ -15,6 +17,11 @@ import {* before each test's assertions. The ad-hoc store persists across tests.*/afterEach(() => {+ // `beginAwaitingAuthCallback` arms a module-level 300s timer and+ // `completeDeepLinkAuthProcessing` deliberately leaves it (and the flag)+ // alone, so drop both here or they leak into the next test.+ endAwaitingAuthCallback();+ vi.useRealTimers();completeDeepLinkAuthProcessing();});@@ -23,6 +30,7 @@ describe('deepLinkAuthState transitions', () => {completeDeepLinkAuthProcessing();expect(getDeepLinkAuthState()).toEqual({isProcessing: false,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -36,6 +44,7 @@ describe('deepLinkAuthState transitions', () => {beginDeepLinkAuthProcessing();expect(getDeepLinkAuthState()).toEqual({isProcessing: true,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -47,6 +56,7 @@ describe('deepLinkAuthState transitions', () => {completeDeepLinkAuthProcessing();expect(getDeepLinkAuthState()).toEqual({isProcessing: false,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -58,6 +68,7 @@ describe('deepLinkAuthState transitions', () => {failDeepLinkAuthProcessing('token expired');expect(getDeepLinkAuthState()).toEqual({isProcessing: false,+ awaitingCallback: false,errorMessage: 'token expired',errorMessageKey: null,requiresAppDataReset: false,@@ -68,6 +79,7 @@ describe('deepLinkAuthState transitions', () => {failDeepLinkAuthProcessing('cannot decrypt', { requiresAppDataReset: true });expect(getDeepLinkAuthState()).toEqual({isProcessing: false,+ awaitingCallback: false,errorMessage: 'cannot decrypt',errorMessageKey: null,requiresAppDataReset: true,@@ -81,6 +93,7 @@ describe('deepLinkAuthState transitions', () => {failDeepLinkAuthProcessing('', { messageKey: 'welcome.coreConfigUnreadable' });expect(getDeepLinkAuthState()).toEqual({isProcessing: false,+ awaitingCallback: false,errorMessage: '',errorMessageKey: 'welcome.coreConfigUnreadable',requiresAppDataReset: false,@@ -152,6 +165,7 @@ describe('useDeepLinkAuthState hook', () => {const { result } = renderHook(() => useDeepLinkAuthState());expect(result.current).toEqual({isProcessing: false,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -162,6 +176,7 @@ describe('useDeepLinkAuthState hook', () => {});expect(result.current).toEqual({isProcessing: true,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -172,9 +187,62 @@ describe('useDeepLinkAuthState hook', () => {});expect(result.current).toEqual({isProcessing: false,+ awaitingCallback: false,errorMessage: 'denied',errorMessageKey: null,requiresAppDataReset: false,});});});++describe('awaitingCallback', () => {+ // This flag exists because `isProcessing` ends the moment the browser opens,+ // which made the hand-off screen vanish while the user was still in it.+ it('spans the browser round-trip and is cleared by the arriving callback', () => {+ beginAwaitingAuthCallback();+ expect(getDeepLinkAuthState().awaitingCallback).toBe(true);++ // The launch step finishing must NOT end the wait.+ completeDeepLinkAuthProcessing();+ expect(getDeepLinkAuthState().awaitingCallback).toBe(true);++ // Redeeming an arriving deep link does.+ beginDeepLinkAuthProcessing();+ expect(getDeepLinkAuthState().awaitingCallback).toBe(false);+ });++ it('is cleared by a failure and by an explicit end', () => {+ beginAwaitingAuthCallback();+ failDeepLinkAuthProcessing('nope');+ expect(getDeepLinkAuthState().awaitingCallback).toBe(false);++ beginAwaitingAuthCallback();+ endAwaitingAuthCallback();+ expect(getDeepLinkAuthState().awaitingCallback).toBe(false);+ });++ it('ending when not waiting is a no-op', () => {+ completeDeepLinkAuthProcessing();+ expect(getDeepLinkAuthState().awaitingCallback).toBe(false);+ endAwaitingAuthCallback();+ expect(getDeepLinkAuthState().awaitingCallback).toBe(false);+ });++ it('gives up by itself after 300s, with no component mounted to do it', () => {+ vi.useFakeTimers();+ beginAwaitingAuthCallback();++ vi.advanceTimersByTime(299_999);+ expect(getDeepLinkAuthState().awaitingCallback).toBe(true);++ vi.advanceTimersByTime(1);+ expect(getDeepLinkAuthState().awaitingCallback).toBe(false);+ });++ it('a callback arriving cancels the pending timeout', () => {+ vi.useFakeTimers();+ beginAwaitingAuthCallback();+ beginDeepLinkAuthProcessing();+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/app/src/store/deepLinkAuthState.ts b/app/src/store/deepLinkAuthState.tsindex 77d5551377..7133b839d8 100644--- a/app/src/store/deepLinkAuthState.ts+++ b/app/src/store/deepLinkAuthState.ts@@ -1,7 +1,19 @@import { useSyncExternalStore } from 'react';interface DeepLinkAuthState {+ /**+ * An auth STEP is executing. True twice per sign-in and briefly each time:+ * once while the login URL is being prepared and the browser opened, and+ * again while an arriving deep link is redeemed. It is NOT "waiting for the+ * user to finish in the browser" — `awaitingCallback` is.+ */isProcessing: boolean;+ /**+ * The user has been handed to the system browser and the callback has not+ * come back yet. Spans the whole time the app is idle waiting on another+ * window, which is exactly the window a hand-off screen must cover.+ */+ awaitingCallback: boolean;errorMessage: string | null;// i18n key to render INSTEAD of `errorMessage`, for failures whose copy is// translated. This module is reached from non-React code (the deep-link@@ -19,6 +31,7 @@ interface DeepLinkAuthState {const initialState: DeepLinkAuthState = {isProcessing: false,+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -48,8 +61,11 @@ export const subscribeDeepLinkAuthState = (listener: () => void): (() => void) =};export const beginDeepLinkAuthProcessing = (): void => {+ clearAwaitTimer();setDeepLinkAuthState({isProcessing: true,+ // A callback that has arrived is no longer awaited.+ awaitingCallback: false,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -59,6 +75,7 @@ export const beginDeepLinkAuthProcessing = (): void => {export const completeDeepLinkAuthProcessing = (): void => {setDeepLinkAuthState({isProcessing: false,+ awaitingCallback: deepLinkAuthState.awaitingCallback,errorMessage: null,errorMessageKey: null,requiresAppDataReset: false,@@ -69,13 +86,56 @@ export const failDeepLinkAuthProcessing = (message: string,options: { requiresAppDataReset?: boolean; messageKey?: string } = {}): void => {+ clearAwaitTimer();setDeepLinkAuthState({isProcessing: false,+ awaitingCallback: false,errorMessage: message,errorMessageKey: options.messageKey ?? null,requiresAppDataReset: Boolean(options.requiresAppDataReset),});};+/**+ * How long to hold the hand-off before giving up on the browser.+ *+ * Matches the loopback listener's own lifetime: past this point no callback+ * can arrive, so continuing to show a spinner is a lie.+ */+const AWAIT_CALLBACK_TIMEOUT_MS = 300_000;+let awaitTimer: ReturnType<typeof setTimeout> | null = null;++const clearAwaitTimer = (): void => {+ if (awaitTimer === null) return;+ clearTimeout(awaitTimer);+ awaitTimer = null;+};++/**+ * The browser is open and we are waiting on it. Called right after `openUrl`+ * succeeds, because `completeDeepLinkAuthProcessing()` fires immediately after+ * that and would otherwise drop the UI back to the sign-in screen while the+ * user is still in the browser.+ */+export const beginAwaitingAuthCallback = (): void => {+ clearAwaitTimer();+ // The timer lives here, not in the component that started the sign-in: the+ // hand-off screen unmounts that component, which would take the only way of+ // ever clearing this flag with it and strand the user on a spinner with no+ // control. Module scope outlives any mount.+ awaitTimer = setTimeout(() => {+ awaitTimer = null;+ endAwaitingAuthCallback();+ }, AWAIT_CALLBACK_TIMEOUT_MS);+ setDeepLinkAuthState({ ...deepLinkAuthState, awaitingCallback: true });+};++/** Stop waiting — the callback arrived, failed, or the user gave up. */+export const endAwaitingAuthCallback = (): void => {+ clearAwaitTimer();+ if (!deepLinkAuthState.awaitingCallback) return;+ setDeepLinkAuthState({ ...deepLinkAuthState, awaitingCallback: false });+};+export const useDeepLinkAuthState = (): DeepLinkAuthState =>useSyncExternalStore(subscribeDeepLinkAuthState, getDeepLinkAuthState, getDeepLinkAuthState);diff --git a/app/src/store/userScopedStorage.ts b/app/src/store/userScopedStorage.tsindex 15d0ab7160..b4368e5a93 100644--- a/app/src/store/userScopedStorage.ts+++ b/app/src/store/userScopedStorage.ts@@ -135,6 +135,39 @@ export function setActiveUserId(id: string | null): void {}}+/**+ * The id an identity flip is restarting *into*.+ *+ * This is a sibling of `ACTIVE_USER_KEY` and lives here for the same reason:+ * it is read during bootstrap to *decide* the active user, so it cannot be+ * namespaced by one. A scoped marker would be written under the outgoing+ * user's namespace and looked for under the incoming one, which is the #4545+ * restart loop it exists to break. It lives in this module rather than at the+ * call site so every unscoped identity key stays in the module that owns the+ * scope.+ */+const IDENTITY_FLIP_SEED_KEY = 'OPENHUMAN_IDENTITY_FLIP_SEED';++/** Record the id the flip is restarting into. */+export function markIdentityFlipSeed(userId: string): void {+ try {+ localStorage.setItem(IDENTITY_FLIP_SEED_KEY, userId);+ } catch {+ // Storage unavailable: the loop guard is best-effort, not load-bearing.+ }+}++/** Read and clear the marker. Returns null when no flip is pending. */+export function consumeIdentityFlipSeed(): string | null {+ try {+ const id = localStorage.getItem(IDENTITY_FLIP_SEED_KEY);+ if (id) localStorage.removeItem(IDENTITY_FLIP_SEED_KEY);+ return id && id.trim() ? id : null;+ } catch {+ return null;+ }+}+/*** One-shot migration for users upgrading from the pre-#900 build, where* persist blobs lived at unscoped keys (`persist:accounts`, etc.). On thediff --git a/app/src/utils/__tests__/bootstrapActiveUser.test.ts b/app/src/utils/__tests__/bootstrapActiveUser.test.tsindex 08c8bc5596..0ae36479cd 100644--- a/app/src/utils/__tests__/bootstrapActiveUser.test.ts+++ b/app/src/utils/__tests__/bootstrapActiveUser.test.ts@@ -14,7 +14,12 @@*/import { describe, expect, test, vi } from 'vitest';-import { resolveActiveUserBootstrap, shouldSkipLocalActiveUserRead } from '../bootstrapActiveUser';+import {+ consumeIdentityFlipSeed,+ markIdentityFlipSeed,+ resolveActiveUserBootstrap,+ shouldSkipLocalActiveUserRead,+} from '../bootstrapActiveUser';describe('shouldSkipLocalActiveUserRead', () => {test('cloud mode skips the local read', () => {@@ -122,3 +127,76 @@ describe('gateway mode is a remote core, not a local one', () => {expect(getActiveUserIdFromCore).not.toHaveBeenCalled();});});++describe('identity-flip seed marker (#4545, local-core variant)', () => {+ // The loop this guards: sign in with TinyHumans after using "Continue+ // Locally". `handleIdentityFlip` corrects the seed and restarts, but a LOCAL+ // core re-primes from `active_user.toml`, which still names the local user.+ // The next refresh sees the same mismatch and restarts again, forever.+ it('prefers a pending flip seed over the core file, and consumes it once', async () => {+ const getActiveUserIdFromCore = vi.fn().mockResolvedValue('local-stale-user');+ const consumeIdentityFlipSeed = vi+ .fn()+ .mockReturnValueOnce('tinyhumans-user')+ .mockReturnValue(null);++ const first = await resolveActiveUserBootstrap({+ isStandaloneNativeWindow: false,+ coreMode: 'local',+ getActiveUserIdFromCore,+ consumeIdentityFlipSeed,+ });+ expect(first).toBe('tinyhumans-user');+ // The stale file is never consulted while a flip is pending.+ expect(getActiveUserIdFromCore).not.toHaveBeenCalled();++ // Second boot: the marker is spent, so the normal source takes over.+ const second = await resolveActiveUserBootstrap({+ isStandaloneNativeWindow: false,+ coreMode: 'local',+ getActiveUserIdFromCore,+ consumeIdentityFlipSeed,+ });+ expect(second).toBe('local-stale-user');+ expect(getActiveUserIdFromCore).toHaveBeenCalledTimes(1);+ });++ it('leaves cloud mode on its existing path when no flip is pending', async () => {+ const getActiveUserIdFromCore = vi.fn().mockResolvedValue('should-not-be-read');+ const resolved = await resolveActiveUserBootstrap({+ isStandaloneNativeWindow: false,+ coreMode: 'cloud',+ getActiveUserIdFromCore,+ consumeIdentityFlipSeed: () => null,+ });+ expect(resolved).toBeNull();+ expect(getActiveUserIdFromCore).not.toHaveBeenCalled();+ });+});++describe('consumeIdentityFlipSeed storage failures', () => {+ // Private windows, cleared site data and quota errors all make localStorage+ // throw. The loop guard is best-effort: it must degrade to "no flip pending"+ // rather than take the boot path down with it.+ it('returns null when reading localStorage throws', () => {+ const getItem = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {+ throw new Error('SecurityError');+ });+ try {+ expect(consumeIdentityFlipSeed()).toBeNull();+ } finally {+ getItem.mockRestore();+ }+ });++ it('round-trips a marker and clears it so the next boot sees nothing', () => {+ markIdentityFlipSeed('user-abc');+ expect(consumeIdentityFlipSeed()).toBe('user-abc');+ expect(consumeIdentityFlipSeed()).toBeNull();+ });++ it('treats a blank marker as no flip pending', () => {+ markIdentityFlipSeed(' ');+ expect(consumeIdentityFlipSeed()).toBeNull();+ });+});diff --git a/app/src/utils/__tests__/desktopDeepLinkListener.test.ts b/app/src/utils/__tests__/desktopDeepLinkListener.test.tsindex ffcff2d6db..254992ff4f 100644--- a/app/src/utils/__tests__/desktopDeepLinkListener.test.ts+++ b/app/src/utils/__tests__/desktopDeepLinkListener.test.ts@@ -187,6 +187,7 @@ describe('desktopDeepLinkListener', () => {expect(windowControls.setFocus).toHaveBeenCalledTimes(1);expect(getDeepLinkAuthState()).toEqual({isProcessing: false,+ awaitingCallback: false,// Literal copy, not a key: only the localized failures carry one.errorMessageKey: null,errorMessage:diff --git a/app/src/utils/bootstrapActiveUser.ts b/app/src/utils/bootstrapActiveUser.tsindex 069d4cd412..32fa69e790 100644--- a/app/src/utils/bootstrapActiveUser.ts+++ b/app/src/utils/bootstrapActiveUser.ts@@ -1,3 +1,5 @@+import { consumeIdentityFlipSeed, markIdentityFlipSeed } from '../store/userScopedStorage';+/*** Decide which async source seeds `userScopedStorage`'s active-user id at* boot, before `primeActiveUserId(...)` runs.@@ -21,6 +23,12 @@* `userScopedStorage.ts::primeActiveUserId` and the "cloud-mode reload* survival" test.*/+// The marker itself lives with `OPENHUMAN_ACTIVE_USER_ID` in+// `userScopedStorage.ts`: both are unscoped by necessity because they are read+// to *decide* the active user. Re-exported here because this is where the+// bootstrap reads it.+export { consumeIdentityFlipSeed, markIdentityFlipSeed };+/** Every core mode the picker and the gateway section can persist. */type StoredCoreMode = 'local' | 'cloud' | 'gateway' | null;@@ -28,6 +36,8 @@ interface BootstrapContext {isStandaloneNativeWindow: boolean;coreMode: StoredCoreMode;getActiveUserIdFromCore: () => Promise<string | null>;+ /** Injectable for tests; defaults to the module-level reader. */+ consumeIdentityFlipSeed?: () => string | null;}export function shouldSkipLocalActiveUserRead(opts: {@@ -43,6 +53,17 @@ export function shouldSkipLocalActiveUserRead(opts: {}export function resolveActiveUserBootstrap(ctx: BootstrapContext): Promise<string | null> {+ // A pending flip outranks every other source: it is the id this process was+ // restarted in order to adopt.+ // `?? consumeIdentityFlipSeed()` would fall through to the module reader+ // whenever an injected one returned null, so a test that deliberately says+ // "no flip pending" still hit real storage.+ const readFlipSeed = ctx.consumeIdentityFlipSeed ?? consumeIdentityFlipSeed;+ const flipped = readFlipSeed();+ if (flipped) {+ return Promise.resolve<string | null>(flipped);+ }+if (shouldSkipLocalActiveUserRead({isStandaloneNativeWindow: ctx.isStandaloneNativeWindow,