* feat(session): structured externalRefs + list PR chip Add optional metadata.externalRefs for durable session↔GitHub PR identity and a clickable primary-PR chip on session list rows, plus GET /api/sessions/:id/external-refs. Fixes titles-as-identity hacks without title parsing (tiann/hapi#1160). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(session): validate external PR URL identity Prevent structured PR chips from linking outside the declared GitHub repository and pull request. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(session): preserve externalRefs on merge + restore row focus group Carry forward metadata.externalRefs when consolidating into a replacement session row that omitted them (explicit new values still win). Move group/session-row back onto the focusable list button so keyboard tooltips reveal correctly (PR #1161 review). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(session): carry forward externalRefs on bootstrap/metadata write Preserve metadata.externalRefs when CLI pickExistingSessionMetadata and hub updateSessionMetadata receive sparse replacements that omit the field; explicit incoming refs (including []) still win. Closes the resume/bootstrap data-loss path left after mergeSessions (PR #1161). Co-authored-by: Cursor <cursoragent@cursor.com> * feat(session): opt-in GitHub PR awareness and explicit attach Add hub githubPrAwareness (default off), features API, PUT/CLI external-refs write path, Settings toggle, link dialog, hapi link-pr, and MCP link_pr so sessions can attach to PRs without title scraping. Depends on #1161 schema. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(session): cache PR status on externalRefs for chip display Extend GithubPrExternalRef with optional status/statusCheckedAt/statusAction so Meta can write classifier health onto the attachment. Chip renders emoji + #N with status tone. Fixes link_pr tool-list expectations in MCP tests. Part of tiann/hapi#1162 / #1163 (awareness + state in one PR). Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): mock AppContext for General settings language test SettingsGeneralPage now reads githubPrAwareness via useAppContext / useFeatures; wrap the settings page suite with mocks so the language inline test stops throwing AppContext is not available. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): put PR chip left of session list time Chip was a trailing sibling outside the row button, so rows with chips shoved the relative-time column left. Keep time as the stable trailing meta; optional chip sits immediately before it. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): mute PR chip when statusCheckedAt is older than 2h Cache honesty for Meta-filled externalRefs — never live-query GitHub from the browser; stale chips show ? and a muted tone. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): use relative ago in PR chip tooltip title Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): keep companion baseUrl when mocking AppContext for features Co-authored-by: Cursor <cursoragent@cursor.com> * feat(session): forge-native PR chip snapshot + estate display profile Replace Meta babysit status enums with GitHub-shaped openState/checks/merge plus opaque estateCode. Chip terms (emoji, action prose) come from $HAPI_HOME/pr-chip-display.json served on GET /api/features. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): use bun:test in prChipDisplay tests Hub package typechecks include *.test.ts and has no vitest types; CI failed resolving 'vitest' from the forge chip display suite. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(web): compact PR chip to emoji; details on hover/long-press Session list chips show status glyph only (estate emoji, or PR/?) so multi-digit numbers stop crowding the row. Full repo#N + status copy moves to HoverTooltip (desktop hover/focus) and touch long-press. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): show PR detail in session action menu, not chip long-press Keep desktop HoverTooltip on the compact emoji chip. Mobile long-press stays on the session row; linked PR identity/status now tops that menu. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): chip-specific hover tooltip + emoji in PR menu header Keep HoverTooltip scoped to the PR chip (not row), unclip overflow, and front the same status glyph in list long-press and session ⋯ menus. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): give claudeRemote first-result test a 15s CI timeout Same flake as sibling cases under full-suite load; default 5s timed out twice on #1163 after upstream merge. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): drop duplicate vitest timeout after merge Upstream #1493 uses it(name, { timeout }, fn); the merge also kept the legacy third-arg timeout, which Vitest 4 types reject. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub,cli): address Codex Majors on PR awareness Owner-gate PATCH /features, persist githubPrAwareness via updateSettings, and fail MCP link_pr unless flushMetadata keeps the ref. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli,web,shared): close remaining Codex findings on #1163 Gate MCP link_pr on hub awareness, upsert externalRefs, mark undated chip snapshots stale, and hide the settings toggle from tenants. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub,cli,web): CLI features probe + preserve secondary PR refs Expose GET /cli/features and /cli/sessions/:id/external-refs for CLI auth, upsert primary links in hapi link-pr and the web dialog, and tick chip/menu staleness on a minute clock. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub,cli,web): atomic external-ref upsert + create-session gate Hub merges refs inside the metadata-version retry loop; CLI/web call upsert/remove-primary instead of snapshot PUT. Strip externalRefs on CLI create when awareness is off; list chips are display-only in the row button. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(shared,hub,cli): preserve PR health cache on same-identity upsert Re-linking an already-linked github_pr was wiping openState/checks/merge snapshots. Merge identity fields instead of replace-on-upsert. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(shared,cli): case-insensitive PR identity + valid source fixtures Treat owner/repo as case-insensitive on upsert/re-link so cached health is not dropped, and keep regression fixtures within agent|user|inferred. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): initializeToken before hapi link-pr hub calls Match ping-peer/inspect-peer so settings.json auth and apiUrl load before getAuthToken/axios; keep --help free of prompts. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): omit link_pr from standalone hapi mcp defaults Keep awareness opt-in: internal bridges still pass --tools after hub probe. Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): match default MCP tool registration order list_peers registers after ping/inspect on the stdio bridge. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli,shared): exact link_pr auto-approve + single primary refs Stop substring/call-id matching for link_pr, and reject multi-primary externalRefs at the Metadata/PUT schema boundary. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): drop duplicate showSessionSummaryInChat in markdown-a test Upstream merge left a duplicated mock field that broke tsc. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): cap externalRefs count and disable env-pinned PR toggle Bound externalRefs at 32 in schema + socket update-metadata ingress; forward disabled on SettingsSwitch when HAPI_GITHUB_PR_AWARENESS pins the hub. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): validate mutate externalRefs + hapi-scoped link_pr approval Re-parse upsert transforms with ExternalRefsSchema before persist; only auto-approve link_pr when MCP server provenance is hapi or the tool name is a verified HAPI bridge identity. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): trust HAPI link_pr provenance from envelope only Auto-approve link_pr variants only when trustedHapiMcp is set from MCP elicitation envelope serverName, not from tool arguments. ACP no longer reads forged serverName from rawInput; HAPI mcp_tool_call approvals route through the permission handler instead of blanket bridge auto-accept. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): outer envelope only for trusted HAPI MCP provenance Do not treat nested elicitation request.serverName as trusted identity; poll features query so hub-global githubPrAwareness updates reach other tabs. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): reject duplicate external ref identities in schema Case-insensitive github_pr repo+number pairs cannot appear twice in externalRefs; prevents upsert health merge depending on array order. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): bound repo slugs, hoist PR polling, toggle errors Cap GitHub repo slugs at 140 chars; share one features query and minute clock across session list rows; surface githubPrAwareness toggle failures. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): hub upsert link_pr + read-only untrusted gate MCP link_pr uses atomic hub upsert (no metadata flush retry loop); block untrusted link_pr auto-approve in read-only mode. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): authoritative hub upsert + merge retry + 400 invalid refs Stop replaying stale externalRefs through CLI metadata after hub upsert; recompute merge metadata from the latest target row on version retry; map ExternalRefsSchema failures to 400 on upsert routes. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): fail merge before deleting source on metadata contention Use METADATA_RETRY_ATTEMPTS for carry-forward metadata during session merge; throw if externalRefs never commit so the source row is not deleted. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): merge metadata before moving source-owned rows Run carry-forward metadata merge before messages, scratchlist, and attachments transfer so a failed merge leaves the source intact. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): validate externalRefs on CLI session create Share externalRefsInMetadataValid between socket and REST session ingestion so malformed metadata.externalRefs returns 400 before persist. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): reject non-boolean githubPrAwareness in settings.json Match serverChanBackgroundOnly: Boolean("false") is true and would silently enable the opt-in PR-awareness flag from a hand-edited file. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): reveal nested PR chip tooltip on session-row focus Non-interactive chips sit inside the row button as spans; wire SESSION_ROW_TOOLTIP_FOCUS_CLASS so keyboard focus shows the tooltip. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): keep raw metadata when linking PR on unparsed rows mutateSessionExternalRefs reads the on-disk metadata blob instead of cache-null fallback so link/unlink cannot wipe name/summary/worktree. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): prefer merge conflicts over passing checks on PR chip Candidate forge keys now rank conflicting/blocked merge ahead of checks.pass/pending so the chip cannot look healthy when unmergeable. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): localize PR chip detail strings for zh-CN Map default forge labels and checked/stale/linked through i18n so tooltips are not mixed-language; pass estate labels through unchanged. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): prefer terminal PR openState over clean/pass chip Merged/closed/draft snapshots must not show "ready to merge" when the last poll still has clean+pass. Also localize aria-label status via the same forge-label map as tooltips. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): a11y label and i18n for Link PR invalid input Give the PR field an aria-label and show localized invalid-input copy instead of English parseGithubPrInput errors in the dialog. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): gate PR awareness switch; expose nested chip to AT Disable the settings toggle until features load so owners cannot flip a placeholder off state. Nested session-row chips use sr-only detail so the focused row announces PR identity and status. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): refresh MCP link_pr catalog when awareness flips Re-fetch hub githubPrAwareness for each new HTTP MCP session and invalidate stale sessions so listTools picks up the toggle without restarting the Happy server. Stdio --tools remains spawn-scoped. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): gate link_pr at call time without killing MCP sessions Keep link_pr in the HTTP and stdio catalogs under dynamic awareness, and re-check the hub flag on each call. Avoids 404ing the stdio bridge session when Settings toggles awareness mid-run. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): hide MCP link_pr via enable/disable when awareness flips Keep HTTP/stdio transports alive; toggle RegisteredTool visibility from hub settings and sync the Codex stdio catalog without killing cached sessions. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): avoid link_pr list_changed loops; poll idle HTTP clients Only call RegisteredTool enable/disable on actual visibility transitions. Add a bounded awareness poll so Claude HTTP MCP learns Settings flips without a client request, and cover idempotent + poll-only transitions. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(#1163): accept GHES hosts for GitHub PR external refs Fold the upstreamable multi-host parser core into PR awareness: validate github.com and *.ghe.com (plus configureGitHubHosts inject), preserve forge host in parse/build/upsert, and relax schema URL matching accordingly. Browser-safe — no operator YAML or Meta tooling in this change. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): keep GHES host through attach + PR identity Pass parsed.url from UI/CLI/MCP builders, and key identity/dedupe on host+repo+number so github.com and Enterprise PRs with the same slug do not collide or share cached health. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): typecheck link-pr GHES attachment test Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): assert GHES link-pr body via toHaveBeenCalledWith Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): do not auto-approve link_pr in read-only mode Trusted HAPI MCP provenance must not bypass read-only permission mode when linking a PR; leave the write pending for user approval. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): make list PR chip open its PR and show #N Render the session-list chip as a sibling link beside the row button (no nested interactive content) and include the PR number in the compact glyph so operators can tell which PR is linked at a glance. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): drop invalid host from SessionList PR chip test SessionSummaryMetadata has no host field; CI typecheck failed on the fixture metadata literal. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): put session-row focus group on the row button Restore group/session-row on the focusable button so attention and schedule HoverTooltips still reveal under group-focus-visible. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): align stdio default-tool test with peer/session_job catalog Standalone MCP defaults now include spawn_peer and session_job; keep asserting link_pr stays opt-in. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): match merge metadata failure tests to preserve contract SessionCache throws "Failed to preserve session metadata during merge" after exhausted retries / store errors; update hub expectations. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): prompt for Codex link_pr instead of native auto-approve Native approval_mode approve bypassed BasePermissionHandler's read-only guard; prompt so linking a PR still requires permission in read-only. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): satisfy typecheck on link_pr approval regression Avoid optional tools property access that failed cli tsc under strict null checks. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): align archive timeout assertion with 503 Cloudflare contract Upstream #2423 maps ArchiveCleanupError timeout to 503 (not 504) so Tunnel keeps JSON bodies; update the missed singleflight assertion. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): memoize session-list PR clock between minute ticks Avoid sampling Date.now() every render so memoized SessionItem rows do not rerender on unrelated SSE updates when awareness is off. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): preserve machine-spawn stub when attaching a PR External-ref metadata writes used to clear the preallocation tag, so adoptPreallocatedSession failed after an early link. Pass preservePreallocation and cover stub → link → adopt. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): size PR chip padding from quick-action span Pinned active rows show Unpin + Archive; reserve the CSS action span so the chip no longer overlaps Unpin and steals clicks. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): align quick-unpin unread focus test with #2434 panels session-group-unread-peek was removed when collapsed groups kept unread rows in per-row CollapsiblePanels; update the #2443 focus assertion. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1163): unblock passkey browser CI after shared-RP rematch Playwright route.fulfill drops Location fragments on 3xx, so the callback never received #state/#code and the opener hung. Apply the fragment via a document navigation in the harness. Also reuse the parsed complete form body instead of reading the request twice. Co-authored-by: Cursor <cursoragent@cursor.com> * Revert "fix(#1163): unblock passkey browser CI after shared-RP rematch" This reverts commit 0092ea4b8c69add993fdd2f4b3da411eca641364. * Revert "Revert "fix(#1163): unblock passkey browser CI after shared-RP rematch"" This reverts commit 1094372855204375a72101c07fa06f70a1aefdd7. --------- Co-authored-by: Cursor <cursoragent@cursor.com>
hapi-web
React Mini App / PWA for monitoring and controlling hapi sessions.
What it does
- Session list with status, pending approvals, todos, and summaries.
- Chat view with streaming updates and message sending.
- Permission approval and denial workflows.
- Codex
request_user_inputchoices honorisOther: None of the above focuses optional notes, supports empty notes, and preserves the canonical wire value across languages. Recorded other answers and notes remain visible in live and historical cards; Pi/MCP forms without the flag are unchanged. - Permission mode and model selection.
- Machine list and remote session spawn.
- File browser and git status/diff views.
- PWA install prompt and offline banner.
- Optional unread-session count on the Windows taskbar when installed as an Edge/Chrome PWA (toggleable in Display settings; off by default).
Runtime behavior
- When opened inside Telegram, auth uses Telegram WebApp init data.
- When opened in a normal browser, you can log in with
CLI_API_TOKEN:<namespace>(orCLI_API_TOKENfor the default namespace). - The login screen includes a top-right hub picker; if unset, the app uses the same origin it was loaded from.
- Live updates come from the hub via SSE.
- Session
@suggestions require conversation content, including untitled conversations. Names and directory labels affect display/search, not eligibility; empty stubs stay excluded. See the session list behavior guide for search and picker rules.
Routes
See src/router.tsx for route definitions.
/- Redirect to /sessions./sessions- Session list./sessions/$sessionId- Chat interface./sessions/new- Create new session./sessions/$sessionId/files- File browser with git status./sessions/$sessionId/file- File viewer with diff support./sessions/$sessionId/terminal- Terminal interface./browse- Workspace browser, enabled by the runner's configured workspace roots./share- Share-target landing (Web Share Target POST →?id=, or native/share#url=&text=&title=)./settings- Settings category hub (mobile) and responsive master-detail shell./settings/general- Language preferences./settings/display- Appearance, typography, colors, and session list preferences./settings/chat- Message input, concise view, tool card, and conversation color preferences./settings/voice- Everyday voice assistant preferences./settings/voice/voices- Full-page voice picker./settings/voice/advanced- Voice persona, tuning, and diagnostics./settings/machines- Machine management and runner status./settings/storage- SQLite storage sizes for the hub owner./settings/usage- Cache-aware token usage dashboard for the hub owner./settings/about- Application links and version information.
Features
Session list (src/components/SessionList.tsx)
- Active/inactive status indicator.
- Title-side activity/unread indicator: grey spinner while a foreground turn runs with all output read, blue spinner while it runs with unread output, a blue static dot while only background tasks remain, and a theme-foreground dot for unread content when no work is running. Reading clears the unread state without stopping the spinner. Permission/input requests keep their own symbols; the title indicator does not certify a successful turn outcome, and background work is owned by the title rather than duplicated on the agent icon.
- Session title from name, summary, or path.
- Todo progress display.
- Pending permission request count.
- Pending-request status and session-row symbols distinguish questions from approvals and locate the correlated card; async questions open the live question panel.
- Agent name and model display.
- Metadata search with relevance ranking, wildcard matching, and date/unread/machine filters.
- Stable user-input ordering across sessions and machine/project groups; agent output and status updates do not reorder ordinary rows.
- Machine/project grouping, pinned and in-progress sections, and configurable collapsed previews.
Session title lock
The rename dialog has a per-session lock beside the title input. New and existing sessions are unlocked by default. Saving a manual name does not automatically lock it: agents may still rename an unlocked session. Locking prevents agent title updates; users can still edit or generate a title and save it while locked. Save applies the title and lock together; Cancel discards both changes. Unlocking allows future agent title updates without immediately changing the current title. The Hub persists and enforces the lock across clients, restarts, and resume.
Chat interface (src/components/SessionChat.tsx)
- Message thread with infinite scroll.
- Concise view (header toggle or
/settings/chat, per device): shows only user input and each round's final reply (src/chat/conciseView.ts). Permission requests, questions, plan proposals, user shell commands, and errors stay visible; the full thread returns while a search target is active. - Composer for sending messages.
- Composer send shortcut: Alt+S (independent of the Enter behavior setting).
- A collapsible Awaiting your reply section above the composer collects all live non-blocking
request_user_inputquestions, including those outside the loaded transcript. Answer there or dismiss individual questions without sending an answer or stopping the agent. Collapsing preserves drafts; blocking permissions retain their existing controls. - Permission mode and model selection for supported agents.
Cursor Auto uses CLI Auto for new/resumed sessions configured with Auto. Switching a live session to Auto when ACP does not advertise a literal Auto option relaunches the Cursor ACP process in place under
--model autowhile preserving the hub session id. - Session abort and handoff controls.
- Codex Continue planning hides the current proposal's action menu locally and focuses the composer without sending a message or replacing its draft. The plan document remains readable; recycled cards stay dismissed and new proposals get fresh action menus.
- Context size display.
- Per-session scratchlist (
src/components/AssistantChat/ScratchlistPanel.tsx)- Workbench panel for held notes/drafts; distinct from the queue.
- Add/delete/reorder entries; promote to composer (copy) or queue (send).
- Entries and attachments saved on the hub and synced across devices.
- Reordering affects only the current view and resets when entries refresh.
- Keyboard shortcut: Ctrl/Cmd+Shift+S to focus the add-input.
File browser (src/routes/sessions/files.tsx)
- Git status view (staged/unstaged files).
- File search with ripgrep.
- Navigate to file viewer.
File viewer (src/routes/sessions/file.tsx)
- File content display with syntax highlighting.
- Staged/unstaged diff view.
Terminal (src/routes/sessions/terminal.tsx)
- Remote terminal via xterm.js
- Real-time via Socket.IO
/terminal - Resize handling
Voice assistant
- ElevenLabs (@elevenlabs/react), Gemini Live, and Qwen Realtime backends
- Real-time voice control
- Standard and realtime composer dictation with provider capability selection
New session (src/components/NewSession/)
Modular session creation:
- Machine selector
- Directory input with recent paths. The path tail is revealed after loading or selecting a path and after leaving the editor. Unfocused inputs support horizontal touch scrolling; focused inputs retain native editing and text selection.
- Agent type selector
- Model selector
- Per-agent permission, effort, and collaboration controls when supported
First-User-Experience (FUE)
For a new, non-essential feature whose affordance would otherwise be hard to discover, consider the existing FUE primitive rather than a permanent UI block. Optional, not a requirement for every feature or a reason to expand a bug fix.
src/lib/use-fue.ts:useFue(featureId)returns{ status, engage, dismiss }; acknowledgement is isolated per feature inhapi.fue.v1.<featureId>localStorage keys.src/components/Fue.tsx:FueDotmarks the affordance;FueCalloutexplains it whilestatus === 'engaging'.- Dismissal requires an affirmative user action ("Got it"), never an auto-timeout.
- The FUE dot and feature-specific badges/counters are mutually exclusive; onboarding wins until acknowledged.
- Opt in per feature; skip the wrapper if an upstream component already supplies onboarding.
- Working example:
ScratchlistToggleButtoninsrc/components/AssistantChat/ComposerButtons.tsx. Use the source rather than maintaining a copied example here.
Browser settings export/import
Settings → About exports and imports browser-local settings as JSON. Only keys in SETTINGS_STORAGE_KEYS (src/lib/settingsTransfer.ts) move; import replaces them and reloads.
A new hapi* localStorage key must be classified: in SETTINGS_STORAGE_KEYS if the user chose it to configure the app and it makes sense in another browser on the same hub, otherwise in NOT_SETTINGS_KEYS (src/lib/settingsTransfer.test.ts). Data, drafts, last-used values, per-session or per-path UI state, dismissals, device-bound state, credentials, and trust grants are not settings. The test fails on unclassified keys.
Authentication
See src/hooks/useAuth.ts and src/hooks/useAuthSource.ts.
- Telegram Mini App: Uses initData from WebApp SDK.
- Browser: Uses CLI_API_TOKEN from login prompt.
- JWT tokens with auto-refresh.
Data fetching
See src/hooks/queries/ for query hooks and src/hooks/mutations/ for mutations.
- Sessions, messages, machines via TanStack Query.
- Git status and file operations.
- Optimistic updates for message sending.
Real-time updates
See src/hooks/useSSE.ts.
- SSE connection to
/api/events. - Session/message/machine update events.
- Automatic cache invalidation on events.
Syntax highlighting
Code fences load their Shiki grammar on demand and reuse one highlighter. Plain text and unknown languages fetch no grammars; aliases, line wrapping and the 150 ms streaming debounce are retained. A Markdown source fence loads the full supported set to preserve its embedded-language colors. Failed loads or rendering fall back to the current plain text instead of retaining an older code block.
The PWA caches optional grammar/theme chunks after use, outside its install-time precache. Previously used grammars remain available offline; an unseen language falls back to plain text while offline. Only successful JavaScript responses are cached, so SSO HTML/redirects cannot replace a grammar module.
Stack
React 19 + Vite + TanStack Router/Query + Tailwind + @assistant-ui/react + xterm.js + @elevenlabs/react + socket.io-client + workbox + shiki.
Source structure
src/router.tsx- Route definitions.src/components/- UI components.src/hooks/- Data fetching and state hooks.src/api/client.ts- API client.src/types/api.ts- Type definitions.
Development
From the repo root:
bun install
bun run dev:web
If testing in Telegram, set:
HAPI_PUBLIC_URLto the public HTTPS URL of the dev server.CORS_ORIGINSto include the dev server origin.
Tests
Unit tests run under vitest + jsdom:
bun run test:web
End-to-end browser tests for the scratchlist component (real Chromium, real
inert focus blocking, real localStorage round-trips) live at the repo root
under e2e/:
bun run test:e2e # headless
bun run test:e2e:ui # Playwright UI mode (debug)
The spec drives a Vite-served fixture page (web/e2e-fixtures/scratchlist-fixture.html)
that mounts the production ScratchlistPanel in isolation, so no hub /
auth / socket setup is required.
Build
bun run build:web
The built assets land in web/dist and are served by hapi-hub. The single executable can embed these assets.
Standalone hosting
You can host web/dist on a static host (GitHub Pages, Cloudflare Pages) and point it at any hapi hub:
- Build the web app. If your static host uses a subpath, set the Vite base:
bun run build:web -- --base /<repo>/
- Deploy
web/distto your static host. - Set hub CORS to allow the static origin (
HAPI_PUBLIC_URLorCORS_ORIGINS). - Open the static site, click the top-right Hub button on the login screen, and enter the hapi hub origin.
Clear the hub override in the same dialog to return to same-origin behavior.
Shared Passkeys
Web and native apps use RP ID auth.hapi.run. Web registration/sign-in opens
a popup on the isolated static authentication origin; the Hub performs all
verification. The opener keeps the PKCE verifier and exchanges only a short-lived
authorization code. Configure HAPI_PUBLIC_URL as the canonical HTTPS Hub origin.
Separately hosted web apps need an explicit Hub CORS_ORIGINS entry for their
callback origin. Wildcards do not authorize authentication callbacks. Popups
and the opener relationship must be allowed; do not set COOP headers that sever
the cross-origin popup/opener relationship on either site.
Build the independent authentication site with bun run build:passkey-site.
Deploy only website/dist/auth/ to auth.hapi.run, not the marketing app.
Serve the supplied _headers policies (or equivalent host configuration),
including CSP, frame restrictions, origin-only referrers and no-store, and preserve the
.well-known files. No third-party scripts, analytics, or service worker belong
on this origin. The Hub callback path /passkey/callback must serve the web
app shell (including on separately hosted static deployments).
See the authentication contract for transaction, challenge/account binding, and code-exchange details.
The bridge uses Referrer-Policy: strict-origin: only the authentication origin
is disclosed, never its fragment or path. Do not replace it with no-referrer:
Chromium otherwise serializes a cross-origin form POST's Origin as null,
which the Hub correctly rejects. Hub ceremony responses remain no-referrer.
Browser regression: bun run test:passkey:browser uses Chromium's virtual
authenticator against the production Hub and built static site, with all page
requests intercepted locally. It checks both web-created → native and
native-created → web authentication. Install the normal Playwright Chromium
build, or use an existing Chrome with PLAYWRIGHT_CHANNEL=chrome.