Skip to content

The agent that grows with you

refactor(desktop,tui): free-tier challenge wiring lives in topical modules, not the facades

kshitijk4poor69a12d220367
diff --git a/apps/desktop/electron/challenge-window-ipc.ts b/apps/desktop/electron/challenge-window-ipc.ts
new file mode 100644
index 00000000000..e289e726eef
--- /dev/null
+++ b/apps/desktop/electron/challenge-window-ipc.ts
@@ -0,0 +1,14 @@
+import { ipcMain } from 'electron'
+
+import { type ChallengeWindowDependencies, createChallengeWindows, parseChallengeRequest } from './challenge-window'
+
+/** The renderer's `hermes:freeTierChallenge:run` invoke (preload `freeTierChallenge.run`). */
+export function registerChallengeWindowIpc(dependencies: ChallengeWindowDependencies): void {
+ const windows = createChallengeWindows(dependencies)
+
+ ipcMain.handle('hermes:freeTierChallenge:run', (_event, payload) => {
+ const request = parseChallengeRequest(payload)
+
+ return request ? windows.run(request) : 'refused'
+ })
+}
diff --git a/apps/desktop/electron/challenge-window.ts b/apps/desktop/electron/challenge-window.ts
index d3f9072092d..55a50da07c2 100644
--- a/apps/desktop/electron/challenge-window.ts
+++ b/apps/desktop/electron/challenge-window.ts
@@ -49,7 +49,7 @@ export interface ChallengeRequest {
attempt?: number
}
-interface ChallengeWindowDependencies {
+export interface ChallengeWindowDependencies {
isReady: () => boolean
getSession: () => Session | null
resolvePortalBaseUrl: () => string
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 1cf7cf14489..8d65d7e4104 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -125,6 +125,8 @@ import {
readBundleSwapStamp,
relaunchIntoSwappedBundle
} from './bundle-swap'
+import { CHALLENGE_PARTITION } from './challenge-window'
+import { registerChallengeWindowIpc } from './challenge-window-ipc'
import { registerChatOnboardingWindow } from './chat-onboarding-window'
import { provisionCliLinks } from './cli-provision'
import { closeStopFailureMessage, finishWindowsCloseStop, type RuntimeLock } from './close-stop-kill'
@@ -448,8 +450,7 @@ import {
} from './pool-spawn-coordinator'
import { createPoolStopper } from './pool-stop'
import { poolTouchKeys } from './pool-touch-scope'
-import { CHALLENGE_PARTITION, createChallengeWindows, parseChallengeRequest } from './challenge-window'
-import { createPortalSession } from './portal-session'
+import { createPortalSession, resolvePortalBaseUrl } from './portal-session'
import {
createKeepAwake,
type KeepAwakeMode,
@@ -8148,17 +8149,6 @@ async function freshGatewayWsUrl(profile) {
// with that agent's session cookie — no prompt. Each agent still completes
// its own PKCE exchange; SSO removes the human click, not a security check.
-// Canonical Nous portal base URL, overridable for staging/dev. Mirrors the CLI
-// convention (hermes_cli/auth.py DEFAULT_NOUS_PORTAL_URL + the same env names)
-// so a single override flips every Hermes surface to the same portal.
-const DEFAULT_NOUS_PORTAL_URL = 'https://portal.nousresearch.com'
-
-function resolvePortalBaseUrl() {
- const raw = process.env.HERMES_PORTAL_BASE_URL || process.env.NOUS_PORTAL_BASE_URL || DEFAULT_NOUS_PORTAL_URL
-
- return String(raw).trim().replace(/\/+$/, '')
-}
-
const { hasLivePortalSession, hasPortalAccessToken, renewPortalAccessSilently, openPortalLoginWindow } =
createPortalSession({
isReady: () => app.isReady(),
@@ -8169,17 +8159,6 @@ const { hasLivePortalSession, hasPortalAccessToken, renewPortalAccessSilently, o
rememberLog
})
-// The free tier's browser challenge (hermes_cli/anon_challenge.py): the portal
-// page runs in a hidden window of its own partition, revealed only if it asks
-// for the human. See electron/challenge-window.ts.
-const freeTierChallengeWindows = createChallengeWindows({
- isReady: () => app.isReady(),
- getSession: () => session.fromPartition(CHALLENGE_PARTITION),
- resolvePortalBaseUrl,
- createWindow: options => new BrowserWindow(options),
- rememberLog
-})
-
// Discover the hosted (Hermes Cloud) agents the signed-in user can see. Calls
// the NAS trimmed-summary endpoint over the partition-bound net, so the portal
// session cookie is attached automatically (no bearer needed — NAS accepts the
@@ -18490,10 +18469,13 @@ ipcMain.on('hermes:devtools:disable-f12', (_event, on) => {
}
})
-ipcMain.handle('hermes:freeTierChallenge:run', (_event, payload) => {
- const request = parseChallengeRequest(payload)
-
- return request ? freeTierChallengeWindows.run(request) : 'refused'
+// Free-tier browser challenge: a hidden portal window (electron/challenge-window.ts).
+registerChallengeWindowIpc({
+ isReady: () => app.isReady(),
+ getSession: () => session.fromPartition(CHALLENGE_PARTITION),
+ resolvePortalBaseUrl,
+ createWindow: options => new BrowserWindow(options),
+ rememberLog
})
ipcMain.handle('hermes:openExternal', async (_event, url) => {
diff --git a/apps/desktop/electron/portal-session.ts b/apps/desktop/electron/portal-session.ts
index 2da2d444dac..ef96a16cd56 100644
--- a/apps/desktop/electron/portal-session.ts
+++ b/apps/desktop/electron/portal-session.ts
@@ -23,6 +23,17 @@ interface CookieWindowOptions {
type CookieWindowOutcome = 'landed' | 'closed' | 'timeout' | Error
+// Canonical Nous portal base URL, overridable for staging/dev. Mirrors the CLI
+// convention (hermes_cli/auth.py DEFAULT_NOUS_PORTAL_URL + the same env names)
+// so a single override flips every Hermes surface to the same portal.
+const DEFAULT_NOUS_PORTAL_URL = 'https://portal.nousresearch.com'
+
+export function resolvePortalBaseUrl() {
+ const raw = process.env.HERMES_PORTAL_BASE_URL || process.env.NOUS_PORTAL_BASE_URL || DEFAULT_NOUS_PORTAL_URL
+
+ return String(raw).trim().replace(/\/+$/, '')
+}
+
// Portal credentials belong to NAS, independently of the selected gateway.
// Read the jar on every operation so provider changes never latch in Desktop.
export function createPortalSession({
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/free-tier.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/free-tier.ts
new file mode 100644
index 00000000000..00b09417221
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/free-tier.ts
@@ -0,0 +1,23 @@
+import { runFreeTierChallenge } from '@/store/free-tier-challenge'
+import { activeGatewayConnectionId, requestGatewayForAgent } from '@/store/gateway'
+
+import type { GatewayEventContext } from './types'
+
+/**
+ * free_tier.challenge: the account service wants a browser challenge cleared
+ * before it mints the free-tier token. The backend polls for the result on its
+ * own; this only gets the page loaded (hidden). Any source's challenge is worth
+ * running: it is the install's identity, not the focused session's.
+ */
+export function handleFreeTierEvent({ deps, event, payload }: GatewayEventContext): boolean {
+ if (event.type !== 'free_tier.challenge') {
+ return false
+ }
+
+ const connectionId = event.connectionId ?? activeGatewayConnectionId()
+ const profile = event.profile ?? deps.activeGatewayProfile
+
+ void runFreeTierChallenge(payload, (method, params) => requestGatewayForAgent(connectionId, profile, method, params))
+
+ return true
+}
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts
index 5e956645774..901003ab81c 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/index.ts
@@ -17,6 +17,7 @@ import { noteSessionEvent } from '@/store/session-states'
import { setSessionDraftingTool } from '@/store/tool-drafting'
import { handleDesktopBridgeEvent } from './desktop-bridge'
+import { handleFreeTierEvent } from './free-tier'
import { handleInputRequestEvent } from './input-requests'
import { handleLifecycleEvent } from './lifecycle'
import { handleMessageStreamEvent } from './message-stream'
@@ -81,6 +82,7 @@ const PROVIDER_WAIT_SUPERSEDING_EVENT_TYPES = new Set([
// whether it did, so dispatch stops at the first taker.
const HANDLERS: GatewayEventHandler[] = [
handleLifecycleEvent,
+ handleFreeTierEvent,
handleSessionInfoEvent,
handleControlEvent,
handleMessageStreamEvent,
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts
index 5ef4221cb5c..06641ecb48f 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts
@@ -3,8 +3,6 @@ import type { HermesSkin } from '@hermes/shared/skin'
import { invalidateContextBreakdown } from '@/app/shell/hooks/use-context-breakdown'
import { clearClarifyRequest } from '@/store/clarify'
-import { runFreeTierChallenge } from '@/store/free-tier-challenge'
-import { activeGatewayConnectionId, requestGatewayForAgent } from '@/store/gateway'
import {
notifyCronChanged,
notifyPairingChanged,
@@ -55,19 +53,6 @@ export function handleLifecycleEvent(ctx: GatewayEventContext): boolean {
return true
}
- if (event.type === 'free_tier.challenge') {
- // The account service wants a browser challenge cleared before it mints
- // the free-tier token. The backend polls for the result on its own; this
- // only gets the page loaded (hidden). Any source's challenge is worth
- // running: it is the install's identity, not the focused session's.
- const connectionId = event.connectionId ?? activeGatewayConnectionId()
- const profile = event.profile ?? deps.activeGatewayProfile
-
- void runFreeTierChallenge(payload, (method, params) => requestGatewayForAgent(connectionId, profile, method, params))
-
- return true
- }
-
if (event.type === 'skin.changed') {
// A runtime skin switch (Hermes activating an authored skin, or `/skin`
// on another surface). Only the active source+profile's change repaints.
diff --git a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
index ccc0c777ae8..3761d459995 100644
--- a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
+++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
@@ -2247,34 +2247,6 @@ describe('createGatewayEventHandler', () => {
})
})
- describe('free_tier.challenge', () => {
- beforeEach(() => {
- openExternalUrlMock.mockClear()
- })
-
- it('shows the link and opens one tab per ticket; an optional check opens nothing', () => {
- const ctx = buildCtx([])
- const onEvent = createGatewayEventHandler(ctx)
- const url = 'https://portal.example/challenge?code=t'
-
- const event = (required: boolean) =>
- ({
- payload: { attempt: 0, expires_in: 600, message: 'A quick check first.', required, type: 'browser', url },
- type: 'free_tier.challenge'
- }) as any
-
- onEvent(event(false))
- expect(openExternalUrlMock).not.toHaveBeenCalled()
-
- onEvent(event(true))
- onEvent(event(true))
-
- const printed = (ctx.system.sys as ReturnType<typeof vi.fn>).mock.calls.map(c => c[0]).join('\n')
- expect(printed).toContain(url)
- expect(openExternalUrlMock).toHaveBeenCalledTimes(1)
- })
- })
-
describe('session.usage', () => {
it('merges a live usage tick into uiState (payload.usage shape, see tui_gateway _start_usage_ticker)', () => {
patchUiState({ sid: 'sess-1' })
diff --git a/ui-tui/src/__tests__/gatewayBrowserLinks.test.ts b/ui-tui/src/__tests__/gatewayBrowserLinks.test.ts
new file mode 100644
index 00000000000..0357aed439b
--- /dev/null
+++ b/ui-tui/src/__tests__/gatewayBrowserLinks.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { createFreeTierChallengePresenter } from '../app/gatewayBrowserLinks.js'
+
+const url = 'https://portal.example/challenge?code=t'
+
+const challenge = (required: boolean) => ({
+ attempt: 0,
+ expires_in: 600,
+ message: 'A quick check first.',
+ required,
+ type: 'browser' as const,
+ url
+})
+
+describe('free_tier.challenge presenter', () => {
+ it('shows the link and opens one tab per ticket; an optional check opens nothing', () => {
+ const sys = vi.fn()
+ const open = vi.fn()
+ const show = createFreeTierChallengePresenter(sys, open)
+
+ show(challenge(false))
+ expect(open).not.toHaveBeenCalled()
+
+ show(challenge(true))
+ show(challenge(true))
+
+ expect(sys.mock.calls.map(c => c[0]).join('\n')).toContain(url)
+ expect(open).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index f24ecce0921..861b2eaff3a 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -30,6 +30,7 @@ import type { Msg, SessionInfo, SubagentProgress } from '../types.js'
import { applyConnectionRequest, applyConnectionUpdate } from './connectionOperationStore.js'
import { applyDelegationStatus, getDelegationState } from './delegationStore.js'
+import { createFreeTierChallengePresenter, presentBillingVerification } from './gatewayBrowserLinks.js'
import { applyGoalSnapshot } from './goalStatus.js'
import type { GatewayEventHandlerContext, NoticeLevel } from './interfaces.js'
import { getOverlayState, patchOverlayState, SENSITIVE_PROMPTS } from './overlayStore.js'
@@ -464,8 +465,8 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
// an abandoned-prompt record, so the tool.complete and message.complete
// paths can't both persist the same prompt twice.
const persistedAbandonedClarify = new Set<string>()
- // One browser tab per free-tier challenge ticket, however many attempts resume it.
- const openedChallengeUrls = new Set<string>()
+ const showChallenge = createFreeTierChallengePresenter(sys, openExternalUrl)
+ const showBillingVerification = presentBillingVerification(sys, openExternalUrl)
// When a clarify prompt is dismissed without an answer (the backend request
// timed out and returned no answer), the live ClarifyPrompt overlay is
@@ -829,28 +830,11 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
}
return
- case 'free_tier.challenge': {
- // The account service wants a browser check before the free-tier token
- // (hermes_cli/anon_challenge.py). The gateway polls for the result on
- // its own; this only puts the link where the user is. An optional
- // check is the desktop's to run hidden, never the user's.
- const challenge = ev.payload
-
- if (!challenge?.required || !challenge.url) {
- return
- }
- sys(challenge.message)
- sys(challenge.url)
-
- if (!openedChallengeUrls.has(challenge.url)) {
- openedChallengeUrls.add(challenge.url)
- void openExternalUrl(challenge.url)
- }
+ case 'free_tier.challenge':
+ showChallenge(ev.payload)
return
- }
-
case 'session.info': {
let info = ev.payload as SessionInfo | undefined
@@ -1016,36 +1000,11 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
turnController.clearNotice(ev.payload?.key)
return
- case 'billing.step_up.verification': {
- // The billing step-up device flow runs in the headless gateway, so it
- // can't open a browser or print the URL where the user sees it. Surface
- // the link here (clickable/copyable in the transcript) and best-effort
- // open it via the TUI process's own opener. This event arrives while the
- // billing.step_up RPC is still polling (and may even outlive the RPC's
- // 120s timeout), so the link — not the RPC result — is the source of truth.
- if (!ev.payload) {
- return
- }
- const url = ev.payload.verification_url
- const code = ev.payload.user_code
-
- if (!url) {
- return
- }
-
- sys(t('gatewayMsg.billing.openLinkRemoteSpending'))
- sys(url)
-
- if (code) {
- sys(t('gatewayMsg.billing.enterCode', code))
- }
-
- void openExternalUrl(url)
+ case 'billing.step_up.verification':
+ showBillingVerification(ev.payload)
return
- }
-
case 'gateway.stderr': {
// Every raw line is already in the /logs buffer (gatewayClient.pushLog).
// Only failure-looking lines earn an activity row, and a traceback's
diff --git a/ui-tui/src/app/gatewayBrowserLinks.ts b/ui-tui/src/app/gatewayBrowserLinks.ts
new file mode 100644
index 00000000000..4490b827d1e
--- /dev/null
+++ b/ui-tui/src/app/gatewayBrowserLinks.ts
@@ -0,0 +1,64 @@
+import type { BillingStepUpVerificationPayload, FreeTierChallengePayload } from '@hermes/shared/gateway-events'
+
+import { t } from '../i18n/runtime.js'
+
+// Links the headless gateway needs the user to open in a browser: it cannot open one or print
+// where the user sees it, so the TUI shows the link (clickable/copyable) and opens it itself.
+
+type Sys = (text: string) => void
+type OpenUrl = (url: string) => unknown
+
+/**
+ * `billing.step_up.verification`: the billing step-up device flow. The event arrives while the
+ * billing.step_up RPC is still polling (and may outlive its 120s timeout), so the link, not the
+ * RPC result, is the source of truth.
+ */
+export function presentBillingVerification(
+ sys: Sys,
+ openExternalUrl: OpenUrl
+): (payload: BillingStepUpVerificationPayload | undefined) => void {
+ return payload => {
+ const url = payload?.verification_url
+
+ if (!url) {
+ return
+ }
+
+ sys(t('gatewayMsg.billing.openLinkRemoteSpending'))
+ sys(url)
+
+ if (payload.user_code) {
+ sys(t('gatewayMsg.billing.enterCode', payload.user_code))
+ }
+
+ void openExternalUrl(url)
+ }
+}
+
+/**
+ * `free_tier.challenge`: the account service wants a browser check before it
+ * mints the free-tier token (hermes_cli/anon_challenge.py). The gateway polls
+ * for the result on its own; this only puts the link where the user is. An
+ * optional check is the desktop's to run hidden, never the user's. One browser
+ * tab per ticket, however many attempts resume it.
+ */
+export function createFreeTierChallengePresenter(
+ sys: Sys,
+ openExternalUrl: OpenUrl
+): (challenge: FreeTierChallengePayload | undefined) => void {
+ const opened = new Set<string>()
+
+ return challenge => {
+ if (!challenge?.required || !challenge.url) {
+ return
+ }
+
+ sys(challenge.message)
+ sys(challenge.url)
+
+ if (!opened.has(challenge.url)) {
+ opened.add(challenge.url)
+ void openExternalUrl(challenge.url)
+ }
+ }
+}