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
feat: pixie-forge media gen + federation TLS + setup polish (#161)
[._.]/ Adam Eivybb5377a03ab0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6774dc1dd0..25e1f3ebee 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,10 +2,22 @@## Changed+- **PortOS browser launches headed by default; setup/update auto-opens the dashboard in it.** The CDP-managed Chrome instance (`portos-browser`) used to default to `--headless=new`, which made sense for pure CDP automation but meant a fresh `./setup.sh` left no visible browser window even though the user expected to land on the dashboard. Default flipped to headed (`browser/server.js`); `data/browser-config.json` can still set `headless: true` to opt back in for headless workflows. New `scripts/open-ui-in-browser.js` polls `/api/system/health` and `/api/browser/health` (90s API timeout, separate 15s browser/CDP timeout, 500ms interval) and then POSTs to `/api/browser/navigate` with the dashboard URL — `http://localhost:5553` (loopback HTTP mirror) when HTTPS is on so the first paint doesn't trip a cert warning, otherwise `http://localhost:5555`. Hooked into `setup.sh` (after `npm start` returns) and `update.sh` / `update.ps1` (after `npm run pm2:restart`); fail-soft so the parent script's exit code is unaffected by Chrome being unreachable. Files: `browser/server.js`, `scripts/open-ui-in-browser.js` (new), `setup.sh`, `update.sh`, `update.ps1`.++- **`npm run setup` is now the all-in-one install command.** Previously `setup` only ran `setup-data + setup-db + setup-browser` and `install:all` was the longer chain that ended with `&& npm run setup`. That meant a user typing `npm run setup` got an under-prepared workspace (no dependencies installed). Restructured: `setup` now does the full chain (submodules + workspace deps + esbuild postinstall + node-pty rebuild + data/db/browser setup) and `install:all` is a backward-compat alias that calls `setup`. `setup.sh` switched its primary call from `npm run install:all` to `npm run setup`. To keep `update.sh` / `update.ps1` from doing every install twice (their existing `safe_install` retry block + the new `npm run setup` superset), the post-install `npm run setup` call in both scripts was replaced with the three data-side scripts directly (`setup-data` + `setup-db` + `setup-browser`), preserving the resilient ENOTEMPTY retry while avoiding redundant npm installs. The auto-open script's API readiness timeout was also bumped from 30s → 90s (with a separate 15s timeout for the browser-CDP poll) since first-boot can exceed 30s on slow disks. Files: `package.json`, `setup.sh`, `update.sh`, `update.ps1`, `scripts/open-ui-in-browser.js`.+- **Death Clock now multi-color in every surface (DRY)** — extracted the colored 7-unit countdown from `CompactCountdown` in MeatSpace's Overview tab into a shared `DeathClockCountdown` component used by the Dashboard widget, the Ambient/fullscreen view, and MeatSpace itself. The values are now colored consistently (years/months/weeks/days/hours/minutes/seconds → blue/purple/teal/green/yellow/orange/red) with a `size` prop ('sm' for the dashboard widget, 'md' for the MeatSpace hero, 'lg' for Ambient) so each surface picks its own type scale without duplicating the unit/color list. Adds weeks to the Dashboard widget and Ambient view (was 6 units, now 7) to match the MeatSpace layout. Files: `client/src/components/DeathClockCountdown.jsx` (new), `client/src/components/DeathClockWidget.jsx` (use shared), `client/src/pages/Ambient.jsx` (use shared), `client/src/components/meatspace/tabs/OverviewTab.jsx` (use shared).## Fixed+- **`portos-server` crash-loop on `Cannot find package 'multer'` from `videoGen.js`.** The new `server/routes/videoGen.js` was written against `multer` for `multipart/form-data` uploads but `multer` was never added to `server/package.json`, so a fresh `npm install --prefix server` left the server unable to import the route — `pm2 logs portos-server --err` showed an `ERR_MODULE_NOT_FOUND` loop and the API never bound to :5555. Fixed by switching to the existing `server/lib/multipart.js` helper (a stream-to-disk multer.diskStorage replacement that was already in the tree), which has the same `req.file = { path, originalname, mimetype, size }` contract. No new dependency added — per `CLAUDE.md`'s "default to writing code yourself", reusing the in-tree replacement is the right call. File: `server/routes/videoGen.js`.++- **`scripts/open-ui-in-browser.js` polled the wrong port when HTTPS was on.** The auto-open script's polling URLs (`/api/system/health`, `/api/browser/health`, `/api/browser/navigate`) were hardcoded to `http://localhost:5555`, but when a Tailscale cert is provisioned `:5555` speaks TLS only — every plain-HTTP request hit a handshake mismatch and timed out. The script computes a `LOCAL_BASE` once at startup: when `data/certs/cert.pem` exists it uses the loopback HTTP mirror (`http://localhost:5553`) for everything; otherwise plain `http://localhost:5555`. Same logic was already correct for the URL handed to the browser; now it's also used for the polls. File: `scripts/open-ui-in-browser.js`.++- **Federation peers stay offline after enabling Tailscale HTTPS.** When `npm run setup:cert` provisioned an HTTPS cert, every outbound federation hop (probe, query, announce, peer Socket.IO relay) started failing because Node's default `fetch()`/socket.io-client run with `rejectUnauthorized: true` and the peer's cert (real Let's Encrypt or self-signed fallback) couldn't always be verified by the calling instance. Per `CLAUDE.md`'s security model the Tailnet IS the trust boundary, so federation traffic doesn't need a second TLS validation layer on top of WireGuard. New `server/lib/peerHttpClient.js` exports a `peerFetch()` that uses `https.request` with a shared `https.Agent({ rejectUnauthorized: false, keepAlive: true })` for `https://` URLs and falls through to global `fetch` for `http://` URLs, plus a `peerSocketOptions` constant (`rejectUnauthorized: false`, `transports: ['websocket', 'polling']`) spread into the `io()` call in `peerSocketRelay.js`. The `peerBaseUrl()` builder is unchanged — the URL string is the same; only the dispatcher tolerates the cert. Two side issues fixed in the same pass: (1) the announce protocol now carries the announcer's Tailscale-issued hostname (`host` field added to `announceSchema` and to `announceSelf`'s POST body, sourced from a new `getSelfHost()` helper that reads `data/certs/meta.json` or `PORTOS_HOST` env override). `handleAnnounce` adopts the host on the receiving side when the peer record doesn't already have one, never overwriting a user-set value. This means bidirectional peer auto-creation finally produces records that can be reached over HTTPS instead of leaving an `address`-only row that can only speak plain HTTP. (2) Probe failures now log a classified one-line diagnostic (`DNS lookup failed`, `Connection refused`, `Host unreachable`, `Probe timeout`, `TLS reject`) instead of a generic `err.message`, so the next time something silently goes offline the cause is visible without strace. (3) `startPolling()` now clears `nextProbeAt`/`consecutiveFailures` on every peer at boot — a server restart is a clear "try again now" signal, and without this peers stuck at backoff tier 5 (24h) wouldn't auto-recover for up to a day after the fix is deployed. Files: `server/lib/peerHttpClient.js` (new), `server/lib/peerSelfHost.js` (new), `server/services/instances.js` (`peerFetch` everywhere, `getSelfHost()` in `announceSelf`, `host` adoption in `handleAnnounce`, `classifyProbeError`), `server/routes/instances.js` (`announceSchema.host`), `server/services/peerSocketRelay.js` (`peerSocketOptions`, `peerFetch` for initial agent fetch). Tests: `server/lib/peerHttpClient.test.js` (new, 2 tests for `peerSocketOptions` shape + `peerFetch` http fall-through), `server/lib/peerSelfHost.test.js` (new, 4 tests for env override / missing meta / tailscale mode / self-signed mode), `server/services/instances.test.js` extended with 4 new `handleAnnounce` host-flow tests.++- **Port story documented and startup banner clarified.** The unified port allocation has been correct in code since the Tailscale HTTPS work landed but docs and startup messages disagreed: `CLAUDE.md` still showed `health: 5554` as an example, the README told users to open `http://localhost:5554`, and the boot logs split the API URL and the loopback URL across two unrelated lines. There's now a single canonical statement of the rules: `:5555` is **always** the user-facing port (its scheme flips between HTTP and HTTPS based on whether `data/certs/{cert,key}.pem` exists, but the port number does not); `:5553` is a loopback-only HTTP mirror that spawns when HTTPS is on so curl/scripts skip cert warnings; `:5554` is dev-only Vite. The startup banner now prints all reachable URLs in one block (`https://<host>.<tailnet>.ts.net:5555`, `https://<tailscale-ip>:5555 (cert warning)`, `http://localhost:5553`), with the trusted hostname URL drawn from `getSelfHost()`. Files: `CLAUDE.md` (Port Allocation section corrected), `docs/PORTS.md` (new "How `:5555`, `:5553`, and `:5554` Relate" section with diagram), `README.md` (Quick Start + Network Access updated), `server/index.js` (banner), `client/vite.config.js` (one-line comment confirming the hardcoded `:5555` is intentional).+- **Codex 5.5 review round 1: navigation + lint + bundle** — addressed the four "Next 1-2 Days" items from `CODEX5.5_REVIEW.md`.- **Client lint runs again.** `npm run lint --prefix client` was crashing with `TypeError: expand is not a function` because the top-level `brace-expansion: ^5.0.5` security override was being inherited by ESLint's `minimatch@3` chain, which still consumes the v1 CommonJS API. Added a nested override (`"minimatch@3": { "brace-expansion": "^1.1.12" }`) so minimatch gets a patched-but-API-compatible version while everything else still gets v5. Fixing lint exposed real issues that pre-commit was silently skipping: `CharacterSheet.jsx:218` referenced an undefined `put` (should be `charPut`); `domIndex.js`/`voiceClient.js` used browser globals (`CSS`, `OfflineAudioContext`, `MediaRecorder`, `AudioWorkletNode`) that weren't declared in `eslint.config.js`. All errors fixed; lint is now 0 errors.- **Removed `/cos/scripts` dead route.** Sidebar + nav manifest pointed to a `scripts` tab that was merged into `Jobs` back in v1.34.0. Selecting Scripts from `⌘K`/voice/sidebar silently fell through to Tasks. Cleared the entry from both `Layout.jsx` and `navManifest.js`.@@ -18,6 +30,17 @@## Added+- **pixie-forge integration: full local image + video generation, models management, and AUTOMATIC1111-compatible tailnet API.** PortOS now ships the entire UI/UX of the standalone `pixie-forge` app folded into the same monorepo. The Image Gen page is replaced with a richer port (model picker, LoRA list with per-LoRA scale, quantization 3–8 bit, gallery with lightbox + remix + send-to-video, deletes), a new Video Gen page (`/video-gen`) handles LTX models with image-to-video, frame count, FPS, and tiling, a Media History page (`/media-history`) shows the generated-video grid with ffmpeg-based stitching and "continue from last frame" piping back into Image Gen, and a Media Models page (`/media-models`) lists every cached HuggingFace model + LoRA with disk usage and one-click delete.++ - **Three-mode backend**: `settings.imageGen.mode` toggles between **External** (current AUTOMATIC1111/Forge passthrough — unchanged behavior, default for backward compat) and **Local** (mflux on Apple Silicon, diffusers on Windows). The dispatcher in `server/services/imageGen/index.js` makes `generateImage()` mode-agnostic — the existing `/api/image-gen/generate` endpoint, the CoS tools registry, and avatar generation all keep working without code changes regardless of the active mode.+ - **PortOS as an A1111 server on the tailnet**: a new gated `/sdapi/v1/*` surface (txt2img, options, sd-models, samplers, progress) exposes whichever backend PortOS is configured for to *other* tailnet machines, so a Mac running PortOS in Local mode can serve as the SD backend for any A1111 client across the LAN. Off by default — `Settings → Image Gen → Expose A1111 API` is the toggle.+ - **HF cache + new data categories**: PortOS honors any existing `HF_HOME` (or HF's default `~/.cache/huggingface`) — it intentionally does NOT override it, so users keep their existing model cache wherever it already is. The new Media Models page lists every cached HF repo from `<HF_HOME>/hub` (or the default) with on-disk sizes and one-click delete. DataManager picks up three new categories under `data/` itself: `videos`, `video-thumbnails`, and `loras` (LoRA adapter `.safetensors` files live alongside the gen output, not in HF cache).+ - **Optional install — mirrors voice**: `scripts/setup-image-video.sh` installs `mflux`, `mlx_video`, `mlx_vlm`, `transformers<5`, `safetensors`, `huggingface_hub`, `numpy`, `cv2`, `tqdm` (or torch/diffusers on Windows), plus `ffmpeg`. Like voice, this is opt-in — fresh PortOS installs run external-only until you flip mode to Local and point the Settings tab at a Python with these packages installed.+ - **SSE-driven local progress**: the local backend spawns a Python child and streams `STATUS:`/`STAGE:`/`DOWNLOAD:`/tqdm-style progress over per-job `/api/{image,video}-gen/:jobId/events` SSE. The same emissions feed `imageGenEvents` / `videoGenEvents` (bridged to Socket.IO) so existing socket consumers (the Image Gen progress hook, voice agent, etc.) light up identically across modes. Cancel sends SIGTERM to the active child.+ - **Existing CoS tool entry preserved**: `Stable Diffusion` tool registration in CoS tools registry continues to work and now follows whichever mode is active.++ Files: `server/services/imageGen/{index,external,local}.js` (new dispatcher + per-mode services; old `server/services/imageGen.js` removed), `server/services/videoGen/{local,events}.js` (new), `server/routes/{imageGen,videoGen,imageVideoModels,sdapi}.js` (videoGen, models, sdapi new; imageGen rewired through dispatcher), `server/lib/fileUtils.js` (new PATHS: `loras`, `videos`, `videoThumbnails`), `server/index.js` (new route mounts, new static dirs for `/data/videos` and `/data/video-thumbnails`), `server/services/socket.js` (video-gen socket bridge), `server/services/dataManager.js` (videos/video-thumbnails/loras categories), `server/lib/navManifest.js` (`nav.video-gen`, `nav.media-history`, `nav.media-models`), `client/src/pages/{ImageGen,VideoGen,MediaHistory,MediaModels}.jsx` (ImageGen rewritten, others new), `client/src/components/settings/ImageGenTab.jsx` (mode picker, local config, A1111 expose toggle), `client/src/services/apiImageVideo.js` (new), `client/src/components/Layout.jsx` (sidebar AI section), `client/src/App.jsx` (new lazy routes), `scripts/setup-image-video.sh` (new), `scripts/{imagine_win,generate_win}.py` (copied from pixie-forge for Windows path).+- **Brain → Import: guided ChatGPT data-export wizard** — first slice of a "import from third parties" workflow lives at `/brain/import`. The page presents a source picker (ChatGPT available now; Claude/Notion placeholders for future slices; Obsidian short-circuits to the existing Brain → Notes vault flow) and on selection drives a 6-step wizard: (1) inline OpenAI export instructions with a deep link to the official help article, (2) drag-or-browse upload of the extracted `conversations.json` with client-side parse + 50 MB guard, (3) preview pane showing total conversations, message count, character total, custom-GPT (`gizmo`) count, earliest/latest dates and a sample of titles, (4) configure tags + skip-empty toggle, (5) progress, (6) per-conversation results with a deep-link to `Brain → Memory` and an expandable list of imported/skipped IDs. Each conversation becomes a Brain Memory record (title, transcript truncated to fit the 10K content cap, tags including any `gizmo-*` indicator, `source: 'chatgpt-import'` and `sourceCreatedAt` set from ChatGPT's `create_time`) while the full structured transcript and message tree is archived to `data/brain/imports/chatgpt/<conversation-id>.json` so a richer viewer or re-tagger can be built later without re-uploading. The mapping-tree walk reconstructs the visible conversation thread by following `current_node` back to the root (so edited/regenerated branches don't pollute the import) and gracefully renders non-text parts (`image_asset_pointer` becomes `[image]`, etc.). New endpoints: `GET /api/brain/import/sources`, `POST /api/brain/import/chatgpt/preview`, `POST /api/brain/import/chatgpt`. Nav manifest registers `nav.brain.import` with aliases `brain-import`, `import-chatgpt`, `chatgpt-import` and keywords `chatgpt`, `openai`, `export`, `third-party` so `⌘K` and voice resolve "import chatgpt" / "chatgpt import" straight to the wizard.Files: `server/services/chatgptImport.js` (new — parser + Memory writer + transcript archiver), `server/routes/brainImport.js` (new), `server/services/chatgptImport.test.js` (new — 12 unit tests for tree walk, parts coercion, tag sanitisation, truncation, skip-empty), `server/routes/brainImport.test.js` (new — 4 route tests covering sources, preview validation, and import dispatch), `server/index.js` (mount), `server/lib/navManifest.js` (entry), `client/src/components/brain/tabs/ImportTab.jsx` (new — source picker + ChatGPT wizard), `client/src/pages/Brain.jsx` (case wiring), `client/src/components/brain/constants.js` (TABS entry), `client/src/components/Layout.jsx` (sidebar link), `client/src/services/apiBrain.js` (3 new helpers).diff --git a/CLAUDE.md b/CLAUDE.mdindex e6df92b766..427fbacdbd 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -32,17 +32,15 @@ The default database password `portos` (in `ecosystem.config.cjs`, `docker-compo## Architecture-PortOS is a monorepo with Express.js server (port 5555) and React/Vite client (port 5554). PM2 manages app lifecycles. Data persists to JSON files in `./data/`.+PortOS is a monorepo with Express.js server (always user-facing on `:5555`, HTTP or HTTPS) and React/Vite client (Vite dev server on `:5554` in `npm run dev`; in `npm start` the built client is served from `:5555` directly). PM2 manages app lifecycles. Data persists to JSON files in `./data/`.### Port Allocation-PortOS uses ports 5554-5561. In native mode, PostgreSQL uses the system pg on port 5432; in Docker mode, port 5561. Define all ports in `ecosystem.config.cjs` using the `ports` object:+PortOS uses ports 5553-5561. In native mode, PostgreSQL uses the system pg on port 5432; in Docker mode, port 5561.-```javascript-ports: { api: 5555, health: 5554 } // labeled ports for documentation-```+The user-facing port is always **`:5555`** — its scheme flips between HTTP and HTTPS based on whether a TLS cert is provisioned (`npm run setup:cert`), but the port number does not. When HTTPS is on, a loopback-only HTTP mirror also spawns on `:5553` so local curl/scripts don't have to deal with cert warnings. `:5554` is the Vite dev server, used only in `npm run dev`.-See `docs/PORTS.md` for the full port allocation guide.+Define all ports in the top-level `PORTS` object in `ecosystem.config.cjs` (see `server/lib/ports.js` for the canonical re-export). See `docs/PORTS.md` for the full port allocation guide and a diagram of how `:5555`, `:5553`, and `:5554` relate.### Server (`server/`)- **Routes**: HTTP handlers with Zod validationdiff --git a/README.md b/README.mdindex 0ba5592731..ca49de1fce 100644--- a/README.md+++ b/README.md@@ -158,7 +158,16 @@ pm2 start ecosystem.config.cjspm2 save```-Access PortOS at `http://localhost:5554` (or via Tailscale at `http://[your-machine]:5554`).+Access PortOS at `http://localhost:5555` (or via Tailscale at `http://<machine>.<tailnet>.ts.net:5555`).++For HTTPS (recommended — required for the in-browser microphone, and you'll get a trusted cert via Tailscale's Let's Encrypt integration):++```bash+npm run setup:cert # uses `tailscale cert` if available, else self-signed+pm2 restart ecosystem.config.cjs+```++After that, `https://<machine>.<tailnet>.ts.net:5555` is the user-facing URL on every device. The same `:5555` is used for both HTTP and HTTPS — only the scheme changes. When HTTPS is enabled a loopback-only HTTP mirror also spawns at `http://localhost:5553` so local curl/scripts skip cert warnings (override with `PORTOS_HTTP_PORT`).PM2 keeps PortOS running in the background and auto-restarts on reboot (with `pm2 save` + `pm2 startup`).@@ -166,9 +175,11 @@ PM2 keeps PortOS running in the background and auto-restarts on reboot (with `pm```bashnpm run install:all # Install all dependencies-npm run dev # Vite hot-reload on 5554, API on 5555+npm run dev # Vite hot-reload on :5554, API on :5555 — open :5554 in dev```+`:5554` is **only** used in dev for the Vite hot-reload server; in production (`npm start` / PM2) the React build is served from `:5555` directly.+## Network AccessPortOS binds to `0.0.0.0` so you can access it from any device on your Tailscale network:@@ -177,7 +188,7 @@ PortOS binds to `0.0.0.0` so you can access it from any device on your Tailscale- Check logs and restart services from your phone- View dashboard on your tablet while coding on your laptop-> **Security Note**: PortOS is designed for private Tailscale networks. Do not expose ports 5554-5561 to the public internet. See the [Security Audit](./docs/SECURITY_AUDIT.md) for hardening details.+> **Security Note**: PortOS is designed for private Tailscale networks. Do not expose ports 5553-5561 to the public internet. See the [Security Audit](./docs/SECURITY_AUDIT.md) for hardening details.## Tech Stack@@ -232,7 +243,7 @@ Configure AI providers for the runner and Chief of Staff:### Architecture & Operations- [Architecture Overview](./docs/ARCHITECTURE.md) — System design, data flow, and service diagram- [API Reference](./docs/API.md) — 50+ REST endpoints and WebSocket events-- [Port Allocation](./docs/PORTS.md) — Port conventions (5554-5561) and allocation guide+- [Port Allocation](./docs/PORTS.md) — Port conventions (5553-5561) and allocation guide- [PM2 Configuration](./docs/PM2.md) — PM2 patterns and best practices### Developmentdiff --git a/browser/server.js b/browser/server.jsindex 4f6f3fd273..12a835da1c 100644--- a/browser/server.js+++ b/browser/server.js@@ -16,7 +16,11 @@ const HEALTH_PORT = parseInt(process.env.PORT || '5557', 10);const CDP_HOST = process.env.CDP_HOST || '127.0.0.1';let chromeProcess = null;-let headlessMode = true;+// Default headed — PortOS runs on a single user's dev machine where seeing+// the browser window matters (auto-opening the UI on setup/update, debugging+// CDP automation visually). Set `headless: true` in data/browser-config.json+// to opt back in for headless workflows.+let headlessMode = false;let downloadWs = null;let downloadWsReconnectTimer = null;let downloadDirCurrent = null;@@ -147,7 +151,7 @@ async function launchBrowser() {return;}- headlessMode = config.headless !== false;+ headlessMode = config.headless === true;const profileDir = config.userDataDir || DEFAULT_PROFILE_DIR;const chromePath = getChromePath();diff --git a/client/eslint.config.js b/client/eslint.config.jsindex 22eb779637..794474a110 100644--- a/client/eslint.config.js+++ b/client/eslint.config.js@@ -11,6 +11,7 @@ const browserGlobals = {requestAnimationFrame: 'readonly', cancelAnimationFrame: 'readonly',queueMicrotask: 'readonly',fetch: 'readonly', URL: 'readonly', URLSearchParams: 'readonly',+ EventSource: 'readonly',FormData: 'readonly', File: 'readonly', FileReader: 'readonly',Blob: 'readonly', Event: 'readonly', CustomEvent: 'readonly',EventTarget: 'readonly', AbortController: 'readonly', AbortSignal: 'readonly',diff --git a/client/src/App.jsx b/client/src/App.jsxindex a2f752bd71..7527db4fa2 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -1,5 +1,5 @@import { Suspense, lazy, useEffect } from 'react';-import { Routes, Route, Navigate } from 'react-router-dom';+import { Routes, Route, Navigate, useLocation } from 'react-router-dom';import Layout from './components/Layout';import { getSettings, updateSettings } from './services/api';import BrailleSpinner from './components/BrailleSpinner';@@ -45,7 +45,11 @@ const OpenClawPage = lazyWithReload(() => import('./pages/OpenClaw'));const Submodules = lazyWithReload(() => import('./pages/Submodules'));const ChiefOfStaff = lazyWithReload(() => import('./pages/ChiefOfStaff'));const Ask = lazyWithReload(() => import('./pages/Ask'));+const MediaGen = lazyWithReload(() => import('./pages/MediaGen'));const ImageGen = lazyWithReload(() => import('./pages/ImageGen'));+const VideoGen = lazyWithReload(() => import('./pages/VideoGen'));+const MediaHistory = lazyWithReload(() => import('./pages/MediaHistory'));+const MediaModels = lazyWithReload(() => import('./pages/MediaModels'));const CreateApp = lazyWithReload(() => import('./pages/CreateApp'));const Templates = lazyWithReload(() => import('./pages/Templates'));const PromptManager = lazyWithReload(() => import('./pages/PromptManager'));@@ -76,6 +80,13 @@ const PageLoader = () => (</div>);+// Preserve query string when redirecting legacy media routes — Settings.jsx's+// /image-gen?settings=1 chain depends on ?settings=1 reaching the new path.+function RedirectWithSearch({ to }) {+ const { search } = useLocation();+ return <Navigate to={`${to}${search}`} replace />;+}+// Force full reload on HMR — partial hot-replacement of the route tree// causes stale lazy imports and React Router errors on nested pathsif (import.meta.hot) {@@ -166,7 +177,17 @@ export default function App() {<Route path="character" element={<CharacterSheet />} /><Route path="ask" element={<Ask />} /><Route path="ask/:conversationId" element={<Ask />} />- <Route path="image-gen" element={<ImageGen />} />+ <Route path="media" element={<MediaGen />}>+ <Route index element={<Navigate to="/media/image" replace />} />+ <Route path="image" element={<ImageGen />} />+ <Route path="video" element={<VideoGen />} />+ <Route path="history" element={<MediaHistory />} />+ <Route path="models" element={<MediaModels />} />+ </Route>+ <Route path="image-gen" element={<RedirectWithSearch to="/media/image" />} />+ <Route path="video-gen" element={<RedirectWithSearch to="/media/video" />} />+ <Route path="media-history" element={<RedirectWithSearch to="/media/history" />} />+ <Route path="media-models" element={<RedirectWithSearch to="/media/models" />} /><Route path="wiki" element={<Navigate to="/wiki/overview" replace />} /><Route path="wiki/:tab" element={<Wiki />} /><Route path="agents" element={<Agents />} />diff --git a/client/src/components/Drawer.jsx b/client/src/components/Drawer.jsxnew file mode 100644index 0000000000..e7ef11919a--- /dev/null+++ b/client/src/components/Drawer.jsx@@ -0,0 +1,53 @@+import { useEffect } from 'react';+import { X } from 'lucide-react';++// Right-side slide-in panel for "settings over a feature page" pattern.+// Mobile (<sm): full width. Desktop: ~520px. Backdrop click + Esc close it.+// Caller controls open state — typically driven by a URL search param so the+// view stays deep-linkable per the project convention.+export default function Drawer({ open, onClose, title, children, widthClass = 'sm:w-[520px]' }) {+ useEffect(() => {+ if (!open) return;+ const onKey = (e) => { if (e.key === 'Escape') onClose(); };+ window.addEventListener('keydown', onKey);+ const prevOverflow = document.body.style.overflow;+ document.body.style.overflow = 'hidden';+ return () => {+ window.removeEventListener('keydown', onKey);+ document.body.style.overflow = prevOverflow;+ };+ }, [open, onClose]);++ if (!open) return null;++ return (+ <>+ <div+ className="fixed inset-0 z-40 bg-black/60"+ onClick={onClose}+ aria-hidden="true"+ />+ <aside+ role="dialog"+ aria-modal="true"+ aria-label={title}+ className={`fixed inset-y-0 right-0 z-50 w-full ${widthClass} bg-port-card border-l border-port-border shadow-2xl flex flex-col`}+ >+ <header className="flex items-center justify-between px-4 py-3 border-b border-port-border">+ <h2 className="text-base font-medium text-white">{title}</h2>+ <button+ type="button"+ onClick={onClose}+ className="p-2 rounded-lg text-gray-400 hover:text-white hover:bg-port-border/50 min-h-[40px] min-w-[40px] flex items-center justify-center"+ aria-label="Close settings"+ >+ <X className="w-5 h-5" />+ </button>+ </header>+ <div className="flex-1 overflow-y-auto p-4">+ {children}+ </div>+ </aside>+ </>+ );+}diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 6a468a8aae..ed4193c5b6 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -67,8 +67,8 @@ import {FilePen,MessageCircle,Swords,- Image as ImageIcon,HardDrive,+ Layers,MessagesSquare,BookOpen,NotebookPen,@@ -100,16 +100,16 @@ const navItems = [label: 'AI',icon: Bot,children: [- { to: '/image-gen', label: 'Image Gen', icon: ImageIcon },- { to: '/settings/image-gen', label: 'Image Gen Settings', icon: Settings },+ { to: '/media', label: 'Media Gen', icon: Layers },{ to: '/prompts', label: 'Prompts', icon: FileText },{ to: '/ai', label: 'Providers', icon: Bot }]},- { label: 'Apps', icon: Package, dynamic: 'apps', children: [] },+ { label: 'Apps', icon: Package, dynamic: 'apps', defaultTo: '/apps', children: [] },{label: 'Brain',icon: Brain,+ defaultTo: '/brain/inbox',children: [{ to: '/brain/config', label: 'Config', icon: Settings },{ to: '/brain/daily-log', label: 'Daily Log', icon: NotebookPen },@@ -143,6 +143,7 @@ const navItems = [label: 'Chief of Staff',icon: Crown,showBadge: true,+ defaultTo: '/cos/tasks',children: [{ to: '/cos/agents', label: 'Agents', icon: Cpu },{ to: '/cos/briefing', label: 'Briefing', icon: Newspaper },@@ -159,6 +160,7 @@ const navItems = [{label: 'Comms',icon: MessagesSquare,+ defaultTo: '/messages/inbox',children: [{ to: '/messages/config', label: 'Config', icon: Settings },{ to: '/messages/drafts', label: 'Drafts', icon: FilePen },@@ -191,6 +193,7 @@ const navItems = [{label: 'Digital Twin',icon: Heart,+ defaultTo: '/digital-twin/overview',children: [{ to: '/digital-twin/accounts', label: 'Accounts', icon: Globe },{ to: '/ask', label: 'Ask Yourself', icon: MessageCircle },@@ -212,6 +215,7 @@ const navItems = [{label: 'MeatSpace',icon: Skull,+ defaultTo: '/meatspace/overview',children: [{ to: '/meatspace/age', label: 'Age', icon: Clock },{ to: '/meatspace/alcohol', label: 'Alcohol', icon: Activity },@@ -228,6 +232,7 @@ const navItems = [{label: 'POST',icon: Zap,+ defaultTo: '/post/launcher',children: [{ to: '/post/config', label: 'Config', icon: Settings },{ to: '/post/history', label: 'History', icon: History },@@ -239,7 +244,12 @@ const navItems = [{label: 'Settings',icon: Settings,+ defaultTo: '/settings/general',children: [+ { to: '/settings/backup', label: 'Backup', icon: Download },+ { to: '/settings/database', label: 'Database', icon: Database },+ { to: '/settings/general', label: 'General', icon: Settings },+ { to: '/settings/mortalloom', label: 'MortalLoom', icon: Activity },{ to: '/settings/telegram', label: 'Telegram', icon: MessageSquare },{ to: '/settings/voice', label: 'Voice', icon: Mic }]@@ -247,10 +257,9 @@ const navItems = [{label: 'System',icon: HardDrive,+ defaultTo: '/cos/health',children: [- { to: '/settings/backup', label: 'Backup', icon: Download },{ to: '/data', label: 'Data', icon: HardDrive },- { to: '/settings/database', label: 'Database', icon: Database },{ to: '/cos/health', label: 'Health', icon: Activity },{ to: '/instances', label: 'Instances', icon: Network },{ to: '/loops', label: 'Loops', icon: RefreshCw },@@ -459,57 +468,71 @@ export default function Layout() {}// Collapsible section+ const defaultChildPath = item.defaultTo+ || (item.children && item.children.find(c => c.to)?.to)+ || null;++ const navigateToSection = () => {+ if (defaultChildPath) {+ navigate(defaultChildPath);+ // Ensure the section is expanded so the user can see siblings+ if (!expandedSections[item.label] && !collapsed) {+ toggleSection(item.label);+ }+ } else {+ toggleSection(item.label);+ }+ setMobileOpen(false);+ };++ const sectionRowClasses = `flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${+ isSectionActive(item)+ ? 'bg-port-accent/10 text-port-accent'+ : 'text-gray-400 hover:text-white hover:bg-port-border/50'+ }`;+return (<div key={item.label} className="mx-2">- <button- onClick={() => {- if (collapsed) {- // When collapsed, navigate to first child- if (item.children && item.children.length > 0) {- navigate(item.children[0].to);- }- } else {- toggleSection(item.label);- }- }}- className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${- collapsed ? 'lg:justify-center lg:px-2' : 'justify-between'- } ${- isSectionActive(item)- ? 'bg-port-accent/10 text-port-accent'- : 'text-gray-400 hover:text-white hover:bg-port-border/50'- }`}- title={collapsed ? item.label : undefined}- >- <div className="flex items-center gap-3">- <div className="relative">- <Icon size={20} className="shrink-0" />- {/* Badge for collapsed state on collapsible sections */}- {item.showBadge && unreadCount > 0 && collapsed && (- <span className="absolute -top-1.5 -right-1.5 min-w-[14px] h-[14px] flex items-center justify-center text-[9px] font-bold rounded-full bg-yellow-500 text-black px-0.5">- {unreadCount > 9 ? '9+' : unreadCount}- </span>- )}+ <div className={`flex items-stretch ${collapsed ? 'lg:justify-center' : ''}`}>+ <button+ type="button"+ onClick={navigateToSection}+ className={`flex-1 ${sectionRowClasses} ${collapsed ? 'lg:justify-center lg:px-2' : 'justify-between'}`}+ title={collapsed ? item.label : undefined}+ >+ <div className="flex items-center gap-3">+ <div className="relative">+ <Icon size={20} className="shrink-0" />+ {item.showBadge && unreadCount > 0 && collapsed && (+ <span className="absolute -top-1.5 -right-1.5 min-w-[14px] h-[14px] flex items-center justify-center text-[9px] font-bold rounded-full bg-yellow-500 text-black px-0.5">+ {unreadCount > 9 ? '9+' : unreadCount}+ </span>+ )}+ </div>+ <span className={`whitespace-nowrap ${collapsed ? 'lg:hidden' : ''}`}>+ {item.label}+ </span></div>- <span className={`whitespace-nowrap ${collapsed ? 'lg:hidden' : ''}`}>- {item.label}- </span>- </div>+ {!collapsed && item.showBadge && unreadCount > 0 && (+ <span className="min-w-[18px] h-[18px] flex items-center justify-center text-[10px] font-bold rounded-full bg-yellow-500 text-black px-1">+ {unreadCount > 9 ? '9+' : unreadCount}+ </span>+ )}+ </button>{!collapsed && (- <div className="flex items-center gap-2">- {/* Badge for expanded state on collapsible sections */}- {item.showBadge && unreadCount > 0 && (- <span className="min-w-[18px] h-[18px] flex items-center justify-center text-[10px] font-bold rounded-full bg-yellow-500 text-black px-1">- {unreadCount > 9 ? '9+' : unreadCount}- </span>- )}+ <button+ type="button"+ aria-label={expandedSections[item.label] ? `Collapse ${item.label}` : `Expand ${item.label}`}+ onClick={() => toggleSection(item.label)}+ className="px-2 text-gray-400 hover:text-white hover:bg-port-border/50 rounded-lg"+ >{expandedSections[item.label]? <ChevronDown size={16} />: <ChevronRight size={16} />}- </div>+ </button>)}- </button>+ </div>{/* Children items */}{expandedSections[item.label] && !collapsed && (diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsxnew file mode 100644index 0000000000..4b6225446e--- /dev/null+++ b/client/src/components/media/MediaCard.jsx@@ -0,0 +1,117 @@+import { Trash2, Download, Film, Image as ImageIcon, Sparkles } from 'lucide-react';++// Single card used everywhere a generated image/video appears in a grid:+// the Image Gen page's recent gallery, the Video Gen page's recent renders,+// and the Media History tab. Action visibility is opt-in — pass only the+// callbacks you want rendered. Image-only actions (remix, send-to-video) and+// video-only actions (continue) are auto-hidden when the kind doesn't match.+export default function MediaCard({+ item,+ onPreview,+ onClick, // overrides preview when set (e.g. stitch mode toggling selection)+ onRemix,+ onSendToVideo,+ onContinue,+ onDelete,+ selectionLabel = null, // e.g. "1", "2" — shown as the stitch order badge+ selected = false,+ disabled = false,+ hideActions = false,+}) {+ const { kind, prompt, modelId, previewUrl, downloadUrl } = item;+ const isVideo = kind === 'video';+ const handleTileClick = onClick || (() => onPreview?.(item));++ return (+ <div className={`bg-port-card border rounded-xl overflow-hidden ${selected ? 'border-port-accent' : 'border-port-border'}`}>+ <button+ type="button"+ onClick={() => handleTileClick(item)}+ disabled={disabled}+ className="block w-full aspect-square bg-port-bg relative disabled:cursor-not-allowed disabled:opacity-40"+ >+ {previewUrl ? (+ <img src={previewUrl} alt={prompt} className="w-full h-full object-cover" loading="lazy" />+ ) : (+ <div className="w-full h-full flex items-center justify-center text-gray-600">+ {isVideo ? <Film className="w-10 h-10" /> : <ImageIcon className="w-10 h-10" />}+ </div>+ )}+ <span className="absolute bottom-1 right-1 text-[9px] px-1.5 py-0.5 bg-black/70 text-white rounded uppercase tracking-wide">+ {isVideo ? 'Video' : 'Image'}+ </span>+ {selectionLabel != null && (+ <div className="absolute top-1.5 left-1.5 w-5 h-5 rounded-full bg-port-accent text-white text-[10px] font-bold flex items-center justify-center">+ {selectionLabel}+ </div>+ )}+ {item.stitchedFrom && (+ <span className="absolute top-1.5 right-1.5 text-[9px] px-1 py-0.5 bg-port-success/80 text-white rounded">stitched</span>+ )}+ </button>+ <div className="p-2 space-y-1.5">+ <p className="text-[11px] text-gray-300 line-clamp-2" title={prompt}>{prompt}</p>+ <div className="flex flex-wrap gap-1 text-[9px]">+ {modelId && <span className="px-1.5 py-0.5 bg-port-accent/20 text-port-accent rounded">{modelId}</span>}+ {item.width && <span className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded">{item.width}×{item.height}</span>}+ {item.steps && <span className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded">{item.steps}st</span>}+ {item.numFrames && <span className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded">{item.numFrames}f</span>}+ {item.fps && <span className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded">{item.fps}fps</span>}+ {item.seed != null && <span className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded">seed {item.seed}</span>}+ </div>+ {!hideActions && (+ <div className="flex gap-1">+ {!isVideo && onRemix && (+ <button+ type="button"+ onClick={() => onRemix(item)}+ className="flex-1 px-1.5 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded flex items-center justify-center gap-1"+ title="Reuse settings"+ >+ <Sparkles className="w-3 h-3" /> Remix+ </button>+ )}+ {!isVideo && onSendToVideo && (+ <button+ type="button"+ onClick={() => onSendToVideo(item)}+ className="flex-1 px-1.5 py-1 bg-port-success/20 hover:bg-port-success/40 text-port-success text-[10px] rounded flex items-center justify-center"+ title="Send to Video"+ >+ <Film className="w-3 h-3" />+ </button>+ )}+ {isVideo && onContinue && (+ <button+ type="button"+ onClick={() => onContinue(item)}+ className="flex-1 px-1.5 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded flex items-center justify-center gap-1"+ title="Use last frame as Image Gen source"+ >+ <ImageIcon className="w-3 h-3" /> Continue+ </button>+ )}+ <a+ href={downloadUrl}+ download+ className="px-1.5 py-1 bg-port-border hover:bg-port-border/70 text-white text-[10px] rounded flex items-center justify-center"+ title="Download"+ >+ <Download className="w-3 h-3" />+ </a>+ {onDelete && (+ <button+ type="button"+ onClick={() => onDelete(item)}+ className="px-1.5 py-1 bg-port-error/20 hover:bg-port-error/40 text-port-error text-[10px] rounded flex items-center justify-center"+ title="Delete"+ >+ <Trash2 className="w-3 h-3" />+ </button>+ )}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxnew file mode 100644index 0000000000..c466c9c51d--- /dev/null+++ b/client/src/components/media/MediaLightbox.jsx@@ -0,0 +1,164 @@+import { useEffect } from 'react';+import { X, Copy, Sparkles, Film, Image as ImageIcon, Download } from 'lucide-react';+import toast from '../ui/Toast';++// Full-screen preview for a normalized media item (image or video). Shows the+// media on the left, all generation settings on the right with copy buttons+// for the prompts, plus contextual actions (Remix, Send to Video, Continue+// from last frame). Esc + backdrop click close. Caller wires action handlers.+export default function MediaLightbox({ item, onClose, onRemix, onSendToVideo, onContinue }) {+ useEffect(() => {+ if (!item) return;+ const onKey = (e) => { if (e.key === 'Escape') onClose(); };+ window.addEventListener('keydown', onKey);+ const prev = document.body.style.overflow;+ document.body.style.overflow = 'hidden';+ return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };+ }, [item, onClose]);++ if (!item) return null;+ const isVideo = item.kind === 'video';++ const copy = (text, label = 'Prompt') => {+ if (!text) return;+ if (!navigator.clipboard?.writeText) { toast.error('Clipboard unavailable on insecure context'); return; }+ navigator.clipboard.writeText(text).then(+ () => toast.success(`${label} copied`),+ () => toast.error('Copy failed')+ );+ };++ const meta = [+ ['Model', item.modelId],+ ['Resolution', item.width && item.height ? `${item.width}×${item.height}` : null],+ ['Steps', item.steps],+ ['Guidance', item.guidance],+ ['CFG', item.raw?.cfgScale ?? item.raw?.cfg_scale],+ ['Quantize', item.quantize],+ ['Seed', item.seed],+ ['Frames', item.numFrames],+ ['FPS', item.fps],+ ['Created', item.createdAt && new Date(item.createdAt).toLocaleString()],+ ].filter(([, v]) => v != null && v !== '');++ return (+ <div+ role="presentation"+ className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4"+ onClick={onClose}+ onKeyDown={(e) => e.key === 'Escape' && onClose()}+ >+ <div+ className="relative bg-port-card border border-port-border rounded-xl overflow-hidden max-w-6xl w-full max-h-[92vh] flex flex-col md:flex-row"+ onClick={(e) => e.stopPropagation()}+ role="presentation"+ >+ <div className="flex-1 bg-black flex items-center justify-center min-h-0">+ {isVideo ? (+ <video src={item.downloadUrl} controls autoPlay loop className="max-w-full max-h-[92vh]" />+ ) : (+ <img src={item.previewUrl} alt={item.prompt} className="max-w-full max-h-[92vh] object-contain" />+ )}+ </div>++ <aside className="md:w-80 lg:w-96 shrink-0 flex flex-col border-t md:border-t-0 md:border-l border-port-border max-h-[40vh] md:max-h-[92vh]">+ <header className="flex items-center justify-between p-3 border-b border-port-border">+ <span className="text-xs uppercase tracking-wide text-gray-400">{isVideo ? 'Video' : 'Image'} settings</span>+ <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-3 space-y-3 text-xs">+ {item.prompt && (+ <div>+ <div className="flex items-center justify-between mb-1">+ <span className="text-gray-500 uppercase tracking-wide">Prompt</span>+ <button+ type="button"+ onClick={() => copy(item.prompt, 'Prompt')}+ className="p-1 rounded text-gray-400 hover:text-white hover:bg-port-border/50"+ title="Copy prompt"+ >+ <Copy className="w-3 h-3" />+ </button>+ </div>+ <p className="text-gray-200 whitespace-pre-wrap">{item.prompt}</p>+ </div>+ )}++ {item.negativePrompt && (+ <div>+ <div className="flex items-center justify-between mb-1">+ <span className="text-gray-500 uppercase tracking-wide">Negative</span>+ <button+ type="button"+ onClick={() => copy(item.negativePrompt, 'Negative prompt')}+ className="p-1 rounded text-gray-400 hover:text-white hover:bg-port-border/50"+ title="Copy negative prompt"+ >+ <Copy className="w-3 h-3" />+ </button>+ </div>+ <p className="text-gray-300 whitespace-pre-wrap">{item.negativePrompt}</p>+ </div>+ )}++ {meta.length > 0 && (+ <dl className="grid grid-cols-[auto,1fr] gap-x-3 gap-y-1">+ {meta.map(([k, v]) => (+ <div key={k} className="contents">+ <dt className="text-gray-500">{k}</dt>+ <dd className="text-gray-200 break-all">{String(v)}</dd>+ </div>+ ))}+ </dl>+ )}+ </div>++ <footer className="flex flex-wrap gap-1.5 p-3 border-t border-port-border">+ {!isVideo && onRemix && (+ <button+ type="button"+ onClick={() => { onRemix(item); onClose(); }}+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs bg-port-accent/20 hover:bg-port-accent/40 text-port-accent rounded"+ >+ <Sparkles className="w-3.5 h-3.5" /> Remix+ </button>+ )}+ {!isVideo && onSendToVideo && (+ <button+ type="button"+ onClick={() => { onSendToVideo(item); onClose(); }}+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs bg-port-success/20 hover:bg-port-success/40 text-port-success rounded"+ >+ <Film className="w-3.5 h-3.5" /> Send to Video+ </button>+ )}+ {isVideo && onContinue && (+ <button+ type="button"+ onClick={() => { onContinue(item); onClose(); }}+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs bg-port-accent/20 hover:bg-port-accent/40 text-port-accent rounded"+ >+ <ImageIcon className="w-3.5 h-3.5" /> Continue+ </button>+ )}+ <a+ href={item.downloadUrl}+ download+ className="flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs bg-port-border hover:bg-port-border/70 text-white rounded"+ >+ <Download className="w-3.5 h-3.5" />+ </a>+ </footer>+ </aside>+ </div>+ </div>+ );+}diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.jsnew file mode 100644index 0000000000..7fede8e568--- /dev/null+++ b/client/src/components/media/normalize.js@@ -0,0 +1,42 @@+// Normalizes raw image-gallery / video-history records into a single shape+// consumed by <MediaCard>. Lets the same card render in any history grid.+export function normalizeImage(i) {+ return {+ kind: 'image',+ key: `image:${i.filename}`,+ filename: i.filename,+ previewUrl: i.path || `/data/images/${i.filename}`,+ downloadUrl: i.path || `/data/images/${i.filename}`,+ prompt: i.prompt || i.metadata?.prompt || '(no prompt)',+ negativePrompt: i.negativePrompt || i.negative_prompt || null,+ modelId: i.modelId || i.model || null,+ width: i.width,+ height: i.height,+ steps: i.steps,+ guidance: i.guidance,+ quantize: i.quantize,+ seed: i.seed,+ createdAt: i.createdAt,+ raw: i,+ };+}++export function normalizeVideo(v) {+ return {+ kind: 'video',+ key: `video:${v.id}`,+ id: v.id,+ filename: v.filename,+ previewUrl: v.thumbnail ? `/data/video-thumbnails/${v.thumbnail}` : null,+ downloadUrl: `/data/videos/${v.filename}`,+ prompt: v.prompt || '(no prompt)',+ modelId: v.modelId,+ width: v.width,+ height: v.height,+ numFrames: v.numFrames,+ fps: v.fps,+ stitchedFrom: v.stitchedFrom,+ createdAt: v.createdAt,+ raw: v,+ };+}diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxindex 6705599713..ed2588d859 100644--- a/client/src/components/settings/ImageGenTab.jsx+++ b/client/src/components/settings/ImageGenTab.jsx@@ -1,40 +1,66 @@-import { useState, useEffect, useCallback } from 'react';-import { Save, Image, Zap, Wrench, Wand2, Sparkles } from 'lucide-react';+/**+ * Image Gen Settings — mode picker (External SD API vs local mflux), per-mode+ * configuration, and the "expose A1111 API on the tailnet" toggle so other+ * machines can use this PortOS as their image/video backend.+ */++import { useState, useEffect, useCallback, useRef } from 'react';+import {+ Save, Image as ImageIcon, Zap, Wrench, Cloud, Cpu, Globe, AlertTriangle,+ Sparkles+} from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';-import { useImageGenProgress } from '../../hooks/useImageGenProgress';+import LocalSetupPanel from './LocalSetupPanel';import {getSettings, updateSettings, getImageGenStatus, generateImage,- registerTool, updateTool, getToolsList+ registerTool, updateTool, getToolsList,} from '../../services/api';const SDAPI_TOOL_ID = 'sdapi';const DEFAULT_TEST_PROMPT = 'a small cyberpunk fox sitting on a neon-lit rooftop at night, cinematic, highly detailed';-const normalizeUrl = (url) => (url || '').trim().replace(/\/+$/, '');export function ImageGenTab() {const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);++ // Mode + per-mode config+ const [mode, setMode] = useState('external');const [sdapiUrl, setSdapiUrl] = useState('');- const [savedUrl, setSavedUrl] = useState('');+ const [pythonPath, setPythonPath] = useState('');+ const [exposeA1111, setExposeA1111] = useState(false);++ // Snapshot of saved values so we can show the "dirty" state+ const [saved, setSaved] = useState({ mode: 'external', sdapiUrl: '', pythonPath: '', exposeA1111: false });+const [status, setStatus] = useState(null);const [checking, setChecking] = useState(false);const [toolRegistered, setToolRegistered] = useState(false);const [testPrompt, setTestPrompt] = useState(DEFAULT_TEST_PROMPT);- const [testNegativePrompt, setTestNegativePrompt] = useState('');const [rendering, setRendering] = useState(false);const [renderResult, setRenderResult] = useState(null);- const { progress: renderProgress, begin: beginRender, end: endRender } = useImageGenProgress();+ const renderEsRef = useRef(null);++ // Close any in-flight test-render SSE on unmount so we don't fire setState+ // on a torn-down component if the user navigates away mid-render.+ useEffect(() => () => renderEsRef.current?.close(), []);useEffect(() => {Promise.all([getSettings(), getToolsList()])- .then(([settings, tools]) => {- const url = normalizeUrl(settings?.imageGen?.sdapiUrl);+ .then(([s, tools]) => {+ const ig = s?.imageGen || {};+ const m = ig.mode || 'external';+ const url = normalizeUrl(ig.external?.sdapiUrl || ig.sdapiUrl);+ const py = ig.local?.pythonPath || '';+ const expose = ig.expose?.a1111 === true;+ setMode(m);setSdapiUrl(url);- setSavedUrl(url);- setToolRegistered(tools.some(t => t.id === SDAPI_TOOL_ID));+ setPythonPath(py);+ setExposeA1111(expose);+ setSaved({ mode: m, sdapiUrl: url, pythonPath: py, exposeA1111: expose });+ setToolRegistered(tools.some((t) => t.id === SDAPI_TOOL_ID));}).catch(() => toast.error('Failed to load image gen settings')).finally(() => setLoading(false));@@ -48,13 +74,28 @@ export function ImageGenTab() {.finally(() => setChecking(false));}, []);+ const isDirty = mode !== saved.mode+ || normalizeUrl(sdapiUrl) !== saved.sdapiUrl+ || pythonPath !== saved.pythonPath+ || exposeA1111 !== saved.exposeA1111;+const handleSave = async () => {setSaving(true);const url = normalizeUrl(sdapiUrl) || undefined;-+ const patch = {+ imageGen: {+ mode,+ external: { sdapiUrl: url },+ local: { pythonPath: pythonPath || undefined },+ expose: { a1111: exposeA1111 },+ // Keep the legacy field populated so anything still reading+ // `imageGen.sdapiUrl` directly stays working.+ sdapiUrl: url,+ },+ };try {- await updateSettings({ imageGen: { sdapiUrl: url } });- setSavedUrl(url || '');+ await updateSettings(patch);+ setSaved({ mode, sdapiUrl: url || '', pythonPath, exposeA1111 });toast.success('Image gen settings saved');} catch (err) {toast.error(err.message || 'Failed to save settings');@@ -62,19 +103,20 @@ export function ImageGenTab() {return;}+ // Register/update CoS tool entry. The tool is "enabled" whenever the+ // active provider is configured (external URL set, or local Python set).+ const enabled = mode === 'external' ? !!url : !!pythonPath;const toolData = {- name: 'Stable Diffusion',+ name: mode === 'external' ? 'Stable Diffusion (External)' : 'Stable Diffusion (Local mflux)',category: 'image-generation',- description: 'Generate images via Stable Diffusion API (AUTOMATIC1111 / Forge WebUI)',- enabled: !!url,- config: { sdapiUrl: url },- promptHints: 'Use POST /api/image-gen/generate with { prompt, negativePrompt, width, height, steps, cfgScale }. Use POST /api/image-gen/avatar for character portraits.'+ description: 'Generate images via the active PortOS image gen backend',+ enabled,+ config: { mode, sdapiUrl: url, pythonPath },+ promptHints: 'Use POST /api/image-gen/generate with { prompt, negativePrompt, width, height, steps }. Use POST /api/image-gen/avatar for character portraits.',};if (toolRegistered) {- await updateTool(SDAPI_TOOL_ID, toolData).catch(err => {- toast.error(err.message || 'Failed to update CoS tools registry');- });- } else if (url) {+ await updateTool(SDAPI_TOOL_ID, toolData).catch((err) => toast.error(err.message || 'Failed to update CoS tools registry'));+ } else if (enabled) {try {await registerTool({ id: SDAPI_TOOL_ID, ...toolData });setToolRegistered(true);@@ -90,182 +132,246 @@ export function ImageGenTab() {if (!testPrompt.trim() || rendering) return;setRendering(true);setRenderResult(null);- beginRender();-try {- const result = await generateImage({- prompt: testPrompt.trim(),- negativePrompt: testNegativePrompt.trim() || undefined- });- setRenderResult(result);+ const result = await generateImage({ prompt: testPrompt.trim() });+ // Local mode returns immediately after spawning the Python child —+ // the PNG isn't on disk yet. Subscribe to the per-job SSE and only+ // mark the render complete on the `complete` event (or fail on+ // `error`). External mode awaits internally and the file is on disk+ // by the time generateImage resolves, so we can short-circuit.+ if (result?.mode === 'local' && result?.generationId) {+ await new Promise((resolve, reject) => {+ const es = new EventSource(`/api/image-gen/${result.generationId}/events`);+ renderEsRef.current = es;+ const closeEs = () => { es.close(); renderEsRef.current = null; };+ es.onmessage = (e) => {+ const msg = (() => { try { return JSON.parse(e.data); } catch { return null; } })();+ if (!msg) return;+ if (msg.type === 'complete') {+ closeEs();+ setRenderResult({ ...result, ...msg.result });+ resolve();+ } else if (msg.type === 'error') {+ closeEs();+ reject(new Error(msg.error || 'Generation failed'));+ }+ };+ es.onerror = () => { closeEs(); reject(new Error('Lost connection during test render')); };+ });+ } else {+ setRenderResult(result);+ }toast.success('Test render complete');} catch (err) {toast.error(err.message || 'Test render failed');} finally {setRendering(false);- endRender();}};if (loading) return <BrailleSpinner text="Loading image gen settings" />;- const isDirty = normalizeUrl(sdapiUrl) !== savedUrl;- const canRender = !!savedUrl && status?.connected !== false;- const progressPct = renderProgress?.progress != null ? Math.round(renderProgress.progress * 100) : null;+ // The advertised A1111 URL must be the canonical user-facing endpoint+ // (`<tailscale-host>.<tailnet>.ts.net:5555` / `<tailscale-ip>:5555`), not+ // the loopback HTTP mirror at :5553 or a localhost dev URL — those aren't+ // reachable from other tailnet machines.+ const advertisedA1111Url = (() => {+ if (typeof window === 'undefined') return null;+ const h = window.location.hostname;+ // Local dev / loopback mirror — we can't infer the tailnet hostname+ // from the browser; tell the user to look it up.+ if (h === 'localhost' || h === '127.0.0.1' || h === '::1') return null;+ // Real tailnet host — use the canonical user-facing port (:5555) and+ // match the currently-active scheme so the hint works in both HTTPS-on+ // (Tailscale cert provisioned) and HTTP-only PortOS deployments.+ const scheme = window.location.protocol === 'http:' ? 'http' : 'https';+ return `${scheme}://${h}:5555`;+ })();return (<div className="space-y-5">- <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">+ {/* Mode picker */}+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4"><div className="flex items-center gap-2 text-white">- <Image size={18} />- <h2 className="text-lg font-semibold">Stable Diffusion API</h2>+ <ImageIcon size={18} />+ <h2 className="text-lg font-semibold">Backend</h2></div>+ <p className="text-xs text-gray-500">+ PortOS can either talk to a remote AUTOMATIC1111 / Forge server or run image+ generation locally with mflux on this Mac. Pick whichever fits — you can also+ expose this PortOS as an A1111-compatible endpoint for other tailnet boxes.+ </p>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <button+ type="button"+ onClick={() => setMode('external')}+ className={`text-left p-4 rounded-lg border transition-colors ${mode === 'external' ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400 hover:bg-port-border/30 hover:text-white'}`}+ >+ <div className="flex items-center gap-2">+ <Cloud className="w-4 h-4" />+ <span className="font-medium text-sm">External SD API</span>+ </div>+ <p className="text-xs text-gray-500 mt-1">Forward to a remote AUTOMATIC1111 / Forge server (e.g. another tailnet box).</p>+ </button>+ <button+ type="button"+ onClick={() => setMode('local')}+ className={`text-left p-4 rounded-lg border transition-colors ${mode === 'local' ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400 hover:bg-port-border/30 hover:text-white'}`}+ >+ <div className="flex items-center gap-2">+ <Cpu className="w-4 h-4" />+ <span className="font-medium text-sm">Local (mflux)</span>+ </div>+ <p className="text-xs text-gray-500 mt-1">Run Flux + LTX models on this machine. Apple Silicon recommended.</p>+ </button>+ </div>+ </div>- <div className="space-y-1">- <label className="block text-sm text-gray-400">API URL</label>- <p className="text-xs text-gray-500 mb-1">- Base URL for AUTOMATIC1111 / Forge WebUI (e.g. http://localhost:7860)- </p>+ {/* External-mode config */}+ {mode === 'external' && (+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4">+ <h3 className="text-sm font-medium text-gray-300">External AUTOMATIC1111 / Forge URL</h3><inputtype="text"value={sdapiUrl}- onChange={e => setSdapiUrl(e.target.value)}+ onChange={(e) => setSdapiUrl(e.target.value)}className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"placeholder="http://localhost:7860"/>+ <p className="text-xs text-gray-500">Base URL for the SD WebUI server PortOS should send generation requests to.</p></div>+ )}- <div className="flex items-center gap-3">- <button- onClick={handleSave}- disabled={saving}- className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm rounded-lg transition-colors disabled:opacity-50 min-h-[40px]"- >- {saving ? <BrailleSpinner /> : <Save size={14} />}- Save- </button>-- <button- onClick={checkStatus}- disabled={checking || !sdapiUrl.trim() || isDirty}- className="flex items-center gap-2 px-4 py-2 bg-port-border hover:bg-port-border/70 text-white text-sm rounded-lg transition-colors disabled:opacity-50 min-h-[40px]"- title={isDirty ? 'Save settings first to test' : 'Test connection to SD API'}- >- {checking ? <BrailleSpinner /> : <Zap size={14} />}- Test Connection- </button>+ {/* Local-mode config */}+ {mode === 'local' && (+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4">+ <h3 className="text-sm font-medium text-gray-300">Local Python (mflux + mlx_video)</h3>+ <p className="text-xs text-gray-500">+ Pick a Python 3.10+ interpreter — PortOS auto-detects venvs and conda installs and can install+ missing packages directly. HF model weights stream into the standard <code>~/.cache/huggingface</code>+ and are surfaced in <a href="/media/models" className="text-port-accent hover:underline">Media → Models</a>.+ </p>+ <LocalSetupPanel pythonPath={pythonPath} onPythonPathChange={setPythonPath} /></div>+ )}+ {/* Save + status */}+ <div className="flex items-center gap-3">+ <button+ type="button"+ onClick={handleSave}+ disabled={saving || !isDirty}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm rounded-lg transition-colors disabled:opacity-50 min-h-[40px]"+ >+ {saving ? <BrailleSpinner /> : <Save size={14} />}+ Save+ </button>+ <button+ type="button"+ onClick={checkStatus}+ disabled={checking || isDirty}+ className="flex items-center gap-2 px-4 py-2 bg-port-border hover:bg-port-border/70 text-white text-sm rounded-lg transition-colors disabled:opacity-50 min-h-[40px]"+ title={isDirty ? 'Save settings first to test' : 'Probe the active backend'}+ >+ {checking ? <BrailleSpinner /> : <Zap size={14} />}+ Test Connection+ </button>{status && (- <div className={`flex items-center gap-2 text-sm ${status.connected ? 'text-port-success' : 'text-port-error'}`}>- <span className={`w-2 h-2 rounded-full ${status.connected ? 'bg-port-success' : 'bg-port-error'}`} />- {status.connected ? `Connected — model: ${status.model}` : status.reason || 'Not connected'}- </div>+ <span className={`text-sm ${status.connected ? 'text-port-success' : 'text-port-error'}`}>+ {status.connected+ ? `${status.mode} — ${status.model || status.pythonPath}`+ : status.reason || 'Not connected'}+ </span>)}-- <div className="border-t border-port-border pt-4 space-y-2">- <h3 className="text-sm font-medium text-gray-300">CoS Integration</h3>- <p className="text-xs text-gray-500">- When configured, this tool is registered with the CoS tools registry. Agents can use it to generate- images for briefings, character avatars, and other visual content. Images are stored in <code className="text-gray-400">./data/images/</code>.- </p>- {toolRegistered && (- <div className="flex items-center gap-2 text-xs text-port-success">- <Wrench size={12} />- Registered as CoS tool- </div>- )}- </div></div>+ {/* Tailnet expose */}<div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4"><div className="flex items-center gap-2 text-white">- <Wand2 size={18} />- <h2 className="text-lg font-semibold">Test Render</h2>+ <Globe size={18} />+ <h2 className="text-lg font-semibold">Expose as A1111 API on the Tailnet</h2></div><p className="text-xs text-gray-500">- Send a real prompt to your SD API to verify generation end-to-end. For a richer experience visit the <a href="/image-gen" className="text-port-accent hover:underline">Image Gen</a> page.+ When enabled, PortOS mounts an AUTOMATIC1111-compatible surface at+ <code className="text-gray-400"> /sdapi/v1/* </code> so other machines on your tailnet can point any A1111 client at this box and use whichever backend you picked above. Off by default — flip on only when you actually want to share this server.</p>-- <div className="space-y-1">- <label className="block text-xs font-medium text-gray-400">Prompt</label>- <textarea- value={testPrompt}- onChange={e => setTestPrompt(e.target.value)}- rows={2}- disabled={rendering}- className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y"- placeholder="Describe the image you want..."+ <label className="flex items-center gap-3 cursor-pointer">+ <input+ type="checkbox"+ checked={exposeA1111}+ onChange={(e) => setExposeA1111(e.target.checked)}+ className="rounded"/>- </div>+ <span className="text-sm text-gray-300">Enable <code className="text-gray-400">/sdapi/v1/*</code></span>+ </label>+ {exposeA1111 && (+ <div className="text-xs space-y-1 bg-port-bg border border-port-border rounded-lg p-3">+ <div className="flex items-center gap-1 text-port-warning">+ <AlertTriangle className="w-3 h-3" /> Anyone with tailnet access to this host can hit the API. PortOS does not authenticate.+ </div>+ <div className="text-gray-400">+ {advertisedA1111Url ? (+ <>Other machines should set their SD API URL to <code className="text-gray-300">{advertisedA1111Url}</code></>+ ) : (+ <>Other machines should set their SD API URL to <code className="text-gray-300">https://<your-tailscale-host>:5555</code> (run <code className="text-gray-300">tailscale status</code> on this machine to see the hostname).</>+ )}+ </div>+ </div>+ )}+ </div>- <div className="space-y-1">- <label className="block text-xs font-medium text-gray-400">Negative Prompt (optional)</label>- <textarea- value={testNegativePrompt}- onChange={e => setTestNegativePrompt(e.target.value)}- rows={2}- disabled={rendering}- className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y"- placeholder="What to avoid (uses sensible default if blank)..."- />+ {/* Test render */}+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4">+ <div className="flex items-center gap-2 text-white">+ <Sparkles size={18} />+ <h2 className="text-lg font-semibold">Test Render</h2></div>-+ <p className="text-xs text-gray-500">+ Send a prompt through the active backend to verify end-to-end. For richer controls, visit the+ <a href="/image-gen" className="text-port-accent hover:underline ml-1">Image Gen</a> page.+ </p>+ <textarea+ value={testPrompt}+ onChange={(e) => setTestPrompt(e.target.value)}+ rows={2}+ disabled={rendering}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y"+ placeholder="Describe the image you want..."+ /><button+ type="button"onClick={handleRenderTest}- disabled={rendering || !canRender || !testPrompt.trim()}+ disabled={rendering || isDirty || !testPrompt.trim()}className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm rounded-lg transition-colors disabled:opacity-50 min-h-[40px]"- title={!canRender ? 'Save settings and verify connection first' : 'Generate a test image'}+ title={isDirty ? 'Save settings first' : 'Generate a test image'}>{rendering ? <BrailleSpinner /> : <Sparkles size={14} />}{rendering ? 'Rendering...' : 'Render Test Image'}</button>-- {(rendering || renderResult) && (+ {renderResult && (<div className="border border-port-border rounded-lg overflow-hidden bg-port-bg">- <div className="aspect-square w-full max-w-md mx-auto relative">- {renderProgress?.currentImage ? (- <img- src={`data:image/png;base64,${renderProgress.currentImage}`}- alt="Diffusing..."- className="w-full h-full object-contain"- />- ) : renderResult ? (- <img- src={renderResult.path}- alt="Test render"- className="w-full h-full object-contain"- />- ) : (- <div className="w-full h-full flex items-center justify-center text-gray-500 text-sm">- Waiting for first preview...- </div>- )}- {rendering && progressPct != null && (- <div className="absolute bottom-0 left-0 right-0 h-1 bg-black/40">- <div className="h-full bg-port-accent transition-all" style={{ width: `${progressPct}%` }} />- </div>- )}+ <img+ src={renderResult.path}+ alt="Test render"+ className="w-full max-w-md mx-auto object-contain"+ />+ <div className="px-3 py-2 text-xs text-gray-400 flex items-center justify-between border-t border-port-border">+ <span className="truncate">Saved: {renderResult.filename}</span>+ <a href={renderResult.path} download className="text-port-accent hover:underline ml-2 shrink-0">Download</a></div>- {rendering && (- <div className="px-3 py-2 text-xs text-gray-400 flex items-center justify-between border-t border-port-border">- <span>- {renderProgress?.step != null && renderProgress?.totalSteps- ? `Step ${renderProgress.step}/${renderProgress.totalSteps}`- : 'Starting diffusion...'}- </span>- {progressPct != null && <span className="text-port-accent">{progressPct}%</span>}- </div>- )}- {!rendering && renderResult && (- <div className="px-3 py-2 text-xs text-gray-400 flex items-center justify-between border-t border-port-border">- <span className="truncate">Saved: {renderResult.filename}</span>- <a href={renderResult.path} download className="text-port-accent hover:underline ml-2 shrink-0">Download</a>- </div>- )}</div>)}</div>++ {/* CoS integration footer */}+ <div className="text-xs text-gray-500 px-1 flex items-center gap-2">+ {toolRegistered && (+ <>+ <Wrench className="w-3 h-3" />+ Registered as CoS tool — agents can use this backend for briefings, avatars, and visual content.+ </>+ )}+ </div></div>);}diff --git a/client/src/components/settings/LocalSetupPanel.jsx b/client/src/components/settings/LocalSetupPanel.jsxnew file mode 100644index 0000000000..537d3ff1a4--- /dev/null+++ b/client/src/components/settings/LocalSetupPanel.jsx@@ -0,0 +1,235 @@+import { useState, useEffect, useCallback, useRef } from 'react';+import { CheckCircle2, XCircle, Wand2, RefreshCw, Terminal, AlertTriangle, Box } from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';++export default function LocalSetupPanel({ pythonPath, onPythonPathChange }) {+ const [detecting, setDetecting] = useState(false);+ const [check, setCheck] = useState(null); // { required, installed, missing, missingPip }+ const [checking, setChecking] = useState(false);+ const [installing, setInstalling] = useState(false);+ const [installLog, setInstallLog] = useState([]);+ const [creatingVenv, setCreatingVenv] = useState(false);+ const logRef = useRef(null);+ const installEsRef = useRef(null);++ // Closing the install EventSource on unmount stops setInstalling /+ // setInstallLog calls firing on a torn-down component if the user+ // navigates away mid pip-install.+ useEffect(() => () => installEsRef.current?.close(), []);++ const refreshCheck = useCallback(async (path) => {+ if (!path) { setCheck(null); return; }+ setChecking(true);+ try {+ const res = await fetch(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(path)}`);+ if (!res.ok) { setCheck(null); return; }+ setCheck(await res.json());+ } catch {+ // Server down / offline — clear the check rather than getting stuck+ // in a perpetual "Checking…" state.+ setCheck(null);+ } finally {+ setChecking(false);+ }+ }, []);++ // Debounce typing in the path input so we don't spawn a python subprocess+ // per keystroke. Settled value triggers /setup/check.+ useEffect(() => {+ const t = setTimeout(() => refreshCheck(pythonPath), 400);+ return () => clearTimeout(t);+ }, [pythonPath, refreshCheck]);++ // Auto-scroll install log to bottom+ useEffect(() => {+ if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;+ }, [installLog]);++ const handleDetect = async () => {+ setDetecting(true);+ try {+ const res = await fetch('/api/image-gen/setup/python');+ if (!res.ok) { toast.error('Detection failed'); return; }+ const { path } = await res.json();+ if (path) {+ onPythonPathChange(path);+ toast.success(`Detected ${path}`);+ } else {+ toast.error('No Python 3 found on this system');+ }+ } catch {+ toast.error('Detection failed');+ } finally {+ // Always clear detecting state — without this, a fetch reject would+ // leave the button stuck disabled forever.+ setDetecting(false);+ }+ };++ const handleInstall = () => {+ if (!check?.missingPip?.length) return;+ setInstalling(true);+ setInstallLog([]);++ const url = `/api/image-gen/setup/install?pythonPath=${encodeURIComponent(pythonPath)}&packages=${encodeURIComponent(check.missingPip.join(','))}`;+ const es = new EventSource(url);+ installEsRef.current = es;++ es.onmessage = (e) => {+ const event = (() => { try { return JSON.parse(e.data); } catch { return null; } })();+ if (!event) return;+ setInstallLog(prev => [...prev.slice(-200), event]);+ if (event.type === 'complete') {+ es.close();+ installEsRef.current = null;+ setInstalling(false);+ toast.success('Packages installed');+ refreshCheck(pythonPath);+ } else if (event.type === 'error') {+ es.close();+ installEsRef.current = null;+ setInstalling(false);+ toast.error(event.message);+ refreshCheck(pythonPath);+ }+ };++ es.onerror = () => {+ es.close();+ installEsRef.current = null;+ setInstalling(false);+ };+ };++ const handleCreateVenv = async () => {+ setCreatingVenv(true);+ try {+ const res = await fetch('/api/image-gen/setup/create-venv', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({}),+ });+ if (!res.ok) {+ const json = await res.json().catch(() => ({}));+ toast.error(json.error || 'Venv creation failed');+ return;+ }+ const { pythonPath: venvPython } = await res.json();+ onPythonPathChange(venvPython);+ toast.success(`Created venv at ${venvPython}`);+ } catch {+ toast.error('Failed to create venv');+ } finally {+ // Always clear so a fetch reject doesn't leave the button disabled.+ setCreatingVenv(false);+ }+ };++ return (+ <div className="space-y-4">+ {/* Python path + detect */}+ <div className="flex items-center gap-2">+ <input+ type="text"+ value={pythonPath || ''}+ onChange={(e) => onPythonPathChange(e.target.value)}+ className="flex-1 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ placeholder="/usr/local/bin/python3"+ />+ <button+ type="button"+ onClick={handleDetect}+ disabled={detecting}+ className="flex items-center gap-2 px-3 py-2 text-sm text-gray-300 hover:text-white border border-port-border rounded-lg hover:bg-port-border/50 min-h-[40px] disabled:opacity-50"+ title="Auto-detect Python 3"+ >+ {detecting ? <BrailleSpinner /> : <Wand2 size={14} />} Detect+ </button>+ </div>++ {/* Required packages */}+ {pythonPath && (+ <div className="border border-port-border rounded-lg p-3 bg-port-bg/50">+ <div className="flex items-center justify-between mb-2">+ <h4 className="text-sm font-medium text-gray-300">Required packages</h4>+ <button+ type="button"+ onClick={() => refreshCheck(pythonPath)}+ disabled={checking}+ className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50 disabled:opacity-50"+ title="Re-check"+ >+ <RefreshCw size={14} className={checking ? 'animate-spin' : ''} />+ </button>+ </div>+ {!check ? (+ <p className="text-xs text-gray-500">{checking ? 'Checking…' : 'Set a Python path to check installed packages.'}</p>+ ) : (+ <>+ <ul className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs mb-3">+ {check.required.map(pkg => {+ const ok = check.installed.includes(pkg);+ return (+ <li key={pkg} className="flex items-center gap-2">+ {ok+ ? <CheckCircle2 size={14} className="text-port-success shrink-0" />+ : <XCircle size={14} className="text-port-error shrink-0" />}+ <code className={ok ? 'text-gray-300' : 'text-port-error'}>{pkg}</code>+ </li>+ );+ })}+ </ul>+ {check.externallyManaged && check.missing.length > 0 ? (+ <div className="space-y-2">+ <div className="flex items-start gap-2 text-xs text-port-warning bg-port-warning/10 border border-port-warning/30 rounded p-2">+ <AlertTriangle size={14} className="shrink-0 mt-0.5" />+ <div>+ This Python is <strong>externally managed</strong> (PEP 668) — pip can't install into it.+ Create a PortOS-owned venv to install packages safely without touching your system Python.+ </div>+ </div>+ <button+ type="button"+ onClick={handleCreateVenv}+ disabled={creatingVenv}+ className="flex items-center gap-2 px-3 py-2 text-sm bg-port-accent hover:bg-port-accent/80 text-white rounded-lg disabled:opacity-50 min-h-[40px]"+ >+ {creatingVenv ? <BrailleSpinner /> : <Box size={14} />}+ {creatingVenv ? 'Creating venv…' : 'Create PortOS venv'}+ </button>+ </div>+ ) : check.missing.length > 0 ? (+ <button+ type="button"+ onClick={handleInstall}+ disabled={installing}+ className="flex items-center gap-2 px-3 py-2 text-sm bg-port-accent hover:bg-port-accent/80 text-white rounded-lg disabled:opacity-50 min-h-[40px]"+ >+ {installing ? <BrailleSpinner /> : <Terminal size={14} />}+ {installing ? 'Installing…' : `Install ${check.missing.length} missing package${check.missing.length === 1 ? '' : 's'}`}+ </button>+ ) : (+ <p className="text-xs text-port-success flex items-center gap-2">+ <CheckCircle2 size={14} /> All required packages installed.+ </p>+ )}+ {(installing || installLog.length > 0) && (+ <pre+ ref={logRef}+ className="mt-3 max-h-48 overflow-y-auto text-[11px] font-mono text-gray-400 bg-black/40 border border-port-border rounded p-2 whitespace-pre-wrap"+ >+ {installLog.map((e, i) => (+ <div key={i} className={e.type === 'error' ? 'text-port-error' : e.type === 'complete' ? 'text-port-success' : ''}>+ {e.message}+ </div>+ ))}+ </pre>+ )}+ </>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/hooks/useImageGenProgress.js b/client/src/hooks/useImageGenProgress.jsindex db33ce44dc..7ffe926375 100644--- a/client/src/hooks/useImageGenProgress.js+++ b/client/src/hooks/useImageGenProgress.js@@ -72,5 +72,22 @@ export function useImageGenProgress() {setProgress(null);}, []);- return { progress, begin, end };+ // Resume tracking an in-flight job spawned before this hook mounted.+ // Seeds state from the server snapshot (last frame + step) so the user+ // sees current progress immediately after navigating back.+ const resume = useCallback((activeJob) => {+ if (!activeJob?.generationId) return;+ activeRef.current = true;+ generationIdRef.current = activeJob.generationId;+ setProgress({+ generationId: activeJob.generationId,+ progress: activeJob.progress ?? 0,+ step: activeJob.step ?? 0,+ totalSteps: activeJob.totalSteps ?? null,+ eta: activeJob.eta ?? null,+ currentImage: activeJob.currentImage ?? null,+ });+ }, []);++ return { progress, begin, end, resume };}diff --git a/client/src/lib/genUtils.js b/client/src/lib/genUtils.jsnew file mode 100644index 0000000000..e3a3e169b7--- /dev/null+++ b/client/src/lib/genUtils.js@@ -0,0 +1,12 @@+// Shared bits between Image Gen and Video Gen pages.++export const MAX_SEED = 0xFFFFFFFF;++export const randomSeed = () => String(Math.floor(Math.random() * MAX_SEED));++// SSE handlers receive bare strings from EventSource; partial frames or+// keep-alive pings would crash the page if we threw on parse.+export const safeParseJSON = (s) => {+ if (typeof s !== 'string' || !s.startsWith('{')) return null;+ try { return JSON.parse(s); } catch { return null; }+};diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex a70009988e..11676fbbf9 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -1,53 +1,90 @@-import { useState, useEffect, useCallback } from 'react';-import { Image as ImageIcon, Sparkles, Download, RefreshCw, Settings as SettingsIcon, Dice5, Copy, AlertTriangle } from 'lucide-react';-import { Link } from 'react-router-dom';+/**+ * Image Generation page.+ *+ * Works against either an external SD API (default) or PortOS's local mflux+ * backend, picked in Settings → Image Gen. The external mode uses the+ * /api/image-gen/generate JSON endpoint; the local mode kicks off a job and+ * subscribes to /api/image-gen/:jobId/events SSE for streaming progress and+ * additional knobs (model picker, LoRAs, quantization).+ */++import { useState, useEffect, useCallback, useRef } from 'react';+import { useNavigate, useSearchParams, Link } from 'react-router-dom';+import Drawer from '../components/Drawer';+import { ImageGenTab } from '../components/settings/ImageGenTab';+import MediaCard from '../components/media/MediaCard';+import MediaLightbox from '../components/media/MediaLightbox';+import { normalizeImage } from '../components/media/normalize';+import {+ Image as ImageIcon, Sparkles, Download, RefreshCw, Settings as SettingsIcon,+ Dice5, AlertTriangle, X, Film+} from 'lucide-react';import toast from '../components/ui/Toast';import BrailleSpinner from '../components/BrailleSpinner';import { useImageGenProgress } from '../hooks/useImageGenProgress';-import { generateImage, getImageGenStatus } from '../services/api';+import {+ getImageGenStatus, generateImage, listImageModels, listLoras, listImageGallery,+ cancelImageGen, deleteImage, getActiveImageJob,+} from '../services/api';+import { randomSeed, safeParseJSON } from '../lib/genUtils';const RESOLUTIONS = [- { label: '512×512 (square)', w: 512, h: 512 },- { label: '768×512 (landscape)', w: 768, h: 512 },- { label: '512×768 (portrait)', w: 512, h: 768 },+ { label: '512×512', w: 512, h: 512 },+ { label: '768×512', w: 768, h: 512 },+ { label: '512×768', w: 512, h: 768 },+ { label: '768×768', w: 768, h: 768 },+ { label: '1024×1024', w: 1024, h: 1024 },{ label: '832×1216 (Flux portrait)', w: 832, h: 1216 },- { label: '1024×1024 (HD square)', w: 1024, h: 1024 },- { label: '1216×832 (Flux landscape)', w: 1216, h: 832 }+ { label: '1216×832 (Flux landscape)', w: 1216, h: 832 },+ { label: '1024×576 (16:9)', w: 1024, h: 576 },+ { label: '576×1024 (9:16)', w: 576, h: 1024 },];const DEFAULT_NEGATIVE = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';-const HISTORY_KEY = 'portos-image-gen-history';-const MAX_HISTORY = 24;-const MAX_SEED = 0xFFFFFFFF;--function loadHistory() {- const raw = localStorage.getItem(HISTORY_KEY);- if (!raw) return [];- const parsed = JSON.parse(raw);- return Array.isArray(parsed) ? parsed : [];-}--function saveHistory(items) {- localStorage.setItem(HISTORY_KEY, JSON.stringify(items.slice(0, MAX_HISTORY)));-}export default function ImageGen() {+ const navigate = useNavigate();+ const [searchParams, setSearchParams] = useSearchParams();+ const settingsOpen = searchParams.get('settings') === '1';+ const openSettings = () => setSearchParams(prev => { const n = new URLSearchParams(prev); n.set('settings', '1'); return n; });+ const closeSettings = () => setSearchParams(prev => { const n = new URLSearchParams(prev); n.delete('settings'); return n; });+ const [status, setStatus] = useState(null);+ const [statusLoading, setStatusLoading] = useState(true);+ const [models, setModels] = useState([]);+ const [availableLoras, setAvailableLoras] = useState([]);+ const [gallery, setGallery] = useState([]);+ const [preview, setPreview] = useState(null);+const [prompt, setPrompt] = useState('');const [negativePrompt, setNegativePrompt] = useState(DEFAULT_NEGATIVE);- const [width, setWidth] = useState(768);- const [height, setHeight] = useState(512);- const [steps, setSteps] = useState(25);+ const [modelId, setModelId] = useState('');+ const [width, setWidth] = useState(1024);+ const [height, setHeight] = useState(1024);+ const [steps, setSteps] = useState('');+ const [guidance, setGuidance] = useState('');const [cfgScale, setCfgScale] = useState(7);+ const [quantize, setQuantize] = useState('8');const [seed, setSeed] = useState('');+ const [selectedLoras, setSelectedLoras] = useState([]);const [generating, setGenerating] = useState(false);+ const [statusMsg, setStatusMsg] = useState('');+ const [localProgress, setLocalProgress] = useState(null); // local mode SSE-driven 0..1const [result, setResult] = useState(null);- const [history, setHistory] = useState(() => loadHistory());-- const [status, setStatus] = useState(null);- const [statusLoading, setStatusLoading] = useState(true);-- const { progress, begin: beginGenerate, end: endGenerate } = useImageGenProgress();+ const [error, setError] = useState(null);+ const eventSourceRef = useRef(null);++ // External-mode socket-driven progress (kept for backward compat with+ // existing AUTOMATIC1111 wiring; the local mode also feeds the same hook+ // via imageGenEvents so the same UI bits light up).+ const { progress: externalProgress, begin: beginGenerate, end: endGenerate, resume: resumeGenerate } = useImageGenProgress();++ const isLocalMode = status?.mode === 'local';+ // Prefer the socket-driven hook (carries currentImage for both modes since+ // local mflux now writes stepwise frames). Fall back to the local SSE's+ // simpler progress shape if the hook hasn't received its first event yet.+ const progress = externalProgress || localProgress;+ const progressPct = progress?.progress != null ? Math.round(progress.progress * 100) : null;const refreshStatus = useCallback(() => {setStatusLoading(true);@@ -57,128 +94,250 @@ export default function ImageGen() {.finally(() => setStatusLoading(false));}, []);- useEffect(() => { refreshStatus(); }, [refreshStatus]);+ const refreshGallery = useCallback(() => {+ listImageGallery().then(setGallery).catch(() => {});+ }, []);++ useEffect(() => {+ refreshStatus();+ listImageModels().then((m) => {+ setModels(m);+ if (m.length && !modelId) setModelId(m[0].id);+ }).catch(() => {});+ listLoras().then(setAvailableLoras).catch(() => {});+ refreshGallery();+ // Resume an in-flight job so the user can navigate away mid-render and+ // come back to the same prompt + settings + live preview frame.+ getActiveImageJob().then(({ activeJob }) => {+ if (!activeJob) return;+ if (activeJob.prompt) setPrompt(activeJob.prompt);+ if (activeJob.negativePrompt != null) setNegativePrompt(activeJob.negativePrompt);+ if (activeJob.modelId) setModelId(activeJob.modelId);+ if (activeJob.width) setWidth(activeJob.width);+ if (activeJob.height) setHeight(activeJob.height);+ if (activeJob.steps != null) setSteps(activeJob.steps);+ if (activeJob.guidance != null) setGuidance(activeJob.guidance);+ if (activeJob.seed != null) setSeed(activeJob.seed);+ if (activeJob.quantize != null) setQuantize(String(activeJob.quantize));+ setGenerating(true);+ setStatusMsg('Resuming…');+ resumeGenerate(activeJob);+ // Re-attach the per-job SSE so raw status text resumes too.+ const es = new EventSource(`/api/image-gen/${activeJob.generationId}/events`);+ eventSourceRef.current = es;+ es.onmessage = (e) => {+ const msg = safeParseJSON(e.data);+ if (!msg) return;+ if (msg.type === 'status') setStatusMsg(msg.message);+ if (msg.type === 'progress') setLocalProgress({ progress: msg.progress });+ if (msg.type === 'complete' || msg.type === 'error') {+ setGenerating(false);+ es.close();+ }+ };+ }).catch(() => {});+ return () => eventSourceRef.current?.close();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const currentModel = models.find((m) => m.id === modelId);+ const matchedResolution = RESOLUTIONS.find((r) => r.w === width && r.h === height);+ const resolutionLabel = matchedResolution?.label || `${width}×${height}`;const handleResolutionChange = (e) => {- const r = RESOLUTIONS.find(r => r.label === e.target.value);+ const r = RESOLUTIONS.find((r) => r.label === e.target.value);if (r) { setWidth(r.w); setHeight(r.h); }};- const handleRandomSeed = () => {- setSeed(String(Math.floor(Math.random() * MAX_SEED)));+ const handleRandomSeed = () => setSeed(randomSeed());++ const startLocalGeneration = async () => {+ setLocalProgress({ progress: 0 });+ const payload = {+ prompt: prompt.trim(),+ negativePrompt: negativePrompt.trim() || undefined,+ modelId: modelId || undefined,+ width, height,+ steps: steps ? Number(steps) : undefined,+ guidance: guidance ? Number(guidance) : undefined,+ seed: seed && Number(seed) >= 0 ? Number(seed) : undefined,+ quantize,+ loraFilenames: selectedLoras.map((l) => l.filename),+ loraScales: selectedLoras.map((l) => l.scale),+ };+ const data = await generateImage(payload);++ return new Promise((resolve, reject) => {+ const jobId = data.jobId || data.generationId;+ const es = new EventSource(`/api/image-gen/${jobId}/events`);+ eventSourceRef.current = es;++ es.onmessage = (ev) => {+ const msg = safeParseJSON(ev.data);+ if (!msg) return;+ if (msg.type === 'status') setStatusMsg(msg.message);+ if (msg.type === 'progress') {+ setLocalProgress({ progress: msg.progress });+ setStatusMsg(msg.message);+ }+ if (msg.type === 'complete') {+ setResult({+ ...data,+ ...msg.result,+ prompt: payload.prompt,+ negativePrompt: payload.negativePrompt,+ width, height,+ steps: payload.steps ?? currentModel?.steps,+ guidance: payload.guidance ?? currentModel?.guidance,+ });+ es.close();+ resolve(msg.result);+ }+ if (msg.type === 'error') {+ es.close();+ reject(new Error(msg.error));+ }+ };+ es.onerror = () => {+ es.close();+ reject(new Error('Lost connection to server'));+ };+ });};const handleGenerate = async (e) => {e?.preventDefault?.();if (!prompt.trim() || generating) return;-setGenerating(true);+ setStatusMsg('Starting...');+ setError(null);setResult(null);+ // Both modes go through the socket-driven progress hook now — local mflux+ // emits stepwise frames via the imageGenEvents bus the same way external+ // SD API does, so the same hook drives the live preview for both.beginGenerate();- const payload = {- prompt: prompt.trim(),- negativePrompt: negativePrompt.trim() || undefined,- width,- height,- steps,- cfgScale- };- if (seed && Number(seed) >= 0) payload.seed = Number(seed);-try {- const data = await generateImage(payload);- const entry = {- id: data.generationId || data.filename,- filename: data.filename,- path: data.path,- prompt: payload.prompt,- negativePrompt: payload.negativePrompt || '',- width, height, steps, cfgScale,- seed: payload.seed ?? null,- createdAt: Date.now()- };- setResult(entry);- setHistory(prev => {- const next = [entry, ...prev.filter(h => h.id !== entry.id)].slice(0, MAX_HISTORY);- saveHistory(next);- return next;- });+ if (isLocalMode) {+ await startLocalGeneration();+ } else {+ const payload = {+ prompt: prompt.trim(),+ negativePrompt: negativePrompt.trim() || undefined,+ width, height,+ steps: steps ? Number(steps) : 25,+ cfgScale,+ };+ if (seed && Number(seed) >= 0) payload.seed = Number(seed);+ const data = await generateImage(payload);+ setResult({ ...data, prompt: payload.prompt, negativePrompt: payload.negativePrompt, width, height, steps: payload.steps, cfgScale });+ }toast.success('Image generated');+ refreshGallery();} catch (err) {+ setError(err.message || 'Image generation failed');toast.error(err.message || 'Image generation failed');} finally {setGenerating(false);+ setLocalProgress(null);endGenerate();}};- const handleReusePrompt = (entry) => {- setPrompt(entry.prompt);- setNegativePrompt(entry.negativePrompt || DEFAULT_NEGATIVE);- setWidth(entry.width);- setHeight(entry.height);- setSteps(entry.steps);- setCfgScale(entry.cfgScale);- setSeed(entry.seed != null ? String(entry.seed) : '');- toast.success('Settings copied to form');+ const handleCancel = async () => {+ eventSourceRef.current?.close();+ await cancelImageGen().catch(() => {});+ setGenerating(false);+ setStatusMsg('Cancelled');};- const handleClearHistory = () => {- setHistory([]);- saveHistory([]);+ const handleDelete = async (filename) => {+ await deleteImage(filename).catch(() => {});+ setGallery((g) => g.filter((img) => img.filename !== filename));+ };++ const sendToVideo = (filename) => {+ navigate(`/video-gen?sourceImageFile=${encodeURIComponent(filename)}`);+ };++ const handleRemix = (img) => {+ if (img.prompt) setPrompt(img.prompt);+ if (img.negativePrompt || img.negative_prompt) setNegativePrompt(img.negativePrompt || img.negative_prompt);+ if (img.seed != null) setSeed(String(img.seed));+ if (img.steps) setSteps(String(img.steps));+ if (img.guidance != null) setGuidance(String(img.guidance));+ if (img.quantize) setQuantize(String(img.quantize));+ if (img.width) setWidth(img.width);+ if (img.height) setHeight(img.height);+ if (img.modelId && models.some((m) => m.id === img.modelId)) setModelId(img.modelId);++ // Restore LoRAs from the new `loraFilenames` field; fall back to the+ // legacy `loraPaths` (absolute server paths) for older sidecar metadata+ // — extract the basename so the lookup against `availableLoras` works.+ const sidecarFilenames = img.loraFilenames?.length+ ? img.loraFilenames+ : (img.loraPaths || []).map((p) => p.split(/[\\/]/).pop());+ if (sidecarFilenames.length) {+ const restored = sidecarFilenames.map((fn, i) => {+ const match = availableLoras.find((l) => l.filename === fn);+ return match ? { filename: match.filename, name: match.name, scale: img.loraScales?.[i] ?? 1.0 } : null;+ }).filter(Boolean);+ setSelectedLoras(restored);+ }+ window.scrollTo({ top: 0, behavior: 'smooth' });};- const progressPct = progress?.progress != null ? Math.round(progress.progress * 100) : null;- const matchedResolution = RESOLUTIONS.find(r => r.w === width && r.h === height);- const resolutionLabel = matchedResolution?.label || `${width}×${height}`;const notConnected = status && status.connected === false;return (<div className="space-y-6">- <div className="flex items-center justify-between">- <div className="flex items-center gap-3">- <ImageIcon className="w-6 h-6 text-port-accent" />- <h1 className="text-2xl font-bold text-white">Image Gen</h1>- </div>- <div className="flex items-center gap-2">+ <div className="flex items-center justify-between gap-2 text-xs">+ {status ? (+ <span className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-full border ${+ status.connected+ ? 'border-port-success/40 bg-port-success/10 text-port-success'+ : 'border-port-error/40 bg-port-error/10 text-port-error'+ }`}>+ {status.connected ? (+ <><span className="w-2 h-2 rounded-full bg-port-success" /> {status.model || (status.mode === 'local' ? 'mflux/local' : 'external SD API')}</>+ ) : (+ <>+ <AlertTriangle className="w-3 h-3" />+ {status.reason || 'Not connected'} —+ <button type="button" onClick={openSettings} className="underline">Settings</button>+ </>+ )}+ </span>+ ) : (+ <span className="text-gray-500">Checking…</span>+ )}+ <div className="flex items-center gap-1"><buttononClick={refreshStatus}disabled={statusLoading}- className="p-2 rounded-lg text-gray-400 hover:text-white hover:bg-port-border/50 disabled:opacity-50 min-h-[40px] min-w-[40px] flex items-center justify-center"- title="Refresh API status"+ className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50 disabled:opacity-50"+ title="Refresh status">- <RefreshCw className={`w-4 h-4 ${statusLoading ? 'animate-spin' : ''}`} />+ <RefreshCw className={`w-3.5 h-3.5 ${statusLoading ? 'animate-spin' : ''}`} /></button>- <Link- to="/settings/image-gen"- className="flex items-center gap-2 px-3 py-2 text-sm text-gray-300 hover:text-white border border-port-border rounded-lg hover:bg-port-border/50 min-h-[40px]"+ <button+ type="button"+ onClick={openSettings}+ className="flex items-center gap-1.5 px-2 py-1 text-gray-300 hover:text-white border border-port-border rounded hover:bg-port-border/50"+ title="Image Gen settings">- <SettingsIcon className="w-4 h-4" /> Settings- </Link>+ <SettingsIcon className="w-3.5 h-3.5" /> Settings+ </button></div></div>- {status && (- <div className={`flex items-center gap-2 text-sm px-3 py-2 rounded-lg border ${- status.connected- ? 'border-port-success/40 bg-port-success/10 text-port-success'- : 'border-port-error/40 bg-port-error/10 text-port-error'- }`}>- {status.connected- ? <><span className="w-2 h-2 rounded-full bg-port-success" /> Connected — model: {status.model}</>- : <><AlertTriangle className="w-4 h-4" /> {status.reason || 'Not connected'} — configure in <Link to="/settings/image-gen" className="underline">Settings</Link></>- }- </div>- )}-- <div className="grid grid-cols-1 lg:grid-cols-[1fr,1.2fr] gap-6">- <form onSubmit={handleGenerate} className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">+ <form onSubmit={handleGenerate} className="grid grid-cols-1 lg:grid-cols-[1fr,1.2fr] gap-6">+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4"><div><label className="block text-sm font-medium text-gray-300 mb-1">Prompt</label><textareavalue={prompt}- onChange={e => setPrompt(e.target.value)}+ onChange={(e) => setPrompt(e.target.value)}rows={4}disabled={generating}className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y"@@ -190,15 +349,29 @@ export default function ImageGen() {<label className="block text-sm font-medium text-gray-300 mb-1">Negative Prompt</label><textareavalue={negativePrompt}- onChange={e => setNegativePrompt(e.target.value)}- rows={3}+ onChange={(e) => setNegativePrompt(e.target.value)}+ rows={2}disabled={generating}className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y"placeholder="What to avoid..."/></div>- <div className="grid grid-cols-2 gap-3">+ <div className="grid grid-cols-2 md:grid-cols-3 gap-3">+ {isLocalMode && models.length > 0 && (+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">Model</label>+ <select+ value={modelId}+ onChange={(e) => { setModelId(e.target.value); setSteps(''); setGuidance(''); }}+ disabled={generating}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ >+ {models.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}+ </select>+ </div>+ )}+<div><label className="block text-xs font-medium text-gray-400 mb-1">Resolution</label><select@@ -207,7 +380,7 @@ export default function ImageGen() {disabled={generating}className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50">- {RESOLUTIONS.map(r => <option key={r.label} value={r.label}>{r.label}</option>)}+ {RESOLUTIONS.map((r) => <option key={r.label} value={r.label}>{r.label}</option>)}{!matchedResolution && <option value={resolutionLabel}>{resolutionLabel} (custom)</option>}</select></div>@@ -218,7 +391,7 @@ export default function ImageGen() {<inputtype="number"value={seed}- onChange={e => setSeed(e.target.value)}+ onChange={(e) => setSeed(e.target.value)}disabled={generating}placeholder="Random"className="flex-1 bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"@@ -236,57 +409,136 @@ export default function ImageGen() {</div><div>- <label className="block text-xs font-medium text-gray-400 mb-1">Steps ({steps})</label>+ <label className="block text-xs font-medium text-gray-400 mb-1">+ Steps {currentModel?.steps && `(default: ${currentModel.steps})`}+ </label><input- type="range"- min={5}- max={75}+ type="number" min={1} max={150}value={steps}+ onChange={(e) => setSteps(e.target.value)}+ placeholder={String(currentModel?.steps || 25)}disabled={generating}- onChange={e => setSteps(Number(e.target.value))}- className="w-full accent-port-accent"+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"/></div>+ {isLocalMode ? (+ <>+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">+ Guidance {currentModel?.guidance != null && `(default: ${currentModel.guidance})`}+ </label>+ <input+ type="number" min={0} max={20} step={0.5}+ value={guidance}+ onChange={(e) => setGuidance(e.target.value)}+ placeholder={String(currentModel?.guidance ?? '')}+ disabled={generating}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ />+ </div>+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">Quantize (bits)</label>+ <select+ value={quantize}+ onChange={(e) => setQuantize(e.target.value)}+ disabled={generating}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ >+ {['3', '4', '5', '6', '8'].map((q) => <option key={q} value={q}>{q}-bit{q === '8' ? ' (default)' : q === '4' ? ' (fast)' : ''}</option>)}+ </select>+ </div>+ </>+ ) : (+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">CFG Scale ({cfgScale})</label>+ <input+ type="range" min={1} max={20} step={0.5}+ value={cfgScale}+ disabled={generating}+ onChange={(e) => setCfgScale(Number(e.target.value))}+ className="w-full accent-port-accent"+ />+ </div>+ )}+ </div>++ {isLocalMode && availableLoras.length > 0 && (<div>- <label className="block text-xs font-medium text-gray-400 mb-1">CFG Scale ({cfgScale})</label>- <input- type="range"- min={1}- max={20}- step={0.5}- value={cfgScale}- disabled={generating}- onChange={e => setCfgScale(Number(e.target.value))}- className="w-full accent-port-accent"- />+ <label className="block text-sm font-medium text-gray-300 mb-2">LoRAs</label>+ <div className="space-y-2 max-h-48 overflow-y-auto">+ {availableLoras.map((lora) => {+ const selected = selectedLoras.find((s) => s.filename === lora.filename);+ return (+ <div key={lora.filename} className="flex items-center gap-3">+ <label className="flex items-center gap-2 cursor-pointer flex-1">+ <input+ type="checkbox"+ checked={!!selected}+ disabled={generating}+ onChange={(e) => {+ if (e.target.checked) setSelectedLoras((p) => [...p, { filename: lora.filename, name: lora.name, scale: 1.0 }]);+ else setSelectedLoras((p) => p.filter((s) => s.filename !== lora.filename));+ }}+ className="rounded"+ />+ <span className="text-sm text-gray-300">{lora.name}</span>+ </label>+ {selected && (+ <div className="flex items-center gap-2">+ <span className="text-xs text-gray-500">Scale</span>+ <input+ type="number" min={0} max={2} step={0.1}+ value={selected.scale}+ disabled={generating}+ onChange={(e) => {+ const scale = parseFloat(e.target.value) || 0;+ setSelectedLoras((p) => p.map((s) => s.filename === lora.filename ? { ...s, scale } : s));+ }}+ className="w-20 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-gray-200"+ />+ </div>+ )}+ </div>+ );+ })}+ </div></div>- </div>+ )}<div className="flex items-center gap-2 pt-2">- <button- type="submit"- disabled={generating || !prompt.trim() || notConnected}- className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors min-h-[40px]"- >- {generating ? <BrailleSpinner /> : <Sparkles className="w-4 h-4" />}- {generating ? 'Generating...' : 'Generate'}- </button>- {generating && progressPct != null && (- <span className="text-xs text-port-accent">{progressPct}%</span>+ {generating ? (+ <button+ type="button"+ onClick={handleCancel}+ className="flex items-center gap-2 px-4 py-2 bg-port-error hover:bg-port-error/80 text-white text-sm font-medium rounded-lg min-h-[40px]"+ >+ <X className="w-4 h-4" /> Cancel+ </button>+ ) : (+ <button+ type="submit"+ disabled={!prompt.trim() || notConnected}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"+ >+ <Sparkles className="w-4 h-4" /> Generate+ </button>)}+ {progressPct != null && <span className="text-xs text-port-accent">{progressPct}%</span>}</div>- </form>++ {(generating || error) && (+ <div className={`text-xs ${error ? 'text-port-error' : 'text-gray-400'}`}>+ {error || statusMsg || 'Working...'}+ </div>+ )}+ </div><div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3"><div className="flex items-center justify-between"><h2 className="text-sm font-medium text-gray-300">Preview</h2>{result && !generating && (- <a- href={result.path}- download- className="flex items-center gap-1 text-xs text-port-accent hover:underline"- >+ <a href={result.path} download className="flex items-center gap-1 text-xs text-port-accent hover:underline"><Download className="w-3 h-3" /> Download</a>)}@@ -294,17 +546,13 @@ export default function ImageGen() {<div className="aspect-square w-full bg-port-bg border border-port-border rounded-lg overflow-hidden flex items-center justify-center relative">{progress?.currentImage ? (- <img- src={`data:image/png;base64,${progress.currentImage}`}- alt="Diffusing..."- className="w-full h-full object-contain"- />+ <img src={`data:image/png;base64,${progress.currentImage}`} alt="Diffusing..." className="w-full h-full object-contain" />) : result ? (<img src={result.path} alt={result.prompt} className="w-full h-full object-contain" />) : generating ? (<div className="text-gray-500 text-sm flex flex-col items-center gap-2"><BrailleSpinner />- <span>Starting diffusion...</span>+ <span>{statusMsg || 'Starting diffusion...'}</span></div>) : (<div className="text-gray-600 text-sm flex flex-col items-center gap-2">@@ -320,76 +568,63 @@ export default function ImageGen() {)}</div>- {generating && (- <div className="text-xs text-gray-400 flex items-center justify-between">- <span>- {progress?.step != null && progress?.totalSteps- ? `Step ${progress.step}/${progress.totalSteps}`- : 'Waiting for first preview...'}- </span>- {progress?.eta != null && progress.eta > 0 && (- <span>ETA: {progress.eta.toFixed(1)}s</span>- )}- </div>- )}-{result && !generating && (- <div className="text-xs text-gray-400 space-y-1">- <div className="flex items-center justify-between gap-2">- <span className="truncate">{result.filename}</span>- <span className="shrink-0">{result.width}×{result.height}</span>- </div>- <div className="text-gray-500 line-clamp-2" title={result.prompt}>{result.prompt}</div>+ <div className="flex flex-wrap items-center gap-2 text-xs text-gray-400">+ <span className="truncate flex-1">{result.filename}</span>+ <span>{result.width}×{result.height}</span>+ {result.seed != null && <span>seed {result.seed}</span>}+ <button+ type="button"+ onClick={() => sendToVideo(result.filename)}+ className="flex items-center gap-1 px-2 py-1 bg-port-success/20 hover:bg-port-success/40 text-port-success rounded text-xs"+ >+ <Film className="w-3 h-3" /> Send to Video+ </button></div>)}</div>- </div>+ </form>- {history.length > 0 && (+ {gallery.length > 0 && (<div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3"><div className="flex items-center justify-between">- <h2 className="text-sm font-medium text-gray-300">Session History ({history.length})</h2>- <button- onClick={handleClearHistory}- className="text-xs text-gray-500 hover:text-port-error transition-colors"- >- Clear- </button>+ <h2 className="text-sm font-medium text-gray-300">Recent renders ({Math.min(gallery.length, 6)} of {gallery.length})</h2>+ {gallery.length > 6 && (+ <Link to="/media/history" className="text-xs text-port-accent hover:underline">View all →</Link>+ )}</div><div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">- {history.map(item => (- <div key={item.id} className="group relative bg-port-bg border border-port-border rounded-lg overflow-hidden">- <div className="aspect-square w-full">- <img src={item.path} alt={item.prompt} className="w-full h-full object-cover" loading="lazy" />- </div>- <div className="absolute inset-0 bg-black/70 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity p-2 flex flex-col justify-between">- <p className="text-xs text-gray-200 line-clamp-3" title={item.prompt}>{item.prompt}</p>- <div className="flex items-center gap-1">- <button- onClick={() => handleReusePrompt(item)}- className="flex-1 px-2 py-1 text-xs bg-port-accent/80 hover:bg-port-accent text-white rounded flex items-center justify-center gap-1 min-h-[32px]"- title="Reuse settings"- >- <Copy className="w-3 h-3" /> Reuse- </button>- <a- href={item.path}- download- className="px-2 py-1 text-xs bg-port-border hover:bg-port-border/70 text-white rounded flex items-center justify-center min-h-[32px]"- title="Download"- >- <Download className="w-3 h-3" />- </a>- </div>- </div>- </div>- ))}+ {gallery.slice(0, 6).map((img) => {+ const item = normalizeImage(img);+ return (+ <MediaCard+ key={item.key}+ item={item}+ onPreview={() => setPreview(img)}+ onRemix={() => handleRemix(img)}+ onSendToVideo={() => sendToVideo(img.filename)}+ onDelete={() => handleDelete(img.filename)}+ />+ );+ })}</div>- <p className="text-xs text-gray-500">- History is stored in your browser only. Files persist on the server in <code className="text-gray-400">./data/images/</code>.- </p></div>)}++ <MediaLightbox+ item={preview ? normalizeImage(preview) : null}+ onClose={() => setPreview(null)}+ // Guard against the click landing after the lightbox close path has+ // already nulled `preview` — without this the closure throws on+ // preview.filename access.+ onRemix={() => preview && handleRemix(preview)}+ onSendToVideo={() => preview?.filename && sendToVideo(preview.filename)}+ />+++ <Drawer open={settingsOpen} onClose={closeSettings} title="Media Generation Settings">+ <ImageGenTab />+ </Drawer></div>);}diff --git a/client/src/pages/MediaGen.jsx b/client/src/pages/MediaGen.jsxnew file mode 100644index 0000000000..1ff1591e10--- /dev/null+++ b/client/src/pages/MediaGen.jsx@@ -0,0 +1,48 @@+import { useNavigate, useLocation, Outlet } from 'react-router-dom';+import { Layers, Image as ImageIcon, Film, History, HardDrive } from 'lucide-react';++const TABS = [+ { id: 'image', label: 'Image', icon: ImageIcon },+ { id: 'video', label: 'Video', icon: Film },+ { id: 'history', label: 'History', icon: History },+ { id: 'models', label: 'Models', icon: HardDrive }+];++export default function MediaGen() {+ const navigate = useNavigate();+ const { pathname } = useLocation();+ const activeTab = pathname.split('/')[2] || 'image';++ return (+ <div className="space-y-4">+ <div className="flex items-center gap-3">+ <Layers className="w-6 h-6 text-port-accent" />+ <h1 className="text-2xl font-bold text-white">Media Gen</h1>+ </div>++ <div className="flex border-b border-port-border" role="tablist">+ {TABS.map(({ id, label, icon: Icon }) => {+ const isActive = activeTab === id;+ return (+ <button+ key={id}+ onClick={() => navigate(`/media/${id}`)}+ className={`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors ${+ isActive+ ? 'text-port-accent border-b-2 border-port-accent bg-port-accent/5'+ : 'text-gray-400 hover:text-white hover:bg-port-card'+ }`}+ role="tab"+ aria-selected={isActive}+ >+ <Icon size={16} aria-hidden="true" />+ {label}+ </button>+ );+ })}+ </div>++ <Outlet />+ </div>+ );+}diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsxnew file mode 100644index 0000000000..2efebc8562--- /dev/null+++ b/client/src/pages/MediaHistory.jsx@@ -0,0 +1,210 @@+/**+ * Media History — unified timeline of generated images + videos with filter+ * chips, ffmpeg stitching (videos only), Remix + Send-to-Video for images,+ * and "continue from last frame" piping back into Image Gen.+ */++import { useState, useEffect, useCallback, useMemo } from 'react';+import { Link, useNavigate } from 'react-router-dom';+import { Combine, Image as ImageIcon, Film } from 'lucide-react';+import toast from '../components/ui/Toast';+import MediaCard from '../components/media/MediaCard';+import MediaLightbox from '../components/media/MediaLightbox';+import { normalizeImage, normalizeVideo } from '../components/media/normalize';+import {+ listVideoHistory, deleteVideoHistoryItem, extractLastFrame, stitchVideos,+ listImageGallery, deleteImage,+} from '../services/api';++const FILTERS = [+ { id: 'all', label: 'All' },+ { id: 'image', label: 'Images' },+ { id: 'video', label: 'Videos' },+];++export default function MediaHistory() {+ const navigate = useNavigate();+ const [items, setItems] = useState([]);+ const [loading, setLoading] = useState(true);+ const [filter, setFilter] = useState('all');+ const [stitchMode, setStitchMode] = useState(false);+ const [selected, setSelected] = useState([]); // video ids+ const [stitching, setStitching] = useState(false);+ const [preview, setPreview] = useState(null);++ const refresh = useCallback(async () => {+ setLoading(true);+ const [images, videos] = await Promise.all([+ listImageGallery().catch(() => []),+ listVideoHistory().catch(() => []),+ ]);+ const merged = [+ ...(Array.isArray(images) ? images.map(normalizeImage) : []),+ ...(Array.isArray(videos) ? videos.map(normalizeVideo) : []),+ ].sort((a, b) => new Date(b.createdAt || 0) - new Date(a.createdAt || 0));+ setItems(merged);+ setLoading(false);+ }, []);++ useEffect(() => { refresh(); }, [refresh]);++ const filtered = useMemo(+ () => filter === 'all' ? items : items.filter(i => i.kind === filter),+ [items, filter]+ );+ const counts = useMemo(() => ({+ all: items.length,+ image: items.filter(i => i.kind === 'image').length,+ video: items.filter(i => i.kind === 'video').length,+ }), [items]);++ const toggleSelect = (videoId) => {+ setSelected((s) => s.includes(videoId) ? s.filter((x) => x !== videoId) : [...s, videoId]);+ };++ const handleStitch = async () => {+ if (selected.length < 2) return;+ setStitching(true);+ try {+ await stitchVideos(selected);+ toast.success(`Stitched ${selected.length} videos`);+ setStitchMode(false);+ setSelected([]);+ refresh();+ } catch (err) {+ toast.error(err.message || 'Stitch failed');+ } finally {+ setStitching(false);+ }+ };++ const handleDelete = async (item) => {+ try {+ await (item.kind === 'image'+ ? deleteImage(item.filename)+ : deleteVideoHistoryItem(item.id));+ setItems((all) => all.filter((x) => x.key !== item.key));+ } catch (err) {+ toast.error(err.message || 'Delete failed');+ }+ };++ const handleContinue = async (item) => {+ try {+ const { filename } = await extractLastFrame(item.id);+ navigate(`/media/image?lastFrameFile=${encodeURIComponent(filename)}`);+ } catch (err) {+ toast.error(err.message || 'Failed to extract last frame');+ }+ };++ const handleRemix = (item) => {+ const params = new URLSearchParams();+ if (item.prompt) params.set('prompt', item.prompt);+ if (item.modelId) params.set('modelId', item.modelId);+ if (item.width) params.set('width', String(item.width));+ if (item.height) params.set('height', String(item.height));+ if (item.seed != null) params.set('seed', String(item.seed));+ if (item.steps) params.set('steps', String(item.steps));+ navigate(`/media/image?${params}`);+ };++ const handleSendToVideo = (item) => {+ navigate(`/media/video?sourceImageFile=${encodeURIComponent(item.filename)}`);+ };++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <div className="flex items-center gap-1 text-xs">+ {FILTERS.map((f) => (+ <button+ key={f.id}+ type="button"+ onClick={() => setFilter(f.id)}+ className={`px-2.5 py-1 rounded-full border ${+ filter === f.id+ ? 'bg-port-accent/20 border-port-accent text-port-accent'+ : 'border-port-border text-gray-400 hover:text-white hover:bg-port-border/50'+ }`}+ >+ {f.label} <span className="opacity-60">{counts[f.id]}</span>+ </button>+ ))}+ </div>+ <div className="flex items-center gap-1">+ <Link to="/media/image" className="flex items-center gap-1.5 px-2 py-1 text-xs text-gray-300 hover:text-white border border-port-border rounded hover:bg-port-border/50">+ <ImageIcon className="w-3.5 h-3.5" /> Image+ </Link>+ <Link to="/media/video" className="flex items-center gap-1.5 px-2 py-1 text-xs text-gray-300 hover:text-white border border-port-border rounded hover:bg-port-border/50">+ <Film className="w-3.5 h-3.5" /> Video+ </Link>+ <button+ type="button"+ onClick={() => { setStitchMode((m) => !m); setSelected([]); }}+ className={`flex items-center gap-1.5 px-2 py-1 text-xs rounded border ${+ stitchMode+ ? 'bg-port-accent text-white border-port-accent'+ : 'border-port-border text-gray-300 hover:text-white hover:bg-port-border/50'+ }`}+ >+ <Combine className="w-3.5 h-3.5" /> {stitchMode ? `Cancel (${selected.length})` : 'Stitch'}+ </button>+ {stitchMode && selected.length >= 2 && (+ <button+ type="button"+ onClick={handleStitch}+ disabled={stitching}+ className="flex items-center gap-1.5 px-2 py-1 text-xs bg-port-success hover:bg-port-success/80 disabled:opacity-50 text-white rounded"+ >+ {stitching ? 'Stitching…' : `Stitch ${selected.length}`}+ </button>+ )}+ </div>+ </div>++ {loading ? (+ <div className="text-gray-500 text-sm">Loading…</div>+ ) : filtered.length === 0 ? (+ <div className="bg-port-card border border-port-border rounded-xl p-8 text-center text-gray-500 text-sm">+ {filter === 'video'+ ? <>No videos yet. <Link to="/media/video" className="text-port-accent hover:underline">Generate one →</Link></>+ : filter === 'image'+ ? <>No images yet. <Link to="/media/image" className="text-port-accent hover:underline">Generate one →</Link></>+ : <>Nothing here yet. Try <Link to="/media/image" className="text-port-accent hover:underline">Image</Link> or <Link to="/media/video" className="text-port-accent hover:underline">Video</Link>.</>}+ </div>+ ) : (+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">+ {filtered.map((it) => {+ const inStitch = stitchMode && it.kind === 'video';+ const idx = inStitch ? selected.indexOf(it.id) : -1;+ return (+ <MediaCard+ key={it.key}+ item={it}+ onPreview={setPreview}+ onClick={inStitch ? () => toggleSelect(it.id) : undefined}+ onRemix={!stitchMode ? handleRemix : undefined}+ onSendToVideo={!stitchMode ? handleSendToVideo : undefined}+ onContinue={!stitchMode ? handleContinue : undefined}+ onDelete={!stitchMode ? handleDelete : undefined}+ selectionLabel={idx !== -1 ? idx + 1 : null}+ selected={idx !== -1}+ disabled={stitchMode && it.kind !== 'video'}+ hideActions={stitchMode}+ />+ );+ })}+ </div>+ )}++ <MediaLightbox+ item={preview}+ onClose={() => setPreview(null)}+ onRemix={handleRemix}+ onSendToVideo={handleSendToVideo}+ onContinue={handleContinue}+ />+ </div>+ );+}diff --git a/client/src/pages/MediaModels.jsx b/client/src/pages/MediaModels.jsxnew file mode 100644index 0000000000..c1d565315d--- /dev/null+++ b/client/src/pages/MediaModels.jsx@@ -0,0 +1,145 @@+/**+ * Media Models — view + clean up cached HuggingFace model weights and LoRA files.+ *+ * HF models live at HF's standard location (`~/.cache/huggingface/hub` unless+ * the user set HF_HOME). PortOS doesn't move or symlink them — it just reads+ * sizes for display and offers Delete to free disk space. LoRAs sit in+ * `data/loras/` and are tracked by DataManager.+ */++import { useState, useEffect, useCallback } from 'react';+import { Trash2, RefreshCw, Image as ImageIcon, Film } from 'lucide-react';+import toast from '../components/ui/Toast';+import { listCachedModels, deleteCachedModel, deleteLora } from '../services/api';++export default function MediaModels() {+ const [data, setData] = useState({ models: [], loras: [], hubDir: '', diskUsage: {} });+ const [loading, setLoading] = useState(true);+ const [busy, setBusy] = useState(null);++ const refresh = useCallback(() => {+ setLoading(true);+ listCachedModels()+ .then(setData)+ .catch(() => setData({ models: [], loras: [], hubDir: '', diskUsage: {} }))+ .finally(() => setLoading(false));+ }, []);++ useEffect(() => { refresh(); }, [refresh]);++ const handleDeleteModel = async (id) => {+ setBusy(id);+ try {+ await deleteCachedModel(id);+ toast.success('Model deleted — will re-download on next use');+ setData((d) => ({ ...d, models: d.models.filter((m) => m.id !== id) }));+ } catch (err) {+ toast.error(err.message || 'Delete failed');+ } finally {+ setBusy(null);+ }+ };++ const handleDeleteLora = async (filename) => {+ setBusy(filename);+ try {+ await deleteLora(filename);+ toast.success('LoRA deleted');+ setData((d) => ({ ...d, loras: d.loras.filter((l) => l.filename !== filename) }));+ } catch (err) {+ toast.error(err.message || 'Delete failed');+ } finally {+ setBusy(null);+ }+ };++ return (+ <div className="space-y-6">+ <div className="flex items-center justify-end gap-2">+ <button+ onClick={refresh}+ disabled={loading}+ className="p-2 rounded-lg text-gray-400 hover:text-white hover:bg-port-border/50 disabled:opacity-50 min-h-[40px] min-w-[40px] flex items-center justify-center"+ title="Refresh"+ >+ <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />+ </button>+ </div>++ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">+ {Object.entries(data.diskUsage || {}).map(([key, value]) => (+ <div key={key} className="bg-port-card border border-port-border rounded-xl p-4">+ <div className="text-xs text-gray-400 capitalize">{key}</div>+ <div className="text-lg font-semibold text-white">{value}</div>+ </div>+ ))}+ </div>++ {data.hubDir && (+ <p className="text-xs text-gray-500">+ HuggingFace cache: <code className="text-gray-400">{data.hubDir}</code>+ </p>+ )}++ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3">+ <h2 className="text-sm font-medium text-gray-300 flex items-center gap-2">+ <ImageIcon className="w-4 h-4" /> Cached Models ({data.models.length})+ </h2>+ {data.models.length === 0 ? (+ <p className="text-xs text-gray-500">No models cached yet. They'll appear here as you generate.</p>+ ) : (+ <div className="space-y-2">+ {data.models.map((m) => (+ <div key={m.id} className="flex items-center gap-3 bg-port-bg border border-port-border rounded-lg p-3">+ <div className="flex-1 min-w-0">+ <div className="text-sm text-white truncate">{m.label || m.repo}</div>+ <div className="text-xs text-gray-500 truncate">{m.repo}</div>+ </div>+ <span className="text-sm text-gray-400 shrink-0">{m.sizeHuman}</span>+ <button+ type="button"+ onClick={() => handleDeleteModel(m.id)}+ disabled={busy === m.id}+ className="px-3 py-1.5 text-xs bg-port-error/20 hover:bg-port-error/40 text-port-error rounded disabled:opacity-50 flex items-center gap-1"+ >+ <Trash2 className="w-3 h-3" /> {busy === m.id ? 'Deleting...' : 'Delete'}+ </button>+ </div>+ ))}+ </div>+ )}+ </div>++ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3">+ <h2 className="text-sm font-medium text-gray-300 flex items-center gap-2">+ <Film className="w-4 h-4" /> LoRAs ({data.loras.length})+ </h2>+ {data.loras.length === 0 ? (+ <p className="text-xs text-gray-500">+ Drop <code className="text-gray-400">.safetensors</code> LoRA files into <code className="text-gray-400">data/loras/</code> and they'll show up here for use in Image Gen.+ </p>+ ) : (+ <div className="space-y-2">+ {data.loras.map((l) => (+ <div key={l.filename} className="flex items-center gap-3 bg-port-bg border border-port-border rounded-lg p-3">+ <div className="flex-1 min-w-0">+ <div className="text-sm text-white truncate">{l.name}</div>+ <div className="text-xs text-gray-500 truncate">{l.filename}</div>+ </div>+ <span className="text-sm text-gray-400 shrink-0">{l.sizeHuman}</span>+ <button+ type="button"+ onClick={() => handleDeleteLora(l.filename)}+ disabled={busy === l.filename}+ className="px-3 py-1.5 text-xs bg-port-error/20 hover:bg-port-error/40 text-port-error rounded disabled:opacity-50 flex items-center gap-1"+ >+ <Trash2 className="w-3 h-3" /> {busy === l.filename ? 'Deleting...' : 'Delete'}+ </button>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex 7f1af5b158..ca3b47f2e4 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -1,9 +1,8 @@-import { useParams, useNavigate } from 'react-router-dom';+import { useParams, useNavigate, Navigate } from 'react-router-dom';import { BackupTab } from '../components/settings/BackupTab';import { DatabaseTab } from '../components/settings/DatabaseTab';import { TelegramTab } from '../components/settings/TelegramTab';import { GeneralTab } from '../components/settings/GeneralTab';-import { ImageGenTab } from '../components/settings/ImageGenTab';import { MortalLoomTab } from '../components/settings/MortalLoomTab';import { VoiceTab } from '../components/settings/VoiceTab';@@ -11,17 +10,27 @@ const TABS = [{ id: 'general', label: 'General' },{ id: 'backup', label: 'Backup' },{ id: 'database', label: 'Database' },- { id: 'image-gen', label: 'Image Gen' },{ id: 'voice', label: 'Voice' },{ id: 'telegram', label: 'Telegram' },{ id: 'mortalloom', label: 'MortalLoom' }];+// Settings pages now host themselves as drawers on their feature pages where+// it makes sense. Redirect old direct URLs to the new home so bookmarks and+// stale palette entries keep working.+const REDIRECTS = {+ 'image-gen': '/image-gen?settings=1'+};+export default function Settings() {const { tab } = useParams();const navigate = useNavigate();const activeTab = tab || 'general';+ if (REDIRECTS[activeTab]) {+ return <Navigate to={REDIRECTS[activeTab]} replace />;+ }+const handleTabChange = (tabId) => {navigate(`/settings/${tabId}`);};@@ -31,7 +40,6 @@ export default function Settings() {case 'general': return <GeneralTab />;case 'backup': return <BackupTab />;case 'database': return <DatabaseTab />;- case 'image-gen': return <ImageGenTab />;case 'voice': return <VoiceTab />;case 'telegram': return <TelegramTab />;case 'mortalloom': return <MortalLoomTab />;diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxnew file mode 100644index 0000000000..187ed01084--- /dev/null+++ b/client/src/pages/VideoGen.jsx@@ -0,0 +1,551 @@+/**+ * Video Generation page (LTX models via mlx_video on macOS, diffusers on+ * Windows). Local-only — there is no external A1111 equivalent for video.+ *+ * Accepts a source image either via direct upload or via the+ * `?sourceImageFile=` query param so the Image Gen page can pipe a generation+ * straight into video.+ */++import { useState, useEffect, useRef, useCallback } from 'react';+import { useSearchParams, useNavigate, Link } from 'react-router-dom';+import Drawer from '../components/Drawer';+import { ImageGenTab } from '../components/settings/ImageGenTab';+import MediaCard from '../components/media/MediaCard';+import MediaLightbox from '../components/media/MediaLightbox';+import { normalizeVideo } from '../components/media/normalize';+import {+ Film, Sparkles, Settings as SettingsIcon, RefreshCw, AlertTriangle,+ Dice5, X, Upload+} from 'lucide-react';+import toast from '../components/ui/Toast';+import BrailleSpinner from '../components/BrailleSpinner';+import {+ getVideoGenStatus, generateVideo, cancelVideoGen,+ listVideoHistory, deleteVideoHistoryItem, extractLastFrame,+} from '../services/api';+import { randomSeed, safeParseJSON } from '../lib/genUtils';++const RESOLUTIONS = [+ { label: '512×320 (16:10)', w: 512, h: 320 },+ { label: '640×384 (5:3)', w: 640, h: 384 },+ { label: '704×448 (16:10)', w: 704, h: 448 },+ { label: '768×512 (3:2 default)', w: 768, h: 512 },+ { label: '1024×576 (16:9)', w: 1024, h: 576 },+ { label: '512×768 (portrait)', w: 512, h: 768 },+];++const FRAME_OPTIONS = [25, 49, 73, 97, 121, 145, 169, 193, 217, 241];+const FPS_OPTIONS = [16, 24, 30];+const TILING_OPTIONS = [+ { value: 'auto', label: 'Auto (recommended)' },+ { value: 'none', label: 'None (fastest, more VRAM)' },+ { value: 'spatial', label: 'Spatial only' },+ { value: 'temporal', label: 'Temporal only' },+];++export default function VideoGen() {+ const [searchParams, setSearchParams] = useSearchParams();+ const incomingSourceImage = searchParams.get('sourceImageFile');+ const settingsOpen = searchParams.get('settings') === '1';+ const openSettings = () => setSearchParams(prev => { const n = new URLSearchParams(prev); n.set('settings', '1'); return n; });+ const closeSettings = () => setSearchParams(prev => { const n = new URLSearchParams(prev); n.delete('settings'); return n; });++ const [status, setStatus] = useState(null);+ const [statusLoading, setStatusLoading] = useState(true);+ const [models, setModels] = useState([]);++ const [prompt, setPrompt] = useState('');+ const [negativePrompt, setNegativePrompt] = useState('');+ const [modelId, setModelId] = useState('');+ const [width, setWidth] = useState(768);+ const [height, setHeight] = useState(512);+ const [numFrames, setNumFrames] = useState(121);+ const [fps, setFps] = useState(24);+ const [steps, setSteps] = useState('');+ const [guidanceScale, setGuidanceScale] = useState('');+ const [seed, setSeed] = useState('');+ const [tiling, setTiling] = useState('auto');+ const [disableAudio, setDisableAudio] = useState(false);+ const [sourceImageFile, setSourceImageFile] = useState(incomingSourceImage || null);+ const [sourceImageUpload, setSourceImageUpload] = useState(null);+ // Re-sync when ImageGen pipes a new image via ?sourceImageFile=...+ // React Router doesn't remount on query-string-only navigation, so the+ // initial useState capture would otherwise stick.+ useEffect(() => {+ if (incomingSourceImage) {+ setSourceImageFile(incomingSourceImage);+ setSourceImageUpload(null);+ }+ }, [incomingSourceImage]);+ const [history, setHistory] = useState([]);+ const [preview, setPreview] = useState(null);+ const navigate = useNavigate();++ const refreshHistory = useCallback(() => {+ listVideoHistory().then((items) => setHistory(Array.isArray(items) ? items : [])).catch(() => {});+ }, []);+ useEffect(() => { refreshHistory(); }, [refreshHistory]);++ const handleDeleteHistory = async (item) => {+ await deleteVideoHistoryItem(item.id).catch((err) => toast.error(err.message || 'Delete failed'));+ setHistory((h) => h.filter((v) => v.id !== item.id));+ };+ const handleContinueHistory = async (item) => {+ try {+ const { filename } = await extractLastFrame(item.id);+ navigate(`/media/image?lastFrameFile=${encodeURIComponent(filename)}`);+ } catch (err) {+ toast.error(err.message || 'Failed to extract last frame');+ }+ };++ const [generating, setGenerating] = useState(false);+ const [progress, setProgress] = useState(null);+ const [statusMsg, setStatusMsg] = useState('');+ const [result, setResult] = useState(null);+ const [error, setError] = useState(null);+ const eventSourceRef = useRef(null);++ const refreshStatus = useCallback(() => {+ setStatusLoading(true);+ getVideoGenStatus()+ .then((s) => {+ setStatus(s);+ setModels(s.models || []);+ // Functional update so a stale `modelId` closure can't reset the+ // user's selected model on a refresh — only set when no choice yet.+ if (s.defaultModel) setModelId((prev) => prev || s.defaultModel);+ })+ .catch(() => setStatus({ connected: false, reason: 'Status check failed' }))+ .finally(() => setStatusLoading(false));+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ useEffect(() => {+ refreshStatus();+ return () => eventSourceRef.current?.close();+ }, [refreshStatus]);++ const currentModel = models.find((m) => m.id === modelId);+ const matchedResolution = RESOLUTIONS.find((r) => r.w === width && r.h === height);+ const resolutionLabel = matchedResolution?.label || `${width}×${height}`;+ const progressPct = progress?.progress != null ? Math.round(progress.progress * 100) : null;++ const handleResolutionChange = (e) => {+ const r = RESOLUTIONS.find((r) => r.label === e.target.value);+ if (r) { setWidth(r.w); setHeight(r.h); }+ };++ const handleRandomSeed = () => setSeed(randomSeed());++ const clearSourceImage = () => {+ setSourceImageFile(null);+ setSourceImageUpload(null);+ if (incomingSourceImage) {+ const next = new URLSearchParams(searchParams);+ next.delete('sourceImageFile');+ setSearchParams(next, { replace: true });+ }+ };++ const handleGenerate = async (e) => {+ e?.preventDefault?.();+ if (!prompt.trim() || generating) return;+ setGenerating(true);+ setProgress({ progress: 0 });+ setStatusMsg('Starting...');+ setResult(null);+ setError(null);++ try {+ const data = await generateVideo({+ prompt: prompt.trim(),+ negativePrompt: negativePrompt.trim() || '',+ modelId,+ width, height,+ numFrames,+ fps,+ steps: steps || '',+ guidanceScale: guidanceScale || '',+ seed: seed || '',+ tiling,+ disableAudio: disableAudio ? 'true' : 'false',+ sourceImageFile: sourceImageFile || '',+ sourceImage: sourceImageUpload || '',+ });++ const jobId = data.jobId || data.generationId;+ const es = new EventSource(`/api/video-gen/${jobId}/events`);+ eventSourceRef.current = es;++ es.onmessage = (ev) => {+ const msg = safeParseJSON(ev.data);+ if (!msg) return;+ if (msg.type === 'status') setStatusMsg(msg.message);+ if (msg.type === 'progress') {+ setProgress({ progress: msg.progress });+ setStatusMsg(msg.message);+ }+ if (msg.type === 'complete') {+ setResult(msg.result);+ setGenerating(false);+ setProgress({ progress: 1 });+ setStatusMsg('Complete');+ es.close();+ toast.success('Video generated');+ refreshHistory();+ }+ if (msg.type === 'error') {+ setError(msg.error);+ setGenerating(false);+ es.close();+ toast.error(msg.error);+ }+ };+ es.onerror = () => {+ setError('Lost connection to server');+ setGenerating(false);+ es.close();+ };+ } catch (err) {+ setError(err.message || 'Video generation failed');+ setGenerating(false);+ toast.error(err.message || 'Video generation failed');+ }+ };++ const handleCancel = async () => {+ eventSourceRef.current?.close();+ await cancelVideoGen().catch(() => {});+ setGenerating(false);+ setStatusMsg('Cancelled');+ };++ const notConnected = status && status.connected === false;++ return (+ <div className="space-y-6">+ <div className="flex items-center justify-between gap-2 text-xs">+ {status ? (+ <span className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-full border ${+ status.connected+ ? 'border-port-success/40 bg-port-success/10 text-port-success'+ : 'border-port-error/40 bg-port-error/10 text-port-error'+ }`}>+ {status.connected ? (+ <><span className="w-2 h-2 rounded-full bg-port-success" /> {status.pythonPath || 'local Python'}</>+ ) : (+ <>+ <AlertTriangle className="w-3 h-3" />+ {status.reason || 'Local Python not configured'} —+ <button type="button" onClick={openSettings} className="underline">Settings</button>+ </>+ )}+ </span>+ ) : (+ <span className="text-gray-500">Checking…</span>+ )}+ <div className="flex items-center gap-1">+ <button+ onClick={refreshStatus}+ disabled={statusLoading}+ className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50 disabled:opacity-50"+ title="Refresh status"+ >+ <RefreshCw className={`w-3.5 h-3.5 ${statusLoading ? 'animate-spin' : ''}`} />+ </button>+ <button+ type="button"+ onClick={openSettings}+ className="flex items-center gap-1.5 px-2 py-1 text-gray-300 hover:text-white border border-port-border rounded hover:bg-port-border/50"+ title="Video Gen settings"+ >+ <SettingsIcon className="w-3.5 h-3.5" /> Settings+ </button>+ </div>+ </div>++ <form onSubmit={handleGenerate} className="grid grid-cols-1 lg:grid-cols-[1fr,1.2fr] gap-6">+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">+ <div>+ <label className="block text-sm font-medium text-gray-300 mb-1">Prompt</label>+ <textarea+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ rows={4}+ disabled={generating}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y"+ placeholder="Describe the video you want to generate..."+ />+ </div>++ <div>+ <label className="block text-sm font-medium text-gray-300 mb-1">Negative Prompt</label>+ <textarea+ value={negativePrompt}+ onChange={(e) => setNegativePrompt(e.target.value)}+ rows={2}+ disabled={generating}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y"+ placeholder="What to avoid..."+ />+ </div>++ {/* Source image (image-to-video) */}+ <div className="border border-port-border/50 rounded-lg p-3 space-y-2">+ <div className="flex items-center justify-between">+ <span className="text-xs font-medium text-gray-400">Source Image (optional, image-to-video)</span>+ {(sourceImageFile || sourceImageUpload) && (+ <button type="button" onClick={clearSourceImage} className="text-xs text-port-error hover:underline">Clear</button>+ )}+ </div>+ {sourceImageFile && (+ <div className="flex items-center gap-2">+ <img src={`/data/images/${sourceImageFile}`} alt="Source" className="w-16 h-16 object-cover rounded border border-port-border" />+ <span className="text-xs text-gray-500 truncate">{sourceImageFile}</span>+ </div>+ )}+ {!sourceImageFile && (+ <label className="flex items-center gap-2 text-xs text-gray-400 cursor-pointer hover:text-white">+ <Upload className="w-4 h-4" />+ <span>{sourceImageUpload ? sourceImageUpload.name : 'Upload an image'}</span>+ <input+ type="file"+ accept="image/*"+ disabled={generating}+ onChange={(e) => setSourceImageUpload(e.target.files?.[0] || null)}+ className="hidden"+ />+ </label>+ )}+ </div>++ <div className="grid grid-cols-2 gap-3">+ {models.length > 0 && (+ <div className="col-span-2">+ <label className="block text-xs font-medium text-gray-400 mb-1">Model</label>+ <select+ value={modelId}+ onChange={(e) => { setModelId(e.target.value); setSteps(''); setGuidanceScale(''); }}+ disabled={generating}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ >+ {models.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}+ </select>+ </div>+ )}++ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">Resolution</label>+ <select+ value={resolutionLabel}+ onChange={handleResolutionChange}+ disabled={generating}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ >+ {RESOLUTIONS.map((r) => <option key={r.label} value={r.label}>{r.label}</option>)}+ </select>+ </div>++ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">Frames</label>+ <select+ value={numFrames}+ onChange={(e) => setNumFrames(Number(e.target.value))}+ disabled={generating}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ >+ {FRAME_OPTIONS.map((f) => <option key={f} value={f}>{f} ({(f / fps).toFixed(1)}s @ {fps}fps)</option>)}+ </select>+ </div>++ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">FPS</label>+ <select+ value={fps}+ onChange={(e) => setFps(Number(e.target.value))}+ disabled={generating}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ >+ {FPS_OPTIONS.map((f) => <option key={f} value={f}>{f}</option>)}+ </select>+ </div>++ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">Seed</label>+ <div className="flex items-center gap-1">+ <input+ type="number"+ value={seed}+ onChange={(e) => setSeed(e.target.value)}+ disabled={generating}+ placeholder="Random"+ className="flex-1 bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ />+ <button+ type="button"+ onClick={handleRandomSeed}+ disabled={generating}+ className="p-2 text-gray-400 hover:text-white border border-port-border rounded-lg hover:bg-port-border/50 disabled:opacity-50 min-h-[40px] min-w-[40px] flex items-center justify-center"+ title="Randomize seed"+ >+ <Dice5 className="w-4 h-4" />+ </button>+ </div>+ </div>++ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">+ Steps {currentModel?.steps && `(default: ${currentModel.steps})`}+ </label>+ <input+ type="number" min={1} max={150}+ value={steps}+ onChange={(e) => setSteps(e.target.value)}+ placeholder={String(currentModel?.steps || 25)}+ disabled={generating}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ />+ </div>++ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1">+ CFG Scale {currentModel?.guidance != null && `(default: ${currentModel.guidance})`}+ </label>+ <input+ type="number" min={0} max={20} step={0.5}+ value={guidanceScale}+ onChange={(e) => setGuidanceScale(e.target.value)}+ placeholder={String(currentModel?.guidance ?? 3.0)}+ disabled={generating}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ />+ </div>++ <div className="col-span-2">+ <label className="block text-xs font-medium text-gray-400 mb-1">Tiling</label>+ <select+ value={tiling}+ onChange={(e) => setTiling(e.target.value)}+ disabled={generating}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ >+ {TILING_OPTIONS.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}+ </select>+ </div>++ <label className="col-span-2 flex items-center gap-2 text-xs text-gray-400 cursor-pointer">+ <input+ type="checkbox"+ checked={disableAudio}+ onChange={(e) => setDisableAudio(e.target.checked)}+ disabled={generating}+ className="rounded"+ />+ Disable audio (LTX-2 only — speeds up generation)+ </label>+ </div>++ <div className="flex items-center gap-2 pt-2">+ {generating ? (+ <button+ type="button"+ onClick={handleCancel}+ className="flex items-center gap-2 px-4 py-2 bg-port-error hover:bg-port-error/80 text-white text-sm font-medium rounded-lg min-h-[40px]"+ >+ <X className="w-4 h-4" /> Cancel+ </button>+ ) : (+ <button+ type="submit"+ disabled={!prompt.trim() || notConnected}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"+ >+ <Sparkles className="w-4 h-4" /> Generate+ </button>+ )}+ {progressPct != null && <span className="text-xs text-port-accent">{progressPct}%</span>}+ </div>++ {(generating || error) && (+ <div className={`text-xs ${error ? 'text-port-error' : 'text-gray-400'}`}>+ {error || statusMsg || 'Working...'}+ </div>+ )}+ </div>++ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3">+ <h2 className="text-sm font-medium text-gray-300">Preview</h2>+ <div className="aspect-video w-full bg-port-bg border border-port-border rounded-lg overflow-hidden flex items-center justify-center relative">+ {result ? (+ <video src={result.path || `/data/videos/${result.filename}`} controls autoPlay loop className="w-full h-full" />+ ) : generating ? (+ <div className="text-gray-500 text-sm flex flex-col items-center gap-2">+ <BrailleSpinner />+ <span>{statusMsg || 'Starting...'}</span>+ </div>+ ) : (+ <div className="text-gray-600 text-sm flex flex-col items-center gap-2">+ <Film className="w-12 h-12" />+ <span>Your generated video will appear here</span>+ </div>+ )}+ {generating && progressPct != null && (+ <div className="absolute bottom-0 left-0 right-0 h-1 bg-black/50">+ <div className="h-full bg-port-accent transition-all" style={{ width: `${progressPct}%` }} />+ </div>+ )}+ </div>+ {result && (+ <div className="flex flex-wrap items-center gap-2 text-xs text-gray-400">+ <span className="truncate flex-1">{result.filename}</span>+ <a+ href={result.path || `/data/videos/${result.filename}`}+ download+ className="text-port-accent hover:underline"+ >+ Download+ </a>+ </div>+ )}+ </div>+ </form>++ {history.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3">+ <div className="flex items-center justify-between">+ <h2 className="text-sm font-medium text-gray-300">Recent renders ({Math.min(history.length, 6)} of {history.length})</h2>+ {history.length > 6 && (+ <Link to="/media/history" className="text-xs text-port-accent hover:underline">View all →</Link>+ )}+ </div>+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">+ {history.slice(0, 6).map((v) => {+ const item = normalizeVideo(v);+ return (+ <MediaCard+ key={item.key}+ item={item}+ onPreview={() => setPreview(item)}+ onContinue={() => handleContinueHistory(v)}+ onDelete={() => handleDeleteHistory(v)}+ />+ );+ })}+ </div>+ </div>+ )}++ <MediaLightbox+ item={preview}+ onClose={() => setPreview(null)}+ onContinue={(item) => handleContinueHistory(item.raw)}+ />++ <Drawer open={settingsOpen} onClose={closeSettings} title="Media Generation Settings">+ <ImageGenTab />+ </Drawer>+ </div>+ );+}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 8c194b1c61..ebf5c18eb7 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -35,6 +35,7 @@ export * from './apiOpenClaw.js';export * from './apiPalette.js';export * from './apiDashboard.js';export * from './apiAsk.js';+export * from './apiImageVideo.js';// Default export for simplified imports (get/post/put/delete helpers)export { default } from './apiCore.js';diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsnew file mode 100644index 0000000000..bb4c4dcbbb--- /dev/null+++ b/client/src/services/apiImageVideo.js@@ -0,0 +1,50 @@+import { request } from './apiCore.js';++// Image gen — local backend extras (gallery, models, LoRAs, cancel, delete).+// generateImage / getImageGenStatus / generateAvatar live in apiSystem.js for+// backward compatibility with existing call sites.+export const listImageModels = () => request('/image-gen/models');+export const listLoras = () => request('/image-gen/loras');+export const listImageGallery = () => request('/image-gen/gallery');+export const getActiveImageJob = () => request('/image-gen/active');+export const cancelImageGen = () => request('/image-gen/cancel', { method: 'POST' });+export const deleteImage = (filename) => request(`/image-gen/${encodeURIComponent(filename)}`, { method: 'DELETE' });++// Video gen+export const getVideoGenStatus = () => request('/video-gen/status');+export const listVideoModels = () => request('/video-gen/models');+export const cancelVideoGen = () => request('/video-gen/cancel', { method: 'POST' });+export const listVideoHistory = () => request('/video-gen/history');+export const deleteVideoHistoryItem = (id) => request(`/video-gen/history/${encodeURIComponent(id)}`, { method: 'DELETE' });+export const extractLastFrame = (id) => request(`/video-gen/last-frame/${encodeURIComponent(id)}`, { method: 'POST' });+export const stitchVideos = (videoIds) => request('/video-gen/stitch', {+ method: 'POST',+ body: JSON.stringify({ videoIds }),+});++// generateVideo always sends multipart/form-data via FormData. Bypass the+// JSON-only request() helper because the server route expects multipart for+// the optional sourceImage upload (and uniform multipart parsing for both+// upload and no-upload paths is simpler than branching on Content-Type).+export async function generateVideo(fields) {+ const fd = new FormData();+ for (const [k, v] of Object.entries(fields)) {+ if (v == null || v === '') continue;+ if (v instanceof Blob) fd.append(k, v);+ else fd.append(k, String(v));+ }+ const res = await fetch('/api/video-gen', { method: 'POST', body: fd });+ if (!res.ok) {+ const body = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));+ const err = new Error(body.error || `HTTP ${res.status}`);+ err.code = body.code;+ err.status = res.status;+ throw err;+ }+ return res.json();+}++// Models management (HF cache + LoRAs)+export const listCachedModels = () => request('/image-video/models');+export const deleteCachedModel = (dirName) => request(`/image-video/models/hf/${encodeURIComponent(dirName)}`, { method: 'DELETE' });+export const deleteLora = (filename) => request(`/image-video/models/lora/${encodeURIComponent(filename)}`, { method: 'DELETE' });diff --git a/docs/PORTS.md b/docs/PORTS.mdindex 04d561af6c..65a091c0dc 100644--- a/docs/PORTS.md+++ b/docs/PORTS.md@@ -24,8 +24,8 @@ Common port labels:| Port | Process | Label | Description ||------|---------|-------|-------------|| 5553 | portos-server | api-local | Loopback-only HTTP mirror of the API (only listens when HTTPS is active on 5555). Lets `http://localhost:5553` work without cert warnings. Override with `PORTOS_HTTP_PORT`. |-| 5554 | portos-client | ui | Vite dev server (React UI) |-| 5555 | portos-server | api | Main API server |+| 5554 | portos-client | ui | Vite dev server (React UI) — only present in `npm run dev`; `npm start` serves the built client from :5555 directly. |+| 5555 | portos-server | api | Main API server — **always the user-facing port**. Switches between HTTP and HTTPS based on whether `data/certs/{cert,key}.pem` exists. || 5556 | portos-browser | cdp | Chrome DevTools Protocol || 5557 | portos-browser | health | Browser health check API || 5558 | portos-cos | api | CoS Agent Runner (isolated process) |@@ -33,6 +33,25 @@ Common port labels:| 5560 | portos-autofixer-ui | ui | Autofixer web UI || 5561 | portos-db | db | PostgreSQL Docker container (native mode uses system pg on 5432) |+## How `:5555`, `:5553`, and `:5554` Relate++These three ports are easy to confuse, so:++```+ ┌─ :5555 ─ HTTPS app (Tailscale cert) ← always user-facing+remote browser ──────────┤+ └─ :5555 ─ HTTP app (no cert) ← always user-facing++local scripts / curl ────── :5553 ─ HTTP loopback mirror (HTTPS mode only, 127.0.0.1)++vite dev (npm run dev) ──── :5554 ─ Vite dev server (dev only, separate process)+```++Rules of thumb:+1. **`:5555` is the only port a remote user ever needs.** The scheme (HTTP vs HTTPS) flips based on whether a TLS cert is provisioned (`npm run setup:cert`); the port number does not.+2. **`:5553` is a convenience for local terminals.** When HTTPS is on, `https://localhost:5555` would trip a cert warning (the cert covers `<machine>.<tailnet>.ts.net`, not `localhost`). The loopback HTTP mirror on `:5553` lets curl/scripts skip TLS entirely. It binds to `127.0.0.1` only — never reachable over the network.+3. **`:5554` is `vite dev` only.** In `npm run dev`, Vite serves the React UI from `:5554` and proxies `/api` calls to `:5555`. In `npm start` (production), the React build is served from `:5555` itself; `:5554` is unused.+## Defining Ports in ecosystem.config.cjsDefine all ports in a top-level `PORTS` object as the single source of truth:diff --git a/lib/slashdo b/lib/slashdoindex e43d63e9ce..a38ee04326 160000--- a/lib/slashdo+++ b/lib/slashdo@@ -1 +1 @@-Subproject commit e43d63e9ce01b5f68c89c9dfb28ef8f738cd2490+Subproject commit a38ee04326684df8063148a88da96958cf6c2342diff --git a/package.json b/package.jsonindex eaab16d17d..dd619bbfe1 100644--- a/package.json+++ b/package.json@@ -18,9 +18,9 @@"pm2:status": "node ./node_modules/pm2/bin/pm2 status","pm2:save": "node ./node_modules/pm2/bin/pm2 save","pm2:startup": "node ./node_modules/pm2/bin/pm2 startup",- "install:all": "git submodule update --init --recursive && npm install && npm install --prefix client && npm install --prefix server && npm install --prefix autofixer && node client/node_modules/esbuild/install.js && node server/node_modules/esbuild/install.js && npm rebuild node-pty --prefix server && npm run setup",+ "install:all": "npm run setup","migrations": "node scripts/run-migrations.js",- "setup": "node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-browser.js",+ "setup": "git submodule update --init --recursive && npm install && npm install --prefix client && npm install --prefix server && npm install --prefix autofixer && node client/node_modules/esbuild/install.js && node server/node_modules/esbuild/install.js && npm rebuild node-pty --prefix server && node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-browser.js","setup:data": "node scripts/setup-data.js","setup:db": "node scripts/setup-db.js","setup:browser": "node scripts/setup-browser.js",diff --git a/scripts/generate_win.py b/scripts/generate_win.pynew file mode 100644index 0000000000..8fb722cfad--- /dev/null+++ b/scripts/generate_win.py@@ -0,0 +1,144 @@+"""+Windows video generation backend using diffusers + LTX-Video-0.9.5.+Supports both text-to-video (T2V) and image-to-video (I2V).+Accepts the same-style CLI args as imagine_win.py; generate.js dispatches here on win32.+"""+import argparse+import os+import sys+import warnings++warnings.filterwarnings('ignore')+os.environ['XFORMERS_DISABLED'] = '1'+os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'python'++import torch+import numpy as np+import cv2+from PIL import Image++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def log(msg):+ print(msg, file=sys.stderr, flush=True)+++def progress_callback(pipe, step, timestep, callback_kwargs):+ total = pipe._num_timesteps+ pct = int((step + 1) / total * 100)+ bar = '█' * (pct // 5) + '▒' * (20 - pct // 5)+ log(f'{pct}%|{bar}| {step + 1}/{total}')+ return callback_kwargs+++def save_video(frames, path, fps):+ """Save a list of PIL images as an MP4 using cv2 (always available)."""+ if not frames:+ raise RuntimeError('No frames to save')+ w, h = frames[0].size+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')+ writer = cv2.VideoWriter(path, fourcc, float(fps), (w, h))+ if not writer.isOpened():+ raise RuntimeError(f'cv2.VideoWriter failed to open: {path}')+ for frame in frames:+ arr = np.array(frame.convert('RGB'))+ writer.write(arr[:, :, ::-1]) # RGB → BGR+ writer.release()+++# ---------------------------------------------------------------------------+# Main+# ---------------------------------------------------------------------------++LTX_MODEL_ID = 'Lightricks/LTX-Video-0.9.5-dev'++def main():+ p = argparse.ArgumentParser()+ p.add_argument('--model', default='ltx_video')+ p.add_argument('--prompt', required=True)+ p.add_argument('--negative-prompt', default='worst quality, inconsistent motion, blurry, jittery, distorted')+ p.add_argument('--height', type=int, default=512)+ p.add_argument('--width', type=int, default=768)+ p.add_argument('--num-frames', type=int, default=121)+ p.add_argument('--fps', type=int, default=24)+ p.add_argument('--steps', type=int, default=25)+ p.add_argument('--guidance', type=float, default=3.0)+ p.add_argument('--seed', type=int, default=None)+ p.add_argument('--output', required=True)+ p.add_argument('--image', default=None)+ args = p.parse_args()++ dtype = torch.bfloat16+ generator = torch.Generator('cuda').manual_seed(args.seed) if args.seed is not None else None++ os.makedirs(os.path.dirname(args.output), exist_ok=True)++ # LTX-Video requires num_frames == 8k + 1+ num_frames = args.num_frames+ if (num_frames - 1) % 8 != 0:+ num_frames = ((num_frames - 1) // 8) * 8 + 1+ log(f'STATUS:Adjusted frames to {num_frames} (LTX requires 8k+1)')++ neg = args.negative_prompt or 'worst quality, inconsistent motion, blurry, jittery, distorted'++ if args.image:+ from diffusers import LTXImageToVideoPipeline+ log('STATUS:Loading LTX-Video image-to-video pipeline...')+ log('STATUS:(First run auto-downloads ~9.5 GB — subsequent runs use cache)')+ pipe = LTXImageToVideoPipeline.from_pretrained(LTX_MODEL_ID, torch_dtype=dtype)+ pipe = pipe.to('cuda')+ pipe.enable_vae_tiling()++ src = Image.open(args.image).convert('RGB').resize(+ (args.width, args.height), Image.LANCZOS+ )+ log(f'STATUS:Generating video from image ({args.width}x{args.height}, {num_frames} frames, {args.steps} steps)...')+ result = pipe(+ image=src,+ prompt=args.prompt,+ negative_prompt=neg,+ height=args.height,+ width=args.width,+ num_frames=num_frames,+ num_inference_steps=args.steps,+ guidance_scale=args.guidance,+ decode_timestep=0.05,+ decode_noise_scale=0.025,+ generator=generator,+ callback_on_step_end=progress_callback,+ callback_on_step_end_tensor_inputs=['latents'],+ )+ else:+ from diffusers import LTXPipeline+ log('STATUS:Loading LTX-Video text-to-video pipeline...')+ log('STATUS:(First run auto-downloads ~9.5 GB — subsequent runs use cache)')+ pipe = LTXPipeline.from_pretrained(LTX_MODEL_ID, torch_dtype=dtype)+ pipe = pipe.to('cuda')+ pipe.enable_vae_tiling()++ log(f'STATUS:Generating video ({args.width}x{args.height}, {num_frames} frames, {args.steps} steps)...')+ result = pipe(+ prompt=args.prompt,+ negative_prompt=neg,+ height=args.height,+ width=args.width,+ num_frames=num_frames,+ num_inference_steps=args.steps,+ guidance_scale=args.guidance,+ decode_timestep=0.05,+ decode_noise_scale=0.025,+ generator=generator,+ callback_on_step_end=progress_callback,+ callback_on_step_end_tensor_inputs=['latents'],+ )++ log('STATUS:Saving video...')+ save_video(result.frames[0], args.output, args.fps)+ log(f'STATUS:Saved to {args.output}')+ log('STATUS:Done')+++if __name__ == '__main__':+ main()diff --git a/scripts/imagine_win.py b/scripts/imagine_win.pynew file mode 100644index 0000000000..d256e9e5d7--- /dev/null+++ b/scripts/imagine_win.py@@ -0,0 +1,207 @@+"""+Windows image generation backend using diffusers + local Flux model files.+Accepts the same CLI args as mflux-generate so imagine.js needs no change.+"""+import argparse+import json+import os+import sys+import warnings++warnings.filterwarnings('ignore')+os.environ['XFORMERS_DISABLED'] = '1'+# Avoid protobuf descriptor crash when converting T5 slow tokenizer+os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'python'++import torch+from diffusers import AutoencoderKL, FluxPipeline, FluxTransformer2DModel+from diffusers.schedulers import FlowMatchEulerDiscreteScheduler+from safetensors.torch import load_file+from transformers import (+ CLIPTextConfig, CLIPTextModel, CLIPTokenizer,+ T5Config, T5EncoderModel, T5TokenizerFast,+)++# ---------------------------------------------------------------------------+# Paths+# ---------------------------------------------------------------------------+DOWNLOADS = os.path.join(os.path.expanduser('~'), 'Downloads')+HF_FLUX_CACHE = None # resolved at runtime++FLUX_FILES = {+ 'schnell': os.path.join(DOWNLOADS, 'flux1-schnell-fp8.safetensors'),+ 'dev': os.path.join(DOWNLOADS, 'flux1-dev-fp8.safetensors'),+}+VAE_FILE = os.path.join(DOWNLOADS, 'ae.safetensors')+CLIP_FILE = os.path.join(DOWNLOADS, 'clip_l.safetensors')+T5_FILE = os.path.join(DOWNLOADS, 't5xxl_fp16.safetensors')++MODEL_ID_MAP = {+ 'schnell': 'schnell',+ 'flux2-klein-4b': 'schnell',+ 'flux2-klein-9b': 'dev',+ 'dev': 'dev',+}++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def log(msg):+ print(msg, file=sys.stderr, flush=True)+++def find_flux_hf_cache():+ """Return the local snapshot dir for FLUX.1-schnell configs."""+ hub = os.path.join(os.path.expanduser('~'), '.cache', 'huggingface', 'hub')+ snap_root = os.path.join(hub, 'models--black-forest-labs--FLUX.1-schnell', 'snapshots')+ if not os.path.isdir(snap_root):+ return None+ snaps = sorted(os.listdir(snap_root))+ return os.path.join(snap_root, snaps[-1]) if snaps else None+++def progress_callback(pipe, step, timestep, callback_kwargs):+ total = pipe._num_timesteps+ pct = int((step + 1) / total * 100)+ bar = '█' * (pct // 5) + '▒' * (20 - pct // 5)+ log(f'{pct}%|{bar}| {step + 1}/{total}')+ return callback_kwargs+++def build_pipeline(flux_key, hf_cache, dtype):+ log(f'STATUS:Loading tokenizers...')+ tokenizer = CLIPTokenizer.from_pretrained(hf_cache, subfolder='tokenizer')+ # Load T5 fast tokenizer from pre-built tokenizer.json to avoid protobuf/spiece issues+ t2_tok_file = os.path.join(hf_cache, 'tokenizer_2', 'tokenizer.json')+ tokenizer_2 = T5TokenizerFast(+ tokenizer_file=t2_tok_file,+ model_max_length=512,+ legacy=False,+ )+ scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(hf_cache, subfolder='scheduler')++ log('STATUS:Loading CLIP text encoder...')+ clip_cfg = CLIPTextConfig.from_pretrained(os.path.join(hf_cache, 'text_encoder'))+ text_encoder = CLIPTextModel(clip_cfg)+ text_encoder.load_state_dict(load_file(CLIP_FILE), strict=False)+ # CLIP is small (~0.5 GB) — keep on CUDA so the pipeline's _execution_device resolves to CUDA+ text_encoder = text_encoder.to(dtype).to('cuda')++ log('STATUS:Loading T5 text encoder (CPU)...')+ t5_cfg = T5Config.from_pretrained(os.path.join(hf_cache, 'text_encoder_2'))+ text_encoder_2 = T5EncoderModel(t5_cfg)+ text_encoder_2.load_state_dict(load_file(T5_FILE), strict=False)+ # T5 stays on CPU to save ~4 GB of VRAM for the transformer.+ # Register a pre-hook that moves any CUDA inputs back to CPU so the+ # pipeline's .to(execution_device) call doesn't cause a device mismatch.+ text_encoder_2 = text_encoder_2.to(dtype)+ def _cpu_input_hook(module, args, kwargs):+ args = tuple(x.cpu() if isinstance(x, torch.Tensor) else x for x in args)+ kwargs = {k: v.cpu() if isinstance(v, torch.Tensor) else v for k, v in kwargs.items()}+ return args, kwargs+ text_encoder_2.register_forward_pre_hook(_cpu_input_hook, with_kwargs=True)++ log('STATUS:Loading VAE...')+ vae = AutoencoderKL.from_single_file(+ VAE_FILE, config=hf_cache, subfolder='vae', torch_dtype=dtype+ ).to('cuda')++ log(f'STATUS:Loading Flux transformer ({flux_key})...')+ transformer = FluxTransformer2DModel.from_single_file(+ FLUX_FILES[flux_key], torch_dtype=dtype+ ).to('cuda')++ log('STATUS:Assembling pipeline...')+ pipe = FluxPipeline(+ scheduler=scheduler,+ text_encoder=text_encoder,+ tokenizer=tokenizer,+ text_encoder_2=text_encoder_2,+ tokenizer_2=tokenizer_2,+ vae=vae,+ transformer=transformer,+ )+ # Reduces activation peak memory so the 22GB transformer has breathing room+ pipe.enable_attention_slicing()+ return pipe+++# ---------------------------------------------------------------------------+# Main+# ---------------------------------------------------------------------------++def main():+ p = argparse.ArgumentParser()+ p.add_argument('--model', default='schnell')+ p.add_argument('--prompt', required=True)+ p.add_argument('--negative-prompt', default='')+ p.add_argument('--height', type=int, default=1024)+ p.add_argument('--width', type=int, default=1024)+ p.add_argument('--steps', type=int, default=4)+ p.add_argument('--seed', type=int, default=None)+ p.add_argument('--guidance', type=float, default=0.0)+ p.add_argument('--quantize', type=int, default=8) # ignored on Windows+ p.add_argument('--output', required=True)+ p.add_argument('--metadata', action='store_true')+ p.add_argument('--lora-paths', nargs='*', default=[])+ p.add_argument('--lora-scales', nargs='*', type=float, default=[])+ args = p.parse_args()++ flux_key = MODEL_ID_MAP.get(args.model, 'schnell')+ dtype = torch.bfloat16++ hf_cache = find_flux_hf_cache()+ if not hf_cache:+ log('ERROR: Flux config cache not found. Run the app Settings page first.')+ sys.exit(1)++ for label, path in [('Flux model', FLUX_FILES[flux_key]), ('VAE', VAE_FILE),+ ('CLIP', CLIP_FILE), ('T5', T5_FILE)]:+ if not os.path.exists(path):+ log(f'ERROR: {label} file not found: {path}')+ sys.exit(1)++ generator = torch.Generator('cuda').manual_seed(args.seed) if args.seed is not None else None++ pipe = build_pipeline(flux_key, hf_cache, dtype)++ log(f'STATUS:Generating image ({args.width}x{args.height}, {args.steps} steps)...')++ result = pipe(+ prompt=args.prompt,+ negative_prompt=args.negative_prompt or None,+ height=args.height,+ width=args.width,+ num_inference_steps=args.steps,+ guidance_scale=args.guidance if args.guidance > 0 else 0.0,+ generator=generator,+ callback_on_step_end=progress_callback,+ callback_on_step_end_tensor_inputs=['latents'],+ )++ image = result.images[0]+ os.makedirs(os.path.dirname(args.output), exist_ok=True)+ image.save(args.output)+ log(f'STATUS:Saved to {args.output}')++ if args.metadata:+ meta = {+ 'model': args.model,+ 'prompt': args.prompt,+ 'negative_prompt': args.negative_prompt,+ 'height': args.height,+ 'width': args.width,+ 'steps': args.steps,+ 'seed': args.seed,+ 'guidance': args.guidance,+ }+ meta_path = args.output.replace('.png', '.metadata.json')+ with open(meta_path, 'w') as f:+ json.dump(meta, f, indent=2)++ log('STATUS:Done')+++if __name__ == '__main__':+ main()diff --git a/scripts/open-ui-in-browser.js b/scripts/open-ui-in-browser.jsnew file mode 100644index 0000000000..a645fc7895--- /dev/null+++ b/scripts/open-ui-in-browser.js@@ -0,0 +1,105 @@+#!/usr/bin/env node+// Open the PortOS dashboard in the PortOS-managed Chrome instance.+// Used after setup.sh / update.sh / update.ps1 finish PM2 boot so the user+// lands on the dashboard without having to manually open a tab.+//+// Fail-soft: every failure path logs and exits 0 — never break setup/update+// because Chrome happens to be unreachable.+import { existsSync } from 'node:fs';+import { join, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));+const CERT_PATH = join(ROOT, 'data', 'certs', 'cert.pem');+const KEY_PATH = join(ROOT, 'data', 'certs', 'key.pem');+const API_PORT = Number(process.env.PORT) || 5555;+const HTTP_LOOPBACK_PORT = Number(process.env.PORTOS_HTTP_PORT) || 5553;+// The server only enables HTTPS when BOTH cert and key exist (matches+// lib/tailscale-https.js loadCert) — checking only cert.pem would falsely+// route to the loopback mirror during a half-finished setup:cert.+const HTTPS_MODE = existsSync(CERT_PATH) && existsSync(KEY_PATH);++// When HTTPS is on, :5555 speaks TLS only — plain http:// requests hit a TLS+// mismatch and time out. The loopback HTTP mirror on :5553 serves the same+// app and skips the cert warning. We use it for both polling and the URL+// handed to the browser. See docs/PORTS.md.+const LOCAL_BASE = HTTPS_MODE+ ? `http://localhost:${HTTP_LOOPBACK_PORT}`+ : `http://localhost:${API_PORT}`;+const TARGET_URL = LOCAL_BASE;++// First-boot startup can take a while: the server binds, opens the DB pool,+// loads the brain index, attaches Socket.IO, then health responds. 90s is+// roomy for a fresh checkout on slow disks; if PortOS still isn't up, the+// user has bigger problems than the auto-open script.+const API_TIMEOUT_MS = 90_000;+const BROWSER_TIMEOUT_MS = 15_000;+const POLL_INTERVAL_MS = 500;++async function poll(checkFn, label, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (await checkFn()) return true;+ await new Promise(r => setTimeout(r, POLL_INTERVAL_MS));+ }+ console.warn(`⚠️ ${label} didn't respond within ${timeoutMs / 1000}s — skipping auto-open. Check \`pm2 logs portos-server\` for startup errors.`);+ return false;+}++async function ping(url) {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 1500);+ const ok = await fetch(url, { signal: controller.signal })+ .then(r => r.ok)+ .catch(() => false);+ clearTimeout(timeout);+ return ok;+}++const apiHealthUrl = `${LOCAL_BASE}/api/system/health`;+const browserHealthUrl = `${LOCAL_BASE}/api/browser/health`;+const navigateUrl = `${LOCAL_BASE}/api/browser/navigate`;++const apiReady = await poll(() => ping(apiHealthUrl), 'PortOS API', API_TIMEOUT_MS);+if (!apiReady) process.exit(0);++// Browser process may take a few seconds longer than the API to reach Chrome.+// We don't gate strictly on it — even if the health endpoint says "unhealthy"+// we still POST navigate, which will trigger a launch via the route handler+// when CDP isn't yet up. The poll just gives Chrome a head start.+await poll(async () => {+ // Use the same per-request AbortController guard that ping() uses — without+ // a timeout, a hung TCP connection (accepted but never responds) would let+ // a single fetch await forever and ignore BROWSER_TIMEOUT_MS entirely.+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), 1500);+ const res = await fetch(browserHealthUrl, { signal: controller.signal }).catch(() => null);+ clearTimeout(timer);+ if (!res?.ok) return false;+ const json = await res.json().catch(() => null);+ return json?.connected === true;+}, 'PortOS browser CDP', BROWSER_TIMEOUT_MS);++// 5s navigate timeout — without this, a hung accept-without-response would+// stall setup.sh / update.* indefinitely even though this step is fail-soft.+const navController = new AbortController();+const navTimer = setTimeout(() => navController.abort(), 5000);+const res = await fetch(navigateUrl, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ url: TARGET_URL }),+ signal: navController.signal,+}).catch(err => {+ console.warn(`⚠️ Could not reach navigate endpoint: ${err.message}`);+ return null;+});+clearTimeout(navTimer);++if (!res) process.exit(0);+if (!res.ok) {+ const text = await res.text().catch(() => '');+ console.warn(`⚠️ Navigate failed (HTTP ${res.status}): ${text.slice(0, 200)}`);+ process.exit(0);+}++console.log(`🌐 Opened ${TARGET_URL} in PortOS browser`);diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.shnew file mode 100755index 0000000000..bcd740525f--- /dev/null+++ b/scripts/setup-image-video.sh@@ -0,0 +1,81 @@+#!/usr/bin/env bash+# Bootstrap local image + video generation stack (mflux on Apple Silicon,+# diffusers on Windows). Optional — only needed if you want PortOS to render+# images/videos locally instead of (or in addition to) talking to an external+# AUTOMATIC1111 server. Models are downloaded on first use into HF's standard+# cache (~/.cache/huggingface) and surfaced in the PortOS Models manager.+#+# Env overrides:+# PYTHON_BIN Python 3 binary to use (default: python3)+# PORTOS_DATA Path to PortOS data dir (default: ./data, resolved from $REPO_ROOT)+# INSTALL_VIDEO '1' to also install mlx_video for LTX video generation (default: 1 on macOS, 0 on Windows)++set -euo pipefail++PYTHON_BIN="${PYTHON_BIN:-python3}"+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"+PORTOS_DATA="${PORTOS_DATA:-${REPO_ROOT}/data}"++have() { command -v "$1" >/dev/null 2>&1; }+is_macos() { [[ "$(uname -s)" == "Darwin" ]]; }++if ! have "$PYTHON_BIN"; then+ echo "❌ $PYTHON_BIN not found. Install Python 3.10+ first." >&2+ exit 1+fi++mkdir -p "${PORTOS_DATA}/loras"+mkdir -p "${PORTOS_DATA}/videos"+mkdir -p "${PORTOS_DATA}/video-thumbnails"++INSTALL_VIDEO="${INSTALL_VIDEO:-$(is_macos && echo 1 || echo 0)}"++# Install via pip --user so we don't pollute the system or require a venv.+# mflux comes with the mflux-generate CLI which the local image backend+# spawns directly. transformers<5 is required for MLX compatibility.+echo "📦 Installing image generation packages (mflux + deps)..."+"$PYTHON_BIN" -m pip install --upgrade --user \+ mflux \+ "transformers<5" \+ safetensors \+ huggingface_hub \+ numpy \+ opencv-python \+ tqdm++if [[ "$INSTALL_VIDEO" == "1" ]]; then+ if is_macos; then+ echo "📦 Installing video generation packages (mlx_video + mlx_vlm)..."+ "$PYTHON_BIN" -m pip install --upgrade --user \+ mlx \+ mlx_vlm \+ mlx_video+ else+ echo "📦 Installing video generation packages (diffusers + torch)..."+ "$PYTHON_BIN" -m pip install --upgrade --user \+ torch \+ diffusers \+ accelerate+ fi+fi++# ffmpeg — required for thumbnails, last-frame extraction, and stitch.+if ! have ffmpeg; then+ if is_macos && have brew; then+ echo "📦 brew install ffmpeg"+ brew install ffmpeg+ else+ echo "⚠️ ffmpeg not on PATH and could not auto-install — install ffmpeg yourself for video features."+ fi+fi++PYTHON_PATH="$(command -v "$PYTHON_BIN")"+echo ""+echo "✅ Image/video stack ready."+echo " Python: $PYTHON_PATH"+echo " HF cache: ~/.cache/huggingface (HF default)"+echo " LoRAs: ${PORTOS_DATA}/loras"+echo " Videos: ${PORTOS_DATA}/videos"+echo ""+echo "Set this Python path in PortOS Settings → Image Gen → Local."diff --git a/server/index.js b/server/index.jsindex e3b70a1cca..a16ffc6cfb 100644--- a/server/index.js+++ b/server/index.js@@ -7,6 +7,7 @@ import { PORTS } from './lib/ports.js';import { existsSync } from 'fs';import { readFile, unlink } from 'fs/promises';import { createTailscaleServers } from '../lib/tailscale-https.js';+import { getSelfHost } from './lib/peerSelfHost.js';import alertsRoutes from './routes/alerts.js';import appleHealthRoutes from './routes/appleHealth.js';@@ -77,6 +78,9 @@ import loopsRoutes from './routes/loops.js';import characterRoutes from './routes/character.js';import toolsRoutes from './routes/tools.js';import imageGenRoutes from './routes/imageGen.js';+import videoGenRoutes from './routes/videoGen.js';+import imageVideoModelsRoutes from './routes/imageVideoModels.js';+import sdapiRoutes from './routes/sdapi.js';import openclawRoutes from './routes/openclaw.js';import askRoutes from './routes/ask.js';import { ensureSelf, startPolling } from './services/instances.js';@@ -303,6 +307,11 @@ app.use('/api/loops', loopsRoutes);app.use('/api/character', characterRoutes);app.use('/api/tools', toolsRoutes);app.use('/api/image-gen', imageGenRoutes);+app.use('/api/video-gen', videoGenRoutes);+app.use('/api/image-video/models', imageVideoModelsRoutes);+// AUTOMATIC1111-compatible surface for tailnet clients — gated by+// settings.imageGen.expose.a1111 so it returns 403 unless the user opted in.+app.use('/sdapi/v1', sdapiRoutes);app.use('/api/openclaw', openclawRoutes);app.use('/api/ask', askRoutes);@@ -388,6 +397,10 @@ restoreLoops().catch(err => console.error(`❌ Loop restore failed: ${err.messag// Serve generated images from configured images directoryapp.use('/data/images', express.static(PATHS.images));+// Serve generated videos + thumbnails so the Media UI and tailnet clients+// can pull them by URL without going through an explicit download route.+app.use('/data/videos', express.static(PATHS.videos));+app.use('/data/video-thumbnails', express.static(PATHS.videoThumbnails));// Serve built client UI (production mode — no Vite dev server needed)const CLIENT_DIST = join(__dirname, '..', 'client', 'dist');@@ -423,23 +436,28 @@ ensureSelf().then(() => {// Start server only after sync log is initializedhttpServer.listen(PORT, HOST, () => {- console.log(`🚀 PortOS server running at ${scheme}://${HOST}:${PORT}`);- if (!httpsEnabled) {- console.log(`⚠️ HTTP only — getUserMedia (mic) will not work over Tailscale IP. Run "npm run setup:cert" to enable HTTPS.`);- } else {+ // One canonical "where do I open this" banner — :5555 is always user-facing+ // (HTTP or HTTPS), :PORTOS_HTTP_PORT (default 5553) is the loopback HTTP+ // mirror that only spawns when HTTPS is active. See docs/PORTS.md.+ console.log(`🚀 PortOS listening on :${PORT} (${scheme})`);+ if (httpsEnabled) {+ const selfHost = getSelfHost();+ if (selfHost) console.log(` ✅ https://${selfHost}:${PORT} (trusted via Tailscale)`);+ console.log(` 🔐 https://<tailscale-ip>:${PORT} (cert warning unless using the hostname above)`);initCertRenewer(httpServer);- // Loopback-HTTP mirror (created by createTailscaleServers) — attach- // Socket.IO to the same instance so websocket events are identical.const localHttpPort = Number(process.env.PORTOS_HTTP_PORT) || PORTS.API_LOCAL;if (localHttpServer) {io.attach(localHttpServer);localHttpServer.listen(localHttpPort, '127.0.0.1', () => {- console.log(`🔓 Local HTTP also at http://localhost:${localHttpPort} (loopback only, no cert warnings)`);+ console.log(` 🔓 http://localhost:${localHttpPort} (loopback HTTP mirror, no cert warnings)`);});localHttpServer.on('error', (err) => {- console.warn(`⚠️ Local HTTP fallback on :${localHttpPort} failed: ${err.message} — Tailscale HTTPS still active`);+ console.warn(`⚠️ Loopback HTTP mirror on :${localHttpPort} failed: ${err.message} — HTTPS still active`);});}+ } else {+ console.log(` 🌐 http://localhost:${PORT}`);+ console.log(`⚠️ HTTP only — getUserMedia (mic) won't work over Tailscale IP. Run "npm run setup:cert" to enable HTTPS.`);}// Set up process error handlers with io instancediff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 260084c6a2..c6b421c21e 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -6,10 +6,15 @@import { mkdir, readFile, writeFile, rename, unlink } from 'fs/promises';import { existsSync } from 'fs';+import { execFile } from 'child_process';+import { promisify } from 'util';import { randomUUID } from 'crypto';import { join, dirname } from 'path';import { fileURLToPath } from 'url';+const execFileAsync = promisify(execFile);+const IS_WIN = process.platform === 'win32';+// Cache __dirname calculation for services importing this moduleconst __lib_filename = fileURLToPath(import.meta.url);const __lib_dirname = dirname(__lib_filename);@@ -57,6 +62,9 @@ export const PATHS = {missions: join(__lib_dirname, '../../data/cos/missions'),tools: join(__lib_dirname, '../../data/tools'),images: join(__lib_dirname, '../../data/images'),+ loras: join(__lib_dirname, '../../data/loras'),+ videos: join(__lib_dirname, '../../data/videos'),+ videoThumbnails: join(__lib_dirname, '../../data/video-thumbnails'),slashdo: join(__lib_dirname, '../../lib/slashdo')};@@ -494,3 +502,40 @@ export async function loadSlashdoFile(commandName, { stripFrontmatter = false }}return content;}++export function formatBytes(bytes) {+ if (!bytes) return '0 B';+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];+ const i = Math.floor(Math.log(bytes) / Math.log(1024));+ return (bytes / Math.pow(1024, i)).toFixed(i > 1 ? 1 : 0) + ' ' + units[i];+}++// Size in bytes of every file under `path`. Shells out to `du -sk` (or+// PowerShell on Windows) — orders of magnitude faster than walking with+// node's recursive readdir on large trees (hundreds of GB / 200k+ files).+// Returns 0 + logs on failure (missing tool, permission denied, timeout) so+// the Media Models endpoint stays responsive even on unusual systems instead+// of throwing and 500ing the whole route.+export async function dirSize(path) {+ if (!existsSync(path)) return 0;+ if (IS_WIN) {+ // Pass the path via an env var so a literal apostrophe in the path can't+ // close the PowerShell string and inject commands.+ const result = await execFileAsync('powershell', [+ '-NoProfile', '-Command',+ '(Get-ChildItem -Recurse -File $Env:DIRSIZE_TARGET | Measure-Object -Property Length -Sum).Sum',+ ], { encoding: 'utf8', timeout: 60_000, env: { ...process.env, DIRSIZE_TARGET: path } }).catch((err) => ({ error: err }));+ if (result.error) {+ console.log(`⚠️ dirSize(${path}) failed: ${result.error.message}`);+ return 0;+ }+ return parseInt(result.stdout.trim(), 10) || 0;+ }+ const result = await execFileAsync('du', ['-sk', path], { encoding: 'utf8', timeout: 60_000 }).catch((err) => ({ error: err }));+ if (result.error) {+ console.log(`⚠️ dirSize(${path}) failed: ${result.error.message}`);+ return 0;+ }+ const kb = parseInt(result.stdout.split('\t')[0], 10) || 0;+ return kb * 1024;+}diff --git a/server/lib/httpClient.js b/server/lib/httpClient.jsindex 377521b5fd..bc9e0226b7 100644--- a/server/lib/httpClient.js+++ b/server/lib/httpClient.js@@ -6,7 +6,7 @@import https from 'https';// Wraps https.request as fetch-compatible for self-signed cert support-function insecureFetch(agent) {+export function insecureFetch(agent) {return async (url, { method = 'GET', headers = {}, body, signal } = {}) => {const u = new URL(url);return new Promise((resolve, reject) => {diff --git a/server/lib/multipart.js b/server/lib/multipart.jsindex c254131c41..046a002edf 100644--- a/server/lib/multipart.js+++ b/server/lib/multipart.js@@ -1,12 +1,20 @@/*** Streaming multipart/form-data parser — multer.diskStorage() replacement.- * Streams file content directly to disk; never buffers entire body in memory.*- * Returns an Express middleware for a single file field.- * Populates req.file with { path, originalname, mimetype, size }.+ * True streaming: file content is written to disk in chunks as it arrives,+ * never buffered in memory. Text fields are buffered (small by definition).+ * Boundary detection keeps a small lookback (boundary length) between+ * chunks so a boundary spanning a chunk edge isn't missed.+ *+ * Returns an Express middleware. Populates:+ * - req.body[name] — for text parts (Content-Disposition has no filename)+ * - req.file = { path, originalname, mimetype, size } — for the matching+ * file part (Content-Disposition has filename and name === fieldName).+ * Other file parts (different field names) are silently skipped.*/import { createWriteStream } from 'fs';+import { unlink } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';import { randomUUID } from 'crypto';@@ -16,110 +24,323 @@ export function uploadSingle(fieldName, { limits = {}, fileFilter } = {}) {return (req, res, next) => {const ct = req.headers['content-type'] || '';- if (!ct.startsWith('multipart/form-data')) return next(new Error('Expected multipart/form-data'));+ if (!ct.startsWith('multipart/form-data')) {+ const err = new Error('Expected multipart/form-data');+ err.status = 400; err.code = 'INVALID_CONTENT_TYPE';+ return next(err);+ }const bm = ct.match(/boundary=([^\s;]+)/);- if (!bm) return next(new Error('Missing multipart boundary'));- parseStream(req, bm[1], fieldName, maxSize, fileFilter, next);+ if (!bm) {+ const err = new Error('Missing multipart boundary');+ err.status = 400; err.code = 'INVALID_CONTENT_TYPE';+ return next(err);+ }+ streamMultipart(req, bm[1], fieldName, maxSize, fileFilter, next);};}-function parseStream(stream, boundary, fieldName, maxSize, fileFilter, next) {- const END_MARKER = Buffer.from('\r\n--' + boundary);+function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, next) {+ const PART_DELIM = Buffer.from('\r\n--' + boundary);+ const FIRST_DELIM = Buffer.from('--' + boundary);const HEADER_END = Buffer.from('\r\n\r\n');- let buf = Buffer.alloc(0); // lookahead buffer while streaming file content- let ws = null; // WriteStream for current file- let filePath = null;- let fileMeta = null;- let fileSize = 0;- let streaming = false; // true once past headers, writing file bytes+ const STATE_PREAMBLE = 0; // before first boundary+ const STATE_HEADERS = 1; // accumulating part headers+ const STATE_BODY = 2; // streaming part body (text or file)+ const STATE_AFTER_BOUNDARY = 3; // just past a boundary; expect CRLF or `--`+ const STATE_DONE = 4;++ let state = STATE_PREAMBLE;+ let buf = Buffer.alloc(0);let done = false;+ let pendingFlush = 0; // outstanding async ws.end callbacks+ let endSeen = false; // 'end' event fired but we may still be flushing+ let textCharCount = 0;+ const TEXT_FIELD_TOTAL_CAP = 1024 * 1024; // 1MB cap on aggregate text fields++ // Per-part state+ let currentName = null;+ let currentFilename = null;+ let isMatchingFile = false; // true when current part is the file we want+ let writeStream = null;+ let writePath = null;+ let bytesWritten = 0;+ let textBuf = null; // Buffer when current part is a text field- // Header accumulation: keep prior chunks + a spillover window to detect \r\n\r\n across boundaries- const headerChunks = [];- let headerSpill = Buffer.alloc(0); // last (HEADER_END.length - 1) bytes from previous chunk+ const body = {};+ let fileResult = null;const fail = (err) => {- if (!done) { done = true; if (ws) ws.destroy(); next(err); }+ if (done) return;+ done = true;+ state = STATE_DONE;+ if (writeStream) {+ writeStream.destroy();+ // Best-effort cleanup of the partially-written file.+ if (writePath) unlink(writePath).catch(() => {});+ }+ req.removeAllListeners('data');+ next(err);};- const writeChunk = (chunk) => {+ const finish = () => {if (done) return;- const combined = buf.length ? Buffer.concat([buf, chunk]) : chunk;- const idx = combined.indexOf(END_MARKER);- if (idx !== -1) {- const tail = combined.slice(0, idx);- fileSize += tail.length;- if (fileSize > maxSize) return fail(new Error(`File too large (max ${maxSize} bytes)`));- ws.end(tail);- ws.once('finish', () => {- if (!done) {- done = true;- stream.file = { path: filePath, ...fileMeta, size: fileSize };- next();+ // If 'end' fires before we hit the terminal `--<boundary>--`, the+ // request is truncated/malformed — reject with 400 instead of silently+ // accepting a partial upload (could matter for a 2GB Apple Health+ // import that gets cut off mid-stream).+ if (state !== STATE_DONE) {+ // Clean up any partially-written file before failing.+ if (writeStream) writeStream.destroy();+ if (writePath) unlink(writePath).catch(() => {});+ // Also drop the in-progress fileResult if endPart already finalized+ // a file from a part that was followed by truncated data.+ if (fileResult?.path) unlink(fileResult.path).catch(() => {});+ done = true;+ const err = new Error('Truncated multipart request — never reached terminal boundary');+ err.code = 'INVALID_MULTIPART';+ err.status = 400;+ next(err);+ return;+ }+ done = true;+ req.body = body;+ if (fileResult) req.file = fileResult;+ next();+ };++ // Start a new part — parse headers, set up text buffer or file write stream.+ const startPart = (headerBlock) => {+ // Reset per-part state so a part with no Content-Type can't inherit+ // the previous part's mimetype, and stale flags don't carry over.+ currentName = null;+ currentFilename = null;+ currentFileMimetype = null;+ isMatchingFile = false;+ textBuf = null;+ const headerStr = headerBlock.toString('utf-8');+ // Negative lookbehind keeps `name=` inside `filename=` from matching.+ const nameMatch = headerStr.match(/(?<!file)name="([^"]+)"/i);+ if (!nameMatch) return fail(new Error('Multipart part missing Content-Disposition name'));+ currentName = nameMatch[1];+ const filenameMatch = headerStr.match(/filename="([^"]*)"/i);+ currentFilename = filenameMatch?.[1];++ if (currentFilename != null && currentFilename !== '') {+ isMatchingFile = currentName === fileFieldName;+ const mimeMatch = headerStr.match(/Content-Type:\s*([^\r\n]+)/i);+ currentFileMimetype = mimeMatch ? mimeMatch[1].trim() : 'application/octet-stream';+ if (isMatchingFile) {+ const fileMeta = { originalname: currentFilename, mimetype: currentFileMimetype };++ if (fileFilter) {+ // CONTRACT: fileFilter MUST call its `cb` synchronously. We read+ // `fr` immediately because the parser is consuming a streaming+ // body and can't pause headers indefinitely without buffering+ // unbounded bytes for the next part. (multer's docs allow async+ // filters, but in this codebase all callers — appleHealth.js+ // and videoGen.js — are sync. We surface a clear error if a+ // future async filter slips in instead of crashing on `fr.err`+ // dereference.)+ let fr = null;+ fileFilter(req, fileMeta, (err, accept) => { fr = { err, accept }; });+ if (fr === null) {+ const err = new Error('fileFilter must invoke its callback synchronously');+ err.status = 500; err.code = 'INVALID_FILE_FILTER';+ return fail(err);+ }+ if (fr.err) return fail(fr.err);+ if (!fr.accept) {+ // Set status/code so the centralized error middleware returns a+ // 400 to the client instead of a 500 (the err thrown by the+ // filter rejection is a client-input error, not a server bug).+ const rejectErr = new Error('File type not allowed');+ rejectErr.status = 400;+ rejectErr.code = 'INVALID_FILE_TYPE';+ return fail(rejectErr);+ }+ }++ const rawExt = currentFilename.match(/\.[^.]+$/)?.[0] || '';+ const ext = rawExt.replace(/[^a-zA-Z0-9.]/g, '');+ writePath = join(tmpdir(), `upload-${randomUUID()}${ext}`);+ writeStream = createWriteStream(writePath);+ writeStream.on('error', fail);+ bytesWritten = 0;+ }+ // Non-matching file part: no buffer, no stream — bytes are silently+ // discarded as the body advances past them.+ } else {+ textBuf = Buffer.alloc(0);+ }+ };++ // Emit `chunk` to the current part's destination (file write or text buffer+ // or the void). Enforces maxSize for the matching file and the global+ // text-field cap. Returns true to keep streaming, false on error/abort.+ const writePartChunk = (chunk) => {+ if (chunk.length === 0) return true;+ if (currentFilename != null && currentFilename !== '') {+ if (isMatchingFile) {+ bytesWritten += chunk.length;+ if (bytesWritten > maxSize) {+ const err = new Error(`File too large (max ${maxSize} bytes)`);+ err.status = 413; err.code = 'PAYLOAD_TOO_LARGE';+ fail(err);+ return false;+ }+ if (!writeStream.write(chunk)) {+ // Backpressure: pause the request stream and resume on drain.+ req.pause();+ writeStream.once('drain', () => req.resume());}- });- buf = Buffer.alloc(0);+ }+ // Non-matching file: drop bytes silently.} else {- // Keep last END_MARKER.length-1 bytes buffered (boundary may span chunks)- const safe = combined.length - (END_MARKER.length - 1);- if (safe > 0) {- fileSize += safe;- if (fileSize > maxSize) return fail(new Error(`File too large (max ${maxSize} bytes)`));- ws.write(combined.slice(0, safe));- buf = combined.slice(safe);+ textCharCount += chunk.length;+ if (textCharCount > TEXT_FIELD_TOTAL_CAP) {+ const err = new Error(`Text fields too large (max ${TEXT_FIELD_TOTAL_CAP} bytes)`);+ err.status = 413; err.code = 'PAYLOAD_TOO_LARGE';+ fail(err);+ return false;+ }+ textBuf = Buffer.concat([textBuf, chunk]);+ }+ return true;+ };++ // Finalize the current part — flush any pending data, then move on.+ const endPart = (cb) => {+ if (currentFilename != null && currentFilename !== '') {+ if (isMatchingFile && writeStream) {+ const ws = writeStream;+ const path = writePath;+ const size = bytesWritten;+ const filename = currentFilename;+ const mimetype = currentFileMimetype || 'application/octet-stream';+ writeStream = null;+ writePath = null;+ pendingFlush += 1;+ ws.end(() => {+ fileResult = { path, originalname: filename, mimetype, size };+ pendingFlush -= 1;+ cb();+ // If 'end' arrived while we were still flushing, finalize now.+ if (endSeen && pendingFlush === 0 && !done) finish();+ });+ } else {+ cb();+ }+ } else if (textBuf != null) {+ const value = textBuf.toString('utf-8');+ if (Object.prototype.hasOwnProperty.call(body, currentName)) {+ if (Array.isArray(body[currentName])) body[currentName].push(value);+ else body[currentName] = [body[currentName], value];} else {- buf = combined;+ body[currentName] = value;}+ textBuf = null;+ cb();+ } else {+ cb();}};- stream.on('data', (chunk) => {+ // Captured by startPart so endPart's async cb has the right mimetype even+ // after the next part may have started.+ let currentFileMimetype = null;++ const tick = () => {if (done) return;- if (streaming) return writeChunk(chunk);-- // Search for \r\n\r\n only in the window of spillover + new chunk (O(n) per chunk)- const window = headerSpill.length ? Buffer.concat([headerSpill, chunk]) : chunk;- const hEnd = window.indexOf(HEADER_END);- if (hEnd === -1) {- headerChunks.push(chunk);- // Keep last (HEADER_END.length - 1) bytes as spillover for next chunk- headerSpill = window.length >= HEADER_END.length- ? window.slice(window.length - (HEADER_END.length - 1))- : window;- return;- }- // Headers found — reconstruct full header block from prior chunks + window up to hEnd- const fullHeader = Buffer.concat([...headerChunks, window.slice(0, hEnd)]);- const headerStr = fullHeader.toString('utf-8');- const dispMatch = headerStr.match(/Content-Disposition:[^\r\n]*name="([^"]+)"[^\r\n]*filename="([^"]+)"/i);- if (!dispMatch || dispMatch[1] !== fieldName) return fail(new Error(`Expected field "${fieldName}"`));-- const originalname = dispMatch[2];- const mimeMatch = headerStr.match(/Content-Type:\s*([^\r\n]+)/i);- const mimetype = mimeMatch ? mimeMatch[1].trim() : 'application/octet-stream';- const rawExt = originalname.match(/\.[^.]+$/)?.[0] || '';- const ext = rawExt.replace(/[^a-zA-Z0-9.]/g, '');- fileMeta = { originalname, mimetype };-- if (fileFilter) {- let fr = null;- fileFilter(null, fileMeta, (err, accept) => { fr = { err, accept }; });- if (fr.err) return fail(fr.err);- if (!fr.accept) return fail(new Error('File type not allowed'));+ while (true) {+ if (state === STATE_PREAMBLE) {+ const idx = buf.indexOf(FIRST_DELIM);+ if (idx === -1) {+ // Need more bytes; drop everything past the last possible boundary start.+ const safe = buf.length - (FIRST_DELIM.length - 1);+ if (safe > 0) buf = buf.slice(safe);+ return;+ }+ buf = buf.slice(idx + FIRST_DELIM.length);+ state = STATE_AFTER_BOUNDARY;+ continue;+ }++ if (state === STATE_AFTER_BOUNDARY) {+ if (buf.length < 2) return;+ const trailing = buf.slice(0, 2);+ if (trailing[0] === 0x2d && trailing[1] === 0x2d) { // `--`+ buf = Buffer.alloc(0);+ // Mark clean termination so finish() can distinguish a proper+ // end from a truncated request that hit 'end' mid-stream.+ state = STATE_DONE;+ return finish();+ }+ if (trailing[0] !== 0x0d || trailing[1] !== 0x0a) {+ const err = new Error('Malformed multipart: missing CRLF after boundary');+ err.status = 400; err.code = 'INVALID_MULTIPART';+ return fail(err);+ }+ buf = buf.slice(2);+ state = STATE_HEADERS;+ continue;+ }++ if (state === STATE_HEADERS) {+ const hEnd = buf.indexOf(HEADER_END);+ if (hEnd === -1) return; // wait for more bytes+ const headers = buf.slice(0, hEnd);+ buf = buf.slice(hEnd + HEADER_END.length);+ startPart(headers);+ if (done) return;+ state = STATE_BODY;+ continue;+ }++ if (state === STATE_BODY) {+ const idx = buf.indexOf(PART_DELIM);+ if (idx === -1) {+ // No boundary yet — emit what's safe and hold back PART_DELIM.length-1+ // trailing bytes so a boundary spanning the next chunk isn't missed.+ const safe = buf.length - (PART_DELIM.length - 1);+ if (safe > 0) {+ if (!writePartChunk(buf.slice(0, safe))) return;+ buf = buf.slice(safe);+ }+ return;+ }+ // Found end of part. Emit everything before the boundary, then advance.+ if (!writePartChunk(buf.slice(0, idx))) return;+ buf = buf.slice(idx + PART_DELIM.length);+ // endPart may be async (file flush) — pause the request, resume after.+ req.pause();+ endPart(() => {+ state = STATE_AFTER_BOUNDARY;+ req.resume();+ tick(); // process anything already buffered+ });+ return;+ }++ return; // unknown state}+ };- filePath = join(tmpdir(), `upload-${randomUUID()}${ext}`);- ws = createWriteStream(filePath);- ws.on('error', fail);- streaming = true;- writeChunk(window.slice(hEnd + HEADER_END.length));+ req.on('data', (chunk) => {+ if (done) return;+ buf = Buffer.concat([buf, chunk]);+ tick();});- stream.on('end', () => {- if (!done && !streaming) { stream.file = undefined; next(); }+ req.on('end', () => {+ if (done) return;+ endSeen = true;+ // Drain anything still in buf as part of the current state.+ tick();+ // If a file flush is still pending, the endPart callback will finalize.+ if (!done && pendingFlush === 0) finish();});- stream.on('error', fail);+ req.on('error', fail);}diff --git a/server/lib/multipart.test.js b/server/lib/multipart.test.jsnew file mode 100644index 0000000000..d4535e0c4d--- /dev/null+++ b/server/lib/multipart.test.js@@ -0,0 +1,105 @@+import { describe, it, expect, vi } from 'vitest';+import { Readable } from 'stream';+import { uploadSingle } from './multipart.js';++vi.mock('fs', () => ({+ createWriteStream: () => {+ const chunks = [];+ const handlers = {};+ return {+ // Node's writable.write returns true (no backpressure) — match that.+ write: (c) => { chunks.push(Buffer.from(c)); return true; },+ // Mirror Node's end signatures: end(), end(buf), end(buf, cb), end(cb).+ end: (data, cb) => {+ let callback;+ if (typeof data === 'function') {+ callback = data;+ } else {+ if (data) chunks.push(Buffer.from(data));+ if (typeof cb === 'function') callback = cb;+ }+ if (callback) callback();+ setImmediate(() => handlers.finish?.());+ },+ destroy: () => {},+ on: (evt, fn) => { handlers[evt] = fn; },+ once: (evt, fn) => { handlers[evt] = fn; },+ _chunks: chunks,+ };+ },+}));++const BOUNDARY = '----WebKitFormBoundaryTEST';++function makeMultipartReq(parts) {+ // parts: [{ name, filename?, contentType?, body }]+ const lines = [];+ for (const p of parts) {+ lines.push(`--${BOUNDARY}\r\n`);+ if (p.filename) {+ lines.push(`Content-Disposition: form-data; name="${p.name}"; filename="${p.filename}"\r\n`);+ lines.push(`Content-Type: ${p.contentType || 'application/octet-stream'}\r\n\r\n`);+ } else {+ lines.push(`Content-Disposition: form-data; name="${p.name}"\r\n\r\n`);+ }+ lines.push(p.body);+ lines.push('\r\n');+ }+ lines.push(`--${BOUNDARY}--\r\n`);++ const bodyBuf = Buffer.concat(lines.map((l) => Buffer.isBuffer(l) ? l : Buffer.from(l)));+ const stream = Readable.from([bodyBuf]);+ stream.headers = { 'content-type': `multipart/form-data; boundary=${BOUNDARY}` };+ return stream;+}++const runMiddleware = (req) => new Promise((resolve, reject) => {+ const mw = uploadSingle('sourceImage', { limits: { fileSize: 1024 * 1024 } });+ mw(req, {}, (err) => err ? reject(err) : resolve());+});++describe('uploadSingle multipart parser', () => {+ it('parses text fields into req.body when no file is present', async () => {+ const req = makeMultipartReq([+ { name: 'prompt', body: 'a cat' },+ { name: 'width', body: '512' },+ { name: 'tiling', body: 'auto' },+ ]);+ await runMiddleware(req);+ expect(req.body).toEqual({ prompt: 'a cat', width: '512', tiling: 'auto' });+ expect(req.file).toBeUndefined();+ });++ it('parses text fields and an optional file in one request', async () => {+ const req = makeMultipartReq([+ { name: 'prompt', body: 'a dog' },+ { name: 'width', body: '768' },+ { name: 'sourceImage', filename: 'cat.png', contentType: 'image/png', body: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a]) },+ ]);+ await runMiddleware(req);+ expect(req.body.prompt).toBe('a dog');+ expect(req.body.width).toBe('768');+ expect(req.file).toBeDefined();+ expect(req.file.originalname).toBe('cat.png');+ expect(req.file.mimetype).toBe('image/png');+ });++ it('handles file as the FIRST part (text fields after)', async () => {+ const req = makeMultipartReq([+ { name: 'sourceImage', filename: 'a.png', contentType: 'image/png', body: Buffer.from([0xff, 0xee]) },+ { name: 'prompt', body: 'leading file' },+ ]);+ await runMiddleware(req);+ expect(req.body.prompt).toBe('leading file');+ expect(req.file?.originalname).toBe('a.png');+ });++ it('rejects requests without the multipart Content-Type', async () => {+ const stream = Readable.from(['nope']);+ stream.headers = { 'content-type': 'application/json' };+ const mw = uploadSingle('sourceImage');+ await new Promise((resolve, reject) => mw(stream, {}, (err) => err ? resolve(err) : reject(new Error('expected error')))).then((err) => {+ expect(err.message).toMatch(/multipart/i);+ });+ });+});diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex ba0c11977b..f4af08eb99 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -9,8 +9,12 @@ export const NAV_COMMANDS = [{ id: 'nav.cybercity', path: '/city', label: 'CyberCity', section: 'Main', aliases: ['city', 'cybercity'], keywords: ['3d', 'visualization'] },{ id: 'nav.apps', path: '/apps', label: 'Apps', section: 'Main', aliases: ['apps'] },- { id: 'nav.image-gen', path: '/image-gen', label: 'Image Gen', section: 'AI', aliases: ['image-gen', 'imagegen', 'generate-image', 'sd', 'stable-diffusion'], keywords: ['stable diffusion', 'render', 'art', 'picture', 'photo', 'draw'] },- { id: 'nav.settings.image-gen', path: '/settings/image-gen', label: 'Image Gen Settings', section: 'AI', aliases: ['image-gen-settings', 'sd-settings'] },+ { id: 'nav.media', path: '/media/image', label: 'Media Gen', section: 'AI', aliases: ['media', 'media-gen', 'mediagen', 'generate'], keywords: ['image', 'video', 'render', 'art', 'movie'] },+ { id: 'nav.media.image', path: '/media/image', label: 'Image', section: 'AI', aliases: ['image-gen', 'imagegen', 'generate-image', 'sd', 'stable-diffusion'], keywords: ['stable diffusion', 'render', 'art', 'picture', 'photo', 'draw', 'flux', 'mflux'] },+ { id: 'nav.media.video', path: '/media/video', label: 'Video', section: 'AI', aliases: ['video-gen', 'videogen', 'generate-video', 'ltx'], keywords: ['video', 'animate', 'movie', 'clip', 'ltx'] },+ { id: 'nav.media.history', path: '/media/history', label: 'Media History', section: 'AI', aliases: ['media-history', 'video-history'], keywords: ['videos', 'gallery', 'stitch'] },+ { id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'AI', aliases: ['media-models', 'image-models', 'video-models', 'huggingface', 'loras'], keywords: ['hf cache', 'lora', 'model storage', 'disk'] },+ { id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'AI', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },{ id: 'nav.prompts', path: '/prompts', label: 'Prompts', section: 'AI', aliases: ['prompts'] },{ id: 'nav.providers', path: '/ai', label: 'Providers', section: 'AI', aliases: ['providers', 'ai-providers'] },@@ -102,12 +106,14 @@ export const NAV_COMMANDS = [{ id: 'nav.post.memory', path: '/post/memory', label: 'Memory', section: 'POST', aliases: ['post-memory'] },{ id: 'nav.post.wordplay', path: '/post/wordplay', label: 'Wordplay', section: 'POST', aliases: ['post-wordplay'] },- { id: 'nav.settings.telegram', path: '/settings/telegram', label: 'Telegram', section: 'Settings', aliases: ['settings', 'settings-telegram', 'telegram'] },- { id: 'nav.settings.voice', path: '/settings/voice', label: 'Voice', section: 'Settings', aliases: ['settings-voice', 'voice'] },+ { id: 'nav.settings.backup', path: '/settings/backup', label: 'Backup', section: 'Settings', aliases: ['backup', 'settings-backup'] },+ { id: 'nav.settings.database', path: '/settings/database', label: 'Database', section: 'Settings', aliases: ['settings-database', 'database'] },+ { id: 'nav.settings.general', path: '/settings/general', label: 'General', section: 'Settings', aliases: ['settings', 'settings-general', 'general'] },+ { id: 'nav.settings.mortalloom', path: '/settings/mortalloom', label: 'MortalLoom', section: 'Settings', aliases: ['settings-mortalloom', 'mortalloom'] },+ { id: 'nav.settings.telegram', path: '/settings/telegram', label: 'Telegram', section: 'Settings', aliases: ['settings-telegram', 'telegram'] },+ { id: 'nav.settings.voice', path: '/settings/voice', label: 'Voice', section: 'Settings', aliases: ['settings-voice', 'voice', 'voice-settings'], keywords: ['mic', 'microphone', 'speech', 'tts', 'whisper', 'kokoro'] },- { id: 'nav.settings.backup', path: '/settings/backup', label: 'Backup', section: 'System', aliases: ['backup'] },{ id: 'nav.data', path: '/data', label: 'Data', section: 'System', aliases: ['data'] },- { id: 'nav.settings.database', path: '/settings/database', label: 'Database', section: 'System', aliases: ['settings-database', 'database'] },{ id: 'nav.cos.health', path: '/cos/health', label: 'Health', section: 'System', aliases: ['cos-health'] },{ id: 'nav.instances', path: '/instances', label: 'Instances', section: 'System', aliases: ['instances'] },{ id: 'nav.loops', path: '/loops', label: 'Loops', section: 'System', aliases: ['loops'] },diff --git a/server/lib/peerHttpClient.js b/server/lib/peerHttpClient.jsnew file mode 100644index 0000000000..0d59268a44--- /dev/null+++ b/server/lib/peerHttpClient.js@@ -0,0 +1,15 @@+// Federation HTTP/Socket.IO client — TLS validation off (Tailnet is the trust boundary).+import https from 'node:https';+import { insecureFetch } from './httpClient.js';++const peerHttpsAgent = new https.Agent({ rejectUnauthorized: false, keepAlive: true });+const httpsFetch = insecureFetch(peerHttpsAgent);++export const peerSocketOptions = {+ rejectUnauthorized: false,+ transports: ['websocket', 'polling']+};++export function peerFetch(url, options = {}) {+ return url.startsWith('https://') ? httpsFetch(url, options) : fetch(url, options);+}diff --git a/server/lib/peerHttpClient.test.js b/server/lib/peerHttpClient.test.jsnew file mode 100644index 0000000000..7e6ba6a198--- /dev/null+++ b/server/lib/peerHttpClient.test.js@@ -0,0 +1,15 @@+import { describe, it, expect } from 'vitest';+import { peerSocketOptions, peerFetch } from './peerHttpClient.js';++describe('peerHttpClient', () => {+ it('peerSocketOptions disables cert validation for Socket.IO peer connections', () => {+ expect(peerSocketOptions.rejectUnauthorized).toBe(false);+ expect(peerSocketOptions.transports).toContain('websocket');+ });++ it('peerFetch falls through to global fetch for http:// URLs', async () => {+ await expect(peerFetch('http://127.0.0.1:1/should-not-exist', {+ signal: AbortSignal.timeout(50)+ })).rejects.toBeDefined();+ });+});diff --git a/server/lib/peerSelfHost.js b/server/lib/peerSelfHost.jsnew file mode 100644index 0000000000..508cae58a5--- /dev/null+++ b/server/lib/peerSelfHost.js@@ -0,0 +1,23 @@+// Returns the Tailscale-issued hostname this PortOS sends in federation+// announces. Self-signed mode binds to localhost + IPs, which can't be+// announced as a host, so falls through to null.+import { readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { PATHS, safeJSONParse } from './fileUtils.js';++const META_PATH = join(PATHS.data, 'certs', 'meta.json');++export function getSelfHost() {+ if (process.env.PORTOS_HOST) return process.env.PORTOS_HOST;++ const stat = statSync(META_PATH, { throwIfNoEntry: false });+ if (!stat) return null;++ // safeJSONParse so a partially-written meta.json (mid setup:cert) doesn't+ // throw at every announce/probe — getSelfHost is called in hot paths.+ const meta = safeJSONParse(readFileSync(META_PATH, 'utf-8'), null);+ if (!meta) return null;+ return meta.mode === 'tailscale' && typeof meta.hostname === 'string' && meta.hostname+ ? meta.hostname+ : null;+}diff --git a/server/lib/peerSelfHost.test.js b/server/lib/peerSelfHost.test.jsnew file mode 100644index 0000000000..8086c2d8b6--- /dev/null+++ b/server/lib/peerSelfHost.test.js@@ -0,0 +1,54 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++vi.mock('./fileUtils.js', () => ({+ PATHS: { data: '/mock/data' },+ safeJSONParse: (s, fallback) => { try { return JSON.parse(s); } catch { return fallback; } }+}));++vi.mock('node:fs', () => ({+ readFileSync: vi.fn(),+ statSync: vi.fn()+}));++import { readFileSync, statSync } from 'node:fs';+import { getSelfHost } from './peerSelfHost.js';++describe('peerSelfHost.getSelfHost', () => {+ beforeEach(() => {+ delete process.env.PORTOS_HOST;+ vi.clearAllMocks();+ });++ afterEach(() => {+ delete process.env.PORTOS_HOST;+ });++ it('honors PORTOS_HOST env override before reading meta.json', () => {+ process.env.PORTOS_HOST = 'override.example.ts.net';+ expect(getSelfHost()).toBe('override.example.ts.net');+ expect(statSync).not.toHaveBeenCalled();+ });++ it('returns null when meta.json does not exist', () => {+ statSync.mockReturnValue(undefined);+ expect(getSelfHost()).toBeNull();+ });++ it('returns hostname from tailscale-mode meta.json', () => {+ statSync.mockReturnValue({ mtimeMs: 1 });+ readFileSync.mockReturnValue(JSON.stringify({+ mode: 'tailscale',+ hostname: 'void.taile8179.ts.net'+ }));+ expect(getSelfHost()).toBe('void.taile8179.ts.net');+ });++ it('returns null for self-signed mode (no announceable hostname)', () => {+ statSync.mockReturnValue({ mtimeMs: 1 });+ readFileSync.mockReturnValue(JSON.stringify({+ mode: 'self-signed',+ ips: ['127.0.0.1', '100.111.11.146']+ }));+ expect(getSelfHost()).toBeNull();+ });+});diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.jsnew file mode 100644index 0000000000..041850f0c6--- /dev/null+++ b/server/lib/pythonSetup.js@@ -0,0 +1,174 @@+import { execFile, spawn } from 'node:child_process';+import { existsSync } from 'node:fs';+import { homedir, platform } from 'node:os';+import { join } from 'node:path';+import { promisify } from 'node:util';+import { PATHS } from './fileUtils.js';++const execFileAsync = promisify(execFile);+const IS_WIN = platform() === 'win32';+const IS_DARWIN = platform() === 'darwin';++export const REQUIRED_PACKAGES = IS_DARWIN+ ? ['mflux', 'mlx', 'mlx_vlm', 'mlx_video', 'transformers', 'safetensors', 'huggingface_hub', 'numpy', 'cv2', 'tqdm']+ : IS_WIN+ ? ['transformers', 'safetensors', 'huggingface_hub', 'numpy', 'cv2', 'tqdm', 'torch', 'diffusers']+ : ['mflux', 'transformers', 'safetensors', 'huggingface_hub', 'numpy', 'cv2', 'tqdm'];++const PIP_NAMES = {+ cv2: 'opencv-python',+ // mlx-compatible transformers must stay <5 — pin only on macOS where the+ // mlx path matters; Windows torch path uses latest.+ ...(IS_DARWIN ? { transformers: 'transformers<5' } : {}),+};++export const pipNameFor = (importName) => PIP_NAMES[importName] || importName;++const HOME = homedir();++// Earlier = preferred. Non-externally-managed Pythons (venvs, conda) win+// over Homebrew/system Pythons because PEP 668 blocks pip there.+const PYTHON_CANDIDATES = IS_WIN+ ? [+ join(PATHS.data, 'python', 'venv', 'Scripts', 'python.exe'),+ join(HOME, '.portos', 'venv', 'Scripts', 'python.exe'),+ join(HOME, '.pixie-forge', 'venv', 'Scripts', 'python.exe'),+ join(HOME, 'miniconda3', 'python.exe'),+ join(HOME, 'anaconda3', 'python.exe'),+ 'C:\\miniconda3\\python.exe',+ 'C:\\anaconda3\\python.exe',+ join(HOME, 'AppData', 'Local', 'Programs', 'Python', 'Python313', 'python.exe'),+ join(HOME, 'AppData', 'Local', 'Programs', 'Python', 'Python312', 'python.exe'),+ join(HOME, 'AppData', 'Local', 'Programs', 'Python', 'Python311', 'python.exe'),+ 'C:\\Python313\\python.exe',+ 'C:\\Python312\\python.exe',+ 'C:\\Python311\\python.exe',+ ]+ : [+ join(PATHS.data, 'python', 'venv', 'bin', 'python3'),+ join(HOME, '.portos', 'venv', 'bin', 'python3'),+ join(HOME, '.pixie-forge', 'venv', 'bin', 'python3'),+ '/opt/miniconda3/bin/python3',+ '/opt/anaconda3/bin/python3',+ join(HOME, 'miniconda3', 'bin', 'python3'),+ join(HOME, 'anaconda3', 'bin', 'python3'),+ join(HOME, '.pyenv', 'shims', 'python3'),+ '/opt/homebrew/bin/python3',+ '/usr/local/bin/python3',+ '/usr/bin/python3',+ ];++export async function detectPython() {+ for (const p of PYTHON_CANDIDATES) {+ if (existsSync(p)) return p;+ }+ const which = IS_WIN ? 'where' : 'which';+ const name = IS_WIN ? 'python' : 'python3';+ const { stdout } = await execFileAsync(which, [name], { timeout: 5000 }).catch(() => ({ stdout: '' }));+ return stdout.trim().split(/\r?\n/)[0] || null;+}++// Used by /api/image-gen/setup/* routes to validate user-supplied pythonPath+// before exec. Single-user / Tailnet model means we trust the operator, but+// "you can shell out to anything" is still too sharp — restrict to actual+// python interpreters by basename, and accept a candidate path if it is one+// we discovered ourselves.+const PYTHON_BASENAMES = IS_WIN+ ? ['python.exe', 'python3.exe']+ : ['python', 'python3'];++export function isAllowedPython(pythonPath) {+ if (typeof pythonPath !== 'string' || !pythonPath) return false;+ if (PYTHON_CANDIDATES.includes(pythonPath)) return true;+ // Allow any path whose basename looks like a python interpreter — covers+ // user-typed venvs (`/path/to/.venv/bin/python3.12`) without opening up+ // arbitrary-binary execution.+ const base = pythonPath.split(/[\\/]/).pop().toLowerCase();+ if (PYTHON_BASENAMES.includes(base)) return true;+ // Also accept python3.NN variants like python3.10, python3.11, python.exe etc.+ if (/^python(3(\.\d+)?)?(\.exe)?$/i.test(base)) return true;+ return false;+}++// Returns true if `pythonPath` has a PEP 668 EXTERNALLY-MANAGED marker next+// to its stdlib — pip will refuse to install into it.+export async function isExternallyManaged(pythonPath) {+ const { stdout } = await execFileAsync(pythonPath, [+ '-c', 'import sysconfig; print(sysconfig.get_path("stdlib"))'+ ], { timeout: 10_000 }).catch(() => ({ stdout: '' }));+ const stdlib = stdout.trim();+ if (!stdlib) return false;+ return existsSync(join(stdlib, 'EXTERNALLY-MANAGED'));+}++// Idempotent: if the venv exists, returns its python path without recreating.+// Windows venvs put the interpreter at Scripts\python.exe, POSIX at bin/python3.+export async function createVenv(basePython, targetDir) {+ const venvPython = IS_WIN+ ? join(targetDir, 'Scripts', 'python.exe')+ : join(targetDir, 'bin', 'python3');+ if (existsSync(venvPython)) return venvPython;+ await execFileAsync(basePython, ['-m', 'venv', targetDir], { timeout: 120_000 });+ if (!existsSync(venvPython)) {+ throw new Error(`Venv created but interpreter missing at ${venvPython}`);+ }+ return venvPython;+}++export async function checkPackages(pythonPath) {+ const probe = REQUIRED_PACKAGES.map(pkg =>+ `try:\n import ${pkg}\n print("OK:${pkg}")\nexcept Exception:\n print("MISSING:${pkg}")`+ ).join('\n');++ const { stdout } = await execFileAsync(pythonPath, ['-c', probe], { timeout: 30_000 });++ const installed = [];+ const missing = [];+ for (const line of stdout.trim().split(/\r?\n/)) {+ if (line.startsWith('OK:')) installed.push(line.slice(3).trim());+ else if (line.startsWith('MISSING:')) missing.push(line.slice(8).trim());+ }+ return { installed, missing, missingPip: missing.map(pipNameFor) };+}++// Spawn pip install; emit each line via onLog. Resolves on exit.+// onLog gets `{ type: 'log' | 'error' | 'complete', message }`.+// Returns `{ promise, kill }` so the route can SIGTERM the pip child if+// the SSE client disconnects mid-install (otherwise a 10-minute torch+// upgrade would keep running invisibly).+export function installPackages(pythonPath, importNames, onLog) {+ const pipSpecs = importNames.map(pipNameFor);+ onLog({ type: 'log', message: `pip install ${pipSpecs.join(' ')}` });++ const proc = spawn(pythonPath, [+ '-m', 'pip', 'install', '--upgrade', '--progress-bar', 'on',+ ...pipSpecs,+ ], { stdio: ['ignore', 'pipe', 'pipe'] });++ const promise = new Promise((resolve) => {+ const handleOutput = (chunk) => {+ for (const line of chunk.toString().split(/[\r\n]+/)) {+ const trimmed = line.trim();+ if (trimmed) onLog({ type: 'log', message: trimmed });+ }+ };+ proc.stdout.on('data', handleOutput);+ proc.stderr.on('data', handleOutput);++ proc.on('close', (code) => {+ if (code === 0) {+ onLog({ type: 'complete', message: 'All packages installed successfully.' });+ resolve({ ok: true, code: 0 });+ } else {+ onLog({ type: 'error', message: `pip exited with code ${code}` });+ resolve({ ok: false, code });+ }+ });+ proc.on('error', (err) => {+ onLog({ type: 'error', message: err.message });+ resolve({ ok: false, code: -1 });+ });+ });++ return { promise, kill: () => { if (!proc.killed) proc.kill('SIGTERM'); } };+}diff --git a/server/lib/sseUtils.js b/server/lib/sseUtils.jsnew file mode 100644index 0000000000..c724a3155f--- /dev/null+++ b/server/lib/sseUtils.js@@ -0,0 +1,56 @@+// Shared helpers for the per-job SSE streams used by imageGen/local.js and+// videoGen/local.js. Both providers attach a list of `res` clients to a+// per-jobId record and broadcast diffuser progress as SSE frames; this module+// keeps the wire format and the response headers in one place.++// Filters Python child noise (HF/torch/bitsandbytes/xformers warnings, deprecation+// notices, etc.) that would otherwise drown the user's view of real progress.+export const PYTHON_NOISE_RE = /xformers|xFormers|triton|Triton|bitsandbytes|Please reinstall|Memory-efficient|Set XFORMERS|FutureWarning|UserWarning|DeprecationWarning|torch\.distributed|Unable to import.*torchao|Skipping import of cpp|NOTE: Redirects/i;++// Late-connecting EventSource clients sometimes re-attach during the brief+// window between `complete` and the route teardown. Hold the SSE list open+// for this many ms after the underlying job finishes so a client that+// connected just after the terminal broadcast still gets it (replayed from+// `job.lastPayload`) instead of hanging until timeout.+export const SSE_CLEANUP_DELAY_MS = 5000;++export const broadcastSse = (job, payload) => {+ // Cache the most recent payload on the job so attachSseClient can replay+ // it to a client that connects after this fired. Without this, a client+ // that races with `complete` would hang waiting for a frame that already+ // shipped.+ job.lastPayload = payload;+ const msg = `data: ${JSON.stringify(payload)}\n\n`;+ for (const c of job.clients) c.write(msg);+};++export const attachSseClient = (jobs, jobId, res) => {+ const job = jobs.get(jobId);+ if (!job) return false;+ res.writeHead(200, {+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache',+ Connection: 'keep-alive',+ });+ job.clients.push(res);+ // Replay the last broadcasted frame so a client that connected after a+ // `complete`/`error` (within the SSE_CLEANUP_DELAY_MS grace window) sees+ // the terminal state instead of an empty stream.+ if (job.lastPayload) {+ res.write(`data: ${JSON.stringify(job.lastPayload)}\n\n`);+ }+ res.req.on('close', () => {+ job.clients = job.clients.filter((c) => c !== res);+ });+ return true;+};++// Drains any late-connecting EventSource clients then removes the job+// from the per-provider job map. Both providers do this on child exit.+export const closeJobAfterDelay = (jobs, jobId, delay = SSE_CLEANUP_DELAY_MS) => {+ setTimeout(() => {+ const job = jobs.get(jobId);+ if (job) for (const c of job.clients) c.end();+ jobs.delete(jobId);+ }, delay);+};diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 63bf68c25c..263c58b1dc 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -1,51 +1,214 @@/**- * Image Generation Routes+ * Image Generation Routes — works against either the external SD API or the+ * local mflux backend, depending on settings.imageGen.mode.*- * Endpoints for generating images via Stable Diffusion API.+ * Generic endpoints (status, generate, avatar) go through the dispatcher.+ * Local-mode endpoints (events SSE, gallery, loras, cancel, delete) target+ * the local module directly because their shape doesn't apply to external.*/import { Router } from 'express';import { z } from 'zod';import { asyncHandler } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';-import * as imageGen from '../services/imageGen.js';+import * as imageGen from '../services/imageGen/index.js';+import { local } from '../services/imageGen/index.js';+import {+ REQUIRED_PACKAGES, detectPython, checkPackages, installPackages,+ isExternallyManaged, createVenv, isAllowedPython, pipNameFor,+} from '../lib/pythonSetup.js';+import { PATHS } from '../lib/fileUtils.js';+import { join } from 'node:path';const router = Router();const generateSchema = z.object({prompt: z.string().min(1).max(2000),negativePrompt: z.string().max(2000).optional(),+ modelId: z.string().max(64).optional(),width: z.number().int().min(64).max(2048).optional(),height: z.number().int().min(64).max(2048).optional(),steps: z.number().int().min(1).max(150).optional(),cfgScale: z.number().min(0).max(30).optional(),- seed: z.number().int().min(0).optional()+ guidance: z.number().min(0).max(30).optional(),+ seed: z.number().int().min(0).optional(),+ // mflux supports 3/4/5/6/8 bit quantization; 8 is the default.+ quantize: z.union([z.literal(3), z.literal(4), z.literal(5), z.literal(6), z.literal(8), z.literal('3'), z.literal('4'), z.literal('5'), z.literal('6'), z.literal('8')]).optional(),+ // Filenames only (basenames) — server resolves against PATHS.loras and+ // applies the prefix-check. Old payloads sent absolute server paths+ // (`loraPaths`); accept both for back-compat with stored gallery sidecars.+ loraFilenames: z.array(z.string().max(256).regex(/^[^/\\]+$/, 'lora filename must not contain path separators')).max(8).optional(),+ loraPaths: z.array(z.string().max(512)).max(8).optional(),+ loraScales: z.array(z.number().min(0).max(2)).max(8).optional(),});const avatarSchema = z.object({name: z.string().max(100).optional(),characterClass: z.string().max(100).optional(),- prompt: z.string().max(2000).optional()+ prompt: z.string().max(2000).optional(),});-// GET /api/image-gen/status - Check SD API connection-router.get('/status', asyncHandler(async (req, res) => {- const status = await imageGen.checkConnection();- res.json(status);+router.get('/status', asyncHandler(async (_req, res) => {+ res.json(await imageGen.checkConnection());+}));++router.get('/active', asyncHandler(async (_req, res) => {+ res.json({ activeJob: await imageGen.getActiveJob() });}));-// POST /api/image-gen/generate - Generate an imagerouter.post('/generate', asyncHandler(async (req, res) => {const data = validateRequest(generateSchema, req.body);- const result = await imageGen.generateImage(data);- res.json(result);+ res.json(await imageGen.generateImage(data));}));-// POST /api/image-gen/avatar - Generate a character avatarrouter.post('/avatar', asyncHandler(async (req, res) => {const data = validateRequest(avatarSchema, req.body);- const result = await imageGen.generateAvatar(data);- res.json(result);+ res.json(await imageGen.generateAvatar(data));+}));++// Local-only: list image models and LoRAs the local backend can use.+router.get('/models', (_req, res) => {+ res.json(local.listImageModels());+});++router.get('/loras', asyncHandler(async (_req, res) => {+ res.json(await local.listLoras());+}));++router.get('/gallery', asyncHandler(async (_req, res) => {+ res.json(await local.listGallery());+}));++// SSE progress stream for the local backend. EventSource consumers (the+// ImageGen page) attach here using the jobId returned from POST /generate.+router.get('/:jobId/events', (req, res) => {+ const ok = local.attachSseClient(req.params.jobId, res);+ if (!ok) res.status(404).json({ error: 'Job not found or expired' });+});++router.post('/cancel', (_req, res) => {+ const cancelled = local.cancel();+ res.json({ ok: cancelled });+});++router.delete('/:filename', asyncHandler(async (req, res) => {+ res.json(await local.deleteImage(req.params.filename));+}));++// --- Local-mode setup automation ---++router.get('/setup/python', asyncHandler(async (_req, res) => {+ const path = await detectPython();+ res.json({ path });+}));++const checkSchema = z.object({ pythonPath: z.string().min(1) });++router.get('/setup/check', asyncHandler(async (req, res) => {+ const { pythonPath } = validateRequest(checkSchema, req.query);+ if (!isAllowedPython(pythonPath)) {+ return res.status(400).json({ error: 'pythonPath must be a python interpreter (basename python/python3/python3.NN)' });+ }+ const [pkgs, externallyManaged] = await Promise.all([+ checkPackages(pythonPath),+ isExternallyManaged(pythonPath),+ ]);+ res.json({+ pythonPath,+ externallyManaged,+ required: REQUIRED_PACKAGES,+ ...pkgs,+ });+}));++const venvSchema = z.object({+ basePython: z.string().min(1).optional(),+});++router.post('/setup/create-venv', asyncHandler(async (req, res) => {+ const { basePython } = validateRequest(venvSchema, req.body || {});+ if (basePython && !isAllowedPython(basePython)) {+ return res.status(400).json({ error: 'basePython must be a python interpreter (basename python/python3/python3.NN)' });+ }+ const base = basePython || (await detectPython());+ if (!base) {+ return res.status(400).json({ error: 'No base Python 3 found to bootstrap a venv. Install Python 3.10+ first.' });+ }+ const target = join(PATHS.data, 'python', 'venv');+ const venvPython = await createVenv(base, target);+ res.json({ pythonPath: venvPython, target });}));+// Allowlist: only PortOS's own required pip names (or their pinned variants+// like `transformers<5`) are installable. Without this, the endpoint would+// happily pip-install arbitrary PyPI packages — the install runs as the+// PortOS user and pip itself executes setup.py from the package, so an+// arbitrary package install is effectively arbitrary code execution.+// Build the pip-spec allowlist from REQUIRED_PACKAGES via pipNameFor — that+// translates import names (`cv2`) to their actual pip specs+// (`opencv-python`). Without this mapping, the allowlist would contain+// import-only names that can't actually be installed but ALSO don't appear+// here as their pip specs, so the legitimate install request would 400.+// Worse: an import name like `cv2` isn't a real PyPI package but if a+// typosquat existed under that name it'd be installable.+const REQUIRED_PIP_NAMES = new Set([+ ...REQUIRED_PACKAGES.map(pipNameFor),+ // Windows torch path also installs torch + diffusers, which are in+ // REQUIRED_PACKAGES on Windows but not on macOS — keep them allowlisted+ // unconditionally so a Windows install requested from a macOS server+ // (unlikely but possible) doesn't 400 unhelpfully.+ 'torch',+ 'diffusers',+ // Both the bare `transformers` and the macOS-pinned `transformers<5`+ // variant should be installable; pipNameFor only emits the pinned+ // variant on macOS, so list both unconditionally for safety.+ 'transformers',+ 'transformers<5',+]);++const installSchema = z.object({+ pythonPath: z.string().min(1),+ packages: z.array(z.string().min(1)).min(1).max(40),+});++// EventSource consumers re-run /setup/check on `complete` to refresh status.+router.get('/setup/install', (req, res) => {+ const pythonPath = req.query.pythonPath;+ const packages = String(req.query.packages || '').split(',').filter(Boolean);+ const parsed = installSchema.safeParse({ pythonPath, packages });+ if (!parsed.success) {+ res.writeHead(400, { 'Content-Type': 'application/json' });+ return res.end(JSON.stringify({ error: parsed.error.message }));+ }+ if (!isAllowedPython(parsed.data.pythonPath)) {+ res.writeHead(400, { 'Content-Type': 'application/json' });+ return res.end(JSON.stringify({ error: 'pythonPath must be a python interpreter' }));+ }+ const disallowed = parsed.data.packages.filter((p) => !REQUIRED_PIP_NAMES.has(p));+ if (disallowed.length) {+ res.writeHead(400, { 'Content-Type': 'application/json' });+ return res.end(JSON.stringify({ error: `Packages not in allowlist: ${disallowed.join(', ')}` }));+ }++ res.writeHead(200, {+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache',+ Connection: 'keep-alive',+ });+ // `send` and `safeEnd` no-op once the response has ended so a late+ // pip-output line (or the promise.then below) doesn't trigger+ // ERR_STREAM_WRITE_AFTER_END or double-end the response.+ const send = (event) => {+ if (!res.writableEnded) res.write(`data: ${JSON.stringify(event)}\n\n`);+ };+ const safeEnd = () => { if (!res.writableEnded) res.end(); };++ const { promise, kill } = installPackages(parsed.data.pythonPath, parsed.data.packages, send);+ promise.then(safeEnd);++ // Client navigation away should kill pip — a torch upgrade can run for+ // 10+ minutes and would otherwise keep going invisibly.+ req.on('close', () => { kill(); safeEnd(); });+});+export default router;diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex b625fe86ce..73c73a836b 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -3,13 +3,21 @@ import express from 'express';import { request } from '../lib/testHelper.js';import imageGenRoutes from './imageGen.js';-vi.mock('../services/imageGen.js', () => ({+vi.mock('../services/imageGen/index.js', () => ({checkConnection: vi.fn(),generateImage: vi.fn(),- generateAvatar: vi.fn()+ generateAvatar: vi.fn(),+ local: {+ listImageModels: vi.fn(() => []),+ listLoras: vi.fn(async () => []),+ listGallery: vi.fn(async () => []),+ attachSseClient: vi.fn(() => false),+ cancel: vi.fn(() => false),+ deleteImage: vi.fn(async () => ({ ok: true })),+ },}));-import * as imageGen from '../services/imageGen.js';+import * as imageGen from '../services/imageGen/index.js';describe('Image Gen Routes', () => {let app;diff --git a/server/routes/imageVideoModels.js b/server/routes/imageVideoModels.jsnew file mode 100644index 0000000000..2084e8ff39--- /dev/null+++ b/server/routes/imageVideoModels.js@@ -0,0 +1,139 @@+/**+ * Models Management — HuggingFace cache + LoRAs.+ *+ * HF models live at HF's standard cache location (~/.cache/huggingface/hub by+ * default). PortOS doesn't move or symlink them — it just reads from there+ * for the Models manager UI, separate from DataManager (which only tracks+ * files inside data/). LoRAs the user drops into data/loras/ are still+ * tracked by DataManager and shown here too.+ */++import { Router } from 'express';+import { existsSync } from 'fs';+import { readdir, stat, rm } from 'fs/promises';+import { homedir } from 'os';+import { join } from 'path';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { PATHS, formatBytes, dirSize } from '../lib/fileUtils.js';++const router = Router();+const HF_DEFAULT_HUB = join(homedir(), '.cache', 'huggingface', 'hub');++// HF stores its hub cache under <HF_HOME>/hub/models--<org>--<name>. Honor+// HF_HOME if the user set one, otherwise fall back to HF's own default+// (~/.cache/huggingface/hub).+const HF_HUB_DIR = () =>+ process.env.HF_HOME ? join(process.env.HF_HOME, 'hub') : HF_DEFAULT_HUB;++// Friendly labels for our default model picks. Anything else is shown by repo id.+const APP_MODELS = {+ 'black-forest-labs--FLUX.1-schnell': 'Flux 1 Schnell (Image)',+ 'black-forest-labs--FLUX.1-dev': 'Flux 1 Dev (Image)',+ 'notapalindrome--ltx2-mlx-av': 'LTX-2 Unified (Video)',+ 'notapalindrome--ltx23-mlx-av': 'LTX-2.3 Unified (Video)',+ 'notapalindrome--ltx23-mlx-av-q4': 'LTX-2.3 Distilled Q4 (Video)',+ 'mlx-community--gemma-3-12b-it-4bit': 'Gemma 3 12B 4-bit (Text Encoder)',+};++// Bound concurrent dirSize calls — each one spawns a `du` (or PowerShell)+// child, and a hub with 50+ models would otherwise create a process storm+// that stalls the API.+async function mapWithConcurrency(items, concurrency, fn) {+ const results = new Array(items.length);+ let next = 0;+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, async () => {+ while (true) {+ const i = next++;+ if (i >= items.length) return;+ results[i] = await fn(items[i], i);+ }+ }));+ return results;+}++router.get('/', asyncHandler(async (_req, res) => {+ const hubDir = HF_HUB_DIR();++ const entries = existsSync(hubDir)+ ? (await readdir(hubDir)).filter((f) => f.startsWith('models--'))+ : [];++ const [models, loras, totalImages, totalVideos] = await Promise.all([+ mapWithConcurrency(entries, 4, async (dirName) => {+ const fullPath = join(hubDir, dirName);+ const modelKey = dirName.replace('models--', '');+ const [org, ...nameParts] = modelKey.split('--');+ const name = nameParts.join('--');+ const size = await dirSize(fullPath);+ return {+ id: dirName,+ org,+ name,+ repo: `${org}/${name}`,+ label: APP_MODELS[modelKey] || null,+ size,+ sizeHuman: formatBytes(size),+ };+ }),+ (async () => {+ const out = [];+ if (!existsSync(PATHS.loras)) return out;+ for (const f of await readdir(PATHS.loras)) {+ if (!f.endsWith('.safetensors')) continue;+ const s = await stat(join(PATHS.loras, f));+ out.push({+ filename: f,+ name: f.replace(/^lora-/, '').replace(/\.safetensors$/, ''),+ size: s.size,+ sizeHuman: formatBytes(s.size),+ });+ }+ return out;+ })(),+ dirSize(PATHS.images),+ dirSize(PATHS.videos),+ ]);+ models.sort((a, b) => b.size - a.size);++ const totalModels = models.reduce((sum, m) => sum + m.size, 0);+ const totalLoras = loras.reduce((sum, l) => sum + l.size, 0);++ res.json({+ models,+ loras,+ hubDir,+ diskUsage: {+ models: formatBytes(totalModels),+ loras: formatBytes(totalLoras),+ images: formatBytes(totalImages),+ videos: formatBytes(totalVideos),+ total: formatBytes(totalModels + totalLoras + totalImages + totalVideos),+ },+ });+}));++router.delete('/hf/:dirName', asyncHandler(async (req, res) => {+ const dirName = req.params.dirName;+ if (!dirName.startsWith('models--') || dirName.includes('/') || dirName.includes('\\') || dirName.includes('..')) {+ throw new ServerError('Invalid model directory name', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const fullPath = join(HF_HUB_DIR(), dirName);+ if (!existsSync(fullPath)) throw new ServerError('Model not found', { status: 404, code: 'NOT_FOUND' });+ console.log(`🗑️ Deleting HF model cache: ${dirName}`);+ await rm(fullPath, { recursive: true, force: true });+ res.json({ ok: true });+}));++router.delete('/lora/:filename', asyncHandler(async (req, res) => {+ const filename = req.params.filename;+ if (!filename.endsWith('.safetensors') || filename.includes('/') || filename.includes('\\') || filename.includes('..')) {+ throw new ServerError('Invalid filename', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const filePath = join(PATHS.loras, filename);+ if (!existsSync(filePath)) throw new ServerError('LoRA not found', { status: 404, code: 'NOT_FOUND' });+ console.log(`🗑️ Deleting LoRA: ${filename}`);+ await rm(filePath, { force: true });+ res.json({ ok: true });+}));++export default router;diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 9acd32bb70..4b5c28ea35 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -59,7 +59,10 @@ const updatePeerSchema = z.object({const announceSchema = z.object({port: z.number().int().min(1).max(65535),instanceId: z.string().uuid(),- name: z.string().optional()+ name: z.string().optional(),+ // Tailscale-issued DNS name announcing peer reaches itself at; receiver+ // stores it on the peer record so callbacks use https://<host>:<port>.+ host: z.string().optional().nullable()});const querySchema = z.object({@@ -138,7 +141,8 @@ router.post('/peers/announce', asyncHandler(async (req, res) => {address,port: data.port,instanceId: data.instanceId,- name: data.name+ name: data.name,+ host: data.host});const self = await instances.getSelf();diff --git a/server/routes/sdapi.js b/server/routes/sdapi.jsnew file mode 100644index 0000000000..a7e3655644--- /dev/null+++ b/server/routes/sdapi.js@@ -0,0 +1,252 @@+/**+ * AUTOMATIC1111 / Forge — compatible API surface.+ *+ * Mounts at /sdapi/v1/* so other machines on the Tailscale network can point+ * their own AUTOMATIC1111 client at this PortOS instance. We dispatch through+ * the imageGen layer so the underlying provider is whatever PortOS is+ * configured for (external pass-through or local mflux).+ *+ * Gated by settings.imageGen.expose.a1111 (default false). When the toggle is+ * off, every endpoint returns 403 — better than half-implementing the surface+ * because clients fail fast and the user knows to flip the toggle.+ *+ * Implements just enough of the A1111 surface for txt2img + status/progress+ * polling. A1111 has dozens of additional endpoints (img2img, controlnet,+ * embedded LoRAs, etc.) that we punt on until someone needs them.+ */++import { Router } from 'express';+import { readFile } from 'fs/promises';+import { join } from 'path';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { PATHS } from '../lib/fileUtils.js';+import { getSettings } from '../services/settings.js';+import { generateImage, getMode, getActiveJob } from '../services/imageGen/index.js';+import { local as localImage } from '../services/imageGen/index.js';+import { imageGenEvents } from '../services/imageGenEvents.js';+import { listVideoModels, defaultVideoModelId } from '../services/videoGen/local.js';++const router = Router();++// Build a completion waiter for a future generationId. Listeners attach+// immediately so a fast Python child can't emit 'completed' before we're+// listening, but the id-match check uses a registered id (set by .register()+// once generateImage returns). 5-minute timeout matches the external client.+// The returned `cleanup()` is exposed so the caller can detach listeners+// even if generateImage throws before we ever resolve/reject.+function createCompletionWaiter() {+ let registeredId = null;+ let resolve, reject;+ // Swallow the unhandled-rejection if the caller never awaits .promise+ // (e.g. generateImage throws and the route exits via the error path).+ const promise = new Promise((res, rej) => { resolve = res; reject = rej; });+ promise.catch(() => {});+ const onComplete = (ev) => { if (ev.generationId === registeredId) { cleanup(); resolve(ev); } };+ const onFailed = (ev) => { if (ev.generationId === registeredId) { cleanup(); reject(new ServerError(ev.error || 'Generation failed', { status: 500, code: 'GEN_FAILED' })); } };+ const timer = setTimeout(() => { cleanup(); reject(new ServerError('Generation timed out', { status: 504, code: 'GEN_TIMEOUT' })); }, 5 * 60 * 1000);+ const cleanup = () => {+ clearTimeout(timer);+ imageGenEvents.off('completed', onComplete);+ imageGenEvents.off('failed', onFailed);+ };+ imageGenEvents.on('completed', onComplete);+ imageGenEvents.on('failed', onFailed);+ return { register: (id) => { registeredId = id; }, promise, cleanup };+}++const ensureExposed = async () => {+ const s = await getSettings();+ return s.imageGen?.expose?.a1111 === true;+};++router.use(asyncHandler(async (req, res, next) => {+ if (await ensureExposed()) return next();+ res.status(403).json({ error: 'PortOS A1111 API is disabled — toggle "Expose A1111 API" in Settings > Image Gen' });+}));++// Mirrors A1111's /sdapi/v1/options. Most clients only consult+// `sd_model_checkpoint` so we stuff our active mode/model into that field.+router.get('/options', asyncHandler(async (_req, res) => {+ const mode = await getMode();+ const models = localImage.listImageModels();+ const defaultModel = mode === 'local' ? `portos-local-${models[0]?.id || 'dev'}` : 'portos-external';+ res.json({+ sd_model_checkpoint: defaultModel,+ sampler_name: 'Euler',+ portos: { mode },+ });+}));++router.post('/options', (_req, res) => {+ // A1111 lets clients PUT the active checkpoint here; we don't support+ // switching the underlying model from a remote client (security + scope),+ // but we acknowledge so clients that always send options don't error out.+ res.json({ ok: true });+});++// Static catalog. Returns one entry per local image model so clients can show+// a model picker; the external mode shows a single "remote-passthrough" stub.+router.get('/sd-models', asyncHandler(async (_req, res) => {+ const mode = await getMode();+ if (mode === 'local') {+ return res.json(localImage.listImageModels().map((m) => ({+ title: `portos-local-${m.id} [flux]`,+ model_name: `portos-local-${m.id}`,+ hash: null,+ sha256: null,+ filename: m.id,+ config: null,+ })));+ }+ res.json([{ title: 'portos-external [passthrough]', model_name: 'portos-external', hash: null, sha256: null, filename: 'external', config: null }]);+}));++// Minimal stub — A1111 clients usually just check that this returns an array.+router.get('/samplers', (_req, res) => {+ res.json([+ { name: 'Euler', aliases: ['k_euler'], options: {} },+ { name: 'Euler a', aliases: ['k_euler_a'], options: {} },+ ]);+});++// LTX models surfaced as a PortOS extension — clients that know about us can+// list video options without hitting a separate endpoint.+router.get('/portos/video-models', (_req, res) => {+ res.json({ models: listVideoModels(), defaultModel: defaultVideoModelId() });+});++// Live progress — A1111 clients poll this every ~500ms while a generation is+// running. The dispatcher's getActiveJob() surfaces the current generation+// snapshot for both modes (local mflux emits stepwise frames as currentImage+// base64; external SD polls the upstream /progress endpoint). When nothing+// is in flight we return a "no active job" payload that A1111 clients+// understand as idle.+router.get('/progress', asyncHandler(async (_req, res) => {+ const job = await getActiveJob();+ if (!job) {+ return res.json({+ progress: 0,+ eta_relative: 0,+ state: { sampling_step: 0, sampling_steps: 0 },+ current_image: null,+ textinfo: 'PortOS — no active generation',+ });+ }+ res.json({+ progress: typeof job.progress === 'number' ? job.progress : 0,+ eta_relative: 0,+ state: {+ sampling_step: typeof job.step === 'number' ? job.step : 0,+ sampling_steps: typeof job.totalSteps === 'number' ? job.totalSteps : 0,+ },+ current_image: job.currentImage || null,+ textinfo: `PortOS — ${job.mode || 'unknown'} mode${job.modelId ? ` (${job.modelId})` : ''}`,+ });+}));++// Mirror imageGen.js's generateSchema bounds — A1111 clients can be sloppy+// (e.g. defaulting steps=999 from a preset) and we want a clear 400 instead+// of letting bad values through to the dispatcher.+const txt2imgSchema = z.object({+ prompt: z.string().min(1).max(2000),+ negative_prompt: z.string().max(2000).optional().nullable(),+ width: z.number().int().min(64).max(2048).optional(),+ height: z.number().int().min(64).max(2048).optional(),+ steps: z.number().int().min(1).max(150).optional(),+ cfg_scale: z.number().min(0).max(30).optional(),+ seed: z.number().int().optional(),+ sd_model_checkpoint: z.string().max(128).optional(),+}).passthrough(); // tolerate extra A1111 fields the client sends++router.post('/txt2img', asyncHandler(async (req, res) => {+ const parsed = txt2imgSchema.safeParse(req.body || {});+ if (!parsed.success) {+ throw new ServerError(`Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`, { status: 400, code: 'VALIDATION_ERROR' });+ }+ const {+ prompt,+ negative_prompt,+ width,+ height,+ steps,+ cfg_scale,+ seed,+ sd_model_checkpoint,+ } = parsed.data;++ // Map an A1111-style "portos-local-<id>" checkpoint name back to our+ // internal model id so remote clients can pick a local model. Anything+ // else falls through to whatever PortOS has set as the active mode.+ let modelId;+ if (typeof sd_model_checkpoint === 'string' && sd_model_checkpoint.startsWith('portos-local-')) {+ modelId = sd_model_checkpoint.replace(/^portos-local-/, '').split(' ')[0];+ }++ // In local mode generateImage returns the moment the Python child is+ // spawned — the file isn't on disk yet. Subscribe to the completion event+ // BEFORE calling generateImage so a fast job (cached weights, low steps)+ // can't fire before we attach. External mode awaits internally and the+ // file is on disk by the time generateImage resolves, so the wait is a+ // no-op there.+ const mode = await getMode();+ const localWait = mode === 'local'+ ? createCompletionWaiter()+ : { register: () => {}, promise: Promise.resolve(), cleanup: () => {} };++ let result;+ try {+ result = await generateImage({+ prompt,+ negativePrompt: negative_prompt,+ modelId,+ width,+ height,+ steps,+ cfgScale: cfg_scale,+ seed: seed != null && seed >= 0 ? Number(seed) : undefined,+ });+ } catch (err) {+ // Detach the waiter listeners + clear the timeout if generateImage+ // threw before we even registered (provider misconfigured / busy).+ localWait.cleanup();+ throw err;+ }++ localWait.register(result.generationId);+ // Local mode: the completion event carries the actual seed used (mflux+ // generates a random one when the client didn't pass one). External mode+ // returns Promise.resolve() with no payload — fall back to result.seed+ // (which providers populate from their own response when available) and+ // finally to the request seed.+ const completionEvent = await localWait.promise;++ // A1111 clients expect base64-encoded images in `images: []`. Read the+ // file the dispatcher saved under data/images/. If the read fails AFTER+ // we already awaited completion, that's a real internal error — surface+ // it with a 5xx instead of returning images:[] (which A1111 clients+ // silently treat as a no-op).+ const filePath = join(PATHS.images, result.filename);+ const buf = await readFile(filePath).catch(() => null);+ if (!buf) {+ throw new ServerError(`Generation completed but ${result.filename} could not be read`, { status: 500, code: 'GEN_OUTPUT_MISSING' });+ }+ const actualSeed = completionEvent?.seed ?? result.seed ?? seed;+ res.json({+ images: [buf.toString('base64')],+ parameters: { prompt, negative_prompt, width, height, steps, cfg_scale, seed: actualSeed },+ info: JSON.stringify({+ prompt,+ negative_prompt,+ seed: actualSeed,+ model: result.model || sd_model_checkpoint,+ width,+ height,+ steps,+ cfg_scale,+ portos: { mode: result.mode, filename: result.filename, path: result.path },+ }),+ });+}));++export default router;diff --git a/server/routes/sdapi.test.js b/server/routes/sdapi.test.jsnew file mode 100644index 0000000000..beacc340a2--- /dev/null+++ b/server/routes/sdapi.test.js@@ -0,0 +1,198 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn(),+}));++vi.mock('../services/imageGen/index.js', () => ({+ generateImage: vi.fn(),+ getMode: vi.fn(),+ getActiveJob: vi.fn(),+ local: { listImageModels: vi.fn(() => [{ id: 'dev', name: 'Flux 1 Dev' }]) },+}));++// Use a real EventEmitter so listeners attached by the route actually fire+// when the test calls `imageGenEvents.emit(...)`. The factory body is hoisted,+// so the EventEmitter has to be created INSIDE the factory.+vi.mock('../services/imageGenEvents.js', async () => {+ const { EventEmitter } = await import('events');+ return { imageGenEvents: new EventEmitter() };+});++vi.mock('../services/videoGen/local.js', () => ({+ listVideoModels: vi.fn(() => []),+ defaultVideoModelId: vi.fn(() => 'ltx_video'),+}));++vi.mock('fs/promises', () => ({+ readFile: vi.fn(),+}));++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { images: '/mock/images' },+}));++import { getSettings } from '../services/settings.js';+import * as imageGen from '../services/imageGen/index.js';+import { imageGenEvents as realEmitter } from '../services/imageGenEvents.js';+import { readFile } from 'fs/promises';+import sdapiRoutes from './sdapi.js';++const enabled = () => getSettings.mockResolvedValue({ imageGen: { expose: { a1111: true } } });+const disabled = () => getSettings.mockResolvedValue({ imageGen: { expose: { a1111: false } } });++describe('sdapi routes — A1111-compatible surface', () => {+ let app;+ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/sdapi/v1', sdapiRoutes);+ vi.clearAllMocks();+ });++ describe('gating', () => {+ it('returns 403 on every endpoint when expose.a1111 is false', async () => {+ disabled();+ const r1 = await request(app).get('/sdapi/v1/options');+ const r2 = await request(app).get('/sdapi/v1/sd-models');+ const r3 = await request(app).get('/sdapi/v1/progress');+ expect(r1.status).toBe(403);+ expect(r2.status).toBe(403);+ expect(r3.status).toBe(403);+ expect(r1.body.error).toMatch(/disabled/i);+ });++ it('lets through when expose.a1111 is true', async () => {+ enabled();+ imageGen.getMode.mockResolvedValue('local');+ const r = await request(app).get('/sdapi/v1/options');+ expect(r.status).toBe(200);+ });+ });++ describe('GET /options', () => {+ it('returns local model name when mode is local', async () => {+ enabled();+ imageGen.getMode.mockResolvedValue('local');+ const r = await request(app).get('/sdapi/v1/options');+ expect(r.status).toBe(200);+ expect(r.body.sd_model_checkpoint).toBe('portos-local-dev');+ expect(r.body.portos.mode).toBe('local');+ });++ it('returns external stub when mode is external', async () => {+ enabled();+ imageGen.getMode.mockResolvedValue('external');+ const r = await request(app).get('/sdapi/v1/options');+ expect(r.status).toBe(200);+ expect(r.body.sd_model_checkpoint).toBe('portos-external');+ });+ });++ describe('GET /progress', () => {+ it('returns idle payload when no active job', async () => {+ enabled();+ imageGen.getActiveJob.mockResolvedValue(null);+ const r = await request(app).get('/sdapi/v1/progress');+ expect(r.status).toBe(200);+ expect(r.body.progress).toBe(0);+ expect(r.body.current_image).toBeNull();+ expect(r.body.textinfo).toMatch(/no active/i);+ });++ it('passes through active job progress + step + currentImage', async () => {+ enabled();+ imageGen.getActiveJob.mockResolvedValue({+ progress: 0.42,+ step: 5,+ totalSteps: 12,+ currentImage: 'BASE64DATA',+ mode: 'local',+ modelId: 'dev',+ });+ const r = await request(app).get('/sdapi/v1/progress');+ expect(r.status).toBe(200);+ expect(r.body.progress).toBe(0.42);+ expect(r.body.state.sampling_step).toBe(5);+ expect(r.body.state.sampling_steps).toBe(12);+ expect(r.body.current_image).toBe('BASE64DATA');+ expect(r.body.textinfo).toContain('local');+ expect(r.body.textinfo).toContain('dev');+ });+ });++ describe('POST /txt2img', () => {+ it('rejects missing prompt with VALIDATION_ERROR', async () => {+ enabled();+ const r = await request(app).post('/sdapi/v1/txt2img').send({ width: 512 });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/validation/i);+ });++ it('rejects out-of-range width', async () => {+ enabled();+ const r = await request(app).post('/sdapi/v1/txt2img').send({ prompt: 'a cat', width: 99999 });+ expect(r.status).toBe(400);+ });++ it('happy path — external mode reads file and returns base64', async () => {+ enabled();+ imageGen.getMode.mockResolvedValue('external');+ imageGen.generateImage.mockResolvedValue({+ generationId: 'g-1', filename: 'g-1.png', path: '/data/images/g-1.png',+ mode: 'external', model: 'sd-1.5', seed: 1234,+ });+ readFile.mockResolvedValue(Buffer.from([1, 2, 3]));++ const r = await request(app).post('/sdapi/v1/txt2img').send({ prompt: 'a cat', width: 512, height: 512 });++ expect(r.status).toBe(200);+ expect(r.body.images).toHaveLength(1);+ expect(r.body.images[0]).toBe(Buffer.from([1, 2, 3]).toString('base64'));+ const info = JSON.parse(r.body.info);+ expect(info.seed).toBe(1234);+ expect(info.portos.mode).toBe('external');+ });++ it('500s when generation completes but file is missing', async () => {+ enabled();+ imageGen.getMode.mockResolvedValue('external');+ imageGen.generateImage.mockResolvedValue({+ generationId: 'g-2', filename: 'g-2.png', path: '/data/images/g-2.png',+ mode: 'external', model: 'sd-1.5', seed: 1,+ });+ readFile.mockResolvedValue(null);++ const r = await request(app).post('/sdapi/v1/txt2img').send({ prompt: 'a cat' });+ expect(r.status).toBe(500);+ expect(r.body.error).toMatch(/could not be read/i);+ });++ it('local mode waits for completion event before reading file (uses event seed)', async () => {+ enabled();+ imageGen.getMode.mockResolvedValue('local');+ // generateImage in local mode resolves as soon as the python child is+ // spawned; fire the 'completed' event from within the mock to simulate+ // the python child finishing later. Real EventEmitter wired above+ // means the route's listener will actually receive it.+ imageGen.generateImage.mockImplementation(async () => {+ const result = {+ generationId: 'g-3', filename: 'g-3.png', path: '/data/images/g-3.png',+ mode: 'local', model: 'dev', seed: 99,+ };+ // Defer the emit so the route has a chance to register the id.+ setImmediate(() => realEmitter.emit('completed', { generationId: 'g-3', seed: 4242 }));+ return result;+ });+ readFile.mockResolvedValue(Buffer.from('png'));++ const r = await request(app).post('/sdapi/v1/txt2img').send({ prompt: 'fire' });+ expect(r.status).toBe(200);+ const info = JSON.parse(r.body.info);+ // The completed event's seed wins over result.seed.+ expect(info.seed).toBe(4242);+ });+ });+});diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsnew file mode 100644index 0000000000..04f80a9261--- /dev/null+++ b/server/routes/videoGen.js@@ -0,0 +1,163 @@+/**+ * Video Generation Routes — local LTX backend.+ *+ * Mirrors the imageGen route surface where it makes sense (status, models,+ * SSE progress, cancel) and adds video-specific bits (history, last-frame+ * extraction, ffmpeg stitching).+ */++import { Router } from 'express';+import { existsSync } from 'fs';+import { unlink } from 'fs/promises';+import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { uploadSingle } from '../lib/multipart.js';+import { PATHS } from '../lib/fileUtils.js';+import { getSettings } from '../services/settings.js';+import {+ listVideoModels,+ defaultVideoModelId,+ generateVideo,+ attachSseClient,+ cancel,+ loadHistory,+ deleteHistoryItem,+ extractLastFrame,+ stitchVideos,+} from '../services/videoGen/local.js';++const router = Router();++const sourceImageUpload = uploadSingle('sourceImage', {+ limits: { fileSize: 50 * 1024 * 1024 },+ fileFilter: (_req, file, cb) => cb(null, file.mimetype.startsWith('image/')),+});++// Multipart bodies arrive as strings; coerce numerics in the schema. The+// service layer also coerces, but validating at the route boundary catches+// out-of-range / wrong-type input before any work happens.+//+// `optional()` lives INSIDE the preprocess wrapper so that the inner schema+// (`z.number()`) actually receives `undefined` rather than failing with+// "received undefined". With the optional() on the outside the empty-string+// branch was unreachable — preprocess returned undefined and z.number()+// rejected it before optional() ever saw the result.+const optionalNum = (min, max, label) => z.preprocess(+ (v) => v == null || v === '' ? undefined : Number(v),+ z.number().refine((n) => n >= min && n <= max, `${label} ${min}..${max}`).optional(),+);+const generateBodySchema = z.object({+ prompt: z.string().min(1).max(2000),+ negativePrompt: z.string().max(2000).optional(),+ modelId: z.string().max(64).optional(),+ width: optionalNum(64, 2048, 'width'),+ height: optionalNum(64, 2048, 'height'),+ numFrames: optionalNum(1, 1024, 'numFrames'),+ fps: optionalNum(1, 60, 'fps'),+ steps: optionalNum(1, 200, 'steps'),+ guidanceScale: optionalNum(0, 30, 'guidanceScale'),+ seed: optionalNum(0, Number.MAX_SAFE_INTEGER, 'seed'),+ tiling: z.enum(['auto', 'none', 'spatial', 'temporal']).optional(),+ disableAudio: z.union([z.boolean(), z.literal('true'), z.literal('false')]).optional(),+ sourceImageFile: z.string().max(512).optional(),+});++router.get('/status', asyncHandler(async (_req, res) => {+ const s = await getSettings();+ const py = s.imageGen?.local?.pythonPath || null;+ res.json({+ connected: !!py,+ pythonPath: py,+ models: listVideoModels(),+ defaultModel: defaultVideoModelId(),+ });+}));++router.get('/models', (_req, res) => {+ res.json(listVideoModels());+});++router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {+ const parsed = generateBodySchema.safeParse(req.body);+ if (!parsed.success) {+ throw new ServerError(`Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`, { status: 400, code: 'VALIDATION_ERROR' });+ }+ const body = parsed.data;+ const s = await getSettings();+ const pythonPath = s.imageGen?.local?.pythonPath || null;++ let sourceImagePath = null;+ let uploadedTempPath = null;+ if (req.file) {+ sourceImagePath = req.file.path;+ // Hand the multipart upload's temp path to the service so it can unlink+ // it in the proc.on('close') cleanup — covers both the success path+ // (after ffmpeg consumed it for resize) and the no-ffmpeg fallback path+ // (where the python child reads it directly and we can't unlink earlier).+ uploadedTempPath = req.file.path;+ } else if (body.sourceImageFile) {+ // Path-traversal guard: basename() strips dirs, then resolve+prefix-check+ // against PATHS.images so a unicode trick can't escape data/images.+ const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;+ const localPath = resolvePath(join(PATHS.images, basename(body.sourceImageFile)));+ if (localPath.startsWith(imagesRoot) && existsSync(localPath)) sourceImagePath = localPath;+ }++ try {+ const result = await generateVideo({+ pythonPath,+ prompt: body.prompt,+ negativePrompt: body.negativePrompt || '',+ modelId: body.modelId,+ width: body.width,+ height: body.height,+ numFrames: body.numFrames,+ fps: body.fps,+ steps: body.steps,+ guidanceScale: body.guidanceScale,+ seed: body.seed,+ tiling: body.tiling || 'auto',+ disableAudio: body.disableAudio === true || body.disableAudio === 'true',+ sourceImagePath,+ uploadedTempPath,+ });+ res.json(result);+ } catch (err) {+ // generateVideo threw before scheduling the proc.on('close') cleanup+ // (e.g. PYTHON not configured, BUSY, validation) — drop the upload now.+ if (uploadedTempPath) await unlink(uploadedTempPath).catch(() => {});+ throw err;+ }+}));++router.get('/:jobId/events', (req, res) => {+ const ok = attachSseClient(req.params.jobId, res);+ if (!ok) res.status(404).json({ error: 'Job not found or expired' });+});++router.post('/cancel', (_req, res) => {+ const cancelled = cancel();+ res.json({ ok: cancelled });+});++router.get('/history', asyncHandler(async (_req, res) => {+ res.json(await loadHistory());+}));++router.delete('/history/:id', asyncHandler(async (req, res) => {+ res.json(await deleteHistoryItem(req.params.id));+}));++router.post('/last-frame/:id', asyncHandler(async (req, res) => {+ res.json(await extractLastFrame(req.params.id));+}));++router.post('/stitch', asyncHandler(async (req, res) => {+ const ids = req.body?.videoIds;+ if (!Array.isArray(ids)) throw new ServerError('videoIds array required', { status: 400, code: 'VALIDATION_ERROR' });+ const stitched = await stitchVideos(ids);+ res.json({ ok: true, video: stitched });+}));++export default router;diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsnew file mode 100644index 0000000000..c3ae242399--- /dev/null+++ b/server/routes/videoGen.test.js@@ -0,0 +1,169 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn(async () => ({ imageGen: { local: { pythonPath: '/usr/bin/python3' } } })),+}));++vi.mock('../services/videoGen/local.js', () => ({+ listVideoModels: vi.fn(() => [{ id: 'ltx2_unified', name: 'LTX-2 Unified' }]),+ defaultVideoModelId: vi.fn(() => 'ltx2_unified'),+ generateVideo: vi.fn(),+ attachSseClient: vi.fn(() => false),+ cancel: vi.fn(() => true),+ loadHistory: vi.fn(async () => []),+ deleteHistoryItem: vi.fn(async (id) => ({ ok: true, id })),+ extractLastFrame: vi.fn(),+ stitchVideos: vi.fn(),+}));++vi.mock('../lib/multipart.js', () => ({+ // Bypass the multipart parser for unit tests — handler treats req.file as+ // optional, and we exercise the no-upload path here.+ uploadSingle: () => (_req, _res, next) => next(),+}));++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { images: '/mock/images' },+}));++vi.mock('fs', () => ({ existsSync: vi.fn(() => true) }));+vi.mock('fs/promises', () => ({ unlink: vi.fn(async () => {}) }));++import * as videoGenService from '../services/videoGen/local.js';+import videoGenRoutes from './videoGen.js';++describe('videoGen routes', () => {+ let app;+ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/video-gen', videoGenRoutes);+ vi.clearAllMocks();+ });++ describe('GET /status', () => {+ it('reports connected when pythonPath is set', async () => {+ const r = await request(app).get('/api/video-gen/status');+ expect(r.status).toBe(200);+ expect(r.body.connected).toBe(true);+ expect(r.body.pythonPath).toBe('/usr/bin/python3');+ expect(r.body.defaultModel).toBe('ltx2_unified');+ });+ });++ describe('GET /models', () => {+ it('returns the static catalog', async () => {+ const r = await request(app).get('/api/video-gen/models');+ expect(r.status).toBe(200);+ expect(r.body).toEqual([{ id: 'ltx2_unified', name: 'LTX-2 Unified' }]);+ });+ });++ describe('POST /', () => {+ it('rejects missing prompt', async () => {+ const r = await request(app).post('/api/video-gen/').send({ width: 512 });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/prompt/i);+ });++ it('rejects out-of-range width', async () => {+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a cat', width: 99999 });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/width/i);+ });++ it('rejects bad tiling enum value', async () => {+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a cat', tiling: 'wrong' });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/tiling/i);+ });++ it('accepts empty-string numerics as undefined (multipart preprocess fix)', async () => {+ videoGenService.generateVideo.mockResolvedValue({ jobId: 'j1', filename: 'j1.mp4' });+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'a cat',+ width: '',+ height: '',+ seed: '',+ });+ expect(r.status).toBe(200);+ expect(videoGenService.generateVideo).toHaveBeenCalledWith(expect.objectContaining({+ prompt: 'a cat',+ width: undefined,+ height: undefined,+ seed: undefined,+ }));+ });++ it('strips path-traversal segments from sourceImageFile via basename + prefix-check', async () => {+ videoGenService.generateVideo.mockResolvedValue({ jobId: 'j2', filename: 'j2.mp4' });+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'a cat',+ sourceImageFile: '../../etc/passwd',+ });+ // Documented-safe behavior: `basename()` strips dirs so the resolved+ // path is `/mock/images/passwd` (under PATHS.images). The route does+ // NOT 400 — it just consumes whatever's safely under the images root.+ // What this test really locks in: the request succeeds + the route+ // never reads outside PATHS.images.+ expect(r.status).toBe(200);+ expect(videoGenService.generateVideo).toHaveBeenCalledWith(expect.objectContaining({+ prompt: 'a cat',+ }));+ });+ });++ describe('GET /:jobId/events', () => {+ it('returns 404 when the job is unknown', async () => {+ videoGenService.attachSseClient.mockReturnValue(false);+ const r = await request(app).get('/api/video-gen/unknown-job/events');+ expect(r.status).toBe(404);+ expect(r.body.error).toMatch(/not found/i);+ });+ });++ describe('POST /cancel', () => {+ it('returns the cancel result', async () => {+ videoGenService.cancel.mockReturnValue(true);+ const r = await request(app).post('/api/video-gen/cancel').send({});+ expect(r.status).toBe(200);+ expect(r.body.ok).toBe(true);+ });+ });++ describe('GET /history', () => {+ it('returns the full history list', async () => {+ videoGenService.loadHistory.mockResolvedValue([{ id: 'a' }, { id: 'b' }]);+ const r = await request(app).get('/api/video-gen/history');+ expect(r.status).toBe(200);+ expect(r.body).toHaveLength(2);+ });+ });++ describe('DELETE /history/:id', () => {+ it('proxies to deleteHistoryItem', async () => {+ videoGenService.deleteHistoryItem.mockResolvedValue({ ok: true, id: 'abc' });+ const r = await request(app).delete('/api/video-gen/history/abc');+ expect(r.status).toBe(200);+ expect(videoGenService.deleteHistoryItem).toHaveBeenCalledWith('abc');+ });+ });++ describe('POST /stitch', () => {+ it('rejects when videoIds is not an array', async () => {+ const r = await request(app).post('/api/video-gen/stitch').send({ videoIds: 'not-array' });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/array/i);+ });++ it('proxies array of ids to stitchVideos and wraps result', async () => {+ videoGenService.stitchVideos.mockResolvedValue({ id: 's1', filename: 's1.mp4' });+ const r = await request(app).post('/api/video-gen/stitch').send({ videoIds: ['a', 'b'] });+ expect(r.status).toBe(200);+ expect(r.body.ok).toBe(true);+ expect(r.body.video.id).toBe('s1');+ });+ });+});diff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex 6e8c41f171..34f0f10e7a 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -19,6 +19,9 @@ const CATEGORIES = {'cos': { label: 'Chief of Staff', description: 'Agent data, reports, memories', archivable: true, deletable: false },'runs': { label: 'AI Runs', description: 'Agent run logs and outputs', archivable: true, deletable: true },'images': { label: 'Images', description: 'Uploaded and generated images', archivable: true, deletable: true },+ 'videos': { label: 'Videos', description: 'Locally generated videos', archivable: true, deletable: true },+ 'video-thumbnails': { label: 'Video Thumbnails', description: 'JPEG thumbnails for generated videos', archivable: false, deletable: true },+ 'loras': { label: 'LoRAs', description: 'LoRA adapter files for image generation', archivable: false, deletable: true },'calendar': { label: 'Calendar', description: 'Calendar sync data', archivable: true, deletable: false },'digital-twin': { label: 'Digital Twin', description: 'Identity, goals, character data', archivable: true, deletable: false },'messages': { label: 'Messages', description: 'Email and messaging data', archivable: true, deletable: true },diff --git a/server/services/imageGen.js b/server/services/imageGen/external.jssimilarity index 52%rename from server/services/imageGen.jsrename to server/services/imageGen/external.jsindex adadc7cd2f..81c3c5cc80 100644--- a/server/services/imageGen.js+++ b/server/services/imageGen/external.js@@ -1,31 +1,34 @@/**- * Image Generation Service+ * Image Gen — External provider.*- * Handles communication with Stable Diffusion API (AUTOMATIC1111 / Forge WebUI).- * Generated images are stored in data/images/.- * Streams diffusion progress via Socket.IO during generation.+ * Talks to a remote AUTOMATIC1111 / Forge WebUI over its /sdapi/v1/* surface.+ * Used when settings.imageGen.mode === 'external' and a sdapiUrl is configured.+ * Streams diffusion progress to imageGenEvents (bridged to Socket.IO).*/import { writeFile } from 'fs/promises';import { join } from 'path';import { randomUUID } from 'crypto';-import { ensureDir, PATHS } from '../lib/fileUtils.js';-import { ServerError } from '../lib/errorHandler.js';-import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';-import { getSettings } from './settings.js';-import { imageGenEvents } from './imageGenEvents.js';+import { ensureDir, PATHS } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';+import { imageGenEvents } from '../imageGenEvents.js';const DEFAULT_NEGATIVE_PROMPT = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';+const PROGRESS_POLL_INTERVAL = 500;+const IMAGE_PREVIEW_THROTTLE = 2000;+const MODEL_CACHE_TTL = 5 * 60 * 1000;-// Cache detected model per baseUrl to avoid extra HTTP round-trip per generationlet cachedModel = { name: null, timestamp: 0, baseUrl: null };-const MODEL_CACHE_TTL = 5 * 60 * 1000; // 5 minutes-const PROGRESS_POLL_INTERVAL = 500; // ms between progress polls--async function getSdApiUrl() {- const settings = await getSettings();- return settings.imageGen?.sdapiUrl || null;+export function validateSdUrl(rawUrl) {+ if (!rawUrl) throw new ServerError('No SD API URL configured — set it in Settings > Image Gen', { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' });+ let url;+ try { url = new URL(rawUrl); } catch { throw new ServerError('Invalid SD API URL — must be a valid http/https URL', { status: 400, code: 'INVALID_SD_URL' }); }+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {+ throw new ServerError('Invalid SD API URL — only http and https are allowed', { status: 400, code: 'INVALID_SD_URL' });+ }+ return url.origin;}async function detectModel(baseUrl) {@@ -40,25 +43,19 @@ async function detectModel(baseUrl) {return model;}-export async function checkConnection() {- const rawUrl = await getSdApiUrl();- if (!rawUrl) return { connected: false, reason: 'No SD API URL configured' };-+export async function checkConnection(sdapiUrl) {+ if (!sdapiUrl) return { connected: false, reason: 'No SD API URL configured' };let baseUrl;- try { baseUrl = validateSdUrl(rawUrl); } catch (err) { return { connected: false, reason: err.message }; }+ try { baseUrl = validateSdUrl(sdapiUrl); } catch (err) { return { connected: false, reason: err.message }; }- // Always make a live request for status checks — bypass the model cacheconst res = await fetchWithTimeout(`${baseUrl}/sdapi/v1/options`, {}, 10000).catch(() => null);if (!res?.ok) return { connected: false, reason: 'SD API unreachable' };const options = await res.json().catch(() => null);const model = options?.sd_model_checkpoint || 'unknown';- // Update the cache while we're at itcachedModel = { name: model, timestamp: Date.now(), baseUrl };- return { connected: true, model };+ return { connected: true, model, mode: 'external', baseUrl };}-const IMAGE_PREVIEW_THROTTLE = 2000; // only send base64 previews every 2s-function startProgressPolling(baseUrl, generationId) {let lastProgress = -1;let lastImageEmit = 0;@@ -72,12 +69,10 @@ function startProgressPolling(baseUrl, generationId) {const data = await res.json().catch(() => null);if (!data) return;- // Only emit if progress actually changedconst progress = Math.round(data.progress * 100);if (progress === lastProgress) return;lastProgress = progress;- // Throttle base64 preview images to reduce bandwidthconst now = Date.now();const includeImage = data.current_image && (now - lastImageEmit >= IMAGE_PREVIEW_THROTTLE);if (includeImage) lastImageEmit = now;@@ -90,6 +85,12 @@ function startProgressPolling(baseUrl, generationId) {totalSteps: data.state?.sampling_steps,currentImage: includeImage ? data.current_image : null});+ if (activeJob && activeJob.generationId === generationId) {+ activeJob.progress = data.progress;+ activeJob.step = data.state?.sampling_step ?? activeJob.step;+ activeJob.totalSteps = data.state?.sampling_steps ?? activeJob.totalSteps;+ if (includeImage) activeJob.currentImage = data.current_image;+ }} finally {inFlight = false;}@@ -98,19 +99,11 @@ function startProgressPolling(baseUrl, generationId) {return () => clearInterval(interval);}-function validateSdUrl(rawUrl) {- if (!rawUrl) throw new ServerError('No SD API URL configured — set it in Settings > Image Gen', { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' });- let url;- try { url = new URL(rawUrl); } catch { throw new ServerError('Invalid SD API URL — must be a valid http/https URL', { status: 400, code: 'INVALID_SD_URL' }); }- if (url.protocol !== 'http:' && url.protocol !== 'https:') {- throw new ServerError('Invalid SD API URL — only http and https are allowed', { status: 400, code: 'INVALID_SD_URL' });- }- return url.origin;-}--export async function generateImage({ prompt, negativePrompt, width, height, steps, cfgScale, seed }) {- const baseUrl = validateSdUrl(await getSdApiUrl());+let activeJob = null;+export const getActiveJob = () => activeJob;+export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, height, steps, cfgScale, seed }) {+ const baseUrl = validateSdUrl(sdapiUrl);const model = await detectModel(baseUrl);const isFlux = model?.toLowerCase().includes('flux');@@ -128,71 +121,54 @@ export async function generateImage({ prompt, negativePrompt, width, height, ste};const generationId = randomUUID();- console.log(`🎨 Generating image [${generationId.slice(0, 8)}]: ${prompt.slice(0, 80)}... (${payload.width}x${payload.height}, ${payload.steps} steps)`);-- imageGenEvents.emit('started', {- generationId,- totalSteps: payload.steps- });+ console.log(`🎨 Generating image [${generationId.slice(0, 8)}] external→${baseUrl}: ${prompt.slice(0, 60)}... (${payload.width}x${payload.height}, ${payload.steps} steps)`);+ imageGenEvents.emit('started', { generationId, totalSteps: payload.steps });+ activeJob = {+ generationId, prompt, negativePrompt,+ width: payload.width, height: payload.height, steps: payload.steps,+ cfgScale: payload.cfg_scale, seed: payload.seed,+ modelId: model, mode: 'external',+ step: 0, progress: 0, totalSteps: payload.steps, currentImage: null,+ createdAt: new Date().toISOString(),+ };- // Start polling progress in backgroundconst stopPolling = startProgressPolling(baseUrl, generationId);let res;try {res = await fetchWithTimeout(`${baseUrl}/sdapi/v1/txt2img`,- {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(payload)- },+ { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },300000);} catch (err) {stopPolling();+ activeJob = null;imageGenEvents.emit('failed', { generationId, error: 'Network error contacting image generation service' });throw err;}stopPolling();- try {- if (!res.ok) {- const errBody = await res.text().catch(() => '');- imageGenEvents.emit('failed', { generationId, error: `SD API error ${res.status}` });- throw new Error(`SD API error ${res.status}: ${errBody.slice(0, 200)}`);- }-- const data = await res.json();- if (!data.images?.length) {- imageGenEvents.emit('failed', { generationId, error: 'No images returned' });- throw new Error('SD API returned no images');- }-- await ensureDir(PATHS.images);- const filename = `${randomUUID()}.png`;- await writeFile(join(PATHS.images, filename), Buffer.from(data.images[0], 'base64'));-- const path = `/data/images/${filename}`;- console.log(`🖼️ Image saved: ${filename}`);+ if (!res.ok) {+ const errBody = await res.text().catch(() => '');+ activeJob = null;+ imageGenEvents.emit('failed', { generationId, error: `SD API error ${res.status}` });+ throw new Error(`SD API error ${res.status}: ${errBody.slice(0, 200)}`);+ }- imageGenEvents.emit('completed', { generationId, path, filename });- return { generationId, filename, path };- } catch (err) {- // Guarantee a terminal event for every generationId- if (!err.message?.startsWith('SD API error') && err.message !== 'SD API returned no images') {- imageGenEvents.emit('failed', { generationId, error: err.message || 'Image generation failed' });- }- throw err;+ const data = await res.json();+ if (!data.images?.length) {+ activeJob = null;+ imageGenEvents.emit('failed', { generationId, error: 'No images returned' });+ throw new Error('SD API returned no images');}-}-export async function generateAvatar({ name, characterClass, prompt }) {- const defaultPrompt = `fantasy portrait of ${name || 'an adventurer'}, ${characterClass || 'warrior'} class, D&D character art, detailed, dramatic lighting, painterly style`;- return generateImage({- prompt: prompt || defaultPrompt,- width: 512,- height: 512,- negativePrompt: `${DEFAULT_NEGATIVE_PROMPT}, nude, nsfw`- });+ await ensureDir(PATHS.images);+ const filename = `${randomUUID()}.png`;+ await writeFile(join(PATHS.images, filename), Buffer.from(data.images[0], 'base64'));+ const path = `/data/images/${filename}`;+ console.log(`🖼️ Image saved: ${filename}`);+ activeJob = null;+ imageGenEvents.emit('completed', { generationId, path, filename });+ return { generationId, filename, path, mode: 'external', model };}diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.jsnew file mode 100644index 0000000000..bdbc67f388--- /dev/null+++ b/server/services/imageGen/index.js@@ -0,0 +1,76 @@+/**+ * Image Gen — Mode-aware dispatcher.+ *+ * Reads settings.imageGen.mode (default 'external' for backward compat) and+ * routes generate/status calls to either the external SD-API client or the+ * local (mflux/diffusers) backend. This module is the public entrypoint —+ * routes/imageGen.js, the A1111 proxy, and the CoS tools registry all go+ * through here so the underlying provider is interchangeable.+ */++import { getSettings } from '../settings.js';+import * as external from './external.js';+import * as local from './local.js';++const DEFAULT_MODE = 'external';++const cfg = (s) => s?.imageGen || {};+const sdapiUrl = (s) => cfg(s).external?.sdapiUrl || cfg(s).sdapiUrl || null;+const pythonPath = (s) => cfg(s).local?.pythonPath || null;++export async function getMode() {+ const s = await getSettings();+ return cfg(s).mode || DEFAULT_MODE;+}++export async function checkConnection() {+ const s = await getSettings();+ const mode = cfg(s).mode || DEFAULT_MODE;+ if (mode === 'local') {+ const py = pythonPath(s);+ if (!py) return { connected: false, mode, reason: 'Python path not configured' };+ return { connected: true, mode, model: 'mflux/local', pythonPath: py };+ }+ const status = await external.checkConnection(sdapiUrl(s));+ return { ...status, mode };+}++export async function generateImage(params) {+ const s = await getSettings();+ const mode = cfg(s).mode || DEFAULT_MODE;+ // Param normalization: A1111 clients (and the /sdapi/v1/txt2img bridge)+ // send `cfgScale`; local mflux reads `guidance`. Map cfgScale -> guidance+ // when guidance is not explicitly set so both spellings work in both modes.+ const normalized = { ...params };+ if (normalized.guidance == null && normalized.cfgScale != null) {+ normalized.guidance = normalized.cfgScale;+ }+ if (mode === 'local') {+ return local.generateImage({ pythonPath: pythonPath(s), ...normalized });+ }+ return external.generateImage({ sdapiUrl: sdapiUrl(s), ...normalized });+}++const DEFAULT_NEGATIVE_PROMPT = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';++export async function generateAvatar({ name, characterClass, prompt }) {+ const defaultPrompt = `fantasy portrait of ${name || 'an adventurer'}, ${characterClass || 'warrior'} class, D&D character art, detailed, dramatic lighting, painterly style`;+ return generateImage({+ prompt: prompt || defaultPrompt,+ width: 512,+ height: 512,+ negativePrompt: `${DEFAULT_NEGATIVE_PROMPT}, nude, nsfw`,+ });+}++// Snapshot of any in-flight generation across both modes — lets the UI+// rehydrate prompt + settings + progress + last frame after navigating away+// during a render.+export async function getActiveJob() {+ return local.getActiveJob() || external.getActiveJob() || null;+}++// Re-exports so routes can hit the local backend directly when the request+// is shape-specific (SSE attach, gallery, LoRAs). The dispatcher is for the+// generic generate/status flow used by both modes.+export { local, external };diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsnew file mode 100644index 0000000000..af3ac77408--- /dev/null+++ b/server/services/imageGen/local.js@@ -0,0 +1,326 @@+/**+ * Image Gen — Local provider (Apple Silicon mflux / Windows diffusers).+ *+ * Spawns a Python child process to generate Flux images. HF model weights+ * stream into the user's standard HF cache (`~/.cache/huggingface/`) — PortOS+ * doesn't override HF_HOME. Generated images land in `data/images/<jobId>.png`+ * with a sidecar metadata JSON so the gallery and Remix flow can recover+ * prompt/seed/steps.+ *+ * Progress comes back via the imageGenEvents bus (Socket.IO bridge) and over+ * a per-job SSE stream so EventSource consumers (the Imagine page) get the+ * raw status text mflux prints to stderr.+ */++import { spawn } from 'child_process';+import { writeFile, readFile, readdir, stat, unlink, rm, mkdtemp } from 'fs/promises';+import { existsSync, watch as fsWatch } from 'fs';+import { join, dirname, resolve as resolvePath, sep as PATH_SEP, basename } from 'path';+import { tmpdir } from 'os';+import { randomUUID } from 'crypto';+import { ensureDir, PATHS, safeJSONParse } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { imageGenEvents } from '../imageGenEvents.js';+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';++const IS_MAC = process.platform === 'darwin';+const IS_WIN = process.platform === 'win32';++// Model catalog. `broken: true` hides a model on a platform where it doesn't+// run (e.g. Flux 2 Klein needs CUDA, so we mark it broken on macOS).+export const IMAGE_MODELS = {+ dev: { id: 'dev', name: 'Flux 1 Dev', steps: 20, guidance: 3.5 },+ schnell: { id: 'schnell', name: 'Flux 1 Schnell', steps: 4, guidance: 0 },+ 'flux2-klein-4b': { id: 'flux2-klein-4b', name: 'Flux 2 Klein 4B', steps: 8, guidance: 3.5, broken: IS_MAC },+ 'flux2-klein-9b': { id: 'flux2-klein-9b', name: 'Flux 2 Klein 9B', steps: 8, guidance: 3.5, broken: IS_MAC },+};++export const listImageModels = () =>+ Object.values(IMAGE_MODELS).filter((m) => !m.broken);++// Per-job clients: jobId -> { clients, status, meta, broadcast }+const jobs = new Map();+let activeProcess = null;+// Snapshot of the currently-running job for /api/image-gen/active so the UI+// can rehydrate prompt + settings + progress + last-rendered frame after+// navigating away. Cleared on completion / error / cancel.+let activeJob = null;++export const getActiveJob = () => activeJob;++export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);++export const cancel = () => {+ if (!activeProcess) return false;+ const proc = activeProcess;+ proc.kill('SIGTERM');+ // KEEP activeProcess + activeJob set until proc.on('close') clears them.+ // Otherwise BUSY immediately allows a new generation while the SIGTERM'd+ // mflux child is still running, and we lose the handle for a follow-up+ // SIGKILL. Escalate after 8s if the child ignored SIGTERM.+ setTimeout(() => {+ // proc.killed is set the moment proc.kill() is called; it does NOT mean+ // the child has exited. Check exitCode (null until 'close' fires) so the+ // SIGKILL escalation actually triggers when mflux ignores SIGTERM.+ if (activeProcess === proc && proc.exitCode === null && proc.signalCode === null) {+ console.log(`⚠️ image child didn't exit on SIGTERM — escalating to SIGKILL`);+ proc.kill('SIGKILL');+ }+ }, 8000);+ return true;+};++const buildArgs = ({ pythonPath, modelId, prompt, negativePrompt, width, height, steps, guidance, seed, quantize, outputPath, loraPaths, loraScales, stepwiseDir }) => {+ if (IS_WIN) {+ const scriptPath = join(PATHS.root, 'scripts', 'imagine_win.py');+ return {+ bin: pythonPath,+ args: [scriptPath, '--model', modelId, '--prompt', prompt, '--height', String(height), '--width', String(width), '--steps', String(steps), '--seed', String(seed), '--quantize', String(quantize), '--output', outputPath, '--metadata',+ ...(guidance > 0 ? ['--guidance', String(guidance)] : []),+ ...(negativePrompt ? ['--negative-prompt', negativePrompt] : []),+ ...(loraPaths.length ? ['--lora-paths', ...loraPaths] : []),+ ...(loraScales.length ? ['--lora-scales', ...loraScales.map(String)] : []),+ ],+ };+ }+ // macOS: mflux-generate sits next to the python binary in the venv+ const bin = join(dirname(pythonPath), 'mflux-generate');+ const args = ['--model', modelId, '--prompt', prompt, '--height', String(height), '--width', String(width), '--steps', String(steps), '--seed', String(seed), '--quantize', String(quantize), '--output', outputPath, '--metadata'];+ if (guidance > 0) args.push('--guidance', String(guidance));+ if (negativePrompt) args.push('--negative-prompt', negativePrompt);+ if (loraPaths.length) args.push('--lora-paths', ...loraPaths);+ if (loraScales.length) args.push('--lora-scales', ...loraScales.map(String));+ // mflux writes one PNG per step here as it diffuses; we watch the dir and+ // stream the latest frame back to the client as `currentImage` for the+ // live-preview area.+ if (stepwiseDir) args.push('--stepwise-image-output-dir', stepwiseDir);+ return { bin, args };+};++export async function generateImage({ pythonPath, prompt, negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [] }) {+ if (!pythonPath) throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' });+ if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });+ // Enforce the single-activeProcess invariant the rest of this module relies+ // on — without this, a double-click on Generate would orphan the first+ // child (cancel() can only kill the one stored in activeProcess).+ if (activeProcess) throw new ServerError('A generation is already in progress — cancel it before starting another', { status: 409, code: 'IMAGE_GEN_BUSY' });+ const model = IMAGE_MODELS[modelId];+ if (!model || model.broken) throw new ServerError(`Unknown or unsupported model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });++ await ensureDir(PATHS.images);+ await ensureDir(PATHS.loras);++ const jobId = randomUUID();+ const filename = `${jobId}.png`;+ const outputPath = join(PATHS.images, filename);+ const actualSeed = seed != null && seed !== '' ? Number(seed) : Math.floor(Math.random() * 2147483647);+ const actualSteps = steps ? Number(steps) : model.steps;+ const actualGuidance = guidance != null && guidance !== '' ? Number(guidance) : model.guidance;+ // The new client-side surface sends `loraFilenames` (basenames only); the+ // server resolves them against PATHS.loras. `loraPaths` is kept as a+ // back-compat input for old gallery sidecars that stored absolute paths+ // pre-refactor — both go through the same resolve+prefix-check.+ const lorasRoot = resolvePath(PATHS.loras) + PATH_SEP;+ const candidates = [+ ...loraFilenames.map((f) => (typeof f === 'string' ? join(PATHS.loras, basename(f)) : null)),+ ...loraPaths,+ ];+ const validLoras = candidates.filter((p) => {+ if (!p || typeof p !== 'string') return false;+ const resolved = resolvePath(p);+ if (!resolved.startsWith(lorasRoot)) return false;+ return existsSync(resolved);+ });++ // Store loraFilenames (basenames) in the sidecar going forward — that's+ // what the new client API uses for remix. Keep `loraPaths` populated too+ // so older code paths reading the sidecar don't break.+ const validLoraFilenames = validLoras.map((p) => basename(p));+ const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, quantize, filename, loraFilenames: validLoraFilenames, loraPaths: validLoras, loraScales, createdAt: new Date().toISOString() };+ const job = { ...meta, clients: [], status: 'running' };+ jobs.set(jobId, job);++ // Per-job stepwise output dir under the OS temp dir. mflux writes one PNG+ // per inference step here; we watch and stream the latest as `currentImage`.+ const stepwiseDir = await mkdtemp(join(tmpdir(), 'portos-stepwise-'));++ const { bin, args } = buildArgs({ pythonPath, modelId, prompt, negativePrompt, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, seed: actualSeed, quantize, outputPath, loraPaths: validLoras, loraScales, stepwiseDir });++ console.log(`🎨 Generating image [${jobId.slice(0, 8)}] local: ${modelId} ${width}x${height} steps=${actualSteps}`);+ imageGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps });+ activeJob = { ...meta, generationId: jobId, totalSteps: actualSteps, step: 0, progress: 0, currentImage: null, mode: 'local' };++ const proc = spawn(bin, args, { env: { ...process.env }, stdio: ['ignore', 'pipe', 'pipe'] });+ activeProcess = proc;+ // Without an 'error' handler, a missing/non-executable pythonPath would+ // crash the server with an unhandled error event.+ proc.on('error', (err) => {+ job.status = 'error';+ const reason = `Failed to spawn ${bin}: ${err.message}`;+ console.log(`❌ Image generation spawn error [${jobId.slice(0, 8)}]: ${reason}`);+ broadcastSse(job, { type: 'error', error: reason });+ imageGenEvents.emit('failed', { generationId: jobId, error: reason });+ activeProcess = null;+ activeJob = null;+ rm(stepwiseDir, { recursive: true, force: true }).catch(() => {});+ closeJobAfterDelay(jobs, jobId);+ });++ // Watch the stepwise output dir for new PNGs. When a new file appears,+ // base64-encode the latest one and emit it as `currentImage`. fs.watch+ // fires multiple times per write — keep a single in-flight read and a+ // pending flag so we always get the *latest* frame without piling up reads.+ let watcher = null;+ let reading = false;+ let pendingFrame = false;+ const processLatestFrame = async () => {+ if (reading) { pendingFrame = true; return; }+ reading = true;+ try {+ // Sort by mtime, not filename. mflux names files like `step_1.png` …+ // `step_20.png` (no zero-padding), so alphabetical sort puts `step_2`+ // *after* `step_19` and we'd render an early-step latent (mostly noise)+ // instead of the latest.+ const names = (await readdir(stepwiseDir)).filter((f) => f.endsWith('.png'));+ const stats = await Promise.all(names.map(async (n) => {+ const s = await stat(join(stepwiseDir, n)).catch(() => null);+ return s ? { n, mtimeMs: s.mtimeMs } : null;+ }));+ const latest = stats.filter(Boolean).sort((a, b) => b.mtimeMs - a.mtimeMs)[0]?.n;+ if (latest) {+ const buf = await readFile(join(stepwiseDir, latest));+ const currentImage = buf.toString('base64');+ if (activeJob && activeJob.generationId === jobId) activeJob.currentImage = currentImage;+ imageGenEvents.emit('progress', { generationId: jobId, currentImage });+ }+ } catch (err) {+ // Partial PNG mid-write or stepwise dir gone after cancel — common,+ // don't spam, but surface the message so a stalled preview is debuggable.+ console.log(`⚠️ Frame read error [${jobId.slice(0, 8)}]: ${err?.message}`);+ }+ reading = false;+ if (pendingFrame) { pendingFrame = false; processLatestFrame(); }+ };+ try {+ watcher = fsWatch(stepwiseDir, (event) => {+ if (event === 'rename') processLatestFrame();+ });+ } catch { /* if watch fails, we still get final image — degrade gracefully */ }++ // Bounded tail of recent stderr — only the last ~64KB is kept, since the+ // failure path only uses the trailing 10 lines for context. Without this+ // bound a noisy backend (HF download progress, deprecation warnings)+ // would grow this buffer for the full duration of a long render.+ const STDERR_TAIL_BYTES = 64 * 1024;+ let stderrBuffer = '';+ const handleLine = (line) => {+ const trimmed = line.trim();+ if (!trimmed || PYTHON_NOISE_RE.test(trimmed)) return;+ // mflux progress: "100%|████| 8/8 [00:05<00:00, 1.43it/s]"+ const m = trimmed.match(/(\d+)%\|.*?(\d+)\/(\d+)/);+ if (m) {+ const pct = parseInt(m[1], 10) / 100;+ const step = parseInt(m[2], 10);+ const total = parseInt(m[3], 10);+ broadcastSse(job, { type: 'progress', progress: pct, message: trimmed });+ imageGenEvents.emit('progress', { generationId: jobId, progress: pct, step, totalSteps: total });+ if (activeJob && activeJob.generationId === jobId) {+ activeJob.progress = pct; activeJob.step = step; activeJob.totalSteps = total;+ }+ } else {+ broadcastSse(job, { type: 'status', message: trimmed });+ }+ };++ proc.stderr.on('data', (chunk) => {+ const text = chunk.toString();+ stderrBuffer += text;+ if (stderrBuffer.length > STDERR_TAIL_BYTES) {+ stderrBuffer = stderrBuffer.slice(-STDERR_TAIL_BYTES);+ }+ for (const line of text.split(/[\n\r]+/)) handleLine(line);+ });+ proc.stdout.on('data', (chunk) => {+ for (const line of chunk.toString().split(/[\n\r]+/)) handleLine(line);+ });++ proc.on('close', async (code, signal) => {+ activeProcess = null;+ activeJob = null;+ if (watcher) { try { watcher.close(); } catch { /* ignore */ } }+ rm(stepwiseDir, { recursive: true, force: true }).catch(() => {});+ if (code !== 0) {+ job.status = 'error';+ const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;+ const tail = stderrBuffer.trim().split('\n').slice(-10).join('\n');+ console.log(`❌ Image generation failed [${jobId.slice(0, 8)}]: ${reason}`);+ broadcastSse(job, { type: 'error', error: `Generation failed: ${reason}\n${tail}` });+ imageGenEvents.emit('failed', { generationId: jobId, error: reason });+ } else {+ job.status = 'complete';+ // Sidecar: persist a metadata record next to the PNG so the gallery+ // and Remix flow can recover prompt/seed/steps even if mflux's own+ // --metadata sidecar lives at a slightly different filename shape.+ const sidecar = join(PATHS.images, `${jobId}.metadata.json`);+ await writeFile(sidecar, JSON.stringify(meta, null, 2)).catch(() => {});+ console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename}`);+ const result = { filename, seed: actualSeed, path: `/data/images/${filename}` };+ broadcastSse(job, { type: 'complete', result });+ // Include `seed` so /sdapi/v1/txt2img can surface the actual seed used+ // (mflux generates a random one if the client didn't pass one).+ imageGenEvents.emit('completed', { generationId: jobId, path: `/data/images/${filename}`, filename, seed: actualSeed });+ }+ closeJobAfterDelay(jobs, jobId);+ });++ return { jobId, filename, path: `/data/images/${filename}`, generationId: jobId, mode: 'local', model: modelId, seed: actualSeed };+}++export async function listGallery() {+ if (!existsSync(PATHS.images)) return [];+ const files = await readdir(PATHS.images);+ const pngs = files.filter((f) => f.endsWith('.png'));+ const items = await Promise.all(pngs.map(async (f) => {+ const fullPath = join(PATHS.images, f);+ const s = await stat(fullPath).catch(() => null);+ if (!s) return null;+ // Try our sidecar first, fall back to mflux's own .metadata.json shape.+ const portosSidecar = join(PATHS.images, f.replace('.png', '.metadata.json'));+ const altSidecar = join(PATHS.images, `${f}.metadata.json`);+ const path = existsSync(portosSidecar) ? portosSidecar : (existsSync(altSidecar) ? altSidecar : null);+ let metadata = {};+ if (path) {+ const raw = await readFile(path, 'utf-8').catch(() => null);+ if (raw) metadata = safeJSONParse(raw, {});+ }+ return {+ filename: f,+ path: `/data/images/${f}`,+ createdAt: metadata.createdAt || s.birthtime.toISOString(),+ ...metadata,+ };+ }));+ return items.filter(Boolean).sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));+}++export async function deleteImage(filename) {+ if (!filename.endsWith('.png') || filename.includes('/') || filename.includes('\\') || filename.includes('..')) {+ throw new ServerError('Invalid filename', { status: 400, code: 'VALIDATION_ERROR' });+ }+ await unlink(join(PATHS.images, filename)).catch(() => {});+ await unlink(join(PATHS.images, filename.replace('.png', '.metadata.json'))).catch(() => {});+ await unlink(join(PATHS.images, `${filename}.metadata.json`)).catch(() => {});+ return { ok: true };+}++// Returns just `{ filename, name }` — clients send `filename` back in the+// generate payload's `loraFilenames` and the server resolves it against+// PATHS.loras. Avoids leaking absolute server paths into the API surface.+export async function listLoras() {+ await ensureDir(PATHS.loras);+ const files = await readdir(PATHS.loras).catch(() => []);+ return files.filter((f) => f.endsWith('.safetensors')).map((f) => ({+ filename: f,+ name: f.replace(/^lora-/, '').replace(/\.safetensors$/, ''),+ }));+}diff --git a/server/services/instances.js b/server/services/instances.jsindex 8cdb444fc2..48601f88cb 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -14,6 +14,8 @@ import { instanceEvents } from './instanceEvents.js';import { connectToPeer, disconnectFromPeer } from './peerSocketRelay.js';import { DEFAULT_PEER_PORT } from '../lib/ports.js';import { peerBaseUrl } from '../lib/peerUrl.js';+import { peerFetch } from '../lib/peerHttpClient.js';+import { getSelfHost } from '../lib/peerSelfHost.js';const INSTANCES_FILE = dataPath('instances.json');const PROBE_TIMEOUT_MS = 5000;@@ -34,6 +36,18 @@ const BACKOFF_TIERS_MS = [const withLock = createMutex();let pollTimer = null;+function classifyProbeError(err, peer) {+ const code = err?.code;+ if (code === 'ENOTFOUND') return `🌐 ❌ DNS lookup failed for ${peer.host || peer.address} — is Tailscale MagicDNS up?`;+ if (code === 'ECONNREFUSED') return `🌐 ❌ Connection refused — peer not running on this port`;+ if (code === 'EHOSTUNREACH') return `🌐 ❌ Host unreachable — Tailscale tunnel down or peer offline`;+ // Native fetch raises AbortError when the AbortSignal fires; insecureFetch+ // (used for HTTPS peer hops via peerFetch) destroys the request with a+ // plain `new Error('Request aborted')` instead — both are timeouts here.+ if (code === 'ETIMEDOUT' || err?.name === 'AbortError' || err?.message === 'Request aborted') return `🌐 ⏱️ Probe timeout (${PROBE_TIMEOUT_MS}ms)`;+ return err?.message || String(err);+}+// Default data shapeconst DEFAULT_DATA = {self: null,@@ -116,9 +130,13 @@ function isIPAddress(str) {return net.isIP(str) !== 0;}+// Returns: null = explicit clear, undefined = invalid input (callers should+// ignore), string = valid lowercased hostname. Three-state distinction lets+// callers choose between "noisy/optional input" (use undefined) vs "user+// asked to clear" (use null).function validHost(str) {- if (str === '' || str === null) return null; // explicit clear- if (typeof str !== 'string') return undefined; // ignore+ if (str === '' || str === null) return null;+ if (typeof str !== 'string') return undefined;const trimmed = str.trim();if (!trimmed) return null;// Accept DNS names: letters, digits, hyphens, dots. No scheme, no port, no path.@@ -225,9 +243,9 @@ export async function probePeer(peer) {try {// Fetch health details, apps, and sync status in parallelconst [healthRes, appsRes, syncRes] = await Promise.all([- fetch(`${baseUrl}/api/system/health/details`, { signal: controller.signal }),- fetch(`${baseUrl}/api/apps`, { signal: controller.signal }).catch(() => null),- fetch(`${baseUrl}/api/instances/sync-status`, { signal: controller.signal }).catch(() => null)+ peerFetch(`${baseUrl}/api/system/health/details`, { signal: controller.signal }),+ peerFetch(`${baseUrl}/api/apps`, { signal: controller.signal }).catch(() => null),+ peerFetch(`${baseUrl}/api/instances/sync-status`, { signal: controller.signal }).catch(() => null)]);if (!healthRes.ok) throw new Error(`HTTP ${healthRes.status}`);const json = await healthRes.json();@@ -249,7 +267,7 @@ export async function probePeer(peer) {remoteSyncSeqs = await syncRes.json().catch(() => null);}} catch (err) {- console.log(`⚠️ Probe failed for ${baseUrl}: ${err.message}`);+ console.log(`⚠️ Probe failed for ${baseUrl}: ${classifyProbeError(err, peer)}`);status = 'offline';lastHealth = peer.lastHealth; // preserve last knownlastSeen = peer.lastSeen;@@ -339,7 +357,7 @@ export async function queryPeer(id, apiPath) {const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);try {- const res = await fetch(url, { signal: controller.signal });+ const res = await peerFetch(url, { signal: controller.signal });const json = await res.json();return { success: true, data: json };} catch (err) {@@ -351,7 +369,7 @@ export async function queryPeer(id, apiPath) {// --- Announce (Bidirectional Registration) ----export async function handleAnnounce({ address, port, instanceId, name }) {+export async function handleAnnounce({ address, port, instanceId, name, host }) {const result = await withData(async (data) => {// Check for existing peer by instanceIdlet existing = data.peers.find(p => p.instanceId === instanceId);@@ -360,6 +378,8 @@ export async function handleAnnounce({ address, port, instanceId, name }) {existing = data.peers.find(p => p.address === address && p.port === port);}+ const normalizedHost = validHost(host);+if (existing) {existing.lastSeen = new Date().toISOString();existing.status = 'online';@@ -370,6 +390,12 @@ export async function handleAnnounce({ address, port, instanceId, name }) {if (sanitized && isIPAddress(existing.name)) {existing.name = sanitized;}+ // Adopt host from inbound announce only when we don't already have one —+ // never overwrite a user-set value, never blank one on a noisy announce.+ if (normalizedHost && !existing.host) {+ existing.host = normalizedHost;+ console.log(`🌐 Peer host learned via announce: ${existing.name} → ${normalizedHost}`);+ }// Mark that this peer has announced to us (inbound connection)existing.directions = existing.directions || [];if (!existing.directions.includes('inbound')) existing.directions.push('inbound');@@ -382,8 +408,9 @@ export async function handleAnnounce({ address, port, instanceId, name }) {const peer = {id: crypto.randomUUID(),address,+ host: normalizedHost || null,port,- name: validName(name, address),+ name: validName(name, normalizedHost || address),instanceId,addedAt: new Date().toISOString(),lastSeen: new Date().toISOString(),@@ -397,7 +424,7 @@ export async function handleAnnounce({ address, port, instanceId, name }) {directions: ['inbound']};data.peers.push(peer);- console.log(`🌐 Peer announced (new): ${peer.name} (${address}:${port})`);+ console.log(`🌐 Peer announced (new): ${peer.name} (${peerBaseUrl(peer)})`);instanceEvents.emit('peers:updated', data.peers);return { created: true, peer };});@@ -417,18 +444,20 @@ async function announceSelf(peer) {if (!data.self) return;const selfPort = parseInt(process.env.PORT, 10) || DEFAULT_PEER_PORT;+ const selfHost = getSelfHost();const url = `${peerBaseUrl(peer)}/api/instances/peers/announce`;const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);try {- const res = await fetch(url, {+ const res = await peerFetch(url, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({port: selfPort,instanceId: data.self.instanceId,- name: data.self.name+ name: data.self.name,+ host: selfHost}),signal: controller.signal});@@ -472,6 +501,20 @@ export function startPolling() {if (pollTimer) return;console.log(`🌐 Instance polling started (${POLL_INTERVAL_MS / 1000}s interval)`);+ // Backoff is a rate limit on the polling loop, not a durable judgment about+ // the peer — boot may itself be the deploy that fixes connectivity, so clear it.+ withData(async (data) => {+ let cleared = 0;+ for (const peer of data.peers) {+ if (peer.nextProbeAt) {+ peer.nextProbeAt = null;+ peer.consecutiveFailures = 0;+ cleared++;+ }+ }+ if (cleared > 0) console.log(`🌐 Cleared backoff on ${cleared} peer(s) for fresh probe after boot`);+ }).catch(err => console.error(`❌ Failed to clear peer backoff on boot: ${err.message}`));+// Initial probe after a short delaysetTimeout(() => probeAllPeers(), INITIAL_PROBE_DELAY_MS);diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex 0a7ec6c81d..db0937fce3 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -686,6 +686,85 @@ describe('instances.js', () => {const inboundCount = result.peer.directions.filter(d => d === 'inbound').length;expect(inboundCount).toBe(1);});++ it('should store host on a new peer announced over Tailscale', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [] });+ fetch.mockRejectedValue(new Error('offline'));++ const result = await handleAnnounce({+ address: '100.111.11.146',+ port: 5555,+ instanceId: 'remote-instance',+ name: 'null',+ host: 'null.taile8179.ts.net'+ });++ expect(result.created).toBe(true);+ expect(result.peer.host).toBe('null.taile8179.ts.net');+ });++ it('should learn host on existing peer when previously absent', async () => {+ const existing = {+ id: 'p1',+ address: '100.111.11.146',+ port: 5555,+ instanceId: 'remote-instance',+ name: 'null',+ host: null,+ status: 'offline',+ directions: ['outbound']+ };+ readJSONFile.mockResolvedValue({ self: null, peers: [existing] });++ const result = await handleAnnounce({+ address: '100.111.11.146',+ port: 5555,+ instanceId: 'remote-instance',+ name: 'null',+ host: 'null.taile8179.ts.net'+ });++ expect(result.peer.host).toBe('null.taile8179.ts.net');+ });++ it('should not overwrite a user-set host on existing peer', async () => {+ const existing = {+ id: 'p1',+ address: '100.111.11.146',+ port: 5555,+ instanceId: 'remote-instance',+ name: 'null',+ host: 'manual.example.ts.net',+ status: 'online',+ directions: ['outbound']+ };+ readJSONFile.mockResolvedValue({ self: null, peers: [existing] });++ const result = await handleAnnounce({+ address: '100.111.11.146',+ port: 5555,+ instanceId: 'remote-instance',+ name: 'null',+ host: 'auto.different.ts.net'+ });++ expect(result.peer.host).toBe('manual.example.ts.net');+ });++ it('should drop invalid host strings via validHost', async () => {+ readJSONFile.mockResolvedValue({ self: null, peers: [] });+ fetch.mockRejectedValue(new Error('offline'));++ const result = await handleAnnounce({+ address: '100.111.11.146',+ port: 5555,+ instanceId: 'remote-instance',+ name: 'null',+ host: 'has spaces and:colons'+ });++ expect(result.peer.host).toBeNull();+ });});// --- Polling ---diff --git a/server/services/peerSocketRelay.js b/server/services/peerSocketRelay.jsindex 61289eded6..a72b741f84 100644--- a/server/services/peerSocketRelay.js+++ b/server/services/peerSocketRelay.js@@ -8,6 +8,7 @@import { io } from 'socket.io-client';import { instanceEvents } from './instanceEvents.js';import { peerBaseUrl } from '../lib/peerUrl.js';+import { peerFetch, peerSocketOptions } from '../lib/peerHttpClient.js';// Map<peerId, { socket, agents: Map<agentId, agent>, peer }>const peerConnections = new Map();@@ -25,7 +26,8 @@ export function connectToPeer(peer) {reconnection: true,reconnectionAttempts: 5,reconnectionDelay: 5000,- timeout: CONNECT_TIMEOUT_MS+ timeout: CONNECT_TIMEOUT_MS,+ ...peerSocketOptions});// `host` is required so fetchPeerAgents() can rebuild the HTTPS URL via peerBaseUrl()@@ -101,7 +103,7 @@ async function fetchPeerAgents(conn) {const timeout = setTimeout(() => controller.abort(), CONNECT_TIMEOUT_MS);try {- const res = await fetch(url, { signal: controller.signal });+ const res = await peerFetch(url, { signal: controller.signal });if (!res.ok) return;const data = await res.json();const agents = data.running || data.agents || [];diff --git a/server/services/socket.js b/server/services/socket.jsindex b7f8fec9db..bc1c637d1c 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -19,6 +19,7 @@ import { instanceEvents } from './instanceEvents.js';import { reviewEvents } from './review.js';import { loopEvents } from './loops.js';import { imageGenEvents } from './imageGenEvents.js';+import { videoGenEvents } from './videoGen/events.js';import * as shellService from './shell.js';import {validateSocketData,@@ -542,7 +543,7 @@ export function initSocket(io) {setupLoopEventForwarding();// Set up image generation event forwarding- setupImageGenEventForwarding();+ setupMediaGenEventForwarding();}function cleanupStream(socketId) {@@ -771,11 +772,12 @@ function setupLoopEventForwarding() {loopEvents.on('output', (data) => broadcastToLoops('loop:output', data));}-// Set up image generation event forwarding — broadcast to all clients-let imageGenForwardingSetup = false;-function setupImageGenEventForwarding() {- if (imageGenForwardingSetup) return;- imageGenForwardingSetup = true;+// Bridge both image-gen AND video-gen events from their internal EventEmitters+// onto Socket.IO so client UIs can subscribe via `image-gen:*` / `video-gen:*`.+let mediaGenForwardingSetup = false;+function setupMediaGenEventForwarding() {+ if (mediaGenForwardingSetup) return;+ mediaGenForwardingSetup = true;imageGenEvents.on('started', (data) => {if (ioInstance) ioInstance.emit('image-gen:started', data);});@@ -788,4 +790,17 @@ function setupImageGenEventForwarding() {imageGenEvents.on('failed', (data) => {if (ioInstance) ioInstance.emit('image-gen:failed', data);});++ videoGenEvents.on('started', (data) => {+ if (ioInstance) ioInstance.emit('video-gen:started', data);+ });+ videoGenEvents.on('progress', (data) => {+ if (ioInstance) ioInstance.emit('video-gen:progress', data);+ });+ videoGenEvents.on('completed', (data) => {+ if (ioInstance) ioInstance.emit('video-gen:completed', data);+ });+ videoGenEvents.on('failed', (data) => {+ if (ioInstance) ioInstance.emit('video-gen:failed', data);+ });}diff --git a/server/services/videoGen/events.js b/server/services/videoGen/events.jsnew file mode 100644index 0000000000..20b8fc02cf--- /dev/null+++ b/server/services/videoGen/events.js@@ -0,0 +1,5 @@+import { EventEmitter } from 'events';++// Bridge for video gen progress — server/services/socket.js subscribes+// and forwards as Socket.IO events `video-gen:started|progress|completed|failed`.+export const videoGenEvents = new EventEmitter();diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsnew file mode 100644index 0000000000..0fbf7aee31--- /dev/null+++ b/server/services/videoGen/local.js@@ -0,0 +1,426 @@+/**+ * Video Gen — Local provider (mlx_video on macOS, diffusers on Windows).+ *+ * Spawns a Python child to render an LTX video. Output lives in `data/videos/`+ * with thumbnails in `data/video-thumbnails/`. History is appended to+ * `data/video-history.json` so the Media History page can grid-view them.+ *+ * Image-to-video accepts either an in-PortOS image filename (from data/images)+ * or an upload — both get resized via ffmpeg to match target resolution before+ * the model sees them.+ */++import { execFile, spawn } from 'child_process';+import { existsSync } from 'fs';+import { unlink, writeFile } from 'fs/promises';+import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';+import { tmpdir } from 'os';+import { randomUUID } from 'crypto';+import { promisify } from 'util';+import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { videoGenEvents } from './events.js';+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';++const execFileAsync = promisify(execFile);++const IS_WIN = process.platform === 'win32';++// Platform-specific catalog. macOS = MLX/mlx_video, Windows = diffusers.+const MODELS_MACOS = {+ ltx2_unified: { name: 'LTX-2 Unified (~42 GB)', repo: 'notapalindrome/ltx2-mlx-av', steps: 30, guidance: 3.0 },+ ltx23_unified: { name: 'LTX-2.3 Unified Beta (~48 GB)', repo: 'notapalindrome/ltx23-mlx-av', steps: 25, guidance: 3.0 },+ ltx23_distilled_q4: { name: 'LTX-2.3 Distilled Q4 (~22 GB)', repo: 'notapalindrome/ltx23-mlx-av-q4', steps: 25, guidance: 3.0 },+};+const MODELS_WINDOWS = {+ ltx_video: { name: 'LTX-Video 0.9.5 — T2V + I2V (~9.5 GB, auto-downloads)', steps: 25, guidance: 3.0 },+};+export const VIDEO_MODELS = IS_WIN ? MODELS_WINDOWS : MODELS_MACOS;++export const listVideoModels = () =>+ Object.entries(VIDEO_MODELS).map(([id, m]) => ({ id, ...m }));++export const defaultVideoModelId = () => IS_WIN ? 'ltx_video' : 'ltx2_unified';++const HISTORY_FILE = join(PATHS.data, 'video-history.json');++// Validate that a sidecar/history-supplied filename is a safe basename under+// the expected directory — guards against tampered history entries with+// path-traversal segments (`../etc/passwd`) leaking into ffmpeg or unlink.+const safeUnder = (root, name) => {+ if (typeof name !== 'string' || !name || name.includes('/') || name.includes('\\') || name.includes('..')) return null;+ const rootResolved = resolvePath(root) + PATH_SEP;+ const fullPath = resolvePath(join(root, name));+ return fullPath.startsWith(rootResolved) ? fullPath : null;+};++const jobs = new Map();+let activeProcess = null;++export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);++export const cancel = () => {+ if (!activeProcess) return false;+ const proc = activeProcess;+ proc.kill('SIGTERM');+ // KEEP activeProcess set until proc.on('close') clears it. Without this,+ // the BUSY guard immediately allows a new generation while the SIGTERM'd+ // child is still running (mlx_video can ignore SIGTERM mid-tensor-op),+ // and we'd lose the handle for a follow-up SIGKILL. Escalate after 8s.+ setTimeout(() => {+ // proc.killed is set the moment proc.kill() is called; it does NOT mean+ // the child has exited. Check exitCode (null until 'close' fires) so the+ // SIGKILL escalation actually triggers when mlx_video ignores SIGTERM.+ if (activeProcess === proc && proc.exitCode === null && proc.signalCode === null) {+ console.log(`⚠️ video child didn't exit on SIGTERM — escalating to SIGKILL`);+ proc.kill('SIGKILL');+ }+ }, 8000);+ return true;+};++// ffmpeg discovery is async (which/where takes ~10ms+) and the result is+// stable for the process lifetime — cache the first hit so subsequent video+// generations don't re-shell-out and don't block the event loop.+let cachedFfmpegPath;+const findFfmpeg = async () => {+ if (cachedFfmpegPath !== undefined) return cachedFfmpegPath;+ const candidates = IS_WIN+ ? ['C:\\ffmpeg\\bin\\ffmpeg.exe', 'C:\\Program Files\\ffmpeg\\bin\\ffmpeg.exe']+ : ['/opt/homebrew/bin/ffmpeg', '/usr/local/bin/ffmpeg', '/usr/bin/ffmpeg'];+ for (const p of candidates) {+ if (existsSync(p)) { cachedFfmpegPath = p; return p; }+ }+ const cmd = IS_WIN ? 'where' : 'which';+ const { stdout } = await execFileAsync(cmd, ['ffmpeg'], { timeout: 5000 }).catch(() => ({ stdout: '' }));+ cachedFfmpegPath = stdout.trim().split(/\r?\n/)[0] || null;+ return cachedFfmpegPath;+};++const generateThumbnail = async (videoPath, jobId) => {+ await ensureDir(PATHS.videoThumbnails);+ const thumbFilename = `${jobId}.jpg`;+ const thumbPath = join(PATHS.videoThumbnails, thumbFilename);+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) return null;+ return new Promise((resolve) => {+ const proc = spawn(ffmpeg, ['-i', videoPath, '-vframes', '1', '-q:v', '5', '-y', thumbPath], { stdio: 'ignore' });+ proc.on('close', (code) => resolve(code === 0 ? thumbFilename : null));+ // Without this, a stale ffmpeg path or permission error emits 'error'+ // (never 'close') and the Promise never settles — the entire video gen+ // close handler that awaits this would hang forever.+ proc.on('error', (err) => {+ console.log(`⚠️ ffmpeg thumbnail failed to spawn: ${err.message}`);+ resolve(null);+ });+ });+};++export const loadHistory = () => readJSONFile(HISTORY_FILE, []);+export const saveHistory = (h) => atomicWrite(HISTORY_FILE, h);++const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, tiling, disableAudio, sourceImagePath, outputPath }) => {+ if (IS_WIN) {+ const scriptPath = join(PATHS.root, 'scripts', 'generate_win.py');+ const args = [scriptPath, '--model', modelId, '--prompt', prompt, '--height', String(height), '--width', String(width), '--num-frames', String(numFrames), '--fps', String(fps), '--steps', String(steps), '--guidance', String(guidance), '--seed', String(seed), '--output', outputPath];+ if (negativePrompt) args.push('--negative-prompt', negativePrompt);+ if (sourceImagePath) args.push('--image', sourceImagePath);+ return { bin: pythonPath, args };+ }+ const args = [+ '-m', 'mlx_video.generate_av',+ '--prompt', prompt,+ '--height', String(height),+ '--width', String(width),+ '--num-frames', String(numFrames),+ '--seed', String(seed),+ '--fps', String(fps),+ '--steps', String(steps),+ '--cfg-scale', String(guidance),+ '--output-path', outputPath,+ '--model-repo', model.repo,+ '--text-encoder-repo', 'mlx-community/gemma-3-12b-it-4bit',+ '--tiling', tiling,+ ];+ if (negativePrompt) args.push('--negative-prompt', negativePrompt);+ if (disableAudio) args.push('--no-audio');+ if (sourceImagePath) args.push('--image', sourceImagePath);+ return { bin: pythonPath, args };+};++export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = 121, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null }) {+ if (!pythonPath) throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'VIDEO_GEN_NOT_CONFIGURED' });+ if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });+ // Enforce the single-activeProcess invariant — without this a double-submit+ // would orphan the first child (cancel() only kills the one in activeProcess).+ if (activeProcess) throw new ServerError('A video generation is already in progress — cancel it before starting another', { status: 409, code: 'VIDEO_GEN_BUSY' });++ const model = VIDEO_MODELS[modelId];+ if (!model) throw new ServerError(`Unknown video model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });++ await ensureDir(PATHS.videos);+ await ensureDir(PATHS.videoThumbnails);++ const jobId = randomUUID();+ const filename = `${jobId}.mp4`;+ const outputPath = join(PATHS.videos, filename);+ const w = Math.floor(Number(width) / 64) * 64;+ const h = Math.floor(Number(height) / 64) * 64;+ const actualSeed = seed != null && seed !== '' ? Number(seed) : Math.floor(Math.random() * 2147483647);+ const actualSteps = steps ? Number(steps) : model.steps;+ const actualGuidance = guidanceScale != null && guidanceScale !== '' ? Number(guidanceScale) : model.guidance;+ const parsedNumFrames = Number(numFrames);+ const parsedFps = Number(fps);++ // Resize source image to match the model resolution. mlx_video requires+ // exact dimensions (it doesn't auto-pad), and pixie-forge learned the+ // hard way that letting the model upscale a portrait reference makes+ // garbled output.+ let resolvedSourceImage = sourceImagePath;+ let resizedTempPath = null;+ if (resolvedSourceImage) {+ const ffmpeg = await findFfmpeg();+ if (ffmpeg) {+ const resizedPath = join(tmpdir(), `resized-${jobId}.png`);+ const resizeResult = await execFileAsync(ffmpeg, [+ '-i', resolvedSourceImage,+ '-vf', `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h}`,+ '-update', '1', '-frames:v', '1',+ '-y', resizedPath,+ ], { timeout: 10000 }).catch((err) => ({ error: err }));+ if (resizeResult.error) {+ console.log(`⚠️ Failed to resize source image, using original: ${resizeResult.error.message}`);+ } else {+ resolvedSourceImage = resizedPath;+ resizedTempPath = resizedPath;+ }+ }+ }++ const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, filename, createdAt: new Date().toISOString() };+ const job = { ...meta, clients: [], status: 'running' };+ jobs.set(jobId, job);++ const { bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, outputPath });++ console.log(`🎬 Generating video [${jobId.slice(0, 8)}]: ${modelId} ${w}x${h} frames=${parsedNumFrames} steps=${actualSteps}`);+ videoGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps, ...meta });++ // Clear PYTHONPATH so the child uses the venv's own site-packages instead+ // of the parent shell's PYTHONPATH. Setting to `undefined` in a spread does+ // NOT unset the var — Node coerces it to the literal string "undefined" —+ // so build the env explicitly and `delete`.+ const childEnv = { ...process.env };+ delete childEnv.PYTHONPATH;+ const proc = spawn(bin, args, { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });+ activeProcess = proc;+ // Without an 'error' handler, a missing/non-executable pythonPath would+ // crash the server with an unhandled error event.+ proc.on('error', (err) => {+ job.status = 'error';+ const reason = `Failed to spawn ${bin}: ${err.message}`;+ console.log(`❌ Video generation spawn error [${jobId.slice(0, 8)}]: ${reason}`);+ broadcastSse(job, { type: 'error', error: reason });+ videoGenEvents.emit('failed', { generationId: jobId, error: reason });+ activeProcess = null;+ if (resizedTempPath) unlink(resizedTempPath).catch(() => {});+ closeJobAfterDelay(jobs, jobId);+ });++ let outputBuf = '';++ const handleLine = (raw) => {+ const line = raw.trim();+ if (!line || PYTHON_NOISE_RE.test(line)) return;+ if (line.startsWith('STATUS:')) {+ broadcastSse(job, { type: 'status', message: line.slice(7) });+ } else if (line.startsWith('STAGE:')) {+ const parts = line.split(':');+ const step = parseInt(parts[3], 10) || 0;+ const total = parseInt(parts[4], 10) || 1;+ broadcastSse(job, { type: 'progress', progress: step / total, message: parts.slice(5).join(':') });+ videoGenEvents.emit('progress', { generationId: jobId, progress: step / total, step, totalSteps: total });+ } else if (line.startsWith('DOWNLOAD:')) {+ broadcastSse(job, { type: 'status', message: `Downloading model... ${line.slice(9)}` });+ } else {+ const m = line.match(/(\d+)%\|/);+ if (m) {+ const pct = parseInt(m[1], 10) / 100;+ broadcastSse(job, { type: 'progress', progress: pct, message: line });+ videoGenEvents.emit('progress', { generationId: jobId, progress: pct });+ }+ }+ };++ proc.stdout.on('data', (chunk) => {+ outputBuf += chunk.toString();+ const lines = outputBuf.split('\n');+ outputBuf = lines.pop();+ for (const line of lines) {+ if (!line.trim()) continue;+ // mlx_video emits a single JSON line on stdout when finished —+ // capture it for the metadata sidecar.+ try {+ const parsed = JSON.parse(line.trim());+ if (parsed.video_path) job.resultJson = parsed;+ } catch { /* not JSON */ }+ }+ });++ proc.stderr.on('data', (chunk) => {+ for (const line of chunk.toString().split(/[\n\r]+/)) handleLine(line);+ });++ proc.on('close', async (code, signal) => {+ activeProcess = null;+ // Cleanup the resized temp image if we made one. Track via a flag rather+ // than a path-prefix check — tmpdir() can return a symlinked path+ // (macOS /var → /private/var) so startsWith() can silently miss.+ if (resizedTempPath) await unlink(resizedTempPath).catch(() => {});+ // Cleanup the original multipart upload temp file too — without this,+ // every i2v request leaves a file in os.tmpdir() forever.+ if (uploadedTempPath) await unlink(uploadedTempPath).catch(() => {});++ if (code !== 0) {+ job.status = 'error';+ const reason = signal === 'SIGKILL'+ ? 'Process killed (likely out of memory — try a smaller model or resolution)'+ : signal ? `Killed by signal ${signal}` : `Exit code ${code}`;+ console.log(`❌ Video generation failed [${jobId.slice(0, 8)}]: ${reason}`);+ broadcastSse(job, { type: 'error', error: `Generation failed: ${reason}` });+ videoGenEvents.emit('failed', { generationId: jobId, error: reason });+ } else {+ job.status = 'complete';+ const thumbnail = await generateThumbnail(outputPath, jobId);+ const history = await loadHistory();+ history.unshift({ ...meta, thumbnail });+ await saveHistory(history);+ console.log(`✅ Video generated [${jobId.slice(0, 8)}]: ${filename}`);+ broadcastSse(job, { type: 'complete', result: { filename, seed: actualSeed, thumbnail, path: `/data/videos/${filename}` } });+ videoGenEvents.emit('completed', { generationId: jobId, filename, path: `/data/videos/${filename}`, thumbnail });+ }+ closeJobAfterDelay(jobs, jobId);+ });++ return { jobId, generationId: jobId, filename, mode: 'local', model: modelId };+}++// Extract the last frame of a video as a PNG into data/images/ — used to+// chain a clip into Imagine for "continue from last frame" remixing.+export async function extractLastFrame(historyId) {+ const history = await loadHistory();+ const item = history.find((h) => h.id === historyId);+ if (!item) throw new ServerError('Video not found', { status: 404, code: 'NOT_FOUND' });+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });+ // Validate against tampered history entries — without this, a `../...`+ // filename could make ffmpeg read arbitrary files outside data/videos.+ const videoPath = safeUnder(PATHS.videos, item.filename);+ if (!videoPath) throw new ServerError('Invalid video filename', { status: 400, code: 'VALIDATION_ERROR' });+ if (!existsSync(videoPath)) throw new ServerError('Video file not found on disk', { status: 404, code: 'NOT_FOUND' });++ await ensureDir(PATHS.images);+ const frameFilename = `lastframe-${item.id}.png`;+ const framePath = join(PATHS.images, frameFilename);++ return new Promise((resolve, reject) => {+ const proc = spawn(ffmpeg, ['-sseof', '-0.1', '-i', videoPath, '-vframes', '1', '-q:v', '2', '-y', framePath], { stdio: 'ignore' });+ proc.on('close', (code) => {+ if (code !== 0) return reject(new ServerError('Failed to extract last frame', { status: 500, code: 'FFMPEG_FAILED' }));+ console.log(`🎞️ Extracted last frame: ${frameFilename}`);+ resolve({ filename: frameFilename, path: `/data/images/${frameFilename}` });+ });+ proc.on('error', (err) => {+ reject(new ServerError(`ffmpeg failed to spawn: ${err.message}`, { status: 500, code: 'FFMPEG_FAILED' }));+ });+ });+}++// Concat selected videos (preserving order) into a single MP4. Uses ffmpeg's+// concat demuxer which is stream-copy, so it's fast and lossless — but the+// inputs must share codec/resolution. The Media History page already only+// lets users stitch from a single model so this holds in practice.+export async function stitchVideos(videoIds) {+ if (!Array.isArray(videoIds) || videoIds.length < 2) {+ throw new ServerError('Need at least 2 videos to stitch', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });++ const history = await loadHistory();+ const videos = videoIds.map((id) => history.find((h) => h.id === id)).filter(Boolean);+ if (videos.length < 2) throw new ServerError('Some videos not found', { status: 400, code: 'VALIDATION_ERROR' });++ // Validate every history-supplied filename through safeUnder before+ // letting it reach ffmpeg's concat manifest. Tampered history entries+ // could otherwise smuggle `..` segments into ffmpeg input.+ const videoPaths = videos.map((v) => safeUnder(PATHS.videos, v.filename));+ if (videoPaths.some((p) => !p)) {+ throw new ServerError('One or more video filenames failed validation', { status: 400, code: 'VALIDATION_ERROR' });+ }+ for (const p of videoPaths) {+ if (!existsSync(p)) throw new ServerError(`Missing: ${basename(p)}`, { status: 404, code: 'NOT_FOUND' });+ }++ const jobId = randomUUID();+ const listFile = join(tmpdir(), `concat-${jobId}.txt`);+ // ffmpeg concat-demuxer escape: per its docs, single quotes in filenames+ // must be replaced with `'\''`. Inside quoted strings ffmpeg also treats+ // backslash as an escape character — on Windows where paths are+ // `C:\foo\bar.mp4`, that corrupts the path. Normalize to forward slashes+ // (which ffmpeg accepts on Windows just fine) before quoting.+ const escapeForConcat = (p) => p.replace(/\\/g, '/').replace(/'/g, "'\\''");+ await writeFile(listFile, videoPaths.map((p) => `file '${escapeForConcat(p)}'`).join('\n'));++ const outFilename = `stitched-${jobId}.mp4`;+ const outPath = join(PATHS.videos, outFilename);++ // Use a try/finally so the concat list temp file is cleaned up even when+ // ffmpeg rejects — otherwise it leaks one file per failed stitch.+ try {+ await new Promise((resolve, reject) => {+ const proc = spawn(ffmpeg, ['-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', '-y', outPath], { stdio: 'ignore' });+ proc.on('close', (code) => code === 0 ? resolve() : reject(new ServerError('Stitch failed', { status: 500, code: 'FFMPEG_FAILED' })));+ proc.on('error', (err) => reject(new ServerError(`ffmpeg failed to spawn: ${err.message}`, { status: 500, code: 'FFMPEG_FAILED' })));+ });+ } finally {+ await unlink(listFile).catch(() => {});+ }++ const thumb = await generateThumbnail(outPath, jobId);+ const stitchedMeta = {+ id: jobId,+ prompt: `Stitched: ${videos.map((v) => v.prompt).join(' + ')}`,+ modelId: videos[0].modelId,+ seed: 0,+ width: videos[0].width,+ height: videos[0].height,+ numFrames: videos.reduce((sum, v) => sum + (v.numFrames || 0), 0),+ fps: videos[0].fps,+ filename: outFilename,+ thumbnail: thumb,+ createdAt: new Date().toISOString(),+ stitchedFrom: videoIds,+ };+ const h = await loadHistory();+ h.unshift(stitchedMeta);+ await saveHistory(h);+ console.log(`🎬 Stitched ${videos.length} videos: ${outFilename}`);+ return stitchedMeta;+}++export async function deleteHistoryItem(id) {+ const history = await loadHistory();+ const item = history.find((h) => h.id === id);+ if (!item) throw new ServerError('Not found', { status: 404, code: 'NOT_FOUND' });+ // Same path-traversal guard as extractLastFrame — unlink only if the+ // filename resolves to inside the expected dir.+ const videoFile = safeUnder(PATHS.videos, item.filename);+ if (videoFile) await unlink(videoFile).catch(() => {});+ if (item.thumbnail) {+ const thumbFile = safeUnder(PATHS.videoThumbnails, item.thumbnail);+ if (thumbFile) await unlink(thumbFile).catch(() => {});+ }+ await saveHistory(history.filter((h) => h.id !== id));+ return { ok: true };+}diff --git a/setup.sh b/setup.shindex cd5a46e24c..0b1e3d204c 100755--- a/setup.sh+++ b/setup.sh@@ -19,13 +19,11 @@ if [ "$NODE_VERSION" -lt 18 ]; thenexit 1fi-# Run the canonical install: submodules + root/client/server/autofixer deps +-# esbuild postinstall + node-pty rebuild + npm run setup (data dir, db, browser).-# install:all ends with `npm run setup` so this single call covers what the old-# split `npm install` + `npm run setup` did, plus the workspace deps the old-# script was missing.+# `npm run setup` is the all-in-one: submodules + root/client/server/autofixer+# deps + esbuild postinstall + node-pty rebuild + data dir, db, and browser+# setup. install:all is kept as a backward-compat alias.echo "Installing dependencies and running setup..."-if ! npm run install:all; then+if ! npm run setup; thenecho ""echo "==================================="echo " Setup incomplete"@@ -84,6 +82,8 @@ if [ "$start_now" = "1" ]; thenecho ""echo "Starting PortOS..."npm start+ # Open the dashboard in the PortOS-managed browser. Fail-soft.+ node scripts/open-ui-in-browser.js || trueecho ""echo "==================================="echo " PortOS is running"diff --git a/update.ps1 b/update.ps1index c01684a451..751a3c72e8 100644--- a/update.ps1+++ b/update.ps1@@ -146,9 +146,15 @@ if (-not (Test-Path "client/node_modules/vite/bin/vite.js")) {}Step "npm-install" "done" "Dependencies installed"-# Run setup (data dirs + browser deps)+# Run data/db/browser setup. Don't call `npm run setup` — that re-runs the+# installs we just did above. The three scripts here are the data-side half+# of `npm run setup` and are idempotent.Step "setup" "running" "Running setup..."-Invoke-Logged npm run setup+Invoke-Logged node scripts/setup-data.js+if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }+Invoke-Logged node scripts/setup-db.js+if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }+Invoke-Logged node scripts/setup-browser.jsif ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }Invoke-Logged node scripts/setup-ghostty.jsStep "setup" "done" "Setup complete"@@ -216,6 +222,13 @@ if ($LASTEXITCODE -ne 0) {Step "restart" "done" "PortOS restarted"Write-SafeHost ""+# Open the dashboard in the PortOS-managed browser. Fail-soft — explicitly+# reset $LASTEXITCODE to 0 after the call so a non-zero exit from the auto-+# open script doesn't propagate as the script's own exit code (the update+# is already complete by this point).+Invoke-Logged node scripts/open-ui-in-browser.js+$global:LASTEXITCODE = 0+Write-SafeHost "===================================" -ForegroundColor GreenWrite-SafeHost " ✅ Update Complete!" -ForegroundColor GreenWrite-SafeHost "===================================" -ForegroundColor Greendiff --git a/update.sh b/update.shindex a67c49b35c..d77d4dcbc8 100755--- a/update.sh+++ b/update.sh@@ -104,9 +104,13 @@ if [ ! -f "client/node_modules/vite/bin/vite.js" ]; thenfistep "npm-install" "done" "Dependencies installed"-# Run setup (data dirs + browser deps)+# Run data/db/browser setup. Don't call `npm run setup` — that re-runs the+# installs we just did above. The three scripts here are the data-side half+# of `npm run setup` and are idempotent.step "setup" "running" "Running setup..."-run npm run setup+run node scripts/setup-data.js+run node scripts/setup-db.js+run node scripts/setup-browser.jsrun node scripts/setup-ghostty.js || truestep "setup" "done" "Setup complete"log ""@@ -168,6 +172,10 @@ fistep "restart" "done" "PortOS restarted"log ""+# Open the dashboard in the PortOS-managed browser. Fail-soft — never blocks+# the update return.+run node scripts/open-ui-in-browser.js || true+log "==================================="log " ✅ Update Complete!"log "==================================="