Skip to content

A motion design studio on your own machine: Claude makes the video step by step, you approve every stage. Bring your own Claude Code or API key.

Windows: a PowerShell installer, and setup that works on Windows

Gerrod Noordsy69bbcdd1ff98
diff --git a/README.md b/README.md
index 419fee0..d572cfa 100644
--- a/README.md
+++ b/README.md
@@ -43,8 +43,9 @@ sessions and days.
## Quick start
-> **Tested mostly on Linux so far.** A Windows version is coming in the next two weeks (by October 20, 2026). macOS
-> should mostly work but hasn't been tested yet.
+> **Tested mostly on Linux so far.** A Windows version is coming in the next two weeks (by October 20, 2026): the
+> installer is ready, sessions are next ([docs/WINDOWS.md](docs/WINDOWS.md)). macOS should mostly work but hasn't
+> been tested yet.
You need **Node 20+** and **ffmpeg**. For real videos you also need one of:
- [Claude Code](https://claude.com/claude-code), logged in (your plan pays), or
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 3c27ae1..79f8093 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -114,6 +114,14 @@ depend on setup (`harness/skills/blender-3d`, `harness/skills/assets`, the toolk
are installed into each project by `torch.mjs`. A pipeline step with `"when": "music"` is marked `skipped` at start
when the studio or the brief has no music; a skipped step counts as finished only once its own predecessors are.
+## Platforms (`src/platform.mjs`)
+
+What differs between Linux, macOS and Windows: finding a program on the `PATH` (with `PATHEXT` on Windows),
+running `.cmd` programs like npm through `cmd.exe` with quoted arguments, Windows' own `tar.exe`, Git Bash, the
+`PATH` separator and opening a file. Each function takes `platform`, `env` and `exists` as options, so
+`test/platform.test.mjs` checks the Windows behaviour on any machine. The Windows installer is `install.ps1`; the
+port's status is in [WINDOWS.md](WINDOWS.md).
+
## Keys (`src/keys.mjs`)
One registry of the keys a studio can hold (Anthropic, ElevenLabs), what each is for, and when a project needs it:
diff --git a/docs/SETUP.md b/docs/SETUP.md
index 9b5c9ac..191a6ca 100644
--- a/docs/SETUP.md
+++ b/docs/SETUP.md
@@ -86,7 +86,7 @@ installed). On other systems the other toolkits still install; Nova is reported
## Platforms
**Mortiflix has mostly been tested on Linux so far.** A Windows version is coming in the next two weeks (by
-October 20, 2026). macOS should work for most of setup (the code has its Blender build, Chrome location and uv
+October 20, 2026): the installer and setup are ready, sessions are next. See [WINDOWS.md](WINDOWS.md). macOS should work for most of setup (the code has its Blender build, Chrome location and uv
installer) but hasn't been tested, and Nova FX doesn't build there. ComfyUI's install assumes an NVIDIA card with CUDA.
If an install fails, the walkthrough shows the command and its last lines of output; fixes and reports are welcome.
diff --git a/docs/WINDOWS.md b/docs/WINDOWS.md
new file mode 100644
index 0000000..18355bf
--- /dev/null
+++ b/docs/WINDOWS.md
@@ -0,0 +1,90 @@
+# Windows
+
+> **Work in progress.** Installing works as described below, but a session (the part where Claude makes the video)
+> doesn't run on Windows yet: see [What's left](#whats-left). The goal is a working Windows version by October 20, 2026.
+
+## Install
+
+In **PowerShell** (not CMD; you don't need to run it as Administrator):
+
+```powershell
+irm https://raw.githubusercontent.com/GTKottman/mortiflix-oss/main/install.ps1 | iex
+```
+
+It checks for what Mortiflix needs and offers to install what's missing, asking first each time:
+
+| Needs | Why | Installed with |
+|---|---|---|
+| Windows 10 1809 or newer | what Node 20, Claude Code and winget need | |
+| Node.js 20+ | runs Mortiflix | `winget install OpenJS.NodeJS.LTS` |
+| Git for Windows | downloads Mortiflix and the 3D toolkits; its Git Bash runs the sessions' shell commands | `winget install Git.Git` |
+| ffmpeg | renders and checks every video | `winget install Gyan.FFmpeg` |
+| Claude Code (optional) | does the work on your Claude plan; an Anthropic API key works instead | Anthropic's installer, `irm https://claude.ai/install.ps1 \| iex` |
+
+Node and Git may show Windows' "allow this app to make changes" prompt. Then it clones Mortiflix into
+`%USERPROFILE%\mortiflix-oss` (or updates the clone that's there), runs `npm install` and `npm link` (which puts
+`mortiflix` in `%APPDATA%\npm`, already on your PATH), and starts `mortiflix init`.
+
+Choices, as environment variables (set them before the line above):
+
+```powershell
+$env:MORTIFLIX_DIR = 'D:\mortiflix-oss' # where the code goes
+$env:MORTIFLIX_BRANCH = 'main' # which branch to clone
+$env:MORTIFLIX_YES = '1' # yes to every question
+$env:MORTIFLIX_SKIP_INIT = '1' # stop before mortiflix init
+```
+
+From a clone: `powershell -ExecutionPolicy Bypass -File install.ps1 -Dir D:\mortiflix-oss -Yes -SkipInit`.
+
+Run it again any time to update. `mortiflix doctor` shows what's there, with the winget command for anything
+missing.
+
+## What `mortiflix setup` does on Windows
+
+- **Music**: renders in your Chrome, or in **Microsoft Edge** if there's no Chrome (Edge is Chromium and comes with
+ Windows), so nothing is downloaded.
+- **Downloads** are unpacked with Windows' own `tar.exe` (`C:\Windows\System32`), never the GNU tar from Git for
+ Windows, which reads `C:\…` as a network address.
+- **npm and npx** (`.cmd` programs on Windows) are run through `cmd.exe` with each argument quoted, so a studio
+ under a folder with spaces (`C:\Users\Ada Lovelace\Mortiflix`) works.
+- **uv** and **browser-harness** install to `%USERPROFILE%\.local\bin`, as on Linux.
+- **Blender**: yours is reused from `C:\Program Files\Blender Foundation`; otherwise the official Windows zip is
+ unpacked into the studio. **Nova FX doesn't build on Windows yet** (the other toolkits install).
+- **Local narration** (ComfyUI + Qwen3-TTS) installs the same way, with PyTorch for CUDA; its window stays hidden.
+
+## Removing it
+
+```powershell
+npm uninstall -g mortiflix
+Remove-Item -Recurse -Force "$env:USERPROFILE\mortiflix-oss", "$env:USERPROFILE\Mortiflix\tools"
+```
+
+`%USERPROFILE%\Mortiflix` is your studio (projects, keys): delete it only if you mean to. Node, Git, ffmpeg and
+Claude Code are ordinary programs: remove them in Settings › Apps, or `winget uninstall <id>`.
+
+## What's left
+
+Found by reading the code for Linux-only assumptions. Checked items are done on this branch.
+
+**Installing**
+- [x] `install.ps1`: prerequisites with winget, Claude Code, clone/update, `npm link`, `mortiflix init`
+- [x] `src/platform.mjs`: finding programs (PATHEXT), running `.cmd` programs, Windows' tar, Git Bash, opening files
+- [x] `mortiflix setup`: the repository path (`file:///C:/…`), tar, npm/npx, Edge, hidden ComfyUI window
+- [x] `mortiflix doctor`: Git Bash, git, and winget hints
+- [ ] Run the installer and every setup part on a real Windows 10 and 11 machine
+
+**Running sessions** (next)
+- [ ] The bridge listens on a Unix socket path (`src/bridge.mjs`); on Windows it has to be a named pipe
+ (`\\.\pipe\mfx-…`)
+- [ ] Sessions' `PATH` is joined with `:` (`src/backends/claude-code.mjs`, `src/backends/anthropic-api.mjs`); use
+ `pathDelimiter()`
+- [ ] `bin/mfx` is a Node script with a shebang: Git Bash runs it, but Claude Code's PowerShell tool needs an
+ `mfx.cmd` next to it
+- [ ] Stopping a session kills its process group (`process.kill(-pid)`: claude-code backend, the API backend's
+ shell, the render queue); Windows needs `taskkill /T /F /PID`
+- [ ] The API backend's shell is `bash`; on Windows, Git Bash from `findGitBash()`
+- [ ] The Remotion template links `node_modules` with a directory symlink (needs Developer Mode or admin on
+ Windows); use a junction. It also runs `sleep`, which Windows doesn't have
+- [ ] `secrets.json` relies on file mode 600, which Windows ignores; the user profile's permissions protect it.
+ Say so in SECURITY.md, or set an ACL
+- [ ] Nova FX's C core: build with MSVC or MinGW (it uses OpenMP and Vulkan)
diff --git a/install.ps1 b/install.ps1
new file mode 100644
index 0000000..8d88471
--- /dev/null
+++ b/install.ps1
@@ -0,0 +1,163 @@
+# Mortiflix for Windows: one command in PowerShell gets you from nothing to `mortiflix init`.
+#
+# irm https://raw.githubusercontent.com/GTKottman/mortiflix-oss/main/install.ps1 | iex
+#
+# or, from a checkout: powershell -ExecutionPolicy Bypass -File install.ps1 [-Dir <folder>] [-Yes] [-SkipInit]
+#
+# It checks for Node 20+, Git for Windows and ffmpeg, and offers to install what's missing with winget (Windows'
+# own package manager; Node and Git may show a Windows "allow changes" prompt). It offers Claude Code too, with
+# Anthropic's own installer. Then it clones Mortiflix (or updates your clone), installs its one npm dependency, puts
+# `mortiflix` on your PATH with `npm link`, and runs `mortiflix init`. Nothing is installed without asking.
+#
+# Run through `iex` it can't take parameters, so the same choices are environment variables:
+# MORTIFLIX_DIR where the code goes (default: %USERPROFILE%\mortiflix-oss)
+# MORTIFLIX_BRANCH the branch to clone (default: main)
+# MORTIFLIX_YES=1 answer yes to every question
+# MORTIFLIX_SKIP_INIT=1 stop before `mortiflix init`
+param(
+ [string]$Dir = $env:MORTIFLIX_DIR,
+ [string]$Branch = $env:MORTIFLIX_BRANCH,
+ [switch]$Yes = ($env:MORTIFLIX_YES -eq '1'),
+ [switch]$SkipInit = ($env:MORTIFLIX_SKIP_INIT -eq '1')
+)
+
+function Install-Mortiflix {
+ param([string]$Dir, [string]$Branch, [bool]$Yes, [bool]$SkipInit)
+ $ErrorActionPreference = 'Stop'
+ $Repo = 'https://github.com/GTKottman/mortiflix-oss.git'
+ if (-not $Dir) { $Dir = Join-Path $env:USERPROFILE 'mortiflix-oss' }
+ if (-not $Branch) { $Branch = 'main' }
+
+ function Say([string]$Text) { Write-Host $Text }
+ function Ok([string]$Text) { Write-Host " [ok] $Text" -ForegroundColor Green }
+ function Missing([string]$Text) { Write-Host " [--] $Text" -ForegroundColor Yellow }
+ function Fail([string]$Text) { throw "Mortiflix install stopped: $Text" }
+
+ function Ask([string]$Question, [bool]$Default = $true) {
+ if ($Yes) { return $true }
+ $hint = if ($Default) { '[Y/n]' } else { '[y/N]' }
+ $a = (Read-Host "$Question $hint").Trim().ToLower()
+ if (-not $a) { return $Default }
+ return $a.StartsWith('y')
+ }
+
+ # Programs installed a moment ago aren't on this window's PATH yet: read it again from the registry, and keep the
+ # folders that per-user installers use (Claude Code, uv, npm's global folder).
+ function Update-Path {
+ $machine = [Environment]::GetEnvironmentVariable('Path', 'Machine')
+ $user = [Environment]::GetEnvironmentVariable('Path', 'User')
+ $extra = @((Join-Path $env:USERPROFILE '.local\bin'), (Join-Path $env:APPDATA 'npm'))
+ $env:Path = (@($machine, $user) + $extra | Where-Object { $_ }) -join ';'
+ }
+
+ function Find([string]$Name) {
+ $c = Get-Command $Name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
+ if ($c) { return $c.Source }
+ return $null
+ }
+
+ # Runs a program and stops the install if it fails (PowerShell doesn't stop on a program's exit code by itself).
+ # Only programs: a function or alias with the same name (PowerShell names ignore case) must never run instead.
+ function Run([string]$File, [string[]]$Arguments) {
+ Say " > $File $($Arguments -join ' ')"
+ $exe = Find $File
+ if (-not $exe) { Fail "$File isn't on the PATH" }
+ & $exe @Arguments
+ if ($LASTEXITCODE -ne 0) { Fail "$File exited with $LASTEXITCODE" }
+ }
+
+ function Install-WithWinget([string]$Id, [string]$Name) {
+ if (-not (Find 'winget')) {
+ Fail "$Name is missing and winget isn't available to install it. Install it yourself, open a new PowerShell window and run this again. (winget comes with the App Installer from the Microsoft Store.)"
+ }
+ Run 'winget' @('install', '--id', $Id, '--exact', '--source', 'winget', '--accept-package-agreements', '--accept-source-agreements')
+ Update-Path
+ }
+
+ Say ''
+ Say 'Mortiflix: a motion design studio on your own machine'
+ Say ''
+
+ $build = [Environment]::OSVersion.Version.Build
+ if ($build -lt 17763) { Fail "Windows 10 version 1809 or newer is needed (this is build $build)." }
+ Update-Path
+
+ # ---- what Mortiflix needs ----
+ Say 'Checking what this computer has:'
+
+ $node = Find 'node'
+ $nodeMajor = 0
+ if ($node) { $nodeMajor = [int]((& $node --version) -replace '^v(\d+).*', '$1') }
+ if ($nodeMajor -ge 20) { Ok "Node $(& $node --version)" }
+ else {
+ if ($node) { Missing "Node $(& $node --version) is too old: Mortiflix needs 20 or newer" } else { Missing 'Node.js: runs Mortiflix' }
+ if (-not (Ask ' Install Node.js LTS with winget?')) { Fail 'Node.js 20 or newer is needed.' }
+ Install-WithWinget 'OpenJS.NodeJS.LTS' 'Node.js'
+ if (-not (Find 'node')) { Fail 'Node.js installed, but this window can''t see it yet: open a new PowerShell window and run this again.' }
+ Ok "Node $(node --version)"
+ }
+
+ if (Find 'git') { Ok 'Git for Windows' }
+ else {
+ Missing 'Git for Windows: downloads Mortiflix, and its Git Bash runs the sessions'' shell commands'
+ if (-not (Ask ' Install Git for Windows with winget?')) { Fail 'Git is needed to download Mortiflix.' }
+ Install-WithWinget 'Git.Git' 'Git'
+ if (-not (Find 'git')) { Fail 'Git installed, but this window can''t see it yet: open a new PowerShell window and run this again.' }
+ Ok 'Git for Windows'
+ }
+
+ if ((Find 'ffmpeg') -and (Find 'ffprobe')) { Ok 'ffmpeg' }
+ else {
+ Missing 'ffmpeg: renders and checks every video'
+ if (Ask ' Install ffmpeg with winget?') {
+ Install-WithWinget 'Gyan.FFmpeg' 'ffmpeg'
+ if (Find 'ffmpeg') { Ok 'ffmpeg' } else { Missing 'ffmpeg installed: open a new PowerShell window before you make a video' }
+ } else { Missing 'skipped: videos can''t render until ffmpeg is installed (winget install Gyan.FFmpeg)' }
+ }
+
+ if (Find 'claude') { Ok 'Claude Code' }
+ else {
+ Missing 'Claude Code: does the work with your Claude plan (or use an Anthropic API key instead, asked for later)'
+ if (Ask ' Install Claude Code with Anthropic''s installer (claude.ai/install.ps1)?') {
+ # In its own PowerShell, so nothing it does (an `exit`, its variables) reaches this install.
+ Run 'powershell.exe' @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', 'irm https://claude.ai/install.ps1 | iex')
+ Update-Path
+ if (Find 'claude') { Ok 'Claude Code: run "claude" once to log in' } else { Missing 'Claude Code installed: open a new PowerShell window and run "claude" once to log in' }
+ } else { Say ' Skipped: Mortiflix can use an Anthropic API key, or the free demo backend.' }
+ }
+
+ # ---- Mortiflix itself ----
+ Say ''
+ if (Test-Path (Join-Path $Dir '.git')) {
+ Say "Updating Mortiflix in $Dir"
+ Run 'git' @('-C', $Dir, 'pull', '--ff-only')
+ } elseif ((Test-Path $Dir) -and (Get-ChildItem -Force $Dir | Select-Object -First 1)) {
+ Fail ("$Dir already exists and isn't a Mortiflix checkout. Pick another folder, e.g. " + '$env:MORTIFLIX_DIR = ''C:\somewhere''' + ', and run this again.')
+ } else {
+ Say "Downloading Mortiflix into $Dir"
+ Run 'git' @('clone', '--branch', $Branch, $Repo, $Dir)
+ }
+
+ Push-Location $Dir
+ try {
+ Run 'npm.cmd' @('install', '--no-audit', '--no-fund', '--loglevel=error')
+ Run 'npm.cmd' @('link', '--no-audit', '--no-fund', '--loglevel=error')
+ } finally { Pop-Location }
+ Update-Path
+ $mfx = Find 'mortiflix'
+ if (-not $mfx) { Fail "npm link finished but mortiflix isn't on the PATH: add $(Join-Path $env:APPDATA 'npm') to your PATH, or run: node `"$Dir\bin\mortiflix`"" }
+ Ok "mortiflix is on your PATH ($mfx)"
+
+ Say ''
+ if ($SkipInit) {
+ Say 'Done. Next: mortiflix init'
+ return
+ }
+ Say 'Starting `mortiflix init`: it makes your studio folder and walks through setup.'
+ & $mfx init
+ Say ''
+ Say 'Any time: mortiflix doctor (what''s here), mortiflix serve (the studio in your browser).'
+ Say 'New PowerShell windows already have mortiflix on the PATH.'
+}
+
+Install-Mortiflix -Dir $Dir -Branch $Branch -Yes ([bool]$Yes) -SkipInit ([bool]$SkipInit)
diff --git a/src/cli.mjs b/src/cli.mjs
index e28ec6c..60137e7 100644
--- a/src/cli.mjs
+++ b/src/cli.mjs
@@ -14,6 +14,7 @@ import * as setup from './setup.mjs';
import { costText } from './usage.mjs';
import * as booth from './booth.mjs';
import * as rec from './record.mjs';
+import * as plat from './platform.mjs';
const C = process.stdout.isTTY && !process.env.NO_COLOR
? { b: (s) => `\x1b[1m${s}\x1b[0m`, dim: (s) => `\x1b[2m${s}\x1b[0m`, acc: (s) => `\x1b[38;5;208m${s}\x1b[0m`, red: (s) => `\x1b[31m${s}\x1b[0m`, green: (s) => `\x1b[32m${s}\x1b[0m` }
@@ -187,6 +188,9 @@ async function init(root, a) {
console.log(`\n Then: ${C.b('mortiflix demo')} for a free walk-through, or ${C.b('mortiflix serve')} to open the studio in your browser.`);
}
+// What to install a missing tool with on Windows (doctor's hint).
+const WINGET = process.platform === 'win32' ? { ffmpeg: 'Gyan.FFmpeg', ffprobe: 'Gyan.FFmpeg', npx: 'OpenJS.NodeJS.LTS', git: 'Git.Git' } : {};
+
function doctor(root) {
const config = existsSync(paths(root).config) ? loadConfig(root) : null;
const row = (ok, name, detail) => console.log(`${ok ? C.green('✔') : C.red('✖')} ${name.padEnd(14)} ${C.dim(detail)}`);
@@ -197,9 +201,13 @@ function doctor(root) {
const r = b.available(config || loadConfig(root), root);
row(r.ok, name, `${r.detail}${config?.backend === name ? ' ← in use' : ''}`);
}
- for (const [bin, why] of [['ffmpeg', 'renders, checks, the demo'], ['ffprobe', 'the final pass'], ['npx', 'Remotion']]) {
- const r = spawnSync(bin, ['-version'], { encoding: 'utf8' });
- row(r.status === 0 || (bin === 'npx' && spawnSync('npx', ['--version']).status === 0), bin, why);
+ for (const [bin, why] of [['ffmpeg', 'renders, checks, the demo'], ['ffprobe', 'the final pass'], ['npx', 'Remotion'], ['git', 'installs the 3D toolkits and local narration']]) {
+ const found = plat.which(bin);
+ row(Boolean(found) || bin === 'git', bin, found ? why : `${why}: not found${WINGET[bin] ? ` (winget install ${WINGET[bin]})` : ''}`);
+ }
+ if (process.platform === 'win32') {
+ const bash = plat.findGitBash();
+ row(Boolean(bash), 'git bash', bash || 'sessions run shell commands in Git Bash: install Git for Windows (winget install Git.Git)');
}
if (process.platform === 'linux') row(spawnSync('bwrap', ['--version']).status === 0, 'bwrap', `optional session sandbox (${config?.sandbox ? 'on' : 'off'})`);
for (const k of keys.keyStatus(root)) {
@@ -357,8 +365,11 @@ async function review(root, given) {
} else console.log(`${C.b(`[${i}] ${it.label}`)} ${C.dim(it.kind)} ${join(projectPaths(root, id).state, it.file)}`);
});
const files = sub.items.filter((it) => it.file);
- if (files.length && process.platform === 'linux' && (await rl.question(C.dim('\nOpen the files? [y/N] '))).toLowerCase() === 'y') {
- for (const it of files) spawn('xdg-open', [join(projectPaths(root, id).state, it.file)], { detached: true, stdio: 'ignore' }).unref();
+ if (files.length && (await rl.question(C.dim('\nOpen the files? [y/N] '))).toLowerCase() === 'y') {
+ for (const it of files) {
+ const o = plat.openCommand(join(projectPaths(root, id).state, it.file));
+ spawn(o.file, o.args, { ...o.options, detached: true, stdio: 'ignore' }).on('error', () => {}).unref();
+ }
}
const answers = {};
for (const q of sub.questions) {
diff --git a/src/platform.mjs b/src/platform.mjs
new file mode 100644
index 0000000..51fd159
--- /dev/null
+++ b/src/platform.mjs
@@ -0,0 +1,80 @@
+// The few things that differ between Linux, macOS and Windows, in one place, so the rest of the code doesn't guess.
+// Every function takes the platform and environment as options, so tests can ask "what would Windows do?" on Linux.
+//
+// which(bin) a program on the PATH, found without spawning a shell (Windows: tries PATHEXT, e.g. npm.cmd)
+// command(cmd, args) what to spawn: Windows can't spawn npm.cmd/npx.cmd directly (Node refuses .cmd/.bat without a
+// shell since 20.12), so those go through cmd.exe with their arguments quoted for it
+// systemTar() Windows' own tar.exe (bsdtar: unpacks .tar.gz and .zip). Git for Windows' GNU tar reads
+// "C:\..." as a remote host, so it must not be the one found first on the PATH
+// findGitBash() Git for Windows' bash.exe: Claude Code's Bash tool and the sessions' shell commands need it
+// openCommand(file) how to open a file in its default app
+import { existsSync } from 'node:fs';
+import { delimiter as hostDelimiter, dirname, join, win32, posix } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+// The repository's folder (works on Windows, where a file URL's pathname is "/C:/...").
+export const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+const pathFor = (platform) => (platform === 'win32' ? win32 : posix);
+const envGet = (env, name) => env[name] ?? env[Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase())];
+
+export function which(bin, { platform = process.platform, env = process.env, exists = existsSync } = {}) {
+ const p = pathFor(platform);
+ const exts = platform === 'win32' ? ['', ...String(envGet(env, 'PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean).map((e) => e.toLowerCase())] : [''];
+ // On Windows a bare name with no extension (npm's shell script for Git Bash) can't be spawned: skip it.
+ const usable = (f) => exists(f) && (platform !== 'win32' || /\.[a-z0-9]+$/i.test(f));
+ if (/[\\/]/.test(bin)) return exts.map((e) => bin + e).find(usable) || null;
+ for (const dir of String(envGet(env, 'PATH') || '').split(platform === 'win32' ? ';' : ':').filter(Boolean)) {
+ for (const e of exts) {
+ const f = p.join(dir.replace(/^"(.*)"$/, '$1'), bin + e);
+ if (usable(f)) return f;
+ }
+ }
+ return null;
+}
+
+// cmd.exe quoting for one argument. Inside quotes, cmd only treats " and % specially; neither can be escaped
+// reliably for a batch file's %*, so arguments carrying them are refused instead of being passed on mangled.
+export function cmdQuote(arg) {
+ const s = String(arg);
+ if (/["%\r\n]/.test(s)) throw new Error(`can't pass ${JSON.stringify(s)} to a .cmd program: it contains " or %`);
+ return s && !/[\s&()<>^|,;=!']/.test(s) ? s : `"${s}"`;
+}
+
+// What to spawn for `cmd args`: { file, args, options }. Pass `options` on to spawn/spawnSync.
+export function command(cmd, args = [], { platform = process.platform, env = process.env, exists = existsSync } = {}) {
+ if (platform !== 'win32') return { file: cmd, args, options: {} };
+ const found = which(cmd, { platform, env, exists }) || cmd;
+ if (!/\.(cmd|bat)$/i.test(found)) return { file: found, args, options: { windowsHide: true } };
+ const line = [found, ...args].map(cmdQuote).join(' ');
+ return { file: envGet(env, 'ComSpec') || 'cmd.exe', args: ['/d', '/s', '/c', `"${line}"`], options: { windowsVerbatimArguments: true, windowsHide: true } };
+}
+
+export function systemTar({ platform = process.platform, env = process.env, exists = existsSync } = {}) {
+ if (platform !== 'win32') return 'tar';
+ const own = win32.join(envGet(env, 'SystemRoot') || 'C:\\Windows', 'System32', 'tar.exe');
+ return exists(own) ? own : 'tar';
+}
+
+// Where Git for Windows keeps bash.exe: Claude Code's own setting first, then the usual install folders, then
+// next to whichever git.exe is on the PATH (…\Git\cmd\git.exe → …\Git\bin\bash.exe).
+export function findGitBash({ platform = process.platform, env = process.env, exists = existsSync } = {}) {
+ if (platform !== 'win32') return which('bash', { platform, env, exists });
+ const set = envGet(env, 'CLAUDE_CODE_GIT_BASH_PATH');
+ const places = [set];
+ for (const base of [envGet(env, 'ProgramFiles'), envGet(env, 'ProgramFiles(x86)'), envGet(env, 'ProgramW6432')]) if (base) places.push(win32.join(base, 'Git', 'bin', 'bash.exe'));
+ const local = envGet(env, 'LOCALAPPDATA');
+ if (local) places.push(win32.join(local, 'Programs', 'Git', 'bin', 'bash.exe'));
+ const git = which('git', { platform, env, exists });
+ if (git) places.push(win32.join(win32.dirname(win32.dirname(git)), 'bin', 'bash.exe'));
+ return places.filter(Boolean).find((f) => exists(f)) || null;
+}
+
+// The separator between PATH entries, for code that builds a session's PATH.
+export const pathDelimiter = (platform = process.platform) => (platform === process.platform ? hostDelimiter : platform === 'win32' ? ';' : ':');
+
+export function openCommand(file, { platform = process.platform } = {}) {
+ if (platform === 'win32') return { file: 'cmd.exe', args: ['/d', '/s', '/c', `"start "" ${cmdQuote(file)}"`], options: { windowsVerbatimArguments: true, windowsHide: true } };
+ if (platform === 'darwin') return { file: 'open', args: [file], options: {} };
+ return { file: 'xdg-open', args: [file], options: {} };
+}
diff --git a/src/setup.mjs b/src/setup.mjs
index aa6b735..10fd788 100644
--- a/src/setup.mjs
+++ b/src/setup.mjs
@@ -19,10 +19,11 @@ import { pipeline as streamPipeline } from 'node:stream/promises';
import { loadConfig, saveConfig, UserError } from './studio.mjs';
import { voiceConfig } from './voice/index.mjs';
import * as qwen from './voice/qwen.mjs';
+import * as plat from './platform.mjs';
export const STRUDEL_VERSION = '1.3.0';
const OS = platform();
-export const REPO_ROOT = join(dirname(new URL(import.meta.url).pathname), '..');
+export const REPO_ROOT = plat.REPO_ROOT;
const EXE = OS === 'win32' ? '.exe' : '';
export const toolsDir = (root) => join(root, 'tools');
@@ -74,21 +75,20 @@ export const PARTS = [
// ---- running things ----
-function which(bin) {
- const r = spawnSync(OS === 'win32' ? 'where' : 'sh', OS === 'win32' ? [bin] : ['-c', `command -v ${bin}`], { encoding: 'utf8' });
- return r.status === 0 ? r.stdout.split(/\r?\n/)[0].trim() || null : null;
-}
+const which = (bin) => plat.which(bin);
function version(bin, args = ['--version']) {
- const r = spawnSync(bin, args, { encoding: 'utf8', timeout: 20_000 });
- return r.status === 0 ? (r.stdout || r.stderr).split('\n')[0].trim() : null;
+ const c = plat.command(bin, args);
+ const r = spawnSync(c.file, c.args, { ...c.options, encoding: 'utf8', timeout: 20_000 });
+ return r.status === 0 ? (r.stdout || r.stderr).split(/\r?\n/)[0].trim() : null;
}
// A command whose output streams to `log`, line by line. Rejects on a non-zero exit.
export function run(cmd, args, { cwd, env, log = () => {} } = {}) {
return new Promise((ok, fail) => {
log(`$ ${[cmd, ...args].join(' ')}`);
- const p = spawn(cmd, args, { cwd, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'], shell: OS === 'win32' });
+ const c = plat.command(cmd, args);
+ const p = spawn(c.file, c.args, { ...c.options, cwd, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] });
let tail = '';
const onData = (d) => {
const s = String(d);
@@ -148,7 +148,10 @@ function chromeCandidates(root) {
}
if (OS === 'darwin') out.push('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium');
else if (OS === 'win32') {
- for (const base of [process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)'], process.env.LOCALAPPDATA].filter(Boolean)) out.push(join(base, 'Google', 'Chrome', 'Application', 'chrome.exe'));
+ const bases = [process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)'], process.env.LOCALAPPDATA].filter(Boolean);
+ for (const base of bases) out.push(join(base, 'Google', 'Chrome', 'Application', 'chrome.exe'));
+ // Edge is Chromium and comes with Windows 10 and 11: it renders Strudel the same way, with nothing to download.
+ for (const base of bases) out.push(join(base, 'Microsoft', 'Edge', 'Application', 'msedge.exe'));
} else for (const b of ['google-chrome-stable', 'google-chrome', 'chromium', 'chromium-browser']) { const p = which(b); if (p) out.push(p); }
return out;
}
@@ -267,7 +270,7 @@ async function installTransitions(root, log) {
const fresh = `${dir}.new`;
rmSync(fresh, { recursive: true, force: true });
mkdirSync(fresh, { recursive: true });
- await run('tar', ['-xzf', tgz, '-C', fresh, '--strip-components=1'], { log });
+ await run(plat.systemTar(), ['-xzf', tgz, '-C', fresh, '--strip-components=1'], { log });
rmSync(tgz, { force: true });
if (!existsSync(join(fresh, 'catalog.json'))) throw new Error('the download has no catalog.json');
rmSync(dir, { recursive: true, force: true });
@@ -280,7 +283,7 @@ async function installStrudel(root, log) {
const dir = join(toolsDir(root), 'strudel');
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'mortiflix-strudel', private: true, license: 'AGPL-3.0-or-later', dependencies: { '@strudel/web': STRUDEL_VERSION } }, null, 2) + '\n');
- await run(OS === 'win32' ? 'npm.cmd' : 'npm', ['install', '--no-audit', '--no-fund', '--loglevel=error'], { cwd: dir, log });
+ await run('npm', ['install', '--no-audit', '--no-fund', '--loglevel=error'], { cwd: dir, log });
const s = strudelStatus(root);
if (!s.ok) throw new Error('npm finished but @strudel/web is missing');
return s;
@@ -290,7 +293,7 @@ async function installChrome(root, log) {
const have = chromeStatus(root);
if (have.ok) { log(`Using ${have.path}`); saveToolPath(root, 'chrome', have.path); return have; }
const dir = join(toolsDir(root), 'browsers');
- await run(OS === 'win32' ? 'npx.cmd' : 'npx', ['--yes', '@puppeteer/browsers', 'install', 'chrome-headless-shell@stable', '--path', dir], { log });
+ await run('npx', ['--yes', '@puppeteer/browsers', 'install', 'chrome-headless-shell@stable', '--path', dir], { log });
const s = chromeStatus(root);
if (!s.ok) throw new Error('the headless Chrome download finished but no executable was found');
saveToolPath(root, 'chrome', s.path);
@@ -301,7 +304,7 @@ async function ensureUv(log) {
const have = findUv();
if (have) return have;
log('Installing uv (Astral\'s Python tool manager) for your user: https://docs.astral.sh/uv/');
- if (OS === 'win32') await run('powershell', ['-ExecutionPolicy', 'ByPass', '-c', 'irm https://astral.sh/uv/install.ps1 | iex'], { log });
+ if (OS === 'win32') await run('powershell', ['-NoProfile', '-ExecutionPolicy', 'ByPass', '-c', 'irm https://astral.sh/uv/install.ps1 | iex'], { log });
else await run('sh', ['-c', 'curl -LsSf https://astral.sh/uv/install.sh | sh'], { log });
const uv = findUv();
if (!uv) throw new Error('uv installed but wasn\'t found in ~/.local/bin: open a new terminal and run setup again');
@@ -358,7 +361,7 @@ async function installBlender(root, log) {
try { mkdirSync(join(dest, rel.version), { recursive: true }); await run('cp', ['-R', join(mnt, 'Blender.app'), join(dest, rel.version)], { log }); }
finally { await run('hdiutil', ['detach', mnt], { log }).catch(() => {}); }
} else {
- await run('tar', [OS === 'win32' ? '-xf' : '-xJf', file, '-C', dest], { log });
+ await run(plat.systemTar(), [OS === 'win32' ? '-xf' : '-xJf', file, '-C', dest], { log });
}
rmSync(file, { force: true });
const s = blenderStatus(root);
@@ -396,7 +399,7 @@ export function startComfy(root) {
if (!existsSync(py)) throw new UserError('the studio\'s ComfyUI isn\'t installed (mortiflix setup narration)');
const port = Number(new URL(voiceConfig(root).qwen.url).port || 8188);
const out = createWriteStream(join(ws, 'comfyui.log'), { flags: 'a' });
- const p = spawn(py, [join(ws, 'main.py'), '--listen', '127.0.0.1', '--port', String(port)], { cwd: ws, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
+ const p = spawn(py, [join(ws, 'main.py'), '--listen', '127.0.0.1', '--port', String(port)], { cwd: ws, detached: true, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
p.stdout.pipe(out); p.stderr.pipe(out);
p.unref();
return { pid: p.pid, log: join(ws, 'comfyui.log') };
@@ -441,7 +444,7 @@ async function fetchRepo(root, repo, log) {
const tgz = await download(`https://codeload.github.com/${repo}/tar.gz/HEAD`, join(toolsDir(root), 'downloads', `${name}.tar.gz`), log);
rmSync(dest, { recursive: true, force: true });
mkdirSync(dest, { recursive: true });
- await run('tar', ['-xzf', tgz, '-C', dest, '--strip-components=1'], { log });
+ await run(plat.systemTar(), ['-xzf', tgz, '-C', dest, '--strip-components=1'], { log });
rmSync(tgz, { force: true });
return dest;
}
diff --git a/test/platform.test.mjs b/test/platform.test.mjs
new file mode 100644
index 0000000..f145f46
--- /dev/null
+++ b/test/platform.test.mjs
@@ -0,0 +1,85 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import * as plat from '../src/platform.mjs';
+
+// A pretend Windows machine: which files exist, and its environment.
+const files = (...list) => { const set = new Set(list.map((f) => f.toLowerCase())); return (f) => set.has(f.toLowerCase()); };
+const WIN_ENV = {
+ Path: 'C:\\Windows\\System32;C:\\Program Files\\nodejs\\;"C:\\Program Files\\Git\\cmd"',
+ PATHEXT: '.COM;.EXE;.BAT;.CMD',
+ SystemRoot: 'C:\\Windows',
+ ComSpec: 'C:\\Windows\\system32\\cmd.exe',
+ ProgramFiles: 'C:\\Program Files',
+};
+const win = (exists, env = WIN_ENV) => ({ platform: 'win32', env, exists });
+
+test('REPO_ROOT is the repository folder, from a file URL', () => {
+ assert.ok(existsSync(join(plat.REPO_ROOT, 'package.json')));
+ assert.ok(existsSync(join(plat.REPO_ROOT, 'src', 'platform.mjs')));
+});
+
+test('which on Windows: PATHEXT, quoted PATH entries, and npm\'s extensionless shell script is skipped', () => {
+ const fs = files('C:\\Program Files\\nodejs\\npm', 'C:\\Program Files\\nodejs\\npm.cmd', 'C:\\Program Files\\nodejs\\node.exe', 'C:\\Program Files\\Git\\cmd\\git.exe');
+ assert.equal(plat.which('npm', win(fs)), 'C:\\Program Files\\nodejs\\npm.cmd');
+ assert.equal(plat.which('node', win(fs)), 'C:\\Program Files\\nodejs\\node.exe');
+ assert.equal(plat.which('git', win(fs)), 'C:\\Program Files\\Git\\cmd\\git.exe');
+ assert.equal(plat.which('ffmpeg', win(fs)), null);
+ // Environment names are case-insensitive on Windows (PATH vs Path).
+ assert.equal(plat.which('node', win(fs, { PATH: 'C:\\Program Files\\nodejs' })), 'C:\\Program Files\\nodejs\\node.exe');
+});
+
+test('which on Linux searches PATH with ":"', () => {
+ const fs = files('/usr/bin/ffmpeg');
+ assert.equal(plat.which('ffmpeg', { platform: 'linux', env: { PATH: '/bin:/usr/bin' }, exists: fs }), '/usr/bin/ffmpeg');
+ assert.equal(plat.which('npm', { platform: 'linux', env: { PATH: '/bin:/usr/bin' }, exists: fs }), null);
+});
+
+test('command: .cmd programs go through cmd.exe, quoted; .exe and Linux run directly', () => {
+ const fs = files('C:\\Program Files\\nodejs\\npm.cmd', 'C:\\Program Files\\nodejs\\node.exe');
+ const npm = plat.command('npm', ['install', '--prefix', 'C:\\Users\\Ada Lovelace\\Mortiflix\\tools\\strudel'], win(fs));
+ assert.equal(npm.file, 'C:\\Windows\\system32\\cmd.exe');
+ assert.deepEqual(npm.args, ['/d', '/s', '/c', '""C:\\Program Files\\nodejs\\npm.cmd" install --prefix "C:\\Users\\Ada Lovelace\\Mortiflix\\tools\\strudel""']);
+ assert.equal(npm.options.windowsVerbatimArguments, true);
+ const node = plat.command('node', ['-v'], win(fs));
+ assert.deepEqual([node.file, node.args], ['C:\\Program Files\\nodejs\\node.exe', ['-v']]);
+ assert.deepEqual(plat.command('npm', ['i'], { platform: 'linux' }), { file: 'npm', args: ['i'], options: {} });
+});
+
+test('cmdQuote: plain words stay bare, cmd metacharacters are quoted, " and % are refused', () => {
+ assert.equal(plat.cmdQuote('--yes'), '--yes');
+ assert.equal(plat.cmdQuote('a&b'), '"a&b"');
+ assert.equal(plat.cmdQuote('chrome-headless-shell@stable'), 'chrome-headless-shell@stable');
+ assert.equal(plat.cmdQuote(''), '""');
+ assert.throws(() => plat.cmdQuote('say "hi"'), /contains " or %/);
+ assert.throws(() => plat.cmdQuote('%PATH%'), /contains " or %/);
+});
+
+test('systemTar prefers Windows\' own tar.exe over whatever tar is first on the PATH', () => {
+ assert.equal(plat.systemTar(win(files('C:\\Windows\\System32\\tar.exe'))), 'C:\\Windows\\System32\\tar.exe');
+ assert.equal(plat.systemTar(win(files())), 'tar');
+ assert.equal(plat.systemTar({ platform: 'linux' }), 'tar');
+});
+
+test('findGitBash: Claude Code\'s setting, the usual folder, or next to git.exe', () => {
+ const custom = 'D:\\Tools\\Git\\bin\\bash.exe';
+ assert.equal(plat.findGitBash(win(files(custom), { ...WIN_ENV, CLAUDE_CODE_GIT_BASH_PATH: custom })), custom);
+ assert.equal(plat.findGitBash(win(files('C:\\Program Files\\Git\\bin\\bash.exe'))), 'C:\\Program Files\\Git\\bin\\bash.exe');
+ const scoop = { ...WIN_ENV, Path: 'C:\\Users\\a\\scoop\\apps\\git\\current\\cmd', ProgramFiles: 'C:\\Nowhere' };
+ assert.equal(plat.findGitBash(win(files('C:\\Users\\a\\scoop\\apps\\git\\current\\cmd\\git.exe', 'C:\\Users\\a\\scoop\\apps\\git\\current\\bin\\bash.exe'), scoop)),
+ 'C:\\Users\\a\\scoop\\apps\\git\\current\\bin\\bash.exe');
+ assert.equal(plat.findGitBash(win(files())), null);
+});
+
+test('openCommand per platform', () => {
+ assert.equal(plat.openCommand('/a/b.png', { platform: 'linux' }).file, 'xdg-open');
+ assert.equal(plat.openCommand('/a/b.png', { platform: 'darwin' }).file, 'open');
+ const w = plat.openCommand('C:\\My Videos\\final.mp4', { platform: 'win32' });
+ assert.deepEqual(w.args, ['/d', '/s', '/c', '"start "" "C:\\My Videos\\final.mp4""']);
+});
+
+test('pathDelimiter', () => {
+ assert.equal(plat.pathDelimiter('win32'), ';');
+ assert.equal(plat.pathDelimiter('linux'), ':');
+});