diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f2e8786 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +# Scenes, templates and fixtures are compared byte for byte: LF everywhere, on every checkout. +* text=auto eol=lf +*.png binary +*.jpg binary +*.ico binary +*.zip binary +*.mp4 binary +*.woff2 binary diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 79c4087..b8aba5e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,7 +15,7 @@ permissions: jobs: test: name: Test and typecheck - # The product is Mac-only, and the end-to-end tests bind this machine's LAN address. + # The end-to-end tests bind this machine's LAN address. (Windows has its own job below.) runs-on: macos-latest timeout-minutes: 20 steps: @@ -52,3 +52,38 @@ jobs: working-directory: apps/apple/Kit - run: swift test working-directory: apps/apple/Kit + + windows: + name: Server and switcher on Windows + # The server runs on Windows too (apps/windows bundles it): its tests there, where paths, renames + # and links behave differently. GitHub's runners are admins, so the file-link tests run too. + runs-on: windows-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version-file: .bun-version + - run: bun install --frozen-lockfile + - run: bun test + - run: bun run typecheck + + windows-app: + name: Windows app (dotnet test, build) + runs-on: windows-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # The Core tests start Bun stub servers; without bun they skip. + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version-file: .bun-version + - uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0 + with: + dotnet-version: 10.0.x + - run: dotnet test apps/windows/ViewSwitcher.Core.Tests + - run: dotnet build apps/windows/ViewSwitcher.Windows/ViewSwitcher.Windows.csproj -c Release -p:Platform=x64 -warnaserror diff --git a/AGENTS.md b/AGENTS.md index 68410c5..31496b4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,7 @@ Statuses on the board: To Do, In Progress, In Review, Blocked, Done. ## Workstreams -Scene editor (EDIT) first and landing page (SITE) in parallel; Mac app (MAC) after EDIT merges. The Product map holds the order. +Scene editor (EDIT) first and landing page (SITE) in parallel; Mac app (MAC) after EDIT merges; Windows app (WIN) after that. The Product map holds the order. ## Task codes @@ -28,6 +28,7 @@ Scene editor (EDIT) first and landing page (SITE) in parallel; Mac app (MAC) aft - `MAC`: Mac app (plan `gz7zkvlaofixz6ljsljdj6sh`) - `MCP`: agent connection, the MCP server and Edit with AI (plan `q47xu7oithlmzpkeshfn5bdh`) - `PHONE`: iPhone app, one universal app with the iPad's (plan `yxec9dlaej36ib1ytknvdoq7`) +- `WIN`: Windows app: the server on Windows and the WinUI 3 shell (plan `krx65gign63m8v3pb27jnpep`) - `HARD`: hardening: CI and repo hygiene, the live path, the trust boundary, the Mac and iOS shells, vocabulary (plan `giqaj703oqbthlkfknwewy9h`) - `ISSUE`: bugs, debt and loose ends found outside a slice @@ -52,10 +53,17 @@ Bun workspaces monorepo: a live-stream switcher that drives OBS (`apps/`, `packa - `packages/shared` holds the wire types and pure logic, whichever app uses it: `resolveStream` and `parseLibraryPath` (server and switcher), the HTML scanner (`scanElements`, the editor), the pack validator (server, `packages/packs`, the site), and the OBS math only the server uses (`coverTransform`, `obsColor`, in `apps/server/src/live/placement.ts`). Keep it dependency-free and tested (`bun test`). - `apps/web` must stay a static SPA (no SSR or server functions). The iPad app (`apps/apple`, target ViewSwitcher iPad) loads it from the server over its USB-C tunnel; deploy with `bun run ipad:deploy`. Safe areas come from the shells: `env(safe-area-inset-*)` on the iPad, `--shell-*` variables and `data-shell` from the Mac app (MAC-13a). - `apps/apple` is one Xcode project generated from `project.yml` (XcodeGen; the .xcodeproj is gitignored): ViewSwitcher.app for macOS around the server compiled with `bun build --compile` (Contents/Helpers), the iPad app, and the shared ViewSwitcherKit package. The server must keep running as that binary (no repo-relative paths without an env override, see `apps/server/src/config.ts`). Build with `bun run mac:build`, check with `bun run mac:e2e` (never on port 7420), test with `xcodebuild test` (apps/apple/README.md). +- `apps/windows` is the Windows app: a WinUI 3 shell (.NET 10, Windows App SDK, unpackaged) around the same server compiled for Windows (`Helpers\viewswitcher-server.exe`) and the switcher in WebView2; `ViewSwitcher.Core` ports Kit's logic with its tests (apps/windows/README.md). Build with `bun run win:build`, check with `bun run win:e2e` (never on port 7420), test with `bun run win:test`. The page in its window gets no host objects or web messages. +- The server runs on macOS and Windows: + - a path from `relative()` becomes a library path with `/` (`split(sep).join("/")`), never with a backslash; + - per-user folders come from `platform-dirs.ts`; + - a folder is claimed with `fsx.ts` `claimRename` (Windows never renames over a folder), and a file replaced with `renameOver`; + - what phones and agents are told names the computer through `COMPUTER` ("Mac" or "PC"). + Tests that need a file symlink, a named pipe or POSIX permissions use `test.skipIf(!fileLinks)` / `test.skipIf(!posix)` (`test-links.ts`); folder links work on Windows through junctions. Checkouts are LF (`.gitattributes`). - Scenes are untrusted code (agents, template packs from anyone): `/library/` pages are served with a CSP sandbox (`apps/server/src/scene-sandbox.ts`) and every scene frame is sandboxed (`apps/web/src/lib/scene-frame.ts`). Never give a scene frame `allow-same-origin` together with `allow-scripts`, except the editor's, which only ever loads `?inert` (served with `script-src 'none'`); never reach into a scene frame with contentDocument except that one; the program page talks to scenes through the bridge (`scene-bridge.ts`). Template packs: docs/template-packs.md. - Routes live in one table, `apps/server/src/http/routes.ts`, and `http/dispatch.ts` is the only way in: host guard, audience, exact Origin for non-GET (and WebSocket upgrades), JSON body (multipart for the two upload routes), then the handler, with `frame-ancestors 'self'` and nosniff on everything outside `/library/`. Every route declares its audience (`mac`, `macOrUsb`, `paired`, `public`; gate.ts); undeclared is Mac-only, and so is a path no route has. With the Wi-Fi setting off, nothing but this Mac and the USB-C device is served (tailscale serve included). - No absolute filesystem paths in API responses, except `GET /api/info` (the library folder and Edit with AI's commands, for the Mac app's Open Library Folder and the sheet) and `GET /api/agent/viewswitcher.mcpb` (the Claude Desktop extension, whose command is this install's server), which are `mac` routes: `isMac` in `apps/server/src/gate.ts` (loopback peer and Host, no proxy headers, not the Wi-Fi listener, and not the USB-C iPad, whose bridge sockets are marked). Phones paired over Wi-Fi never get these, nor `/mcp`. Errors go through `scrub.ts`, and only `mac` sees a 500's message. - Every library path a client sends, read or write, goes through `resolveInLibrary` (`apps/server/src/library/contain.ts`): real-path containment through links, and no dot segments except a staged pack's preview, which may only be read. - `/mcp` (agents, `apps/server/src/mcp/`) is a `mac` route, refuses any `Origin` that `originAllowed` rejects, and sits under `hostTrusted`. The agent on-air guard (`agent-guard.ts`) limits MCP tools only, never the switcher's own routes. - The agent skill and library CLAUDE.md that new libraries get live in `apps/server/library-kit/`; change the skill there. -- Typecheck: `bun run typecheck` (apps/web and its tests, apps/server, packages/shared with its tests). CI (`.github/workflows/ci.yml`) runs it with `bun test`, `astro check`, the switcher build and Kit's `swift test` on every PR; keep it green. Bun is pinned in `.bun-version`. +- Typecheck: `bun run typecheck` (apps/web and its tests, apps/server, packages/shared with its tests). CI (`.github/workflows/ci.yml`) runs it with `bun test`, `astro check`, the switcher build and Kit's `swift test` on macOS, and `bun test`, the typecheck, `dotnet test` and the Windows app's build on Windows, on every PR; keep it green. Bun is pinned in `.bun-version`. diff --git a/README.md b/README.md index dd2bea3..cd2070d 100644 --- a/README.md +++ b/README.md @@ -85,8 +85,11 @@ bun run start # builds the switcher, serves everything on http://loca # or, while working on the app itself: bun run dev # server on :7420 (watch) + Vite on http://localhost:5173 bun run mac:dev # builds the Mac app (Debug) and runs it, attached to the server above (or starting one from source) +bun run win:dev # on Windows: builds the Windows app (Debug) and runs it, the same way ``` +The server runs on macOS and Windows. The Windows app (a WinUI 3 shell, the same server compiled for Windows, the switcher in WebView2, phones and tablets over the Wi-Fi) is in [apps/windows](apps/windows/README.md); it needs the .NET 10 SDK to build. + Vite's dev server proxies `/api`, `/library` and `/ws` to the server and keeps the browser's Host (`apps/web/vite.config.ts`), so the dev page at `http://localhost:5173` is the server's own origin and its changes are accepted; no extra setting is needed. Another dev host needs its origin in `VIEWSWITCHER_ORIGINS`. The library (your shows) is `~/ViewSwitcher Library` unless `VIEWSWITCHER_LIBRARY` says otherwise. The first run creates it with the agent skill and a first show, "My channel". Closing the Mac app's window keeps the server running for OBS and the iPhone or iPad; Quit (in the menu bar or ⌘Q) stops it. @@ -97,16 +100,17 @@ The library (your shows) is `~/ViewSwitcher Library` unless `VIEWSWITCHER_LIBRAR | var | default | |---|---| | `VIEWSWITCHER_LIBRARY` | `~/ViewSwitcher Library` | -| `VIEWSWITCHER_STATE` | `~/Library/Application Support/ViewSwitcher`: this Mac's own state for each library (paired phones and tablets, the agent on-air setting), kept outside the library so nothing cloned, pulled or synced with it can carry them | +| `VIEWSWITCHER_STATE` | `~/Library/Application Support/ViewSwitcher` (on Windows `%APPDATA%\ViewSwitcher`): this computer's own state for each library (paired phones and tablets, the agent on-air setting), kept outside the library so nothing cloned, pulled or synced with it can carry them | | `PORT` | `7420` | | `HOST` | `127.0.0.1`. Loopback only: the server refuses to start with another address; the Wi-Fi setting is the way onto the network (below) | | `VIEWSWITCHER_LAN` | `1` also listens on the Wi-Fi from the start (the Mac app passes its "Let Phones and Tablets on This Wi-Fi Connect" setting) | | `VIEWSWITCHER_LAN_HOST` | `0.0.0.0`: the address the Wi-Fi listener binds (tests bind this Mac's LAN IP) | | `VIEWSWITCHER_ADMIN_TOKEN` | set by the Mac app at each launch: the secret for the pairing endpoints (`/api/remote…`); unset, they answer 404 | -| `OBS_URL` / `OBS_PASSWORD` | `ws://127.0.0.1:4455` / read from OBS's own settings on this Mac | +| `OBS_URL` / `OBS_PASSWORD` | `ws://127.0.0.1:4455` / read from OBS's own settings on this computer (`~/Library/Application Support/obs-studio`, on Windows `%APPDATA%\obs-studio`) | | `OBS_SCENE` / `OBS_PROGRAM_SOURCE` / `OBS_GROUND_SOURCE` | `ViewSwitcher` / `ViewSwitcher Program` / `ViewSwitcher Ground` | | `OBS_SOURCES` (or the older `OBS_DEVICES`) | `Camera,Screen,iPad`: the OBS sources a view can place in its camera boxes. A view hides each of these that it has no camera box for, and also any other source a view has ever placed (a Guest or Camera 2 box; remembered in `.viewswitcher/state.json`). Every other item in the ViewSwitcher scene (a mic, music, a watermark) and the program and ground sources are never touched. | -| `VIEWSWITCHER_EDITOR` | app for "Open the file", e.g. `Cursor` (default: your text editor) | +| `VIEWSWITCHER_EDITOR` | app for "Open the file", e.g. `Cursor` (on Windows, the editor's .exe; default: your text editor, or Notepad) | +| `VIEWSWITCHER_STOP_ON_STDIN` | Windows app: `1` stops the server, saving paired devices first, when its stdin closes (Windows has no SIGTERM) | | `VIEWSWITCHER_LOG` | `1` prints requests, placements and OBS-browser errors | | `VIEWSWITCHER_USB` | `0` turns off the USB-C bridge | | `VIEWSWITCHER_WEB_DIST` / `VIEWSWITCHER_STARTER` / `VIEWSWITCHER_LIBRARY_KIT` | `apps/web/dist` / `apps/server/starter` / `apps/server/library-kit` (the Mac app points these into its Resources) | diff --git a/apps/apple/scripts/node-modules-dirs.ts b/apps/apple/scripts/node-modules-dirs.ts index 0b0e688..3517396 100644 --- a/apps/apple/scripts/node-modules-dirs.ts +++ b/apps/apple/scripts/node-modules-dirs.ts @@ -3,7 +3,7 @@ // bun apps/apple/scripts/node-modules-dirs.ts prints one path per line, relative to // It exits non-zero rather than print a short list, so build.sh never skips a folder in silence. import { readFileSync } from "node:fs"; -import { join } from "node:path"; +import { join, posix } from "node:path"; export function nodeModulesDirs(repo: string): string[] { const { workspaces } = JSON.parse(readFileSync(join(repo, "package.json"), "utf8")); @@ -15,9 +15,10 @@ export function nodeModulesDirs(repo: string): string[] { throw new Error(`can't clean for workspace pattern ${JSON.stringify(pattern)}`); } // A workspace is a folder with a package.json; Bun.Glob skips dot folders (.git, .pu/worktrees). - for (const file of new Bun.Glob(`${pattern.replace(/\/+$/, "")}/package.json`).scanSync({ cwd: repo })) { + for (const found of new Bun.Glob(`${pattern.replace(/\/+$/, "")}/package.json`).scanSync({ cwd: repo })) { + const file = found.split("\\").join("/"); // Glob answers with backslashes on Windows if (file.split("/").includes("node_modules")) continue; - dirs.add(join(file, "..", "node_modules")); + dirs.add(posix.join(file, "..", "node_modules")); } } return [...dirs].sort(); diff --git a/apps/server/src/agent-connect.test.ts b/apps/server/src/agent-connect.test.ts index 9d7c271..4fb5204 100644 --- a/apps/server/src/agent-connect.test.ts +++ b/apps/server/src/agent-connect.test.ts @@ -2,10 +2,12 @@ import { describe, expect, test } from "bun:test"; import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { claudeCodeCommand, commandLine, detectClients, MCPB_LAUNCHER, mcpbFile, mcpbManifest, shellFolder, stdioLaunch } from "./agent-connect"; +import { listZip, readZipEntrySync } from "@viewswitcher/packs"; +import { claudeCodeCommand, commandLine, compiled, detectClients, MCPB_LAUNCHER, MCPB_LAUNCHER_WINDOWS, mcpbFile, mcpbManifest, shellFolder, stdioLaunch } from "./agent-connect"; +import { posix } from "../../../test-links"; const HOME = "/Users/sam"; -const detect = (files: string[], path = "/usr/bin:/bin") => detectClients({ home: HOME, path, exists: (p) => files.includes(p) }); +const detect = (files: string[], path = "/usr/bin:/bin") => detectClients({ home: HOME, path, exists: (p) => files.includes(p), platform: "darwin" }); describe("detectClients", () => { test("nothing installed", () => { @@ -29,24 +31,62 @@ describe("detectClients", () => { }); }); +describe("detectClients on Windows", () => { + const WHOME = "C:\\Users\\sam"; + const LOCAL = `${WHOME}\\AppData\\Local`; + const win = (files: string[], path = "C:\\Windows\\System32;C:\\Windows") => + detectClients({ home: WHOME, path, exists: (p) => files.includes(p), platform: "win32", localAppData: LOCAL, programFiles: "C:\\Program Files", appData: `${WHOME}\\AppData\\Roaming` }); + test("nothing installed", () => { + expect(win([])).toEqual({ claudeCode: false, claudeDesktop: false, cursor: false, codex: false, vscode: false }); + }); + test("apps where their Windows installers put them", () => { + expect(win([`${LOCAL}\\AnthropicClaude\\claude.exe`, `${LOCAL}\\Programs\\cursor\\Cursor.exe`, `${LOCAL}\\Programs\\Microsoft VS Code\\Code.exe`])).toEqual({ + claudeCode: false, claudeDesktop: true, cursor: true, codex: false, vscode: true, + }); + expect(win(["C:\\Program Files\\Microsoft VS Code\\Code.exe"]).vscode).toBe(true); + }); + test("claude and codex on %PATH% (;-separated), as .exe or npm's .cmd, or in Claude Code's own folder", () => { + expect(win(["D:\\tools\\claude.exe"], "C:\\Windows;D:\\tools").claudeCode).toBe(true); + expect(win([`${WHOME}\\.local\\bin\\claude.exe`]).claudeCode).toBe(true); + expect(win([`${WHOME}\\AppData\\Roaming\\npm\\codex.cmd`]).codex).toBe(true); + expect(win(["D:\\tools\\claude.exe"]).claudeCode).toBe(false); + expect(win(["D:\\tools\\claude"], "D:\\tools").claudeCode).toBe(false); // no extension: not something Windows runs + }); +}); + describe("commands", () => { test("stdio: the compiled sidecar, or bun with index.ts from source, with the server's port", () => { const app = "/Applications/ViewSwitcher.app/Contents/Helpers/viewswitcher-server"; expect(stdioLaunch(app, null, 7420)).toEqual({ command: app, args: ["--mcp-stdio", "--port", "7420"] }); expect(stdioLaunch("/opt/homebrew/bin/bun", "/src/vs/apps/server/src/index.ts", 7433)).toEqual({ command: "/opt/homebrew/bin/bun", args: ["/src/vs/apps/server/src/index.ts", "--mcp-stdio", "--port", "7433"] }); - expect(commandLine(stdioLaunch("/Volumes/My Disk/ViewSwitcher.app/Contents/Helpers/viewswitcher-server", null, 7420))).toBe("'/Volumes/My Disk/ViewSwitcher.app/Contents/Helpers/viewswitcher-server' --mcp-stdio --port 7420"); + expect(commandLine(stdioLaunch("/Volumes/My Disk/ViewSwitcher.app/Contents/Helpers/viewswitcher-server", null, 7420), "darwin")).toBe("'/Volumes/My Disk/ViewSwitcher.app/Contents/Helpers/viewswitcher-server' --mcp-stdio --port 7420"); + }); + test("stdio on Windows: double quotes around a path with spaces, backslashes as they are", () => { + const exe = "C:\\Users\\Sam Lee\\AppData\\Local\\ViewSwitcher\\current\\Helpers\\viewswitcher-server.exe"; + expect(commandLine(stdioLaunch(exe, null, 7420), "win32")).toBe(`"${exe}" --mcp-stdio --port 7420`); + expect(commandLine(stdioLaunch("C:\\vs\\Helpers\\viewswitcher-server.exe", null, 7420), "win32")).toBe("C:\\vs\\Helpers\\viewswitcher-server.exe --mcp-stdio --port 7420"); + }); + test("compiled: inside the binary on macOS (/$bunfs) and Windows (B:\\~BUN), not from source", () => { + expect(compiled("/$bunfs/root")).toBe(true); + expect(compiled("B:\\~BUN\\root")).toBe(true); + expect(compiled("/src/vs/apps/server/src")).toBe(false); + expect(compiled("C:\\Users\\sam\\vs\\apps\\server\\src")).toBe(false); }); test("Claude Code in the library folder, from ~ with spaces escaped", () => { - expect(claudeCodeCommand(`${HOME}/ViewSwitcher Library`, HOME)).toBe("cd ~/ViewSwitcher\\ Library && claude"); - expect(claudeCodeCommand(`${HOME}/Shows/Sam's (2026)`, HOME)).toBe("cd ~/Shows/Sam\\'s\\ \\(2026\\) && claude"); - expect(claudeCodeCommand("/Volumes/Show Drive/Library", HOME)).toBe("cd /Volumes/Show\\ Drive/Library && claude"); + expect(claudeCodeCommand(`${HOME}/ViewSwitcher Library`, HOME, "darwin")).toBe("cd ~/ViewSwitcher\\ Library && claude"); + expect(claudeCodeCommand(`${HOME}/Shows/Sam's (2026)`, HOME, "darwin")).toBe("cd ~/Shows/Sam\\'s\\ \\(2026\\) && claude"); + expect(claudeCodeCommand("/Volumes/Show Drive/Library", HOME, "darwin")).toBe("cd /Volumes/Show\\ Drive/Library && claude"); expect(shellFolder("/Users/samuel/x", HOME)).toBe("/Users/samuel/x"); }); + test("Claude Code on Windows: PowerShell, the folder single-quoted with quotes doubled", () => { + expect(claudeCodeCommand("C:\\Users\\sam\\ViewSwitcher Library", "C:\\Users\\sam", "win32")).toBe("Set-Location 'C:\\Users\\sam\\ViewSwitcher Library'; claude"); + expect(claudeCodeCommand("D:\\Sam's Shows", "C:\\Users\\sam", "win32")).toBe("Set-Location 'D:\\Sam''s Shows'; claude"); + }); }); describe("the Claude Desktop extension (.mcpb)", () => { const launch = stdioLaunch("/Applications/ViewSwitcher.app/Contents/Helpers/viewswitcher-server", null, 7421); - const manifest = mcpbManifest({ launch, version: "1.0.0" }); + const manifest = mcpbManifest({ launch, version: "1.0.0", platform: "darwin" }); test("an MCPB 0.3 manifest with the fields the spec requires", () => { expect(manifest.manifest_version).toBe("0.3"); @@ -62,7 +102,7 @@ describe("the Claude Desktop extension (.mcpb)", () => { expect(manifest.compatibility.platforms).toEqual(["darwin"]); }); - test("unzips to the manifest and an executable launcher for the same command", () => { + test.skipIf(!posix)("unzips to the manifest and an executable launcher for the same command", () => { const dir = mkdtempSync(join(tmpdir(), "vs-mcpb-")); try { writeFileSync(join(dir, "viewswitcher.mcpb"), mcpbFile(manifest)); @@ -76,4 +116,19 @@ describe("the Claude Desktop extension (.mcpb)", () => { rmSync(dir, { recursive: true, force: true }); } }); + + test("on Windows: made for win32, with a .cmd launcher that runs the same command", () => { + const exe = "C:\\Users\\Sam Lee\\AppData\\Local\\ViewSwitcher\\current\\Helpers\\viewswitcher-server.exe"; + const m = mcpbManifest({ launch: stdioLaunch(exe, null, 7420), version: "1.0.0", platform: "win32" }); + expect(m.compatibility.platforms).toEqual(["win32"]); + expect(m.server.entry_point).toBe(MCPB_LAUNCHER_WINDOWS); + expect(m.server.mcp_config).toEqual({ command: exe, args: ["--mcp-stdio", "--port", "7420"] }); + expect(m.long_description).toContain("this PC"); + const zip = mcpbFile(m); + const entries = listZip(zip); + expect(entries.map((e) => e.name).sort()).toEqual(["manifest.json", MCPB_LAUNCHER_WINDOWS]); + const text = (name: string) => new TextDecoder().decode(readZipEntrySync(zip, entries.find((e) => e.name === name)!)); + expect(JSON.parse(text("manifest.json"))).toEqual(m); + expect(text(MCPB_LAUNCHER_WINDOWS)).toBe(`@echo off\r\nrem ViewSwitcher's MCP connection on this PC (the same command as manifest.json).\r\n"${exe}" --mcp-stdio --port 7420\r\n`); + }); }); diff --git a/apps/server/src/agent-connect.ts b/apps/server/src/agent-connect.ts index e4244a3..be45ad2 100644 --- a/apps/server/src/agent-connect.ts +++ b/apps/server/src/agent-connect.ts @@ -1,29 +1,38 @@ -// How an agent on this Mac connects (the switcher's Edit with AI sheet): which agent apps are +// How an agent on this computer connects (the switcher's Edit with AI sheet): which agent apps are // installed, the stdio command, the Claude Code command, and the Claude Desktop extension (.mcpb). -// Everything here can contain absolute paths, so main.ts answers with it only to this Mac (a mac route, gate.ts isMac), -// and /api/agent/clients turns it into booleans. -import { join } from "node:path"; +// Everything here can contain absolute paths, so main.ts answers with it only to this computer (a mac route, gate.ts isMac), +// and /api/agent/clients turns it into booleans. macOS and Windows differ in where apps live, in how +// a shell quotes a word, and in the .mcpb's launcher; `platform` picks (process.platform by default). +import { posix, win32 } from "node:path"; import type { AgentClients } from "@viewswitcher/shared"; import { storedZip } from "@viewswitcher/packs"; +type Platform = NodeJS.Platform; +const isWin = (p: Platform) => p === "win32"; + export type DetectEnv = { home: string; - /** $PATH. */ + /** $PATH (%PATH% on Windows). */ path: string; exists: (path: string) => boolean; + /** %LOCALAPPDATA%, %ProgramFiles% and %APPDATA% on Windows (defaults under the home folder and C:\Program Files). */ + localAppData?: string; + programFiles?: string; + appData?: string; + platform?: Platform; }; /** * Where command-line agents usually live. The Mac app starts the server from launchd, whose PATH is * only /usr/bin:/bin:/usr/sbin:/sbin, so $PATH alone misses an installed `claude`. */ -const binDirs = (home: string) => [join(home, ".local/bin"), join(home, ".claude/local"), "/opt/homebrew/bin", "/usr/local/bin", join(home, ".bun/bin"), join(home, ".npm-global/bin")]; +const binDirs = (home: string) => [posix.join(home, ".local/bin"), posix.join(home, ".claude/local"), "/opt/homebrew/bin", "/usr/local/bin", posix.join(home, ".bun/bin"), posix.join(home, ".npm-global/bin")]; -export function detectClients(env: DetectEnv): AgentClients { - const appDirs = ["/Applications", join(env.home, "Applications")]; - const app = (name: string) => appDirs.some((d) => env.exists(join(d, `${name}.app`))); +function detectMac(env: DetectEnv): AgentClients { + const appDirs = ["/Applications", posix.join(env.home, "Applications")]; + const app = (name: string) => appDirs.some((d) => env.exists(posix.join(d, `${name}.app`))); const dirs = [...new Set([...env.path.split(":").filter(Boolean), ...binDirs(env.home)])]; - const bin = (name: string) => dirs.some((d) => env.exists(join(d, name))); + const bin = (name: string) => dirs.some((d) => env.exists(posix.join(d, name))); return { claudeCode: bin("claude"), claudeDesktop: app("Claude"), @@ -33,17 +42,51 @@ export function detectClients(env: DetectEnv): AgentClients { }; } +/** + * On Windows: command-line agents on %PATH% (or where their installers put them: ~\.local\bin for + * Claude Code's, npm's global folder for both), as .exe or the .cmd shims npm writes; apps under + * %LOCALAPPDATA%\Programs (per-user installs), %LOCALAPPDATA%\AnthropicClaude (Claude Desktop) or + * Program Files. + */ +function detectWindows(env: DetectEnv): AgentClients { + const j = win32.join; + const local = env.localAppData || j(env.home, "AppData", "Local"); + const roaming = env.appData || j(env.home, "AppData", "Roaming"); + const programs = env.programFiles || "C:\\Program Files"; + const dirs = [...new Set([...env.path.split(";").filter(Boolean), j(env.home, ".local", "bin"), j(roaming, "npm"), j(env.home, ".bun", "bin")])]; + const bin = (name: string) => dirs.some((d) => [".exe", ".cmd"].some((ext) => env.exists(j(d, name + ext)))); + const anyOf = (...paths: string[]) => paths.some((p) => env.exists(p)); + return { + claudeCode: bin("claude"), + claudeDesktop: anyOf(j(local, "AnthropicClaude", "claude.exe"), j(local, "Programs", "Claude", "Claude.exe"), j(programs, "Claude", "Claude.exe")), + cursor: anyOf(j(local, "Programs", "cursor", "Cursor.exe"), j(programs, "Cursor", "Cursor.exe")), + codex: bin("codex") || anyOf(j(local, "Programs", "Codex", "Codex.exe")), + vscode: anyOf(j(local, "Programs", "Microsoft VS Code", "Code.exe"), j(programs, "Microsoft VS Code", "Code.exe")), + }; +} + +export function detectClients(env: DetectEnv): AgentClients { + return isWin(env.platform ?? process.platform) ? detectWindows(env) : detectMac(env); +} + /** * What an agent runs for the stdio connection: this server's own executable with --mcp-stdio and the * port it listens on (never PORT, which the agent's own environment may have for something else). In - * the Mac app that's the compiled sidecar (`entry` null); from source it's bun with index.ts. + * the apps that's the compiled server (`entry` null); from source it's bun with index.ts. */ export function stdioLaunch(execPath: string, entry: string | null, port: number): { command: string; args: string[] } { return { command: execPath, args: [...(entry ? [entry] : []), "--mcp-stdio", "--port", String(port)] }; } -/** One word for a shell: as it is when that's safe, else in single quotes. */ -export function shellWord(s: string): string { +/** + * Whether this server runs compiled (bun build --compile), where import.meta.dir is inside the binary: + * /$bunfs/… on macOS, B:\~BUN\… on Windows. + */ +export const compiled = (dir: string) => dir.startsWith("/$bunfs") || /^[A-Za-z]:[\\/]~BUN[\\/]/.test(dir); + +/** One word for a shell: as it is when that's safe, else quoted (single quotes for sh; double quotes on Windows, where cmd, PowerShell and agents' configs all read them). */ +export function shellWord(s: string, platform: Platform = process.platform): string { + if (isWin(platform)) return /^[\w@%+=:,.\\/-]+$/.test(s) ? s : `"${s.replaceAll('"', '\\"')}"`; return /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replaceAll("'", `'\\''`)}'`; } @@ -55,24 +98,33 @@ export function shellFolder(path: string, home: string): string { return escape(path); } -export function commandLine(launch: { command: string; args: string[] }): string { - return [launch.command, ...launch.args].map(shellWord).join(" "); +export function commandLine(launch: { command: string; args: string[] }, platform: Platform = process.platform): string { + return [launch.command, ...launch.args].map((w) => shellWord(w, platform)).join(" "); } -/** Claude Code started in the library, where its .mcp.json connects it to the switcher. */ -export function claudeCodeCommand(library: string, home: string): string { +/** + * Claude Code started in the library, where its .mcp.json connects it to the switcher. On Windows, for + * PowerShell (Windows Terminal's shell; both 5.1 and 7 read it): a single-quoted path, quotes doubled. + */ +export function claudeCodeCommand(library: string, home: string, platform: Platform = process.platform): string { + if (isWin(platform)) return `Set-Location '${library.replaceAll("'", "''")}'; claude`; return `cd ${shellFolder(library, home)} && claude`; } /** Inside the bundle: MCPB requires an entry point in it, so it carries a launcher for the real command. */ export const MCPB_LAUNCHER = "server/viewswitcher"; +/** Windows runs a .cmd launcher, not a shell script. */ +export const MCPB_LAUNCHER_WINDOWS = "server/viewswitcher.cmd"; /** * The Claude Desktop extension's manifest (MCPB 0.3, github.com/modelcontextprotocol/mcpb, MANIFEST.md). * A "binary" server whose command is this install's own executable, so the bundle carries no code of * ours, only a launcher script for the required entry point. The command carries the port (stdioLaunch). + * It's made for the computer it's downloaded on, so it names that one platform. */ -export function mcpbManifest(o: { launch: { command: string; args: string[] }; version: string }) { +export function mcpbManifest(o: { launch: { command: string; args: string[] }; version: string; platform?: Platform }) { + const win = isWin(o.platform ?? process.platform); + const computer = win ? "this PC" : "this Mac"; return { manifest_version: "0.3", name: "viewswitcher", @@ -80,25 +132,28 @@ export function mcpbManifest(o: { launch: { command: string; args: string[] }; v version: o.version, description: "Edit your ViewSwitcher views and see them rendered, from Claude.", long_description: - "Connects Claude to ViewSwitcher on this Mac: it reads your library, edits views under the same rules as the switcher, looks at a rendered picture of its work in OBS, and puts a view on air only when your on-air setting allows it. ViewSwitcher must be open.", + `Connects Claude to ViewSwitcher on ${computer}: it reads your library, edits views under the same rules as the switcher, looks at a rendered picture of its work in OBS, and puts a view on air only when your on-air setting allows it. ViewSwitcher must be open.`, author: { name: "ViewSwitcher", url: "https://viewswitcher.com" }, homepage: "https://viewswitcher.com", support: "https://viewswitcher.com/support", server: { type: "binary", - entry_point: MCPB_LAUNCHER, + entry_point: win ? MCPB_LAUNCHER_WINDOWS : MCPB_LAUNCHER, mcp_config: { command: o.launch.command, args: o.launch.args }, }, - compatibility: { platforms: ["darwin"] }, + compatibility: { platforms: [win ? "win32" : "darwin"] }, }; } /** The .mcpb file: a zip with the manifest and the launcher. */ export function mcpbFile(manifest: ReturnType): Uint8Array { const { command, args } = manifest.server.mcp_config; - const launcher = `#!/bin/sh\n# ViewSwitcher's MCP connection on this Mac (the same command as manifest.json).\nexec ${commandLine({ command, args })}\n`; + const win = manifest.compatibility.platforms[0] === "win32"; + const launcher = win + ? `@echo off\r\nrem ViewSwitcher's MCP connection on this PC (the same command as manifest.json).\r\n${commandLine({ command, args }, "win32")}\r\n` + : `#!/bin/sh\n# ViewSwitcher's MCP connection on this Mac (the same command as manifest.json).\nexec ${commandLine({ command, args }, "darwin")}\n`; return storedZip([ { name: "manifest.json", data: `${JSON.stringify(manifest, null, 2)}\n` }, - { name: MCPB_LAUNCHER, data: launcher, executable: true }, + { name: manifest.server.entry_point, data: launcher, executable: true }, ]); } diff --git a/apps/server/src/agent-endpoints.test.ts b/apps/server/src/agent-endpoints.test.ts index 3a0e466..72479eb 100644 --- a/apps/server/src/agent-endpoints.test.ts +++ b/apps/server/src/agent-endpoints.test.ts @@ -2,12 +2,18 @@ // /api/info's commands, /api/agent/clients and the Claude Desktop extension answer only this Mac. import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import type { Subprocess } from "bun"; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import http from "node:http"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { basename, join } from "node:path"; +import { listZip, readZipEntrySync } from "@viewswitcher/packs"; +import { commandLine } from "./agent-connect"; import { freePort, SERVER_START_MS, startServer } from "./test-server"; +const WINDOWS = process.platform === "win32"; +/** The same text, ignoring case on Windows, whose paths are case-insensitive. */ +const same = (a: string, b: string) => (WINDOWS ? a.toLowerCase() === b.toLowerCase() : a === b); + let port = 0; let proc: Subprocess; const library = mkdtempSync(join(tmpdir(), "vs-agent-endpoints-")); @@ -42,10 +48,10 @@ describe("from this Mac", () => { test("/api/info has the Claude Code and stdio commands for this install", async () => { const info = JSON.parse(new TextDecoder().decode((await request("/api/info")).body)); expect(info.library).toBe(library); - expect(info.claudeCode).toEndWith(" && claude"); - expect(info.claudeCode).toContain(library.split("/").pop()!); - // From source: bun with index.ts. - expect(info.stdio).toBe(`${process.execPath} ${join(import.meta.dir, "index.ts")} --mcp-stdio --port ${port}`); + expect(info.claudeCode).toEndWith(WINDOWS ? "; claude" : " && claude"); + expect(info.claudeCode).toContain(basename(library)); + // From source: bun with index.ts. (Windows paths match whatever their case: the server may see C:\Users\x\Dev where this test sees dev.) + expect(same(info.stdio, commandLine({ command: process.execPath, args: [join(import.meta.dir, "index.ts"), "--mcp-stdio", "--port", String(port)] }))).toBe(true); }); test("/api/info says whether the Mac app started this server, and which process it is", async () => { @@ -67,9 +73,11 @@ describe("from this Mac", () => { expect(r.status).toBe(200); expect(r.disposition).toContain('filename="ViewSwitcher.mcpb"'); writeFileSync(join(scratch, "v.mcpb"), r.body); - expect(Bun.spawnSync(["unzip", "-q", join(scratch, "v.mcpb"), "-d", join(scratch, "out")]).exitCode).toBe(0); - const manifest = JSON.parse(readFileSync(join(scratch, "out/manifest.json"), "utf8")); - expect(manifest.server.mcp_config).toEqual({ command: process.execPath, args: [join(import.meta.dir, "index.ts"), "--mcp-stdio", "--port", String(port)] }); + const zip = new Uint8Array(r.body); + const entry = listZip(zip).find((e) => e.name === "manifest.json")!; + const manifest = JSON.parse(new TextDecoder().decode(readZipEntrySync(zip, entry))); + expect(same(JSON.stringify(manifest.server.mcp_config), JSON.stringify({ command: process.execPath, args: [join(import.meta.dir, "index.ts"), "--mcp-stdio", "--port", String(port)] }))).toBe(true); + expect(manifest.compatibility.platforms).toEqual([WINDOWS ? "win32" : "darwin"]); }); }); diff --git a/apps/server/src/atomic.ts b/apps/server/src/atomic.ts index f083555..4e55921 100644 --- a/apps/server/src/atomic.ts +++ b/apps/server/src/atomic.ts @@ -3,8 +3,9 @@ // a full disk or two writers at once never leave half a file for the next start to misread. // (A scene the editor saves goes through scene-edit.ts replaceChecked, which also checks the file is // still the version that was read; a new file that claims its name is an exclusive create instead.) -import { chmod, mkdir, rename, rm, writeFile } from "node:fs/promises"; +import { chmod, mkdir, rm, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; +import { renameOver } from "./fsx"; import { plainFolder } from "./library/contain"; /** @@ -22,7 +23,7 @@ export async function writeAtomic(file: string, data: string | Uint8Array, { mod try { await writeFile(tmp, data, { mode }); if (mode !== undefined) await chmod(tmp, mode); // past the umask - await rename(tmp, file); + await renameOver(tmp, file); } catch (e) { await rm(tmp, { force: true }).catch(() => {}); throw e; diff --git a/apps/server/src/config.test.ts b/apps/server/src/config.test.ts index 1da28b4..a4473d9 100644 --- a/apps/server/src/config.test.ts +++ b/apps/server/src/config.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { join, resolve } from "node:path"; +import { basename, dirname, join, resolve } from "node:path"; /** config.ts read in a fresh process with `env`, so each case sees its own environment. */ function configWith(env: Record, { state = "/tmp/vs-config-test-state" }: { state?: string | null } = {}) { @@ -21,9 +21,9 @@ describe("config paths", () => { }); test("follow the env overrides the Mac app passes", () => { const c = configWith({ VIEWSWITCHER_STARTER: "/app/Resources/starter", VIEWSWITCHER_WEB_DIST: "/app/Resources/web", VIEWSWITCHER_LIBRARY_KIT: "/app/Resources/library-kit", PORT: "7433" }); - expect(c.starter).toBe("/app/Resources/starter"); - expect(c.webDist).toBe("/app/Resources/web"); - expect(c.libraryKit).toBe("/app/Resources/library-kit"); + expect(c.starter).toBe(resolve("/app/Resources/starter")); + expect(c.webDist).toBe(resolve("/app/Resources/web")); + expect(c.libraryKit).toBe(resolve("/app/Resources/library-kit")); expect(c.port).toBe(7433); }); }); @@ -31,7 +31,8 @@ describe("config paths", () => { describe("this Mac's state for the library (machineState)", () => { test("lives under VIEWSWITCHER_STATE, one folder per library, never in the library", () => { const c = configWith({ VIEWSWITCHER_LIBRARY: "/nowhere/My Library" }); - expect(c.machineState).toMatch(/^\/tmp\/vs-config-test-state\/libraries\/[0-9a-f]{16}$/); + expect(dirname(c.machineState)).toBe(join(resolve("/tmp/vs-config-test-state"), "libraries")); + expect(basename(c.machineState)).toMatch(/^[0-9a-f]{16}$/); expect(c.machineState.startsWith(c.library)).toBe(false); }); test("a server a test starts without VIEWSWITCHER_STATE refuses, rather than touch this Mac's real state", () => { diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index dfb0a50..f1c7e40 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -2,14 +2,14 @@ import { readFileSync } from "node:fs"; import { homedir } from "node:os"; import { machineStateDir } from "./machine-state"; import { join, resolve } from "node:path"; +import { obsWebsocketConfig, stateRoot } from "./platform-dirs"; const env = process.env; -/** On this Mac, read the obs-websocket password from OBS's own settings when OBS_PASSWORD isn't set. */ +/** On this computer, read the obs-websocket password from OBS's own settings when OBS_PASSWORD isn't set. */ function localObsPassword(): string | undefined { try { - const file = join(homedir(), "Library/Application Support/obs-studio/plugin_config/obs-websocket/config.json"); - const c = JSON.parse(readFileSync(file, "utf8")); + const c = JSON.parse(readFileSync(obsWebsocketConfig(), "utf8")); return c.auth_required && c.server_password ? c.server_password : undefined; } catch { return undefined; @@ -29,7 +29,7 @@ export const config = { // A server a test starts (NODE_ENV=test, which bun test sets and children inherit) must name its // own state root: it may never fall back to this Mac's real pairings and setting. if (!env.VIEWSWITCHER_STATE && env.NODE_ENV === "test") throw new Error("VIEWSWITCHER_STATE must be set under bun test (test-server.ts TEST_STATE_ROOT), so a test never touches this Mac's real state"); - return machineStateDir(env.VIEWSWITCHER_STATE ?? join(homedir(), "Library/Application Support/ViewSwitcher"), this.library); + return machineStateDir(env.VIEWSWITCHER_STATE ?? stateRoot(), this.library); }, // The next three default to the repo; the Mac app's compiled server (where import.meta.dir is // inside the binary) passes the copies in its Resources folder. diff --git a/apps/server/src/fsx.ts b/apps/server/src/fsx.ts new file mode 100644 index 0000000..c6a2573 --- /dev/null +++ b/apps/server/src/fsx.ts @@ -0,0 +1,52 @@ +// Renames that behave the same on macOS and Windows. +// +// - claimRename: move a staged folder to a name nobody has, atomically, failing with EEXIST when the name +// is taken. POSIX rename replaces an empty folder quietly, so there the name is claimed first with a +// plain mkdir and the staged folder renamed onto it. Windows never replaces a folder on rename (it +// refuses with EPERM even when the target is empty), so there the rename alone is the claim. +// - renameOver: replace a file with a finished copy. Windows refuses (EPERM, EBUSY, EACCES) while another +// handle has the target open without delete sharing, a reader or the file watcher for an instant, so +// there it is tried again for a short while. +import { lstat, mkdir, rename, rmdir } from "node:fs/promises"; + +export const WINDOWS = process.platform === "win32"; + +const busy = (e: unknown) => ["EPERM", "EBUSY", "EACCES"].includes((e as NodeJS.ErrnoException).code ?? ""); + +function exists(): NodeJS.ErrnoException { + const e = new Error("EEXIST: file already exists") as NodeJS.ErrnoException; + e.code = "EEXIST"; + return e; +} + +/** Move the folder `from` to `to`, which must not exist yet: EEXIST when it does (or appears meanwhile). */ +export async function claimRename(from: string, to: string, win = WINDOWS): Promise { + if (win) { + try { + await rename(from, to); + } catch (e) { + // Anything already at `to` (a folder, a file, a link) makes the rename fail: it was taken. + if (await lstat(to).then(() => true, () => false)) throw exists(); + throw e; + } + return; + } + await mkdir(to); // EEXIST when taken + await rename(from, to).catch(async (e) => { + await rmdir(to).catch(() => {}); // only if still empty: never someone else's files + throw e; + }); +} + +/** rename(from, to), replacing `to`, tried again on Windows while something briefly holds `to` open. */ +export async function renameOver(from: string, to: string, { win = WINDOWS, forMs = 2000 } = {}): Promise { + const until = Date.now() + forMs; + for (let wait = 10; ; wait = Math.min(wait * 2, 200)) { + try { + return await rename(from, to); + } catch (e) { + if (!win || !busy(e) || Date.now() > until) throw e; + await Bun.sleep(wait); + } + } +} diff --git a/apps/server/src/http-guard.test.ts b/apps/server/src/http-guard.test.ts index f586d77..581b78b 100644 --- a/apps/server/src/http-guard.test.ts +++ b/apps/server/src/http-guard.test.ts @@ -9,6 +9,7 @@ import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { starterPack, zipPack } from "@viewswitcher/packs"; import { SERVER_START_MS, TEST_STATE_ROOT, freePort, startServer } from "./test-server"; +import { fileLinks } from "../../../test-links"; let port = 0; let proc: Subprocess; @@ -202,7 +203,7 @@ describe("framing: nobody but the switcher's own pages can frame it", () => { }); describe("library paths obey the real-path rule, for reads as for writes", () => { - test("a link out of the library, plain or ?edit or ?bridge, is a 404; a link inside it works", async () => { + test.skipIf(!fileLinks)("a link out of the library, plain or ?edit or ?bridge, is a 404; a link inside it works", async () => { writeFileSync(join(outside, "secret.html"), "Outsidesecret"); symlinkSync(join(outside, "secret.html"), join(library, "my-channel/templates/away.html")); symlinkSync(outside, join(library, "my-channel/assets-away")); diff --git a/apps/server/src/http/dispatch.test.ts b/apps/server/src/http/dispatch.test.ts index 43a3cba..2fc00a1 100644 --- a/apps/server/src/http/dispatch.test.ts +++ b/apps/server/src/http/dispatch.test.ts @@ -3,6 +3,7 @@ import { describe, expect, test } from "bun:test"; import type { Server } from "bun"; import { type DispatchOptions, dispatcher, HttpError, type Route, type SocketData } from "./dispatch"; +import { COMPUTER } from "../platform-dirs"; const LIBRARY = "/Users/someone/ViewSwitcher Library"; const MAC = { address: "127.0.0.1", port: 50000 }; @@ -128,7 +129,7 @@ describe("the response wrapper", () => { for (const [req, peer] of [[local("/boom"), USB], [fromPhone("/boom"), PHONE]] as const) { const r = (await d(req, srv(peer)))!; expect(r.status).toBe(500); - expect(((await r.json()) as { error: string }).error).toBe("Something went wrong on the Mac. Its server log has the details."); + expect(((await r.json()) as { error: string }).error).toBe(`Something went wrong on the ${COMPUTER}. Its server log has the details.`); } }); test("a refusal from a handler keeps its status, scrubbed, for anyone", async () => { diff --git a/apps/server/src/http/dispatch.ts b/apps/server/src/http/dispatch.ts index edc168a..a353f8f 100644 --- a/apps/server/src/http/dispatch.ts +++ b/apps/server/src/http/dispatch.ts @@ -19,6 +19,7 @@ // /library/ keeps its own headers (scene-sandbox.ts), with no frame-ancestors: a scene has nothing // to click, framing one gives a page nothing it can read, and a sandboxed document's 'self' is an // opaque origin in some engines, which would blank every scene tile in the switcher. +import { COMPUTER } from "../platform-dirs"; import { EditError } from "@viewswitcher/shared"; import type { Server } from "bun"; import { admits, type Audience, type Caller, callerOf, isMacOrUsb, pageLoad, type Peer } from "../gate"; @@ -124,9 +125,9 @@ function secured(res: Response, path: string): Response { }); } -const REMOTE_OFF = "This Mac isn't letting phones and tablets connect right now. On the Mac, turn on Phones and Tablets in ViewSwitcher."; -const PAIR_FIRST = "Pair this phone or tablet first: open ViewSwitcher on the Mac, then Phones and Tablets."; -const PLAIN_500 = "Something went wrong on the Mac. Its server log has the details."; +const REMOTE_OFF = `This ${COMPUTER} isn't letting phones and tablets connect right now. On the ${COMPUTER}, turn on Phones and Tablets in ViewSwitcher.`; +const PAIR_FIRST = `Pair this phone or tablet first: open ViewSwitcher on the ${COMPUTER}, then Phones and Tablets.`; +const PLAIN_500 = `Something went wrong on the ${COMPUTER}. Its server log has the details.`; export function dispatcher(o: DispatchOptions): (req: Request, srv: Server) => Promise { /** An error as a response: the message scrubbed, and a 500's only for this Mac. */ diff --git a/apps/server/src/http/routes/agent.ts b/apps/server/src/http/routes/agent.ts index 7ae71e1..af228b0 100644 --- a/apps/server/src/http/routes/agent.ts +++ b/apps/server/src/http/routes/agent.ts @@ -27,7 +27,7 @@ export function agentRoutes(d: RouteDeps): Route[] { // Which agent apps this Mac has, so Edit with AI lists them first. Booleans only. method: "GET", path: "/api/agent/clients", - handler: () => json(detectClients({ home: homedir(), path: process.env.PATH ?? "", exists: existsSync })), + handler: () => json(detectClients({ home: homedir(), path: process.env.PATH ?? "", exists: existsSync, localAppData: process.env.LOCALAPPDATA, programFiles: process.env.ProgramFiles, appData: process.env.APPDATA })), }, { // Add to Claude Desktop: an extension made for this install, whose command is this server's own executable. diff --git a/apps/server/src/http/routes/library.ts b/apps/server/src/http/routes/library.ts index 5b8270c..c92a6fb 100644 --- a/apps/server/src/http/routes/library.ts +++ b/apps/server/src/http/routes/library.ts @@ -3,6 +3,7 @@ import * as lib from "../../library"; import { customizeScene, duplicateScene, orgDir, sceneFromTemplate } from "../../library-actions"; import { resolveInLibrary } from "../../library/contain"; +import { editorCommand } from "../../open-file"; import { plainName } from "../../paths"; import { editScene, parseEdit, renameScene, scenePath } from "../../scene-edit"; import { Audience } from "../../gate"; @@ -54,8 +55,7 @@ export function libraryRoutes(d: RouteDeps): Route[] { post("/api/open", async (b) => { // Opens the file in an editor on this Mac: a link to somewhere outside the library opens nothing. const abs = await resolveInLibrary(root, b.path); - const app = process.env.VIEWSWITCHER_EDITOR; - Bun.spawn(app ? ["open", "-a", app, abs] : ["open", "-t", abs], { stdout: "ignore", stderr: "ignore" }); + Bun.spawn(editorCommand(abs), { stdout: "ignore", stderr: "ignore" }); return { ok: true }; }), // Scene editor: patch the file (409 when it changed since the editor loaded it), or show a change diff --git a/apps/server/src/lan-listen.test.ts b/apps/server/src/lan-listen.test.ts new file mode 100644 index 0000000..2d4eab8 --- /dev/null +++ b/apps/server/src/lan-listen.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, test } from "bun:test"; +import { lanListeners } from "./lan-listen"; + +/** A pretend Bun server per hostname, recording what was published to it and whether it was stopped. */ +function fakes(fail: string[] = []) { + const made: { hostname: string; stopped: boolean; published: string[]; stop: () => void; publish: (t: string, m: string) => void }[] = []; + const serve = (hostname: string) => { + if (fail.includes(hostname)) throw new Error(`Failed to start server. Is port 7420 in use?`); + const s = { hostname, stopped: false, published: [] as string[], stop() { s.stopped = true; }, publish(_t: string, m: string) { s.published.push(m); } }; + made.push(s); + return s as any; + }; + return { made, serve }; +} + +describe("the Wi-Fi listener", () => { + test("macOS: one listener on every address", () => { + const f = fakes(); + const lan = lanListeners({ host: "0.0.0.0", addresses: () => ["192.168.1.5"], serve: f.serve, perAddress: false, log: () => {} }); + expect(lan.start()).toBeNull(); + expect(f.made.map((s) => s.hostname)).toEqual(["0.0.0.0"]); + expect(lan.on).toBe(true); + expect(lan.has(f.made[0])).toBe(true); + expect(lan.has({})).toBe(false); + lan.stop(); + expect(f.made[0]!.stopped).toBe(true); + expect(lan.on).toBe(false); + }); + + test("Windows: one on each address, published to all, following the addresses as they change", async () => { + const f = fakes(); + let addresses = ["192.168.4.32", "100.65.202.51"]; + const lan = lanListeners({ host: "0.0.0.0", addresses: () => addresses, serve: f.serve, perAddress: true, everyMs: 20, log: () => {} }); + expect(lan.start()).toBeNull(); + expect(f.made.map((s) => s.hostname)).toEqual(["192.168.4.32", "100.65.202.51"]); + lan.publish("all", "hello"); + expect(f.made.every((s) => s.published.includes("hello"))).toBe(true); + // A new Wi-Fi network: its address is listened on, the old one closed. + addresses = ["10.0.0.9", "100.65.202.51"]; + await Bun.sleep(80); + expect(f.made.find((s) => s.hostname === "192.168.4.32")!.stopped).toBe(true); + expect(lan.servers.map((s) => (s as any).hostname).sort()).toEqual(["10.0.0.9", "100.65.202.51"]); + lan.stop(); + expect(f.made.every((s) => s.stopped)).toBe(true); + // Stopped: no more following. + addresses = ["172.16.0.2"]; + await Bun.sleep(60); + expect(f.made.some((s) => s.hostname === "172.16.0.2")).toBe(false); + }); + + test("an address that can't be listened on is skipped; none at all says why", () => { + const some = fakes(["100.65.202.51"]); + const lan = lanListeners({ host: "0.0.0.0", addresses: () => ["192.168.4.32", "100.65.202.51"], serve: some.serve, perAddress: true, log: () => {} }); + expect(lan.start()).toBeNull(); + expect(lan.servers.length).toBe(1); + lan.stop(); + const none = fakes(["0.0.0.0"]); + const off = lanListeners({ host: "0.0.0.0", addresses: () => [], serve: none.serve, perAddress: false, log: () => {} }); + expect(off.start()).toContain("Is port 7420 in use?"); + expect(off.on).toBe(false); + const noWifi = lanListeners({ host: "0.0.0.0", addresses: () => [], serve: fakes().serve, perAddress: true, log: () => {} }); + expect(noWifi.start()).toContain("no network address"); + }); + + test("a set address (VIEWSWITCHER_LAN_HOST, the tests') is used as it is, on every platform", () => { + const f = fakes(); + const lan = lanListeners({ host: "192.168.4.32", addresses: () => ["10.0.0.1"], serve: f.serve, perAddress: true, log: () => {} }); + lan.start(); + expect(f.made.map((s) => s.hostname)).toEqual(["192.168.4.32"]); + lan.stop(); + }); +}); diff --git a/apps/server/src/lan-listen.ts b/apps/server/src/lan-listen.ts new file mode 100644 index 0000000..6819cb1 --- /dev/null +++ b/apps/server/src/lan-listen.ts @@ -0,0 +1,89 @@ +// The Wi-Fi listener(s): how phones and tablets reach the server while Wi-Fi access is on. +// +// On macOS one listener on every address (0.0.0.0) sits beside the loopback one on the same port. Windows +// refuses that bind (the port is taken by 127.0.0.1's), but lets a listener on each of this PC's own +// addresses share it. So there, it listens on each address, and follows them: a new Wi-Fi network (a new +// address) is listened on within a few seconds, and one that went away is closed. +import type { Server } from "bun"; + +export type LanListeners> = { + /** Listening, or an error saying why not (nothing could be bound). */ + start(): string | null; + stop(): void; + readonly on: boolean; + /** Whether a request came in through one of these listeners. */ + has(server: unknown): boolean; + publish(topic: string, text: string): void; + /** The listeners, for the sockets' sake (one per address on Windows). */ + readonly servers: S[]; +}; + +export function lanListeners>(o: { + host: string; + /** This computer's addresses (lan.ts thisMac), for a listener on each where 0.0.0.0 can't be shared. */ + addresses: () => string[]; + serve: (hostname: string) => S; + /** Windows' rule: one listener per address (default: process.platform). */ + perAddress?: boolean; + everyMs?: number; + log?: (message: string) => void; +}): LanListeners { + const perAddress = (o.perAddress ?? process.platform === "win32") && o.host === "0.0.0.0"; + const servers = new Map(); + let on = false; + let timer: ReturnType | undefined; + const log = o.log ?? ((m: string) => console.log(m)); + + /** Listen on what should be listened on now; the first error when nothing could be. */ + function sync(): string | null { + const want = new Set(perAddress ? o.addresses() : [o.host]); + let error: string | null = null; + for (const [host, s] of servers) { + if (want.has(host)) continue; + s.stop(true); + servers.delete(host); + log(`[wifi] ${host} went away; stopped listening there`); + } + for (const host of want) { + if (servers.has(host)) continue; + try { + servers.set(host, o.serve(host)); + if (perAddress) log(`[wifi] listening on ${host}`); + } catch (e) { + error ??= (e as Error).message; + log(`[wifi] couldn't listen on ${host}: ${(e as Error).message}`); + } + } + return servers.size === 0 ? (error ?? "no network address to listen on (is the Wi-Fi connected?)") : null; + } + + return { + start() { + if (on) return null; + const error = sync(); + if (error && servers.size === 0) return error; + on = true; + if (perAddress) { + timer = setInterval(sync, o.everyMs ?? 5000); + timer.unref?.(); + } + return null; + }, + stop() { + on = false; + clearInterval(timer); + for (const s of servers.values()) s.stop(true); + servers.clear(); + }, + get on() { + return on; + }, + has: (server) => [...servers.values()].some((s) => s === server), + publish(topic, text) { + for (const s of servers.values()) s.publish(topic, text); + }, + get servers() { + return [...servers.values()]; + }, + }; +} diff --git a/apps/server/src/lan.test.ts b/apps/server/src/lan.test.ts index e1e8d4f..d58e428 100644 --- a/apps/server/src/lan.test.ts +++ b/apps/server/src/lan.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { lanAddresses, pairingOrder, vpnAddresses } from "./lan"; +import { lanAddresses, localNameFrom, pairingOrder, vpn, vpnAddresses } from "./lan"; test("LAN addresses: IPv4, not loopback or link-local", () => { const i = (address: string, family = "IPv4", internal = false) => ({ address, family, internal, netmask: "", mac: "", cidr: null }) as any; @@ -24,3 +24,19 @@ test("VPN addresses come from utun, ipsec and ppp interfaces", () => { const i = (address: string) => ({ address, family: "IPv4", internal: false, netmask: "", mac: "", cidr: null }) as any; expect(vpnAddresses({ en0: [i("192.168.1.68")], utun4: [i("100.101.1.2")], ipsec0: [i("10.8.0.2")], ppp0: [i("10.9.0.1")] })).toEqual(["100.101.1.2", "10.8.0.2", "10.9.0.1"]); }); + +test("Windows adapters by name: Tailscale and the virtual switches of WSL and VMs never come first", () => { + const i = (address: string) => ({ address, family: "IPv4", internal: false, netmask: "", mac: "", cidr: null }) as any; + // As this PC lists them: Tailscale first, then Wi-Fi. + const ifaces = { Tailscale: [i("100.65.202.51")], "vEthernet (WSL (Hyper-V firewall))": [i("172.24.16.1")], "Wi-Fi": [i("192.168.4.32")], "Ethernet 2": [i("10.0.0.7")] }; + expect(lanAddresses(ifaces)).toEqual(["192.168.4.32", "10.0.0.7", "100.65.202.51", "172.24.16.1"]); + expect(vpnAddresses(ifaces)).toEqual(["100.65.202.51", "172.24.16.1"]); + expect(pairingOrder(lanAddresses(ifaces), vpnAddresses(ifaces))[0]).toBe("192.168.4.32"); + for (const name of ["Tailscale", "ZeroTier One [abc]", "WireGuard Tunnel", "OpenVPN TAP-Windows6", "vEthernet (Default Switch)", "VMware Network Adapter VMnet8", "VirtualBox Host-Only Network"]) expect(vpn(name)).toBe(true); + for (const name of ["Wi-Fi", "Ethernet", "Ethernet 2", "en0"]) expect(vpn(name)).toBe(false); +}); + +test("a .local name from the computer's own name, when it can be one", () => { + expect(localNameFrom("DESKTOP-OPRO3MQ")).toBe("desktop-opro3mq.local"); + expect(localNameFrom("Sam's PC")).toBeNull(); +}); diff --git a/apps/server/src/lan.ts b/apps/server/src/lan.ts index 03efdbc..840d6f3 100644 --- a/apps/server/src/lan.ts +++ b/apps/server/src/lan.ts @@ -1,10 +1,18 @@ -// This Mac on the local network: its IPv4 addresses and its Bonjour name (.local), for +// This computer on the local network: its IPv4 addresses and its mDNS name (.local), for // the host guard (origin.ts) and the addresses the pairing QR code points at. Both can change while -// the server runs (a new Wi-Fi network, a renamed Mac), so they are read again every few seconds. -import { networkInterfaces } from "node:os"; +// the server runs (a new Wi-Fi network, a renamed computer), so they are read again every few seconds. +import { hostname, networkInterfaces } from "node:os"; -/** A VPN's interface (utun: Tailscale and most VPNs; ipsec, ppp): a phone on the Wi-Fi can't reach it. */ -const vpn = (name: string) => /^(utun|ipsec|ppp)\d*$/.test(name); +/** + * An interface a phone on the Wi-Fi can't reach: a VPN's (utun: Tailscale and most VPNs on macOS; ipsec, + * ppp), and on Windows, where adapters go by name, Tailscale, ZeroTier, WireGuard, OpenVPN and TAP + * adapters, and the virtual switches of WSL, Hyper-V, VMware and VirtualBox. + */ +export const vpn = (name: string) => + /^(utun|ipsec|ppp)\d*$/.test(name) || /^(tailscale|zerotier|wireguard|openvpn|nordlynx|proton|mullvad|tap|tun|vethernet|vmware|virtualbox|vboxnet|hyper-v)\b/i.test(name); + +/** ".local" for a computer name that can be one (letters, digits and hyphens), else null. */ +export const localNameFrom = (name: string) => (/^[A-Za-z0-9-]{1,63}$/.test(name) ? `${name}.local`.toLowerCase() : null); /** IPv4 addresses on this Mac's network interfaces, apart from loopback and link-local (169.254/16). * VPN interfaces come last, so the pairing QR code never prefers a Tailscale 100.x address over a Wi-Fi @@ -41,6 +49,8 @@ export function pairingOrder(addresses: string[], vpns: string[]): string[] { function readLocalName(): string | null { const forced = process.env.VIEWSWITCHER_LOCAL_NAME; if (forced !== undefined) return forced ? `${forced.replace(/\.local$/i, "")}.local`.toLowerCase() : null; + // Windows 10 and later answer mDNS for their own computer name. + if (process.platform === "win32") return localNameFrom(hostname()); if (process.platform !== "darwin") return null; try { const p = Bun.spawnSync(["/usr/sbin/scutil", "--get", "LocalHostName"], { stdout: "pipe", stderr: "ignore" }); diff --git a/apps/server/src/library-kit.test.ts b/apps/server/src/library-kit.test.ts index 90dd850..5c45007 100644 --- a/apps/server/src/library-kit.test.ts +++ b/apps/server/src/library-kit.test.ts @@ -3,6 +3,7 @@ import { lstat, mkdtemp, mkdir, readdir, readFile, rm, stat, symlink, writeFile import { tmpdir } from "node:os"; import { join } from "node:path"; import { ensureLibrary, findGit, FIRST_ORG, KIT_FILES } from "./library-kit"; +import { fileLinks, posix } from "../../../test-links"; const kit = join(import.meta.dir, "../library-kit"); const starter = join(import.meta.dir, "../starter"); @@ -49,7 +50,7 @@ describe("ensureLibrary", () => { expect(await readFile(join(root, ".gitignore"), "utf8")).toContain(".viewswitcher/"); }); - test("a kit file that's there but can't be read (a folder, a named pipe) is the person's: left alone, and the start settles", async () => { + test.skipIf(!posix)("a kit file that's there but can't be read (a folder, a named pipe) is the person's: left alone, and the start settles", async () => { const root = await tempDir(); await mkdir(join(root, "CLAUDE.md")); expect(Bun.spawnSync(["mkfifo", join(root, "AGENTS.md")]).exitCode).toBe(0); @@ -105,7 +106,7 @@ describe("ensureLibrary", () => { expect(r.git).toBe(false); }); - test("a kit file someone made a link stays a link, even when the kit has a newer version", async () => { + test.skipIf(!fileLinks)("a kit file someone made a link stays a link, even when the kit has a newer version", async () => { const root = await tempDir(); const oldKit = await tempDir(); for (const { from } of KIT_FILES) { diff --git a/apps/server/src/library-links.test.ts b/apps/server/src/library-links.test.ts index 5d53b72..288ca70 100644 --- a/apps/server/src/library-links.test.ts +++ b/apps/server/src/library-links.test.ts @@ -6,6 +6,7 @@ import { mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync import { tmpdir } from "node:os"; import { join } from "node:path"; import * as lib from "./library"; +import { fileLinks } from "../../../test-links"; const library = mkdtempSync(join(tmpdir(), "vs-links-")); const outside = mkdtempSync(join(tmpdir(), "vs-links-out-")); @@ -38,7 +39,7 @@ describe("library changes through a folder linked outside", () => { await expect(lib.createProject(o, "Show", [])).rejects.toThrow(OUTSIDE); empty(d); }); - test("New project from a template that links outside: refused", async () => { + test.skipIf(!fileLinks)("New project from a template that links outside: refused", async () => { put(join(outside, "tpl.html"), "Outside"); symlinkSync(join(outside, "tpl.html"), join(org, "templates/linked.html")); await expect(lib.createProject(org, "From linked", ["linked"])).rejects.toThrow(OUTSIDE); @@ -86,7 +87,7 @@ describe("library changes through a folder linked outside", () => { }); describe("deletions through a folder linked outside", () => { - test("Revert (a stream's own copy) and Revert transition never delete outside the library", async () => { + test.skipIf(!fileLinks)("Revert (a stream's own copy) and Revert transition never delete outside the library", async () => { const { projectId } = await lib.createProject(org, "Del", ["brb"]); const { streamId } = await lib.createStream(org, projectId, "Del", "2026-12-08"); // The stream's folder links outside, where a file has the copy's name. @@ -106,7 +107,7 @@ describe("deletions through a folder linked outside", () => { }); describe("links that stay in the library still work", () => { - test("assets/ linked to another org's assets, and a template linked to another template", async () => { + test.skipIf(!fileLinks)("assets/ linked to another org's assets, and a template linked to another template", async () => { const o = join(library, "o3"); put(join(o, "org.json"), "{}"); put(join(o, "templates/brb.html")); diff --git a/apps/server/src/library-pipes.test.ts b/apps/server/src/library-pipes.test.ts index e338f8d..2b4bce2 100644 --- a/apps/server/src/library-pipes.test.ts +++ b/apps/server/src/library-pipes.test.ts @@ -13,9 +13,10 @@ import { readGuide } from "./mcp/server"; import { PathError } from "./paths"; import { readText, writeText } from "./library-files"; import { loadedFiles } from "./scene-refs"; +import { posix } from "../../../test-links"; const root = mkdtempSync(join(tmpdir(), "vs-pipes-")); -const realRoot = realpathSync(root); +const realRoot = realpathSync.native(root); const away = mkdtempSync(join(tmpdir(), "vs-pipes-away-")); afterAll(() => { rmSync(root, { recursive: true, force: true }); @@ -26,6 +27,7 @@ const fifo = (rel: string) => expect(Bun.spawnSync(["mkfifo", join(root, rel)]). const settled = (p: Promise) => Promise.race([p.then((v) => ({ v }), (e: Error) => ({ e: e.message })), Bun.sleep(3000).then(() => "hung" as const)]); beforeAll(async () => { + if (!posix) return; // no named pipes on Windows await mkdir(join(root, "daisy/templates/_shared"), { recursive: true }); await writeFile(join(root, "daisy/org.json"), JSON.stringify({ name: "Daisy" })); await writeFile(join(root, "daisy/templates/brb.html"), `BRB`); @@ -35,7 +37,7 @@ beforeAll(async () => { await symlink(join(away, "secret.html"), join(root, "daisy/templates/linked.html")); }); -describe("a named pipe in the library", () => { +describe.skipIf(!posix)("a named pipe in the library", () => { test("read_file refuses it", async () => { const r = await settled(readText(root, "daisy/templates/pipe.html", 7420)); expect(r).not.toBe("hung"); @@ -113,12 +115,12 @@ describe("a named pipe in the library", () => { }); }); -test("duplicating a view that is a link outside the library is refused, and nothing is copied in", async () => { +test.skipIf(!posix)("duplicating a view that is a link outside the library is refused, and nothing is copied in", async () => { await expect(duplicate(root, "daisy/templates/linked.html")).rejects.toThrow("outside the library"); expect((await readdir(join(root, "daisy/templates"))).filter((f) => f.includes("copy"))).toEqual([]); }); -test("a stream's copy of a view keeps the view's permissions, through the umask as cp gives them", async () => { +test.skipIf(!posix)("a stream's copy of a view keeps the view's permissions, through the umask as cp gives them", async () => { await mkdir(join(root, "daisy/projects/q/scenes"), { recursive: true }); await mkdir(join(root, "daisy/projects/q/streams/s"), { recursive: true }); // A mode the umask changes (0o666): the copy has it through the umask, as cp gives it, never looser. diff --git a/apps/server/src/library-scan.test.ts b/apps/server/src/library-scan.test.ts index 8f12dba..eec3168 100644 --- a/apps/server/src/library-scan.test.ts +++ b/apps/server/src/library-scan.test.ts @@ -9,6 +9,7 @@ import { titledCopy } from "./library"; import { readNoFollow } from "./library/contain"; import { LibraryScanner, noLinkFiles } from "./library/scanner"; import { createSceneTitles } from "./scene-titles"; +import { fileLinks, posix } from "../../../test-links"; /** * One scanner per test, as the server has one: its title cache carries from scan to scan. It keeps @@ -186,7 +187,7 @@ describe("links out of the library are never read", () => { }); const everything = async () => JSON.stringify(await scanner.scanOrg(ORG)); - test("a view that is a link to a file outside is left out, and its title isn't read", async () => { + test.skipIf(!fileLinks)("a view that is a link to a file outside is left out, and its title isn't read", async () => { await symlink(join(away, "secret.html"), join(root, ORG, "projects/p/scenes/leak.html")); await symlink(join(away, "secret.html"), join(root, ORG, "templates/leak.html")); const l = await scanner.scanOrg(ORG); @@ -195,12 +196,12 @@ describe("links out of the library are never read", () => { expect(await everything()).not.toContain("Outside"); }); - test("a view that is a link to another view in the library is listed with its title", async () => { + test.skipIf(!fileLinks)("a view that is a link to another view in the library is listed with its title", async () => { await symlink(join(root, ORG, "templates/title.html"), join(root, ORG, "projects/p/scenes/again.html")); expect(await labels()).toContain("p/scenes/again.html=Title"); }); - test("folders, JSON files and pictures linked outside are left out too", async () => { + test.skipIf(!fileLinks)("folders, JSON files and pictures linked outside are left out too", async () => { await symlink(join(away, "folder"), join(root, ORG, "projects/p/streams/a-linked")); await rm(join(root, ORG, "projects/p/scenes"), { recursive: true }); await symlink(join(away, "folder"), join(root, ORG, "projects/p/scenes")); @@ -221,7 +222,7 @@ describe("links out of the library are never read", () => { expect(await everything()).not.toContain("Outside"); }); - test("a title is read only through a path with no link in it: a folder swapped for a link after the check reads as no title", async () => { + test.skipIf(!fileLinks)("a title is read only through a path with no link in it: a folder swapped for a link after the check reads as no title", async () => { await mkdir(join(away, "real"), { recursive: true }); await writeFile(join(away, "real/x.html"), view("Outside")); await symlink(join(away, "real"), join(away, "swapped")); @@ -244,7 +245,7 @@ describe("links out of the library are never read", () => { expect(await titles.titleOf(file)).toBe(""); }); - test("a named pipe named like a view can't hang the scan: it lists with no title", async () => { + test.skipIf(!posix)("a named pipe named like a view can't hang the scan: it lists with no title", async () => { const fifo = join(root, ORG, "projects/p/scenes/pipe.html"); expect(Bun.spawnSync(["mkfifo", fifo]).exitCode).toBe(0); const l = await Promise.race([scanner.scanOrg(ORG), Bun.sleep(3000).then(() => null)]); @@ -252,7 +253,7 @@ describe("links out of the library are never read", () => { expect(l!.projects[0]!.scenes.find((s) => s.name === "pipe")?.label).toBe("pipe"); }); - test("a named pipe where a JSON file goes (project.json) can't hang the scan: it reads as missing", async () => { + test.skipIf(!posix)("a named pipe where a JSON file goes (project.json) can't hang the scan: it reads as missing", async () => { await rm(join(root, ORG, "projects/p/project.json")); expect(Bun.spawnSync(["mkfifo", join(root, ORG, "projects/p/project.json")]).exitCode).toBe(0); const l = await Promise.race([scanner.scanOrg(ORG), Bun.sleep(3000).then(() => null)]); diff --git a/apps/server/src/library.ts b/apps/server/src/library.ts index 35f03e9..16ac029 100644 --- a/apps/server/src/library.ts +++ b/apps/server/src/library.ts @@ -1,10 +1,11 @@ import { randomBytes } from "node:crypto"; import { chmod, cp, lstat, mkdir, readdir, readFile, rename, rm, rmdir, stat, writeFile } from "node:fs/promises"; -import { dirname, extname, join, relative } from "node:path"; +import { basename, dirname, extname, join, relative, sep } from "node:path"; import { fillPlaceholders, graphemes, isTextFile, ORG_TRANSITION, parseTemplateId, placeholderVars, readTitle, setTitle, slugify, TRANSITION_FILE as TRANSITION, transitionCandidates } from "@viewswitcher/shared"; import type { Org } from "@viewswitcher/shared"; import { walkFiles } from "@viewswitcher/packs"; import { writeAtomic } from "./atomic"; +import { claimRename } from "./fsx"; import { libraryStaging, readNoFollow, resolveInLibrary, withNoLinks } from "./library/contain"; import { dirs, readJson } from "./library/read"; import { inside, PathError, plainName } from "./paths"; @@ -52,18 +53,13 @@ export async function createOrg(libraryRoot: string, starter: string, name: stri // The org id goes into its files ({{ORG_ID}}), so an id taken meanwhile is filled again for the next. await rm(work, { recursive: true, force: true }); await fillStarter(starter, work, placeholderVars({ id, name, accent, ground })); - // Claim the name first: mkdir without recursive fails if the folder appeared meanwhile (two - // creates at once, an agent), where rename alone would quietly replace an empty one. + // Claimed atomically (fsx.ts): a folder that appeared meanwhile (two creates at once, an agent) takes the next name. try { - await mkdir(dir); + await claimRename(work, dir); } catch (e) { if ((e as NodeJS.ErrnoException).code === "EEXIST") continue; throw e; } - await rename(work, dir).catch(async (e) => { - await rmdir(dir).catch(() => {}); // only if still empty: never someone else's files - throw e; - }); return { orgId: id }; } } finally { @@ -155,7 +151,7 @@ export async function isFile(path: string) { * write follows; the library is the org folder's parent). Links that stay in the library are fine. * Every change here that makes a file or folder calls this for where it writes and what it reads. */ -const contained = (orgDir: string, abs: string) => resolveInLibrary(dirname(orgDir), relative(dirname(orgDir), abs), { forWrite: true }); +const contained = (orgDir: string, abs: string) => resolveInLibrary(dirname(orgDir), relative(dirname(orgDir), abs).split(sep).join("/"), { forWrite: true }); /** * Copy `real` (a real path, as contained() gives) to a new file only: read through the no-link open (so a @@ -285,8 +281,8 @@ export async function revert(orgDir: string, projectId: string, streamId: string export async function duplicate(libraryRoot: string, path: string, check?: BeforeCreate) { if (!path.endsWith(".html")) throw new PathError("Only views can be duplicated"); const src = inside(libraryRoot, path); - const dir = src.slice(0, src.lastIndexOf("/")); - const base = src.slice(dir.length + 1, -5); + const dir = dirname(src); + const base = basename(src, ".html"); // What it copies must really be in the library: a view that is a link outside isn't read (contain.ts). const html = await readNoFollow(await resolveInLibrary(libraryRoot, path)); return { name: await writeFresh(dir, `${base}-copy`, ".html", titledCopy(html), check) }; diff --git a/apps/server/src/library/contain.test.ts b/apps/server/src/library/contain.test.ts index 46620b1..3dee255 100644 --- a/apps/server/src/library/contain.test.ts +++ b/apps/server/src/library/contain.test.ts @@ -4,6 +4,7 @@ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, import { tmpdir } from "node:os"; import { join } from "node:path"; import { plainStateFolder, realLibraryPath, resolveInLibrary } from "./contain"; +import { fileLinks, posix } from "../../../../test-links"; const library = mkdtempSync(join(tmpdir(), "vs-contain-")); const outside = mkdtempSync(join(tmpdir(), "vs-contain-out-")); @@ -15,7 +16,7 @@ const put = (rel: string, text = "x") => { mkdirSync(join(library, rel, ".."), { recursive: true }); writeFileSync(join(library, rel), text); }; -const real = (rel: string) => join(realpathSync(library), rel); +const real = (rel: string) => join(realpathSync.native(library), rel); const TOKEN = "0123456789abcdef01234567"; put("daisy/templates/brb.html"); put("daisy/.git/config"); @@ -24,10 +25,13 @@ put(".viewswitcher/settings.json", "{}"); put(`daisy/.viewswitcher/staging/${TOKEN}/covers/brb.html`); put(`daisy/.viewswitcher/staging/${TOKEN}/meta.json`, "{}"); writeFileSync(join(outside, "secret.txt"), "secret"); -symlinkSync(join(outside, "secret.txt"), join(library, "daisy/templates/away.html")); +// Links to files need symlink rights on Windows (test-links.ts); the tests that use them skip without. +if (fileLinks) { + symlinkSync(join(outside, "secret.txt"), join(library, "daisy/templates/away.html")); + symlinkSync(join(library, "daisy/templates/brb.html"), join(library, "daisy/templates/alias.html")); + symlinkSync(join(library, ".viewswitcher/settings.json"), join(library, "daisy/settings.json")); +} symlinkSync(outside, join(library, "daisy/away")); -symlinkSync(join(library, "daisy/templates/brb.html"), join(library, "daisy/templates/alias.html")); -symlinkSync(join(library, ".viewswitcher/settings.json"), join(library, "daisy/settings.json")); symlinkSync(join(outside, "nothing-yet.html"), join(library, "daisy/templates/dangling.html")); const refused = (p: string, o?: { forWrite?: boolean }) => expect(resolveInLibrary(library, p, o)).rejects.toThrow(); @@ -37,16 +41,16 @@ describe("resolveInLibrary", () => { expect(await resolveInLibrary(library, "daisy/templates/brb.html")).toBe(real("daisy/templates/brb.html")); expect(await resolveInLibrary(library, "daisy/projects/new/scenes/x.html", { forWrite: true })).toBe(real("daisy/projects/new/scenes/x.html")); }); - test("a link that stays in the library is followed", async () => { + test.skipIf(!fileLinks)("a link that stays in the library is followed", async () => { expect(await resolveInLibrary(library, "daisy/templates/alias.html")).toBe(real("daisy/templates/brb.html")); }); - test("a link out of the library, a folder linked out, and a link to nowhere are refused", async () => { + test.skipIf(!fileLinks)("a link out of the library, a folder linked out, and a link to nowhere are refused", async () => { await refused("daisy/templates/away.html"); await refused("daisy/away/secret.txt"); await refused("daisy/away/new.html", { forWrite: true }); await refused("daisy/templates/dangling.html", { forWrite: true }); }); - test("dot-folders and dot-files are refused, also through a link", async () => { + test.skipIf(!fileLinks)("dot-folders and dot-files are refused, also through a link", async () => { for (const p of ["daisy/.git/config", ".viewswitcher/settings.json", "daisy/.env", "daisy/settings.json", ".git", "daisy/templates/../.env", "daisy/./templates/brb.html"]) await refused(p); }); test("bad shapes are refused", async () => { @@ -63,7 +67,7 @@ describe("resolveInLibrary", () => { }); describe("realLibraryPath", () => { - test("where a path really is, as a library path", () => { + test.skipIf(!fileLinks)("where a path really is, as a library path", () => { expect(realLibraryPath(library, "daisy/templates/alias.html")).toBe("daisy/templates/brb.html"); expect(realLibraryPath(library, "daisy/templates/new.html")).toBe("daisy/templates/new.html"); expect(realLibraryPath(library, "daisy/templates/away.html")).toBe("daisy/templates/away.html"); @@ -71,7 +75,7 @@ describe("realLibraryPath", () => { }); describe("a path that can't be read", () => { - test("a file or a folder with no permission is refused as that, not as a link", async () => { + test.skipIf(!posix)("a file or a folder with no permission is refused as that, not as a link", async () => { put("daisy/locked/x.css"); put("daisy/assets/sealed.png"); chmodSync(join(library, "daisy/assets/sealed.png"), 0o000); @@ -122,3 +126,14 @@ describe("plainStateFolder", () => { expect(existsSync(join(root, ".viewswitcher"))).toBe(false); }); }); + +describe("the no-link read (withNoLinks)", () => { + // macOS refuses a link anywhere in the path at the open (O_NOFOLLOW_ANY); Windows has no such open, so + // contain.ts checks the path's real form first. Linux's O_NOFOLLOW checks only the last segment. + test.skipIf(process.platform === "linux")("a file read through a folder that is a link (a junction on Windows) is refused", async () => { + const { readNoFollow } = await import("./contain"); + symlinkSync(join(library, "daisy/templates"), join(library, "daisy/via-folder-link")); + expect(await readNoFollow(real("daisy/templates/brb.html"))).toBe("x"); + await expect(readNoFollow(join(realpathSync.native(library), "daisy/via-folder-link/brb.html"))).rejects.toThrow("outside the library"); + }); +}); diff --git a/apps/server/src/library/contain.ts b/apps/server/src/library/contain.ts index 57e99d3..dc6ca2c 100644 --- a/apps/server/src/library/contain.ts +++ b/apps/server/src/library/contain.ts @@ -10,7 +10,7 @@ // folder that isn't there yet will be made inside. // // Paths still go through inside() and plainName() (paths.ts) first; this adds what the real files say. -import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, realpathSync } from "node:fs"; +import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from "node:fs"; import { type FileHandle, lstat, open, realpath, rename } from "node:fs/promises"; import { basename, dirname, isAbsolute, join, relative, sep } from "node:path"; import { inside, PathError } from "../paths"; @@ -168,14 +168,14 @@ export const plainStateFolder = (libraryRoot: string, now = new Date()) => plain */ export function realLibraryPath(libraryRoot: string, path: string): string { try { - const realRoot = realpathSync(libraryRoot); + const realRoot = realpathSync.native(libraryRoot); let probe = inside(libraryRoot, path); let rest = ""; while (!existsSync(probe)) { rest = `/${basename(probe)}${rest}`; probe = dirname(probe); } - const back = relative(realRoot, realpathSync(probe)) + rest; + const back = relative(realRoot, realpathSync.native(probe)).split(sep).join("/") + rest; return back.startsWith("..") || isAbsolute(back) ? path : back; } catch { return path; @@ -187,7 +187,32 @@ export function realLibraryPath(libraryRoot: string, path: string): string { * folder swapped for a link after the scan checked it gives ELOOP too. Elsewhere, the last segment only. * (Together with O_NOFOLLOW, macOS refuses the open with EINVAL.) */ -export const NO_LINKS = process.platform === "darwin" ? 0x20000000 : constants.O_NOFOLLOW; +export const NO_LINKS = process.platform === "darwin" ? 0x20000000 : (constants.O_NOFOLLOW ?? 0); + +/** + * Windows has no no-follow open at all (O_NOFOLLOW is undefined there), so macOS's rule (no link + * anywhere in the path) is checked before the open: neither `abs` nor any folder above it is a link (a + * symlink or a junction: lstat says so for both). One lstat per folder, not a realpath comparison, + * because Windows spells one folder two ways (C:\PROGRA~1 and C:\Program Files) and neither is a link. + * Throws ELOOP like the open would. The instant between this check and the open is the race the + * Decisions page (2026-11-26, library containment) leaves undefended. + */ +const WINDOWS = process.platform === "win32"; +const loop = () => Object.assign(new Error("ELOOP: a link on the way"), { code: "ELOOP" }); +async function noLinksOnWindows(abs: string) { + if (!WINDOWS) return; + for (let at = abs; ; at = dirname(at)) { + if ((await lstat(at)).isSymbolicLink()) throw loop(); + if (dirname(at) === at) return; + } +} +function noLinksOnWindowsSync(abs: string) { + if (!WINDOWS) return; + for (let at = abs; ; at = dirname(at)) { + if (lstatSync(at).isSymbolicLink()) throw loop(); + if (dirname(at) === at) return; + } +} /** * `use` on the file at `abs`, opened only when no part of `abs` is a link (NO_LINKS) and it's a plain @@ -196,7 +221,7 @@ export const NO_LINKS = process.platform === "darwin" ? 0x20000000 : constants.O * file the switcher reads in full on its own (titles, hashes, the editor's copy, a pack install) uses this. */ export async function withNoLinks(abs: string, use: (f: FileHandle) => Promise): Promise { - const f = await open(abs, constants.O_RDONLY | constants.O_NONBLOCK | NO_LINKS).catch((e) => { + const f = await noLinksOnWindows(abs).then(() => open(abs, constants.O_RDONLY | constants.O_NONBLOCK | NO_LINKS)).catch((e) => { // A path that became a link since it was checked is refused like one that was a link then (a 400, not a 500). throw (e as NodeJS.ErrnoException).code === "ELOOP" ? outside() : e; }); @@ -225,6 +250,7 @@ export async function readPlainText(abs: string): Promise { /** readNoFollow at one instant (the agents' on-air guard checks at a commit): the same open, synchronously. */ export function readNoFollowSync(abs: string): string { + noLinksOnWindowsSync(abs); const fd = openSync(abs, constants.O_RDONLY | constants.O_NONBLOCK | NO_LINKS); try { if (!fstatSync(fd).isFile()) throw new PathError("That isn't a plain file (a folder, a named pipe or a device?)"); diff --git a/apps/server/src/library/scanner.ts b/apps/server/src/library/scanner.ts index d7ff6c2..c3758f9 100644 --- a/apps/server/src/library/scanner.ts +++ b/apps/server/src/library/scanner.ts @@ -86,7 +86,7 @@ export class LibraryScanner { // Titles are kept by real path (readNoFollow), so under the library's real root too when it differs. const real = (() => { try { - return realpathSync(this.libraryRoot); + return realpathSync.native(this.libraryRoot); } catch { return this.libraryRoot; } diff --git a/apps/server/src/machine-state.test.ts b/apps/server/src/machine-state.test.ts index 3e2f71a..53d5b6c 100644 --- a/apps/server/src/machine-state.test.ts +++ b/apps/server/src/machine-state.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { basename, dirname, join, resolve } from "node:path"; import { machineStateDir, migrateMachineState } from "./machine-state"; const scratch = () => mkdtempSync(join(tmpdir(), "vs-ms-")); @@ -22,7 +22,8 @@ describe("machineStateDir", () => { test("one folder per library path, under the state root, outside the library", () => { const a = machineStateDir("/state", "/Users/me/ViewSwitcher Library"); - expect(a).toMatch(/^\/state\/libraries\/[0-9a-f]{16}$/); + expect(dirname(a)).toBe(join(resolve("/state"), "libraries")); + expect(basename(a)).toMatch(/^[0-9a-f]{16}$/); expect(machineStateDir("/state", "/Users/me/ViewSwitcher Library/")).toBe(a); // the same path, written another way expect(machineStateDir("/state", "/Users/me/Other Library")).not.toBe(a); }); diff --git a/apps/server/src/machine-state.ts b/apps/server/src/machine-state.ts index 83eed4a..b4dc409 100644 --- a/apps/server/src/machine-state.ts +++ b/apps/server/src/machine-state.ts @@ -16,7 +16,7 @@ export function machineStateDir(stateRoot: string, library: string): string { // is the same library; its resolved path before the first run creates it. let at = resolve(library); try { - at = realpathSync(at); + at = realpathSync.native(at); } catch {} const key = createHash("sha256").update(at).digest("hex").slice(0, 16); return join(resolve(stateRoot), "libraries", key); diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index a522388..b49b1db 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -4,7 +4,7 @@ import { mkdir, readFile } from "node:fs/promises"; import { join, sep } from "node:path"; import type { ServerMessage } from "@viewswitcher/shared"; import type { Server, ServerWebSocket } from "bun"; -import { stdioLaunch } from "./agent-connect"; +import { compiled, stdioLaunch } from "./agent-connect"; import { type BuiltinPackFiles, buildBuiltins, readBuiltins } from "./builtin-packs"; import { config } from "./config"; import { createLog } from "./log"; @@ -12,7 +12,8 @@ import { loopbackAddress } from "./gate"; import { dispatcher, type SocketData } from "./http/dispatch"; import { pairPageResponse, routes, secure } from "./http/routes"; import { pairingOrder, thisMac } from "./lan"; -import { appParent, watchParent } from "./parent-watch"; +import { type LanListeners, lanListeners } from "./lan-listen"; +import { appParent, stopsOnStdinEnd, watchParent } from "./parent-watch"; import { plainStateFolder } from "./library/contain"; import { LibraryScanner } from "./library/scanner"; import { migrateMachineState } from "./machine-state"; @@ -87,8 +88,9 @@ pairing.onRemoved = (id) => { /** The main listener on 127.0.0.1, from the end of startup on. */ let server: Server | undefined; -/** The Wi-Fi listener, while "Let phones and tablets on this Wi-Fi connect" is on. */ -let lanServer: Server | null = null; +/** The Wi-Fi listener(s), while "Let phones and tablets on this Wi-Fi connect" is on (lan-listen.ts: one per address on Windows). */ +let lan: LanListeners> | null = null; +const lanOn = () => !!lan?.on; // ---------------------------------------------------------------- live state @@ -96,7 +98,7 @@ let lanServer: Server | null = null; function publish(msg: ServerMessage) { const text = JSON.stringify(msg); server?.publish("all", text); - lanServer?.publish("all", text); + lan?.publish("all", text); } const log = createLog(config.verbose); @@ -113,6 +115,7 @@ const store = await LiveStore.open({ obsSetup: null, usb: { enabled: false, attached: false, connected: false }, agent: { onAir: (await readSettings(machineState)).agentOnAir, lastSeen: null, client: null }, + host: process.platform === "win32" ? "windows" : "mac", }, }); const state = store.state; @@ -218,7 +221,7 @@ watch(config.library, { recursive: true }, (_event, filename) => { // ---------------------------------------------------------------- phones and tablets /** This Mac's .local name and LAN addresses, while something can reach us over the network; null otherwise (origin.ts). */ -const lanNames = () => (lanServer ? thisMac() : null); +const lanNames = () => (lanOn() ? thisMac() : null); function remoteStatus() { const mac = thisMac(); @@ -226,10 +229,10 @@ function remoteStatus() { const connected = new Map(); for (const ws of sockets) if (ws.data.remote) connected.set(ws.data.remote, (connected.get(ws.data.remote) ?? 0) + 1); return { - enabled: !!lanServer, + enabled: lanOn(), port: config.port, localName: mac.localName, - urls: lanServer ? [...(mac.localName ? [mac.localName] : []), ...addresses].map((h) => `http://${h}:${config.port}/`) : [], + urls: lanOn() ? [...(mac.localName ? [mac.localName] : []), ...addresses].map((h) => `http://${h}:${config.port}/`) : [], code: pairing.codeExpiresAt() ? { expiresAt: pairing.codeExpiresAt() } : null, /** The last code was cancelled by wrong guesses: someone on the network is guessing. */ codeGuessed: pairing.codeGuessed, @@ -238,22 +241,26 @@ function remoteStatus() { } function setLan(on: boolean): string | null { - if (on && !lanServer) { - try { - lanServer = Bun.serve({ hostname: config.lanHost, port: config.port, fetch: handle, websocket }); - console.log(`[wifi] phones and tablets may connect: http://${thisMac().localName ?? config.lanHost}:${config.port}`); - } catch (e) { - console.error("[wifi] couldn't listen on the network:", (e as Error).message); - return `Couldn't listen on the network: ${(e as Error).message}`; + if (on && !lanOn()) { + lan ??= lanListeners({ + host: config.lanHost, + // Every address this computer has, VPNs' included, as 0.0.0.0 would be (Tailscale reaches it too). + addresses: () => thisMac().addresses, + serve: (hostname) => Bun.serve({ hostname, port: config.port, fetch: handle, websocket }), + }); + const error = lan.start(); + if (error) { + console.error("[wifi] couldn't listen on the network:", error); + return `Couldn't listen on the network: ${error}`; } + console.log(`[wifi] phones and tablets may connect: http://${thisMac().localName ?? config.lanHost}:${config.port}`); } - if (!on && lanServer) { - const s = lanServer; - lanServer = null; + if (!on && lanOn()) { + const s = lan!; // Off means off: the port closes and every paired phone or tablet is cut off now, on the Wi-Fi or through // tailscale serve (they stay paired). Only this Mac's and the USB-C device's sockets have no remote. for (const ws of sockets) if (ws.data.lan || ws.data.remote) ws.close(1001, "Wi-Fi connections were turned off"); - s.stop(true); + s.stop(); console.log("[wifi] network listener closed; 127.0.0.1 only"); } return null; @@ -263,11 +270,11 @@ function setLan(on: boolean): string | null { const adminSecret = config.adminToken.length >= 32 ? sha3(config.adminToken) : null; const isAdmin = (req: Request) => adminSecret !== null && sha3(req.headers.get("x-viewswitcher-admin") ?? "") === adminSecret; // digests, not raw secrets (pairing.ts) -// What an agent runs to connect over stdio: this executable with --mcp-stdio. In the Mac app's compiled -// sidecar, import.meta.dir is inside the binary (/$bunfs/…); from source, bun runs index.ts. +// What an agent runs to connect over stdio: this executable with --mcp-stdio. In the apps' compiled +// server, import.meta.dir is inside the binary (agent-connect.ts compiled()); from source, bun runs index.ts. /** The Mac app passes its version (MCPB wants semver; a source checkout has none). */ const extensionVersion = /^\d+\.\d+\.\d+$/.test(process.env.VIEWSWITCHER_VERSION ?? "") ? process.env.VIEWSWITCHER_VERSION! : "1.0.0"; -const ownStdio = (port: number) => stdioLaunch(process.execPath, import.meta.dir.startsWith("/$bunfs") ? null : join(import.meta.dir, "index.ts"), port); +const ownStdio = (port: number) => stdioLaunch(process.execPath, compiled(import.meta.dir) ? null : join(import.meta.dir, "index.ts"), port); // The MCP server for agents on this Mac (mcp/). It shares the switcher's state and its way of going on air. const mcp: McpDeps = { @@ -320,8 +327,8 @@ const handle = dispatcher({ allowedOrigins: config.allowedOrigins, lan: lanNames, // One setting for everything not from this Mac or the USB-C bridge: the Wi-Fi listener and tailscale serve. - remoteAccess: () => !!lanServer, - onLan: (srv) => srv === lanServer, + remoteAccess: lanOn, + onLan: (srv) => !!lan?.has(srv), remote: (req) => pairing.check(tokenFromCookie(req.headers.get("cookie")))?.id ?? null, renew: (remote, c) => { const token = tokenFromCookie(c.req.headers.get("cookie")); @@ -358,15 +365,28 @@ for (const sig of ["SIGTERM", "SIGINT"] as const) { process.on(sig, () => void pairing.flush().finally(() => process.exit(0))); } -// Started by the Mac app: exit if the app goes away without stopping us (parent-watch.ts). +// Started by the Mac or Windows app: exit if the app goes away without stopping us (parent-watch.ts). const parent = appParent(); if (parent) { watchParent(parent, () => { - console.log("[viewswitcher] the Mac app is gone; stopping"); + console.log("[viewswitcher] the app that started this server is gone; stopping"); void pairing.flush().finally(() => process.exit(0)); }); } +// Windows has no SIGTERM: the Windows app holds a pipe on stdin and closes it to stop the server, which +// then writes paired phones and tablets first, as on SIGTERM. Opt-in, since a server started with no +// stdin at all (the Mac app's /dev/null) would read that as the end at once. +if (stopsOnStdinEnd()) { + const stop = () => { + console.log("[viewswitcher] the app closed stdin; stopping"); + void pairing.flush().finally(() => process.exit(0)); + }; + process.stdin.on("end", stop); + process.stdin.on("close", stop); + process.stdin.resume(); +} + // USB-C link for the ViewSwitcher iPad app (see usb-bridge.ts). if (process.env.VIEWSWITCHER_USB !== "0" && usbAvailable()) { store.update({ usb: { ...state.usb, enabled: true } }); diff --git a/apps/server/src/mcp/server.test.ts b/apps/server/src/mcp/server.test.ts index ab10e3b..7b74c0f 100644 --- a/apps/server/src/mcp/server.test.ts +++ b/apps/server/src/mcp/server.test.ts @@ -18,9 +18,10 @@ import { ensureLibrary } from "../library-kit"; import type { PreviewResult } from "../preview-types"; import { readForEdit, sceneHash } from "../scene-edit"; import { createMcpServer, INSTRUCTIONS } from "./server"; +import { fileLinks } from "../../../../test-links"; const root = mkdtempSync(join(tmpdir(), "vs-mcp-")); -const realRoot = realpathSync(root); +const realRoot = realpathSync.native(root); const outside = mkdtempSync(join(tmpdir(), "vs-mcp-outside-")); const ORG = "my-channel"; const PORT = 7433; @@ -197,7 +198,7 @@ describe("read tools", () => { expect(r.isError).toBe(true); expect(r.text).toContain(`/library/${ORG}/assets/logo.png`); }); - test("read_file refuses dot-folders, other orgs' escapes and links out of the library", async () => { + test.skipIf(!fileLinks)("read_file refuses dot-folders, other orgs' escapes and links out of the library", async () => { await writeFile(join(outside, "secret.md"), "secret"); await symlink(join(outside, "secret.md"), join(root, ORG, "link.md")); for (const path of [".viewswitcher/state.json", ".claude/skills/viewswitcher-scenes/SKILL.md", `${ORG}/../CLAUDE.md`, `${ORG}/link.md`, `${ORG}/.git/config`]) { @@ -414,7 +415,7 @@ describe("go_on_air and the agent guard", () => { await writeFile(join(root, ORG, "assets", "page.html"), "x"); expect((await call("go_on_air", { path: `${ORG}/assets/page.html` })).text).toContain("Only a show's templates"); }); - test("while live, writes to the on-air scene, its transitions and _shared are refused with a way around", async () => { + test.skipIf(!fileLinks)("while live, writes to the on-air scene, its transitions and _shared are refused with a way around", async () => { const { projectId } = await data("create_project", { org: ORG, name: "Guarded", templates: ["teaching"] }); const { streamId } = await data("create_stream", { org: ORG, projectId, name: "Live", date: "2026-12-06" }); const copy = await data("customize_scene", { org: ORG, projectId, streamId, name: "teaching" }); @@ -448,7 +449,7 @@ describe("go_on_air and the agent guard", () => { }); describe("structural tools stay inside the library", () => { - test("duplicate_scene of a link to a file outside is refused; a link inside still copies", async () => { + test.skipIf(!fileLinks)("duplicate_scene of a link to a file outside is refused; a link inside still copies", async () => { await writeFile(join(outside, "elsewhere.html"), "Secret"); await symlink(join(outside, "elsewhere.html"), join(root, ORG, "templates", "linked-out.html")); const r = await call("duplicate_scene", { path: `${ORG}/templates/linked-out.html` }); @@ -468,7 +469,7 @@ describe("structural tools stay inside the library", () => { expect(r.isError).toBe(true); expect(r.text).toContain("outside the library"); }); - test("create_project won't copy a template linked outside; add_asset won't write into an assets folder linked outside", async () => { + test.skipIf(!fileLinks)("create_project won't copy a template linked outside; add_asset won't write into an assets folder linked outside", async () => { await writeFile(join(outside, "tpl.html"), "Outside"); await symlink(join(outside, "tpl.html"), join(root, ORG, "templates", "linked-tpl.html")); const r = await call("create_project", { org: ORG, name: "From linked", templates: ["linked-tpl"] }); @@ -484,7 +485,7 @@ describe("structural tools stay inside the library", () => { expect(a.isError).toBe(true); expect((await readdir(outside)).length).toBe(before); }); - test("the switcher's own Duplicate (library-actions) won't copy a scene linked outside either", async () => { + test.skipIf(!fileLinks)("the switcher's own Duplicate (library-actions) won't copy a scene linked outside either", async () => { const { duplicateScene } = await import("../library-actions"); await expect(duplicateScene(root, `${ORG}/templates/linked-out.html`)).rejects.toThrow("outside the library"); }); @@ -710,7 +711,7 @@ describe("the guard at the commit instant", () => { state.agent.onAir = "always"; expect((await write()).isError).toBe(false); }); - test("the switcher's Duplicate: a copy never lands in a folder linked outside, and a leading slash is refused", async () => { + test.skipIf(!fileLinks)("the switcher's Duplicate: a copy never lands in a folder linked outside, and a leading slash is refused", async () => { const { duplicateScene } = await import("../library-actions"); const { mkdir } = await import("node:fs/promises"); // A folder that links outside, holding a link back to a scene inside the library. @@ -749,7 +750,7 @@ describe("dangling links where a new file would go", () => { }); describe("destination folders linked outside, with a name that links back in", () => { - test("add_asset, scene_from_template and create_project refuse; nothing is written outside", async () => { + test.skipIf(!fileLinks)("add_asset, scene_from_template and create_project refuse; nothing is written outside", async () => { const { mkdir } = await import("node:fs/promises"); const away = join(outside, "away"); await mkdir(join(away, "assets"), { recursive: true }); @@ -790,7 +791,7 @@ describe("destination folders linked outside, with a name that links back in", ( expect((await call("create_stream", { org: ORG, projectId, name: "Out", date: "2026-12-10" })).isError).toBe(true); expect(await readdir(awayStreams)).toEqual([]); }); - test("a template set's template linked outside the library isn't copied", async () => { + test.skipIf(!fileLinks)("a template set's template linked outside the library isn't copied", async () => { const { mkdir } = await import("node:fs/promises"); await mkdir(join(root, ORG, "templates", "far"), { recursive: true }); await writeFile(join(root, ORG, "templates/far/pack.json"), JSON.stringify({ format: 1, id: "far", name: "Far", version: "1.0.0", description: "x", views: ["v"] })); diff --git a/apps/server/src/mcp/server.ts b/apps/server/src/mcp/server.ts index 1bcd003..4036ae4 100644 --- a/apps/server/src/mcp/server.ts +++ b/apps/server/src/mcp/server.ts @@ -156,7 +156,7 @@ export function createMcpServer(deps: McpDeps): McpServer { Object.entries(loads.read).every(([p, h]) => { try { // Non-blocking and plain files only: this runs on the event loop, where a named pipe would stop the server. - return textHash(readNoFollowSync(realpathSync(inside(root, p)))) === h; + return textHash(readNoFollowSync(realpathSync.native(inside(root, p)))) === h; } catch { return false; } diff --git a/apps/server/src/mcp/stdio.test.ts b/apps/server/src/mcp/stdio.test.ts index 97ee609..7e5fe30 100644 --- a/apps/server/src/mcp/stdio.test.ts +++ b/apps/server/src/mcp/stdio.test.ts @@ -124,7 +124,7 @@ describe("relayStdio", () => { { jsonrpc: "2.0", id: 1, error: { code: -32000, message: NOT_RUNNING } }, { jsonrpc: "2.0", id: 2, error: { code: -32000, message: NOT_RUNNING } }, ]); - expect(NOT_RUNNING).toContain("Open ViewSwitcher on this Mac"); + expect(NOT_RUNNING).toContain(process.platform === "win32" ? "Open ViewSwitcher on this PC" : "Open ViewSwitcher on this Mac"); }); test("a call that reached the server is never sent twice: a dropped connection is answered, not retried", async () => { // A switcher that reads the request, then drops the connection before answering (Restart Server mid-call). diff --git a/apps/server/src/mcp/stdio.ts b/apps/server/src/mcp/stdio.ts index 3eb64dd..56dcb2c 100644 --- a/apps/server/src/mcp/stdio.ts +++ b/apps/server/src/mcp/stdio.ts @@ -7,7 +7,7 @@ // to what the relay itself needs. export const MAC_APP_ID = "com.twowitstudios.viewswitcher.mac"; -export const NOT_RUNNING = "ViewSwitcher isn't running. Open ViewSwitcher on this Mac, then try again."; +export const NOT_RUNNING = `ViewSwitcher isn't running. Open ViewSwitcher on this ${process.platform === "win32" ? "PC" : "Mac"}, then try again.`; export const DROPPED = "The connection to ViewSwitcher dropped before it answered, so this may or may not have happened. Check with get_state or read_file before you try it again."; export const DEFAULT_PORT = 7420; @@ -56,6 +56,29 @@ type Message = { jsonrpc?: string; id?: string | number | null; method?: string; const openMacApp = () => Bun.spawn(["open", "-b", MAC_APP_ID], { stdin: "ignore", stdout: "ignore", stderr: "ignore" }).exited; +/** + * The Windows app beside this server: ViewSwitcher.exe, one folder above Helpers\viewswitcher-server.exe + * (apps/windows), or null when this server isn't the installed one (a source run has no app to open). + */ +export function windowsAppFor(execPath: string, exists: (p: string) => boolean = (p) => require("node:fs").existsSync(p)): string | null { + const helpers = execPath.replace(/[\\/][^\\/]+$/, ""); + if (!/[\\/]Helpers$/i.test(helpers)) return null; + const app = `${helpers.replace(/[\\/]Helpers$/i, "")}\\ViewSwitcher.exe`; + return exists(app) ? app : null; +} + +/** + * Started through Explorer, not as this relay's child: an agent may run the relay in a job that ends + * everything it started when the relay ends, and the app has to outlive it. + */ +const openWindowsApp = async () => { + const app = windowsAppFor(process.execPath); + if (!app) throw new Error("this server isn't the installed ViewSwitcher, so there's no app beside it to open"); + await Bun.spawn(["explorer.exe", app], { stdin: "ignore", stdout: "ignore", stderr: "ignore" }).exited; +}; + +const openApp = () => (process.platform === "win32" ? openWindowsApp() : openMacApp()); + /** The ids of the requests in a message or batch (notifications and responses have none to answer). */ const requestIds = (body: unknown): (string | number)[] => (Array.isArray(body) ? body : [body]).flatMap((m: Message) => (m && typeof m.method === "string" && (typeof m.id === "string" || typeof m.id === "number") ? [m.id] : [])); @@ -80,7 +103,7 @@ export async function relayStdio(opts: RelayOptions): Promise { if (opened) return false; opened = true; log("[mcp] ViewSwitcher isn't answering; opening it"); - await (opts.openApp ?? openMacApp)().catch((e) => log(`[mcp] couldn't open ViewSwitcher: ${(e as Error).message}`)); + await (opts.openApp ?? openApp)().catch((e) => log(`[mcp] couldn't open ViewSwitcher: ${(e as Error).message}`)); for (const end = Date.now() + waitMs; Date.now() < end; await Bun.sleep(pollMs)) if (await up()) return true; return false; } finally { diff --git a/apps/server/src/open-file.ts b/apps/server/src/open-file.ts new file mode 100644 index 0000000..981fcb5 --- /dev/null +++ b/apps/server/src/open-file.ts @@ -0,0 +1,8 @@ +// "Open in editor" on this computer: the command that opens a library file in a text editor. Always an +// argument list, never a shell string, so a file name can't become a command. + +/** VIEWSWITCHER_EDITOR (an app name on macOS, an executable on Windows), else the system's text editor. */ +export function editorCommand(abs: string, editor: string | undefined = process.env.VIEWSWITCHER_EDITOR, platform: NodeJS.Platform = process.platform): string[] { + if (platform === "win32") return [editor || "notepad.exe", abs]; + return editor ? ["open", "-a", editor, abs] : ["open", "-t", abs]; +} diff --git a/apps/server/src/packs.test.ts b/apps/server/src/packs.test.ts index ddd10b2..c383b53 100644 --- a/apps/server/src/packs.test.ts +++ b/apps/server/src/packs.test.ts @@ -9,6 +9,7 @@ import { addFromTemplate, createOrg, createProject } from "./library"; import { LibraryScanner } from "./library/scanner"; import { cancelPack, installPack, PackError, removeSet, stagePack, sweepStaging } from "./packs"; import { SHOWS, SHOWS_DIR, showPacks, starterPack, writeZip, zipPack } from "@viewswitcher/packs"; +import { fileLinks } from "../../../test-links"; const starter = resolve(import.meta.dir, "../starter"); const scanOrg = (root: string, org: string) => new LibraryScanner(root).scanOrg(org); @@ -212,7 +213,7 @@ describe("removing a set", () => { expect(await readFile(join(root, org, "templates/starter/_shared/theme.css"), "utf8")).toContain("--accent"); }); - test("counts a scene that is a link to one made from it (the set's files stay)", async () => { + test.skipIf(!fileLinks)("counts a scene that is a link to one made from it (the set's files stay)", async () => { await installPack(root, org, (await stagePack(root, org, { zip: starterZip }, null)).token); const { projectId } = await createProject(join(root, org), "Show", ["starter/teaching"]); const real = join(root, org, "projects", projectId, "scenes/teaching.html"); @@ -222,7 +223,7 @@ describe("removing a set", () => { expect(await readFile(join(root, org, "templates/starter/_shared/theme.css"), "utf8")).toContain("--accent"); }); - test("a scene that is a link outside the library isn't read to count it", async () => { + test.skipIf(!fileLinks)("a scene that is a link outside the library isn't read to count it", async () => { await installPack(root, org, (await stagePack(root, org, { zip: starterZip }, null)).token); const { projectId } = await createProject(join(root, org), "Show", ["starter/teaching"]); const away = await mkdtemp(join(tmpdir(), "vs-packs-away-")); @@ -415,7 +416,7 @@ describe("an org's .viewswitcher/ or staging/ linked outside the library", () => } }); - test("a staged file swapped for a link (a file outside the library): install refuses and copies nothing", async () => { + test.skipIf(!fileLinks)("a staged file swapped for a link (a file outside the library): install refuses and copies nothing", async () => { const away = await mkdtemp(join(tmpdir(), "vs-packs-away-")); try { await writeFile(join(away, "secret.css"), "outside secret"); diff --git a/apps/server/src/packs.ts b/apps/server/src/packs.ts index 5cf0fee..c1d43a3 100644 --- a/apps/server/src/packs.ts +++ b/apps/server/src/packs.ts @@ -14,6 +14,7 @@ import { dirname, join } from "node:path"; import { checkPack, fillPlaceholders, installedPath, isTextFile, libraryUrl, PACK_LIMITS, placeholderVars, planPack, readTitle } from "@viewswitcher/shared"; import type { PackEntry, PackFile, PackManifest, StagedPack } from "@viewswitcher/shared"; import { writeAtomic } from "./atomic"; +import { claimRename } from "./fsx"; import { exists, readOrg } from "./library"; import { libraryStaging, readNoFollow, readNoFollowBytes, resolveInLibrary, STAGING, STAGING_TOKEN, stagingIn } from "./library/contain"; import { limit } from "./limit"; @@ -198,20 +199,15 @@ export async function installPack(libraryRoot: string, orgId: string, token: unk await rm(final, { recursive: true, force: true }); await fillCopy(join(dir, "raw"), final, meta.files, await varsFor(libraryRoot, orgId, libraryUrl(`${orgId}/templates/${set}`))); await mkdir(join(orgDir, "templates"), { recursive: true }); - // Claim the name first: mkdir without recursive fails if the folder appeared meanwhile (two - // installs at once, an agent), where rename alone would quietly replace an empty one. + // The one step that fills the org: atomic, and only onto a name nobody has (fsx.ts), so a set that + // appeared meanwhile (two installs at once, an agent) is never replaced. const target = inside(orgDir, `templates/${set}`); try { - await mkdir(target); + await claimRename(final, target); } catch (e) { if ((e as NodeJS.ErrnoException).code === "EEXIST") throw new PackError("A set with that name just appeared. Drop the pack again."); throw plainFsError(e, "Installing it"); } - // The one step that fills the org: atomic, onto the empty folder just claimed. - await rename(final, target).catch(async (e) => { - await rmdir(target).catch(() => {}); // only if still empty: never someone else's files - throw e; - }); return { set }; } catch (e) { throw plainFsError(e, "Installing it"); diff --git a/apps/server/src/pair-page.ts b/apps/server/src/pair-page.ts index d2fe376..bcbadb2 100644 --- a/apps/server/src/pair-page.ts +++ b/apps/server/src/pair-page.ts @@ -4,6 +4,8 @@ const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); +import { COMPUTER } from "./platform-dirs"; + export const PAIR_PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'"; export function pairPage({ name }: { name: string }): string { @@ -37,7 +39,7 @@ export function pairPage({ name }: { name: string }): string {

Pair with ViewSwitcher

-

On the Mac: Phones and Tablets.

+

On the ${COMPUTER}: Phones and Tablets in ViewSwitcher.

diff --git a/apps/server/src/pairing.test.ts b/apps/server/src/pairing.test.ts index 51725d1..595972d 100644 --- a/apps/server/src/pairing.test.ts +++ b/apps/server/src/pairing.test.ts @@ -3,6 +3,7 @@ import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { CODE_ALPHABET, CODE_LENGTH, CODE_TTL_MS, COOKIE, remoteName, guessName, MAX_CODE_FAILURES, MAX_PEER_FAILURES, normalizeCode, Pairing, PEER_WINDOW_MS, sha3, tokenCookie, tokenFromCookie } from "./pairing"; +import { posix } from "../../../test-links"; const clock = () => { let t = 1_000_000; @@ -150,14 +151,14 @@ describe("device tokens", () => { c.tick(90_000); expect(p.check(r.token)?.lastSeen).toBe(c.now()); }); - test("a removal that can't be written says so (it would come back after a restart)", async () => { + test.skipIf(!posix)("a removal that can't be written says so (it would come back after a restart)", async () => { const p = new Pairing({ file: "/dev/null/nope/devices.json" }); const r = p.pair(p.newCode().code, "a", "192.168.1.20"); if (!r.ok) throw new Error("pairing failed"); await expect(p.remove(r.remote.id)).rejects.toThrow("couldn't save"); expect(p.check(r.token)).toBeNull(); // still refused now }); - test("devices.json keeps hashes only (0600) and survives a restart", async () => { + test.skipIf(!posix)("devices.json keeps hashes only (0600) and survives a restart", async () => { const file = join(dir, "devices.json"); const p = await new Pairing({ file }).load(); const r = p.pair(p.newCode().code, "iPad", "192.168.1.20"); diff --git a/apps/server/src/pairing.ts b/apps/server/src/pairing.ts index 8362838..d983c80 100644 --- a/apps/server/src/pairing.ts +++ b/apps/server/src/pairing.ts @@ -11,6 +11,7 @@ // Secrets are compared by hashing both sides with SHA3-256 and comparing the digests (the // aidd-timing-safe-compare rule). Don't "fix" this to a raw === or crypto.timingSafeEqual: a digest // has no prefix structure to guess one character at a time, and the raw secret never reaches a log. +import { COMPUTER } from "./platform-dirs"; import { readFile } from "node:fs/promises"; import { writeAtomic } from "./atomic"; @@ -138,13 +139,13 @@ export class Pairing { if (recent.length) this.peers.set(peer, recent); else this.peers.delete(peer); if (recent.length >= MAX_PEER_FAILURES) { - return { ok: false, reason: "limited", error: "Too many tries. Wait a few minutes, then ask the Mac for a new code." }; + return { ok: false, reason: "limited", error: `Too many tries. Wait a few minutes, then ask the ${COMPUTER} for a new code.` }; } const code = this.code; // An old code (a QR code scanned again) isn't a guess: it doesn't count against anyone. if (!code || code.expiresAt <= t) { this.code = null; - return { ok: false, reason: "expired", error: "That code has expired. Ask the Mac for a new one (Phones and Tablets in its menu)." }; + return { ok: false, reason: "expired", error: `That code has expired. Ask the ${COMPUTER} for a new one (Phones and Tablets in ViewSwitcher).` }; } // Hash both sides, compare digests (see the top of this file). if (sha3(normalizeCode(candidate)) !== code.hash) { @@ -153,7 +154,7 @@ export class Pairing { this.code = null; this.codeGuessed = true; } - return { ok: false, reason: "wrong", error: "That code isn't right. Check it on the Mac and try again." }; + return { ok: false, reason: "wrong", error: `That code isn't right. Check it on the ${COMPUTER} and try again.` }; } this.code = null; // single use const token = randomToken(); diff --git a/apps/server/src/parent-watch.ts b/apps/server/src/parent-watch.ts index 432168e..1a8ac92 100644 --- a/apps/server/src/parent-watch.ts +++ b/apps/server/src/parent-watch.ts @@ -2,12 +2,15 @@ // quit), so the port is never left held by an orphan. The app passes its pid in // VIEWSWITCHER_PARENT_PID; a server started any other way (bun run dev) has none and is never watched. -/** The Mac app that started this server, or null when something else did. */ +/** The Mac or Windows app that started this server, or null when something else did. */ export function appParent(env: Record = process.env): number | null { const pid = Number(env.VIEWSWITCHER_PARENT_PID); return Number.isInteger(pid) && pid > 1 ? pid : null; } +/** Whether the app that started this server stops it by closing stdin (the Windows app: no SIGTERM there). */ +export const stopsOnStdinEnd = (env: Record = process.env) => env.VIEWSWITCHER_STOP_ON_STDIN === "1"; + /** Whether a process with this pid exists. EPERM means it does, under another user. */ export function alive(pid: number): boolean { try { diff --git a/apps/server/src/paths.test.ts b/apps/server/src/paths.test.ts index bfa7424..a1f1aa7 100644 --- a/apps/server/src/paths.test.ts +++ b/apps/server/src/paths.test.ts @@ -1,12 +1,13 @@ import { describe, expect, test } from "bun:test"; -import { inside, plainName } from "./paths"; +import { resolve } from "node:path"; +import { inside, plainName, windowsUnsafe } from "./paths"; const root = "/tmp/lib"; describe("inside", () => { test("allows paths in the library", () => { - expect(inside(root, "projects/ld/scenes/teaching.html")).toBe("/tmp/lib/projects/ld/scenes/teaching.html"); - expect(inside(root, "/assets/logo.png")).toBe("/tmp/lib/assets/logo.png"); + expect(inside(root, "projects/ld/scenes/teaching.html")).toBe(resolve("/tmp/lib/projects/ld/scenes/teaching.html")); + expect(inside(root, "/assets/logo.png")).toBe(resolve("/tmp/lib/assets/logo.png")); }); test("rejects escapes", () => { for (const p of ["../etc/passwd", "projects/../../x", "", "a\0b"]) { @@ -15,6 +16,26 @@ describe("inside", () => { }); }); +describe("on Windows", () => { + test("refuses what Windows reads as something else: backslashes, drives and streams, devices, a trailing dot or space", () => { + for (const p of ["daisy\\templates\\brb.html", "daisy/templates/brb.html:hidden", "C:/Windows/win.ini", "daisy/CON", "daisy/nul.html", "daisy/com1.txt", "daisy/templates/brb.html.", "daisy/brb ", "daisy/a*b", "daisy/a?b"]) { + expect(() => inside(root, p, true)).toThrow(); + } + for (const n of ["CON", "aux.html", "LPT9", "logo.png.", "a:b"]) expect(() => plainName(n, true)).toThrow(); + }); + test("still allows the names a library has", () => { + expect(inside(root, "daisy/templates/brb.html", true)).toBe(resolve("/tmp/lib/daisy/templates/brb.html")); + expect(inside(root, "daisy/projects/live/streams/12-07-show/console.html", true)).toBeTruthy(); + expect(plainName("Daisy logo.png", true)).toBe("Daisy logo.png"); + expect(windowsUnsafe("contour.html")).toBe(false); + expect(windowsUnsafe("con.html")).toBe(true); + }); + test("off Windows, the same names are left alone", () => { + expect(inside(root, "daisy/templates/brb.html:hidden", false)).toBe(resolve("/tmp/lib/daisy/templates/brb.html:hidden")); + expect(plainName("CON", false)).toBe("CON"); + }); +}); + describe("plainName", () => { test("accepts upload names, rejects traversal and dot-files", () => { expect(plainName("Daisy logo (transparent).png".replace(/[()]/g, ""))).toBeTruthy(); diff --git a/apps/server/src/paths.ts b/apps/server/src/paths.ts index 7d21647..73fc378 100644 --- a/apps/server/src/paths.ts +++ b/apps/server/src/paths.ts @@ -2,9 +2,20 @@ import { isAbsolute, relative, resolve, sep } from "node:path"; export class PathError extends Error {} +/** + * A path segment Windows would read as something other than a plain name: a backslash (a separator + * there), a colon (a drive, or an NTFS alternate data stream: "brb.html:hidden"), the other characters + * Windows forbids, a reserved device name (CON, NUL, COM1, …, with or without an extension), or a + * trailing dot or space (which Windows strips, so "brb.html." would be brb.html). + */ +export const windowsUnsafe = (segment: string) => + /[\\:*?"<>|\x00-\x1f]/.test(segment) || /^(con|prn|aux|nul|conin\$|conout\$|com[0-9¹²³]|lpt[0-9¹²³])(\..*)?$/i.test(segment) || /[. ]$/.test(segment); + /** Resolve a library-relative path, refusing anything that escapes the library. */ -export function inside(root: string, rel: string): string { +export function inside(root: string, rel: string, win = process.platform === "win32"): string { if (typeof rel !== "string" || rel.length === 0 || rel.includes("\0")) throw new PathError("Bad path"); + // On Windows a library path is still "/"-separated: anything Windows would read differently is refused. + if (win && rel.replace(/^\/+/, "").split("/").some((s) => s !== "" && s !== "." && s !== ".." && windowsUnsafe(s))) throw new PathError(`Bad path: ${rel}`); const abs = resolve(root, rel.replace(/^\/+/, "")); const back = relative(root, abs); if (back === "" || back.startsWith("..") || isAbsolute(back) || back.split(sep).includes("..")) { @@ -13,8 +24,8 @@ export function inside(root: string, rel: string): string { return abs; } -/** A single file or folder name: no separators, no dot-files. */ -export function plainName(name: string): string { - if (!/^[A-Za-z0-9][A-Za-z0-9._ -]{0,120}$/.test(name) || name.includes("..")) throw new PathError(`Bad name: ${name}`); +/** A single file or folder name: no separators, no dot-files (and nothing Windows reads as a device). */ +export function plainName(name: string, win = process.platform === "win32"): string { + if (!/^[A-Za-z0-9][A-Za-z0-9._ -]{0,120}$/.test(name) || name.includes("..") || (win && windowsUnsafe(name))) throw new PathError(`Bad name: ${name}`); return name; } diff --git a/apps/server/src/platform-dirs.test.ts b/apps/server/src/platform-dirs.test.ts new file mode 100644 index 0000000..c9bd9f6 --- /dev/null +++ b/apps/server/src/platform-dirs.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, test } from "bun:test"; +import { join } from "node:path"; +import { appSupport, COMPUTER, obsWebsocketConfig, stateRoot } from "./platform-dirs"; + +describe("where this computer keeps OBS's settings and ViewSwitcher's state", () => { + test("macOS: ~/Library/Application Support", () => { + expect(appSupport("darwin", {}, "/Users/sam")).toBe(join("/Users/sam", "Library/Application Support")); + }); + test("Windows: %APPDATA% (Roaming), where OBS keeps obs-studio", () => { + const roaming = "C:\\Users\\sam\\AppData\\Roaming"; + expect(appSupport("win32", { APPDATA: roaming }, "C:\\Users\\sam")).toBe(roaming); + expect(appSupport("win32", {}, "C:\\Users\\sam")).toBe(join("C:\\Users\\sam", "AppData", "Roaming")); + expect(obsWebsocketConfig(roaming)).toBe(join(roaming, "obs-studio", "plugin_config", "obs-websocket", "config.json")); + expect(stateRoot(roaming)).toBe(join(roaming, "ViewSwitcher")); + }); + test("elsewhere: XDG", () => { + expect(appSupport("linux", { XDG_CONFIG_HOME: "/x" }, "/home/sam")).toBe("/x"); + expect(appSupport("linux", {}, "/home/sam")).toBe(join("/home/sam", ".config")); + }); + test("what phones and agents are told the computer is", () => { + expect(COMPUTER).toBe(process.platform === "win32" ? "PC" : "Mac"); + }); +}); diff --git a/apps/server/src/platform-dirs.ts b/apps/server/src/platform-dirs.ts new file mode 100644 index 0000000..509d18b --- /dev/null +++ b/apps/server/src/platform-dirs.ts @@ -0,0 +1,20 @@ +// Where this computer keeps per-user app data: ~/Library/Application Support on macOS, %APPDATA% +// (Roaming) on Windows, $XDG_CONFIG_HOME or ~/.config elsewhere. OBS keeps its settings in the same +// place, under obs-studio/. +import { homedir } from "node:os"; +import { join } from "node:path"; + +export function appSupport(platform: NodeJS.Platform = process.platform, env: Record = process.env, home = homedir()): string { + if (platform === "darwin") return join(home, "Library/Application Support"); + if (platform === "win32") return env.APPDATA || join(home, "AppData", "Roaming"); + return env.XDG_CONFIG_HOME || join(home, ".config"); +} + +/** obs-websocket's settings (its password), as OBS on this computer writes them. */ +export const obsWebsocketConfig = (dir = appSupport()) => join(dir, "obs-studio", "plugin_config", "obs-websocket", "config.json"); + +/** This computer's ViewSwitcher state root (machine-state.ts), unless VIEWSWITCHER_STATE moves it. */ +export const stateRoot = (dir = appSupport()) => join(dir, "ViewSwitcher"); + +/** What people call the computer the server runs on, in what phones and agents are told: "Mac" or "PC". */ +export const COMPUTER: "Mac" | "PC" = process.platform === "win32" ? "PC" : "Mac"; diff --git a/apps/server/src/remote.test.ts b/apps/server/src/remote.test.ts index c8dc8b6..adaf6de 100644 --- a/apps/server/src/remote.test.ts +++ b/apps/server/src/remote.test.ts @@ -10,6 +10,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { lanAddresses, pairingOrder, vpnAddresses } from "./lan"; import { freePort, SERVER_START_MS, startServer } from "./test-server"; +import { COMPUTER } from "./platform-dirs"; // The address the server puts in the QR code (its own pairingOrder), and the one this test connects to. const advertised = pairingOrder(lanAddresses(), vpnAddresses())[0]; @@ -219,7 +220,7 @@ describe.skipIf(!ip)(`over the Wi-Fi (${ip})`, () => { const broken = { path: "my-channel/templates/gone.html" }; const phone = await lan("/api/scenes/duplicate", { method: "POST", headers: own, body: JSON.stringify(broken) }); expect(phone.status).toBe(500); - expect(JSON.parse(phone.body).error).toBe("Something went wrong on the Mac. Its server log has the details."); + expect(JSON.parse(phone.body).error).toBe(`Something went wrong on the ${COMPUTER}. Its server log has the details.`); const here = await mac("/api/scenes/duplicate", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(broken) }); expect(JSON.parse(here.body).error).toContain("ENOENT"); // The switcher's frame rule reaches phones too. diff --git a/apps/server/src/scene-edit.test.ts b/apps/server/src/scene-edit.test.ts index 3fd1e28..3fb8280 100644 --- a/apps/server/src/scene-edit.test.ts +++ b/apps/server/src/scene-edit.test.ts @@ -7,6 +7,7 @@ import { join } from "node:path"; import { scanElements, textOf, untagForEdit } from "@viewswitcher/shared"; import { PathError } from "./paths"; import { editScene, HASHED_CHANGES, readForEdit, sceneHash, viewHashes } from "./scene-edit"; +import { fileLinks, posix } from "../../../test-links"; const starter = join(import.meta.dir, "../starter"); const SCENE = "acme/templates/teaching.html"; @@ -50,7 +51,7 @@ describe("viewHashes (sent with a library change)", () => { expect(await viewHashes(root, [copy])).toEqual({ [copy]: r.hash }); await rm(join(root, copy)); }); - test("a named pipe named like a view gives no hash and never hangs (the watcher's flush waits on this)", async () => { + test.skipIf(!posix)("a named pipe named like a view gives no hash and never hangs (the watcher's flush waits on this)", async () => { const pipe = "acme/templates/pipe.html"; expect(Bun.spawnSync(["mkfifo", join(root, pipe)]).exitCode).toBe(0); try { @@ -65,7 +66,7 @@ describe("viewHashes (sent with a library change)", () => { } }); - test("only views and transitions it can read inside the library; a big batch only up to its limit", async () => { + test.skipIf(!fileLinks)("only views and transitions it can read inside the library; a big batch only up to its limit", async () => { const away = await mkdtemp(join(tmpdir(), "vs-edit-away-")); try { await writeFile(join(away, "x.html"), "outside"); @@ -112,7 +113,7 @@ describe("editScene", () => { }); describe("saving keeps the file what it was", () => { - test("permissions survive a save", async () => { + test.skipIf(!posix)("permissions survive a save", async () => { const abs = join(root, "acme/templates/brb.html"); await chmod(abs, 0o664); const text = await readFile(abs, "utf8"); @@ -120,7 +121,7 @@ describe("saving keeps the file what it was", () => { expect((await editScene(root, "acme/templates/brb.html", sceneHash(text), [{ id, text: "Back soon" }])).ok).toBe(true); expect((await stat(abs)).mode & 0o777).toBe(0o664); }); - test("a linked scene stays a link and its target changes", async () => { + test.skipIf(!fileLinks)("a linked scene stays a link and its target changes", async () => { const target = join(root, "acme/templates/ending.html"); const link = join(root, "acme/templates/ending-link.html"); await symlink(target, link); @@ -130,7 +131,7 @@ describe("saving keeps the file what it was", () => { expect((await lstat(link)).isSymbolicLink()).toBe(true); expect(await readFile(target, "utf8")).toContain(">Thanks!<"); }); - test("a link to a file outside the library is refused", async () => { + test.skipIf(!fileLinks)("a link to a file outside the library is refused", async () => { const outside = join(root, "..", `vs-outside-${process.pid}.html`); await writeFile(outside, "

outside

"); await symlink(outside, join(root, "acme/templates/out.html")); diff --git a/apps/server/src/scene-edit.ts b/apps/server/src/scene-edit.ts index cda474c..118319d 100644 --- a/apps/server/src/scene-edit.ts +++ b/apps/server/src/scene-edit.ts @@ -5,6 +5,7 @@ import { chmod, lstat, rename, rm, stat, writeFile } from "node:fs/promises"; import { basename, dirname, join } from "node:path"; import { applyEdits, canRemove, EditError, isLibraryUrl, isViewPath, orgOf, parseLibraryPath, projectViewOf, readTitle, setTitle, slugify, tagForEdit } from "@viewswitcher/shared"; import type { SceneEdit } from "@viewswitcher/shared"; +import { renameOver } from "./fsx"; import { readNoFollow, resolveInLibrary } from "./library/contain"; import { inside, PathError, plainName } from "./paths"; @@ -134,7 +135,7 @@ export async function replaceChecked(real: string, read: Stats, current: string, return { ok: false as const, hash: sceneHash(latest) }; } hooks.atRename?.(); // synchronously, in the same tick as the rename: a last refusal (the MCP guard) - await rename(tmp, real); + await renameOver(tmp, real); replaced = true; return { ok: true as const }; } finally { diff --git a/apps/server/src/scene-titles.test.ts b/apps/server/src/scene-titles.test.ts index 9d303ef..1e7347b 100644 --- a/apps/server/src/scene-titles.test.ts +++ b/apps/server/src/scene-titles.test.ts @@ -1,7 +1,11 @@ // The title cache against a filesystem the test controls: what's read again and what isn't. import { describe, expect, test } from "bun:test"; +import { resolve } from "node:path"; import { createSceneTitles, type FileStamp } from "./scene-titles"; +/** The test's paths ("/lib/o/a.html") as this platform writes them (C:liboa.html on Windows), as the server's are. */ +const P = (p: string) => resolve(p); + /** Files by absolute path, each with its text and stamp; `reads` counts the reads of each. */ function disk() { const files = new Map(); @@ -9,7 +13,7 @@ function disk() { /** Paths whose next read fails (EACCES, EMFILE under load) though their stat works. */ const failNextRead = new Set(); let ino = 1; - const titles = createSceneTitles({ + const cache = createSceneTitles({ stat: async (abs) => { const f = files.get(abs); if (!f) throw new Error("ENOENT"); @@ -23,17 +27,18 @@ function disk() { return f.text; }, }); + const titles = { titleOf: (abs: string) => cache.titleOf(P(abs)), forget: (root: string, paths: string[]) => cache.forget(P(root), paths) }; return { titles, put: (abs: string, title: string, stamp: Partial = {}) => - files.set(abs, { text: `${title}`, stamp: { size: 100, mtimeMs: 1000, ctimeMs: 1000, ino: ino++, ...stamp } }), + files.set(P(abs), { text: `${title}`, stamp: { size: 100, mtimeMs: 1000, ctimeMs: 1000, ino: ino++, ...stamp } }), /** Change the text, keeping the stamp but for `change`. */ rewrite: (abs: string, title: string, change: Partial = {}) => { - const f = files.get(abs)!; - files.set(abs, { text: `${title}`, stamp: { ...f.stamp, ...change } }); + const f = files.get(P(abs))!; + files.set(P(abs), { text: `${title}`, stamp: { ...f.stamp, ...change } }); }, - reads: (abs: string) => reads.get(abs) ?? 0, - failNextRead: (abs: string) => failNextRead.add(abs), + reads: (abs: string) => reads.get(P(abs)) ?? 0, + failNextRead: (abs: string) => failNextRead.add(P(abs)), }; } diff --git a/apps/server/src/scrub.ts b/apps/server/src/scrub.ts index fe07878..d2fca89 100644 --- a/apps/server/src/scrub.ts +++ b/apps/server/src/scrub.ts @@ -1,19 +1,25 @@ // Responses never carry absolute paths (AGENTS.md), but a filesystem error names the file it failed // on. This takes the library's folder out of a message: a path inside it becomes the library path // people know ("daisy/templates/brb.html"), and the folder itself "the library". Both spellings are -// scrubbed, because macOS reports /var/… as /private/var/… once a link is followed. +// scrubbed, because macOS reports /var/… as /private/var/… once a link is followed. On Windows a path +// inside it is written with backslashes, and any case: it comes out as the same "/" library path. import { realpathSync } from "node:fs"; +const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + /** A scrub for messages about the library at `root`. */ -export function pathScrub(root: string): (message: string) => string { +export function pathScrub(root: string, win = process.platform === "win32"): (message: string) => string { const real = (() => { try { - return realpathSync(root); + return realpathSync.native(root); } catch { return root; } })(); // Longest first: one spelling may contain the other. const roots = [...new Set([real, root])].sort((a, b) => b.length - a.length); - return (message) => roots.reduce((t, r) => t.split(`${r}/`).join("").split(r).join("the library"), String(message)); + if (!win) return (message) => roots.reduce((t, r) => t.split(`${r}/`).join("").split(r).join("the library"), String(message)); + // A Windows path ends at a quote, a line end, or the end: "lstat 'C:\…\daisy\x.html'" → "lstat 'daisy/x.html'". + const patterns = roots.map((r) => new RegExp(`${escape(r.replace(/[\\/]+$/, ""))}(?:[\\\\/]([^'"\\n]*))?`, "gi")); + return (message) => patterns.reduce((t, re) => t.replace(re, (_, rest?: string) => (rest ? rest.replaceAll("\\", "/") : "the library")), String(message)); } diff --git a/apps/server/src/windows.test.ts b/apps/server/src/windows.test.ts new file mode 100644 index 0000000..7053d29 --- /dev/null +++ b/apps/server/src/windows.test.ts @@ -0,0 +1,81 @@ +// The server's Windows paths, tested on every platform where the platform is a parameter, and for real +// on Windows where it can't be (renames). +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { claimRename, renameOver } from "./fsx"; +import { editorCommand } from "./open-file"; +import { pathScrub } from "./scrub"; +import { windowsAppFor } from "./mcp/stdio"; +import { parentGone, stopsOnStdinEnd } from "./parent-watch"; + +const root = mkdtempSync(join(tmpdir(), "vs-windows-")); +afterAll(() => rmSync(root, { recursive: true, force: true })); + +describe("claimRename: a staged folder takes a name nobody has", () => { + for (const win of [false, true]) { + if (win !== (process.platform === "win32")) continue; // each platform's own rename rules, only there + test(`${win ? "Windows" : "POSIX"}: moves it, and refuses a name that's taken, whatever is there`, async () => { + const dir = mkdtempSync(join(root, "claim-")); + const staged = join(dir, "staged"); + mkdirSync(staged); + writeFileSync(join(staged, "org.json"), "{}"); + await claimRename(staged, join(dir, "show"), win); + expect(readdirSync(join(dir, "show"))).toEqual(["org.json"]); + const again = join(dir, "again"); + mkdirSync(again); + mkdirSync(join(dir, "empty-taken")); + await expect(claimRename(again, join(dir, "empty-taken"), win)).rejects.toMatchObject({ code: "EEXIST" }); + await expect(claimRename(again, join(dir, "show"), win)).rejects.toMatchObject({ code: "EEXIST" }); + expect(readdirSync(join(dir, "show"))).toEqual(["org.json"]); // never replaced + }); + } + test("renameOver replaces a file", async () => { + writeFileSync(join(root, "a.tmp"), "new"); + writeFileSync(join(root, "a.json"), "old"); + await renameOver(join(root, "a.tmp"), join(root, "a.json")); + expect(await Bun.file(join(root, "a.json")).text()).toBe("new"); + }); +}); + +describe("errors name library paths, not Windows folders", () => { + test("a path inside the library, any case, with backslashes, becomes the library path", () => { + const scrub = pathScrub("C:\\Users\\Sam\\ViewSwitcher Library", true); + expect(scrub("ENOENT: no such file or directory, lstat 'C:\\Users\\Sam\\ViewSwitcher Library\\my-show\\templates\\gone.html'")).toBe("ENOENT: no such file or directory, lstat 'my-show/templates/gone.html'"); + expect(scrub("EACCES: c:\\users\\sam\\viewswitcher library\\x.html")).toBe("EACCES: x.html"); + expect(scrub("can't read C:\\Users\\Sam\\ViewSwitcher Library")).toBe("can't read the library"); + expect(scrub("elsewhere: D:\\other\\file")).toBe("elsewhere: D:\\other\\file"); + }); +}); + +describe("Open in editor", () => { + test("Windows: the editor, or Notepad, with the file as its own argument", () => { + expect(editorCommand("C:\\lib\\a b.html", undefined, "win32")).toEqual(["notepad.exe", "C:\\lib\\a b.html"]); + expect(editorCommand("C:\\lib\\a.html", "C:\\Program Files\\Code\\Code.exe", "win32")).toEqual(["C:\\Program Files\\Code\\Code.exe", "C:\\lib\\a.html"]); + }); + test("macOS: open, as before", () => { + expect(editorCommand("/lib/a.html", undefined, "darwin")).toEqual(["open", "-t", "/lib/a.html"]); + expect(editorCommand("/lib/a.html", "Visual Studio Code", "darwin")).toEqual(["open", "-a", "Visual Studio Code", "/lib/a.html"]); + }); +}); + +describe("--mcp-stdio opens the Windows app beside the installed server", () => { + test("Helpers\\viewswitcher-server.exe → ViewSwitcher.exe one folder up, when it's there", () => { + const server = "C:\\Users\\sam\\AppData\\Local\\ViewSwitcher\\current\\Helpers\\viewswitcher-server.exe"; + expect(windowsAppFor(server, (p) => p === "C:\\Users\\sam\\AppData\\Local\\ViewSwitcher\\current\\ViewSwitcher.exe")).toBe("C:\\Users\\sam\\AppData\\Local\\ViewSwitcher\\current\\ViewSwitcher.exe"); + expect(windowsAppFor(server, () => false)).toBeNull(); + expect(windowsAppFor("C:\\Users\\sam\\.bun\\bin\\bun.exe", () => true)).toBeNull(); // a source run has no app + }); +}); + +describe("the Windows app's stop and parent", () => { + test("only a server the app started with VIEWSWITCHER_STOP_ON_STDIN=1 stops when stdin ends", () => { + expect(stopsOnStdinEnd({ VIEWSWITCHER_STOP_ON_STDIN: "1" })).toBe(true); + expect(stopsOnStdinEnd({})).toBe(false); + }); + test("a parent that's gone is gone on Windows too (no reparenting to pid 1 there)", () => { + expect(parentGone(4242, 4242, () => false)).toBe(true); + expect(parentGone(4242, 4242, () => true)).toBe(false); + }); +}); diff --git a/apps/site/src/data/faq.ts b/apps/site/src/data/faq.ts index 78e13b8..96e6c16 100644 --- a/apps/site/src/data/faq.ts +++ b/apps/site/src/data/faq.ts @@ -15,5 +15,8 @@ export const FAQS: Faq[] = [ ? `Yes, with ViewSwitcher for iPhone and iPad (${IPAD_PRICE} once, one purchase for both). Held sideways, your views fill the phone like a deck. On the Mac, in ViewSwitcher's menu bar, turn on Let Phones and Tablets on This Wi-Fi Connect, then tap Scan the code in the app. Only phones and tablets you pair can switch scenes. Use it on Wi-Fi you trust, like home or church Wi-Fi.` : `Yes. ViewSwitcher for iPhone and iPad is coming to the App Store (${IPAD_PRICE} once, one purchase for both). Held sideways, your views fill the phone like a deck, and you pair it by scanning the code the Mac shows. Until then, any phone can switch from its browser: in ViewSwitcher's menu bar, turn on Let Phones and Tablets on This Wi-Fi Connect and scan the QR code with the phone's camera. Only phones and tablets you pair can switch scenes. Use it on Wi-Fi you trust, like home or church Wi-Fi.`, more: { href: "/ipad", label: "ViewSwitcher for iPhone and iPad" } }, - { q: "Windows?", a: "Not yet. ViewSwitcher is Mac only for now. If you'd use it on Windows, tell us on GitHub." }, + { q: "Windows?", a: site.windowsAppReleased + ? "Yes. ViewSwitcher for Windows 10 and 11 is free too: download the installer, run it, and ViewSwitcher sets up OBS for you the first time. Phones and tablets connect over the Wi-Fi the same way, and it keeps itself up to date." + : "Coming soon. ViewSwitcher for Windows 10 and 11 is on its way, with everything the Mac app does: OBS set up for you, phones and tablets over the Wi-Fi, and Edit with AI.", + ...(site.windowsAppReleased ? { more: { href: site.windowsSetupUrl, label: "Download for Windows" } } : {}) }, ]; diff --git a/apps/site/src/site.config.ts b/apps/site/src/site.config.ts index 20db546..771ae9a 100644 --- a/apps/site/src/site.config.ts +++ b/apps/site/src/site.config.ts @@ -19,6 +19,10 @@ const TEMPLATE_DOWNLOADS_URL: string | null = "/templates"; // Null: the template pages say installing packs comes with the next update. Set (e.g. "1.1.0"): "Needs ViewSwitcher 1.1.0 or later." const PACK_INSTALL_VERSION: string | null = "1.1.0"; +// THE WINDOWS SWITCH: true once a release carries ViewSwitcher-win-Setup.exe (bun run win:release --publish). +// Before: "Windows? Coming soon". After: the FAQ answers with the download. A build can override it with SITE_WINDOWS_APP=1 or 0. +const WINDOWS_APP_RELEASED = false; + // THE AI SWITCH: true once Edit with AI (MCP) ships, in v1.2.0. How it works step 1 then says // you can connect your favorite AI in one click, with the Edit with AI sheet as its picture, and /download // gets a line. False: today's step 1. A build can override it with SITE_AI_CONNECT_RELEASED=1 or 0. @@ -30,6 +34,9 @@ export const site = { repo: "2witstudios/viewswitcher", /** The Mac release must publish an asset with exactly this name for this link to resolve. */ dmgUrl: "https://github.com/2witstudios/viewswitcher/releases/latest/download/ViewSwitcher.dmg", + /** The Windows release's installer (apps/windows/scripts/build.ts, Velopack): this exact asset name. */ + windowsSetupUrl: "https://github.com/2witstudios/viewswitcher/releases/latest/download/ViewSwitcher-win-Setup.exe", + windowsAppReleased: flag("SITE_WINDOWS_APP", WINDOWS_APP_RELEASED, process.env.SITE_WINDOWS_APP), /** The Mac app's current release. Update with each release: the version that /download and the structured data state. */ mac: { version: "1.2.0", minOS: "14", minOSName: "macOS 14 Sonoma" }, /** Drop the demo recording here (public/demo/viewswitcher-demo.mp4) and the hero plays it. */ diff --git a/apps/web/src/components/AgentSheet.tsx b/apps/web/src/components/AgentSheet.tsx index a4db2cc..fb831f9 100644 --- a/apps/web/src/components/AgentSheet.tsx +++ b/apps/web/src/components/AgentSheet.tsx @@ -1,14 +1,14 @@ // Edit with AI: connect the agent people already use, see whether one is connected, // and choose what agents may put on air. Opened from the header, "ask your agent" hints, and the Mac // app's Edit with AI… menu item (/?ai or #ai). -import type { AgentClients, AgentOnAir } from "@viewswitcher/shared"; +import { type AgentClients, type AgentOnAir, hostName } from "@viewswitcher/shared"; import { type ReactNode, useEffect, useReducer, useRef, useState, useSyncExternalStore } from "react"; import { type AgentInfo, api, copy, MCPB_URL } from "../lib/api"; import { agentStatusText, codexToml, CONNECTED_FOR_MS, cursorDeeplink, DEFAULT_CLAUDE_CODE, defaultStdio, mcpUrl, inOrder, ON_AIR_CHOICES, ON_AIR_SCOPE, otherPortNote, pendingChoice, shownChoice, SETUP_GUIDE_URL, sheetParts, type Way, waysIn, wantsAgentSheet, withoutAgentSheet, } from "../lib/agent"; -import { clientKind } from "../lib/client-kind"; +import { clientKind, inDesktopApp } from "../lib/client-kind"; import { useLive } from "../lib/live"; import { Overlay, toast } from "./ui"; import { trapTab } from "../lib/modal"; @@ -49,7 +49,7 @@ export const SparkleIcon = () => ( /** One settings request at a time, in the order they're made (lib/agent.ts inOrder). */ const settingsInOrder = inOrder(); const kind = typeof navigator !== "undefined" ? clientKind(navigator.userAgent) : "browser"; -const inMacApp = kind === "mac"; +const inApp = inDesktopApp(kind); export function AgentSheet() { const isOpen = useSyncExternalStore((l) => (listeners.add(l), () => listeners.delete(l)), () => open); @@ -58,9 +58,11 @@ export function AgentSheet() { function Sheet({ onClose }: { onClose: () => void }) { const agent = useLive((l) => l.state?.agent); + /** "Mac" or "PC": the computer the server runs on (LiveState.host). */ + const computer = hostName(useLive((l) => l.state?.host)); const parts = sheetParts(kind); const [now, setNow] = useState(Date.now); - // undefined while asking; null when this isn't the Mac running ViewSwitcher (another machine). + // undefined while asking; null when this isn't the computer running ViewSwitcher (another machine). const [info, setInfo] = useState(undefined); const [clients, setClients] = useState(null); @@ -128,8 +130,8 @@ function Sheet({ onClose }: { onClose: () => void }) {

{agentStatusText(agent, now)}

Connect the AI agent you already use. It reads your library, adds template sets, makes views from your templates and edits them, looks at each one rendered in OBS and fixes what it sees.

- {parts.connectOnMac &&

Connect an agent on your Mac: open Edit with AI there.

} - {parts.waysIn && } + {parts.connectOnMac &&

Connect an agent on your {computer}: open Edit with AI there.

} + {parts.waysIn && } {parts.onAirSetting && (
@@ -154,7 +156,7 @@ function Sheet({ onClose }: { onClose: () => void }) { ); } -/** `pending`: the text isn't known yet (this Mac's details are still on their way): shown as such, not copyable. */ +/** `pending`: the text isn't known yet (this computer's details are still on their way): shown as such, not copyable. */ function Copyable({ label, text, multiline = false, pending = false }: { label: string; text: string; multiline?: boolean; pending?: boolean }) { return (
@@ -166,7 +168,8 @@ function Copyable({ label, text, multiline = false, pending = false }: { label: const TITLES: Record = { "claude-code": "Claude Code", "claude-desktop": "Claude Desktop", cursor: "Cursor", others: "Codex, VS Code and other agents" }; -function WaysIn({ info, clients }: { info: AgentInfo | null | undefined; clients: AgentClients | null }) { +function WaysIn({ info, clients, computer }: { info: AgentInfo | null | undefined; clients: AgentClients | null; computer: string }) { + const windows = computer === "PC"; const port = info?.port ?? (location.port || 7420); const url = mcpUrl(port); const elsewhere = info === null; @@ -178,17 +181,17 @@ function WaysIn({ info, clients }: { info: AgentInfo | null | undefined; clients case "claude-code": return ( <> -

In Terminal, start Claude Code in your library folder. The library's .mcp.json connects it to ViewSwitcher; the first time, Claude Code asks you once to allow the viewswitcher server.

+

In {windows ? "Windows Terminal (PowerShell)" : "Terminal"}, start Claude Code in your library folder. The library's .mcp.json connects it to ViewSwitcher; the first time, Claude Code asks you once to allow the viewswitcher server.

{portNote &&

{portNote}

} ); case "claude-desktop": return elsewhere ? ( -

Open Edit with AI on the Mac that runs ViewSwitcher to add it there.

+

Open Edit with AI on the {computer} that runs ViewSwitcher to add it there.

) : ( <> -

Adds ViewSwitcher to Claude Desktop as an extension made for this Mac. {inMacApp ? "Claude Desktop opens and asks you to install it." : "Open the downloaded file and Claude Desktop asks you to install it."}

+

Adds ViewSwitcher to Claude Desktop as an extension made for this {computer}. {inApp ? "Claude Desktop opens and asks you to install it." : "Open the downloaded file and Claude Desktop asks you to install it."}

@@ -206,10 +209,10 @@ function WaysIn({ info, clients }: { info: AgentInfo | null | undefined; clients case "others": return ( <> -

Any MCP client on this Mac: the Streamable HTTP address, or the stdio command.

+

Any MCP client on this {computer}: the Streamable HTTP address, or the stdio command.

-

Codex: add this to ~/.codex/config.toml.

+

Codex: add this to {windows ? "%USERPROFILE%\\.codex\\config.toml" : "~/.codex/config.toml"}.

); @@ -218,10 +221,10 @@ function WaysIn({ info, clients }: { info: AgentInfo | null | undefined; clients return (
- {elsewhere &&

These connect an agent on the Mac that runs ViewSwitcher; the switcher only lets agents in from that Mac.

} + {elsewhere &&

These connect an agent on the {computer} that runs ViewSwitcher; the switcher only lets agents in from that {computer}.

} {waysIn(clients).map(({ way, installed }) => (
-

{TITLES[way]}{installed && On this Mac}

+

{TITLES[way]}{installed && On this {computer}}

{body(way)}
))} diff --git a/apps/web/src/lib/client-kind.test.ts b/apps/web/src/lib/client-kind.test.ts index 2b4422d..9f92d42 100644 --- a/apps/web/src/lib/client-kind.test.ts +++ b/apps/web/src/lib/client-kind.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { clientKind, connectorUrl } from "./client-kind"; +import { clientKind, connectorUrl, inDesktopApp } from "./client-kind"; const SAFARI_IPAD = "Mozilla/5.0 (iPad; CPU OS 18_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"; const CHROME = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"; @@ -15,6 +15,14 @@ describe("clientKind", () => { // Electron's default UA names the app; even unpatched it must not read as the iPad. expect(clientKind("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) ViewSwitcher/0.1.0 Chrome/142.0.0.0 Electron/39.0.0 Safari/537.36")).toBe("browser"); }); + test("the Windows app's window is the desktop app, not the iPad app", () => { + const EDGE = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/158.0.0.0 Safari/537.36 Edg/158.0.0.0"; + expect(clientKind(`${EDGE} ViewSwitcher-Windows/1.0.0`)).toBe("windows"); + expect(inDesktopApp(clientKind(`${EDGE} ViewSwitcher-Windows/1.0.0`))).toBe(true); + expect(inDesktopApp(clientKind(`${CHROME} ViewSwitcher-Mac/0.1.0`))).toBe(true); + expect(inDesktopApp(clientKind(EDGE))).toBe(false); + expect(clientKind(EDGE)).toBe("browser"); + }); test("browsers", () => { expect(clientKind(CHROME)).toBe("browser"); expect(clientKind(SAFARI_IPAD)).toBe("browser"); diff --git a/apps/web/src/lib/client-kind.ts b/apps/web/src/lib/client-kind.ts index 3a47ae3..9414c8b 100644 --- a/apps/web/src/lib/client-kind.ts +++ b/apps/web/src/lib/client-kind.ts @@ -3,17 +3,21 @@ // The iPad app appends "ViewSwitcher-iPad" (the native app, apps/apple, adds "/"; the // Capacitor build before it added nothing); builds before the Mac app appended plain "ViewSwitcher" // at the very end, so that still counts until every iPad is redeployed. The Mac app sends -// "ViewSwitcher-Mac/", so its window is never mistaken for the iPad and never bounces to the -// iPad connector. +// "ViewSwitcher-Mac/" and the Windows app "ViewSwitcher-Windows/", so neither +// window is ever mistaken for the iPad and bounced to the iPad connector. -export type ClientKind = "ipad" | "mac" | "browser"; +export type ClientKind = "ipad" | "mac" | "windows" | "browser"; export function clientKind(userAgent: string): ClientKind { if (/\bViewSwitcher-iPad\b/.test(userAgent) || /\sViewSwitcher$/.test(userAgent)) return "ipad"; if (/\bViewSwitcher-Mac\b/.test(userAgent)) return "mac"; + if (/\bViewSwitcher-Windows\b/.test(userAgent)) return "windows"; return "browser"; } +/** The switcher in ViewSwitcher's own window on the computer that runs it (the Mac or the Windows app). */ +export const inDesktopApp = (kind: ClientKind) => kind === "mac" || kind === "windows"; + /** Where the iPad app's bundled connector page lives: viewswitcher://connector/ in the native app, capacitor://localhost/ in older builds. */ export function connectorUrl(userAgent: string): string { return /\bViewSwitcher-iPad\/\d/.test(userAgent) ? "viewswitcher://connector/" : "capacitor://localhost/"; diff --git a/apps/windows/.gitignore b/apps/windows/.gitignore new file mode 100644 index 0000000..b6369f4 --- /dev/null +++ b/apps/windows/.gitignore @@ -0,0 +1,6 @@ +build/ +bin/ +obj/ +*.user +.vs/ +TestResults/ diff --git a/apps/windows/README.md b/apps/windows/README.md new file mode 100644 index 0000000..0c1cc69 --- /dev/null +++ b/apps/windows/README.md @@ -0,0 +1,92 @@ +# apps/windows: ViewSwitcher for Windows + +The Windows app: a native WinUI 3 shell (Windows App SDK, unpackaged and self-contained, .NET 10) around +the same server the Mac app bundles, compiled with `bun build --compile --target=bun-windows-x64`, and +the switcher in WebView2. It mirrors `apps/apple`'s Mac app; Kit's logic is ported one for one into +`ViewSwitcher.Core`. + +| project | what | +|---|---| +| `ViewSwitcher.Core` | The Kit port, no UI: live state, the tray's text and menu, server states and restart policy, the supervisor and controller, the typed API, the navigation policy, pairing text, the page's shell script. | +| `ViewSwitcher.Core.Tests` | Kit's tests, ported to xUnit. The controller and supervisor tests start Bun stub servers for real (skipped without bun). | +| `ViewSwitcher.Windows` | The app: `ViewSwitcher.exe` (code-only WinUI: no XAML pages). | +| `scripts/` | `payload.ts` (the server and its resources), `build.ts` (the app and its Velopack release), `dev.ts`, `e2e.ts`, `icons.ts`. | + +## Prerequisites + +- Windows 10 (1809) or 11 with the WebView2 Runtime (built into Windows 11). +- The .NET 10 SDK (`winget install Microsoft.DotNet.SDK.10`), and the pinned Bun (`.bun-version`). +- For a release: `dotnet tool install -g vpk` (Velopack). + +## Commands (from the repo root) + +```sh +bun run win:dev # Debug app against the server in this checkout (attaches to whatever answers on PORT, e.g. `bun run dev`) +bun run win:test # ViewSwitcher.Core.Tests +bun run win:build --app # apps/windows/build/app: ViewSwitcher.exe with Helpers\ and Resources\ +bun run win:build # + the Velopack release in apps/windows/build/release (ViewSwitcher-win-Setup.exe, the package, releases.win.json) +bun run win:build --arch arm64 # for ARM PCs +bun run win:e2e # drives build/app on port 7435 (E2E_PORT), OBS offline, a temp library; E2E_LAN=1 adds the Wi-Fi checks +bun run win:release [--publish] # from a clean origin/main with the pinned Bun; --publish uploads to the version's DRAFT GitHub release +bun run win:icons # Assets/*.ico from the brand mark +``` + +Never run the e2e on port 7420 (it refuses): that's the person's own ViewSwitcher. + +## The app + +- **Server** (`ServerSupervisor`, `ServerController`): as on the Mac. It attaches to a ViewSwitcher + server already on `PORT`, else starts `Helpers\viewswitcher-server.exe` and owns it, restarts it at + 0, 2 and 10 s, and gives up after a fourth crash within a minute (Restart Server in the tray). Windows + has no SIGTERM, so: + - the app holds a pipe on the server's stdin and closes it to stop it (`VIEWSWITCHER_STOP_ON_STDIN=1`, + `apps/server/src/main.ts`), ending it after 3 s if it hasn't gone; + - the server runs in a kill-on-close Job Object, so it never outlives the app, even one ended from + Task Manager. `VIEWSWITCHER_PARENT_PID` still makes it watch the app as well. + - Refused connections to 127.0.0.1 fail at once (`Loopback.cs`: no SYN retries), since Windows + otherwise takes 2 s to say nothing is listening. +- **Log**: `%LOCALAPPDATA%\ViewSwitcher\Logs\server.log` (a development build's `server-dev.log`), + restarted past 5 MB. Settings: `%APPDATA%\ViewSwitcher\App\settings.json`, beside the server's + state for this PC (`%APPDATA%\ViewSwitcher\libraries\…`). The web view's data: + `%LOCALAPPDATA%\ViewSwitcher\WebView2`. +- **Window** (`SwitcherWindow.cs`): WebView2 on `http://127.0.0.1:7420/`, user agent + `ViewSwitcher-Windows/` (the switcher reads it as the desktop app, + `apps/web/src/lib/client-kind.ts`). + - The main frame stays on the server. Other web pages open in the browser, Cursor's MCP install link + only from the switcher's own page, other schemes are refused, and nothing opens a second window. + - No permissions (camera, microphone, …) and no downloads, except Edit with AI's Claude Desktop + extension, which is saved to Downloads and opened. + - No host objects and no web messages: the page has no way to call into the app (scenes are untrusted). + - A failed load is tried again on the same page. Closing the window hides it; the server keeps serving. + - The system title bar, in the switcher's graphite (`data-shell="windows"`, no insets). +- **Tray** (`Tray.cs`): the brand mark, red while something is on air, the on-air line as its tooltip, + and the status menu (`StatusMenu.Items`). A left click opens the window. +- **Phones and Tablets** (`RemotesWindow.cs`): + - The Wi-Fi setting, a one-time code with its QR code, the addresses, and the paired devices. + - mDNS (`DnsServiceRegister`) announces "ViewSwitcher" `_http._tcp` while Wi-Fi is on. + - Windows lets phones in only through the firewall and only on a private network. The window checks + both (`netsh`, `Get-NetConnectionProfile`). **Set Up Windows for Phones…** asks once through + Windows' admin prompt to add the rule ("ViewSwitcher (phones and tablets)": the server, private + networks, the port) and to make the Wi-Fi private. +- **Toasts, one instance, Open at Login**: Windows App SDK notifications (tag `server`, so a new one + replaces the last); `AppInstance` redirects a second launch to the first; the per-user `Run` key + (`--login` starts in the tray). +- **Updates** (`Updates.cs`): Velopack from GitHub Releases (`releases.win.json`). Checked at launch + and every 6 hours, applied when the person says so. Not in a development build, the e2e, or with + `VIEWSWITCHER_UPDATES=0`. +- **E2E** (`E2E.cs`): with `VIEWSWITCHER_E2E_DIR`, the app writes `app.json` (state, server pid, the + tray's menu, what it opened or notified) and runs `cmd-N.json` commands. Its windows never take the + foreground. + +USB-C to an iPhone or iPad isn't on Windows yet (ISSUE-39: Apple's usbmuxd is Apple Mobile Device +Service on TCP 27015 there). Phones and tablets connect over the Wi-Fi. + +## Release + +`bun run win:release --publish` builds from `origin/main` with the pinned Bun, then uploads +`ViewSwitcher-win-Setup.exe`, the full package and the update feed to the draft release `v` +(the version is the Mac app's, `apps/apple/project.yml`, so both platforms ship together). + +With `WINDOWS_SIGN_PARAMS` set (signtool's arguments for the code-signing certificate, WIN-21), vpk +signs every executable and the installer. Without it the build is unsigned, and Windows SmartScreen +warns on first run ("More info → Run anyway"). diff --git a/apps/windows/ViewSwitcher.Core.Tests/LogicTests.cs b/apps/windows/ViewSwitcher.Core.Tests/LogicTests.cs new file mode 100644 index 0000000..838d130 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core.Tests/LogicTests.cs @@ -0,0 +1,324 @@ +namespace ViewSwitcher.Core.Tests; + +// The pure parts of the Kit port: the tray's text and menu, navigation, pairing text, the shell script. +// Each mirrors the Swift test it ports (MenuStatusTests, StatusMenuTests, NavigationPolicyTests, +// RemotesTests, ShellAndFeedTests). + +public class MenuStatusTests +{ + static LiveState State(string? onAir = null, bool connected = true, ObsSetup? setup = null, bool streaming = false, bool recording = false, string? auth = null, UsbStatus? usb = null) => + new(onAir is null ? null : new OnAir(onAir), new ObsStatus(connected, recording, streaming, auth), setup, usb); + + static readonly ObsSetup Ready = new(true, true, true); + + [Fact] + public void NoServer() + { + var s = MenuStatus.From(null); + Assert.Equal("Server not responding", s.OnAir); + Assert.Equal("OBS: unknown", s.Obs); + Assert.False(s.Live); + Assert.False(s.ObsReady); + } + + [Fact] + public void OnAirLabelIsTheTitleAndRedIcon() + { + var s = MenuStatus.From(State("Starting Soon", setup: Ready)); + Assert.Equal("Starting Soon", s.Title); + Assert.True(s.Live); + Assert.Equal("On air: Starting Soon", s.OnAir); + Assert.Equal("OBS: connected", s.Obs); + Assert.True(s.ObsReady); + } + + [Fact] + public void LongTitlesAreCutWithAnEllipsis() + { + var s = MenuStatus.From(State("A very long scene name for a show that runs long", setup: Ready)); + Assert.InRange(s.Title.Length, 2, MenuStatus.TitleMax); // a cut that ends in a space is trimmed + Assert.Equal("A very long scene name…", s.Title); + Assert.EndsWith("…", s.Title); + } + + [Fact] + public void ObsLines() + { + Assert.Equal("OBS: needs setup", MenuStatus.From(State(setup: new(true, false, true))).Obs); + Assert.Equal("OBS: connected · add Camera, Screen", MenuStatus.From(State(setup: Ready with { MissingDevices = ["Camera", "Screen"] })).Obs); + Assert.Equal("OBS: connected · live, recording", MenuStatus.From(State(setup: Ready, streaming: true, recording: true)).Obs); + Assert.Equal("OBS: needs a password", MenuStatus.From(State(connected: false, auth: "missing")).Obs); + Assert.Equal("OBS: refused the password", MenuStatus.From(State(connected: false, auth: "wrong")).Obs); + Assert.Equal("OBS: not connected", MenuStatus.From(State(connected: false)).Obs); + Assert.False(MenuStatus.From(State(setup: new(true, true, true, Ordered: false))).ObsReady); + } + + [Fact] + public void UsbLine() + { + Assert.Equal("iPhone or iPad: USB link off", MenuStatus.From(State()).Ipad); + Assert.Equal("iPhone: connected over USB", MenuStatus.From(State(usb: new(true, true, true, "iPhone"))).Ipad); + } + + [Fact] + public void ServerMessagesAreReadLeniently() + { + var s = ServerMessage.State($$"""{"t":"state","state":{{TestServers.StateJson}}}"""); + Assert.NotNull(s); + Assert.False(s!.Obs.Connected); + Assert.Null(ServerMessage.State("""{"t":"library:changed","paths":[]}""")); + Assert.Null(ServerMessage.State("not json")); + var later = ServerMessage.State("""{"t":"state","state":{"onAir":{"label":"BRB","path":"x"},"obs":{"connected":true,"streaming":true,"newField":1},"somethingNew":[1,2]}}"""); + Assert.Equal("BRB", later!.OnAir!.Label); + Assert.True(later.ObsLive); + } +} + +public class StatusMenuTests +{ + static StatusMenu.Context Ctx(ServerState server, MenuStatus? status = null, bool obs = true, bool wifi = false, bool usb = false) => + new(status ?? MenuStatus.From(new LiveState(null, new ObsStatus(obs), new ObsSetup(true, true, true))), server, obs, wifi, Updater: true, OpenAtLogin: false, Usb: usb); + + static List Titles(StatusMenu.Context c) => StatusMenu.Items(c).Select(i => i.Title).ToList(); + + static StatusMenu.ActionItem Find(StatusMenu.Context c, StatusMenu.Action a) => StatusMenu.Items(c).OfType().Single(i => i.Action == a); + + [Fact] + public void OwnedServerOffersEverything() + { + var c = Ctx(ServerState.Owned, wifi: true); + var titles = Titles(c); + Assert.Equal(["Nothing on air", "OBS: connected", null, "Open ViewSwitcher", "Edit with AI…", "Open in Browser", "Open Library Folder", "Set Up OBS Again", null, StatusMenu.WifiTitle, "Phones and Tablets…", null, "Check for Updates…", "Open at Login", "Show Server Log", null, "Quit ViewSwitcher"], titles); + Assert.True(Find(c, StatusMenu.Action.ToggleWifi).Checked); + Assert.Equal(RemoteText.Help, Find(c, StatusMenu.Action.ToggleWifi).ToolTip); + } + + [Fact] + public void TheUsbLineOnlyWhereThereIsAUsbLink() + { + Assert.DoesNotContain("iPhone or iPad: USB link off", Titles(Ctx(ServerState.Owned))); + Assert.Contains("iPhone or iPad: USB link off", Titles(Ctx(ServerState.Owned, usb: true))); + } + + [Fact] + public void AttachedServerKeepsRunningOnQuitAndHasNoPairing() + { + var c = Ctx(ServerState.Attached); + Assert.Equal("Quit ViewSwitcher (server keeps running)", Titles(c).Last()); + Assert.False(Find(c, StatusMenu.Action.ToggleWifi).Enabled); + Assert.False(Find(c, StatusMenu.Action.OpenRemotes).Enabled); + Assert.True(Find(c, StatusMenu.Action.OpenInBrowser).Enabled); + } + + [Fact] + public void WhileTheServerIsDownItsLineLeadsAndRestartIsOffered() + { + var crashed = Ctx(ServerState.Crashed(1), MenuStatus.From(null), obs: false); + Assert.Equal("Server keeps stopping", Titles(crashed)[0]); + Assert.True(Find(crashed, StatusMenu.Action.RestartServer).Enabled); + Assert.False(Find(crashed, StatusMenu.Action.EditWithAI).Enabled); + Assert.False(Find(crashed, StatusMenu.Action.SetUpObs).Enabled); + Assert.Equal("Restarting Server…", Find(Ctx(ServerState.Restarting(1, 1)), StatusMenu.Action.RestartServer).Text); + Assert.False(Find(Ctx(ServerState.Starting), StatusMenu.Action.RestartServer).Enabled); + Assert.Equal("Server stopped again: restarting…", StatusMenu.ServerLine(ServerState.Restarting(2, 1))); + Assert.DoesNotContain(StatusMenu.Items(Ctx(ServerState.Owned)), i => i is StatusMenu.ActionItem { Action: StatusMenu.Action.RestartServer }); + } + + [Fact] + public void SetUpObsNeedsObsConnected() + { + Assert.False(Find(Ctx(ServerState.Owned, obs: false), StatusMenu.Action.SetUpObs).Enabled); + var notReady = MenuStatus.From(new LiveState(null, new ObsStatus(true), new ObsSetup(false, false, false))); + Assert.Equal("Set Up OBS…", Find(Ctx(ServerState.Owned, notReady), StatusMenu.Action.SetUpObs).Text); + } +} + +public class RestartPolicyTests +{ + [Fact] + public void ZeroThenTwoThenTenThenStop() + { + var p = RestartPolicy.Standard; + Assert.Equal(TimeSpan.Zero, p.Delay(1)); + Assert.Equal(TimeSpan.FromSeconds(2), p.Delay(2)); + Assert.Equal(TimeSpan.FromSeconds(10), p.Delay(3)); + Assert.Null(p.Delay(4)); + Assert.Null(p.Delay(0)); + } + + [Fact] + public void OldCrashesDontCount() + { + var now = DateTime.UtcNow; + Assert.Single(RestartPolicy.Standard.Recent([now.AddSeconds(-61), now.AddSeconds(-5)], now)); + } +} + +public class NavigationPolicyTests +{ + static readonly Uri Server = new("http://127.0.0.1:7420/"); + static Uri U(string s) => new(s); + + [Fact] + public void TheMainFrameStaysOnTheServer() + { + Assert.Equal(NavigationKind.Allow, NavigationPolicy.Window(U("http://127.0.0.1:7420/editor?x"), Server, mainFrame: true).Kind); + Assert.Equal(NavigationKind.Allow, NavigationPolicy.Window(U("about:blank"), Server, true).Kind); + var away = NavigationPolicy.Window(U("https://viewswitcher.com/ai"), Server, true); + Assert.Equal(NavigationKind.OpenInBrowser, away.Kind); + Assert.Equal(U("https://viewswitcher.com/ai"), away.Url); + Assert.Equal(NavigationKind.OpenInBrowser, NavigationPolicy.Window(U("http://127.0.0.1:7421/"), Server, true).Kind); // another port is another site + Assert.Equal(NavigationKind.OpenInBrowser, NavigationPolicy.Window(U("http://localhost:7420/"), Server, true).Kind); + } + + [Fact] + public void OtherSchemesAreRefused() + { + foreach (var s in new[] { @"file:///C:/Windows/win.ini", "ms-settings:privacy", "javascript:alert(1)", "vscode://file/x", "cursor://anysphere.cursor-deeplink/mcp/install?name=x" }) + Assert.Equal(NavigationKind.Deny, NavigationPolicy.Window(U(s), Server, true).Kind); + } + + [Fact] + public void CursorsInstallOnlyFromTheSwitchersOwnPage() + { + var link = U("cursor://anysphere.cursor-deeplink/mcp/install?name=viewswitcher&config=e30"); + Assert.Equal(NavigationKind.OpenInBrowser, NavigationPolicy.Window(link, Server, true, fromSwitcher: true).Kind); + Assert.True(NavigationPolicy.StartedBySwitcher(U("http://127.0.0.1:7420/"), true, Server)); + Assert.False(NavigationPolicy.StartedBySwitcher(U("http://127.0.0.1:7420/library/daisy/templates/brb.html"), true, Server)); + Assert.False(NavigationPolicy.StartedBySwitcher(U("http://127.0.0.1:7420/"), false, Server)); + Assert.False(NavigationPolicy.IsCursorInstall(U("cursor://anysphere.cursor-deeplink/other"))); + } + + [Fact] + public void NewWindowsNeverOpenInside() + { + Assert.Equal(NavigationKind.OpenInBrowser, NavigationPolicy.Window(U("http://127.0.0.1:7420/program"), Server, true, newWindow: true).Kind); + Assert.Equal(NavigationKind.Deny, NavigationPolicy.Window(U("file:///C:/x"), Server, true, newWindow: true).Kind); + } + + [Fact] + public void FramesLoadWebAndDataButNoAppSchemes() + { + Assert.Equal(NavigationKind.Allow, NavigationPolicy.Window(U("http://127.0.0.1:7420/library/a/b.html"), Server, mainFrame: false).Kind); + Assert.Equal(NavigationKind.Allow, NavigationPolicy.Window(U("data:text/html,x"), Server, false).Kind); + Assert.Equal(NavigationKind.Deny, NavigationPolicy.Window(U("file:///C:/x"), Server, false).Kind); + } + + [Fact] + public void TheExtensionIsTheOneDownload() + { + Assert.True(NavigationPolicy.IsExtensionDownload(U("http://127.0.0.1:7420/api/agent/viewswitcher.mcpb"), Server)); + Assert.False(NavigationPolicy.IsExtensionDownload(U("http://127.0.0.1:7420/library/daisy/assets/x.zip"), Server)); + Assert.False(NavigationPolicy.IsExtensionDownload(U("http://evil.example/api/agent/viewswitcher.mcpb"), Server)); + } + + [Fact] + public void RetryKeepsThePage() + { + Assert.Equal(U("http://127.0.0.1:7420/editor?path=x"), NavigationPolicy.RetryTarget(U("http://127.0.0.1:7420/editor?path=x"), null, Server)); + Assert.Equal(U("http://127.0.0.1:7420/streams"), NavigationPolicy.RetryTarget(U("https://elsewhere.example/"), U("http://127.0.0.1:7420/streams"), Server)); + Assert.Equal(U("http://127.0.0.1:7420/"), NavigationPolicy.RetryTarget(null, null, Server)); + } +} + +public class RemoteTextTests +{ + [Fact] + public void CodesAreReadInTwoHalves() => Assert.Equal("K7PQ-2MXA", RemoteText.Code("K7PQ2MXA")); + + [Fact] + public void Expiry() + { + var now = DateTimeOffset.FromUnixTimeSeconds(1_000_000); + Assert.Equal("Expires in 4:59", RemoteText.Expiry((1_000_000 + 299) * 1000.0, now)); + Assert.Equal("Expires in 5:00", RemoteText.Expiry((1_000_000 + 400) * 1000.0, now)); // never more than a code lives + Assert.Equal("Expired", RemoteText.Expiry((1_000_000 - 1) * 1000.0, now)); + } + + [Fact] + public void LastSeen() + { + var now = DateTimeOffset.FromUnixTimeSeconds(10_000_000); + RemoteDevice D(double agoSeconds, int connected = 0) => new("d", "Phone", 0, (10_000_000 - agoSeconds) * 1000, connected); + Assert.Equal("Connected now", RemoteText.LastSeen(D(5000, 1), now)); + Assert.Equal("Seen just now", RemoteText.LastSeen(D(10), now)); + Assert.Equal("Seen 3 min ago", RemoteText.LastSeen(D(200), now)); + Assert.Equal("Seen 2 h ago", RemoteText.LastSeen(D(7300), now)); + Assert.Equal("Seen 1 day ago", RemoteText.LastSeen(D(90_000), now)); + Assert.Equal("Seen 3 days ago", RemoteText.LastSeen(D(3 * 86_400 + 5), now)); + } +} + +public class ShellInfoTests +{ + [Fact] + public void TheScriptCarriesTheKindAndAQuotedNotice() + { + var info = new ShellInfo("It's \"restarting\" "); + var json = info.ToJson(); + Assert.Contains("\"kind\":\"windows\"", json); + Assert.DoesNotContain("", json); // System.Text.Json escapes < and > + var script = info.UserScript(); + Assert.Contains(json, script); + Assert.Contains("window.top !== window", script); + Assert.DoesNotContain("postMessage", script); // the page has no way to talk to the app + Assert.Equal($"window.viewswitcherShell && window.viewswitcherShell.apply({json});", info.ApplyScript()); + Assert.Contains("\"notice\":null", new ShellInfo().ToJson()); + } +} + +public class ServerInfoTests +{ + [Fact] + public void AnOrphanIsTheAppsOwnServerWhoseAppIsGone() + { + var info = new ServerInfo("C:\\lib", 7420, Sidecar: true, ParentPid: 100, Pid: 200); + Assert.True(info.IsOrphan(ownPid: 300, isAlive: _ => false)); + Assert.False(info.IsOrphan(300, _ => true)); + Assert.False(info.IsOrphan(100, _ => false)); // its parent is this app + Assert.False((info with { Sidecar = false }).IsOrphan(300, _ => false)); + Assert.False((info with { Pid = null }).IsOrphan(300, _ => false)); + } +} + +public class ServerLogTests +{ + [Fact] + public void OneLogPerBuild() + { + Assert.Equal(Path.Combine("L", "ViewSwitcher", "Logs", "server.log"), ServerLog.File("L", dev: false, null)); + Assert.Equal(Path.Combine("L", "ViewSwitcher", "Logs", "server-dev.log"), ServerLog.File("L", dev: true, null)); + Assert.Equal(Path.Combine("E", "server.log"), ServerLog.File("L", dev: false, "E")); + } + + [Fact] + public void ALongLogStartsOver() + { + var dir = TestServers.TempDir(); + var file = Path.Combine(dir, "logs", "server.log"); + ServerLog.Cap(file, max: 10); + Assert.True(Directory.Exists(Path.Combine(dir, "logs"))); + File.WriteAllText(file, "short"); + ServerLog.Cap(file, max: 10); + Assert.Equal("short", File.ReadAllText(file)); + File.WriteAllText(file, new string('x', 50)); + ServerLog.Cap(file, max: 10); + Assert.Equal("", File.ReadAllText(file)); + } +} + +public class AppSettingsTests +{ + [Fact] + public void RemembersWifiAndTheWindow() + { + var file = Path.Combine(TestServers.TempDir(), "App", "settings.json"); + Assert.False(AppSettings.Load(file).WifiRemotes); // off by default + new AppSettings { WifiRemotes = true, Window = new(10, 20, 1440, 900, false) }.Save(file); + var s = AppSettings.Load(file); + Assert.True(s.WifiRemotes); + Assert.Equal(1440, s.Window!.Width); + File.WriteAllText(file, "{ broken"); + Assert.False(AppSettings.Load(file).WifiRemotes); + } +} diff --git a/apps/windows/ViewSwitcher.Core.Tests/ServerTests.cs b/apps/windows/ViewSwitcher.Core.Tests/ServerTests.cs new file mode 100644 index 0000000..2faf7b2 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core.Tests/ServerTests.cs @@ -0,0 +1,307 @@ +using System.Diagnostics; + +namespace ViewSwitcher.Core.Tests; + +// Kit's ServerControllerTests, ServerSupervisorTests and ServerAPITests on Windows: Bun stub servers, +// started and killed for real (skipped without bun). + +public sealed class ServerControllerTests : IDisposable +{ + readonly string tmp = TestServers.TempDir(); + readonly List started = []; + static readonly ServerConnector Fast = new(readyTimeout: TimeSpan.FromSeconds(10), slowFor: TimeSpan.FromSeconds(0.5)); + + public void Dispose() + { + foreach (var s in started) s.StopAsync().Wait(5000); + try { Directory.Delete(tmp, true); } catch (IOException) { } catch (UnauthorizedAccessException) { } + } + + async Task Connect(Uri b, Launch launch) + { + var s = await Fast.ConnectOrStart(b, () => launch, CancellationToken.None); + started.Add(s); + return s; + } + + [Fact] + public async Task ProbeTellsViewSwitcherFromOthersAndNothing() + { + using var vs = TestServers.Stub.Answering(TestServers.StateJson); + using var other = TestServers.Stub.Answering("""{"hello":"world"}"""); + using var missing = TestServers.Stub.Answering("nope", 404); + Assert.Equal(Probe.ViewSwitcher, await Fast.Probe(vs.Base, TimeSpan.FromSeconds(2))); + Assert.Equal(Probe.Other, await Fast.Probe(other.Base, TimeSpan.FromSeconds(2))); + Assert.Equal(Probe.Other, await Fast.Probe(missing.Base, TimeSpan.FromSeconds(2))); + Assert.Equal(Probe.None, await Fast.Probe(TestServers.BaseFor(TestServers.FreePort()), TimeSpan.FromSeconds(2))); + } + + [Fact] + public async Task AttachesToARunningServerAndNeverStopsIt() + { + using var vs = TestServers.Stub.Answering(TestServers.StateJson); + var s = await Fast.ConnectOrStart(vs.Base, () => throw new InvalidOperationException("must not start one"), CancellationToken.None); + Assert.False(s.Owned); + await s.StopAsync(); + Assert.Equal(Probe.ViewSwitcher, await Fast.Probe(vs.Base, TimeSpan.FromSeconds(2))); + } + + [Fact] + public async Task APortSomethingElseHoldsIsTaken() + { + using var other = TestServers.Stub.Answering("", 200); + var e = await Assert.ThrowsAsync(() => Fast.ConnectOrStart(other.Base, () => throw new InvalidOperationException(), CancellationToken.None)); + Assert.Equal(ServerErrorKind.PortTaken, e.Error.Kind); + Assert.Contains($"port {other.Base.Port}", e.Message); + } + + [SkippableFact] + public async Task StartsOwnsAndStopsThroughStdin() + { + var port = TestServers.FreePort(); + var b = TestServers.BaseFor(port); + var s = await Connect(b, TestServers.Launch(port, TestServers.Serving, tmp)); + Assert.True(s.Owned); + Assert.NotNull(s.Pid); + Assert.Equal(Probe.ViewSwitcher, await Fast.Probe(b, TimeSpan.FromSeconds(2))); + var watch = Stopwatch.StartNew(); + await s.StopAsync(); + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(2.5), $"closing stdin stopped it ({watch.Elapsed})"); // not the 3 s kill + Assert.Equal(0, s.ExitCode); + Assert.Equal(Probe.None, await Fast.Probe(b, TimeSpan.FromSeconds(2))); + Assert.Contains("stub up", File.ReadAllText(Path.Combine(tmp, "logs", "server.log"))); + } + + [SkippableFact] + public async Task AServerThatIgnoresStdinIsEndedAfterThreeSeconds() + { + var port = TestServers.FreePort(); + var deaf = $"process.stdin.resume(); Bun.serve({{ hostname: '127.0.0.1', port: Number(process.env.PORT), fetch: () => Response.json({TestServers.StateJson}) }});"; + var s = await Connect(TestServers.BaseFor(port), TestServers.Launch(port, deaf, tmp)); + var watch = Stopwatch.StartNew(); + await s.StopAsync(); + Assert.InRange(watch.Elapsed.TotalSeconds, 2.5, 8); + Assert.NotNull(s.ExitCode); + } + + [SkippableFact] + public async Task OneThatDiesWhileStartingSaysWhy() + { + var port = TestServers.FreePort(); + var e = await Assert.ThrowsAsync(() => Connect(TestServers.BaseFor(port), TestServers.Launch(port, "console.error('no library here'); process.exit(3);", tmp))); + Assert.Equal(ServerErrorKind.StartFailed, e.Error.Kind); + Assert.Contains("stopped while starting", e.Message); + Assert.Contains("no library here", e.Message); + } + + [SkippableFact] + public async Task OneThatNeverAnswersIsGivenUpOn() + { + var port = TestServers.FreePort(); + var quick = new ServerConnector(readyTimeout: TimeSpan.FromSeconds(1.5), slowFor: TimeSpan.FromSeconds(0.3)); + var e = await Assert.ThrowsAsync(() => quick.ConnectOrStart(TestServers.BaseFor(port), () => TestServers.Launch(port, $"{TestServers.StopsOnStdin} console.log('thinking'); setInterval(() => {{}}, 1000);", tmp), CancellationToken.None)); + Assert.Contains("didn't answer within 1 s", e.Message); + Assert.Contains("thinking", e.Message); + } + + [Fact] + public async Task AMissingExecutableSaysSo() + { + var port = TestServers.FreePort(); + var launch = new Launch(Path.Combine(tmp, "nope.exe"), [], new Dictionary(), Path.Combine(tmp, "logs", "server.log")); + var e = await Assert.ThrowsAsync(() => Fast.ConnectOrStart(TestServers.BaseFor(port), () => launch, CancellationToken.None)); + Assert.Contains("couldn't start", e.Message); + } + + [SkippableFact] + public async Task ACrashIsReported() + { + var port = TestServers.FreePort(); + var s = await Connect(TestServers.BaseFor(port), TestServers.Launch(port, TestServers.Serving, tmp)); + var crashed = new TaskCompletionSource(); + s.Crashed += code => crashed.TrySetResult(code); + Process.GetProcessById(s.Pid!.Value).Kill(); + Assert.Same(crashed.Task, await Task.WhenAny(crashed.Task, Task.Delay(5000))); + Assert.NotNull(s.ExitCode); + } +} + +public sealed class ServerSupervisorTests : IDisposable +{ + readonly string tmp = TestServers.TempDir(); + readonly List supervisors = []; + /// Fast enough for a test, in the same shape as the real one. + static readonly RestartPolicy Quick = new([TimeSpan.Zero, TimeSpan.FromSeconds(0.3), TimeSpan.FromSeconds(0.6)], TimeSpan.FromSeconds(60)); + + public void Dispose() + { + foreach (var s in supervisors) s.Quit()?.StopAsync().Wait(5000); + try { Directory.Delete(tmp, true); } catch (IOException) { } catch (UnauthorizedAccessException) { } + } + + (ServerSupervisor, Uri) Make(RestartPolicy? policy = null, string? script = null) + { + var port = TestServers.FreePort(); + var b = TestServers.BaseFor(port); + var launch = TestServers.Launch(port, script ?? TestServers.Serving, tmp); + var s = new ServerSupervisor(b, () => launch, new ServerConnector(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(0.5)), policy ?? Quick); + supervisors.Add(s); + return (s, b); + } + + /// Kill the running server as a crash would, and wait until the supervisor has it back (or gave up). + static async Task Crash(ServerSupervisor s) + { + if (s.Server?.Pid is not int old) return null; + Process.GetProcessById(old).Kill(); + await TestServers.Until(() => s.Server?.Pid != old); + await TestServers.Until(() => s.State == ServerState.Owned || s.State.Stopped); + return s.Server?.Pid; + } + + [SkippableFact] + public async Task StartsItsOwnServerAndStopsItOnQuit() + { + var (s, b) = Make(); + var seen = new List(); + s.Changed += (_, next) => { lock (seen) seen.Add(next); }; + await s.Start(); + Assert.Equal(ServerState.Owned, s.State); + Assert.Equal([ServerState.Owned], seen); // starting is the state it begins in + var own = s.Quit(); + Assert.Equal(ServerState.Quitting, s.State); + Assert.NotNull(own); + await own!.StopAsync(); + Assert.Equal(Probe.None, await new ServerConnector().Probe(b, TimeSpan.FromSeconds(2))); + } + + [Fact] + public async Task AttachesAndNeverStopsWhatItDidntStart() + { + using var running = TestServers.Stub.Answering(TestServers.StateJson); + var s = new ServerSupervisor(running.Base, () => throw new ServerException(ServerError.StartFailed("must not start one")), policy: Quick); + supervisors.Add(s); + await s.Start(); + Assert.Equal(ServerState.Attached, s.State); + Assert.Null(s.Quit()); + } + + [SkippableFact] + public async Task BringsACrashedServerBack() + { + var (s, b) = Make(); + var seen = new List(); + s.Changed += (_, next) => { lock (seen) seen.Add(next); }; + await s.Start(); + var first = s.Server?.Pid; + var second = await Crash(s); + Assert.Equal(ServerState.Owned, s.State); + Assert.NotNull(second); + Assert.NotEqual(first, second); + lock (seen) + { + Assert.Equal(3, seen.Count); + Assert.Equal(ServerStateKind.Restarting, seen[1].Kind); + Assert.Equal(1, seen[1].Attempt); + } + Assert.Equal(Probe.ViewSwitcher, await new ServerConnector().Probe(b, TimeSpan.FromSeconds(2))); + } + + [SkippableFact] + public async Task WaitsLongerEachTimeThenGivesUpAndRestartServerStartsAfresh() + { + var (s, _) = Make(); + var attempts = new List(); + s.Changed += (_, next) => { if (next.Kind == ServerStateKind.Restarting) lock (attempts) attempts.Add(next.Attempt); }; + await s.Start(); + for (var i = 0; i < 3; i++) await Crash(s); + Assert.Equal(ServerState.Owned, s.State); // three crashes in a minute are each restarted + Assert.Equal([1, 2, 3], attempts); + Process.GetProcessById(s.Server!.Pid!.Value).Kill(); + Assert.True(await TestServers.Until(() => s.State.Kind == ServerStateKind.Crashed), $"the fourth crash stops the restarts ({s.State})"); + Assert.Null(s.Server); + await s.Start(); + Assert.Equal(ServerState.Owned, s.State); + await Crash(s); + Assert.Equal(1, attempts.Last()); // the count started over + } + + [SkippableFact] + public async Task QuitWhileWaitingToRestartRestartsNothing() + { + var (s, b) = Make(new RestartPolicy([TimeSpan.FromSeconds(0.5)], TimeSpan.FromSeconds(60))); + await s.Start(); + Process.GetProcessById(s.Server!.Pid!.Value).Kill(); + Assert.True(await TestServers.Until(() => s.State.Kind == ServerStateKind.Restarting)); + Assert.Null(s.Quit()); + await Task.Delay(1500); + Assert.Equal(ServerState.Quitting, s.State); + Assert.Equal(Probe.None, await new ServerConnector().Probe(b, TimeSpan.FromSeconds(2))); + } + + [Fact] + public async Task APortSomeoneElseHoldsFails() + { + using var other = TestServers.Stub.Answering(""); + var s = new ServerSupervisor(other.Base, () => throw new InvalidOperationException(), new ServerConnector(slowFor: TimeSpan.FromSeconds(0.3)), Quick); + supervisors.Add(s); + await s.Start(); + Assert.Equal(ServerStateKind.Failed, s.State.Kind); + Assert.Equal(ServerErrorKind.PortTaken, s.State.Error!.Kind); + Assert.True(s.State.Stopped); + } + + [Fact] + public async Task AnAttachedServerThatGoesAwayIsLost() + { + var running = TestServers.Stub.Answering(TestServers.StateJson); + var s = new ServerSupervisor(running.Base, () => throw new InvalidOperationException(), policy: Quick); + supervisors.Add(s); + await s.Start(); + await s.CheckAttached(); + Assert.Equal(ServerState.Attached, s.State); // still answering + running.Dispose(); + await s.CheckAttached(); + Assert.Equal(ServerState.Lost, s.State); + } +} + +public sealed class ServerApiTests +{ + [Fact] + public async Task PairingCallsCarryTheSecretAndOthersDont() + { + const string status = """{"enabled":true,"port":7420,"localName":"studio.local","urls":["http://studio.local:7420/"],"code":{"code":"K7PQ2MXA","expiresAt":1},"devices":[{"id":"a","name":"Phone","pairedAt":1,"lastSeen":2,"connected":1}],"pairUrl":"http://192.168.1.5:7420/pair?c=K7PQ2MXA"}"""; + using var stub = new TestServers.Stub(r => r.Url!.AbsolutePath switch + { + "/api/remote/code" => (200, status), + "/api/remote" => (200, status), + "/api/obs/setup" => (200, """{"missing":["Camera"],"switched":false}"""), + _ => (500, """{"error":"nope"}"""), + }); + var api = new ServerApi(stub.Base, "secret"); + var s = await api.NewPairingCode(); + Assert.Equal("K7PQ2MXA", s.Code!.Code); + Assert.Equal("Phone", s.Devices[0].Name); + Assert.Equal("http://192.168.1.5:7420/pair?c=K7PQ2MXA", s.PairUrl); + await api.SetRemoteEnabled(false); + var setup = await api.SetUpObs(); + Assert.Equal(["Camera"], setup.Missing); + lock (stub.Requests) + { + Assert.Equal(("POST", "/api/remote/code", "secret"), (stub.Requests[0].Method, stub.Requests[0].Path, stub.Requests[0].Admin)); + Assert.Equal("""{"enabled":false}""", stub.Requests[1].Body); + Assert.Null(stub.Requests[2].Admin); // only the pairing calls carry it + } + var e = await Assert.ThrowsAsync(() => api.Info()); + Assert.Equal("nope", e.Message); + } + + [Fact] + public async Task AServerWithAnotherSecretSaysPairingNeedsTheAppsOwn() + { + using var stub = TestServers.Stub.Answering("""{"error":"Not found"}""", 404); + var e = await Assert.ThrowsAsync(() => new ServerApi(stub.Base, "secret").RemoteStatus()); + Assert.Equal(ServerApi.PairingNeedsOwnServer, e.Message); + } +} diff --git a/apps/windows/ViewSwitcher.Core.Tests/TestServers.cs b/apps/windows/ViewSwitcher.Core.Tests/TestServers.cs new file mode 100644 index 0000000..350e3be --- /dev/null +++ b/apps/windows/ViewSwitcher.Core.Tests/TestServers.cs @@ -0,0 +1,117 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using System.Text; + +namespace ViewSwitcher.Core.Tests; + +/// Stub servers for the controller and supervisor tests (Kit's TestServers.swift): Bun scripts started for real. +public static class TestServers +{ + public const string StateJson = """{"onAir":null,"obs":{"connected":false,"recording":false,"streaming":false},"obsSetup":null,"usb":{"enabled":false,"attached":false,"connected":false},"warnings":[]}"""; + + /// Like the real server: stops when its stdin closes (the app's stop on Windows). + public const string StopsOnStdin = "process.stdin.on('end', () => process.exit(0)); process.stdin.resume();"; + + public static readonly string Serving = $"{StopsOnStdin} Bun.serve({{ hostname: '127.0.0.1', port: Number(process.env.PORT), fetch: () => Response.json({StateJson}) }}); console.log('stub up');"; + + /// bun on PATH (or where its installer puts it), else null: those tests then skip. + public static string? Bun + { + get + { + var dirs = (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator) + .Append(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".bun", "bin")); + return dirs.Select(d => Path.Combine(d, OperatingSystem.IsWindows() ? "bun.exe" : "bun")).FirstOrDefault(File.Exists); + } + } + + public static string TempDir() + { + var d = Path.Combine(Path.GetTempPath(), "vs-win-tests-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(d); + return d; + } + + /// A port nothing listens on. + public static int FreePort() + { + var l = new TcpListener(IPAddress.Loopback, 0); + l.Start(); + var port = ((IPEndPoint)l.LocalEndpoint).Port; + l.Stop(); + return port; + } + + public static Uri BaseFor(int port) => new($"http://127.0.0.1:{port}/"); + + /// A launch of with bun on . + public static Launch Launch(int port, string script, string dir, string name = "stub.ts", Dictionary? env = null) + { + Skip.If(Bun is null, "bun isn't installed"); + var bun = Bun!; + var file = Path.Combine(dir, name); + File.WriteAllText(file, script); + var vars = new Dictionary + { + ["PORT"] = port.ToString(), + ["SystemRoot"] = Environment.GetEnvironmentVariable("SystemRoot") ?? @"C:\Windows", + ["USERPROFILE"] = Environment.GetEnvironmentVariable("USERPROFILE") ?? "", + ["TEMP"] = Path.GetTempPath(), + }; + foreach (var (k, v) in env ?? []) vars[k] = v; + return new Launch(bun, [file], vars, Path.Combine(dir, "logs", "server.log")); + } + + public static async Task Until(Func check, double seconds = 10) + { + var end = DateTime.UtcNow.AddSeconds(seconds); + while (DateTime.UtcNow < end) + { + if (check()) return true; + await Task.Delay(25); + } + return check(); + } + + /// An in-process HTTP server answering every request with . + public sealed class Stub : IDisposable + { + readonly HttpListener listener = new(); + public Uri Base { get; } + public List<(string Method, string Path, string? Admin, string Body)> Requests { get; } = []; + + public Stub(Func handler) + { + var port = FreePort(); + Base = BaseFor(port); + listener.Prefixes.Add(Base.ToString()); + listener.Start(); + _ = Task.Run(async () => + { + while (listener.IsListening) + { + HttpListenerContext c; + try { c = await listener.GetContextAsync(); } catch { return; } + var body = new StreamReader(c.Request.InputStream).ReadToEnd(); + lock (Requests) Requests.Add((c.Request.HttpMethod, c.Request.Url!.AbsolutePath, c.Request.Headers["x-viewswitcher-admin"], body)); + var (status, text) = handler(c.Request); + var bytes = Encoding.UTF8.GetBytes(text); + c.Response.StatusCode = status; + c.Response.ContentType = "application/json"; + await c.Response.OutputStream.WriteAsync(bytes); + c.Response.Close(); + } + }); + } + + public static Stub Answering(string body, int status = 200) => new(_ => (status, body)); + + public void Dispose() + { + listener.Stop(); + listener.Close(); + } + } +} + diff --git a/apps/windows/ViewSwitcher.Core.Tests/ViewSwitcher.Core.Tests.csproj b/apps/windows/ViewSwitcher.Core.Tests/ViewSwitcher.Core.Tests.csproj new file mode 100644 index 0000000..63a5903 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core.Tests/ViewSwitcher.Core.Tests.csproj @@ -0,0 +1,26 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/apps/windows/ViewSwitcher.Core/AppSettings.cs b/apps/windows/ViewSwitcher.Core/AppSettings.cs new file mode 100644 index 0000000..bbb65ef --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/AppSettings.cs @@ -0,0 +1,46 @@ +using System.Text.Json; + +namespace ViewSwitcher.Core; + +/// +/// What the Windows app remembers (the Mac app's UserDefaults): "Let phones and tablets on this Wi-Fi +/// connect" (off by default) and where the window was. One small JSON file, written whole. +/// +public sealed class AppSettings +{ + public bool WifiRemotes { get; set; } + public WindowPlacement? Window { get; set; } + + public sealed record WindowPlacement(int X, int Y, int Width, int Height, bool Maximized); + + public static AppSettings Load(string file) + { + try + { + return JsonSerializer.Deserialize(File.ReadAllText(file), Json.Options) ?? new(); + } + catch (Exception e) when (e is IOException or JsonException or UnauthorizedAccessException) + { + return new(); + } + } + + public void Save(string file) + { + Directory.CreateDirectory(Path.GetDirectoryName(file)!); + var tmp = $"{file}.{Guid.NewGuid():N}.tmp"; + File.WriteAllText(tmp, JsonSerializer.Serialize(this, Json.Options)); + File.Move(tmp, file, overwrite: true); + } +} + +/// +/// The app's own files. Settings sit beside the server's state for this computer (%APPDATA%\ViewSwitcher, +/// apps/server/src/platform-dirs.ts); the log and the web view's cache in %LOCALAPPDATA%\ViewSwitcher, +/// where the installer puts the app, and which an uninstall may clear. A development build keeps its own. +/// +public static class AppPaths +{ + public static string Settings(string appData, bool dev) => Path.Combine(appData, "ViewSwitcher", "App", dev ? "settings-dev.json" : "settings.json"); + public static string WebView(string localAppData, bool dev) => Path.Combine(localAppData, "ViewSwitcher", dev ? "WebView2-dev" : "WebView2"); +} diff --git a/apps/windows/ViewSwitcher.Core/JobObject.cs b/apps/windows/ViewSwitcher.Core/JobObject.cs new file mode 100644 index 0000000..19b7cf3 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/JobObject.cs @@ -0,0 +1,91 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +namespace ViewSwitcher.Core; + +/// +/// A Windows Job Object that ends every process in it when the app's handle to it closes: the server the +/// app starts never outlives the app, even when the app is ended from Task Manager or crashes (macOS has +/// the server watch its parent instead, apps/server/src/parent-watch.ts, which runs here too). +/// +[SupportedOSPlatform("windows")] +public sealed partial class JobObject : IDisposable +{ + readonly nint handle; + + public JobObject() + { + handle = CreateJobObjectW(0, null); + if (handle == 0) throw new Win32Exception(); + var info = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION { BasicLimitInformation = new() { LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE } }; + var size = Marshal.SizeOf(); + var ptr = Marshal.AllocHGlobal(size); + try + { + Marshal.StructureToPtr(info, ptr, false); + if (!SetInformationJobObject(handle, JobObjectExtendedLimitInformation, ptr, (uint)size)) throw new Win32Exception(); + } + finally + { + Marshal.FreeHGlobal(ptr); + } + } + + public void Add(Process p) + { + if (!AssignProcessToJobObject(handle, p.Handle)) throw new Win32Exception(); + } + + public void Dispose() => CloseHandle(handle); + + const int JobObjectExtendedLimitInformation = 9; + const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000; + + [StructLayout(LayoutKind.Sequential)] + struct JOBOBJECT_BASIC_LIMIT_INFORMATION + { + public long PerProcessUserTimeLimit; + public long PerJobUserTimeLimit; + public uint LimitFlags; + public nuint MinimumWorkingSetSize; + public nuint MaximumWorkingSetSize; + public uint ActiveProcessLimit; + public nuint Affinity; + public uint PriorityClass; + public uint SchedulingClass; + } + + [StructLayout(LayoutKind.Sequential)] + struct IO_COUNTERS + { + public ulong ReadOperationCount, WriteOperationCount, OtherOperationCount, ReadTransferCount, WriteTransferCount, OtherTransferCount; + } + + [StructLayout(LayoutKind.Sequential)] + struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION + { + public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; + public IO_COUNTERS IoInfo; + public nuint ProcessMemoryLimit; + public nuint JobMemoryLimit; + public nuint PeakProcessMemoryUsed; + public nuint PeakJobMemoryUsed; + } + + [LibraryImport("kernel32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + private static partial nint CreateJobObjectW(nint attributes, string? name); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool SetInformationJobObject(nint job, int infoClass, nint info, uint length); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool AssignProcessToJobObject(nint job, nint process); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CloseHandle(nint handle); +} diff --git a/apps/windows/ViewSwitcher.Core/LiveClient.cs b/apps/windows/ViewSwitcher.Core/LiveClient.cs new file mode 100644 index 0000000..bc472c1 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/LiveClient.cs @@ -0,0 +1,84 @@ +using System.Net.WebSockets; +using System.Text; + +namespace ViewSwitcher.Core; + +/// +/// The tray follows the live state over the server's WebSocket, like any switcher page (Kit's LiveClient): +/// every {"t":"state"} arrives through , a dropped connection through +/// (with a null state first), and it connects again every 2 s until stopped. Events are raised on the +/// context it was started on. +/// +public sealed class LiveClient(Uri baseUri) +{ + readonly Uri url = new UriBuilder(baseUri) { Scheme = "ws", Path = "/ws" }.Uri; + CancellationTokenSource? cts; + SynchronizationContext? context; + + public event Action? State; + public event Action? Closed; + + public void Start() + { + Stop(); + context = SynchronizationContext.Current; + cts = new CancellationTokenSource(); + _ = Run(cts.Token); + } + + public void Stop() + { + cts?.Cancel(); + cts = null; + } + + void Raise(Action a) + { + if (context is null) a(); + else context.Post(_ => a(), null); + } + + async Task Run(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + using (var ws = new ClientWebSocket()) + { + ws.Options.Proxy = null; + try + { + await ws.ConnectAsync(url, ct); + await Receive(ws, ct); + } + catch (Exception) when (!ct.IsCancellationRequested) { } + catch (Exception) { return; } + } + if (ct.IsCancellationRequested) return; + Raise(() => { State?.Invoke(null); Closed?.Invoke(); }); + try + { + await Task.Delay(2000, ct); + } + catch (OperationCanceledException) + { + return; + } + } + } + + async Task Receive(ClientWebSocket ws, CancellationToken ct) + { + var buffer = new byte[64 * 1024]; + var message = new MemoryStream(); + while (ws.State == WebSocketState.Open && !ct.IsCancellationRequested) + { + var r = await ws.ReceiveAsync(buffer, ct); + if (r.MessageType == WebSocketMessageType.Close) return; + message.Write(buffer, 0, r.Count); + if (!r.EndOfMessage) continue; + var text = Encoding.UTF8.GetString(message.GetBuffer(), 0, (int)message.Length); + message.SetLength(0); + if (ServerMessage.State(text) is { } state) Raise(() => State?.Invoke(state)); + } + } +} diff --git a/apps/windows/ViewSwitcher.Core/LiveState.cs b/apps/windows/ViewSwitcher.Core/LiveState.cs new file mode 100644 index 0000000..15be9f4 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/LiveState.cs @@ -0,0 +1,57 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace ViewSwitcher.Core; + +// The parts of the server's LiveState (packages/shared/src/types.ts) the Windows app reads; Kit's +// LiveState.swift. Decoding is lenient: a field the server adds later never breaks the tray. + +public sealed record OnAir(string Label); + +public sealed record ObsStatus(bool Connected, bool Recording = false, bool Streaming = false, string? Auth = null); + +public sealed record ObsSetup(bool Scene, bool Program, bool Ground, bool? Ordered = true, IReadOnlyList? MissingDevices = null) +{ + /// packages/shared obsReady: the scene and both of the switcher's own sources exist, in order. + [JsonIgnore] public bool Ready => Scene && Program && Ground && Ordered != false; + [JsonIgnore] public IReadOnlyList Missing => MissingDevices ?? []; +} + +public sealed record UsbStatus(bool Enabled, bool Attached = false, bool Connected = false, string? Device = null); + +public sealed record LiveState(OnAir? OnAir, ObsStatus Obs, ObsSetup? ObsSetup = null, UsbStatus? Usb = null) +{ + /// OBS is streaming or recording: Set Up OBS asks first. + [JsonIgnore] public bool ObsLive => Obs.Streaming || Obs.Recording; +} + +public static class Json +{ + public static readonly JsonSerializerOptions Options = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; +} + +/// A /ws message: only {"t":"state"} matters to the shell. +public static class ServerMessage +{ + public static LiveState? State(string json) + { + try + { + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("t", out var t) || t.GetString() != "state") return null; + if (!root.TryGetProperty("state", out var s) || s.ValueKind != JsonValueKind.Object) return null; + var state = s.Deserialize(Json.Options); + return state?.Obs is null ? null : state; + } + catch (JsonException) + { + return null; + } + } +} diff --git a/apps/windows/ViewSwitcher.Core/Loopback.cs b/apps/windows/ViewSwitcher.Core/Loopback.cs new file mode 100644 index 0000000..ec07355 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/Loopback.cs @@ -0,0 +1,44 @@ +using System.Net; +using System.Net.Sockets; + +namespace ViewSwitcher.Core; + +/// +/// HTTP to this computer's own server. On Windows a connection refused (nothing listening yet) is retried +/// by TCP for about 2 s before it fails, which a probe would take for a busy server. With no SYN +/// retransmissions (SIO_TCP_INITIAL_RTO) the refusal comes at once, as on macOS. Never through a proxy. +/// +public static class Loopback +{ + const int SIO_TCP_INITIAL_RTO = unchecked((int)0x98000011); + /// TCP_INITIAL_RTO_PARAMETERS: Rtt unspecified (0xFFFF), MaxSynRetransmissions none (0xFE). + static readonly byte[] NoSynRetransmissions = [0xFF, 0xFF, 0xFE, 0x00]; + + public static SocketsHttpHandler Handler() => new() + { + UseProxy = false, + PooledConnectionLifetime = TimeSpan.FromMinutes(1), + ConnectCallback = Connect, + }; + + public static HttpClient Client() => new(Handler()) { Timeout = Timeout.InfiniteTimeSpan }; + + static async ValueTask Connect(SocketsHttpConnectionContext ctx, CancellationToken ct) + { + var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + try + { + if (OperatingSystem.IsWindows()) + { + try { socket.IOControl(SIO_TCP_INITIAL_RTO, NoSynRetransmissions, null); } catch (SocketException) { } + } + await socket.ConnectAsync(ctx.DnsEndPoint, ct); + return new NetworkStream(socket, ownsSocket: true); + } + catch + { + socket.Dispose(); + throw; + } + } +} diff --git a/apps/windows/ViewSwitcher.Core/MenuStatus.cs b/apps/windows/ViewSwitcher.Core/MenuStatus.cs new file mode 100644 index 0000000..319df14 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/MenuStatus.cs @@ -0,0 +1,55 @@ +using System.Text.RegularExpressions; + +namespace ViewSwitcher.Core; + +/// What the tray icon shows: the on-air view, OBS and the USB-C link, from the live state (Kit's MenuStatus). +public sealed record MenuStatus(string Title, bool Live, string OnAir, string Obs, string Ipad, bool ObsReady) +{ + public const int TitleMax = 24; + + public static string Short(string s) + { + var chars = s.EnumerateRunes().ToArray(); + if (chars.Length <= TitleMax) return s; + var cut = string.Concat(chars.Take(TitleMax - 1).Select(r => r.ToString())); + return Regex.Replace(cut, @"\s+$", "") + "…"; + } + + /// is null while the server doesn't answer. + public static MenuStatus From(LiveState? state) + { + if (state is null) return new("", false, "Server not responding", "OBS: unknown", "iPad: unknown", false); + var label = state.OnAir?.Label ?? ""; + var setup = state.ObsSetup; + var needsSetup = state.Obs.Connected && setup is not null && !setup.Ready; + + var obs = state.Obs.Auth == "missing" ? "OBS: needs a password" : state.Obs.Auth == "wrong" ? "OBS: refused the password" : "OBS: not connected"; + if (state.Obs.Connected) + { + if (needsSetup) obs = "OBS: needs setup"; + else if (setup is not null && setup.Missing.Count > 0) obs = $"OBS: connected · add {string.Join(", ", setup.Missing)}"; + else obs = "OBS: connected"; + var outputs = new[] { state.Obs.Streaming ? "live" : null, state.Obs.Recording ? "recording" : null }.Where(o => o is not null).ToArray(); + if (outputs.Length > 0) obs += $" · {string.Join(", ", outputs)}"; + } + + string ipad; + if (state.Usb is { Enabled: true } usb) + { + var device = usb.Device ?? "iPad"; // an iPhone is named as one + ipad = usb.Connected ? $"{device}: connected over USB" : usb.Attached ? $"{device}: plugged in · open ViewSwitcher on it" : "iPhone or iPad: not plugged in"; + } + else + { + ipad = "iPhone or iPad: USB link off"; + } + + return new( + label.Length == 0 ? "" : Short(label), + state.OnAir is not null, + label.Length == 0 ? "Nothing on air" : $"On air: {label}", + obs, + ipad, + state.Obs.Connected && setup is not null && !needsSetup); + } +} diff --git a/apps/windows/ViewSwitcher.Core/NavigationPolicy.cs b/apps/windows/ViewSwitcher.Core/NavigationPolicy.cs new file mode 100644 index 0000000..04cc837 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/NavigationPolicy.cs @@ -0,0 +1,71 @@ +namespace ViewSwitcher.Core; + +public enum NavigationKind { Allow, OpenInBrowser, Deny } + +/// What the web view does with a navigation (Kit's NavigationDecision). +public sealed record NavigationDecision(NavigationKind Kind, Uri? Url = null) +{ + public static readonly NavigationDecision Allow = new(NavigationKind.Allow); + public static readonly NavigationDecision Deny = new(NavigationKind.Deny); + public static NavigationDecision OpenInBrowser(Uri url) => new(NavigationKind.OpenInBrowser, url); +} + +/// Kit's NavigationPolicy, for the Windows window. Pure, so the tests cover every case. +public static class NavigationPolicy +{ + static string Scheme(Uri u) => u.Scheme.ToLowerInvariant(); + + public static bool IsWeb(Uri url) => Scheme(url) is "http" or "https"; + + static int? Port(Uri u) => u.IsDefaultPort ? (Scheme(u) == "https" ? 443 : Scheme(u) == "http" ? 80 : null) : u.Port; + + public static bool SameOrigin(Uri a, Uri b) => + Scheme(a) == Scheme(b) && string.Equals(a.Host, b.Host, StringComparison.OrdinalIgnoreCase) && Port(a) == Port(b); + + /// Edit with AI's "Add to Cursor": only Cursor's MCP install, which asks before it adds anything. + public static bool IsCursorInstall(Uri url) => + Scheme(url) == "cursor" && url.Host.Equals("anysphere.cursor-deeplink", StringComparison.OrdinalIgnoreCase) && url.AbsolutePath == "/mcp/install"; + + /// What may leave the window for another app: web pages, and Cursor's install link. + public static bool OpensOutside(Uri url) => IsWeb(url) || IsCursorInstall(url); + + /// A navigation the switcher itself started: from its own pages in the main frame, never a scene (/library/). + public static bool StartedBySwitcher(Uri? source, bool sourceMainFrame, Uri server) => + sourceMainFrame && source is not null && SameOrigin(source, server) && !source.AbsolutePath.StartsWith("/library/", StringComparison.OrdinalIgnoreCase); + + /// Edit with AI's "Add to Claude Desktop": the one download the window lets through (saved to Downloads and opened). + public static bool IsExtensionDownload(Uri url, Uri server) => SameOrigin(url, server) && url.AbsolutePath == "/api/agent/viewswitcher.mcpb"; + + /// Schemes a frame inside the page may load, never file: or app schemes. + public static bool FrameAllowed(Uri url) => Scheme(url) is "http" or "https" or "about" or "blob" or "data"; + + /// + /// The window: the main frame stays on the server; other web pages go to the browser. + /// is window.open / target=_blank, which never opens inside the app. Cursor's install link opens only + /// when . + /// + public static NavigationDecision Window(Uri url, Uri server, bool mainFrame, bool newWindow = false, bool fromSwitcher = false) + { + var outside = IsWeb(url) || (fromSwitcher && IsCursorInstall(url)); + if (newWindow) return outside ? NavigationDecision.OpenInBrowser(url) : NavigationDecision.Deny; + if (!mainFrame) return FrameAllowed(url) ? NavigationDecision.Allow : NavigationDecision.Deny; + if (SameOrigin(url, server)) return NavigationDecision.Allow; + // about:blank and the like while the page sets itself up are harmless; everything else leaves. + if (Scheme(url) == "about") return NavigationDecision.Allow; + return outside ? NavigationDecision.OpenInBrowser(url) : NavigationDecision.Deny; + } + + /// A page on the server the window may load again. + public static bool OnServer(Uri url, Uri server) => Scheme(url).StartsWith("http") && Window(url, server, true).Kind == NavigationKind.Allow; + + /// + /// What the window loads when a load failed (the server restarting) or after Restart Server: the page + /// that failed to open, else the one that was open, when it's on the server; else the root. Never the + /// root when a page can be kept, so nobody is dropped out of the editor. + /// + public static Uri RetryTarget(Uri? failed, Uri? current, Uri server) => + new[] { failed, current }.FirstOrDefault(u => u is not null && OnServer(u, server)) ?? new Uri(server, "/"); + + /// A URL string as a Uri, or null when it isn't one. + public static Uri? Parse(string? s) => Uri.TryCreate(s, UriKind.Absolute, out var u) ? u : null; +} diff --git a/apps/windows/ViewSwitcher.Core/Remotes.cs b/apps/windows/ViewSwitcher.Core/Remotes.cs new file mode 100644 index 0000000..cb2cf5e --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/Remotes.cs @@ -0,0 +1,47 @@ +namespace ViewSwitcher.Core; + +// Phones and tablets on the Wi-Fi: what the server's /api/remote says, and how the app shows it (Kit's +// Remotes.swift). The server keeps the codes and tokens (apps/server/src/pairing.ts); the app only shows +// a code, its QR code, and the paired devices. + +public sealed record RemoteDevice(string Id, string Name, double PairedAt, double LastSeen, int Connected); + +/// is only in the answer that made it: the server never sends a code again. +public sealed record PairingCode(string? Code, double ExpiresAt); + +public sealed record RemoteStatus(bool Enabled, int Port, string? LocalName, IReadOnlyList Urls, PairingCode? Code, bool? CodeGuessed, IReadOnlyList Devices, string? PairUrl = null); + +public static class RemoteText +{ + /// The setting's help text: plain HTTP on the Wi-Fi is the known limit (the Decisions page). + public const string Help = "Phones and tablets you pair can switch views from a browser. Wi-Fi traffic isn't encrypted, so use this on networks you trust, like home or church Wi-Fi."; + + public const string Guessed = "That code was cancelled after too many wrong tries. Someone on this network may be guessing; make a new code when your phone or tablet is ready."; + + /// What Windows needs for phones to reach this PC: the firewall rule, and the Wi-Fi marked private. + public const string WindowsNetwork = "Phones reach this PC over the Wi-Fi. Windows lets them in on a private network: in Settings → Network & internet → Wi-Fi, set this network to Private, and choose Allow if Windows Firewall asks about ViewSwitcher."; + + /// "K7PQ2MXA" → "K7PQ-2MXA", easier to read out and type. + public static string Code(string c) => c.Length == 8 ? $"{c[..4]}-{c[4..]}" : c; + + /// "Expires in 4:59", "Expired". + public static string Expiry(double expiresAt, DateTimeOffset? now = null) + { + var at = (now ?? DateTimeOffset.UtcNow).ToUnixTimeMilliseconds() / 1000.0; + // Never more than the 5 minutes a code lives (the two clocks round differently). + var left = Math.Min(300, (int)Math.Ceiling(expiresAt / 1000 - at)); + return left <= 0 ? "Expired" : $"Expires in {left / 60}:{left % 60:00}"; + } + + /// "Connected now", "Seen 3 min ago", "Seen 2 days ago". + public static string LastSeen(RemoteDevice d, DateTimeOffset? now = null) + { + if (d.Connected > 0) return "Connected now"; + var s = Math.Max(0, (int)((now ?? DateTimeOffset.UtcNow).ToUnixTimeMilliseconds() / 1000.0 - d.LastSeen / 1000)); + if (s < 60) return "Seen just now"; + if (s < 3600) return $"Seen {s / 60} min ago"; + if (s < 86400) return $"Seen {s / 3600} h ago"; + var days = s / 86400; + return $"Seen {days} day{(days == 1 ? "" : "s")} ago"; + } +} diff --git a/apps/windows/ViewSwitcher.Core/ServerApi.cs b/apps/windows/ViewSwitcher.Core/ServerApi.cs new file mode 100644 index 0000000..c8a2820 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/ServerApi.cs @@ -0,0 +1,141 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; + +namespace ViewSwitcher.Core; + +/// What GET /api/info answers, only to this computer itself (a mac route; gate.ts isMac). +public sealed record ServerInfo(string Library, int? Port = null, bool? Sidecar = null, int? ParentPid = null, int? Pid = null, string? ClaudeCode = null, string? Stdio = null) +{ + /// + /// A server an earlier run of the app started and then lost (a crash, an end task). The Job Object + /// usually takes it with the app; one that's still there is replaced rather than attached to. + /// + public bool IsOrphan(int ownPid, Func isAlive) => + Sidecar == true && ParentPid is int parent && parent != ownPid && Pid is not null && !isAlive(parent); +} + +public sealed record ObsSetupResult(IReadOnlyList Missing, bool Switched); + +public sealed class ServerApiException(int status, string message) : Exception(message) +{ + public int Status { get; } = status; +} + +/// The server calls the app makes, typed (Kit's ServerAPI). Every call goes to this computer's own server. +public sealed class ServerApi(Uri baseUri, string? adminToken = null, TimeSpan? timeout = null) +{ + /// One client, never through a proxy: loopback only. + static readonly HttpClient Http = Loopback.Client(); + + public Uri Base { get; } = baseUri; + readonly TimeSpan timeout = timeout ?? TimeSpan.FromSeconds(30); + + /// A server this app didn't start (bun run dev) has another secret and answers 404. + public const string PairingNeedsOwnServer = "Pairing works with the server this app starts. Quit the other ViewSwitcher server (bun run dev), then choose Restart Server."; + + public Task Info() => Get("api/info"); + public Task SetUpObs() => Post("api/obs/setup", new { }); + /// The Claude Desktop extension made for this install. + public Task AgentExtension() => Bytes("api/agent/viewswitcher.mcpb"); + + public Task RemoteStatus() => Remote("api/remote", null); + public Task SetRemoteEnabled(bool on) => Remote("api/remote", new { enabled = on }); + public Task NewPairingCode() => Remote("api/remote/code", new { }); + public Task RemoveDevice(string id) => Remote("api/remote/remove", new { id }); + + async Task Remote(string path, object? body) + { + try + { + return await Send(path, body, admin: true); + } + catch (ServerApiException e) when (e.Status == 404) + { + throw new ServerApiException(404, PairingNeedsOwnServer); + } + } + + Task Get(string path) => Send(path, null, false); + Task Post(string path, object body) => Send(path, body, false); + + async Task Send(string path, object? body, bool admin) + { + var bytes = await Call(path, body, admin); + try + { + return JsonSerializer.Deserialize(bytes, Json.Options) ?? throw new JsonException("null"); + } + catch (JsonException) + { + throw new ServerApiException(200, $"The server's answer didn't make sense ({typeof(T).Name})."); + } + } + + Task Bytes(string path) => Call(path, null, false); + + /// GET, or POST as JSON; the body of a 200, else the server's own reason. + async Task Call(string path, object? body, bool admin) + { + using var cts = new CancellationTokenSource(timeout); + using var req = new HttpRequestMessage(body is null ? HttpMethod.Get : HttpMethod.Post, new Uri(Base, path)); + req.Headers.CacheControl = new() { NoCache = true }; + if (admin && adminToken is not null) req.Headers.Add("x-viewswitcher-admin", adminToken); + // No Origin, as from the Mac app: not a page, so origin.ts lets it through (the admin calls carry the secret). + if (body is not null) req.Content = JsonContent.Create(body, options: Json.Options); + using var res = await Http.SendAsync(req, cts.Token); + var data = await res.Content.ReadAsByteArrayAsync(cts.Token); + if (res.StatusCode != HttpStatusCode.OK) + { + string? reason = null; + try + { + using var doc = JsonDocument.Parse(data); + if (doc.RootElement.TryGetProperty("error", out var e)) reason = e.GetString(); + } + catch (JsonException) { } + throw new ServerApiException((int)res.StatusCode, reason ?? $"The server said no ({(int)res.StatusCode})."); + } + return data; + } +} + +public static class Processes +{ + /// Whether a process with this pid is running. + public static bool Alive(int pid) + { + try + { + using var p = Process.GetProcessById(pid); + return !p.HasExited; + } + catch (ArgumentException) + { + return false; + } + catch (InvalidOperationException) + { + return false; + } + catch (System.ComponentModel.Win32Exception) + { + return true; // there, but not ours to look at + } + } + + /// The executable a process runs, or null when it can't be read (gone, another user's). + public static string? ExecutablePath(int pid) + { + try + { + using var p = Process.GetProcessById(pid); + return p.MainModule?.FileName; + } + catch (Exception) + { + return null; + } + } +} diff --git a/apps/windows/ViewSwitcher.Core/ServerController.cs b/apps/windows/ViewSwitcher.Core/ServerController.cs new file mode 100644 index 0000000..c04d7ce --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/ServerController.cs @@ -0,0 +1,384 @@ +using System.Diagnostics; +using System.Text; +using System.Text.Json; + +namespace ViewSwitcher.Core; + +// The ViewSwitcher server behind the Windows app (Kit's ServerController.swift): attach to one that +// already answers on the port (e.g. `bun run dev`), otherwise start the bundled one and own it. Only a +// server this app started is ever stopped, and an orphan an earlier run left behind is replaced. + +public enum Probe +{ + /// A ViewSwitcher server answers. + ViewSwitcher, + /// Something else answers on the port. + Other, + /// Something holds the port but didn't answer in time. + Slow, + /// Nothing listens. + None, +} + +/// How a server is started: the bundled one, or `bun …/apps/server/src/index.ts` from a checkout. +public sealed record Launch(string Executable, IReadOnlyList Arguments, IReadOnlyDictionary Environment, string LogFile); + +/// A server the app is using: its own (it can be stopped) or one someone else started. +public interface IServer +{ + Uri Base { get; } + bool Owned { get; } + int? Pid { get; } + /// The exit code once an owned server has exited, else null. + int? ExitCode { get; } + /// Raised (on a thread-pool thread) when an owned server exits without : a crash. + event Action? Crashed; + /// Stops the server if this app started it; returns once it has exited. + Task StopAsync(); +} + +/// Finds or starts a server (the supervisor's one dependency, so its tests can stand in for it). +public interface IServerConnector +{ + Task ConnectOrStart(Uri baseUri, Func launch, CancellationToken ct); + Task Probe(Uri baseUri, TimeSpan timeout); +} + +public static class ServerLog +{ + public const long MaxBytes = 5 * 1024 * 1024; + + /// + /// Where this build's server log goes, so builds never share one: the installed app's is + /// %LOCALAPPDATA%\ViewSwitcher\Logs\server.log, a development build's server-dev.log beside it, an + /// end-to-end run's in its own folder. + /// + public static string File(string localAppData, bool dev, string? e2eDir) + { + if (e2eDir is not null) return Path.Combine(e2eDir, "server.log"); + return Path.Combine(localAppData, "ViewSwitcher", "Logs", dev ? "server-dev.log" : "server.log"); + } + + /// Start a fresh log once it's past bytes, so it never grows forever. + public static void Cap(string file, long max = MaxBytes) + { + Directory.CreateDirectory(Path.GetDirectoryName(file)!); + try + { + if (new FileInfo(file) is { Exists: true, Length: var n } && n > max) System.IO.File.WriteAllBytes(file, []); + } + catch (IOException) { } + } +} + +/// The real connector: HTTP probes, and processes in a kill-on-close Job Object. +public sealed class ServerConnector : IServerConnector +{ + static readonly HttpClient Http = Loopback.Client(); + + /// The Job Object every started server goes in (null off Windows, or when it couldn't be made). + readonly JobObject? job = OperatingSystem.IsWindows() ? TryJob() : null; + readonly TimeSpan readyTimeout; + readonly TimeSpan slowFor; + + public ServerConnector(TimeSpan? readyTimeout = null, TimeSpan? slowFor = null) + { + this.readyTimeout = readyTimeout ?? TimeSpan.FromSeconds(20); + this.slowFor = slowFor ?? TimeSpan.FromSeconds(5); + } + + static JobObject? TryJob() + { + try + { + return OperatingSystem.IsWindows() ? new JobObject() : null; + } + catch (Exception) + { + return null; + } + } + + /// What answers at : a ViewSwitcher server, something else, or nothing. + public async Task Probe(Uri baseUri, TimeSpan timeout) + { + using var cts = new CancellationTokenSource(timeout); + try + { + using var res = await Http.GetAsync(new Uri(baseUri, "api/state"), cts.Token); + if (res.StatusCode != System.Net.HttpStatusCode.OK) return Core.Probe.Other; + var text = await res.Content.ReadAsStringAsync(cts.Token); + using var doc = JsonDocument.Parse(text); + var root = doc.RootElement; + return root.ValueKind == JsonValueKind.Object && root.TryGetProperty("obs", out _) && root.TryGetProperty("onAir", out _) ? Core.Probe.ViewSwitcher : Core.Probe.Other; + } + catch (OperationCanceledException) + { + return Core.Probe.Slow; + } + catch (JsonException) + { + return Core.Probe.Other; + } + catch (HttpRequestException e) when (e.HttpRequestError == HttpRequestError.InvalidResponse) + { + return Core.Probe.Other; + } + catch (HttpRequestException) + { + return Core.Probe.None; + } + } + + /// What answers, asking again for up to while it's slow (a busy server isn't "something else" yet). + public async Task SettledProbe(Uri baseUri, CancellationToken ct) + { + var deadline = DateTime.UtcNow + slowFor; + while (true) + { + var p = await Probe(baseUri, TimeSpan.FromSeconds(1.5)); + if (p != Core.Probe.Slow || DateTime.UtcNow >= deadline || ct.IsCancellationRequested) return p; + await Task.Delay(250, ct); + } + } + + public async Task ConnectOrStart(Uri baseUri, Func launch, CancellationToken ct) + { + var taken = new ServerException(ServerError.PortTaken(baseUri.Port.ToString())); + switch (await SettledProbe(baseUri, ct)) + { + case Core.Probe.Other or Core.Probe.Slow: throw taken; + case Core.Probe.None: return await Start(baseUri, launch(), ct); + } + ServerInfo info; + try + { + info = await new ServerApi(baseUri, timeout: TimeSpan.FromSeconds(2)).Info(); + } + catch (Exception e) when (e is HttpRequestException or ServerApiException or OperationCanceledException) + { + // It answered a moment ago but not this: ask again rather than attach to something that may be gone. + return await SettledProbe(baseUri, ct) switch + { + Core.Probe.ViewSwitcher => new AttachedServer(baseUri), + Core.Probe.None => await Start(baseUri, launch(), ct), + _ => throw taken, + }; + } + if (!info.IsOrphan(Environment.ProcessId, Processes.Alive) || info.Pid is not int pid) return new AttachedServer(baseUri); + // The pid comes from whatever answers on the port: it's only ended once it's confirmed to be this + // app's own server executable, left without its app. + var l = launch(); + if (IsLeftoverServer(pid, l.Executable)) + { + await StopOrphan(pid, baseUri, ct); + return await Start(baseUri, l, ct); + } + return await PortFrees(baseUri, TimeSpan.FromSeconds(4), ct) ? await Start(baseUri, launch(), ct) : new AttachedServer(baseUri); + } + + /// Whether runs the same executable this app launches. + static bool IsLeftoverServer(int pid, string executable) + { + var path = Processes.ExecutablePath(pid); + return path is not null && string.Equals(Path.GetFullPath(path), Path.GetFullPath(executable), StringComparison.OrdinalIgnoreCase); + } + + async Task StopOrphan(int pid, Uri baseUri, CancellationToken ct) + { + try + { + using var p = Process.GetProcessById(pid); + p.Kill(); // no stdin of ours to close: its app is gone + } + catch (Exception) { } + if (await PortFrees(baseUri, TimeSpan.FromSeconds(6), ct)) return; + throw new ServerException(ServerError.StartFailed($"A ViewSwitcher server left over from before (process {pid}) wouldn't stop. End it in Task Manager, then open ViewSwitcher again.")); + } + + async Task PortFrees(Uri baseUri, TimeSpan within, CancellationToken ct) + { + var deadline = DateTime.UtcNow + within; + while (DateTime.UtcNow < deadline && !ct.IsCancellationRequested) + { + if (await Probe(baseUri, TimeSpan.FromSeconds(0.5)) == Core.Probe.None) return true; + await Task.Delay(150, ct); + } + return false; + } + + async Task Start(Uri baseUri, Launch launch, CancellationToken ct) + { + var server = OwnedServer.Start(baseUri, launch, job); + var deadline = DateTime.UtcNow + readyTimeout; + while (DateTime.UtcNow < deadline) + { + // Quit, or a restart called off: don't leave a server starting with nobody waiting for it. + if (ct.IsCancellationRequested) + { + await server.StopAsync(); + throw new OperationCanceledException(ct); + } + if (server.ExitCode is not null) + { + await Task.Delay(100, CancellationToken.None); // let the last output land in the tail + throw new ServerException(ServerError.StartFailed($"The ViewSwitcher server stopped while starting.\n\n{server.Tail.Trim()}")); + } + if (await Probe(baseUri, TimeSpan.FromSeconds(0.5)) == Core.Probe.ViewSwitcher) return server; + await Task.Delay(150, CancellationToken.None); + } + await server.StopAsync(); + throw new ServerException(ServerError.StartFailed($"The ViewSwitcher server didn't answer within {(int)readyTimeout.TotalSeconds} s.\n\n{server.Tail.Trim()}")); + } +} + +/// A server someone else started: never stopped. +public sealed class AttachedServer(Uri baseUri) : IServer +{ + public Uri Base { get; } = baseUri; + public bool Owned => false; + public int? Pid => null; + public int? ExitCode => null; +#pragma warning disable CS0067 // never raised: an attached server isn't ours to watch + public event Action? Crashed; +#pragma warning restore CS0067 + public Task StopAsync() => Task.CompletedTask; +} + +/// +/// The app's own server process. Its stdin is a pipe the app holds; closing it is how the app stops the +/// server (Windows has no SIGTERM; apps/server/src/main.ts VIEWSWITCHER_STOP_ON_STDIN), and it's ended +/// outright 3 s later if it hasn't gone. +/// +public sealed class OwnedServer : IServer +{ + readonly Process process; + readonly object gate = new(); + readonly StreamWriter? log; + readonly StringBuilder tail = new(); + readonly TaskCompletionSource exited = new(TaskCreationOptions.RunContinuationsAsynchronously); + bool stopping; + int? exitCode; + + public Uri Base { get; } + public bool Owned => true; + public int? Pid { get; } + public int? ExitCode { get { lock (gate) return exitCode; } } + public event Action? Crashed; + public string Tail { get { lock (gate) return tail.ToString(); } } + + OwnedServer(Uri baseUri, Process process, StreamWriter? log) + { + Base = baseUri; + this.process = process; + this.log = log; + Pid = process.Id; + } + + public static OwnedServer Start(Uri baseUri, Launch launch, JobObject? job) + { + ServerLog.Cap(launch.LogFile); + StreamWriter? log = null; + try + { + log = new StreamWriter(new FileStream(launch.LogFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete)) { AutoFlush = true }; + log.WriteLine($"\n--- {DateTime.Now:O} starting {launch.Executable} {string.Join(" ", launch.Arguments)}"); + } + catch (IOException) { } + + var info = new ProcessStartInfo(launch.Executable) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + StandardOutputEncoding = Encoding.UTF8, + StandardErrorEncoding = Encoding.UTF8, + WorkingDirectory = Path.GetDirectoryName(launch.Executable) ?? Environment.CurrentDirectory, + }; + foreach (var a in launch.Arguments) info.ArgumentList.Add(a); + info.Environment.Clear(); + foreach (var (k, v) in launch.Environment) info.Environment[k] = v; + + var process = new Process { StartInfo = info, EnableRaisingEvents = true }; + try + { + process.Start(); + } + catch (Exception e) + { + log?.WriteLine(e.Message); + log?.Dispose(); + throw new ServerException(ServerError.StartFailed($"The ViewSwitcher server couldn't start.\n\n{e.Message}")); + } + if (OperatingSystem.IsWindows()) + { + try + { + job?.Add(process); + } + catch (Exception e) + { + log?.WriteLine($"--- couldn't put the server in the app's job ({e.Message}); it still exits when the app does (VIEWSWITCHER_PARENT_PID)"); + } + } + var server = new OwnedServer(baseUri, process, log); + process.OutputDataReceived += (_, e) => server.Write(e.Data); + process.ErrorDataReceived += (_, e) => server.Write(e.Data); + process.Exited += (_, _) => server.DidExit(); + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + if (process.HasExited) server.DidExit(); + return server; + } + + void Write(string? line) + { + if (line is null) return; + lock (gate) + { + try { log?.WriteLine(line); } catch (IOException) { } catch (ObjectDisposedException) { } + tail.Append(line).Append('\n'); + if (tail.Length > 2000) tail.Remove(0, tail.Length - 2000); + } + } + + void DidExit() + { + bool wasStopping; + int code; + // The last output lines, outside the lock: their handlers take it. + try { process.WaitForExit(); } catch (Exception) { } + lock (gate) + { + if (exitCode is not null) return; + code = SafeExitCode(); + exitCode = code; + wasStopping = stopping; + try { log?.WriteLine($"--- server exited ({code})"); log?.Dispose(); } catch (Exception) { } + } + exited.TrySetResult(); + if (!wasStopping) Crashed?.Invoke(code); + } + + int SafeExitCode() + { + try { return process.ExitCode; } catch (Exception) { return -1; } + } + + public async Task StopAsync() + { + lock (gate) + { + if (exitCode is not null) return; + stopping = true; + } + try { process.StandardInput.Close(); } catch (Exception) { } // the server's stop signal + if (await Task.WhenAny(exited.Task, Task.Delay(3000)) != exited.Task) + { + try { process.Kill(entireProcessTree: true); } catch (Exception) { } + await Task.WhenAny(exited.Task, Task.Delay(3000)); + } + } +} diff --git a/apps/windows/ViewSwitcher.Core/ServerState.cs b/apps/windows/ViewSwitcher.Core/ServerState.cs new file mode 100644 index 0000000..c7de4d6 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/ServerState.cs @@ -0,0 +1,72 @@ +namespace ViewSwitcher.Core; + +public enum ServerStateKind +{ + /// Launching, or Restart Server: finding a server to attach to, or starting the bundled one. + Starting, + /// The app's own server is running. + Owned, + /// A server someone else started (bun run dev) is running; the app never stops it. + Attached, + /// The app's own server exited by itself; it is being brought back. + Restarting, + /// It kept exiting, so the app stopped bringing it back: Restart Server is up to the person. + Crashed, + /// The server the app attached to went away. + Lost, + /// No server could be started (or the port is someone else's). + Failed, + /// The app is quitting. + Quitting, +} + +/// Where the app's server is in its life (Kit's ServerState): one value, so the tray, the window and Quit read the same thing. +public sealed record ServerState(ServerStateKind Kind, int Attempt = 0, int ExitCode = 0, ServerError? Error = null) +{ + public static readonly ServerState Starting = new(ServerStateKind.Starting); + public static readonly ServerState Owned = new(ServerStateKind.Owned); + public static readonly ServerState Attached = new(ServerStateKind.Attached); + public static readonly ServerState Lost = new(ServerStateKind.Lost); + public static readonly ServerState Quitting = new(ServerStateKind.Quitting); + public static ServerState Restarting(int attempt, int exitCode) => new(ServerStateKind.Restarting, attempt, exitCode); + public static ServerState Crashed(int exitCode) => new(ServerStateKind.Crashed, ExitCode: exitCode); + public static ServerState Failed(ServerError error) => new(ServerStateKind.Failed, Error: error); + + /// A server answers. + public bool Running => Kind is ServerStateKind.Owned or ServerStateKind.Attached; + + /// Nothing is running or on its way: Restart Server is what's left. + public bool Stopped => Kind is ServerStateKind.Crashed or ServerStateKind.Lost or ServerStateKind.Failed; +} + +public enum ServerErrorKind { PortTaken, StartFailed } + +public sealed record ServerError(ServerErrorKind Kind, string Detail) +{ + public static ServerError PortTaken(string port) => new(ServerErrorKind.PortTaken, port); + public static ServerError StartFailed(string why) => new(ServerErrorKind.StartFailed, why); + + public string Message => Kind == ServerErrorKind.PortTaken + ? $"Something else is using port {Detail}, so ViewSwitcher can't start its server there. Quit that app, or set PORT to another port." + : Detail; +} + +public sealed class ServerException(ServerError error) : Exception(error.Message) +{ + public ServerError Error { get; } = error; +} + +/// +/// How the app brings its server back after it exits by itself: at once, then after 2 s, then 10 s, +/// and not a fourth time within a minute (Kit's RestartPolicy). +/// +public sealed record RestartPolicy(IReadOnlyList Delays, TimeSpan Window) +{ + public static readonly RestartPolicy Standard = new([TimeSpan.Zero, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10)], TimeSpan.FromSeconds(60)); + + /// The crashes that still count at . + public List Recent(IEnumerable crashes, DateTime now) => crashes.Where(c => now - c < Window).ToList(); + + /// The wait before restarting, given the crashes that count (the latest included); null means stop. + public TimeSpan? Delay(int crashes) => crashes >= 1 && crashes <= Delays.Count ? Delays[crashes - 1] : null; +} diff --git a/apps/windows/ViewSwitcher.Core/ServerSupervisor.cs b/apps/windows/ViewSwitcher.Core/ServerSupervisor.cs new file mode 100644 index 0000000..21b74b3 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/ServerSupervisor.cs @@ -0,0 +1,137 @@ +namespace ViewSwitcher.Core; + +/// +/// Keeps the app's server running (Kit's ServerSupervisor): attaches or starts it, brings it back when it +/// exits by itself (RestartPolicy), notices when an attached one goes away, and stops it on Quit. Every +/// change of is reported through , on the context it was made on +/// (the UI thread in the app). Its methods are called from that one context. +/// +public sealed class ServerSupervisor(Uri baseUri, Func launch, IServerConnector? connector = null, RestartPolicy? policy = null, Func? clock = null) +{ + readonly IServerConnector connector = connector ?? new ServerConnector(); + readonly RestartPolicy policy = policy ?? RestartPolicy.Standard; + readonly Func now = clock ?? (() => DateTime.UtcNow); + readonly SynchronizationContext? context = SynchronizationContext.Current; + List crashes = []; + bool begun; + CancellationTokenSource? restart; + + public ServerState State { get; private set; } = ServerState.Starting; + /// The server in use while is running. + public IServer? Server { get; private set; } + /// After every change of : (before, after). + public event Action? Changed; + + /// At launch, and Restart Server. Returns once a server runs or it's clear none will. Does nothing while one runs or is on its way. + public async Task Start() + { + if (begun && !State.Stopped) return; + begun = true; + crashes = []; + await Connect(ServerState.Starting, CancellationToken.None); + } + + /// Quit: no more restarts. Returns the server to stop, if the app started it. + public IServer? Quit() + { + restart?.Cancel(); + restart = null; + var s = Server; + Server = null; + Set(ServerState.Quitting); + return s is { Owned: true } ? s : null; + } + + /// The live connection to an attached server dropped: if nothing answers any more, it's gone. + public async Task CheckAttached() + { + if (State.Kind != ServerStateKind.Attached || Server is not { } s) return; + if (await connector.Probe(baseUri, TimeSpan.FromSeconds(1.5)) == Probe.None && Server == s && State.Kind == ServerStateKind.Attached) + { + Server = null; + Set(ServerState.Lost); + } + } + + void Set(ServerState next) + { + var old = State; + if (next == old) return; + State = next; + Changed?.Invoke(old, next); + } + + /// On the supervisor's own context (a server's exit is reported on a thread-pool thread). + void OnContext(Action a) + { + if (context is null || SynchronizationContext.Current == context) a(); + else context.Post(_ => a(), null); + } + + async Task Connect(ServerState phase, CancellationToken ct) + { + Set(phase); + IServer s; + try + { + s = await connector.ConnectOrStart(baseUri, launch, ct); + } + catch (Exception e) + { + if (ct.IsCancellationRequested || State.Kind == ServerStateKind.Quitting) return; + var failure = e is ServerException se ? se.Error : ServerError.StartFailed(e.Message); + // A restart that dies while starting is one more crash; a port someone else took isn't. + if (phase.Kind == ServerStateKind.Restarting && failure.Kind == ServerErrorKind.StartFailed) Crash(phase.ExitCode); + else Set(ServerState.Failed(failure)); + return; + } + if (ct.IsCancellationRequested || State.Kind == ServerStateKind.Quitting) + { + await s.StopAsync(); // Quit came while it was starting + return; + } + Server = s; + s.Crashed += code => OnContext(() => Exited(s, code)); + Set(s.Owned ? ServerState.Owned : ServerState.Attached); + // It may have died before the handler was added. + if (s.ExitCode is int code) Exited(s, code); + } + + void Exited(IServer s, int code) + { + if (Server != s || State.Kind != ServerStateKind.Owned) return; + Server = null; + Crash(code); + } + + void Crash(int code) + { + var at = now(); + crashes = [.. policy.Recent(crashes, at), at]; + if (policy.Delay(crashes.Count) is not TimeSpan delay) + { + Set(ServerState.Crashed(code)); + return; + } + var phase = ServerState.Restarting(crashes.Count, code); + Set(phase); + var cts = new CancellationTokenSource(); + restart = cts; + // Not awaited: whoever saw the crash carries on; the restart reports through Changed. + _ = RestartAfter(delay, phase, cts.Token); + } + + async Task RestartAfter(TimeSpan delay, ServerState phase, CancellationToken ct) + { + try + { + if (delay > TimeSpan.Zero) await Task.Delay(delay, ct); + } + catch (OperationCanceledException) + { + return; + } + if (ct.IsCancellationRequested || State != phase) return; + await Connect(phase, ct); + } +} diff --git a/apps/windows/ViewSwitcher.Core/ShellInfo.cs b/apps/windows/ViewSwitcher.Core/ShellInfo.cs new file mode 100644 index 0000000..8379980 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/ShellInfo.cs @@ -0,0 +1,58 @@ +using System.Text.Json; + +namespace ViewSwitcher.Core; + +/// +/// How the Windows window tells the switcher page where it is (Kit's ShellInfo): <html data-shell="windows"> +/// and a notice banner for what the app itself has to say (its server stopped and is coming back). The +/// Windows window keeps the system title bar, so it sets no insets. The page gets no way to talk back: +/// nothing is posted from the page to the app (scenes are untrusted, AGENTS.md). +/// +public sealed record ShellInfo(string? Notice = null) +{ + public const string Kind = "windows"; + public const string NoticeId = "viewswitcher-shell-notice"; + + public string ToJson() => JsonSerializer.Serialize(new { kind = Kind, fullscreen = false, vars = new Dictionary(), notice = Notice }); + + /// Added to every document the main frame loads, before the page's own scripts. + public string UserScript() => $$""" + (() => { + if (window.top !== window) return; // the main frame only, never a scene + const notice = (text) => { + let el = document.getElementById("{{NoticeId}}"); + if (!text) { if (el) el.remove(); return; } + if (!document.body) return; + if (!el) { + el = document.createElement("div"); + el.id = "{{NoticeId}}"; + el.setAttribute("role", "status"); + Object.assign(el.style, { + position: "fixed", top: "12px", left: "50%", transform: "translateX(-50%)", + zIndex: "2147483647", maxWidth: "min(560px, 90vw)", padding: "10px 16px", borderRadius: "10px", + background: "rgba(32, 32, 36, 0.96)", color: "#fff", border: "1px solid rgba(255, 255, 255, 0.16)", + boxShadow: "0 8px 24px rgba(0, 0, 0, 0.35)", font: "500 13px/1.4 'Segoe UI Variable Text', 'Segoe UI', system-ui, sans-serif", + textAlign: "center", pointerEvents: "none", + }); + document.body.appendChild(el); + } + el.textContent = text; + }; + const apply = (s) => { + const r = document.documentElement; + if (!r) return; + r.dataset.shell = s.kind; + r.classList.toggle("shell-fullscreen", !!s.fullscreen); + for (const [k, v] of Object.entries(s.vars || {})) r.style.setProperty(k, v); + notice(s.notice); + }; + let current = {{ToJson()}}; + Object.defineProperty(window, "viewswitcherShell", { value: Object.freeze({ apply: (s) => { current = s; apply(s); } }) }); + apply(current); + document.addEventListener("DOMContentLoaded", () => apply(current)); + })(); + """; + + /// Re-applies the info in a page that's already loaded. + public string ApplyScript() => $"window.viewswitcherShell && window.viewswitcherShell.apply({ToJson()});"; +} diff --git a/apps/windows/ViewSwitcher.Core/StatusMenu.cs b/apps/windows/ViewSwitcher.Core/StatusMenu.cs new file mode 100644 index 0000000..1e6ab85 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/StatusMenu.cs @@ -0,0 +1,83 @@ +namespace ViewSwitcher.Core; + +/// The tray icon's menu, as data: what it lists for a state of the app, and what each item does (Kit's StatusMenu). +public static class StatusMenu +{ + public enum Action + { + OpenWindow, EditWithAI, OpenInBrowser, OpenLibrary, SetUpObs, + ToggleWifi, OpenRemotes, + RestartServer, CheckForUpdates, ToggleLogin, ShowLog, Quit, + } + + public abstract record Item + { + public virtual string? Title => null; + } + + /// A line of status (never clickable). + public sealed record Info(string Text) : Item + { + public override string? Title => Text; + } + + public sealed record Separator : Item; + + public sealed record ActionItem(string Text, Action Action, bool Enabled = true, bool Checked = false, string? ToolTip = null) : Item + { + public override string? Title => Text; + } + + /// What the app knows when the menu opens. : show the iPhone and iPad line (only where the server has a USB-C link). + public sealed record Context(MenuStatus Status, ServerState Server, bool ObsConnected, bool Wifi, bool Updater, bool OpenAtLogin, bool Usb = false); + + public const string WifiTitle = "Let Phones and Tablets on This Wi-Fi Connect"; + + /// The server line: what's happening to it, when that isn't simply "running". + public static string? ServerLine(ServerState s) => s.Kind switch + { + ServerStateKind.Starting => "Server: starting…", + ServerStateKind.Restarting => s.Attempt > 1 ? "Server stopped again: restarting…" : "Server stopped: restarting…", + ServerStateKind.Crashed => "Server keeps stopping", + ServerStateKind.Lost => "Server: stopped", + ServerStateKind.Failed => "Server: couldn't start", + _ => null, + }; + + public static List Items(Context c) + { + var s = c.Status; + var up = c.Server.Running; + var owned = c.Server.Kind == ServerStateKind.Owned; + var items = new List + { + // While the server is down, what happened to it takes the on-air line ("Server not responding"). + new Info(ServerLine(c.Server) ?? s.OnAir), + new Info(s.Obs), + }; + if (c.Usb) items.Add(new Info(s.Ipad)); + items.AddRange([ + new Separator(), + new ActionItem("Open ViewSwitcher", Action.OpenWindow), + new ActionItem("Edit with AI…", Action.EditWithAI, up), + new ActionItem("Open in Browser", Action.OpenInBrowser, up), + new ActionItem("Open Library Folder", Action.OpenLibrary, up), + new ActionItem(s.ObsReady ? "Set Up OBS Again" : "Set Up OBS…", Action.SetUpObs, up && c.ObsConnected), + new Separator(), + new ActionItem(WifiTitle, Action.ToggleWifi, owned, c.Wifi, RemoteText.Help), + new ActionItem("Phones and Tablets…", Action.OpenRemotes, owned), + new Separator(), + ]); + if (c.Server.Kind == ServerStateKind.Starting) items.Add(new ActionItem("Starting Server…", Action.RestartServer, false)); + else if (c.Server.Kind == ServerStateKind.Restarting) items.Add(new ActionItem("Restarting Server…", Action.RestartServer, false)); + else if (c.Server.Stopped) items.Add(new ActionItem("Restart Server", Action.RestartServer)); + items.AddRange([ + new ActionItem("Check for Updates…", Action.CheckForUpdates, c.Updater), + new ActionItem("Open at Login", Action.ToggleLogin, Checked: c.OpenAtLogin), + new ActionItem("Show Server Log", Action.ShowLog), + new Separator(), + new ActionItem(c.Server.Kind == ServerStateKind.Attached ? "Quit ViewSwitcher (server keeps running)" : "Quit ViewSwitcher", Action.Quit), + ]); + return items; + } +} diff --git a/apps/windows/ViewSwitcher.Core/ViewSwitcher.Core.csproj b/apps/windows/ViewSwitcher.Core/ViewSwitcher.Core.csproj new file mode 100644 index 0000000..ee779c3 --- /dev/null +++ b/apps/windows/ViewSwitcher.Core/ViewSwitcher.Core.csproj @@ -0,0 +1,11 @@ + + + + net10.0 + enable + enable + true + true + false + + diff --git a/apps/windows/ViewSwitcher.Windows.slnx b/apps/windows/ViewSwitcher.Windows.slnx new file mode 100644 index 0000000..58448a0 --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows.slnx @@ -0,0 +1,4 @@ + + + + diff --git a/apps/windows/ViewSwitcher.Windows/App.cs b/apps/windows/ViewSwitcher.Windows/App.cs new file mode 100644 index 0000000..448d88b --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows/App.cs @@ -0,0 +1,329 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Markup; +using ViewSwitcher.Core; + +namespace ViewSwitcher.Windows; + +/// +/// The Windows app (the Mac's AppDelegate): the server's whole life through ServerSupervisor, what the +/// person sees as it comes and goes (the tray, a notification, the window's banner), and the tray's actions. +/// +public sealed partial class App : Application, IXamlMetadataProvider +{ + // Code-only WinUI: the WinUI controls' own XAML types, which a XAML App would generate. + readonly Microsoft.UI.Xaml.XamlTypeInfo.XamlControlsXamlMetaDataProvider controls = new(); + public IXamlType GetXamlType(Type type) => controls.GetXamlType(type); + public IXamlType GetXamlType(string fullName) => controls.GetXamlType(fullName); + public XmlnsDefinition[] GetXmlnsDefinitions() => controls.GetXmlnsDefinitions(); + + public static new App Current => (App)Application.Current; + + ServerSupervisor supervisor = null!; + LiveState? live; + SwitcherWindow? switcher; + RemotesWindow? remotes; + LiveClient? liveClient; + Tray? tray; + readonly Announcer announcer = new(); + Updates? updates; + E2E? e2e; + /// The banner over the switcher, kept here so a window opened later shows it too. + (string Text, DateTime? Until)? notice; + readonly bool startHidden; + bool quitting; + + public App(bool startHidden) + { + this.startHidden = startHidden; + UnhandledException += (_, e) => + { + try { File.AppendAllText(Env.LogFile, $"\n--- app error: {e.Exception}\n"); } catch (Exception) { } + e.Handled = true; + }; + } + + public ServerSupervisor Supervisor => supervisor; + public SwitcherWindow? Switcher => switcher; + public RemotesWindow? Remotes => remotes; + public Tray? TrayIcon => tray; + + protected override async void OnLaunched(LaunchActivatedEventArgs args) + { + Resources.MergedDictionaries.Add(new Microsoft.UI.Xaml.Controls.XamlControlsResources()); + if (!Env.E2E) Notifier.Register(); + supervisor = new ServerSupervisor(Env.Base, Env.Launch); + supervisor.Changed += ServerChanged; + tray = new Tray(Perform, OpenWindow); + Render(); + if (Env.E2EDir is { } dir) e2e = new E2E(dir, this); + updates = Updates.Start(); + await supervisor.Start(); + // At launch, a server that can't start ends the app. + if (supervisor.State.Kind == ServerStateKind.Failed) + { + CouldntStart(supervisor.State.Error!, quit: true); + return; + } + // Opened at login, the app waits in the tray; otherwise the window opens. + if (!startHidden) OpenWindow(); + e2e?.Report(); + } + + /// A second launch of ViewSwitcher (Program.cs redirects it here): show the window. + public void Activated() => OpenWindow(); + + // ------------------------------------------------------------ server + + void ServerChanged(ServerState old, ServerState next) + { + switch (next.Kind) + { + case ServerStateKind.Owned or ServerStateKind.Attached: + AnnounceWifi(); + WatchState(); + if (old.Kind == ServerStateKind.Restarting) + { + Outside.Notify("ViewSwitcher server restarted", "It stopped unexpectedly and is running again.", "server"); + ShowNotice("ViewSwitcher's server stopped unexpectedly and was restarted.", TimeSpan.FromSeconds(8)); + } + else ShowNotice(null); + break; + case ServerStateKind.Restarting: + Down(); + if (next.Attempt == 1) Outside.Notify("ViewSwitcher server stopped", $"It exited ({next.ExitCode}). Restarting it now.", "server"); + ShowNotice("ViewSwitcher's server stopped. Restarting it…"); + break; + case ServerStateKind.Crashed: + Down(); + Outside.Notify("ViewSwitcher server keeps stopping", $"It exited ({next.ExitCode}) again, so it wasn't restarted. Choose Restart Server from the ViewSwitcher icon in the taskbar. Server log: {Env.LogFile}", "server"); + ShowNotice("ViewSwitcher's server keeps stopping. Choose Restart Server from the ViewSwitcher icon in the taskbar."); + break; + case ServerStateKind.Failed: + Down(); + // A restart that found the port taken; at launch and from Restart Server, the caller says why. + if (old.Kind == ServerStateKind.Restarting) + { + Outside.Notify("ViewSwitcher server stopped", next.Error!.Message, "server"); + ShowNotice("ViewSwitcher's server stopped and couldn't restart. Choose Restart Server from the ViewSwitcher icon in the taskbar."); + } + break; + case ServerStateKind.Lost: + Down(); + break; + } + Render(); + e2e?.Report(); + } + + void Down() + { + announcer.Set(false, 0); + live = null; + } + + void CouldntStart(ServerError why, bool quit) + { + var taken = why.Kind == ServerErrorKind.PortTaken; + Outside.Alert(taken ? "Port in use" : "ViewSwitcher couldn't start", why.Message + (taken ? "" : $"\n\nServer log: {Env.LogFile}"), Outside.Icon.Error); + if (quit) Quit(); + } + + async void RestartServer() + { + // A second click while one starts would race it for the port; the supervisor ignores it. + if (!supervisor.State.Stopped) return; + await supervisor.Start(); + if (supervisor.State.Kind == ServerStateKind.Failed) + { + CouldntStart(supervisor.State.Error!, quit: false); + return; + } + switcher?.ReloadCurrent(); + } + + /// The tray follows the live state over the server's WebSocket, like any switcher page. + void WatchState() + { + liveClient?.Stop(); + var client = new LiveClient(Env.Base); + client.State += state => + { + live = state; + Render(); + }; + // Attached to a server someone else started and it went away: Restart Server attaches again, or starts the bundled one. + client.Closed += async () => await supervisor.CheckAttached(); + liveClient = client; + client.Start(); + } + + void ShowNotice(string? text, TimeSpan? @for = null) + { + var until = @for is { } f ? DateTime.UtcNow + f : (DateTime?)null; + notice = text is null ? null : (text, until); + switcher?.ShowNotice(text, until); + } + + // ------------------------------------------------------------ phones and tablets + + /// mDNS follows the setting, for a server this app started (it was launched with the setting). + void AnnounceWifi() => announcer.Set(Env.Wifi && supervisor.State.Kind == ServerStateKind.Owned, int.Parse(Env.Port)); + + public void OpenRemotes() + { + if (remotes is null) + { + remotes = new RemotesWindow(); + remotes.EnabledChanged += _ => + { + AnnounceWifi(); + Render(); + }; + } + remotes.Show(); + } + + /// The tray's checkbox: the server opens or closes its Wi-Fi listener now (closing it disconnects every device). + public async Task ToggleWifi() + { + var on = !Env.Wifi; + try + { + var s = await Env.Api.SetRemoteEnabled(on); + Env.Wifi = s.Enabled; + AnnounceWifi(); + Render(); + if (remotes is not null) await remotes.Changed(s.Enabled); + // The first time it's on, Phones and Tablets shows what Windows needs (the firewall, a private network). + if (s.Enabled && remotes is not { Visible: true }) OpenRemotes(); + } + catch (Exception e) + { + Outside.Alert("Couldn't change Wi-Fi connections", e.Message); + } + } + + // ------------------------------------------------------------ window + + public void OpenWindow() + { + if (switcher is null) + { + switcher = new SwitcherWindow(Env.Base); + if (notice is { } n) switcher.ShowNotice(n.Text, n.Until); + } + switcher.Show(); + } + + void EditWithAI() + { + OpenWindow(); + switcher?.OpenAgentSheet(); + } + + // ------------------------------------------------------------ tray + + MenuStatus Status => MenuStatus.From(supervisor.State.Running ? live : null); + + StatusMenu.Context MenuContext => new(Status, supervisor.State, live?.Obs.Connected == true, Env.Wifi, updates?.Available == true, !Env.E2E && LoginItem.Enabled, Usb: live?.Usb?.Enabled == true); + + public void Render() => tray?.Render(Status, StatusMenu.Items(MenuContext)); + + public void Perform(StatusMenu.Action action) + { + switch (action) + { + case StatusMenu.Action.OpenWindow: OpenWindow(); break; + case StatusMenu.Action.EditWithAI: EditWithAI(); break; + case StatusMenu.Action.OpenInBrowser: Outside.OpenInBrowser(Env.Base); break; + case StatusMenu.Action.OpenLibrary: OpenLibrary(); break; + case StatusMenu.Action.SetUpObs: SetUpObs(); break; + case StatusMenu.Action.ToggleWifi: _ = ToggleWifi(); break; + case StatusMenu.Action.OpenRemotes: OpenRemotes(); break; + case StatusMenu.Action.RestartServer: RestartServer(); break; + case StatusMenu.Action.CheckForUpdates: updates?.Check(interactive: true); break; + case StatusMenu.Action.ToggleLogin: ToggleLogin(); break; + case StatusMenu.Action.ShowLog: ShowLog(); break; + case StatusMenu.Action.Quit: Quit(); break; + } + } + + async void OpenLibrary() + { + try + { + // One of the few answers with an absolute path in it, given only to this PC itself. + var info = await Env.Api.Info(); + Outside.OpenFolder(info.Library); + } + catch (Exception e) + { + Outside.Alert("Couldn't open the library folder", e.Message); + } + } + + /// Setup never switches OBS's scene while it's live (the server checks too), but say so before doing anything. + async void SetUpObs() + { + if (live is { ObsLive: true } l) + { + var go = Outside.Alert($"OBS is {(l.Obs.Streaming ? "streaming" : "recording")}", "Set up the ViewSwitcher scene anyway? OBS will stay on the scene it's showing now; switch to ViewSwitcher in OBS when you're ready.", okCancel: true); + if (!go) return; + } + try + { + var r = await Env.Api.SetUpObs(); + var next = r.Missing.Count == 0 ? "" : $" Add {string.Join(", ", r.Missing)} to the ViewSwitcher scene in OBS, then set up again."; + Outside.Notify("OBS is set up", (r.Switched ? "The ViewSwitcher scene is ready." : "The ViewSwitcher scene is ready; OBS stayed on its current scene.") + next); + } + catch (Exception e) + { + Outside.Alert("Couldn't set up OBS", e.Message); + } + } + + void ToggleLogin() + { + if (Env.E2E) return; + try + { + LoginItem.Enabled = !LoginItem.Enabled; + } + catch (Exception e) + { + Outside.Alert("Couldn't change Open at Login", e.Message); + } + Render(); + } + + void ShowLog() + { + // A server this app attached to writes its own log: show the logs folder rather than a file it doesn't use. + var folder = Path.GetDirectoryName(Env.LogFile)!; + Directory.CreateDirectory(folder); + if (supervisor.State.Kind == ServerStateKind.Attached) + { + Outside.OpenFolder(folder); + return; + } + ServerLog.Cap(Env.LogFile); + if (!File.Exists(Env.LogFile)) File.WriteAllText(Env.LogFile, ""); + Outside.OpenFile(Env.LogFile); + } + + /// Quit stops only a server this app started; then the app ends. + public async void Quit() + { + if (quitting) return; + quitting = true; + liveClient?.Stop(); + announcer.Stop(); + switcher?.Hide(); + var own = supervisor?.Quit(); + if (own is not null) await own.StopAsync(); + e2e?.Report(); + tray?.Dispose(); + if (!Env.E2E) Notifier.Unregister(); + Exit(); + } +} diff --git a/apps/windows/ViewSwitcher.Windows/Assets/TrayDark.ico b/apps/windows/ViewSwitcher.Windows/Assets/TrayDark.ico new file mode 100644 index 0000000..30bc110 Binary files /dev/null and b/apps/windows/ViewSwitcher.Windows/Assets/TrayDark.ico differ diff --git a/apps/windows/ViewSwitcher.Windows/Assets/TrayLight.ico b/apps/windows/ViewSwitcher.Windows/Assets/TrayLight.ico new file mode 100644 index 0000000..8154d9c Binary files /dev/null and b/apps/windows/ViewSwitcher.Windows/Assets/TrayLight.ico differ diff --git a/apps/windows/ViewSwitcher.Windows/Assets/TrayLive.ico b/apps/windows/ViewSwitcher.Windows/Assets/TrayLive.ico new file mode 100644 index 0000000..cd6dacf Binary files /dev/null and b/apps/windows/ViewSwitcher.Windows/Assets/TrayLive.ico differ diff --git a/apps/windows/ViewSwitcher.Windows/Assets/ViewSwitcher.ico b/apps/windows/ViewSwitcher.Windows/Assets/ViewSwitcher.ico new file mode 100644 index 0000000..fbec312 Binary files /dev/null and b/apps/windows/ViewSwitcher.Windows/Assets/ViewSwitcher.ico differ diff --git a/apps/windows/ViewSwitcher.Windows/E2E.cs b/apps/windows/ViewSwitcher.Windows/E2E.cs new file mode 100644 index 0000000..e1e1435 --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows/E2E.cs @@ -0,0 +1,162 @@ +using System.Text.Json; +using System.IO; +using ViewSwitcher.Core; + +namespace ViewSwitcher.Windows; + +/// +/// The end-to-end script's handle on the app (the Mac's E2E.swift), active only with VIEWSWITCHER_E2E_DIR: +/// the app writes app.json (its pid, the server's state and pid, the tray's menu, what it opened or +/// notified) after every change, and runs the commands the script drops in as cmd-N.json, answering in +/// res-N.json. +/// +public sealed class E2E +{ + readonly string dir; + readonly App app; + readonly Microsoft.UI.Dispatching.DispatcherQueueTimer timer; + int next = 1; + + public E2E(string dir, App app) + { + this.dir = dir; + this.app = app; + Directory.CreateDirectory(dir); + timer = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread().CreateTimer(); + timer.Interval = TimeSpan.FromMilliseconds(100); + timer.Tick += (_, _) => Poll(); + timer.Start(); + } + + public void Report() + { + var s = app.Supervisor; + var data = new + { + pid = Environment.ProcessId, + state = s?.State.Kind.ToString(), + attempt = s?.State.Attempt, + error = s?.State.Error?.Message, + serverPid = s?.Server?.Pid, + owned = s?.Server?.Owned, + menu = app.TrayIcon?.Items.Select(i => i switch + { + StatusMenu.ActionItem a => new { title = a.Text, enabled = a.Enabled, @checked = a.Checked }, + _ => new { title = i.Title ?? "-", enabled = false, @checked = false }, + }), + window = app.Switcher?.Visible ?? false, + userAgent = app.Switcher?.UserAgent, + remotes = app.Remotes?.Visible ?? false, + wifi = Env.Wifi, + opened = Snapshot(Outside.Opened), + alerts = Snapshot(Outside.Alerts), + notices = Snapshot(Outside.Notices), + }; + Write("app.json", JsonSerializer.Serialize(data)); + } + + static string[] Snapshot(List l) + { + lock (l) return [.. l]; + } + + void Write(string name, string text) + { + var tmp = Path.Combine(dir, $"{name}.tmp"); + try + { + File.WriteAllText(tmp, text); + File.Move(tmp, Path.Combine(dir, name), overwrite: true); + } + catch (IOException) { } + } + + void Poll() + { + Report(); + var file = Path.Combine(dir, $"cmd-{next}.json"); + if (!File.Exists(file)) return; + string cmd; + try + { + using var doc = JsonDocument.Parse(File.ReadAllText(file)); + cmd = doc.RootElement.GetProperty("cmd").GetString() ?? ""; + } + catch (Exception) + { + return; // still being written + } + var n = next++; + _ = Answer(n, cmd); + } + + async Task Answer(int n, string cmd) + { + string? result; + try + { + result = await Run(cmd); + } + catch (Exception e) + { + result = e.Message; + } + Write($"res-{n}.json", JsonSerializer.Serialize(new { ok = result is null, error = result })); + } + + async Task Run(string cmd) + { + switch (cmd) + { + case "open-window": app.OpenWindow(); return null; + case "close-window": app.Switcher?.Hide(); return null; + case "open-remotes": app.OpenRemotes(); return null; + case "toggle-wifi": await app.ToggleWifi(); return null; + case "restart-server": app.Perform(StatusMenu.Action.RestartServer); return null; + case "edit-with-ai": app.Perform(StatusMenu.Action.EditWithAI); return null; + case "quit": app.Quit(); return null; + // A pairing code, as Phones and Tablets shows it (the script pairs a pretend phone with it). + case "pair-code": + var s = await Env.Api.NewPairingCode(); + await File.WriteAllTextAsync(Path.Combine(dir, "code.txt"), s.Code?.Code ?? ""); + return null; + // Pictures of the app's own windows, without a screenshot of the desktop. + case "capture-switcher": + // The page may still be loading: a few tries. + for (var attempt = 0; ; attempt++) + { + try + { + if (app.Switcher?.Web.CoreWebView2 is not { } core) throw new InvalidOperationException("no switcher window"); + using var mem = new MemoryStream(); + await core.CapturePreviewAsync(Microsoft.Web.WebView2.Core.CoreWebView2CapturePreviewImageFormat.Png, mem.AsRandomAccessStream()); + await File.WriteAllBytesAsync(Path.Combine(dir, "switcher.png"), mem.ToArray()); + return null; + } + catch (Exception) when (attempt < 10) + { + await Task.Delay(500); + } + } + case "capture-remotes": + if (app.Remotes?.Window.Content is not Microsoft.UI.Xaml.UIElement root) return "no Phones and Tablets window"; + await Capture(root, Path.Combine(dir, "remotes.png")); + return null; + default: return $"unknown command {cmd}"; + } + } + + static async Task Capture(Microsoft.UI.Xaml.UIElement root, string file) + { + var rtb = new Microsoft.UI.Xaml.Media.Imaging.RenderTargetBitmap(); + await rtb.RenderAsync(root); + var pixels = await rtb.GetPixelsAsync(); + using var stream = new global::Windows.Storage.Streams.InMemoryRandomAccessStream(); + var encoder = await global::Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(global::Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, stream); + encoder.SetPixelData(global::Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, global::Windows.Graphics.Imaging.BitmapAlphaMode.Premultiplied, (uint)rtb.PixelWidth, (uint)rtb.PixelHeight, 96, 96, System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(pixels)); + await encoder.FlushAsync(); + stream.Seek(0); + using var f = File.Create(file); + await stream.AsStreamForRead().CopyToAsync(f); + } +} diff --git a/apps/windows/ViewSwitcher.Windows/Env.cs b/apps/windows/ViewSwitcher.Windows/Env.cs new file mode 100644 index 0000000..58f5a63 --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows/Env.cs @@ -0,0 +1,86 @@ +using System.Reflection; +using System.Security.Cryptography; +using ViewSwitcher.Core; + +namespace ViewSwitcher.Windows; + +/// Settings from the environment, read once (the Mac app's Environment.swift). +public static class Env +{ + static string? Var(string name) => Environment.GetEnvironmentVariable(name); + + public static readonly string Port = Var("PORT") is { Length: > 0 } p ? p : "7420"; + public static readonly Uri Base = new($"http://127.0.0.1:{Port}/"); + /// scripts/e2e.ts drives the app through files in this folder (E2E.cs). Unset in normal use. + public static readonly string? E2EDir = Var("VIEWSWITCHER_E2E_DIR") is { Length: > 0 } d ? d : null; + public static bool E2E => E2EDir is not null; + public static readonly bool UpdatesEnabled = Var("VIEWSWITCHER_UPDATES") != "0"; + public static readonly string Version = Assembly.GetExecutingAssembly().GetName().Version is { } v ? $"{v.Major}.{v.Minor}.{v.Build}" : "0.0.0"; + + /// The folder ViewSwitcher.exe is in: Helpers\ and Resources\ beside it in an installed or built app. + public static readonly string AppDir = AppContext.BaseDirectory; + public static readonly string Sidecar = Path.Combine(AppDir, "Helpers", "viewswitcher-server.exe"); + /// A build without the bundled server is a development build (bun run win:dev): its own settings, log and web view data. + public static readonly bool Dev = !File.Exists(Sidecar); + + static readonly string LocalAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + static readonly string AppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + public static readonly string LogFile = ServerLog.File(LocalAppData, Dev, E2EDir); + public static readonly string SettingsFile = E2EDir is not null ? Path.Combine(E2EDir, "settings.json") : AppPaths.Settings(AppData, Dev); + public static readonly string WebViewData = E2EDir is not null ? Path.Combine(E2EDir, "WebView2") : AppPaths.WebView(LocalAppData, Dev); + + /// A new secret each launch, for the pairing endpoints only this app may call (/api/remote…). It goes to the server in its environment and never leaves this PC. + public static readonly string AdminToken = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(32)); + + public static ServerApi Api => new(Base, AdminToken); + + public static AppSettings Settings { get; } = AppSettings.Load(SettingsFile); + public static void SaveSettings() + { + try { Settings.Save(SettingsFile); } catch (Exception) { } + } + + /// "Let phones and tablets on this Wi-Fi connect": off by default and remembered. + public static bool Wifi + { + get => Settings.WifiRemotes; + set { Settings.WifiRemotes = value; SaveSettings(); } + } + + /// The bundled server in a built app; `bun apps/server/src/index.ts` from a checkout (VIEWSWITCHER_REPO, set by scripts/dev.ts). + public static Launch Launch() + { + var env = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (System.Collections.DictionaryEntry e in Environment.GetEnvironmentVariables()) env[(string)e.Key] = (string?)e.Value ?? ""; + env["PORT"] = Port; + env["VIEWSWITCHER_ADMIN_TOKEN"] = AdminToken; + env["VIEWSWITCHER_LAN"] = Wifi ? "1" : "0"; + // The server exits if this app goes away without stopping it (parent-watch.ts), and stops when + // the app closes its stdin (main.ts): Windows has no SIGTERM. + env["VIEWSWITCHER_PARENT_PID"] = Environment.ProcessId.ToString(); + env["VIEWSWITCHER_STOP_ON_STDIN"] = "1"; + // The Claude Desktop extension the server makes carries the app's version. + env["VIEWSWITCHER_VERSION"] = Version; + if (!Dev) + { + var res = Path.Combine(AppDir, "Resources"); + env["VIEWSWITCHER_WEB_DIST"] = Path.Combine(res, "web"); + env["VIEWSWITCHER_STARTER"] = Path.Combine(res, "starter"); + env["VIEWSWITCHER_LIBRARY_KIT"] = Path.Combine(res, "library-kit"); + env["VIEWSWITCHER_PACKS"] = Path.Combine(res, "packs"); // the built-in template packs + return new Launch(Sidecar, Array.Empty(), env, LogFile); + } + var repo = Var("VIEWSWITCHER_REPO"); + var bun = Var("BUN") is { Length: > 0 } b ? b : Which("bun.exe"); + if (repo is null || bun is null) + throw new ServerException(ServerError.StartFailed("This build has no server inside it. Run it with bun run win:dev, or build it with bun run win:build.")); + return new Launch(bun, new[] { Path.Combine(repo, "apps", "server", "src", "index.ts") }, env, LogFile); + } + + public static string? Which(string name) + { + var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + var dirs = (Var("PATH") ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries).Append(Path.Combine(home, ".bun", "bin")); + return dirs.Select(d => Path.Combine(d, name)).FirstOrDefault(File.Exists); + } +} diff --git a/apps/windows/ViewSwitcher.Windows/Outside.cs b/apps/windows/ViewSwitcher.Windows/Outside.cs new file mode 100644 index 0000000..0605ea9 --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows/Outside.cs @@ -0,0 +1,111 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using Microsoft.Windows.AppNotifications; +using Microsoft.Windows.AppNotifications.Builder; +using ViewSwitcher.Core; + +namespace ViewSwitcher.Windows; + +/// +/// Everything the app shows or opens outside its window goes through here (the Mac's Outside), so the +/// end-to-end run records it instead of opening browsers, dialogs and notifications on the test machine. +/// +public static partial class Outside +{ + public static readonly List Opened = []; + public static readonly List Alerts = []; + public static readonly List Notices = []; + + /// http(s), plus Cursor's MCP install link: a scene is a page anyone can write, and opening file: or any other app scheme would launch things. + public static void OpenInBrowser(Uri url) + { + if (!NavigationPolicy.OpensOutside(url)) return; + if (Env.E2E) { lock (Opened) Opened.Add(url.AbsoluteUri); return; } + Shell(url.AbsoluteUri); + } + + /// A file the app saved (Add to Claude Desktop's extension), opened in the app that handles it. + public static void OpenFile(string path) + { + if (Env.E2E) { lock (Opened) Opened.Add(path); return; } + Shell(path); + } + + /// A folder in Explorer, or a file shown selected in its folder. + public static void OpenFolder(string path, bool select = false) + { + if (Env.E2E) { lock (Opened) Opened.Add(path); return; } + try + { + var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = false }; + if (select) info.ArgumentList.Add($"/select,{path}"); + else info.ArgumentList.Add(path); + Process.Start(info); + } + catch (Exception) { } + } + + static void Shell(string target) + { + try { Process.Start(new ProcessStartInfo(target) { UseShellExecute = true }); } catch (Exception) { } + } + + public enum Icon : uint { Info = 0x40, Warning = 0x30, Error = 0x10 } + + /// A modal alert (the system's own message box, so it works with no window open). Returns whether the first button (OK / Yes) was chosen; in e2e, . + public static bool Alert(string title, string message, Icon icon = Icon.Warning, bool okCancel = false, bool e2eAnswer = false, nint owner = 0) + { + if (Env.E2E) { lock (Alerts) Alerts.Add($"{title}: {message}"); return e2eAnswer; } + const uint MB_OKCANCEL = 0x1, MB_SETFOREGROUND = 0x10000, MB_TOPMOST = 0x40000; + var r = MessageBoxW(owner, message, title, (uint)icon | (okCancel ? MB_OKCANCEL : 0) | MB_SETFOREGROUND | (owner == 0 ? MB_TOPMOST : 0)); + return r == 1; // IDOK + } + + [LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial int MessageBoxW(nint hwnd, string text, string caption, uint type); + + /// A Windows notification. One at a time: a new one replaces the last (the server's). + public static void Notify(string title, string body, string? tag = null) + { + if (Env.E2E) { lock (Notices) Notices.Add($"{title}: {body}"); return; } + Notifier.Show(title, body, tag); + } +} + +/// Toasts through the Windows App SDK (unpackaged: registered for this exe at launch). +public static class Notifier +{ + static bool registered; + + public static void Register() + { + try + { + AppNotificationManager.Default.Register(); + registered = true; + } + catch (Exception) { } + } + + public static void Unregister() + { + if (!registered) return; + try { AppNotificationManager.Default.Unregister(); } catch (Exception) { } + } + + public static void Show(string title, string body, string? tag) + { + if (!registered) return; + try + { + var n = new AppNotificationBuilder().AddText(title).AddText(body).BuildNotification(); + if (tag is not null) + { + n.Tag = tag; + n.Group = "viewswitcher"; + } + AppNotificationManager.Default.Show(n); + } + catch (Exception) { } + } +} diff --git a/apps/windows/ViewSwitcher.Windows/Program.cs b/apps/windows/ViewSwitcher.Windows/Program.cs new file mode 100644 index 0000000..6cb9e4b --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows/Program.cs @@ -0,0 +1,40 @@ +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml; +using Microsoft.Windows.AppLifecycle; +using Velopack; + +namespace ViewSwitcher.Windows; + +public static class Program +{ + [STAThread] + public static int Main(string[] args) + { + // Velopack's install, update and uninstall hooks run here and exit; a normal start carries on. + VelopackApp.Build().SetAutoApplyOnStartup(false).Run(); + WinRT.ComWrappersSupport.InitializeComWrappers(); + + // One ViewSwitcher at a time (per build): a second launch brings the first one's window forward. + // The end-to-end run has its own, so it never meets the installed app. + var key = Env.E2E ? $"ViewSwitcher-e2e-{Environment.ProcessId}" : Env.Dev ? "ViewSwitcher-dev" : "ViewSwitcher"; + var instance = AppInstance.FindOrRegisterForKey(key); + if (!instance.IsCurrent) + { + instance.RedirectActivationToAsync(AppInstance.GetCurrent().GetActivatedEventArgs()).AsTask().Wait(); + return 0; + } + instance.Activated += (_, _) => Dispatch(() => App.Current.Activated()); + + Application.Start(_ => + { + var queue = DispatcherQueue.GetForCurrentThread(); + Ui = queue; + SynchronizationContext.SetSynchronizationContext(new DispatcherQueueSynchronizationContext(queue)); + new App(startHidden: args.Contains("--login")); + }); + return 0; + } + + static DispatcherQueue? Ui; + static void Dispatch(Action a) => Ui?.TryEnqueue(() => a()); +} diff --git a/apps/windows/ViewSwitcher.Windows/RemotesWindow.cs b/apps/windows/ViewSwitcher.Windows/RemotesWindow.cs new file mode 100644 index 0000000..302a271 --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows/RemotesWindow.cs @@ -0,0 +1,318 @@ +using Microsoft.UI; +using Microsoft.UI.Text; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Imaging; +using QRCoder; +using ViewSwitcher.Core; +using Windows.Graphics; +using System.Runtime.InteropServices.WindowsRuntime; +using Windows.Storage.Streams; + +namespace ViewSwitcher.Windows; + +/// +/// Phones and Tablets (the Mac's RemotesWindow): the Wi-Fi setting, a one-time code with its QR code, the +/// addresses phones use, and the paired devices. Every call carries the app's admin secret; attached +/// to a server it didn't start, pairing isn't available. On Windows it also checks what Windows needs for +/// phones to get in (the firewall rule, the Wi-Fi marked private) and offers to set that up. +/// +public sealed class RemotesWindow +{ + public Window Window { get; } + readonly ToggleSwitch wifi = new() { OnContent = "On", OffContent = "Off" }; + readonly TextBlock status = Text("", 13, dim: true); + readonly TextBlock code = new() { FontSize = 34, FontWeight = FontWeights.SemiBold, FontFamily = new FontFamily("Cascadia Mono, Consolas"), IsTextSelectionEnabled = true }; + readonly TextBlock expiry = Text("", 13, dim: true); + readonly Image qr = new() { Width = 220, Height = 220, Stretch = Stretch.Uniform }; + readonly StackPanel urls = new() { Spacing = 2 }; + readonly StackPanel devices = new() { Spacing = 8 }; + readonly StackPanel pairing = new() { Spacing = 10, Visibility = Visibility.Collapsed }; + readonly InfoBar network = new() { IsClosable = false, Severity = InfoBarSeverity.Warning, Title = "Windows needs one setting for phones to connect" }; + readonly Button newCode = new() { Content = "New Code" }; + readonly DispatcherTimer timer = new() { Interval = TimeSpan.FromSeconds(2) }; + RemoteStatus? last; + string? shownCode; + double codeExpires; + string? pairUrl; + bool syncing; + List publicNets = []; + + /// The setting changed here: (on, the server's answer). + public event Action? EnabledChanged; + + static TextBlock Text(string s, double size = 14, bool dim = false, bool bold = false) => new() + { + Text = s, + FontSize = size, + TextWrapping = TextWrapping.Wrap, + Foreground = new SolidColorBrush(dim ? global::Windows.UI.Color.FromArgb(255, 160, 163, 172) : Colors.White), + FontWeight = bold ? FontWeights.SemiBold : FontWeights.Normal, + }; + + public RemotesWindow() + { + var setup = new Button { Content = "Set Up Windows for Phones…" }; + setup.Click += async (_, _) => await SetUpWindows(); + network.ActionButton = setup; + newCode.Click += async (_, _) => await NewCode(); + wifi.Toggled += async (_, _) => + { + if (syncing) return; + await SetEnabled(wifi.IsOn); + }; + + var head = new StackPanel { Spacing = 6, Children = { Text("Phones and Tablets", 22, bold: true), Text(RemoteText.Help, 13, dim: true) } }; + var row = new Grid { ColumnDefinitions = { new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }, new ColumnDefinition { Width = GridLength.Auto } } }; + var label = Text(StatusMenu.WifiTitle, 14); + label.VerticalAlignment = VerticalAlignment.Center; + row.Children.Add(label); + Grid.SetColumn(wifi, 1); + row.Children.Add(wifi); + + var codeCol = new StackPanel + { + Spacing = 6, + VerticalAlignment = VerticalAlignment.Center, + Children = { Text("Scan the code with the phone's camera, or open one of these addresses on it and type the code:", 13, dim: true), code, expiry, urls, newCode }, + }; + var codeRow = new Grid { ColumnSpacing = 20, ColumnDefinitions = { new ColumnDefinition { Width = GridLength.Auto }, new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) } } }; + var qrFrame = new Border { Background = new SolidColorBrush(Colors.White), Padding = new Thickness(10), CornerRadius = new CornerRadius(8), Child = qr }; + codeRow.Children.Add(qrFrame); + Grid.SetColumn(codeCol, 1); + codeRow.Children.Add(codeCol); + pairing.Children.Add(codeRow); + + var body = new StackPanel + { + Spacing = 16, + Padding = new Thickness(24), + Children = + { + head, row, network, status, pairing, + Text("Paired", 15, bold: true), + devices, + }, + }; + Window = new Window + { + Title = "Phones and Tablets", + Content = new ScrollViewer { Content = body, Background = new SolidColorBrush(SwitcherWindow.Graphite) }, + }; + if (Window.Content is FrameworkElement fe) fe.RequestedTheme = ElementTheme.Dark; + var app = Window.AppWindow; + app.SetIcon(Path.Combine(AppContext.BaseDirectory, "Assets", "ViewSwitcher.ico")); + var scale = GetDpiForWindow(WinRT.Interop.WindowNative.GetWindowHandle(Window)) / 96.0; + app.Resize(new SizeInt32((int)(620 * scale), (int)(760 * scale))); + app.TitleBar.BackgroundColor = global::Windows.UI.Color.FromArgb(255, 16, 17, 22); + app.TitleBar.ForegroundColor = Colors.White; + app.TitleBar.ButtonBackgroundColor = global::Windows.UI.Color.FromArgb(255, 16, 17, 22); + app.TitleBar.ButtonForegroundColor = Colors.White; + app.Closing += (_, e) => + { + e.Cancel = true; + app.Hide(); + timer.Stop(); + }; + timer.Tick += async (_, _) => { await Refresh(); RenderExpiry(); }; + } + + public bool Visible => Window.AppWindow.IsVisible; + + public async void Show() + { + if (Env.E2E) Window.AppWindow.Show(activateWindow: false); + else + { + Window.AppWindow.Show(); + Window.Activate(); + } + timer.Start(); + await Refresh(); + await CheckWindows(); + // Wi-Fi on and no code yet: make one, so the window opens ready to pair. + if (last is { Enabled: true } && shownCode is null) await NewCode(); + } + + public async Task Refresh() + { + try + { + Render(await Env.Api.RemoteStatus()); + } + catch (Exception e) + { + RenderError(e.Message); + } + } + + async Task SetEnabled(bool on) + { + try + { + var s = await Env.Api.SetRemoteEnabled(on); + Env.Wifi = s.Enabled; + EnabledChanged?.Invoke(s.Enabled); + Render(s); + if (s.Enabled) + { + await CheckWindows(); + await NewCode(); + } + else ClearCode(); + } + catch (Exception e) + { + RenderError(e.Message); + } + } + + /// The menu changed the setting: show it, and a fresh code when it's on. + public async Task Changed(bool on) + { + if (!Visible) return; + if (on) { await CheckWindows(); await NewCode(); } + else { ClearCode(); await Refresh(); } + } + + public async Task NewCode() + { + try + { + var s = await Env.Api.NewPairingCode(); + if (s.Code?.Code is { } c) + { + shownCode = c; + codeExpires = s.Code.ExpiresAt; + pairUrl = s.PairUrl; + } + Render(s); + } + catch (Exception e) + { + RenderError(e.Message); + } + } + + void ClearCode() + { + shownCode = null; + pairUrl = null; + qr.Source = null; + } + + void RenderError(string message) + { + status.Text = message; + pairing.Visibility = Visibility.Collapsed; + wifi.IsEnabled = false; + } + + void Render(RemoteStatus s) + { + last = s; + syncing = true; + wifi.IsOn = s.Enabled; + wifi.IsEnabled = true; + syncing = false; + status.Text = !s.Enabled ? "Off: only this PC can use the switcher." : s.CodeGuessed == true ? RemoteText.Guessed : ""; + status.Visibility = status.Text.Length > 0 ? Visibility.Visible : Visibility.Collapsed; + // The code the server sent once stays until it expires or is used (the server never sends it again). + if (s.Code is null && shownCode is not null && codeExpires < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) ClearCode(); + pairing.Visibility = s.Enabled && shownCode is not null ? Visibility.Visible : Visibility.Collapsed; + if (shownCode is not null) + { + code.Text = RemoteText.Code(shownCode); + if (pairUrl is not null && qr.Source is null) _ = ShowQr(pairUrl); + } + urls.Children.Clear(); + foreach (var u in s.Urls) urls.Children.Add(new TextBlock { Text = u, FontSize = 13, IsTextSelectionEnabled = true, Foreground = new SolidColorBrush(Colors.White) }); + RenderExpiry(); + RenderDevices(s.Devices); + network.IsOpen = s.Enabled && network.Message is { Length: > 0 }; + } + + void RenderExpiry() + { + if (shownCode is null) return; + expiry.Text = RemoteText.Expiry(codeExpires); + newCode.Content = expiry.Text == "Expired" ? "New Code" : "Another Code"; + } + + void RenderDevices(IReadOnlyList list) + { + devices.Children.Clear(); + if (list.Count == 0) + { + devices.Children.Add(Text("None yet.", 13, dim: true)); + return; + } + foreach (var d in list) + { + var remove = new Button { Content = "Remove" }; + var id = d.Id; + remove.Click += async (_, _) => + { + try { Render(await Env.Api.RemoveDevice(id)); } catch (Exception e) { RenderError(e.Message); } + }; + var g = new Grid { ColumnDefinitions = { new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }, new ColumnDefinition { Width = GridLength.Auto } } }; + g.Children.Add(new StackPanel { Children = { Text(d.Name, 14), Text(RemoteText.LastSeen(d), 12, dim: true) } }); + Grid.SetColumn(remove, 1); + g.Children.Add(remove); + devices.Children.Add(g); + } + } + + async Task ShowQr(string text) + { + var png = new PngByteQRCode(new QRCodeGenerator().CreateQrCode(text, QRCodeGenerator.ECCLevel.M)).GetGraphic(10); + using var stream = new InMemoryRandomAccessStream(); + await stream.WriteAsync(png.AsBuffer()); + stream.Seek(0); + var bmp = new BitmapImage(); + await bmp.SetSourceAsync(stream); + qr.Source = bmp; + } + + static string ServerExe => Env.Dev ? Env.Which("bun.exe") ?? "" : Env.Sidecar; + + /// + /// What Windows needs for phones to reach the server: Windows Firewall letting the server in on the + /// kind of network each Wi-Fi or Ethernet connection is (whoever's rule it is), and when the Wi-Fi is + /// public and nothing lets the server in there, the network made private (or a rule for public ones). + /// + async Task CheckWindows() + { + if (Env.E2E) return; + var allowed = await WindowsNetwork.AllowedProfiles(ServerExe); + var nets = (await WindowsNetwork.Connections()) + .Where(n => !n.Alias.StartsWith("Tailscale", StringComparison.OrdinalIgnoreCase) && !n.Alias.StartsWith("vEthernet", StringComparison.OrdinalIgnoreCase)) + .ToList(); + var blocked = nets.Where(n => !WindowsNetwork.Covers(allowed, n.Category)).ToList(); + publicNets = blocked.Where(n => n.Category == "Public").ToList(); + if (blocked.Count == 0) + { + network.Message = ""; + network.IsOpen = false; + return; + } + var parts = new List(); + if (publicNets.Count > 0) parts.Add($"Windows treats {string.Join(" and ", publicNets.Select(n => $"\"{n.Alias}\""))} as a public network, where it lets no phone reach ViewSwitcher."); + if (blocked.Count > publicNets.Count) parts.Add("Windows Firewall doesn't let phones reach ViewSwitcher yet."); + network.Severity = InfoBarSeverity.Warning; + network.Message = string.Join(" ", parts) + " Set Up Windows for Phones asks Windows once (an admin prompt) to let ViewSwitcher in on private networks" + (publicNets.Count > 0 ? " and to make this network private. Only do that on a network you trust, like home or church Wi-Fi." : "."); + network.IsOpen = last is { Enabled: true }; + } + + async Task SetUpWindows() + { + var exe = ServerExe; + var ok = await WindowsNetwork.SetUp(exe, int.Parse(Env.Port), publicNets.Select(n => n.Alias)); + await CheckWindows(); + if (!ok && network.IsOpen) network.Severity = InfoBarSeverity.Error; + } + + [System.Runtime.InteropServices.DllImport("user32.dll")] + static extern uint GetDpiForWindow(nint hwnd); +} diff --git a/apps/windows/ViewSwitcher.Windows/SwitcherWindow.cs b/apps/windows/ViewSwitcher.Windows/SwitcherWindow.cs new file mode 100644 index 0000000..edd37b7 --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows/SwitcherWindow.cs @@ -0,0 +1,298 @@ +using Microsoft.UI; +using Microsoft.UI.Windowing; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.Web.WebView2.Core; +using ViewSwitcher.Core; +using Windows.Graphics; + +namespace ViewSwitcher.Windows; + +/// +/// The switcher in a window (the Mac's SwitcherWindow): WebView2 on the server, which stays the only site +/// the main frame shows; other web pages open in the browser, other schemes are refused, and nothing +/// opens a second window. No camera or microphone, no downloads but Edit with AI's Claude Desktop +/// extension. A load that fails (the server restarting) is tried again on the same page. Closing hides +/// the window: the server keeps serving OBS and the phones. The page gets no way to call into the app. +/// +public sealed class SwitcherWindow +{ + public static readonly global::Windows.UI.Color Graphite = global::Windows.UI.Color.FromArgb(255, 11, 12, 15); + static readonly global::Windows.UI.Color Side = global::Windows.UI.Color.FromArgb(255, 16, 17, 22); + + public Window Window { get; } + public WebView2 Web { get; } = new() { DefaultBackgroundColor = Graphite }; + readonly Uri server; + ShellInfo shell = new(); + DateTime? noticeUntil; + Uri? lastFailed; + readonly List crashes = []; + bool ready; + /// What the window's user agent says (E2E.cs checks it). + public string? UserAgent { get; private set; } + + public SwitcherWindow(Uri server) + { + this.server = server; + Window = new Window { Title = Env.Dev ? "ViewSwitcher (development)" : "ViewSwitcher", Content = new Grid { Background = new Microsoft.UI.Xaml.Media.SolidColorBrush(Graphite), Children = { Web } } }; + var app = Window.AppWindow; + app.SetIcon(Path.Combine(AppContext.BaseDirectory, "Assets", "ViewSwitcher.ico")); + var bar = app.TitleBar; + bar.BackgroundColor = Side; + bar.InactiveBackgroundColor = Side; + bar.ForegroundColor = Colors.White; + bar.InactiveForegroundColor = global::Windows.UI.Color.FromArgb(255, 150, 152, 160); + bar.ButtonBackgroundColor = Side; + bar.ButtonInactiveBackgroundColor = Side; + bar.ButtonForegroundColor = Colors.White; + bar.ButtonInactiveForegroundColor = global::Windows.UI.Color.FromArgb(255, 150, 152, 160); + bar.ButtonHoverBackgroundColor = global::Windows.UI.Color.FromArgb(255, 40, 42, 50); + bar.ButtonHoverForegroundColor = Colors.White; + bar.ButtonPressedBackgroundColor = global::Windows.UI.Color.FromArgb(255, 54, 56, 66); + if (app.Presenter is OverlappedPresenter p) + { + try + { + p.PreferredMinimumWidth = 760; + p.PreferredMinimumHeight = 520; + } + catch (Exception) { } + } + Place(); + // Closing hides it: the server keeps running for OBS and the phones (Quit is in the tray). + app.Closing += (_, e) => + { + e.Cancel = true; + Hide(); + }; + _ = Setup(); + } + + void Place() + { + var app = Window.AppWindow; + var scale = (double)GetDpiForWindow(WinRT.Interop.WindowNative.GetWindowHandle(Window)) / 96; + if (Env.Settings.Window is { } w && w.Width >= 400 && w.Height >= 300 && OnScreen(w)) + { + app.MoveAndResize(new RectInt32(w.X, w.Y, w.Width, w.Height)); + if (w.Maximized && app.Presenter is OverlappedPresenter op) op.Maximize(); + return; + } + var area = DisplayArea.GetFromWindowId(app.Id, DisplayAreaFallback.Primary).WorkArea; + var width = Math.Min((int)(1440 * scale), area.Width - 40); + var height = Math.Min((int)(900 * scale), area.Height - 40); + app.MoveAndResize(new RectInt32(area.X + (area.Width - width) / 2, area.Y + (area.Height - height) / 2, width, height)); + } + + static bool OnScreen(AppSettings.WindowPlacement w) + { + var area = DisplayArea.GetFromRect(new RectInt32(w.X, w.Y, w.Width, w.Height), DisplayAreaFallback.None); + return area is not null; + } + + void Remember() + { + var app = Window.AppWindow; + var max = app.Presenter is OverlappedPresenter { State: OverlappedPresenterState.Maximized }; + if (app.Presenter is OverlappedPresenter { State: OverlappedPresenterState.Minimized }) return; + Env.Settings.Window = max && Env.Settings.Window is { } before ? before with { Maximized = true } : new(app.Position.X, app.Position.Y, app.Size.Width, app.Size.Height, max); + Env.SaveSettings(); + } + + public bool Visible => Window.AppWindow.IsVisible; + + public void Show() + { + // The end-to-end run never takes the foreground from whatever the person is doing on the test machine. + if (Env.E2E) + { + Window.AppWindow.Show(activateWindow: false); + return; + } + Window.AppWindow.Show(); + if (Window.AppWindow.Presenter is OverlappedPresenter { State: OverlappedPresenterState.Minimized } p) p.Restore(); + Window.Activate(); + SetForegroundWindow(WinRT.Interop.WindowNative.GetWindowHandle(Window)); + } + + public void Hide() + { + Remember(); + Window.AppWindow.Hide(); + } + + async Task Setup() + { + CoreWebView2Environment env; + try + { + var options = new CoreWebView2EnvironmentOptions { AdditionalBrowserArguments = "--disable-features=msSmartScreenProtection" }; + env = await CoreWebView2Environment.CreateWithOptionsAsync(null, Env.WebViewData, options); + await Web.EnsureCoreWebView2Async(env); + } + catch (Exception e) + { + Outside.Alert("ViewSwitcher needs WebView2", $"The Microsoft Edge WebView2 Runtime isn't available, so the switcher can't be shown. It comes with Windows 11; on Windows 10, install it from Microsoft (go.microsoft.com/fwlink/p/?LinkId=2124703).\n\n{e.Message}", Outside.Icon.Error); + return; + } + var core = Web.CoreWebView2; + var s = core.Settings; + // The switcher reads "ViewSwitcher-Windows" as the desktop app (apps/web/src/lib/client-kind.ts). + s.UserAgent = $"{s.UserAgent} ViewSwitcher-Windows/{Env.Version}"; + UserAgent = s.UserAgent; + s.AreDevToolsEnabled = Env.Dev; + s.AreHostObjectsAllowed = false; + s.IsWebMessageEnabled = false; + s.IsStatusBarEnabled = false; + s.IsGeneralAutofillEnabled = false; + s.IsPasswordAutosaveEnabled = false; + await core.AddScriptToExecuteOnDocumentCreatedAsync(shell.UserScript()); + + core.NavigationStarting += (_, e) => + { + var url = NavigationPolicy.Parse(e.Uri); + if (url is null) { e.Cancel = true; return; } + var fromSwitcher = NavigationPolicy.StartedBySwitcher(NavigationPolicy.Parse(core.Source), true, server); + Decide(NavigationPolicy.Window(url, server, mainFrame: true, fromSwitcher: fromSwitcher), () => e.Cancel = true); + }; + core.FrameNavigationStarting += (_, e) => + { + var url = NavigationPolicy.Parse(e.Uri); + if (url is null || NavigationPolicy.Window(url, server, mainFrame: false).Kind != NavigationKind.Allow) e.Cancel = true; + }; + core.NewWindowRequested += (_, e) => + { + e.Handled = true; // never a second window + if (NavigationPolicy.Parse(e.Uri) is { } url) Decide(NavigationPolicy.Window(url, server, mainFrame: true, newWindow: true), () => { }); + }; + // Schemes WebView2 would hand to Windows itself: never; what may leave goes through NavigationPolicy above. + core.LaunchingExternalUriScheme += (_, e) => e.Cancel = true; + core.PermissionRequested += (_, e) => e.State = CoreWebView2PermissionState.Deny; + core.DownloadStarting += (sender, e) => + { + e.Cancel = true; + if (NavigationPolicy.Parse(e.DownloadOperation.Uri) is { } url && NavigationPolicy.IsExtensionDownload(url, server)) _ = SaveExtension(); + }; + core.NavigationCompleted += (_, e) => + { + if (e.IsSuccess) + { + lastFailed = null; + ApplyShell(); + return; + } + if (e.WebErrorStatus == CoreWebView2WebErrorStatus.OperationCanceled) return; + // The server restarting: try the same page again in a second, never the root when a page can be kept. + lastFailed = NavigationPolicy.Parse(core.Source) ?? lastFailed; + RetrySoon(); + }; + core.ProcessFailed += (_, e) => + { + if (e.ProcessFailedKind is not (CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive or CoreWebView2ProcessFailedKind.BrowserProcessExited)) return; + var now = DateTime.UtcNow; + crashes.RemoveAll(c => now - c > TimeSpan.FromSeconds(30)); + crashes.Add(now); + // A page that keeps crashing its renderer goes back to the root. + if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.BrowserProcessExited) return; + if (crashes.Count >= 2) core.Navigate(new Uri(server, "/").AbsoluteUri); + else core.Reload(); + }; + ready = true; + core.Navigate(server.AbsoluteUri); + } + + void Decide(NavigationDecision d, Action cancel) + { + switch (d.Kind) + { + case NavigationKind.Allow: + return; + case NavigationKind.OpenInBrowser: + cancel(); + Outside.OpenInBrowser(d.Url!); + return; + default: + cancel(); + return; + } + } + + void RetrySoon() + { + var target = NavigationPolicy.RetryTarget(lastFailed, null, server); + Window.DispatcherQueue.TryEnqueue(async () => + { + await Task.Delay(1000); + if (ready && lastFailed is not null) Web.CoreWebView2.Navigate(target.AbsoluteUri); + }); + } + + /// After Restart Server: the page that was open, or the root. + public void ReloadCurrent() + { + if (!ready) return; + var target = NavigationPolicy.RetryTarget(lastFailed, NavigationPolicy.Parse(Web.CoreWebView2.Source), server); + Web.CoreWebView2.Navigate(target.AbsoluteUri); + } + + public void Reload() + { + if (ready) Web.CoreWebView2.Reload(); + } + + /// Edit with AI: the switcher's own sheet (#ai). + public void OpenAgentSheet() + { + if (!ready) return; + var current = NavigationPolicy.Parse(Web.CoreWebView2.Source); + if (current is not null && NavigationPolicy.SameOrigin(current, server) && !current.AbsolutePath.StartsWith("/library/")) + _ = Web.CoreWebView2.ExecuteScriptAsync("location.hash = 'ai';"); + else Web.CoreWebView2.Navigate(new Uri(server, "/?ai").AbsoluteUri); + } + + /// A banner over the switcher (its server stopped and is coming back); ends it by itself. + public void ShowNotice(string? text, DateTime? until = null) + { + if (until is { } u && u <= DateTime.UtcNow) text = null; + shell = new ShellInfo(text); + noticeUntil = until; + ApplyShell(); + if (until is { } end) + { + Window.DispatcherQueue.TryEnqueue(async () => + { + await Task.Delay(end - DateTime.UtcNow); + if (noticeUntil == end) ShowNotice(null); + }); + } + } + + void ApplyShell() + { + if (ready) _ = Web.CoreWebView2.ExecuteScriptAsync(shell.ApplyScript()); + } + + /// Add to Claude Desktop: the extension for this install, saved to Downloads and opened, so Claude Desktop asks to install it. + async Task SaveExtension() + { + try + { + var bytes = await Env.Api.AgentExtension(); + var downloads = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads"); + Directory.CreateDirectory(downloads); + var file = Path.Combine(downloads, "ViewSwitcher.mcpb"); + await File.WriteAllBytesAsync(file, bytes); + Outside.OpenFile(file); + } + catch (Exception e) + { + Outside.Alert("Couldn't add ViewSwitcher to Claude Desktop", e.Message); + } + } + + [System.Runtime.InteropServices.DllImport("user32.dll")] + static extern uint GetDpiForWindow(nint hwnd); + + [System.Runtime.InteropServices.DllImport("user32.dll")] + static extern bool SetForegroundWindow(nint hwnd); +} diff --git a/apps/windows/ViewSwitcher.Windows/Tray.cs b/apps/windows/ViewSwitcher.Windows/Tray.cs new file mode 100644 index 0000000..314c7e5 --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows/Tray.cs @@ -0,0 +1,100 @@ +using System.Runtime.InteropServices; +using H.NotifyIcon.Core; +using Microsoft.Win32; +using ViewSwitcher.Core; + +namespace ViewSwitcher.Windows; + +/// +/// The notification-area icon (the Mac's menu-bar item): red while something is on air, the on-air line +/// as its tooltip, and a menu rebuilt from . A left click opens the window. +/// +public sealed partial class Tray : IDisposable +{ + readonly TrayIconWithContextMenu icon; + readonly Action perform; + readonly Action openWindow; + readonly Microsoft.UI.Dispatching.DispatcherQueue ui; + readonly Dictionary icons = []; + /// The last menu, as titles (E2E.cs reads it back). + public List Items { get; private set; } = []; + + public Tray(Action perform, Action openWindow) + { + this.perform = perform; + this.openWindow = openWindow; + ui = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread(); + icon = new TrayIconWithContextMenu(Env.Dev ? "ViewSwitcher (development)" : "ViewSwitcher") + { + Icon = Load(TrayIconFile(live: false)), + ToolTip = "ViewSwitcher", + ContextMenu = new PopupMenu(), + }; + icon.Create(); + icon.MessageWindow.MouseEventReceived += (_, e) => + { + if (e.MouseEvent == MouseEvent.IconLeftMouseUp) ui.TryEnqueue(() => this.openWindow()); + }; + } + + /// The tray icon for the taskbar's theme: light marks on a dark taskbar, dark on a light one; red while live. + static string TrayIconFile(bool live) + { + if (live) return "TrayLive.ico"; + using var k = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"); + return k?.GetValue("SystemUsesLightTheme") is int light && light == 1 ? "TrayLight.ico" : "TrayDark.ico"; + } + + nint Load(string file) + { + if (icons.TryGetValue(file, out var h)) return h; + var path = Path.Combine(AppContext.BaseDirectory, "Assets", file); + var size = GetSystemMetrics(49 /* SM_CXSMICON */); + h = LoadImageW(0, path, 1 /* IMAGE_ICON */, size, size, 0x10 /* LR_LOADFROMFILE */); + icons[file] = h; + return h; + } + + public void Render(MenuStatus status, List items) + { + icon.UpdateIcon(Load(TrayIconFile(status.Live))); + // The tooltip: what's on air, and OBS, since the tray has no room for a title beside its icon. + var tip = status.Title.Length > 0 ? $"ViewSwitcher · {status.OnAir}" : $"ViewSwitcher · {status.OnAir} · {status.Obs}"; + icon.UpdateToolTip(tip.Length > 120 ? tip[..119] + "…" : tip); + Items = items; + var menu = new PopupMenu(); + foreach (var item in items) + { + switch (item) + { + case StatusMenu.Separator: + menu.Items.Add(new PopupMenuSeparator()); + break; + case StatusMenu.Info info: + menu.Items.Add(new PopupMenuItem(info.Text, (_, _) => { }) { Enabled = false }); + break; + case StatusMenu.ActionItem a: + var action = a.Action; + menu.Items.Add(new PopupMenuItem(a.Text, (_, _) => ui.TryEnqueue(() => perform(action))) { Enabled = a.Enabled, Checked = a.Checked }); + break; + } + } + icon.ContextMenu = menu; + } + + public void Dispose() + { + icon.Dispose(); + foreach (var h in icons.Values) if (h != 0) DestroyIcon(h); + } + + [LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial nint LoadImageW(nint instance, string name, uint type, int cx, int cy, uint load); + + [LibraryImport("user32.dll")] + private static partial int GetSystemMetrics(int index); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool DestroyIcon(nint icon); +} diff --git a/apps/windows/ViewSwitcher.Windows/Updates.cs b/apps/windows/ViewSwitcher.Windows/Updates.cs new file mode 100644 index 0000000..3931328 --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows/Updates.cs @@ -0,0 +1,79 @@ +using Velopack; +using Velopack.Sources; + +namespace ViewSwitcher.Windows; + +/// +/// Updates from GitHub Releases through Velopack (the Mac's Sparkle): checked at launch and every 6 hours, +/// downloaded in the background, and applied when the person says so (never in the middle of a show +/// without asking). Only an installed app has it: not a development build, the e2e run, or with +/// VIEWSWITCHER_UPDATES=0. +/// +public sealed class Updates +{ + public const string Repo = "https://github.com/2witstudios/viewswitcher"; + readonly UpdateManager manager; + readonly System.Threading.Timer timer; + UpdateInfo? ready; + bool checking; + + public bool Available => true; + + Updates(UpdateManager manager) + { + this.manager = manager; + var ui = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread(); + timer = new System.Threading.Timer(_ => ui.TryEnqueue(() => Check(interactive: false)), null, TimeSpan.FromSeconds(30), TimeSpan.FromHours(6)); + } + + public static Updates? Start() + { + if (!Env.UpdatesEnabled || Env.E2E || Env.Dev) return null; + try + { + var m = new UpdateManager(new GithubSource(Repo, null, false)); + return m.IsInstalled ? new Updates(m) : null; + } + catch (Exception) + { + return null; + } + } + + + public async void Check(bool interactive) + { + if (checking) return; + checking = true; + try + { + ready ??= await manager.CheckForUpdatesAsync(); + if (ready is null) + { + if (interactive) Outside.Alert("ViewSwitcher is up to date", $"You have the latest version ({Env.Version}).", Outside.Icon.Info); + return; + } + await manager.DownloadUpdatesAsync(ready); + var version = ready.TargetFullRelease.Version.ToString(); + var now = Outside.Alert("A new ViewSwitcher is ready", $"Version {version} is downloaded. Restart ViewSwitcher now to use it? The server stops for a few seconds, so OBS and phones lose the switcher until it's back. Choose Cancel to update the next time ViewSwitcher starts.", Outside.Icon.Info, okCancel: true); + if (now) + { + var own = App.Current.Supervisor.Quit(); + if (own is not null) await own.StopAsync(); + manager.ApplyUpdatesAndRestart(ready); + } + else + { + manager.WaitExitThenApplyUpdates(ready, silent: true, restart: false); + } + } + catch (Exception e) + { + if (interactive) Outside.Alert("Couldn't check for updates", e.Message); + } + finally + { + checking = false; + } + } +} diff --git a/apps/windows/ViewSwitcher.Windows/ViewSwitcher.Windows.csproj b/apps/windows/ViewSwitcher.Windows/ViewSwitcher.Windows.csproj new file mode 100644 index 0000000..c58a122 --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows/ViewSwitcher.Windows.csproj @@ -0,0 +1,45 @@ + + + + WinExe + net10.0-windows10.0.22621.0 + 10.0.19041.0 + 10.0.19041.0 + ViewSwitcher.Windows + ViewSwitcher + Assets\ViewSwitcher.ico + app.manifest + true + + true + None + true + true + x64;ARM64 + win-x64;win-arm64 + enable + enable + true + $(DefineConstants);DISABLE_XAML_GENERATED_MAIN + 1.0.0 + ViewSwitcher + 2wit Studios + MIT + + + + + + + + + + + + + + + diff --git a/apps/windows/ViewSwitcher.Windows/WindowsServices.cs b/apps/windows/ViewSwitcher.Windows/WindowsServices.cs new file mode 100644 index 0000000..6f1b0a6 --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows/WindowsServices.cs @@ -0,0 +1,211 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using Microsoft.Win32; + +namespace ViewSwitcher.Windows; + +/// Open at Login: the per-user Run key, off by default (a server starting at every login surprises someone who streams once a week). +public static class LoginItem +{ + const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; + static string Name => Env.Dev ? "ViewSwitcher (development)" : "ViewSwitcher"; + + public static bool Enabled + { + get + { + using var k = Registry.CurrentUser.OpenSubKey(RunKey); + return k?.GetValue(Name) is string; + } + set + { + using var k = Registry.CurrentUser.CreateSubKey(RunKey); + if (value) k.SetValue(Name, $"\"{Environment.ProcessPath}\" --login"); + else k.DeleteValue(Name, throwOnMissingValue: false); + } + } +} + +/// +/// What phones on the Wi-Fi need from Windows: an inbound firewall rule for the server on private +/// networks, and the Wi-Fi itself marked private (Windows blocks inbound connections on a public one). +/// Checking needs no rights; setting it up asks once, through Windows' own admin prompt. +/// +public static class WindowsNetwork +{ + public const string RuleName = "ViewSwitcher (phones and tablets)"; + + /// + /// The kinds of network ("Private", "Public", "Domain", or "Any") on which Windows Firewall lets + /// phones reach : every enabled inbound Allow rule for it, ours or the one + /// Windows made when someone chose Allow in its own prompt. + /// + public static async Task> AllowedProfiles(string exe) + { + static string Q(string s) => "'" + s.Replace("'", "''") + "'"; + var script = $"Get-NetFirewallApplicationFilter -Program {Q(exe)} -ErrorAction SilentlyContinue | Get-NetFirewallRule | Where-Object {{ $_.Enabled -eq 'True' -and $_.Action -eq 'Allow' -and $_.Direction -eq 'Inbound' }} | ForEach-Object {{ \"$($_.Profile)\" }}"; + var r = await Run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]); + return r.Out.Split(['\n', ','], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToHashSet(StringComparer.OrdinalIgnoreCase); + } + + /// Whether a network of this kind (Get-NetConnectionProfile's category) is covered by those profiles. + public static bool Covers(HashSet profiles, string category) => + profiles.Contains("Any") || profiles.Contains(category) || (category == "DomainAuthenticated" && profiles.Contains("Domain")); + + public sealed record Connection(string Alias, string Category); + + /// The connected networks and how Windows treats them (Public, Private, DomainAuthenticated). + public static async Task> Connections() + { + var r = await Run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", "Get-NetConnectionProfile | ForEach-Object { \"$($_.InterfaceAlias)`t$($_.NetworkCategory)\" }"]); + return r.Out.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(l => l.Split('\t')) + .Where(p => p.Length == 2) + .Select(p => new Connection(p[0], p[1])) + .ToList(); + } + + /// + /// The one admin step: allow the server in on private networks, and (when asked) mark the named + /// connections private. Windows shows its own prompt; returns whether it ran. + /// + public static async Task SetUp(string serverExe, int port, IEnumerable makePrivate) + { + static string Q(string s) => "'" + s.Replace("'", "''") + "'"; + var script = string.Join("; ", new[] + { + $"netsh advfirewall firewall delete rule name={Q(RuleName)} | Out-Null", + $"netsh advfirewall firewall add rule name={Q(RuleName)} dir=in action=allow program={Q(serverExe)} enable=yes profile=private,domain protocol=TCP localport={port} | Out-Null", + }.Concat(makePrivate.Select(a => $"Set-NetConnectionProfile -InterfaceAlias {Q(a)} -NetworkCategory Private"))); + var info = new ProcessStartInfo("powershell.exe") + { + UseShellExecute = true, + Verb = "runas", + WindowStyle = ProcessWindowStyle.Hidden, + }; + foreach (var a in new[] { "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-Command", script }) info.ArgumentList.Add(a); + try + { + using var p = Process.Start(info); + if (p is null) return false; + await p.WaitForExitAsync(); + return p.ExitCode == 0; + } + catch (System.ComponentModel.Win32Exception) + { + return false; // the prompt was declined + } + } + + static async Task<(int Code, string Out)> Run(string exe, string[] args) + { + var info = new ProcessStartInfo(exe) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true }; + foreach (var a in args) info.ArgumentList.Add(a); + try + { + using var p = Process.Start(info)!; + var output = await p.StandardOutput.ReadToEndAsync(); + await p.WaitForExitAsync(); + return (p.ExitCode, output); + } + catch (Exception) + { + return (-1, ""); + } + } +} + +/// +/// Announces the switcher on the local network as "ViewSwitcher" (_http._tcp), like the Mac's Bonjour, +/// so a phone's ViewSwitcher app can find this PC by name. Windows 10 and later have their own mDNS +/// responder (DnsServiceRegister); the registration lasts until Stop or the app's exit. +/// +public sealed partial class Announcer +{ + nint instance; + nint request; + int port; + static readonly RegisterComplete Callback = (_, _, inst) => { if (inst != 0) DnsServiceFreeInstance(inst); }; + + public void Set(bool on, int port) + { + if (on && this.instance != 0 && this.port == port) return; + Stop(); + if (!on) return; + try { Start(port); } catch (Exception) { Stop(); } + } + + unsafe void Start(int port) + { + this.port = port; + var host = $"{Environment.MachineName}.local"; + var keys = new[] { Marshal.StringToHGlobalUni("path") }; + var values = new[] { Marshal.StringToHGlobalUni("/") }; + try + { + fixed (nint* k = keys, v = values) + { + instance = DnsServiceConstructInstance("ViewSwitcher._http._tcp.local", host, 0, 0, (ushort)port, 0, 0, 1, (nint)k, (nint)v); + } + } + finally + { + Marshal.FreeHGlobal(keys[0]); + Marshal.FreeHGlobal(values[0]); + } + if (instance == 0) return; + var req = new DNS_SERVICE_REGISTER_REQUEST + { + Version = 1, // DNS_QUERY_REQUEST_VERSION1 + InterfaceIndex = 0, + pServiceInstance = instance, + pRegisterCompletionCallback = Marshal.GetFunctionPointerForDelegate(Callback), + }; + request = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(req, request, false); + var status = DnsServiceRegister(request, 0); + if (status != 9506 /* DNS_REQUEST_PENDING */ && status != 0) Stop(); + } + + public void Stop() + { + if (request != 0) + { + try { DnsServiceDeRegister(request, 0); } catch (Exception) { } + Marshal.FreeHGlobal(request); + request = 0; + } + if (instance != 0) + { + DnsServiceFreeInstance(instance); + instance = 0; + } + } + + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + delegate void RegisterComplete(uint status, nint context, nint instance); + + [StructLayout(LayoutKind.Sequential)] + struct DNS_SERVICE_REGISTER_REQUEST + { + public uint Version; + public uint InterfaceIndex; + public nint pServiceInstance; + public nint pRegisterCompletionCallback; + public nint pQueryContext; + public nint hCredentials; + public int unicastEnabled; + } + + [LibraryImport("dnsapi.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial nint DnsServiceConstructInstance(string serviceName, string hostName, nint ip4, nint ip6, ushort port, ushort priority, ushort weight, uint propertiesCount, nint keys, nint values); + + [LibraryImport("dnsapi.dll")] + private static partial uint DnsServiceRegister(nint request, nint cancel); + + [LibraryImport("dnsapi.dll")] + private static partial uint DnsServiceDeRegister(nint request, nint cancel); + + [LibraryImport("dnsapi.dll")] + private static partial void DnsServiceFreeInstance(nint instance); +} diff --git a/apps/windows/ViewSwitcher.Windows/app.manifest b/apps/windows/ViewSwitcher.Windows/app.manifest new file mode 100644 index 0000000..b1dc6e6 --- /dev/null +++ b/apps/windows/ViewSwitcher.Windows/app.manifest @@ -0,0 +1,16 @@ + + + + + + + + + + + + true/PM + PerMonitorV2, PerMonitor + + + diff --git a/apps/windows/scripts/build.ts b/apps/windows/scripts/build.ts new file mode 100644 index 0000000..60fb2e0 --- /dev/null +++ b/apps/windows/scripts/build.ts @@ -0,0 +1,110 @@ +// ViewSwitcher for Windows, built (apps/apple/scripts/build.sh's Windows twin): +// bun run win:build the payload, the app published self-contained, and the Velopack +// release in apps/windows/build/release (ViewSwitcher-win-Setup.exe, +// the full .nupkg and releases.win.json, the update feed) +// bun run win:build --app just apps/windows/build/app (ViewSwitcher.exe with Helpers\ and Resources\) +// bun run win:build --arch arm64 for ARM PCs (x64 by default) +// bun run win:release [--publish] the same, from a clean tree on origin/main; --publish uploads the +// release's Windows files to the DRAFT GitHub release for the version +// Signing: with WINDOWS_SIGN_PARAMS set (signtool's arguments, e.g. "/f cert.pfx /p … /fd sha256 /tr +// http://timestamp.digicert.com /td sha256"), vpk signs every exe and the setup; without, it warns and +// builds unsigned (Windows SmartScreen then warns on first run). +import { cpSync, existsSync, mkdirSync, readFileSync, rmSync } from "node:fs"; +import { join, resolve } from "node:path"; + +const REPO = resolve(import.meta.dir, "../../.."); +const WIN = join(REPO, "apps/windows"); +const BUILD = join(WIN, "build"); +const argv = process.argv.slice(2); +const flag = (f: string) => argv.includes(f); +const value = (f: string, fallback: string) => (argv.includes(f) ? argv[argv.indexOf(f) + 1]! : fallback); +const arch = value("--arch", "x64"); +const rid = `win-${arch}`; +const release = flag("--release"); +const publish = flag("--publish"); + +/** The version every app ships with: the Mac app's (apps/apple/project.yml MARKETING_VERSION), so both platforms release together. */ +function version(): string { + const yml = readFileSync(join(REPO, "apps/apple/project.yml"), "utf8"); + const v = yml.match(/MARKETING_VERSION:\s*"?([\d.]+)"?/)?.[1]; + if (!v || !/^\d+\.\d+\.\d+$/.test(v)) throw new Error("no MARKETING_VERSION in apps/apple/project.yml"); + return v; +} + +function run(cmd: string[], cwd = REPO, env: Record = {}) { + console.log(`[win:build] ${cmd.join(" ")}`); + const p = Bun.spawnSync(cmd, { cwd, stdout: "inherit", stderr: "inherit", env: { ...process.env, DOTNET_CLI_TELEMETRY_OPTOUT: "1", DOTNET_NOLOGO: "1", ...env } }); + if (p.exitCode !== 0) throw new Error(`${cmd[0]} failed (${p.exitCode})`); +} + +/** dotnet and vpk: on PATH, else where the per-user installs put them. */ +function tool(name: string, fallbacks: string[]): string { + const onPath = Bun.which(name); + if (onPath) return onPath; + const found = fallbacks.find(existsSync); + if (!found) throw new Error(`${name} isn't installed (see apps/windows/README.md)`); + return found; +} +const home = process.env.USERPROFILE ?? ""; +const local = process.env.LOCALAPPDATA ?? join(home, "AppData/Local"); +const dotnet = tool("dotnet", [join(local, "Microsoft/dotnet/dotnet.exe"), "C:/Program Files/dotnet/dotnet.exe"]); + +if (release) { + // As release-guard.sh does for the Mac: a release comes from what's on origin/main, nothing local. + const status = Bun.spawnSync(["git", "status", "--porcelain"], { cwd: REPO }).stdout.toString().trim(); + if (status) throw new Error("the tree has changes: commit or stash them first"); + run(["git", "fetch", "--quiet", "origin", "main"]); + const head = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: REPO }).stdout.toString().trim(); + const main = Bun.spawnSync(["git", "rev-parse", "origin/main"], { cwd: REPO }).stdout.toString().trim(); + if (head !== main) throw new Error("HEAD isn't origin/main"); + const pinned = readFileSync(join(REPO, ".bun-version"), "utf8").trim(); + if (Bun.version !== pinned) throw new Error(`bun ${Bun.version} isn't the pinned ${pinned} (.bun-version)`); +} + +const v = version(); +console.log(`[win:build] ViewSwitcher ${v} for ${rid}`); + +// 1. The payload: the switcher, starter, library kit, packs and the compiled server. +run([process.execPath, join(WIN, "scripts/payload.ts"), "--arch", arch]); + +// 2. The app, self-contained (the .NET runtime and the Windows App SDK inside it). +const app = join(BUILD, "app"); +rmSync(app, { recursive: true, force: true }); +run([dotnet, "publish", join(WIN, "ViewSwitcher.Windows/ViewSwitcher.Windows.csproj"), "-c", "Release", "-r", rid, "--self-contained", "-p:Platform=" + (arch === "arm64" ? "ARM64" : "x64"), `-p:Version=${v}`, "-o", app]); +cpSync(join(BUILD, "payload/Helpers"), join(app, "Helpers"), { recursive: true }); +cpSync(join(BUILD, "payload/Resources"), join(app, "Resources"), { recursive: true }); +if (!existsSync(join(app, "ViewSwitcher.exe")) || !existsSync(join(app, "Helpers/viewswitcher-server.exe"))) throw new Error("the app folder is missing ViewSwitcher.exe or its server"); +console.log(`[win:build] ${app}`); +if (flag("--app")) process.exit(0); + +// 3. The Velopack release: the installer, the package and the update feed. +const vpk = tool("vpk", [join(home, ".dotnet/tools/vpk.exe")]); +const out = join(BUILD, "release"); +mkdirSync(out, { recursive: true }); +const sign = process.env.WINDOWS_SIGN_PARAMS; +if (!sign) console.warn("[win:build] WINDOWS_SIGN_PARAMS isn't set: the app and installer are unsigned (SmartScreen will warn)"); +run([ + vpk, "pack", + "--packId", "ViewSwitcher", + "--packVersion", v, + "--packTitle", "ViewSwitcher", + "--packAuthors", "2wit Studios", + "--packDir", app, + "--mainExe", "ViewSwitcher.exe", + "--icon", join(WIN, "ViewSwitcher.Windows/Assets/ViewSwitcher.ico"), + "--runtime", rid, + "--channel", arch === "arm64" ? "win-arm64" : "win", + "--shortcuts", "Desktop,StartMenuRoot", + "--outputDir", out, + ...(sign ? ["--signParams", sign] : []), +]); +console.log(`[win:build] ${out}`); + +if (publish) { + // Onto the DRAFT release for this version (the Mac build makes it; draft so nothing is public until someone publishes it). + const tag = `v${v}`; + const draft = Bun.spawnSync(["gh", "release", "view", tag, "--json", "isDraft", "-q", ".isDraft"], { cwd: REPO }).stdout.toString().trim(); + if (draft !== "true") throw new Error(`there's no draft release ${tag}: make it with bun run mac:release --publish first, or gh release create ${tag} --draft`); + const files = Bun.spawnSync(["cmd", "/c", "dir", "/b", out]).stdout.toString().split(/\r?\n/).filter(Boolean).map((f) => join(out, f)); + run(["gh", "release", "upload", tag, "--clobber", ...files]); +} diff --git a/apps/windows/scripts/dev.ts b/apps/windows/scripts/dev.ts new file mode 100644 index 0000000..cbaf6e2 --- /dev/null +++ b/apps/windows/scripts/dev.ts @@ -0,0 +1,21 @@ +// The Windows app from this checkout (apps/apple/scripts/dev.sh's twin): a Debug build that runs the +// server from source (`bun apps/server/src/index.ts`, VIEWSWITCHER_REPO), or attaches to whatever already +// answers on PORT (e.g. `bun run dev`). Its settings, log and web view data are its own, beside the +// installed app's, and it runs alongside it (one instance per build). +// bun run win:dev builds and opens it +import { existsSync } from "node:fs"; +import { join, resolve } from "node:path"; + +const REPO = resolve(import.meta.dir, "../../.."); +const WIN = join(REPO, "apps/windows"); +const local = process.env.LOCALAPPDATA ?? ""; +const dotnet = Bun.which("dotnet") ?? [join(local, "Microsoft/dotnet/dotnet.exe"), "C:/Program Files/dotnet/dotnet.exe"].find(existsSync); +if (!dotnet) throw new Error("dotnet isn't installed (see apps/windows/README.md)"); + +const build = Bun.spawnSync([dotnet, "build", join(WIN, "ViewSwitcher.Windows/ViewSwitcher.Windows.csproj"), "-c", "Debug", "-p:Platform=x64"], { stdout: "inherit", stderr: "inherit", env: { ...process.env, DOTNET_CLI_TELEMETRY_OPTOUT: "1", DOTNET_NOLOGO: "1" } }); +if (build.exitCode !== 0) process.exit(build.exitCode ?? 1); +const exe = join(WIN, "ViewSwitcher.Windows/bin/x64/Debug/net10.0-windows10.0.22621.0/win-x64/ViewSwitcher.exe"); +// A switcher to load: the dev server builds apps/web on change; without one, build it once. +if (!existsSync(join(REPO, "apps/web/dist/index.html"))) Bun.spawnSync([process.execPath, "x", "vite", "build"], { cwd: join(REPO, "apps/web"), stdout: "inherit", stderr: "inherit" }); +Bun.spawn([exe], { env: { ...process.env, VIEWSWITCHER_REPO: REPO, BUN: process.execPath }, stdout: "ignore", stderr: "ignore" }).unref(); +console.log(`[win:dev] ${exe}`); diff --git a/apps/windows/scripts/e2e.ts b/apps/windows/scripts/e2e.ts new file mode 100644 index 0000000..1343649 --- /dev/null +++ b/apps/windows/scripts/e2e.ts @@ -0,0 +1,227 @@ +// The Windows app end to end (apps/apple/scripts/e2e.ts's Windows twin): drives the built app +// (apps/windows/build/app, from `bun run win:build --app`) on port 7435 (E2E_PORT) with OBS offline, +// updates off, and a temp library, state and control folder (E2E.cs), never the person's own. +// bun run win:e2e everything but Wi-Fi +// E2E_LAN=1 bun run win:e2e also over the Wi-Fi: Windows Firewall asks about the server the first time +// Windows never takes the foreground from the person at the machine: the app shows its windows unactivated. +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { networkInterfaces, tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { listZip, readZipEntrySync } from "../../../packages/packs/src/zip"; + +const REPO = resolve(import.meta.dir, "../../.."); +const APP = join(REPO, "apps/windows/build/app/ViewSwitcher.exe"); +const SERVER = join(REPO, "apps/windows/build/app/Helpers/viewswitcher-server.exe"); +const PORT = process.env.E2E_PORT ?? "7435"; +if (PORT === "7420") throw new Error("never on 7420: that's the person's own ViewSwitcher"); +const BASE = `http://127.0.0.1:${PORT}`; +if (!existsSync(APP)) throw new Error(`no ${APP}: run bun run win:build --app first`); + +const root = mkdtempSync(join(tmpdir(), "vs-win-e2e-")); +const library = join(root, "library"); +const control = join(root, "control"); +mkdirSync(control); +const env: Record = { + ...(process.env as Record), + PORT, + OBS_URL: "ws://127.0.0.1:1", + VIEWSWITCHER_LIBRARY: library, + VIEWSWITCHER_STATE: join(root, "state"), + VIEWSWITCHER_E2E_DIR: control, + VIEWSWITCHER_UPDATES: "0", + VIEWSWITCHER_USB: "0", +}; + +let failures = 0; +const check = (ok: unknown, what: string) => { + console.log(`${ok ? "ok " : "FAIL"} ${what}`); + if (!ok) failures++; +}; +const sleep = (ms: number) => Bun.sleep(ms); +async function until(test: () => boolean | Promise, ms = 20_000) { + const end = Date.now() + ms; + while (Date.now() < end) { + if (await Promise.resolve().then(test).catch(() => false)) return true; + await sleep(100); + } + return false; +} + +type AppState = { pid: number; state: string; attempt: number; error: string | null; serverPid: number | null; owned: boolean | null; menu: { title: string; enabled: boolean; checked: boolean }[]; window: boolean; userAgent: string | null; remotes: boolean; wifi: boolean; opened: string[]; alerts: string[]; notices: string[] }; +const state = (): AppState => JSON.parse(readFileSync(join(control, "app.json"), "utf8")); +let n = 0; +async function cmd(c: string) { + const id = ++n; + writeFileSync(join(control, `cmd-${id}.json`), JSON.stringify({ cmd: c })); + const res = join(control, `res-${id}.json`); + if (!(await until(() => existsSync(res), 15_000))) throw new Error(`no answer to ${c}`); + const r = JSON.parse(readFileSync(res, "utf8")); + if (!r.ok) throw new Error(`${c}: ${r.error}`); +} +const alive = (pid: number) => { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +}; +const answers = async () => fetch(`${BASE}/api/state`).then((r) => r.ok, () => false); +let app: ReturnType | null = null; +const launch = () => (app = Bun.spawn([APP], { env, stdout: "ignore", stderr: "ignore" })); +const kill = (pid: number) => Bun.spawnSync(["taskkill", "/F", "/PID", String(pid)], { stdout: "ignore", stderr: "ignore" }); + +try { + // ------------------------------------------------------------ first run: the bundled server, owned + launch(); + check(await until(() => existsSync(join(control, "app.json")) && state().state === "Owned"), "the app starts its bundled server and owns it"); + const first = state(); + const info = await fetch(`${BASE}/api/info`).then((r) => r.json()); + check(info.sidecar === true && info.parentPid === first.pid && info.pid === first.serverPid, "the server knows the app started it (parentPid), for orphan checks"); + check(info.library === library && existsSync(join(library, "CLAUDE.md")) && existsSync(join(library, "my-channel/org.json")), "first run: a library with the agent kit and a first show"); + check(existsSync(join(control, "server.log")) && readFileSync(join(control, "server.log"), "utf8").includes("[viewswitcher]"), "the server logs into this run's own folder"); + check(String(info.stdio).toLowerCase() === `${SERVER} --mcp-stdio --port ${PORT}`.toLowerCase() || String(info.stdio).toLowerCase().startsWith(`"${SERVER}"`.toLowerCase()), `Edit with AI's stdio command is the bundled server (${info.stdio})`); + check(/^Set-Location '.*'; claude$/.test(info.claudeCode), "Edit with AI's Claude Code command is PowerShell's"); + const state0 = await fetch(`${BASE}/api/state`).then((r) => r.json()); + check(state0.host === "windows", "the live state says the server runs on Windows (the switcher says PC)"); + + // ------------------------------------------------------------ the window and the tray + check(await until(() => state().window && !!state().userAgent), "the switcher window opens"); + check(/ViewSwitcher-Windows\/\d+\.\d+\.\d+/.test(state().userAgent ?? ""), `the window identifies as ViewSwitcher-Windows (${state().userAgent})`); + await cmd("capture-switcher"); + check(existsSync(join(control, "switcher.png")), "the switcher draws (switcher.png)"); + const titles = state().menu.map((m) => m.title); + check(await until(() => state().menu[0]?.title === "Nothing on air"), "the tray follows the live state (Nothing on air)"); + check(titles.includes("Let Phones and Tablets on This Wi-Fi Connect") && titles.includes("Quit ViewSwitcher") && !titles.some((t) => /USB/.test(t)), "the tray menu: Wi-Fi, Quit, and no USB line on Windows"); + check(state().menu.find((m) => m.title.startsWith("Set Up OBS"))?.enabled === false, "Set Up OBS waits for OBS"); + + // ------------------------------------------------------------ agents + const rpc = (id: number, method: string, params: Record = {}) => ({ jsonrpc: "2.0", id, method, params }); + const init = rpc(1, "initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "vs-e2e", version: "1" } }); + const mcpInit = await fetch(`${BASE}/mcp`, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify(init) }).then((r) => r.json(), () => null); + check(mcpInit?.result?.serverInfo, "the bundled server answers /mcp initialize"); + const relay = Bun.spawn([SERVER, "--mcp-stdio", "--port", PORT], { env: { ...env, PORT: "1", VIEWSWITCHER_E2E_DIR: "" }, stdin: "pipe", stdout: "pipe", stderr: "ignore" }); + relay.stdin.write(`${JSON.stringify(init)}\n${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n${JSON.stringify(rpc(2, "tools/list"))}\n`); + relay.stdin.flush(); + let relayed = ""; + const reader = relay.stdout.getReader(); + const listed = await Promise.race([ + (async () => { + for (;;) { + const { value, done } = await reader.read(); + if (done) return null; + relayed += new TextDecoder().decode(value); + const line = relayed.slice(0, relayed.lastIndexOf("\n") + 1).split("\n").find((l) => l.includes('"id":2')); + if (line) return JSON.parse(line); + } + })(), + sleep(10_000).then(() => null), + ]); + relay.kill(); + check((listed?.result?.tools?.length ?? 0) >= 20, `viewswitcher-server.exe --mcp-stdio relays tools/list (${listed?.result?.tools?.length} tools)`); + const mcpb = new Uint8Array(await (await fetch(`${BASE}/api/agent/viewswitcher.mcpb`)).arrayBuffer()); + const entries = listZip(mcpb); + const manifest = JSON.parse(new TextDecoder().decode(readZipEntrySync(mcpb, entries.find((e) => e.name === "manifest.json")!))); + check(manifest.compatibility.platforms[0] === "win32" && manifest.server.entry_point === "server/viewswitcher.cmd" && entries.some((e) => e.name === "server/viewswitcher.cmd"), "the Claude Desktop extension is made for Windows, with a .cmd launcher"); + check(manifest.server.mcp_config.command.toLowerCase() === SERVER.toLowerCase(), "its command is this app's bundled server"); + const evil = await fetch(`${BASE}/api/onair`, { method: "POST", headers: { origin: "https://evil.example", "content-type": "text/plain" }, body: "{}" }); + check(evil.status === 403, "a cross-site POST is refused with 403"); + + // ------------------------------------------------------------ Phones and Tablets + await cmd("open-remotes"); + check(await until(() => state().remotes), "Phones and Tablets opens"); + await sleep(1500); + await cmd("capture-remotes"); + check(existsSync(join(control, "remotes.png")), "Phones and Tablets draws (remotes.png)"); + if (process.env.E2E_LAN === "1") { + const lan = Object.entries(networkInterfaces()) + .filter(([name]) => !/tailscale|vethernet|vmware|virtualbox|loopback/i.test(name)) + .flatMap(([, l]) => l ?? []) + .find((i) => i.family === "IPv4" && !i.internal && !i.address.startsWith("169.254."))?.address; + await cmd("toggle-wifi"); + check(await until(() => state().wifi && state().menu.find((m) => m.title.startsWith("Let Phones"))?.checked === true), "Wi-Fi on: remembered and checked in the tray"); + if (lan) { + const phone = `http://${lan}:${PORT}`; + check(await until(async () => (await fetch(`${phone}/api/state`)).status === 401), `a phone at ${phone} reaches the server, which asks it to pair first`); + await cmd("pair-code"); + const code = readFileSync(join(control, "code.txt"), "utf8"); + const paired = await fetch(`${phone}/api/pair`, { method: "POST", headers: { "content-type": "application/json", "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)" }, body: JSON.stringify({ code, name: "Test iPhone" }) }); + const cookie = paired.headers.get("set-cookie")?.split(";")[0] ?? ""; + check(paired.status === 200 && cookie, "the phone pairs with the code Phones and Tablets shows"); + check((await fetch(`${phone}/api/state`, { headers: { cookie } })).status === 200, "and then uses the switcher over the Wi-Fi"); + } else check(false, "no Wi-Fi or Ethernet address on this PC"); + await cmd("toggle-wifi"); + check(await until(() => !state().wifi), "Wi-Fi off again"); + } else console.log("skip Wi-Fi (E2E_LAN=1 runs it; Windows Firewall asks about the server the first time)"); + + // ------------------------------------------------------------ the server stopping by itself + const before = state().serverPid!; + kill(before); + check(await until(() => state().state === "Owned" && state().serverPid !== before && state().serverPid !== null), "a server that dies is restarted at once"); + check(state().notices.some((m) => m.startsWith("ViewSwitcher server stopped")) && state().notices.some((m) => m.startsWith("ViewSwitcher server restarted")), "with a notification each way"); + check(await answers(), "and answers again"); + + // ------------------------------------------------------------ closing the window keeps serving; Quit frees the port + await cmd("close-window"); + check(await until(() => !state().window), "closing the window hides it"); + check(await answers(), "the server keeps serving with the window closed"); + const serverPid = state().serverPid!; + await cmd("quit"); + check(await until(async () => !(await answers()), 10_000), "Quit stops the server it started"); + check(await until(() => !alive(serverPid), 5000), "the server process is gone (stdin closed)"); + check(await until(() => !alive(first.pid), 10_000), "and the app ends"); + + // ------------------------------------------------------------ ended from Task Manager: the server goes with it + rmSync(join(control, "app.json"), { force: true }); + n = 0; + for (const f of new Bun.Glob("{cmd,res}-*.json").scanSync({ cwd: control })) rmSync(join(control, f)); + launch(); + check(await until(() => existsSync(join(control, "app.json")) && state().state === "Owned"), "the app starts again"); + const orphanPid = state().serverPid!; + kill(state().pid); + check(await until(() => !alive(orphanPid), 8000), "an app ended from Task Manager takes its server with it (Job Object)"); + check(await until(async () => !(await answers()), 5000), "and the port is free"); + + // ------------------------------------------------------------ a server someone else started: attached, never stopped + // As `bun run dev` would be: started by hand, with the app's resources but no app. + const res = join(REPO, "apps/windows/build/app/Resources"); + const other = Bun.spawn([SERVER], { env: { ...env, VIEWSWITCHER_E2E_DIR: "", VIEWSWITCHER_PARENT_PID: "", VIEWSWITCHER_WEB_DIST: join(res, "web"), VIEWSWITCHER_STARTER: join(res, "starter"), VIEWSWITCHER_LIBRARY_KIT: join(res, "library-kit"), VIEWSWITCHER_PACKS: join(res, "packs") }, stdout: "ignore", stderr: "ignore" }); + check(await until(answers), "another server runs on the port"); + rmSync(join(control, "app.json"), { force: true }); + n = 0; + for (const f of new Bun.Glob("{cmd,res}-*.json").scanSync({ cwd: control })) rmSync(join(control, f)); + launch(); + check(await until(() => existsSync(join(control, "app.json")) && state().state === "Attached"), "the app attaches to a server it didn't start"); + check(state().menu.at(-1)?.title === "Quit ViewSwitcher (server keeps running)", "and says Quit leaves it running"); + check(state().menu.find((m) => m.title === "Phones and Tablets…")?.enabled === false, "pairing needs the app's own server"); + const attachedApp = state().pid; + await cmd("quit"); + check(await until(() => !alive(attachedApp), 10_000), "Quit ends the app"); + check(await answers(), "and the other server keeps running"); + other.kill(); + await until(async () => !(await answers()), 5000); + + // ------------------------------------------------------------ the port held by something else + const squatter = Bun.serve({ hostname: "127.0.0.1", port: Number(PORT), fetch: () => new Response("not ViewSwitcher", { headers: { "content-type": "text/html" } }) }); + rmSync(join(control, "app.json"), { force: true }); + n = 0; + launch(); + // It fails, says why, and quits: the last report may already be Quitting. + check(await until(() => existsSync(join(control, "app.json")) && ["Failed", "Quitting"].includes(state().state) && state().serverPid === null), "with the port taken, the app doesn't start a server"); + check(state().alerts.some((a) => a.startsWith("Port in use")), "and says the port is in use"); + check(await until(() => !alive(state().pid), 10_000), "and ends"); + squatter.stop(true); +} catch (e) { + check(false, (e as Error).message); +} finally { + if (app && alive(app.pid)) kill(app.pid); + await sleep(500); + // The windows' pictures stay in apps/windows/build/e2e for a look. + const shots = join(REPO, "apps/windows/build/e2e"); + mkdirSync(shots, { recursive: true }); + for (const p of ["switcher.png", "remotes.png"]) if (existsSync(join(control, p))) copyFileSync(join(control, p), join(shots, p)); + if (failures === 0) rmSync(root, { recursive: true, force: true }); + else console.log(`kept ${root} for a look`); +} +console.log(failures ? `\n${failures} failed` : "\nall passed"); +process.exit(failures ? 1 : 0); diff --git a/apps/windows/scripts/icons.ts b/apps/windows/scripts/icons.ts new file mode 100644 index 0000000..e26a7d9 --- /dev/null +++ b/apps/windows/scripts/icons.ts @@ -0,0 +1,108 @@ +// The Windows app's icons, drawn from the brand mark (apps/site/public/brand/viewswitcher-icon.svg: five +// rounded rectangles, the bottom one red) into .ico files: the app icon (graphite tile), and the tray's +// for a dark and a light taskbar plus the on-air one (all red, as the Mac's StatusIconLive). +// bun apps/windows/scripts/icons.ts writes apps/windows/ViewSwitcher.Windows/Assets/*.ico +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +type RGBA = [number, number, number, number]; +const hex = (h: string, a = 255): RGBA => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16), a]; + +/** The mark in its 24-unit box (the SVG's transform applied): x, y, w, h, radius, and whether it's the red one. */ +const S = 0.76, TX = 0.6, TY = 3.944; +const RECTS = [ + [0, 0, false], [20, 0, false], [4.2, 7.6, false], [15.8, 7.6, false], [10, 15.2, true], +].map(([x, y, red]) => ({ x: TX + (x as number) * S, y: TY + (y as number) * S, w: 10 * S, h: 6 * S, r: 1.2 * S, red: red as boolean })); + +const inRounded = (px: number, py: number, r: { x: number; y: number; w: number; h: number; r: number }) => { + if (px < r.x || py < r.y || px > r.x + r.w || py > r.y + r.h) return false; + const cx = Math.min(Math.max(px, r.x + r.r), r.x + r.w - r.r); + const cy = Math.min(Math.max(py, r.y + r.r), r.y + r.h - r.r); + return (px - cx) ** 2 + (py - cy) ** 2 <= r.r ** 2; +}; + +/** One square image, `size` px, 4×4 supersampled; `pad` is the margin in 24-unit box units. */ +function draw(size: number, o: { mark: RGBA; red: RGBA; tile?: RGBA; pad: number }): Uint8Array { + const px = new Uint8Array(size * size * 4); + const box = 24 + o.pad * 2; + const N = 4; + for (let y = 0; y < size; y++) { + for (let x = 0; x < size; x++) { + let r = 0, g = 0, b = 0, a = 0; + for (let sy = 0; sy < N; sy++) { + for (let sx = 0; sx < N; sx++) { + const ux = ((x + (sx + 0.5) / N) / size) * box - o.pad; + const uy = ((y + (sy + 0.5) / N) / size) * box - o.pad; + const hit = RECTS.find((q) => inRounded(ux, uy, q)); + let c: RGBA | null = hit ? (hit.red ? o.red : o.mark) : null; + if (!c && o.tile) { + // The tile: a rounded square over the whole image (radius a fifth of it). + const t = { x: -o.pad, y: -o.pad, w: box, h: box, r: box * 0.2 }; + if (inRounded(ux, uy, t)) c = o.tile; + } + if (c) { r += c[0] * c[3]; g += c[1] * c[3]; b += c[2] * c[3]; a += c[3]; } + } + } + const i = (y * size + x) * 4; + const n = N * N; + px[i + 3] = Math.round(a / n); + if (a > 0) { px[i] = Math.round(r / a); px[i + 1] = Math.round(g / a); px[i + 2] = Math.round(b / a); } + } + } + return px; +} + +/** A 32-bit BMP entry for an .ico: BITMAPINFOHEADER (height doubled), BGRA bottom-up, then the AND mask. */ +function dib(size: number, rgba: Uint8Array): Uint8Array { + const maskRow = Math.ceil(size / 32) * 4; + const out = new Uint8Array(40 + size * size * 4 + maskRow * size); + const v = new DataView(out.buffer); + v.setUint32(0, 40, true); + v.setInt32(4, size, true); + v.setInt32(8, size * 2, true); + v.setUint16(12, 1, true); + v.setUint16(14, 32, true); + for (let y = 0; y < size; y++) { + for (let x = 0; x < size; x++) { + const s = (y * size + x) * 4; + const d = 40 + ((size - 1 - y) * size + x) * 4; + out[d] = rgba[s + 2]; out[d + 1] = rgba[s + 1]; out[d + 2] = rgba[s]; out[d + 3] = rgba[s + 3]; + } + } + return out; // the AND mask stays zero: alpha says it all +} + +function ico(images: { size: number; data: Uint8Array }[]): Uint8Array { + const head = 6 + 16 * images.length; + const total = head + images.reduce((n, i) => n + i.data.length, 0); + const out = new Uint8Array(total); + const v = new DataView(out.buffer); + v.setUint16(2, 1, true); + v.setUint16(4, images.length, true); + let at = head; + images.forEach((img, k) => { + const e = 6 + 16 * k; + out[e] = img.size >= 256 ? 0 : img.size; + out[e + 1] = img.size >= 256 ? 0 : img.size; + v.setUint16(e + 4, 1, true); + v.setUint16(e + 6, 32, true); + v.setUint32(e + 8, img.data.length, true); + v.setUint32(e + 12, at, true); + out.set(img.data, at); + at += img.data.length; + }); + return out; +} + +const make = (sizes: number[], o: Parameters[1]) => ico(sizes.map((size) => ({ size, data: dib(size, draw(size, o)) }))); + +const dir = join(import.meta.dir, "../ViewSwitcher.Windows/Assets"); +mkdirSync(dir, { recursive: true }); +const RED = hex("#ff4d4f"); +const APP = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256]; +const TRAY = [16, 20, 24, 32, 40, 48, 64]; +writeFileSync(join(dir, "ViewSwitcher.ico"), make(APP, { mark: hex("#f4f5f7"), red: RED, tile: hex("#16181e"), pad: 3 })); +writeFileSync(join(dir, "TrayDark.ico"), make(TRAY, { mark: hex("#f4f5f7"), red: RED, pad: 0 })); +writeFileSync(join(dir, "TrayLight.ico"), make(TRAY, { mark: hex("#16181e"), red: RED, pad: 0 })); +writeFileSync(join(dir, "TrayLive.ico"), make(TRAY, { mark: RED, red: RED, pad: 0 })); +console.log(`[icons] ${dir}`); diff --git a/apps/windows/scripts/payload.ts b/apps/windows/scripts/payload.ts new file mode 100644 index 0000000..7fe20ba --- /dev/null +++ b/apps/windows/scripts/payload.ts @@ -0,0 +1,35 @@ +// The Windows app's payload (apps/windows/build/payload), as apps/apple/scripts/build.sh makes the Mac's: +// the switcher (apps/web, built), the starter kit, the library kit, the built-in template packs, and the +// server compiled to one executable. The app copies it beside ViewSwitcher.exe (Helpers\ and Resources\). +// bun apps/windows/scripts/payload.ts [--arch x64|arm64] +import { cpSync, existsSync, mkdirSync, readdirSync, rmSync } from "node:fs"; +import { join, resolve } from "node:path"; + +const REPO = resolve(import.meta.dir, "../../.."); +const PAYLOAD = join(REPO, "apps/windows/build/payload"); +const arch = process.argv.includes("--arch") ? process.argv[process.argv.indexOf("--arch") + 1] : "x64"; +if (arch !== "x64" && arch !== "arm64") throw new Error(`--arch is x64 or arm64, not ${arch}`); + +function run(cmd: string[], cwd = REPO) { + console.log(`[payload] ${cmd.join(" ")}`); + const p = Bun.spawnSync(cmd, { cwd, stdout: "inherit", stderr: "inherit" }); + if (p.exitCode !== 0) throw new Error(`${cmd[0]} failed (${p.exitCode})`); +} + +rmSync(PAYLOAD, { recursive: true, force: true }); +mkdirSync(join(PAYLOAD, "Resources"), { recursive: true }); +mkdirSync(join(PAYLOAD, "Helpers"), { recursive: true }); + +run([process.execPath, "x", "vite", "build"], join(REPO, "apps/web")); +cpSync(join(REPO, "apps/web/dist"), join(PAYLOAD, "Resources/web"), { recursive: true }); +cpSync(join(REPO, "apps/server/starter"), join(PAYLOAD, "Resources/starter"), { recursive: true }); +cpSync(join(REPO, "apps/server/library-kit"), join(PAYLOAD, "Resources/library-kit"), { recursive: true }); +rmSync(join(PAYLOAD, "Resources/library-kit/README.md"), { force: true }); +// The built-in template packs: the starter and the site's shows, from @viewswitcher/packs (folders only, as the Mac app ships them). +run([process.execPath, "apps/server/src/export-packs.ts", join(PAYLOAD, "Resources/packs")]); +for (const f of readdirSync(join(PAYLOAD, "Resources/packs"))) if (f.endsWith(".zip")) rmSync(join(PAYLOAD, "Resources/packs", f)); + +const exe = join(PAYLOAD, "Helpers/viewswitcher-server.exe"); +run([process.execPath, "build", join(REPO, "apps/server/src/index.ts"), "--compile", "--minify", `--target=bun-windows-${arch}`, "--outfile", exe]); +if (!existsSync(exe)) throw new Error(`no ${exe}`); +console.log(`[payload] ${PAYLOAD} (${arch})`); diff --git a/package.json b/package.json index 2a798df..a76b337 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,12 @@ "mac:build": "bash apps/apple/scripts/build.sh", "mac:release": "bash apps/apple/scripts/build.sh --release", "mac:e2e": "bun apps/apple/scripts/e2e.ts", + "win:dev": "bun apps/windows/scripts/dev.ts", + "win:build": "bun apps/windows/scripts/build.ts", + "win:release": "bun apps/windows/scripts/build.ts --release", + "win:e2e": "bun apps/windows/scripts/e2e.ts", + "win:test": "dotnet test apps/windows/ViewSwitcher.Core.Tests", + "win:icons": "bun apps/windows/scripts/icons.ts", "brand:icons": "bun scripts/brand/icons.ts", "packs:export": "bun apps/server/src/export-packs.ts" }, diff --git a/packages/packs/src/zip.test.ts b/packages/packs/src/zip.test.ts index b365045..f4d5f6c 100644 --- a/packages/packs/src/zip.test.ts +++ b/packages/packs/src/zip.test.ts @@ -1,9 +1,11 @@ import { describe, expect, test } from "bun:test"; -import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { crc32, listZip, readZipEntry, readZipEntrySync, storedZip, writeZip, ZipError } from "./zip"; +const WINDOWS = process.platform === "win32"; + describe("storedZip", () => { test("crc32 matches the standard check value", () => { expect(crc32(new TextEncoder().encode("123456789"))).toBe(0xcbf43926); @@ -20,15 +22,27 @@ describe("storedZip", () => { { name: "empty.txt", data: "" }, { name: "run", data: "#!/bin/sh\n", executable: true }, ])); - const test = Bun.spawnSync(["unzip", "-t", join(dir, "a.zip")]); - expect(test.exitCode).toBe(0); - expect(test.stdout.toString()).toContain("No errors detected"); - expect(Bun.spawnSync(["unzip", "-q", join(dir, "a.zip"), "-d", join(dir, "out")]).exitCode).toBe(0); + if (WINDOWS) { + // Windows has no unzip; its tar (bsdtar) reads zips. And no permission bits to check. + mkdirSync(join(dir, "out")); + // Windows' own tar.exe: a Git Bash GNU tar earlier on PATH can't read zips. + const tar = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe"); + const out = Bun.spawnSync([tar, "-xf", join(dir, "a.zip"), "-C", join(dir, "out")]); + expect(out.stderr.toString()).toBe(""); + expect(out.exitCode).toBe(0); + } else { + const test = Bun.spawnSync(["unzip", "-t", join(dir, "a.zip")]); + expect(test.exitCode).toBe(0); + expect(test.stdout.toString()).toContain("No errors detected"); + expect(Bun.spawnSync(["unzip", "-q", join(dir, "a.zip"), "-d", join(dir, "out")]).exitCode).toBe(0); + } expect(readFileSync(join(dir, "out/manifest.json"), "utf8")).toBe('{"name":"viewswitcher"}'); expect(new Uint8Array(readFileSync(join(dir, "out/icons/ünï.bin")))).toEqual(binary); expect(readFileSync(join(dir, "out/empty.txt"), "utf8")).toBe(""); - expect(statSync(join(dir, "out/run")).mode & 0o777).toBe(0o755); - expect(statSync(join(dir, "out/manifest.json")).mode & 0o111).toBe(0); + if (!WINDOWS) { + expect(statSync(join(dir, "out/run")).mode & 0o777).toBe(0o755); + expect(statSync(join(dir, "out/manifest.json")).mode & 0o111).toBe(0); + } } finally { rmSync(dir, { recursive: true, force: true }); } diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts index 2635e64..73f253b 100644 --- a/packages/shared/src/types.ts +++ b/packages/shared/src/types.ts @@ -175,8 +175,16 @@ export type LiveState = { usb: UsbStatus; warnings: string[]; agent: AgentStatus; + /** The computer the server runs on, for the words the switcher uses ("this Mac", "this PC"). Absent from older servers: a Mac. */ + host?: HostKind; }; +/** The kind of computer ViewSwitcher's server runs on. */ +export type HostKind = "mac" | "windows"; + +/** What people call that computer: "Mac" or "PC". */ +export const hostName = (host: HostKind | undefined) => (host === "windows" ? "PC" : "Mac"); + /** Server → client WebSocket messages. */ export type ServerMessage = | { t: "state"; state: LiveState } diff --git a/test-links.ts b/test-links.ts new file mode 100644 index 0000000..9edd3b6 --- /dev/null +++ b/test-links.ts @@ -0,0 +1,67 @@ +// Links in tests on Windows. Making a symlink there needs an admin or Developer Mode (GitHub's Windows +// runners are admins); a junction, a link to a folder, needs neither. So when a symlink is refused +// (EPERM), one to a folder, or to nothing yet, is made a junction instead: lstat sees a link, realpath +// follows it, as the containment rules expect. A link to a file can't be made that way, and tests that +// need one skip with `test.skipIf(!fileLinks)`. +// Through require, never an import of node:fs: once a module imports its names, patching them below no longer reaches the tests. +const { existsSync, mkdtempSync, rmSync, statSync, writeFileSync } = require("node:fs"); +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; + +const WINDOWS = process.platform === "win32"; + +/** Whether this machine can make a symlink to a file (always off Windows; on Windows only as admin or in Developer Mode). */ +export const fileLinks: boolean = (() => { + if (!WINDOWS) return true; + const dir = mkdtempSync(join(tmpdir(), "vs-can-link-")); + try { + writeFileSync(join(dir, "f"), ""); + require("node:fs").symlinkSync(join(dir, "f"), join(dir, "l"), "file"); + return true; + } catch { + return false; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +})(); + +const refused = (e: unknown) => (e as NodeJS.ErrnoException).code === "EPERM"; +/** Where a link at `path` to `target` points, as an absolute path (a junction needs one). */ +const absTarget = (target: string, path: string) => resolve(dirname(String(path)), String(target)); +const toFile = (target: string, path: string) => { + const abs = absTarget(target, path); + return existsSync(abs) && !statSync(abs).isDirectory(); +}; + +/** A junction at `path` to `target` through mklink (Bun's own symlink(…, "junction") fails on Windows). */ +function junction(target: string, path: string) { + const p = Bun.spawnSync(["cmd", "/d", "/c", "mklink", "/J", resolve(String(path)), absTarget(target, path)], { stdout: "ignore", stderr: "pipe" }); + if (p.exitCode !== 0) throw Object.assign(new Error(`EPERM: couldn't make a junction at ${path}: ${p.stderr.toString().trim()}`), { code: "EPERM" }); +} + +export function linksForWindowsTests() { + if (!WINDOWS || fileLinks) return; + const fs = require("node:fs"); + const fsp = require("node:fs/promises"); + const sync = fs.symlinkSync; + const async = fsp.symlink; + fs.symlinkSync = (target: string, path: string, type?: string) => { + try { + return sync(target, path, type); + } catch (e) { + if (!refused(e) || toFile(target, path)) throw e; + junction(target, path); + } + }; + fsp.symlink = async (target: string, path: string, type?: string) => { + try { + return await async(target, path, type); + } catch (e) { + if (!refused(e) || toFile(target, path)) throw e; + junction(target, path); + } + }; +} + +/** Named pipes (mkfifo) and POSIX permission bits: macOS and Linux, never Windows. */ +export const posix: boolean = !WINDOWS; diff --git a/test-setup.ts b/test-setup.ts index 09f0c49..7cddbe4 100644 --- a/test-setup.ts +++ b/test-setup.ts @@ -1,8 +1,14 @@ // Preloaded by `bun test` (bunfig.toml): every server a test starts, and every module a test imports, -// keeps this Mac's state (paired devices, the agent setting) in a temp folder, never in the real -// ~/Library/Application Support/ViewSwitcher. -import { mkdtempSync } from "node:fs"; +// keeps this computer's state (paired devices, the agent setting) in a temp folder, never in the real +// ~/Library/Application Support/ViewSwitcher (or %APPDATA%\ViewSwitcher on Windows). +// node:fs through require only: an import here would fix its names before test-links patches symlink. +const { mkdtempSync } = require("node:fs"); import { tmpdir } from "node:os"; import { join } from "node:path"; +import { linksForWindowsTests } from "./test-links"; process.env.VIEWSWITCHER_STATE ||= mkdtempSync(join(tmpdir(), "vs-machine-state-")); + +// Windows lets only admins (or Developer Mode) make symlinks; a junction needs neither. The link tests +// are about folders and files reached through a link, so there a folder link is made a junction. +linksForWindowsTests();