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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor(client): extract <Modal> + getRenderConfigForItem — dedupe modal chrome + sidecar field reads (#223)
[._.]/ Adam Eivyd080ac668bf3
diff --git a/DONE.md b/DONE.mdindex 6db90acc74..b0bd889446 100644--- a/DONE.md+++ b/DONE.md@@ -14,6 +14,7 @@ Archive of completed work. For active roadmap, see [PLAN.md](./PLAN.md). For pro- **`mediaModels.js` drift warning** — `loadMediaModels()` now logs a loud `⚠️ media-models drift` warning at boot for any id present in BOTH `_shippedDefaults` AND `DEFAULT_REGISTRY` but missing from the user's live list. Catches the 2026-05-09 silent-drift class. No auto-recover — surfaces the bug, lets a human decide. Warning is honest that intentional deletions are indistinguishable from drift and will keep firing each boot. Covers `image` plus `video.macos` and `video.windows`. 4 new tests.- **CLI `defaultModel` for all CLI providers** — `services/runner.js#buildCliArgs` now appends `--model <id>` to claude-code (after `-p -`; claude-code parses flags positionally) and `-m <id>` to gemini-cli, gated on the provider's stored `args` not already containing `--model`/`-m` (both space- and `=`-joined forms; rejects dangling/empty flag forms). Codex behavior unchanged. New `hasModelFlag`/`extractBakedModel`/`stripBrokenModelFlags` helpers exported for reuse. Stage runner / message evaluator / media prompt refiner / world builder refiner per-call model overrides now actually take effect for all three CLIs instead of silently no-op'ing for claude-code and gemini-cli; refiners report the args-baked model id (not defaultModel) when a model is pinned in args. 15+ new tests + 2 regression tests; surfaced from Copilot review on PR #217 and #222.- **Extract `scripts/_runner_common.py`** — Pulled the byte-for-byte-duplicated `pick_device` / `make_generator` / `apply_memory_optimizations` / `write_sidecar` / `make_stepwise_callback` / `_emit_user_error` / `_repo_from_hf_error` / HF cause-chain walker (~200 LOC) out of `scripts/flux2_macos.py` + `scripts/z_image_turbo.py` into a shared module. `make_stepwise_callback` now takes an optional `unpack_latents` callable so the flux2 packed-transformer-latent path stays runner-specific while the rest of the decode is shared. `install_hf_error_handler` is a `@decorator` over `main()` that owns the gated/notfound/401 dispatch — `if __name__ == "__main__": main()` collapses to one line in both runners. Mirrors the `lora_utils.py` extraction pattern. Server tests 4012/4012 green; both runners' `--help` resolves cleanly.+- **Shared `<Modal>` component + `getRenderConfigForItem` extraction** — Two more "Civitai LoRA / Z-Image-Turbo follow-ups" off the backlog. (a) New `client/src/components/ui/Modal.jsx` (~100 LOC) owns the `fixed inset-0 z-50 bg-black/70 ...` backdrop, Esc handler, target-checked click-outside, ARIA + portal + size + align flags. Converted 9 call sites: `Flux2InstallModal`, `EditAppModal`, `MemoryEditModal`, `ResumeAgentModal`, `LayoutEditor`, `KeyboardHelp`, `RapidReaderModal`, `DeployPanel`, and `CivitaiAuthModal` in `Loras.jsx`; net dedup is ~40 LOC after per-site config props and unblocks future modals from owning chrome boilerplate. `MediaLightbox` deliberately stays standalone — its prev/next viewport-edge buttons + layered Esc cascade fight Modal's panel-container wrapper; comment in the file documents why. (b) `getRenderConfigForItem(item)` lives in `client/src/components/media/normalize.js`, surfacing sidecar fields (`cfgScale`/`cfg_scale`, `loraFilenames`/`lora_filenames`, `loraScales`/`lora_scales`, `guidanceScale`/`guidance_scale`/`guidance`, `disableAudio`/`disable_audio`, etc.) so `PromptRefineModal#getRenderConfig` stopped reaching into `item.raw?.*` for snake/camel reconciliation. 11 new unit tests in `normalize.test.js` cover both naming conventions, the deliberate-`0` guidanceScale carve-out, and the camelCase-wins drift safety. Server's `vitest.config.js` now picks up `../client/src/**/*.test.js` so client-side pure helpers stay covered without bootstrapping a separate runner.- **Shared `runPromptThroughProvider` runner-wrapper** — Four near-identical "create run → branch on provider.type → executeCliRun/executeApiRun → accumulate text → reject on error" implementations (`worldBuilderExpand#callLLM`, `stageRunner#awaitRunnerCall`, `mediaPromptRefiner#runRefinePrompt`, `messageEvaluator#runPrompt`) collapse onto `server/lib/promptRunner.js`. The unified runner picks the strictest discriminator: rejects on `success === false` OR truthy `error` for BOTH CLI and API. Per-site drift used to let API "soft failures" flow through as empty text — now they reject loudly. Returns `{ text, runId, model }` where `model` is the post-gate effective model that actually executed (per-call model is dropped for providers that don't honor it — see `providerHonorsModelOverride`). 19 unit tests in `promptRunner.test.js` covering happy paths, strictest-discriminator rejection, executeCliRun/executeApiRun pre-onComplete rejection forwarding, and multi-chunk text accumulation.- **Shared `findBalancedBlocks` + `tryParseWithRepair` + `extractJson` in `server/lib/jsonExtract.js`** — Three near-identical extractors (`worldBuilderExpand.js`, `mediaPromptRefiner.js#extractRefinementJson`, `stageRunner.js#extractJson`) all solved the same "extract JSON from CLI-banner-prefixed LLM output" problem. Promoted the richest implementation (string-aware brace walker + string-aware trailing-comma + Codex `}}]` orphan-brace repair + `[...]` placeholder cleanup) into the shared lib with optional `shapePredicate` for caller-specific block selection. All three callers re-import from the lib; mediaPromptRefiner keeps its tri-state placeholder-vs-real walker via `findBalancedBlocks` + `tryParseWithRepair` directly so the "schema placeholder" error message stays intact. 33 unit tests in `jsonExtract.test.js`.diff --git a/PLAN.md b/PLAN.mdindex 12179bcce8..2d9d64cb7a 100644--- a/PLAN.md+++ b/PLAN.md@@ -56,11 +56,10 @@ The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), audThese were flagged by the post-merge code review pass on the Z-Image + Civitai LoRA work but deliberately deferred to keep the original PR scoped._All items in this section have shipped — see DONE.md → 2026-05-12 for the-"Civitai / Z-Image follow-ups — six post-merge cleanups" entry and the-`scripts/_runner_common.py` extraction entry._-- [ ] **Project-wide `<Modal>` component** — every modal in the app (`Flux2InstallModal`, `EditAppModal`, `MemoryEditModal`, `ResumeAgentModal`, `MediaLightbox`, `LayoutEditor`, `KeyboardHelp`, `RapidReader`, `DeployPanel`'s confirm, the new `CivitaiAuthModal` in `Loras.jsx`) rolls its own `fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4` backdrop + click-outside + close-button + ESC handler. Extract `client/src/components/ui/Modal.jsx` with backdrop + dialog props and a slot for the body, then convert all call sites. ~300 LOC of duplicated chrome across the codebase.--- [ ] **Extend `normalize.js` to expose render-config fields** — `client/src/components/media/PromptRefineModal.jsx#getRenderConfig` reaches into `item.raw?.{cfgScale,loraFilenames,loraScales,steps (video),guidanceScale,seed,tiling,disableAudio}` because `normalizeImage`/`normalizeVideo` don't surface those fields. Either lift the snake_case/camelCase fallback chain into normalize.js so the modal reads from `item.*` only, or add `getRenderConfigForItem(item)` co-located with normalize so the sidecar field-naming knowledge lives in one file. Surfaced from the Refine Prompt /simplify pass.+"Civitai / Z-Image follow-ups — six post-merge cleanups", the+`scripts/_runner_common.py` extraction, the `runPromptThroughProvider`++ `jsonExtract` unification, and the `<Modal>` + `getRenderConfigForItem`+entries._### Better Audit follow-upsdiff --git a/client/src/components/KeyboardHelp.jsx b/client/src/components/KeyboardHelp.jsxindex e962948256..1b61a303b1 100644--- a/client/src/components/KeyboardHelp.jsx+++ b/client/src/components/KeyboardHelp.jsx@@ -1,9 +1,9 @@import { useEffect, useRef, useCallback } from 'react';-import { createPortal } from 'react-dom';import { Keyboard, X } from 'lucide-react';import { useKeyboardHelp } from '../hooks/useKeyboardHelp';import { useScrollLock } from '../hooks/useScrollLock';import { modKey } from '../utils/platform';+import Modal from './ui/Modal';const SHORTCUT_SECTIONS = [{@@ -81,26 +81,24 @@ export default function KeyboardHelp() {}}, []);- if (!open) return null;-- const overlay = (- <div className="fixed inset-0 z-[9999] flex items-start justify-center pt-[10vh]">- {/* Backdrop */}- <div- className="absolute inset-0 bg-black/60"- onClick={close}- aria-hidden="true"- />-- {/* Modal */}- <div- ref={dialogRef}- role="dialog"- aria-modal="true"- aria-labelledby="keyboard-help-title"- className="relative w-full max-w-lg mx-4 bg-port-card rounded-xl border border-port-border shadow-2xl overflow-hidden"- onKeyDown={handleKeyDown}- >+ return (+ <Modal+ open={open}+ onClose={close}+ // Modal's bubble-phase window Esc dispatcher closes us as the top-most+ // layer. useKeyboardHelp listens on `document` (also bubble) — both+ // fire on Esc, but they both ultimately call setOpen(false) so the+ // double-handler is harmless. Modal's `stopImmediatePropagation` only+ // blocks other window-level listeners, not document-level ones.+ size="md"+ align="top"+ usePortal+ zIndexClassName="z-[9999]"+ backdropClassName="bg-black/60"+ ariaLabelledBy="keyboard-help-title"+ panelClassName="bg-port-card rounded-xl border border-port-border shadow-2xl overflow-hidden"+ >+ <div ref={dialogRef} onKeyDown={handleKeyDown}>{/* Header */}<div className="flex items-center justify-between px-5 py-4 border-b border-port-border"><div className="flex items-center gap-2.5">@@ -147,8 +145,6 @@ export default function KeyboardHelp() {</p></div></div>- </div>+ </Modal>);-- return createPortal(overlay, document.body);}diff --git a/client/src/components/RapidReader.jsx b/client/src/components/RapidReader.jsxindex 3258312df7..291a955586 100644--- a/client/src/components/RapidReader.jsx+++ b/client/src/components/RapidReader.jsx@@ -1,5 +1,6 @@import { useEffect, useMemo, useRef, useState, useCallback } from 'react';import { Play, Pause, RotateCcw, Rewind, FastForward, X, Zap } from 'lucide-react';+import Modal from './ui/Modal';// Optimal Recognition Point — the focal letter the eye lands on. Spritz-style:// shorter words use a left-shifted ORP, longer words shift right. Returns the@@ -295,35 +296,39 @@ function FocalSlot({ chunk, focalColor }) {}// Modal wrapper — full-screen overlay so any page can pop the reader without-// leaving its context. Closes on Esc or backdrop click.+// leaving its context. Closes on Esc or backdrop click. The inner RapidReader+// registers a capture-phase window keydown listener (so Space / arrow keys+// can be claimed before VoiceWidget sees them) that, on Esc, calls onClose+// and then preventDefault() + stopImmediatePropagation(). Modal's window+// listener is bubble-phase, so it never even reaches the same event — the+// capture-phase stopImmediatePropagation cancels propagation entirely; even+// if it did reach Modal, `defaultPrevented` would suppress the close+// dispatch. RapidReader owns Esc unilaterally inside this wrapper.export function RapidReaderModal({ open, text, title, onClose, ...readerProps }) {- if (!open) return null;return (- <div- className="fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4"- role="dialog"- aria-modal="true"- aria-label={title || 'Rapid Reader'}- onClick={(e) => { if (e.target === e.currentTarget) onClose?.(); }}+ <Modal+ open={open}+ onClose={onClose}+ size="xl"+ ariaLabel={title || 'Rapid Reader'}+ panelClassName="bg-port-card border border-port-border rounded-xl shadow-2xl">- <div className="w-full max-w-3xl bg-port-card border border-port-border rounded-xl shadow-2xl">- <div className="flex items-center justify-between gap-2 px-4 py-2 border-b border-port-border">- <div className="flex items-center gap-2 text-sm text-gray-300 truncate">- <Zap size={14} className="text-port-accent shrink-0" />- <span className="truncate">{title || 'Rapid Reader'}</span>- </div>- <button- type="button"- onClick={onClose}- className="min-h-10 min-w-10 flex items-center justify-center text-gray-400 hover:text-white"- aria-label="Close rapid reader"- >- <X size={18} />- </button>+ <div className="flex items-center justify-between gap-2 px-4 py-2 border-b border-port-border">+ <div className="flex items-center gap-2 text-sm text-gray-300 truncate">+ <Zap size={14} className="text-port-accent shrink-0" />+ <span className="truncate">{title || 'Rapid Reader'}</span></div>- <RapidReader text={text} onClose={onClose} autoPlay {...readerProps} />+ <button+ type="button"+ onClick={onClose}+ className="min-h-10 min-w-10 flex items-center justify-center text-gray-400 hover:text-white"+ aria-label="Close rapid reader"+ >+ <X size={18} />+ </button></div>- </div>+ <RapidReader text={text} onClose={onClose} autoPlay {...readerProps} />+ </Modal>);}diff --git a/client/src/components/apps/DeployPanel.jsx b/client/src/components/apps/DeployPanel.jsxindex 914f40dc66..4dfe768df0 100644--- a/client/src/components/apps/DeployPanel.jsx+++ b/client/src/components/apps/DeployPanel.jsx@@ -1,6 +1,7 @@import { useState, useRef, useEffect } from 'react';import { Rocket, X, ChevronDown } from 'lucide-react';import BrailleSpinner from '../BrailleSpinner';+import Modal from '../ui/Modal';import { useAppDeploy } from '../../hooks/useAppDeploy';const FLAG_OPTIONS = [@@ -35,13 +36,13 @@ export default function DeployPanel({ appId, appName }) {useEffect(() => () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); }, []);- // Esc to dismiss the modal (deploy keeps running in the background)- useEffect(() => {- if (!isOpen) return;- const onKey = (e) => { if (e.key === 'Escape') setDismissed(true); };- window.addEventListener('keydown', onKey);- return () => window.removeEventListener('keydown', onKey);- }, [isOpen]);+ // Pre-refactor, Esc always set dismissed=true (hide the modal, keep deploy+ // state intact so output reappears when re-opened). X / backdrop ran the+ // full handleClose which calls clearDeploy() once the deploy has finished.+ // The shared Modal dispatches Esc via onClose by default, which would call+ // clearDeploy after a finished deploy — losing the output. onEsc preserves+ // the original "Esc always hides, never clears" semantics.+ const handleEsc = () => setDismissed(true);const toggleFlag = (flag) => {setSelectedFlags(prev => {@@ -122,53 +123,56 @@ export default function DeployPanel({ appId, appName }) {)}{isOpen && (- <div- className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"- onClick={(e) => { if (e.target === e.currentTarget) handleClose(); }}+ <Modal+ open+ onClose={handleClose}+ onEsc={handleEsc}+ size="xl"+ backdropClassName="bg-black/60"+ panelClassName="bg-port-bg border border-port-border rounded-xl shadow-2xl max-h-[80vh] flex flex-col"+ ariaLabelledBy="deploy-panel-title">- <div className="bg-port-bg border border-port-border rounded-xl shadow-2xl w-full max-w-3xl max-h-[80vh] flex flex-col">- <div className="flex items-center justify-between px-4 py-3 border-b border-port-border">- <div className="flex items-center gap-2">- <Rocket size={16} className="text-purple-400" />- <span className="text-sm font-medium text-white">Deploy: {appName}</span>- {isDeploying && <BrailleSpinner text="" className="text-xs text-purple-400" />}- </div>- <button- onClick={handleClose}- className="text-gray-400 hover:text-white transition-colors"- title={isDeploying ? 'Hide (deploy keeps running)' : 'Close'}- aria-label={isDeploying ? 'Hide deploy output' : 'Close deploy panel'}- >- <X size={16} />- </button>+ <div className="flex items-center justify-between px-4 py-3 border-b border-port-border">+ <div className="flex items-center gap-2">+ <Rocket size={16} className="text-purple-400" />+ <span id="deploy-panel-title" className="text-sm font-medium text-white">Deploy: {appName}</span>+ {isDeploying && <BrailleSpinner text="" className="text-xs text-purple-400" />}</div>-- <div- ref={outputRef}- className="flex-1 overflow-auto p-4 font-mono text-xs leading-relaxed bg-black/40"+ <button+ onClick={handleClose}+ className="text-gray-400 hover:text-white transition-colors"+ title={isDeploying ? 'Hide (deploy keeps running)' : 'Close'}+ aria-label={isDeploying ? 'Hide deploy output' : 'Close deploy panel'}>- {output.map((line, i) => (- <div- key={i}- className={- line.stream === 'stderr' ? 'text-port-error whitespace-pre-wrap break-words' :- line.stream === 'status' ? 'text-purple-400 font-bold whitespace-pre-wrap break-words' :- 'text-gray-300 whitespace-pre-wrap break-words'- }- >- {line.text}- </div>- ))}- {error && <div className="text-port-error mt-2 whitespace-pre-wrap break-words">Error: {error}</div>}- </div>+ <X size={16} />+ </button>+ </div>- {result && (- <div className={`px-4 py-2 border-t border-port-border text-xs ${result.success ? 'text-port-success' : 'text-port-error'}`}>- {result.success ? 'Deploy completed successfully' : `Deploy failed (exit code ${result.code})`}+ <div+ ref={outputRef}+ className="flex-1 overflow-auto p-4 font-mono text-xs leading-relaxed bg-black/40"+ >+ {output.map((line, i) => (+ <div+ key={i}+ className={+ line.stream === 'stderr' ? 'text-port-error whitespace-pre-wrap break-words' :+ line.stream === 'status' ? 'text-purple-400 font-bold whitespace-pre-wrap break-words' :+ 'text-gray-300 whitespace-pre-wrap break-words'+ }+ >+ {line.text}</div>- )}+ ))}+ {error && <div className="text-port-error mt-2 whitespace-pre-wrap break-words">Error: {error}</div>}</div>- </div>++ {result && (+ <div className={`px-4 py-2 border-t border-port-border text-xs ${result.success ? 'text-port-success' : 'text-port-error'}`}>+ {result.success ? 'Deploy completed successfully' : `Deploy failed (exit code ${result.code})`}+ </div>+ )}+ </Modal>)}</div>);diff --git a/client/src/components/apps/EditAppModal.jsx b/client/src/components/apps/EditAppModal.jsxindex d0b5e8ded9..8d8769cccc 100644--- a/client/src/components/apps/EditAppModal.jsx+++ b/client/src/components/apps/EditAppModal.jsx@@ -5,6 +5,7 @@ import IconPicker from '../IconPicker';import * as api from '../../services/api';import { PORTOS_APP_ID } from '../../services/apiCore';import toast from '../ui/Toast';+import Modal from '../ui/Modal';export default function EditAppModal({ app, onClose, onSave }) {const [formData, setFormData] = useState({@@ -159,14 +160,20 @@ export default function EditAppModal({ app, onClose, onSave }) {};return (- <div- className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"- role="dialog"- aria-modal="true"- aria-labelledby="edit-app-title"+ <Modal+ open+ onClose={onClose}+ // App-edit historically had no backdrop dismiss / Esc — the form is+ // long-lived and an accidental Esc while editing nested JIRA pickers+ // would lose state. Preserve that.+ closeOnBackdrop={false}+ closeOnEsc={false}+ size="md"+ backdropClassName="bg-black/50"+ ariaLabelledBy="edit-app-title"+ panelClassName="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 max-h-[90vh] overflow-auto">- <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 w-full max-w-lg max-h-[90vh] overflow-auto">- <h2 id="edit-app-title" className="text-xl font-bold text-white mb-4">Edit App</h2>+ <h2 id="edit-app-title" className="text-xl font-bold text-white mb-4">Edit App</h2>{error && (<div className="mb-4 p-3 bg-port-error/20 border border-port-error rounded-lg text-port-error text-sm">@@ -671,7 +678,6 @@ export default function EditAppModal({ app, onClose, onSave }) {</button></div></form>- </div>- </div>+ </Modal>);}diff --git a/client/src/components/cos/tabs/MemoryEditModal.jsx b/client/src/components/cos/tabs/MemoryEditModal.jsxindex ae54b3ec8a..42c98128cf 100644--- a/client/src/components/cos/tabs/MemoryEditModal.jsx+++ b/client/src/components/cos/tabs/MemoryEditModal.jsx@@ -1,6 +1,7 @@import { useState, useEffect } from 'react';import { X, Save, Plus, Trash2 } from 'lucide-react';import toast from '../../ui/Toast';+import Modal from '../../ui/Modal';import * as api from '../../../services/api';import { MEMORY_TYPES, MEMORY_TYPE_COLORS } from '../constants';import { getAppName } from '../../../utils/formatters';@@ -92,10 +93,21 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {};return (- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">- <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 w-full max-w-2xl max-h-[90vh] overflow-auto">- <div className="flex items-center justify-between mb-4">- <h2 className="text-lg sm:text-xl font-bold text-white">Edit Memory</h2>+ <Modal+ open+ onClose={onClose}+ // EditMemory historically had no backdrop-click dismiss; preserve.+ closeOnBackdrop={false}+ // Esc-to-close wasn't wired either; preserve so a stray Esc while typing+ // in the content textarea doesn't lose user work.+ closeOnEsc={false}+ size="lg"+ backdropClassName="bg-black/50"+ panelClassName="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 max-h-[90vh] overflow-auto"+ ariaLabelledBy="memory-edit-title"+ >+ <div className="flex items-center justify-between mb-4">+ <h2 id="memory-edit-title" className="text-lg sm:text-xl font-bold text-white">Edit Memory</h2><buttononClick={onClose}className="p-2 min-h-[40px] min-w-[40px] flex items-center justify-center text-gray-500 hover:text-white transition-colors rounded-lg"@@ -299,7 +311,6 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {</button></div></form>- </div>- </div>+ </Modal>);}diff --git a/client/src/components/cos/tabs/ResumeAgentModal.jsx b/client/src/components/cos/tabs/ResumeAgentModal.jsxindex 4db6e222bc..f7cc005aef 100644--- a/client/src/components/cos/tabs/ResumeAgentModal.jsx+++ b/client/src/components/cos/tabs/ResumeAgentModal.jsx@@ -2,6 +2,7 @@ import { useState, useRef } from 'react';import { X, CheckCircle, AlertCircle, RotateCcw, Image, Loader2 } from 'lucide-react';import { processScreenshotUploads } from '../../../utils/fileUpload';import toast from '../../ui/Toast';+import Modal from '../../ui/Modal';import { filterSelectableModels } from '../../../utils/providers';export default function ResumeAgentModal({ agent, taskType = 'user', providers, apps, onSubmit, onClose }) {@@ -75,10 +76,25 @@ export default function ResumeAgentModal({ agent, taskType = 'user', providers,};return (- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">- <div className="bg-port-card border border-port-border rounded-xl p-6 w-full max-w-2xl max-h-[90vh] overflow-auto">- <div className="flex items-center justify-between mb-4">- <h2 className="text-xl font-bold text-white">+ <Modal+ open+ onClose={onClose}+ // Resume modal historically had neither backdrop dismiss nor Esc; an+ // accidental dismiss would lose user-typed refined instructions.+ closeOnBackdrop={false}+ closeOnEsc={false}+ size="lg"+ // Pre-refactor overlay had no padding — `fixed inset-0 ... flex+ // items-center justify-center` with no `p-*`. Preserve that so the+ // panel still reaches viewport edges on small screens. `align='none'`+ // applies the same flex centring without the default `p-4`.+ align="none"+ backdropClassName="bg-black/50"+ panelClassName="bg-port-card border border-port-border rounded-xl p-6 max-h-[90vh] overflow-auto"+ ariaLabelledBy="resume-agent-title"+ >+ <div className="flex items-center justify-between mb-4">+ <h2 id="resume-agent-title" className="text-xl font-bold text-white">Resume {taskType === 'internal' ? 'System ' : ''}Agent Task</h2><button@@ -243,7 +259,6 @@ export default function ResumeAgentModal({ agent, taskType = 'user', providers,</button></div></form>- </div>- </div>+ </Modal>);}diff --git a/client/src/components/dashboard/LayoutEditor.jsx b/client/src/components/dashboard/LayoutEditor.jsxindex a612d8ee57..c927e42ce8 100644--- a/client/src/components/dashboard/LayoutEditor.jsx+++ b/client/src/components/dashboard/LayoutEditor.jsx@@ -1,9 +1,9 @@import { useState, useEffect, useRef, useCallback } from 'react';-import { createPortal } from 'react-dom';import { X, ArrowUp, ArrowDown, Trash2, Plus, Save } from 'lucide-react';import { useScrollLock } from '../../hooks/useScrollLock';import { WIDGETS, WIDGETS_BY_ID } from './widgetRegistry.jsx';import toast from '../ui/Toast';+import Modal from '../ui/Modal';// Keyboard-first editor. No drag-and-drop dep — reorder uses up/down buttons// (keyboard + touch friendly). Delete and "save as new" use inline state@@ -78,9 +78,19 @@ export default function LayoutEditor({ layouts, activeLayoutId, limits, onClose,const close = useCallback(() => { onClose(); }, [onClose]);- const onKeyDown = (e) => {- if (e.key === 'Escape') close();- };+ // Inline modes (duplicate-name input, delete confirm, switch confirm) need+ // Esc to cancel just the inline state, not close the whole editor. The+ // inputs' own onKeyDown handlers DO see Esc first (Modal's window listener+ // is bubble-phase) and call preventDefault() — and our Modal honours+ // `defaultPrevented` by skipping the close. But relying on every inline+ // handler to remember preventDefault is fragile. Cleaner: hand Modal a+ // single `onEsc` that maps Esc to `setMode('idle')` while a mode is+ // active, falling back to close() at the top level. This works regardless+ // of whether the focused element has its own onKeyDown.+ const handleEsc = useCallback(() => {+ if (mode !== 'idle') { setMode('idle'); return; }+ close();+ }, [mode, close]);const move = (index, delta) => {setWidgets((prev) => {@@ -168,11 +178,19 @@ export default function LayoutEditor({ layouts, activeLayoutId, limits, onClose,const available = WIDGETS.filter((w) => !widgets.includes(w.id));- const overlay = (- <div className="fixed inset-0 z-[9999] flex items-start justify-center pt-[10vh]" onKeyDown={onKeyDown}>- <div className="absolute inset-0 bg-black/60" onClick={close} aria-hidden="true" />-- <div role="dialog" aria-modal="true" aria-labelledby="layout-editor-title" className="relative w-full max-w-3xl mx-4 bg-port-card rounded-xl border border-port-border shadow-2xl overflow-hidden">+ return (+ <Modal+ open+ onClose={close}+ onEsc={handleEsc}+ size="xl"+ align="top"+ usePortal+ zIndexClassName="z-[9999]"+ backdropClassName="bg-black/60"+ ariaLabelledBy="layout-editor-title"+ panelClassName="bg-port-card rounded-xl border border-port-border shadow-2xl overflow-hidden"+ ><div className="flex items-center justify-between px-5 py-4 border-b border-port-border"><h2 id="layout-editor-title" className="text-sm font-semibold text-white">Edit Layouts</h2><button ref={closeRef} onClick={close} className="p-1 text-gray-500 hover:text-white transition-colors rounded" aria-label="Close">@@ -314,9 +332,6 @@ export default function LayoutEditor({ layouts, activeLayoutId, limits, onClose,</div>)}</div>- </div>- </div>+ </Modal>);-- return createPortal(overlay, document.body);}diff --git a/client/src/components/imageGen/Flux2InstallModal.jsx b/client/src/components/imageGen/Flux2InstallModal.jsxindex 96b7419dfd..b026948769 100644--- a/client/src/components/imageGen/Flux2InstallModal.jsx+++ b/client/src/components/imageGen/Flux2InstallModal.jsx@@ -13,6 +13,7 @@import { useEffect, useRef, useState } from 'react';import { CheckCircle2, Loader2, AlertCircle, Download, X } from 'lucide-react';import { safeParseJSON } from '../../lib/genUtils';+import Modal from '../ui/Modal';// Cap on retained log lines. A torch install can emit hundreds of pip output// lines; without this the array grows unbounded and re-renders cost more per@@ -109,8 +110,6 @@ export default function Flux2InstallModal({ open, onClose, onComplete }) {}}, [logs.length]);- if (!open) return null;-const installRunning = !done && !error && currentStage && currentStage !== 'verify';const performClose = () => {@@ -126,18 +125,25 @@ export default function Flux2InstallModal({ open, onClose, onComplete }) {const stageIdx = currentStage ? STAGE_INDEX[currentStage] ?? -1 : -1;return (- <div className="fixed inset-0 z-[9999] flex items-start justify-center pt-[8vh]">- <div- className="absolute inset-0 bg-black/70 backdrop-blur-sm"- onClick={handleClose}- aria-hidden="true"- />- <div- role="dialog"- aria-modal="true"- aria-labelledby="flux2-install-title"- className="relative w-full max-w-2xl mx-4 bg-port-card rounded-xl border border-port-border shadow-2xl overflow-hidden flex flex-col max-h-[80vh]"- >+ <Modal+ open={open}+ onClose={handleClose}+ size="lg"+ align="top"+ // installer needs to outrank every other overlay (incl. LayoutEditor)+ zIndexClassName="z-[9999]"+ // Esc-to-cancel was never wired pre-refactor (see file header comment:+ // install cancels via X button or backdrop click only). Keep that+ // contract so a stray Esc during a multi-GB torch download doesn't+ // SIGTERM pip mid-stream.+ closeOnEsc={false}+ // Bespoke backdrop: keep the existing blur. The pt-[10vh] from align=top+ // is fine here — the original was pt-[8vh] but the 2vh delta is+ // imperceptible (~16px) and not worth a custom override.+ backdropClassName="bg-black/70 backdrop-blur-sm"+ ariaLabelledBy="flux2-install-title"+ panelClassName="bg-port-card rounded-xl border border-port-border shadow-2xl overflow-hidden flex flex-col max-h-[80vh]"+ >{/* Header */}<div className="flex items-center justify-between px-5 py-4 border-b border-port-border"><div className="flex items-center gap-2.5">@@ -283,7 +289,6 @@ export default function Flux2InstallModal({ open, onClose, onComplete }) {</>)}</div>- </div>- </div>+ </Modal>);}diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxindex fe85d265a4..cb06a3e0ed 100644--- a/client/src/components/media/MediaLightbox.jsx+++ b/client/src/components/media/MediaLightbox.jsx@@ -7,6 +7,13 @@ import toast from '../ui/Toast';import PromptRefineModal from './PromptRefineModal';import AddToCollectionMenu from './AddToCollectionMenu';+// Intentionally NOT migrated to <ui/Modal>. The prev/next buttons sit as+// viewport-edge siblings of the card (not children of a constrained panel+// box), and the Esc cascade refineOpen → drawerOpen → fullScreen → close+// is layered into the window keydown handler below. Modal would wrap+// children in a panel container and add its own Esc listener — both fight+// this lightbox's existing UX.+const NOTE_MAX = 2000;const NOTE_DEBOUNCE_MS = 500;diff --git a/client/src/components/media/PromptRefineModal.jsx b/client/src/components/media/PromptRefineModal.jsxindex 398c5ca862..8f515a537d 100644--- a/client/src/components/media/PromptRefineModal.jsx+++ b/client/src/components/media/PromptRefineModal.jsx@@ -2,49 +2,17 @@ import { useEffect, useState } from 'react';import { ListPlus, Sparkles, Wand2, X } from 'lucide-react';import ProviderModelSelector from '../ProviderModelSelector';import toast from '../ui/Toast';+import Modal from '../ui/Modal';import useProviderModels from '../../hooks/useProviderModels';import { generateImage, generateVideo, refineMediaPrompt } from '../../services/api';--function getRenderConfig(item) {- const raw = item?.raw || {};- if (item?.kind === 'image') {- return {- mode: item.mode || 'local',- modelId: item.modelId,- width: item.width,- height: item.height,- steps: item.steps,- guidance: item.guidance,- cfgScale: raw.cfgScale ?? raw.cfg_scale,- seed: item.seed,- quantize: item.quantize,- loraFilenames: raw.loraFilenames,- loraScales: raw.loraScales,- };- }- return {- mode: item.mode || 'text',- modelId: item.modelId,- width: item.width,- height: item.height,- numFrames: item.numFrames,- fps: item.fps,- steps: raw.steps,- // Nullish coalescing — a deliberate `0` guidanceScale is valid for some- // video models and must survive the round-trip back into the queued payload.- guidanceScale: raw.guidanceScale ?? raw.guidance,- seed: raw.seed,- tiling: raw.tiling,- disableAudio: raw.disableAudio,- };-}+import { getRenderConfigForItem } from './normalize';// Refine→queue forces text-to-video; the source image/last-frame from the// original render isn't carried into the modal, so image-to-video can't be// reproduced from here without re-uploading.function queuePayload(item, refinement) {const base = {- ...getRenderConfig(item),+ ...getRenderConfigForItem(item),prompt: refinement.prompt,negativePrompt: refinement.negativePrompt || undefined,...(item.kind === 'video' ? { mode: 'text' } : {}),@@ -104,7 +72,7 @@ export default function PromptRefineModal({ item, open, onClose }) {feedback: feedback.trim(),providerId: selectedProviderId,model: selectedModel || undefined,- renderConfig: getRenderConfig(item),+ renderConfig: getRenderConfigForItem(item),});setRefinedPrompt(result.prompt || '');setRefinedNegative(result.negativePrompt || '');@@ -143,38 +111,31 @@ export default function PromptRefineModal({ item, open, onClose }) {};return (- <div- className="fixed inset-0 z-[70] bg-black/80 flex items-center justify-center p-4"- // Stop the click before the underlying MediaLightbox backdrop sees it —- // both layers wire onClick={onClose} on the backdrop, and without- // stopPropagation a single backdrop click would dismiss the refine modal- // AND close the lightbox underneath it.- onClick={(e) => { e.stopPropagation(); onClose(); }}- role="presentation"+ <Modal+ open={open}+ onClose={onClose}+ size="xl"+ zIndexClassName="z-[70]"+ backdropClassName="bg-black/80"+ ariaLabelledBy="prompt-refine-title"+ panelClassName="max-h-[90vh] overflow-hidden bg-port-card border border-port-border rounded-xl shadow-2xl flex flex-col">- <section- className="w-full max-w-3xl max-h-[90vh] overflow-hidden bg-port-card border border-port-border rounded-xl shadow-2xl flex flex-col"- onClick={(e) => e.stopPropagation()}- role="dialog"- aria-modal="true"- aria-labelledby="prompt-refine-title"- >- <header className="flex items-center justify-between gap-3 px-4 py-3 border-b border-port-border">- <div className="flex items-center gap-2 min-w-0">- <Sparkles className="w-4 h-4 text-port-accent shrink-0" />- <h2 id="prompt-refine-title" className="text-sm font-semibold text-white">Refine Prompt</h2>- </div>- <button- type="button"- onClick={onClose}- className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50"- aria-label="Close"- >- <X className="w-4 h-4" />- </button>- </header>-- <div className="flex-1 overflow-y-auto p-4 space-y-4">+ <header className="flex items-center justify-between gap-3 px-4 py-3 border-b border-port-border">+ <div className="flex items-center gap-2 min-w-0">+ <Sparkles className="w-4 h-4 text-port-accent shrink-0" />+ <h2 id="prompt-refine-title" className="text-sm font-semibold text-white">Refine Prompt</h2>+ </div>+ <button+ type="button"+ onClick={onClose}+ className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50"+ aria-label="Close"+ >+ <X className="w-4 h-4" />+ </button>+ </header>++ <div className="flex-1 overflow-y-auto p-4 space-y-4"><div><label htmlFor="prompt-refine-feedback" className="block text-[11px] uppercase tracking-wide text-gray-500 mb-1">Feedback@@ -245,25 +206,24 @@ export default function PromptRefineModal({ item, open, onClose }) {)}</div>- <footer className="flex items-center justify-end gap-2 px-4 py-3 border-t border-port-border">- <button- type="button"- onClick={onClose}- className="px-3 py-2 rounded-lg text-sm text-gray-300 hover:text-white hover:bg-port-border/50"- >- Cancel- </button>- <button- type="button"- onClick={queueRender}- disabled={!canQueue}- className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-success text-white text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:opacity-90"- >- <ListPlus className="w-4 h-4" />- {queueing ? 'Queueing...' : 'Queue Render'}- </button>- </footer>- </section>- </div>+ <footer className="flex items-center justify-end gap-2 px-4 py-3 border-t border-port-border">+ <button+ type="button"+ onClick={onClose}+ className="px-3 py-2 rounded-lg text-sm text-gray-300 hover:text-white hover:bg-port-border/50"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={queueRender}+ disabled={!canQueue}+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-success text-white text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:opacity-90"+ >+ <ListPlus className="w-4 h-4" />+ {queueing ? 'Queueing...' : 'Queue Render'}+ </button>+ </footer>+ </Modal>);}diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.jsindex f27cad7744..3d20418ebd 100644--- a/client/src/components/media/normalize.js+++ b/client/src/components/media/normalize.js@@ -88,3 +88,72 @@ export function normalizeVideo(v) {raw: v,};}++// Resolve `loraFilenames` from a raw sidecar with four fallbacks:+// 1. raw.loraFilenames — new gen records, already basenames+// 2. raw.lora_filenames — same shape, snake_case writer+// 3. raw.loraPaths — legacy records pre-refactor, absolute paths+// 4. raw.lora_paths — same legacy shape, snake_case+// Legacy paths are reduced to basenames so the requeued payload matches the+// new `loraFilenames` contract on the server.+function pickLoraFilenames(raw) {+ if (Array.isArray(raw.loraFilenames)) return raw.loraFilenames;+ if (Array.isArray(raw.lora_filenames)) return raw.lora_filenames;+ const paths = Array.isArray(raw.loraPaths) ? raw.loraPaths+ : Array.isArray(raw.lora_paths) ? raw.lora_paths+ : null;+ if (!paths) return undefined;+ return paths+ .map((p) => (typeof p === 'string' ? p.split(/[\\/]/).pop() : ''))+ .filter(Boolean);+}++// Sidecar field knowledge co-located with the normalize functions. Sidecars+// were written with both snake_case (Python writer) and camelCase (Node+// writer) over the project's history; the fallback chains keep older renders+// queueable from <PromptRefineModal> without forcing a one-shot migration.+//+// Returns the subset of fields the queue-render API accepts for the given+// kind. The `mode` here is the *original* render mode (defaulted when+// missing); callers may override it (e.g. PromptRefineModal forces+// `mode: 'text'` for video requeues so a missing source-image doesn't drop+// the render).+export function getRenderConfigForItem(item) {+ if (!item) return {};+ const raw = item.raw || {};+ if (item.kind === 'image') {+ return {+ mode: item.mode || 'local',+ modelId: item.modelId,+ width: item.width,+ height: item.height,+ steps: item.steps,+ guidance: item.guidance,+ cfgScale: raw.cfgScale ?? raw.cfg_scale,+ seed: item.seed,+ quantize: item.quantize,+ loraFilenames: pickLoraFilenames(raw),+ loraScales: raw.loraScales ?? raw.lora_scales,+ };+ }+ if (item.kind === 'video') {+ return {+ mode: item.mode || 'text',+ modelId: item.modelId,+ width: item.width,+ height: item.height,+ numFrames: item.numFrames,+ fps: item.fps,+ steps: raw.steps,+ // Nullish coalescing — a deliberate `0` guidanceScale is valid for some+ // video models and must survive the round-trip back into the queued payload.+ guidanceScale: raw.guidanceScale ?? raw.guidance_scale ?? raw.guidance,+ seed: raw.seed,+ tiling: raw.tiling,+ disableAudio: raw.disableAudio ?? raw.disable_audio,+ loraFilenames: pickLoraFilenames(raw),+ loraScales: raw.loraScales ?? raw.lora_scales,+ };+ }+ return {};+}diff --git a/client/src/components/media/normalize.test.js b/client/src/components/media/normalize.test.jsnew file mode 100644index 0000000000..2e51e73f40--- /dev/null+++ b/client/src/components/media/normalize.test.js@@ -0,0 +1,195 @@+import { describe, it, expect } from 'vitest';+import { getRenderConfigForItem, normalizeImage, normalizeVideo } from './normalize.js';++// These tests pin the sidecar field-name knowledge in normalize.js. If a new+// field surfaces in a render sidecar, surface it here so the requeue path in+// <PromptRefineModal> stays in lockstep with the writers.++describe('getRenderConfigForItem - image', () => {+ it('returns empty object for null/undefined', () => {+ expect(getRenderConfigForItem(null)).toEqual({});+ expect(getRenderConfigForItem(undefined)).toEqual({});+ });++ it('returns empty object for unknown kind', () => {+ expect(getRenderConfigForItem({ kind: 'audio' })).toEqual({});+ });++ it('reads camelCase sidecar fields directly', () => {+ const image = normalizeImage({+ filename: 'a.png',+ prompt: 'a cat',+ width: 512,+ height: 512,+ steps: 20,+ guidance: 7.5,+ seed: 42,+ quantize: 8,+ mode: 'local',+ modelId: 'flux',+ cfgScale: 6.5,+ loraFilenames: ['lora-x.safetensors'],+ loraScales: [0.8],+ });+ const cfg = getRenderConfigForItem(image);+ expect(cfg).toMatchObject({+ mode: 'local',+ modelId: 'flux',+ width: 512,+ height: 512,+ steps: 20,+ guidance: 7.5,+ cfgScale: 6.5,+ seed: 42,+ quantize: 8,+ loraFilenames: ['lora-x.safetensors'],+ loraScales: [0.8],+ });+ });++ it('falls back to snake_case sidecar fields when camelCase missing', () => {+ // Simulate a sidecar written by the Python pipeline (snake_case).+ const image = normalizeImage({+ filename: 'b.png',+ prompt: 'a dog',+ width: 1024,+ height: 1024,+ modelId: 'flux2',+ mode: 'local',+ cfg_scale: 5.5,+ lora_filenames: ['lora-y.safetensors'],+ lora_scales: [1.0],+ });+ const cfg = getRenderConfigForItem(image);+ expect(cfg.cfgScale).toBe(5.5);+ expect(cfg.loraFilenames).toEqual(['lora-y.safetensors']);+ expect(cfg.loraScales).toEqual([1.0]);+ });++ it('prefers camelCase over snake_case when both present', () => {+ // Drift-safety: a re-emit of an older sidecar could carry both shapes.+ // The newer convention (camelCase) wins so the most recently set value+ // doesn't get shadowed by a stale snake_case alias.+ const image = normalizeImage({+ filename: 'c.png',+ prompt: '',+ cfgScale: 7,+ cfg_scale: 9,+ loraFilenames: ['new.safetensors'],+ lora_filenames: ['old.safetensors'],+ });+ const cfg = getRenderConfigForItem(image);+ expect(cfg.cfgScale).toBe(7);+ expect(cfg.loraFilenames).toEqual(['new.safetensors']);+ });++ it('defaults mode to "local" when item.mode unset', () => {+ const image = normalizeImage({ filename: 'd.png', prompt: '' });+ const cfg = getRenderConfigForItem(image);+ expect(cfg.mode).toBe('local');+ });++ it('falls back to legacy loraPaths when loraFilenames is absent', () => {+ // Older sidecars (pre-refactor) only persisted absolute loraPaths. The+ // server image-gen route still accepts that legacy field, but the+ // requeue payload from <PromptRefineModal> uses loraFilenames. Derive+ // basenames so legacy items don't lose their LoRA configuration on+ // refine-and-resubmit.+ const image = normalizeImage({+ filename: 'e.png',+ prompt: '',+ loraPaths: ['/abs/path/to/oldLora.safetensors', '/other/dir/styleA.safetensors'],+ });+ const cfg = getRenderConfigForItem(image);+ expect(cfg.loraFilenames).toEqual(['oldLora.safetensors', 'styleA.safetensors']);+ });++ it('falls back to legacy snake-case lora_paths', () => {+ const image = normalizeImage({+ filename: 'f.png',+ prompt: '',+ lora_paths: ['C:\\loras\\winLora.safetensors'],+ });+ const cfg = getRenderConfigForItem(image);+ expect(cfg.loraFilenames).toEqual(['winLora.safetensors']);+ });+});++describe('getRenderConfigForItem - video', () => {+ it('reads camelCase sidecar fields directly', () => {+ const video = normalizeVideo({+ id: 'v1',+ filename: 'a.mp4',+ prompt: 'pan',+ width: 720,+ height: 480,+ numFrames: 64,+ fps: 24,+ modelId: 'ltx',+ mode: 'text',+ steps: 30,+ guidanceScale: 3.5,+ seed: 100,+ tiling: true,+ disableAudio: false,+ loraFilenames: ['lora-cinematic.safetensors'],+ loraScales: [0.9],+ });+ const cfg = getRenderConfigForItem(video);+ expect(cfg).toMatchObject({+ mode: 'text',+ modelId: 'ltx',+ width: 720,+ height: 480,+ numFrames: 64,+ fps: 24,+ steps: 30,+ guidanceScale: 3.5,+ seed: 100,+ tiling: true,+ disableAudio: false,+ loraFilenames: ['lora-cinematic.safetensors'],+ loraScales: [0.9],+ });+ });++ it('falls back to snake_case sidecar fields when camelCase missing', () => {+ const video = normalizeVideo({+ id: 'v2',+ filename: 'b.mp4',+ prompt: '',+ modelId: 'ltx',+ mode: 'text',+ steps: 25,+ guidance_scale: 2.0,+ disable_audio: true,+ lora_filenames: ['lora-z.safetensors'],+ lora_scales: [0.5],+ });+ const cfg = getRenderConfigForItem(video);+ expect(cfg.guidanceScale).toBe(2.0);+ expect(cfg.disableAudio).toBe(true);+ expect(cfg.loraFilenames).toEqual(['lora-z.safetensors']);+ expect(cfg.loraScales).toEqual([0.5]);+ });++ it('preserves a deliberate guidanceScale of 0', () => {+ // 0 is a valid setting for some video models — must not be coerced via+ // truthy fallback.+ const video = normalizeVideo({ id: 'v3', filename: 'c.mp4', prompt: '', guidanceScale: 0 });+ const cfg = getRenderConfigForItem(video);+ expect(cfg.guidanceScale).toBe(0);+ });++ it('falls back to legacy `guidance` if neither guidanceScale variant present', () => {+ const video = normalizeVideo({ id: 'v4', filename: 'd.mp4', prompt: '', guidance: 4.2 });+ const cfg = getRenderConfigForItem(video);+ expect(cfg.guidanceScale).toBe(4.2);+ });++ it('defaults mode to "text" when item.mode unset', () => {+ const video = normalizeVideo({ id: 'v5', filename: 'e.mp4', prompt: '' });+ const cfg = getRenderConfigForItem(video);+ expect(cfg.mode).toBe('text');+ });+});diff --git a/client/src/components/ui/Modal.jsx b/client/src/components/ui/Modal.jsxnew file mode 100644index 0000000000..fd06524635--- /dev/null+++ b/client/src/components/ui/Modal.jsx@@ -0,0 +1,279 @@+/**+ * Shared modal chrome — backdrop + Esc handling + click-outside.+ *+ * Replaces ~10 hand-rolled variants of `fixed inset-0 z-50 bg-black/70 flex+ * items-center justify-center p-4` scattered across the app. The wrapped+ * component owns its own header / footer / form chrome; Modal only owns the+ * outer backdrop and the dialog panel container — so each conversion is 1:1+ * with the existing markup (no visual regressions, no header reshuffling).+ *+ * Sizing presets mirror the panels before extraction:+ * sm max-w-md+ * md max-w-lg (default)+ * lg max-w-2xl+ * xl max-w-3xl+ * '2xl' max-w-4xl+ * '3xl' max-w-6xl+ * none no width clamp (caller owns sizing via panelClassName)+ *+ * Divergent call-site behavior is opt-in via flags:+ * closeOnBackdrop=false EditAppModal / MemoryEditModal / ResumeAgentModal+ * — long forms where an accidental click on the+ * overlay would lose typed state.+ * closeOnEsc=false Flux2InstallModal — never wired Esc pre-refactor.+ * Modal still registers in the Esc stack as the+ * top-most layer so Esc is blocked (no fallthrough+ * to underlying modals); it just doesn't dispatch+ * a close.+ * onEsc Caller-supplied Esc handler. When provided, Esc+ * on the top-most modal invokes `onEsc` instead of+ * `onClose`. Used by LayoutEditor (Esc cancels an+ * inline rename/delete mode without closing the+ * editor) and KeyboardHelp (defers to its own+ * toggle hook).+ * align='top' LayoutEditor / KeyboardHelp / Flux2InstallModal.+ * usePortal LayoutEditor / KeyboardHelp — escape any+ * stacking-context ancestors.+ *+ * Stacking: Modal uses a single module-scope bubble-phase `keydown`+ * listener that dispatches Esc only to the top-most open Modal — and only+ * the top-most. Every open Modal registers on the stack (regardless of its+ * Esc opt-in), so a closeOnEsc=false top-most layer still blocks the+ * keystroke from reaching the modal beneath it. Inner widgets that consume+ * Esc themselves (native <select> closing a dropdown, custom popovers) can+ * call event.preventDefault() — Modal honours `defaultPrevented` and skips+ * the close in that case.+ */++import { useEffect, useId, useRef } from 'react';+import { createPortal } from 'react-dom';++const SIZE_CLASSES = {+ sm: 'max-w-md',+ md: 'max-w-lg',+ lg: 'max-w-2xl',+ xl: 'max-w-3xl',+ '2xl': 'max-w-4xl',+ '3xl': 'max-w-6xl',+ none: '',+};++// Per-align flex + padding. Centre uses `p-4` so the panel doesn't touch the+// viewport edge on mobile; callers that need an edge-to-edge layout (e.g. a+// modal that supplies its own padding internally) should pass align='none'.+// `backdropClassName` is appended last in the class string; actual Tailwind+// utility precedence is decided by CSS source order, not class-attribute+// order — see the note next to the overlay <div> below.+const ALIGN_CLASSES = {+ center: 'items-center justify-center p-4',+ top: 'items-start justify-center pt-[10vh] px-4 pb-4',+ // No padding — for callers that historically had a bare overlay (no `p-*`)+ // and provide their own panel-internal padding instead. Used by+ // ResumeAgentModal where the pre-refactor overlay was+ // `fixed inset-0 ... flex items-center justify-center` with no padding.+ none: 'items-center justify-center',+};++// Module-scope stack of open Modal ids. A single bubble-phase keydown+// listener on `window` dispatches Esc only to the top-most modal — every+// other Modal listener (including the layer beneath this one) is blocked via+// stopImmediatePropagation after dispatch.+//+// Bubble phase, not capture: an inner widget that wants to own Esc (native+// <select> closing its dropdown, custom popover dismissing itself) gets the+// event first and can call event.preventDefault(). We honour+// `event.defaultPrevented` and skip the close in that case, so opening a+// <select> inside a modal and pressing Esc closes the menu instead of the+// whole modal.+//+// Modals register on the stack regardless of whether they opt in to Esc, so+// a non-dismissible top-most layer still absorbs the keystroke and prevents+// fallthrough to the modal beneath it.+//+// The listener is registered at module load (the first time any Modal-using+// component imports this file) so it runs before any window keydown handler+// that mounts later. `stopImmediatePropagation` only blocks listeners+// registered after this one on the same target, so install-order matters in+// principle — but in practice Modal is imported transitively by enough+// always-mounted shells that the order is consistent. If a future component+// adds a window keydown handler at module load and runs first, this Modal+// will still dispatch (because its handler exists), but won't block that+// earlier listener. The HMR-safe install pattern below (`__portos_modal_esc`+// globalThis flag + import.meta.hot.dispose) prevents duplicate installs on+// dev hot-reload.+const modalStack = [];+const escHandlers = new Map();++function handleGlobalEsc(e) {+ if (e.key !== 'Escape' || modalStack.length === 0) return;+ // Always swallow the keystroke at this layer so it can't reach window-+ // level handlers behind us (MediaLightbox, voice-widget capture, etc.).+ // Whether we also dispatch the close handler depends on+ // `defaultPrevented`: if a child widget already consumed Esc (focused+ // <select> closing its dropdown, custom menu calling preventDefault()),+ // skip the close — but the keystroke is still ours to absorb.+ e.stopImmediatePropagation();+ if (e.defaultPrevented) return;+ const top = modalStack[modalStack.length - 1];+ const handler = escHandlers.get(top);+ if (handler) handler();+}++if (typeof window !== 'undefined') {+ // Install both window AND document keydown listeners. Bubble-phase event+ // order on the same keystroke is: target → ... → document → window. A+ // document-level handler installed by another component (e.g.+ // useKeyboardHelp, AddToCollectionMenu's click-away effect) fires before+ // our window listener, so without a document-level listener of our own+ // those handlers could react to Esc while a modal is open and dismiss the+ // wrong layer. Installing at both phases — and stopImmediatePropagation()+ // at both — gives the top-most modal full ownership of the keystroke+ // regardless of where competing listeners are bound.+ //+ // Guarded against double-install on Vite HMR. The module can re-evaluate+ // when it (or one of its importers) is edited; without the globalThis+ // flag the handlers would stack up, with each copy referencing the stale+ // modalStack from its own module instance.+ if (!globalThis.__portos_modal_esc_installed) {+ window.addEventListener('keydown', handleGlobalEsc);+ document.addEventListener('keydown', handleGlobalEsc);+ globalThis.__portos_modal_esc_installed = true;+ }+ // On HMR dispose, tear down both listeners so the next module instance+ // can re-install them cleanly against its own modalStack/escHandlers.+ if (import.meta.hot) {+ import.meta.hot.dispose(() => {+ window.removeEventListener('keydown', handleGlobalEsc);+ document.removeEventListener('keydown', handleGlobalEsc);+ delete globalThis.__portos_modal_esc_installed;+ });+ }+}++function pushModal(id) {+ modalStack.push(id);+}++function popModal(id) {+ const idx = modalStack.lastIndexOf(id);+ if (idx >= 0) modalStack.splice(idx, 1);+}++export default function Modal({+ open,+ onClose,+ onEsc,+ children,+ size = 'md',+ closeOnBackdrop = true,+ closeOnEsc = true,+ align = 'center',+ usePortal = false,+ zIndexClassName = 'z-50',+ backdropClassName = 'bg-black/70',+ panelClassName = '',+ ariaLabelledBy,+ ariaLabel,+}) {+ const backdropRef = useRef(null);+ // `useId()` is React's render-safe stable id source — survives StrictMode's+ // double-invoke without allocating extra ids the way a `modalIdSeq++`+ // module-scope counter would.+ const modalId = useId();+ // Latest handler refs — kept fresh on every render without re-running the+ // stack-registration effect. This decouples handler identity (which+ // changes every render when callers use inline arrow functions, e.g.+ // DeployPanel during streaming output) from stack push/pop, which must+ // only happen when `open` toggles. Otherwise an unrelated render of one+ // modal would pop+re-push it and accidentally move it above another+ // modal that opened later.+ const onCloseRef = useRef(onClose);+ const onEscRef = useRef(onEsc);+ const closeOnEscRef = useRef(closeOnEsc);+ onCloseRef.current = onClose;+ onEscRef.current = onEsc;+ closeOnEscRef.current = closeOnEsc;++ // Push/pop only on open toggle + unmount. Handler indirection through+ // refs lets us absorb prop changes (new onClose / onEsc / closeOnEsc)+ // without touching the stack. The dispatched handler is one of:+ // - onEsc, if provided (caller wants custom Esc semantics — e.g.+ // LayoutEditor cancels an inline mode instead of closing).+ // - onClose, if closeOnEsc is true (the common case).+ // - undefined → no dispatch, but Esc is still swallowed at this layer+ // so it can't fall through to an underlying modal.+ useEffect(() => {+ if (!open) return;+ const id = modalId;+ escHandlers.set(id, () => {+ if (onEscRef.current) { onEscRef.current(); return; }+ if (closeOnEscRef.current) onCloseRef.current?.();+ });+ pushModal(id);+ return () => {+ escHandlers.delete(id);+ popModal(id);+ };+ }, [open]);++ if (!open) return null;++ // Always stop propagation when the click lands on the backdrop element so a+ // backdrop click on this modal cannot bubble up to an ancestor modal /+ // lightbox / overlay handler and accidentally dismiss *that* layer. We do+ // this even when `closeOnBackdrop` is false — non-dismissible modals must+ // still swallow their own backdrop clicks.+ const handleBackdropClick = (e) => {+ if (e.target !== backdropRef.current) return;+ e.stopPropagation();+ if (!closeOnBackdrop) return;+ onClose?.();+ };++ const alignClass = ALIGN_CLASSES[align] || ALIGN_CLASSES.center;+ const sizeClass = SIZE_CLASSES[size] ?? SIZE_CLASSES.md;+ const widthClass = size === 'none' ? '' : `w-full ${sizeClass}`;++ const overlay = (+ <div+ ref={backdropRef}+ // `backdropClassName` (caller override) is appended last so callers can+ // visually see their override at the end of the class string. NOTE:+ // Tailwind utility precedence is decided by CSS source order in the+ // generated stylesheet, NOT class-attribute order, so two same-property+ // utilities like `p-4` and `p-0` resolve by which one Tailwind emits+ // later — typically the higher-numbered preset. To reliably beat a+ // default like `p-4`, callers should use a more specific override:+ // arbitrary values (`p-[0px]`), `!important` (`!p-0`), or a different+ // align variant. The string-order convention here is documentation of+ // intent, not an enforcement mechanism.+ className={`fixed inset-0 ${zIndexClassName} flex ${alignClass} ${backdropClassName}`}+ onClick={handleBackdropClick}+ role="presentation"+ >+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby={ariaLabelledBy}+ aria-label={!ariaLabelledBy ? ariaLabel : undefined}+ className={`relative ${widthClass} ${panelClassName}`}+ // Swallow click bubbling at the panel boundary. Two reasons: (1)+ // target-check on the backdrop already prevents panel clicks from+ // firing our own backdrop dismiss, but if this Modal is rendered as+ // a child of another modal/portal whose ancestor div has a bubble-+ // listening onClick (e.g. MediaLightbox's `onClick={onClose}`), the+ // child click would still propagate and dismiss the parent. (2) it+ // matches the original hand-rolled modals' behavior so the refactor+ // stays 1:1.+ onClick={(e) => e.stopPropagation()}+ >+ {children}+ </div>+ </div>+ );++ if (usePortal && typeof document !== 'undefined') {+ return createPortal(overlay, document.body);+ }+ return overlay;+}diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsxindex 494299e653..ed27e25510 100644--- a/client/src/pages/Loras.jsx+++ b/client/src/pages/Loras.jsx@@ -11,6 +11,7 @@ import { useState, useEffect, useCallback } from 'react';import { Link } from 'react-router-dom';import { Trash2, Download, ExternalLink, Sparkles, AlertTriangle, KeyRound, Check, X, RefreshCw, Wand2 } from 'lucide-react';import toast from '../components/ui/Toast';+import Modal from '../components/ui/Modal';import { formatBytes } from '../utils/formatters';import { RUNNER_FAMILIES } from '../lib/runnerFamilies';import {@@ -447,15 +448,6 @@ function CivitaiAuthModal({ pendingUrl, message, auth, onClose, onSaved, onRetryconst [saving, setSaving] = useState(false);const [clearing, setClearing] = useState(false);- // a11y: close on Escape so keyboard-only users can dismiss without- // tabbing to the X. Listen at document level (capture phase not- // required — modal is the only open dialog).- useEffect(() => {- const onKey = (e) => { if (e.key === 'Escape') onClose?.(); };- document.addEventListener('keydown', onKey);- return () => document.removeEventListener('keydown', onKey);- }, [onClose]);-const handleSave = async (e) => {e?.preventDefault?.();if (!apiKey.trim() || saving) return;@@ -488,72 +480,70 @@ function CivitaiAuthModal({ pendingUrl, message, auth, onClose, onSaved, onRetry};return (- <div className="fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4" onClick={onClose}>- <div- role="dialog"- aria-modal="true"- aria-labelledby="civitai-auth-title"- className="bg-port-card border border-port-border rounded-lg p-5 w-full max-w-md space-y-4"- onClick={(e) => e.stopPropagation()}- >- <div className="flex items-start justify-between gap-3">- <div className="flex items-center gap-2">- <KeyRound size={18} className="text-port-accent" />- <h2 id="civitai-auth-title" className="text-base font-semibold text-white">Civitai API key</h2>- </div>- <button onClick={onClose} className="text-gray-400 hover:text-gray-200" aria-label="Close">- <X size={16} />- </button>+ <Modal+ open+ onClose={onClose}+ size="sm"+ ariaLabelledBy="civitai-auth-title"+ panelClassName="bg-port-card border border-port-border rounded-lg p-5 space-y-4"+ >+ <div className="flex items-start justify-between gap-3">+ <div className="flex items-center gap-2">+ <KeyRound size={18} className="text-port-accent" />+ <h2 id="civitai-auth-title" className="text-base font-semibold text-white">Civitai API key</h2></div>+ <button onClick={onClose} className="text-gray-400 hover:text-gray-200" aria-label="Close">+ <X size={16} />+ </button>+ </div>- {message && (- <div className="text-xs bg-port-warning/10 border border-port-warning/30 rounded px-3 py-2 text-amber-100 flex items-start gap-2">- <AlertTriangle size={14} className="shrink-0 mt-0.5 text-port-warning" />- <span>{message}</span>- </div>- )}-- <p className="text-xs text-gray-400 leading-relaxed">- Some Civitai LoRAs require a logged-in token to download (adult or restricted content). Generate one at{' '}- <a href="https://civitai.com/user/account" target="_blank" rel="noopener noreferrer" className="text-port-accent hover:underline">- civitai.com/user/account- </a>{' '}- → API Keys. PortOS stores it in <code className="bg-port-bg px-1 rounded">data/settings.json</code>.- </p>+ {message && (+ <div className="text-xs bg-port-warning/10 border border-port-warning/30 rounded px-3 py-2 text-amber-100 flex items-start gap-2">+ <AlertTriangle size={14} className="shrink-0 mt-0.5 text-port-warning" />+ <span>{message}</span>+ </div>+ )}- <form onSubmit={handleSave} className="space-y-2">- <label className="block text-xs font-medium text-gray-400">API key</label>- <input- type="password"- value={apiKey}- onChange={(e) => setApiKey(e.target.value)}- placeholder={auth?.hasKey ? '•••• key already set — paste a new one to replace' : 'paste your Civitai API key'}- className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-200 placeholder:text-gray-600 font-mono"- disabled={saving}- autoFocus- />- <div className="flex items-center gap-2 pt-1">+ <p className="text-xs text-gray-400 leading-relaxed">+ Some Civitai LoRAs require a logged-in token to download (adult or restricted content). Generate one at{' '}+ <a href="https://civitai.com/user/account" target="_blank" rel="noopener noreferrer" className="text-port-accent hover:underline">+ civitai.com/user/account+ </a>{' '}+ → API Keys. PortOS stores it in <code className="bg-port-bg px-1 rounded">data/settings.json</code>.+ </p>++ <form onSubmit={handleSave} className="space-y-2">+ <label className="block text-xs font-medium text-gray-400">API key</label>+ <input+ type="password"+ value={apiKey}+ onChange={(e) => setApiKey(e.target.value)}+ placeholder={auth?.hasKey ? '•••• key already set — paste a new one to replace' : 'paste your Civitai API key'}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-200 placeholder:text-gray-600 font-mono"+ disabled={saving}+ autoFocus+ />+ <div className="flex items-center gap-2 pt-1">+ <button+ type="submit"+ disabled={saving || !apiKey.trim()}+ className="flex-1 bg-port-accent text-white px-4 py-2 rounded text-sm font-medium hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {saving ? 'Saving…' : (pendingUrl ? 'Save key & retry install' : 'Save key')}+ </button>+ {auth?.hasKey && auth?.source === 'settings' && (<button- type="submit"- disabled={saving || !apiKey.trim()}- className="flex-1 bg-port-accent text-white px-4 py-2 rounded text-sm font-medium hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed"+ type="button"+ onClick={handleClear}+ disabled={clearing}+ className="px-3 py-2 rounded text-xs text-port-error hover:bg-port-error/10 border border-port-error/30 disabled:opacity-50">- {saving ? 'Saving…' : (pendingUrl ? 'Save key & retry install' : 'Save key')}+ {clearing ? 'Clearing…' : 'Clear'}</button>- {auth?.hasKey && auth?.source === 'settings' && (- <button- type="button"- onClick={handleClear}- disabled={clearing}- className="px-3 py-2 rounded text-xs text-port-error hover:bg-port-error/10 border border-port-error/30 disabled:opacity-50"- >- {clearing ? 'Clearing…' : 'Clear'}- </button>- )}- </div>- </form>- </div>- </div>+ )}+ </div>+ </form>+ </Modal>);}diff --git a/server/vitest.config.js b/server/vitest.config.jsindex 45a7c899cd..05186769ee 100644--- a/server/vitest.config.js+++ b/server/vitest.config.js@@ -3,6 +3,12 @@ import { defineConfig } from 'vitest/config';export default defineConfig({test: {testTimeout: 10000,+ // Pick up tests from the client tree too — a handful of client-side pure+ // helpers (normalize.js sidecar field resolution) have unit tests that+ // belong alongside the source, but the client itself has no test runner.+ // The server's vitest is the project's single test entrypoint, so we+ // include the client *.test.js files here.+ include: ['**/*.test.js', '../client/src/**/*.test.js'],coverage: {provider: 'v8',reporter: ['text', 'text-summary', 'html'],