From 457121f804dc4ffde182bdc869acef36bb87d59e Mon Sep 17 00:00:00 2001 From: shinyobjectz Date: Thu, 19 Nov 2026 14:29:45 -0800 Subject: [PATCH] raea show, brand and cut on Windows and Linux (#169) raea show asked kill whether the app ran, looked only in /Applications and said it opened files in "the Mac's own viewer". app.ts asks each system its own way through one Here a test can fake: tasklist and the installer's InstallLocation (#178) on Windows, Explorer to open files and start the app, raea.desktop and xdg-open on Linux, and one PowerShell listing to name the harness that ran it. The shell's absolute-path tests take C:\, \\server\share and \ (show.ts absolute/fromCwd). raea brand reads a logo's size from its own header (PNG, GIF, JPEG, WebP, ICO), sips only as a Mac's fallback, and cutting by words off a Mac says what works there. conformance/app.test.ts fakes each system. --- engine/cli/conformance/app.test.ts | 190 +++++++++++++++++++++++++++++ engine/cli/src/app.ts | 162 +++++++++++++++++++----- engine/cli/src/brand.ts | 29 +++++ engine/cli/src/index.ts | 14 ++- engine/cli/src/native.ts | 12 +- engine/cli/src/show.ts | 12 +- 6 files changed, 381 insertions(+), 38 deletions(-) create mode 100644 engine/cli/conformance/app.test.ts diff --git a/engine/cli/conformance/app.test.ts b/engine/cli/conformance/app.test.ts new file mode 100644 index 00000000..60e173c7 --- /dev/null +++ b/engine/cli/conformance/app.test.ts @@ -0,0 +1,190 @@ +// `raea show` and its app on a Mac, Windows and Linux (src/app.ts), each system faked (a Here): where the running +// app's host is, which app is installed, how files open without it, how it's started, and the harness found up the +// processes. #169: on Windows `raea show` asked `kill` whether the app ran, looked only in /Applications, and said +// it had opened the files "in the Mac's own viewer". +import { afterAll, describe, expect, test } from "bun:test"; +import { appHost, computer, harness, installedApp, openFiles, show, type Here } from "../src/app"; +import { pixelsOf } from "../src/brand"; +import { absolute, fromCwd } from "../src/show"; + +const WIN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\raea"; + +/** A system: `platform`, its files (path → text), and its programs' answers; every run is kept in `ran`. */ +function here(platform: string, files: Record = {}, answer: (cmd: string, args: string[]) => { status?: number; stdout?: string } = () => ({})) { + const ran: string[][] = []; + const h: Here & { ran: string[][] } = { + platform, + ran, + run: (cmd, args) => { + ran.push([cmd, ...args]); + const a = answer(cmd, args); + return { status: a.status ?? 0, stdout: a.stdout ?? "" }; + }, + exists: (p) => p in files, + read: (p) => { + if (!(p in files)) throw new Error(`ENOENT ${p}`); + return files[p]; + }, + env: { RAEA_NO_OPEN: undefined }, + home: platform === "win32" ? "C:/Users/me" : "/home/you", + }; + return h; +} + +// the app's host, as the window's (apps/app host/show.ts): an item's link for a show, and /host/shown to say it finds it. +// Its own process: show() posts with a synchronous curl, which a server in this one couldn't answer +const host = Bun.spawn(["bun", "-e", `const s = Bun.serve({ port: 0, fetch: (r) => { const p = new URL(r.url).pathname; return p === "/host/show" ? Response.json({ url: "raea://item/7" }) : p === "/host/shown" ? Response.json({}) : new Response("not found", { status: 404 }); } }); console.log(s.port);`], { stdout: "pipe" }); +afterAll(() => host.kill()); +/** its first line: the port it listens on */ +async function portOf(out: ReadableStream) { + const r = out.getReader(); + let text = ""; + while (!text.includes("\n")) { + const { value, done } = await r.read(); + if (done) throw new Error(`the test's host stopped before it listened: ${text}`); + text += new TextDecoder().decode(value); + } + r.releaseLock(); + return Number(text.trim()); +} +const HOST = `http://127.0.0.1:${await portOf(host.stdout)}`; + +describe("the running app's host", () => { + test("on Windows, its pid is asked of tasklist (Windows has no kill)", () => { + const file = { "C:/Users/me/.raea/app-host.json": JSON.stringify({ url: HOST, pid: 4321 }) }; + const up = here("win32", file, (cmd, args) => (cmd === "tasklist" && args.includes("PID eq 4321") ? { stdout: '"raea.exe","4321","Console","1","80,000 K"\r\n' } : {})); + expect(appHost(up)).toBe(HOST); + expect(up.ran.some(([c]) => c === "kill")).toBe(false); + // a file a stopped app left: tasklist finds no such process ("INFO: No tasks are running...") + const gone = here("win32", file, () => ({ stdout: "INFO: No tasks are running which match the specified criteria.\r\n" })); + expect(appHost(gone)).toBeNull(); + }); + + test("on a Mac or Linux, kill -0", () => { + const file = { "/home/you/.raea/app-host.json": JSON.stringify({ url: HOST, pid: 99 }) }; + expect(appHost(here("linux", file, (cmd) => ({ status: cmd === "kill" ? 0 : 1 })))).toBe(HOST); + expect(appHost(here("linux", file, (cmd) => ({ status: cmd === "kill" ? 1 : 0 })))).toBeNull(); + }); +}); + +describe("the installed app", () => { + test("on Windows, raea.exe in the folder its installer was given (Settings > Apps keeps it)", () => { + const reg = `\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\raea\r\n InstallLocation REG_SZ D:\\Apps\\raea\r\n\r\n`; + const up = here("win32", { "D:\\Apps\\raea\\raea.exe": "" }, (cmd, args) => (cmd === "reg" && args[1] === WIN_KEY ? { stdout: reg } : {})); + expect(installedApp(up)).toBe("D:\\Apps\\raea\\raea.exe"); + }); + + test("on Windows with no InstallLocation, the default folder", () => { + const up = here("win32", { "C:\\Users\\me\\AppData\\Local\\Programs\\raea\\raea.exe": "" }, () => ({ status: 1 })); + up.env.LOCALAPPDATA = "C:\\Users\\me\\AppData\\Local"; + expect(installedApp(up)).toBe("C:\\Users\\me\\AppData\\Local\\Programs\\raea\\raea.exe"); + }); + + test("on a Mac, raea.app in Applications; on Linux, the launcher raea.desktop runs", () => { + expect(installedApp(here("darwin", { "/Applications/raea.app": "" }))).toBe("/Applications/raea.app"); + const desktop = "[Desktop Entry]\nName=raea\nExec=\"/home/you/.local/share/raea-app/launch.sh\"\n"; + expect(installedApp(here("linux", { "/home/you/.local/share/applications/raea.desktop": desktop, "/home/you/.local/share/raea-app/launch.sh": "" }))).toBe("/home/you/.local/share/raea-app/launch.sh"); + expect(installedApp(here("linux"))).toBeUndefined(); + }); +}); + +describe("raea show without the app", () => { + test("on Windows, each file opens in Windows' own viewer through Explorer, its path in Windows' slashes", () => { + const up = here("win32", {}, () => ({ status: 1 })); + const r = show({ files: ["C:/Users/me/cut & keep/a.mp4", "C:/Users/me/b.png"] }, up) as { opened: string[]; viewer: string }; + expect(r.viewer).toBe("Windows' own viewer"); + expect(up.ran.filter(([c]) => c === "explorer.exe")).toEqual([["explorer.exe", "C:\\Users\\me\\cut & keep\\a.mp4"], ["explorer.exe", "C:\\Users\\me\\b.png"]]); + expect(up.ran.some(([c]) => c === "open")).toBe(false); + }); + + test("a question needs the app, said for the system it runs on", () => { + expect(() => show({ files: [], question: "Which?" }, here("win32", {}, () => ({ status: 1 })))).toThrow("isn't on this PC"); + expect(() => show({ files: [], question: "Which?" }, here("darwin"))).toThrow("isn't on this Mac"); + expect(computer(here("linux")).name).toBe("this computer"); + }); + + test("on Linux, xdg-open", () => { + const up = here("linux"); + openFiles(["/home/you/a.mp4"], up); + expect(up.ran).toEqual([["xdg-open", "/home/you/a.mp4"]]); + }); +}); + +describe("raea show starting the app", () => { + test("on Windows: raea.exe started through Explorer, its host waited for, the item posted, no raea:// link", () => { + const files: Record = { "C:\\Users\\me\\AppData\\Local\\Programs\\raea\\raea.exe": "" }; + const up = here("win32", files, (cmd, args) => { + // the app, once started, writes its host's address + if (cmd === "explorer.exe" && args[0].endsWith("raea.exe")) files["C:/Users/me/.raea/app-host.json"] = JSON.stringify({ url: HOST, pid: 77 }); + if (cmd === "tasklist") return { stdout: '"raea.exe","77","Console","1","1 K"' }; + return { status: cmd === "reg" ? 1 : 0 }; + }); + up.env.LOCALAPPDATA = "C:\\Users\\me\\AppData\\Local"; + const r = show({ files: ["C:/Users/me/a.mp4"] }, up) as { url: string; brought: boolean }; + expect(r).toEqual({ url: "raea://item/7", brought: false }); + expect(up.ran.some(([c]) => c === "open" || c === "pgrep")).toBe(false); + }); + + test("on a Mac: open -a, and the window brought up on the item it was started for", () => { + const files: Record = { "/Applications/raea.app": "" }; + const up = here("darwin", files, (cmd, args) => { + if (cmd === "open" && args[0] === "-a") files["/home/you/.raea/app-host.json"] = JSON.stringify({ url: HOST, pid: 77 }); + return { status: cmd === "pgrep" ? 1 : 0 }; + }); + expect(show({ files: ["/tmp/a.mp4"] }, up)).toEqual({ url: "raea://item/7", brought: true }); + expect(up.ran.at(-1)).toEqual(["open", "raea://item/7"]); + }); +}); + +describe("the harness that ran raea show", () => { + test("on Windows, found up every process's record from one PowerShell call, claude.exe as claude", () => { + const list = [`${process.pid}\t500\t"C:\\Users\\me\\raea\\bin\\raea.exe" show a.mp4`, `500\t400\t"C:\\Users\\me\\.local\\bin\\claude.exe" --resume`, `400\t1\tC:\\Windows\\explorer.exe`].join("\r\n"); + const up = here("win32", {}, (cmd) => (cmd === "powershell" ? { stdout: list } : { status: 1 })); + expect(harness(up)).toEqual({ name: "Claude Code", pid: 500 }); + expect(up.ran.filter(([c]) => c === "powershell")).toHaveLength(1); + }); + + test("a runtime's script by its name, the quoted path's spaces kept", () => { + const list = [`${process.pid}\t600\traea.exe show`, `600\t1\t"C:\\Program Files\\nodejs\\node.exe" C:\\Users\\me\\AppData\\Roaming\\npm\\gemini.cmd`].join("\n"); + expect(harness(here("win32", {}, () => ({ stdout: list })))).toEqual({ name: "Gemini", pid: 600 }); + }); + + test("on a Mac or Linux, ps up from the parent", () => { + const up = here("linux", {}, (cmd, args) => (cmd === "ps" && args.at(-1) === String(process.ppid) ? { stdout: " 1 /usr/local/bin/codex exec" } : { stdout: "" })); + expect(harness(up)).toEqual({ name: "Codex", pid: process.ppid }); + }); +}); + +describe("a path from the cwd", () => { + test("a Windows one is absolute, with either slash, a share's too", () => { + for (const p of ["C:\\Users\\me\\a.mp4", "c:/x", "\\\\nas\\clips\\a.mp4", "\\x", "/x"]) expect(absolute(p)).toBe(true); + for (const p of ["a.mp4", "cuts\\a.mp4", "C:a.mp4", "./a"]) expect(absolute(p)).toBe(false); + expect(fromCwd("C:/Users/me/proj", "D:\\clips\\a.mp4")).toBe("D:\\clips\\a.mp4"); + expect(fromCwd("C:/Users/me/proj/", "out\\a.png")).toBe("C:/Users/me/proj/out\\a.png"); + expect(fromCwd("/home/you", "a.png")).toBe("/home/you/a.png"); + }); +}); + +describe("a logo's pixels, on any system", () => { + // until 0.1.8 asked of sips, a Mac's: on Windows and Linux every raster logo in brand.json had no size. Each is the + // head of a 37x23 image from a real encoder (ffmpeg's PNG, GIF and ICO; cwebp's lossy and lossless; Pillow's WebP with + // alpha, VP8X; sips's JPEG, an Exif and a Photoshop block before its frame; ImageMagick's progressive JPEG) + const HEADS: Record = { + png: "iVBORw0KGgoAAAANSUhEUgAAACUAAAAX", + gif: "R0lGODlhJQAXAA==", + "webp lossy": "UklGRiACAABXRUJQVlA4IBQCAAAwDwCdASolABcA", + "webp lossless": "UklGRrIAAABXRUJQVlA4TKUAAAAvJIAF", + "webp with alpha": "UklGRkwCAABXRUJQVlA4IEACAABQDwCdASolABcA", + ico: "AAABAAEAJRc=", + jpeg: "/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAJaADAAQAAAABAAAAFwAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAFwAlAw==", + "jpeg progressive": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wgARCAAXACUD", + }; + for (const [kind, head] of Object.entries(HEADS)) { + test(kind, () => expect(pixelsOf(Buffer.from(head, "base64"))).toEqual({ width: 37, height: 23 })); + } + test("anything else, or a header cut short, has none", () => { + expect(pixelsOf(new TextEncoder().encode("II*\0 a TIFF"))).toBeUndefined(); + expect(pixelsOf(Buffer.from(HEADS.png, "base64").subarray(0, 18))).toBeUndefined(); + expect(pixelsOf(new Uint8Array())).toBeUndefined(); + }); +}); diff --git a/engine/cli/src/app.ts b/engine/cli/src/app.ts index 51f79974..2c39525a 100644 --- a/engine/cli/src/app.ts +++ b/engine/cli/src/app.ts @@ -1,25 +1,104 @@ // The raea app's host, as the native `raea` reaches it (native.ts): where the running app listens, and the verbs that -// post to it: `raea show` (and its --on tasks), `raea library`, and the agent harness a show names as its poster. +// post to it: `raea show` (and its --on tasks), `raea library`, and the agent harness a show names as its poster. On a +// Mac, Windows or Linux (#169: on Windows `raea show` never found the running app, since it asked `kill`, and said it +// had opened the files "in the Mac's own viewer", which it hadn't). import { spawnSync } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import { homedir } from "node:os"; -import { basename } from "node:path"; import { HARNESSES } from "./show"; +/** What these verbs ask of the computer they run on (a test gives its own: conformance/app.test.ts). */ +export interface Here { + platform: string; + run: (cmd: string, args: string[]) => { status: number | null; stdout: string }; + exists: (path: string) => boolean; + read: (path: string) => string; + env: Record; + home: string; +} + +export const HERE: Here = { + platform: process.platform, + run: (cmd, args) => { + const r = spawnSync(cmd, args, { encoding: "utf8" }); + return { status: r.status, stdout: r.stdout ?? "" }; + }, + exists: existsSync, + read: (p) => readFileSync(p, "utf8"), + env: process.env, + home: homedir(), +}; + +/** This computer as raea names it, and the viewer files open in without the app. */ +export function computer(h: Here = HERE): { name: string; viewer: string } { + if (h.platform === "darwin") return { name: "this Mac", viewer: "the Mac's own viewer" }; + if (h.platform === "win32") return { name: "this PC", viewer: "Windows' own viewer" }; + return { name: "this computer", viewer: "the desktop's own viewer" }; +} + +/** Whether process `pid` is running: `kill -0`, or on Windows (which has no kill) tasklist. */ +function alive(pid: number, h: Here): boolean { + if (h.platform !== "win32") return h.run("kill", ["-0", String(pid)]).status === 0; + return h.run("tasklist", ["/FI", `PID eq ${pid}`, "/NH", "/FO", "CSV"]).stdout.includes(`"${pid}"`); +} + /** The running raea app's host: RAEA_FEED_HOST for an agent the app started, else the address the installed app leaves * in ~/.raea/app-host.json while it runs (apps/app host/host-file.ts), if its process is still there. */ -function appHost(): string | null { - if (process.env.RAEA_FEED_HOST) return process.env.RAEA_FEED_HOST; - const file = process.env.RAEA_HOST_FILE || `${homedir()}/.raea/app-host.json`; +export function appHost(h: Here = HERE): string | null { + if (h.env.RAEA_FEED_HOST) return h.env.RAEA_FEED_HOST; + const file = h.env.RAEA_HOST_FILE || `${h.home}/.raea/app-host.json`; try { - const h = JSON.parse(readFileSync(file, "utf8")) as { url?: string; pid?: number }; - if (h.url && h.pid && spawnSync("kill", ["-0", String(h.pid)]).status === 0) return h.url; + const x = JSON.parse(h.read(file)) as { url?: string; pid?: number }; + if (x.url && x.pid && alive(x.pid, h)) return x.url; } catch { // no app running, or a file left by one that stopped } return null; } +/** The installed raea app, RAEA_APP first: on a Mac raea.app in Applications; on Windows raea.exe in the folder its + * installer put it in (the person picks it, #178; Settings > Apps keeps it as InstallLocation), else the default; on + * Linux the launch.sh that linux/install.sh's raea.desktop runs. */ +export function installedApp(h: Here = HERE): string | undefined { + const at: (string | undefined)[] = [h.env.RAEA_APP]; + if (h.platform === "darwin") at.push("/Applications/raea.app", `${h.home}/Applications/raea.app`); + else if (h.platform === "win32") { + const q = h.run("reg", ["query", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\raea", "/v", "InstallLocation"]).stdout; + const dir = /InstallLocation\s+REG_\w+\s+(.+?)\s*$/m.exec(q)?.[1]; + if (dir) at.push(`${dir.replace(/[\\/]$/, "")}\\raea.exe`); + if (h.env.LOCALAPPDATA) at.push(`${h.env.LOCALAPPDATA}\\Programs\\raea\\raea.exe`); + } else { + try { + const entry = h.read(`${h.env.XDG_DATA_HOME || `${h.home}/.local/share`}/applications/raea.desktop`); + at.push(/^Exec="?([^"\n]+?)"?\s*$/m.exec(entry)?.[1]); + } catch { + // not in the desktop's app list + } + } + return at.find((p) => p && h.exists(p)); +} + +/** Files opened as the system opens them (a double-click's app): open, Windows' Explorer, xdg-open. */ +export function openFiles(files: string[], h: Here = HERE) { + if (h.platform === "darwin") h.run("open", files); + // Explorer, not cmd's start: start reads its line as cmd does, so a folder named with & or ^ breaks it + else if (h.platform === "win32") for (const f of files) h.run("explorer.exe", [f.replace(/\//g, "\\")]); + else for (const f of files) h.run("xdg-open", [f]); +} + +/** The installed app started: open -a on a Mac, Explorer on Windows, its launch.sh in the background on Linux. */ +export function startApp(app: string, h: Here = HERE) { + if (h.platform === "darwin") h.run("open", ["-a", app]); + else if (h.platform === "win32") h.run("explorer.exe", [app]); + else h.run("sh", ["-c", 'nohup "$0" >/dev/null 2>&1 &', app]); +} + +/** A quarter of a second between looks for the app's host (Windows has no sleep command: PowerShell's). */ +function pause(h: Here) { + if (h.platform === "win32") h.run("powershell", ["-NoProfile", "-Command", "Start-Sleep -Milliseconds 250"]); + else h.run("/bin/sleep", ["0.25"]); +} + /** POST a host route of the raea app at `at`, answering its JSON; its refusal is thrown as it says it. */ function postHost(at: string, route: string, a: Record): any { const r = spawnSync("curl", ["-sS", "--max-time", "120", "-w", "\n%{http_code}", "-H", "content-type: application/json", "--data-binary", "@-", `${at.replace(/\/$/, "")}${route}`], { input: JSON.stringify(a), encoding: "utf8", maxBuffer: 64 << 20 }); @@ -33,24 +112,26 @@ function postHost(at: string, route: string, a: Record): any { /** `raea show` (show.ts): the item made by the raea app's host (apps/app host/show.ts), the app started first when it's * installed and not running. The window is brought up on it by its raea:// link only with --open or when the app was - * just started; otherwise the page finds it and says so. Without the app, the files open in the Mac's own viewer. */ -export function show(a: Record): unknown { - let at = appHost(); + * just started (on a Mac or Linux: Windows' app has no raea:// link, so there the post lands as its notice); otherwise + * the page finds it and says so. Without the app, the files open in the system's own viewer. */ +export function show(a: Record, h: Here = HERE): unknown { + let at = appHost(h); let launched = false; if (!at) { - const app = [process.env.RAEA_APP, "/Applications/raea.app", `${homedir()}/Applications/raea.app`].find((p) => p && existsSync(p)); + const app = installedApp(h); const files = (a.files as string[]) ?? []; if (!app) { - if (a.question || a.questions) throw new Error("a question needs the raea app, and it isn't on this Mac (raea.io)"); - spawnSync("open", files); - return { opened: files }; + if (a.question || a.questions) throw new Error(`a question needs the raea app, and it isn't on ${computer(h).name} (raea.io)`); + openFiles(files, h); + return { opened: files, ...computer(h) }; } - if (spawnSync("pgrep", ["-f", `${app}/Contents/MacOS/raea-window`]).status === 0) + if (h.platform === "darwin" && h.run("pgrep", ["-f", `${app}/Contents/MacOS/raea-window`]).status === 0) throw new Error("the raea app running here is older than raea show (it leaves no ~/.raea/app-host.json); quit it and open it again to update, then show it again"); - spawnSync("open", ["-a", app]); + startApp(app, h); launched = true; - // the window's host writes its address once it listens: a minute at most, in quarter seconds - for (let i = 0; i < 240 && !(at = appHost()); i++) spawnSync("/bin/sleep", ["0.25"]); + // the window's host writes its address once it listens: a minute at most + const until = Date.now() + 60_000; + while (!(at = appHost(h)) && Date.now() < until) pause(h); if (!at) throw new Error(`the raea app didn't start (no ~/.raea/app-host.json after a minute); open ${app} and show it again`); } let shown: { url: string }; @@ -72,23 +153,48 @@ export function show(a: Record): unknown { return false; } })(); - const brought = !process.env.RAEA_NO_OPEN && (a.open === true || launched || !finds); - if (brought) spawnSync("open", [shown.url]); + const brought = !h.env.RAEA_NO_OPEN && h.platform !== "win32" && (a.open === true || launched || !finds); + if (brought) h.run(h.platform === "darwin" ? "open" : "xdg-open", [shown.url]); return { ...shown, brought }; } +/** A process's parent and command line: ps, or on Windows every process's at once from PowerShell (one call, not one + * per step up: each takes a good part of a second there). */ +function processes(h: Here): { start: number; of: (pid: number) => { ppid: number; args: string } | undefined } { + if (h.platform !== "win32") { + return { + start: process.ppid, + of: (pid) => { + const m = /^\s*(\d+)\s+(.*)$/.exec(h.run("ps", ["-o", "ppid=,args=", "-p", String(pid)]).stdout); + return m ? { ppid: Number(m[1]), args: m[2] } : undefined; + }, + }; + } + const all = new Map(); + const list = h.run("powershell", ["-NoProfile", "-NonInteractive", "-Command", "Get-CimInstance Win32_Process | ForEach-Object { '{0}`t{1}`t{2}' -f $_.ProcessId, $_.ParentProcessId, $_.CommandLine }"]).stdout; + for (const line of list.split(/\r?\n/)) { + const [pid, ppid, ...args] = line.split("\t"); + if (Number(pid) > 0) all.set(Number(pid), { ppid: Number(ppid), args: args.join("\t") }); + } + return { start: all.get(process.pid)?.ppid ?? 0, of: (pid) => all.get(pid) }; +} + /** The agent harness that started this command (show.ts HARNESSES), found up its parent processes: a program's own - * name, or the script a runtime runs (`node .../gemini`). Nothing when no harness is up there. */ -export function harness(): { name: string; pid: number } | undefined { - let pid = process.ppid; + * name (claude, or on Windows claude.exe), or the script a runtime runs (`node .../gemini`). Nothing when no harness + * is up there. (Until 0.1.8 raea's engine had no process.ppid, so this found none anywhere.) */ +export function harness(h: Here = HERE): { name: string; pid: number } | undefined { + const up = processes(h); + let pid = up.start; for (let i = 0; i < 16 && pid > 1; i++) { - const m = /^\s*(\d+)\s+(.*)$/.exec(spawnSync("ps", ["-o", "ppid=,args=", "-p", String(pid)], { encoding: "utf8" }).stdout ?? ""); - if (!m) return undefined; - for (const w of m[2].split(/\s+/).slice(0, 2).map((w) => basename(w).toLowerCase())) { + const p = up.of(pid); + if (!p) return undefined; + // a Windows command line quotes a path with spaces in it: "C:\Program Files\nodejs\node.exe" ... + const words = (p.args.match(/"[^"]*"|\S+/g) ?? []).slice(0, 2).map((w) => w.replace(/^"|"$/g, "")); + for (const w of words.map((w) => w.split(/[\\/]/).pop()!.toLowerCase().replace(/\.(exe|cmd|bat|ps1)$/, ""))) { const hit = HARNESSES.find(([re]) => re.test(w)); if (hit) return { name: hit[1], pid }; } - pid = Number(m[1]); + pid = p.ppid; } return undefined; } @@ -109,7 +215,7 @@ export function task(a: Record): unknown { /** An op of the feed host's libraries (apps/app host/library/service.ts): POST /host/library. */ export function library(a: Record): unknown { const at = appHost(); - if (!at) throw new Error("libraries live in the raea app: open it on this Mac (or set RAEA_FEED_HOST to its address)"); + if (!at) throw new Error(`libraries live in the raea app: open it on ${computer().name} (or set RAEA_FEED_HOST to its address)`); return postHost(at, "/host/library", a); } diff --git a/engine/cli/src/brand.ts b/engine/cli/src/brand.ts index 49085068..cc2f96ba 100644 --- a/engine/cli/src/brand.ts +++ b/engine/cli/src/brand.ts @@ -251,3 +251,32 @@ export function brandKit(input: BrandInput, date = new Date().toISOString().slic ]; return { files, said: said.join("\n") }; } + +/** A raster's pixels from its header: PNG, GIF, JPEG, WebP or ICO (a logo's formats), on any system */ +export function pixelsOf(b: Uint8Array): { width: number; height: number } | undefined { + const v = new DataView(b.buffer, b.byteOffset, b.byteLength); + const tag = (at: number, s: string) => String.fromCharCode(...b.subarray(at, at + s.length)) === s; + const wh = (width: number, height: number) => (width > 0 && height > 0 ? { width, height } : undefined); + try { + if (tag(1, "PNG")) return wh(v.getUint32(16), v.getUint32(20)); + if (tag(0, "GIF8")) return wh(v.getUint16(6, true), v.getUint16(8, true)); + if (tag(0, "RIFF") && tag(8, "WEBP")) { + if (tag(12, "VP8 ")) return wh(v.getUint16(26, true) & 0x3fff, v.getUint16(28, true) & 0x3fff); + if (tag(12, "VP8L")) return wh(1 + (((b[22] & 0x3f) << 8) | b[21]), 1 + (((b[24] & 0xf) << 10) | (b[23] << 2) | ((b[22] & 0xc0) >> 6))); + if (tag(12, "VP8X")) return wh(1 + (b[24] | (b[25] << 8) | (b[26] << 16)), 1 + (b[27] | (b[28] << 8) | (b[29] << 16))); + } + if (b[0] === 0 && b[1] === 0 && b[2] === 1 && b[3] === 0) return wh(b[6] || 256, b[7] || 256); + if (b[0] === 0xff && b[1] === 0xd8) { + // JPEG: its segments up to the first frame header (SOF0-15, not DHT, JPG or DAC) + for (let i = 2; i + 9 < b.length; ) { + if (b[i] !== 0xff) return undefined; + const m = b[i + 1]; + if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return wh(v.getUint16(i + 7), v.getUint16(i + 5)); + i += 2 + v.getUint16(i + 2); + } + } + } catch { + // a header cut short + } + return undefined; +} diff --git a/engine/cli/src/index.ts b/engine/cli/src/index.ts index 2b83fcc1..93539a03 100644 --- a/engine/cli/src/index.ts +++ b/engine/cli/src/index.ts @@ -24,7 +24,7 @@ const out = (stdout: string, exitCode = 0, stderr = "") => ({ stdout, stderr, ex // `raea library` (library.ts), kept apart from the imports above import { libraryVerb } from "./library"; // `raea show` (show.ts): what a session shows the person, in the raea app -import { labelsIn, showVerb } from "./show"; +import { absolute, fromCwd, labelsIn, showVerb } from "./show"; // `raea clothes` (clothes.ts): garments for SOMA's body from words import { clothesVerb } from "./clothes"; // `raea bug` (bug.ts): an agent's report of a bug in raea, to raea's server @@ -113,8 +113,12 @@ Not there: React hooks come from "react" (useMemo, useState), not from raea. /** The workspace a folder is in: the nearest folder at or above it holding .raea/workspace, through the shell's fs. */ async function workspaceAbove(c: Ctx, from: string): Promise { - for (let d = from.replace(/\/$/, ""); d; d = d.slice(0, d.lastIndexOf("/"))) { + // up to the root, / or on Windows C: + for (let d = from.replace(/[\\/]+$/, ""); d; ) { if (await c.fs.exists(`${d}/.raea/workspace`)) return d; + const up = Math.max(d.lastIndexOf("/"), d.lastIndexOf("\\")); + if (up < 0) break; + d = d.slice(0, up); } return undefined; } @@ -123,7 +127,7 @@ async function workspaceAbove(c: Ctx, from: string): Promise export function raeaHandler(host?: Host, engine?: Engine) { return async (args: string[], ctx: unknown) => { const c = ctx as unknown as Ctx; - const p = (rel: string) => (rel.startsWith("/") ? rel : `${c.cwd.replace(/\/$/, "")}/${rel}`); + const p = (rel: string) => fromCwd(c.cwd, rel); const ask = (op: string, a: Record = {}) => { if (!host) throw new Error(`raea ${op} needs a host (the native raea's src/native.ts); this shell has none`); return host(op, a); @@ -163,7 +167,7 @@ export function raeaHandler(host?: Host, engine?: Engine) { if (args.includes("--layout") && args[args.indexOf("--layout") + 1] !== "feature") return out("", 2, "raea init [--layout feature]\n"); if (args.includes("--layout")) { for (const d of FEATURE_DIRS) await c.fs.mkdir(p(d), { recursive: true }); - const name = c.cwd.replace(/\/$/, "").split("/").pop() || "project"; + const name = c.cwd.replace(/[\\/]$/, "").split(/[\\/]/).pop() || "project"; for (const [f, body] of Object.entries(featureLayout(name, shape))) await put(f, body); return out(made.length ? `made ${made.join(", ")}; render it with raea render src/main.tsx\n` : "nothing to make: the project's files are here\n"); } @@ -205,7 +209,7 @@ export function raeaHandler(host?: Host, engine?: Engine) { } await c.fs.mkdir(p(home), { recursive: true }); const done: string[] = []; - const shown = (rel: string) => (home.startsWith("/") ? `shared/components/${rel.slice(home.length + 1)}` : rel); + const shown = (rel: string) => (absolute(home) ? `shared/components/${rel.slice(home.length + 1)}` : rel); for (const n of names) { const set = REGISTRY[n]; if (set) { diff --git a/engine/cli/src/native.ts b/engine/cli/src/native.ts index 15f0f20b..c44b6cbf 100644 --- a/engine/cli/src/native.ts +++ b/engine/cli/src/native.ts @@ -7,16 +7,17 @@ import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { basename, delimiter, dirname, extname } from "node:path"; -import { brandKit } from "./brand"; +import { brandKit, pixelsOf } from "./brand"; import { readSite, stylesOf } from "./scrape"; import { wordsOf } from "./heard"; import { harness, library, show, task } from "./app"; +import { fromCwd } from "./show"; import { clothesHost } from "./wardrobe"; import { raeaHandler, type Engine, type Host } from "./index"; const [raea, ...args] = process.argv.slice(2); const cwd = process.cwd(); -const at = (p: string) => (p.startsWith("/") ? p : `${cwd}/${p}`); +const at = (p: string) => fromCwd(cwd, p); /** The project's shape: its cut's (cuts.json's edit), else a 1080x1920 vertical at 30 fps */ function shape() { @@ -98,6 +99,9 @@ function ensure(name: string): string { } function hearTake(take: string, out: string) { + // parakeet-mlx is Apple silicon's (MLX); elsewhere raea has no transcriber yet, so the two ways that work there + if (process.platform !== "darwin") + throw new Error(`cutting ${take} by its words needs its transcript, and raea transcribes only on a Mac so far: give it one as ${basename(out)} ([{ "text", "start_ms", "end_ms" }], beside it), or cut it by time: --at A-B`); const dir = mkdtempSync(`${tmpdir()}/raea-hear-`); try { const wav = `${dir}/take.wav`; @@ -339,13 +343,15 @@ function curl(url: string, o: { out?: string; secs?: number } = {}): { body: str return { body, url: final || url }; } -/** A logo's size: an SVG's viewBox or width/height, a raster's pixels by sips */ +/** A logo's size: an SVG's viewBox or width/height, a raster's pixels from its header (else, on a Mac, by sips) */ function sizeOf(file: string): { width?: number; height?: number } { if (file.endsWith(".svg")) { const head = readFileSync(file, "utf8").slice(0, 2000); const vb = /viewBox\s*=\s*["']\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(head); return vb ? { width: Math.round(+vb[1]), height: Math.round(+vb[2]) } : {}; } + const own = pixelsOf(readFileSync(file)); + if (own || process.platform !== "darwin") return own ?? {}; const r = spawnSync("sips", ["-g", "pixelWidth", "-g", "pixelHeight", file], { encoding: "utf8" }); const n = (k: string) => Number(new RegExp(`${k}: (\\d+)`).exec(r.stdout ?? "")?.[1]) || undefined; return { width: n("pixelWidth"), height: n("pixelHeight") }; diff --git a/engine/cli/src/show.ts b/engine/cli/src/show.ts index 35e02aac..7ee09a47 100644 --- a/engine/cli/src/show.ts +++ b/engine/cli/src/show.ts @@ -50,6 +50,14 @@ const FLAGS = new Set(["--open"]); /** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts * walks up its parents): any harness, not only the ones that mark their shells. */ +/** Whether a path is absolute: POSIX's /..., and Windows' C:\... (or C:/...), \\server\share\... and \... Until 0.1.8 + * only a POSIX one was, so on Windows `raea show C:\...\cut.mp4` named a file under the cwd (#169). Here, not node:path: + * index.ts runs in the app's own shell too, with no Node. */ +export const absolute = (f: string) => /^(?:[\\/]|[A-Za-z]:[\\/])/.test(f); + +/** `f` from `cwd`: itself when it's absolute */ +export const fromCwd = (cwd: string, f: string) => (absolute(f) ? f : `${cwd.replace(/[\\/]$/, "")}/${f}`); + export const HARNESSES: [RegExp, string][] = [ [/^claude$/, "Claude Code"], [/^codex/, "Codex"], [/^gemini$/, "Gemini"], [/^kimi$/, "Kimi"], [/^opencode$/, "OpenCode"], [/^goose$/, "Goose"], [/^cursor-agent$/, "Cursor"], [/^amp$/, "Amp"], [/^qwen$/, "Qwen Code"], [/^crush$/, "Crush"], [/^aider$/, "Aider"], @@ -80,7 +88,7 @@ export function parseShow(args: string[], cwd: string) { const choices = many("--choice"); const unknown = args.find((a, i) => a.startsWith("--") && !WITH_VALUE.has(a) && !FLAGS.has(a) && !WITH_VALUE.has(args[i - 1] ?? "")); if (unknown) throw new Error(`no ${unknown} here\n${SHOW_USAGE}`); - const abs = (f: string) => (f.startsWith("/") ? f : `${cwd.replace(/\/$/, "")}/${f}`); + const abs = (f: string) => fromCwd(cwd, f); const files = args.filter((a, i) => !a.startsWith("--") && !WITH_VALUE.has(args[i - 1] ?? "")).map(abs); // the questions in order: each --question starts one and its --choice's follow; a --preview after a --choice is that // choice's, after the --question (before any choice) the question's own @@ -151,7 +159,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record ask("task", { item, comments, state, by, sub: a.sub, note: state === "done" ? a.note : undefined, asks: state === "working" && a.asks.length ? a.asks : undefined, version, ...(state === "working" ? { status: a.status, states: a.states, sign } : {}) }) as { item: string; comments: string[] }; const said = (m: { item: string; comments: string[] }, state: string) => `Marked ${m.comments.join(", ")} ${state} on ${m.item}: the person sees ${a.sub ? `${by.name} · ${a.sub}` : by.name} ${state === "working" ? "on them" : "finished them"}${state === "working" && a.status ? `; it reads "${a.status}"${a.states?.length ? ` (its asks: ${a.states.join(", ")})` : ""}` : ""}.`;