The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): show the free-tier sign-in offer when the backend says it is due
alt-glitch05a7997eece5
diff --git a/apps/desktop/src/app/contrib/hooks/desktop-onboarding-metrics.test.ts b/apps/desktop/src/app/contrib/hooks/desktop-onboarding-metrics.test.tsnew file mode 100644index 00000000000..65f981f460e--- /dev/null+++ b/apps/desktop/src/app/contrib/hooks/desktop-onboarding-metrics.test.ts@@ -0,0 +1,52 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'++import { bindDesktopMetrics, resetDesktopMetricsForTests, setDesktopMetricsGate } from '@/store/desktop-metrics'+import type { FreeTierSignInState } from '@/store/free-tier-sign-in'+import type { SharedMetricsRequester } from '@/store/shared-metrics'++import { signInTransition } from './desktop-onboarding-metrics'++const flush = () => new Promise(resolve => setTimeout(resolve, 0))++async function walk(...states: FreeTierSignInState[]): Promise<string[]> {+ const sent: string[] = []++ const request: SharedMetricsRequester = async (_method, params) => {+ sent.push(params?.step ? `${params.step}:${params.event}` : `${params?.signal}:${params?.target}`)++ // SAFETY: the metrics store fires and forgets (`void request(...).catch`); it never reads the answer.+ return undefined as never+ }++ bindDesktopMetrics(request)++ for (let i = 1; i < states.length; i++) {+ signInTransition(states[i - 1], states[i])+ }++ await flush()++ return sent+}++const CLOSED: FreeTierSignInState = { status: 'closed' }+const OFFER: FreeTierSignInState = { status: 'offer' }+const SETTING_UP: FreeTierSignInState = { minting: false, status: 'setting_up' }++beforeEach(() => {+ window.localStorage.clear()+ resetDesktopMetricsForTests()+ setDesktopMetricsGate('on')+})++afterEach(() => resetDesktopMetricsForTests())++describe('sign-in funnel from the offer', () => {+ it('an offer the user signs in from and then cancels is a reach followed by a cancel', async () => {+ expect(await walk(CLOSED, OFFER, SETTING_UP, CLOSED)).toEqual(['sign_in:reached', 'cancelled:free_tier_sign_in'])+ })++ it('"Not now" on the offer is a reach, not a cancelled sign-in', async () => {+ expect(await walk(CLOSED, OFFER, CLOSED)).toEqual(['sign_in:reached'])+ })+})diff --git a/apps/desktop/src/app/contrib/hooks/desktop-onboarding-metrics.ts b/apps/desktop/src/app/contrib/hooks/desktop-onboarding-metrics.tsindex 22b188b13d9..3117c6a1afc 100644--- a/apps/desktop/src/app/contrib/hooks/desktop-onboarding-metrics.ts+++ b/apps/desktop/src/app/contrib/hooks/desktop-onboarding-metrics.ts@@ -107,10 +107,14 @@ export function signInTransition(prev: FreeTierSignInState, next: FreeTierSignInreturn}- if (next.status === 'requested') {+ // The offer reaches the step too: its Sign in goes straight to `setting_up`, never through+ // `requested`. "Not now" closes the step without counting as a cancelled sign-in.+ if (next.status === 'requested' || next.status === 'offer') {recordOnboarding('sign_in', 'reached')} else if (next.status === 'completed' || next.status === 'already_signed_in') {recordOnboarding('sign_in', 'completed')+ } else if (next.status === 'closed' && prev.status === 'offer') {+ closeOnboardingStep('sign_in')} else if (next.status === 'closed' && SIGN_IN_OPEN.has(prev.status)) {recordDislike('cancelled', 'free_tier_sign_in')closeOnboardingStep('sign_in')diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.tsindex 15f4fad8c41..4e3ba0dff2d 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts@@ -11,6 +11,7 @@ import { triggerHaptic } from '@/lib/haptics'import { billingCtaLabel, clearBillingBlock, runBillingRecovery, setBillingBlock } from '@/store/billing-block'import { clearSettledClarifyRequest } from '@/store/clarify'import { setSessionCompacting } from '@/store/compaction'+import { noteFreeTierTurnComplete } from '@/store/free-tier-sign-in'import { reportLocalSetupTurnComplete } from '@/store/local-setup-offer'import { notify } from '@/store/notifications'import { flashPetActivity, markPetUnread, setPetActivity } from '@/store/pet'@@ -409,6 +410,10 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {reportOnboardingTurnComplete(ctx, sessionId)+ if (payload?.status === 'complete') {+ noteFreeTierTurnComplete()+ }+// Structured billing wall forwarded by the gateway (out of credits /// payment required) — cache it + raise a billing-specific toast.if (payload?.billing) {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.tsxindex 4a2002e4e63..e171cd88d47 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@@ -3,10 +3,16 @@ import { act, cleanup, render, screen, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type * as HermesApi from '@/hermes'-import { $freeTierSignIn, openFreeTierSignIn } from '@/store/free-tier-sign-in'+import { $freeTierStatus } from '@/store/free-tier'+import { $freeTierSignIn, noteFreeTierTurnComplete, openFreeTierSignIn } from '@/store/free-tier-sign-in'+import { $onboardingGate } from '@/store/onboarding-gate'+import type { FreeTierStatus } from '@/types/hermes'const pollOAuthSession = vi.fn()-const requestGateway = vi.fn(async () => ({ available: true, has_guest: true }))+// The two answers the dialog reads: `free_tier.status` and `free_tier.claim_nudge`.+type GatewayAnswer = { claimed: boolean } | Partial<FreeTierStatus>++const requestGateway = vi.fn(async (_method?: string): Promise<GatewayAnswer> => ({ available: true, has_guest: true }))// Only the two calls this flow makes are replaced; everything else keeps its// real implementation so the modules the dialog pulls in (the onboarding@@ -35,6 +41,9 @@ beforeEach(() => {afterEach(() => {cleanup()$freeTierSignIn.set({ status: 'closed' })+ $freeTierStatus.set(null)+ $onboardingGate.set({ guideKickoff: 'idle', guideQueued: false, phase: 'idle' })+ Reflect.deleteProperty(window, 'hermesDesktop')vi.restoreAllMocks()vi.clearAllMocks()vi.useRealTimers()@@ -75,4 +84,79 @@ describe('FreeTierSignInDialog', () => {await waitFor(() => expect(screen.getByText('Signed in as [email protected]')).toBeTruthy())expect(screen.getByText('Hermes-4-405B')).toBeTruthy()})++ describe('sign-in offer', () => {+ const dueNow = { available: true, enabled: true, has_guest: true, label: '', model: '', notice_pending: false }++ async function renderDialog() {+ const { FreeTierSignInDialog } = await import('./sign-in-dialog')++ await act(async () => {+ render(+ <QueryClientProvider client={new QueryClient()}>+ <FreeTierSignInDialog />+ </QueryClientProvider>+ )+ })+ }++ beforeEach(() => {+ requestGateway.mockImplementation(async (method?: string) =>+ method === 'free_tier.claim_nudge' ? { claimed: true } : { ...dueNow, nudge_due_in: null }+ )+ })++ it('waits for guided onboarding to leave the screen, then offers sign-in', async () => {+ Object.assign(window, { hermesDesktop: { guestOnboardingEnabled: true } })+ $onboardingGate.set({ guideKickoff: 'started', guideQueued: false, phase: 'guided' })+ await renderDialog()++ await act(async () => {+ $freeTierStatus.set({ ...dueNow, nudge_due_in: 0 })+ })++ expect(requestGateway).not.toHaveBeenCalledWith('free_tier.claim_nudge')++ await act(async () => {+ $onboardingGate.set({ guideKickoff: 'started', guideQueued: false, phase: 'done' })+ })++ await waitFor(() => expect(screen.getByText('Keep going with Hermes')).toBeTruthy())+ expect(requestGateway).toHaveBeenCalledWith('free_tier.claim_nudge')+ })++ it('a finished free-tier turn re-reads the status, and a due offer opens with no user action', async () => {+ await renderDialog()+ await act(async () => {+ $freeTierStatus.set({ ...dueNow, nudge_due_in: null })+ })+ // The backend recorded the finished task before message.complete: the next read says due.+ requestGateway.mockImplementation(async (method?: string) =>+ method === 'free_tier.claim_nudge' ? { claimed: true } : { ...dueNow, nudge_due_in: 0 }+ )++ await act(async () => noteFreeTierTurnComplete())++ await waitFor(() => expect(screen.getByText('Keep going with Hermes')).toBeTruthy())+ })++ it('Sign in continues into the normal sign-in flow', async () => {+ await renderDialog()+ await act(async () => $freeTierSignIn.set({ status: 'offer' }))++ await act(async () => screen.getByRole('button', { name: 'Sign in' }).click())++ await waitFor(() => expect(screen.getByText('Do not share this code.')).toBeTruthy())+ })++ it('Not now closes the offer', async () => {+ await renderDialog()+ await act(async () => $freeTierSignIn.set({ status: 'offer' }))++ await act(async () => screen.getByRole('button', { name: 'Not now' }).click())++ expect($freeTierSignIn.get()).toEqual({ status: 'closed' })+ expect(screen.queryByText('Keep going with Hermes')).toBeNull()+ })+ })})diff --git a/apps/desktop/src/components/free-tier/sign-in-dialog.tsx b/apps/desktop/src/components/free-tier/sign-in-dialog.tsxindex 252f60b5c31..1a4f80c1d67 100644--- a/apps/desktop/src/components/free-tier/sign-in-dialog.tsx+++ b/apps/desktop/src/components/free-tier/sign-in-dialog.tsx@@ -18,9 +18,16 @@ import {import { getGlobalModelOptions } from '@/hermes'import { type Translations, useI18n } from '@/i18n'import { CheckCircle2, Loader2 } from '@/lib/icons'-import { FREE_TIER_MODEL, friendlyWait, NOUS_PROVIDER_ID, refreshFreeTierStatus } from '@/store/free-tier'+import {+ $freeTierStatus,+ FREE_TIER_MODEL,+ friendlyWait,+ NOUS_PROVIDER_ID,+ refreshFreeTierStatus+} from '@/store/free-tier'import {$freeTierSignIn,+ $freeTierTurnCompleted,beginFreeTierSignIn,claimFreeTierSignIn,closeFreeTierSignIn,@@ -28,9 +35,13 @@ import {copyFreeTierUrl,freeTierSignInClaim,type FreeTierSignInFailure,- releaseFreeTierSignIn+ releaseFreeTierSignIn,+ stopFreeTierOffer,+ syncFreeTierOffer} from '@/store/free-tier-sign-in'import { refreshOnboardingProviders } from '@/store/onboarding'+import { $onboardingGate } from '@/store/onboarding-gate'+import { $onboardingSurfaces } from '@/store/onboarding-presence'import { $currentModel, setModelPickerOpen } from '@/store/session'interface FreeTierSignInDialogProps {@@ -72,6 +83,32 @@ export function FreeTierSignInDialog({ onSelectModel }: FreeTierSignInDialogProp}}, [owned, requestGateway, state.status])+ // The sign-in offer rides every status read, and retries once guided+ // onboarding leaves the screen. A completed free-tier turn re-reads the+ // status, since that is when the backend arms the next offer. Only the+ // owner (main windows) times it.+ useEffect(() => {+ if (!owned) {+ return+ }++ const sync = () => syncFreeTierOffer($freeTierStatus.get(), requestGateway)++ const stops = [+ $freeTierStatus.listen(sync),+ $onboardingGate.listen(sync),+ $onboardingSurfaces.listen(sync),+ $freeTierTurnCompleted.listen(() => void refreshFreeTierStatus(requestGateway))+ ]++ sync()++ return () => {+ stops.forEach(stop => stop())+ stopFreeTierOffer()+ }+ }, [owned, requestGateway])+if (!owned || state.status === 'closed' || state.status === 'requested') {return null}@@ -105,6 +142,19 @@ export function FreeTierSignInDialog({ onSelectModel }: FreeTierSignInDialogPropreturn (<Dialog onOpenChange={open => !open && closeFreeTierSignIn()} open><DialogContent onOpenAutoFocus={preventCloseButtonAutoFocus}>+ {state.status === 'offer' && (+ <Screen body={copy.offer.body} heading={copy.offer.heading}>+ <Actions>+ <Button onClick={() => closeFreeTierSignIn()} size="sm" type="button" variant="text">+ {copy.offer.notNow}+ </Button>+ <Button onClick={retry} type="button">+ {copy.offer.signIn}+ </Button>+ </Actions>+ </Screen>+ )}+{state.status === 'setting_up' && (<Screen heading={copy.signInHeading}><Spinner>{state.minting ? copy.settingUp : copy.waiting}</Spinner>diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 80d07577cbc..14022b536fa 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -68,6 +68,14 @@ export const arOverrides = {localTitle: 'يمكن لهذا الجهاز تشغيل النماذج محليًا',localText: (model: string) =>`${model} يناسب أجهزتك. يعمل مجانًا، ولا تغادر المحادثات جهازك. اختره من هنا، من قائمة النماذج، متى شئت.`+ },+ freeTier: {+ offer: {+ heading: 'واصل مع Hermes',+ body: 'أنت تستخدم الحصة المجانية. إذا واصلت استخدام Hermes فستبدأ بمواجهة حدود الاستخدام. سجّل الدخول بحساب Nous مجاني للحصول على حصة أكبر.',+ signIn: 'تسجيل الدخول',+ notNow: 'ليس الآن'+ }}} satisfies TranslationOverridesdiff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.tsindex 68cc39d2e1f..69f0b994cd2 100644--- a/apps/desktop/src/i18n/de.ts+++ b/apps/desktop/src/i18n/de.ts@@ -4634,6 +4634,12 @@ export const deOverrides = {'Hermes konnte den Nous-Dienst nicht erreichen, um Ihre Anmeldung abzuschließen. Prüfen Sie Ihre Internetverbindung und versuchen Sie es erneut. Ihre Session bleibt erhalten.',alreadySignedInHeading: 'Bereits angemeldet.',alreadySignedInBody: 'Dieses Hermes ist bereits mit einem Nous-Konto angemeldet.',+ offer: {+ heading: 'Mit Hermes weitermachen',+ body: 'Sie nutzen das kostenlose Kontingent. Wenn Sie Hermes weiter verwenden, stoßen Sie bald an Grenzen. Melden Sie sich mit einem kostenlosen Nous-Konto an, um ein größeres Kontingent zu erhalten.',+ signIn: 'Anmelden',+ notNow: 'Nicht jetzt'+ },setupFailed: {gateClosed:'Diese Hermes-Version kann ohne Nous-Konto nicht starten. Melden Sie sich an oder legen Sie eines an – kostenlos und in einer Minute erledigt.',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 4550386e49e..468aef152ad 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -4188,6 +4188,12 @@ export const en: Translations = {"Hermes couldn't reach the Nous service to finish signing you in. Check your internet connection and try again. Your session is still here.",alreadySignedInHeading: 'Already signed in.',alreadySignedInBody: 'This Hermes is already signed in to a Nous account.',+ offer: {+ heading: 'Keep going with Hermes',+ body: "You're on the free allowance. If you keep using Hermes, you'll start running into limits. Sign in with a free Nous account for a bigger allowance.",+ signIn: 'Sign in',+ notNow: 'Not now'+ },setupFailed: {gateClosed:"This version of Hermes can't start without a Nous account. Sign in or create one, it's free and only takes a minute.",diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.tsindex ec1fa16cb03..2e672dee2c7 100644--- a/apps/desktop/src/i18n/es.ts+++ b/apps/desktop/src/i18n/es.ts@@ -4629,6 +4629,12 @@ export const esOverrides = {'Hermes no pudo llegar al servicio de Nous para terminar de iniciar tu sesión. Comprueba tu conexión a internet y vuelve a intentarlo. Tu sesión sigue aquí.',alreadySignedInHeading: 'Ya has iniciado sesión.',alreadySignedInBody: 'Este Hermes ya tiene la sesión iniciada en una cuenta de Nous.',+ offer: {+ heading: 'Sigue adelante con Hermes',+ body: 'Estás usando el uso gratuito. Si sigues usando Hermes, empezarás a encontrarte con límites. Inicia sesión con una cuenta gratuita de Nous para tener un uso mayor.',+ signIn: 'Iniciar sesión',+ notNow: 'Ahora no'+ },setupFailed: {gateClosed:'Esta versión de Hermes no puede iniciarse sin una cuenta de Nous. Inicia sesión o crea una: es gratis y solo lleva un minuto.',diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.tsindex 95b5bed2f27..dca43ed18be 100644--- a/apps/desktop/src/i18n/fr.ts+++ b/apps/desktop/src/i18n/fr.ts@@ -4645,6 +4645,12 @@ export const frOverrides = {"Hermes n'a pas pu joindre le service Nous pour terminer votre connexion. Vérifiez votre connexion Internet et réessayez. Votre session reste disponible.",alreadySignedInHeading: 'Déjà connecté.',alreadySignedInBody: 'Cette installation Hermes est déjà connectée à un compte Nous.',+ offer: {+ heading: 'Continuez avec Hermes',+ body: 'Vous utilisez le quota gratuit. Si vous continuez à utiliser Hermes, vous allez commencer à atteindre des limites. Connectez-vous avec un compte Nous gratuit pour obtenir un quota plus important.',+ signIn: 'Se connecter',+ notNow: 'Pas maintenant'+ },setupFailed: {gateClosed:'Cette version de Hermes ne peut pas démarrer sans compte Nous. Connectez-vous ou créez-en un gratuitement en une minute.',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 6e92801daac..870a8059faf 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -4062,6 +4062,14 @@ export const jaOverrides = {description: 'モバイルサイドバーを表示します。',toggle: open => `サイドバーを${open ? '表示' : '非表示'}`}+ },+ freeTier: {+ offer: {+ heading: 'Hermes を使い続ける',+ body: '現在は無料枠をご利用中です。Hermes を使い続けると、いずれ上限に達します。無料の Nous アカウントでサインインすると、より多くの利用枠が使えます。',+ signIn: 'サインイン',+ notNow: '今はしない'+ }}} satisfies TranslationOverridesdiff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex eac4081eefe..1927c3c0c16 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -4193,6 +4193,14 @@ export const ruOverrides = {description: 'Показывает мобильную боковую панель.',toggle: open => `${open ? 'Показать' : 'Скрыть'} боковую панель`}+ },+ freeTier: {+ offer: {+ heading: 'Продолжайте с Hermes',+ body: 'Вы пользуетесь бесплатным лимитом. Если продолжите работать с Hermes, скоро начнёте упираться в ограничения. Войдите с бесплатной учётной записью Nous, чтобы получить больший лимит.',+ signIn: 'Войти',+ notNow: 'Не сейчас'+ }}} satisfies TranslationOverridesdiff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 3cd9d3cd980..bfca14c2d8d 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -3621,6 +3621,13 @@ export interface Translations extends NoticeTranslations {unreachableBody: stringalreadySignedInHeading: stringalreadySignedInBody: string+ /** The "keep going" offer the backend times after a finished task (repeats, backing off). */+ offer: {+ heading: string+ body: string+ signIn: string+ notNow: string+ }// First-launch set-up failure notice: the free tier could not be created at boot.// One sentence per backend code (`hermes_cli/anon_auth.py::ANON_*`); the copy never says// the free MODEL is off — what is unavailable is using Hermes without signing in.@@ -4217,8 +4224,8 @@ export interface Translations extends NoticeTranslations {skipped: stringnoAnswer: stringconfirmAndContinueLabel: string- singleSelectHint: string;- multiSelectHint: string;+ singleSelectHint: string+ multiSelectHint: stringoneQuestion: stringquestionProgress: (answered: number, total: number) => stringnotDelivered: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex c67e3760ca8..6f43aac1e94 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -140,6 +140,14 @@ export const zhHantOverrides = {localTitle: '這台電腦可以在本機執行模型',localText: (model: string) =>`${model} 適合你的硬體。免費執行,對話不會離開你的電腦。隨時在這裡的模型選單中選擇它。`+ },+ freeTier: {+ offer: {+ heading: '繼續使用 Hermes',+ body: '你正在使用免費額度。繼續使用 Hermes 的話,你會開始遇到限制。登入免費的 Nous 帳戶,即可獲得更多額度。',+ signIn: '登入',+ notNow: '暫不'+ }}} satisfies TranslationOverridesdiff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 1bce0003df1..72102e9692f 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -4064,7 +4064,13 @@ export const zhOverrides = {retiredBody: '此免费层身份已被使用或已过期;下次启动时会重新设置。',errorBody: '登录未完成;请重试。',alreadySignedInHeading: '已登录。',- alreadySignedInBody: '此 Hermes 已登录 Nous 账户。'+ alreadySignedInBody: '此 Hermes 已登录 Nous 账户。',+ offer: {+ heading: '继续使用 Hermes',+ body: '你正在使用免费额度。继续使用 Hermes 的话,你会开始遇到限制。登录免费的 Nous 账户,即可获得更多额度。',+ signIn: '登录',+ notNow: '暂不'+ }},modelPicker: {diff --git a/apps/desktop/src/store/free-tier-offer.test.ts b/apps/desktop/src/store/free-tier-offer.test.tsnew file mode 100644index 00000000000..94cbf3ae79b--- /dev/null+++ b/apps/desktop/src/store/free-tier-offer.test.ts@@ -0,0 +1,116 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { $freeTierStatus, type FreeTierRequester } from '@/store/free-tier'+import { $freeTierSignIn, closeFreeTierSignIn, stopFreeTierOffer, syncFreeTierOffer } from '@/store/free-tier-sign-in'+import { $onboardingGate } from '@/store/onboarding-gate'+import type { FreeTierStatus } from '@/types/hermes'++const status = (nudge_due_in: null | number, available = true): FreeTierStatus => ({+ available,+ enabled: true,+ has_guest: available,+ label: 'Nous · free tier',+ model: 'nous/welcome',+ notice_pending: false,+ nudge_due_in+})++// The backend's two answers: what `free_tier.status` reads now, and whether this caller won the claim.+function gateway({ claimed = true, statuses }: { claimed?: boolean; statuses: FreeTierStatus[] }) {+ const queue = [...statuses]++ const requestGateway = vi.fn(async (method: string) => {+ if (method === 'free_tier.claim_nudge') {+ return { claimed }+ }++ return queue.length > 1 ? queue.shift() : queue[0]+ })++ // SAFETY: the code under test asks only these two methods and reads exactly these shapes back.+ return requestGateway as typeof requestGateway & FreeTierRequester+}++const claims = (requestGateway: ReturnType<typeof gateway>) =>+ requestGateway.mock.calls.filter(([method]) => method === 'free_tier.claim_nudge').length++let stop: () => void = () => undefined++// What the dialog owner does: every status read goes through the offer sync.+function own(requestGateway: FreeTierRequester) {+ stop = $freeTierStatus.listen(next => syncFreeTierOffer(next, requestGateway))+}++beforeEach(() => {+ vi.useFakeTimers()+})++afterEach(() => {+ stop()+ stopFreeTierOffer()+ closeFreeTierSignIn()+ $freeTierStatus.set(null)+ $onboardingGate.set({ guideKickoff: 'idle', guideQueued: false, phase: 'idle' })+ Reflect.deleteProperty(window, 'hermesDesktop')+ vi.useRealTimers()+})++describe('sign-in offer after a finished task', () => {+ it('due now: claims once and opens the offer', async () => {+ const requestGateway = gateway({ statuses: [status(null)] })++ syncFreeTierOffer(status(0), requestGateway)+ await vi.advanceTimersByTimeAsync(0)++ expect(claims(requestGateway)).toBe(1)+ expect($freeTierSignIn.get()).toEqual({ status: 'offer' })+ })++ it('due later: waits out nudge_due_in, re-reads the status, then claims', async () => {+ const requestGateway = gateway({ statuses: [status(0), status(null)] })+ own(requestGateway)++ syncFreeTierOffer(status(180), requestGateway)+ await vi.advanceTimersByTimeAsync(179_000)++ expect(requestGateway).not.toHaveBeenCalled()+ expect($freeTierSignIn.get()).toEqual({ status: 'closed' })++ await vi.advanceTimersByTimeAsync(1_000)++ expect(requestGateway).toHaveBeenCalledWith('free_tier.status')+ expect(claims(requestGateway)).toBe(1)+ expect($freeTierSignIn.get()).toEqual({ status: 'offer' })+ })++ it('a claim another window won leaves the dialog closed', async () => {+ const requestGateway = gateway({ claimed: false, statuses: [status(null)] })++ syncFreeTierOffer(status(0), requestGateway)+ await vi.advanceTimersByTimeAsync(0)++ expect(claims(requestGateway)).toBe(1)+ expect($freeTierSignIn.get()).toEqual({ status: 'closed' })+ })++ it('does not claim while guided onboarding is on screen, the dialog is open, or off the free tier', async () => {+ const requestGateway = gateway({ statuses: [status(0)] })++ Object.assign(window, { hermesDesktop: { guestOnboardingEnabled: true } })+ $onboardingGate.set({ guideKickoff: 'started', guideQueued: false, phase: 'guided' })+ syncFreeTierOffer(status(0), requestGateway)+ await vi.advanceTimersByTimeAsync(0)+ $onboardingGate.set({ guideKickoff: 'started', guideQueued: false, phase: 'done' })++ $freeTierSignIn.set({ status: 'requested' })+ syncFreeTierOffer(status(0), requestGateway)+ await vi.advanceTimersByTimeAsync(0)+ $freeTierSignIn.set({ status: 'closed' })++ syncFreeTierOffer(status(0, false), requestGateway)+ await vi.advanceTimersByTimeAsync(0)++ expect(claims(requestGateway)).toBe(0)+ expect($freeTierSignIn.get()).toEqual({ status: 'closed' })+ })+})diff --git a/apps/desktop/src/store/free-tier-sign-in.ts b/apps/desktop/src/store/free-tier-sign-in.tsindex 864826fd65d..391b25e75d9 100644--- a/apps/desktop/src/store/free-tier-sign-in.ts+++ b/apps/desktop/src/store/free-tier-sign-in.ts@@ -1,8 +1,12 @@+import type { FreeTierClaimNudgeResult } from '@hermes/shared'import { atom } from 'nanostores'import { cancelOAuthSession, listOAuthProviders, pollOAuthSession, startOAuthLogin } from '@/hermes'+import type { FreeTierStatus } from '@/types/hermes'-import { type FreeTierRequester, NOUS_PROVIDER_ID, refreshFreeTierStatus } from './free-tier'+import { $freeTierStatus, type FreeTierRequester, NOUS_PROVIDER_ID, refreshFreeTierStatus } from './free-tier'+import { guidedOnboardingActive } from './onboarding-gate'+import { onboardingSurfaceActive } from './onboarding-presence'const POLL_MS = 2000const COPY_FLASH_MS = 1500@@ -24,6 +28,10 @@ export type FreeTierSignInState =// A "please open the dialog" request from an entry point that has no gateway// requester of its own. The mounted host picks it up and drives the flow.| { status: 'requested' }+ // The "keep going" offer after a finished task (backend-timed, repeating with+ // 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' }// `retryAfter`: the seconds the backend asked us to wait before trying// again (0 when it named none); only `busy` screens read it.@@ -105,6 +113,93 @@ export function openFreeTierSignIn() {}}+let offerTimer: number | null = null+let offerTimerFor: FreeTierStatus | null = null+let offerClaiming = false++function clearOfferTimer() {+ if (offerTimer !== null) {+ window.clearTimeout(offerTimer)+ offerTimer = null+ }+}++// Bumped when a turn completes on the free tier. The backend records the finished task before it+// sends message.complete, so the dialog owner's re-read on this signal learns when the next offer is due.+export const $freeTierTurnCompleted = atom(0)++export function noteFreeTierTurnComplete() {+ if ($freeTierStatus.get()?.available) {+ $freeTierTurnCompleted.set($freeTierTurnCompleted.get() + 1)+ }+}++/** Stop a pending offer timer (the dialog owner unmounted). */+export function stopFreeTierOffer() {+ clearOfferTimer()+}++/**+ * Act on the backend's `nudge_due_in` (it alone decides when the next+ * offer is due). Later: one timer that re-reads the status, whose fresh answer+ * comes back through here. Due now: claim it, and only the one caller the+ * backend says `claimed` opens the offer. Called on every status read and when+ * guided onboarding leaves the screen; a guarded call simply waits for the next.+ */+export function syncFreeTierOffer(status: FreeTierStatus | null, requestGateway: FreeTierRequester) {+ // A re-sync on the same read (an onboarding change) keeps its running timer, so it is not pushed back.+ if (offerTimer !== null && status === offerTimerFor) {+ return+ }++ clearOfferTimer()+ const dueIn = status?.available ? (status.nudge_due_in ?? null) : null++ if (dueIn === null) {+ return+ }++ if (dueIn > 0) {+ offerTimerFor = status+ offerTimer = window.setTimeout(() => {+ offerTimer = null+ void refreshFreeTierStatus(requestGateway)+ }, dueIn * 1000)++ return+ }++ void claimFreeTierOffer(requestGateway)+}++const offerBlocked = () =>+ offerClaiming || guidedOnboardingActive() || onboardingSurfaceActive() || $freeTierSignIn.get().status !== 'closed'++async function claimFreeTierOffer(requestGateway: FreeTierRequester) {+ if (offerBlocked()) {+ return+ }++ offerClaiming = true+ let claimed: boolean++ try {+ claimed = (await requestGateway<FreeTierClaimNudgeResult>('free_tier.claim_nudge'))?.claimed === true+ } catch {+ // Not claimed; the next status read tries again. No re-read here, or a failing call would loop.+ return+ } finally {+ offerClaiming = false+ }++ if (claimed && $freeTierSignIn.get().status === 'closed') {+ set({ status: 'offer' })+ }++ // The claim settled the offer either way; re-read so the cached `nudge_due_in` drops.+ void refreshFreeTierStatus(requestGateway)+}+/** Close and abandon. Cancels a live device-code session so the backend is not* left polling a window nobody is watching. */export function closeFreeTierSignIn() {diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex e86020d6f78..5106d1c233d 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -183,6 +183,8 @@ export interface FreeTierStatus {retry_after?: number/** Present while the backend is waiting on a browser challenge. */challenge?: FreeTierChallengePayload | null+ /** Seconds until the one-time first-task sign-in offer is due (0 = now); null when none is owed. */+ nudge_due_in?: number | null}export interface MemoryProviderOAuthStatus {diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.jsonindex fc454f6a3ca..c684a9748b6 100644--- a/locales/_keys.desktop.json+++ b/locales/_keys.desktop.json@@ -1526,6 +1526,10 @@"freeTier.finishingBody","freeTier.finishingHeading","freeTier.notNow",+ "freeTier.offer.body",+ "freeTier.offer.heading",+ "freeTier.offer.notNow",+ "freeTier.offer.signIn","freeTier.openModelPicker","freeTier.otherProviders","freeTier.providerName",