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
docs: update feature overviews, fal.ai automation docs, and JSDoc annotations
[._.]/ Adam Eivy63ac1b264532
diff --git a/PLAN.md b/PLAN.mdindex d97f645228..bafecebacc 100644--- a/PLAN.md+++ b/PLAN.md@@ -1 +1,3 @@-- [x] [models-contextual-backend-install] Install a missing Ollama or LM Studio backend directly from the model catalog blocker instead of sending the user to a terminal command.+# PLAN++diff --git a/README.md b/README.mdindex c166c51ec3..36f0ab5785 100644--- a/README.md+++ b/README.md@@ -101,6 +101,7 @@ A full creative studio for taking an idea from blank page to finished media. Eac- **Series Continuity** — An established-facts ledger (timeline, wardrobe, props, who-knows-what) that catches contradictions and knowledge leaks across issues- **Voice Fingerprint** — Deterministic prose metrics (sentence rhythm, register, vocabulary wells) that flag voice drift between chapters- **Prose Series Export** — Compile a finished prose series into an EPUB or print-ready interior with trim size and title page+- **FableLoom** — Interactive branching narrative engine: visual scene-graph canvas, camera cuts, decision loops vs automatic cuts, helper vs protagonist participation modes, canonical wardrobe/identity locks, teleplay/prose dual-format conversion, deterministic graph validation, and fal.ai scene video automation ([FableLoom docs](./docs/features/fableloom.md))- **Authors** — Reusable author personas: name, writing style, bio, and a physical description that seeds a generated cover-byline headshot- **Media Gen** — Unified surface for image and video generation across local and external backends:- **Image** — FLUX.1, FLUX.2 (klein), Z-Image via MFLUX/diffusers locally; A1111 / external endpoints; OpenAI Codex `gpt-image` mode@@ -237,6 +238,7 @@ Everything you need to manage your dev environment without leaving the browser.- **Flows** — Rendered architecture/data-flow diagrams of how PortOS subsystems and integrations actually connect- **Video Downloader** — Pull clips from YouTube/X via `yt-dlp` into the media library- **Local LLM Playground** — Side-by-side comparison of local Ollama/LM Studio models with TTFT and tokens/sec+- **Local Model Acceleration & Speculative Decoding** — Accelerated local inference via MTPLX (Apple Silicon MTP runtime), DFlash 2 / DSpark speculative drafting, and Docker setups for vLLM / SGLang ([MTPLX docs](./docs/features/mtplx.md) | [DFlash 2 docs](./docs/features/dflash2.md))- **API Explorer** — Searchable complete HTTP and Socket.IO inventories, rendered OpenAPI 3.0.3, AsyncAPI 3, and governed agent-tool contracts; external TTS/image exposure remains explicitly gated- **Templates** — Scaffold new apps from pre-built templates wired up to your AI providers- **Review Hub** — Single inbox for actionable items (CoS approvals, alerts, todos, briefings) across every PortOS subsystem@@ -401,7 +403,9 @@ Full catalog (including design plans, ADRs, and research notes): [docs/README.md### Architecture & Operations- [Architecture Overview](./docs/ARCHITECTURE.md) — System design, data flow, and service diagram- [API Reference](./docs/API.md) — REST endpoints, full route-domain index, and WebSocket events+- [API Tool Contract](./docs/API_TOOL_CONTRACT.md) — Unified semantic tool, Persistent Mind, and Agent Tools MCP contract- [Companion App API](./docs/COMPANION_APP_API.md) — PortDeck native mobile client discovery and HTTP API contract+- [Remote Desktop Broker](./docs/REMOTE_DESKTOP.md) — PortDeck VNC broker security, host setup, and session flow- [Federated Media Providers](./docs/FEDERATED_MEDIA_PROVIDERS.md) — Authenticated, capacity-aware peer audio provider wire contract and setup- [Storage Classification Contract](./docs/STORAGE.md) — when data belongs in PostgreSQL vs the filesystem, plus the new-data-store checklist- [Backup & Restore](./docs/BACKUP.md) — filesystem snapshots + mandatory PostgreSQL dumps and how to restore them@@ -409,6 +413,8 @@ Full catalog (including design plans, ADRs, and research notes): [docs/README.md- [PM2 Configuration](./docs/PM2.md) — PM2 patterns and best practices- [Quota Burn Automation](./docs/QUOTA-BURN.md) — Subscription quota spending loop and window rules- [Three.js Models](./docs/THREEJS_MODELS.md) — Procedural Three.js scene generation and trust boundary+- [Fork-Aware Self-Update](./docs/SELF_UPDATE.md) — Fork-aware self-update flow, release polling, and sync mechanisms+- [Windows Console Focus](./docs/WINDOWS_CONSOLE.md) — Console window focus handling and background spawn mitigation on Windows- [The `METRICS.md` Convention](./docs/METRICS.md) — How a managed app declares the metrics agents should judge it by### Developmentdiff --git a/docs/features/fableloom.md b/docs/features/fableloom.mdindex 58d81dd645..98cc048f07 100644--- a/docs/features/fableloom.md+++ b/docs/features/fableloom.md@@ -256,6 +256,15 @@ draft/degraded work. The completion hookDecision videos are authored as seamless loops; automatic-cut videos land ona final beat that hands cleanly to the next node.+### fal.ai H3 Max browser video automation++For scenes utilizing fal.ai's free MiniMax H3 Max web tool, PortOS provides automated, serialized video production (`POST /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/fal-video`):++- **Serialized runner** (`server/services/fableLoom/falVideoAutomation.js`): jobs execute sequentially against PortOS's persistent Chrome CDP browser (`http://localhost:5556`) so concurrent triggers do not overwrite the single web form.+- **Workflow**: Playwright fills the scene's prompt and camera direction, uploads the scene's current approved storyboard still, triggers generation, monitors progress, and downloads the finished MP4 via authenticated browser context requests.+- **Durable attachment**: The downloaded clip is saved directly into PortOS Media History and attached to the scene node via `attachNodeVideo`. If the scene image changed while rendering, the video is safely preserved in Media History without overwriting the drifted scene.+- **Status & polling**: `GET /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/fal-video/:jobId` provides real-time progress, error diagnostics (such as CAPTCHA challenges or daily allowance limits requiring user action), and completion metadata.+### Episodic production and continuityThe **Production & Continuity** panel plans a whole episode before it queuesdiff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.jsindex d363727e8c..5acde874e6 100644--- a/server/routes/fableLoom.js+++ b/server/routes/fableLoom.js@@ -1,11 +1,11 @@/*** FableLoom REST surface — branching narratives.*- * CRUD for looms/episodes/nodes plus the AI lanes (weave/branch/feedback/review/play)- * and the deterministic graph validation. Every AI endpoint is a direct- * user action in the same request (AI Provider Usage Policy). Scene media- * rides the shared image/video generation queues with a `fableLoom`- * destination tag — there are no bespoke generation endpoints here.+ * CRUD for looms/episodes/nodes plus the AI lanes (weave/branch/feedback/review/play),+ * the deterministic graph validation, and user-triggered fal.ai browser video automation.+ * Every AI endpoint is a direct user action in the same request (AI Provider Usage Policy).+ * Standard scene media rides the shared image/video generation queues with a `fableLoom`+ * destination tag, while fal.ai automation uses a dedicated serialized browser runner.*/import { Router } from 'express';diff --git a/server/services/fableLoom/falVideoAutomation.js b/server/services/fableLoom/falVideoAutomation.jsindex 327c1e42f5..d0dc790f5c 100644--- a/server/services/fableLoom/falVideoAutomation.js+++ b/server/services/fableLoom/falVideoAutomation.js@@ -83,6 +83,12 @@ const falAspectRatio = (requested) => {return '16:9';};+/**+ * Resolves the active Chrome DevTools Protocol endpoint URL for the PortOS Browser.+ *+ * @returns {Promise<string>} CDP HTTP endpoint URL (e.g. http://127.0.0.1:5556).+ * @throws {ServerError} When PortOS Browser is not running and cannot be launched.+ */const cdpEndpoint = async () => {let health = await getHealthStatus();if (!health.connected) health = await launchBrowser();@@ -99,6 +105,12 @@ const cdpEndpoint = async () => {return `http://${endpointHost}:${health.cdpPort}`;};+/**+ * Checks for visible error messages, CAPTCHA challenges, rate limits, or auth walls on the fal.ai page.+ *+ * @param {import('playwright-core').Page} page - Active Playwright page.+ * @returns {Promise<string|null>} User-friendly error diagnosis if found, otherwise null.+ */const visibleFalFailure = async (page) => {const text = await page.locator('[role="alert"]:visible, .text-error:visible').allInnerTexts().catch(() => []);const message = text.map((item) => item.trim()).find(Boolean) || '';@@ -122,6 +134,12 @@ const visibleFalFailure = async (page) => {: null;};+/**+ * Maps uncaught errors to sanitized user-facing error explanations.+ *+ * @param {Error|ServerError} error - Caught error.+ * @returns {string} User-facing failure summary.+ */const safeFailureMessage = (error) => {if (error instanceof ServerError) return error.message;if (error?.name === 'TimeoutError') {@@ -130,10 +148,25 @@ const safeFailureMessage = (error) => {return 'fal.ai browser automation failed. Inspect the PortOS Browser tab, then retry.';};+/**+ * Reads the current video source URL from the given video locator.+ *+ * @param {import('playwright-core').Locator} resultVideo - Video element locator.+ * @returns {Promise<string>} Video source URL.+ */const readVideoSource = (resultVideo) => resultVideo.evaluate((video) => video.currentSrc || video.src || '').catch(() => '');+/**+ * Polls the fal.ai result video element until a new video URL appears or an error is diagnosed.+ *+ * @param {import('playwright-core').Page} page - Active Playwright page.+ * @param {import('playwright-core').Locator} resultVideo - Video element locator.+ * @param {string} previousSourceUrl - URL from any previous completed render.+ * @returns {Promise<string>} Downloadable URL of the generated video.+ * @throws {ServerError} When rendering times out or fal.ai shows an error/captcha.+ */const waitForFalResult = async (page, resultVideo, previousSourceUrl) => {const deadline = Date.now() + FAL_RENDER_TIMEOUT_MS;while (Date.now() < deadline) {@@ -165,6 +198,14 @@ const waitForFalResult = async (page, resultVideo, previousSourceUrl) => {);};+/**+ * Downloads the generated video buffer from fal.ai using the authenticated browser context.+ *+ * @param {import('playwright-core').BrowserContext} context - Playwright browser context.+ * @param {string} sourceUrl - Video asset URL to download.+ * @returns {Promise<Buffer>} Video file buffer.+ * @throws {ServerError} On non-200 HTTP response or when video size exceeds max upload limits.+ */const readFalVideo = async (context, sourceUrl) => {if (!/^https?:\/\//i.test(sourceUrl)) {throw new ServerError('fal.ai finished, but did not expose a downloadable video URL.', {@@ -207,6 +248,12 @@ const readFalVideo = async (context, sourceUrl) => {return buffer;};+/**+ * Executes a single serialized fal.ai video generation job via Playwright CDP automation.+ *+ * @param {object} job - The internal job record to execute.+ * @returns {Promise<void>}+ */const executeJob = async (job) => {let browser = null;let createdPage = null;@@ -333,6 +380,21 @@ const executeJob = async (job) => {}};+/**+ * Enqueues a user-triggered fal.ai H3 Max video automation job for a FableLoom scene.+ *+ * Checks scene existence and validates that an approved storyboard still is present,+ * registers the queued job, and attaches it to the serialized browser runner tail.+ *+ * @param {string} loomId - The ID of the parent loom story.+ * @param {string} episodeId - The ID of the episode containing the scene.+ * @param {string} nodeId - The ID of the scene node to render video for.+ * @param {object} options - Generation options.+ * @param {string} options.prompt - Authored video generation prompt and camera direction.+ * @param {'16:9'|'9:16'|'1:1'} [options.aspectRatio='16:9'] - Target video aspect ratio.+ * @returns {Promise<object>} Public job status descriptor.+ * @throws {ServerError} When scene/image is missing or browser is unavailable.+ */export async function startFalVideoAutomation(loomId, episodeId, nodeId, {prompt,aspectRatio = '16:9',@@ -398,6 +460,16 @@ export async function startFalVideoAutomation(loomId, episodeId, nodeId, {}}+/**+ * Retrieves the public status descriptor for an existing fal.ai video automation job.+ *+ * @param {string} loomId - The ID of the parent loom story.+ * @param {string} episodeId - The ID of the episode containing the scene.+ * @param {string} nodeId - The ID of the scene node.+ * @param {string} jobId - The unique job ID.+ * @returns {object} Public job status descriptor.+ * @throws {ServerError} When the job is not found or does not match scene scope.+ */export function getFalVideoAutomation(loomId, episodeId, nodeId, jobId) {pruneJobs();const job = jobs.get(jobId);@@ -407,6 +479,9 @@ export function getFalVideoAutomation(loomId, episodeId, nodeId, jobId) {return publicJob(job);}+/**+ * Resets all in-memory fal.ai video automation job queues, caches, and run promises (test helper).+ */export function _resetFalVideoAutomations() {jobs.clear();latestJobByScene.clear();