Skip to content

The agent that grows with you

fix(desktop): keep a tour bound to its target across navigation and re-renders

Brooklyn Nicholson98bbfbda6e7c
diff --git a/apps/desktop/src/lib/tour/engine.test.ts b/apps/desktop/src/lib/tour/engine.test.ts
index 91dc8ecf5cc..958e66f3a71 100644
--- a/apps/desktop/src/lib/tour/engine.test.ts
+++ b/apps/desktop/src/lib/tour/engine.test.ts
@@ -6,34 +6,53 @@ import { runTourEngine, type TourDriver, type TourHolder } from './engine'
/** A recording fake of the driver.js surface the engine touches. */
function makeFactory(calls: string[]) {
return (config?: object) => {
- const steps = (config as { steps?: unknown[] } | undefined)?.steps ?? []
+ const cfg = (config ?? {}) as {
+ onDestroyed?: () => void
+ onNextClick?: () => void
+ onPrevClick?: () => void
+ steps?: { onHighlightStarted?: () => void; waitForElement?: number }[]
+ }
+
+ const steps = cfg.steps ?? []
let active = false
let index = 0
- const instance: TourDriver = {
+ const enter = (at: number) => {
+ index = at
+ steps[at]?.onHighlightStarted?.()
+ }
+
+ const instance: TourDriver & { clickNext: () => void; clickPrev: () => void } = {
+ // Stands in for the popover's own Next/Prev buttons. driver.js runs a
+ // configured handler if one exists, otherwise its built-in advance —
+ // both end up entering the step, which is what must trigger the move.
+ clickNext: () => (cfg.onNextClick ? cfg.onNextClick() : instance.moveNext()),
+ clickPrev: () => (cfg.onPrevClick ? cfg.onPrevClick() : instance.movePrevious()),
destroy() {
calls.push('destroy')
active = false
+ cfg.onDestroyed?.()
},
drive(stepIndex?: number) {
calls.push(`drive:${stepIndex ?? 0}`)
active = true
- index = stepIndex ?? 0
+ enter(stepIndex ?? 0)
},
getActiveIndex: () => index,
highlight(step: object) {
calls.push(`highlight:${JSON.stringify(step)}`)
active = true
+ ;(step as { onHighlightStarted?: () => void }).onHighlightStarted?.()
},
isActive: () => active,
isLastStep: () => index >= steps.length - 1,
moveNext() {
calls.push('next')
- index += 1
+ enter(index + 1)
},
movePrevious() {
calls.push('prev')
- index -= 1
+ enter(index - 1)
}
}
@@ -41,6 +60,24 @@ function makeFactory(calls: string[]) {
}
}
+/** A fake app: records where a tour sent it, and what it revealed. */
+function makeHost(startRoute = '/session-1') {
+ let route = startRoute
+ const panes: string[] = []
+
+ return {
+ host: {
+ currentRoute: () => route,
+ navigate: (to: string) => {
+ route = to
+ },
+ revealPane: (pane: string) => void panes.push(pane)
+ },
+ panes,
+ route: () => route
+ }
+}
+
function seedDom() {
document.body.innerHTML = `
<nav aria-label="Primary"><button id="send-btn" aria-label="Send message">Send</button></nav>
@@ -215,3 +252,236 @@ describe('runTourEngine', () => {
}
})
})
+
+describe('tours that move the app', () => {
+ it('navigates and reveals panes as their steps are entered', () => {
+ seedDom()
+ const app = makeHost('/session-1')
+ const holder: TourHolder = {}
+
+ runTourEngine(
+ makeFactory([]),
+ holder,
+ {
+ kind: 'start',
+ steps: [
+ { pane: 'sessions', title: 'Sidebar' },
+ { navigate: '/artifacts', title: 'Artifacts' }
+ ]
+ },
+ collectTourTargets,
+ document,
+ undefined,
+ app.host
+ )
+
+ // The engine moves the app itself, before driver.js sees the step — and
+ // exactly once per step, not once here and once from a driver hook.
+ expect(app.panes).toEqual(['sessions'])
+ expect(app.route()).toBe('/session-1')
+
+ runTourEngine(makeFactory([]), holder, { kind: 'next' }, collectTourTargets, document, undefined, app.host)
+ expect(app.route()).toBe('/artifacts')
+ })
+
+ it('moves the app however the step is reached', () => {
+ // The class of bug this pins: the move used to live on the paths (the API,
+ // then the buttons), so whichever path wasn't wired advanced the text while
+ // the app stayed put — and the step waited forever for an element on a page
+ // it never opened. It now hangs off the step's own onHighlightStarted, the
+ // one hook driver fires for every path, so a custom or agent-authored tour
+ // behaves the same whether the user clicks Next, presses →, or code calls it.
+ seedDom()
+
+ for (const advance of ['api', 'button', 'driver'] as const) {
+ const app = makeHost('/session-1')
+ const holder: TourHolder = {}
+ const factory = makeFactory([])
+
+ runTourEngine(
+ factory,
+ holder,
+ { kind: 'start', steps: [{ title: 'Intro' }, { navigate: '/artifacts', title: 'Away' }] },
+ collectTourTargets,
+ document,
+ undefined,
+ app.host
+ )
+
+ expect(app.route(), advance).toBe('/session-1')
+
+ if (advance === 'api') {
+ runTourEngine(factory, holder, { kind: 'next' }, collectTourTargets, document, undefined, app.host)
+ } else if (advance === 'button') {
+ // The popover's own Next button — driver's handler, not ours.
+ ;(holder.driver as unknown as { clickNext: () => void }).clickNext()
+ } else {
+ // Arrow keys and any other internal advance land here.
+ holder.driver?.moveNext()
+ }
+
+ expect(app.route(), advance).toBe('/artifacts')
+ }
+ })
+
+ it('returns to where it started, however the tour ends', () => {
+ seedDom()
+
+ for (const end of ['lastStep', 'dismissed'] as const) {
+ const app = makeHost('/session-1')
+ const holder: TourHolder = {}
+
+ runTourEngine(
+ makeFactory([]),
+ holder,
+ { kind: 'start', steps: [{ navigate: '/artifacts', title: 'Away' }] },
+ collectTourTargets,
+ document,
+ undefined,
+ app.host
+ )
+
+ expect(app.route()).toBe('/artifacts')
+
+ // 'next' past the last step vs. an Esc/✕ dismissal both destroy the tour.
+ if (end === 'lastStep') {
+ runTourEngine(makeFactory([]), holder, { kind: 'next' }, collectTourTargets, document, undefined, app.host)
+ } else {
+ holder.driver?.destroy()
+ }
+
+ expect(app.route(), end).toBe('/session-1')
+ // Nothing lingers: the slot is empty and the tour owns no other state.
+ expect(holder.driver, end).toBeUndefined()
+ }
+ })
+
+ it('leaves the route alone when no step navigates', () => {
+ seedDom()
+ const app = makeHost('/session-1')
+ const holder: TourHolder = {}
+
+ runTourEngine(
+ makeFactory([]),
+ holder,
+ { kind: 'start', steps: [{ selector: '#send-btn', title: 'Here' }] },
+ collectTourTargets,
+ document,
+ undefined,
+ app.host
+ )
+ holder.driver?.destroy()
+
+ expect(app.route()).toBe('/session-1')
+ })
+
+ it('waits for targets that mount after a step moves the app', () => {
+ seedDom()
+ const app = makeHost()
+
+ // #not-mounted-yet does not exist at start time — it appears after the
+ // navigation. Neither the navigating step NOR the steps after it may fail
+ // selector pre-validation, and each must carry a wait.
+ const result = runTourEngine(
+ makeFactory([]),
+ {},
+ {
+ kind: 'start',
+ steps: [
+ { navigate: '/artifacts', selector: '#not-mounted-yet', title: 'Later' },
+ { selector: '#also-not-here', title: 'Later still' }
+ ]
+ },
+ collectTourTargets,
+ document,
+ undefined,
+ app.host
+ )
+
+ expect(result.success).toBe(true)
+ })
+
+ it('still rejects a bad selector when nothing moves the app', () => {
+ seedDom()
+
+ const result = runTourEngine(
+ makeFactory([]),
+ {},
+ { kind: 'start', steps: [{ selector: '#ghost', title: 'x' }] },
+ collectTourTargets,
+ document,
+ undefined,
+ makeHost().host
+ )
+
+ expect(result.success).toBe(false)
+ expect(result.error).toContain('#ghost')
+ })
+
+ it('survives the surface re-rendering underneath it', async () => {
+ // The bug this pins: sitting idle on a page whose data polls/refetches used
+ // to kill the tour. driver.js holds the highlighted node by REFERENCE, so
+ // when React swapped it for an equivalent one, driver kept measuring a
+ // detached node (rect all zeros) and the spotlight vanished — looking like
+ // the tour closed itself while the user did nothing. Any list that refetches
+ // hits this, so it matters for curated and agent-authored tours alike.
+ seedDom()
+ const calls: string[] = []
+ const holder: TourHolder = {}
+
+ runTourEngine(
+ makeFactory(calls),
+ holder,
+ { kind: 'start', steps: [{ selector: '#send-btn', title: 'Send' }] },
+ collectTourTargets,
+ document,
+ undefined,
+ makeHost().host
+ )
+
+ const drivesBefore = calls.filter(c => c.startsWith('drive:')).length
+
+ // Simulate a refetch: the old node is replaced by an equivalent new one.
+ const old = document.querySelector('#send-btn')!
+
+ old.classList.add('driver-active-element')
+
+ const fresh = old.cloneNode(true) as HTMLElement
+
+ old.replaceWith(fresh)
+ fresh.classList.remove('driver-active-element')
+
+ // MutationObserver callbacks are microtask-scheduled, then rAF-coalesced.
+ await new Promise(resolve => setTimeout(resolve, 50))
+
+ expect(calls.filter(c => c.startsWith('drive:')).length).toBeGreaterThan(drivesBefore)
+ expect(holder.driver?.isActive()).toBe(true)
+ })
+
+ it('stops watching once the tour ends', async () => {
+ seedDom()
+ const calls: string[] = []
+ const holder: TourHolder = {}
+ const factory = makeFactory(calls)
+
+ runTourEngine(
+ factory,
+ holder,
+ { kind: 'start', steps: [{ selector: '#send-btn', title: 'Send' }] },
+ collectTourTargets,
+ document,
+ undefined,
+ makeHost().host
+ )
+ runTourEngine(factory, holder, { kind: 'stop' }, collectTourTargets, document, undefined, makeHost().host)
+
+ const after = calls.length
+ const node = document.querySelector('#send-btn')!
+
+ node.replaceWith(node.cloneNode(true))
+ await new Promise(resolve => setTimeout(resolve, 50))
+
+ // No re-drive attempts once it's over.
+ expect(calls.length).toBe(after)
+ })
+})
diff --git a/apps/desktop/src/lib/tour/engine.ts b/apps/desktop/src/lib/tour/engine.ts
index 2a2c9ca364f..ac5fb887801 100644
--- a/apps/desktop/src/lib/tour/engine.ts
+++ b/apps/desktop/src/lib/tour/engine.ts
@@ -17,6 +17,9 @@ export interface TourDriver {
destroy: () => void
drive: (stepIndex?: number) => void
getActiveIndex: () => number | undefined
+ /** driver.js's own state bag. Used to read the live, eased stage rect so a
+ * companion layer can travel with the cutout instead of jumping ahead. */
+ getState?: (key?: string) => unknown
highlight: (step: object) => void
isActive: () => boolean
isLastStep: () => boolean
@@ -26,21 +29,52 @@ export interface TourDriver {
export type TourDriverFactory = (config?: object) => TourDriver
+/** Look-and-feel passed into every driver instance: the scrim, how the cutout
+ * hugs the highlighted element, and the transition speed. Surface-supplied so
+ * the app can match its own overlay tokens while a guest page keeps
+ * driver.js's defaults. */
+export interface TourStyle {
+ duration?: number
+ overlayColor?: string
+ overlayOpacity?: number
+ popoverOffset?: number
+ stagePadding?: number
+ stageRadius?: number
+}
+
/** Where a surface keeps its live instance between actions (module state in
* the app, a window global in the preview page). */
export interface TourHolder {
driver?: TourDriver
+ /** Tears down the keep-alive observer. Runs with the driver. */
+ release?: () => void
}
-/** One highlighted moment: an element, and what to say about it. Omit the
- * selector for a centered narration step. */
+/** One highlighted moment: an element, what to say about it, and optionally
+ * where the app must be for the element to exist. `navigate` (a route path)
+ * and `pane` (a desktop pane name) run before the step is shown; the host
+ * supplies the actual navigation (see TourHost), so the engine itself stays
+ * self-contained and portable to a guest page. */
export interface TourStep {
+ navigate?: string
+ pane?: string
selector?: string
side?: 'top' | 'right' | 'bottom' | 'left'
text?: string
title?: string
}
+/** How the engine reaches the app around it. Omitted on the preview surface,
+ * where a guest page has neither routes nor panes. */
+export interface TourHost {
+ /** Where the app is right now, so the tour can put it back when it ends. */
+ currentRoute?: () => string
+ /** Go to a route path. */
+ navigate?: (to: string) => void
+ /** Reveal a desktop pane by name. */
+ revealPane?: (pane: string) => void
+}
+
/** A normalized action. `kind` is the verb; the rest is per-verb payload. */
export interface TourAction extends TourStep {
kind: 'targets' | 'show' | 'start' | 'next' | 'prev' | 'stop'
@@ -67,28 +101,150 @@ export function runTourEngine(
holder: TourHolder,
action: TourAction,
collectTargets: (doc: Document, max: number) => TourTarget[],
- doc: Document
+ doc: Document,
+ style?: TourStyle,
+ host?: TourHost
): TourResult {
const kind = action.kind
+ const base = { animate: true, smoothScroll: true, ...(style || {}) }
- const popoverOf = (step: TourStep) =>
+ /** driver.js reads `popoverClass` off the POPOVER object, not off the step
+ * (`r.popoverClass` where r = step.popover), so the entrance animation has
+ * to be declared in here. `first` settles down into place, every step after
+ * rises — styled in app-tour.css. */
+ const popoverOf = (step: TourStep, first = false) =>
step.title || step.text
- ? { description: step.text || '', side: step.side || undefined, title: step.title || '' }
+ ? {
+ description: step.text || '',
+ popoverClass: first ? 'tour-pop-in' : 'tour-pop-next',
+ side: step.side || undefined,
+ title: step.title || ''
+ }
: undefined
- const stepOf = (step: TourStep) => ({ element: step.selector || undefined, popover: popoverOf(step) })
+ /** Move the app where a step needs to be.
+ *
+ * Called from `onHighlightStarted`, which driver.js fires for EVERY way a
+ * step can be reached — the API, its own Next/Prev buttons, arrow keys,
+ * `drive(i)`. Hooking the paths individually is what let a user clicking
+ * Next (or pressing →) advance the text while the app never navigated, so
+ * the step sat waiting for an element on a page it never opened. One hook,
+ * no path can skip it. */
+ const moveFor = (step: TourStep) => {
+ if (step.pane && host?.revealPane) {
+ host.revealPane(step.pane)
+ }
- /** Selectors that match nothing right now — the caller's cue to re-scan. */
- const unmatched = (steps: TourStep[]) =>
- steps
- .map(step => step.selector)
- .filter((selector): selector is string => {
- try {
- return !!selector && !doc.querySelector(selector)
- } catch {
- return true
+ if (step.navigate && host?.navigate) {
+ host.navigate(step.navigate)
+ }
+
+ // No waiting here: a target that mounts after the move is picked up by the
+ // keep-alive below, which re-drives the step the moment the element exists.
+ // driver.js's own `waitForElement` can't do the job — it returns BEFORE the
+ // hooks run, so the step would wait for an element on a page this hook was
+ // about to open, which is the deadlock that looked like a freeze.
+ }
+
+ /** Keep the current step bound to a LIVE node.
+ *
+ * Covers the two ways a step's element goes missing under it:
+ *
+ * - It hasn't mounted yet, because the step just navigated somewhere.
+ * - It mounted, then the surface re-rendered — a poll, a refetch, a list
+ * reordering — and React swapped the node. driver.js holds the highlight
+ * as a node REFERENCE and re-measures it with getBoundingClientRect(), so
+ * a detached node measures all zeros: the spotlight collapses and the
+ * tour looks like it closed itself while the user did nothing.
+ *
+ * Both are "the element the step wants isn't the element driver is holding",
+ * so both are fixed the same way: re-drive the step to rebind. */
+ const bindKeepAlive = (steps: TourStep[]) => {
+ let queued = false
+
+ // Coalesce a mutation burst into one check on the next frame. Falls back to
+ // a timeout where rAF is absent (jsdom, and any host page without it) —
+ // this module is stringified into the preview webview, so it can't assume
+ // browser globals beyond the DOM.
+ const soon = (fn: () => void) => {
+ if (typeof requestAnimationFrame === 'function') {
+ requestAnimationFrame(fn)
+ } else {
+ setTimeout(fn, 16)
+ }
+ }
+
+ const observer = new MutationObserver(() => {
+ if (queued) {
+ return
+ }
+
+ queued = true
+ soon(() => {
+ queued = false
+
+ const driver = holder.driver
+
+ if (!driver?.isActive()) {
+ return
+ }
+
+ const index = driver.getActiveIndex() ?? 0
+ const selector = steps[index]?.selector
+
+ if (!selector) {
+ return
+ }
+
+ const wanted = doc.querySelector(selector)
+
+ // Nothing to bind to yet — a navigating step whose page is still
+ // rendering. The next mutation brings us back.
+ if (!wanted) {
+ return
}
+
+ // Already on the right node: nothing to do. This is the common case,
+ // so it stays a single identity check per mutation batch.
+ if (wanted === doc.querySelector('.driver-active-element')) {
+ return
+ }
+
+ driver.drive(index)
})
+ })
+
+ observer.observe(doc.body, { childList: true, subtree: true })
+
+ return () => observer.disconnect()
+ }
+
+ /** Every step carries its move on `onHighlightStarted`, the one hook driver
+ * fires no matter how the step was reached. */
+ const stepOf = (step: TourStep, first = false) => ({
+ element: step.selector || undefined,
+ onHighlightStarted: () => moveFor(step),
+ popover: popoverOf(step, first)
+ })
+
+ /** Selectors that match nothing right now — the caller's cue to re-scan.
+ *
+ * Skipped entirely once any step moves the app: from that point the later
+ * steps' targets legitimately don't exist yet (they mount on the page the
+ * tour is about to open), so pre-validating them would reject a correct
+ * tour. driver.js waits for each one via `waitForElement` instead. */
+ const unmatched = (steps: TourStep[]) =>
+ steps.some(step => step.navigate || step.pane)
+ ? []
+ : steps
+ .map(step => step.selector)
+ .filter((selector): selector is string => {
+ try {
+ return !!selector && !doc.querySelector(selector)
+ } catch {
+ return true
+ }
+ })
const missing = (selectors: string[]): TourResult => ({
error: 'No element matches selector(s): ' + selectors.join(', '),
@@ -105,6 +261,22 @@ export function runTourEngine(
}
}
+ /** Remove any driver DOM this engine no longer owns.
+ *
+ * driver.js tears itself down through the instance that built it, so an
+ * instance we lose our handle to — a hot reload, a double install, an
+ * exception between create and store — leaves its overlay and popover on
+ * screen forever. They then sit ON TOP of the next tour: the new step is
+ * running underneath a stale popover, which reads as "the tour froze".
+ * Cheap to check, and the only way to guarantee a clean start. */
+ const clearOrphans = () => {
+ for (const node of doc.querySelectorAll('.driver-popover, svg.driver-overlay')) {
+ node.remove()
+ }
+
+ doc.body.classList.remove('driver-active', 'driver-fade', 'driver-simple', 'driver-no-scroll')
+ }
+
if (kind === 'show') {
const gone = unmatched([action])
@@ -113,10 +285,12 @@ export function runTourEngine(
}
if (!holder.driver) {
- holder.driver = factory({ animate: true, smoothScroll: true })
+ clearOrphans()
+ holder.driver = factory(base)
}
- holder.driver.highlight(stepOf(action))
+ // A one-off highlight is its own arrival, so it uses the settle-down enter.
+ holder.driver.highlight(stepOf(action, true))
return { action: kind, success: true }
}
@@ -133,14 +307,38 @@ export function runTourEngine(
holder.driver.destroy()
}
+ // Whatever the previous tour left behind goes now, so this one isn't
+ // rendered underneath a stale popover.
+ clearOrphans()
+
const startAt = action.startAt || 0
+ // A tour that navigates must hand the app back. Captured before the first
+ // step moves anywhere, and restored on EVERY exit — Esc, the ✕, an overlay
+ // click, and the last step all funnel through onDestroyed.
+ const origin = steps.some(step => step.navigate) ? host?.currentRoute?.() : undefined
+
holder.driver = factory({
- animate: true,
+ ...base,
+ onDestroyed: () => {
+ holder.driver = undefined
+ holder.release?.()
+ holder.release = undefined
+
+ if (origin !== undefined && host?.navigate && host.currentRoute?.() !== origin) {
+ host.navigate(origin)
+ }
+ },
showProgress: steps.length > 1,
- smoothScroll: true,
- steps: steps.map(stepOf)
+ // Each step moves the app from its own onHighlightStarted, so buttons,
+ // arrow keys and the API all take the same path (see moveFor).
+ steps: steps.map((step, i) => stepOf(step, i === startAt))
})
+
+ // Survive the surface re-rendering underneath the tour (see bindKeepAlive).
+ holder.release?.()
+ holder.release = bindKeepAlive(steps)
+
holder.driver.drive(startAt)
return { action: kind, activeStep: startAt, steps: steps.length, success: true }
@@ -160,6 +358,8 @@ export function runTourEngine(
return { action: kind, done: true, success: true }
}
+ // No move here: driver fires the step's own onHighlightStarted, which is
+ // where every path — this one, the buttons, arrow keys — does the moving.
if (kind === 'next') {
driver.moveNext()
} else {
@@ -175,6 +375,11 @@ export function runTourEngine(
holder.driver = undefined
}
+ // Belt and braces: destroy() only cleans up what THIS instance built.
+ clearOrphans()
+ holder.release?.()
+ holder.release = undefined
+
return { action: kind, success: true }
}
diff --git a/apps/desktop/src/lib/tour/index.ts b/apps/desktop/src/lib/tour/index.ts
index d70b9b8b9c5..248fffea506 100644
--- a/apps/desktop/src/lib/tour/index.ts
+++ b/apps/desktop/src/lib/tour/index.ts
@@ -21,8 +21,9 @@
*/
export { collectTourTargets, type TourTarget } from './collect-targets'
-export type { TourAction, TourResult, TourStep } from './engine'
+export type { TourAction, TourHost, TourResult, TourStep } from './engine'
export {
+ isTourActive,
listTourTargets,
nextTourStep,
previousTourStep,
diff --git a/apps/desktop/src/lib/tour/run-tour.ts b/apps/desktop/src/lib/tour/run-tour.ts
index 8634cc143e7..88df01d9ab4 100644
--- a/apps/desktop/src/lib/tour/run-tour.ts
+++ b/apps/desktop/src/lib/tour/run-tour.ts
@@ -17,28 +17,84 @@ import './app-tour.css'
import { driver as driverFactory } from 'driver.js'
import { runPreviewTour } from '@/app/chat/right-rail/preview-tour'
+import { revealDesktopPane } from '@/store/pane-focus'
import { collectTourTargets } from './collect-targets'
-import { runTourEngine, type TourAction, type TourHolder, type TourResult, type TourStep } from './engine'
+import {
+ runTourEngine,
+ type TourAction,
+ type TourHolder,
+ type TourHost,
+ type TourResult,
+ type TourStep,
+ type TourStyle
+} from './engine'
+import { type Stage, stopSpotlightBlur, syncSpotlightBlur } from './spotlight-blur'
/** Which document a tour runs against. */
export type TourSurface = 'app' | 'preview'
-/** The app surface's live driver instance, reused across actions. */
+/** The app around the tour, consumed straight from what the app already
+ * exposes: HashRouter means a route IS `location.hash`, and pane reveals are
+ * `revealDesktopPane` (the same path the focus_pane tool drives). Nothing is
+ * registered and nothing persists — a step reads these while it runs. */
+const APP_HOST: TourHost = {
+ currentRoute: () => window.location.hash.replace(/^#/, '') || '/',
+ navigate: to => {
+ window.location.hash = to
+ },
+ revealPane: pane => void revealDesktopPane(pane)
+}
+
+/** The app's own overlay treatment: a softly rounded cutout and a transition
+ * slow enough to read as travel between steps. The fade itself — scrim colour,
+ * strength, and the desaturation of everything outside the spotlight — lives
+ * in app-tour.css, so both layers are tuned in one place and follow the theme
+ * (light fades toward white, dark toward near-black). */
+const TOUR_STYLE: TourStyle = {
+ duration: 520,
+ popoverOffset: 8,
+ stagePadding: 6,
+ stageRadius: 8
+}
+
+/** The one live tour, if any. This is the ONLY thing that outlives an action,
+ * and it holds a driver instance rather than a copy of any app state — the
+ * origin route a navigating tour restores lives in that instance's own
+ * closure, so it dies with the tour. `onDestroyed` empties this slot however
+ * the tour ended (Esc, ✕, overlay click, last step), leaving nothing behind. */
const appHolder: TourHolder = {}
/** Run one tour action on `surface`. Never throws — failures come back as
* `{success: false, error}` so a caller (or the agent) can recover. */
export async function runTour(action: TourAction, surface: TourSurface = 'app'): Promise<TourResult> {
try {
- return surface === 'preview'
- ? await runPreviewTour(action)
- : runTourEngine(driverFactory, appHolder, action, collectTourTargets, document)
+ if (surface === 'preview') {
+ return await runPreviewTour(action)
+ }
+
+ const result = runTourEngine(driverFactory, appHolder, action, collectTourTargets, document, TOUR_STYLE, APP_HOST)
+
+ // Mirror driver.js's cutout onto a blur layer for as long as the tour is
+ // up, and drop the whole thing once it isn't. The layer reads driver's own
+ // per-frame stage rect, so it eases between steps exactly like the cutout.
+ if (isTourActive()) {
+ syncSpotlightBlur(() => (appHolder.driver?.getState?.('__activeStagePosition') as null | Stage) ?? null)
+ } else {
+ stopSpotlightBlur()
+ }
+
+ return result
} catch (error) {
return { error: error instanceof Error ? error.message : String(error), success: false }
}
}
+/** Whether a tour is currently on screen (app surface). The user can dismiss a
+ * tour with Esc, the ✕, or an overlay click, so a caller must never track that
+ * with its own flag — ask here. */
+export const isTourActive = (): boolean => appHolder.driver?.isActive() ?? false
+
/** What's on screen right now, durable (`stable`) handles first. */
export const listTourTargets = (surface?: TourSurface) => runTour({ kind: 'targets' }, surface)