The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): the welcome chat waits for a slow first boot instead of timing out (#130057)
Siddharth Balyan70e62c3b8f29
diff --git a/apps/desktop/src/app/contrib/onboarding-kickoff-machine.ts b/apps/desktop/src/app/contrib/onboarding-kickoff-machine.tsnew file mode 100644index 00000000000..d8aca182e07--- /dev/null+++ b/apps/desktop/src/app/contrib/onboarding-kickoff-machine.ts@@ -0,0 +1,146 @@+import { GatewayReauthRequiredError, JsonRpcGatewayError } from '@hermes/shared'++import { isTimeoutError } from '@/lib/with-timeout'+import { $gatewaySwitching } from '@/store/gateway-switch'+import { $gatewayState } from '@/store/session'++/**+ * The welcome chat's start, as explicit states. While the kickoff is in a state it knows how to wait on+ * (the backend process is alive, the gateway is open or reconnecting, a call is in flight) it waits with no+ * wall-clock deadline: a cold first boot answers late, but it answers (51 s to listen on a Windows ARM64+ * first boot, then a busy backend behind the first calls). It fails only on what waiting cannot fix: an+ * RPC error response, the backend process exiting, or a result it does not expect.+ */+export type KickoffState = 'waiting-backend' | 'preparing' | 'opening' | 'started' | 'off' | 'failed'++/** json-rpc-channel arms a call's timer only for a positive timeout, so 0 waits for the answer. */+export const NO_DEADLINE = 0++/** A failure no amount of waiting fixes. */+export class KickoffFailure extends Error {}++type FailureKind = 'fatal' | 'starting' | 'transient'++function failureKind(error: unknown): FailureKind {+ if (+ error instanceof KickoffFailure ||+ error instanceof JsonRpcGatewayError ||+ error instanceof GatewayReauthRequiredError+ ) {+ return 'fatal'+ }++ // The renderer's own dial budget ran out while main still spawns the profile's backend. The spawn+ // goes on and answers with a connection or an error, so dialing again is waiting, not retrying.+ if (isTimeoutError(error)) {+ return 'starting'+ }++ // A socket that closed or reset under the call.+ return 'transient'+}++const describe = (error: unknown) => (error instanceof Error ? error.message : String(error))++function log(line: string): void {+ const text = `[setup] kickoff ${line}`+ console.info(text)+ // Only error-level console lines reach desktop.log; testers read the transitions there.+ window.hermesDesktop?.logLine?.(text)+}++export interface KickoffMachine {+ enter(next: KickoffState, detail?: string): void+ /** Runs `step` once the gateway is open. A dial that times out on a starting backend runs it again; a+ * dropped connection runs it again once. Anything else, or the backend exiting, rejects. */+ attempt<T>(state: KickoffState, step: () => Promise<T>): Promise<T>+ dispose(): void+}++export function createKickoffMachine(): KickoffMachine {+ let state: KickoffState | 'begin' = 'begin'+ let exitFailure: KickoffFailure | null = null+ const exitWaiters = new Set<(error: KickoffFailure) => void>()++ const enter = (next: KickoffState, detail?: string) => {+ log(`${state} -> ${next}${detail ? ` (${detail})` : ''}`)+ state = next+ }++ const offExit = window.hermesDesktop?.onBackendExit(({ code, signal }) => {+ // A gateway switch stops the old backend on purpose.+ if ($gatewaySwitching.get()) {+ return+ }++ exitFailure = new KickoffFailure(+ `The Hermes backend stopped before the welcome chat opened (code ${code ?? 'none'}, signal ${signal ?? 'none'}).`+ )++ for (const reject of exitWaiters) {+ reject(exitFailure)+ }+ })++ const gatewayOpen = (): Promise<void> => {+ if (exitFailure) {+ return Promise.reject(exitFailure)+ }++ if ($gatewayState.get() === 'open') {+ return Promise.resolve()+ }++ enter('waiting-backend', `gateway ${$gatewayState.get()}`)++ return new Promise((resolve, reject) => {+ const stopState = $gatewayState.listen(next => {+ if (next === 'open') {+ settle()+ resolve()+ }+ })++ const fail = (error: KickoffFailure) => {+ settle()+ reject(error)+ }++ function settle() {+ stopState()+ exitWaiters.delete(fail)+ }++ exitWaiters.add(fail)+ })+ }++ const attempt = async <T>(next: KickoffState, step: () => Promise<T>): Promise<T> => {+ let retried = false+ let detail: string | undefined++ for (;;) {+ await gatewayOpen()+ enter(next, detail)++ try {+ return await step()+ } catch (error) {+ const kind = failureKind(error)++ if (exitFailure) {+ throw exitFailure+ }++ if (kind === 'fatal' || (kind === 'transient' && retried)) {+ throw error+ }++ retried ||= kind === 'transient'+ detail = `${kind === 'starting' ? 'backend still starting' : 'retry'}: ${describe(error)}`+ }+ }+ }++ return { attempt, dispose: () => offExit?.(), enter }+}diff --git a/apps/desktop/src/app/contrib/onboarding-kickoff.ts b/apps/desktop/src/app/contrib/onboarding-kickoff.tsindex 03f5549b508..0096df6a4b1 100644--- a/apps/desktop/src/app/contrib/onboarding-kickoff.ts+++ b/apps/desktop/src/app/contrib/onboarding-kickoff.ts@@ -11,7 +11,6 @@ import { prefetchConnectorCatalog } from '@/store/connector-catalog'import { activeGatewayConnectionId, requestGatewayForProfile } from '@/store/gateway'import { notify } from '@/store/notifications'import { $setupProfileName, type GuideKickoffResult } from '@/store/onboarding-gate'-import { $introView } from '@/store/onboarding-intro'import { prefetchOnboardingPlugins } from '@/store/onboarding-plugins'import {$activeGatewayProfile,@@ -23,6 +22,7 @@ import {import { $activeSessionId, $selectedStoredSessionId } from '@/store/session'import { $sessionStates } from '@/store/session-states'+import { createKickoffMachine, KickoffFailure, NO_DEADLINE } from './onboarding-kickoff-machine'import type { AmbientGatewayRequest } from './session-rpc-dispatcher'function prefetchGuideCatalogs(storedId: null | string): void {@@ -128,44 +128,74 @@ export function useOnboardingKickoff({ requestGateway, resumeSession, runSlashCoconst previousConnectionId = activeGatewayConnectionId()const previousSetupSession = $setupSession.get()const previousThreadIds = $chatOnboardingThreadIds.get()+ const machine = createKickoffMachine()let swapped = falsetry {- const { name: setupProfile } = await requestGateway<OnboardingEnsureSetupProfileResult>(- 'onboarding.ensure_setup_profile',- {}- )+ // Every call here is idempotent, so a retry repeats the whole step. The calls carry no deadline: a cold+ // first boot answers them late, and the machine fails on the signals that mean it never will.+ const prepared = await machine.attempt('preparing', async () => {+ const { name: setupProfile } = await requestGateway<OnboardingEnsureSetupProfileResult>(+ 'onboarding.ensure_setup_profile',+ {},+ NO_DEADLINE+ )- $setupProfileName.set(setupProfile)+ $setupProfileName.set(setupProfile)++ // Foreground: the user is watching the starting screen, so a cold spawn of the setup profile's+ // backend takes the reserved slot and skips the background redial cooldown.+ const record = await requestGatewayForProfile<SetupStatus>(+ setupProfile,+ 'setup.status',+ {},+ NO_DEADLINE,+ undefined,+ { spawnPriority: 'foreground' }+ )- const record = await requestGatewayForProfile<SetupStatus>(setupProfile, 'setup.status', {})+ if (record.ready !== true || record.provider_configured !== true) {+ // A retry after the swap saw a ready provider the first time; the swap has to be undone.+ if (swapped) {+ throw new KickoffFailure('Inference stopped reporting ready while the welcome chat opened.')+ }- if (record.ready !== true || record.provider_configured !== true) {- return 'off'- }+ return null+ }- // The gate gave up waiting (its deadline): the app is already on its normal layout.- const stillStarting = () => {- if ($introView.get() !== 'starting') {- throw new Error('The welcome chat took too long to open.')+ if (!swapped) {+ takeGuideShape()+ rememberLaunchSource()+ swapped = true+ $newChatRoute.set(null)+ $newChatProfile.set(setupProfile)}++ await ensureGatewayProfile(setupProfile)++ // Finds the setup chat by title or creates it; `empty` is true only before its first turn.+ const setupChat = await requestGateway<OnboardingEnsureSetupSessionResult>(+ 'onboarding.ensure_setup_session',+ {},+ NO_DEADLINE+ )++ return { record, setupChat, setupProfile }+ })++ if (!prepared) {+ machine.enter('off', 'no inference ready')++ return 'off'}- stillStarting()- takeGuideShape()- rememberLaunchSource()- swapped = true- $newChatRoute.set(null)- $newChatProfile.set(setupProfile)- await ensureGatewayProfile(setupProfile)- stillStarting()+ const { record, setupChat, setupProfile } = prepared++ machine.enter('opening', `session ${setupChat.session_id}`)const guideRequest: AmbientGatewayRequest = (method, params, timeout) =>requestGatewayForProfile(setupProfile, method, params, timeout)- // Finds the setup chat by title or creates it; `empty` is true only before its first turn.- const setupChat = await requestGateway<OnboardingEnsureSetupSessionResult>('onboarding.ensure_setup_session', {})-const runtimeId = await adoptGuideSession(setupProfile,setupChat.session_id,@@ -174,8 +204,6 @@ export function useOnboardingKickoff({ requestGateway, resumeSession, runSlashCoguideRequest)- stillStarting()-// A relaunch reopens the same setup chat; one whose opening was cut off is sent the command again.const opening = setupChat.empty ? { blank: true, stalled: true } : setupChatOpening(runtimeId)@@ -189,8 +217,11 @@ export function useOnboardingKickoff({ requestGateway, resumeSession, runSlashCo)}+ machine.enter('started')+return 'started'} catch (error) {+ machine.enter('failed', error instanceof Error ? error.message : String(error))$newChatProfile.set(previousNewChatProfile)$newChatRoute.set(previousNewChatRoute)$setupSession.set(previousSetupSession)@@ -215,6 +246,8 @@ export function useOnboardingKickoff({ requestGateway, resumeSession, runSlashCo})return 'failed'+ } finally {+ machine.dispose()}}, [requestGateway, resumeSession, runSlashCommand])}diff --git a/apps/desktop/src/components/onboarding-chat/gate.tsx b/apps/desktop/src/components/onboarding-chat/gate.tsxindex 5660fd6b502..f614d91774c 100644--- a/apps/desktop/src/components/onboarding-chat/gate.tsx+++ b/apps/desktop/src/components/onboarding-chat/gate.tsx@@ -18,10 +18,6 @@ import { $introView } from '@/store/onboarding-intro'import { failIntro, startIntro } from './intro'-// `starting` is never left waiting on a hung kickoff: past this it counts as a failed start. The kickoff-// notices on its next step and undoes what it did.-const INTRO_START_DEADLINE_MS = 45_000-interface OnboardingChatGateProps {enabled: booleanonKickoff: () => Promise<GuideKickoffResult>@@ -74,32 +70,22 @@ export function OnboardingChatGate({ enabled, onKickoff, requestGateway }: Onboa}, [enabled, requestGateway])useEffect(() => {+ // No deadline here: the kickoff waits while the backend is known to be coming and settles itself on+ // the states it cannot wait out (onboarding-kickoff-machine.ts).if (enabled && gate.guideQueued) {const recover = (result: Exclude<GuideKickoffResult, 'started'>) => {failIntro()abandonGuide(result)}- let settled = false-- const settle = (result: GuideKickoffResult) => {- if (settled) {- return- }-- settled = true- window.clearTimeout(deadline)-- if (result !== 'started') {- recover(result)- }- }-- const deadline = window.setTimeout(() => settle('failed'), INTRO_START_DEADLINE_MS)-- void runGuideKickoff(onKickoff).then(settle, () => settle('failed'))-- return () => window.clearTimeout(deadline)+ void runGuideKickoff(onKickoff).then(+ result => {+ if (result !== 'started') {+ recover(result)+ }+ },+ () => recover('failed')+ )}}, [enabled, gate.guideQueued, onKickoff])