Skip to content

The agent that grows with you

feat(desktop): a window ends its onboarding run on onboarding.ended, and re-reads it on reconnect

alt-glitch27776279fc4a
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 901003ab81c..a9696535863 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
@@ -21,6 +21,7 @@ import { handleFreeTierEvent } from './free-tier'
import { handleInputRequestEvent } from './input-requests'
import { handleLifecycleEvent } from './lifecycle'
import { handleMessageStreamEvent } from './message-stream'
+import { handleOnboardingEvent } from './onboarding'
import { handleControlEvent } from './session-control'
import { handleSessionInfoEvent } from './session-info'
import { handleStatusEvent } from './status'
@@ -83,6 +84,7 @@ const PROVIDER_WAIT_SUPERSEDING_EVENT_TYPES = new Set([
const HANDLERS: GatewayEventHandler[] = [
handleLifecycleEvent,
handleFreeTierEvent,
+ handleOnboardingEvent,
handleSessionInfoEvent,
handleControlEvent,
handleMessageStreamEvent,
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/onboarding.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/onboarding.ts
new file mode 100644
index 00000000000..1f77d6b7bdc
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/onboarding.ts
@@ -0,0 +1,22 @@
+import type { GatewayEvent } from '@hermes/shared'
+
+import { noteOnboardingEnded } from '@/store/onboarding-run'
+
+import type { GatewayEventContext } from './types'
+
+/** onboarding.ended: a first-run run ended. Every source's event counts: the run is the install's, and
+ * the window showing it may be subscribed to another chat or profile. */
+export function handleOnboardingEvent({ event }: GatewayEventContext): boolean {
+ if (event.type !== 'onboarding.ended') {
+ return false
+ }
+
+ // SAFETY: the type check above; the backend checks the payload against OnboardingEndedPayload.
+ const ended = (event as GatewayEvent<'onboarding.ended'>).payload
+
+ if (ended) {
+ noteOnboardingEnded(ended)
+ }
+
+ return true
+}
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 03fbbf8e181..b3c4c93b51d 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
@@ -6,7 +6,6 @@ import { toolCallOwnerMessageId } from '@/lib/chat-messages'
import { connectorText, recordOf } from '@/lib/connector-tools'
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'
@@ -52,7 +51,7 @@ const SETTLED_CARDS = new Map([
['setup_beat', dropSetupBeatForCall]
])
-/** What a completed tool leaves behind outside its row: a preview target, or the end of an onboarding run. */
+/** What a completed tool leaves behind outside its row: a preview target, a settled card, or a committed layout. */
function noteToolOutcome(ctx: GatewayEventContext, sessionId: string, cwd: string, pendingProduction: boolean): void {
if (!ctx.deps.sessionInterrupted(sessionId)) {
recordToolPreview(ctx, sessionId, cwd, pendingProduction)
@@ -60,10 +59,6 @@ function noteToolOutcome(ctx: GatewayEventContext, sessionId: string, cwd: strin
SETTLED_CARDS.get(ctx.payload?.name ?? '')?.(sessionId, ctx.payload?.tool_id)
- if (ctx.payload?.name === 'setup_beat' && !ctx.event.replayed) {
- noteSetupBeatResult([sessionId, storedSessionIdForRuntimeId(sessionId)], setupBeatResult(ctx.payload.result))
- }
-
if (!ctx.event.replayed && appliedLayout(ctx.payload?.name, ctx.payload?.result)) {
leaveIntroOnLayout()
}
diff --git a/apps/desktop/src/components/onboarding/first-run/kickoff.test.ts b/apps/desktop/src/components/onboarding/first-run/kickoff.test.ts
index 07e946b7178..b8c58cf4b87 100644
--- a/apps/desktop/src/components/onboarding/first-run/kickoff.test.ts
+++ b/apps/desktop/src/components/onboarding/first-run/kickoff.test.ts
@@ -11,7 +11,7 @@ import { $introCopy } from './intro'
import { firstRunIntro } from './kickoff'
const size = vi.fn()
-const started: OnboardingStartResult = { resumed: false, session_id: 'rt-1', stored_session_id: 'st-1' }
+const started: OnboardingStartResult = { resumed: false, run_id: 'run-1', session_id: 'rt-1', stored_session_id: 'st-1' }
const ensureProfile = async (): Promise<void> => undefined
// SAFETY: the fake answers onboarding.start with its contract result; nothing else reads the answer.
diff --git a/apps/desktop/src/components/onboarding/skip-setup.tsx b/apps/desktop/src/components/onboarding/skip-setup.tsx
index 9cf1b06041f..c0657c63691 100644
--- a/apps/desktop/src/components/onboarding/skip-setup.tsx
+++ b/apps/desktop/src/components/onboarding/skip-setup.tsx
@@ -6,18 +6,15 @@ import { Tip } from '@/components/ui/tooltip'
import { useI18n } from '@/i18n'
import { notifyError } from '@/store/notifications'
import { skipOnboarding } from '@/store/onboarding-run'
-import { $onboardingSession } from '@/store/onboarding-session'
+import { $onboardingSession, isOnboardingChat } from '@/store/onboarding-session'
/** Skip setup, shown in the composer of the onboarding chat only. Once the backend has ended the run,
* like main's: the intro ends on the previous layout at normal size and the tutorial tips stop. */
export function OnboardingSkip({ sessionId }: { sessionId: null | string }) {
- const session = useStore($onboardingSession)
+ useStore($onboardingSession)
- if (!session || !sessionId || session.runtimeId !== sessionId) {
- return null
- }
-
- return <SkipButton runtimeId={session.runtimeId} />
+ // The chat's current runtime id: a resume after a reconnect gives it a new one.
+ return sessionId && isOnboardingChat(sessionId) ? <SkipButton runtimeId={sessionId} /> : null
}
// Split out so the gateway hook mounts only in the onboarding chat, not in every composer.
diff --git a/apps/desktop/src/store/onboarding-run.test.ts b/apps/desktop/src/store/onboarding-run.test.ts
index d6d2f1d55d3..ee7af0d0113 100644
--- a/apps/desktop/src/store/onboarding-run.test.ts
+++ b/apps/desktop/src/store/onboarding-run.test.ts
@@ -6,12 +6,15 @@ import {
$onboardingEnded,
$onboardingSettleFrom,
decideOnboarding,
- noteSetupBeatResult,
+ noteOnboardingEnded,
+ reconcileOnboarding,
skipOnboarding,
startOnboarding
} from './onboarding-run'
+import { isOnboardingChat } from './onboarding-session'
import { $activeGatewayProfile, $freshSessionRequest, $newChatProfile } from './profile'
import { $connection, $selectedStoredSessionId } from './session'
+import { $sessionTiles } from './session-states'
const ensureProfile = async (): Promise<void> => undefined
@@ -20,7 +23,7 @@ const resume = vi.fn(async (storedId: string) => $selectedStoredSessionId.set(st
function backend(state: { eligible: boolean; run: boolean }) {
const calls: string[] = []
- const started = { resumed: false, session_id: 'rt-1', stored_session_id: 'st-1' }
+ const started = { resumed: false, run_id: 'run-1', session_id: 'rt-1', stored_session_id: 'st-1' }
const request = async <T,>(method: string): Promise<T> => {
calls.push(method)
@@ -56,12 +59,12 @@ describe('onboarding run', () => {
expect(clear).not.toContain(true)
})
- it('ends once on the model finishing, and frees the first-run surfaces', async () => {
+ it('ends once when the backend reports the run done, and frees the first-run surfaces', async () => {
const { request } = backend({ eligible: true, run: true })
await startOnboarding(request, resume, { ensureProfile })
- noteSetupBeatResult(['rt-1', 'st-1'], { completed: true })
- noteSetupBeatResult(['rt-1', 'st-1'], { skipped_all: true })
+ noteOnboardingEnded({ outcome: 'done', run_id: 'run-1', stored_session_id: 'st-1' })
+ noteOnboardingEnded({ outcome: 'skipped', run_id: 'run-1', stored_session_id: 'st-1' })
expect($onboardingPhase.get()).toBe('done')
expect($onboardingEnded.get()).toBe('done')
@@ -81,16 +84,42 @@ describe('onboarding run', () => {
expect($onboardingSettleFrom.get()).not.toBeNull()
})
- it('ignores a setup_beat result from another chat, like the old run a rerun closed', async () => {
+ it('ignores the end of another run, like the old run a rerun closed', async () => {
const { request } = backend({ eligible: true, run: true })
await startOnboarding(request, resume, { ensureProfile })
- noteSetupBeatResult(['rt-old', 'st-old'], { skipped_all: true })
+ noteOnboardingEnded({ outcome: 'replaced', run_id: 'run-old', stored_session_id: 'st-old' })
expect($onboardingPhase.get()).toBe('shown')
expect($onboardingEnded.get()).toBeNull()
})
+ it('knows the onboarding chat under the new runtime id a reconnect gives it', async () => {
+ const { request } = backend({ eligible: true, run: true })
+ await startOnboarding(request, resume, { ensureProfile })
+ // SAFETY: storedSessionIdForRuntimeId reads only these two tile fields.
+ $sessionTiles.set([{ runtimeId: 'rt-after-restart', storedSessionId: 'st-1' } as never])
+
+ expect(isOnboardingChat('rt-after-restart')).toBe(true)
+ expect(isOnboardingChat('rt-other')).toBe(false)
+ $sessionTiles.set([])
+ })
+
+ it('ends a run the backend no longer has open when it re-reads the state', async () => {
+ const { request } = backend({ eligible: true, run: true })
+ await startOnboarding(request, resume, { ensureProfile })
+
+ // SAFETY: the fakes answer onboarding.state with its contract result shape.
+ const open = async <T,>(): Promise<T> => ({ eligible: true, run: true, run_id: 'run-1', session_id: 'st-1' }) as T
+ // SAFETY: as above.
+ const reread = async <T,>(): Promise<T> => ({ eligible: true, run: false, run_id: null, session_id: null }) as T
+
+ await reconcileOnboarding(open)
+ expect($onboardingPhase.get()).toBe('shown')
+ await reconcileOnboarding(reread)
+ expect($onboardingEnded.get()).toBe('skipped')
+ })
+
it('stays on the default profile when the start fails', async () => {
$activeGatewayProfile.set('work')
const switched = vi.fn(async (_profile: string) => undefined)
@@ -132,11 +161,11 @@ describe('onboarding run', () => {
// The backend withdraws the old card while the rerun's start is still answering.
const rerun = async <T,>(method: string): Promise<T> => {
if (method === 'onboarding.start') {
- noteSetupBeatResult(['rt-1', 'st-1'], { skipped_all: true })
+ noteOnboardingEnded({ outcome: 'replaced', run_id: 'run-1', stored_session_id: 'st-1' })
}
// SAFETY: the fake answers onboarding.start with its contract result shape.
- return { resumed: false, session_id: 'rt-2', stored_session_id: 'st-2' } as T
+ return { resumed: false, run_id: 'run-2', session_id: 'rt-2', stored_session_id: 'st-2' } as T
}
await startOnboarding(rerun, resume, { ensureProfile, rerun: true })
diff --git a/apps/desktop/src/store/onboarding-run.ts b/apps/desktop/src/store/onboarding-run.ts
index d3de48eb85b..801afd03d69 100644
--- a/apps/desktop/src/store/onboarding-run.ts
+++ b/apps/desktop/src/store/onboarding-run.ts
@@ -10,6 +10,7 @@
import type {
MachineFactsResult,
+ OnboardingEndedPayload,
OnboardingRunStateResult,
OnboardingStartResult
} from '@hermes/shared'
@@ -24,8 +25,8 @@ import { $onboardingPhase } from './onboarding-phase'
import { markOnboardingDecided, setOnboardingSurfaceActive } from './onboarding-presence'
import { $onboardingSession } from './onboarding-session'
import { ensureGatewayProfile, newSessionInProfile } from './profile'
-import { $connection, $selectedStoredSessionId } from './session'
-import type { SetupBeatToolResult } from './setup-beat'
+import { $connection, $gatewayState, $selectedStoredSessionId } from './session'
+import { dropSetupBeat } from './setup-beat'
export type OnboardingRequest = <T = unknown>(
method: string,
@@ -157,7 +158,8 @@ export async function startOnboarding(
// The chat is on screen before the run names it, so the presence never sees a gap.
await resume(started.stored_session_id, true)
- $onboardingSession.set({ runtimeId: started.session_id, storedId: started.stored_session_id })
+ $onboardingSession.set({ runId: started.run_id, runtimeId: started.session_id, storedId: started.stored_session_id })
+ watchRunEnd(request)
if (intro) {
intro.opened(started)
@@ -244,18 +246,49 @@ export async function skipOnboarding(request: OnboardingRequest, runtimeId: stri
leaveSkipped()
}
-/** A `setup_beat` result that ends the run: `completed` (the first-task card answered) or `skipped_all`. `ids`:
- * the event's runtime and stored session; a rerun closes the old chat's card, which must not end the new run. */
-export function noteSetupBeatResult(ids: readonly (null | string)[], result: SetupBeatToolResult): void {
+/** `onboarding.ended` from the backend, sent to every window: the run this window shows ended (the
+ * first-task card answered, Skip setup in any window, a rerun, its chat deleted). Another run's end,
+ * like the old run a rerun closed, does nothing here. */
+export function noteOnboardingEnded({ outcome, run_id }: OnboardingEndedPayload): void {
const session = $onboardingSession.get()
- if (!session || !ids.some(id => id === session.runtimeId || id === session.storedId)) {
+ if (!session || session.runId !== run_id) {
return
}
- if (result.completed) {
- endOnboarding('done')
- } else if (result.skipped_all) {
+ dropSetupBeat(session.runtimeId)
+ endOnboarding(outcome === 'done' ? 'done' : 'skipped')
+}
+
+/** An end this window missed (a reconnect, a backend restart): the run it shows is no longer the run
+ * in progress. */
+export async function reconcileOnboarding(request: OnboardingRequest): Promise<void> {
+ const session = $onboardingSession.get()
+
+ if (!session || $onboardingPhase.get() !== 'shown') {
+ return
+ }
+
+ const state = await request<OnboardingRunStateResult>('onboarding.state')
+
+ if ($onboardingSession.get() === session && state.run_id !== session.runId) {
endOnboarding('skipped')
}
}
+
+let stopWatching: (() => void) | null = null
+
+// Re-read the run on every reconnect and window focus while this window shows one.
+function watchRunEnd(request: OnboardingRequest): void {
+ stopWatching?.()
+
+ const check = () => void reconcileOnboarding(request).catch(error => console.warn('[onboarding] reconcile', error))
+ const offGateway = $gatewayState.listen(state => state === 'open' && check())
+
+ window.addEventListener('focus', check)
+
+ stopWatching = () => {
+ offGateway()
+ window.removeEventListener('focus', check)
+ }
+}
diff --git a/apps/desktop/src/store/onboarding-session.ts b/apps/desktop/src/store/onboarding-session.ts
index d06fdcac06b..78514ffd1a1 100644
--- a/apps/desktop/src/store/onboarding-session.ts
+++ b/apps/desktop/src/store/onboarding-session.ts
@@ -1,6 +1,10 @@
import { atom } from 'nanostores'
+import { storedSessionIdForRuntimeId } from './session-states'
+
export interface OnboardingSession {
+ /** Names the run in `onboarding.ended` and `onboarding.state`. */
+ runId: string
runtimeId: string
storedId: string
}
@@ -8,7 +12,12 @@ export interface OnboardingSession {
/** The onboarding chat while a run is in progress in this window. */
export const $onboardingSession = atom<null | OnboardingSession>(null)
-/** Whether `sessionId` is the runtime id of the onboarding chat in progress. */
+/** Whether runtime id `sessionId` shows the onboarding chat in progress. Matched by the stored id too:
+ * a resume after a reconnect or a backend restart gives the chat a new runtime id. */
export function isOnboardingChat(sessionId: null | string | undefined): boolean {
- return Boolean(sessionId) && $onboardingSession.get()?.runtimeId === sessionId
+ const session = $onboardingSession.get()
+
+ return Boolean(
+ sessionId && session && (session.runtimeId === sessionId || storedSessionIdForRuntimeId(sessionId) === session.storedId)
+ )
}
diff --git a/apps/desktop/src/store/parked-card-answers.test.ts b/apps/desktop/src/store/parked-card-answers.test.ts
index cb00bf7578e..5ce3f00795d 100644
--- a/apps/desktop/src/store/parked-card-answers.test.ts
+++ b/apps/desktop/src/store/parked-card-answers.test.ts
@@ -55,7 +55,7 @@ describe('parked card answers', () => {
expect(answerParkedCard('session-a', 'hello')).toBe(false)
expect($waiting.get()).toBe(false)
- $onboardingSession.set({ runtimeId: 'session-a', storedId: 'stored-a' })
+ $onboardingSession.set({ runId: 'run-1', runtimeId: 'session-a', storedId: 'stored-a' })
expect($waiting.get()).toBe(true)
expect(answerParkedCard('session-a', 'hello')).toBe(true)
expect(answerParkedCard('session-b', 'hello')).toBe(false)
diff --git a/apps/desktop/src/store/setup-beat.test.ts b/apps/desktop/src/store/setup-beat.test.ts
index 90a35ce855d..de6336a19e3 100644
--- a/apps/desktop/src/store/setup-beat.test.ts
+++ b/apps/desktop/src/store/setup-beat.test.ts
@@ -30,7 +30,7 @@ function parkNameCard(requestId: string, open = true) {
}
beforeEach(() => {
- $onboardingSession.set({ runtimeId: 'rt-1', storedId: 'stored-1' })
+ $onboardingSession.set({ runId: 'run-1', runtimeId: 'rt-1', storedId: 'stored-1' })
})
afterEach(() => {
diff --git a/apps/desktop/src/store/setup-beat.ts b/apps/desktop/src/store/setup-beat.ts
index 612e0a7d6cf..35c6eec782c 100644
--- a/apps/desktop/src/store/setup-beat.ts
+++ b/apps/desktop/src/store/setup-beat.ts
@@ -89,6 +89,15 @@ export function clearSetupBeat(requestId: string, sessionId: string): boolean {
return true
}
+/** The run ended: the session's card, if one still waits, is done. */
+export function dropSetupBeat(sessionId: string): void {
+ const request = $setupBeatRequests.get()[sessionId]
+
+ if (request) {
+ clearSetupBeat(request.requestId, sessionId)
+ }
+}
+
/** The setup_beat call `toolCallId` finished: its card is done here too, wherever it was answered. */
export function dropSetupBeatForCall(sessionId: string, toolCallId: string | undefined): void {
const request = $setupBeatRequests.get()[sessionId]