Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
client/src/hooks/ — shared React hooks
State + lifecycle + side-effect hooks. Before writing a useX hook, grep this catalog
first — many domain patterns already have one. When you add a new hook, add it to
index.js AND add a row here.
Pure helpers (no React state) live in client/src/lib/. HTTP/socket clients live in
client/src/services/. Formatting helpers live in client/src/utils/.
Discovery rule
grep -i "what you want to do" client/src/hooks/README.md
Notifications & toasts
| Hook | Purpose | Use when |
|---|---|---|
useActionQueue |
Shared canonical Actions snapshot, socket invalidation, reconnect/tab re-show reconciliation and explicit stale/error state. | Bell, dashboard previews and Actions. |
useNotifications |
Generic toast dispatch + socket-subscribed notification list. | You need to read / dispatch the global notification stream. |
useErrorNotifications |
Subscribes to server error events and shows toasts. | Wire once high in the tree to surface server errors. |
useAIStatusNotifications |
Subscribes to AI operation status events. | Wire once to surface AI run lifecycle as toasts. |
useFableLoomAiRun |
Tracks one FableLoom AI operation, including the attachable shell handoff for TUI providers. | FableLoom series or episode AI actions. |
useAgentFeedbackToast |
Agent completion toast with thumbs-up/down UI. | Show actionable agent-run completion feedback. |
useOnDemandTaskToast |
Toasts when a user-triggered on-demand task run found no work (parked). | Wire once high in the tree so an explicit "Run" that parks isn't a silent no-op. |
useEngagementReminderToast |
Shows explicitly opted-in POST reminders only after a durable server delivery claim. | Wire once high in the tree; reloads and tabs share the same occurrence/generation marker. |
useSharingNotifications |
Subscriber for share-bucket notifications. | Wire once to surface federation/sync events. |
useHealthWarningDismiss |
Dismisses a system-health dashboard warning as resolved, with an Undo toast. | The dashboard widget and the Live health overview page both dismiss/undo warnings. |
Pipeline / Story Builder wiring
| Hook | Purpose | Use when |
|---|---|---|
useArcCanvasSync |
Host-side wiring for the embedded <ArcCanvas>: lastSavedRef dirty-check + updateSeriesFromServer (merges, keeping pending bible edits) / handleIssuesUpdate / flushPending / isDirty (for useUnsavedChangesGuard). Parameterized by flushFields (which bible fields to flush) + silent/onFlushError. |
Embedding <ArcCanvas> in a host that owns series/issues state (PipelineSeries, Story Builder arc step). Don't re-implement the setter contract. |
Progress & streaming (SSE / socket)
| Hook | Purpose | Use when |
|---|---|---|
useGoogleAutoConfigProgress |
Request-correlated Google OAuth setup progress with HTTP settlement and listener cleanup. | Calendar and Messages automated setup. |
useQuotaUpdates |
Reconcile quota cards on scrape completion, reconnect and tab show; the caller owns the entry read. | Usage, Subscriptions and Quota Burn quota cards. |
useSseProgress |
Generic JSON-frame SSE subscriber: EventSource for GET, one abortable fetch stream for method: 'POST' without retry. frames is a bounded history (maxFrames, default 200; 0 for latest-only consumers). |
New SSE progress stream — start here, build on top. |
useSseJobSlot |
Generic single-slot SSE job: captured target from preparation through completion, terminal-frame handling (complete/error/canceled), and sse.closed-without-terminal-frame recovery in one place. Returns { active, pending, jobId, percent, stage, context, start, attach, cancel } (attach(jobId, context) adopts a job another request already started into the idle slot); reserves synchronously, exposes context during kickoff and ignores unmounted responses. Optional readPercent adapts other progress scales; connected distinguishes a live stream from reconnecting, and onSettled(reason, context) refreshes persisted state after completion, failure, cancellation or a terminal disconnect. Pass startRequest/eventsUrl/cancelRequest + per-feature toast copy. |
Any "kick off a job → stream SSE → settle on terminal frame" hook. The reference-audio/YouTube/video-download/MIDI/music-video-render hooks all wrap this — don't re-roll the terminal-frame + lost-connection dance. |
useInstallStream |
BYO-runtime install-log stream lifecycle: stage/log/complete/error frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed onComplete, auto-scroll. method: 'GET' uses EventSource; method: 'POST' reads one fetch stream for a non-idempotent install. |
A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes, OpenCode). Don't re-roll the teardown/onComplete-ref dance. |
useModelDownloadStatus |
Image/video model cache-status + SSE pre-download. useDownloadableAssets(descriptors, options) shares readiness and independent integrity dismissals across asset roles. start(id) commands a pull; startWhenIdle(id) requests one — it waits for the cache verdict, skips an already-resident repo, and queues behind whatever owns the single download lane (queuedModelId while it waits, falsy id to retract). |
Surfacing "Available" vs "Download" badge inline in the gen form; startWhenIdle for a picker where choosing an option IS the request for its weights. |
useModelInputPreview |
useModelInputPreview(fetchPreview, body, { enabled }) — the server's preview of what a render would send to its model (#11317), refreshed 500 ms after the form stops changing; superseded responses dropped, a refusal returned as error. |
Showing the exact prompt and its additions beside a render form before Generate. |
useAgyModels |
Live agy models probe (the AGENT models --model accepts) with models/error/loading/refresh; opt-in via an enabled flag so it never spawns for a disabled backend. |
Any Agy model picker — the Settings default or the per-render override. Don't hardcode a model list: agy exits non-zero on an id outside this catalog. |
useSpritePendingRenders |
Sprite render map reconciled on scoped queue events, entry, reconnect and tab show; submitting sentinel, terminal-before-response recovery and 404-only release. | Queue-backed sprite reference/walk renders; persisted assets reconcile separately on sprites:changed. |
useSpriteRecordCrud |
Rename/delete state machine for one sprite record: view/rename/confirm mode, name draft, busy/inline-error, silent PATCH/DELETE. |
A surface that renames or deletes a sprite record (the Library catalog card, the detail header) — share this so both stay in lock-step. |
useImageGenProgress |
Live diffusion progress for an image-gen call. | Showing per-call image-gen progress. |
useImporterProgress |
Live analyze-phase stage checklist via the importer:progress socket (runId-filtered); exports stageStatusIcon for the status→icon lookup. |
Importer analyze progress UI only. |
useProcessLogs |
Live PM2 log tail for one process over the shared socket: owns the logs:subscribe/line/subscribed/error lifecycle, per-processName frame filtering, and a 1000-line ring buffer. Pass appId so an app with its own PM2_HOME streams from the right home. Returns { logs, subscribed, status, statusDetail, retry, clear }; status is connecting/live/closed/error/disconnected, shared by every consumer — a closed/errored/disconnected stream keeps its lines and retry() resubscribes once (#9959). |
Any surface showing a PM2 process's live output (Processes tab, desktop-app launch progress). |
useMediaJobProgress |
Live progress for a single mediaJobQueue job. |
Subscribing to a known media-job id. |
useSceneBatch |
Counter for one Music Video "generate every missing frame / clip" batch (#10153): { state, begin, register, kickoffFailed, completedWithoutJob, settled, cancel, dismiss }. Fed by a lane's onSettled; cancel() cancels the batch's queued and running jobs through the media-job cancel API (spinners clear via the lane's canceled event). |
A batch of per-scene renders that needs "N of M done · K failed" and "Cancel remaining". |
useSceneClipPlayback |
useSceneClipPlayback(scene) owns the native clip ref, filename resolution, clip-ID-keyed metadata, dimensions, legacy loop state and speed/offset-adjusted coverage; returns those values and onLoadedMetadata. |
Keep unconditional in SceneCard so hiding its preview preserves measurements, while a replacement clip invalidates them. |
useSceneRenderLifecycle |
One Music Video board lane's async-render lifecycle: owns the per-scene spinner state (genScenes), job-id→scene correlation, orphan-terminal reconcile, and the durable-attach + *-gen:completed/failed/canceled socket subscription (with running-cancel toast disambiguation). Optional startedEvent / progressEvent feed sceneProgress (queued → running + fraction) and onSettled({ jobId, sceneId, outcome }) reports each tracked job's terminal outcome; failure toasts name the scene + the failed event's error and a batch collapses into one summary toast; restoreJobs([{ jobId, sceneId }]) re-lights spinners after a reload (#10154). Returns { genScenes, sceneProgress, failedScenes, startScene, clearScene, trackJob, restoreJobs }. |
A board lane that kicks media-job renders per scene and clears spinners from terminal events (reference frame, i2v clip). One call per lane. |
useSlotInFlight |
Whether a render slot ({ jobId, filename }) has an in-flight render; returns { inFlight, setStatus }. A present filename (or 5s grace on a stale/expired job) clears inFlight so the render button never sticks "loading". |
A render button that should disable + spin only while its own slot is actually rendering (comic pages, covers). Wire setStatus to the slot's MediaJobThumb onStatus. |
useMediaJobSse |
The one owner of a displayed media render's lifecycle: start(kickoff, handlers, { jobIdOf, ifIdle, onKickoffError }) runs the POST (or an active-job read), adopts the acknowledged job and awaits its /{kind}-gen/:id/events terminal frame; cancel() cancels only that job (before the acknowledgement it cancels the eventual job once, opening no stream); dispose() (also on unmount) detaches without cancelling durable work. A cancelled/detached/superseded run settles once with an error isMediaRunEnded() recognises. attach() stays the bare transport. |
POST-then-attach (or resume-then-attach) media render flows — Video Gen, Image Gen, Settings Test Render. Don't keep a page-local job id / run token / reject ref / raw EventSource close. |
useOpenClawStream |
OpenClaw SSE chat stream. | OpenClaw file-browser chat surface only. |
usePipelineProgress |
Id-derived runner SSE stream: builds the URL from (urlBuilder, ids), connects only when every id is truthy. |
Any runner SSE keyed by record ids (pipeline auto-run, editorial, manuscript completeness, volume beats, story steps). |
useSeriesRunLifecycle |
One series-scoped background run (Reverse Outline, Continuity Bible) from acknowledgement to settlement: adopt(runId?), terminal-frame settle, and the stream-closed-without-terminal-frame recovery (status read → settle / recovery: 'disconnected' → reattach() / 'unknown' → retryStatus()), plus cancel() that reconciles a canceled:false answer. Every async read is guarded by a run token; never POSTs a generation or polls. |
A series-keyed runner view whose server run can be evicted before the client attaches. Pair with RunRecoveryBanner. |
useStoryStepRuns |
Story Builder step generate/refine runs hoisted above the step rail: <StoryStepRunProvider sessionId> owns one run slot per step id (SSE subscription, phase, onComplete/onError handlers, arbitrary meta), useStoryStepRun(stepId) reads/drives it. |
Any Story Builder surface that starts a step run — the panel unmounts on rail navigation, so run state must not live in it (#3905). |
useSeriesEditorial |
Editorial-roadmap aggregate + batch lifecycle (load, re-attach, SSE, start/cancel, reload). | Any view of the editorial roadmap (panel or Reader Map page). |
useReaderPanel |
Reader-panel snapshot (four personas + mined disagreements) + convene lifecycle (load, re-attach, per-persona SSE, run/cancel, reload). | The Reader Map page's Reader Panel tab (#2170). |
Media (annotations, completion, attachments)
| Hook | Purpose | Use when |
|---|---|---|
useAvatarCapabilities |
Verified animated records for the avatar selectors (GET /avatar/rigged) plus the honest state→clip resolvers (resolveStateClip, resolvePlaybackClip, coverageSummary): an uncovered CoS state falls back to a clip the character actually has, never a pretended one. |
Any surface offering or playing a rigged-record avatar (CoS avatar selector, CoS playback). |
useMediaAnnotations |
Per-entry own/others annotations with back-compat aliases. |
Showing media annotations + ownership. |
useMediaCompletionRefresh |
Refetch on image/video completion socket events. | A list view that needs to refresh when new media lands. |
useOpenClawAttachments |
File attachment handling (base64, size-capped). | OpenClaw attachment UI. |
useMediaPreviewActions |
Shared MediaPreview / MediaLightbox action handlers (images + videos — dispatch by item.kind). |
New surface that exposes the same 4 preview actions. |
useClonedGltf |
Clones a drei-cached GLTF scene with skeleton bindings intact and wires its animations; the colocated GltfPrimitive prevents R3F from disposing shared cache resources. Accepts an optional animation transform for derived clip sets. |
Any skinned GLTF rendered from useGLTF; render its scene through GltfPrimitive so remounts cannot inherit disposed geometry or materials. |
usePreviewRoute |
URL-driven [preview, setPreview] via ?preview=<filename>. |
Any page hosting <MediaPreview> — gives the preview a deep-link. |
useHydratedPreviewRoute |
usePreviewRoute plus a lazy single-item lookup of the OPEN preview's gallery record (image sidecar or video-history entry), merged over the host's item. A compact list item (item.compact) never falls back to its prompt preview; a failed lookup marks it detailError. |
Media History's compact grid, and any page that owns its own media refs and composes a styled prompt on the way out (pipeline canon refs, music-video scenes, deck cards) — otherwise the lightbox shows a label the renderer never saw. Use eager useGallerySidecars when the page needs records for more than the lightbox. |
useImageGenForm |
Owns Image Gen form fields, model/LoRA catalog loading, legacy and remix URL restoration, image-input object URLs, mode-dependent capabilities, and image-pick/remix actions. | Image Gen form compositions that need the complete prompt, model, conditioning-image, cleaner, and handoff lifecycle. |
useImageGenGallery |
Owns Image Gen gallery filters, normalized recent/hidden cards, annotations, URL preview state, and local gallery mutations. | Image Gen gallery and lightbox surfaces that share recent-image, annotation, and preview behavior. |
useImageGenPageRuntime |
Composes the Image Gen form and gallery with backend probes, job/SSE progress, batch submission, cancellation, result/error state, federated targets, and regeneration. | The Image Gen page runtime when its route should remain presentational. |
useImageGenQueue |
Work-scoped live queue of in-flight image renders. | Pages that show per-work image-gen queue state. |
useLocalImageRuntime |
The local image runtime's verdict for one model — { runtime, loading, refresh } — from GET /api/image-gen/status?mode=local&modelId=…, the same diagnoseLocalRuntime the renderer refuses against. runtime carries readiness, reason and a one-button remedy. Pass null while the host is still resolving which model it renders on. |
Any surface whose renders can be blocked by an unhealthy local runtime: pair it with LocalRuntimeStatus to show the verdict and its fix, and read readiness to stand the surface's own Render button down. |
useDeckRenderTarget |
What a deck's next card render runs on — { backends, size, summary, localRuntime, blocked } — resolving the RENDER_TARGET.DECK pin ladder, the card trim, and the local runtime's verdict in one call. |
Any deck surface that queues a render or names the options it will use (the render bar, the card grid's per-card re-render) — resolve it once on the page and pass it down rather than probing per consumer. |
useImageRenderSettings |
Load settings and project shared record → target → install render preferences; returns { imageCfg, backends }. imageCfg.inheritedBackend distinguishes inherited display/runtime preferences from explicit form overrides; local model admission stays server-side. Pass includeExternal to also list an enabled external image service. |
Single-image render slots; pass record and target, and retain the owning record tag on submission. |
useUserTimezone |
Resolve the user's configured IANA timezone (settings.timezone) once, falling back to the browser zone then UTC; returns the tz string. |
A date-scoped surface that must derive "today" the same way the server does (POST launcher/history day keys, #2681). |
useSingleImageRender |
Queue-one-render / wait-for-completion jobId lifecycle: builds opts from imageCfg, calls buildPrompt, POSTs generateImage, tracks the jobId head, and runs a once-per-(key, filename) completion guard before onComplete. |
Single-image render slots driven by EntryThumbSlot/MediaJobThumb (style probe, characters step). Completion SSE stays in the thumb. |
Sockets & lifecycle
| Hook | Purpose | Use when |
|---|---|---|
useProcessSnapshot |
PM2 snapshots from entry reads and server pushes, with reconnect/reshow recovery and stale-read protection. | Process lists and native-launch panels; pass an app id for custom PM2 homes. |
useCosTaskUpdates |
Shared five-event CoS task lifecycle subscription; re-subscribes on socket reconnect and forwards normalized task updates to the current callback. | A CoS task surface with its own task-status reducer. |
useSocketResource |
Initial resource read plus global/room-event, reconnect and tab-show reconciliation; single-flight reads, identity guards, an enabled gate and immediate mutation updates. | Views replacing content polls with existing socket invalidations. |
useFableLoomRun |
Revisioned editorial/production snapshots, identity-safe mutation replies and entry/reconnect/reshow recovery. | FableLoom run views. |
useSocketSubscription |
Refcounted <namespace>:subscribe/unsubscribe for a registerSubscriber room: the first mounted consumer subscribes and re-emits on every socket reconnect, the last to unmount unsubscribes, onResubscribe refetches whatever a consumer may have missed while disconnected, and payload/releasePayload let one consumer set and later release a server-side room mode (ChiefOfStaff's taskLists). |
Any hook/page that emits a literal <ns>:subscribe for cos/errors/notifications/agents/instances/loops/beeper — don't hand-roll the reconnect dance; client/src/socketSubscriptionConventions.test.js enforces this. |
useAccountSyncStatus |
Per-account busy/auth state and deduplicated HTTP/socket sync outcomes. | Calendar and Messages sync controls. |
useSocket |
Shared socket instance; the caller re-renders on connect/disconnect. useSocketConnected (same file) returns the live connected flag as a boolean. |
You need to subscribe to a socket event, or show connection state (components/SocketReconnectingPill.jsx). |
useItermSession |
Socket.IO iterm:* state for the Shell page's iTerm2 view (#8114): list subscription, URL-selected attach with a strict pending-target guard, byte-exact input, and an xterm sized to iTerm2's own grid (never fit, never resized back). Never touches shell:*. |
|
useShellSession |
All Socket.IO shell:* session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (pendingAttachRef {target,generation}, claim, userIdleRef, mountedRef), URL sync, and every session action. Returns { terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCd, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession } so the route stays presentational. sendCd(path) sends a FOLDER over shell:cd rather than composing a cd line — the server renders it for the session's actual shell (server/lib/shellCd.js), which is the only form that works on a Windows cmd.exe session. sendCommand(cmd) submits with CR, never \n (see SUBMIT_KEY in server/lib/tuiHandshake.js). sendImage(file, message) is the one operation that leaves the socket — it POSTs to /api/shell/sessions/:id/image so a running agent TUI gets the photo's path pasted into its prompt. |
The Shell page (pages/Shell.jsx) — don't re-roll the single-subscriber PTY attach lifecycle. |
useUpdateChecker |
Update-available + install-out-of-sync advisories as state ({ update, outOfSync, ignoreUpdate, dismissUpdate, clearOutOfSync, dismissOutOfSync }), never toasts — a non-transient advisory must not occlude the screen's primary action (#3786). Out-of-sync dismissals persist per on-disk commit in safeStorage, so a later git pull re-raises; clearOutOfSync is the session-only clear used when the user acts on it. |
Never call it directly — components/UpdateBanners owns the single instance and Layout renders that once at the app root. A second caller means a second status fetch and socket subscription. |
useCharacterAugmentation |
The propose → tick → selectively-apply loop for cast-integrity character augmentation (#6417): owns preview/accepted/proposing/applying and enforces the rules both surfaces share — nothing accepted until ticked, "no improvement offered" is a success not an error, and a lock stops the flow at propose AND at apply. Caller supplies only the two request thunks and an onApplied. |
A surface that augments character framework fields — Universe cast panel and the Writers Room Cast pane both use it; do not re-roll the state machine. |
useMaintenance |
Server-confirmed maintenance status and refresh; { mode: 'banner' } follows the coarse maintenance:readiness push instead of refetching. |
Admission hold, blockers, and reconnect invalidation; the global banner. |
useLatestRequest |
begin() → isCurrent(): a latest-request-wins guard. Each begin() supersedes earlier requests (and unmount supersedes all), so an older response resolving late can see isCurrent() === false and drop its setState. |
A load keyed on changing input (a debounced search, a ?subject= route param) where responses can arrive out of order and overwrite the view the user has already moved to. |
useMounted |
mountedRef whose .current is true while mounted. |
Async deferred work that must abort on unmount. |
useMemoRecorder |
Owns one memo recorder through permission prompts, stop/cancel, and unmount; exposes { recording, starting, start, stop, cancel, stream }. |
Catalog voice memos and song takes. |
usePortosRestartWatch |
Watches PortOS restarting ITSELF and reloads the page once it answers again: arms on the update stream's restart step, on portos:update:complete, or on a socket disconnect confirmed unreachable, then polls /api/system/health for a version change, a down→up dip, or an uptime reset. update.sh pm2-deletes the server mid-run, so there is no completion event to await. |
Only a surface that launches a PortOS self-update WITHOUT going through an app operation — today just the Update page. useAppOperation already wires it, so App Management surfaces read restarting from there instead. |
usePrevious |
Returns the value from the previous render — snapshot updated in a useEffect. |
Compare-and-act on prop/state change from inside a useEffect. |
usePreviousSync |
Same shape, but snapshot updated during render. | The prior value gates an in-render setState (React's "adjusting state on prop change" pattern); the during-render update avoids an extra discard/rerun cycle. |
useTimeTick |
Singleton-backed wall-clock tick (Date.now()); N subscribers at the same cadence share one setInterval; { enabled: false } unsubscribes a counter whose subject has stopped. |
A widget renders something derived from Date.now() (relative timestamps, threshold-based health labels, countdowns) and is also fed by a deduped useAutoRefetch — without this the label goes stale until the data changes. |
useVisibilityEvent |
Singleton-backed document.visibilitychange subscription (N subscribers share one listener). |
Reacting to tab show/hide without spawning a per-component listener. useAutoRefetch already builds on this. |
UI / interaction
| Hook | Purpose | Use when |
|---|---|---|
useAnchorReveal |
useAnchorReveal(getTarget, key, { reveal? }) — scroll a freshly-opened element into view + flash a tint over it; re-fires when key changes; no-op when key is falsy or getTarget() is null. |
Reveal an editorial finding's anchored manuscript text on open / prev-next step (#1601). |
useAutoRefetch |
Poll-based refetch on an interval, single-flight per instance (ticks during a pending fetch are dropped; mid-flight refetch() calls share one trailing fetch). { pollOnly: true } skips internal data/loading state for side-effect-only callers (returns { refetch } only). |
Only a sanctioned poll — a source that cannot push (hardware telemetry, an external system with no callback). Polling is an anti-pattern: prefer a socket event, adding the server emit if it is missing. |
useSystemActivity |
One shared bounded system-activity snapshot. Socket invalidation coalesces to a single read; reconnect and reshow reconcile missed frames. A failed read stays unknown, never idle. | Update banner and the live-activity widget. GPU samples stay on a visible-only poll — they have no event. |
useAutoSizeTextarea |
[ref, resize] — grows a <textarea> to fit its content (no scroll / hand-resize); recomputes before paint on value change. |
A textarea that should auto-fit content. Prefer the AutoSizeTextarea UI component, which wraps this. |
useChartColors |
Resolves the --port-* theme tokens (accent/success/warning/error, chart-1..4, grid, axis, tooltip surfaces) to concrete rgb() strings via getComputedStyle, re-resolving on theme switch. |
A recharts card needs theme-following colors — SVG fill/stroke props can't read CSS vars, so pass these resolved strings instead of hardcoded hex. |
useClickOutside |
Fire onOutside on mousedown outside a ref — or outside every ref in an array. |
Popovers, menus, drawers. Pass [triggerRef, panelRef] for a portaled panel, which is outside the trigger's subtree. |
useCancelableDebounce |
[schedule, cancel] — schedule(fn, delay) arms a cancelable setTimeout, replacing any pending call; cancel() drops it with no replacement. Call cancel() synchronously right before a navigation that a stale debounced write must not be able to race (React's own unmount cleanup runs asynchronously relative to navigate(), leaving a window under load). |
Any debounced state→URL mirror sitting in front of a route that can change out from under it (Catalog, MediaCollections search-query mirrors) — don't re-roll a bare setTimeout/clearTimeout pair. |
useConfigDraftRevision |
Revision protocol for an editable config draft a server response may overwrite: draftDirty plus markDirty/markSaved/supersede/reset and snapshot() → { wasClean, isStillCurrent() }. |
A form draft with in-flight save/action requests whose responses must not clobber newer edits — pair with shouldReplaceDraft (Eidoverse world controls). |
useConfirmDelete |
Single-at-a-time { confirmingId, isConfirming, requestDelete, cancelDelete, confirmDelete } for arming one list/card row at a time. |
New destructive list action — pair with <InlineConfirmRow> / <ConfirmButtonPair> instead of deleting on the raw trash click. |
useEscapeKey |
useEscapeKey(active, handler) — call handler on Escape while active. |
Non-modal dismissables (in-context popovers/cards); Modal owns Esc for true modals. |
useHoverTooltip |
{ hoveredNode, tooltipPos, handleHover, handlePointerMove } for a canvas hover tooltip. handlePointerMove drops any move that cannot paint a tooltip (nothing hovered, or a touch pointer, where the tooltip is pointer-coarse:hidden), so idle cursor motion stops re-rendering the page. The gate reads a ref, not the hovered state — r3f raycasts on the Canvas' inner div while React delegates the container's move handler, so the enter event's own move still sees the pre-flush null. |
Any 3D graph/canvas view with a cursor-following hover tooltip (BrainGraph) — pass { x: e.clientX, y: e.clientY } to handleHover from the mesh's onPointerOver so the first frame is placed. |
useFocusTrap |
useFocusTrap(active, containerRef, { initialFocusRef? }) — moves focus into the container on open (initialFocusRef if given, else the first focusable), traps Tab/Shift+Tab so it can't escape to the page behind — including from an initialFocusRef aimed at a tabIndex={-1} element, which is outside the tab order and would otherwise fall through to the browser — and restores focus to the opener on close (WCAG 2.4.3 / 2.1.2). |
Modal surfaces (dialogs, drawers, lightboxes). Already wired into Modal and Drawer — reach for it when hand-rolling a new overlay. |
useNoteSave |
useNoteSave({ vaultId, notePath, content }) → { saving, save({ force }), forceOffered, dismissForce } — writes an Obsidian note and owns the iCloud force-save escape hatch: forceOffered turns on only after the server has twice refused the SAME note with a stalled (retrying-cannot-help) verdict. |
Any editor that saves a vault note. Render <ForceSaveNoteRow offered={forceOffered}> next to the editor; never call save({ force: true }) from anything but that row's confirm. |
useVaultNote |
Reads a URL-selected vault note with a sequence guard; returns { note, setNote, loading, error, retry, clear, sequenceRef } and reports failed reads separately from empty selection. |
Brain Notes and Wiki Browse detail panes. |
useCmdKSearch |
⌘K open/close state. |
Anywhere that needs to toggle the palette. |
useContainerWidth |
[ref, width] via ResizeObserver. |
Layout responds to a specific container's width. |
useCooldownTick |
1-second ticker over a { id: epochMs } cooldown map; fires onAllExpired once when every deadline passes. |
Rate-limit countdown labels that need to refetch when the last cooldown clears (agents tabs pattern). |
useDragToPan |
Shared drag-to-pan gesture: mouse-only pointer drag scrolls a surface by writing scrollLeft/scrollTop directly, past a per-caller slop threshold, with built-in click suppression so ending a drag over a control doesn't activate it. canStart(event) opts a gesture out (an interactive child, or another gesture that already claimed the pointerdown); onPanEnd(moved) lets a caller with more than one drag source (a card's own drag) fold this into its own combined click-suppression ref. Returns { surfaceRef, panProps, panned, isPanning }. |
Any pannable overflow surface bigger than its pane (FableLoom's scene graph, a stretched chart) — don't re-roll the scrollLeft/scrollTop drag math. |
useDrawerTab |
Deep-linkable [activeTab, setActiveTab] for a tabbed <Drawer>, backed by a caller-named URL search param (falls back to a default on stale/missing). |
A tabbed config drawer whose open section should be shareable/bookmarkable — use with <Drawer tabs>; don't re-roll the search-param plumbing. |
useLocalLlmStatus |
{ status, loading, selected, setSelected, loadStatus, runAction, installBackend, actionInProgress, busy, progressMsg, setProgressMsg, confirmAction, setConfirmAction } — the installed-model status both local-LLM views read, the single localLlm:progress subscription, and the one busy/toast/refresh path every action routes through. Takes stable onRefresh (extra loads on a status refresh) and onReload (extra reload after an action or complete frame) callbacks. |
LocalLlmRuntimesView / LocalLlmLibraryView — they never mount together, so the mounted one is the only subscriber. |
useDownloadPreflightConfirm |
{ confirm, request({ title, preview, run }), cancel, confirmRun } — shows a loading modal, resolves a disk-preflight assessment, and holds run until confirmed. |
Any weight/LoRA download confirm step — pair with <DownloadPreflightConfirm>. |
useFieldDraft |
Local input draft that commits on blur. | Bible-editor-style single-field input that must dedupe sibling races. |
useSettingsForm |
{ values, saved, isDirty, set(path, value), load(values), markSaved(values?) } — one reducer holding a settings form's editable values and the saved snapshot they are diffed against; a field is one entry in the loaded object, set takes a dotted path or an updater. |
A settings tab/drawer with many fields and a Save button (the Media settings drawer) — instead of one useState per field plus a hand-maintained saved mirror and dirty check. |
useFilmLookPresets |
{ presets, save(label, look), remove(id) } — the install's saved film looks (settings.filmLookPresets), loaded once and shared by every caller on the page. |
Film look controls, the per-shot look picker. |
useStoryImportIntake |
Story Builder "Import a finished work" intake: the form fields plus the analyze → commit → create-session workflow, in one { ...state, patch, analyze, retryIssues, importAndBuild } bag. |
Call from the always-mounted Story Builder index and pass down as intake — holding this in the panel loses the manuscript and analysis on an intake tab flip (#3904). |
useRowDraft |
Multi-column row draft (analogue of useFieldDraft). |
Multi-column row that commits as a unit. |
usePendingListRows |
List-of-rows where a new row is held client-side until a required column fills, then promoted to onChange. |
Editable list whose nameless rows would otherwise be dropped by the server sanitizer (WardrobeSection, CharacterDetailEditor list sections). |
useFirstTouchHint |
{ visible, showOnFirstTouch } — reveals a brief one-time touch gesture hint, then auto-hides it. |
3D canvases whose primary one-finger gesture needs an initial explanation. |
useKeyCapture |
useKeyCapture({ enabled?, enabledInDialog?, onKeyDown, onKeyUp }) — capture-phase window listener whose handler claims an event by returning true; a claimed event is preventDefaulted AND stopImmediatePropagationed so no app-global bubble handler sees it. Which events are offered is decided by the shared shouldIgnoreGlobalKey predicate (lib/a11yKeyboard.js): never events from an editable field, never Space on a focused button (so native activation still works), and not while an aria-modal dialog is open ({ enabledInDialog: true } for a surface that lives INSIDE one — same name and default as useKeyboardShortcuts). Auto-repeat and ⌘/Ctrl/Alt chords deliberately DO still arrive, because a claiming surface tracks press/release itself. Each listener subscribes only when its handler is supplied. |
A surface that must own a key an app-global handler already binds — chiefly Space, which the voice widget uses for push-to-talk: the POST cognitive drills (n-back, go/no-go, reaction-time), the Morse keyer, RapidReader, the OpenWorld playback transport, and the exploration-mode jump key. Not for ordinary shortcuts (that is useKeyboardShortcuts). |
useKeyboardShortcuts |
useKeyboardShortcuts(active, bindings, opts?) — fire a { key: handler } map while active; ignores whatever the shared shouldIgnoreGlobalKey predicate (lib/a11yKeyboard.js) rules out — editable fields, Space on a focused button, ⌘/Ctrl/Alt chords, OS key auto-repeat ({ ignoreRepeat: false } to opt back in), and any keystroke while an aria-modal dialog is open ({ enabledInDialog: true } for a modal-owned shortcut); a falsy handler disables that key. |
Single-surface action shortcuts (editorial comment card prev/next + accept/dismiss/generate, #1603). Not for held-key game input. |
useHfTokenStatus |
Reads the central HuggingFace token status (GET /image-gen/setup/hf-token-status → server/services/hfToken.js: stored → env → hf auth login). Returns { present, source, refresh } where present is TRI-state — null means "unknown/failed", not "absent" — so a slow fetch can't flash a token nag at a user who has one. { enabled } gates the fetch (false resets to unknown, so a modal re-checks per open); { errorAs: 'absent' } opts a surface into offering the paste form when the status call fails. |
Any gated-HuggingFace surface (3D page, MIDI gated modal, Image Gen banners) — use this instead of re-rolling the fetch, or the same blip renders differently per page. |
useKeyboardHelp |
Esc closes, even from inputs/textareas. | Help/cheatsheet modals. |
useLiveSuggest |
Post-typing debounce for an imperative panel trigger: { registerTrigger, scheduleSuggest } re-arms one debounceMs timer per keystroke and fires the registered fn only while enabled and still mounted. |
An editor that asks a sibling AI panel to suggest once the writer pauses (WorkEditor ↔ LiveContinuationPanel). |
useLockToggle |
Optimistic-PATCH lock toggle. | New "lock this field/stage/arc" button — use this, do not re-implement. |
usePersistedOptions |
Registry for "saved default + per-run override" form options: one spec row per option ({ defaultValue, read, clamp, persistOnEdit }) owns the state, per-field dirty flag, hydrate-if-untouched pass and edited-only override collection. Returns { values, edit, hydrate, collectOverrides, inputProps }, all identity-stable and ref-backed so a caller's useCallback needs one dep instead of one per option. |
Any panel where each option must load a saved default, persist edits, and send ONLY edited fields as per-run overrides (AutopilotPanel) — use this instead of hand-copying the state/editedRef/hydrate/collect scaffold per option. |
usePopoverPosition |
Viewport-clamped { left, top, width } for a fixed-position portal popover anchored to a trigger; re-measures on open and rAF-coalesced on capture-phase scroll/resize. Returns { triggerRef, popoverRef, style, reposition }; pass anchorRef to follow a parent-owned trigger and align for start/center/end (default end); opt into constrainHeight to cap scrollable help to the roomier side of its trigger. |
Any portal-into-<body> menu/popover placed relative to a button (ThemeSwitcher, CollectionPickerShell) — use this instead of re-rolling the measure/flip/clamp/reflow plumbing. |
useScrollLock |
Body-scroll lock with ref-count. | Modals, drawers, lightboxes. |
useStickToBottom |
useStickToBottom(containerRef, { enabled, revision }) keeps an overflow-y-auto container pinned to its bottom as content grows; a user scroll up unpins, scrolling back to the bottom re-pins, and enabling opens at the tail. |
A live log or transcript panel (the CoS agent card's running output). Pass the growing array as revision. |
useSidebarResize |
Drag-to-resize split-pane width persisted to localStorage; returns { containerRef, width, maxWidth, onMouseDown, reset } and caps the drag at maxFraction of the measured container. |
A desktop sidebar/split pane with a draggable divider (WorkEditor's storyboard sidebar). |
useSwipeNav |
Horizontal swipe prev/next. | Mobile swipe between siblings. |
useTokenPopover |
Hover/click/pin state machine for an anchored token popover (200ms open, 150ms grace close) plus the hotRef cross-link highlight; returns { pop, hotRef, onTokenEnter/Leave/Click, onPopoverEnter/Leave, closePopover }. |
Prose (or any) tokens that open a detail popover on hover and pin on click (WorkEditor ↔ ProseTokenPopover). |
useUnsavedChangesGuard |
useUnsavedChangesGuard(isDirty, { beforeUnload, scopePath }) → { blocked, proceed, reset } — parks router navigation (sidebar link, ⌘K, voice nav, browser Back) behind react-router's useBlocker while a draft is dirty, and arms beforeunload for tab close/reload. Auto-proceeds once the draft goes clean. scopePath is the path prefix the editor owns, exempting its own pathname-changing in-page moves (a splat route's tab switch). Requires the data router in main.jsx; tests must mount createMemoryRouter + <RouterProvider>. |
Any editor holding an unsaved draft (SongBookViewer, PipelineManuscriptEditor, writers-room WorkEditor) — render the confirm with <UnsavedChangesConfirm guard={…} when={!saving}>, never window.confirm. |
useUrlParams |
[searchParams, updateParams] — updateParams(patch, { replace }) merges a patch into the query string and deletes keys set to null/undefined/'' so a cleared filter leaves the URL clean. Reads the live params off a ref (react-router's functional updater is closure-stale) and is referentially stable. |
Any page whose filter/sort/selection state lives in the URL (Catalog, MediaCollections, Media3D) — don't re-roll the merge-and-prune loop. |
useValidTab |
Resolve the active tab from the :tab URL param against a TABS list, falling back to a default on invalid/missing. |
Any tabbed page whose tab lives in the URL — don't re-roll the new Set(TABS.map(...)) guard. |
useAsyncAction |
running state + toast-on-error. |
Buttons that await an async action. |
useBackupRun |
Manual backup pending state, result feedback, and completion callback. | Dashboard and Settings backup actions. |
useAutoscroll |
rAF autoscroll for a scrollable container: advances scrollTop by pxPerSec, auto-stops at the bottom, pauses on user wheel/touchmove, live speed changes via ref. fitToDuration(sec) solves the speed for a target run time from the measured scroll travel (returns the applied px/s, or null when there is nothing to scroll). Returns { playing, toggle, stop, pxPerSec, setPxPerSec, fitToDuration }. |
SongBook play view; any teleprompter-style surface. |
useAudioSessionClaim |
useAudioSessionClaim(type) → { claim, release } — one arbitrated acquireAudioSession(type) slot with a React lifecycle: claim() drops this instance's previous claim before taking a fresh one, release() is idempotent, and unmount releases whatever is still held. |
A surface owning its OWN AudioContext (MorseTrainer, the Security monitor) or getUserMedia stream (useSingToScore/useSingToVerify) needs the iOS session. An output-only player on the shared transport passes audioSession: 'playback' to createLookaheadTransport instead — don't hand-roll either. |
useAsyncCaptureGuard |
Shared pending-request and generation guard for microphone permission prompts; returns { tryStart, settleStart, isCurrent, cancel } and delegates resource teardown plus caller-owned idle reset. |
Any capture hook that must reject concurrent getUserMedia starts and dispose a stream resolved after cancellation. |
useAssignableInstances |
useAssignableInstances() → { instances, loading, isFederated } — this install's assignable federated instances (self + identified peers) for pinning a CoS task to one machine. Silent fetch; isFederated is false on a single-instance install so callers can hide their picker. |
Any surface offering "which machine should run this?" — the CoS task add form and the task editor. |
useWakeLock |
Holds a screen wake lock (navigator.wakeLock) while active is true; releases on unmount/inactive, re-acquires on visibilitychange; no-op where unsupported. |
Hands-free surfaces that must keep the screen on (SongBook autoscroll). |
Storage & persistence
| Hook | Purpose | Use when |
|---|---|---|
useFailedCaptures |
Recoverable rejected Brain captures: { failures, fail(payload, error, id?), markRetrying(id), discard(id) } keeps each failed submission's immutable payload apart from the composer's next draft; never re-sends by itself (the host's explicit Retry does). |
A capture box that clears its input on submit (Inbox, Quick Capture) and must not lose the text when the server rejects it. Pair with components/brain/FailedCaptureList. |
useLocalStorageBool |
Boolean useState mirrored to localStorage; returns [value, setValue, toggle]. |
Per-user UI preference toggle, and any remembered disclosure (the SongBook viewer's Audio / Sheet controls / Chords used cards). |
useNavWorkingSet |
Sidebar Pinned + Recent working set (localStorage MRU + pins); resolves stored paths to { path, label, icon } rows via a resolveNavEntry arg. |
Rendering the sidebar's Pinned/Recent sections. |
Sidebar navigation data
| Hook | Purpose | Use when |
|---|---|---|
useFocusRefreshedList |
Load-once-then-refresh-on-focus list fetcher: debounces focus refreshes to 30s, sorts by name, and skips re-render when an id|name signature is unchanged. Owns its own warn-on-error. |
Any sidebar/nav list that should refresh when the user returns to the tab without hammering the API. Pass a stable api.* fetch fn. |
useInstanceFeatures |
Shared read of Settings > Features with a module-level cache, so the sidebar, ⌘K, and the Features tab collapse to one fetch. Returns isFeatureEnabled(id); publishInstanceFeatures announces a toggle on the existing INSTANCE_FEATURES_CHANGED window event (the channel the reminder toast and the dashboard widgets already use). Fails open on a fetch error so navigation is never blanked. |
Gating a sidebar row, page, palette entry, or widget on an optional instance feature (post, datadog, jira, gsd). Pair with lib/navFeatures.js for manifest entries. |
useSidebarApps |
Apps list for sidebar nav: socket-driven (apps:changed), archived filtered out, name-sorted. |
The sidebar apps section. |
useSidebarSeries |
Pipeline series for the Create > Pipeline grandchildren (built on useFocusRefreshedList). |
The sidebar pipeline-series section. |
useSidebarUniverses |
Universes for the Create > Universes grandchildren (built on useFocusRefreshedList). |
The sidebar universes section. |
Apps / Sessions / Domain
| Hook | Purpose | Use when |
|---|---|---|
useAppDeploy |
Stream deploy.sh output via Socket.IO. |
App deployment surfaces only. |
useAppOperation |
Socket-based app ops (update, standardize) with step tracking. | App operations UI. |
useAppOverrideActions |
Per-app scheduled-task override mutations ({ handleUpdateOverride, handleBulkToggleOverride }) with shared toast copy + silent flag; pass the tab's refetch. |
Any surface hosting PerAppOverrideList (Schedule tab, Timeline tab) — don't re-copy the write-plus-toast-plus-refetch handlers. |
useTaskAddForm |
Reducer-backed CoS task form orchestration: draft reconciliation, provider/app/feature loading, template and reviewer defaults, uploads, submit gating, and immutable task payload construction. | TaskAddForm and any future surface that needs the same task-entry state machine. |
useTaskModelPins |
Provider/model/effort pins for one CoS scheduled task: optimistic write per change ('' → null clears; picking a provider clears model+effort, picking a model clears the effort only when that model has no tiers at all), rollback when onUpdate resolves falsy, a saving flag to gate "Run Now", plus the derived availableModels (Antigravity base models, stale pin kept selectable), effectiveProviderId and defaultProviderLabel a ProviderModelSelector needs. |
Any surface that retargets a scheduled task's model (schedule card quick controls, config drawer Global defaults) — don't re-roll the select/PUT/rollback trio. |
useRunWithPicker |
Consolidates "Run with" agent picker for app-detail surfaces: owns provider/model/effort state, the process-provider filter, the provider-change effort-reset rule, and returns { selectorProps, pin } where selectorProps spreads onto ProviderModelSelector and pin is the request fragment { provider?, model?, effort? } with empty values dropped. seed prefills a saved pin once the catalog loads. |
Any surface dispatching a CoS task (Issues tab, Pull Requests tab, LaunchVideoPanel, SlashDoRunDrawer) — don't re-assemble the picker setup. Consolidates four duplicate implementations. |
useCanonPatch |
Optimistic canon-entry patch: rebuild the kind list with one entry mutated, apply locally, PATCH the universe, re-apply the server copy. Targets + staleness-guards on the loaded record's universe.id so a mid-flight universe swap can't cross-PATCH or resurrect stale state. apply is setUniverse or onUniverseChange. |
Inline canon-field edits on a universe (UniverseCanonSection, NounsStage). Don't re-roll the optimistic-then-confirm dance. |
useColorMatch |
Drives a song color-match run: counts the singer in with the metronome, walks the notated score in tempo, grades each note against the live mic pitch (#1022 tracker + colorMatch lib), and exposes { running, countingIn, noteColors, summary, activeIndex, start, stop } for the <ScoreSheet> + an accuracy readout. Taps the passed recording stream (no second mic); tears down on stop/unmount. |
The Song editor's color-match panel. Don't re-wire the metronome + tracker + grading loop by hand. |
useClaimReviewers |
The reviewers a /do:next claim will ACTUALLY run for one app — claim-work task metadata resolved OVER the Code Review Defaults, with source naming the layer that won. Stays resolved: false on a failed lookup so "couldn't ask" never reads as "nothing configured". |
Any claim launcher (SlashDoRunDrawer, IssuesTab). useCodeReviewDefaults can't see a claim-work override and would show reviewers the run won't use. |
useCodeReviewDefaults |
Global Code Review Defaults (Review Loop reviewer chain + every per-reviewer <reviewer>Model / <reviewer>Effort pin scalar) via a small Provider/hook pair. |
TaskAddForm, ScheduleTab, anywhere a default reviewer picker is shown. |
useCatalogTypes |
Catalog ingredient type registry (system + user-defined) merged with the static fallback via a Provider/hook pair; synchronous fallback to the built-in six so first render never blanks. | Catalog list/picker/editor; anywhere the catalog type list/lookup is needed. |
useDeathClock |
1-second countdown for death-clock display. | Mortality / death-clock surfaces. |
useFederatedMediaTarget |
'Render here, or on a peer?' for one media kind (#4348): loads the opted-in provider peers, intersects the local per-kind allowlist with the peer’s advertised capabilities, and resolves one readiness verdict via resolvePeerMediaReadiness. Returns the selection state plus submissionFields (mediaProviderPeerId/mediaProviderEngine/modelId), a blockedReason carrying the remedy, and verify() which re-runs the same gates against the clock at submit time. supports(feature) and acceptsInput(role) are bound over the selected peer’s status snapshot so no form holds it directly — the underlying helpers take that status optionally and fall back to the pre-#4826 per-capability reading when it is omitted, which would fail open. Never polls — a capacity window expires on the clock, so only the submit-time check is trustworthy. |
Any render form offering a federated target: RemoteMediaTargetPicker in Image Gen, Video Gen, Music Studio. |
useGoalDetail |
All state + handlers backing the GoalDetailPanel (edit form, todos, milestones, plan/phases, check-ins, progress log, activity/calendar links). Loads activities + subcalendars on mount. | GoalDetailPanel composition shell; not intended for reuse outside the goals panel. |
usePostSession |
MeatSpace POST drill-run state, refresh snapshots, scoring, and idempotent test/training saves. | POST launcher and drill runners. |
useRecordMerge |
Duplicate Universe/Series merge flow: open → dry-run preview → resolve field conflicts → execute, with an onMerged refresh callback. Drives <MergeModal>. |
Surfacing the merge-duplicates UI anywhere (Sharing → Duplicates, Universes page). Don't re-implement the preview/execute dance. |
useProviderCatalog |
The composition catalog behind the preset-first ProviderModelSelector and ProviderComposePopover (#7566): one module-shared fetch of GET /api/providers/catalog (harnesses + enablement, service instances, bootstrap apps, per-harness/per-model effort ladders, compatibility map, sanitized presets), plus compatiblePairs(harnessId), methodsFor(harnessId), modelsFor(serviceSlug), effortLevelsFor(harnessId, model), resolveRef(id) (a preset record, or a synthesized display record for a composite id — no server round trip, so a saved value renders instantly), and savePreset(input) (POST /providers/presets, "Save as preset"). Gate the fetch with the popover's open so a picker that never composes pays nothing. invalidateProviderCatalog() drops the shared cache and makes every mounted hook re-read — the AI Providers page calls it after a harness toggle, a service write or a bootstrap save (#7567), so an open picker's compose flow reflects the change without a reload. |
ProviderComposePopover; any picker that needs to resolve/display a composite id or list harnesses/services/effort ladders without a fresh /providers/composites/:id round trip. |
useProviderModels |
AI providers + two-step provider→model selection. | Any UI that picks a provider + model. |
useReviewerModelOptions |
Selectable model ids and concrete provider defaults per model-taking reviewer for ReviewerPicker's Model column — local-LLM ids from /api/local-llm/status, codex/claude/antigravity tiers from /api/providers (claude's list also spans installed Ollama ids for an Ollama-backed CLI; agy's list collapses to base ids since the row has its own Effort cell). Returns { optionsByReviewer, defaultModels, freeText, unavailable, loaded, reviewers }. |
Every surface that renders ReviewerPicker (Code Review Defaults, TaskAddForm, ScheduleTab, SlashDoRunDrawer) — the picker never fetches; pass this as its modelOptions. |
useLocalImageModels |
This install's local image-model catalog plus the model a blank pin resolves to (settings.imageGen.local.modelId → the shipped default), enabled-gated so nothing is probed until a local render is in play. models is null until fetched, [] when genuinely empty. |
Any local image-model picker — the Settings Local default, and the per-record pin row on decks/universes/series/sprites/music video. |
useLocalModels |
Live installed Ollama/LM Studio model ids per backend, runtime capability badges, the server's editorial recommendation, and installed per backend (null until fetched) — the app-level verdict that counts a macOS bundle with no CLI shim. |
Model pickers that must show currently-installed local models (not just a provider's stale stored models), or explain a selected model's live capabilities. Fold in via mergeModelLists + localBackendForProvider. |
useVisionModelIds |
{ idsByProvider, loaded } — vision-capable model ids the server reports (Ollama /api/show + LM Studio type:'vlm'), keyed by the provider id that serves them ({ ollama: Set, lmstudio: Set }), null until fetched; loaded flips once the fetch settles. Drops backend:'cli' rows (a blanket per-provider claim, not a per-model fact) and never vouches for a provider the server didn't enumerate. |
Any VISION model picker — pass idsByProvider to visionLocalModelFilter / assignmentModelOptions so a new multimodal family (gemma4) isn't hidden by the stale client id regex, and so an installed VLM shows even when the provider's stored models snapshot is stale; gate any "none installed" messaging on loaded and on the provider being a local backend. |
useToolUseModelIds |
{ idsByProvider, loaded } — TOOL-USE (function-calling) capable model ids the server reports (Ollama /api/show tools capability + LM Studio catalog capabilities) via /api/local-llm/tool-use-models, keyed by the provider id that serves them ({ ollama: Set, lmstudio: Set }), null until fetched; loaded flips once the fetch settles. One module-shared fetch across every mounted caller, retried on a later mount if it failed. |
Any AGENT model picker — pass idsByProvider to localToolUseHint / withToolUseOptionLabel so a tool-capable family the client id regex predates (phi4-mini) isn't mislabelled "⚠ no known tool use", and gate the annotation on loaded so the warning isn't asserted mid-fetch. |
useTerminalFullscreen |
useTerminalFullscreen(isFullscreen, exitFullscreen) → { containerRef, toggleRef } — focus trap + Escape-to-exit (ignored while typing inside the terminal) + focus return to the toggle button (unmounted while fullscreen, so useFocusTrap's own restore misses it). |
The Shell and iTerm fullscreen overlays; any terminal-style surface that swaps its own trigger out when maximized. |
useTheme |
Dark/light theme + paired-theme switching. | Theme picker. |
useThreejsModelFamilies |
Three.js subject-family checklist options served by /api/threejs-models/families; [] when the fetch fails, plus the exported GENERAL_FAMILY_ID default. |
Any surface picking a subject family — the taxonomy is served, never mirrored client-side, so the picker and the generation prompt cannot drift. Hide the picker on an empty list rather than rendering an empty select. |
useSingToScore |
Capture a sung melody from the mic and transcribe it into lead-sheet notation. start() opens the mic, counts in on the shared metronome, then accumulates a pitch track relative to beat 1; stop() runs the transcribePitchTrack pipeline (segment → quantize at the song tempo → spell for the key) and returns the lead-sheet body. Exposes { phase, beat, result, error, start, stop, reset }; tears down mic/analyser/tracker/metronome on stop and unmount. |
The Song editor's Sing-to-score panel. |
useSingToVerify |
Captures a singer from a selected score bar after a one-bar count-in, aligns the pitch track to written-note windows, and exposes { phase, beat, rows, error, start, stop, reset, toggleAccept, acceptAll } for explicit note-by-note correction. Tears down mic/analyser/tracker/metronome on stop and unmount. |
The Song editor's Sing-to-verify panel. |
useRoundViewParams |
The Round editor's three URL-param views (?mode=edit, ?stack=1, ?analyze=<refId>) as one hook — every setter replaces so flipping surfaces doesn't pile up history. Returns { editing, setMode, stackOpen, setStack, analyzeId, setAnalyze }. |
/rounds/:id. Add a new Round view here rather than a fourth ad-hoc useSearchParams reader. |
useRoundDraft |
The Round editor's draft lifecycle: load /rounds/:id (resetting to loading on every id change so a partner-link navigation can't save the old draft into the new song), hold the in-memory draft, explicit save (buildRoundPatch, re-points an open ?analyze= deep link at a freshly-saved reference's twin), refreshTemplate, and the AI applyGenerated merge. baseDirty compares the draft's score/key against the last server-persisted savedBase so the derive-harmony action can gate on SAVED state. Returns { song, setSong, loading, savedBase, baseDirty, setField, save, saving, refreshTemplate, refreshing, applyGenerated }. |
/rounds/:id. |
useRoundRows |
Row-level edits on a Round draft — add/update/remove for lyric sections, voice layers and references, applyProposedPart (an analysis-proposed part into the base melody or the harmony parts, capped at SCORE_PARTS_MAX), and remainingPresets (foundation-first VOICE_LAYERS the draft hasn't added, matched on preset id). Nothing persists — the page's Save does. |
The Round edit form + the reference-analysis workbench. |
useRoundPartners |
A Round's quodlibet partners: the all-rounds list (re-fetched per open song, best-effort), partnerSongs (ids resolved to records, missing ones dropped), otherSongs (alphabetical pick list) and togglePartner (capped at PARTNERS_MAX). |
/rounds/:id — the "Sings with" editor and the stacked-parts view. |
useSongTraining |
Drives a song training run over one scope (whole song or a sliced section) on top of useColorMatch: counts in, walks + grades the scope's score, then folds the finished take into the rolling progress history (songProgress.recordAttempt) and surfaces the next aggregate via onProgress. Supports looping (auto-restart after a run) and keeps a lastSummary. Exposes { running, countingIn, noteColors, activeIndex, lastSummary, start, stop }; cancels pending loop relaunches on stop/unmount. |
The Song editor's Training panel. |
useSyncIntegrity |
Fetches per-kind integrity diff from every eligible online peer; reduces to worst-case statusById + byPeer breakdown maps. |
Federated media sync integrity UI — badges, drawers, peer breakdown. |
useSyncSourceSettings |
Shared enabled/interval scheduler settings lifecycle for a machine-local sync source, including status loading, dirty tracking, interval clamping, and save state. | Source settings tabs that use getSettings / updateSettings with a source-specific status endpoint. |
useBeeperOutbox |
The Beeper composer's send lifecycle (#36): submit(body, { clearsDraft = true }) creates the durable outbox row then sends it, surfaces the server's first-contact refusal as an inline confirmation (never a toast, never window.confirm), and refetches when a confirmation invalidation lands. Never retries a send that touched the wire, and latches submit so two calls in one render cannot create two rows. retry(entry) is the narrow exception — it re-dispatches a row still approved, i.e. one refused before the server could claim it (OUTBOX_BREAKER_OPEN), where nothing reached Beeper; dismiss(entry) gives up on such a row, discarding it server-side. onSent fires only for a send whose text IS the draft (clearsDraft), so a failed row's retry cannot clear a newly typed message. Returns { entries, sending, error, confirmation, submit, confirmAndSend, cancelConfirmation, retry, dismiss, refresh }. |
The Beeper thread composer (#35's Send action, wired on #53). |
useBeeperRealtime |
Subscribes to the server's Beeper realtime relay — invalidation frames ({ kind, chatID, ids, seq, ts }, never message content) plus the connected / reconnecting / down transport state. Re-emits beeper:subscribe on every socket connect. Returns { realtime, connectionState, lastInvalidation, seedRealtime }. |
Any Beeper surface that must refetch when the mirror changes (#33). |
useBeeperSettings |
The settings.beeper ingestion + connection slice (enabled, intervalMinutes, baseUrl, attachmentBudgetGb) as a load/edit/save lifecycle, mirroring useSyncSourceSettings but for Beeper's extra fields. Deliberately never reads or writes token/tokenExpiresAt — the server redacts the token from every getSettings response and rejects one on write (#30/#31). Returns { loading, form, setForm, saving, dirty, save }. |
The Comms → Beeper settings card (#30). |
useSystemResourceReport |
The system-resource disk scan plus its cleanup lifecycle: generation-guarded runReport (a late scan can never resurrect rows a newer one removed), one-delete-at-a-time removal keyed on the candidate's server-issued action, and report invalidation after a successful delete. Returns { report, setReport, loading, runReport, cleanup } — cleanup is the prop bag StoragePanel/ModelsPanel/CleanupControl expect. |
Dev Tools → System Resources → Storage, and Models → Status. Don't re-wire the scan/cleanup pair by hand. |
useImageTo3dTargets |
The image-to-3D target registry (GET /api/image-to-3d/targets), fetched once per mount. Returns { targets, loading, error, reload } — error is first-class, because a failed registry read is NOT an empty registry and both call sites render that distinction. |
The /3d render flow (target picker + readiness summary) and Models → 3D (install/repair). Don't re-roll the fetch in a third surface. |
useTwinEvaluationSuite |
Shared lifecycle for the three Digital Twin evaluation-suite panels (Values-Alignment, Adversarial-Boundary, Multi-Turn): loads suite + recent history (silenced), runs every selected provider/model in parallel, prepends fresh runs, and handles the stale-persona / partial-failure toast fan-out. countField names the suite's pass-count key so history stays generic. Returns { items, history, loading, running, results, expanded, setExpanded, run, reload }. |
The Digital Twin TwinEvaluationSuitePanel presentation shell — don't re-roll the load/run/history dance per suite. |
useRepoIntake |
The Brain capture boxes' repository state: repo (the parsed {host,owner,repo} when the ENTIRE capture text is a github.com/gitlab.com repo URL — i.e. exactly when the server will clone it), the two sticky post-clone agent opt-ins (options/toggle, persisted to localStorage), the useRepoStudyConfig knobs it composes, and intakeFor(submittedText) which re-derives at submit time so a sticky tick can't ride along on a capture retyped into a plain thought. Also exports the pure capturedRepo(text). |
Any capture surface that should offer the malware-scan / repo-study runs. Render with components/brain/RepoIntakeOptions; don't re-parse the text in the component. |
useRepoStudyConfig |
The knobs a repo-study dispatch takes — target managed app, the free-form brief, and an optional provider/model/effort pin — plus studyPayload() for the request body. |
Any surface that dispatches a repo study: the capture-time opt-in (via useRepoIntake) and the Links tab's on-demand "Update & study". Render with components/brain/RepoStudyFields. |
useRenderJobQueue |
Per-entry render-job queue for the Universe Builder — pendingByEntryId (entryId → jobId[]), pendingHeadByEntryId (first jobId per entry for single-subscription thumbs), enqueueEntryJobs (append variation/canon jobs), clearPendingForEntry (shift a jobId out, or drop the entry). |
Universe Builder render orchestration. Don't re-roll the per-entry pending-jobs reducer. |
useUniverse |
Loads the universe record for a universeId with mount/cancel guards; returns [universe, setUniverse, loading, error] (setter exposed for optimistic post-mutation updates). |
Any surface that loads a linked universe (pipeline stages, etc.) — use instead of re-rolling the getUniverse-on-mount effect. |
useUniverseAction |
LLM-driven universe mutation scaffolding. | Universe Builder action UIs. |
useUniverseBucketActions |
The Universe Builder's three bucket-scoped LLM mutations — handleGenerateInCategory (eager local merge then best-effort save), handlePromoteVariation, handleAutoSort (both via useUniverseAction) — each with its own ref+state in-flight gate. Returns { autoSorting, handleAutoSort, handleGenerateInCategory, handlePromoteVariation, promoting }. |
Universe Builder composition shell; keep the stale-snapshot merge rules out of the page and the trunk/Other panels. |
useUniverseDraft |
Universe Builder editable-record lifecycle: initial catalog/provider/image settings load, selected-universe hydration, create/save/delete, saved-draft dirty baseline, pending-canon addition merge ledger, keyed category mutations, and lock persistence. | Universe Builder composition shell; expansion/refinement and rendering consume this hook's draft contract instead of owning persistence themselves. |
useUniverseExpand |
Universe Builder LLM expansion + holistic refine lifecycle, including lock-preserving request payloads, deletion-wins pending-canon auto-save, provider selection, and refine-panel state. | Universe Builder Bible panel; keep provider calls and canon-aware auto-save out of presentation components. |
useRecentImageGallery |
Bounded recent-five reads, global totals, lazy hidden pages and exact preview lookup. | Image Gen recent renders. |
useUniverseGallery |
Page-level lightbox + gallery-metadata concern for the Universe Builder. Takes { draft, runsLength }; hydrates a filename→sidecar map (prompt/seed/model), derives previewItems across variations, composite sheets, style probes, and canon/character-sheet refs (namespaced-key dedupe), and wires usePreviewRoute + useMediaPreviewActions + useMediaAnnotations. Returns { previewItems, preview, setPreview, previewActions, openPreviewByFilename, openVariationPreview, annotations, updateAnnotation, bumpGalleryRefresh }. |
Universe Builder image lightbox — don't re-roll the gallery-sidecar/previewItems derivation. |
useUniverseRender |
Universe Builder batch-render settings, scoped render payload compilation, canon-selection defaults, per-entry job queue, and run-list refresh. Returns the shared runRender/handleRender action used by the Render tab and inline bucket/canon controls. |
Universe Builder composition shell and presentational panels; don't fork render payload semantics per tab. |
useUniverseTabs |
useUniverseTabs(categories) → { activeTab, activeBucket, bucketsByKind, hasOtherBuckets, setTab, setBucket }. URL-backed (?tab=&bucket=) tab + sub-bucket state for the Universe Builder, including the self-healing effects that replace-strip a tab/bucket the current categories no longer support. |
Universe Builder composition shell — don't re-roll the tab/bucket search-param plumbing or the stale-param cleanup. |
useUniverseNav |
goToWorld(id) → navigate to /universes/:id, preserve location.search. |
Any Universe Builder caller that needs to switch worlds via URL. |
useVideoFileSrc |
useVideoFileSrc(jobId, { enabled }) → { src, resolving, retry }. Resolves a video-history id to the file it really points at (/data/videos/<filename>) via the by-id lookup GET /api/video-gen/history/:id. Returns source fps when known; opt-in { geometry: true } measures missing dimensions/cadence through the one-record read. |
Any surface rendering a video by history id where the id is NOT the filename stem — notably a CD finalVideoId (the timeline renderer mints timeline-*.mp4 beside a randomUUID() id, so /data/videos/<id>.mp4 404s while <id>.jpg poster loads). Pass the result to <ScenePreview src=…>. Gate autoplay on resolving. |
useVoiceUiSync |
Keeps voice server's UI index in sync with current page. | Wire once at root for voice agent support. |
useMoltworldWs |
Moltworld WebSocket feed. | Moltworld surfaces only. |
useYoutubeIngest |
One YouTube brain-ingest job slot: start/cancel + SSE progress + terminal-frame handling via POST /api/brain/youtube/ingest. Returns { active, percent, stage, start(body), cancel } — start takes the whole payload ({ url, captureTranscript, downloadVideo, ingestAudio, note, agentPrompt, tags }), not a bare URL. onComplete(ingest) fires with the stored ingest record; non-fatal warnings[] on the terminal frame are toasted automatically. |
Quick Capture's YouTube path, and any other surface that ingests a video into the brain. |
useYoutubeTrackImport |
One YouTube-audio-import job slot (#1945): start/cancel + SSE progress + terminal-frame handling via POST /api/tracks/import/youtube. Returns { active, percent, start(url, context), cancel }; onComplete(track, context) fires with the finished Track. Call once per UI surface that can independently kick off an import — a shared slot would let one surface's kickoff orphan another's in-flight job. |
Any picker that lets a user paste a YouTube URL to create a Track (Music Video's create form and track-change row). |
useVideoGenFieldState |
Mutable VideoGen field values, setters, and lifecycle refs initialized from URL handoff values. | Internal state slice composed by useVideoGenForm; keep model reconciliation and submission behavior in their focused units. |
useVideoGenForm |
useVideoGenForm({ models, modelContext, availableLoras, grokEnabled }) → every VideoGen form field + setter, the URL-param prefill paths (ImageGen handoff, Continue, Remix, ?lora=), the mode/backend transitions that clear stale inputs, the derived model/keyframe/IC gates (extendModeBlocked, a2vModeBlocked, icLoraModeBlocked, keyframesError), applyRemix / applyResumedParams, and buildGeneratePayload(). |
The /media/video form — the single client-side source of truth for the payload server/routes/videoGen.js validates. Reuse it for any second entry point that generates video. |
useVideoGenSubmitFlow |
Builds the current VideoGen wire payload and enveloped prompt from a form-state snapshot. | Internal submission slice composed by useVideoGenForm; all local, Grok, and federated request shaping remains in videoGenSubmission. |
useVideoGenValidation |
Derives keyframe errors and all VideoGen submit-blocking predicates from the current fields and model capabilities. | Internal validation slice composed by useVideoGenForm; also exports validateVideoKeyframes for focused tests. |
useVideoDownload |
One full-video-download job slot (#1946): start/cancel + SSE progress + terminal-frame handling via POST /api/devtools/video-download. Returns { active, percent, stage, context, start(url, context), cancel }; onComplete(video) fires with the finished video-history entry. |
The Dev Tools Video Downloader page. |
useForgeScopeRefresh |
One forge-token scope-refresh slot for a managed app (useSseJobSlot over POST /api/apps/:id/forge-auth/refresh): start(scopes) runs gh auth refresh for the app's own forge host (server-derived, enterprise hosts included), device is the { code, url } the user approves in a browser (null until gh prints it), onRefreshed() fires on confirmation. Returns { active, pending, device, start, cancel }. |
Any surface that hits a FORGE_TOKEN_SCOPE_MISSING error — pair with <ForgeScopeFix>. |
useReferenceAudioImport |
One round reference-audio-import job slot (#2120): start/cancel + SSE progress + terminal-frame handling via POST /api/rounds/reference-audio/import. Returns { active, percent, stage, start(url, context), cancel }; onComplete(filename, context) fires with the uploads-dir filename to persist on the reference. Call once per surface that can independently kick off a download. |
The reference-audio attach controls (ReferenceAudioAttach) — the "Download from URL" convenience. |
useMidiTranscription |
One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass startRequest/eventsUrl/cancelRequest). Returns { active, stage, stageLabel, context, start(context), cancel } (stageLabel is the ready-to-render human label for the current STAGE — including a distinct "Downloading model…" for the first-use weight download, which also fires a one-time toast; context is the in-flight job's captured target, for per-target UI gates); onComplete(frame, context) fires with the terminal frame (filename, model, any server-merged extras). |
The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. |
useMusicVideoYoutubeImport |
The Music Video page's two independent useYoutubeTrackImport slots (create form + detail-view track row) plus their URL drafts, the detail slot's captured target project, and the URL-nav backstop that bounces a deep link / Back / ⌘K jump away from an in-flight import back to its project. Returns { createUrl, setCreateUrl, editUrl, setEditUrl, createJob, editJob, startCreate, startEdit, switchBlockedMessage }. |
The Music Video page. Reuse switchBlockedMessage for any additional guard (delete, list picker) so every surface says the same thing. |
useMusicVideoKickoff |
The Music Video autopilot kickoff sequence — analyze → import track lyrics → separate vocals → align words → Cast & Sets check-in → plan — each step skipped when its result already exists and handed the freshest project. A failed analysis stops the run; a failed lyric/vocal/align step still plans; the check-in gates the plan (a sheet waiting for review ends the run until the director approves). A step that throws is toasted by name, a failed or interrupted check-in ends the run with a note, and cancel() (#9940) stops it. Returns { step, stepLabel, running, run(project), cancel() }. |
The Music Video "Analyze & plan" button. |
useMusicVideoCastAndSets |
The Cast & Sets check-in before the plan: applies the project pushed on music-video:cast-and-sets / music-video:dev-artifact and exposes start / regenerate(notes?) / resume / approve / skip, plus runToCheckpoint(project) (start if absent, resolve at review/approved/skipped/failed — or interrupted by a restart, which would otherwise never settle) for the kickoff and cancelWait() to abandon that wait. |
The Music Video autopilot card and sheet viewer. |
useMusicVideoDevArtifacts |
A project's development files ("ingredients"): import a file or a new version, add/resolve notes, approve / request changes, remove; applies the returned project. Returns { busy, upload, addNote, resolveNote, review, remove }. |
The Music Video Development section and viewer drawer. |
useMusicVideoVocalSeparation |
"Separate vocals" (demucs) as a useSseJobSlot: start(projectId) for the button, run(projectId) as a promise resolving with the project carrying its new stem (or null on failure/cancel), stageLabel for install/separation progress, onSeparated(projectId, project) on success. |
The Music Video vocal-stem control and the autopilot kickoff. |
useMusicVideoLyricAlign |
Lyric word alignment as a useSseJobSlot (#10155): run(projectId, cueId?) is a promise resolving with the aligned project (null on cancel/dropped stream, rejecting with the server message on failure), attach(jobId, projectId) adopts a running job after a reload, stageLabel/percent for model-download and per-phrase progress, onAligned(projectId, project) on success. Slot context is { projectId, cueId }. |
Music Video Setup Align words / Re-align and the autopilot kickoff. |
useMusicVideoMidiJob |
useMidiTranscription bound to the music-video API surface, plus the MuScriptor model-size picker state (read fresh at each kickoff). Returns the slot (active/stage/stageLabel/context/start(projectId)/cancel/installGate/gatedGate) plus { model, setModel }; onTranscribed(projectId, midiTranscription) fires on a non-discarded terminal frame. |
The Music Video MIDI button + model select. |
useAutonomousMusicVideo |
Fully-autonomous run (prompt → lyrics → Suno song → video): applies the project pushed on music-video:autonomous and toasts the outcomes that need the director (checkpoint waiting, needs you, finished, failed). Returns { busy, resume(edits?, { inline }?), stop(), cancel() } (an inline resume rejects instead of toasting, for errors shown next to the control). |
The Music Video autonomous run panel. |
useMusicVideoProduction |
Server-owned production run (#9066): start a browserless plan → frames → clips → reviewed-draft run with an allowed provider/model pool and explicit limits, and Stop / Resume / Cancel it; applies the project pushed on music-video:production and toasts terminal outcomes. Returns { busy, start(body), resume(runId, body?), stop(runId), cancel(runId) }. |
The Music Video production panel. |
useMusicVideoRenderJob |
The final-render job (#1760 Phase 2): kickoff (409 → attach to the existing job), SSE progress, terminal-frame handling and non-terminal stream-close recovery. Thin useSseJobSlot adapter with 0–1 progress conversion; returns { active, pending, context, job, progress, start(projectId), cancel, reattach(projectId), reattaching }; a project the server marks rendering re-attaches on load through a READ of the live job (GET /:id/render), never a POST (#9940); onSettled(reason, projectId) fires on every terminal frame; onRendered(projectId, result) / onFailed(projectId) key on the projectId captured at kickoff. |
The Music Video "Render final" control. |
useMusicVideoShotRenders |
The composed final render's per-shot segment cache: GET /:id/shot-renders re-read as render inputs change (debounced) and when a shot render settles, plus live music-video:shot-render progress per shot. Returns { status, live, markLive(sceneId, entry), refresh }; status is null outside the composed render style. |
The shot card's Final render section and the Render final control. |
useMusicVideoStatsOutro |
The cutting room floor outro's clock: start() plays it for seconds on its own rAF clock and fetches the tally afresh; with audioRef it also starts when the song ends; a new project or length stops it. Returns { seconds, t, stats, active, paused, start, stop, pause }; pause freezes the displayed outro for frame capture. |
The storyboard animatic's ending and the board's Ending card. |
useMusicVideoRevisions |
Selective section revision (#8987): open a revision from a reviewed draft excerpt (its flagged sections' takes are rejected, the rest kept), resume it from the server checkpoint — generating ONLY the sections the server reports as needsGeneration through the board's scene lanes, or adopting the draft re-render via attachRender once every revised section has a take — and cancel it. A server refusal toasts as a failure; a throw in the hook's own follow-up AFTER the server succeeded reloads the saved record instead (#9940), so an opened repair whose resume failed stays recoverable from the "Needs attention" banner. Returns { busy, revise(excerptId, sceneIds?), repair(basis), repairPerformance(sceneId, input), resume(revisionId), cancel(revisionId) }. |
The Music Video excerpt panel. |
useMusicVideoAutoReview |
Opt-in automatic review/retries (#8988): start a run over a draft window with explicit review (maxAttempts) and paid-generation (maxGenerations) limits plus a vision reviewer; applies the project pushed on music-video:auto-review and reports outcomes; the server generates a run's revised sections itself (#10014), so the board never submits them and a run completes with no tab open. Returns { busy, action, start(startSec, endSec, limits, reviewer), resume(runId, limits?), stop(runId), cancel(runId) }. |
The Music Video excerpt panel. |
useMusicVideoExcerpts |
Draft excerpt render + timecoded review notes (#8986): a useSseJobSlot render job over a chosen [startSec, endSec) window (any terminal frame reloads the project, since the persisted excerpt shape lives server-side) plus add/edit/delete review-note calls that apply the fresh whole project from each response. Returns { rendering, progress, deletingId, noteBusyId, startExcerpt(startSec, endSec), cancelExcerpt(excerptId), attachRender(jobId, projectId), deleteExcerpt(excerptId), addNote(excerptId, {atSec, note, verdict?}), editNote(excerptId, noteId, patch), deleteNote(excerptId, noteId) }. |
The Music Video excerpt panel. |
useMusicVideoCoverLettering |
Music Video cover Lettering controls (#10345): the install's uploaded typefaces and saved per-artist styles, loaded once. Loads whenever enabled (the section is open). Returns { fonts, styles, uploading, uploadFont(file), removeFont(id), saveStyle({ name, design }), removeStyle(name) } (fonts/styles null until loaded); each mutation applies the server's answer at once. |
CoverArtPanel (Publish stage). |
useMusicVideoPublishKit |
Music Video publishing kit (#9281): a useSseJobSlot build job (encodes, thumbnails, captions, chapters) whose terminal frame reloads the project, plus the one-call copy draft, per-field copy edits, the YouTube thumbnail and cover art, each applying the returned project. Returns { building, progress, build(), cancelBuild(), drafting, saving, draftCopy(body), saveCopy(patch), composingThumbnail, composeThumbnail(body), clearThumbnail(), addThumbnailTest(), removeThumbnailTest(filename), paintingThumbnail, paintThumbnail(body), … } plus the cover-art actions. |
The Music Video Publish stage. |
useMusicVideoPublishing |
Music Video posting (#9282): per-platform drafts filled in the PortOS Browser. prepare returns the filled draft's summary and screenshot (a sign-in-required refusal is kept as the platform's error with its login URL), submit posts that reviewed draft and applies the returned project, discard closes it. Platforms are opt-in (#9287): it loads the saved platforms (enabled + optional account each) and per-platform history (posts, reception tally, recent notes across projects); setPlatform toggles one optimistically and recordPost saves a hand-made post's link or a post's reception and notes. Returns { drafts, busy, errors, prepare(target, options), submit(target), discard(target), platforms, history, enabledTargets, setPlatform(target, change), recordPost(target, body) }. |
The Music Video Publish stage's posting panel. |
useMusicVideoModelSettings |
A project's saved render pins — video backend (local/Grok/fal.ai)/model/generation-mode/audio-reactive LoRA + the image-side frame pin — with the Video Gen catalog they read from. Optimistic-local + silent PATCH, rollback + toast on failure; saving gates the dependent generate buttons. Returns `{ models, modelsLoading, catalogStatus ('loading' |
'ready' |
useMusicVideoSceneMedia |
Both per-scene generation lanes (reference frame + scene clip) over useSceneRenderLifecycle, the frame/shot prompt builders (concept-style + visual-spec direction suffix), visual-spec reference-image conditioning with explicit unsupported-backend feedback (#8965), the batch "generate the missing ones" actions, restores in-flight scene renders from the server queue on mount (getMusicVideoSceneJobs) so a reload doesn't invite duplicate submits, and folds the persisted scene.lastFailure (socket music-video:scene-failure) onto the scene (#10154). Loads the Casting media of each cast member a shot names in characterVariant (#12763) so frame conditioning leads with their guides. Returns { genScenes, genVideoScenes, conditioning, castMedia, buildFramePrompt, buildShotPrompt, generateFrame, generateSceneVideo, continueSceneVideo, generateMissingFrames, generateMissingVideos, planMissingFrames, planMissingVideos, frameBatch, videoBatch, sceneProgress, videoSceneProgress } (the batches run counted via useSceneBatch; the board confirms count + estimate before calling generateMissing*). |
The Music Video scene board — don't re-wire the two lanes or re-derive the i2v/a2v/extend payloads. |
useMusicVideoTakes |
Scene-take review + external-asset handoff for the Music Video board (#8965): serialized select / reject / note / gallery-import take mutations folded back as scene patches, the handoff manifest download, and the handoff import (gallery upload per file, then scene association by file tag with provider provenance). Returns { busy, selectTake, reviewTake, importTake, exportHandoff, importHandoffFiles }. |
The Music Video board's take strips, contact sheet and handoff row — don't re-sequence take mutations per call site. |
useMusicVideoTreatment |
The Music Video pre-production treatment (#8980): serialized brief/arc/shot-direction saves that each carry the latest known treatment revision (a 409 from a newer copy reloads the project), explicit compile (AI or deterministic) with skip-reason feedback, the Apply review (loadPreview → apply({ overwrite, addTextCues })) and proof verdicts. Returns { compiling, preview, previewing, applying, save, compile, loadPreview, apply, reviewProof, clearPreview }. |
The Music Video treatment panel — don't re-derive the revision bookkeeping per call site. |
useMusicVideoManualTempo |
The manual-tempo fallback for a project whose auto-detected BPM is null: BPM/offset drafts (reset on project switch), tap-tempo estimation, and the persisted setMusicVideoManualTempo call. Returns { bpm, setBpm, offset, setOffset, saving, tap, submit }. |
The Music Video "No tempo detected" row. |
useCanvasDprSize |
DevicePixelRatio-aware canvas sizing shared by the piano-roll renderers (<PianoRoll>, <MidiPianoRoll>): sizes the bitmap to container-width × height (or the container height when height is undefined) at the DPR, applies the transform, and redraws via a drawRef on mount + every ResizeObserver resize (observer created once per height, never churned by draw-closure changes). Returns a ref holding the current CSS width so draw code doesn't measure the DOM per frame. |
Both piano-roll canvases. |
useCanvasRollPalette |
Resolves a canvas palette into a ref — rollPalette by default, or any resolver passed as the second argument (the Core Assembly avatar reads --port-accent-2), re-resolving on theme switch (data-port-theme MutationObserver) and repainting through a drawRef. Hands back a ref, not state, so a theme swap redraws the imperative canvas without a React re-render. |
Both piano-roll canvases need theme-aware accent/bg colors that canvas fillStyle can't read from CSS vars. |
usePrefersReducedMotion |
The user's prefers-reduced-motion setting as a boolean, tracking live changes. |
An imperative animation (a rAF canvas loop, a three.js frameloop) that must stop scheduling frames itself — CSS animations honor the media query on their own. |
useMidiNotes |
Fetch + parse a transcribed .mid file into the piano-roll view-model (parseMidiFile in lib/midiNotes.js), with a module-level per-URL cache so remounts (collapse, tab switches) don't refetch/reparse. Returns { status: 'idle'|'loading'|'ready'|'error', data, error, reload }; a generation counter drops stale in-flight responses on URL change/unmount. Plain fetch of the static file URL — errors surface inline, never as toasts (#2477). |
<MidiVisualization> (Rounds ReferenceAnalysis + Music Video). |
useChordPlayer |
Chord-sheet play-along transport for a SongBook tab/chordpro sheet (#4104) — the chord counterpart of useDrumPlayer: parses the (already-transposed) text, owns one createChordPlayer, the practice settings (tempo + beats-per-chord persisted per song, count-in, machine-global click) and the sounding-chord highlight read off the audio clock. Returns { chordCount, hasChords, writtenTempo, bpm, setBpm, setBpmPercent, beatsPerBar, setBeatsPerBar, countInBars, setCountInBars, clickEnabled, setClickEnabled, playing, pulse, sounding, getPlayhead, toggle, stop }. Timing edits stop playback rather than re-time a running schedule. |
<ChordTransportBar> + <ChordPreview> (SongBook viewer/editor/importer). |
useDrumPlayer |
Drum play-along transport for a SongBook drum chart (#3115): parses the chart (lib/drumNotation.js), owns one createDrumPlayer per chart plus the practice settings and the sheet playhead. Returns { chart, barCount, writtenTempo, bpm, setBpm, setBpmPercent, countInBars, setCountInBars, loopEnabled, setLoopEnabled, loopFrom, loopTo, setLoopRange, clickEnabled, setClickEnabled, clickVolume, setClickVolume, kitId, setKitId, playing, activeStep, currentBar, toggle, stop }. The practice tempo persists per song in safeStorage (never into the record) while the selected kit (songbook:drumKit), the click toggle (songbook:drumClick) and the click level (songbook:drumClickVolume) persist per MACHINE; a timing-critical edit (tempo / count-in / loop) STOPS playback rather than re-timing already-scheduled audio, while the click toggle, the click level and the kit swap apply live (raising the level off silence also unmutes, so the slider is never a dead control); the player + its interval + scheduled hits tear down on stop, chart change and unmount. |
The SongBook viewer and snapshot-based drum previews. Don't hand-wire createDrumPlayer + BPM persistence + playhead state again. |
useMidiPlayer |
React wrapper over lib/midiPlayback.js (#2490): one synth player per parsed MIDI view-model, torn down when the data changes/unmounts so oscillators never outlive the roll. Returns { playing, toggle, seek(sec), getPosition } — getPosition is the stable ref the <MidiPianoRoll> rAF playhead reads; no AudioContext is touched until the first toggle. A resume failure resets playing instead of lying. |
<MidiVisualization> (Rounds ReferenceAnalysis + Music Video). |
Hosted worlds
| Hook | Purpose | Use when |
|---|---|---|
useEidoverseFrame |
Per-load Eidoverse handshake with origin/window/session validation and browser-only label preferences. | Embedding the managed Eidoverse renderer. |
useGallerySidecars |
Hydrates a known filename list into its image-metadata sidecars (the prompt actually sent, negative, model, seed, size), keyed on contents rather than array identity, with a setSidecar splice for a freshly written record. |
Any page showing renders it owns the refs for (universe draft, deck cards) that must open the lightbox on the real render prompt. |
useGalleryPreviewResolver |
Builds the stable resolveItem callback that resolves a ?preview= param the host's own items list does not contain, by looking the record up in the gallery and normalizing it. usePreviewRoute uses it as its DEFAULT. |
Call it directly only to narrow the lookup — collectionId scopes it to one collection. |
useGeneratedPreview |
One OS-isolated generated-preview session. Emits generated-preview:open for request and returns inert JPEG frames, seek/command functions, and a recording blob. Reconnect opens a fresh session with the current controls and playhead; idle/capacity closure returns status: 'idle' until the viewer calls resume(). Film-look and title-card controls ride the open and later commands. A revision change reopens; a control change does not. Unsupported hosts surface status: 'unavailable' and never fall back to an iframe. |
Music-video composition, code-video, and code-animation previews. |
useImageVariants |
Fetches the original-vs-cleaned variant set for the one open image (GET /api/image-gen/:filename/variants), normalized; reuses the held group across toggle clicks and aborts a superseded lookup. null while unfetched or failed, [] when the image is not indexed. |
MediaPreview calls it for every image preview; neither a page-owned ref list nor a 60-row gallery window is a complete source of variant lineage. |
useGalleryPage |
Bounded image or mixed-media browsing with debounced server search, scopes, totals, stale-response cancellation and retryable next pages. preserveLoadedOnRefresh reloads the retained window in compact pages while keeping existing cards mounted. |
Gallery grids and pickers; getGalleryImages hydrates known references separately. |
useListResource |
useListResource(fetcher, { enabled }) → { items, state: 'loading'|'ready'|'error', error, retry, setItems } — one list read whose failure stays distinct from an empty result; a superseded response is dropped. fetcher must be referentially stable. |
Any picker or list section fed by one list fetch (LoRA library, track library, model catalog) — render <ListLoadError onRetry={retry}> on 'error' and the empty copy only on 'ready', never .catch(() => []). |
useProviderList |
useProviderList({ enabled }) → the useListResource shape ({ items, state, error, retry, setItems }) over GET /providers, silent so the caller owns the error UI. |
Any picker or tab that needs the provider list — render <ListLoadError what="AI providers" onRetry={retry}> on error, and gate "no providers" copy on state === 'ready'. |
usePagedCollection |
usePagedCollection(fetchPage, { enabled }) — bounded cursor pages, deduplication by id, single-flight loading, abort/stale-query protection, retry, reset, and local mutation via setItems; an optional meta returned by fetchPage is exposed as the latest page's response-level data. |
Growing cursor-based collections; pair with InfiniteScrollFooter. |
| useGoalOrganize / useGoalCreate | Shared goal suggestion preview, explicit apply, and guarded create flows for both Goals views. | Goals List and Tree views. |
| useGraphNodeDetail | Selection-keyed graph record loading with render-time identity gating and late-response disposal. | Brain and CoS graph detail panels. |
| useModelLifecycle | Targeted 3D model lifecycle reads, cancellation and bounded transient recovery. | Image-to-3D and procedural model views. |
| useMusicVideoProductionReview | Server-authoritative art/storyboard/proof approvals and SSE proof rendering, with stale-readiness suppression. | Music Video production review. |
| useMusicVideoProofReview | Revision-bound animated-proof playback state, render range, approval blockers and evidence payload. Returns playback/media setters, range/setRange, and approval state/actions. | ProductionReviewPanel and its proof content. |
| useCalendarWindowEvents | useCalendarWindowEvents(startDate, endDate) — sequential 200-event offset pages for a complete calendar window, account/event deduplication, retry and date/sync supersession. | Day/Week/Month grids; pair with CalendarWindowStatus to disclose incomplete availability. |
| useMusicVideoReviewDraft.js | Sequential exact-version availability checks for implicit imported draft selection; stale requests abort, unavailable newer drafts are disclosed, explicit review versions remain pinned. |
| useRunwayCatalog.js | Shared Runway model catalog capabilities and cached model selection. |