Skip to content

The agent that grows with you

feat(desktop): sign-in result shows who signed in and what moved (#143236)

Siddharth Balyan20428afaf323
diff --git a/apps/desktop/ENGINEERING.md b/apps/desktop/ENGINEERING.md
index 5a01082a372..7974846ab8e 100644
--- a/apps/desktop/ENGINEERING.md
+++ b/apps/desktop/ENGINEERING.md
@@ -157,7 +157,13 @@ notice_pending, model, label) read from local auth state with zero network, and
first-launch ready screen and the own-key strip are the SAME state rendered for two situations,
keyed on `notice_pending`; there is no localStorage latch, so the CLI and the desktop cannot
disagree about whether the notice was shown. Sign-in goes through the existing
-`POST /api/providers/oauth/nous/start` + poll route, which over a free-tier identity registers the
-connector transfer and reports `reason`, `account_email` and `model` on completion; every entry
-point (Billing, status chip, ready screen) opens the one free-tier sign-in dialog. Never branch on
+`POST /api/providers/oauth/nous/start` + poll route, which the dialog long-polls (`?wait=`: the
+backend answers once the session leaves `pending`; the loop never asks again sooner than 2 s, so an
+older backend that answers at once is not hammered). On completion it reports `reason`,
+`account_email`, `model` and `handoff_status` (what the replaced free tier's apps did, with the
+backend's own copy in `lines`); a move still retrying is followed through the
+`/api/providers/oauth/nous/handoff` long-poll until it settles or the dialog closes. Every entry
+point (Billing, status chip, ready screen) opens the one free-tier sign-in dialog, and a Nous sign-in
+from the onboarding picker that moved apps shows the same result screen once onboarding leaves the
+screen (onboarding paints above every dialog). Never branch on
provider display names: the picker row carries `free_tier_row`, status cards carry `free_tier`.
diff --git a/apps/desktop/src/api/config.ts b/apps/desktop/src/api/config.ts
index 9548b7f2d1b..976f79976e4 100644
--- a/apps/desktop/src/api/config.ts
+++ b/apps/desktop/src/api/config.ts
@@ -1,4 +1,5 @@
import type {
+ AppHandoffStatus,
ConfigSchemaResponse,
CustomEndpointsResponse,
CustomEndpointUpdate,
@@ -353,14 +354,37 @@ export function submitOAuthCode(
})
}
+// A long-poll waits this long at most for a change (the backend caps it at 25 s); the request's own
+// timeout leaves room for the hold plus a slow answer.
+export const OAUTH_LONG_POLL_SECONDS = 25
+const OAUTH_LONG_POLL_TIMEOUT_MS = 45_000
+
+/** One sign-in poll. With `waitSeconds` it is a long-poll: the backend answers
+ * once the session leaves `pending`, or after the wait with `pending`. */
export function pollOAuthSession(
providerId: string,
sessionId: string,
- profile?: ProfileScope
+ profile?: ProfileScope,
+ waitSeconds = 0
): Promise<OAuthPollResponse> {
+ const query = waitSeconds > 0 ? `?wait=${waitSeconds}` : ''
+
return window.hermesDesktop.api<OAuthPollResponse>({
...capabilityScoped(profile),
- path: `/api/providers/oauth/${encodeURIComponent(providerId)}/poll/${encodeURIComponent(sessionId)}`
+ path: `/api/providers/oauth/${encodeURIComponent(providerId)}/poll/${encodeURIComponent(sessionId)}${query}`,
+ ...(waitSeconds > 0 ? { timeoutMs: OAUTH_LONG_POLL_TIMEOUT_MS } : {})
+ })
+}
+
+/** The free tier's handoff after a Nous sign-in. A long-poll: given `since`
+ * (the `updated_at` on screen) the backend answers once the record changes. */
+export function getNousHandoffStatus(since: null | string, profile?: ProfileScope): Promise<AppHandoffStatus> {
+ const query = new URLSearchParams({ wait: String(OAUTH_LONG_POLL_SECONDS), ...(since ? { since } : {}) })
+
+ return window.hermesDesktop.api<AppHandoffStatus>({
+ ...capabilityScoped(profile),
+ path: `/api/providers/oauth/nous/handoff?${query}`,
+ timeoutMs: OAUTH_LONG_POLL_TIMEOUT_MS
})
}
diff --git a/apps/desktop/src/components/free-tier/sign-in-dialog.test.tsx b/apps/desktop/src/components/free-tier/sign-in-dialog.test.tsx
index 009a4562b97..ab598eec742 100644
--- a/apps/desktop/src/components/free-tier/sign-in-dialog.test.tsx
+++ b/apps/desktop/src/components/free-tier/sign-in-dialog.test.tsx
@@ -6,7 +6,7 @@ import type * as HermesApi from '@/hermes'
import { $freeTierStatus } from '@/store/free-tier'
import { $freeTierSignIn, noteFreeTierTurnComplete, openFreeTierSignIn } from '@/store/free-tier-sign-in'
import { markOnboardingDecided, setOnboardingSurfaceActive } from '@/store/onboarding-presence'
-import type { FreeTierStatus } from '@/types/hermes'
+import type { AppHandoffStatus, FreeTierStatus } from '@/types/hermes'
const pollOAuthSession = vi.fn()
// The two answers the dialog reads: `free_tier.status` and `free_tier.claim_nudge`.
@@ -20,6 +20,8 @@ const requestGateway = vi.fn(async (_method?: string): Promise<GatewayAnswer> =>
vi.mock('@/hermes', async importOriginal => ({
...(await importOriginal<typeof HermesApi>()),
pollOAuthSession: (providerId: string, sessionId: string) => pollOAuthSession(providerId, sessionId),
+ getGlobalModelOptions: async () => ({ providers: [] }),
+ getNousHandoffStatus: async () => ({ lines: [], state: 'idle' }),
startOAuthLogin: async () => ({
expires_in: 900,
flow: 'device_code' as const,
@@ -41,6 +43,7 @@ beforeEach(() => {
afterEach(() => {
cleanup()
+ window.location.hash = ''
$freeTierSignIn.set({ status: 'closed' })
$freeTierStatus.set(null)
setOnboardingSurfaceActive('onboarding', false)
@@ -50,9 +53,9 @@ afterEach(() => {
})
describe('FreeTierSignInDialog', () => {
- it('shows the transfer code, then the signed-in screen once the poll approves', async () => {
+ it('shows the code small, then the signed-in screen once the poll approves', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
- pollOAuthSession.mockResolvedValue({
+ pollOAuthSession.mockResolvedValueOnce({ session_id: 'session-1', status: 'pending' }).mockResolvedValue({
account_email: '[email protected]',
model: 'Hermes-4-405B',
reason: null,
@@ -74,17 +77,84 @@ describe('FreeTierSignInDialog', () => {
openFreeTierSignIn()
})
- await waitFor(() => expect(screen.getByText('Do not share this code.')).toBeTruthy())
+ await waitFor(() => expect(screen.getByText('Finish in your browser')).toBeTruthy())
+ expect(screen.getByText('ABCD-EFGH')).toBeTruthy()
+ expect(screen.getByText('Do not share it.')).toBeTruthy()
- // The 2s poll tick is what carries the approval through to the last screen.
await act(async () => {
await vi.advanceTimersByTimeAsync(2100)
})
- await waitFor(() => expect(screen.getByText('Signed in as [email protected]')).toBeTruthy())
+ await waitFor(() => expect(screen.getByText('Signed in as')).toBeTruthy())
+ expect(screen.getByText('[email protected]')).toBeTruthy()
+ expect(screen.getByText('Your account now carries inference and tools.')).toBeTruthy()
expect(screen.getByText('Hermes-4-405B')).toBeTruthy()
})
+ describe('result screen', () => {
+ async function renderCompleted(handoff: AppHandoffStatus | null) {
+ const { FreeTierSignInDialog } = await import('./sign-in-dialog')
+
+ await act(async () => {
+ render(
+ <QueryClientProvider client={new QueryClient()}>
+ <FreeTierSignInDialog />
+ </QueryClientProvider>
+ )
+ })
+ await act(async () =>
+ $freeTierSignIn.set({ email: '[email protected]', handoff, model: null, status: 'completed' })
+ )
+ }
+
+ it('shows what moved in the backend lines, and Reconnect opens the app left behind', async () => {
+ await renderCompleted({
+ dropped_toolkits: ['slack'],
+ lines: ['Your apps moved to [email protected]: gmail.', 'Reconnect in [email protected]: slack.'],
+ moved_toolkits: ['gmail'],
+ state: 'claimed'
+ })
+
+ expect(screen.getByText('Your apps moved to [email protected]: gmail.')).toBeTruthy()
+ expect(screen.getByText('Reconnect in [email protected]: slack.')).toBeTruthy()
+ expect(screen.queryByText('Your account now carries inference and tools.')).toBeNull()
+
+ await act(async () => screen.getByRole('button', { name: 'Reconnect' }).click())
+
+ expect(window.location.hash).toBe('#/capabilities?tab=connectors&connector=slack')
+ expect($freeTierSignIn.get()).toEqual({ status: 'closed' })
+ })
+
+ it('Reconnect for a sign-in made for another profile names that profile in the link', async () => {
+ const { connectorsTarget } = await import('./sign-in-dialog')
+ const handoff: AppHandoffStatus = { dropped_toolkits: ['slack'], lines: ['x'], state: 'claimed' }
+
+ expect(connectorsTarget(handoff, { connectionId: 'athena', profile: 'work' })).toBe(
+ '/capabilities?tab=connectors&connector=slack&profile=work&connection=athena'
+ )
+ expect(connectorsTarget(handoff, 'work')).toBe('/capabilities?tab=connectors&connector=slack&profile=work')
+ expect(connectorsTarget(handoff)).toBe('/capabilities?tab=connectors&connector=slack')
+ })
+
+ it('a move still retrying is a waiting note with no connectors button', async () => {
+ await renderCompleted({ lines: ['Moving your free-tier apps to this account.'], state: 'retrying' })
+
+ expect(screen.getByRole('status').textContent).toContain('Moving your free-tier apps to this account.')
+ expect(screen.queryByRole('button', { name: 'Reconnect' })).toBeNull()
+ expect(screen.queryByRole('button', { name: 'Open Connectors' })).toBeNull()
+ })
+
+ it('apps that probably moved already offer a look at Connectors', async () => {
+ await renderCompleted({
+ lines: ['Your free-tier apps were probably moved already.'],
+ probably_moved: true,
+ state: 'gone'
+ })
+
+ expect(screen.getByRole('button', { name: 'Open Connectors' })).toBeTruthy()
+ })
+ })
+
describe('sign-in offer', () => {
const dueNow = { available: true, enabled: true, has_guest: true, label: '', model: '', notice_pending: false }
@@ -101,6 +171,7 @@ describe('FreeTierSignInDialog', () => {
}
beforeEach(() => {
+ pollOAuthSession.mockResolvedValue({ session_id: 'session-1', status: 'pending' })
requestGateway.mockImplementation(async (method?: string) =>
method === 'free_tier.claim_nudge' ? { claimed: true } : { ...dueNow, nudge_due_in: null }
)
@@ -145,7 +216,7 @@ describe('FreeTierSignInDialog', () => {
await act(async () => screen.getByRole('button', { name: 'Sign in' }).click())
- await waitFor(() => expect(screen.getByText('Do not share this code.')).toBeTruthy())
+ await waitFor(() => expect(screen.getByText('Do not share it.')).toBeTruthy())
})
it('Not now closes the offer', async () => {
diff --git a/apps/desktop/src/components/free-tier/sign-in-dialog.tsx b/apps/desktop/src/components/free-tier/sign-in-dialog.tsx
index 56489045d9f..8524abb288a 100644
--- a/apps/desktop/src/components/free-tier/sign-in-dialog.tsx
+++ b/apps/desktop/src/components/free-tier/sign-in-dialog.tsx
@@ -1,11 +1,10 @@
import { useStore } from '@nanostores/react'
import { useQueryClient } from '@tanstack/react-query'
-import type * as React from 'react'
import { type ReactNode, useEffect, useId } from 'react'
import { useGatewayRequest } from '@/app/gateway/hooks/use-gateway-request'
+import { CAPABILITIES_ROUTE } from '@/app/routes'
import type { ModelSelection } from '@/app/shell/model-menu-panel'
-import { DeviceCode } from '@/components/onboarding/flow'
import { Button } from '@/components/ui/button'
import {
Dialog,
@@ -15,7 +14,7 @@ import {
DialogTitle,
preventCloseButtonAutoFocus
} from '@/components/ui/dialog'
-import { getGlobalModelOptions } from '@/hermes'
+import { getGlobalModelOptions, type ProfileScope } from '@/hermes'
import { type Translations, useI18n } from '@/i18n'
import { CheckCircle2, Loader2 } from '@/lib/icons'
import {
@@ -31,11 +30,12 @@ import {
beginFreeTierSignIn,
claimFreeTierSignIn,
closeFreeTierSignIn,
- copyFreeTierCode,
- copyFreeTierUrl,
freeTierSignInClaim,
type FreeTierSignInFailure,
+ type FreeTierSignInState,
+ handoffStillMoving,
releaseFreeTierSignIn,
+ reopenFreeTierSignInPage,
sameGatewayRoute,
stopFreeTierOffer,
syncFreeTierOffer
@@ -44,6 +44,7 @@ import { $localModelOfferPending } from '@/store/local-model-offer'
import { refreshOnboardingProviders } from '@/store/onboarding'
import { $onboardingSurfaceClear } from '@/store/onboarding-presence'
import { $currentModel, setModelPickerOpen } from '@/store/session'
+import type { AppHandoffStatus } from '@/types/hermes'
interface FreeTierSignInDialogProps {
/** The app's model-assignment path. Used only to re-home a live session that
@@ -163,29 +164,22 @@ export function FreeTierSignInDialog({ onSelectModel }: FreeTierSignInDialogProp
)}
{state.status === 'code' && (
- <Screen body={copy.codeBody} heading={copy.signInHeading}>
- <DeviceCode code={state.code} copied={state.codeCopied} onCopy={() => void copyFreeTierCode()} />
- <div className="flex min-w-0 items-center justify-between gap-3">
- <a
- className="min-w-0 truncate text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary) underline underline-offset-2 hover:text-foreground"
- href={state.url}
- rel="noreferrer"
- target="_blank"
- >
- {state.url}
- </a>
- <Button onClick={() => void copyFreeTierUrl()} size="xs" type="button" variant="text">
- {state.urlCopied ? t.common.copied : copy.copyLink}
- </Button>
- </div>
- <p className="text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">
+ <Screen heading={copy.finishInBrowser}>
+ {/* The code is only there to compare with the browser page, so it stays small. */}
+ <p className="flex flex-wrap items-baseline gap-x-2 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">
+ <span className="font-mono text-sm tracking-widest text-foreground">{state.code}</span>
{copy.doNotShare}
</p>
<div className="flex items-center justify-between gap-3">
<Spinner>{copy.waiting}</Spinner>
- <Button onClick={() => closeFreeTierSignIn()} size="sm" type="button" variant="ghost">
- {t.common.cancel}
- </Button>
+ <div className="flex items-center gap-2">
+ <Button onClick={() => void reopenFreeTierSignInPage()} size="sm" type="button" variant="text">
+ {copy.openPageAgain}
+ </Button>
+ <Button onClick={() => closeFreeTierSignIn()} size="sm" type="button" variant="ghost">
+ {t.common.cancel}
+ </Button>
+ </div>
</div>
</Screen>
)}
@@ -196,37 +190,7 @@ export function FreeTierSignInDialog({ onSelectModel }: FreeTierSignInDialogProp
</Screen>
)}
- {state.status === 'completed' && (
- <Screen
- body={copy.completedBody}
- heading={state.email ? copy.signedInAs(state.email) : copy.signedIn}
- icon={CheckCircle2}
- >
- {state.model && (
- <div className="flex min-w-0 flex-wrap items-center gap-2">
- <span className="font-mono text-[0.625rem] uppercase tracking-[0.2em] text-muted-foreground">
- {copy.defaultModel}
- </span>
- <span className="min-w-0 truncate font-mono text-[length:var(--conversation-text-font-size)]">
- {state.model}
- </span>
- <Button
- onClick={() => finish(state.model, () => setModelPickerOpen(true))}
- size="inline"
- type="button"
- variant="text"
- >
- {copy.change}
- </Button>
- </div>
- )}
- <Actions>
- <Button onClick={() => finish(state.model)} type="button">
- {copy.done}
- </Button>
- </Actions>
- </Screen>
- )}
+ {state.status === 'completed' && <SignedInScreen copy={copy} finish={finish} state={state} />}
{state.status === 'already_signed_in' && (
<Screen body={copy.alreadySignedInBody} heading={copy.alreadySignedInHeading}>
@@ -251,7 +215,7 @@ export function FreeTierSignInDialog({ onSelectModel }: FreeTierSignInDialogProp
request) has nothing to retry: the backend's sentence names the way out. */}
{state.kind === 'unavailable' ? null : (
<Button onClick={retry} type="button">
- {state.kind === 'superseded' ? copy.startAgain : copy.tryAgain}
+ {copy.tryAgain}
</Button>
)}
</Actions>
@@ -289,15 +253,6 @@ function failureBody(
// in when an older backend sent none.
return message ?? copy.busyBody(friendlyWait(retryAfter || 60))
- case 'rejected':
- return copy.rejectedBody
-
- case 'retired':
- return copy.retiredBody
-
- case 'superseded':
- return copy.supersededBody
-
case 'timed_out':
return copy.timedOutBody
@@ -311,21 +266,11 @@ function failureBody(
}
}
-function Screen({
- body,
- children,
- heading,
- icon
-}: {
- body?: string
- children: ReactNode
- heading: string
- icon?: React.ComponentType<{ className?: string }>
-}) {
+function Screen({ body, children, heading }: { body?: string; children: ReactNode; heading: string }) {
return (
<>
<DialogHeader>
- <DialogTitle icon={icon}>{heading}</DialogTitle>
+ <DialogTitle>{heading}</DialogTitle>
{body ? <DialogDescription>{body}</DialogDescription> : null}
</DialogHeader>
{children}
@@ -348,3 +293,121 @@ function Spinner({ children }: { children: ReactNode }) {
function Actions({ children }: { children: ReactNode }) {
return <div className="flex items-center justify-end gap-2">{children}</div>
}
+
+/** The result screen: who is signed in, set large, then what the free tier's apps did. */
+function SignedInScreen({
+ copy,
+ finish,
+ state
+}: {
+ copy: FreeTierCopy
+ finish: (model: null | string, after?: () => void) => void
+ state: Extract<FreeTierSignInState, { status: 'completed' }>
+}) {
+ const { email, handoff, model, scope } = state
+
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle icon={CheckCircle2}>{email ? copy.signedInAsLabel : copy.signedIn}</DialogTitle>
+ {email ? (
+ <p className="min-w-0 truncate text-xl font-semibold tracking-tight text-foreground">{email}</p>
+ ) : null}
+ {handoff?.lines.length ? null : <DialogDescription>{copy.completedBody}</DialogDescription>}
+ </DialogHeader>
+ {handoff ? <HandoffResult handoff={handoff} /> : null}
+ {model && (
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <span className="font-mono text-[0.625rem] uppercase tracking-[0.2em] text-muted-foreground">
+ {copy.defaultModel}
+ </span>
+ <span className="min-w-0 truncate font-mono text-[length:var(--conversation-text-font-size)]">{model}</span>
+ <Button
+ onClick={() => finish(model, () => setModelPickerOpen(true))}
+ size="inline"
+ type="button"
+ variant="text"
+ >
+ {copy.change}
+ </Button>
+ </div>
+ )}
+ <Actions>
+ {connectorsTarget(handoff, scope) ? (
+ <Button
+ onClick={() => finish(model, () => openConnectors(handoff, scope))}
+ size="sm"
+ type="button"
+ variant="text"
+ >
+ {handoff?.state === 'claimed' ? copy.reconnect : copy.openConnectors}
+ </Button>
+ ) : null}
+ <Button onClick={() => finish(model)} type="button">
+ {copy.done}
+ </Button>
+ </Actions>
+ </>
+ )
+}
+
+/** What the free tier's apps did, in the backend's own lines. While the move
+ * is still retried the line is a small note that updates itself. */
+function HandoffResult({ handoff }: { handoff: AppHandoffStatus }) {
+ if (!handoff.lines.length) {
+ return null
+ }
+
+ if (handoffStillMoving(handoff)) {
+ return <Spinner>{handoff.lines.join(' ')}</Spinner>
+ }
+
+ return (
+ <div className="grid gap-1 text-[length:var(--conversation-text-font-size)] text-foreground">
+ {handoff.lines.map(line => (
+ <p key={line}>{line}</p>
+ ))}
+ </div>
+ )
+}
+
+/** Where the completed screen's connectors button goes: the one app to
+ * reconnect, the whole list for several, or the list to check when the apps
+ * probably moved already. Null when there is nothing to do there. A sign-in
+ * made for another profile names it (and its connection), the same way a
+ * chat's connector links do, so the page acts in that profile only. */
+export function connectorsTarget(handoff: AppHandoffStatus | null, scope?: ProfileScope): null | string {
+ const dropped = handoff?.state === 'claimed' ? (handoff.dropped_toolkits ?? []) : []
+ const checkMoved = handoff?.state === 'gone' && handoff.probably_moved === true
+
+ if (!dropped.length && !checkMoved) {
+ return null
+ }
+
+ const params = new URLSearchParams({ tab: 'connectors' })
+
+ if (dropped.length === 1) {
+ params.set('connector', dropped[0])
+ }
+
+ const profile = (typeof scope === 'object' ? scope?.profile : scope)?.trim()
+ const connectionId = typeof scope === 'object' ? scope?.connectionId?.trim() : null
+
+ if (profile) {
+ params.set('profile', profile)
+
+ if (connectionId) {
+ params.set('connection', connectionId)
+ }
+ }
+
+ return `${CAPABILITIES_ROUTE}?${params.toString()}`
+}
+
+function openConnectors(handoff: AppHandoffStatus | null, scope?: ProfileScope) {
+ const target = connectorsTarget(handoff, scope)
+
+ if (target) {
+ window.location.hash = `#${target}`
+ }
+}
diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.ts
index ef95e807e35..fa52d7628c5 100644
--- a/apps/desktop/src/i18n/de.ts
+++ b/apps/desktop/src/i18n/de.ts
@@ -4343,28 +4343,25 @@ export const deOverrides = {
signIn: 'Anmelden',
signInHeading: 'Melden Sie sich mit einem Nous-Konto an, um mehr Modelle und Tools freizuschalten.',
settingUp: 'Kostenlose Inferenz wird eingerichtet…',
- codeBody: 'Geben Sie diesen Code in Ihrem Browser ein, um die Anmeldung abzuschließen.',
- copyLink: 'Link kopieren',
+ finishInBrowser: 'Im Browser abschließen',
doNotShare: 'Diesen Code nicht weitergeben.',
+ openPageAgain: 'Seite erneut öffnen',
waiting: 'Warten auf Anmeldung…',
finishingHeading: 'Anmeldung wird abgeschlossen…',
finishingBody: 'Im Browser bestätigt. Ihre Konto-Tokens werden abgerufen.',
- signedInAs: email => `Angemeldet als ${email}`,
+ signedInAsLabel: 'Angemeldet als',
signedIn: 'Angemeldet.',
completedBody: 'Ihr Konto hat jetzt Zugriff auf Inferenz und Tools.',
+ reconnect: 'Neu verbinden',
+ openConnectors: 'Konnektoren öffnen',
defaultModel: 'Standardmodell',
change: 'Ändern',
done: 'Fertig',
notNow: 'Nicht jetzt',
tryAgain: 'Erneut versuchen',
- startAgain: 'Neu starten',
didNotComplete: 'Anmeldung nicht abgeschlossen',
- rejectedBody: 'Die Anmeldung wurde im Browser abgelehnt. Sie bleiben im kostenlosen Tarif.',
- supersededBody: 'Ein neuerer Anmeldecode hat diesen ersetzt.',
timedOutHeading: 'Anmeldung abgelaufen',
timedOutBody: 'Der Code wurde nicht rechtzeitig verwendet. Sie bleiben im kostenlosen Tarif.',
- retiredBody:
- 'Diese Gratis-Tarif-Identität wurde bereits verwendet oder ist abgelaufen; beim nächsten Start wird eine neue eingerichtet.',
errorBody: 'Die Anmeldung wurde nicht abgeschlossen; starten Sie sie erneut.',
busyHeading: 'Fast geschafft',
busyBody: wait =>
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index d5e5b0dd55b..57a5b060464 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -3911,28 +3911,25 @@ export const en: Translations = {
signIn: 'Sign in',
signInHeading: 'Sign in with a Nous account to unlock more models and tools.',
settingUp: 'Setting up free inference…',
- codeBody: 'Enter this code in your browser to finish signing in.',
- copyLink: 'Copy link',
- doNotShare: 'Do not share this code.',
+ finishInBrowser: 'Finish in your browser',
+ doNotShare: 'Do not share it.',
+ openPageAgain: 'Open page again',
waiting: 'Waiting for sign-in…',
finishingHeading: 'Finishing sign-in…',
finishingBody: 'Approved in the browser. Collecting your account tokens.',
- signedInAs: email => `Signed in as ${email}`,
+ signedInAsLabel: 'Signed in as',
signedIn: 'Signed in.',
completedBody: 'Your account now carries inference and tools.',
+ reconnect: 'Reconnect',
+ openConnectors: 'Open Connectors',
defaultModel: 'Default model',
change: 'Change',
done: 'Done',
notNow: 'Not now',
tryAgain: 'Try again',
- startAgain: 'Start again',
didNotComplete: "Sign-in didn't finish",
- rejectedBody: "No problem, you're still on the free Nous service. Sign in whenever you're ready.",
- supersededBody: 'A newer sign-in code replaced this one. Use the newest one, or start again.',
timedOutHeading: 'That sign-in link has expired',
timedOutBody: "Start again whenever you're ready. You're still on the free Nous service.",
- retiredBody:
- "Your session ended before the sign-in finished. Hermes will start a new one; then sign in again whenever you're ready.",
errorBody: "Sign-in didn't finish. Try again whenever you're ready.",
busyHeading: 'Almost there',
busyBody: wait =>
diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.ts
index 666b6f482e9..34a9287d0f6 100644
--- a/apps/desktop/src/i18n/es.ts
+++ b/apps/desktop/src/i18n/es.ts
@@ -4334,29 +4334,25 @@ export const esOverrides = {
signIn: 'Iniciar sesión',
signInHeading: 'Inicia sesión con una cuenta de Nous para desbloquear más modelos y herramientas.',
settingUp: 'Configurando la inferencia gratuita…',
- codeBody: 'Introduce este código en tu navegador para terminar de iniciar sesión.',
- copyLink: 'Copiar enlace',
+ finishInBrowser: 'Termina en tu navegador',
doNotShare: 'No compartas este código.',
+ openPageAgain: 'Abrir la página de nuevo',
waiting: 'Esperando el inicio de sesión…',
finishingHeading: 'Terminando el inicio de sesión…',
finishingBody: 'Aprobado en el navegador. Obteniendo los tokens de tu cuenta.',
- signedInAs: (email: string) => `Sesión iniciada como ${email}`,
+ signedInAsLabel: 'Sesión iniciada como',
signedIn: 'Sesión iniciada.',
completedBody: 'Tu cuenta ya incluye inferencia y herramientas.',
+ reconnect: 'Reconectar',
+ openConnectors: 'Abrir Conectores',
defaultModel: 'Modelo predeterminado',
change: 'Cambiar',
done: 'Listo',
notNow: 'Ahora no',
tryAgain: 'Reintentar',
- startAgain: 'Empezar de nuevo',
didNotComplete: 'No se completó el inicio de sesión',
- rejectedBody: 'No pasa nada, sigues en el servicio gratuito de Nous. Inicia sesión cuando quieras.',
- supersededBody:
- 'Un código de inicio de sesión más reciente sustituyó a este. Usa el más reciente o empieza de nuevo.',
timedOutHeading: 'Ese enlace de inicio de sesión caducó',
timedOutBody: 'Empieza de nuevo cuando quieras. Sigues en el servicio gratuito de Nous.',
- retiredBody:
- 'Tu sesión terminó antes de completar el inicio de sesión. Hermes iniciará una nueva; luego vuelve a iniciar sesión cuando quieras.',
errorBody: 'No se completó el inicio de sesión. Vuelve a intentarlo cuando quieras.',
busyHeading: 'Ya casi está',
busyBody: (wait: string) =>
diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.ts
index a75b1320f7b..3585156c94d 100644
--- a/apps/desktop/src/i18n/fr.ts
+++ b/apps/desktop/src/i18n/fr.ts
@@ -4351,28 +4351,25 @@ export const frOverrides = {
signIn: 'Se connecter',
signInHeading: 'Connectez-vous avec un compte Nous pour débloquer davantage de modèles et outils.',
settingUp: "Configuration de l'inférence gratuite…",
- codeBody: 'Saisissez ce code dans votre navigateur pour terminer la connexion.',
- copyLink: 'Copier le lien',
+ finishInBrowser: 'Terminez dans votre navigateur',
doNotShare: 'Ne partagez pas ce code.',
+ openPageAgain: 'Rouvrir la page',
waiting: 'En attente de la connexion…',
finishingHeading: 'Finalisation de la connexion…',
finishingBody: 'Autorisation accordée dans le navigateur. Récupération des jetons de votre compte.',
- signedInAs: email => `Connecté en tant que ${email}`,
+ signedInAsLabel: 'Connecté en tant que',
signedIn: 'Connecté.',
completedBody: "Votre compte donne maintenant accès à l'inférence et aux outils.",
+ reconnect: 'Reconnecter',
+ openConnectors: 'Ouvrir les connecteurs',
defaultModel: 'Modèle par défaut',
change: 'Modifier',
done: 'Terminé',
notNow: 'Pas maintenant',
tryAgain: 'Réessayer',
- startAgain: 'Recommencer',
didNotComplete: "La connexion n'a pas abouti",
- rejectedBody: "La connexion a été refusée dans le navigateur. Vous restez sur l'offre gratuite.",
- supersededBody: 'Un code de connexion plus récent a remplacé celui-ci.',
timedOutHeading: 'Délai de connexion dépassé',
timedOutBody: "Le code n'a pas été utilisé à temps. Vous restez sur l'offre gratuite.",
- retiredBody:
- "Cette identité d'offre gratuite a déjà été utilisée ou a expiré ; une nouvelle sera créée au prochain démarrage.",
errorBody: "La connexion n'a pas abouti ; relancez-la.",
busyHeading: 'Presque terminé',
busyBody: wait =>
diff --git a/apps/desktop/src/i18n/overlay-gaps.json b/apps/desktop/src/i18n/overlay-gaps.json
index 104b28be8e5..4e0ec247671 100644
--- a/apps/desktop/src/i18n/overlay-gaps.json
+++ b/apps/desktop/src/i18n/overlay-gaps.json
@@ -695,27 +695,27 @@
"freeTier.busyBody": ["ar","ja","ru","zh","zh-hant"],
"freeTier.busyHeading": ["ar","ja","ru","zh","zh-hant"],
"freeTier.change": ["ar","ja","ru","zh-hant"],
- "freeTier.codeBody": ["ar","ja","ru","zh-hant"],
"freeTier.completedBody": ["ar","ja","ru","zh-hant"],
- "freeTier.copyLink": ["ar","ja","ru","zh-hant"],
"freeTier.defaultModel": ["ar","ja","ru","zh-hant"],
"freeTier.didNotComplete": ["ar","ja","ru","zh-hant"],
"freeTier.dismiss": ["ar","ja","ru","zh-hant"],
"freeTier.doNotShare": ["ar","ja","ru","zh-hant"],
"freeTier.done": ["ar","ja","ru","zh-hant"],
"freeTier.errorBody": ["ar","ja","ru","zh-hant"],
+ "freeTier.finishInBrowser": ["ar","ja","ru","zh-hant"],
"freeTier.finishingBody": ["ar","ja","ru","zh-hant"],
"freeTier.finishingHeading": ["ar","ja","ru","zh-hant"],
"freeTier.notNow": ["ar","ja","ru","zh-hant"],
+ "freeTier.openConnectors": ["ar","ja","ru","zh-hant"],
"freeTier.openModelPicker": ["ar","ja","ru","zh-hant"],
+ "freeTier.openPageAgain": ["ar","ja","ru","zh-hant"],
"freeTier.otherProviders": ["ar","ja","ru","zh-hant"],
"freeTier.providerName": ["ar","ja","ru","zh-hant"],
"freeTier.providerRowPitch": ["ar","ja","ru","zh-hant"],
"freeTier.providerRowTitle": ["ar","ja","ru","zh-hant"],
"freeTier.readyCaption": ["ar","ja","ru","zh-hant"],
"freeTier.readyTitle": ["ar","ja","ru","zh-hant"],
- "freeTier.rejectedBody": ["ar","ja","ru","zh-hant"],
- "freeTier.retiredBody": ["ar","ja","ru","zh-hant"],
+ "freeTier.reconnect": ["ar","ja","ru","zh-hant"],
"freeTier.settingUp": ["ar","ja","ru","zh-hant"],
"freeTier.setupFailed.gateClosed": ["ar","ja","ru","zh","zh-hant"],
"freeTier.setupFailed.generic": ["ar","ja","ru","zh","zh-hant"],
@@ -732,12 +732,10 @@
"freeTier.signInHeading": ["ar","ja","ru","zh-hant"],
"freeTier.signInInstead": ["ar","ja","ru","zh-hant"],
"freeTier.signedIn": ["ar","ja","ru","zh-hant"],
- "freeTier.signedInAs": ["ar","ja","ru","zh-hant"],
- "freeTier.startAgain": ["ar","ja","ru","zh-hant"],
+ "freeTier.signedInAsLabel": ["ar","ja","ru","zh-hant"],
"freeTier.statusLabel": ["ar","ja","ru","zh-hant"],
"freeTier.stripBody": ["ar","ja","ru","zh-hant"],
"freeTier.stripTitle": ["ar","ja","ru","zh-hant"],
- "freeTier.supersededBody": ["ar","ja","ru","zh-hant"],
"freeTier.timedOutBody": ["ar","ja","ru","zh-hant"],
"freeTier.timedOutHeading": ["ar","ja","ru","zh-hant"],
"freeTier.tryAgain": ["ar","ja","ru","zh-hant"],
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 3511a4424c1..0f2e489af4f 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -3378,27 +3378,27 @@ catalog: CatalogTranslations
signIn: string
signInHeading: string
settingUp: string
- codeBody: string
- copyLink: string
+ finishInBrowser: string
doNotShare: string
+ openPageAgain: string
waiting: string
finishingHeading: string
finishingBody: string
- signedInAs: (email: string) => string
+ /** Over the account email on the completed screen. */
+ signedInAsLabel: string
signedIn: string
completedBody: string
+ /** The free tier's apps: reconnect the ones that did not move; open Connectors to check. */
+ reconnect: string
+ openConnectors: string
defaultModel: string
change: string
done: string
notNow: string
tryAgain: string
- startAgain: string
didNotComplete: string
- rejectedBody: string
- supersededBody: string
timedOutHeading: string
timedOutBody: string
- retiredBody: string
errorBody: string
/** The account service asked for a short wait mid sign-in (a busy account, a rate limit, the ops pause). */
busyHeading: string
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 5b808e471c3..485376eb48b 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -3783,27 +3783,25 @@ export const zhOverrides = {
signIn: '登录',
signInHeading: '登录 Nous 账户以解锁更多模型和工具。',
settingUp: '正在设置免费推理…',
- codeBody: '在浏览器中输入此代码以完成登录。',
- copyLink: '复制链接',
+ finishInBrowser: '在浏览器中完成',
doNotShare: '请勿分享此代码。',
+ openPageAgain: '重新打开页面',
waiting: '等待登录…',
finishingHeading: '正在完成登录…',
finishingBody: '已在浏览器中批准。正在获取账户令牌。',
- signedInAs: email => `已登录为 ${email}`,
+ signedInAsLabel: '已登录为',
signedIn: '已登录。',
completedBody: '现在由你的账户提供推理和工具。',
+ reconnect: '重新连接',
+ openConnectors: '打开连接器',
defaultModel: '默认模型',
change: '更改',
done: '完成',
notNow: '暂不',
tryAgain: '重试',
- startAgain: '重新开始',
didNotComplete: '登录未完成',
- rejectedBody: '登录在浏览器中被拒绝。你仍在免费层。',
- supersededBody: '一个更新的登录代码替换了此代码。',
timedOutHeading: '登录超时',
timedOutBody: '代码未在有效期内使用。你仍在免费层。',
- retiredBody: '此免费层身份已被使用或已过期;下次启动时会重新设置。',
errorBody: '登录未完成;请重试。',
alreadySignedInHeading: '已登录。',
alreadySignedInBody: '此 Hermes 已登录 Nous 账户。',
diff --git a/apps/desktop/src/lib/long-poll.ts b/apps/desktop/src/lib/long-poll.ts
new file mode 100644
index 00000000000..f9ecde80a2c
--- /dev/null
+++ b/apps/desktop/src/lib/long-poll.ts
@@ -0,0 +1,13 @@
+// The sign-in and handoff reads are long-polls: the backend holds each request until something
+// changes. An older backend answers at once, so a loop never asks again sooner than this after its
+// previous ask started.
+export const LONG_POLL_MIN_GAP_MS = 2000
+
+export function pause(ms: number): Promise<void> {
+ return new Promise(resolve => window.setTimeout(resolve, ms))
+}
+
+/** Wait out the rest of the minimum gap after an ask that started at `askedAt` (`Date.now()`). */
+export function restOfLongPollGap(askedAt: number): Promise<void> {
+ return pause(Math.max(0, LONG_POLL_MIN_GAP_MS - (Date.now() - askedAt)))
+}
diff --git a/apps/desktop/src/store/free-tier-sign-in.test.ts b/apps/desktop/src/store/free-tier-sign-in.test.ts
index 8a3bd206873..ee326587e6b 100644
--- a/apps/desktop/src/store/free-tier-sign-in.test.ts
+++ b/apps/desktop/src/store/free-tier-sign-in.test.ts
@@ -2,16 +2,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as HermesApi from '@/hermes'
import type { FreeTierRequester } from '@/store/free-tier'
+import { markOnboardingDecided, setOnboardingSurfaceActive } from '@/store/onboarding-presence'
+import type { AppHandoffStatus } from '@/types/hermes'
const startOAuthLogin = vi.fn()
const pollOAuthSession = vi.fn()
const cancelOAuthSession = vi.fn(async (_id: string) => ({ ok: true }))
+const getNousHandoffStatus = vi.fn()
vi.mock('@/hermes', async importOriginal => ({
...(await importOriginal<typeof HermesApi>()),
cancelOAuthSession: (id: string) => cancelOAuthSession(id),
+ getNousHandoffStatus: (since: null | string) => getNousHandoffStatus(since),
listOAuthProviders: async () => ({ providers: [] }),
- pollOAuthSession: (providerId: string, sessionId: string) => pollOAuthSession(providerId, sessionId),
+ pollOAuthSession: (providerId: string, sessionId: string, _profile?: unknown, wait?: number) =>
+ pollOAuthSession(providerId, sessionId, wait),
startOAuthLogin: () => startOAuthLogin()
}))
@@ -71,7 +76,6 @@ describe('free-tier sign-in failure screens', () => {
it('maps the account service verdicts onto ruled screens', async () => {
const { signInFailureKind } = await import('./free-tier-sign-in')
- expect(signInFailureKind('account_busy')).toBe('busy')
expect(signInFailureKind('anon_rate_limited')).toBe('busy')
expect(signInFailureKind('anon_gate_paused')).toBe('busy')
expect(signInFailureKind('anon_unreachable')).toBe('unreachable')
@@ -79,7 +83,7 @@ describe('free-tier sign-in failure screens', () => {
expect(signInFailureKind('anon_gate_closed')).toBe('unavailable')
expect(signInFailureKind('anon_pow_required')).toBe('unavailable')
expect(signInFailureKind('anon_account_locked')).toBe('unavailable')
- expect(signInFailureKind('user_declined')).toBe('rejected')
+ expect(signInFailureKind('timeout')).toBe('timed_out')
expect(signInFailureKind('wat')).toBe('error')
expect(signInFailureKind(null)).toBe('error')
})
@@ -107,3 +111,138 @@ describe('free-tier sign-in failure screens', () => {
})
})
})
+
+describe('free-tier sign-in long-polls', () => {
+ it('long-polls the sign-in, and never asks again sooner than the gap when the backend answers at once', async () => {
+ const { beginFreeTierSignIn } = await import('./free-tier-sign-in')
+ startOAuthLogin.mockResolvedValueOnce(start('session-poll'))
+ pollOAuthSession.mockResolvedValue({ session_id: 'session-poll', status: 'pending' })
+
+ await beginFreeTierSignIn(requestGateway)
+ await vi.advanceTimersByTimeAsync(10)
+
+ expect(pollOAuthSession).toHaveBeenCalledTimes(1)
+ expect(pollOAuthSession).toHaveBeenCalledWith('nous', 'session-poll', 25)
+
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(pollOAuthSession).toHaveBeenCalledTimes(2)
+ })
+
+ const approvedWith = (handoff: AppHandoffStatus) => ({
+ account_email: '[email protected]',
+ handoff_status: handoff,
+ model: null,
+ session_id: 'session-moved',
+ status: 'approved'
+ })
+
+ const retrying: AppHandoffStatus = {
+ lines: ['Moving your free-tier apps to this account.'],
+ state: 'retrying',
+ updated_at: 't1'
+ }
+
+ it('follows a move that is still retrying until it settles', async () => {
+ const { $freeTierSignIn, beginFreeTierSignIn } = await import('./free-tier-sign-in')
+
+ const claimed: AppHandoffStatus = {
+ dropped_toolkits: [],
+ lines: ['Your apps moved.'],
+ state: 'claimed',
+ updated_at: 't2'
+ }
+
+ startOAuthLogin.mockResolvedValueOnce(start('session-moved'))
+ pollOAuthSession.mockResolvedValue(approvedWith(retrying))
+ getNousHandoffStatus.mockResolvedValueOnce(claimed)
+
+ await beginFreeTierSignIn(requestGateway)
+ await vi.advanceTimersByTimeAsync(10)
+
+ expect(getNousHandoffStatus).toHaveBeenCalledWith('t1')
+ expect($freeTierSignIn.get()).toMatchObject({ email: '[email protected]', handoff: claimed, status: 'completed' })
+
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(getNousHandoffStatus).toHaveBeenCalledTimes(1)
+ })
+
+ it('stops following the move once the dialog closes', async () => {
+ const { beginFreeTierSignIn, closeFreeTierSignIn } = await import('./free-tier-sign-in')
+ startOAuthLogin.mockResolvedValueOnce(start('session-moved'))
+ pollOAuthSession.mockResolvedValue(approvedWith(retrying))
+ getNousHandoffStatus.mockResolvedValue(retrying)
+
+ await beginFreeTierSignIn(requestGateway)
+ await vi.advanceTimersByTimeAsync(10)
+ closeFreeTierSignIn()
+ const asked = getNousHandoffStatus.mock.calls.length
+
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(getNousHandoffStatus.mock.calls.length).toBe(asked)
+ })
+
+ it('keeps following the move through a failed read', async () => {
+ const { $freeTierSignIn, beginFreeTierSignIn } = await import('./free-tier-sign-in')
+ const claimed: AppHandoffStatus = { lines: ['Your apps moved.'], state: 'claimed', updated_at: 't2' }
+ startOAuthLogin.mockResolvedValueOnce(start('session-moved'))
+ pollOAuthSession.mockResolvedValue(approvedWith(retrying))
+ getNousHandoffStatus.mockRejectedValueOnce(new Error('connection reset')).mockResolvedValueOnce(claimed)
+
+ await beginFreeTierSignIn(requestGateway)
+ await vi.advanceTimersByTimeAsync(10_000)
+
+ expect($freeTierSignIn.get()).toMatchObject({ handoff: claimed, status: 'completed' })
+ })
+
+ it('stops after a bounded run of failed reads, leaving the note that the move continues', async () => {
+ const { $freeTierSignIn, beginFreeTierSignIn } = await import('./free-tier-sign-in')
+ startOAuthLogin.mockResolvedValueOnce(start('session-moved'))
+ pollOAuthSession.mockResolvedValue(approvedWith(retrying))
+ getNousHandoffStatus.mockRejectedValue(new Error('backend gone'))
+
+ await beginFreeTierSignIn(requestGateway)
+ await vi.advanceTimersByTimeAsync(600_000)
+ const asked = getNousHandoffStatus.mock.calls.length
+
+ await vi.advanceTimersByTimeAsync(600_000)
+ expect(getNousHandoffStatus.mock.calls.length).toBe(asked)
+ expect(asked).toBeGreaterThan(1)
+ expect($freeTierSignIn.get()).toMatchObject({ handoff: retrying, status: 'completed' })
+ })
+
+ it('shows the onboarding sign-in result only when it moved apps and nothing is on screen', async () => {
+ const { $freeTierSignIn, showFreeTierSignInResult } = await import('./free-tier-sign-in')
+ const claimed: AppHandoffStatus = { lines: ['Your apps moved.'], state: 'claimed', updated_at: 't2' }
+ markOnboardingDecided()
+
+ showFreeTierSignInResult({ handoff_status: null, session_id: 's', status: 'approved' })
+ expect($freeTierSignIn.get()).toEqual({ status: 'closed' })
+
+ $freeTierSignIn.set({ status: 'offer' })
+ showFreeTierSignInResult({ handoff_status: claimed, session_id: 's', status: 'approved' })
+ expect($freeTierSignIn.get()).toEqual({ status: 'offer' })
+
+ $freeTierSignIn.set({ status: 'closed' })
+ showFreeTierSignInResult({
+ account_email: '[email protected]',
+ handoff_status: claimed,
+ session_id: 's',
+ status: 'approved'
+ })
+ expect($freeTierSignIn.get()).toMatchObject({ email: '[email protected]', handoff: claimed, status: 'completed' })
+ })
+
+ it('holds the onboarding sign-in result until onboarding leaves the screen, since it sits above dialogs', async () => {
+ const { $freeTierSignIn, showFreeTierSignInResult } = await import('./free-tier-sign-in')
+ const claimed: AppHandoffStatus = { lines: ['Your apps moved.'], state: 'claimed', updated_at: 't2' }
+ const scope = { connectionId: 'athena', profile: 'work' }
+ markOnboardingDecided()
+ setOnboardingSurfaceActive('onboarding', true)
+
+ showFreeTierSignInResult({ handoff_status: claimed, session_id: 's', status: 'approved' }, scope)
+ expect($freeTierSignIn.get()).toEqual({ status: 'closed' })
+
+ setOnboardingSurfaceActive('onboarding', false)
+ expect($freeTierSignIn.get()).toMatchObject({ handoff: claimed, scope, status: 'completed' })
+ })
+})
diff --git a/apps/desktop/src/store/free-tier-sign-in.ts b/apps/desktop/src/store/free-tier-sign-in.ts
index df3bd696f36..2cb0e14d978 100644
--- a/apps/desktop/src/store/free-tier-sign-in.ts
+++ b/apps/desktop/src/store/free-tier-sign-in.ts
@@ -1,26 +1,31 @@
import type { FreeTierClaimNudgeResult } from '@hermes/shared'
import { atom } from 'nanostores'
-import { cancelOAuthSession, listOAuthProviders, pollOAuthSession, startOAuthLogin } from '@/hermes'
+import {
+ cancelOAuthSession,
+ getNousHandoffStatus,
+ listOAuthProviders,
+ OAUTH_LONG_POLL_SECONDS,
+ pollOAuthSession,
+ type ProfileScope,
+ startOAuthLogin
+} from '@/hermes'
+import { LONG_POLL_MIN_GAP_MS, pause, restOfLongPollGap } from '@/lib/long-poll'
import { gatewayActivationEpoch } from '@/store/gateway'
-import type { FreeTierStatus } from '@/types/hermes'
+import type { AppHandoffStatus, FreeTierStatus, OAuthPollResponse } from '@/types/hermes'
import { $freeTierStatus, type FreeTierRequester, NOUS_PROVIDER_ID, refreshFreeTierStatus } from './free-tier'
import { $localModelOfferPending } from './local-model-offer'
-import { onboardingSurfaceActive } from './onboarding-presence'
-
-const POLL_MS = 2000
-const COPY_FLASH_MS = 1500
+import { afterOnboardingSurfaceClear, onboardingSurfaceActive } from './onboarding-presence'
/** Why a sign-in ended without tokens. Each maps to one ruled screen:
* `busy` (the account service asked for a short wait — a busy account, a
* rate limit, the ops pause), `unreachable` (the service could not be
* reached or errored; a sign-in cannot help until it is back), `unavailable`
* (a terminal refusal: this version, a proof-of-work request, a locked
- * session), and the ruled outcomes of the transfer itself. Anything the
- * backend does not name lands on `error`, which carries its own message. */
-export type FreeTierSignInFailure =
- 'busy' | 'error' | 'rejected' | 'retired' | 'superseded' | 'timed_out' | 'unavailable' | 'unreachable'
+ * session), and `timed_out` (the code expired). Anything the backend does
+ * not name lands on `error`, which carries its own message. */
+export type FreeTierSignInFailure = 'busy' | 'error' | 'timed_out' | 'unavailable' | 'unreachable'
export type FreeTierSignInState =
| { status: 'already_signed_in' }
@@ -33,7 +38,17 @@ export type FreeTierSignInState =
// back-off). Unlike `requested` it waits for the user's Sign in before
// starting the transfer.
| { status: 'offer' }
- | { email: null | string; model: null | string; status: 'completed' }
+ // `handoff`: the free tier's apps moving to this account (null when the
+ // sign-in replaced no free tier). Followed while it is still retrying.
+ // `scope`: the profile the sign-in ran for when it is not the active one,
+ // so Reconnect opens that profile's apps.
+ | {
+ email: null | string
+ handoff: AppHandoffStatus | null
+ model: null | string
+ scope?: ProfileScope
+ status: 'completed'
+ }
// `retryAfter`: the seconds the backend asked us to wait before trying
// again (0 when it named none); only `busy` screens read it.
| { kind: FreeTierSignInFailure; message: null | string; retryAfter: number; status: 'failed' }
@@ -41,14 +56,8 @@ export type FreeTierSignInState =
// identity (the first `start` does it), which is the one case where the user
// waits on something worth naming.
| { minting: boolean; status: 'setting_up' }
- | {
- code: string
- codeCopied: boolean
- sessionId: string
- url: string
- urlCopied: boolean
- status: 'code'
- }
+ // `code` is shown only to compare with the browser page; `url` reopens it.
+ | { code: string; sessionId: string; status: 'code'; url: string }
export const $freeTierSignIn = atom<FreeTierSignInState>({ status: 'closed' })
@@ -73,19 +82,14 @@ export function freeTierSignInClaim() {
return $claim
}
-let pollTimer: number | null = null
let expiryTimer: number | null = null
// Each begin/close bumps the generation. A continuation that resumes after an await (a poll that was
// already in flight when the dialog closed, a start call for an abandoned attempt) compares its own
-// generation and drops out, so a stale attempt never publishes over the one now on screen.
+// generation and drops out, so a stale attempt never publishes over the one now on screen. The poll
+// loops end the same way.
let attempt = 0
function clearTimers() {
- if (pollTimer !== null) {
- window.clearInterval(pollTimer)
- pollTimer = null
- }
-
if (expiryTimer !== null) {
window.clearTimeout(expiryTimer)
expiryTimer = null
@@ -239,15 +243,12 @@ export function closeFreeTierSignIn() {
set({ status: 'closed' })
}
-// The reasons the backend names on a non-approved terminal poll: the transfer's
-// own outcomes, and the account service's `anon_*` verdicts when it was busy,
+// The reasons the backend names on a non-approved terminal poll: an expired
+// code, and the account service's `anon_*` verdicts when it was busy,
// unreachable or refused mid sign-in (`hermes_cli/anon_sign_in.py`). Anything
// else falls through to the generic error screen, which shows the backend's
// own message.
const FAILURE_BY_REASON: Record<string, FreeTierSignInFailure> = {
- account_busy: 'busy',
- account_not_anonymous: 'retired',
- account_retired: 'retired',
anon_account_locked: 'unavailable',
anon_gate_closed: 'unavailable',
anon_gate_paused: 'busy',
@@ -255,9 +256,7 @@ const FAILURE_BY_REASON: Record<string, FreeTierSignInFailure> = {
anon_rate_limited: 'busy',
anon_server_error: 'unreachable',
anon_unreachable: 'unreachable',
- superseded: 'superseded',
- timeout: 'timed_out',
- user_declined: 'rejected'
+ timeout: 'timed_out'
}
/** The screen a failed poll maps to, exported for the dialog's tests. */
@@ -284,9 +283,9 @@ async function openSignInUrl(url: string) {
/**
* Drive one sign-in attempt end to end: resolve what identity this Hermes is
- * on, start the transfer, open the consent page, then poll until it resolves.
- * Safe to call again from a "Try again" button — it clears any previous timers
- * first.
+ * on, start the device-code sign-in, open its page, then long-poll until it
+ * resolves. Safe to call again from a "Try again" button — it clears any
+ * previous timers first.
*/
export async function beginFreeTierSignIn(requestGateway: FreeTierRequester) {
clearTimers()
@@ -352,14 +351,7 @@ export async function beginFreeTierSignIn(requestGateway: FreeTierRequester) {
return
}
- set({
- code: start.user_code,
- codeCopied: false,
- sessionId: start.session_id,
- status: 'code',
- url: start.verification_url,
- urlCopied: false
- })
+ set({ code: start.user_code, sessionId: start.session_id, status: 'code', url: start.verification_url })
// Lapse locally when the code's own window closes, instead of polling a
// dead session forever. The backend usually flips it first and its message
@@ -370,7 +362,7 @@ export async function beginFreeTierSignIn(requestGateway: FreeTierRequester) {
fail('timed_out', null)
}, ttlMs)
- pollTimer = window.setInterval(() => void pollOnce(start.session_id, requestGateway, mine), POLL_MS)
+ void pollUntilDone(start.session_id, requestGateway, mine)
} catch (error) {
if (!stale()) {
fail('error', error instanceof Error ? error.message : String(error))
@@ -378,41 +370,32 @@ export async function beginFreeTierSignIn(requestGateway: FreeTierRequester) {
}
}
-async function pollOnce(sessionId: string, requestGateway: FreeTierRequester, mine: number) {
- const stale = () => mine !== attempt
+// Long-poll the sign-in until it leaves `pending`, then finish it. The loop ends with its screen: a
+// close, a newer attempt or the local expiry floor.
+async function pollUntilDone(sessionId: string, requestGateway: FreeTierRequester, mine: number) {
+ const stale = () => mine !== attempt || $freeTierSignIn.get().status !== 'code'
try {
- const result = await pollOAuthSession(NOUS_PROVIDER_ID, sessionId)
-
- if (stale() || result.status === 'pending') {
- return
- }
+ for (;;) {
+ const askedAt = Date.now()
+ const result = await pollOAuthSession(NOUS_PROVIDER_ID, sessionId, undefined, OAUTH_LONG_POLL_SECONDS)
- clearTimers()
-
- if (result.status !== 'approved') {
- fail(signInFailureKind(result.reason), result.error_message ?? null, Number(result.retry_after) || 0)
+ if (stale()) {
+ return
+ }
- return
- }
+ if (result.status !== 'pending') {
+ clearTimers()
- set({ status: 'finishing' })
+ return await finishSignIn(result, requestGateway, mine)
+ }
- // The tokens are on disk now, so the backend's view of this identity has
- // changed: reload its env and re-read the free-tier verdict before the
- // completed screen claims the user is signed in.
- await requestGateway('reload.env').catch(() => undefined)
- await refreshFreeTierStatus(requestGateway)
+ await restOfLongPollGap(askedAt)
- if (stale()) {
- return
+ if (stale()) {
+ return
+ }
}
-
- set({
- email: result.account_email ?? null,
- model: result.model ?? null,
- status: 'completed'
- })
} catch (error) {
if (!stale()) {
fail('error', error instanceof Error ? error.message : String(error))
@@ -420,39 +403,105 @@ async function pollOnce(sessionId: string, requestGateway: FreeTierRequester, mi
}
}
-async function copyAndFlash(text: string, field: 'codeCopied' | 'urlCopied') {
- try {
- await navigator.clipboard.writeText(text)
- } catch {
+async function finishSignIn(result: OAuthPollResponse, requestGateway: FreeTierRequester, mine: number) {
+ if (result.status !== 'approved') {
+ fail(signInFailureKind(result.reason), result.error_message ?? null, Number(result.retry_after) || 0)
+
return
}
- const current = $freeTierSignIn.get()
+ set({ status: 'finishing' })
+
+ // The tokens are on disk now, so the backend's view of this identity has
+ // changed: reload its env and re-read the free-tier verdict before the
+ // completed screen claims the user is signed in.
+ await requestGateway('reload.env').catch(() => undefined)
+ await refreshFreeTierStatus(requestGateway)
- if (current.status !== 'code') {
+ if (mine !== attempt) {
return
}
- const { sessionId } = current
- set({ ...current, [field]: true })
+ const handoff = result.handoff_status ?? null
+ set({ email: result.account_email ?? null, handoff, model: result.model ?? null, status: 'completed' })
- window.setTimeout(() => {
- const later = $freeTierSignIn.get()
+ if (handoff && handoffStillMoving(handoff)) {
+ void followHandoff(handoff, mine)
+ }
+}
+
+/** The move is still being retried in the background, so its result can still change. */
+export function handoffStillMoving(handoff: AppHandoffStatus): boolean {
+ return handoff.state === 'pending' || handoff.state === 'retrying'
+}
+
+/** A Nous sign-in that finished in the onboarding picker and replaced the free
+ * tier: show the same result screen this dialog shows. Onboarding paints above
+ * every dialog, so the result waits until it leaves the screen; never over a
+ * sign-in already on screen. `scope` is the profile the sign-in ran for. */
+export function showFreeTierSignInResult(result: OAuthPollResponse, scope?: ProfileScope) {
+ const handoff = result.handoff_status
+
+ if (!handoff) {
+ return
+ }
- if (later.status === 'code' && later.sessionId === sessionId) {
- set({ ...later, [field]: false })
+ afterOnboardingSurfaceClear(() => {
+ if ($freeTierSignIn.get().status !== 'closed') {
+ return
}
- }, COPY_FLASH_MS)
+
+ const mine = ++attempt
+ clearTimers()
+ set({ email: result.account_email ?? null, handoff, model: null, scope, status: 'completed' })
+
+ if (handoffStillMoving(handoff)) {
+ void followHandoff(handoff, mine, scope)
+ }
+ })
}
-export function copyFreeTierCode() {
- const state = $freeTierSignIn.get()
+// Failed handoff reads in a row before the result stops following the move. The note on screen stays
+// true either way: the move continues in the background whether or not this window hears about it.
+const HANDOFF_READ_RETRIES = 4
- return state.status === 'code' ? copyAndFlash(state.code, 'codeCopied') : Promise.resolve()
+// Keep the completed screen's handoff current while the move is retried, until it settles or the
+// dialog closes. A failed read leaves the last answer on screen: it already says the move continues.
+async function followHandoff(shown: AppHandoffStatus, mine: number, scope?: ProfileScope) {
+ let current = shown
+ let failures = 0
+
+ while (mine === attempt && handoffStillMoving(current)) {
+ const askedAt = Date.now()
+
+ try {
+ current = await getNousHandoffStatus(current.updated_at ?? null, scope)
+ failures = 0
+ } catch {
+ if (++failures > HANDOFF_READ_RETRIES) {
+ return
+ }
+
+ // Back off: 4 s, 8 s, 16 s, 32 s.
+ await pause(LONG_POLL_MIN_GAP_MS * 2 ** failures)
+
+ continue
+ }
+
+ const screen = $freeTierSignIn.get()
+
+ if (mine !== attempt || screen.status !== 'completed') {
+ return
+ }
+
+ set({ ...screen, handoff: current })
+ await restOfLongPollGap(askedAt)
+ }
}
-export function copyFreeTierUrl() {
+/** Reopen the sign-in page the code belongs to. */
+export function reopenFreeTierSignInPage() {
const state = $freeTierSignIn.get()
- return state.status === 'code' ? copyAndFlash(state.url, 'urlCopied') : Promise.resolve()
+ return state.status === 'code' ? openSignInUrl(state.url) : Promise.resolve()
}
diff --git a/apps/desktop/src/store/onboarding-owner.test.ts b/apps/desktop/src/store/onboarding-owner.test.ts
index ef244eb7f61..0df45f0d2fa 100644
--- a/apps/desktop/src/store/onboarding-owner.test.ts
+++ b/apps/desktop/src/store/onboarding-owner.test.ts
@@ -28,11 +28,14 @@ vi.mock('@/store/gateway', async importOriginal => ({
const owner = { connectionId: 'athena', profile: 'leverage-ai' }
const requests: HermesApiRequest[] = []
let authFlow: 'device_code' | 'pkce'
+// The sign-in long-poll asks at once, so a test that cancels a waiting flow keeps it pending.
+let pollStatus: 'approved' | 'pending'
let deferStart: (() => Promise<void>) | undefined
beforeEach(() => {
vi.useFakeTimers()
authFlow = 'device_code'
+ pollStatus = 'approved'
deferStart = undefined
requests.length = 0
setApiRequestConnection(owner.connectionId)
@@ -63,7 +66,7 @@ beforeEach(() => {
}
if (path.includes('/poll/') || path.endsWith('/submit')) {
- return { ok: true, status: 'approved' }
+ return { ok: true, status: path.endsWith('/submit') ? 'approved' : pollStatus }
}
if (path.startsWith('/api/model/options')) {
@@ -147,6 +150,7 @@ it.each(['device_code', 'pkce'] as const)(
)
it('cancels on the original owner after the foreground changes', async () => {
+ pollStatus = 'pending'
const ctx = beginContext()
await startProviderOAuth({ ...makeOAuthProvider('openai-codex'), flow: 'device_code' }, ctx)
switchForeground()
diff --git a/apps/desktop/src/store/onboarding.test.ts b/apps/desktop/src/store/onboarding.test.ts
index 773d815c118..c46cddfc6b2 100644
--- a/apps/desktop/src/store/onboarding.test.ts
+++ b/apps/desktop/src/store/onboarding.test.ts
@@ -1168,7 +1168,7 @@ describe('device-code poll expiry', () => {
return deviceStart(2)
}
- if (path === '/api/providers/oauth/nous/poll/device-sess-1') {
+ if (path.startsWith('/api/providers/oauth/nous/poll/device-sess-1')) {
return { status: 'pending' }
}
@@ -1195,7 +1195,7 @@ describe('device-code poll expiry', () => {
return deviceStart(600)
}
- if (path === '/api/providers/oauth/nous/poll/device-sess-1') {
+ if (path.startsWith('/api/providers/oauth/nous/poll/device-sess-1')) {
return { status: 'pending' }
}
diff --git a/apps/desktop/src/store/onboarding.ts b/apps/desktop/src/store/onboarding.ts
index acf828dff80..d259883efcc 100644
--- a/apps/desktop/src/store/onboarding.ts
+++ b/apps/desktop/src/store/onboarding.ts
@@ -6,6 +6,7 @@ import {
getGlobalModelOptions,
getRecommendedDefaultModel,
listOAuthProviders,
+ OAUTH_LONG_POLL_SECONDS,
pollOAuthSession,
type ProfileScope,
setEnvVar,
@@ -14,6 +15,7 @@ import {
validateProviderCredential
} from '@/hermes'
import { translateNow } from '@/i18n'
+import { restOfLongPollGap } from '@/lib/long-poll'
import { isProviderSetupErrorMessage } from '@/lib/provider-setup-errors'
import { evaluateRuntimeReadiness, type RuntimeReadinessResult } from '@/lib/runtime-readiness'
import {
@@ -23,6 +25,7 @@ import {
refreshFreeTierStatus,
setFreeTierRoute
} from '@/store/free-tier'
+import { showFreeTierSignInResult } from '@/store/free-tier-sign-in'
import { $gatewayBootGeneration } from '@/store/live-sync'
import { setMainModelAssignment } from '@/store/model-assignment'
import { dismissNotification, notify, notifyError } from '@/store/notifications'
@@ -104,7 +107,6 @@ export interface OnboardingContext {
const CONFIGURED_CACHE_KEY = 'hermes-desktop-onboarded-v1'
const SKIP_CACHE_KEY = 'hermes-onboarding-skipped-v1'
-const POLL_MS = 2000
const COPY_FLASH_MS = 1500
export const DEFAULT_ONBOARDING_REASON = 'No inference provider is configured.'
export const DEFAULT_MANUAL_ONBOARDING_REASON = 'Add or switch inference provider.'
@@ -182,7 +184,6 @@ export const $desktopOnboarding = atom<DesktopOnboardingState>(INITIAL)
let flowGeneration = 0
let flowScope: OnboardingScope | undefined
-let pollTimer: number | null = null
let providersRefreshPromise: null | Promise<void> = null
const errMessage = (e: unknown) => (e instanceof Error ? e.message : String(e))
@@ -206,12 +207,8 @@ const setFlow = (flow: OnboardingFlow) => patch(flow.status === 'idle' ? { flow
const sessionIdFor = (flow: OnboardingFlow) => ('start' in flow && flow.start ? flow.start.session_id : undefined)
+// The poll loop itself ends with its flow (see `pollSession`); only the expiry floor is a timer.
function clearPoll() {
- if (pollTimer !== null) {
- window.clearInterval(pollTimer)
- pollTimer = null
- }
-
clearPollExpiry()
}
@@ -946,7 +943,7 @@ export async function startProviderOAuth(provider: OAuthProvider, ctx: Onboardin
message: translateNow('onboarding.signInExpired')
})
)
- pollTimer = window.setInterval(() => void pollSession(provider, start, ctx, generation), POLL_MS)
+ void pollSession(provider, start, ctx, generation)
} catch (error) {
if (generation !== flowGeneration) {
return
@@ -956,31 +953,61 @@ export async function startProviderOAuth(provider: OAuthProvider, ctx: Onboardin
}
}
-// Poll a session-backed device-code flow until it resolves.
+// Long-poll a session-backed device-code flow until it resolves. The loop ends with its flow: a
+// cancel, a newer flow, or the local expiry floor all move the flow off this session's `polling`.
async function pollSession(provider: OAuthProvider, start: DeviceStart, ctx: OnboardingContext, generation: number) {
+ const live = () => {
+ const { flow } = $desktopOnboarding.get()
+
+ return generation === flowGeneration && flow.status === 'polling' && sessionIdFor(flow) === start.session_id
+ }
+
try {
- const { error_message, status } = await pollOAuthSession(provider.id, start.session_id, ctx.scope)
+ for (;;) {
+ const askedAt = Date.now()
+ const result = await pollOAuthSession(provider.id, start.session_id, ctx.scope, OAUTH_LONG_POLL_SECONDS)
- if (generation !== flowGeneration) {
- return
- }
+ if (!live()) {
+ return
+ }
- if (status === 'approved') {
- clearPoll()
- setFlow({ status: 'success', provider })
- await completeWithModelConfirm(ctx, provider.name, [provider.id], reason =>
+ if (result.status === 'approved') {
+ clearPoll()
+ setFlow({ status: 'success', provider })
+ // A Nous sign-in that replaced the free tier shows what moved, the same screen the
+ // free-tier sign-in shows; onboarding carries on underneath.
+ showFreeTierSignInResult(result, ctx.scope)
+ await completeWithModelConfirm(ctx, provider.name, [provider.id], reason =>
+ setFlow({
+ status: 'error',
+ provider,
+ message: providerResolutionFailure(reason)
+ })
+ )
+
+ return
+ }
+
+ if (result.status !== 'pending') {
+ clearPoll()
setFlow({
status: 'error',
provider,
- message: providerResolutionFailure(reason)
+ start,
+ ...signInDidNotFinish(provider, result.error_message || result.status)
})
- )
- } else if (status !== 'pending') {
- clearPoll()
- setFlow({ status: 'error', provider, start, ...signInDidNotFinish(provider, error_message || status) })
+
+ return
+ }
+
+ await restOfLongPollGap(askedAt)
+
+ if (!live()) {
+ return
+ }
}
} catch (error) {
- if (generation !== flowGeneration) {
+ if (!live()) {
return
}
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index 513e0d6e2b2..dbbb1f22e78 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -140,24 +140,40 @@ export interface OAuthPollResponse {
account_email?: null | string
error_message?: null | string
expires_at?: null | number
+ /** Approved Nous sign-ins only: the free tier's handoff the sign-in ran
+ * (what moved, what to reconnect). Null when it replaced no free tier. */
+ handoff_status?: AppHandoffStatus | null
/** Approved sign-ins only: the default model the backend settled on. Null
* when the config already pointed at the user's own model and was left
* alone. */
model?: null | string
- /** Why a non-approved terminal status ended that way: `user_declined`
- * (status `denied`), or `superseded` / `account_retired` /
- * `account_not_anonymous` / `account_busy` / `timeout` (status `error`).
- * `error_message` carries the matching user-facing text. */
+ /** Why a non-approved terminal status ended that way: `timeout`, or one of
+ * the account service's `anon_*` verdicts (status `error`). `error_message`
+ * carries the matching user-facing text. */
reason?: null | string
- /** Failed sign-ins over a free-tier identity: the seconds the account service
- * asked the client to wait before trying again (0 or absent when none). */
+ /** Failed Nous sign-ins: the seconds the account service asked the client
+ * to wait before trying again (0 or absent when none). */
retry_after?: null | number
- /** Failed sign-ins over a free-tier identity: whether a later attempt can succeed. */
+ /** Failed Nous sign-ins: whether a later attempt can succeed. */
retryable?: boolean | null
session_id: string
status: 'approved' | 'denied' | 'error' | 'expired' | 'pending'
}
+/** The free tier's apps moving to the account that replaced it
+ * (`hermes_cli/guest_handoff.py`, `wire_status`). `lines` is the backend's
+ * own copy for this state, the same lines the terminal prints. */
+export interface AppHandoffStatus {
+ account_email?: null | string
+ connectors_kind?: null | string
+ dropped_toolkits?: string[]
+ lines: string[]
+ moved_toolkits?: string[]
+ probably_moved?: boolean
+ state: 'claimed' | 'failed' | 'gone' | 'idle' | 'paused' | 'pending' | 'retrying'
+ updated_at?: null | string
+}
+
/** Result of the `free_tier.status` RPC. Pull-only: it reads local auth state
* and makes no network call, so it is safe to refresh on the ambient status
* cadence. */
diff --git a/hermes_cli/anon_sign_in.py b/hermes_cli/anon_sign_in.py
index 0cd7f6ab43d..2bd4601c679 100644
--- a/hermes_cli/anon_sign_in.py
+++ b/hermes_cli/anon_sign_in.py
@@ -108,12 +108,14 @@ class Waiting(SignInState):
@dataclass(frozen=True)
class Completed(SignInState):
"""``handoff`` holds the guest handoff's result lines (what moved, what to reconnect), empty
- when the sign-in replaced no free tier."""
+ when the sign-in replaced no free tier. ``handoff_status`` is the latest handoff record it ran,
+ in ``guest_handoff.wire_status`` form, for a surface that renders the result itself."""
email: str = ""
model: str = ""
model_changed: bool = False
handoff: tuple[str, ...] = ()
+ handoff_status: Optional[dict[str, Any]] = None
kind: ClassVar[str] = "completed"
ok: ClassVar[bool] = True
@@ -234,6 +236,19 @@ def _handoff_lines(results: list[dict[str, Any]]) -> tuple[str, ...]:
return tuple(line for view in results for line in result_lines(view))
+def _handoff_status(results: list[dict[str, Any]], replaced: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:
+ """The handoff a completed sign-in reports (``guest_handoff.wire_status`` form): the latest record its
+ own run attempted, else the replaced free tier's saved record (another process held the claim, or
+ the run's budget ran out first), else None when it replaced no free tier. Read under the scope."""
+ from hermes_cli import anon_auth as _core
+ from hermes_cli.guest_handoff import record_status, wire_status
+ if results:
+ return wire_status(results[-1])
+ anon_token = replaced.get("anon_token") if _core.is_guest_state(replaced) else None
+ status = record_status(anon_token) if isinstance(anon_token, str) and anon_token else None
+ return wire_status(status) if status else None
+
+
def run_sign_in(
*,
timeout_seconds: float = 15.0,
@@ -336,6 +351,7 @@ def run_sign_in(
_core.persist_nous_credentials(account_state)
if may_persist:
settled = _core.settle_after_upgrade(account_state)
+ handoff_status = _handoff_status(handoff.results, state)
except Exception as exc:
# persist_nous_credentials takes the auth-store lock, writes auth.json, takes the shared
# store's file lock and reseeds the credential pool: a lock timeout or a read-only home
@@ -350,4 +366,5 @@ def run_sign_in(
email=_account_email(account_state, handoff.account_email),
model=str(settled.get("model") or ""),
model_changed=bool(settled.get("changed")),
- handoff=_handoff_lines(handoff.results))
+ handoff=_handoff_lines(handoff.results),
+ handoff_status=handoff_status)
diff --git a/hermes_cli/guest_handoff.py b/hermes_cli/guest_handoff.py
index b8ff11fb02e..39fdd5b109c 100644
--- a/hermes_cli/guest_handoff.py
+++ b/hermes_cli/guest_handoff.py
@@ -551,6 +551,13 @@ def public_view(record: dict[str, Any]) -> dict[str, Any]:
"updated_at": record.get("updated_at")}
+def _status_of(record: dict[str, Any]) -> dict[str, Any]:
+ view = public_view(record)
+ if _retryable(record):
+ view["state"] = RETRYING if _account_bound_to(record) else PAUSED
+ return view
+
+
def handoff_status() -> dict[str, Any]:
"""This profile's latest handoff, or ``{"state": "idle"}``. A pure read (no lock, no network). An
active move bound to an account this profile no longer holds reads as ``paused``."""
@@ -562,11 +569,23 @@ def handoff_status() -> dict[str, Any]:
mine = [r for r in records if home in r.get("profiles", ())]
if not mine:
return {"state": IDLE}
- latest = max(mine, key=lambda r: str(r.get("updated_at") or ""))
- view = public_view(latest)
- if _retryable(latest):
- view["state"] = RETRYING if _account_bound_to(latest) else PAUSED
- return view
+ return _status_of(max(mine, key=lambda r: str(r.get("updated_at") or "")))
+
+
+def record_status(anon_token: str) -> Optional[dict[str, Any]]:
+ """The handoff of one free-tier credential (as :func:`handoff_status` reads it), or None when no
+ record exists. A pure read: what a sign-in reports when its own run attempted nothing (another
+ process held the claim, or the budget ran out first)."""
+ try:
+ record = _load(_records_path())["records"].get(_token_key(anon_token))
+ except RuntimeError:
+ return None
+ return _status_of(record) if record else None
+
+
+def wire_status(status: dict[str, Any]) -> dict[str, Any]:
+ """A status as the desktop reads it: the fields, plus the user copy for them (:func:`result_lines`)."""
+ return {**status, "lines": result_lines(status)}
def status_lines(status: dict[str, Any]) -> list[str]:
diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.py
index 02ab67e9385..61db6225bcf 100644
--- a/hermes_cli/web_routers/oauth.py
+++ b/hermes_cli/web_routers/oauth.py
@@ -24,7 +24,7 @@ from hermes_cli.web_server_oauth import (
_external_process_cli_command, _oauth_profile_name, _oauth_sessions, _oauth_sessions_lock, _truncate_token,
)
from hermes_cli.web_models import OAuthSubmitBody
-from hermes_cli.web_routers._common import scoped_to_thread
+from hermes_cli.web_routers._common import config_scoped_to_thread, scoped_to_thread
_log = logging.getLogger("hermes_cli.web_server")
router = APIRouter()
@@ -853,10 +853,27 @@ async def submit_oauth_code(
raise HTTPException(status_code=400, detail=f"submit not supported for {provider_id}")
+# A long-poll answers as soon as what it watches changes, and otherwise after at most this long, so
+# the request stays well inside the desktop's own request timeout.
+_LONG_POLL_CAP_SECONDS = 25.0
+
+
+async def _long_poll(read: Callable[[], Any], changed: Callable[[Any], bool], wait: float, tick: float) -> Any:
+ """Re-run the async *read* every *tick* seconds until *changed* holds or *wait* (capped) runs out;
+ the last read is the answer. ``wait <= 0`` is one plain read."""
+ deadline = time.monotonic() + min(max(wait, 0.0), _LONG_POLL_CAP_SECONDS)
+ value = await read()
+ while not changed(value) and (left := deadline - time.monotonic()) > 0:
+ await asyncio.sleep(min(tick, left))
+ value = await read()
+ return value
+
+
@router.get("/api/providers/oauth/{provider_id}/poll/{session_id}")
-async def poll_oauth_session(provider_id: str, session_id: str, profile: Optional[str] = None):
+async def poll_oauth_session(provider_id: str, session_id: str, profile: Optional[str] = None, wait: float = 0):
"""Poll a session's status (no auth — read-only state). One endpoint serves
- every device-code flow: all report progress via the worker-updated ``status``."""
+ every device-code flow: all report progress via the worker-updated ``status``.
+ With *wait* (seconds) it is a long-poll: it answers once the session leaves ``pending``."""
requested_profile = _validate_oauth_profile(profile)
with _oauth_sessions_lock:
sess = _oauth_sessions.get(session_id)
@@ -866,19 +883,46 @@ async def poll_oauth_session(provider_id: str, session_id: str, profile: Optiona
raise HTTPException(status_code=400, detail="Provider mismatch for session")
if sess.get("profile") != requested_profile:
raise HTTPException(status_code=400, detail="OAuth session profile mismatch")
+
+ async def _status() -> str:
+ with _oauth_sessions_lock:
+ return "cancelled" if sess.get("cancelled") else sess["status"]
+
+ # The poller thread writes the session dict, so watching it costs no network.
+ await _long_poll(_status, lambda status: status != "pending", wait, tick=0.25)
return {
"session_id": session_id, "status": sess["status"],
"error_message": sess.get("error_message"), "expires_at": sess.get("expires_at"),
# Nous: why a sign-in ended, who signed in, and the default model the completion settled on
# (None when the config was on the user's own model).
"reason": sess.get("reason"), "account_email": sess.get("account_email"), "model": sess.get("model"),
- # What the replaced free tier's handoff did: one user-facing line each (moved, reconnect).
- "handoff": sess.get("handoff"),
+ # What the replaced free tier's handoff did: one user-facing line each (moved, reconnect),
+ # and the same result as fields (``guest_handoff.wire_status``; None without a handoff).
+ "handoff": sess.get("handoff"), "handoff_status": sess.get("handoff_status"),
# Failed Nous sign-ins: can a later attempt succeed, and after how long.
"retryable": sess.get("retryable"), "retry_after": sess.get("retry_after"),
}
[email protected]("/api/providers/oauth/nous/handoff")
+async def nous_handoff_status(
+ request: Request, profile: Optional[str] = None, since: Optional[str] = None, wait: float = 0,
+):
+ """The profile's latest free-tier handoff (``guest_handoff.wire_status``). Token-protected. A
+ long-poll: given *since* (the ``updated_at`` the caller already shows) and *wait*, it answers once
+ the record changes. The keepalive retries a move in the background; this only reads."""
+ _require_token(request)
+ profile_name = _validate_oauth_profile(profile)
+
+ def _read() -> dict[str, Any]:
+ from hermes_cli.guest_handoff import handoff_status, wire_status
+ return wire_status(handoff_status())
+
+ return await _long_poll(
+ lambda: config_scoped_to_thread(profile_name, _read),
+ lambda status: since is None or status.get("updated_at") != since, wait, tick=1.0)
+
+
@router.delete("/api/providers/oauth/sessions/{session_id}")
async def cancel_oauth_session(session_id: str, request: Request, profile: Optional[str] = None):
"""Cancel a pending OAuth session. Token-protected.
diff --git a/hermes_cli/web_server_oauth.py b/hermes_cli/web_server_oauth.py
index 8454417a705..e1827595521 100644
--- a/hermes_cli/web_server_oauth.py
+++ b/hermes_cli/web_server_oauth.py
@@ -235,6 +235,8 @@ def _record_sign_in_state(sess: dict[str, Any], state: Any) -> None:
sess["model"] = state.model if state.model_changed else None
# What the free tier's handoff did (moved apps, apps to reconnect); empty without one.
sess["handoff"] = list(state.handoff)
+ # The same result as fields, so the desktop can name the apps and follow a retry.
+ sess["handoff_status"] = state.handoff_status
return
if kind == "cancelled":
sess["status"] = "cancelled"
diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.json
index 6cebfb3a9d4..0e82256f4f0 100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@ -1651,15 +1651,14 @@
"freeTier.busyBody",
"freeTier.busyHeading",
"freeTier.change",
- "freeTier.codeBody",
"freeTier.completedBody",
- "freeTier.copyLink",
"freeTier.defaultModel",
"freeTier.didNotComplete",
"freeTier.dismiss",
"freeTier.doNotShare",
"freeTier.done",
"freeTier.errorBody",
+ "freeTier.finishInBrowser",
"freeTier.finishingBody",
"freeTier.finishingHeading",
"freeTier.notNow",
@@ -1667,15 +1666,16 @@
"freeTier.offer.heading",
"freeTier.offer.notNow",
"freeTier.offer.signIn",
+ "freeTier.openConnectors",
"freeTier.openModelPicker",
+ "freeTier.openPageAgain",
"freeTier.otherProviders",
"freeTier.providerName",
"freeTier.providerRowPitch",
"freeTier.providerRowTitle",
"freeTier.readyCaption",
"freeTier.readyTitle",
- "freeTier.rejectedBody",
- "freeTier.retiredBody",
+ "freeTier.reconnect",
"freeTier.settingUp",
"freeTier.setupFailed.gateClosed",
"freeTier.setupFailed.generic",
@@ -1692,12 +1692,10 @@
"freeTier.signInHeading",
"freeTier.signInInstead",
"freeTier.signedIn",
- "freeTier.signedInAs",
- "freeTier.startAgain",
+ "freeTier.signedInAsLabel",
"freeTier.statusLabel",
"freeTier.stripBody",
"freeTier.stripTitle",
- "freeTier.supersededBody",
"freeTier.timedOutBody",
"freeTier.timedOutHeading",
"freeTier.tryAgain",
diff --git a/tests/hermes_cli/test_anon_surfaces.py b/tests/hermes_cli/test_anon_surfaces.py
index 836a8e8f6d3..1a82cf68386 100644
--- a/tests/hermes_cli/test_anon_surfaces.py
+++ b/tests/hermes_cli/test_anon_surfaces.py
@@ -202,6 +202,7 @@ def test_no_chat_copy_of_any_sign_in_state_leaks_a_terminal_verb_or_a_forbidden_
"retry_after": 0.0,
# Every handoff result line a completed sign-in can carry.
"handoff": tuple(line for view in _HANDOFF_VIEWS for line in guest_handoff.result_lines(view)),
+ "handoff_status": guest_handoff.wire_status(_HANDOFF_VIEWS[0]),
}
forbidden = re.compile(r"claim|nous portal|anonymous|guest", re.IGNORECASE)
terminal_or_url = re.compile(r"hermes |https?://", re.IGNORECASE)
diff --git a/tests/hermes_cli/test_desktop_signin_long_poll.py b/tests/hermes_cli/test_desktop_signin_long_poll.py
new file mode 100644
index 00000000000..2c6e2eb22f3
--- /dev/null
+++ b/tests/hermes_cli/test_desktop_signin_long_poll.py
@@ -0,0 +1,128 @@
+"""The desktop's sign-in and handoff reads are long-polls.
+
+``GET /api/providers/oauth/{provider}/poll/{session}?wait=`` holds the request until the sign-in
+leaves ``pending``; ``GET /api/providers/oauth/nous/handoff?since=&wait=`` holds it until the free
+tier's handoff record changes. Both carry the handoff as fields (``guest_handoff.wire_status``) so
+the desktop can name the apps that moved and the ones to reconnect. Driven through the real FastAPI
+routes against the fake portal ``hermes auth upgrade`` is tested with.
+"""
+
+from __future__ import annotations
+
+import pytest
+from fastapi.testclient import TestClient
+
+from hermes_cli import anon_auth, guest_handoff
+from hermes_cli.web_server import _SESSION_TOKEN, app
+from tests.hermes_cli.test_anon_upgrade import EMAIL, free_account, portal
+
+client = TestClient(app)
+HEADERS = {"X-Hermes-Session-Token": _SESSION_TOKEN}
+
+__all__ = ["free_account", "portal"] # fixtures imported from the CLI test module
+
+
+def _poll(session_id: str, wait: float) -> dict:
+ resp = client.get(f"/api/providers/oauth/nous/poll/{session_id}", params={"wait": wait}, headers=HEADERS)
+ assert resp.status_code == 200, resp.text
+ return resp.json()
+
+
+def test_one_long_poll_returns_the_finished_sign_in_with_the_handoff_as_fields(portal, free_account):
+ anon_auth.ensure_portal_identity(explicit=True)
+ portal.claim_reply["connectors"] = {"kind": "moved", "moved_toolkits": ["gmail"], "dropped_toolkits": ["slack"]}
+
+ start = client.post("/api/providers/oauth/nous/start", headers=HEADERS).json()
+ body = _poll(start["session_id"], wait=25)
+
+ assert body["status"] == "approved"
+ handoff = body["handoff_status"]
+ assert handoff["state"] == "claimed"
+ assert handoff["account_email"] == EMAIL
+ assert handoff["moved_toolkits"] == ["gmail"] and handoff["dropped_toolkits"] == ["slack"]
+ # The fields' copy is the same lines every other sign-in surface prints.
+ assert handoff["lines"] == body["handoff"] == guest_handoff.result_lines(handoff)
+ assert "anon_token" not in handoff
+
+
+def test_a_sign_in_that_replaced_no_free_tier_reports_no_handoff(portal, free_account):
+ start = client.post("/api/providers/oauth/nous/start", headers=HEADERS).json()
+ body = _poll(start["session_id"], wait=25)
+ assert body["status"] == "approved"
+ assert body["handoff_status"] is None and body["handoff"] == []
+
+
+def test_a_move_no_attempt_reached_still_reports_the_waiting_record(portal, free_account, monkeypatch):
+ """Another process holds the claim, so this sign-in's own run attempts nothing: the poll still
+ reports the replaced free tier's record (still moving) instead of no handoff at all."""
+ anon_auth.ensure_portal_identity(explicit=True)
+ monkeypatch.setattr(guest_handoff, "_run_one", lambda *a, **kw: None)
+
+ start = client.post("/api/providers/oauth/nous/start", headers=HEADERS).json()
+ body = _poll(start["session_id"], wait=25)
+
+ assert body["status"] == "approved"
+ # A move bound to this account and not yet attempted reads as retrying (handoff_status's rule).
+ assert body["handoff_status"]["state"] == "retrying"
+ assert body["handoff_status"]["lines"] == guest_handoff.result_lines({"state": "retrying"})
+ assert not portal.claims
+
+
+def test_a_long_poll_answers_pending_once_its_wait_runs_out(portal):
+ anon_auth.ensure_portal_identity(explicit=True)
+ portal.token_pending = True
+ start = client.post("/api/providers/oauth/nous/start", headers=HEADERS).json()
+ try:
+ assert _poll(start["session_id"], wait=0.3)["status"] == "pending"
+ finally:
+ client.delete(f"/api/providers/oauth/sessions/{start['session_id']}", headers=HEADERS)
+
+
+def _handoff(**params) -> dict:
+ resp = client.get("/api/providers/oauth/nous/handoff", params=params, headers=HEADERS)
+ assert resp.status_code == 200, resp.text
+ return resp.json()
+
+
+def test_the_handoff_route_reads_the_record_the_sign_in_left(portal, free_account):
+ anon_auth.ensure_portal_identity(explicit=True)
+ start = client.post("/api/providers/oauth/nous/start", headers=HEADERS).json()
+ signed_in = _poll(start["session_id"], wait=25)["handoff_status"]
+
+ status = _handoff()
+ assert status["state"] == "claimed" and status["moved_toolkits"] == ["gmail"]
+ assert status["updated_at"] == signed_in["updated_at"]
+ assert status["lines"] == [f"Your apps moved to {EMAIL}: gmail."]
+
+
+def test_the_handoff_long_poll_answers_when_the_record_changes(monkeypatch):
+ retrying = {"state": "retrying", "updated_at": "t1", "moved_toolkits": [], "dropped_toolkits": []}
+ claimed = {"state": "claimed", "updated_at": "t2", "account_email": EMAIL, "connectors_kind": "moved",
+ "moved_toolkits": ["gmail"], "dropped_toolkits": []}
+ reads = iter([retrying, retrying, claimed])
+ monkeypatch.setattr(guest_handoff, "handoff_status", lambda: next(reads, claimed))
+
+ status = _handoff(since="t1", wait=25)
+
+ assert status["state"] == "claimed" and status["updated_at"] == "t2"
+ assert status["lines"] == [f"Your apps moved to {EMAIL}: gmail."]
+
+
+def test_the_handoff_long_poll_returns_the_unchanged_record_after_its_wait(monkeypatch):
+ retrying = {"state": "retrying", "updated_at": "t1", "moved_toolkits": [], "dropped_toolkits": []}
+ monkeypatch.setattr(guest_handoff, "handoff_status", lambda: retrying)
+
+ status = _handoff(since="t1", wait=0.2)
+
+ assert status["state"] == "retrying"
+ assert status["lines"] == guest_handoff.result_lines(retrying)
+
+
+def test_the_handoff_route_needs_the_session_token():
+ assert client.get("/api/providers/oauth/nous/handoff").status_code == 401
+
+
[email protected]("since", [None, "anything"])
+def test_with_no_record_the_handoff_is_idle(portal, since):
+ params = {"wait": 0} if since is None else {"since": since, "wait": 0}
+ assert _handoff(**params)["state"] == "idle"
diff --git a/website/docs/developer-guide/cli-internals.md b/website/docs/developer-guide/cli-internals.md
index f01bda84c55..3b5da77adf6 100644
--- a/website/docs/developer-guide/cli-internals.md
+++ b/website/docs/developer-guide/cli-internals.md
@@ -130,7 +130,9 @@ code, polls the token endpoint on one deadline (an expired code is `TimedOut`),
runs `settle_after_upgrade` exactly once, and never lets a persist or settle failure escape as an
exception: it becomes `Failed`. It works with or without a free tier on disk. `Completed.email`
comes from the access token's `email` claim; `Completed.handoff` carries the guest handoff's result
-lines (what moved, what to reconnect). Every state carries its own `.copy` (the chat form, which
+lines (what moved, what to reconnect) and `Completed.handoff_status` the latest record as fields
+(`guest_handoff.wire_status`: the public view plus those `lines`), for a surface that renders the
+result itself. Every state carries its own `.copy` (the chat form, which
never contains a raw exception, a URL or a `hermes` verb) and `.copy_terminal`, so no caller maps a
reason to a string. `cancelled()` is checked at least once a second inside the token poll and once more
before the save; a cancel always wins and nothing is saved. TLS verification comes from
@@ -152,7 +154,9 @@ are released; the handoff runner never settles.
When any writer saves a Nous account over a free-tier identity, `hermes_cli/guest_handoff.py` hands
that identity's connected apps to the account: `POST /api/anonymous/claim {"token": "<anon_...>"}`
with the account's own Bearer token. Nothing asks the user first; the result is shown afterwards
-(`hermes auth status nous`, `guest_handoff.handoff_status()` for the desktop). Sign-in code does not
+(`hermes auth status nous`; the desktop reads it from the sign-in poll's `handoff_status` and, while a
+move is still retrying, from the `GET /api/providers/oauth/nous/handoff?since=&wait=` long-poll, which
+answers once the record's `updated_at` changes). Sign-in code does not
call it:
- `note_replacement` runs at the two lowest write seams (`auth._store_provider_state` and