diff --git a/apps/desktop/electron/chat-onboarding-window.ts b/apps/desktop/electron/chat-onboarding-window.ts new file mode 100644 index 0000000000..f9d33774cb --- /dev/null +++ b/apps/desktop/electron/chat-onboarding-window.ts @@ -0,0 +1,53 @@ +import { type BrowserWindow, ipcMain, screen } from 'electron' + +import { type GrowRequest, growWindowBounds } from './window-growth' + +interface ChatOnboardingWindowOptions { + enabled: boolean + mainWindow: () => BrowserWindow | null +} + +export function registerChatOnboardingWindow({ enabled, mainWindow }: ChatOnboardingWindowOptions): void { + ipcMain.on('hermes:chat-onboarding:grow', (event, request: GrowRequest) => { + const win = mainWindow() + + if (!enabled || !win || win.isDestroyed() || event.sender !== win.webContents) { + return + } + + // Renderer CSS pixels become native DIP here, including the user's zoom. + const bounds = win.getBounds() + + win.setBounds( + growWindowBounds(request, { + bounds, + frameWidth: bounds.width - win.getContentBounds().width, + workArea: screen.getDisplayMatching(bounds).workArea, + zoom: event.sender.getZoomFactor() || 1 + }), + true + ) + }) + + ipcMain.on('hermes:chat-onboarding:solo-boot', event => { + const win = mainWindow() + + if (!enabled || !win || win.isDestroyed() || event.sender !== win.webContents) { + return + } + + const area = screen.getDisplayMatching(win.getBounds()).workArea + const width = Math.min(600, area.width) + const height = Math.min(640, area.height) + + win.setBounds( + { + height, + width, + x: Math.round(area.x + (area.width - width) / 2), + y: Math.round(area.y + (area.height - height) / 2) + }, + true + ) + }) +} diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts index 2a5fe0ffef..241f420de5 100644 --- a/apps/desktop/electron/main.ts +++ b/apps/desktop/electron/main.ts @@ -97,6 +97,7 @@ import { } from './browser-windows' import { detectBundleSkew } from './bundle-skew' import { detectBundleSwap } from './bundle-swap' +import { registerChatOnboardingWindow } from './chat-onboarding-window' import { applyConnectionChange, sshQuitShouldBlock, teardownSshState } from './connection-apply' import { apiRequestRegistryConnectionId, @@ -425,7 +426,6 @@ import { registrySshScopeForWindowRoute, WindowConnectionRouteRegistry } from './window-connection-route' -import { growWindowBounds } from './window-growth' import { createWindowOpenHandler } from './window-open-policy' import { installWindowRendererLifecycle } from './window-renderer-lifecycle' import { createWindowRevealController } from './window-reveal' @@ -13858,43 +13858,9 @@ const introRevealController = createIntroRevealWindowController({ wireWindow: window => wireCommonWindowHandlers(window, zoomWiringForWindowKind('petOverlay')) }) -ipcMain.on('hermes:chat-onboarding:grow', (event, request) => { - if (!GUEST_ONBOARDING || !mainWindow || mainWindow.isDestroyed() || event.sender !== mainWindow.webContents) { - return - } - - // Renderer CSS pixels become native DIP here, including the user's zoom. - const bounds = mainWindow.getBounds() - - mainWindow.setBounds( - growWindowBounds(request, { - bounds, - frameWidth: bounds.width - mainWindow.getContentBounds().width, - workArea: screen.getDisplayMatching(bounds).workArea, - zoom: event.sender.getZoomFactor() || 1 - }), - true - ) -}) - -ipcMain.on('hermes:chat-onboarding:solo-boot', event => { - if (!GUEST_ONBOARDING || !mainWindow || mainWindow.isDestroyed() || event.sender !== mainWindow.webContents) { - return - } - - const area = screen.getDisplayMatching(mainWindow.getBounds()).workArea - const width = Math.min(600, area.width) - const height = Math.min(640, area.height) - - mainWindow.setBounds( - { - height, - width, - x: Math.round(area.x + (area.width - width) / 2), - y: Math.round(area.y + (area.height - height) / 2) - }, - true - ) +registerChatOnboardingWindow({ + enabled: GUEST_ONBOARDING, + mainWindow: () => mainWindow }) // The pet overlay: a single transparent, frameless, always-on-top window that diff --git a/apps/desktop/src/app/contrib/handoff-leg.ts b/apps/desktop/src/app/contrib/handoff-leg.ts index e00a179b0d..278bf14167 100644 --- a/apps/desktop/src/app/contrib/handoff-leg.ts +++ b/apps/desktop/src/app/contrib/handoff-leg.ts @@ -1,6 +1,5 @@ -/** Stored-id recovery and per-session brief painting adapted from alt-glitch's - * 487823507711c2d26da8fd1684be78f12966d14d. Failed/uncertain submits retain the - * original session; they must never close it or start a second build. */ +/** Failed/uncertain submits retain the original session; + * they must never close it or start a second build. */ import { JsonRpcGatewayError } from '@hermes/shared' import type { ClientSessionState } from '@/app/types' diff --git a/apps/desktop/src/app/contrib/handoff-receipt.ts b/apps/desktop/src/app/contrib/handoff-receipt.ts index 4700463ffa..3ef068f020 100644 --- a/apps/desktop/src/app/contrib/handoff-receipt.ts +++ b/apps/desktop/src/app/contrib/handoff-receipt.ts @@ -1,27 +1,11 @@ -import { atom } from 'nanostores' - -import { $setupHandoff } from '@/components/onboarding-chat/setup-profile' import { readKey, writeJson } from '@/lib/storage' import type { HandoffReceipt } from './handoff-leg' -export const $handoffError = atom(null) // A failed disk write still remembers the original identity for this window. // Nothing is submitted until the next save verifies durable persistence. const unsavedReceipts = new Map() -/** Only a deliberate retry lifts an error; re-rendering a directive does not. */ -export function retrySetupHandoff(): void { - const state = $setupHandoff.get() - - if (state?.phase !== 'error') { - return - } - - $handoffError.set(null) - $setupHandoff.set({ ...state, phase: 'pending' }) -} - /** A navigation/submit receipt, never a copy of either profile's memory. */ export function handoffReceiptKey(connection: null | string, guideStoredId: string): string { return `hermes.onboarding.handoff.v1.connection.${encodeURIComponent(connection ?? 'ambient')}.profile.default.guide.${encodeURIComponent(guideStoredId)}` diff --git a/apps/desktop/src/app/contrib/onboarding-handoff.ts b/apps/desktop/src/app/contrib/onboarding-handoff.ts index 0aa1ad186e..7a1a2b1454 100644 --- a/apps/desktop/src/app/contrib/onboarding-handoff.ts +++ b/apps/desktop/src/app/contrib/onboarding-handoff.ts @@ -1,28 +1,20 @@ -/** Welcome-chat creation, durable first-build handoff, and progress check-ins. */ +/** Durable first-build handoff and progress check-ins. */ import { useStore } from '@nanostores/react' -import { useCallback, useEffect } from 'react' +import { useEffect } from 'react' import { PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } from '@/api/client' import type { useSessionActions } from '@/app/session/hooks/use-session-actions' -import type { SessionCreateOverrides } from '@/app/session/hooks/use-session-actions/create-overrides' -import type { ClientSessionState } from '@/app/types' -import { - $chatOnboardingThreadIds, - endChatOnboardingSolo, - pickOnboardingGreeting, - startChatOnboardingSolo -} from '@/components/onboarding-chat/assembly' import { $setupCheckIn, watchFirstBuild } from '@/components/onboarding-chat/first-build' import { + $handoffError, $setupHandoff, $setupSession, buildFirstTaskSeedMessages, buildHandoffCompleteNote, - ensureSetupProfile, firstTaskTitle, - markSetupHandoffDone, - SETUP_CHAT_TITLE, + guideSourceConnectionId, + retrySetupHandoff, SETUP_PROFILE } from '@/components/onboarding-chat/setup-profile' import { declinedLookAround, showProfileSignpost } from '@/components/onboarding-chat/signpost' @@ -30,25 +22,16 @@ import { findGroupOfPane } from '@/components/pane-shell/tree/model' import { $layoutTree, activateTreePane } from '@/components/pane-shell/tree/store' import { toChatMessages } from '@/lib/chat-messages' import { isOnboardingEnabled } from '@/lib/onboarding-enabled' -import { activeGatewayConnectionId, requestGatewayForAgent, requestGatewayForProfile } from '@/store/gateway' -import { loadMachineProfile } from '@/store/machine' +import { requestGatewayForAgent } from '@/store/gateway' import { dismissNotification, notify } from '@/store/notifications' import { $onboardingAnswers } from '@/store/onboarding-answers' -import { beginOnboardingHandoff, completeOnboardingFlow, skipGuide } from '@/store/onboarding-gate' -import { buildChatOnboardingSeedMessages } from '@/store/onboarding-script' -import { - $activeGatewayProfile, - $newChatProfile, - $newChatRoute, - ensureGatewayAgent, - ensureGatewayProfile -} from '@/store/profile' +import { beginOnboardingHandoff, completeOnboardingFlow } from '@/store/onboarding-gate' +import { $activeGatewayProfile, $newChatProfile, $newChatRoute, ensureGatewayAgent } from '@/store/profile' import { $activeSessionId, $messages, $selectedStoredSessionId, forgetSessionOwnerHintsForSession, - getSessionOwnerHint, setActiveSessionId, setAwaitingResponse, setBusy, @@ -57,210 +40,28 @@ import { import { patchSessionTile } from '@/store/session-states' import { BUILD_PROFILE, type HandoffDeps, type HandoffReceipt, paintHandoffBrief, startHandoff } from './handoff-leg' -import { - $handoffError, - handoffReceiptKey, - readHandoffReceipt, - retrySetupHandoff, - saveHandoffReceipt -} from './handoff-receipt' +import { handoffReceiptKey, readHandoffReceipt, saveHandoffReceipt } from './handoff-receipt' import type { AmbientGatewayRequest } from './session-rpc-dispatcher' -type SeedMessage = ReturnType[number] - -interface SetupStatus { - ready?: boolean - provider_configured?: boolean - free_tier?: boolean -} - -/** The welcome chat's owning source: its recorded owner hint, else the active - * gateway's registry id, else null. Null is the ambient route for the profile - * (a local-only install creates the setup profile as a registry secondary - * with no connection id and records no hint; a legacy primary has no registry - * id either), the same socket the welcome chat itself runs on. It is never a - * missing owner, and never 'local': an explicit local id would retarget a - * legacy remote primary onto this machine. */ -function guideSourceConnectionId(guideStoredId: null | string | undefined): null | string { - return (guideStoredId && getSessionOwnerHint(guideStoredId)?.connectionId) || activeGatewayConnectionId() || null -} - -export interface OnboardingHandoffOptions { - activeSessionIdRef: { current: null | string } - ensureSessionState: (sessionId: string, storedSessionId?: null | string) => ClientSessionState - updateSessionState: ( - sessionId: string, - updater: (state: ClientSessionState) => ClientSessionState, - storedSessionId?: null | string - ) => ClientSessionState - createBackendSessionForSend: ( - preview?: null | string, - seedMessages?: SeedMessage[], - overrides?: SessionCreateOverrides - ) => Promise +export interface OnboardingHandoffOptions extends Pick< + Parameters[0], + 'activeSessionIdRef' | 'ensureSessionState' | 'updateSessionState' +> { + createBackendSessionForSend: ReturnType['createBackendSessionForSend'] requestGateway: AmbientGatewayRequest - resumeSession: ReturnType['resumeSession'] - /** Runs `create` with the session-create leg pinned to `profile` instead of - * the selected chat's owner. The caller owns the mechanism (its own - * `requestGateway` is what reads the pin); the hook only needs to say which - * backend the new session belongs on. */ + /** Pin creation to the target profile while the guide remains selected; + * the caller's own requestGateway is what reads the pin. */ runCreatePinnedTo: (profile: string, create: () => Promise) => Promise } -interface GuideSession { - id: string - resolved_id?: string -} - -async function adoptGuideSession( - canonical: GuideSession, - freeTier: SetupStatus['free_tier'], - resumeSession: OnboardingHandoffOptions['resumeSession'], - guideRequest: AmbientGatewayRequest -): Promise { - await resumeSession(canonical.resolved_id ?? canonical.id, true) - const adoptedRuntimeId = $activeSessionId.get() - $chatOnboardingThreadIds.set(adoptedRuntimeId ? [canonical.id, adoptedRuntimeId] : [canonical.id]) - $setupSession.set({ - connectionId: guideSourceConnectionId(canonical.id), - profile: SETUP_PROFILE, - runtimeId: adoptedRuntimeId ?? canonical.id, - storedId: canonical.id - }) - - if (freeTier) { - await guideRequest('config.set', { - session_id: adoptedRuntimeId ?? canonical.id, - key: 'reasoning', - value: 'minimal' - }) - } -} - -/** Returns the first-chat kickoff; wires the handoff and check-in effects. */ export function useOnboardingHandoff({ activeSessionIdRef, ensureSessionState, updateSessionState, createBackendSessionForSend, requestGateway, - resumeSession, runCreatePinnedTo }: OnboardingHandoffOptions) { - const kickoffFirstChat = useCallback(async (): Promise => { - if (!isOnboardingEnabled()) { - return false - } - - const previousNewChatProfile = $newChatProfile.get() - const previousNewChatRoute = $newChatRoute.get() - const previousProfile = $activeGatewayProfile.get() - const previousConnectionId = activeGatewayConnectionId() - const previousSetupSession = $setupSession.get() - const previousThreadIds = $chatOnboardingThreadIds.get() - let swapped = false - - try { - await ensureSetupProfile(requestGateway) - - // Probe the guide's own socket before switching profiles so a refusal - // leaves classic onboarding on the user's current backend. - const record = await requestGatewayForProfile(SETUP_PROFILE, 'setup.status', {}) - - if (record.ready !== true || record.provider_configured !== true) { - return false - } - - swapped = true - $newChatRoute.set(null) - $newChatProfile.set(SETUP_PROFILE) - await ensureGatewayProfile(SETUP_PROFILE) - - startChatOnboardingSolo() - window.hermesDesktop?.chatOnboarding?.soloBoot?.() - await loadMachineProfile() - - const seedMessages = buildChatOnboardingSeedMessages( - pickOnboardingGreeting(), - record.provider_configured === true && record.free_tier !== true - ) - - const guideRequest: OnboardingHandoffOptions['requestGateway'] = (method, params, timeout) => - requestGatewayForProfile(SETUP_PROFILE, method, params, timeout) - - // The exact title is the durable registry: a relaunch adopts the guide - // before creating, so UNIQUE(title) cannot strand an untitled duplicate. - const registryHit = await guideRequest<{ sessions?: GuideSession[] }>('session.list', { - include_hidden: true, - title: SETUP_CHAT_TITLE - }) - - const canonical = registryHit?.sessions?.[0] - - if (canonical?.id) { - await adoptGuideSession(canonical, record.free_tier, resumeSession, guideRequest) - - // runGuideKickoff records the guided phase only after adoption. - return true - } - - const createOverrides: SessionCreateOverrides = { title: SETUP_CHAT_TITLE } - - if (record.free_tier) { - createOverrides.reasoningEffort = 'minimal' - } - - const runtimeId = await runCreatePinnedTo(SETUP_PROFILE, () => - createBackendSessionForSend(null, seedMessages, createOverrides) - ) - - if (!runtimeId) { - throw new Error('The welcome chat could not be created. Please try again.') - } - - const storedId = $selectedStoredSessionId.get() - $chatOnboardingThreadIds.set(storedId ? [storedId, runtimeId] : [runtimeId]) - $setupSession.set({ - connectionId: guideSourceConnectionId(storedId), - profile: SETUP_PROFILE, - runtimeId, - storedId - }) - - // Manual title authority prevents the hidden runbook becoming the title. - await guideRequest('session.title', { session_id: runtimeId, title: SETUP_CHAT_TITLE }).catch(() => undefined) - - // session.create persisted both seed rows before the phase can advance. - return true - } catch (error) { - $newChatProfile.set(previousNewChatProfile) - $newChatRoute.set(previousNewChatRoute) - $setupSession.set(previousSetupSession) - $chatOnboardingThreadIds.set(previousThreadIds) - endChatOnboardingSolo() - skipGuide() - - if (swapped) { - await ( - previousConnectionId - ? ensureGatewayAgent(previousConnectionId, previousProfile) - : ensureGatewayProfile(previousProfile) - ).catch(restoreError => { - notify({ kind: 'error', title: 'Could not restore your profile', message: String(restoreError) }) - }) - } - - console.error('[setup] welcome chat could not start', error) - notify({ - kind: 'error', - title: 'Welcome chat needs attention', - message: error instanceof Error ? error.message : 'The welcome chat could not start.' - }) - - return false - } - }, [createBackendSessionForSend, requestGateway, resumeSession, runCreatePinnedTo]) - // The receipt survives failure and relaunch; only a confirmed go signal // completes onboarding. Never fall back to building in the guide chat. const setupHandoff = useStore($setupHandoff) @@ -334,7 +135,6 @@ export function useOnboardingHandoff({ const previousNewChatProfile = $newChatProfile.get() const previousNewChatRoute = $newChatRoute.get() let receipt: HandoffReceipt | null = null - let receiptKey: string | null = null const request: HandoffDeps['request'] = (owner, method, params) => requestGatewayForAgent(owner.connectionId, owner.profile, method, params, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS) @@ -345,7 +145,8 @@ export function useOnboardingHandoff({ } $setupSession.set(setupSession) - receiptKey = handoffReceiptKey(connectionId, setupSession.storedId) + // Resume only has the guide's stored id, so its source must also key the saved receipt. + const receiptKey = handoffReceiptKey(guideSourceConnectionId(setupSession.storedId), setupSession.storedId) receipt = readHandoffReceipt(receiptKey) const owner: HandoffReceipt['owner'] = receipt?.owner ?? { connectionId, profile: BUILD_PROFILE } // Save facts before session.create freezes the new agent's memory. @@ -355,7 +156,7 @@ export function useOnboardingHandoff({ read: () => receipt, save: value => { receipt = value - saveHandoffReceipt(receiptKey!, value) + saveHandoffReceipt(receiptKey, value) }, personalize: async () => { const result = await request<{ saved?: boolean; profile?: string; target?: string }>( @@ -371,8 +172,7 @@ export function useOnboardingHandoff({ create: async () => { await ensureGatewayAgent(owner.connectionId, owner.profile) $newChatProfile.set(BUILD_PROFILE) - // An ambient owner pins no route on the new chat either; the - // profile is the whole address. + // A null connection uses the profile's ambient route. $newChatRoute.set( owner.connectionId ? { connectionId: owner.connectionId, profile: owner.profile } : null ) @@ -391,8 +191,7 @@ export function useOnboardingHandoff({ throw new Error('Could not open the first-build session.') } - // Selection is usable only while it still names THIS create, not - // whichever thread the user clicked while the request was away. + // Ignore selection if the user navigated away during creation. const storedId = ensureSessionState(runtimeId).storedSessionId ?? ($activeSessionId.get() === runtimeId ? $selectedStoredSessionId.get() : null) @@ -407,17 +206,13 @@ export function useOnboardingHandoff({ }, request, bind: (value, running, snapshot) => { - // An ambient owner (null connection id) has no route to pin: the - // build session is reached the way any session on that profile - // is, through the profile resolver. if (value.owner.connectionId) { const ownerRoute = { connectionId: value.owner.connectionId, profile: value.owner.profile } setSessionOwnerHint(value.storedId, ownerRoute) patchSessionTile(value.storedId, { runtimeId: value.runtimeId, ownerRoute }) } else { - // Explicit on both records: the tile patch merges, so an - // omitted route would keep whatever a previous bind left there. + // Clear both records: an omitted route survives the tile merge. forgetSessionOwnerHintsForSession(value.storedId) patchSessionTile(value.storedId, { runtimeId: value.runtimeId, ownerRoute: undefined }) } @@ -437,8 +232,7 @@ export function useOnboardingHandoff({ value.storedId ) - // Rebind a reclaimed runtime only if the user still has this - // stored chat selected. Background recovery must not steal focus. + // Background recovery must not steal focus. if ($selectedStoredSessionId.get() === value.storedId) { activeSessionIdRef.current = value.runtimeId setActiveSessionId(value.runtimeId) @@ -450,13 +244,12 @@ export function useOnboardingHandoff({ setupHandoff ) - // Naming is not identity and must not gate submission. Create's title - // is pending metadata on older backends, so explicitly title afterward. + // Create's title is pending metadata on older backends. + // Title after acceptance so naming cannot gate submission. const chatTitle = firstTaskTitle(receipt.task) await request(receipt.owner, 'session.title', { session_id: receipt.runtimeId, title: chatTitle }).catch( error => console.warn('[handoff] title could not be saved', error) ) - markSetupHandoffDone() completeOnboardingFlow() $handoffError.set(null) dismissNotification('onboarding-handoff') @@ -537,9 +330,6 @@ export function useOnboardingHandoff({ updateSessionState ]) - // The during-task check-in: first-build.ts decides WHEN (see its header), - // this delivers it — a hidden note into the build's own session, which the - // agent answers as a short status plus one ask. const checkIn = useStore($setupCheckIn) useEffect(() => { @@ -555,6 +345,4 @@ export function useOnboardingHandoff({ PROMPT_SUBMIT_REQUEST_TIMEOUT_MS ).catch(() => undefined) }, [checkIn, requestGateway]) - - return kickoffFirstChat } diff --git a/apps/desktop/src/app/contrib/onboarding-kickoff.ts b/apps/desktop/src/app/contrib/onboarding-kickoff.ts new file mode 100644 index 0000000000..4406e99149 --- /dev/null +++ b/apps/desktop/src/app/contrib/onboarding-kickoff.ts @@ -0,0 +1,198 @@ +import { useCallback } from 'react' + +import type { useSessionActions } from '@/app/session/hooks/use-session-actions' +import type { SessionCreateOverrides } from '@/app/session/hooks/use-session-actions/create-overrides' +import { + $chatOnboardingThreadIds, + endChatOnboardingSolo, + pickOnboardingGreeting, + startChatOnboardingSolo +} from '@/components/onboarding-chat/assembly' +import { + $setupSession, + ensureSetupProfile, + guideSourceConnectionId, + SETUP_CHAT_TITLE, + SETUP_PROFILE +} from '@/components/onboarding-chat/setup-profile' +import { isOnboardingEnabled } from '@/lib/onboarding-enabled' +import { activeGatewayConnectionId, requestGatewayForProfile } from '@/store/gateway' +import { loadMachineProfile } from '@/store/machine' +import { notify } from '@/store/notifications' +import { skipGuide } from '@/store/onboarding-gate' +import { buildChatOnboardingSeedMessages } from '@/store/onboarding-script' +import { + $activeGatewayProfile, + $newChatProfile, + $newChatRoute, + ensureGatewayAgent, + ensureGatewayProfile +} from '@/store/profile' +import { $activeSessionId, $selectedStoredSessionId } from '@/store/session' + +import type { AmbientGatewayRequest } from './session-rpc-dispatcher' + +export interface OnboardingKickoffOptions extends Pick< + ReturnType, + 'createBackendSessionForSend' | 'resumeSession' +> { + requestGateway: AmbientGatewayRequest + /** The caller's own requestGateway is what reads the pin. */ + runCreatePinnedTo: (profile: string, create: () => Promise) => Promise +} + +interface SetupStatus { + ready?: boolean + provider_configured?: boolean + free_tier?: boolean +} + +interface GuideSession { + id: string + resolved_id?: string +} + +async function adoptGuideSession( + canonical: GuideSession, + freeTier: SetupStatus['free_tier'], + resumeSession: OnboardingKickoffOptions['resumeSession'], + guideRequest: AmbientGatewayRequest +): Promise { + await resumeSession(canonical.resolved_id ?? canonical.id, true) + const adoptedRuntimeId = $activeSessionId.get() + $chatOnboardingThreadIds.set(adoptedRuntimeId ? [canonical.id, adoptedRuntimeId] : [canonical.id]) + $setupSession.set({ + connectionId: guideSourceConnectionId(canonical.id), + profile: SETUP_PROFILE, + runtimeId: adoptedRuntimeId ?? canonical.id, + storedId: canonical.id + }) + + if (freeTier) { + await guideRequest('config.set', { + session_id: adoptedRuntimeId ?? canonical.id, + key: 'reasoning', + value: 'minimal' + }) + } +} + +/** Seed the runbook and banked greeting on hermes-setup before advancing the phase. + * The seeded assistant row opens the chat without a model turn. */ +export function useOnboardingKickoff({ + createBackendSessionForSend, + requestGateway, + resumeSession, + runCreatePinnedTo +}: OnboardingKickoffOptions) { + return useCallback(async (): Promise => { + if (!isOnboardingEnabled()) { + return false + } + + const previousNewChatProfile = $newChatProfile.get() + const previousNewChatRoute = $newChatRoute.get() + const previousProfile = $activeGatewayProfile.get() + const previousConnectionId = activeGatewayConnectionId() + const previousSetupSession = $setupSession.get() + const previousThreadIds = $chatOnboardingThreadIds.get() + let swapped = false + + try { + await ensureSetupProfile(requestGateway) + + // Probe the guide's own socket before switching profiles so a refusal + // leaves classic onboarding on the user's current backend. + const record = await requestGatewayForProfile(SETUP_PROFILE, 'setup.status', {}) + + if (record.ready !== true || record.provider_configured !== true) { + return false + } + + swapped = true + $newChatRoute.set(null) + $newChatProfile.set(SETUP_PROFILE) + await ensureGatewayProfile(SETUP_PROFILE) + + startChatOnboardingSolo() + window.hermesDesktop?.chatOnboarding?.soloBoot?.() + await loadMachineProfile() + + const seedMessages = buildChatOnboardingSeedMessages(pickOnboardingGreeting(), record.free_tier !== true) + + const guideRequest: AmbientGatewayRequest = (method, params, timeout) => + requestGatewayForProfile(SETUP_PROFILE, method, params, timeout) + + // The exact title is the durable registry: a relaunch adopts the guide + // before creating, so UNIQUE(title) cannot strand an untitled duplicate. + const registryHit = await guideRequest<{ sessions?: GuideSession[] }>('session.list', { + include_hidden: true, + title: SETUP_CHAT_TITLE + }) + + const canonical = registryHit?.sessions?.[0] + + if (canonical?.id) { + await adoptGuideSession(canonical, record.free_tier, resumeSession, guideRequest) + + // runGuideKickoff records the guided phase only after adoption. + return true + } + + const createOverrides: SessionCreateOverrides = { title: SETUP_CHAT_TITLE } + + if (record.free_tier) { + createOverrides.reasoningEffort = 'minimal' + } + + const runtimeId = await runCreatePinnedTo(SETUP_PROFILE, () => + createBackendSessionForSend(null, seedMessages, createOverrides) + ) + + if (!runtimeId) { + throw new Error('The welcome chat could not be created. Please try again.') + } + + const storedId = $selectedStoredSessionId.get() + $chatOnboardingThreadIds.set(storedId ? [storedId, runtimeId] : [runtimeId]) + $setupSession.set({ + connectionId: guideSourceConnectionId(storedId), + profile: SETUP_PROFILE, + runtimeId, + storedId + }) + + // Manual title authority prevents the hidden runbook becoming the title. + await guideRequest('session.title', { session_id: runtimeId, title: SETUP_CHAT_TITLE }).catch(() => undefined) + + // session.create persisted both seed rows before the phase can advance. + return true + } catch (error) { + $newChatProfile.set(previousNewChatProfile) + $newChatRoute.set(previousNewChatRoute) + $setupSession.set(previousSetupSession) + $chatOnboardingThreadIds.set(previousThreadIds) + endChatOnboardingSolo() + skipGuide() + + if (swapped) { + await ( + previousConnectionId + ? ensureGatewayAgent(previousConnectionId, previousProfile) + : ensureGatewayProfile(previousProfile) + ).catch(restoreError => { + notify({ kind: 'error', title: 'Could not restore your profile', message: String(restoreError) }) + }) + } + + console.error('[setup] welcome chat could not start', error) + notify({ + kind: 'error', + title: 'Welcome chat needs attention', + message: error instanceof Error ? error.message : 'The welcome chat could not start.' + }) + + return false + } + }, [createBackendSessionForSend, requestGateway, resumeSession, runCreatePinnedTo]) +} diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx index 2f594de08f..0a4a519886 100644 --- a/apps/desktop/src/app/contrib/wiring.tsx +++ b/apps/desktop/src/app/contrib/wiring.tsx @@ -157,6 +157,7 @@ import { useQuickEntryBridge } from './hooks/use-quick-entry-bridge' import { useSessionTileDelegate } from './hooks/use-session-tile-delegate' import { McpInstallDeepLinkDialog } from './mcp-install-deeplink-dialog' import { useOnboardingHandoff } from './onboarding-handoff' +import { useOnboardingKickoff } from './onboarding-kickoff' import { $restartPreviewServer, useTitlebarToolContributions } from './panes' import { type AmbientGatewayRequest, createSessionRpcDispatcher } from './session-rpc-dispatcher' import { ChatRoutesSurface, SidebarSurface, StatusbarSurface, TerminalSurface } from './surfaces' @@ -640,13 +641,19 @@ export function ContribWiring({ children }: { children: ReactNode }) { } }, []) - const kickoffFirstChat = useOnboardingHandoff({ + const kickoffFirstChat = useOnboardingKickoff({ + createBackendSessionForSend, + requestGateway, + resumeSession, + runCreatePinnedTo + }) + + useOnboardingHandoff({ activeSessionIdRef, ensureSessionState, updateSessionState, createBackendSessionForSend, requestGateway, - resumeSession, runCreatePinnedTo }) diff --git a/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx b/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx index ea96b309b0..c45a377621 100644 --- a/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx +++ b/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx @@ -460,10 +460,17 @@ export function useStatusbarItems({ variant: 'menu' }, { + // The model id is the quiet part; the sign-in is the action, so it is + // solid and set off by a gap instead of touching the label. detail: ( - - {freeTierCopy.signIn} - + <> + + {freeTier?.model ?? FREE_TIER_MODEL} + + + {freeTierCopy.signIn} + + ), // Shown while a free-tier identity exists and the tier is on: it names the // identity that carries the connectors (and inference when nothing else @@ -471,8 +478,9 @@ export function useStatusbarItems({ hidden: !freeTier?.available, icon: , id: 'free-tier', - label: freeTierCopy.statusLabel(freeTier?.model ?? FREE_TIER_MODEL), + label: freeTierCopy.providerName, onSelect: () => openFreeTierSignIn(), + title: freeTierCopy.statusLabel(freeTier?.model ?? FREE_TIER_MODEL), toggleLabel: copy.toggleFreeTier, variant: 'action' }, diff --git a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx index 011abaa3f2..9c4702ceba 100644 --- a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx +++ b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx @@ -345,8 +345,8 @@ const ReasoningTextPart: ReasoningMessagePartComponent = () => { } - disableArtifacts isRunning={status.type === 'running' || messageRunning} + scratchpad text={separateGluedReasoningBlocks(text.trimStart())} /> ) diff --git a/apps/desktop/src/components/intro-reveal/README.md b/apps/desktop/src/components/intro-reveal/README.md index af0c05d703..543b9fab45 100644 --- a/apps/desktop/src/components/intro-reveal/README.md +++ b/apps/desktop/src/components/intro-reveal/README.md @@ -1,31 +1,35 @@ # Intro reveal -The cinematic runs in a transparent Electron window at `?win=intro`. -It covers the primary display and plays over the desktop while the app hides. -The surface owns its animation clock and synthesized sound; it has no gateway. -The main renderer owns the phase and the persistent seen key. +An idealized chat types a request, works through tools and a cube viewport, +streams a reply, expands into parallel agents, then closes on the brand. +The seven beats take 22 seconds, followed by a 900 ms dissolve. Reduced motion +shows the brand briefly. Sound defaults on and respects the haptics mute preference. +Fonts are the existing Collapse and JetBrains Mono faces. -The seven beats are ask, send, working, reply, everywhere, brand and dissolve. -Typing, tool activity, the cube and sound follow the same score. -Normal playback lasts 22 seconds; the exit dissolve lasts 900 ms. -Reduced motion shows the brand briefly. Click, Enter or Escape skips. -Sound defaults on and respects the existing haptics mute preference. +Eligibility is `guestOnboardingEnabled && !firstRunSkipped && !hasSeenIntroReveal()`. +Electron sets the flag from `HERMES_GUEST_ONBOARDING=1` or `--guest-onboarding`. +The gate queues the guided chat on completion; the chat gate acknowledges the +free-tier notice as the cinematic starts. With the flag off, neither gate starts. -There is one launch gate, enabled by `HERMES_GUEST_ONBOARDING=1` or -`--guest-onboarding`. Preload exposes that decision as `guestOnboardingEnabled`. -First-run eligibility also requires an unseen intro and no first-run skip. -With the launch gate off, neither the store nor native IPC opens the film. +| Piece | Path | +| --- | --- | +| Main-window gate and conductor | `index.tsx` | +| Phase, seen-key ownership and IPC listeners | `../../store/intro-reveal.ts` | +| Overlay boot and surface | `intro-root.tsx`, `intro-reveal-surface.tsx` | +| Clock, score, cube and synthesized sound | `use-intro-clock.ts`, `timeline.ts`, `viewport-cube.ts`, `sound.ts` | +| Constellation, brand and text effects | `scenes/` | +| Native window and preload bridge | `../../../electron/intro-reveal-window.ts`, `../../../electron/preload.ts` | -The renderer deadman is 26 seconds. The independent native watchdog is -34 seconds, deliberately longer; both return the main window if playback stalls. -Finishing records seen, clears the phase and requests `{showMain: true}`. -The guided-chat edge and app-shell mount arrive with the later gate/handoff steps. +The transparent native window (`?win=intro`) covers the primary display while +the main app hides. The overlay owns the clock because the hidden main renderer's +animation frames are throttled. The main renderer owns the phase and seen key. -Rehearse from `apps/desktop` with isolated app state: +The screen must ALWAYS come back. Four independent layers: -```sh -intro_tmp=$(mktemp -d /tmp/hermes-intro.XXXXXX) -env -u NODE_ENV HERMES_GUEST_ONBOARDING=1 HERMES_HOME="$intro_tmp/.hermes" HERMES_DESKTOP_USER_DATA_DIR="$intro_tmp/electron-user-data" npm run dev -``` +1. Normal completion: the overlay clock finishes → main renderer closes it. +2. Esc/click: local close with a 1.2s fallback that bypasses the main renderer. +3. Local deadman: the overlay force-closes itself `INTRO_DEADMAN_MS` after + mount, even with all IPC dead. +4. Main-process watchdog (34s) destroys the window unconditionally. -Collapse comes from the UI package; JetBrains Mono comes from desktop styles. +Rehearsal with isolated state: see [Desktop Engineering Guide](../../../AGENTS.md#rehearsing-the-guided-onboarding). diff --git a/apps/desktop/src/components/intro-reveal/index.tsx b/apps/desktop/src/components/intro-reveal/index.tsx index 553de07790..223aadded5 100644 --- a/apps/desktop/src/components/intro-reveal/index.tsx +++ b/apps/desktop/src/components/intro-reveal/index.tsx @@ -13,8 +13,7 @@ import { import { $desktopOnboarding } from '@/store/onboarding' import { beginOnboardingFlow, queueGuideAfterIntro } from '@/store/onboarding-gate' -import { IntroRevealSurface } from './intro-reveal-surface' -import { INTRO_DEADMAN_MS, INTRO_EXIT_MS, INTRO_WALL_MS } from './timeline' +import { INTRO_DEADMAN_MS, INTRO_EXIT_MS } from './timeline' interface IntroRevealGateProps { enabled: boolean @@ -23,7 +22,6 @@ interface IntroRevealGateProps { export function IntroRevealGate({ enabled }: IntroRevealGateProps) { const onboarding = useStore($desktopOnboarding) const intro = useStore($introReveal) - const nativeSurface = Boolean(window.hermesDesktop?.introReveal) const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches useEffect(() => { @@ -59,7 +57,7 @@ export function IntroRevealGate({ enabled }: IntroRevealGateProps) { return } - const total = reduceMotion ? 2600 : nativeSurface ? INTRO_DEADMAN_MS : INTRO_WALL_MS + const total = reduceMotion ? 2600 : INTRO_DEADMAN_MS const id = window.setTimeout( intro.phase === 'leaving' ? finishIntroReveal : leaveIntroReveal, @@ -67,15 +65,7 @@ export function IntroRevealGate({ enabled }: IntroRevealGateProps) { ) return () => window.clearTimeout(id) - }, [intro.phase, nativeSurface, reduceMotion]) + }, [intro.phase, reduceMotion]) - if (!enabled || !isIntroRevealEnabled() || intro.phase === 'hidden' || nativeSurface) { - return null - } - - return ( -
- -
- ) + return null } diff --git a/apps/desktop/src/components/intro-reveal/intro-reveal-surface.tsx b/apps/desktop/src/components/intro-reveal/intro-reveal-surface.tsx index be0994d07e..f5773d508d 100644 --- a/apps/desktop/src/components/intro-reveal/intro-reveal-surface.tsx +++ b/apps/desktop/src/components/intro-reveal/intro-reveal-surface.tsx @@ -7,22 +7,17 @@ import { cn } from '@/lib/utils' import { BrandClose } from './scenes/brand' import { SideAgents } from './scenes/side-agents' import { BLUE, BLUE_DIM, EASE, NOUS_SHADOW } from './scenes/style' -import { decoded } from './scenes/text' +import { decoded, SPINNER } from './scenes/text' import { INTRO_BEATS, INTRO_PROMPT, INTRO_REPLY_WORDS, INTRO_TOOL_ROWS } from './timeline' import { useIntroClock } from './use-intro-clock' import { viewportSlot } from './viewport-cube' const INTRO_BEAT_INDEX: Record = Object.fromEntries(INTRO_BEATS.map((b, i) => [b.id, i])) -const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] const SKIP = 'Skip' const SURFACES = 'Desktop · Messages · Phone · Anywhere' -interface IntroRevealSurfaceProps { - onSkip?: () => void -} - -export function IntroRevealSurface({ onSkip }: IntroRevealSurfaceProps = {}) { - const { frame, leaving, faded, skip, glowRef, stageRef, brandRef, viewportRef } = useIntroClock(onSkip) +export function IntroRevealSurface() { + const { frame, leaving, faded, skip, glowRef, stageRef, brandRef, viewportRef } = useIntroClock() const everywhere = frame.beat >= INTRO_BEAT_INDEX.everywhere const brand = frame.beat >= INTRO_BEAT_INDEX.brand @@ -115,7 +110,7 @@ function HeroChat({ frame, viewportRef }: HeroChatProps) { return (

Your agent, everywhere diff --git a/apps/desktop/src/components/intro-reveal/scenes/text.ts b/apps/desktop/src/components/intro-reveal/scenes/text.ts index b6c65d9a2e..fe7466b5a5 100644 --- a/apps/desktop/src/components/intro-reveal/scenes/text.ts +++ b/apps/desktop/src/components/intro-reveal/scenes/text.ts @@ -1,5 +1,7 @@ const SCRAMBLE_CHARS = '/\\|-_=+<>~:*' +export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] + export const scrambleGlyph = (i: number, tick: number) => { const n = (i * 2654435761 + tick * 40503) >>> 0 diff --git a/apps/desktop/src/components/intro-reveal/use-intro-clock.ts b/apps/desktop/src/components/intro-reveal/use-intro-clock.ts index 23056eb9f2..1a1ac814ee 100644 --- a/apps/desktop/src/components/intro-reveal/use-intro-clock.ts +++ b/apps/desktop/src/components/intro-reveal/use-intro-clock.ts @@ -75,7 +75,7 @@ function frameAt(t: number, beat: number): Frame { return { beat, replyWords, tick: Math.floor(t / 45), toolDone, toolShown, typed } } -export function useIntroClock(onSkip?: () => void) { +export function useIntroClock() { const glowRef = useRef(null) const stageRef = useRef(null) const brandRef = useRef(null) @@ -88,17 +88,11 @@ export function useIntroClock(onSkip?: () => void) { const skip = useCallback(() => { setClockLeaving(true) - if (onSkip) { - onSkip() - - return - } - window.hermesDesktop?.introReveal?.skip?.() window.setTimeout(() => { void window.hermesDesktop?.introReveal?.close?.({ showMain: true }).catch(() => undefined) }, 1200) - }, [onSkip]) + }, []) useEffect(() => { const id = window.setTimeout(() => { diff --git a/apps/desktop/src/components/onboarding-chat/assembly.ts b/apps/desktop/src/components/onboarding-chat/assembly.ts index 8cd87e377e..379a58229c 100644 --- a/apps/desktop/src/components/onboarding-chat/assembly.ts +++ b/apps/desktop/src/components/onboarding-chat/assembly.ts @@ -1,16 +1,9 @@ /** - * The layout assembly for in-chat onboarding. + * The guided chat starts alone in a small window. Picking a layout assembles + * the app around the conversation. * - * The guided chat starts SOLO: just the chat pane in a small window — no - * sidebar, nothing to explain. When the user picks a layout in the - * ::onboarding card, the app assembles around the conversation. - * - * The OS window grows OUTWARD by the MINIMUM each layout needs — the - * sidebar's width to the left, the terminal/rail minimums where a layout - * has them — animated (macOS setBounds animate), so the chat stays roughly - * where it was and the window ends as small as the layout allows, but never - * so small that the sidebar it just docked pops back out as a floating - * Sheet. + * The window grows outward by the minimum the new panes need, with a viewport + * floor so the sidebar stays docked. Native window bounds own the animation. */ import { useStore } from '@nanostores/react' @@ -43,33 +36,15 @@ export const $chatOnboardingSolo = atom(false) // Presence mirror — see onboarding-presence.ts (update toast stands down). $chatOnboardingSolo.subscribe(solo => setOnboardingSurfaceActive('solo-chat', solo)) -/** The guided-setup session's ids — stored AND runtime, because consumers key - * sessions differently (the thread list by stored id, the composer by runtime - * id). That one thread gets the onboarding transcript treatment and drops the - * composer's git strip; every other session is untouched. */ +/** The thread list keys by stored id; the composer keys by runtime id. Both + * identify the conversation that gets onboarding transcript treatment. */ export const $chatOnboardingThreadIds = atom([]) -/** The opening line of the guided chat — PRE-BANKED, never generated. The - * first thing a new user sees must be instant; the model's cold-stack first - * turn took up to 10 seconds in live runs. The transcript renders this - * client-side the moment the chat opens; the model is told what was said - * and picks up from the user's answer. The lines themselves live in the i18n - * catalog (`guidedGreeting`) so they arrive in the user's language. */ - +/** Bank the localized opener before inference: cold first turns took 10 s. + * The typed reveal and seed rows share it so the model sees what the user saw. */ export const $onboardingGreeting = atom('') -/** Pick (and remember) the canned opening line for this run. When the host - * reports a suggestable account name (machineUserName), the greeting ends by - * offering it as a default — \"or I can just call you akp\". The suggestion - * rides the SAME word the seed rows bank, so the canonical row, the typed - * reveal, and what the runbook says was said can never disagree. - * - * Read from the i18n catalog rather than a local constant: the runbook tells - * the model to answer in the user's own language from its first real turn, so - * an English opener on a Japanese machine would be two different agents in - * two consecutive messages. Locales without their own copy fall back to - * English per-key through defineLocale, which is the same trade every other - * string in the app makes. */ +/** First-write-wins keeps the opener stable through profile and backend boot. */ export function pickOnboardingGreeting(): string { const existing = $onboardingGreeting.get() @@ -78,19 +53,14 @@ export function pickOnboardingGreeting(): string { } const copy = TRANSLATIONS[getRuntimeI18nLocale()].guidedGreeting - const lines = copy.lines.length > 0 ? copy.lines : TRANSLATIONS.en.guidedGreeting.lines - const line = lines[Math.floor(Math.random() * lines.length)] ?? lines[0] ?? '' const suggested = machineUserName() - $onboardingGreeting.set(suggested ? `${line}\n\n${copy.nameSuggestion(suggested)}` : line) + $onboardingGreeting.set(suggested ? `${copy.line}\n\n${copy.nameSuggestion(suggested)}` : copy.line) return $onboardingGreeting.get() } -/** Whether the layout card's pick happened. A STORE, not card-local state: - * applying the layout replaces the pane tree, which remounts the chat pane - * and the card with it — component state would forget the selection the - * moment it takes effect. */ +/** Applying a layout remounts the card, so its selection must outlive the component. */ export const $chatLayoutPicked = atom(false) let previousLayout: { id: string; tree: LayoutNode | null } | null = null @@ -103,23 +73,15 @@ export function startChatOnboardingSolo(): void { previousLayout = { id: $activePresetId.get(), tree: $layoutTree.get() } $chatOnboardingSolo.set(true) $chatLayoutPicked.set(false) - // Bank the opening line the moment the solo chat owns the screen. The - // machine profile is one local IPC; everything after it in the kickoff — - // the setup profile, its backend boot, the session create — takes seconds - // to minutes, and the greeting must be typing in the whole time instead of - // the empty-draft wordmark. The kickoff picks again and gets this same - // banked line (pick is first-write-wins). + // The local machine probe finishes before the backend boots, letting the + // greeting type while kickoff is still waiting for a session. void loadMachineProfile().then(() => { if ($chatOnboardingSolo.get()) { pickOnboardingGreeting() } }) - // One zone, strip pinned off. applyTree ADOPTS panes the preset doesn't - // declare (sessions, terminal, …) into this group as tabs — with the strip - // never shown and workspace active, they're simply invisible until the - // assembled layout re-places them. That adoption is also why reactive - // unhides (files on cwd-arrival) can't pop a zone open mid-flow: there is - // no other zone to open. + // Adoption puts other panes in this same group. Hiding its strip keeps them + // invisible, including reactive arrivals, until a layout places them. applyLayoutPreset('chat-solo', group(['workspace'], { tabStrip: 'never' })) } @@ -141,10 +103,7 @@ export function endChatOnboardingSolo(): void { } } -/** Minimal per-edge growth per layout — the least the window must gain for - * the new panes to be usable, NOT a chat-size-preserving projection (which - * balloons the window). Left = sessions sidebar; Elite adds its right rail - * and terminal row. Tune by feel. */ +/** Grow by what the new panes need, not by a projection that keeps the chat's size (that balloons the window). */ interface LayoutGrowth { bottom?: number left?: number @@ -157,40 +116,19 @@ const LAYOUT_GROWTH = new Map([ ['terminal-deck', { bottom: 200, left: 220, right: 240 }] ]) -/** - * Put the tree in the state this layout describes — on the first pick AND on - * every re-pick. - * - * All of it has to re-run, because all of it persists: dismissals, dock - * enforcement, the sidebar's open state. A re-pick that only swapped the - * preset tree inherited the previous layout's records and came up as a mix of - * the two (Elite after Basic kept Basic's terminal dismissal, so Elite's - * terminal was placed and invisible). - */ +/** Re-picks must reset persisted dismissals, docks, and sidebar visibility: + * swapping only the tree left Elite's terminal dismissed after Basic. */ function reconcileLayout(id: string, tree: LayoutNode): void { applyLayoutPreset(id, tree) const declared = new Set(allPaneIds(tree)) - // Everything this layout asks for is wanted, whatever the last one decided. undismissTreePanes(declared) - // The preset IS the layout. Adoption otherwise keeps every pane the preset - // doesn't declare, and during a first run each of them is a surface the - // user has no idea exists: a Terminal tab beside the chat on Basic, an - // empty Cronjobs column, a Bots roster tabbed onto Sessions (its dock is - // `enforce: true`, so it re-homes there on every pick). That last one also - // costs the sidebar its plain face — two panes in the left zone is what - // conjures a tab strip over what should just be the sessions list. - // - // So: anything the picked layout didn't ask for is dismissed. The pane - // isn't gone, only unplaced — its own toggle (⌃` for the terminal, the - // Layout menu, `revealTreePane`) brings it back the moment the user wants - // it. - // - // Candidates come from the REGISTRY, not just the tree: a pane that isn't - // placed yet still gets its dismissal recorded, and adoption skips dismissed - // panes — so this holds whether the pane arrives before or after the sweep. + // plugins/hermes-bots/plugin.tsx enforces a dock onto Sessions; adoption + // otherwise adds its roster and a tab strip to the sidebar. Dismiss every + // undeclared pane, including registry entries not placed yet, so subsequent + // adoption cannot bring them back. Their own toggles still can. const dismissUndeclared = () => { for (const paneId of new Set([ ...allPaneIds($layoutTree.get() ?? tree), @@ -202,37 +140,21 @@ function reconcileLayout(id: string, tree: LayoutNode): void { } } - // The tree now HAS a sessions column, but the renderer drops the whole left - // column when the persisted ⌘B state says closed ($sidebarOpen → - // $collapsedTreeSides) — picking a layout with a sidebar is an explicit - // intent to see it, so open the side through its store (truthful toggle), - // the same way resetLayoutTree reopens bound sides. + // A persisted closed sidebar would hide the column this pick just requested. setSidebarOpen(true) - // Dock invariants normally run once at boot, against whatever tree existed - // then — the SOLO tree, which has no sessions column for a left-docking - // pane to anchor to. That pass burns the ledger entry, so re-running - // adoption alone left those panes stranded as tabs in the chat zone. Reopen - // the window first, now that the layout they should dock into exists. + // Solo boot consumed dock enforcement before a sidebar existed. Reset its + // ledger so adoption can dock against the newly placed Sessions column. resetEnforcedDocks() adoptContributedPanes() - // LAST, because panes can be a CONSEQUENCE of the assembly above: a plugin - // registers more panes the moment one of its own becomes visible. Sweeping - // before that point swept a tree those arrivals had not happened in yet, - // and Basic still landed with an empty Cronjobs column beside the chat. + // Visibility can register more plugin panes synchronously. Sweep last to + // include those arrivals (Basic otherwise gained an empty Cronjobs column). dismissUndeclared() } -/** - * A layout pick, from the chat card. The FIRST one also performs the solo→app - * transition (see module header); later picks re-arrange the app that is - * already there. - * - * The window is grown once, on that first pick. `grow` moves the edges OUTWARD - * by a delta, so re-growing per pick would ratchet the window bigger every - * time the user toggled between two layouts. - */ +/** Grow only when leaving solo mode: repeating a delta would ratchet the window + * larger on every re-pick. Reconcile panes on every pick. */ export function assembleChatOnboarding(id: string, tree: LayoutNode): void { const firstPick = $chatOnboardingSolo.get() @@ -243,13 +165,8 @@ export function assembleChatOnboarding(id: string, tree: LayoutNode): void { bottom: growth.bottom ?? 0, left: growth.left ?? 0, right: growth.right ?? 0, - // Every layout here docks a sessions sidebar, and the deltas above are - // measured against the panes, not against the viewport the sidebar needs - // to stay docked. Growing the solo card by a sidebar's width can still - // land under the breakpoint — at first-run zoom, Basic did — and the - // sidebar then arrives as a floating Sheet over the chat instead of - // sliding in beside it. Ask for the floor and let main clamp it to the - // display. + // Pane deltas can leave Basic below the sidebar's docking breakpoint at + // the user's zoom. Main applies this viewport floor, then the display clamp. minWidth: DOCKED_SIDEBAR_MIN_PX, top: growth.top ?? 0 }) @@ -260,10 +177,7 @@ export function assembleChatOnboarding(id: string, tree: LayoutNode): void { $chatOnboardingSolo.set(false) } -/** Skip the guided setup: assemble the default layout so the user lands in - * the full app immediately, and mark onboarding done so nothing resumes it. - * The guided chat stays in the transcript — skipping is about ending the - * questionnaire, not destroying the conversation. */ +/** Skip ends setup without deleting its conversation; the phase write prevents resuming it. */ export function skipChatOnboarding(): void { const preset = registry.getArea('layouts').find(contribution => contribution.id === 'basic') @@ -277,15 +191,7 @@ export function skipChatOnboarding(): void { skipGuide() } -/** - * True while the user is inside the first-run story — the solo guided chat, - * or any thread the flow owns afterwards (Setup's chat, the first - * build). Chrome that would read as noise over those conversations checks - * this: floating panels, the profile-swap spinner. - * - * Threads are matched on BOTH ids because consumers key sessions differently - * (the thread list by stored id, the composer by runtime id). - */ +/** Suppress floating panels and swap chrome throughout the flow's conversations. */ export function useOnboardingChatActive(): boolean { const solo = useStore($chatOnboardingSolo) const threadIds = useStore($chatOnboardingThreadIds) diff --git a/apps/desktop/src/components/onboarding-chat/cards/build.tsx b/apps/desktop/src/components/onboarding-chat/cards/build.tsx index 31be6e5d7e..1a22f57dbb 100644 --- a/apps/desktop/src/components/onboarding-chat/cards/build.tsx +++ b/apps/desktop/src/components/onboarding-chat/cards/build.tsx @@ -7,20 +7,22 @@ import { useAuiState } from '@assistant-ui/react' import { useStore } from '@nanostores/react' -import { useEffect, useState } from 'react' +import { useEffect, useMemo, useState } from 'react' import { requestComposerSubmit } from '@/app/chat/composer/focus' import { useSessionView } from '@/app/chat/session-view' -import { $handoffError, retrySetupHandoff } from '@/app/contrib/handoff-receipt' +import { handoffReceiptKey, readHandoffReceipt } from '@/app/contrib/handoff-receipt' import { resolveSessionOwner } from '@/app/session/hooks/use-session-actions/utils' import type { CardProps } from '@/components/onboarding-chat/cards/frame' import { Chip } from '@/components/onboarding-chat/chip' import { + $handoffError, $setupHandoff, firstTaskTitle, - hasCompletedSetupHandoff, + guideSourceConnectionId, parseHandoffPlan, requestSetupHandoff, + retrySetupHandoff, SETUP_PROFILE } from '@/components/onboarding-chat/setup-profile' import { Button } from '@/components/ui/button' @@ -97,8 +99,8 @@ export function FirstBuildCard({ attrs, locked }: CardProps) { * session on the user's default profile, seeds it, and moves the user there. * * Nothing to ask — the build's shape was settled by the `first` step and there - * is one surface now, so the card just narrates: opening → landed. Both - * latches (atom + storage) make re-parses, re-mounts, and relaunches inert, + * is one surface now, so the card just narrates: opening → landed. The request + * atom and accepted receipt make re-parses, re-mounts, and relaunches inert, * and a locked (replayed) transcript never re-fires. */ export function HandoffCard({ attrs, locked }: CardProps) { @@ -109,10 +111,19 @@ export function HandoffCard({ attrs, locked }: CardProps) { const brief = (attrs.brief ?? '').trim().slice(0, 240) const plan = parseHandoffPlan(attrs.plan) const state = useStore($setupHandoff) - const error = useStore($handoffError) + let error = useStore($handoffError) + let completed = false + + try { + completed = + !!storedId && + readHandoffReceipt(handoffReceiptKey(guideSourceConnectionId(storedId), storedId))?.status === 'accepted' + } catch (receiptError) { + error = String(receiptError) + } useEffect(() => { - if (!task || !brief || locked || !storedId || !runtimeId || $setupHandoff.get() || hasCompletedSetupHandoff()) { + if (!task || !brief || locked || !storedId || !runtimeId || $setupHandoff.get() || completed) { return } @@ -140,14 +151,14 @@ export function HandoffCard({ attrs, locked }: CardProps) { return () => { cancelled = true } - }, [brief, locked, plan, task, storedId, runtimeId]) + }, [brief, locked, plan, task, storedId, runtimeId, completed]) if (!task || !brief) { return null } - const settled = state?.phase === 'done' || (state === null && hasCompletedSetupHandoff()) - const failed = state?.phase === 'error' + const settled = state?.phase === 'done' || (state === null && completed) + const failed = state?.phase === 'error' || error !== null const title = state?.sessionTitle ?? firstTaskTitle(task) return ( @@ -175,33 +186,33 @@ export function ProgressCard({ attrs, locked }: CardProps) { const messages = useStore(view.$messages) const messageId = useAuiState(state => state.message.id) const title = (attrs.title ?? '').trim() || 'Working on it' - const index = messages.findIndex(message => message.id === messageId) - const previous = index < 0 ? [] : messages.slice(0, index) + const steps = useMemo(() => { + const index = messages.findIndex(message => message.id === messageId) + const previous = index < 0 ? [] : messages.slice(0, index) - const steps = previous.flatMap(message => { - const directives = message.parts.flatMap(part => - part.type === 'text' ? (segmentTranscriptDirectives(part.text) ?? []) : [] - ) - - const progress = directives - .filter( - segment => - segment.kind === 'directive' && - segment.directive.name === 'onboarding' && - segment.directive.attrs.step === 'progress' + return previous.flatMap(message => { + const directives = message.parts.flatMap(part => + part.type === 'text' ? (segmentTranscriptDirectives(part.text) ?? []) : [] ) - .at(-1) - return progress?.kind === 'directive' - ? [{ id: message.id, title: progress.directive.attrs.title?.trim() || 'Working on it' }] - : [] - }) + const progress = directives + .filter( + segment => + segment.kind === 'directive' && + segment.directive.name === 'onboarding' && + segment.directive.attrs.step === 'progress' + ) + .at(-1) - steps.push({ id: messageId, title }) + return progress?.kind === 'directive' + ? [{ id: message.id, title: progress.directive.attrs.title?.trim() || 'Working on it' }] + : [] + }) + }, [messages, messageId]) return (

- {steps.map(step => { + {[...steps, { id: messageId, title }].map(step => { const current = step.id === messageId return ( diff --git a/apps/desktop/src/components/onboarding-chat/cards/setup.tsx b/apps/desktop/src/components/onboarding-chat/cards/setup.tsx index 95356545c5..672db633b9 100644 --- a/apps/desktop/src/components/onboarding-chat/cards/setup.tsx +++ b/apps/desktop/src/components/onboarding-chat/cards/setup.tsx @@ -1,10 +1,8 @@ /** - * The setup picks — connectors, accent, layout. + * The three setup picks — accent, connectors, layout. * - * Everything applies LIVE on click: the accent retints the app, the layout - * preset rearranges the panes behind the chat. That's the trick. The model - * never enumerates options in prose; it only places the card, and the catalog - * lives in options.tsx so the cards and previews can't drift. + * Picks apply live. The shared catalog keeps cards and previews in agreement + * without asking the model to enumerate the options. */ import { useStore } from '@nanostores/react' diff --git a/apps/desktop/src/components/onboarding-chat/setup-profile.ts b/apps/desktop/src/components/onboarding-chat/setup-profile.ts index 46e9dd03bd..570d62862e 100644 --- a/apps/desktop/src/components/onboarding-chat/setup-profile.ts +++ b/apps/desktop/src/components/onboarding-chat/setup-profile.ts @@ -24,11 +24,13 @@ import { atom } from 'nanostores' +import { handoffReceiptKey, readHandoffReceipt } from '@/app/contrib/handoff-receipt' import type { GatewayRequest } from '@/app/session/hooks/use-prompt-actions/utils' -import { readKey, writeKey } from '@/lib/storage' +import { activeGatewayConnectionId } from '@/store/gateway' import { machineDescription } from '@/store/machine' import type { OnboardingAnswers } from '@/store/onboarding-answers' import { PLAIN_SPEECH } from '@/store/onboarding-script' +import { getSessionOwnerHint } from '@/store/session' /** Profile name of the onboarding guide. Prefixed so it can't collide with a * profile a user actually named "setup". */ @@ -39,8 +41,6 @@ export const SETUP_PROFILE = 'hermes-setup' * this string is also a registry key — change the words, keep them stable. */ export const SETUP_CHAT_TITLE = 'Welcome to Hermes' -const HANDOFF_DONE_KEY = 'hermes-setup-handoff-done-v1' - export type SetupHandoffPhase = 'done' | 'error' | 'opening' | 'pending' /** What KIND of first job this is. Two shapes we script ourselves: @@ -81,6 +81,19 @@ export interface SetupHandoffState { /** The handoff beacon: HandoffCard raises it, the wiring effect performs it. * Null until the model emits the handoff directive. */ export const $setupHandoff = atom(null) +export const $handoffError = atom(null) + +/** Only a deliberate retry lifts an error; re-rendering a directive does not. */ +export function retrySetupHandoff(): void { + const state = $setupHandoff.get() + + if (state?.phase !== 'error') { + return + } + + $handoffError.set(null) + $setupHandoff.set({ ...state, phase: 'pending' }) +} /** The issuing welcome chat owns the completion note, even in a background tile. */ export interface SetupSession { @@ -92,11 +105,20 @@ export interface SetupSession { export const $setupSession = atom(null) -/** Raise the handoff request (once per task — re-parses and re-mounts of the - * directive are no-ops, and a relaunch after a completed handoff stays - * quiet thanks to the storage latch). */ +/** A null connection is the ambient profile route. Substituting 'local' + * would retarget a legacy remote primary onto this machine. */ +export function guideSourceConnectionId(guideStoredId: null | string | undefined): null | string { + return (guideStoredId && getSessionOwnerHint(guideStoredId)?.connectionId) || activeGatewayConnectionId() || null +} + +/** The request atom suppresses remounts; only an accepted receipt suppresses relaunches. */ export function requestSetupHandoff(task: string, brief: string, plan: HandoffPlan, guide: SetupSession): boolean { - if ($setupHandoff.get() !== null || readKey(HANDOFF_DONE_KEY) === '1') { + if ( + $setupHandoff.get() !== null || + (guide.storedId && + readHandoffReceipt(handoffReceiptKey(guideSourceConnectionId(guide.storedId), guide.storedId))?.status === + 'accepted') + ) { return false } @@ -105,19 +127,7 @@ export function requestSetupHandoff(task: string, brief: string, plan: HandoffPl return true } -/** Burn the relaunch latch — the build session exists and its chat is open. */ -export function markSetupHandoffDone(): void { - writeKey(HANDOFF_DONE_KEY, '1') -} - -/** True once a handoff completed on this install (survives relaunch) — used - * by the card to render its settled state when the atom is long gone. */ -export function hasCompletedSetupHandoff(): boolean { - return readKey(HANDOFF_DONE_KEY) === '1' -} - export function resetSetupHandoffForTests(): void { - writeKey(HANDOFF_DONE_KEY, null) $setupHandoff.set(null) $setupSession.set(null) } diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts index 37932dfedf..0414f660e5 100644 --- a/apps/desktop/src/i18n/ar.ts +++ b/apps/desktop/src/i18n/ar.ts @@ -2513,11 +2513,7 @@ export const ar = defineLocale({ } }, guidedGreeting: { - lines: [ - 'أهلا، تفضل بالدخول. أنا Hermes. امنحني دقيقتين لأرتب المكان حولك، ثم نبدأ بشيء تريد إنجازه فعلا.\n\nبداية، بماذا أناديك؟', - 'أهلا، أنا Hermes. سؤالان سريعان ويصبح هذا المكان مكانك، ثم نجد لك ما يستحق العمل عليه.\n\nإذن، بماذا أناديك؟', - 'مرحبا، لقد وجدتني. أنا Hermes. دعني أرتب كل شيء حولك، ثم نختار شيئا حقيقيا نبدأ به.\n\nلكن أولا، بماذا أناديك؟' - ], + line: 'أهلا، تفضل بالدخول. أنا Hermes. امنحني دقيقتين لأرتب المكان حولك، ثم نبدأ بشيء تريد إنجازه فعلا.\n\nبداية، بماذا أناديك؟', nameSuggestion: (name: string) => `(يمكنني أن أناديك ${name} إن كنت تفضل ذلك.)` }, install: { diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 97f9c0d3d0..138a55ad4d 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -3348,11 +3348,7 @@ export const en: Translations = { }, guidedGreeting: { - lines: [ - "Hey, come on in. I'm Hermes. Give me two minutes to set the place up around you, then we'll put me to work on something you actually want done.\n\nFirst though, what should I call you?", - "Hey there, I'm Hermes. A couple of quick things and this will feel like yours, then we'll find you something worth doing.\n\nSo, what should I call you?", - "Hi, you found me. I'm Hermes. Let me get everything arranged around you, then we'll pick something real to start on.\n\nFirst things first though, what should I call you?" - ], + line: "Hey, come on in. I'm Hermes. Give me two minutes to set the place up around you, then we'll put me to work on something you actually want done.\n\nFirst though, what should I call you?", nameSuggestion: (name: string) => `(I can also just call you ${name}, if you prefer.)` }, install: { @@ -3521,7 +3517,8 @@ export const en: Translations = { stripBody: 'Open the model picker to try them, or sign in with a Nous account.', openModelPicker: 'Open model picker', dismiss: 'Dismiss', - statusLabel: model => `Nous · free tier · ${model}`, + providerName: 'Nous', + statusLabel: model => `Nous · ${model}`, signIn: 'Sign in', signInHeading: 'Sign in with a Nous account to unlock more models and tools.', settingUp: 'Setting up free inference…', diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts index c3ea280375..0bcd88fcab 100644 --- a/apps/desktop/src/i18n/ja.ts +++ b/apps/desktop/src/i18n/ja.ts @@ -2898,11 +2898,7 @@ export const ja = defineLocale({ }, guidedGreeting: { - lines: [ - 'やあ、どうぞ。Hermes です。二分だけください、あなたに合わせて整えます。それから、本当にやりたいことに取りかかりましょう。\n\nまずは、何とお呼びすればいいですか。', - 'どうも、Hermes です。いくつか伺えば、ここはあなたのものになります。そのあとで、やる価値のあることを見つけましょう。\n\nでは、何とお呼びすればいいですか。', - 'こんにちは、見つけてくれましたね。Hermes です。まわりを整えてから、何か実のあるものを一つ選んで始めましょう。\n\nその前に、何とお呼びすればいいですか。' - ], + line: 'やあ、どうぞ。Hermes です。二分だけください、あなたに合わせて整えます。それから、本当にやりたいことに取りかかりましょう。\n\nまずは、何とお呼びすればいいですか。', nameSuggestion: (name: string) => `(よければ、${name} さんとお呼びします。)` }, install: { diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts index 35904d5514..6e56ebe064 100644 --- a/apps/desktop/src/i18n/ru.ts +++ b/apps/desktop/src/i18n/ru.ts @@ -3052,11 +3052,7 @@ export const ru = defineLocale({ } }, guidedGreeting: { - lines: [ - 'Заходите. Я Hermes. Дайте мне пару минут — обустрою тут всё под вас, а потом займёмся тем, что вам правда нужно.\n\nДля начала: как к вам обращаться?', - 'Привет, я Hermes. Пара вопросов — и здесь станет по-вашему, а дальше найдём занятие, которое того стоит.\n\nИтак, как к вам обращаться?', - 'Привет, вы меня нашли. Я Hermes. Сейчас всё вокруг вас расставлю, а потом выберем что-нибудь настоящее.\n\nНо сперва: как к вам обращаться?' - ], + line: 'Заходите. Я Hermes. Дайте мне пару минут — обустрою тут всё под вас, а потом займёмся тем, что вам правда нужно.\n\nДля начала: как к вам обращаться?', nameSuggestion: (name: string) => `(Могу звать вас просто ${name}, если так удобнее.)` }, install: { diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts index c2e4de2269..69771dc20e 100644 --- a/apps/desktop/src/i18n/types.ts +++ b/apps/desktop/src/i18n/types.ts @@ -2885,7 +2885,7 @@ export interface Translations { * an English opener above a Japanese reply reads as two different agents. * `nameSuggestion` offers the OS account name as a default. */ guidedGreeting: { - lines: readonly string[] + line: string nameSuggestion: (name: string) => string } install: { @@ -3025,6 +3025,8 @@ export interface Translations { openModelPicker: string dismiss: string // Statusbar chip. + /** The status-bar chip's label: the provider name alone; the model id and the sign-in follow it. */ + providerName: string statusLabel: (model: string) => string // Sign-in dialog. signIn: string diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts index f883b96916..e10152391f 100644 --- a/apps/desktop/src/i18n/zh-hant.ts +++ b/apps/desktop/src/i18n/zh-hant.ts @@ -2798,11 +2798,7 @@ export const zhHant = defineLocale({ }, guidedGreeting: { - lines: [ - '來了,進來吧。我是 Hermes。給我兩分鐘,把這裡按你的習慣整理一下,然後我們找件你真正想做的事來做。\n\n先說,我該怎麼稱呼你?', - '你好,我是 Hermes。幾個小問題,這裡就像是你自己的了,然後我們找點值得做的事。\n\n那麼,我該怎麼稱呼你?', - '嗨,你找到我了。我是 Hermes。讓我先把一切安排到位,然後我們挑一件實實在在的事開始。\n\n不過第一件事:我該怎麼稱呼你?' - ], + line: '來了,進來吧。我是 Hermes。給我兩分鐘,把這裡按你的習慣整理一下,然後我們找件你真正想做的事來做。\n\n先說,我該怎麼稱呼你?', nameSuggestion: (name: string) => `(如果你願意,我也可以直接叫你 ${name}。)` }, install: { diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts index 677be13356..3c254a7a03 100644 --- a/apps/desktop/src/i18n/zh.ts +++ b/apps/desktop/src/i18n/zh.ts @@ -3491,11 +3491,7 @@ export const zh: Translations = { }, guidedGreeting: { - lines: [ - '来了,进来吧。我是 Hermes。给我两分钟,把这里按你的习惯收拾一下,然后我们找件你真正想做的事来做。\n\n先说,我该怎么称呼你?', - '你好,我是 Hermes。几个小问题,这里就像是你自己的了,然后我们找点值得做的事。\n\n那么,我该怎么称呼你?', - '嗨,你找到我了。我是 Hermes。让我先把一切安排到位,然后我们挑一件实实在在的事开始。\n\n不过第一件事:我该怎么称呼你?' - ], + line: '来了,进来吧。我是 Hermes。给我两分钟,把这里按你的习惯收拾一下,然后我们找件你真正想做的事来做。\n\n先说,我该怎么称呼你?', nameSuggestion: (name: string) => `(如果你愿意,我也可以直接叫你 ${name}。)` }, install: { @@ -3656,7 +3652,8 @@ export const zh: Translations = { stripBody: '打开模型选择器试用,或登录 Nous 账户。', openModelPicker: '打开模型选择器', dismiss: '关闭', - statusLabel: model => `Nous · 免费层 · ${model}`, + providerName: 'Nous', + statusLabel: model => `Nous · ${model}`, signIn: '登录', signInHeading: '登录 Nous 账户以解锁更多模型和工具。', settingUp: '正在设置免费推理…', diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts index 92ad0ac23d..9acf23ded4 100644 --- a/apps/desktop/src/sdk/index.ts +++ b/apps/desktop/src/sdk/index.ts @@ -22,7 +22,6 @@ import { atom, computed, type ReadableAtom } from 'nanostores' import type { ReactNode } from 'react' import { capabilityScoped } from '@/api/client' -import { requestComposerSubmit } from '@/app/chat/composer/focus' import { PRIMARY_SESSION_VIEW } from '@/app/chat/session-view' import { openSession, type OpenSessionIntent } from '@/app/open-session' import type { ClientSessionState } from '@/app/types' @@ -1273,11 +1272,6 @@ export const host = { revealTreePane(id) }, - /** Submit through the active composer; false means no surface claimed it. - * Hidden prompts omit the user bubble. */ - submitPrompt: (text: string, options: { hidden?: boolean } = {}): boolean => - requestComposerSubmit(text, options.hidden ? { displayKind: 'hidden' } : {}), - /** HEAR the gateway stream (message deltas, session lifecycle, tool * activity, …) by event type — `'*'` for everything. Returns a disposer. * Listeners are isolated; a throw can't affect app dispatch. */ diff --git a/apps/desktop/src/store/intro-reveal.ts b/apps/desktop/src/store/intro-reveal.ts index 132034d1e1..63d4416de5 100644 --- a/apps/desktop/src/store/intro-reveal.ts +++ b/apps/desktop/src/store/intro-reveal.ts @@ -1,3 +1,12 @@ +/** + * The main renderer owns the phase; the native overlay owns the clock because + * animation frames in the hidden main window are throttled. Native skip/close + * events return here so every exit records seen and restores the main window. + * + * This store alone owns hermes-intro-reveal-seen-v1. First-run eligibility is + * guest onboarding enabled, not explicitly skipped, and not seen. The gate + * observes completion to queue the guided chat without coupling this store to it. + */ import { atom } from 'nanostores' import { isOnboardingEnabled } from '@/lib/onboarding-enabled' diff --git a/apps/desktop/src/store/machine.ts b/apps/desktop/src/store/machine.ts index 2a60e8e5c4..09506f58fc 100644 --- a/apps/desktop/src/store/machine.ts +++ b/apps/desktop/src/store/machine.ts @@ -1,25 +1,11 @@ -/** - * What Hermes knows about the computer it was just installed on. - * - * One question, really: is this machine new? A brand-new computer makes "set - * this thing up for me" the likeliest first task rather than one option among - * several — drivers, updates, a package manager, the tools they just told us - * they use — and it is a task Hermes can do end to end with no account - * anywhere, which is exactly what the first build has to be. - * - * A Spark answers yes on its own, without waiting for the account age to say - * so; see machineIsSpark. - * - * Loaded once, before the guided chat's runbook is composed. - */ +/** Machine facts load before the runbook so a new computer or Spark can lead + * with machine setup as the first task. */ import { atom } from 'nanostores' import type { DesktopMachineProfile } from '@/global' -/** A computer this young is almost certainly still being set up. Wide enough - * to cover the week someone spends getting around to it, short enough that a - * machine in daily use never trips it. */ +/** Allow time to get around to setup without treating a daily-use machine as new. */ const NEW_MACHINE_DAYS = 21 export const $machine = atom(null) @@ -57,10 +43,8 @@ const NON_NAME_USERNAMES = new Set([ 'user' ]) -/** A suggestable name for the guided chat's first question: the OS account - * name, when it actually looks like something you could be called. The login - * handle is a hint, never a truth — the greeting offers it as a default and - * the user still picks. Null means no suggestion; the guide just asks. */ +/** The login handle is only a suggestion; the user still chooses their name. + * Null means the guide asks without a default. */ export function machineUserName(): string | null { const raw = ($machine.get()?.username ?? '').trim() @@ -71,17 +55,8 @@ export function machineUserName(): string | null { return NON_NAME_USERNAMES.has(raw.toLowerCase()) ? null : raw } -/** The OS display language, as an English language name the model can act on - * ("Japanese", "Brazilian Portuguese"). Null when the machine hasn't - * answered, or when it is already English. - * - * Deliberately NOT limited to the six locales the UI ships: the chrome can - * only be translated where a bundle exists, but the MODEL speaks whatever the - * user does, and a Portuguese speaker being answered in Portuguese matters - * more than the sidebar labels matching. `Intl.DisplayNames` turns the raw - * tag into the name of a language rather than a code the model has to - * decode — and its own fallback ('code') hands back the tag if it doesn't - * know it either, which is still a better instruction than nothing. */ +/** Name the OS language for the model, independent of the UI's bundled locales. + * English, missing or invalid tags need no language instruction. */ export function machineLanguageName(): string | null { const tag = ($machine.get()?.locale ?? '').trim() @@ -98,21 +73,8 @@ export function machineLanguageName(): string | null { } } -/** A Spark, either kind. Neither is a machine anyone owns for its own sake — - * both are bought to be set up — so one takes the front of the flow whatever - * its account age says. - * - * The two are identified differently because they are different computers. - * An **RTX Spark** is a Windows-on-Arm PC (the N1X superchip, in this fall's - * ASUS / Dell / HP / Lenovo / Surface / MSI laptops and mini desktops); the - * OEM badge on the case is not a name we can enumerate, so it is recognised - * by its shape — Windows, Arm, NVIDIA silicon, a combination nothing else - * currently ships. A **DGX Spark** is the Linux GB10 developer box, and it - * says so in the device tree. - * - * On that string, underscores are separators rather than letters: a real unit - * reports `NVIDIA_DGX_Spark`, which \b reads as ONE word and would never - * match. */ +/** Recognize RTX Sparks by platform/architecture/GPU and DGX Sparks by model. + * Device-tree underscores separate words: real units report NVIDIA_DGX_Spark. */ export function machineIsSpark(): boolean { const profile = $machine.get() @@ -150,15 +112,8 @@ export function machineKind(): string { } } -/** One line for the machine-setup brief, so the agent that picks the job up - * starts knowing what it is looking at instead of asking. - * - * Age leads, because it is the fact that changes the work: on a machine - * someone unboxed this week the drivers, updates and toolchain are genuinely - * undone, and doing them is worth an afternoon of the user's life. On a - * machine that has been running for two years most of it is already handled, - * and an agent that doesn't know that will "fix" things that were never - * broken. */ +/** Age leads the setup brief because a new machine needs work that a + * daily-use machine may already have done. */ export function machineDescription(): string { const profile = $machine.get() @@ -184,7 +139,3 @@ function daysAgo(days: null | number): string { return days === 1 ? 'yesterday' : `${days} days ago` } - -export function resetMachineProfileForTests(): void { - $machine.set(null) -} diff --git a/apps/desktop/src/store/onboarding-gate.ts b/apps/desktop/src/store/onboarding-gate.ts index 1c129dff21..2b067579ed 100644 --- a/apps/desktop/src/store/onboarding-gate.ts +++ b/apps/desktop/src/store/onboarding-gate.ts @@ -8,7 +8,7 @@ import { DEFAULT_ANSWERS, setOnboardingAnswers } from './onboarding-answers' const PHASE_KEY = 'hermes-onboarding-phase-v1' -export type OnboardingPhase = 'idle' | 'cinematic' | 'guided' | 'handoff' | 'done' +export type OnboardingPhase = 'idle' | 'cinematic' | 'guided' | 'skipped' | 'handoff' | 'done' export interface OnboardingGateState { phase: OnboardingPhase @@ -21,7 +21,8 @@ function loadGate(): OnboardingGateState { const saved = readKey(PHASE_KEY) const phase = - isOnboardingEnabled() && (saved === 'cinematic' || saved === 'guided' || saved === 'handoff' || saved === 'done') + isOnboardingEnabled() && + (saved === 'cinematic' || saved === 'guided' || saved === 'skipped' || saved === 'handoff' || saved === 'done') ? saved : 'idle' @@ -96,7 +97,9 @@ export function runGuideKickoff(kickoff: () => Promise): Promise 0 } -/** Hard reset for tests. */ export function resetOnboardingPresenceForTests(): void { $onboardingSurfaces.set(EMPTY) } diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css index d7b8d45985..85a44eac9c 100644 --- a/apps/desktop/src/styles.css +++ b/apps/desktop/src/styles.css @@ -699,6 +699,16 @@ --ui-editor-surface-background: var(--ui-bg-chrome); } + /* The status bar spans the rail AND the content column. Transparent, it + showed the body's hard stop through itself, and the seam cut whichever + item sat on it (the free-tier chip, in the guided window). Finder's + shape: the bar belongs to the opaque content column across the full + width, and the rail's glass ends at its top edge. Window scope has no + seam, so the bar stays transparent there. */ + :root[data-hermes-glass][data-hermes-glass-scope='sidebar'] [data-slot='statusbar'] { + --ui-sidebar-surface-background: var(--ui-bg-chrome); + } + /* Clear mode (native window opacity) fades EVERYTHING in the window uniformly, so when an overlay opens over a session two layers of text fade by the same amount and fight through the overlay's light default @@ -3010,7 +3020,8 @@ button[data-slot='aui_msg-reactions'] svg { Widgets on the shared shell (components/chat/widget-shell.ts → `--ui-widget-surface-background`) and any chat-surface card are matched on their class, so new ones inherit this without touching the list. */ -[data-hud-shell] [data-slot='composer-bounds'] +[data-hud-shell] + [data-slot='composer-bounds'] :is( [data-slot='clarify-inline'], [data-slot='tool-block'],