The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): tour engine — highlight and narrate any DOM
Brooklyn Nicholson018176915b28
diff --git a/apps/desktop/src/lib/tour/app-tour.css b/apps/desktop/src/lib/tour/app-tour.cssnew file mode 100644index 00000000000..84cd7dd35be--- /dev/null+++ b/apps/desktop/src/lib/tour/app-tour.css@@ -0,0 +1,72 @@+/* Theme bridge for the APP surface's tour popovers: driver.js ships a fixed+ light palette, so repaint it with the app's own tokens and it follows every+ theme (including custom skins) for free. Scoped to driver.js's classes.++ The preview surface keeps the stock look on purpose — it renders inside a+ guest page where these variables don't exist. */++.driver-popover {+ background-color: var(--color-popover);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md);+ box-shadow: var(--shadow-nous);+ color: var(--color-popover-foreground);+ font-family: var(--font-sans);+}++.driver-popover-title {+ font-size: 0.875rem;+ font-weight: 600;+ line-height: 1.4;+}++.driver-popover-description {+ color: var(--color-muted-foreground);+ font-size: 0.8125rem;+}++.driver-popover-progress-text {+ color: var(--color-muted-foreground);+ font-size: 0.75rem;+}++.driver-popover-close-btn {+ color: var(--color-muted-foreground);+}++.driver-popover-close-btn:hover,+.driver-popover-close-btn:focus {+ color: var(--color-foreground);+}++.driver-popover-footer-btn {+ background-color: var(--color-secondary);+ border-color: var(--color-border);+ border-radius: var(--radius-sm);+ color: var(--color-secondary-foreground);+ font-family: var(--font-sans);+ text-shadow: none;+}++.driver-popover-footer-btn:hover,+.driver-popover-footer-btn:focus {+ background-color: var(--color-accent);+ color: var(--color-accent-foreground);+}++/* Each arrow variant paints exactly one border edge; the rest are transparent. */+.driver-popover-arrow-side-left {+ border-left-color: var(--color-popover);+}++.driver-popover-arrow-side-right {+ border-right-color: var(--color-popover);+}++.driver-popover-arrow-side-top {+ border-top-color: var(--color-popover);+}++.driver-popover-arrow-side-bottom {+ border-bottom-color: var(--color-popover);+}diff --git a/apps/desktop/src/lib/tour/collect-targets.ts b/apps/desktop/src/lib/tour/collect-targets.tsnew file mode 100644index 00000000000..2a7ad83c28a--- /dev/null+++ b/apps/desktop/src/lib/tour/collect-targets.ts@@ -0,0 +1,159 @@+/**+ * TOUR TARGET COLLECTOR — discovers what a tour can point at.+ *+ * Fully generic: works on ANY document (the Hermes app's own DOM or an+ * arbitrary page in the preview webview) by scanning for the things that make+ * an element addressable — explicit `data-tour` markers first, then the+ * standard affordances (aria-labels, roles, headings, labelled interactive+ * elements). Each target carries a CSS selector, a human label, and whether+ * that selector is STABLE (an identity attribute that survives a re-render) or+ * merely positional, so a caller can prefer the durable ones.+ *+ * Injected into preview webviews as source (`collectTourTargets.toString()`),+ * so it must stay self-contained: no imports, no closures, no renderer+ * globals. Types erase at compile time.+ */++export interface TourTarget {+ /** Human-readable label (aria-label, text content, alt, title …). */+ label: string+ /** Viewport rect, rounded: [x, y, width, height]. */+ rect: [number, number, number, number]+ /** Element role: explicit ARIA role or the tag name. */+ role: string+ /** A CSS selector that uniquely matches this element right now. */+ selector: string+ /** True when the selector keys off identity (data-tour, id, data-testid,+ * aria-label) rather than DOM position — i.e. it survives a re-render. */+ stable: boolean+}++/** Scan `doc` for tourable elements (capped at `max`). Self-contained. */+export function collectTourTargets(doc: Document, max: number): TourTarget[] {+ const results: TourTarget[] = []+ const seen = new Set<Element>()++ const cssEscape = (value: string) =>+ typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(value) : value.replace(/["\\]/g, '\\$&')++ const labelOf = (el: Element): string => {+ for (const attr of ['aria-label', 'title', 'alt', 'placeholder']) {+ const value = el.getAttribute(attr)++ if (value) {+ return value+ }+ }++ const text = (el.textContent || '').trim().replace(/\s+/g, ' ')++ return text.length > 80 ? text.slice(0, 77) + '…' : text+ }++ /** Identity-based selector, or '' when the element has no durable handle. */+ const stableSelector = (el: Element): string => {+ const dataTour = el.getAttribute('data-tour')++ if (dataTour) {+ return '[data-tour="' + cssEscape(dataTour) + '"]'+ }++ if (el.id) {+ return '#' + cssEscape(el.id)+ }++ const testId = el.getAttribute('data-testid')++ if (testId) {+ return '[data-testid="' + cssEscape(testId) + '"]'+ }++ const aria = el.getAttribute('aria-label')+ const byAria = aria ? el.tagName.toLowerCase() + '[aria-label="' + cssEscape(aria) + '"]' : ''++ return byAria && doc.querySelectorAll(byAria).length === 1 ? byAria : ''+ }++ /** Positional fallback: tag + nth-child path up to an id or <body>. */+ const positionalSelector = (el: Element): string => {+ const path: string[] = []+ let node: Element | null = el++ while (node && node !== doc.body && path.length < 8) {+ if (node.id) {+ path.unshift('#' + cssEscape(node.id))++ break+ }++ const parent: Element | null = node.parentElement+ const index = parent ? Array.prototype.indexOf.call(parent.children, node) : -1++ path.unshift(node.tagName.toLowerCase() + (index >= 0 ? ':nth-child(' + (index + 1) + ')' : ''))+ node = parent+ }++ return path.join(' > ')+ }++ const visible = (el: Element): boolean => {+ const rect = el.getBoundingClientRect()++ if (rect.width < 4 || rect.height < 4) {+ return false+ }++ const win = doc.defaultView++ return !win || (rect.bottom > 0 && rect.top < win.innerHeight && rect.right > 0 && rect.left < win.innerWidth)+ }++ const push = (el: Element) => {+ if (results.length >= max || seen.has(el) || !visible(el)) {+ return+ }++ const label = labelOf(el)++ if (!label) {+ return+ }++ const stable = stableSelector(el)+ const selector = stable || positionalSelector(el)++ // Only report selectors that resolve back to this exact element.+ if (!selector || doc.querySelector(selector) !== el) {+ return+ }++ const rect = el.getBoundingClientRect()++ seen.add(el)+ results.push({+ label,+ rect: [Math.round(rect.x), Math.round(rect.y), Math.round(rect.width), Math.round(rect.height)],+ role: el.getAttribute('role') || el.tagName.toLowerCase(),+ selector,+ stable: !!stable+ })+ }++ // Priority order: explicit tour markers, then landmarks/headings, then+ // labelled interactive elements. Each tier only fills remaining capacity.+ for (const el of doc.querySelectorAll('[data-tour]')) {+ push(el)+ }++ for (const el of doc.querySelectorAll('nav, main, aside, header, footer, [role], h1, h2, h3')) {+ push(el)+ }++ for (const el of doc.querySelectorAll('a[href], button, input, select, textarea, [tabindex], [aria-label]')) {+ push(el)+ }++ // Durable handles first: a caller picking off the top gets selectors that+ // survive a re-render, and positional ones stay available as a last resort.+ return results.sort((a, b) => Number(b.stable) - Number(a.stable))+}diff --git a/apps/desktop/src/lib/tour/engine.test.ts b/apps/desktop/src/lib/tour/engine.test.tsnew file mode 100644index 00000000000..91dc8ecf5cc--- /dev/null+++ b/apps/desktop/src/lib/tour/engine.test.ts@@ -0,0 +1,217 @@+import { describe, expect, it } from 'vitest'++import { collectTourTargets } from './collect-targets'+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 ?? []+ let active = false+ let index = 0++ const instance: TourDriver = {+ destroy() {+ calls.push('destroy')+ active = false+ },+ drive(stepIndex?: number) {+ calls.push(`drive:${stepIndex ?? 0}`)+ active = true+ index = stepIndex ?? 0+ },+ getActiveIndex: () => index,+ highlight(step: object) {+ calls.push(`highlight:${JSON.stringify(step)}`)+ active = true+ },+ isActive: () => active,+ isLastStep: () => index >= steps.length - 1,+ moveNext() {+ calls.push('next')+ index += 1+ },+ movePrevious() {+ calls.push('prev')+ index -= 1+ }+ }++ return instance+ }+}++function seedDom() {+ document.body.innerHTML = `+ <nav aria-label="Primary"><button id="send-btn" aria-label="Send message">Send</button></nav>+ <main><h1>Inbox</h1><div data-tour="composer">Composer</div><section><p>Positional only</p></section></main>+ `+ // happy-dom lays nothing out — every rect is 0×0, which the collector's+ // visibility filter (rightly) drops. Give elements a real-looking box.+ Element.prototype.getBoundingClientRect = () =>+ ({ bottom: 40, height: 32, left: 8, right: 128, top: 8, width: 120, x: 8, y: 8 }) as DOMRect+}++describe('collectTourTargets', () => {+ it('reports resolving selectors, durable handles first', () => {+ seedDom()+ const targets = collectTourTargets(document, 150)++ expect(targets.length).toBeGreaterThan(0)+ expect(targets.some(t => t.selector === '[data-tour="composer"]')).toBe(true)++ for (const target of targets) {+ expect(document.querySelector(target.selector)).not.toBeNull()+ expect(target.label).toBeTruthy()+ }++ // Stable targets sort ahead of positional ones, so a caller taking the+ // first N gets selectors that survive a re-render.+ const firstPositional = targets.findIndex(t => !t.stable)++ if (firstPositional !== -1) {+ expect(targets.slice(firstPositional).every(t => !t.stable)).toBe(true)+ }+ })++ it('flags identity selectors stable and nth-child paths not', () => {+ seedDom()+ const targets = collectTourTargets(document, 150)+ const byTour = targets.find(t => t.selector === '[data-tour="composer"]')+ const positional = targets.find(t => t.selector.includes('nth-child'))++ expect(byTour?.stable).toBe(true)+ expect(positional?.stable ?? false).toBe(false)+ })++ it('honors the cap', () => {+ seedDom()+ expect(collectTourTargets(document, 2)).toHaveLength(2)+ })+})++describe('runTourEngine', () => {+ it('targets answers with the page identity and its targets', () => {+ seedDom()+ const result = runTourEngine(makeFactory([]), {}, { kind: 'targets' }, collectTourTargets, document)++ expect(result.success).toBe(true)+ expect(result.targets?.length).toBeGreaterThan(0)+ })++ it('show validates the selector before touching driver.js', () => {+ seedDom()+ const calls: string[] = []+ const holder: TourHolder = {}+ const factory = makeFactory(calls)+ const bad = runTourEngine(factory, holder, { kind: 'show', selector: '#nope' }, collectTourTargets, document)++ expect(bad.success).toBe(false)+ expect(bad.error).toContain('#nope')+ // The recovery hint points at the re-scan, not a dead end.+ expect(bad.hint).toContain('targets')+ expect(calls).toEqual([])++ const good = runTourEngine(+ factory,+ holder,+ { kind: 'show', selector: '#send-btn', text: 'Click here to send', title: 'Send' },+ collectTourTargets,+ document+ )++ expect(good.success).toBe(true)+ expect(calls.some(c => c.startsWith('highlight:'))).toBe(true)+ expect(holder.driver).toBeDefined()+ })++ it('start → next pages through and cleans up after the last step', () => {+ seedDom()+ const calls: string[] = []+ const holder: TourHolder = {}+ const factory = makeFactory(calls)++ const started = runTourEngine(+ factory,+ holder,+ {+ kind: 'start',+ steps: [+ { selector: '#send-btn', title: 'Send' },+ { text: 'That is the whole flow.', title: 'Done' }+ ]+ },+ collectTourTargets,+ document+ )++ expect(started).toMatchObject({ activeStep: 0, steps: 2, success: true })+ expect(runTourEngine(factory, holder, { kind: 'next' }, collectTourTargets, document)).toMatchObject({+ activeStep: 1,+ success: true+ })++ // Advancing past the last step ends the tour.+ expect(runTourEngine(factory, holder, { kind: 'next' }, collectTourTargets, document)).toMatchObject({+ done: true,+ success: true+ })+ expect(holder.driver).toBeUndefined()+ })++ it('start honors startAt and rejects unknown selectors, naming each', () => {+ seedDom()+ const holder: TourHolder = {}+ const factory = makeFactory([])++ expect(+ runTourEngine(+ factory,+ holder,+ { kind: 'start', startAt: 1, steps: [{ selector: '#send-btn' }, { title: 'Second' }] },+ collectTourTargets,+ document+ )+ ).toMatchObject({ activeStep: 1, success: true })++ const result = runTourEngine(+ factory,+ {},+ { kind: 'start', steps: [{ selector: '#ghost', title: 'x' }, { selector: '#send-btn' }] },+ collectTourTargets,+ document+ )++ expect(result.success).toBe(false)+ expect(result.error).toContain('#ghost')+ expect(result.error).not.toContain('#send-btn')+ })++ it('treats a malformed selector as unmatched instead of throwing', () => {+ seedDom()+ const result = runTourEngine(makeFactory([]), {}, { kind: 'show', selector: '<<<' }, collectTourTargets, document)++ expect(result.success).toBe(false)+ expect(result.error).toContain('<<<')+ })++ it('next without a running tour errors, stop is idempotent', () => {+ const holder: TourHolder = {}+ const factory = makeFactory([])++ expect(runTourEngine(factory, holder, { kind: 'next' }, collectTourTargets, document).success).toBe(false)+ expect(runTourEngine(factory, holder, { kind: 'stop' }, collectTourTargets, document).success).toBe(true)+ expect(runTourEngine(factory, holder, { kind: 'stop' }, collectTourTargets, document).success).toBe(true)+ })++ it('is self-contained source (injectable into a guest page)', () => {+ // The preview surface stringifies these functions into a webview. Any+ // captured import/closure reference would throw there — the source must+ // reference nothing but its own parameters and page globals.+ for (const source of [runTourEngine.toString(), collectTourTargets.toString()]) {+ expect(source).not.toContain('__vite')+ expect(source).not.toContain('import(')+ expect(source).not.toContain('require(')+ }+ })+})diff --git a/apps/desktop/src/lib/tour/engine.ts b/apps/desktop/src/lib/tour/engine.tsnew file mode 100644index 00000000000..2a2c9ca364f--- /dev/null+++ b/apps/desktop/src/lib/tour/engine.ts@@ -0,0 +1,182 @@+/**+ * TOUR ENGINE — the one function that runs a tour action, on BOTH surfaces.+ *+ * The app surface calls it directly (imported driver.js factory + a module+ * holder + `document`). The preview surface injects `runTourEngine.toString()`+ * into the pane's <webview> alongside the driver.js IIFE and calls it with the+ * page's own globals. Because the same source runs in both places it MUST stay+ * self-contained: no imports, no closure references, no renderer globals —+ * everything arrives as a parameter. The minimal structural types below erase+ * at compile time, so the stringified function stays plain JS.+ */++import type { TourTarget } from './collect-targets'++/** The slice of a driver.js instance the engine drives. */+export interface TourDriver {+ destroy: () => void+ drive: (stepIndex?: number) => void+ getActiveIndex: () => number | undefined+ highlight: (step: object) => void+ isActive: () => boolean+ isLastStep: () => boolean+ moveNext: () => void+ movePrevious: () => void+}++export type TourDriverFactory = (config?: object) => TourDriver++/** 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+}++/** One highlighted moment: an element, and what to say about it. Omit the+ * selector for a centered narration step. */+export interface TourStep {+ selector?: string+ side?: 'top' | 'right' | 'bottom' | 'left'+ text?: string+ title?: string+}++/** 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'+ startAt?: number+ steps?: TourStep[]+}++export interface TourResult {+ action?: string+ activeStep?: number+ done?: boolean+ error?: string+ hint?: string+ steps?: number+ success: boolean+ targets?: TourTarget[]+ title?: string+ url?: string+}++/** Run one tour action. Self-contained (see module doc). */+export function runTourEngine(+ factory: TourDriverFactory,+ holder: TourHolder,+ action: TourAction,+ collectTargets: (doc: Document, max: number) => TourTarget[],+ doc: Document+): TourResult {+ const kind = action.kind++ const popoverOf = (step: TourStep) =>+ step.title || step.text+ ? { description: step.text || '', side: step.side || undefined, title: step.title || '' }+ : undefined++ const stepOf = (step: TourStep) => ({ element: step.selector || undefined, popover: popoverOf(step) })++ /** 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+ }+ })++ const missing = (selectors: string[]): TourResult => ({+ error: 'No element matches selector(s): ' + selectors.join(', '),+ hint: "The DOM may have re-rendered — re-scan with 'targets' and prefer targets marked stable.",+ success: false+ })++ if (kind === 'targets') {+ return {+ success: true,+ targets: collectTargets(doc, 150),+ title: doc.title,+ url: doc.location ? doc.location.href : ''+ }+ }++ if (kind === 'show') {+ const gone = unmatched([action])++ if (gone.length > 0) {+ return missing(gone)+ }++ if (!holder.driver) {+ holder.driver = factory({ animate: true, smoothScroll: true })+ }++ holder.driver.highlight(stepOf(action))++ return { action: kind, success: true }+ }++ if (kind === 'start') {+ const steps = action.steps || []+ const gone = unmatched(steps)++ if (gone.length > 0) {+ return missing(gone)+ }++ if (holder.driver) {+ holder.driver.destroy()+ }++ const startAt = action.startAt || 0++ holder.driver = factory({+ animate: true,+ showProgress: steps.length > 1,+ smoothScroll: true,+ steps: steps.map(stepOf)+ })+ holder.driver.drive(startAt)++ return { action: kind, activeStep: startAt, steps: steps.length, success: true }+ }++ if (kind === 'next' || kind === 'prev') {+ const driver = holder.driver++ if (!driver || !driver.isActive()) {+ return { error: "No tour is running — start one first.", success: false }+ }++ if (kind === 'next' && driver.isLastStep()) {+ driver.destroy()+ holder.driver = undefined++ return { action: kind, done: true, success: true }+ }++ if (kind === 'next') {+ driver.moveNext()+ } else {+ driver.movePrevious()+ }++ return { action: kind, activeStep: driver.getActiveIndex(), success: true }+ }++ if (kind === 'stop') {+ if (holder.driver) {+ holder.driver.destroy()+ holder.driver = undefined+ }++ return { action: kind, success: true }+ }++ return { error: 'Unknown tour action: ' + kind, success: false }+}diff --git a/apps/desktop/src/lib/tour/index.ts b/apps/desktop/src/lib/tour/index.tsnew file mode 100644index 00000000000..d70b9b8b9c5--- /dev/null+++ b/apps/desktop/src/lib/tour/index.ts@@ -0,0 +1,34 @@+/**+ * TOURS — highlight-and-narrate walkthroughs for any surface.+ *+ * Two consumers, one engine:+ *+ * - The `tour` agent tool, via the gateway (see run-tour.ts).+ * - Your own curated tours, via this module:+ *+ * ```ts+ * import { startTour, showTourStep, stopTour } from '@/lib/tour'+ *+ * startTour([+ * { selector: '[data-tour="composer"]', title: 'Composer', text: 'Type here.' },+ * { selector: '[data-tour="files"]', title: 'Files', text: 'Your project.' }+ * ])+ * ```+ *+ * Tours run against whatever is in the DOM — mark elements with `data-tour="…"`+ * to give them durable handles (see `collectTourTargets`, which reports those+ * first and flags every selector as stable or positional).+ */++export { collectTourTargets, type TourTarget } from './collect-targets'+export type { TourAction, TourResult, TourStep } from './engine'+export {+ listTourTargets,+ nextTourStep,+ previousTourStep,+ runTour,+ showTourStep,+ startTour,+ stopTour,+ type TourSurface+} from './run-tour'diff --git a/apps/desktop/src/lib/tour/run-tour.ts b/apps/desktop/src/lib/tour/run-tour.tsnew file mode 100644index 00000000000..8634cc143e7--- /dev/null+++ b/apps/desktop/src/lib/tour/run-tour.ts@@ -0,0 +1,59 @@+/**+ * RUN TOUR — the tour verbs, on either surface.+ *+ * `runTour` is the generic entry (one normalized action in, a result out) and+ * the named verbs below are the ergonomic API — used by the agent tool through+ * the gateway, and by any curated in-app tour. surface='app' drives driver.js+ * against the Hermes DOM; surface='preview' runs the same engine source inside+ * the preview pane's guest page.+ *+ * Dynamic-imported by gateway-event.ts, so driver.js (and the preview's raw+ * injection payload) stay off the boot path until a tour actually runs.+ */++import 'driver.js/dist/driver.css'+import './app-tour.css'++import { driver as driverFactory } from 'driver.js'++import { runPreviewTour } from '@/app/chat/right-rail/preview-tour'++import { collectTourTargets } from './collect-targets'+import { runTourEngine, type TourAction, type TourHolder, type TourResult, type TourStep } from './engine'++/** Which document a tour runs against. */+export type TourSurface = 'app' | 'preview'++/** The app surface's live driver instance, reused across actions. */+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)+ } catch (error) {+ return { error: error instanceof Error ? error.message : String(error), success: false }+ }+}++/** What's on screen right now, durable (`stable`) handles first. */+export const listTourTargets = (surface?: TourSurface) => runTour({ kind: 'targets' }, surface)++/** Spotlight one element with a popover, replacing any current highlight. */+export const showTourStep = (step: TourStep, surface?: TourSurface) => runTour({ ...step, kind: 'show' }, surface)++/** Begin a multi-step tour the user pages through with Next/Prev. */+export const startTour = (steps: TourStep[], surface?: TourSurface, startAt = 0) =>+ runTour({ kind: 'start', startAt, steps }, surface)++/** Advance a running tour; past the last step it ends and cleans up. */+export const nextTourStep = (surface?: TourSurface) => runTour({ kind: 'next' }, surface)++/** Step a running tour backward. */+export const previousTourStep = (surface?: TourSurface) => runTour({ kind: 'prev' }, surface)++/** End the tour and clear the overlay. Safe to call when none is running. */+export const stopTour = (surface?: TourSurface) => runTour({ kind: 'stop' }, surface)