The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
The local-setup offer works in the new onboarding: tour step, post-task card, model-menu row (#129506)
Siddharth Balyanf52cb57d4434
diff --git a/apps/desktop/src/app/chat/built-in-tour.ts b/apps/desktop/src/app/chat/built-in-tour.tsindex 24097876ef9..bb2b1577500 100644--- a/apps/desktop/src/app/chat/built-in-tour.ts+++ b/apps/desktop/src/app/chat/built-in-tour.ts@@ -8,13 +8,10 @@* mode without that nav row, a collapsed pane) is dropped, never guessed at.*/-import { getLocalCatalog, getLocalModelsStatus } from '@/hermes'import { runtimeTranslations } from '@/i18n'-import { localSetupEligible } from '@/lib/tips/local-cta'import { startTour, type TourResult } from '@/lib/tour'import { $interfaceMode } from '@/store/interface-mode'-import { $localModelsEnabled } from '@/store/local-models-flag'-import { $connection } from '@/store/session'+import { readLocalSetupEligibility } from '@/store/local-setup-offer'export type BuiltInTourPreset = 'quick' | 'full'@@ -61,19 +58,12 @@ function onScreen(selector: string): boolean {return width >= 4 && height >= 4}-/** Whether the model stop says this computer can run a local model. It is the- * local-setup tip's answer (the backend's catalog `fits` check, on a local- * connection, with nothing set up yet), and only where the Local Models pane- * exists to point at. */+/** Whether the model stop says this computer can run a local model: the+ * local-setup offer's answer (the backend's catalog `fits` check, on a local+ * connection, with nothing set up yet). */async function canRunLocalModel(): Promise<boolean> {- const mode = $connection.get()?.mode ?? null-- if (!$localModelsEnabled.get() || mode !== 'local') {- return false- }-- const read = Promise.all([getLocalModelsStatus(), getLocalCatalog()]).then(- ([status, catalog]) => localSetupEligible(mode, status, catalog.models),+ const read = readLocalSetupEligibility().then(+ ({ fit }) => fit !== null,() => false)diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsxindex c56ddbf953f..723e1f1266d 100644--- a/apps/desktop/src/app/chat/composer/index.tsx+++ b/apps/desktop/src/app/chat/composer/index.tsx@@ -81,6 +81,7 @@ import { useSlashCompletions } from './hooks/use-slash-completions'import { useStatusDrawer } from './hooks/use-status-drawer'import { useSessionStatusPresence } from './hooks/use-status-presence'import { shouldConvertPasteToAttachment } from './large-paste'+import { LocalSetupCard } from './local-setup-card'import { ActionBadges } from './micro-actions'import { chipTypedPathOnSpace, pathifyRefs } from './path-refs'import { QueuePanel } from './queue-panel'@@ -1499,6 +1500,7 @@ export function ChatBar({onUndone={clearDraft}readLiveText={syncDraftFromEditor}/>+ <LocalSetupCard busy={busy} guidedChat={guidedChat} /><VoiceActivity state={voiceActivityState} /><VoicePlaybackActivity />{queueEdit && editingQueuedPrompt && (diff --git a/apps/desktop/src/app/chat/composer/local-setup-card.tsx b/apps/desktop/src/app/chat/composer/local-setup-card.tsxnew file mode 100644index 00000000000..b494ef8a463--- /dev/null+++ b/apps/desktop/src/app/chat/composer/local-setup-card.tsx@@ -0,0 +1,82 @@+import { useStore } from '@nanostores/react'+import { useEffect } from 'react'++import { useSessionView } from '@/app/chat/session-view'+import { Button } from '@/components/ui/button'+import { Codicon } from '@/components/ui/codicon'+import { useI18n } from '@/i18n'+import {+ $localSetupEligibility,+ $localSetupOffer,+ dismissLocalSetupOffer,+ readLocalSetupEligibility,+ requestLocalSetupMenu+} from '@/store/local-setup-offer'+import { isHudWindow } from '@/store/windows'++import { useComposerScope } from './scope'++interface LocalSetupCardProps {+ busy: boolean+ guidedChat: boolean+}++/**+ * "This could run on your computer" strip above the input, after the first+ * finished turn once onboarding is over (store/local-setup-offer.ts). The offer+ * is about the machine, not the chat, so it sits in the main window's primary+ * composer (not tiles, not the HUD) and survives a relaunch until x or Show me.+ * Only while that session is idle: an automatic follow-up turn hides it, the+ * next idle brings it back. Offers, never hijacks: "Show me" opens this+ * composer's model menu on click, nothing moves by itself.+ */+export function LocalSetupCard({ busy, guidedChat }: LocalSetupCardProps) {+ const primary = useSessionView().kind === 'primary'+ const { target } = useComposerScope()+ const offer = useStore($localSetupOffer)+ const eligibility = useStore($localSetupEligibility)+ const fit = eligibility?.fit+ const { t } = useI18n()+ const copy = t.composer.localSetup++ // No answer yet (relaunch, or the backend just changed) or a failed one: ask again.+ useEffect(() => {+ if (offer.state === 'shown' && (!eligibility || eligibility.transient)) {+ void readLocalSetupEligibility()+ }+ }, [offer.state, eligibility])++ if (offer.state !== 'shown' || !fit || !primary || busy || guidedChat || isHudWindow()) {+ return null+ }++ return (+ <div+ className="flex items-center justify-between gap-2 rounded-lg border border-[color-mix(in_srgb,var(--dt-composer-ring)_32%,transparent)] bg-accent/18 px-2 py-1.5"+ data-slot="composer-local-setup"+ role="status"+ >+ <div className="flex min-w-0 items-center gap-2">+ <Codicon className="shrink-0 text-(--ui-accent)" name="chip" size="0.85rem" />+ <div className="min-w-0 text-[0.72rem] leading-snug">+ <div className="font-medium text-foreground">{copy.title}</div>+ <div className="truncate text-muted-foreground/88">{copy.text(fit.model.display_name)}</div>+ </div>+ </div>+ <div className="flex shrink-0 items-center gap-1">+ <Button onClick={() => requestLocalSetupMenu(target)} size="xs" type="button" variant="secondary">+ {copy.action}+ </Button>+ <Button+ aria-label={t.common.close}+ onClick={dismissLocalSetupOffer}+ size="icon-xs"+ type="button"+ variant="ghost"+ >+ <Codicon name="close" size="0.7rem" />+ </Button>+ </div>+ </div>+ )+}diff --git a/apps/desktop/src/app/chat/composer/model-pill.tsx b/apps/desktop/src/app/chat/composer/model-pill.tsxindex f152a732169..f68a66c8380 100644--- a/apps/desktop/src/app/chat/composer/model-pill.tsx+++ b/apps/desktop/src/app/chat/composer/model-pill.tsx@@ -14,6 +14,7 @@ import { useI18n } from '@/i18n'import { ChevronDown } from '@/lib/icons'import { formatModelPillLabel, providerDisplayName } from '@/lib/model-status-label'import { cn } from '@/lib/utils'+import { $localSetupMenuRequest, acceptLocalSetupOffer } from '@/store/local-setup-offer'import { $currentModelSource, setModelPickerOpen } from '@/store/session'import { useComposerModelPillLabel } from './contrib'@@ -117,6 +118,22 @@ export function ModelPill({[scope.target, disabled, hasLiveMenu])+ // The local-setup card's "Show me": open THIS composer's menu (the card names+ // its own composer), where the offer row sits on top. The offer is accepted+ // only once a menu actually opened. A click fired it, never a background event.+ useEffect(+ () =>+ $localSetupMenuRequest.listen(request => {+ if (!request || request.target !== scope.target || disabled || !hasLiveMenu) {+ return+ }++ acceptLocalSetupOffer()+ setOpen(true)+ }),+ [scope.target, disabled, hasLiveMenu]+ )+// The composer pick is sticky: a manual selection is pinned and every NEW// chat uses it instead of the Settings → Model default — silently, which has// cost users real money on a forgotten paid-model pick (#62055). Surface thediff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.tsindex 5ace4517b66..37a737328fc 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts@@ -1,6 +1,7 @@import type { BillingBlock } from '@hermes/shared'import { burstVibeHearts } from '@/components/chat/vibe-hearts'+import { $chatOnboardingThreadIds } from '@/components/onboarding-chat/assembly'import { reportFirstBuildTurnComplete } from '@/components/onboarding-chat/first-build'import { translateNow } from '@/i18n'import { coerceGatewayText, coerceThinkingText } from '@/lib/chat-runtime'@@ -10,12 +11,14 @@ import { triggerHaptic } from '@/lib/haptics'import { billingCtaLabel, clearBillingBlock, runBillingRecovery, setBillingBlock } from '@/store/billing-block'import { clearSettledClarifyRequest } from '@/store/clarify'import { setSessionCompacting } from '@/store/compaction'+import { reportLocalSetupTurnComplete } from '@/store/local-setup-offer'import { notify } from '@/store/notifications'import { flashPetActivity, markPetUnread, setPetActivity } from '@/store/pet'import { clearAllPrompts } from '@/store/prompts'import { providerWaitText, setSessionProviderWait } from '@/store/provider-wait'import { setCurrentUsage, setTurnStartedAt } from '@/store/session'import { refreshSupportedSessionControlAfterTurn } from '@/store/session-control'+import { storedSessionIdForRuntimeId } from '@/store/session-states'import { pruneFinishedSessionSubagents } from '@/store/subagents'import { clearActiveSessionTodos } from '@/store/todos'@@ -381,6 +384,19 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {// put a check-in into that session (no-op everywhere else).reportFirstBuildTurnComplete(sessionId, finalText)+ // The whole agent loop has returned: the end of a task, not a step in one.+ // Only the session on screen counts, which drops subagent mirrors (child ids).+ if (isActiveEvent) {+ const setupThreads = $chatOnboardingThreadIds.get()+ const storedId = storedSessionIdForRuntimeId(sessionId)++ reportLocalSetupTurnComplete({+ failed: payload?.status !== 'complete',+ sessionId,+ setupChat: setupThreads.includes(sessionId) || (storedId !== null && setupThreads.includes(storedId))+ })+ }+// Structured billing wall forwarded by the gateway (out of credits /// payment required) — cache it + raise a billing-specific toast.if (payload?.billing) {diff --git a/apps/desktop/src/app/shell/local-setup-menu-row.tsx b/apps/desktop/src/app/shell/local-setup-menu-row.tsxnew file mode 100644index 00000000000..c827ad55cc1--- /dev/null+++ b/apps/desktop/src/app/shell/local-setup-menu-row.tsx@@ -0,0 +1,53 @@+import { useStore } from '@nanostores/react'+import { useEffect } from 'react'++import { SETTINGS_ROUTE } from '@/app/routes'+import { Codicon } from '@/components/ui/codicon'+import { DropdownMenuItem, dropdownMenuRow, DropdownMenuSeparator } from '@/components/ui/dropdown-menu'+import { useI18n } from '@/i18n'+import { cn } from '@/lib/utils'+import { $localSetupRowFit, acceptLocalSetupOffer, refreshLocalSetupEligibility } from '@/store/local-setup-offer'+import { requestRoute } from '@/store/recovery-requests'++/**+ * "Run locally" at the top of the composer's model menu, for as long as this+ * machine qualifies and nothing is set up. The permanent home of the+ * local-setup offer: the card can be dismissed, this row stays until setup+ * completes. Every menu open re-reads eligibility (a user action, not a poll),+ * so finishing setup retires the row. A menu item, so the keyboard reaches it.+ */+export function LocalSetupMenuRow() {+ const fit = useStore($localSetupRowFit)+ const copy = useI18n().t.shell.modelMenu.localSetup++ useEffect(() => {+ void refreshLocalSetupEligibility()+ }, [])++ if (!fit) {+ return null+ }++ return (+ <>+ <DropdownMenuItem+ className={cn(dropdownMenuRow, 'items-start gap-2 py-1.5')}+ data-slot="model-menu-local-setup"+ onSelect={() => {+ acceptLocalSetupOffer()+ requestRoute(`${SETTINGS_ROUTE}?tab=providers&pview=local`)+ }}+ >+ <Codicon className="mt-0.5 shrink-0 text-(--ui-accent)" name="chip" size="0.8rem" />+ <span className="min-w-0 flex-1 leading-snug">+ <span className="block font-medium text-foreground">{copy.title}</span>+ <span className="block truncate text-(--ui-text-tertiary)">+ {copy.text(fit.model.display_name, fit.model.size_label)}+ </span>+ </span>+ <span className="shrink-0 self-center text-(--ui-accent)">{copy.action}</span>+ </DropdownMenuItem>+ <DropdownMenuSeparator className="mx-0" />+ </>+ )+}diff --git a/apps/desktop/src/app/shell/model-catalog-menu.tsx b/apps/desktop/src/app/shell/model-catalog-menu.tsxindex ceb4dbc2798..0229b8c8348 100644--- a/apps/desktop/src/app/shell/model-catalog-menu.tsx+++ b/apps/desktop/src/app/shell/model-catalog-menu.tsx@@ -158,6 +158,8 @@ interface ModelCatalogMenuProps {controller: ModelMenuController/** Rows appended under the catalog (Refresh Models, Edit Models, …). */footer?: ReactNode+ /** Rows above the search, outside the keyboard list (the local-setup offer). */+ header?: ReactNodegateway?: HermesGateway/** Owner-routed RPC for catalog reads. Preferred over `gateway.request` so* a tile's menu queries the session owner's backend, not chrome's. */@@ -191,6 +193,7 @@ interface ProviderGroup {export function ModelCatalogMenu({controller,footer,+ header,gateway,includeMoa = false,ownerConnectionId,@@ -591,6 +594,7 @@ export function ModelCatalogMenu({return (<>+ {header}<DropdownMenuSearcharia-label={copy.search}onKeyDown={event => {diff --git a/apps/desktop/src/app/shell/model-menu-panel.tsx b/apps/desktop/src/app/shell/model-menu-panel.tsxindex d8a4ca569bf..337e1e3f53d 100644--- a/apps/desktop/src/app/shell/model-menu-panel.tsx+++ b/apps/desktop/src/app/shell/model-menu-panel.tsx@@ -11,6 +11,7 @@ import { modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'import { cn } from '@/lib/utils'import { $currentModelSource } from '@/store/session'+import { LocalSetupMenuRow } from './local-setup-menu-row'import { ModelCatalogMenu } from './model-catalog-menu'import { type ModelMenuHostProps, useModelMenuController } from './use-model-menu-controller'@@ -101,6 +102,7 @@ export function ModelMenuPanel({ onFollowDefaultModel, ...props }: ModelMenuPane</>}gateway={gateway}+ header={<LocalSetupMenuRow />}includeMoaownerConnectionId={ownerConnectionId}profile={profile}diff --git a/apps/desktop/src/components/onboarding-chat/intro.ts b/apps/desktop/src/components/onboarding-chat/intro.tsindex 08a216c2754..e9f0755674e 100644--- a/apps/desktop/src/components/onboarding-chat/intro.ts+++ b/apps/desktop/src/components/onboarding-chat/intro.ts@@ -4,7 +4,6 @@ import { DEMO_LAYOUT_ID } from '@/app/contrib/layout-presets'import { PANE_TOGGLE_REVEAL_EVENT } from '@/components/pane-shell'import { $activePresetId } from '@/components/pane-shell/tree/store'import { TIP_CATALOG } from '@/lib/tips/catalog'-import { LOCAL_SETUP_TIP_ID } from '@/lib/tips/local-cta'import { $sidebarOpen, CHAT_SIDEBAR_PANE_ID } from '@/store/layout'import { notify } from '@/store/notifications'import { $onboardingGate, $setupProfileName, completeGuide, leaveGuide, skipGuide } from '@/store/onboarding-gate'@@ -123,8 +122,8 @@ export function skipIntro(): void {notify({ kind: 'info', message: 'Switching you over to your default profile' })skipGuide()- // Skip stops the rest of the first run: the tutorial tips and the local-model tip.- retireTips([...TIP_CATALOG.map(tip => tip.id), LOCAL_SETUP_TIP_ID])+ // Skip stops the tutorial tips. The local-setup offer still arms: its card waits for a finished task.+ retireTips(TIP_CATALOG.map(tip => tip.id))selectProfile(launch?.profile ?? 'default')}diff --git a/apps/desktop/src/components/onboarding-chat/signpost.ts b/apps/desktop/src/components/onboarding-chat/signpost.tsindex 912e444152d..b95f1418b4c 100644--- a/apps/desktop/src/components/onboarding-chat/signpost.ts+++ b/apps/desktop/src/components/onboarding-chat/signpost.ts@@ -1,8 +1,17 @@import { translateNow } from '@/i18n'+import { readLocalSetupEligibility } from '@/store/local-setup-offer'+/** Tour handles (`data-tour`). A targets scan returns these same selectors, so a curated step and a+ * model-driven step point at the same node. */const RAIL = '[data-tour="profile-rail"]'const SESSIONS = '[data-tour="sessions-sidebar"]'+const MODEL_PILL = '[data-tour="model-pill"]'+/** Eligibility is one status + catalog read, usually already cached. The tour does not wait longer than this. */+const LOCAL_FIT_WAIT_MS = 1500++/** Waits for a visible node. The profile rail mounts a render or two after the handoff switches profiles, and+ * the tour engine returns a no-match for a selector that is not in the DOM yet. Returns false on timeout. */async function waitFor(selector: string, timeoutMs = 6000): Promise<boolean> {const deadline = Date.now() + timeoutMs@@ -23,13 +32,22 @@ async function waitFor(selector: string, timeoutMs = 6000): Promise<boolean> {return false}+/** The caller does not await this, so the tour does not delay the handoff. */export async function showHandoffTour(): Promise<void> {if (!(await waitFor(RAIL))) {return}- const sessionsVisible = await waitFor(SESSIONS, 1500)- const copy = (key: string) => translateNow(`handoffTour.${key}`)+ const [sessionsVisible, localModel, pillVisible] = await Promise.all([+ waitFor(SESSIONS, 1500),+ localStepModel(),+ waitFor(MODEL_PILL, 1500)+ ])++ const localVisible = localModel !== null && pillVisible+ const copy = (key: string, ...args: unknown[]) => translateNow(`handoffTour.${key}`, ...args)+ // Imported here instead of at the top: this module is reachable from the boot path through the handoff+ // hook, and run-tour.ts keeps driver.js and its stylesheet out of that path.const { startTour } = await import('@/lib/tour')await startTour([@@ -37,6 +55,34 @@ export async function showHandoffTour(): Promise<void> {...(sessionsVisible? [{ selector: SESSIONS, side: 'right' as const, text: copy('sessionsText'), title: copy('sessionsTitle') }]: []),- { accent: true, selector: RAIL, side: 'right', text: copy('stayText'), title: copy('stayTitle') }+ { accent: true, selector: RAIL, side: 'right', text: copy('stayText'), title: copy('stayTitle') },+ ...(localVisible+ ? [+ {+ accent: true,+ selector: MODEL_PILL,+ side: 'top' as const,+ text: copy('localText', localModel),+ title: copy('localTitle')+ }+ ]+ : [])])}++/** Display name of the model this machine can run, or null when it doesn't qualify or the read is slow. */+async function localStepModel(): Promise<null | string> {+ let timer: ReturnType<typeof setTimeout> | undefined++ const timeout = new Promise<null>(resolve => {+ timer = setTimeout(() => resolve(null), LOCAL_FIT_WAIT_MS)+ })++ const fit = readLocalSetupEligibility().then(({ fit }) => fit?.model.display_name ?? null)++ try {+ return await Promise.race([fit, timeout])+ } finally {+ clearTimeout(timer)+ }+}diff --git a/apps/desktop/src/components/tips/local-runtime-update-offer.ts b/apps/desktop/src/components/tips/local-runtime-update-offer.tsindex aa0903119a6..2d472ed9e87 100644--- a/apps/desktop/src/components/tips/local-runtime-update-offer.ts+++ b/apps/desktop/src/components/tips/local-runtime-update-offer.ts@@ -1,7 +1,7 @@import { getLocalModelsJobs, getLocalModelsStatus } from '@/hermes'import type { Translations } from '@/i18n/types'import { queryClient } from '@/lib/query-client'-import { localSetupDue } from '@/lib/tips/local-cta'+import { localTipDue } from '@/lib/tips/local-cta'import { $activeGatewayRoute } from '@/store/gateway'import { $localModelsEnabled } from '@/store/local-models-flag'import { localRuntimeInstallBusy, startLocalRuntimeInstall } from '@/store/local-runtime-jobs'@@ -97,7 +97,7 @@ export function offerLocalRuntimeUpdateTip(copy: Translations['tips'], openLocalconst tipId = `local-runtime-update:${status.configured_tag}`- if ($retiredTips.get().includes(tipId) || !localSetupDue(Date.now(), $tipShownAt.get()[tipId])) {+ if ($retiredTips.get().includes(tipId) || !localTipDue(Date.now(), $tipShownAt.get()[tipId])) {return false}diff --git a/apps/desktop/src/components/tips/local-setup-offer.test.ts b/apps/desktop/src/components/tips/local-setup-offer.test.tsdeleted file mode 100644index 251873d687b..00000000000--- a/apps/desktop/src/components/tips/local-setup-offer.test.ts+++ /dev/null@@ -1,144 +0,0 @@-/**- * The campaign offer against the live stores: eligibility fetch, the showTip- * wiring (button included), retirement, the reshow clock, and the cursor- * guard that keeps a campaign showing from restarting the rotation's walk.- */--import { cleanup } from '@testing-library/react'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'--const getLocalModelsStatus = vi.fn()-const getLocalCatalog = vi.fn()--vi.mock('@/hermes', () => ({- getLocalCatalog: (...args: unknown[]) => getLocalCatalog(...args),- getLocalModelsStatus: (...args: unknown[]) => getLocalModelsStatus(...args)-}))--import { en } from '@/i18n/en'-import { LOCAL_SETUP_TIP_ID } from '@/lib/tips/local-cta'-import { $localModelsEnabled } from '@/store/local-models-flag'-import { $connection } from '@/store/session'-import { $activeTip, $lastTipId, $retiredTips, $tipShownAt } from '@/store/tips'--import { offerLocalSetupTip, resetLocalSetupOfferCache } from './local-setup-offer'--function primeEligibleBackend() {- getLocalModelsStatus.mockResolvedValue({ models: [], runtime_installed: false })- getLocalCatalog.mockResolvedValue({ models: [{ fits: true, id: 'qwen3.8-27b' }] })-}--async function flushFetch() {- await Promise.resolve()- await Promise.resolve()- await Promise.resolve()-}--describe('offerLocalSetupTip', () => {- beforeEach(() => {- resetLocalSetupOfferCache()- // The campaign ships behind --local like every local-models surface.- $localModelsEnabled.set(true)- $activeTip.set(null)- $retiredTips.set([])- $tipShownAt.set({})- $lastTipId.set(null)- $connection.set({ mode: 'local' } as never)- getLocalModelsStatus.mockReset()- getLocalCatalog.mockReset()- })-- afterEach(() => {- cleanup()- })-- it('holds the first quiet moment while the read flies, then shows on the next', async () => {- primeEligibleBackend()-- const openLocalModels = vi.fn()-- // First offer: fetch in flight — the moment is HELD (true, so the- // rotation's walk cannot take it and arm the cooldown ahead of the- // campaign), but nothing is on screen yet.- expect(offerLocalSetupTip(en.tips, openLocalModels)).toBe(true)- expect($activeTip.get()).toBeNull()- await flushFetch()-- // Second offer: cached yes — bubble goes up with the CTA wired.- expect(offerLocalSetupTip(en.tips, openLocalModels)).toBe(true)-- const tip = $activeTip.get()-- expect(tip?.tipId).toBe(LOCAL_SETUP_TIP_ID)- expect(tip?.action?.label).toBe(en.tips.items['local-setup'].action)-- tip?.action?.onSelect()- expect(openLocalModels).toHaveBeenCalledTimes(1)- // The CTA closes the bubble on its way to the pane.- expect($activeTip.get()).toBeNull()- })-- it('never restarts the rotation walk: the campaign id stays out of the cursor', async () => {- primeEligibleBackend()- $lastTipId.set('cron')-- offerLocalSetupTip(en.tips, vi.fn())- await flushFetch()- offerLocalSetupTip(en.tips, vi.fn())-- expect($activeTip.get()?.tipId).toBe(LOCAL_SETUP_TIP_ID)- expect($lastTipId.get()).toBe('cron')- })-- it('stays quiet on an ineligible machine without refetching', async () => {- getLocalModelsStatus.mockResolvedValue({ models: [{ id: 'staged' }], runtime_installed: true })- getLocalCatalog.mockResolvedValue({ models: [{ fits: true, id: 'qwen3.8-27b' }] })-- offerLocalSetupTip(en.tips, vi.fn())- await flushFetch()-- expect(offerLocalSetupTip(en.tips, vi.fn())).toBe(false)- expect($activeTip.get()).toBeNull()- expect(getLocalModelsStatus).toHaveBeenCalledTimes(1)- })-- it('honors the ✕ forever and the ignored-bubble clock for a week', async () => {- primeEligibleBackend()-- $retiredTips.set([LOCAL_SETUP_TIP_ID])- expect(offerLocalSetupTip(en.tips, vi.fn())).toBe(false)- expect(getLocalModelsStatus).not.toHaveBeenCalled()-- $retiredTips.set([])- $tipShownAt.set({ [LOCAL_SETUP_TIP_ID]: Date.now() - 60_000 })- expect(offerLocalSetupTip(en.tips, vi.fn())).toBe(false)- expect(getLocalModelsStatus).not.toHaveBeenCalled()- })-- it('asks nothing of a remote backend', () => {- $connection.set({ mode: 'remote' } as never)-- expect(offerLocalSetupTip(en.tips, vi.fn())).toBe(false)- expect(getLocalModelsStatus).not.toHaveBeenCalled()- })-- it('never runs without the --local launch flag (strict), even on an eligible machine', () => {- $localModelsEnabled.set(false)-- expect(offerLocalSetupTip(en.tips, vi.fn())).toBe(false)- // Declined before any read: no fetch, no held moment, no cooldown spent.- expect(getLocalModelsStatus).not.toHaveBeenCalled()- expect($activeTip.get()).toBeNull()- })-- it('a failed read stands down for the session instead of retrying', async () => {- getLocalModelsStatus.mockRejectedValue(new Error('backend gone'))- getLocalCatalog.mockRejectedValue(new Error('backend gone'))-- offerLocalSetupTip(en.tips, vi.fn())- await flushFetch()-- expect(offerLocalSetupTip(en.tips, vi.fn())).toBe(false)- expect(getLocalModelsStatus).toHaveBeenCalledTimes(1)- })-})diff --git a/apps/desktop/src/components/tips/local-setup-offer.ts b/apps/desktop/src/components/tips/local-setup-offer.tsdeleted file mode 100644index e8abdf2a821..00000000000--- a/apps/desktop/src/components/tips/local-setup-offer.ts+++ /dev/null@@ -1,126 +0,0 @@-/**- * The local-setup campaign: one bubble on the model pill for machines that- * could run local models and haven't set them up.- *- * Not a rotation tip — a campaign the rotation CONSULTS first at each quiet- * due moment (use-tip-rotation.ts): conditional (most machines qualify or- * don't, permanently), actionable (it carries the one button a tip may- * have), and perishable (setting up local models — or the ✕ — ends it).- * A live "your GPU can run this, free and private" outranks the walk's- * "the model name is a button" whenever both are true, and an ignored- * bubble may return in a week rather than walking on forever.- *- * Eligibility is fetched, not assumed: the backend's own fit check (the- * same catalog `fits` the Local Models pane prices its hero with) decides- * whether this machine qualifies. Reads are lazy — nothing polls for a- * bubble. The first quiet due moment kicks one status+catalog read and- * holds the turn (no walk tip may spend the cooldown ahead of a pending- * campaign); the cached answer serves every later one. Completing- * setup flips the next read to ineligible, so the campaign retires itself- * without bookkeeping — and the cache dies with a connection change,- * because eligibility is a fact about the backend's machine.- */--import { getLocalCatalog, getLocalModelsStatus } from '@/hermes'-import type { Translations } from '@/i18n/types'-import { LOCAL_SETUP_TIP_ID, localSetupDue, localSetupEligible } from '@/lib/tips/local-cta'-import { $localModelsEnabled } from '@/store/local-models-flag'-import { $connection } from '@/store/session'-import { $retiredTips, $tipShownAt, dismissTip, showTip } from '@/store/tips'--/** The pill the bubble points at — the same handle the rotation's- * model-switch tip uses, so the two can never drift to different anchors. */-const MODEL_PILL_TARGETS = ['[data-tour="model-pill"]'] as const--let eligibilityCache: { eligible: boolean } | null = null-let eligibilityInFlight = false-let boundToConnection = false--/** Reset the session cache — tests only. */-export function resetLocalSetupOfferCache(): void {- eligibilityCache = null- eligibilityInFlight = false-}--/**- * Offer the campaign the current quiet moment. True = it put its bubble up- * and the moment is spent; false = the rotation's walk may have it.- */-export function offerLocalSetupTip(copy: Translations['tips'], openLocalModels: () => void): boolean {- // Local models ship behind the --local launch flag; without it there is- // no Local Models pane for the button to open, so the campaign never runs- // (and never spends a status/catalog read).- if (!$localModelsEnabled.get()) {- return false- }-- if ($retiredTips.get().includes(LOCAL_SETUP_TIP_ID)) {- return false- }-- if (!localSetupDue(Date.now(), $tipShownAt.get()[LOCAL_SETUP_TIP_ID])) {- return false- }-- // Local backends only: on a remote connection (cloud resolves to remote)- // the models would run on the far machine, and "stays on your computer"- // would be promising someone else's computer. Checked before the cache so- // a re-home mid-session can't serve a stale yes.- if (($connection.get()?.mode ?? null) !== 'local') {- return false- }-- if (!boundToConnection) {- boundToConnection = true- $connection.listen(() => resetLocalSetupOfferCache())- }-- if (!eligibilityCache) {- if (!eligibilityInFlight) {- eligibilityInFlight = true-- void Promise.all([getLocalModelsStatus(), getLocalCatalog()])- .then(([status, catalog]) => {- eligibilityCache = {- eligible: localSetupEligible($connection.get()?.mode ?? null, status, catalog.models)- }- })- .catch(() => {- // No backend answer, no campaign this session. The next launch —- // or the next connection — asks again.- eligibilityCache = { eligible: false }- })- .finally(() => {- eligibilityInFlight = false- })- }-- // Hold the moment while the read flies: nothing shows and no cooldown- // arms, so the next tick answers from the cache. Handing this moment to- // the rotation instead would put a walk tip up first and park the- // campaign behind the six-hour cooldown — the exact inversion of the- // priority. Costs an ineligible machine one 30s tick, once per session.- return true- }-- if (!eligibilityCache.eligible) {- return false- }-- showTip({- action: {- label: copy.items['local-setup'].action,- onSelect: () => {- dismissTip()- openLocalModels()- }- },- side: 'top',- targets: MODEL_PILL_TARGETS,- text: copy.items['local-setup'].text,- tipId: LOCAL_SETUP_TIP_ID,- title: copy.items['local-setup'].title- })-- return true-}diff --git a/apps/desktop/src/components/tips/tutorial-lifetime.test.tsx b/apps/desktop/src/components/tips/tutorial-lifetime.test.tsxindex 462a6884eb7..92d90d1f8db 100644--- a/apps/desktop/src/components/tips/tutorial-lifetime.test.tsx+++ b/apps/desktop/src/components/tips/tutorial-lifetime.test.tsx@@ -22,7 +22,6 @@ vi.mock('@/store/session', async () => {return { $awaitingResponse: atom(false), $busy: atom(false) }})vi.mock('react-router', () => ({ useNavigate: () => vi.fn() }))-vi.mock('./local-setup-offer', () => ({ offerLocalSetupTip: () => false }))vi.mock('./local-runtime-update-offer', () => ({ offerLocalRuntimeUpdateTip: () => false }))import { en } from '@/i18n/en'diff --git a/apps/desktop/src/components/tips/use-tip-rotation.test.tsx b/apps/desktop/src/components/tips/use-tip-rotation.test.tsxindex c5bbae2e220..906e90e9093 100644--- a/apps/desktop/src/components/tips/use-tip-rotation.test.tsx+++ b/apps/desktop/src/components/tips/use-tip-rotation.test.tsx@@ -7,10 +7,8 @@ import { $localModelsEnabled } from '@/store/local-models-flag'import { $awaitingResponse, $busy, $connection } from '@/store/session'import { $activeTip, $nextTipAt, $retiredTips, $tipsEnabled, $tipShownAt } from '@/store/tips'-import { offerLocalSetupTip } from './local-setup-offer'import { useTipRotation } from './use-tip-rotation'-vi.mock('./local-setup-offer', () => ({ offerLocalSetupTip: vi.fn(() => false) }))vi.mock('@/store/tutorial-lifetime', () => ({ checkTutorialLifetime: vi.fn() }))const reply = async (request: { path: string }) =>@@ -69,7 +67,6 @@ it('offers the update at the first quiet moment despite tutorial settling and coawait vi.advanceTimersByTimeAsync(2_000)})expect($activeTip.get()?.action?.label).toBe('Update now')- expect(offerLocalSetupTip).not.toHaveBeenCalled()expect(api.mock.calls.some(([request]) => 'method' in request && request.method === 'POST')).toBe(false)})@@ -179,34 +176,6 @@ it.each(['flag-off', 'tips-off', 'remote'])('does not read or offer when %s', asexpect($activeTip.get()).toBeNull()})-it('keeps tutorial settling and cooldown when no engine update is available', async () => {- api.mockImplementation(async request =>- request.path.endsWith('/jobs')- ? { jobs: [] }- : {- enabled: true,- runtime_installed: true,- update_available: false,- configured_tag: 'target'- }- )- mount()- await act(async () => {- await vi.advanceTimersByTimeAsync(4 * 60_000)- })- expect(offerLocalSetupTip).not.toHaveBeenCalled()- await act(async () => {- await vi.advanceTimersByTimeAsync(60_000)- })- expect(offerLocalSetupTip).toHaveBeenCalledTimes(1)- $nextTipAt.set(Date.now() + 6 * 60 * 60_000)- $activeTip.set(null)- await act(async () => {- await vi.advanceTimersByTimeAsync(60_000)- })- expect(offerLocalSetupTip).toHaveBeenCalledTimes(1)-})-it('stops the fast check when the host unmounts', async () => {api.mockImplementation(async request =>request.path.endsWith('/jobs')diff --git a/apps/desktop/src/components/tips/use-tip-rotation.ts b/apps/desktop/src/components/tips/use-tip-rotation.tsindex 3125432e59c..0c3ba761879 100644--- a/apps/desktop/src/components/tips/use-tip-rotation.ts+++ b/apps/desktop/src/components/tips/use-tip-rotation.ts@@ -35,7 +35,6 @@ import { $activeTip, $lastTipId, $nextTipAt, $retiredTips, $tipsEnabled, $tipShoimport { checkTutorialLifetime } from '@/store/tutorial-lifetime'import { offerLocalRuntimeUpdateTip } from './local-runtime-update-offer'-import { offerLocalSetupTip } from './local-setup-offer'const TICK_MS = 30_000const UPDATE_TICK_MS = 1_000@@ -119,11 +118,11 @@ export function useTipRotation(copy: Translations['tips']) {return}- // Campaigns outrank the walk: a conditional, actionable tip that is- // live right now (the local-setup CTA) says something about THIS- // machine, which beats the catalog's standing introduction. It shares- // the cooldown, so taking the moment still costs it the usual hours.- if (offerUpdate() || offerLocalSetupTip(copy, openLocalModels)) {+ // The engine-update campaign outranks the walk: it says something about+ // THIS machine. It shares the cooldown, so taking the moment still costs+ // it the usual hours. (The local-setup offer left the rotation: it runs on+ // events in store/local-setup-offer.ts, not on this clock.)+ if (offerUpdate()) {return}diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 8086e55e056..7d54f1b4de3 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -2288,6 +2288,19 @@ export const ar = defineLocale({ageMin: 'دقيقة'}},+ handoffTour: {+ profileTitle: 'مهمتك الأولى تعمل على الملف الشخصي الافتراضي',+ profileText:+ 'يبدّل هذا الشريط بين الملفات الشخصية. المضاء الآن هو الافتراضي، حيث توجد جلسة المهمة. والآخر هو ملف الإعداد، حيث توجد محادثة الترحيب.',+ sessionsTitle: 'لكل ملف شخصي جلساته الخاصة',+ sessionsText:+ 'هذه القائمة تخص الملف الافتراضي. «جلسة جديدة» تبدأ جلسة على الملف المحدد. بدّل الملف من الشريط فتتغير القائمة معه.',+ stayTitle: 'Hermes على بُعد نقرة',+ stayText: 'انتقل إلى ملف الإعداد وافتح «مرحبًا بك في Hermes» متى احتجت إلى مساعدة. ستبقى هناك.',+ localTitle: 'يمكن لهذا الجهاز تشغيل النماذج محليًا',+ localText: (model: string) =>+ `${model} يناسب أجهزتك. يعمل مجانًا، ولا تغادر المحادثات جهازك. اختره من هنا، من قائمة النماذج، متى شئت.`+ },composer: {message: 'الرسالة',wakingProfile: profile => `جار إيقاظ ${profile}`,@@ -2420,6 +2433,11 @@ export const ar = defineLocale({editingQueuedInComposer: 'جار تحرير رسالة في الطابور',restoredDraftNotice: 'تمت استعادة رسالتك غير المُرسلة',restoredDraftUndo: 'تراجع',+ localSetup: {+ title: 'يمكن تشغيل هذا على جهازك',+ text: (model: string) => `${model} يناسب هذا الجهاز. مجاني، وتبقى المحادثات على جهازك.`,+ action: 'أرني'+ },queueEdit: 'تحرير الرسالة المجدولة',queueExpand: 'توسيع',queueCollapse: 'طي',@@ -2934,7 +2952,12 @@ export const ar = defineLocale({free: 'مجاني',cacheRead: 'قراءة من الذاكرة المؤقتة',priceTitle: (input: string, output: string, cache: string) =>- `الإدخال ${input}/Mtok · الإخراج ${output}/Mtok` + (cache ? ` · قراءة من الذاكرة المؤقتة ${cache}/Mtok` : '')+ `الإدخال ${input}/Mtok · الإخراج ${output}/Mtok` + (cache ? ` · قراءة من الذاكرة المؤقتة ${cache}/Mtok` : ''),+ localSetup: {+ title: 'تشغيل محلي · مجاني وخاص',+ text: (model: string, size: string) => `${model} يناسب هذا الجهاز · تنزيل ${size}`,+ action: 'إعداد'+ }},modelOptions: {noOptions: 'لا توجد خيارات لهذا النموذج',@@ -3747,11 +3770,6 @@ export const ar = defineLocale({text: 'حدّث المحرك الذي يشغّل نماذجك المحلية. قد تنقطع الطلبات المحلية الجارية.',action: 'التحديث الآن'},- 'local-setup': {- title: 'هذا الجهاز يمكنه تشغيل النماذج محليًا',- text: 'عتادك قادر على تشغيل نموذج محلي. تبقى محادثاتك على جهازك ولا تكلف شيئًا.',- action: 'إعداد الآن'- },'right-pane': {title: 'لوحة العمل',text: 'الملفات والطرفية والمراجعة والمتصفح المدمج تتشارك اللوحة الجانبية.'diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.tsindex c6532709541..a08b2fbca01 100644--- a/apps/desktop/src/i18n/de.ts+++ b/apps/desktop/src/i18n/de.ts@@ -4321,6 +4321,11 @@ export const deOverrides = {editingQueuedInComposer: 'Bearbeitet eingereihten Turn im Composer',restoredDraftNotice: 'Ihre nicht gesendete Nachricht wurde wiederhergestellt',restoredDraftUndo: 'Rückgängig',+ localSetup: {+ title: 'Das könnte auf Ihrem Computer laufen',+ text: (model: string) => `${model} passt auf diesen Rechner. Kostenlos, und Chats bleiben auf Ihrem Computer.`,+ action: 'Zeigen'+ },queueEdit: 'Bearbeiten',queueExpand: 'Ausklappen',queueCollapse: 'Einklappen',@@ -4734,6 +4739,9 @@ export const deOverrides = {}},handoffTour: {+ localTitle: 'Dieser Rechner kann Modelle lokal ausführen',+ localText: (model: string) =>+ `${model} passt zu Ihrer Hardware. Es läuft kostenlos, und Chats verlassen Ihren Computer nie. Wählen Sie es jederzeit hier im Modellmenü.`,profileTitle: 'Ihre erste Aufgabe läuft im Standardprofil',profileText:'Diese Leiste wechselt die Profile. Das jetzt hervorgehobene ist „Standard", wo die Aufgaben-Session lebt. Das andere ist das Einrichtungsprofil, wo der Willkommens-Chat lebt.',@@ -5038,7 +5046,12 @@ export const deOverrides = {free: 'kostenlos',cacheRead: 'Cache-Lesung',priceTitle: (input: string, output: string, cache: string) =>- `Eingabe ${input}/Mtok · Ausgabe ${output}/Mtok` + (cache ? ` · Cache-Lesung ${cache}/Mtok` : '')+ `Eingabe ${input}/Mtok · Ausgabe ${output}/Mtok` + (cache ? ` · Cache-Lesung ${cache}/Mtok` : ''),+ localSetup: {+ title: 'Lokal ausführen · kostenlos, privat',+ text: (model: string, size: string) => `${model} passt auf diesen Rechner · ${size} Download`,+ action: 'Einrichten'+ }},modelOptions: {noOptions: 'Keine Optionen für dieses Modell',@@ -6155,11 +6168,6 @@ export const deOverrides = {text: 'Aktualisieren Sie die Engine, die Ihre lokalen Modelle ausführt. Laufende lokale Anfragen können unterbrochen werden.',action: 'Jetzt aktualisieren'},- 'local-setup': {- title: 'Dieses Gerät kann Modelle lokal ausführen',- text: 'Ihre Hardware kann ein lokales Modell ausführen. Chats bleiben auf Ihrem Computer und kosten nichts.',- action: 'Einrichten'- },'right-pane': {title: 'Der Arbeitsbereich',text: 'Dateien, Terminal, Review und der In-App-Browser teilen sich die rechte Seite.'diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex dce02b02749..4f239d04771 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3942,6 +3942,11 @@ export const en: Translations = {editingQueuedInComposer: 'Editing queued turn in composer',restoredDraftNotice: 'Restored your unsent message',restoredDraftUndo: 'Undo',+ localSetup: {+ title: 'This could run on your computer',+ text: (model: string) => `${model} fits this machine. Free, and chats stay on your computer.`,+ action: 'Show me'+ },queueEdit: 'Edit',queueExpand: 'Expand',queueCollapse: 'Collapse',@@ -4357,7 +4362,10 @@ export const en: Translations = {sessionsText:'This list belongs to the default profile. New session starts one on whichever profile is selected. Switch profiles on the rail and the list changes with it.',stayTitle: 'Hermes is one click away',- stayText: 'Switch to the setup profile and open Welcome to Hermes whenever you want a hand. It stays there.'+ stayText: 'Switch to the setup profile and open Welcome to Hermes whenever you want a hand. It stays there.',+ localTitle: 'This machine can run models locally',+ localText: (model: string) =>+ `${model} fits your hardware. It runs free, and chats never leave your computer. Pick it here, in the model menu, whenever you want.`},appTour: {sessions: { title: 'Your chats', text: 'Every conversation lives here. Search, pin or reopen any of them.' },@@ -4655,7 +4663,12 @@ export const en: Translations = {free: 'free',cacheRead: 'cached read',priceTitle: (input: string, output: string, cache: string) =>- `Input ${input}/Mtok · Output ${output}/Mtok` + (cache ? ` · Cached read ${cache}/Mtok` : '')+ `Input ${input}/Mtok · Output ${output}/Mtok` + (cache ? ` · Cached read ${cache}/Mtok` : ''),+ localSetup: {+ title: 'Run locally · free, private',+ text: (model: string, size: string) => `${model} fits this machine · ${size} download`,+ action: 'Set up'+ }},modelOptions: {noOptions: 'No options for this model',@@ -5682,11 +5695,6 @@ export const en: Translations = {text: 'Update the engine that runs your local models. Active local requests may be interrupted.',action: 'Update now'},- 'local-setup': {- title: 'This machine can run models locally',- text: 'Your hardware can serve a local model. Chats stay on your computer and cost nothing.',- action: 'Set it up'- },'right-pane': {title: 'The working pane',text: 'Files, terminal, review and the in-app browser share the right side.'diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.tsindex 231b30a539d..c3a3488bb26 100644--- a/apps/desktop/src/i18n/es.ts+++ b/apps/desktop/src/i18n/es.ts@@ -4314,6 +4314,11 @@ export const esOverrides = {editingQueuedInComposer: 'Editando turno en cola en el compositor',restoredDraftNotice: 'Se restauró tu mensaje sin enviar',restoredDraftUndo: 'Deshacer',+ localSetup: {+ title: 'Esto podría ejecutarse en este equipo',+ text: (model: string) => `${model} cabe en este equipo. Gratis, y los chats se quedan en este equipo.`,+ action: 'Muéstrame'+ },queueEdit: 'Editar',queueExpand: 'Expandir',queueCollapse: 'Contraer',@@ -4728,6 +4733,9 @@ export const esOverrides = {}},handoffTour: {+ localTitle: 'Este equipo puede ejecutar modelos localmente',+ localText: (model: string) =>+ `${model} encaja con tu hardware. Funciona gratis y los chats nunca salen de este equipo. Elígelo aquí, en el menú de modelos, cuando quieras.`,profileTitle: 'Tu primera tarea se ejecuta en el perfil predeterminado',profileText:'Esta barra cambia de perfil. El que está iluminado ahora es el predeterminado, donde está la sesión de la tarea. El otro es el perfil de configuración, donde está el chat de bienvenida.',@@ -5030,7 +5038,12 @@ export const esOverrides = {free: 'gratis',cacheRead: 'lectura en caché',priceTitle: (input: string, output: string, cache: string) =>- `Entrada ${input}/Mtok · Salida ${output}/Mtok` + (cache ? ` · Lectura en caché ${cache}/Mtok` : '')+ `Entrada ${input}/Mtok · Salida ${output}/Mtok` + (cache ? ` · Lectura en caché ${cache}/Mtok` : ''),+ localSetup: {+ title: 'Ejecutar en local · gratis, privado',+ text: (model: string, size: string) => `${model} cabe en este equipo · descarga de ${size}`,+ action: 'Configurar'+ }},modelOptions: {noOptions: 'No hay opciones para este modelo',@@ -6147,11 +6160,6 @@ export const esOverrides = {text: 'Actualiza el motor que ejecuta tus modelos locales. Las solicitudes locales activas pueden interrumpirse.',action: 'Actualizar ahora'},- 'local-setup': {- title: 'Este equipo puede ejecutar modelos localmente',- text: 'Tu hardware puede servir un modelo local. Los chats se quedan en tu equipo y no cuestan nada.',- action: 'Configurarlo'- },'right-pane': {title: 'El panel de trabajo',text: 'Archivos, terminal, revisión y el navegador integrado comparten el lado derecho.'diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.tsindex ddfbd1102d9..fb62f736f46 100644--- a/apps/desktop/src/i18n/fr.ts+++ b/apps/desktop/src/i18n/fr.ts@@ -4334,6 +4334,12 @@ export const frOverrides = {editingQueuedInComposer: "Modification du tour en file d'attente dans le compositeur",restoredDraftNotice: 'Votre message non envoyé a été restauré',restoredDraftUndo: 'Annuler',+ localSetup: {+ title: 'Ceci pourrait tourner sur votre ordinateur',+ text: (model: string) =>+ `${model} tient sur cette machine. Gratuit, et les conversations restent sur votre ordinateur.`,+ action: 'Montrez-moi'+ },queueEdit: 'Modifier',queueExpand: 'Déplier',queueCollapse: 'Replier',@@ -4749,6 +4755,9 @@ export const frOverrides = {}},handoffTour: {+ localTitle: 'Cette machine peut exécuter des modèles en local',+ localText: (model: string) =>+ `${model} convient à votre matériel. Il tourne gratuitement et les conversations ne quittent jamais votre ordinateur. Choisissez-le ici, dans le menu des modèles, quand vous voulez.`,profileTitle: 'Votre première tâche utilise le profil par défaut',profileText:"Cette barre change de profil. Celui qui est éclairé est le profil par défaut, où se trouve la session de la tâche. L'autre est le profil de configuration, où se trouve la conversation de bienvenue.",@@ -5052,7 +5061,12 @@ export const frOverrides = {free: 'gratuit',cacheRead: 'lecture en cache',priceTitle: (input: string, output: string, cache: string) =>- `Entrée ${input}/Mtok · Sortie ${output}/Mtok` + (cache ? ` · Lecture en cache ${cache}/Mtok` : '')+ `Entrée ${input}/Mtok · Sortie ${output}/Mtok` + (cache ? ` · Lecture en cache ${cache}/Mtok` : ''),+ localSetup: {+ title: 'Exécuter en local · gratuit, privé',+ text: (model: string, size: string) => `${model} tient sur cette machine · téléchargement de ${size}`,+ action: 'Configurer'+ }},modelOptions: {noOptions: 'Aucune option pour ce modèle',@@ -6169,11 +6183,6 @@ export const frOverrides = {text: 'Mettez à jour le moteur qui exécute vos modèles locaux. Les requêtes locales actives peuvent être interrompues.',action: 'Mettre à jour maintenant'},- 'local-setup': {- title: 'Cette machine peut exécuter des modèles en local',- text: 'Votre matériel peut servir un modèle local. Les conversations restent sur votre ordinateur et ne coûtent rien.',- action: 'Configurer'- },'right-pane': {title: 'Le volet de travail',text: "Les fichiers, le terminal, la revue et le navigateur intégré partagent le côté droit de l'application."diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 594985275dd..4278c4883b0 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -2679,6 +2679,26 @@ export const ja = defineLocale({}},+ handoffTour: {+ profileTitle: '最初のタスクはデフォルトのプロファイルで実行されます',++ profileText:+ 'このレールでプロファイルを切り替えます。いま点灯しているのが default で、タスクのセッションはここにあります。もう一方はセットアップ用のプロファイルで、ウェルカムチャットはそちらにあります。',++ sessionsTitle: 'プロファイルごとにセッションが分かれています',++ sessionsText:+ 'この一覧は default プロファイルのものです。「新しいセッション」は選択中のプロファイルで始まります。レールでプロファイルを切り替えると一覧も変わります。',++ stayTitle: 'Hermes はワンクリックで呼べます',++ stayText:+ '手を借りたいときは、セットアッププロファイルに切り替えて「Hermes へようこそ」を開いてください。いつでもそこにあります。',+ localTitle: 'このマシンはローカルでモデルを実行できます',+ localText: (model: string) =>+ `${model} はお使いのハードウェアで動きます。無料で、チャットはこのコンピューターから出ません。いつでもここ、モデルメニューから選べます。`+ },+composer: {message: 'メッセージ',wakingProfile: profile => `${profile} を起動中…`,@@ -2833,6 +2853,11 @@ export const ja = defineLocale({editingQueuedInComposer: 'コンポーザーでキュー済みターンを編集中',restoredDraftNotice: '未送信のメッセージを復元しました',restoredDraftUndo: '元に戻す',+ localSetup: {+ title: 'このコンピューターで実行できます',+ text: (model: string) => `${model} はこのマシンで動きます。無料で、チャットはこのコンピューターから出ません。`,+ action: '見てみる'+ },queueEdit: '編集',queueExpand: '展開',queueCollapse: '折りたたむ',@@ -3383,7 +3408,12 @@ export const ja = defineLocale({free: '無料',cacheRead: 'キャッシュ読み取り',priceTitle: (input: string, output: string, cache: string) =>- `入力 ${input}/Mtok · 出力 ${output}/Mtok` + (cache ? ` · キャッシュ読み取り ${cache}/Mtok` : '')+ `入力 ${input}/Mtok · 出力 ${output}/Mtok` + (cache ? ` · キャッシュ読み取り ${cache}/Mtok` : ''),+ localSetup: {+ title: 'ローカルで実行 · 無料・プライベート',+ text: (model: string, size: string) => `${model} はこのマシンで動きます · ${size} をダウンロード`,+ action: '設定する'+ }},modelOptions: {noOptions: 'このモデルにはオプションがありません',@@ -4260,11 +4290,6 @@ export const ja = defineLocale({text: 'ローカルモデルを実行するエンジンを更新します。実行中のローカルリクエストが中断される場合があります。',action: '今すぐ更新'},- 'local-setup': {- title: 'このマシンはローカルでモデルを実行できます',- text: 'お使いのハードウェアでローカルモデルを動かせます。会話はこのコンピュータから出ず、料金もかかりません。',- action: 'セットアップ'- },'right-pane': {title: '作業用ペイン',text: 'ファイル、ターミナル、レビュー、アプリ内ブラウザはサイドペインにまとまっています。'diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex 1804cc0bcb0..bd900555789 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -2881,6 +2881,20 @@ export const ru = defineLocale({},markAllRead: 'Отметить все как прочитанные'},+ handoffTour: {+ profileTitle: 'Первая задача выполняется в профиле по умолчанию',+ profileText:+ 'Эта панель переключает профили. Сейчас подсвечен default — там сессия задачи. Другой — профиль настройки, там приветственный чат.',+ sessionsTitle: 'У каждого профиля свои сессии',+ sessionsText:+ 'Этот список относится к профилю default. «Новая сессия» создаёт её в выбранном профиле. Переключите профиль на панели — и список сменится.',+ stayTitle: 'Hermes в одном клике',+ stayText:+ 'Переключитесь на профиль настройки и откройте «Добро пожаловать в Hermes», когда понадобится помощь. Он остаётся там.',+ localTitle: 'Этот компьютер может запускать модели локально',+ localText: (model: string) =>+ `${model} подходит для вашего оборудования. Работает бесплатно, а чаты не покидают ваш компьютер. Выберите её здесь, в меню моделей, когда захотите.`+ },composer: {message: 'Сообщение',wakingProfile: profile => `Пробуждаем ${profile}…`,@@ -3036,6 +3050,12 @@ export const ru = defineLocale({editingQueuedInComposer: 'Редактирование хода в очереди в композере',restoredDraftNotice: 'Восстановлено ваше неотправленное сообщение',restoredDraftUndo: 'Отменить',+ localSetup: {+ title: 'Это может работать на вашем компьютере',+ text: (model: string) =>+ `${model} подходит для этого компьютера. Бесплатно, а чаты остаются на вашем компьютере.`,+ action: 'Показать'+ },queueEdit: 'Изменить',queueExpand: 'Раскрыть',queueCollapse: 'Свернуть',@@ -3610,7 +3630,12 @@ export const ru = defineLocale({free: 'бесплатно',cacheRead: 'чтение из кэша',priceTitle: (input: string, output: string, cache: string) =>- `Вход ${input}/Mtok · Выход ${output}/Mtok` + (cache ? ` · Чтение из кэша ${cache}/Mtok` : '')+ `Вход ${input}/Mtok · Выход ${output}/Mtok` + (cache ? ` · Чтение из кэша ${cache}/Mtok` : ''),+ localSetup: {+ title: 'Запуск локально · бесплатно, приватно',+ text: (model: string, size: string) => `${model} подходит для этого компьютера · загрузка ${size}`,+ action: 'Настроить'+ }},modelOptions: {noOptions: 'Для этой модели нет опций',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 6a441001184..0ebfdb36700 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -3269,6 +3269,8 @@ export interface Translations {editingQueuedInComposer: stringrestoredDraftNotice: stringrestoredDraftUndo: string+ /** The local-setup offer above the input after the first finished task. */+ localSetup: { title: string; text: (model: string) => string; action: string }queueEdit: stringqueueExpand: stringqueueCollapse: string@@ -3648,6 +3650,8 @@ export interface Translations {sessionsText: stringstayTitle: stringstayText: string+ localTitle: string+ localText: (model: string) => string}/** The app's own tour, run when `gui_tour` starts with no steps. */appTour: {@@ -3913,6 +3917,7 @@ export interface Translations {free: stringcacheRead: stringpriceTitle: (input: string, output: string, cache: string) => string+ localSetup: { title: string; text: (model: string, size: string) => string; action: string }}modelOptions: {noOptions: string@@ -4704,7 +4709,6 @@ export interface Translations {* a button, and `action` is its label. */items: Record<TipId, { title: string; text: string }> & {'local-runtime-update': { title: string; text: string; action: string }- 'local-setup': { title: string; text: string; action: string }}}diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 99e7319cde1..476c95783c5 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -2888,6 +2888,25 @@ export const zhHant = defineLocale({}},+ handoffTour: {+ profileTitle: '你的第一個任務在預設設定檔中執行',++ profileText:+ '這條欄用來切換設定檔。現在亮著的是 default,任務工作階段就在這裡。另一個是設定用的設定檔,歡迎聊天在那裡。',++ sessionsTitle: '每個設定檔都有自己的工作階段',++ sessionsText:+ '這個清單屬於 default 設定檔。「新工作階段」會在目前選取的設定檔中開始。在欄上切換設定檔,清單也會跟著改變。',++ stayTitle: 'Hermes 一鍵可及',++ stayText: '需要幫忙時,切換到設定用的設定檔並開啟「歡迎使用 Hermes」。它會一直在那裡。',+ localTitle: '這台電腦可以在本機執行模型',+ localText: (model: string) =>+ `${model} 適合你的硬體。免費執行,對話不會離開你的電腦。隨時在這裡的模型選單中選擇它。`+ },+composer: {message: '訊息',wakingProfile: profile => `正在喚醒 ${profile}…`,@@ -3042,6 +3061,11 @@ export const zhHant = defineLocale({editingQueuedInComposer: '在輸入框中編輯排隊回合',restoredDraftNotice: '已還原你未送出的訊息',restoredDraftUndo: '復原',+ localSetup: {+ title: '這可以在你的電腦上執行',+ text: (model: string) => `${model} 適合這台電腦。免費,對話留在你的電腦上。`,+ action: '帶我看看'+ },queueEdit: '編輯',queueExpand: '展開',queueCollapse: '收起',@@ -3565,7 +3589,12 @@ export const zhHant = defineLocale({free: '免費',cacheRead: '快取讀取',priceTitle: (input: string, output: string, cache: string) =>- `輸入 ${input}/Mtok · 輸出 ${output}/Mtok` + (cache ? ` · 快取讀取 ${cache}/Mtok` : '')+ `輸入 ${input}/Mtok · 輸出 ${output}/Mtok` + (cache ? ` · 快取讀取 ${cache}/Mtok` : ''),+ localSetup: {+ title: '本機執行 · 免費、私密',+ text: (model: string, size: string) => `${model} 適合這台電腦 · 下載 ${size}`,+ action: '設定'+ }},modelOptions: {noOptions: '此模型沒有可用選項',@@ -4396,11 +4425,6 @@ export const zhHant = defineLocale({text: '更新執行本機模型的引擎。進行中的本機請求可能會中斷。',action: '立即更新'},- 'local-setup': {- title: '這台電腦可以本地執行模型',- text: '你的硬體可以執行本地模型。對話不離開你的電腦,而且完全免費。',- action: '立即設定'- },'right-pane': {title: '工作面板',text: '檔案、終端機、審閱與內建瀏覽器都在側邊面板裡。'diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 602252a0dbf..17dc411d5fe 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -3542,6 +3542,25 @@ export const zh = defineLocale({markAllRead: '全部标记为已读'},+ handoffTour: {+ profileTitle: '你的第一个任务在默认配置文件中运行',++ profileText:+ '这条栏用于切换配置文件。现在亮着的是 default,任务会话就在这里。另一个是设置配置文件,欢迎聊天在那里。',++ sessionsTitle: '每个配置文件都有自己的会话',++ sessionsText:+ '这个列表属于 default 配置文件。“新会话”会在当前选中的配置文件中开始。在栏上切换配置文件,列表也会随之变化。',++ stayTitle: 'Hermes 一键可达',++ stayText: '需要帮忙时,切换到设置配置文件并打开“欢迎使用 Hermes”。它会一直在那里。',+ localTitle: '这台电脑可以在本地运行模型',+ localText: (model: string) =>+ `${model} 适合你的硬件。免费运行,对话不会离开你的电脑。随时在这里的模型菜单中选择它。`+ },+composer: {message: '消息',wakingProfile: profile => `正在唤醒 ${profile}…`,@@ -3704,6 +3723,11 @@ export const zh = defineLocale({editingQueuedInComposer: '正在输入框中编辑排队回合',restoredDraftNotice: '已恢复你未发送的消息',restoredDraftUndo: '撤销',+ localSetup: {+ title: '这可以在你的电脑上运行',+ text: (model: string) => `${model} 适合这台电脑。免费,对话留在你的电脑上。`,+ action: '带我看看'+ },queueEdit: '编辑',queueExpand: '展开',queueCollapse: '收起',@@ -4340,7 +4364,12 @@ export const zh = defineLocale({free: '免费',cacheRead: '缓存读取',priceTitle: (input: string, output: string, cache: string) =>- `输入 ${input}/Mtok · 输出 ${output}/Mtok` + (cache ? ` · 缓存读取 ${cache}/Mtok` : '')+ `输入 ${input}/Mtok · 输出 ${output}/Mtok` + (cache ? ` · 缓存读取 ${cache}/Mtok` : ''),+ localSetup: {+ title: '本地运行 · 免费、私密',+ text: (model: string, size: string) => `${model} 适合这台电脑 · 下载 ${size}`,+ action: '设置'+ }},modelOptions: {noOptions: '此模型没有可用选项',@@ -5214,11 +5243,6 @@ export const zh = defineLocale({text: '更新运行本地模型的引擎。正在进行的本地请求可能会中断。',action: '立即更新'},- 'local-setup': {- title: '这台电脑可以本地运行模型',- text: '你的硬件可以运行本地模型。对话不离开你的电脑,而且完全免费。',- action: '立即设置'- },'right-pane': {title: '工作面板',text: '文件、终端、审阅和内置浏览器都在侧边面板里。'diff --git a/apps/desktop/src/lib/tips/local-cta.test.ts b/apps/desktop/src/lib/tips/local-cta.test.tsindex 44c350e68b6..3ceb3b8a9b0 100644--- a/apps/desktop/src/lib/tips/local-cta.test.ts+++ b/apps/desktop/src/lib/tips/local-cta.test.ts@@ -1,86 +1,18 @@-/**- * The local-setup campaign's policy, tested as the pure decisions they are:- * who qualifies (eligibility), when the bubble may return (the clock), and- * that the campaign cannot corrupt the rotation's cursor.- */+/** The local campaign tips' reshow clock. */import { describe, expect, it } from 'vitest'-import { TIP_CATALOG } from '@/lib/tips/catalog'-import { LOCAL_SETUP_RESHOW_MS, LOCAL_SETUP_TIP_ID, localSetupDue, localSetupEligible } from '@/lib/tips/local-cta'-import type { LocalCatalogModel, LocalModelsStatus } from '@/types/hermes'+import { LOCAL_TIP_RESHOW_MS, localTipDue } from '@/lib/tips/local-cta'-function status(overrides: Partial<LocalModelsStatus> = {}): LocalModelsStatus {- return {- active_model_id: null,- loading: {},- models: [],- models_dir: '',- placement: null,- runtime_installed: false,- server_running: false,- ...overrides- } as LocalModelsStatus-}--function fittingModel(): LocalCatalogModel {- return { fits: true, id: 'qwen3.8-27b' } as LocalCatalogModel-}--describe('localSetupEligible', () => {- it('offers setup to a local backend with a fitting model and nothing staged', () => {- expect(localSetupEligible('local', status(), [fittingModel()])).toBe(true)- })-- it('never promises local privacy on a remote or cloud backend', () => {- for (const mode of ['remote', 'cloud', 'ssh', null]) {- expect(localSetupEligible(mode, status(), [fittingModel()])).toBe(false)- }- })-- it('stays quiet when no catalog model fits the machine', () => {- expect(localSetupEligible('local', status(), [{ fits: false } as LocalCatalogModel])).toBe(false)- expect(localSetupEligible('local', status(), [])).toBe(false)- })-- it('retires itself once the machine is set up', () => {- const setUp = status({- models: [{ id: 'qwen3.8-27b' }] as LocalModelsStatus['models'],- runtime_installed: true- })-- expect(localSetupEligible('local', setUp, [fittingModel()])).toBe(false)- })-- it('still offers when the runtime exists but no model is staged', () => {- expect(localSetupEligible('local', status({ runtime_installed: true }), [fittingModel()])).toBe(true)- })-- it('answers false while state is still loading', () => {- expect(localSetupEligible('local', null, [fittingModel()])).toBe(false)- expect(localSetupEligible('local', status(), null)).toBe(false)- })-})--describe('localSetupDue', () => {+describe('localTipDue', () => {it('is due when never shown', () => {- expect(localSetupDue(Date.now(), undefined)).toBe(true)+ expect(localTipDue(Date.now(), undefined)).toBe(true)})it('holds for a week after an ignored showing, then returns', () => {const now = Date.now()- expect(localSetupDue(now, now - LOCAL_SETUP_RESHOW_MS + 1000)).toBe(false)- expect(localSetupDue(now, now - LOCAL_SETUP_RESHOW_MS)).toBe(true)- })-})--describe('campaign identity', () => {- it('lives outside the rotation catalog — the walk must never land on it', () => {- // TipId already excludes the campaign id at the type level; this guards- // the runtime data against someone re-adding it as a catalog entry.- const ids: readonly string[] = TIP_CATALOG.map(def => def.id)-- expect(ids).not.toContain(LOCAL_SETUP_TIP_ID)+ expect(localTipDue(now, now - LOCAL_TIP_RESHOW_MS + 1000)).toBe(false)+ expect(localTipDue(now, now - LOCAL_TIP_RESHOW_MS)).toBe(true)})})diff --git a/apps/desktop/src/lib/tips/local-cta.ts b/apps/desktop/src/lib/tips/local-cta.tsindex df667a56b8b..8025b64fd77 100644--- a/apps/desktop/src/lib/tips/local-cta.ts+++ b/apps/desktop/src/lib/tips/local-cta.ts@@ -1,55 +1,16 @@/**- * The local-setup call to action — eligibility as data in, data out.+ * Reshow clock for the local-models campaign tips in the rotation (today: the+ * engine update). A tip ignored (timed out) may return, but on a much longer+ * clock than the rotation's: it is the same message twice, not a tour moving on.*- * The one campaign tip the app currently runs: a machine that could serve a- * local model, on a backend that has none staged, gets one bubble on the- * model pill saying so, with the button that starts the already-built- * one-click setup. Everything here is a pure decision over fetched state so- * the policy is testable without a DOM or a backend.- *- * Why this is not a rotation tip: the rotation teaches the app the user- * already has, on a weeks-long walk. This tip is conditional (most machines- * either qualify or don't, permanently), actionable (it carries a button),- * and perishable (setting up local models — or ✕ — ends it forever). It- * outranks the walk when live because "your GPU can do this" beats "the- * model name is a button" every time both are true.- */--import type { LocalCatalogModel, LocalModelsStatus } from '@/types/hermes'--/** Retirement/shown-at ledger id. Not a `TipId` — the rotation never walks it. */-export const LOCAL_SETUP_TIP_ID = 'local-setup'--/** A CTA ignored (timed out) may return, but on a much longer clock than the- * rotation's: it is the same message twice, not a tour moving on. */-export const LOCAL_SETUP_RESHOW_MS = 7 * 24 * 60 * 60_000--/**- * Machines qualify when the catalog has a model that FITS (the backend's- * physics check, same answer the pane's hero uses) and nothing is servable- * yet — no runtime or no staged models. A set-up machine never qualifies, so- * completing setup retires this tip without any bookkeeping.- *- * `connectionMode` must be 'local': on a remote backend (cloud resolves to- * remote) the models would run on the far machine, and a bubble promising- * "stays on your computer" would be promising someone else's computer.+ * The local-setup offer used to live here too; it moved out of the rotation to+ * store/local-setup-offer.ts, which runs on events instead of this clock.*/-export function localSetupEligible(- connectionMode: null | string,- status: LocalModelsStatus | null,- catalog: readonly LocalCatalogModel[] | null-): boolean {- if (connectionMode !== 'local' || !status || !catalog) {- return false- }- const needsSetup = !status.runtime_installed || status.models.length === 0-- return needsSetup && catalog.some(model => model.fits)-}+export const LOCAL_TIP_RESHOW_MS = 7 * 24 * 60 * 60_000/** Due = never shown, or shown long enough ago that repeating it reads as a* reminder rather than a nag. Retirement is the caller's ledger, not ours. */-export function localSetupDue(now: number, shownAt: number | undefined): boolean {- return shownAt === undefined || now - shownAt >= LOCAL_SETUP_RESHOW_MS+export function localTipDue(now: number, shownAt: number | undefined): boolean {+ return shownAt === undefined || now - shownAt >= LOCAL_TIP_RESHOW_MS}diff --git a/apps/desktop/src/store/local-setup-offer.ts b/apps/desktop/src/store/local-setup-offer.tsnew file mode 100644index 00000000000..01c7c011702--- /dev/null+++ b/apps/desktop/src/store/local-setup-offer.ts@@ -0,0 +1,370 @@+/**+ * The local-setup offer: "this machine can run a model locally" for every+ * machine that qualifies, delivered by state transitions, never by a timer.+ *+ * Three surfaces read this one record:+ *+ * - The handoff tour ends on the model pill (`signpost.ts`) when the machine+ * qualifies. Every guided user who reaches the handoff sees it.+ * - A card above the primary composer after the first finished turn once+ * onboarding is over (handoff or skip). It renders only while that session+ * is idle, so an automatic follow-up turn hides it and the next idle shows it.+ * - A "Run locally" row at the top of the model menu, until setup is done.+ *+ * States move only on events: `armed` when onboarding ends, `shown` on the+ * first eligible `message.complete`, `dismissed` on ✕, `accepted` on the card's+ * button. Local setup completing ends it by eligibility: a machine with a+ * runtime and a staged model no longer qualifies, so every surface hides.+ *+ * The predecessor was a tip in the rotation: 5-10 min settle, a six-hour+ * cooldown shared with every tip, a quiet check, a 22 s linger, and a 7-day+ * reshow. It fired on rtxspark and vespyr with nobody watching and recorded+ * itself as shown, which hid it for a week.+ */++import { atom, computed } from 'nanostores'++import { getLocalCatalog, getLocalModelsStatus } from '@/hermes'+import { isOnboardingEnabled } from '@/lib/onboarding-enabled'+import { Codecs, persistentAtom } from '@/lib/persisted'+import { readKey } from '@/lib/storage'+import type { LocalCatalogModel, LocalModelsStatus } from '@/types/hermes'++import { $localModelsEnabled } from './local-models-flag'+import { $desktopOnboarding } from './onboarding'+import { $onboardingGate, $onboardingStateRead, type OnboardingPhase } from './onboarding-gate'+import { $connection } from './session'+import { $retiredTips } from './tips'++type LocalSetupOfferState = 'accepted' | 'armed' | 'dismissed' | 'shown' | 'unarmed'++interface OfferRecord {+ armedBy: null | string+ /** ISO time of the last transition, for `state()` readouts. */+ at: null | string+ /** Runtime id of the session whose finished turn showed the card (diagnostics only). */+ sessionId: null | string+ state: LocalSetupOfferState+}++const OFFER_STATES: readonly LocalSetupOfferState[] = ['accepted', 'armed', 'dismissed', 'shown', 'unarmed']+const EMPTY: OfferRecord = { armedBy: null, at: null, sessionId: null, state: 'unarmed' }++/** Persisted as a flat string record so `Codecs.stringRecord` does the parsing at the storage boundary. */+function toRecord(stored: Record<string, string>): OfferRecord {+ const state = OFFER_STATES.find(candidate => candidate === stored.state)++ return state+ ? { armedBy: stored.armedBy ?? null, at: stored.at ?? null, sessionId: stored.sessionId ?? null, state }+ : EMPTY+}++function toStored(record: OfferRecord): Record<string, string> {+ return Object.fromEntries(Object.entries(record).filter((entry): entry is [string, string] => entry[1] !== null))+}++const STORAGE_KEY = 'hermes.desktop.offers.local-setup.v1'++/** Desktop-global like the tip ledgers: the offer is about this machine, not a profile. */+const $stored = persistentAtom<Record<string, string>>(STORAGE_KEY, {}, Codecs.stringRecord)++export const $localSetupOffer = computed($stored, toRecord)++/** The stored record as another window may have left it. */+function readStoredRecord(): OfferRecord {+ const raw = readKey(STORAGE_KEY)++ return raw === null ? EMPTY : toRecord(Codecs.stringRecord.decode(raw))+}++function setRecord(record: OfferRecord): void {+ $stored.set(toStored(record))+}++// Another window moved the offer (dismissed it, say): adopt that, so this window+// neither keeps showing a card the user closed nor writes an older state over it.+window.addEventListener('storage', event => {+ if (event.key === STORAGE_KEY) {+ $stored.set(event.newValue === null ? {} : Codecs.stringRecord.decode(event.newValue))+ }+})++/** The recommended catalog row that fits, when this machine qualifies. */+interface LocalSetupFit {+ model: LocalCatalogModel+}++interface Eligibility {+ checkedAt: number+ fit: LocalSetupFit | null+ reason: string+ /** A failed read or a connection not up yet: shown in `state()` but never cached, so the next read retries. */+ transient?: boolean+}++/** Session cache: eligibility is a fact about the backend's machine, so a connection change drops it. */+export const $localSetupEligibility = atom<Eligibility | null>(null)++let eligibilityRead: Promise<Eligibility> | null = null+/** Bumped on every invalidation: a read that started before it must not land after it. */+let eligibilityGeneration = 0++function pickLocalSetupFit(+ connectionMode: null | string,+ status: LocalModelsStatus | null,+ catalog: readonly LocalCatalogModel[] | null+): Eligibility {+ const at = Date.now()++ if (connectionMode === null) {+ return { checkedAt: at, fit: null, reason: 'connection not established yet', transient: true }+ }++ if (connectionMode !== 'local') {+ return { checkedAt: at, fit: null, reason: `connection is ${connectionMode}, not local` }+ }++ if (!status || !catalog) {+ return { checkedAt: at, fit: null, reason: 'no local-models status or catalog' }+ }++ if (status.runtime_installed && status.models.length > 0) {+ return { checkedAt: at, fit: null, reason: 'local models already set up' }+ }++ const fitting = catalog.filter(model => model.fits)+ const model = fitting.find(candidate => candidate.recommended) ?? fitting[0]++ return model+ ? { checkedAt: at, fit: { model }, reason: `fits ${model.id}` }+ : { checkedAt: at, fit: null, reason: 'no catalog model fits this machine' }+}++/** One status + catalog read per connection; a transient miss is retried on the next read. */+export function readLocalSetupEligibility(): Promise<Eligibility> {+ const cached = $localSetupEligibility.get()++ return cached && !cached.transient ? Promise.resolve(cached) : refreshLocalSetupEligibility()+}++/** Read again, keeping the current answer on screen until the new one lands. */+export function refreshLocalSetupEligibility(): Promise<Eligibility> {+ const mode = $connection.get()?.mode ?? null++ // Settled without a request: the flag, a missing connection, or a remote+ // backend (whose hardware is not this computer's) all answer "no" locally.+ if (!$localModelsEnabled.get() || mode !== 'local') {+ const settled = $localModelsEnabled.get()+ ? pickLocalSetupFit(mode, null, null)+ : { checkedAt: Date.now(), fit: null, reason: 'local models are off in this build' }++ $localSetupEligibility.set(settled)++ return Promise.resolve(settled)+ }++ const generation = eligibilityGeneration++ eligibilityRead ??= Promise.all([getLocalModelsStatus(), getLocalCatalog()])+ .then(([status, catalog]) => pickLocalSetupFit(mode, status, catalog.models))+ .catch((error: Error) => ({+ checkedAt: Date.now(),+ fit: null,+ reason: `eligibility read failed: ${error.message}`,+ transient: true+ }))+ .then(result => {+ if (generation !== eligibilityGeneration) {+ return result+ }++ eligibilityRead = null++ // A failed re-read keeps a good answer on screen rather than hiding the offer on one bad fetch.+ if (!(result.transient && $localSetupEligibility.get()?.fit)) {+ $localSetupEligibility.set(result)+ }++ return result+ })++ return eligibilityRead+}++/** Drop the cached answer: the backend it described is gone (connection or profile changed; debug reset). */+function invalidateLocalSetupEligibility(): void {+ eligibilityGeneration += 1+ eligibilityRead = null+ $localSetupEligibility.set(null)+}++/** Which backend's machine the cached answer describes. Window-state republishes keep it. */+function backendIdentity(): string {+ const connection = $connection.get()++ return connection ? `${connection.mode ?? ''}|${connection.connectionId ?? ''}|${connection.baseUrl}` : ''+}++let lastBackend = backendIdentity()++$connection.listen(() => {+ const next = backendIdentity()++ if (next !== lastBackend) {+ lastBackend = next+ invalidateLocalSetupEligibility()+ }+})++const FINAL_STATES: readonly LocalSetupOfferState[] = ['accepted', 'dismissed']++function transition(state: LocalSetupOfferState, patch: Partial<OfferRecord>): void {+ // Another window may have closed the offer since this one last read it; a final state stays final.+ const stored = readStoredRecord()++ if (FINAL_STATES.includes(stored.state)) {+ $stored.set(toStored(stored))++ return+ }++ setRecord({ ...$localSetupOffer.get(), ...patch, at: new Date().toISOString(), state })+}++/** The guide will not run for this identity: `onboarding.state` answered without starting it, or "choose a provider later". */+function guideWillNotStart(): boolean {+ return $onboardingStateRead.get() || $desktopOnboarding.get().firstRunSkipped+}++/**+ * Guided onboarding ending (either way) arms the offer, and so does an install+ * where the guide never runs (flag off, or `idle` with the guide ruled out).+ * `cinematic`/`guided`/`handoff`, and an `idle` the guide may still leave, wait:+ * the card must not land on top of the guide.+ */+function armFromPhase(phase: OnboardingPhase): void {+ if ($localSetupOffer.get().state !== 'unarmed') {+ return+ }++ // Someone who closed the old local-setup tip already answered this offer.+ if ($retiredTips.get().includes('local-setup')) {+ transition('dismissed', { armedBy: 'retired-tip' })+ } else if (phase === 'done' || phase === 'skipped') {+ transition('armed', { armedBy: `onboarding:${phase}` })+ } else if (!isOnboardingEnabled()) {+ transition('armed', { armedBy: 'no-guided-onboarding' })+ } else if (phase === 'idle' && guideWillNotStart()) {+ transition('armed', { armedBy: 'guide-will-not-start' })+ }+}++$onboardingGate.subscribe(gate => armFromPhase(gate.phase))+$desktopOnboarding.listen(() => armFromPhase($onboardingGate.get().phase))+$onboardingStateRead.listen(() => armFromPhase($onboardingGate.get().phase))++interface TurnCompleteSignal {+ /** Anything but a completed turn: errored, interrupted, cancelled. */+ failed: boolean+ sessionId: null | string+ /** A turn of the setup chat itself (its closing words after `start_chat`). */+ setupChat: boolean+}++/**+ * `message.complete` for the session the user is looking at. The whole agent+ * loop has returned at this point (tool calls and interim messages come before+ * it), so this is the end of a task, not a step in one. Turns that did not+ * complete do not count; the caller only reports the session on screen.+ */+export function reportLocalSetupTurnComplete({ failed, sessionId, setupChat }: TurnCompleteSignal): void {+ const offer = $localSetupOffer.get()++ if (failed || !sessionId || setupChat || offer.state !== 'armed') {+ return+ }++ // The task chat that setup hands off to speaks first: its opening turn asks which direction to take.+ // That question is not a finished task, so the card waits for the next completed turn.+ if (offer.armedBy === 'onboarding:done' && offer.sessionId === null) {+ transition('armed', { sessionId })++ return+ }++ void readLocalSetupEligibility().then(({ fit }) => {+ if (fit && $localSetupOffer.get().state === 'armed') {+ transition('shown', { sessionId })+ }+ })+}++export function dismissLocalSetupOffer(): void {+ transition('dismissed', {})+}++export function acceptLocalSetupOffer(): void {+ transition('accepted', {})+}++/** The card is live: shown, still eligible. The composer adds "and this session is idle". */+export const $localSetupCardLive = computed(+ [$localSetupOffer, $localSetupEligibility],+ (offer, eligibility) => offer.state === 'shown' && Boolean(eligibility?.fit)+)++/** The model-menu row stays until setup completes, whatever happened to the card. */+export const $localSetupRowFit = computed($localSetupEligibility, eligibility => eligibility?.fit ?? null)++/** Asks the pill of one composer (by scope target) to open its menu, where the row sits on top. */+export const $localSetupMenuRequest = atom<null | { seq: number; target: string }>(null)++export function requestLocalSetupMenu(target: string): void {+ $localSetupMenuRequest.set({ seq: ($localSetupMenuRequest.get()?.seq ?? 0) + 1, target })+}++// ── Debug handle ────────────────────────────────────────────────────────────+// Ships in packaged builds on purpose: rtxspark/vespyr run MSIX bundles we+// drive over CDP, and `state()` is how a run that showed nothing explains itself.++interface LocalSetupOfferDebug {+ force: () => Promise<Eligibility>+ reset: () => void+ state: () => {+ eligibility: Eligibility | null+ localModelsEnabled: boolean+ offer: OfferRecord+ onboardingPhase: OnboardingPhase+ }+}++declare global {+ interface Window {+ __hermesTips?: LocalSetupOfferDebug+ }+}++window.__hermesTips = {+ /** Skip onboarding and waiting: mark the card shown now, if the machine qualifies. */+ force: async () => {+ invalidateLocalSetupEligibility()+ const result = await readLocalSetupEligibility()++ if (result.fit) {+ transition('shown', { armedBy: 'debug:force', sessionId: 'debug' })+ }++ return result+ },+ reset: () => {+ $stored.set({})+ invalidateLocalSetupEligibility()+ armFromPhase($onboardingGate.get().phase)+ },+ state: () => ({+ eligibility: $localSetupEligibility.get(),+ localModelsEnabled: $localModelsEnabled.get(),+ offer: $localSetupOffer.get(),+ onboardingPhase: $onboardingGate.get().phase+ })+}