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
address review (claude): process-group kill on install cancel, atomic CLIP stage, modal done-ref
[._.]/ Adam Eivy3669e009e5b7
diff --git a/PLAN.md b/PLAN.mdindex 5c83047b19..18b6cb9d8f 100644--- a/PLAN.md+++ b/PLAN.md@@ -21,6 +21,9 @@ _Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-ag- [ ] [pythonsetup-arch-tests] **Test coverage for arch-aware `detectPython()` + `/setup/check` arch fields.** Added 2026-05-28 with the VideoGen inline Local Python setup fix. New helpers (`probePythonArch`, `isArchMismatch`, `detectArm64Python`, `HOST_ARCH`) and the new `/api/image-gen/setup/check` response fields (`interpreterArch`, `hostArch`, `archMismatch`, `suggestedArm64Python`) have no test coverage — the existing `server/routes/imageGen.test.js` skips all `/setup/*` routes entirely. Worth a `pythonSetup.test.js` that mocks `node:os` + `node:child_process` to verify: (1) on `darwin/arm64`, `detectPython` prefers arm64 candidates over x86_64; (2) `/setup/check` includes the new arch fields and only sets `archMismatch: true` when the host is arm64; (3) `suggestedArm64Python` is null when no viable arm64 candidate exists. Deferred from the fix because the `/setup/*` route family has zero existing test harness and adding one is its own piece of work.- [ ] [mediacard-use-mediaimage-for-syncing-assets] **`MediaCard.jsx` grid thumbnails still use a raw `<img src={previewUrl}>`.** Same peer-sync placeholder/live-swap gap that `[peer-sync-medialightbox-use-mediaimage-for-syncing-assets]` fixed for the lightbox — `client/src/components/media/MediaCard.jsx` (~line 42) doesn't get the "Syncing" placeholder or the `peerSync:asset-arrived` atomic swap. Swap the raw `<img>` for `MediaImage`. Surfaced by that item's cross-check during the batch-clear (2026-05-25); was outside its stated scope.- [ ] [chrome-canary-followups] **Hardening for the custom-Chrome-binary feature (xhigh code-review 2026-05-25).** _DONE in the v2.10.0 release review: (b) both `spawn()` calls now have `.on('error', …)` listeners; (d) `browser/server.js#loadConfig` now try/catches the `JSON.parse`; (e) `setup-browser.js#loadConfig` now warns + returns `null` and `applyCanaryToConfig` skips the save when the existing config is unreadable; (f) top-level `runCanarySetup()` is now `.catch()`-wrapped. (c) is tracked separately in `[setup-browser-canary-headless]`. Remaining: (a), (g)–(o)._ **High-severity:** (a) On macOS headed mode (the default), `browser/server.js:208` uses `macAppBundle` only and silently ignores `chromePath` — a UI user who fills in `chromePath` for Canary/Chromium/Brave but leaves `macAppBundle` empty gets stock Chrome and the log misreports the binary; couple the two fields in the UI (or auto-derive `macAppBundle` from `chromePath` when the latter is inside a `.app`). (b) Neither `spawn(chromePath, …)` (line 216) nor `spawn('/usr/bin/open', …)` (line 208) has an `.on('error', …)` listener — a typo in `chromePath` emits 'error' with no listener → `uncaughtException` → portos-browser PM2 child crashes and restart-loops. (c) `scripts/setup-browser.js#applyCanaryToConfig` writes `chromePath` + `macAppBundle` but doesn't flip `headless: false`; combined with the seed default of `headless: true` (`data.reference/browser-config.json`), a fresh install accepting Canary runs Canary invisibly. (d) `browser/server.js#loadConfig` does bare `JSON.parse(raw)` with no try/catch — combined with setup-browser's non-atomic `writeFileSync` and the `cachedConfig` race, a partial-file write crashes the supervisor on next start (PM2 restart-loop forever). **Medium-severity:** (e) `setup-browser.js#loadConfig` silently catches all JSON parse errors and returns `{}`, then `applyCanaryToConfig` saves `{chromePath, macAppBundle}` only — wiping every other user-customized key. (f) Top-level `await runCanarySetup()` has no try/catch — any EACCES on data/browser-config.json aborts `npm run setup` / `update.sh` at what was previously a no-op step. (g) Idempotency guard only checks `chromePath`: users who decline get re-prompted on every update, and users who set only `macAppBundle` keep getting re-prompted. (h) `PORTOS_USE_CANARY` only matches literal `'0'`/`'false'` (opt-out) or `'1'`/`'true'` (opt-in) — `'no'`/`'off'`/`'yes'`/`'on'`/`'True'` fall through both branches. (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo password prompt under non-TTY + `PORTOS_USE_CANARY=1` (update.sh stalls). (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write — GET /api/browser/config returns pre-update values until process restart. (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` pattern (`server/lib/fileUtils.js`). **Low-severity:** (l) `spawnSync` failure-status check `result.status !== 0` treats `status: null` (spawn-failure / signal kill) identically to a non-zero exit and never logs `result.error` — masks ENOENT/EPERM/SIGKILL. (m) `optionalPath` Zod schema accepts any string up to 1024 chars; no `.app`/`.exe` sanity check — user pastes the bundle into `chromePath` → spawn() EISDIR. (n) `launchBrowser`'s reuse-existing-Chrome early-return (line 167) fires BEFORE `headlessMode = config.headless === true` (line 170), leaving the module-level default `false` after a PM2 restart that reuses Chrome — /health reports wrong mode (pre-existing, but in a function touched by this change). (o) `detectCanary` on macOS only checks `/Applications/...`; misses per-user `~/Applications/Google Chrome Canary.app` installs (corporate Macs, `HOMEBREW_CASK_OPTS=--appdir=$HOME/Applications`).+- [ ] [ref-watch-phosphene-teacache-extend-a2v-denoise] **TeaCache through Extend + A2V Stage-1 denoise loops.** From `reference-watch` review of phosphene (commits `ea98aad8` + `17be2a79`, 2026-05-28). PortOS's `scripts/generate_ltx2.py` invokes `ExtendPipeline.extend_from_video(...)` (~line 378) and `AudioToVideoPipeline.generate_and_save(...)` (~line 417) directly without passing a TeaCache controller, so the slowest two modes in the panel run full denoise. Phosphene reuses the existing Stage-1 calibration (`ti2vid_two_stages._build_teacache_controller(n_steps, thresh=0.5)`) by monkey-patching `guided_denoise_loop` on the `ltx_pipelines_mlx.retake` and `ltx_pipelines_mlx.a2vid_two_stage` modules, gating activation on a per-call module-level config dict, set before the pipeline call and cleared in `finally`. Predicted ~1.2× on extend at default threshold (up to ~3× at 1.5); similar for A2V Stage 1. Fix: install both monkey-patches at the top of `generate_ltx2.py`, wire `_EXTEND_TC_CONFIG` / `_A2V_TC_CONFIG` from the helper's `run_extend`/`run_a2v` paths, and add a `--no-teacache` CLI flag (default-on). **Decision needed:** ride along with the `[ref-watch-phosphene-bump-ltx2-pin-v0148]` pin bump (the calibration constants are part of the same upstream surface that gets renamed) or land independently against today's pin? Scope: small/medium.+- [ ] [ref-watch-phosphene-strip-malloc-subprocess-env] **Strip `Malloc*` env vars before spawning Python subprocesses.** From `reference-watch` review of phosphene (commit `0d7cb137`, 2026-05-28). PortOS's `server/services/videoGen/local.js:609` passes `process.env` through to the Python child unchanged (`const childEnv = { ...process.env, ...(await hfTokenEnv()) };`). On macOS, when the user launched PortOS from Pinokio or any tool that exports an empty/zero `MallocStackLogging` (or related `Malloc*`) var, every Python subprocess prints `MallocStackLogging: can't turn off malloc stack logging because it was not enabled` once per child exit — flooding stderr (~50+ lines per gen for image-gen, which fans out into download/helper subprocesses). Fix: add a `stripDebugMallocEnv(env)` helper in `server/lib/processEnv.js` (new) — `Object.fromEntries(Object.entries(env).filter(([k]) => !k.startsWith('Malloc')))` — barrel it from `server/lib/index.js` per the module-org rule, document in `server/lib/README.md`. Then route every Node→Python spawn through it: `server/services/videoGen/local.js:611`, plus the image-gen spawn sites (grep `spawn.*python` under `server/`). Scope: small.+- [ ] [ref-watch-phosphene-pin-mlx-lazy-eval-cadence-envs] **Pin `LTX2_DIT_EVAL_EVERY=1` + `LTX2_GEMMA_EVAL_EVERY=1` at helper boot.** From `reference-watch` review of phosphene (commit `ec1437fe`, 2026-05-28). PortOS's `scripts/generate_ltx2.py` doesn't set either env, so the upstream `ltx-2-mlx` default (`=8`) governs lazy MLX graph eval cadence. Phosphene's M4 Max 64 GB matrix on I2V Balanced 5s / 121 f shows `=8` → ~3 min/step, `=1` → ~7 s/step (~25× faster denoise); `=0` is also fast but extends the documented post-decode hang. Fix: add at the very top of `generate_ltx2.py`, BEFORE any `from ltx_pipelines_mlx import …`, `os.environ.setdefault("LTX2_DIT_EVAL_EVERY", "1"); os.environ.setdefault("LTX2_GEMMA_EVAL_EVERY", "1")`. Smoke-test all five modes (t2v/i2v/fflf/extend/a2v) on a real Mac before merging since `=1` interacts with the same post-decode hang the existing `[ref-watch-phosphene-sigkill-watchdog-videogen-local]` slug already plans to mitigate. Scope: small.## Deferred Architecture (human-led planning)@@ -105,6 +108,7 @@ Items here need a research / design pass, an explicit decision, or a preconditio- [ ] [cos-on-demand-mark-app-review-started-dedupe] **`evaluateTasks` on-demand loop — dedupe `markAppReviewStarted` calls per app.** Surfaced by gemini review (2026-05-23) at `server/services/cos.js:730`. When multiple on-demand requests for the same app are queued in a single evaluation cycle, `markAppReviewStarted` is called once per request — wasted state writes (single-user / single-instance so not a correctness bug, just churn). Collect unique `appId`s before the loop and call once. Nit-level priority.- [ ] [subagent-spawner-top-level-side-effects] **`subAgentSpawner.js` top-level side effects — move init into an explicit `initSpawner()`.** Surfaced by gemini review (2026-05-23) at `server/services/subAgentSpawner.js:153`. Module-load wires event listeners + timers, which interferes with test isolation (each test import re-arms them). Wrap the init block in `export function initSpawner()` and call it from `server/index.js` after dependencies are ready. Treat as a refactor — needs care that no consumer of the module relies on the import-time wiring.- [ ] [ref-watch-phosphene-long-clip-temporal-boost-12fps] **"Long Clip Temporal Boost" (render at 12fps, interpolate to 24fps).** From `reference-watch` review of phosphene (commit `53585fc`, 2026-05-22). Phosphene added a 12fps render path that uses ffmpeg's `minterpolate` / RIFE downstream to fill back to 24fps, doubling the effective clip length per memory budget. PortOS doesn't have an interpolation post-step in `server/services/videoGen/local.js` — adding one is a feature decision, not a bug fix. The math helpers (`_duration_to_8k_frames`, LTX `8k+1` frame-count snapping) are useful regardless; PortOS's `DEFAULT_NUM_FRAMES = 121` is already 8k+1-aligned but UI-side validation could borrow this pattern. **Decision needed:** is this worth a feature surface? No clear user pain motivating it today.+- [ ] [ref-watch-phosphene-t2v-standard-env-gated-two-stage] **Env-gated two-stage T2V perf experiment.** From `reference-watch` review of phosphene (commit `5004b40b`, 2026-05-28). PortOS's `scripts/generate_ltx2.py#run_text` already routes through `TwoStagePipeline` *when `cfg_scale` is set* (~line 221-222) — but the default no-CFG path uses single-stage `TextToVideoPipeline`. Phosphene's experiment routes T2V Standard through `pipe.generate_two_stage()` (half-res Stage 1 + 2× latent upsample + 3-step Stage 2 refine, the same recipe HQ + I2V Standard already use) even without CFG, gated on `PHOSPHENE_T2V_TWO_STAGE=1`. Predicted ~30-35 % wall-time reduction on T2V Standard (M4 Max 7:40 → 5:15 on a 5 s clip; math: 5.0 step-equivalents + ~30 s vs 8.0 step-equivalents native). Fix: in `run_text`, when `cfg_scale is None`, branch on a new `PORTOS_T2V_TWO_STAGE` env (or settings flag) to call `pipe.generate_two_stage(...)` with stage1_steps=8, stage2_steps=3, cfg_scale=1.0. **Decision needed:** worth the A/B knob, or just flip the default to two-stage T2V universally once we've validated quality? Scope: small.### Federated media sync — deferred follow-ups (2026-05-23)diff --git a/client/src/components/videoGen/RuntimeInstallModal.jsx b/client/src/components/videoGen/RuntimeInstallModal.jsxindex 027194d7a8..6a4aa83120 100644--- a/client/src/components/videoGen/RuntimeInstallModal.jsx+++ b/client/src/components/videoGen/RuntimeInstallModal.jsx@@ -28,6 +28,11 @@ export default function RuntimeInstallModal({ open, runtime, label, onClose, onCconst [confirmingCancel, setConfirmingCancel] = useState(false);const logsEndRef = useRef(null);const esRef = useRef(null);+ // Mirror `done` into a ref so es.onerror can read the latest value — the+ // effect's closure captures the initial `done=false` and never refreshes,+ // so without this the modal flashes "Connection to installer lost" when+ // the server cleanly closes the SSE socket right after sending `complete`.+ const doneRef = useRef(false);// Stash onComplete in a ref so the EventSource effect doesn't tear down// mid-install on every parent re-render with a fresh inline arrow.const onCompleteRef = useRef(onComplete);@@ -62,6 +67,7 @@ export default function RuntimeInstallModal({ open, runtime, label, onClose, onCsetLogs([]);setStreamStarted(false);setDone(false);+ doneRef.current = false;setError(null);setConfirmingCancel(false);pendingRef.current = [];@@ -81,6 +87,7 @@ export default function RuntimeInstallModal({ open, runtime, label, onClose, onCappendLog({ kind: 'log', text: msg.message });} else if (msg.type === 'complete') {setDone(true);+ doneRef.current = true;appendLog({ kind: 'success', text: msg.message });flush();es.close();@@ -96,7 +103,7 @@ export default function RuntimeInstallModal({ open, runtime, label, onClose, onC};es.onerror = () => {- setError((prev) => prev ?? (done ? null : 'Connection to installer lost. Restart PortOS or try again.'));+ setError((prev) => prev ?? (doneRef.current ? null : 'Connection to installer lost. Restart PortOS or try again.'));es.close();esRef.current = null;};diff --git a/scripts/generate_hunyuan.py b/scripts/generate_hunyuan.pyindex 0e6eaa8fb5..26b5008266 100644--- a/scripts/generate_hunyuan.py+++ b/scripts/generate_hunyuan.py@@ -40,10 +40,16 @@ def parse_args() -> argparse.Namespace:p.add_argument("--guidance", type=float, default=6.0, help="embedded_guidance_scale for the cfg-distilled model")p.add_argument("--seed", type=int, default=42)p.add_argument("--precision", default="fp32", choices=["fp16", "bf16", "fp32"],- help="dtype for DiT + VAE + text encoder. fp32 matches upstream's "- "sample_video_mps.py — fp16/bf16 trip an MPS matmul assertion "- "(`Destination NDArray and Accumulator NDArray cannot have "- "different datatype`) at the first text-encoder forward pass.")+ help="dtype for DiT + VAE + text encoder. fp32 is the ONLY working "+ "value on Apple Silicon MPS — verified empirically that both fp16 "+ "and bf16 trip `MPSNDArrayMatrixMultiplication.mm:5799 failed "+ "assertion: Destination NDArray and Accumulator NDArray cannot "+ "have different datatype` within ~2s of the first forward pass. "+ "MPS matmul kernels always use an fp32 accumulator internally, so "+ "a non-fp32 output dtype guarantees a mismatch. Upstream's "+ "sample_video_mps.py reaches the same conclusion. The choices list "+ "keeps fp16/bf16 selectable in case a future PyTorch/MPS release "+ "fixes this, but DO NOT switch the default without re-testing.")p.add_argument("--output", required=True)return p.parse_args()@@ -160,9 +166,20 @@ def stage_hunyuan_model_base(repo_dir, snapshot_dir):te2 = base / "text_encoder_2"if not (te2 / "config.json").is_file():+ # Stage into `.partial` and atomic-rename so an interrupted snapshot+ # (Ctrl-C, network drop) can't satisfy the `config.json`-only+ # idempotency gate above with a half-downloaded directory — without+ # this, the next run would skip the download and fail deep inside+ # hyvideo with a confusing missing-weights error. Mirrors the+ # text_encoder branch below.+ te2_staging = te2.with_name(te2.name + ".partial")+ shutil.rmtree(te2_staging, ignore_errors=True)+ te2_staging.mkdir(parents=True)print(f"STAGE:download-clip:{CLIP_REPO}", file=sys.stderr, flush=True)with heartbeat("download-clip"):- _snap(CLIP_REPO, local_dir=str(te2), allow_patterns=list(CLIP_FILES))+ _snap(CLIP_REPO, local_dir=str(te2_staging), allow_patterns=list(CLIP_FILES))+ shutil.rmtree(te2, ignore_errors=True)+ os.replace(te2_staging, te2)te = base / "text_encoder"if not (te / "config.json").is_file():diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex d7c08cd9b2..41c468082a 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -248,9 +248,15 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {}send({ type: 'log', message: `▸ Starting ${info.label} install via ${info.installEnvVar}=1 bash scripts/setup-image-video.sh` });+ // `detached: true` puts bash in its own process group so a cancel from the+ // client can take down uv / pip / git children too. Without it, SIGTERM on+ // bash leaves a multi-GB `git clone` (and any subsequent pip downloads)+ // orphaned to init — the user sees the modal close but the bandwidth keeps+ // burning until the network drops or the snapshot completes.const child = spawn('bash', [scriptPath], {env: { ...process.env, [info.installEnvVar]: '1' },stdio: ['ignore', 'pipe', 'pipe'],+ detached: true,});runtimeInstallInFlight.set(info.id, child);@@ -289,7 +295,16 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {});req.on('close', () => {- if (!child.killed) child.kill('SIGTERM');+ if (!child.killed && child.pid) {+ // Negative pid signals the whole process group — required because+ // `setup-image-video.sh` shells out to `uv pip install` / `git clone`,+ // and a plain `child.kill('SIGTERM')` only signals bash itself, leaving+ // the slow children running in the background. Wrap in try/catch so an+ // already-dead group (race with the close handler) doesn't crash the+ // server with ESRCH.+ try { process.kill(-child.pid, 'SIGTERM'); }+ catch { child.kill('SIGTERM'); }+ }safeEnd();});}));