Skip to content

The agent that grows with you

feat(desktop): open first-run onboarding and park its setup_beat cards

alt-glitch2a1713c2d1b8
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index 0178e7ad70e..2dedf98f8b0 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -52,6 +52,7 @@ import { $interfaceMode, shownInMode } from '@/store/interface-mode'
import { $pinnedSessionIds, pinSession, restoreWorktree, unpinSession } from '@/store/layout'
import { notifyError } from '@/store/notifications'
import { markOnboardingDecided } from '@/store/onboarding-presence'
+import { decideOnboarding } from '@/store/onboarding-run'
import { $poolLimitsSettingsRequest } from '@/store/pool-limits'
import { $previewTarget } from '@/store/preview'
import {
@@ -90,7 +91,7 @@ import { reportPendingUpdateRun } from '@/store/shared-metrics'
import { $archivedSessions } from '@/store/sidebar-archive'
import { $titlebarAppActionsSide, titlebarAppActionsClusterCounts } from '@/store/titlebar-app-actions'
import { armWakeWord, stopClientCapture } from '@/store/wake-word'
-import { isAuxiliaryWindow, isBrowserWindow, isHudWindow } from '@/store/windows'
+import { isAuxiliaryWindow, isBrowserWindow, isHudWindow, isMainWindow } from '@/store/windows'
import { useSkinCommand } from '@/themes/use-skin-command'
import type { SessionInfo } from '@/types/hermes'
@@ -598,8 +599,15 @@ export function ContribWiring({ children }: { children: ReactNode }) {
}
}, [startSessionInWorkspace, startWorkSessionRequest])
- // Nothing decides whether first-run onboarding runs yet, so first-run surfaces are free at boot.
- useEffect(() => markOnboardingDecided(), [])
+ // The main window asks the backend whether first-run onboarding is due and opens it; every other
+ // window never runs it, so its first-run surfaces are free at once.
+ useEffect(() => {
+ if (!isMainWindow()) {
+ markOnboardingDecided()
+ } else if (gatewayState === 'open') {
+ void decideOnboarding(requestGateway, resumeSession)
+ }
+ }, [gatewayState, requestGateway, resumeSession])
// "New project" DRAG completion: the dialog created a project that was
// dropped onto a chat zone (tab-strip slot / pane edge / pane center). Open
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
index bbd6abcd7cb..3e7139fa18e 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
@@ -31,6 +31,7 @@ import {
} from '@/store/prompts'
import { requestRoute } from '@/store/recovery-requests'
import { forgetServerRequest } from '@/store/server-requests'
+import { clearSetupBeat } from '@/store/setup-beat'
import { clearThemePick } from '@/store/theme-pick'
import type { GatewayEventContext } from './types'
@@ -192,7 +193,7 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {
clearVaultSaveLoginRequest(sessionId, id)
} else if ($vaultUnlockRequests.get()[key]?.requestId === id) {
clearVaultUnlockRequest(sessionId, id)
- } else if (sessionId && clearThemePick(id, sessionId)) {
+ } else if (sessionId && (clearThemePick(id, sessionId) || clearSetupBeat(id, sessionId))) {
deps.updateSessionState(sessionId, state => ({ ...state, needsInput: false }))
}
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts
index 2ebc11c9794..879ed054393 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts
@@ -1,4 +1,4 @@
-import { JSON_RPC_INTERNAL_ERROR } from '@hermes/shared'
+import { JSON_RPC_INTERNAL_ERROR, type SetupBeat } from '@hermes/shared'
import {
hasLivePreviewSurface,
@@ -38,6 +38,7 @@ import {
previewScopeForRuntime,
storedSessionIdForRuntimeId
} from '@/store/session-states'
+import { parkSetupBeat } from '@/store/setup-beat'
import { parkThemePick } from '@/store/theme-pick'
import { requestScrollToBottom } from '@/store/thread-scroll'
import { $toursEnabled } from '@/store/tours'
@@ -725,6 +726,38 @@ const themePick: Handler = ctx => {
notifyInput(ctx, translateNow(`assistant.themePicker.${picker}`))
}
+const SETUP_BEATS: readonly SetupBeat[] = ['name', 'theme', 'layout', 'connectors', 'plugins', 'tour', 'build']
+
+const setupBeat: Handler = ctx => {
+ const { request, sessionId } = ctx
+ const beat = SETUP_BEATS.find(candidate => candidate === request.params.beat)
+
+ if (!sessionId || !beat) {
+ request.respond({})
+
+ return
+ }
+
+ if (declineIfSessionStopped(ctx)) {
+ return
+ }
+
+ const { card } = request.params
+ const question = str(request.params.question)
+
+ rememberServerRequest(request)
+ parkSetupBeat({
+ beat,
+ // SAFETY: a non-array object is the contract's `card: Record<string, unknown>`.
+ card: typeof card === 'object' && card !== null && !Array.isArray(card) ? (card as Record<string, unknown>) : {},
+ question,
+ requestId: request.id,
+ sessionId
+ })
+ markNeedsInput(ctx)
+ notifyInput(ctx, question)
+}
+
/** Method → handler. Every `ServerRequestMap` key the desktop answers. */
export const SERVER_REQUEST_HANDLERS: Record<string, Handler> = {
approval,
@@ -733,6 +766,7 @@ export const SERVER_REQUEST_HANDLERS: Record<string, Handler> = {
'preview.act': previewAct,
'preview.read': previewRead,
secret,
+ setup_beat: setupBeat,
sudo,
'terminal.read': terminalRead,
'theme.apply': themeApply,
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts
index 81a696d292b..a29566f64f2 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts
@@ -2,6 +2,7 @@ import { isPreviewableTarget, toolPreviewOutcome } from '@/components/assistant-
import { toolCallOwnerMessageId } from '@/lib/chat-messages'
import { invalidateSlashCompletions } from '@/lib/slash-completion-cache'
import { refreshBackgroundProcesses } from '@/store/composer-status'
+import { noteSetupBeatResult } from '@/store/onboarding-run'
import { flashPetActivity, setPetActivity } from '@/store/pet'
import { recordPreviewArtifact, reofferPreviewArtifact } from '@/store/preview-status'
import { $sessionStates, storedSessionIdForRuntimeId } from '@/store/session-states'
@@ -105,6 +106,10 @@ export function handleToolEvent(ctx: GatewayEventContext): boolean {
recordToolPreview(ctx, sessionId, state?.cwd ?? '', pendingProduction)
}
+ if (payload?.name === 'setup_beat' && !event.replayed) {
+ noteSetupBeatResult(payload.result)
+ }
+
if (isActiveEvent) {
setPetActivity({ toolRunning: false })
diff --git a/apps/desktop/src/store/onboarding-run.test.ts b/apps/desktop/src/store/onboarding-run.test.ts
new file mode 100644
index 00000000000..f243eff4fe7
--- /dev/null
+++ b/apps/desktop/src/store/onboarding-run.test.ts
@@ -0,0 +1,58 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('./profile', () => ({ ensureGatewayProfile: vi.fn(async () => undefined) }))
+
+import { $onboardingPhase } from './onboarding-phase'
+import { $onboardingDecided, $onboardingSurfaceClear } from './onboarding-presence'
+import { $onboardingEnded, decideOnboarding, noteSetupBeatResult, startOnboarding } from './onboarding-run'
+import { $connection } from './session'
+
+const STARTED = { resumed: false, session_id: 'rt-1', stored_session_id: 'st-1' }
+
+function backend(state: { eligible: boolean; run: boolean }) {
+ const calls: string[] = []
+
+ const request = async <T>(method: string): Promise<T> => {
+ calls.push(method)
+
+ // SAFETY: the fake answers each method with its contract's result shape.
+ return (method === 'onboarding.state' ? state : STARTED) as T
+ }
+
+ return { calls, request }
+}
+
+beforeEach(() => {
+ $connection.set({ mode: 'local' } as never)
+ $onboardingPhase.set('idle')
+ $onboardingEnded.set(null)
+})
+
+describe('onboarding run', () => {
+ it('opens the onboarding chat when due and never shows a clear moment before it', async () => {
+ const clear: boolean[] = []
+ const stop = $onboardingSurfaceClear.subscribe(value => clear.push(value))
+ const { calls, request } = backend({ eligible: true, run: true })
+ const resume = vi.fn(async () => undefined)
+
+ await decideOnboarding(request, resume)
+ stop()
+
+ expect(calls).toEqual(['onboarding.state', 'onboarding.start'])
+ expect(resume).toHaveBeenCalledWith('st-1', true)
+ expect($onboardingDecided.get()).toBe(true)
+ expect(clear).not.toContain(true)
+ })
+
+ it('ends once on the model finishing, and frees the first-run surfaces', async () => {
+ const { request } = backend({ eligible: true, run: true })
+
+ await startOnboarding(request, vi.fn(async () => undefined))
+ noteSetupBeatResult(JSON.stringify({ completed: true }))
+ noteSetupBeatResult({ skipped_all: true })
+
+ expect($onboardingPhase.get()).toBe('done')
+ expect($onboardingEnded.get()).toBe('done')
+ expect($onboardingSurfaceClear.get()).toBe(true)
+ })
+})
diff --git a/apps/desktop/src/store/onboarding-run.ts b/apps/desktop/src/store/onboarding-run.ts
new file mode 100644
index 00000000000..508777d4314
--- /dev/null
+++ b/apps/desktop/src/store/onboarding-run.ts
@@ -0,0 +1,165 @@
+/**
+ * First-run onboarding as this window runs it: one chat in the default profile, opened by the
+ * backend's `onboarding.start`, ended by the model (`setup_beat(beat="done")`) or by Skip setup.
+ *
+ * This module is the one writer of `$onboardingPhase` and of the `onboarding` presence surface, so
+ * the two never disagree: the surface is open exactly while the phase is `shown`. The backend owns
+ * whether onboarding is due (`onboarding.state`) and writes the install-level flag when a run ends.
+ */
+
+import type { MachineFactsResult, OnboardingRunStateResult, OnboardingStartResult } from '@hermes/shared'
+import { atom } from 'nanostores'
+
+import { getRuntimeI18nLocale } from '@/i18n/runtime'
+
+import { $onboardingPhase } from './onboarding-phase'
+import { markOnboardingDecided, setOnboardingSurfaceActive } from './onboarding-presence'
+import { ensureGatewayProfile } from './profile'
+import { $connection } from './session'
+
+export type OnboardingRequest = <T>(method: string, params?: Record<string, unknown>) => Promise<T>
+
+/** Opens a stored session on screen, replacing the route (`useSessionActions().resumeSession`). */
+export type OnboardingResume = (storedId: string, replaceRoute?: boolean) => Promise<void>
+
+export interface OnboardingSession {
+ runtimeId: string
+ storedId: string
+}
+
+/** The onboarding chat while a run is on screen in this window. */
+export const $onboardingSession = atom<null | OnboardingSession>(null)
+
+/** How the last run in this window ended; the end-of-onboarding surfaces wake on it. */
+export const $onboardingEnded = atom<'done' | 'skipped' | null>(null)
+
+// The backend runs onboarding in its root profile whichever profile the app was on.
+const ONBOARDING_PROFILE = 'default'
+
+$onboardingPhase.subscribe(phase => setOnboardingSurfaceActive('onboarding', phase === 'shown'))
+
+/** Same machine as this app (`local`), or a backend somewhere else (`remote`). A local connection is
+ * this machine; any other compares the backend's OS and architecture with Electron's. */
+async function factsSource(request: OnboardingRequest): Promise<'local' | 'remote'> {
+ if ($connection.get()?.mode === 'local') {
+ return 'local'
+ }
+
+ const [profile, facts] = await Promise.all([
+ window.hermesDesktop?.getMachineProfile?.().catch(() => null),
+ request<MachineFactsResult>('machine.facts').catch(() => null)
+ ])
+
+ const arch = (value: null | string | undefined) => (value === 'x64' || value === 'amd64' ? 'x86_64' : value)
+
+ const same =
+ Boolean(profile && facts) &&
+ profile?.platform === facts?.machine.os_family &&
+ arch(profile?.arch) === arch(facts?.machine.native_arch)
+
+ return same ? 'local' : 'remote'
+}
+
+/** Open the onboarding chat (a new one for a rerun, else the run in progress or a new one). */
+export async function startOnboarding(
+ request: OnboardingRequest,
+ resume: OnboardingResume,
+ { rerun = false }: { rerun?: boolean } = {}
+): Promise<boolean> {
+ $onboardingPhase.set('shown')
+ $onboardingEnded.set(null)
+
+ try {
+ await ensureGatewayProfile(ONBOARDING_PROFILE)
+
+ const started = await request<OnboardingStartResult>('onboarding.start', {
+ facts_source: await factsSource(request),
+ locale: getRuntimeI18nLocale(),
+ rerun
+ })
+
+ $onboardingSession.set({ runtimeId: started.session_id, storedId: started.stored_session_id })
+ await resume(started.stored_session_id, true)
+
+ return true
+ } catch (error) {
+ console.warn('[onboarding] could not start', error)
+ $onboardingSession.set(null)
+ $onboardingPhase.set('failed')
+
+ return false
+ }
+}
+
+let decision: null | Promise<void> = null
+
+/**
+ * The main window's boot check, once per launch: open onboarding when the backend says it is due on
+ * this install and the free tier can drive it. First-run surfaces wait until this has answered; the
+ * presence surface is set before the answer is published, so they never see a clear moment in between.
+ */
+export function decideOnboarding(request: OnboardingRequest, resume: OnboardingResume): Promise<void> {
+ decision ??= readAndStart(request, resume)
+
+ return decision
+}
+
+
+async function readAndStart(request: OnboardingRequest, resume: OnboardingResume): Promise<void> {
+ try {
+ const state = await request<OnboardingRunStateResult>('onboarding.state')
+
+ if (state.run && state.eligible) {
+ await startOnboarding(request, resume)
+ }
+ } catch (error) {
+ console.warn('[onboarding] state could not be read', error)
+ } finally {
+ markOnboardingDecided()
+ }
+}
+
+/** The run ended: the model finished it or the user skipped. Later calls for the same run do nothing. */
+export function endOnboarding(outcome: 'done' | 'skipped'): void {
+ if ($onboardingPhase.get() !== 'shown') {
+ return
+ }
+
+ $onboardingPhase.set(outcome)
+ $onboardingEnded.set(outcome)
+ $onboardingSession.set(null)
+}
+
+/** Skip setup: the backend ends the run and closes the card that waits. */
+export async function skipOnboarding(request: OnboardingRequest, runtimeId: string): Promise<void> {
+ try {
+ await request('onboarding.skip', { session_id: runtimeId })
+ } catch (error) {
+ console.warn('[onboarding] skip failed', error)
+ }
+
+ endOnboarding('skipped')
+}
+
+/** A `setup_beat` result that ends the run: `completed` (the model said done) or `skipped_all`. */
+export function noteSetupBeatResult(result: unknown): void {
+ const value = typeof result === 'string' ? parseJson(result) : result
+
+ if (typeof value !== 'object' || value === null) {
+ return
+ }
+
+ if ('completed' in value && value.completed === true) {
+ endOnboarding('done')
+ } else if ('skipped_all' in value && value.skipped_all === true) {
+ endOnboarding('skipped')
+ }
+}
+
+function parseJson(text: string): unknown {
+ try {
+ return JSON.parse(text)
+ } catch {
+ return null
+ }
+}
diff --git a/apps/desktop/src/store/setup-beat.ts b/apps/desktop/src/store/setup-beat.ts
new file mode 100644
index 00000000000..9a5f09358fa
--- /dev/null
+++ b/apps/desktop/src/store/setup-beat.ts
@@ -0,0 +1,66 @@
+/**
+ * Open `setup_beat` requests: the onboarding chat's card for one beat, one per session.
+ *
+ * The setup_beat tool row reads this to draw the beat's card. A pick answers the request with
+ * `{answer}`; composer text answers it with `{said}` (the backend treats words on the name card as
+ * the name). The backend's `request.cancel` (timeout, Stop, Skip setup) clears the entry by request
+ * id, so a late cancel never erases a newer card the same session raised.
+ */
+
+import type { SetupBeat } from '@hermes/shared'
+import { atom } from 'nanostores'
+
+import { registerParkedCardAnswer } from './parked-card-answers'
+import { respondToServerRequest } from './server-requests'
+
+export interface SetupBeatRequest {
+ beat: SetupBeat
+ /** The beat's data from `agent/onboarding_flow.py::BEATS` (options, suggested slugs, plugin names). */
+ card: Record<string, unknown>
+ question: string
+ requestId: string
+ sessionId: string
+}
+
+export const $setupBeatRequests = atom<Record<string, SetupBeatRequest>>({})
+
+export function parkSetupBeat(request: SetupBeatRequest): void {
+ $setupBeatRequests.set({ ...$setupBeatRequests.get(), [request.sessionId]: request })
+}
+
+/** Drop the card for `requestId`; a no-op when the session's card is a newer one. */
+export function clearSetupBeat(requestId: string, sessionId: string): boolean {
+ const { [sessionId]: current, ...others } = $setupBeatRequests.get()
+
+ if (current?.requestId !== requestId) {
+ return false
+ }
+
+ $setupBeatRequests.set(others)
+
+ return true
+}
+
+function respond(sessionId: string, result: { answer: Record<string, unknown> } | { said: string }): boolean {
+ const request = $setupBeatRequests.get()[sessionId]
+
+ if (!request) {
+ return false
+ }
+
+ clearSetupBeat(request.requestId, sessionId)
+
+ return respondToServerRequest(request.requestId, result)
+}
+
+/** Answer the session's card with the beat's picks. False when no card waits. */
+export function answerSetupBeat(sessionId: string, answer: Record<string, unknown>): boolean {
+ return respond(sessionId, { answer })
+}
+
+/** Composer text typed while a card waits answers it as the user's words. */
+export function sayToSetupBeat(sessionId: string, text: string): boolean {
+ return Boolean(text.trim()) && respond(sessionId, { said: text.trim() })
+}
+
+registerParkedCardAnswer('setup_beat', sayToSetupBeat)