diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b604bd7ea..ab01939fe 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -33,6 +33,18 @@ jobs: - run: npm ci - run: npm test - run: npm run build + - run: npm run smoke + + # Bun cross-compiles all five from here (scripts/build-binary.ts), from the client built above: + # release/ompweb--.tar.gz, .zip for Windows. The x64 targets name -baseline (no AVX2 needed): in Bun 1.4.4 + # that is the default x64 runtime too (the same bytes), and naming it keeps a later Bun from shipping a -modern one. + # They keep the plain ompweb--x64 names. + - name: Build the release binaries + run: | + for target in bun-linux-x64-baseline bun-linux-arm64 bun-darwin-x64-baseline bun-darwin-arm64 bun-windows-x64-baseline; do + npx bun scripts/build-binary.ts --target "$target" + done + - run: npm run smoke -- --binary release/ompweb-linux-x64/ompweb - name: Create draft GitHub Release env: @@ -44,6 +56,12 @@ jobs: gh release create "$TAG" --repo "$GITHUB_REPOSITORY" --verify-tag --title "$TAG" --notes-file release-notes.md --draft fi + - name: Attach the binaries to the draft release + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ github.ref_name }} + run: gh release upload "$TAG" release/ompweb-*.tar.gz release/ompweb-*.zip --repo "$GITHUB_REPOSITORY" --clobber + - name: Publish to npm run: | PACKAGE_NAME="$(node -p 'require("./package.json").name')" diff --git a/.github/workflows/verify-pr.yml b/.github/workflows/verify-pr.yml index 580789079..fc5e7f02c 100644 --- a/.github/workflows/verify-pr.yml +++ b/.github/workflows/verify-pr.yml @@ -58,6 +58,46 @@ jobs: - name: Verify production build run: npm run build + - name: Smoke test + run: npm run smoke + + # The release binary for this runner (the -baseline x64 build releases ship), from the client built above, with its + # own `ompweb host` daemon (scripts/build-binary.ts). + - name: Binary smoke test + shell: bash + run: | + if [ "$RUNNER_OS" = Windows ]; then + npx bun scripts/build-binary.ts --target bun-windows-x64-baseline + npm run smoke -- --binary release/ompweb-windows-x64/ompweb.exe + else + npx bun scripts/build-binary.ts --target bun-linux-x64-baseline + npm run smoke -- --binary release/ompweb-linux-x64/ompweb + fi + + - name: Packed install smoke test + shell: bash + run: | + npm pack --ignore-scripts + npm install -g --prefix "$RUNNER_TEMP/ompweb-prefix" ./kahme247-ompweb-*.tgz + npm run smoke -- --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix")/@kahme247/ompweb" + + # Bun's postinstall does not run here: the launcher must fall back to @oven/bun-- (spec R1). + - name: Packed install smoke test (install scripts disabled) + shell: bash + run: | + npm install -g --ignore-scripts --prefix "$RUNNER_TEMP/ompweb-prefix-no-scripts" ./kahme247-ompweb-*.tgz + npm run smoke -- --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix-no-scripts")/@kahme247/ompweb" + + - name: Parse Windows PowerShell scripts (Windows only) + if: runner.os == 'Windows' + shell: pwsh + run: | + foreach ($f in 'scripts/windows/omp-web-service.ps1', 'scripts/windows/omp-web-tray.ps1') { + $e = $null + [System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path $f).Path, [ref]$null, [ref]$e) | Out-Null + if ($e) { $e; exit 1 } + } + - name: Verify Windows System Tray & Shortcuts (Windows only) if: runner.os == 'Windows' run: | diff --git a/.gitignore b/.gitignore index 558c77dc3..3d11b4863 100644 --- a/.gitignore +++ b/.gitignore @@ -13,11 +13,10 @@ # testing coverage/ -# next.js -/.next/ -/out/ +# build output /build /dist +/release .turbo/ .cache/ @@ -34,8 +33,6 @@ screenshots/ # debug .logs/ *.log -/.next-dev.log -/.next-dev-error.log npm-debug.log* yarn-debug.log* yarn-error.log* @@ -50,7 +47,6 @@ yarn-error.log* # typescript *.tsbuildinfo -next-env.d.ts # editor / IDE .idea/ diff --git a/AGENTS.md b/AGENTS.md index f04474faf..98ece8130 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,13 +3,15 @@ ## Quick Start ```bash -npm run dev # port 30178 +npm run dev # Bun server with hot reload (HMR for the SPA), port 30178 +npm run build # bundle the SPA into dist/ (scripts/build-client.ts) +npm start # serve dist/ + the API, port 30177 +npm test # bun test --parallel +npm run smoke # start the built server and `ompweb host` (or a packed install: -- --package ; a binary: -- --binary ) and check them +npm run build:binary [-- --target bun--] # build, then compile release/ompweb--/ and its .tar.gz/.zip (scripts/build-binary.ts) +npm run typecheck && npm run lint ``` -Typecheck: `node_modules/.bin/tsc --noEmit` -Lint: `npm run lint` -**Never run `next build` during dev** — pollutes `.next/` and breaks `npm run dev`. - The dev server needs the `omp` binary installed (on `PATH`, or set `OMP_WEB_OMP_BIN`). All live-agent features go through it; session browsing works without it. @@ -17,12 +19,12 @@ All live-agent features go through it; session browsing works without it. ## Architecture -omp-web never imports `@oh-my-pi/*` or `@earendil-works/*` packages (they are -Bun-only and cannot run inside Node/Next). See `DESIGN.md` for the full porting -contract. +omp-web never imports `@oh-my-pi/*` or `@earendil-works/*` packages, even +though the server now runs on Bun: live work goes through the installed `omp` +child. See `DESIGN.md` for the full porting contract. ``` -Browser Next.js Server omp child process +Browser Bun server (server/app.ts) omp child process │ │ │ ├─ GET /api/sessions ────▶ reads ~/.omp/agent/sessions/ │ ├─ GET /api/sessions/[id] reads .jsonl file directly │ @@ -38,6 +40,14 @@ Browser Next.js Server omp child process │◀── event: s data: {...} ──│ │ ``` +The launcher (`bin/omp-web.js`) and the host daemon (`bin/omp-web-host.js`) +and tray run on Node. The launcher spawns `bun server/main.ts` (Bun resolved by +`bin/bun-runtime.js`: the npm `@oven/bun-*` binary, else `bun` on `PATH`), which +serves the SPA from `dist/`, the API routes and the password gate in one +process. Nothing in the daemon or tray may use a Bun API. The compiled binary +(`server/binary.ts`) is the exception: one Bun program that runs the server in +its own process (no launcher), `ompweb host` and `ompweb hash-password`. + **Session browsing** (read-only): pure-Node parsing of omp session `.jsonl` files via `lib/session-reader.ts` — no child process involved. **Sending a message**: `startRpcSession()` in `lib/rpc-manager.ts` asks the @@ -65,6 +75,18 @@ Shared foundations in `lib/omp/`: ## File Map ``` +server/ + main.ts production entry: sets NODE_ENV, then `startProduction` (app.ts); prints the `Ready on` line the launcher waits for + binary.ts the compiled `ompweb` (scripts/build-binary.ts): the launcher's checks (`checkLaunchSecurity`) and `startProduction` in-process, `host` (lib/hosts/host-cli.ts), `hash-password`; refuses tray/service commands + dev.ts dev entry (`bun --hot`): serves the HTML import with HMR; re-runs itself once with OMP_WEB_PUBLIC_* set so `bunfig.toml` can inline them + app.ts `startServer`: `Bun.serve` + route table + gate + SPA fallback; `startProduction` (listen, `register()`, Ready line); `parseListenArgs` + routes.ts the API route table (see "Adding an API route"); `routePattern`, `dispatch` + http.ts `finalizeResponse` (security headers, gzip for pages and static files, never `/api/`), `serveFile` (dist/, public/, KaTeX), `renderIndex` + client-env.ts build-time constants for the browser bundle (app version, event-stream worker hash) +app/ + index.html the SPA shell, the bundler entry; #root holds static copies of RouteLoadingFallback and (swapped in on /login by an inline script) LoginForm's first render, painted before the bundle runs + client.tsx browser entry: renders `LoginForm` on `/login`, else `AppShell` (a path check, no router) + boot.ts runs first in client.tsx: installs the sidebar history bridge before AppShell registers popstate listeners app/api/ sessions/route.ts GET list all sessions sessions/search/route.ts GET ?q= — NDJSON { scores } batches (titles + transcripts); closing the request stops the scan @@ -75,7 +97,7 @@ app/api/ agent/[id]/route.ts GET state | POST any RPC command events/route.ts GET multiplexed SSE | POST subscribe/unsubscribe channels hosts/route.ts GET hosts (this machine first) | POST { label } → token once + login command | PATCH { id, label?, allowAgentStart? } (`local`: label only, empty resets to "This machine") | DELETE ?id= revoke (registry first, then close the link); 503 if hosts.json is unreadable - hosts/link/route.ts GET downlink (NDJSON stream) | POST uplink (NDJSON batch) — the `ompweb host` daemon; bearer-token auth, skipped by `proxy.ts` + hosts/link/route.ts GET downlink (NDJSON stream) | POST uplink (NDJSON batch) — the `ompweb host` daemon; bearer-token auth, skipped by the `proxy.ts` gate hosts/link/blob/[reqId]/route.ts POST raw bytes for a large op result (daemon → main) notifications/devices/route.ts GET VAPID key + subscribed | PUT { deviceId, prefs, subscription? } notifications/presence/route.ts POST { clientId, deviceId, visible, sessionId, seq } @@ -106,8 +128,10 @@ app/api/ worktrees/route.ts GET/POST/DELETE git worktrees lib/ + dynamic.tsx `dynamic()` over `React.lazy` + `Suspense` + navigation.ts `useRouter`/`useSearchParams` over the History API omp/ shared omp foundations (paths, CLI probe, RpcProcess) - hosts/ hosts and the local daemon (see "Remote hosts"); none of the daemon-loaded files may import `next/*` or `@/` + hosts/ hosts and the local daemon (see "Remote hosts"); none of the daemon-loaded files may import `@/` (the daemon runs on Node through `jiti`) host.ts `Host` interface, `HostStatus`, `isLinkUp` local-host.ts `localHost`, the daemon's side: spawn + file checks on the daemon's machine; `resolveSpawnCwdResult`; `SESSION_EDIT_EXTENSION_PATH` (from the module's own location: the daemon runs in HOME). Never imported by main, nor is `daemon.ts` (`no-direct-local.test.mjs`) local-bootstrap.ts web server side of the local link: `localLinkUrl`, `ensureLocalHostLink` (the `local` record + `host.json`) @@ -206,16 +230,55 @@ hooks/ useBtw.ts /btw records/active panel/history dialog fed by btw_* SSE frames bin/ - omp-web-host.js `ompweb host [login]`: daemon CLI; token read from stdin, never argv. `omp-web.js host` requires it in-process (no child) so SIGTERM/SIGINT reach the daemon's stop + bun-runtime.js resolves the Bun binary (npm `@oven/bun-*`, else PATH, minimum version check); used by the launcher, scripts and nix + omp-web-host.js `ompweb host [login]`: loads lib/hosts/host-cli.ts through jiti; token read from stdin, never argv. `omp-web.js host` requires it in-process (no child) so SIGTERM/SIGINT reach the daemon's stop + +scripts/ + build-client.ts `npm run build`: bundles app/index.html into dist/ (Bun.build + tailwind-plugin.ts; fonts emitted as /assets files) + tailwind-plugin.ts bun-plugin-tailwind minus Tailwind's color-mix() polyfill (Bun 1.4.4 drops repeated @supports rules); build and dev + smoke.ts `npm run smoke`: starts the built server (or `--binary `) and `ompweb host` with a throwaway HOME; checks the SPA, an asset, the API, a session listed through the daemon and SSE + build-binary.ts `npm run build:binary`: compiles server/binary.ts (NODE_ENV define, no .env/bunfig autoload) into release/ompweb--/ beside dist/, public/, the KaTeX files, the session-edit extension and the licenses; archives it + licenses.ts the release's `licenses/`: license files of every npm package the server and client bundles hold (Bun.build metafiles; build-client.ts writes build/client-packages.json) and `bun-LICENSE-.md`, the vendored license of the embedded Bun runtime. Bumping Bun: vendor its LICENSE.md for the new version, or build-binary.ts stops + +dist/ build output (git-ignored, shipped in the package); the production server reads index.html and assets from here +bunfig.toml Bun dev-server bundling: tailwind plugin and the OMP_WEB_PUBLIC_* inlining ``` --- ## Key Design Decisions & Traps +### Adding an API route +1. Create `app/api//route.ts` exporting `GET`/`POST`/`PUT`/`PATCH`/`DELETE` handlers (plain `Request` → `Response`; dynamic segments `[id]`, catch-all `[...path]`). +2. Add one `import * as x from "@/app/api//route"` and one entry to `ROUTE_MODULES` in `server/routes.ts`; the key is the directory under `app/api` (`"sessions/[id]"`). +3. `server/routes.test.ts` fails when the table and the files on disk differ, and when a route module exports anything but method handlers. + +The table is static imports, not a runtime glob, so `bun build --compile` (`scripts/build-binary.ts`) bundles every handler. `dispatch` answers HEAD from `GET`, OPTIONS and a missing method (405 with `allow`), passes `params` as a promise (plus `disableIdleTimeout`, below), and turns a throw into a 500 JSON body. + +### Bun server (`server/`) +- Bun's 10 s `idleTimeout` stays on: it reaps sockets that stall before or during a request, and it also cuts a handler still working after 10 s. So `handle` (`server/app.ts`) calls `server.timeout(request, 0)` for an `/api/` request that `proxy()` reports as `"authenticated"` (never `"public"`) and puts the 10 s back once the handler returns or throws: the setting outlives the response on a keep-alive socket. A handler whose response stays open without traffic (SSE `/api/events`, the login SSE, the clone/search/bash-output/file streams) calls `disableIdleTimeout` from the route context (`dispatch`, `server/routes.ts`) to keep it off until that stream ends or is cancelled; a new stream must do the same, or it is cut after 10 s idle. The host link is gate-exempt (`"public"`), and `lib/hosts/hub.ts` calls `disableIdleTimeout` only once the bearer token checks out. `maxRequestBodySize` is left at Bun's 128 MiB default, above the 101 MB upload cap and the 64 MB link legs; do not lower it. +- Bun's router matches the **raw** path, while `request.url` is normalized (`..` and `%2e%2e` resolved). The gate and handlers read `request.url`, so each route re-matches the normalized path against its own `URLPattern` after the gate and answers 404 if it no longer matches. Never serve a gated route under an ungated path. +- Redirects carry a relative `Location` (`request.url` is always `http://` under Bun, so an absolute URL would leave https behind a TLS proxy). +- `Response.redirect()` headers are immutable; `finalizeResponse` (`server/http.ts`) copies every answer into a fresh `Response` to set the security headers and gzip. Do not mutate a handler's response headers elsewhere. +- `globalThis` state survives `bun --hot` re-evaluation, and `register()` (`instrumentation.node.ts`) runs once per process behind a `globalThis` guard in `server/dev.ts`. New server singletons use the `globalThis` registry pattern of `rpc-manager.ts`. +- Dev (`npm run dev`) serves the SPA from the HTML import with HMR, bundled in memory, and re-runs itself once with `OMP_WEB_PUBLIC_*` set because `bunfig.toml` inlines them from the environment Bun started with. Dev pages carry `script-src blob:` in their CSP (HMR updates run as blob scripts); production does not. +- `OMP_WEB_PACKAGE_DIR` (set by the launcher) is the root for `dist/`, `public/` and KaTeX; `process.cwd()` is the fallback for dev and tests. The compiled binary sets it to its own directory (unless set) before any server module loads, so every runtime file must come from that root: a module's `import.meta.url` in the binary is Bun's virtual `/$bunfs/`, which no other process can read. A new file the server or daemon reads at runtime also goes into `scripts/build-binary.ts`'s copy list. +- The binary needs `process.env.NODE_ENV` defined as `"production"` at build time (`scripts/build-binary.ts`): a plain `bun build --compile` inlines `"development"`, and the server then never writes the daemon's link. `npm run smoke -- --binary` catches that (no session lists). +- `Bun.serve` turns on `SO_REUSEPORT` when `development` is false, so a second omp-web would share the port instead of failing; `startServer` passes `reusePort: false`, and `startProduction` (`server/app.ts`) reports an `EADDRINUSE` in one line. +- The in-app update worker runs on Node (`OMP_WEB_NODE_BIN`, the launcher's `process.execPath`), not Bun. The compiled binary has no in-app update: `Bun.isStandaloneExecutable` turns it off (`lib/self-update.ts`) and `/api/app-update` names the release page (`installMethod: "binary"`). +- Bun's `fs.watch` drops an event that follows the previous one within ~2 ms, so the file channel (`openFileChannel`, `lib/event-stream-hub.ts`) re-stats the file ~50 ms after every event. +- `bun:sqlite` `.get()` returns `null` for no row (not `undefined`). +- `bun:sqlite` `close()` keeps the database file open while prepared statements are alive (until GC), so Windows cannot remove or replace it: the stores close with `close(true)`, which finalizes them (`closeNotificationStore`, `closeUsageDatabase`). +- `readSttConfig` lives in server-only `lib/stt-jobs.ts`; the browser bundle must never import it. +- Browser code must not import `next/*`: use `lib/dynamic.tsx` and `lib/navigation.ts`. + +### Tests (`bun test`) +- DOM tests import `tests/setup-dom.mjs` first and then import Testing Library dynamically, so its queries bind to that document. `bun test --parallel` gives every file a fresh global; nothing is torn down. +- A module under test that must see a fake builtin is imported with a fresh query (`?fresh=N`) after `mockBuiltin(t, name, overrides)` (`tests/mock-builtin.mjs`, built on `mock.module`; Bun's `mock.restore()` does not undo `mock.module`, so the helper restores by hand). + ### RPC session lifecycle (`lib/rpc-manager.ts`) - One wrapper per session id, keyed in a `globalThis` registry. -- `globalThis` survives Next.js hot-reload; plain module-level Map does not. +- `globalThis` survives `bun --hot` re-evaluation; a plain module-level Map does not. - Idle sessions are disposed after a timeout; concurrent `startRpcSession()` calls must share a single start promise. - Two cleanup backstops, both unref'd so they never hold the event loop: @@ -268,8 +331,8 @@ bin/ project state key on `hostProjectKey` (bare path on this machine, `:`). - **Link = two HTTP legs, both dialled by the daemon** (`/api/hosts/link`): `GET` is the downlink (long-lived NDJSON, main → daemon), `POST` the uplink - (batched NDJSON, daemon → main). No WebSocket: `next start` route handlers - cannot accept upgrades and there is no custom server (and no `ws`). Every + (batched NDJSON, daemon → main). No WebSocket yet: the route handlers are + plain `Request` → `Response` functions with no upgrade path (and no `ws`). Every line except `hello`/`welcome`/`ping`/`pong` has a per-direction `seq`; `ack` rides the hello and every POST (the `x-omp-web-ack` header on an uplink POST). The hello is a POST body, never a header (proxy header @@ -334,8 +397,10 @@ bin/ hello) and is then destroyed; no replacement spawns beside it. `restartAllRpcSessions` (omp update) restarts local sessions only. Remote-only transport members (`onResync`, `lost`) are optional on - `RpcTransport` and duck-typed: route bundles and instrumentation load - separate `hub.ts` module instances, so never `instanceof RemoteRpcTransport`. + `RpcTransport` and duck-typed. There is one module graph, but live objects on + `globalThis` outlive a `bun --hot` re-evaluation, which may re-create the + `RemoteRpcTransport` class (not verified); duck typing holds either way, so + never `instanceof RemoteRpcTransport`. - **Live-link recycle rule.** A prompt, history-edit or MCP command that times out normally recycles the child. On a remote host it does so only if the host sent uplink traffic after the command was dispatched (`lastUplinkAt`, @@ -354,10 +419,9 @@ bin/ the `get_state` reconcile. With `autoResumeSessions` on, an interrupted session resumes after its host's hello (`resumeOnHostLink`, `lib/session-resume.ts`), once, after the orphan's exit. -- **Proxy exclusion.** `proxy.ts` does not run for `/api/hosts/link` and its - subpaths (its matcher excludes exactly those). Next buffers a proxied request - body and silently truncates it past 10 MB, below the link's 16 MB uplink and - 64 MB blob limits. The hub verifies the `Authorization: Bearer ` +- **Proxy exclusion.** The `proxy.ts` gate lets `/api/hosts/link` and its + subpaths through (the `UNGATED` pattern names exactly those): the daemon has + no session cookie, so it authenticates with its bearer token instead. The hub verifies the `Authorization: Bearer ` header before reading any body (401 unknown token, 503 unreadable `hosts.json`). Keep `/api/hosts` itself behind the proxy. - **Remote paths never reach `allowFileRoot`** or any other main-side @@ -368,9 +432,9 @@ bin/ in `hub.ts`, and `sessionFileExists`/`spawn` accept only paths under the daemon's sessions directory. A remote session export is always served as an attachment: inline, its HTML would run on main's origin. -- **Daemon-loaded modules must not import `next/*` or `@/`.** `bin/omp-web-host.js` - loads `lib/hosts/daemon.ts` through plain `jiti`, which does not resolve the - `@/` alias and has no Next runtime. That covers everything the daemon pulls in +- **Daemon-loaded modules must not import `@/` or use Bun APIs.** `bin/omp-web-host.js` + loads `lib/hosts/daemon.ts` through plain `jiti` on the Node runtime, which does + not resolve the `@/` alias and has no `Bun` global (the tray modules likewise). That covers everything the daemon pulls in (`daemon.ts`, `link-protocol.ts`, `local-host.ts`, `session-ops.ts`, `host.ts`, and their `lib/` imports). Use relative imports there. - **Registry.** `/omp-web/hosts.json` (0600, atomic write) stores @@ -500,8 +564,9 @@ wait for that commit: route serves the copy until the blob has the copy's size. A daily sweep (run on the next media write) deletes copies omp now holds and files older than 30 days. -- `ToolCallBlock` shows `?thumb=1` (480px WebP made once with `sharp` and cached - next to the copies; full image if sharp is unavailable) and opens the full +- `ToolCallBlock` shows `?thumb=1` (480px WebP made once with `Bun.Image`, which + applies EXIF orientation, and cached next to the copies; full image if the + bytes do not decode) and opens the full image in the lightbox. The route serves only PNG/JPEG/GIF/WebP by magic bytes. ### Event protocol differences vs pi @@ -560,7 +625,7 @@ during the wait. EventSource and multiplexes every tab's subscriptions: frames arrive as `event: `, control frames as `event: mux` (`hello`/`open`/`end`). Subscriptions are attached with `POST /api/events`. Its URL carries a - content hash (`next.config.ts`) so a changed worker never serves stale tabs. + content hash (`server/client-env.ts`) so a changed worker never serves stale tabs. - Tabs use `openEventStream(channel)` (`lib/event-stream.ts`), which keeps EventSource semantics: `onerror` + CONNECTING = reconnecting on its own, CLOSED = fatal (e.g. 409 for a wrapper-less session; the chat hook then @@ -802,7 +867,7 @@ during the wait. ### Update notifications (`/api/omp-update`, `/api/app-update`) - Automatic in-app self-updating has been removed in favor of explicit user notifications and manual terminal commands. -- `GET /api/app-update` queries the npm registry for `@kahme247/ompweb` updates, detects the install manager (`bun` vs `npm` via `detectInstallMethod`), and returns `updateAvailable` plus the exact terminal command (e.g. `npm install -g @kahme247/ompweb` or `bun add -g @kahme247/ompweb`). +- `GET /api/app-update` queries the npm registry for `@kahme247/ompweb` updates, detects the install (`installMethod`: `bun` vs `npm` via `detectInstallMethod`, `binary` for the compiled release), and returns `updateAvailable` plus the exact terminal command (e.g. `npm install -g @kahme247/ompweb` or `bun add -g @kahme247/ompweb`; for `binary`, the release page, which Settings shows under a download message). - `POST /api/omp-update` (`action: "check"`) runs `omp update --check` and returns `updateAvailable` plus `updateCommand: "omp update"`. - `POST /api/omp-update` (`action: "restart"`) restarts active OMP sessions after a manual CLI update. - Notifications in `AppShell` and settings cards in `SettingsConfig` present the update notification alongside copyable terminal update commands. @@ -1056,13 +1121,3 @@ buttons, links and expandable text, ignoring drags and text selection, or Enter on the focused card. There is no separate action button). Icons come from `lucide-react` — do not add new inline SVGs. The command palette (`components/CommandPalette.tsx`, ⌘K/Ctrl+K) is built on `cmdk`. - - - -# This is NOT the Next.js you know - -This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices. - -This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean. - - diff --git a/CHANGELOG.md b/CHANGELOG.md index 739937744..5b7df3942 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,9 +10,13 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **Run sessions on other machines from one ompweb.** Link a machine (for example a MacBook) with **Settings → Hosts → Add host**, then run `ompweb host login --url ` (the token is read from stdin) and `ompweb host` there. The remote machine keeps its own `omp`, agent directory and credentials; ompweb routes. The sidebar groups sessions by host, the new-session screen has a host picker, and chat, history, notifications and resume work on every host. If the link drops, the run continues on the remote machine and the chat shows an offline banner until the host reconnects. Agents can pass `host` to `new_session` (it defaults to the agent's own host), which asks for confirmation on a remote host unless the host allows it; an agent on a remote host always asks before it starts or messages a session on this machine. Explorer, Git, worktrees and the skills, plugins, agents and MCP settings are not available on remote hosts yet. - **Restarting or redeploying ompweb no longer interrupts a run on this machine.** "This machine" now runs through a local `ompweb host` daemon, installed as a second service (`ompweb-host`) by `ompweb systemd install`, `ompweb launchd install` and the Windows tray install. The daemon keeps the omp processes; a restarted web server adopts them, with no resume prompt, and the dialogs and browser tool calls omp was waiting on come back. The daemon is required: until it is installed and linked, "This machine" shows offline (with a banner showing the install command) and new sessions there cannot start. An `ompweb` run in a terminal or with npx installs no service: keep `ompweb host` running in a second terminal. Restarting the daemon still ends runs, and `ompweb systemd restart` leaves it alone. If the web server comes back on another port, the daemon follows it. A `npm run dev` server does not take over the daemon. "This machine" can be renamed in **Settings → Hosts**. +- **ompweb as a single binary, with no Node or npm.** Each release now also carries `ompweb-linux-x64`, `ompweb-linux-arm64`, `ompweb-darwin-x64`, `ompweb-darwin-arm64` (`.tar.gz`) and `ompweb-windows-x64` (`.zip`): one `ompweb` program with the web files beside it. It takes the same options and environment variables as the npm `ompweb`, and runs the daemon too (`ompweb host`). It has no tray, service installers or in-app update: the README's "Single binary" section shows the service units, and Settings → System links the release page when an update is out. Build one with `npm run build:binary`. ### Fixes & Improvements +- **ompweb now runs on Bun instead of Next.js.** The npm package brings its own Bun, so installs and updates work as before, with no change to URLs, ports, settings or the password gate. Host link uploads are no longer cut at 10 MB. `OMP_WEB_DEV_ORIGIN` is removed: it only configured the Next development server. `npm run build` no longer interferes with `npm run dev`. The skills.sh search now gives up after 10 s and falls back to the `skills find` CLI instead of waiting on a stalled skills.sh. + - **If you start ompweb from a terminal (`ompweb` or `npx`), start it again once after the in-app update to this version.** The launcher that is already running applies the update and then tries to restart the server with Next, which the update removed, so the server does not come back. systemd, launchd and the tray start the new launcher and are not affected. + - Browsers older than Safari 16.2 or Chrome 111 lose the colours ompweb mixes with `color-mix()` (tints, borders and focus rings), which no longer carry a solid fallback. Those browsers were outside the Next.js build's targets too. - **The service installers set up the host daemon too.** `ompweb systemd install`, `ompweb-launchd install` and the Windows tray install now register `ompweb host` as a second unit (`ompweb-host`) next to the web service, restarting it after a 10 s delay so it can wait for the web server to write its host link on first install. `uninstall` and `status` cover both, and the tray menus show the daemon state. - **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails. - **An update whose worker died is reported as failed.** A running update whose worker process is gone, or whose lease has expired, now becomes a failed attempt the dialog can show and clean up, instead of waiting forever. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e505c658c..6bf9eadae 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,12 +4,12 @@ Thanks for your interest in contributing! ## Setup -- Node.js 24 or newer +- Node.js 24 or newer (the server runs on [Bun](https://bun.sh), which `npm install` provides) - The [omp](https://github.com/can1357/oh-my-pi) binary on your `PATH` (or set `OMP_WEB_OMP_BIN`) ```bash npm install -npm run dev # http://127.0.0.1:30178 +npm run dev # http://127.0.0.1:30178, Bun hot reload ``` The repository tracks a [graphify](https://github.com/Graphify-Labs/graphify) code @@ -32,19 +32,20 @@ afterwards and commit the graph. ## Checks (must pass before submitting) ```bash -npx tsc --noEmit # type check +npm run typecheck # type check npm run lint # ESLint, zero warnings -npm test # unit tests +npm test # unit tests (bun test --parallel) ``` -Avoid `npm run build` during local development — it writes to `.next/` and -interferes with the dev server. Builds are for release work. +`npm run build` bundles the browser app into `dist/` and `npm run smoke` +starts the built server and checks it; the dev server never reads `dist/`. ### React tests -Tests use `node:test` and `jiti`; no Jest or Vitest configuration is required. +Tests use `bun test` with `node:test`-style `test()` calls; no Jest or Vitest configuration is required. +Mock a Node builtin with `mockBuiltin` (`tests/mock-builtin.mjs`, built on `mock.module`) and import the module under test afterwards with a fresh `?fresh=N` query. For interactive components and hooks, import `tests/setup-dom.mjs` before -`@testing-library/react/pure.js`, and register `cleanup` with `afterEach`. +`@testing-library/react/pure.js` (both imported dynamically, in that order), and register `cleanup` with `afterEach`. Use DOM queries and `@testing-library/user-event` for component interactions, and `renderHook` for hook state and lifecycle tests. Keep the real jsdom `window` and `document`; mock only the browser or network APIs a scenario needs. diff --git a/DESIGN.md b/DESIGN.md index a3f79b23d..59862d50b 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -22,8 +22,9 @@ do not assume that Pi-specific implementation changes can be merged unchanged. is an explicit user choice and must be protected by a trusted network boundary and HTTPS. 3. **Node-first installation.** A normal user installs Node.js 24+ and OMP, - then runs `npx ompweb@latest` or installs `ompweb` globally. ompweb does not - require users to install Bun for its own runtime. + then runs `npx ompweb@latest` or installs `ompweb` globally. The npm package + brings its own Bun for the web server, so users do not install Bun + themselves. 4. **Native compatibility over imitation.** Prefer OMP's CLI and documented on-disk formats to copied SDK internals. If a capability cannot be done safely through those boundaries, leave it out rather than emulating it @@ -51,7 +52,7 @@ do not assume that Pi-specific implementation changes can be merged unchanged. Browser │ HTTP / Server-Sent Events ▼ -ompweb (Next.js on Node) +ompweb (Bun server, started by the Node launcher) ├─ reads native OMP session files and selected configuration ├─ serves allow-listed project files └─ starts one `omp --mode rpc-ui` child per active session @@ -63,9 +64,9 @@ ompweb (Next.js on Node) ### Why the CLI boundary is locked OMP SDK packages are Bun-only TypeScript and import Bun APIs. Importing -`@oh-my-pi/*` or `@earendil-works/*` into a Node/Next server would make the -application unreliable or non-runnable. Therefore, production code must not -add those runtime dependencies. +`@oh-my-pi/*` or `@earendil-works/*` into the ompweb server, even though it runs on +Bun, would tie it to omp's internals and make the application unreliable. +Therefore, production code must not add those runtime dependencies. Live work goes through the user’s installed `omp --mode rpc-ui` process. This keeps the agent version, providers, extensions, and session behavior aligned @@ -107,8 +108,8 @@ machine's filesystem. The link is two HTTP requests that the `ompweb host` daemon opens to the server: a long-lived response for server → daemon and batched POSTs for -daemon → server. Next route handlers cannot accept WebSocket upgrades and -ompweb runs without a custom server, so there is no WebSocket. The daemon +daemon → server. There is no WebSocket yet: the route handlers +are plain `Request` → `Response` functions. The daemon forwards omp's NDJSON unchanged and answers a fixed allow-list of host operations; there is no generic exec or file-read operation. A host is trusted like the serving machine: control of the server or of a host token is @@ -273,7 +274,7 @@ behavior, not blindly the implementation. Releases are independent: 1. Run typecheck, lint, relevant tests, and a production build. -2. Confirm `npm pack --dry-run` contains the built `.next` output and exposes +2. Confirm `npm pack --dry-run` contains the built `dist/` output and exposes the `ompweb` binary. 3. Publish `ompweb@` only from an npm account authorized for that package. @@ -282,7 +283,7 @@ Releases are independent: ## Non-goals - Reimplementing OMP, its provider registry, or its credential database. -- Embedding Bun-only OMP SDK packages in the Node server. +- Embedding Bun-only OMP SDK packages in the omp-web server. - Turning a local agent workspace into an internet-facing multi-user service. - Unrestricted filesystem browsing or arbitrary browser-triggered host tools. - Automatic bulk synchronization from `agegr/pi-web`. diff --git a/README.ja.md b/README.ja.md index 242a2da4b..d237626f6 100644 --- a/README.ja.md +++ b/README.ja.md @@ -27,7 +27,7 @@ ## 必要条件 - [omp](https://github.com/can1357/oh-my-pi) がインストールされ、`PATH` に含まれていること(または `OMP_WEB_OMP_BIN` で指定) -- Node.js `>= 24` +- Node.js `>= 24`。サーバーは [Bun](https://bun.sh) で動作し、npm パッケージの依存関係として自動的にインストールされます(同梱の Bun が見つからない場合は `PATH` 上の Bun を使用します) キュー内のフォローアップに対する **Steer** 操作には、`promote_queued_message` RPC コマンドをサポートする omp ランタイムが必要です(omp 18.1.16 では未対応)。古いランタイムではエラーを表示し、メッセージはフォローアップとしてキューに残ります。ompweb が重複したステアリングメッセージを送信することはありません。 @@ -50,6 +50,8 @@ npm install -g @kahme247/ompweb ompweb ``` +**Node や npm を使わない単一バイナリ**もリリースごとに配布しています。手順は英語版 README の [Single binary](README.md#single-binary) を参照してください。 + ブラウザで [http://127.0.0.1:30177](http://127.0.0.1:30177) を開きます。 ### CLI オプション @@ -143,16 +145,16 @@ npm run dev ローカル開発サーバーは [http://127.0.0.1:30178](http://127.0.0.1:30178) で起動します。 +`npm run dev` は Bun のホットリロード付きでサーバーを起動します。`npm run build` はブラウザアプリを `dist/` にバンドルし、`npm start` はそれをポート 30177 で配信します(`npm run smoke` で結果を確認できます)。`npm run dev:lan` は開発サーバーをすべてのインターフェースにバインドします。 + ### チェックコマンド ```bash npm run typecheck # 型チェック (TypeScript) npm run lint # ESLint -npm test # テスト実行 +npm test # テスト実行 (bun test) ``` -> **注意**: ローカル開発中に `npm run build` を実行しないでください(`.next/` が生成され `npm run dev` に影響を与える恐れがあります)。 - ## クレジットとライセンス - [agegr/pi-web](https://github.com/agegr/pi-web) (MIT) をベースに [can1357/oh-my-pi](https://github.com/can1357/oh-my-pi) 向けに適合・拡張したフォークです。 diff --git a/README.md b/README.md index 8def0093d..ab720ac33 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ A clean, modern web UI for the [oh-my-pi (omp)](https://github.com/can1357/oh-my ## Requirements - [omp](https://github.com/can1357/oh-my-pi) installed and available on your `PATH` (or specified via `OMP_WEB_OMP_BIN`) -- Node.js `>= 24` +- Node.js `>= 24`. The server runs on [Bun](https://bun.sh), which installs automatically as a dependency of the npm package (a Bun on your `PATH` is used if the bundled one is missing) The **Steer** action on a queued follow-up requires an omp runtime with the `promote_queued_message` RPC command (not available in omp 18.1.16). Older runtimes report an error and leave the message queued as a follow-up; ompweb does not send a duplicate steering message. @@ -110,6 +110,8 @@ npm install -g @kahme247/ompweb ompweb ``` +**Or download the single binary** (no Node or npm): see [Single binary](#single-binary). + Open [http://127.0.0.1:30177](http://127.0.0.1:30177) in your browser. ### CLI Options @@ -203,6 +205,85 @@ the daemon's link when it starts, so start the web server first. - **Development:** `npm run dev` does not take the daemon (see [Development](#development)). +### Single binary + +Each [release](https://github.com/kahme247/ompweb/releases/latest) also ships +ompweb as one compiled program with the files it serves beside it: +`ompweb-linux-x64.tar.gz`, `ompweb-linux-arm64.tar.gz`, `ompweb-darwin-x64.tar.gz`, +`ompweb-darwin-arm64.tar.gz` and `ompweb-windows-x64.zip`. It needs no Node, npm +or Bun; only omp must be installed. The x64 builds use Bun's baseline runtime, so +they also run on CPUs without AVX2. Each archive carries the licenses of what it +bundles in `licenses/`. + +```bash +tar -xzf ompweb-linux-x64.tar.gz -C ~/.local/share # unpacks ompweb-linux-x64/ +~/.local/share/ompweb-linux-x64/ompweb # the web server: same options and environment variables as above +~/.local/share/ompweb-linux-x64/ompweb host # the local daemon, in a second terminal +``` + +- **Keep `ompweb` in its directory.** It serves `dist/`, `public/` and the other + files from the directory it is in (a symlink to it on your `PATH` works), or + from `OMP_WEB_PACKAGE_DIR` when that is set. +- **macOS** quarantines downloads: run `xattr -dr com.apple.quarantine ompweb-darwin-arm64` + once before the first start. +- **macOS 15 and later** ask before an app may reach your local network. If + `ompweb host` on a Mac reports `ECONNREFUSED` for a server on your LAN while + `curl` reaches it, allow your terminal (or `ompweb`) under System Settings → + Privacy & Security → Local Network. A server reached over a VPN such as + Tailscale, or a host started from an SSH session, is not affected. +- **No tray, service installers or in-app update.** To update, stop `ompweb` and + `ompweb host`, replace the directory with the new release, and start both again; + **Settings → System** links the release page when a new version is out. + Your sessions and settings live in `~/.omp`, not in that directory. +- **As systemd user services**, write the two units yourself (adjust the paths; + add omp's directory to `PATH`, or set `OMP_WEB_OMP_BIN`): + +```ini +# ~/.config/systemd/user/ompweb.service +[Unit] +Description=ompweb web service + +[Service] +WorkingDirectory=%h +ExecStart=%h/.local/share/ompweb-linux-x64/ompweb --no-open +Environment=PATH=%h/.local/bin:%h/.bun/bin:/usr/local/bin:/usr/bin:/bin +# OMP_WEB_PASSWORD_HASH, PORT and OMP_WEB_HOSTNAME go here, as for ompweb-systemd. +EnvironmentFile=-%h/.omp/agent/web-service.env +Restart=on-failure +RestartSec=3 + +[Install] +WantedBy=default.target +``` + +```ini +# ~/.config/systemd/user/ompweb-host.service +[Unit] +Description=ompweb host daemon +# It exits until the web server has written its link: keep restarting. +StartLimitIntervalSec=0 + +[Service] +WorkingDirectory=%h +ExecStart=%h/.local/share/ompweb-linux-x64/ompweb host +Environment=PATH=%h/.local/bin:%h/.bun/bin:/usr/local/bin:/usr/bin:/bin +EnvironmentFile=-%h/.omp/agent/web-service.env +Restart=always +RestartSec=10 + +[Install] +WantedBy=default.target +``` + +```bash +systemctl --user daemon-reload +systemctl --user enable --now ompweb ompweb-host +``` + + On macOS, two launchd agents (`ProgramArguments` `…/ompweb --no-open` and + `…/ompweb host`, with `RunAtLoad` and `KeepAlive`) do the same; on Windows, two + Task Scheduler tasks that run `ompweb.exe --no-open` and `ompweb.exe host` at logon. + ### Run as a Windows Service (System Tray) Install ompweb as a Windows background service with a system tray icon and autostart at login: @@ -449,7 +530,6 @@ Notes: | `OMP_WEB_DISABLE_AUTOUPDATE` | Set to `1` to disable update checks and in-app updates; restart after changing | `0` | | `OMP_WEB_NAME` | Name shown in browser tabs and installed-app names. `url`, `host` or `domain` (any case) uses the hostname the browser connected to, without port; localhost and IP addresses keep `omp web`. Any other value is used as-is. Restart after changing | `omp web` | | `OMP_WEB_OMP_BIN` | Path to `omp` binary if not on `PATH` | _auto-detected_ | -| `OMP_WEB_DEV_ORIGIN` | Additional allowed hostname for the development server (no scheme or port); ignored in production | _None_ | | `PI_CODING_AGENT_DIR` | Custom omp agent directory | `~/.omp/agent` | | `OMP_WEB_STT_ENDPOINT` | OpenAI-compatible transcription endpoint URL. Leave unset to transcribe with `OMP_WEB_STT_MODEL` through omp's own credentials | _None_ | | `OMP_WEB_STT_KEY` | Optional API key for the STT endpoint | _None_ | @@ -581,29 +661,16 @@ A dev server does not take over the local daemon: only the production web server writes the daemon's `host.json`, so "This machine" shows offline in dev and the daemon stays linked to your installed ompweb. -The development server allows loopback and RFC1918 private IPv4 origins -(`10.0.0.0/8`, `172.16.0.0/12`, and `192.168.0.0/16`). When using a tunnel -or reverse proxy with a custom hostname, set it without editing `next.config.ts`: - -```bash -OMP_WEB_DEV_ORIGIN=dev.example.com npm run dev -``` - -For a persistent setup, set the variable in your local environment or service -configuration and restart the dev server. This does not change the bind address -or enable authentication. Next.js hostname patterns cannot express IPv6 CIDRs; -a private IPv6 origin must be supplied explicitly (for example, `[fd00::1]`). +`npm run dev` runs the server with Bun hot reload. `npm run build` bundles the browser app into `dist/`, and `npm start` serves it on port 30177 (`npm run smoke` checks the result). `npm run dev:lan` binds the dev server to all interfaces. `npm run build:binary` builds the [single binary](#single-binary) for this machine into `release/` (`-- --target bun-linux-arm64` and the like for another platform; `npm run smoke -- --binary release/ompweb-linux-x64/ompweb` checks it). ### Checks ```bash npm run typecheck # Type check (TypeScript) npm run lint # ESLint -npm test # Run test suite +npm test # Run test suite (bun test) ``` -> **Note**: Do not run `npm run build` during local dev — it populates `.next/` and can break `npm run dev`. - ## License & Credits - Forked from [agegr/pi-web](https://github.com/agegr/pi-web) (MIT) and adapted for [can1357/oh-my-pi](https://github.com/can1357/oh-my-pi). diff --git a/README.zh-CN.md b/README.zh-CN.md index df75d178c..e4a4c66aa 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -27,7 +27,7 @@ ## 环境要求 - 已安装 [omp](https://github.com/can1357/oh-my-pi) 且在 `PATH` 中(或通过 `OMP_WEB_OMP_BIN` 指定路径) -- Node.js `>= 24` +- Node.js `>= 24`。服务器运行在 [Bun](https://bun.sh) 上,Bun 会作为 npm 包的依赖自动安装(找不到随包安装的 Bun 时使用 `PATH` 中的 Bun) 将排队的后续消息转为 **Steer** 需要 omp 运行时支持 `promote_queued_message` RPC 命令(omp 18.1.16 尚不支持)。旧版运行时会返回错误,消息仍作为后续消息排队;ompweb 不会重复发送一条引导消息。 @@ -50,6 +50,8 @@ npm install -g @kahme247/ompweb ompweb ``` +每个版本也提供**无需 Node 或 npm 的单一可执行文件**,用法见英文 README 的 [Single binary](README.md#single-binary)。 + 在浏览器中打开 [http://127.0.0.1:30177](http://127.0.0.1:30177)。 ### CLI 选项 @@ -136,16 +138,16 @@ npm run dev 本地开发服务器运行在 [http://127.0.0.1:30178](http://127.0.0.1:30178)。 +`npm run dev` 以 Bun 热重载方式运行服务器。`npm run build` 将浏览器端应用打包到 `dist/`,`npm start` 在 30177 端口提供该产物(可用 `npm run smoke` 检查结果)。`npm run dev:lan` 会将开发服务器绑定到所有网络接口。 + ### 代码检查 ```bash npm run typecheck # TypeScript 类型检查 npm run lint # ESLint 检查 -npm test # 运行测试套件 +npm test # 运行测试套件 (bun test) ``` -> **注意**:本地开发期间请勿运行 `npm run build`,以免污染 `.next/` 导致开发服务器异常。 - ## 致谢与许可证 - 分叉自 [agegr/pi-web](https://github.com/agegr/pi-web)(MIT),针对 [can1357/oh-my-pi](https://github.com/can1357/oh-my-pi) 进行适配。 diff --git a/app/api/agent/[id]/bash-output/route.ts b/app/api/agent/[id]/bash-output/route.ts index 1dab13a61..61ce4966d 100644 --- a/app/api/agent/[id]/bash-output/route.ts +++ b/app/api/agent/[id]/bash-output/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { tmpdir } from "node:os"; import { Readable } from "node:stream"; import { @@ -17,7 +16,7 @@ import { isBashOutputPathReferencedBySession } from "@/lib/session-file-referenc // path — a path alone is never enough. export async function GET( _req: Request, - { params }: { params: Promise<{ id: string }> } + { params, disableIdleTimeout }: { params: Promise<{ id: string }>; disableIdleTimeout: () => void } ) { const { id } = await params; let path: string | null = null; @@ -27,26 +26,27 @@ export async function GET( path = url.searchParams.get("path"); download = url.searchParams.get("download") === "1"; } catch { - return NextResponse.json({ error: "invalid url" }, { status: 400 }); + return Response.json({ error: "invalid url" }, { status: 400 }); } if (!path) { - return NextResponse.json({ error: "path required" }, { status: 400 }); + return Response.json({ error: "path required" }, { status: 400 }); } const resolved = resolveBashOutputPath(path, tmpdir()); if (!resolved) { - return NextResponse.json({ error: "invalid path" }, { status: 400 }); + return Response.json({ error: "invalid path" }, { status: 400 }); } if (!await isBashOutputPathReferencedBySession(resolved, id)) { - return NextResponse.json({ error: "forbidden" }, { status: 403 }); + return Response.json({ error: "forbidden" }, { status: 403 }); } try { if (download) { const { handle } = await openRegularFileNoFollow(resolved); - const stream = Readable.toWeb(handle.createReadStream()) as ReadableStream; + const stream = Readable.toWeb(handle.createReadStream()) as unknown as ReadableStream; + disableIdleTimeout(); return new Response(stream, { headers: { "Content-Type": "text/plain; charset=utf-8", @@ -58,13 +58,13 @@ export async function GET( const result = await readUtf8FileWithinLimit(resolved); if (result.tooLarge) { - return NextResponse.json({ + return Response.json({ error: `Full output is too large to display (limit ${MAX_INLINE_BASH_OUTPUT_BYTES} bytes)`, data: { size: result.size, maxBytes: MAX_INLINE_BASH_OUTPUT_BYTES }, }, { status: 413 }); } - return NextResponse.json({ success: true, data: { output: result.content } }); + return Response.json({ success: true, data: { output: result.content } }); } catch { - return NextResponse.json({ error: "full output unavailable" }, { status: 404 }); + return Response.json({ error: "full output unavailable" }, { status: 404 }); } } diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index a8edbce26..3276a2652 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse, hostOfflineResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; import { startRpcSession, getRpcSession, WebRpcError } from "@/lib/rpc-manager"; import { sessionSpawnTarget } from "@/lib/hosts/session-index"; @@ -29,17 +28,17 @@ const LIVE_SESSION_ONLY = new Set(["get_skill_diagnostics", "set_skill_startup_d * errors stay opaque English text. */ function commandErrorResponse(error: unknown) { if (error instanceof RequestBodyTooLargeError) { - return NextResponse.json({ error: "Agent command is too large", code: "request_too_large" }, { status: 413 }); + return Response.json({ error: "Agent command is too large", code: "request_too_large" }, { status: 413 }); } if (error instanceof SyntaxError) { - return NextResponse.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); + return Response.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); } // host_offline falls through to apiErrorResponse: 503 {hostOffline: true}. if (error instanceof WebRpcError && error.code !== "host_offline") { - return NextResponse.json({ error: error.message, code: error.code }, { status: 400 }); + return Response.json({ error: error.message, code: error.code }, { status: 400 }); } if (error instanceof RpcCommandError) { - return NextResponse.json({ error: error.message, code: error.code ?? "rpc_command_failed" }, { status: 400 }); + return Response.json({ error: error.message, code: error.code ?? "rpc_command_failed" }, { status: 400 }); } return apiErrorResponse(error); } @@ -54,7 +53,7 @@ export async function POST( try { const body = await parseJsonWithinLimit<{ type?: unknown; [key: string]: unknown }>(req, MAX_AGENT_COMMAND_REQUEST_BYTES); if (typeof body.type !== "string" || !body.type.trim()) { - return NextResponse.json({ error: "command type is required", code: "command_type_required" }, { status: 400 }); + return Response.json({ error: "command type is required", code: "command_type_required" }, { status: 400 }); } // The per-chat advisor choice rides on the query string (never the RPC @@ -72,16 +71,16 @@ export async function POST( if (existing?.isAlive()) { if (noSpawn || liveOnly || existing.advisorSpawned === advisor || existing.isRunning() || existing.isEditingHistory()) { const result = await existing.send(body); - return NextResponse.json({ success: true, data: result }); + return Response.json({ success: true, data: result }); } // Disposing a child behind a down link would wait for the link to return. const offline = hostOfflineResponse(existing.host); if (offline) return offline; await existing.destroyAndWait(); } - if (noSpawn) return NextResponse.json({ success: true, data: NO_SPAWN_REPLIES[body.type] }); + if (noSpawn) return Response.json({ success: true, data: NO_SPAWN_REPLIES[body.type] }); if (liveOnly) { - return NextResponse.json( + return Response.json( { error: "Skill diagnostics require a running session", code: "skill_diagnostics_unavailable" }, { status: 409 }, ); @@ -93,7 +92,7 @@ export async function POST( const offline = hostOfflineResponse(host); if (offline) return offline; const target = await sessionSpawnTarget(id, host); - if (!target) return NextResponse.json({ error: "Session not found", code: "session_not_found" }, { status: 404 }); + if (!target) return Response.json({ error: "Session not found", code: "session_not_found" }, { status: 404 }); // A cold set_model must reach omp before the saved model is restored: // spawning with only --resume lets omp exit on an unrestorable saved @@ -126,20 +125,20 @@ export async function POST( // precedence) rethrows the RPC error, so a real failure still surfaces. try { const result = await session.send(body); - return NextResponse.json({ success: true, data: result }); + return Response.json({ success: true, data: result }); } catch (error) { const state = (await session.send({ type: "get_state" })) as { model?: { id?: unknown; provider?: unknown }; } | null; if (state?.model?.provider === body.provider && state?.model?.id === body.modelId) { - return NextResponse.json({ success: true, data: { id: body.modelId, provider: body.provider } }); + return Response.json({ success: true, data: { id: body.modelId, provider: body.provider } }); } throw error; } } const result = await session.send(body); - return NextResponse.json({ success: true, data: result }); + return Response.json({ success: true, data: result }); } catch (error) { return commandErrorResponse(error); } @@ -155,14 +154,14 @@ export async function GET( try { const session = getRpcSession(id); if (!session || !session.isAlive()) { - return NextResponse.json({ running: false }); + return Response.json({ running: false }); } try { const state = await session.send({ type: "get_state" }); - return NextResponse.json({ running: true, state }); + return Response.json({ running: true, state }); } catch (error) { if (error instanceof WebRpcError && error.code === "session_unresponsive") { - return NextResponse.json({ running: false, recovered: true }); + return Response.json({ running: false, recovered: true }); } throw error; } diff --git a/app/api/agent/new/route.ts b/app/api/agent/new/route.ts index 2bea6734e..d5acf1bb0 100644 --- a/app/api/agent/new/route.ts +++ b/app/api/agent/new/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse, opErrorResponse, resolveHostOrError } from "@/lib/api-utils"; import { WebRpcError, startNewRpcSession } from "@/lib/rpc-manager"; import { RpcCommandError } from "@/lib/omp/rpc-process"; @@ -7,14 +6,14 @@ import { MAX_AGENT_COMMAND_REQUEST_BYTES } from "@/lib/image-attachments"; function newSessionErrorResponse(error: unknown) { if (error instanceof RequestBodyTooLargeError) { - return NextResponse.json({ error: "New session request is too large", code: "request_too_large" }, { status: 413 }); + return Response.json({ error: "New session request is too large", code: "request_too_large" }, { status: 413 }); } if (error instanceof SyntaxError) { - return NextResponse.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); + return Response.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); } // host_offline falls through to apiErrorResponse: 503 {hostOffline: true}. if ((error instanceof WebRpcError && error.code !== "host_offline") || error instanceof RpcCommandError) { - return NextResponse.json( + return Response.json( { error: error.message, code: error instanceof WebRpcError ? error.code : (error.code ?? "rpc_command_failed") }, { status: 400 }, ); @@ -38,7 +37,7 @@ export async function POST(req: Request) { const { host } = target; if (!requestedCwd || typeof requestedCwd !== "string") { - return NextResponse.json({ error: "cwd is required", code: "cwd_required" }, { status: 400 }); + return Response.json({ error: "cwd is required", code: "cwd_required" }, { status: 400 }); } const { provider, modelId, toolNames, thinkingLevel, advisor, ...promptCommand } = command as { provider?: string; modelId?: string; toolNames?: string[]; thinkingLevel?: string; advisor?: boolean; [key: string]: unknown }; @@ -46,7 +45,7 @@ export async function POST(req: Request) { // child RPC: a stale or forged id would address the wrong session. delete promptCommand.sessionId; if (typeof promptCommand.type !== "string" || !promptCommand.type.trim()) { - return NextResponse.json({ error: "command type is required", code: "command_type_required" }, { status: 400 }); + return Response.json({ error: "command type is required", code: "command_type_required" }, { status: 400 }); } // The cwd is checked on its host; the host answers with the path it will use. @@ -66,12 +65,12 @@ export async function POST(req: Request) { } if (promptCommand.type === "ensure_session") { - return NextResponse.json({ success: true, sessionId: realSessionId, data: null }); + return Response.json({ success: true, sessionId: realSessionId, data: null }); } const result = await session.send(promptCommand); - return NextResponse.json({ success: true, sessionId: realSessionId, data: result }); + return Response.json({ success: true, sessionId: realSessionId, data: result }); } catch (error) { // The child was spawned but the prompt never ran: without this cleanup a // failed set_model/set_thinking_level/prompt leaves an orphaned omp @@ -80,7 +79,7 @@ export async function POST(req: Request) { // wrapper stays for the reconnect (and disposing it would wait for the link). // Its id lets the client open it instead of starting a second session. if (error instanceof WebRpcError && error.code === "host_offline") { - return NextResponse.json({ error: error.message, code: error.code, hostOffline: true, delivery: error.delivery, sessionId: realSessionId }, { status: 503 }); + return Response.json({ error: error.message, code: error.code, hostOffline: true, delivery: error.delivery, sessionId: realSessionId }, { status: 503 }); } await session.destroyAndWait(); throw error; diff --git a/app/api/agents/route.ts b/app/api/agents/route.ts index 09ebbddf0..c6b3e60ed 100644 --- a/app/api/agents/route.ts +++ b/app/api/agents/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { existsSync, statSync } from "fs"; import { dirname, resolve } from "path"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; @@ -6,8 +5,6 @@ import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-fo import { AGENT_NAME_RE, MAX_AGENT_BYTES, deleteAgent, discoverAgents, readAgentFile, resolveAgentsScope, unpackBundled, validateAgentFileReference, validateAgentPayload, writeAgent, type AgentPayload } from "@/lib/omp/agents-service"; import { getProjectAgentsDir, getUserAgentsDir } from "@/lib/omp/paths"; -export const dynamic = "force-dynamic"; - // JSON can expand control characters in a maximum-size agent prompt to six // bytes each, with room for the envelope fields. const MAX_AGENT_REQUEST_BYTES = MAX_AGENT_BYTES * 6 + 64 * 1024; @@ -64,7 +61,7 @@ export async function GET(request: Request) { const cwd = project?.cwd; const result = await discoverAgents(cwd); const agents = scope === "all" ? result.agents : result.agents.filter((agent) => agent.scope === scope); - return NextResponse.json({ + return Response.json({ agents, diagnostics: result.diagnostics, userPath: getUserAgentsDir(), @@ -73,7 +70,7 @@ export async function GET(request: Request) { }); } catch (error) { const message = error instanceof Error ? error.message : String(error); - return NextResponse.json({ error: message }, { status: /not allowed/i.test(message) ? 403 : 400 }); + return Response.json({ error: message }, { status: /not allowed/i.test(message) ? 403 : 400 }); } } @@ -85,7 +82,7 @@ export async function POST(request: Request) { const project = body.scope === "project" ? await allowedProjectScope(body.cwd) : undefined; const cwd = project?.cwd; const targetDir = project?.dir ?? resolveAgentsScope(cwd, body.scope); - return NextResponse.json({ success: true, ...unpackBundled(targetDir, false) }); + return Response.json({ success: true, ...unpackBundled(targetDir, false) }); } if (body.scope !== "user" && body.scope !== "project") throw new Error("scope must be user or project"); const project = body.scope === "project" ? await allowedProjectScope(body.cwd) : undefined; @@ -97,11 +94,11 @@ export async function POST(request: Request) { const scopeDir = project?.dir ?? resolveAgentsScope(cwd, body.scope); const written = writeAgent(scopeDir, body.name.trim(), body.agent as AgentPayload, body.previousName); const agent = readAgentFile(written.path); - return NextResponse.json({ success: true, ...written, agent }); + return Response.json({ success: true, ...written, agent }); } catch (error) { - if (error instanceof RequestBodyTooLargeError) return NextResponse.json({ error: "Agent request is too large" }, { status: 413 }); + if (error instanceof RequestBodyTooLargeError) return Response.json({ error: "Agent request is too large" }, { status: 413 }); const message = error instanceof Error ? error.message : String(error); - return NextResponse.json({ error: message }, { status: /not allowed/i.test(message) ? 403 : 400 }); + return Response.json({ error: message }, { status: /not allowed/i.test(message) ? 403 : 400 }); } } @@ -117,11 +114,11 @@ export async function PUT(request: Request) { validateAgentPayload({ ...(body.agent as Record), name: body.name }); const scopeDir = project?.dir ?? resolveAgentsScope(cwd, body.scope); const written = writeAgent(scopeDir, body.name.trim(), body.agent as AgentPayload, body.previousName); - return NextResponse.json({ success: true, ...written, agent: readAgentFile(written.path) }); + return Response.json({ success: true, ...written, agent: readAgentFile(written.path) }); } catch (error) { - if (error instanceof RequestBodyTooLargeError) return NextResponse.json({ error: "Agent request is too large" }, { status: 413 }); + if (error instanceof RequestBodyTooLargeError) return Response.json({ error: "Agent request is too large" }, { status: 413 }); const message = error instanceof Error ? error.message : String(error); - return NextResponse.json({ error: message }, { status: /not allowed/i.test(message) ? 403 : 400 }); + return Response.json({ error: message }, { status: /not allowed/i.test(message) ? 403 : 400 }); } } @@ -134,11 +131,11 @@ export async function DELETE(request: Request) { if (typeof body.name !== "string" || !body.name.trim()) throw new Error("name is required"); const scopeDir = project?.dir ?? resolveAgentsScope(cwd, body.scope); validateAgentFileReference(scopeDir, body.name.trim()); - return NextResponse.json({ success: true, ...deleteAgent(scopeDir, body.name.trim()) }); + return Response.json({ success: true, ...deleteAgent(scopeDir, body.name.trim()) }); } catch (error) { - if (error instanceof RequestBodyTooLargeError) return NextResponse.json({ error: "Agent request is too large" }, { status: 413 }); + if (error instanceof RequestBodyTooLargeError) return Response.json({ error: "Agent request is too large" }, { status: 413 }); const message = error instanceof Error ? error.message : String(error); const status = /not found/i.test(message) ? 404 : /not allowed/i.test(message) ? 403 : 400; - return NextResponse.json({ error: message }, { status }); + return Response.json({ error: message }, { status }); } } diff --git a/app/api/app-update/notes/route.ts b/app/api/app-update/notes/route.ts index 475d9dd58..295325a35 100644 --- a/app/api/app-update/notes/route.ts +++ b/app/api/app-update/notes/route.ts @@ -1,8 +1,6 @@ import { getGitHubReleaseNotes } from "@/lib/github-release-notes"; import { checkNpmUpdate } from "@/lib/npm-update"; -export const dynamic = "force-dynamic"; - const NO_STORE_HEADERS = { "Cache-Control": "no-store" }; function noContent(): Response { diff --git a/app/api/app-update/route.ts b/app/api/app-update/route.ts index 47ae0cb5b..afc33bedd 100644 --- a/app/api/app-update/route.ts +++ b/app/api/app-update/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { isApiRequestOriginAllowed, shouldCheckApiRequestOrigin } from "@/lib/request-security"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { checkNpmUpdate } from "@/lib/npm-update"; @@ -15,8 +14,6 @@ import { validateCommitSelfUpdate, } from "@/lib/self-update"; -export const dynamic = "force-dynamic"; - type CommitResult = { accepted: true; attemptId: string }; async function commitAppUpdate(attemptId: string): Promise { @@ -39,11 +36,11 @@ async function commitAppUpdate(attemptId: string): Promise { } } -function errorResponse(error: unknown): NextResponse { +function errorResponse(error: unknown): Response { if (error instanceof SelfUpdateError) { - return NextResponse.json({ error: error.message, code: error.code }, { status: error.httpStatus }); + return Response.json({ error: error.message, code: error.code }, { status: error.httpStatus }); } - return NextResponse.json({ error: "The application update could not be started", code: "update_failed" }, { status: 500 }); + return Response.json({ error: "The application update could not be started", code: "update_failed" }, { status: 500 }); } export async function GET(request: Request) { @@ -51,7 +48,7 @@ export async function GET(request: Request) { const status = await checkNpmUpdate(force); const support = getSelfUpdateSupport(); const selfUpdateStatus = status.updatesDisabled ? null : getSelfUpdateStatus(); - return NextResponse.json({ + return Response.json({ ...status, selfUpdateSupported: support.supported, ...(selfUpdateStatus ? { selfUpdateStatus } : {}), @@ -60,10 +57,10 @@ export async function GET(request: Request) { export async function POST(request: Request) { if (shouldCheckApiRequestOrigin(request) && !isApiRequestOriginAllowed(request)) { - return NextResponse.json({ error: "Cross-origin API requests are not allowed", code: "cross_origin_forbidden" }, { status: 403 }); + return Response.json({ error: "Cross-origin API requests are not allowed", code: "cross_origin_forbidden" }, { status: 403 }); } if (request.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase() !== "application/json") { - return NextResponse.json({ error: "Content-Type must be application/json", code: "unsupported_media_type" }, { status: 415 }); + return Response.json({ error: "Content-Type must be application/json", code: "unsupported_media_type" }, { status: 415 }); } try { const body = await parseJsonWithinLimit | null>(request, 4_096); @@ -71,22 +68,22 @@ export async function POST(request: Request) { const keys = Object.keys(body); if (body.action === "prepare" && keys.length === 1) { const result = await prepareSelfUpdate(); - return NextResponse.json(result, { status: 202 }); + return Response.json(result, { status: 202 }); } if (body.action === "acknowledge" && keys.length === 2 && typeof body.attemptId === "string") { - return NextResponse.json(acknowledgeSelfUpdate(body.attemptId)); + return Response.json(acknowledgeSelfUpdate(body.attemptId)); } if (body.action === "commit" && keys.length === 2 && typeof body.attemptId === "string") { const result = await commitAppUpdate(body.attemptId); - return NextResponse.json(result, { status: 202 }); + return Response.json(result, { status: 202 }); } if (body.action === "status" && keys.length === 1) { const selfUpdateStatus = getSelfUpdateStatus(); - return NextResponse.json(selfUpdateStatus ?? null, { headers: { "Cache-Control": "no-store" } }); + return Response.json(selfUpdateStatus ?? null, { headers: { "Cache-Control": "no-store" } }); } throw new SelfUpdateError("invalid_action", "action must be prepare, commit, status, or acknowledge"); } catch (error) { - if (error instanceof RequestBodyTooLargeError) return NextResponse.json({ error: error.message, code: "body_too_large" }, { status: 413 }); + if (error instanceof RequestBodyTooLargeError) return Response.json({ error: error.message, code: "body_too_large" }, { status: 413 }); if (error instanceof SyntaxError) return errorResponse(new SelfUpdateError("invalid_json", "Request body must be valid JSON")); return errorResponse(error); } diff --git a/app/api/auth/accounts/[provider]/route.ts b/app/api/auth/accounts/[provider]/route.ts index c297aa8a0..54dbb6553 100644 --- a/app/api/auth/accounts/[provider]/route.ts +++ b/app/api/auth/accounts/[provider]/route.ts @@ -1,9 +1,6 @@ -import { NextResponse } from "next/server"; import { invalidateModelsCache } from "@/lib/models-cache"; import { runUtilityCommand } from "@/lib/omp/rpc-utility"; -export const dynamic = "force-dynamic"; - /** Entry of omp's `get_logout_accounts` response. Labels never carry a raw key. */ interface OmpProviderAccount { credentialId: number; @@ -33,14 +30,14 @@ export async function GET(_req: Request, { params }: { params: Promise<{ provide 30_000, ); const list = Array.isArray(accounts) ? accounts.filter(isAccount) : []; - return NextResponse.json({ + return Response.json({ supported: true, accounts: list.map(({ credentialId, label, detail, type }) => ({ credentialId, label, detail, type })), }); } catch (error) { const message = error instanceof Error ? error.message : String(error); - if (message.includes(UNSUPPORTED)) return NextResponse.json({ supported: false, accounts: [] }); - return NextResponse.json({ error: message }, { status: 500 }); + if (message.includes(UNSUPPORTED)) return Response.json({ supported: false, accounts: [] }); + return Response.json({ error: message }, { status: 500 }); } } @@ -49,17 +46,17 @@ export async function DELETE(req: Request, { params }: { params: Promise<{ provi const raw = new URL(req.url).searchParams.get("credentialId") ?? ""; const credentialId = Number(raw); if (!/^\d+$/.test(raw) || !Number.isSafeInteger(credentialId)) { - return NextResponse.json({ error: "credentialId must be an integer" }, { status: 400 }); + return Response.json({ error: "credentialId must be an integer" }, { status: 400 }); } const { provider } = await params; try { await runUtilityCommand({ type: "logout", providerId: provider, credentialId }, 60_000); invalidateModelsCache(); - return NextResponse.json({ ok: true }); + return Response.json({ ok: true }); } catch (error) { const message = error instanceof Error ? error.message : String(error); if (message.includes(UNSUPPORTED)) { - return NextResponse.json( + return Response.json( { error: "omp-web cannot disconnect accounts with this omp version. Update omp, or run `omp` in a terminal and use /logout.", code: "logout_unsupported", @@ -67,6 +64,6 @@ export async function DELETE(req: Request, { params }: { params: Promise<{ provi { status: 501 }, ); } - return NextResponse.json({ error: message }, { status: 500 }); + return Response.json({ error: message }, { status: 500 }); } } diff --git a/app/api/auth/all-providers/route.ts b/app/api/auth/all-providers/route.ts index f47c89d63..166e399f6 100644 --- a/app/api/auth/all-providers/route.ts +++ b/app/api/auth/all-providers/route.ts @@ -1,8 +1,6 @@ import { readModelsConfig } from "@/lib/omp/models-config"; import { type OmpLoginProvider, type OmpModel, runUtilityCommand } from "@/lib/omp/rpc-utility"; -export const dynamic = "force-dynamic"; - // omp exposes no "all known providers" query over RPC, and API keys live in // its SQLite credential store which omp-web must not touch. What we CAN see is // which providers currently resolve models (env keys, stored keys, models.yml) diff --git a/app/api/auth/api-key/[provider]/route.ts b/app/api/auth/api-key/[provider]/route.ts index 3a4bea2bb..0c74032a4 100644 --- a/app/api/auth/api-key/[provider]/route.ts +++ b/app/api/auth/api-key/[provider]/route.ts @@ -1,9 +1,6 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse } from "@/lib/api-utils"; import { type OmpLoginProvider, type OmpModel, runUtilityCommand } from "@/lib/omp/rpc-utility"; -export const dynamic = "force-dynamic"; - type Params = { params: Promise<{ provider: string }> }; // omp stores API keys in its encrypted SQLite credential store (agent.db), @@ -30,7 +27,7 @@ export async function GET(_req: Request, { params }: Params) { ); const loginProvider = loginProviders.find((p) => p.id === provider); const modelCount = models.filter((m) => m.provider === provider).length; - return NextResponse.json({ + return Response.json({ provider, displayName: loginProvider?.name ?? provider, configured: modelCount > 0 || loginProvider?.authenticated === true, @@ -44,7 +41,7 @@ export async function GET(_req: Request, { params }: Params) { // POST /api/auth/api-key/[provider] — not supported against omp's credential store export async function POST(_req: Request, { params }: Params) { const { provider } = await params; - return NextResponse.json( + return Response.json( { error: `Cannot store an API key for "${provider}" from omp-web. ${API_KEY_WRITE_GUIDANCE}`, code: "api_key_store_unsupported" }, { status: 501 }, ); @@ -53,7 +50,7 @@ export async function POST(_req: Request, { params }: Params) { // DELETE /api/auth/api-key/[provider] — not supported against omp's credential store export async function DELETE(_req: Request, { params }: Params) { const { provider } = await params; - return NextResponse.json( + return Response.json( { error: `Cannot remove the API key for "${provider}" from omp-web. ${API_KEY_WRITE_GUIDANCE}`, code: "api_key_remove_unsupported" }, { status: 501 }, ); diff --git a/app/api/auth/login/[provider]/route.ts b/app/api/auth/login/[provider]/route.ts index 052eaedab..69dcdcdfd 100644 --- a/app/api/auth/login/[provider]/route.ts +++ b/app/api/auth/login/[provider]/route.ts @@ -4,8 +4,6 @@ import { enableProvider } from "@/lib/omp/model-roles"; import { RpcProcess, type RpcFrame } from "@/lib/omp/rpc-process"; import { disposeUtilityRpc } from "@/lib/omp/rpc-utility"; -export const dynamic = "force-dynamic"; - /** * Interactive login over a dedicated `omp --mode rpc-ui` process. omp drives * the flow with extension_ui_request frames: `open_url` carries the OAuth URL, @@ -66,8 +64,9 @@ export async function POST( // GET /api/auth/login/[provider] — SSE stream for the login flow export async function GET( req: Request, - { params }: { params: Promise<{ provider: string }> } + { params, disableIdleTimeout }: { params: Promise<{ provider: string }>; disableIdleTimeout: () => void } ) { + disableIdleTimeout(); const { provider } = await params; const token = `${provider}-${Date.now()}-${Math.random().toString(36).slice(2)}`; const registry = getLoginRegistry(); @@ -85,7 +84,7 @@ export async function GET( } }; // OAuth flows sit idle while the user is in the browser; keep the SSE - // connection alive past proxy/Next idle timeouts. + // connection alive past reverse-proxy idle timeouts. const heartbeat = setInterval(() => { if (closed) return; try { diff --git a/app/api/auth/providers/route.ts b/app/api/auth/providers/route.ts index 803476d93..501844d6c 100644 --- a/app/api/auth/providers/route.ts +++ b/app/api/auth/providers/route.ts @@ -1,7 +1,5 @@ import { type OmpLoginProvider, runUtilityCommand } from "@/lib/omp/rpc-utility"; -export const dynamic = "force-dynamic"; - // Login-capable providers via the omp RPC get_login_providers command. This is // omp's own /login list (OAuth subscriptions plus key-creation flows), so no // hardcoded exclusions or display-name overrides are needed anymore. diff --git a/app/api/cwd/browse/route.ts b/app/api/cwd/browse/route.ts index 5c9ecb62c..9fd8343f6 100644 --- a/app/api/cwd/browse/route.ts +++ b/app/api/cwd/browse/route.ts @@ -1,4 +1,3 @@ -import { NextRequest, NextResponse } from "next/server"; import { apiErrorResponse } from "@/lib/api-utils"; import { stat } from "fs/promises"; import { @@ -11,11 +10,11 @@ import { } from "@/lib/directory-browser"; // GET /api/cwd/browse?path=... — lists readable subdirectories in the filesystem. -export async function GET(request: NextRequest) { +export async function GET(request: Request) { try { - const requested = request.nextUrl.searchParams.get("path")?.trim(); + const requested = new URL(request.url).searchParams.get("path")?.trim(); if (shouldShowWindowsDrivePicker(requested)) { - return NextResponse.json({ path: "", parentPath: null, drives: await listWindowsDrives(), directories: [] }); + return Response.json({ path: "", parentPath: null, drives: await listWindowsDrives(), directories: [] }); } const candidate = getBrowseStartDirectory(requested); @@ -23,18 +22,18 @@ export async function GET(request: NextRequest) { try { resolved = await resolveDirectory(candidate); } catch { - return NextResponse.json({ error: "Directory does not exist", code: "directory_not_found" }, { status: 404 }); + return Response.json({ error: "Directory does not exist", code: "directory_not_found" }, { status: 404 }); } const directoryStat = await stat(resolved); if (!directoryStat.isDirectory()) { - return NextResponse.json({ error: "Path is not a directory", code: "not_a_directory" }, { status: 400 }); + return Response.json({ error: "Path is not a directory", code: "not_a_directory" }, { status: 400 }); } const directories = await listDirectories(resolved); - return NextResponse.json({ + return Response.json({ path: resolved, parentPath: getParentDirectory(resolved), directories, diff --git a/app/api/cwd/validate/route.ts b/app/api/cwd/validate/route.ts index e4c3a3dde..1f8cb6a24 100644 --- a/app/api/cwd/validate/route.ts +++ b/app/api/cwd/validate/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse, opErrorResponse, resolveHostOrError } from "@/lib/api-utils"; import { allowFileRoot } from "@/lib/file-access"; import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; @@ -12,7 +11,7 @@ export async function POST(req: Request) { const cwd = typeof body.cwd === "string" ? body.cwd.trim() : ""; if (!cwd) { - return NextResponse.json({ error: "Path is required", code: "path_required" }, { status: 400 }); + return Response.json({ error: "Path is required", code: "path_required" }, { status: 400 }); } const target = resolveHostOrError(body.hostId); @@ -21,7 +20,7 @@ export async function POST(req: Request) { if (!result.ok) return opErrorResponse(result); // Browsable only on this machine: another host's paths do not exist here. if (target.host.id === LOCAL_HOST_ID) allowFileRoot(result.value.cwd); - return NextResponse.json({ + return Response.json({ success: true, cwd: result.value.cwd, projectRoot: result.value.projectRoot, diff --git a/app/api/default-cwd/route.ts b/app/api/default-cwd/route.ts index 49a7a902e..d30e04dab 100644 --- a/app/api/default-cwd/route.ts +++ b/app/api/default-cwd/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse } from "@/lib/api-utils"; import { mkdirSync } from "fs"; import { homedir } from "os"; @@ -13,7 +12,7 @@ export async function POST() { const dir = join(homedir(), `omp-cwd-${date}`); mkdirSync(dir, { recursive: true }); allowFileRoot(dir); - return NextResponse.json({ cwd: dir }); + return Response.json({ cwd: dir }); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/events/route.ts b/app/api/events/route.ts index c36a33a7d..0c163b7d9 100644 --- a/app/api/events/route.ts +++ b/app/api/events/route.ts @@ -1,15 +1,13 @@ -import { NextResponse } from "next/server"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { EventStreamConnection, getEventStreamConnection } from "@/lib/event-stream-hub"; import { parseEventStreamRequest, UNKNOWN_CONNECTION_CODE } from "@/lib/event-stream-protocol"; -export const dynamic = "force-dynamic"; - const MAX_REQUEST_BYTES = 16 * 1024; // GET /api/events — the browser's single multiplexed live-event stream. // Subscriptions are attached with POST (see lib/event-stream-protocol.ts). -export function GET(req: Request) { +export function GET(req: Request, { disableIdleTimeout }: { disableIdleTimeout: () => void }) { + disableIdleTimeout(); const connection = new EventStreamConnection(req.signal); return new Response(connection.stream, { headers: { @@ -28,22 +26,22 @@ export async function POST(req: Request) { body = await parseJsonWithinLimit(req, MAX_REQUEST_BYTES); } catch (error) { const status = error instanceof RequestBodyTooLargeError ? 413 : 400; - return NextResponse.json({ error: "Invalid event stream request", code: "invalid_event_stream_request" }, { status }); + return Response.json({ error: "Invalid event stream request", code: "invalid_event_stream_request" }, { status }); } const request = parseEventStreamRequest(body); if (!request) { - return NextResponse.json({ error: "Invalid event stream request", code: "invalid_event_stream_request" }, { status: 400 }); + return Response.json({ error: "Invalid event stream request", code: "invalid_event_stream_request" }, { status: 400 }); } const connection = getEventStreamConnection(request.connectionId); if (!connection) { - return NextResponse.json({ error: "Unknown event stream connection", code: UNKNOWN_CONNECTION_CODE }, { status: 404 }); + return Response.json({ error: "Unknown event stream connection", code: UNKNOWN_CONNECTION_CODE }, { status: 404 }); } if ("unsubscribe" in request) { connection.unsubscribe(request.unsubscribe); - return NextResponse.json({ ok: true }); + return Response.json({ ok: true }); } const result = await connection.subscribe(request.subscribe.id, request.subscribe.channel); return result.ok - ? NextResponse.json({ ok: true }) - : NextResponse.json({ error: result.error, code: result.code }, { status: result.status }); + ? Response.json({ ok: true }) + : Response.json({ error: result.error, code: result.code }, { status: result.status }); } diff --git a/app/api/file-index/route.ts b/app/api/file-index/route.ts index 8731050e1..a7685a057 100644 --- a/app/api/file-index/route.ts +++ b/app/api/file-index/route.ts @@ -1,4 +1,3 @@ -import { NextRequest, NextResponse } from "next/server"; import { apiErrorResponse } from "@/lib/api-utils"; import { execFile } from "child_process"; import { promisify } from "util"; @@ -51,7 +50,7 @@ interface CacheEntry { expiresAt: number; } -// Per-cwd cache on globalThis so it survives Next.js hot-reload; the @ menu +// Per-cwd cache on globalThis so it survives a `bun --hot` re-evaluation; the @ menu // re-requests on every open and searches on every keystroke, so listings must // not be recomputed within a short window. declare global { @@ -150,30 +149,31 @@ function listWithWalk(cwd: string): FileListing { // before ranking and reports a `truncated` flag; refresh=1 rebuilds the listing // instead of using the TTL cache, for the explorer's refresh button. // Guarded by the same allow-list as /api/files. -export async function GET(req: NextRequest) { +export async function GET(req: Request) { try { - const cwd = req.nextUrl.searchParams.get("cwd")?.trim() ?? ""; + const { searchParams } = new URL(req.url); + const cwd = searchParams.get("cwd")?.trim() ?? ""; if (!cwd || (!cwd.startsWith("/") && !isWindowsAbsolutePath(cwd))) { - return NextResponse.json({ error: "cwd must be an absolute path", code: "cwd_must_be_absolute" }, { status: 400 }); + return Response.json({ error: "cwd must be an absolute path", code: "cwd_must_be_absolute" }, { status: 400 }); } - const query = req.nextUrl.searchParams.get("q")?.slice(0, MAX_QUERY_LENGTH) ?? ""; + const query = searchParams.get("q")?.slice(0, MAX_QUERY_LENGTH) ?? ""; const allowedRoots = await getAllowedFileRoots(); if (!isFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } let stat: fs.Stats; try { stat = fs.statSync(cwd); } catch { - return NextResponse.json({ error: "Directory not found", code: "directory_not_found" }, { status: 404 }); + return Response.json({ error: "Directory not found", code: "directory_not_found" }, { status: 404 }); } if (!stat.isDirectory()) { - return NextResponse.json({ error: "Not a directory", code: "not_a_directory" }, { status: 400 }); + return Response.json({ error: "Not a directory", code: "not_a_directory" }, { status: 400 }); } if (!isExistingFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } const cache = getIndexCache(); @@ -182,7 +182,7 @@ export async function GET(req: NextRequest) { // or a file the agent just wrote stays invisible. loadListing collapses // concurrent rebuilds onto one scan, which is the whole bound: an age gate // on top of it can only suppress the refresh the user actually asked for. - const forceRefresh = req.nextUrl.searchParams.get("refresh") === "1"; + const forceRefresh = searchParams.get("refresh") === "1"; let cached = cache.get(cwd); if (!cached || cached.expiresAt <= now || forceRefresh) { const listing = await loadListing(cwd); @@ -199,13 +199,13 @@ export async function GET(req: NextRequest) { } if (query) { - const limit = parseResultLimit(req.nextUrl.searchParams.get("limit")); + const limit = parseResultLimit(searchParams.get("limit")); cached.entries ??= buildEntriesFromFiles(cached.listing.files); // Directories score a ranking bonus, so a caller that only renders files // must drop them before the limit is applied: "api" in this repo matches // 67 directories, which would otherwise consume half the budget and // silently push matching files out of the response. - if (req.nextUrl.searchParams.get("kind") === "file") { + if (searchParams.get("kind") === "file") { cached.fileEntries ??= cached.entries.filter((entry) => !entry.isDir); // Ask for one past the limit: the extra row never ships, it only tells // the panel that the list it shows is incomplete. A listing that hit the @@ -213,16 +213,16 @@ export async function GET(req: NextRequest) { // though fewer than `limit` rows matched what survived. const ranked = filterFileEntries(cached.fileEntries, query, limit + 1); const truncated = ranked.length > limit || cached.listing.hardTruncated; - return NextResponse.json({ + return Response.json({ matches: truncated ? ranked.slice(0, limit) : ranked, truncated, }); } - return NextResponse.json({ matches: filterFileEntries(cached.entries, query, limit) }); + return Response.json({ matches: filterFileEntries(cached.entries, query, limit) }); } const { files, hardTruncated } = cached.listing; - return NextResponse.json({ + return Response.json({ files: files.slice(0, MAX_FILES), truncated: hardTruncated || files.length > MAX_FILES, }); diff --git a/app/api/files/[...path]/route.ts b/app/api/files/[...path]/route.ts index 4f59f883e..f219f1e15 100644 --- a/app/api/files/[...path]/route.ts +++ b/app/api/files/[...path]/route.ts @@ -1,4 +1,3 @@ -import { NextRequest, NextResponse } from "next/server"; import { apiErrorResponse } from "@/lib/api-utils"; import { getContentDisposition } from "@/lib/content-disposition"; import fs from "fs"; @@ -71,7 +70,7 @@ function parseFileRequestType(value: string): FileRequestType | null { } async function getUploadDirectory(segments: string[]): Promise< - { directory: string } | { response: NextResponse } + { directory: string } | { response: Response } > { // Strictly absolute: unlike the read path this never fans a relative request // out over the allowed roots, which would turn "pick me a directory" into @@ -79,17 +78,17 @@ async function getUploadDirectory(segments: string[]): Promise< const directory = filePathFromSegments(segments); const allowedRoots = await getAllowedFileRoots(); if (!isFilePathAllowed(directory, allowedRoots)) { - return { response: NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }) }; + return { response: Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }) }; } let stat: fs.Stats; try { stat = fs.statSync(directory); } catch { - return { response: NextResponse.json({ error: "Upload directory not found", code: "upload_directory_not_found" }, { status: 404 }) }; + return { response: Response.json({ error: "Upload directory not found", code: "upload_directory_not_found" }, { status: 404 }) }; } if (!stat.isDirectory()) { - return { response: NextResponse.json({ error: "Upload target is not a directory", code: "upload_target_not_directory" }, { status: 400 }) }; + return { response: Response.json({ error: "Upload target is not a directory", code: "upload_target_not_directory" }, { status: 400 }) }; } // A browsable directory can be a symlink. Resolve both sides before writes @@ -104,7 +103,7 @@ async function getUploadDirectory(segments: string[]): Promise< } } if (!isFilePathAllowed(realDirectory, realRoots)) { - return { response: NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }) }; + return { response: Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }) }; } return { directory: realDirectory }; @@ -116,7 +115,7 @@ function parseUploadFileNames(value: unknown): string[] | null { } export async function POST( - request: NextRequest, + request: Request, { params }: { params: Promise<{ path: string[] }> } ) { try { @@ -124,34 +123,35 @@ export async function POST( const uploadDirectory = await getUploadDirectory(segments); if ("response" in uploadDirectory) return uploadDirectory.response; const { directory } = uploadDirectory; - const type = request.nextUrl.searchParams.get("type") ?? "upload"; + const { searchParams } = new URL(request.url); + const type = searchParams.get("type") ?? "upload"; if (type === "upload-check") { let body: { fileNames?: unknown } | null; try { body = await parseJsonWithinLimit<{ fileNames?: unknown }>(request, MAX_UPLOAD_CHECK_REQUEST_BYTES); } catch (error) { - if (error instanceof RequestBodyTooLargeError) return NextResponse.json({ error: "Upload check request is too large", code: "upload_check_too_large" }, { status: 413 }); + if (error instanceof RequestBodyTooLargeError) return Response.json({ error: "Upload check request is too large", code: "upload_check_too_large" }, { status: 413 }); body = null; } const fileNames = parseUploadFileNames(body?.fileNames); if (!fileNames) { - return NextResponse.json({ error: "fileNames must be an array of strings", code: "invalid_file_names" }, { status: 400 }); + return Response.json({ error: "fileNames must be an array of strings", code: "invalid_file_names" }, { status: 400 }); } const validationError = validateUploadFileNames(fileNames); if (validationError) { - return NextResponse.json({ error: validationError }, { status: 400 }); + return Response.json({ error: validationError }, { status: 400 }); } - return NextResponse.json(inspectUploadTargets(directory, fileNames)); + return Response.json(inspectUploadTargets(directory, fileNames)); } if (type !== "upload") { - return NextResponse.json({ error: "Invalid upload request type", code: "invalid_upload_type" }, { status: 400 }); + return Response.json({ error: "Invalid upload request type", code: "invalid_upload_type" }, { status: 400 }); } - const strategy = parseUploadConflictStrategy(request.nextUrl.searchParams.get("conflict")); + const strategy = parseUploadConflictStrategy(searchParams.get("conflict")); if (!strategy) { - return NextResponse.json({ error: "Invalid conflict strategy", code: "invalid_conflict_strategy" }, { status: 400 }); + return Response.json({ error: "Invalid conflict strategy", code: "invalid_conflict_strategy" }, { status: 400 }); } let formData: FormData; @@ -159,26 +159,26 @@ export async function POST( formData = await parseFormDataWithinLimit(request, MAX_UPLOAD_REQUEST_BYTES); } catch (error) { if (error instanceof RequestBodyTooLargeError) { - return NextResponse.json({ error: "Uploads must total 100MB or less", code: "upload_total_too_large" }, { status: 413 }); + return Response.json({ error: "Uploads must total 100MB or less", code: "upload_total_too_large" }, { status: 413 }); } throw error; } const files = formData.getAll("files").filter((entry): entry is File => typeof entry !== "string"); if (files.some((file) => file.size > MAX_UPLOAD_FILE_BYTES)) { - return NextResponse.json({ error: "Each upload must be 25MB or smaller", code: "upload_file_too_large" }, { status: 413 }); + return Response.json({ error: "Each upload must be 25MB or smaller", code: "upload_file_too_large" }, { status: 413 }); } if (files.reduce((total, file) => total + file.size, 0) > MAX_UPLOAD_TOTAL_BYTES) { - return NextResponse.json({ error: "Uploads must total 100MB or less", code: "upload_total_too_large" }, { status: 413 }); + return Response.json({ error: "Uploads must total 100MB or less", code: "upload_total_too_large" }, { status: 413 }); } const fileNames = files.map((file) => file.name); const validationError = validateUploadFileNames(fileNames); if (validationError) { - return NextResponse.json({ error: validationError }, { status: 400 }); + return Response.json({ error: validationError }, { status: 400 }); } const inspection = inspectUploadTargets(directory, fileNames); if (strategy === "error" && inspection.conflicts.length > 0) { - return NextResponse.json({ + return Response.json({ error: "One or more files already exist", code: "upload_conflict", conflicts: inspection.conflicts, @@ -231,12 +231,12 @@ export async function POST( } } - return NextResponse.json( + return Response.json( { uploaded, skipped, errors }, { status: errors.length > 0 ? 207 : 200 }, ); } catch (error) { - return NextResponse.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); + return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); } } @@ -400,67 +400,74 @@ ${bodyHtml} } export async function GET( - request: NextRequest, - { params }: { params: Promise<{ path: string[] }> } + request: Request, + { params, disableIdleTimeout }: { params: Promise<{ path: string[] }>; disableIdleTimeout: () => void } ) { try { const { path: segments } = await params; - const rawType = request.nextUrl.searchParams.get("type") ?? "list"; + const { searchParams } = new URL(request.url); + const rawType = searchParams.get("type") ?? "list"; const type = parseFileRequestType(rawType); if (!type) { - return NextResponse.json({ error: "Invalid file request type", code: "invalid_request_type" }, { status: 400 }); + return Response.json({ error: "Invalid file request type", code: "invalid_request_type" }, { status: 400 }); } - const sessionId = request.nextUrl.searchParams.get("sessionId"); + const sessionId = searchParams.get("sessionId"); const access = await authorizeFileAccess(segments, sessionId, type !== "list"); if (!access.ok) { - return NextResponse.json({ error: access.error, code: access.code }, { status: access.status }); + return Response.json({ error: access.error, code: access.code }, { status: access.status }); } const { filePath, stat } = access; + // A paused media element stops reading its stream, which Bun's idle timeout would cut. Lifted once the stream exists. + const stream = (contentType: string, asDownload = false) => { + const response = streamFile(filePath, stat, contentType, request.headers.get("range"), asDownload); + disableIdleTimeout(); + return response; + }; if (type === "read") { if (!stat.isFile()) { - return NextResponse.json({ error: "Not a file", code: "not_a_file" }, { status: 400 }); + return Response.json({ error: "Not a file", code: "not_a_file" }, { status: 400 }); } const imageMime = getImageMime(filePath); if (imageMime) { if (stat.size > IMAGE_PREVIEW_MAX_BYTES) { - return NextResponse.json({ error: "Image too large (>10MB)", code: "image_too_large" }, { status: 413 }); + return Response.json({ error: "Image too large (>10MB)", code: "image_too_large" }, { status: 413 }); } - return streamFile(filePath, stat, imageMime, request.headers.get("range")); + return stream(imageMime); } const audioMime = getAudioMime(filePath); if (audioMime) { - return streamFile(filePath, stat, audioMime, request.headers.get("range")); + return stream(audioMime); } const documentMime = getDocumentMime(filePath); if (documentMime) { - return streamFile(filePath, stat, documentMime, request.headers.get("range")); + return stream(documentMime); } if (stat.size > TEXT_PREVIEW_MAX_BYTES) { - return NextResponse.json({ error: "File too large for preview (>256KB)", code: "file_too_large_preview" }, { status: 413 }); + return Response.json({ error: "File too large for preview (>256KB)", code: "file_too_large_preview" }, { status: 413 }); } const content = fs.readFileSync(filePath, "utf-8"); const language = getLanguage(filePath); - return NextResponse.json({ content, language, size: stat.size }); + return Response.json({ content, language, size: stat.size }); } if (type === "download") { if (!stat.isFile()) { - return NextResponse.json({ error: "Not a file", code: "not_a_file" }, { status: 400 }); + return Response.json({ error: "Not a file", code: "not_a_file" }, { status: 400 }); } const mime = getImageMime(filePath) || getAudioMime(filePath) || getDocumentMime(filePath) || "application/octet-stream"; - return streamFile(filePath, stat, mime, request.headers.get("range"), true); + return stream(mime, true); } if (type === "meta") { if (!stat.isFile()) { - return NextResponse.json({ error: "Not a file", code: "not_a_file" }, { status: 400 }); + return Response.json({ error: "Not a file", code: "not_a_file" }, { status: 400 }); } const imageMime = getImageMime(filePath); const audioMime = getAudioMime(filePath); const documentMime = getDocumentMime(filePath); - return NextResponse.json({ + return Response.json({ size: stat.size, language: getLanguage(filePath), mime: imageMime || audioMime || documentMime || "text/plain", @@ -470,13 +477,13 @@ export async function GET( if (type === "preview") { if (!stat.isFile()) { - return NextResponse.json({ error: "Not a file", code: "not_a_file" }, { status: 400 }); + return Response.json({ error: "Not a file", code: "not_a_file" }, { status: 400 }); } if (getFileExt(filePath) !== "docx") { - return NextResponse.json({ error: "Preview not available for this file type", code: "preview_unavailable" }, { status: 400 }); + return Response.json({ error: "Preview not available for this file type", code: "preview_unavailable" }, { status: 400 }); } if (stat.size > DOCX_PREVIEW_MAX_BYTES) { - return NextResponse.json({ error: "DOCX too large for preview (>10MB)", code: "docx_too_large" }, { status: 413 }); + return Response.json({ error: "DOCX too large for preview (>10MB)", code: "docx_too_large" }, { status: 413 }); } const mammoth = await import("mammoth"); @@ -501,7 +508,7 @@ export async function GET( // type === "list" if (!stat.isDirectory()) { - return NextResponse.json({ error: "Not a directory", code: "not_a_directory" }, { status: 400 }); + return Response.json({ error: "Not a directory", code: "not_a_directory" }, { status: 400 }); } // Avoid per-entry stat calls for normal files and directories. Symlinks and @@ -522,7 +529,7 @@ export async function GET( return a.name.localeCompare(b.name); }); - return NextResponse.json({ entries, path: filePath }); + return Response.json({ entries, path: filePath }); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/git/diff/route.ts b/app/api/git/diff/route.ts index 924c0993d..79f2d1076 100644 --- a/app/api/git/diff/route.ts +++ b/app/api/git/diff/route.ts @@ -1,28 +1,28 @@ -import { NextRequest, NextResponse } from "next/server"; import { getAllowedFileRoots, isExistingFilePathAllowed, isFilePathAllowed, isWindowsAbsolutePath } from "@/lib/file-access"; import { getGitFileDiff } from "@/lib/git-changes"; -export async function GET(request: NextRequest) { +export async function GET(request: Request) { try { - const cwd = request.nextUrl.searchParams.get("cwd")?.trim() ?? ""; - const filePath = request.nextUrl.searchParams.get("path")?.trim() ?? ""; + const { searchParams } = new URL(request.url); + const cwd = searchParams.get("cwd")?.trim() ?? ""; + const filePath = searchParams.get("path")?.trim() ?? ""; if (!cwd || (!cwd.startsWith("/") && !isWindowsAbsolutePath(cwd))) { - return NextResponse.json({ error: "cwd must be an absolute path", code: "cwd_must_be_absolute" }, { status: 400 }); + return Response.json({ error: "cwd must be an absolute path", code: "cwd_must_be_absolute" }, { status: 400 }); } if (!filePath || (!filePath.startsWith("/") && !isWindowsAbsolutePath(filePath))) { - return NextResponse.json({ error: "path must be an absolute path", code: "path_must_be_absolute" }, { status: 400 }); + return Response.json({ error: "path must be an absolute path", code: "path_must_be_absolute" }, { status: 400 }); } const allowedRoots = await getAllowedFileRoots(); if (!isFilePathAllowed(cwd, allowedRoots) || !isFilePathAllowed(filePath, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } if (!isExistingFilePathAllowed(cwd, allowedRoots) || !isExistingFilePathAllowed(filePath, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } - return NextResponse.json(await getGitFileDiff(cwd, filePath)); + return Response.json(await getGitFileDiff(cwd, filePath)); } catch (error) { - return NextResponse.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); + return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); } } diff --git a/app/api/git/status/route.ts b/app/api/git/status/route.ts index 2e9488a3f..c446f5f99 100644 --- a/app/api/git/status/route.ts +++ b/app/api/git/status/route.ts @@ -1,35 +1,34 @@ import fs from "fs"; -import { NextRequest, NextResponse } from "next/server"; import { getAllowedFileRoots, isExistingFilePathAllowed, isFilePathAllowed, isWindowsAbsolutePath } from "@/lib/file-access"; import { getGitStatus } from "@/lib/git-changes"; -export async function GET(request: NextRequest) { +export async function GET(request: Request) { try { - const cwd = request.nextUrl.searchParams.get("cwd")?.trim() ?? ""; + const cwd = new URL(request.url).searchParams.get("cwd")?.trim() ?? ""; if (!cwd || (!cwd.startsWith("/") && !isWindowsAbsolutePath(cwd))) { - return NextResponse.json({ error: "cwd must be an absolute path", code: "cwd_must_be_absolute" }, { status: 400 }); + return Response.json({ error: "cwd must be an absolute path", code: "cwd_must_be_absolute" }, { status: 400 }); } const allowedRoots = await getAllowedFileRoots(); if (!isFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } let stat: fs.Stats; try { stat = fs.statSync(cwd); } catch { - return NextResponse.json({ error: "Directory not found", code: "directory_not_found" }, { status: 404 }); + return Response.json({ error: "Directory not found", code: "directory_not_found" }, { status: 404 }); } if (!stat.isDirectory()) { - return NextResponse.json({ error: "Not a directory", code: "not_a_directory" }, { status: 400 }); + return Response.json({ error: "Not a directory", code: "not_a_directory" }, { status: 400 }); } if (!isExistingFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } - return NextResponse.json(await getGitStatus(cwd)); + return Response.json(await getGitStatus(cwd)); } catch (error) { - return NextResponse.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); + return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); } } diff --git a/app/api/github-repo/route.ts b/app/api/github-repo/route.ts index 11523d20b..a90b4a242 100644 --- a/app/api/github-repo/route.ts +++ b/app/api/github-repo/route.ts @@ -1,28 +1,27 @@ import fs from "fs"; -import { NextRequest, NextResponse } from "next/server"; import { getAllowedFileRoots, isExistingFilePathAllowed, isFilePathAllowed, isWindowsAbsolutePath } from "@/lib/file-access"; import { resolveGithubRepo } from "@/lib/github-repo"; -export async function GET(request: NextRequest) { - const cwd = request.nextUrl.searchParams.get("cwd")?.trim() ?? ""; +export async function GET(request: Request) { + const cwd = new URL(request.url).searchParams.get("cwd")?.trim() ?? ""; if (!cwd || (!cwd.startsWith("/") && !isWindowsAbsolutePath(cwd))) { - return NextResponse.json({ error: "cwd must be an absolute path", code: "cwd_must_be_absolute" }, { status: 400 }); + return Response.json({ error: "cwd must be an absolute path", code: "cwd_must_be_absolute" }, { status: 400 }); } const allowedRoots = await getAllowedFileRoots(); if (!isFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } let stat: fs.Stats; try { stat = fs.statSync(cwd); } catch { - return NextResponse.json({ error: "Directory not found", code: "directory_not_found" }, { status: 404 }); + return Response.json({ error: "Directory not found", code: "directory_not_found" }, { status: 404 }); } if (!stat.isDirectory()) { - return NextResponse.json({ error: "Not a directory", code: "not_a_directory" }, { status: 400 }); + return Response.json({ error: "Not a directory", code: "not_a_directory" }, { status: 400 }); } if (!isExistingFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } - return NextResponse.json({ repo: await resolveGithubRepo(cwd) }); + return Response.json({ repo: await resolveGithubRepo(cwd) }); } diff --git a/app/api/home/route.ts b/app/api/home/route.ts index a21f3d662..bea1117d3 100644 --- a/app/api/home/route.ts +++ b/app/api/home/route.ts @@ -1,6 +1,5 @@ -import { NextResponse } from "next/server"; import { homedir } from "os"; export async function GET() { - return NextResponse.json({ home: homedir() }); + return Response.json({ home: homedir() }); } diff --git a/app/api/hosts/link/blob/[reqId]/route.ts b/app/api/hosts/link/blob/[reqId]/route.ts index f4f9b0287..1df0bdc0b 100644 --- a/app/api/hosts/link/blob/[reqId]/route.ts +++ b/app/api/hosts/link/blob/[reqId]/route.ts @@ -1,9 +1,7 @@ import { handleLinkBlob } from "@/lib/hosts/hub"; -export const dynamic = "force-dynamic"; - // POST /api/hosts/link/blob/ — the bytes of one large host op result, // uploaded by the daemon before its `res` line (lib/hosts/hub.ts). -export async function POST(req: Request, { params }: { params: Promise<{ reqId: string }> }) { - return handleLinkBlob(req, (await params).reqId); +export async function POST(req: Request, { params, disableIdleTimeout }: { params: Promise<{ reqId: string }>; disableIdleTimeout: () => void }) { + return handleLinkBlob(req, (await params).reqId, disableIdleTimeout); } diff --git a/app/api/hosts/link/route.ts b/app/api/hosts/link/route.ts index 72a780d1d..151ea6cb8 100644 --- a/app/api/hosts/link/route.ts +++ b/app/api/hosts/link/route.ts @@ -1,16 +1,16 @@ import { handleLinkGet, handleLinkPost } from "@/lib/hosts/hub"; -export const dynamic = "force-dynamic"; - // The `ompweb host` daemon's link (lib/hosts/hub.ts). proxy.ts does not run -// for this path: the hub checks the host's bearer token before reading a body. +// for this path: the hub checks the host's bearer token before reading a body, +// and only then lifts Bun's idle timeout (disableIdleTimeout, server/app.ts). +type Context = { disableIdleTimeout: () => void }; // GET /api/hosts/link — downlink: a long-lived NDJSON stream, server → daemon. -export function GET(req: Request) { - return handleLinkGet(req); +export function GET(req: Request, { disableIdleTimeout }: Context) { + return handleLinkGet(req, disableIdleTimeout); } // POST /api/hosts/link — uplink: a batch of NDJSON messages, daemon → server. -export function POST(req: Request) { - return handleLinkPost(req); +export function POST(req: Request, { disableIdleTimeout }: Context) { + return handleLinkPost(req, disableIdleTimeout); } diff --git a/app/api/hosts/route.ts b/app/api/hosts/route.ts index 583093187..df5cf3087 100644 --- a/app/api/hosts/route.ts +++ b/app/api/hosts/route.ts @@ -1,14 +1,11 @@ -import { NextResponse } from "next/server"; import { closeHostLink, hostsSnapshot, listHosts, notifyHostsChange } from "@/lib/hosts/hub"; import { createHost, HostRegistryUnreadableError, revokeHost, UnknownHostError, updateHost } from "@/lib/hosts/registry"; import { isRecord } from "@/lib/type-guards"; -export const dynamic = "force-dynamic"; - const MAX_LABEL_LENGTH = 100; const noStore = { "cache-control": "no-store" }; -const fail = (error: string, status: number) => NextResponse.json({ error }, { status, headers: noStore }); +const fail = (error: string, status: number) => Response.json({ error }, { status, headers: noStore }); function failFor(error: unknown) { if (error instanceof HostRegistryUnreadableError) { @@ -50,7 +47,7 @@ function requestOrigin(req: Request): string { } export function GET() { - return NextResponse.json(hostsSnapshot(), { headers: noStore }); + return Response.json(hostsSnapshot(), { headers: noStore }); } export async function POST(req: Request) { @@ -60,7 +57,7 @@ export async function POST(req: Request) { try { const { host, token } = createHost(label); notifyHostsChange(); - return NextResponse.json( + return Response.json( { host: listHosts().find((h) => h.id === host.id), token, @@ -87,7 +84,7 @@ export async function PATCH(req: Request) { try { updateHost(body.id, { label, allowAgentStart }); notifyHostsChange(); - return NextResponse.json({ host: hostsSnapshot().hosts.find((h) => h.id === body.id) }, { headers: noStore }); + return Response.json({ host: hostsSnapshot().hosts.find((h) => h.id === body.id) }, { headers: noStore }); } catch (error) { return failFor(error); } @@ -102,7 +99,7 @@ export async function DELETE(req: Request) { if (!revokeHost(id)) return fail("Unknown host", 404); closeHostLink(id); notifyHostsChange(); - return NextResponse.json({ ok: true }, { headers: noStore }); + return Response.json({ ok: true }, { headers: noStore }); } catch (error) { return failFor(error); } diff --git a/app/api/manifest/route.ts b/app/api/manifest/route.ts index c31282b98..87078766c 100644 --- a/app/api/manifest/route.ts +++ b/app/api/manifest/route.ts @@ -1,14 +1,15 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; -import type { MetadataRoute } from "next"; import { getInstallName } from "@/lib/install-name"; -// Packaged public assets are read/encoded once per server module. Native -// installers fetch HTTP icons without cookies, even with a credentialed manifest. +// Packaged public assets are read/encoded once per server module, from the +// package directory the launcher names (the working directory is wherever +// ompweb was started). Native installers fetch HTTP icons without cookies, +// even with a credentialed manifest. const pngDataUrl = (filename: string) => - `data:image/png;base64,${readFileSync(join(process.cwd(), "public", filename)).toString("base64")}`; + `data:image/png;base64,${readFileSync(join(process.env.OMP_WEB_PACKAGE_DIR ?? process.cwd(), "public", filename)).toString("base64")}`; -const manifest: MetadataRoute.Manifest = { +const manifest = { description: "Web UI for the oh-my-pi (omp) coding agent", start_url: "/", scope: "/", diff --git a/app/api/mcp/route.ts b/app/api/mcp/route.ts index 279d88394..dc88a511c 100644 --- a/app/api/mcp/route.ts +++ b/app/api/mcp/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; import { deleteMcpServer, parseMcpListOutput, readDiscoveredMcpServers, readMcpConfig, readUserMcpConfig, type McpLiveServer, validateMcpServer, writeMcpServer } from "@/lib/omp/mcp-config"; import { WebRpcError, getRpcSession, startRpcSession } from "@/lib/rpc-manager"; @@ -9,12 +8,11 @@ import { RpcCommandError } from "@/lib/omp/rpc-process"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { redactMcpServer } from "@/lib/omp/mcp-config"; -export const dynamic = "force-dynamic"; const MAX_MCP_REQUEST_BYTES = 1024 * 1024; function mcpErrorResponse(error: unknown) { const status = error instanceof RequestBodyTooLargeError ? 413 : 400; - return NextResponse.json({ error: error instanceof RequestBodyTooLargeError ? "MCP request is too large" : error instanceof Error ? error.message : String(error) }, { status }); + return Response.json({ error: error instanceof RequestBodyTooLargeError ? "MCP request is too large" : error instanceof Error ? error.message : String(error) }, { status }); } /** Stable client-safe message for the GET liveError field: raw child-process @@ -107,7 +105,7 @@ export async function GET(request: Request) { liveError = sanitizeMcpLiveError(error); } } - return NextResponse.json({ root: file?.root ?? null, path: file?.path ?? null, exists: file?.exists ?? false, servers: Object.entries(file?.config.mcpServers ?? {}).sort(([a], [b]) => a.localeCompare(b)).map(([name, config]) => ({ name, config: redactMcpServer(config) })), user: safeUser, inventory, liveServers, liveError }); + return Response.json({ root: file?.root ?? null, path: file?.path ?? null, exists: file?.exists ?? false, servers: Object.entries(file?.config.mcpServers ?? {}).sort(([a], [b]) => a.localeCompare(b)).map(([name, config]) => ({ name, config: redactMcpServer(config) })), user: safeUser, inventory, liveServers, liveError }); } catch (error) { return mcpErrorResponse(error); } @@ -119,7 +117,7 @@ export async function POST(request: Request) { const cwd = await allowedCwd(body.cwd); validateMcpServer(body.name, body.server); if (body.previousName !== undefined && typeof body.previousName !== "string") throw new Error("previousName must be a string"); - return NextResponse.json({ success: true, ...writeMcpServer(cwd, body.name as string, body.server, body.previousName) }); + return Response.json({ success: true, ...writeMcpServer(cwd, body.name as string, body.server, body.previousName) }); } catch (error) { return mcpErrorResponse(error); } @@ -129,7 +127,7 @@ export async function PUT(request: Request) { try { const body = await parseJsonWithinLimit<{ name?: unknown; server?: unknown }>(request, MAX_MCP_REQUEST_BYTES); validateMcpServer(body.name, body.server); - return NextResponse.json({ success: true, message: "MCP server configuration is valid" }); + return Response.json({ success: true, message: "MCP server configuration is valid" }); } catch (error) { return mcpErrorResponse(error); } @@ -140,7 +138,7 @@ export async function DELETE(request: Request) { const body = await parseJsonWithinLimit<{ cwd?: unknown; name?: unknown }>(request, MAX_MCP_REQUEST_BYTES); const cwd = await allowedCwd(body.cwd); if (typeof body.name !== "string") throw new Error("name is required"); - return NextResponse.json({ success: true, ...deleteMcpServer(cwd, body.name) }); + return Response.json({ success: true, ...deleteMcpServer(cwd, body.name) }); } catch (error) { return mcpErrorResponse(error); } @@ -162,10 +160,10 @@ export async function PATCH(request: Request) { if (!target) throw new Error("Session not found"); ({ session } = await startRpcSession(body.sessionId, target.sessionFile, target.cwd, undefined, undefined, target.recordedCwd, undefined, host)); } - if (session.isRunning()) return NextResponse.json({ error: "Wait for the current run to finish before changing MCP servers." }, { status: 409 }); + if (session.isRunning()) return Response.json({ error: "Wait for the current run to finish before changing MCP servers." }, { status: 409 }); await session.changeMcp(body.action, typeof body.name === "string" ? body.name : undefined); - return NextResponse.json({ success: true }); + return Response.json({ success: true }); } catch (error) { - return NextResponse.json({ error: sanitizeMcpLiveError(error) }, { status: error instanceof WebRpcError && error.code === "session_busy" ? 409 : 400 }); + return Response.json({ error: sanitizeMcpLiveError(error) }, { status: error instanceof WebRpcError && error.code === "session_busy" ? 409 : 400 }); } } diff --git a/app/api/media/[hash]/route.ts b/app/api/media/[hash]/route.ts index bc38d2479..8ef489355 100644 --- a/app/api/media/[hash]/route.ts +++ b/app/api/media/[hash]/route.ts @@ -2,10 +2,8 @@ import { readFile } from "node:fs/promises"; import { fetchMediaFromHosts } from "@/lib/hosts/session-index"; import { createThumbnail, existingThumbnail, imageMimeType, mediaFilePath, storeMediaCopy } from "@/lib/media-cache"; -export const dynamic = "force-dynamic"; - -function image(body: Buffer, type: string, immutable = true): Response { - // A view, not a copy: these buffers come from readFile/sharp, never a SharedArrayBuffer. +function image(body: Uint8Array, type: string, immutable = true): Response { + // A view, not a copy: these buffers come from readFile/Bun.Image, never a SharedArrayBuffer. return new Response(new Uint8Array(body.buffer as ArrayBuffer, body.byteOffset, body.byteLength), { headers: { "Content-Type": type, diff --git a/app/api/model-roles/route.ts b/app/api/model-roles/route.ts index aca4af4ad..4bfcbb63d 100644 --- a/app/api/model-roles/route.ts +++ b/app/api/model-roles/route.ts @@ -1,14 +1,11 @@ -import { NextResponse } from "next/server"; import { invalidateModelsCache } from "@/lib/models-cache"; import { readModelRoles, writeModelRoles } from "@/lib/omp/model-roles"; -export const dynamic = "force-dynamic"; - export function GET() { try { - return NextResponse.json(readModelRoles()); + return Response.json(readModelRoles()); } catch (error) { - return NextResponse.json({ error: String(error) }, { status: 400 }); + return Response.json({ error: String(error) }, { status: 400 }); } } @@ -16,15 +13,15 @@ export async function PUT(request: Request) { try { const body = await request.json() as { roles?: unknown }; if (!body.roles || typeof body.roles !== "object" || Array.isArray(body.roles)) { - return NextResponse.json({ error: "roles must be an object" }, { status: 400 }); + return Response.json({ error: "roles must be an object" }, { status: 400 }); } const roles = Object.fromEntries(Object.entries(body.roles).filter((entry): entry is [string, string] => typeof entry[1] === "string" && entry[0].trim().length > 0 && entry[1].trim().length > 0, )); writeModelRoles(roles); invalidateModelsCache(); - return NextResponse.json({ success: true, roles }); + return Response.json({ success: true, roles }); } catch (error) { - return NextResponse.json({ error: String(error) }, { status: 400 }); + return Response.json({ error: String(error) }, { status: 400 }); } } diff --git a/app/api/models-config/catalog/route.ts b/app/api/models-config/catalog/route.ts index 4dcf7f513..a44487317 100644 --- a/app/api/models-config/catalog/route.ts +++ b/app/api/models-config/catalog/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { flattenModelsDevCatalog, recommendModelCatalogPreset, @@ -6,8 +5,6 @@ import { type ModelCatalogEntry, } from "@/lib/model-catalog"; -export const dynamic = "force-dynamic"; - const MODELS_DEV_URL = "https://models.dev/api.json"; const CATALOG_TTL_MS = 60 * 60 * 1000; const FETCH_TIMEOUT_MS = 15_000; @@ -74,8 +71,8 @@ export async function GET(req: Request) { const entries = await loadCatalog(); const models = searchModelCatalog(entries, query, provider, limit); const recommendation = recommendModelCatalogPreset(entries, query, provider, baseUrl); - return NextResponse.json({ models, recommendation, source: MODELS_DEV_URL }); + return Response.json({ models, recommendation, source: MODELS_DEV_URL }); } catch (error) { - return NextResponse.json({ error: error instanceof Error ? error.message : String(error) }, { status: 502 }); + return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 502 }); } } diff --git a/app/api/models-config/route.ts b/app/api/models-config/route.ts index 7249e7b0b..a9ecb4b33 100644 --- a/app/api/models-config/route.ts +++ b/app/api/models-config/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse } from "@/lib/api-utils"; import { invalidateModelsCache } from "@/lib/models-cache"; import { disposeUtilityRpc } from "@/lib/omp/rpc-utility"; @@ -10,21 +9,19 @@ import { type ModelsFileConfig, } from "@/lib/omp/models-config"; -export const dynamic = "force-dynamic"; - export async function GET() { const file = readModelsConfigFile(); if (file.parseError) { // The editor must show the failure instead of an empty form — an empty // form invites a Save that would wipe the user's real providers. - return NextResponse.json({ + return Response.json({ providers: {}, parseError: file.parseError, path: file.path, code: "models_config_unparseable", }); } - return NextResponse.json(file.config); + return Response.json(file.config); } // PUT /api/models-config[?overwrite=true] @@ -36,13 +33,13 @@ export async function PUT(req: Request) { try { validateModelsConfig(body); } catch (error) { - return NextResponse.json({ error: error instanceof Error ? error.message : String(error) }, { status: 400 }); + return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 400 }); } try { writeModelsConfig(body, { overwriteUnparseable }); } catch (error) { if (error instanceof ModelsConfigParseError) { - return NextResponse.json( + return Response.json( { error: `${error.message} — fix it by hand; omp-web will not overwrite it`, code: "models_config_unparseable" }, { status: 409 }, ); @@ -53,7 +50,7 @@ export async function PUT(req: Request) { // The utility process loads models.yml once at startup. A cache flush alone // would still query that stale registry after a provider was added. disposeUtilityRpc(); - return NextResponse.json({ success: true }); + return Response.json({ success: true }); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/models-config/test/route.ts b/app/api/models-config/test/route.ts index 576572b1d..e576c1091 100644 --- a/app/api/models-config/test/route.ts +++ b/app/api/models-config/test/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { mkdtempSync, rmSync, writeFileSync } from "fs"; import { tmpdir } from "os"; import { join } from "path"; @@ -11,8 +10,6 @@ import { import { type OmpModel, runIsolatedUtilityCommand } from "@/lib/omp/rpc-utility"; import { isRecord } from "@/lib/type-guards"; -export const dynamic = "force-dynamic"; - // Registry resolution (spawn + model discovery), not a completion round-trip: // omp-web cannot send test prompts without going through a full agent session. const TEST_TIMEOUT_MS = 60_000; @@ -27,12 +24,12 @@ export async function POST(req: Request) { try { const body = await req.json() as { providerName?: unknown; provider?: unknown; model?: unknown }; const providerName = typeof body.providerName === "string" ? body.providerName.trim() : ""; - if (!providerName) return NextResponse.json({ ok: false, error: "providerName is required", code: "provider_name_required" }, { status: 400 }); - if (!isRecord(body.provider)) return NextResponse.json({ ok: false, error: "provider is required", code: "provider_required" }, { status: 400 }); - if (!isRecord(body.model)) return NextResponse.json({ ok: false, error: "model is required", code: "model_required" }, { status: 400 }); + if (!providerName) return Response.json({ ok: false, error: "providerName is required", code: "provider_name_required" }, { status: 400 }); + if (!isRecord(body.provider)) return Response.json({ ok: false, error: "provider is required", code: "provider_required" }, { status: 400 }); + if (!isRecord(body.model)) return Response.json({ ok: false, error: "model is required", code: "model_required" }, { status: 400 }); const modelId = typeof body.model.id === "string" ? body.model.id.trim() : ""; - if (!modelId) return NextResponse.json({ ok: false, error: "Model ID is required", code: "model_id_required" }, { status: 400 }); + if (!modelId) return Response.json({ ok: false, error: "Model ID is required", code: "model_id_required" }, { status: 400 }); const config = { providers: { @@ -45,7 +42,7 @@ export async function POST(req: Request) { try { validateModelsConfig(config); } catch (error) { - return NextResponse.json({ ok: false, error: errorMessage(error) }); + return Response.json({ ok: false, error: errorMessage(error) }); } // Isolated throwaway agent dir: the spawned omp sees only this candidate @@ -68,7 +65,7 @@ export async function POST(req: Request) { const found = models.find((m) => m.provider === providerName && m.id === modelId); if (!found) { - return NextResponse.json({ + return Response.json({ ok: false, error: `Model ${providerName}/${modelId} did not resolve — check the API key and provider config`, code: "model_test_unresolved", @@ -76,13 +73,13 @@ export async function POST(req: Request) { }); } - return NextResponse.json({ + return Response.json({ ok: true, latencyMs, responseText: `${found.provider}/${found.id} resolved (configuration only; credentials were not contacted)`, }); } catch (error) { - return NextResponse.json({ ok: false, error: errorMessage(error) }, { status: 500 }); + return Response.json({ ok: false, error: errorMessage(error) }, { status: 500 }); } finally { if (tempDir) rmSync(tempDir, { recursive: true, force: true }); } diff --git a/app/api/models/route.ts b/app/api/models/route.ts index b69b82ee5..da870d50a 100644 --- a/app/api/models/route.ts +++ b/app/api/models/route.ts @@ -5,8 +5,6 @@ import { getModelsConfigPath } from "@/lib/omp/paths"; import { readDisabledProviders } from "@/lib/omp/model-roles"; import { readAnthropicSlowMode } from "@/lib/omp/settings-config"; -export const dynamic = "force-dynamic"; - // The omp model registry (auth + models.yml) is global, not per-cwd, so one // cache entry serves every request. The ?cwd= query parameter is still // accepted for client compatibility but no longer affects the result. diff --git a/app/api/notifications/devices/route.ts b/app/api/notifications/devices/route.ts index 53e91a41b..c58ac51ae 100644 --- a/app/api/notifications/devices/route.ts +++ b/app/api/notifications/devices/route.ts @@ -1,26 +1,23 @@ -import { NextResponse } from "next/server"; import { isValidNotificationId, parseNotificationPrefs } from "@/lib/notification-events"; import { getVapidPublicKey } from "@/lib/notification-hub"; import { getDevice, parsePushSubscription, saveDevice } from "@/lib/notification-store"; import { isRecord } from "@/lib/type-guards"; -export const dynamic = "force-dynamic"; - /** GET /api/notifications/devices?deviceId= — VAPID public key and whether this device has a push subscription. */ export async function GET(req: Request) { const deviceId = new URL(req.url).searchParams.get("deviceId"); const device = isValidNotificationId(deviceId) ? getDevice(deviceId) : undefined; - return NextResponse.json({ publicKey: getVapidPublicKey(), subscribed: Boolean(device?.subscription) }); + return Response.json({ publicKey: getVapidPublicKey(), subscribed: Boolean(device?.subscription) }); } /** PUT /api/notifications/devices { deviceId, prefs, subscription? } — an omitted subscription keeps the stored one. */ export async function PUT(req: Request) { const body: unknown = await req.json().catch(() => null); if (!isRecord(body) || !isValidNotificationId(body.deviceId)) { - return NextResponse.json({ error: "deviceId is required", code: "invalid_device" }, { status: 400 }); + return Response.json({ error: "deviceId is required", code: "invalid_device" }, { status: 400 }); } const subscription = body.subscription === undefined ? undefined : parsePushSubscription(body.subscription); - if (subscription === null) return NextResponse.json({ error: "Invalid push subscription", code: "invalid_subscription" }, { status: 400 }); + if (subscription === null) return Response.json({ error: "Invalid push subscription", code: "invalid_subscription" }, { status: 400 }); const device = saveDevice(body.deviceId, parseNotificationPrefs(body.prefs), subscription); - return NextResponse.json({ subscribed: Boolean(device.subscription) }); + return Response.json({ subscribed: Boolean(device.subscription) }); } diff --git a/app/api/notifications/history/route.ts b/app/api/notifications/history/route.ts index eee8b690c..5272b54ed 100644 --- a/app/api/notifications/history/route.ts +++ b/app/api/notifications/history/route.ts @@ -1,20 +1,17 @@ -import { NextResponse } from "next/server"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { clearHistory, listHistory, markHistoryRead, removeHistory } from "@/lib/notification-store"; import { isRecord } from "@/lib/type-guards"; -export const dynamic = "force-dynamic"; - const MAX_BODY_BYTES = 32 * 1024; const MAX_IDS = 100; const MAX_ID_LENGTH = 256; -const invalid = () => NextResponse.json({ error: "Invalid history request", code: "invalid_history_request" }, { status: 400 }); +const invalid = () => Response.json({ error: "Invalid history request", code: "invalid_history_request" }, { status: 400 }); const isId = (value: unknown): value is string => typeof value === "string" && value.length > 0 && value.length <= MAX_ID_LENGTH; /** GET /api/notifications/history — every entry, newest first. */ export async function GET() { - return NextResponse.json({ entries: listHistory() }); + return Response.json({ entries: listHistory() }); } /** PATCH /api/notifications/history { ids } — mark entries read. A client marks what it shows, never entries it has not seen. */ @@ -23,12 +20,12 @@ export async function PATCH(req: Request) { try { body = await parseJsonWithinLimit(req, MAX_BODY_BYTES); } catch (error) { - if (error instanceof RequestBodyTooLargeError) return NextResponse.json({ error: "History request is too large", code: "request_too_large" }, { status: 413 }); + if (error instanceof RequestBodyTooLargeError) return Response.json({ error: "History request is too large", code: "request_too_large" }, { status: 413 }); return invalid(); } if (!isRecord(body) || !Array.isArray(body.ids) || body.ids.length > MAX_IDS || !body.ids.every(isId)) return invalid(); markHistoryRead(body.ids); - return NextResponse.json({ ok: true }); + return Response.json({ ok: true }); } /** @@ -41,5 +38,5 @@ export async function DELETE(req: Request) { if (isId(id)) removeHistory(id); else if (id === null && params.get("all") === "1") clearHistory(); else return invalid(); - return NextResponse.json({ ok: true }); + return Response.json({ ok: true }); } diff --git a/app/api/notifications/presence/route.ts b/app/api/notifications/presence/route.ts index cc3175195..c3497b5eb 100644 --- a/app/api/notifications/presence/route.ts +++ b/app/api/notifications/presence/route.ts @@ -1,10 +1,7 @@ -import { NextResponse } from "next/server"; import { isValidNotificationId } from "@/lib/notification-events"; import { reportPresence } from "@/lib/notification-hub"; import { isRecord } from "@/lib/type-guards"; -export const dynamic = "force-dynamic"; - /** POST /api/notifications/presence { clientId, deviceId, visible, sessionId, seq } — which session this tab shows. */ export async function POST(req: Request) { const body: unknown = await req.json().catch(() => null); @@ -12,9 +9,9 @@ export async function POST(req: Request) { !isRecord(body) || !isValidNotificationId(body.clientId) || !isValidNotificationId(body.deviceId) || typeof body.visible !== "boolean" || !Number.isSafeInteger(body.seq) ) { - return NextResponse.json({ error: "Invalid presence report", code: "invalid_presence" }, { status: 400 }); + return Response.json({ error: "Invalid presence report", code: "invalid_presence" }, { status: 400 }); } const sessionId = typeof body.sessionId === "string" && body.sessionId ? body.sessionId : null; reportPresence({ clientId: body.clientId, deviceId: body.deviceId, visible: body.visible, sessionId, seq: Number(body.seq) }); - return new NextResponse(null, { status: 204 }); + return new Response(null, { status: 204 }); } diff --git a/app/api/notifications/test/route.ts b/app/api/notifications/test/route.ts index eafce070e..2cb4fc129 100644 --- a/app/api/notifications/test/route.ts +++ b/app/api/notifications/test/route.ts @@ -1,16 +1,13 @@ -import { NextResponse } from "next/server"; import { isValidNotificationId } from "@/lib/notification-events"; import { sendTestPush } from "@/lib/notification-hub"; import { isRecord } from "@/lib/type-guards"; -export const dynamic = "force-dynamic"; - /** POST /api/notifications/test { deviceId } — one push to this device; 502 when the push service refuses it. */ export async function POST(req: Request) { const body: unknown = await req.json().catch(() => null); if (!isRecord(body) || !isValidNotificationId(body.deviceId)) { - return NextResponse.json({ error: "deviceId is required", code: "invalid_device" }, { status: 400 }); + return Response.json({ error: "deviceId is required", code: "invalid_device" }, { status: 400 }); } const result = await sendTestPush(body.deviceId); - return result.ok ? new NextResponse(null, { status: 204 }) : NextResponse.json({ error: result.error, code: "push_failed" }, { status: 502 }); + return result.ok ? new Response(null, { status: 204 }) : Response.json({ error: result.error, code: "push_failed" }, { status: 502 }); } diff --git a/app/api/omp-settings/route.ts b/app/api/omp-settings/route.ts index d93e6d74a..60973924f 100644 --- a/app/api/omp-settings/route.ts +++ b/app/api/omp-settings/route.ts @@ -1,16 +1,13 @@ -import { NextResponse } from "next/server"; import { invalidateModelsCache } from "@/lib/models-cache"; import { disposeUtilityRpc, runUtilityCommand, type OmpModel } from "@/lib/omp/rpc-utility"; import { readNativeSettings, writeNativeSettings, type NativeSettings } from "@/lib/omp/settings-config"; import { assertNoAmbiguousModelScopes } from "@/lib/model-scope"; -export const dynamic = "force-dynamic"; - export function GET() { try { - return NextResponse.json(readNativeSettings()); + return Response.json(readNativeSettings()); } catch (error) { - return NextResponse.json({ error: String(error) }, { status: 400 }); + return Response.json({ error: String(error) }, { status: 400 }); } } @@ -18,7 +15,7 @@ export async function PUT(request: Request) { try { const body = await request.json() as { settings?: NativeSettings }; if (!body.settings || typeof body.settings !== "object" || Array.isArray(body.settings)) { - return NextResponse.json({ error: "settings must be an object" }, { status: 400 }); + return Response.json({ error: "settings must be an object" }, { status: 400 }); } if (body.settings.enabledModels !== undefined) { // The utility process is best-effort here: settings remain editable when @@ -42,8 +39,8 @@ export async function PUT(request: Request) { invalidateModelsCache(); disposeUtilityRpc(); } - return NextResponse.json({ success: true, settings: readNativeSettings().settings }); + return Response.json({ success: true, settings: readNativeSettings().settings }); } catch (error) { - return NextResponse.json({ error: String(error) }, { status: 400 }); + return Response.json({ error: String(error) }, { status: 400 }); } } diff --git a/app/api/omp-update/route.ts b/app/api/omp-update/route.ts index 632340ab5..6d2c41812 100644 --- a/app/api/omp-update/route.ts +++ b/app/api/omp-update/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { isApiRequestOriginAllowed, shouldCheckApiRequestOrigin } from "@/lib/request-security"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { checkOmpUpdate } from "@/lib/omp/updates"; @@ -7,44 +6,44 @@ import { acknowledgeSelfUpdate, commitSelfUpdate, getSelfUpdateStatus, + getSelfUpdateSupport, markSelfUpdateStopping, prepareSelfUpdate, SelfUpdateError, validateCommitSelfUpdate, } from "@/lib/self-update"; -export const dynamic = "force-dynamic"; - const OMP_KIND = "omp" as const; -function errorResponse(error: unknown): NextResponse { +function errorResponse(error: unknown): Response { if (error instanceof SelfUpdateError) { - return NextResponse.json({ error: error.message, code: error.code }, { status: error.httpStatus }); + return Response.json({ error: error.message, code: error.code }, { status: error.httpStatus }); } - return NextResponse.json({ error: "The OMP update could not be started", code: "update_failed" }, { status: 500 }); + return Response.json({ error: "The OMP update could not be started", code: "update_failed" }, { status: 500 }); } export async function POST(request: Request) { if (shouldCheckApiRequestOrigin(request) && !isApiRequestOriginAllowed(request)) { - return NextResponse.json({ error: "Cross-origin API requests are not allowed", code: "cross_origin_forbidden" }, { status: 403 }); + return Response.json({ error: "Cross-origin API requests are not allowed", code: "cross_origin_forbidden" }, { status: 403 }); } if (request.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase() !== "application/json") { - return NextResponse.json({ error: "Content-Type must be application/json", code: "unsupported_media_type" }, { status: 415 }); + return Response.json({ error: "Content-Type must be application/json", code: "unsupported_media_type" }, { status: 415 }); } try { const body = await parseJsonWithinLimit | null>(request, 4_096); if (!body || typeof body !== "object" || Array.isArray(body)) throw new SelfUpdateError("invalid_action", "action must be check, restart, update, status, or acknowledge"); const keys = Object.keys(body); if (body.action === "check") { - return NextResponse.json(await checkOmpUpdate(body.force === true)); + // selfUpdateSupported: whether "Update now" can run here (never in the compiled binary, lib/self-update.ts). + return Response.json({ ...await checkOmpUpdate(body.force === true), selfUpdateSupported: getSelfUpdateSupport().supported }); } if (body.action === "restart" && keys.length === 1) { const sessionsRestarted = await restartAllRpcSessions(); - return NextResponse.json({ success: true, sessionsRestarted }); + return Response.json({ success: true, sessionsRestarted }); } if (body.action === "update" && keys.length === 1) { const result = await prepareSelfUpdate(OMP_KIND); - return NextResponse.json(result, { status: 202 }); + return Response.json(result, { status: 202 }); } if (body.action === "commit" && keys.length === 2 && typeof body.attemptId === "string") { const commitState = validateCommitSelfUpdate(body.attemptId, OMP_KIND); @@ -52,18 +51,18 @@ export async function POST(request: Request) { if (commitState === "ready") markSelfUpdateStopping(body.attemptId, OMP_KIND); await commitSelfUpdate(body.attemptId, OMP_KIND); } - return NextResponse.json({ accepted: true, attemptId: body.attemptId }, { status: 202 }); + return Response.json({ accepted: true, attemptId: body.attemptId }, { status: 202 }); } if (body.action === "status" && keys.length === 1) { const selfUpdateStatus = getSelfUpdateStatus(OMP_KIND); - return NextResponse.json(selfUpdateStatus ?? null, { headers: { "Cache-Control": "no-store" } }); + return Response.json(selfUpdateStatus ?? null, { headers: { "Cache-Control": "no-store" } }); } if (body.action === "acknowledge" && keys.length === 2 && typeof body.attemptId === "string") { - return NextResponse.json(acknowledgeSelfUpdate(body.attemptId, OMP_KIND)); + return Response.json(acknowledgeSelfUpdate(body.attemptId, OMP_KIND)); } throw new SelfUpdateError("invalid_action", "action must be check, restart, update, status, or acknowledge"); } catch (error) { - if (error instanceof RequestBodyTooLargeError) return NextResponse.json({ error: error.message, code: "body_too_large" }, { status: 413 }); + if (error instanceof RequestBodyTooLargeError) return Response.json({ error: error.message, code: "body_too_large" }, { status: 413 }); if (error instanceof SyntaxError) return errorResponse(new SelfUpdateError("invalid_json", "Request body must be valid JSON")); return errorResponse(error); } diff --git a/app/api/omp-version/route.ts b/app/api/omp-version/route.ts index 447da2279..976e8051f 100644 --- a/app/api/omp-version/route.ts +++ b/app/api/omp-version/route.ts @@ -1,11 +1,8 @@ -import { NextResponse } from "next/server"; import { getOmpVersion } from "@/lib/omp/omp-cli"; -export const dynamic = "force-dynamic"; - /** Runtime probe of the installed omp binary ("omp/17.1.3"), separate from the * build-time omp-web version — the two can legitimately drift. */ export async function GET() { const version = await getOmpVersion(); - return NextResponse.json({ version }); + return Response.json({ version }); } diff --git a/app/api/plugins/route.ts b/app/api/plugins/route.ts index 8b8dd152e..30fec1f7f 100644 --- a/app/api/plugins/route.ts +++ b/app/api/plugins/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { execFile } from "child_process"; import { existsSync, promises as fs } from "fs"; import { basename, extname, join } from "path"; @@ -14,8 +13,6 @@ import type { PluginsResponse, } from "@/lib/api-types"; -export const dynamic = "force-dynamic"; - // Plugin management is delegated to the user's omp binary (`omp plugin ...`); // omp-web never embeds the Bun-only SDK. `--json` output shapes are mirrored // from oh-my-pi coding-agent src/cli/plugin-cli.ts + extensibility/plugins. @@ -266,25 +263,25 @@ function readScope(scope: unknown): PluginScope { /** Dynamic CLI failures keep their message; a missing omp binary is the one * known cause worth a stable code for client-side localization. */ -function pluginErrorResponse(error: unknown): NextResponse { +function pluginErrorResponse(error: unknown): Response { const message = error instanceof Error ? error.message : String(error); if (message.includes("omp binary not found")) { - return NextResponse.json({ error: message, code: "omp_not_found" }, { status: 500 }); + return Response.json({ error: message, code: "omp_not_found" }, { status: 500 }); } - return NextResponse.json({ error: message }, { status: 500 }); + return Response.json({ error: message }, { status: 500 }); } export async function GET(req: Request) { const { searchParams } = new URL(req.url); const cwd = searchParams.get("cwd"); - if (!cwd) return NextResponse.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); + if (!cwd) return Response.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); try { const allowedRoots = await getAllowedFileRoots(); if (!isExistingFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } - return NextResponse.json(await readPlugins(cwd)); + return Response.json(await readPlugins(cwd)); } catch (error) { return pluginErrorResponse(error); } @@ -299,32 +296,32 @@ export async function POST(req: Request) { scope?: PluginScope; cwd?: string; }; - if (!body.cwd) return NextResponse.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); - if (!body.action) return NextResponse.json({ error: "action required", code: "action_required" }, { status: 400 }); + if (!body.cwd) return Response.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); + if (!body.action) return Response.json({ error: "action required", code: "action_required" }, { status: 400 }); const allowedRoots = await getAllowedFileRoots(); if (!isExistingFilePathAllowed(body.cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } const source = body.source?.trim(); const scopeArgs = readScope(body.scope) === "project" ? ["--scope", "project"] : []; if (body.action === "install") { - if (!source) return NextResponse.json({ error: "source required", code: "source_required" }, { status: 400 }); + if (!source) return Response.json({ error: "source required", code: "source_required" }, { status: 400 }); await runOmp(["plugin", "install", source, "--json", ...scopeArgs], { cwd: body.cwd, timeout: 300_000 }); } else if (body.action === "remove") { - if (!source) return NextResponse.json({ error: "source required", code: "source_required" }, { status: 400 }); + if (!source) return Response.json({ error: "source required", code: "source_required" }, { status: 400 }); await runOmp(["plugin", "uninstall", source, "--json", ...scopeArgs], { cwd: body.cwd, timeout: 120_000 }); } else if (body.action === "update") { await runOmp(["plugin", "upgrade", ...(source ? [source, ...scopeArgs] : [])], { cwd: body.cwd, timeout: 300_000 }); } else if (body.action === "disable" || body.action === "enable") { - if (!source) return NextResponse.json({ error: "source required", code: "source_required" }, { status: 400 }); + if (!source) return Response.json({ error: "source required", code: "source_required" }, { status: 400 }); await runOmp(["plugin", body.action, source, "--json", ...scopeArgs], { cwd: body.cwd, timeout: 60_000 }); } else { - return NextResponse.json({ error: `Unsupported action: ${body.action}`, code: "plugin_unsupported_action" }, { status: 400 }); + return Response.json({ error: `Unsupported action: ${body.action}`, code: "plugin_unsupported_action" }, { status: 400 }); } - return NextResponse.json(await readPlugins(body.cwd)); + return Response.json(await readPlugins(body.cwd)); } catch (error) { return pluginErrorResponse(error); } diff --git a/app/api/projects/clone/route.ts b/app/api/projects/clone/route.ts index 5a6d7ca0b..a2a3c03eb 100644 --- a/app/api/projects/clone/route.ts +++ b/app/api/projects/clone/route.ts @@ -1,7 +1,6 @@ import { spawn } from "child_process"; import { mkdir, rm } from "fs/promises"; import { join } from "path"; -import { NextResponse } from "next/server"; import { apiErrorResponse } from "@/lib/api-utils"; import { cloneDirectoryName } from "@/lib/git-clone"; import { createChildProcessEnvironment } from "@/lib/project-command-env"; @@ -62,23 +61,23 @@ function runGitClone(url: string, target: string, signal: AbortSignal, onOutput: // Clones `url` into `/` and streams NDJSON frames: // output chunks, then exactly one of done / cancelled / error. The target is // removed on failure or cancellation (DELETE, or the client disconnecting). -export async function POST(req: Request) { +export async function POST(req: Request, { disableIdleTimeout }: { disableIdleTimeout: () => void }) { let body: { id?: unknown; parent?: unknown; url?: unknown }; try { body = await req.json(); } catch { - return NextResponse.json({ error: "Invalid request", code: "invalid_request" }, { status: 400 }); + return Response.json({ error: "Invalid request", code: "invalid_request" }, { status: 400 }); } const id = typeof body.id === "string" && CLONE_ID.test(body.id) ? body.id : null; const url = typeof body.url === "string" ? body.url.trim() : ""; const name = cloneDirectoryName(url); - if (!id || clones.has(id)) return NextResponse.json({ error: "Invalid request", code: "invalid_request" }, { status: 400 }); - if (!name) return NextResponse.json({ error: "Enter an https:// or ssh Git URL", code: "invalid_git_url" }, { status: 400 }); + if (!id || clones.has(id)) return Response.json({ error: "Invalid request", code: "invalid_request" }, { status: 400 }); + if (!name) return Response.json({ error: "Enter an https:// or ssh Git URL", code: "invalid_git_url" }, { status: 400 }); let target: string; try { target = join(validateProjectPath(typeof body.parent === "string" ? body.parent : ""), name); } catch (error) { - if (error instanceof ProjectPathError) return NextResponse.json({ error: error.message, code: error.code }, { status: 400 }); + if (error instanceof ProjectPathError) return Response.json({ error: error.message, code: error.code }, { status: 400 }); throw error; } // Registered before any await so a cancel sent while the target is being @@ -94,10 +93,11 @@ export async function POST(req: Request) { } catch (error) { clones.delete(id); if ((error as NodeJS.ErrnoException).code === "EEXIST") { - return NextResponse.json({ error: `Already exists: ${target}`, code: "clone_target_exists" }, { status: 409 }); + return Response.json({ error: `Already exists: ${target}`, code: "clone_target_exists" }, { status: 409 }); } return apiErrorResponse(error); } + disableIdleTimeout(); const encoder = new TextEncoder(); const stream = new ReadableStream({ async start(streamController) { @@ -136,7 +136,7 @@ export async function POST(req: Request) { export async function DELETE(req: Request) { const body = await req.json().catch(() => ({})) as { id?: unknown }; const controller = typeof body.id === "string" ? clones.get(body.id) : undefined; - if (!controller) return NextResponse.json({ error: "No clone in progress", code: "clone_not_found" }, { status: 404 }); + if (!controller) return Response.json({ error: "No clone in progress", code: "clone_not_found" }, { status: 404 }); controller.abort(); - return NextResponse.json({ ok: true }); + return Response.json({ ok: true }); } diff --git a/app/api/projects/route.ts b/app/api/projects/route.ts index 804f91ca0..af286fef5 100644 --- a/app/api/projects/route.ts +++ b/app/api/projects/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse, opErrorResponse, resolveHostOrError } from "@/lib/api-utils"; import { allowFileRoot } from "@/lib/file-access"; import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; @@ -42,7 +41,7 @@ export async function GET() { // empty managed project derives no root from sessions). Only this // machine's: another host's paths do not exist here. for (const project of projects) if (project.hostId === LOCAL_HOST_ID) allowFileRoot(project.path); - return NextResponse.json({ projects }); + return Response.json({ projects }); } catch (error) { return apiErrorResponse(error); } @@ -61,12 +60,12 @@ export async function POST(req: Request) { const { host } = target; const result = await host.sessionOps.addProject(cwd, launchConfig); if (!result.ok) return opErrorResponse(result); - if (host.id !== LOCAL_HOST_ID) return NextResponse.json({ project: { ...result.value, hostId: host.id } }); + if (host.id !== LOCAL_HOST_ID) return Response.json({ project: { ...result.value, hostId: host.id } }); allowFileRoot(result.value.path); - return NextResponse.json({ project: result.value }); + return Response.json({ project: result.value }); } catch (error) { if (error instanceof ProjectPathError) { - return NextResponse.json({ error: error.message, code: error.code }, { status: 400 }); + return Response.json({ error: error.message, code: error.code }, { status: 400 }); } return apiErrorResponse(error); } @@ -98,23 +97,23 @@ export async function PATCH(req: Request) { ? [{ cwd: body.cwd, alias: body.alias, sortOrder: body.sortOrder, pinOrder: body.pinOrder, launchConfig: body.launchConfig }] : []; if (rawUpdates.length === 0) { - return NextResponse.json({ error: "Path is required", code: "path_required" }, { status: 400 }); + return Response.json({ error: "Path is required", code: "path_required" }, { status: 400 }); } if (rawUpdates.length > MAX_PRESENTATION_UPDATES) { - return NextResponse.json({ error: "Too many updates", code: "too_many_updates" }, { status: 400 }); + return Response.json({ error: "Too many updates", code: "too_many_updates" }, { status: 400 }); } const parsed: ProjectUpdate[] = []; for (const item of rawUpdates) { const entry = item as { cwd?: unknown; alias?: unknown; sortOrder?: unknown; pinOrder?: unknown; launchConfig?: unknown }; const cwd = typeof entry.cwd === "string" ? entry.cwd.trim() : ""; - if (!cwd) return NextResponse.json({ error: "Path is required", code: "path_required" }, { status: 400 }); + if (!cwd) return Response.json({ error: "Path is required", code: "path_required" }, { status: 400 }); const alias = entry.alias === null ? null : typeof entry.alias === "string" ? entry.alias : undefined; const sortOrder = entry.sortOrder === null ? null : typeof entry.sortOrder === "number" && Number.isFinite(entry.sortOrder) ? entry.sortOrder : undefined; const pinOrder = entry.pinOrder === null ? null : typeof entry.pinOrder === "number" && Number.isFinite(entry.pinOrder) ? entry.pinOrder : undefined; - if (entry.alias !== undefined && alias === undefined) return NextResponse.json({ error: "Alias must be a string", code: "invalid_alias" }, { status: 400 }); - if (entry.sortOrder !== undefined && sortOrder === undefined) return NextResponse.json({ error: "Sort order must be a number", code: "invalid_sort_order" }, { status: 400 }); - if (entry.pinOrder !== undefined && pinOrder === undefined) return NextResponse.json({ error: "Pin order must be a number", code: "invalid_pin_order" }, { status: 400 }); + if (entry.alias !== undefined && alias === undefined) return Response.json({ error: "Alias must be a string", code: "invalid_alias" }, { status: 400 }); + if (entry.sortOrder !== undefined && sortOrder === undefined) return Response.json({ error: "Sort order must be a number", code: "invalid_sort_order" }, { status: 400 }); + if (entry.pinOrder !== undefined && pinOrder === undefined) return Response.json({ error: "Pin order must be a number", code: "invalid_pin_order" }, { status: 400 }); const launchConfig = entry.launchConfig === null ? null : parseLaunchConfig(entry.launchConfig); parsed.push({ cwd, alias, sortOrder, pinOrder, launchConfig }); } @@ -127,10 +126,10 @@ export async function PATCH(req: Request) { // in-memory browse authorization behind. Never for another host's paths. if (target.host.id === LOCAL_HOST_ID) for (const root of result.value.newRoots) allowFileRoot(root); const { projects } = result.value; - return NextResponse.json({ projects: target.host.id === LOCAL_HOST_ID ? projects : projects.map((project) => ({ ...project, hostId: target.host.id })) }); + return Response.json({ projects: target.host.id === LOCAL_HOST_ID ? projects : projects.map((project) => ({ ...project, hostId: target.host.id })) }); } catch (error) { if (error instanceof ProjectPathError) { - return NextResponse.json({ error: error.message, code: error.code }, { status: 400 }); + return Response.json({ error: error.message, code: error.code }, { status: 400 }); } return apiErrorResponse(error); } @@ -144,13 +143,13 @@ export async function DELETE(req: Request) { const body = await req.json() as { cwd?: unknown; hostId?: unknown }; const cwd = typeof body.cwd === "string" ? body.cwd.trim() : ""; if (!cwd) { - return NextResponse.json({ error: "Path is required", code: "path_required" }, { status: 400 }); + return Response.json({ error: "Path is required", code: "path_required" }, { status: 400 }); } const target = resolveHostOrError(body.hostId); if ("response" in target) return target.response; const result = await target.host.sessionOps.hideProject(cwd); if (!result.ok) return opErrorResponse(result); - return NextResponse.json({ success: true }); + return Response.json({ success: true }); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/provider-usage/route.ts b/app/api/provider-usage/route.ts index fc50b8ba1..9f749fe87 100644 --- a/app/api/provider-usage/route.ts +++ b/app/api/provider-usage/route.ts @@ -1,8 +1,5 @@ -import { NextResponse } from "next/server"; import { getProviderUsage } from "@/lib/provider-usage"; -export const dynamic = "force-dynamic"; - const IDENTIFIER_RE = /^[A-Za-z0-9._:/-]{1,200}$/; function readIdentifier(value: string | null): string | undefined { @@ -20,16 +17,16 @@ export async function GET(request: Request) { const modelId = readIdentifier(rawModel); if ((rawProvider !== null && !provider) || (rawModel !== null && !modelId)) { - return NextResponse.json( + return Response.json( { error: "Invalid provider or model identifier", code: "invalid_usage_query" }, { status: 400 }, ); } try { - return NextResponse.json(await getProviderUsage({ provider, modelId }, searchParams.get("refresh") === "true")); + return Response.json(await getProviderUsage({ provider, modelId }, searchParams.get("refresh") === "true")); } catch { - return NextResponse.json( + return Response.json( { error: "Provider usage is currently unavailable", code: "provider_usage_unavailable" }, { status: 502 }, ); diff --git a/app/api/providers/enable/route.ts b/app/api/providers/enable/route.ts index 03cf53913..f99e7eeaa 100644 --- a/app/api/providers/enable/route.ts +++ b/app/api/providers/enable/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { invalidateModelsCache } from "@/lib/models-cache"; import { enableProvider } from "@/lib/omp/model-roles"; import { disposeUtilityRpc } from "@/lib/omp/rpc-utility"; @@ -7,13 +6,13 @@ export async function POST(request: Request) { try { const body = await request.json() as { provider?: unknown }; if (typeof body.provider !== "string" || !body.provider.trim()) { - return NextResponse.json({ error: "provider is required" }, { status: 400 }); + return Response.json({ error: "provider is required" }, { status: 400 }); } enableProvider(body.provider); invalidateModelsCache(); disposeUtilityRpc(); - return NextResponse.json({ success: true }); + return Response.json({ success: true }); } catch (error) { - return NextResponse.json({ error: String(error) }, { status: 400 }); + return Response.json({ error: String(error) }, { status: 400 }); } } diff --git a/app/api/sessions/[id]/archive/route.ts b/app/api/sessions/[id]/archive/route.ts index 7fb81da54..19d194d71 100644 --- a/app/api/sessions/[id]/archive/route.ts +++ b/app/api/sessions/[id]/archive/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse, hostOfflineResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; import { HostOpError } from "@/lib/hosts/link-protocol"; import { invalidateHostSessionList } from "@/lib/hosts/session-index"; @@ -20,7 +19,7 @@ export async function POST( // flattening their tree in the sidebar. Archive leaves first instead. const hasChildren = (await sessionOps.listSessions()).some((session) => session.parentSessionId === id); if (hasChildren) { - return NextResponse.json( + return Response.json( { error: "Archive child sessions before archiving this session", code: "session_has_children" }, { status: 409 }, ); @@ -36,10 +35,10 @@ export async function POST( if (!result.ok) return opErrorResponse(result); invalidateHostSessionList(resolved.host.id); clearExitedRpcSession(id); - return NextResponse.json({ ok: true, archived: true, archivedPath: result.value.archivedPath }); + return Response.json({ ok: true, archived: true, archivedPath: result.value.archivedPath }); } catch (error) { if (error instanceof HostOpError) return apiErrorResponse(error); const message = error instanceof Error ? error.message : String(error); - return NextResponse.json({ error: message, code: "session_archive_failed" }, { status: 500 }); + return Response.json({ error: message, code: "session_archive_failed" }, { status: 500 }); } } diff --git a/app/api/sessions/[id]/auto-name/route.ts b/app/api/sessions/[id]/auto-name/route.ts index 8894e1e6d..c37afa577 100644 --- a/app/api/sessions/[id]/auto-name/route.ts +++ b/app/api/sessions/[id]/auto-name/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { deriveSessionTitleFromFirstMessage, sanitizeSessionTitle } from "@/lib/session-title"; import { getRpcSession, startRpcSession, WebRpcError } from "@/lib/rpc-manager"; import { invalidateHostSessionList, sessionSpawnTarget } from "@/lib/hosts/session-index"; @@ -45,13 +44,13 @@ export async function POST( const generated = sanitizeSessionTitle((await rpc.generateTitle()) ?? undefined); if (generated) { invalidateSessionCaches(rpc.sessionFile); - return NextResponse.json({ title: generated, generated: true, usage: null }); + return Response.json({ title: generated, generated: true, usage: null }); } } catch (error) { // A busy/restarting session reports a typed error the UI can show; any // other failure degrades to the fallback below. if (error instanceof WebRpcError) { - return NextResponse.json({ error: error.message, code: error.code }, { status: 409 }); + return Response.json({ error: error.message, code: error.code }, { status: 409 }); } } } @@ -63,12 +62,12 @@ export async function POST( const info = (await sessionOps.listSessions()).find((session) => session.id === id); const storedTitle = sanitizeSessionTitle(info?.name); if (storedTitle) { - return NextResponse.json({ title: storedTitle, generated: false, usage: null }); + return Response.json({ title: storedTitle, generated: false, usage: null }); } const derived = deriveSessionTitleFromFirstMessage(info?.firstMessage); if (!derived) { - return NextResponse.json( + return Response.json( { error: "The session has no user messages to name", code: "session_no_messages_to_name" }, { status: 409 }, ); @@ -76,7 +75,7 @@ export async function POST( // Title generation/path resolution yielded; Edit may now own this session. if (getRpcSession(id)?.isEditingHistory()) { - return NextResponse.json({ error: "Wait for the history edit to finish", code: "session_busy" }, { status: 409 }); + return Response.json({ error: "Wait for the history edit to finish", code: "session_busy" }, { status: 409 }); } // Save title both to disk and through the live process so it persists immediately. @@ -90,10 +89,10 @@ export async function POST( // Saved on disk; ignore RPC sync failure. } } - return NextResponse.json({ title: derived, generated: false, usage: null }); + return Response.json({ title: derived, generated: false, usage: null }); } catch (error) { if (error instanceof HostOpError) return apiErrorResponse(error); - return NextResponse.json( + return Response.json( { error: error instanceof Error ? error.message : String(error) }, { status: 500 }, ); diff --git a/app/api/sessions/[id]/context/route.ts b/app/api/sessions/[id]/context/route.ts index 533b0e98a..713155f91 100644 --- a/app/api/sessions/[id]/context/route.ts +++ b/app/api/sessions/[id]/context/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { buildSessionContext } from "@/lib/session-reader"; import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; import { getRpcSession } from "@/lib/rpc-manager"; @@ -19,28 +18,28 @@ export async function GET( const boundary = url.searchParams.get("boundary"); if (boundary !== null) { if (boundary !== "1" || url.searchParams.getAll("boundary").length !== 1) { - return NextResponse.json({ error: "Invalid boundary mode", code: "invalid_boundary" }, { status: 400 }); + return Response.json({ error: "Invalid boundary mode", code: "invalid_boundary" }, { status: 400 }); } if (["sync", "leafId", "includePreCompaction", "cursor", "limit"].some((option) => url.searchParams.has(option))) { - return NextResponse.json({ error: "Boundary mode requires the current active context", code: "invalid_boundary_options" }, { status: 400 }); + return Response.json({ error: "Boundary mode requires the current active context", code: "invalid_boundary_options" }, { status: 400 }); } } let cursor: SessionHistoryCursor | null = null; let limit = MAX_SYNC_MESSAGES; if (sync !== null && sync !== "1") { - return NextResponse.json({ error: "Invalid sync mode", code: "invalid_sync" }, { status: 400 }); + return Response.json({ error: "Invalid sync mode", code: "invalid_sync" }, { status: 400 }); } if (sync === "1") { try { cursor = parseHistoryCursor(url.searchParams.get("cursor")); } catch { - return NextResponse.json({ error: "Invalid history cursor", code: "invalid_sync_cursor" }, { status: 400 }); + return Response.json({ error: "Invalid history cursor", code: "invalid_sync_cursor" }, { status: 400 }); } const rawLimit = url.searchParams.get("limit"); if (rawLimit !== null) { limit = Number(rawLimit); if (!/^[1-9]\d*$/.test(rawLimit) || !Number.isInteger(limit) || limit > MAX_SYNC_MESSAGES) { - return NextResponse.json({ error: "Invalid history page limit", code: "invalid_sync_limit" }, { status: 400 }); + return Response.json({ error: "Invalid history page limit", code: "invalid_sync_limit" }, { status: 400 }); } } } @@ -64,7 +63,7 @@ export async function GET( const session = notFound && (boundary === "1" || (sync === "1" && !cursor?.lastEntryId && leafId === undefined)) ? getRpcSession(id) : undefined; if (session?.isAlive() && !(await session.host.sessionFileExists(session.sessionFile))) { if (boundary === "1") { - return NextResponse.json({ entryIds: [] }, { headers: { "Cache-Control": "no-store" } }); + return Response.json({ entryIds: [] }, { headers: { "Cache-Control": "no-store" } }); } const response: SessionSyncResponse = { ...selectSessionHistory(buildSessionContext([]), cursor, limit), @@ -72,12 +71,12 @@ export async function GET( leafId: null, live: session.getStreamSnapshot(), }; - return NextResponse.json(response, { headers: { "Cache-Control": "no-store" } }); + return Response.json(response, { headers: { "Cache-Control": "no-store" } }); } return "response" in result ? result.response : opErrorResponse(result); } if (boundary === "1") { - return NextResponse.json(result.value, { headers: { "Cache-Control": "no-store" } }); + return Response.json(result.value, { headers: { "Cache-Control": "no-store" } }); } if (sync === "1") { const page = result.value as { history: SessionHistoryPage; leafId: string | null; tipId: string | null }; @@ -88,9 +87,9 @@ export async function GET( ? session.getStreamSnapshot() : null; const response: SessionSyncResponse = { ...page.history, sessionId: id, leafId: page.leafId, live }; - return NextResponse.json(response, { headers: { "Cache-Control": "no-store" } }); + return Response.json(response, { headers: { "Cache-Control": "no-store" } }); } - return NextResponse.json(result.value); + return Response.json(result.value); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/sessions/[id]/entries/[entryId]/thinking/route.ts b/app/api/sessions/[id]/entries/[entryId]/thinking/route.ts index b08467729..8af09f0cf 100644 --- a/app/api/sessions/[id]/entries/[entryId]/thinking/route.ts +++ b/app/api/sessions/[id]/entries/[entryId]/thinking/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; export async function GET( @@ -9,14 +8,14 @@ export async function GET( const blockIndexParam = new URL(req.url).searchParams.get("blockIndex"); const blockIndex = blockIndexParam === null ? Number.NaN : Number(blockIndexParam); if (!Number.isSafeInteger(blockIndex) || blockIndex < 0) { - return NextResponse.json({ error: "Valid blockIndex is required", code: "invalid_block_index" }, { status: 400 }); + return Response.json({ error: "Valid blockIndex is required", code: "invalid_block_index" }, { status: 400 }); } try { const resolved = await resolveSessionHostOr404(id); if ("response" in resolved) return resolved.response; const result = await resolved.host.sessionOps.readThinking(id, entryId, blockIndex); - return result.ok ? NextResponse.json(result.value) : opErrorResponse(result); + return result.ok ? Response.json(result.value) : opErrorResponse(result); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/sessions/[id]/export/route.ts b/app/api/sessions/[id]/export/route.ts index eb99df227..657016bd6 100644 --- a/app/api/sessions/[id]/export/route.ts +++ b/app/api/sessions/[id]/export/route.ts @@ -2,8 +2,6 @@ import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/li import { getContentDisposition } from "@/lib/content-disposition"; import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; -export const runtime = "nodejs"; - /** Render a session to self-contained HTML with the omp binary on its host (`omp --export`). */ export async function GET( req: Request, diff --git a/app/api/sessions/[id]/route.ts b/app/api/sessions/[id]/route.ts index f43106a5e..8ac26b264 100644 --- a/app/api/sessions/[id]/route.ts +++ b/app/api/sessions/[id]/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse, hostOfflineResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; import { HostOpError } from "@/lib/hosts/link-protocol"; import { invalidateHostSessionList } from "@/lib/hosts/session-index"; @@ -8,20 +7,20 @@ import { clearExitedRpcSession, getLiveRpcSessionIds, getRpcSession, WebRpcError /** Stable, client-safe error body for catch-all handlers: details go to the * server log only, never to the browser. */ -function sessionsErrorResponse(error: unknown): NextResponse { +function sessionsErrorResponse(error: unknown): Response { if (error instanceof WebRpcError && error.code === "session_busy") { - return NextResponse.json({ error: error.message, code: error.code }, { status: 409 }); + return Response.json({ error: error.message, code: error.code }, { status: 409 }); } if (error instanceof RequestBodyTooLargeError) { - return NextResponse.json({ error: "Request body is too large", code: "request_too_large" }, { status: 413 }); + return Response.json({ error: "Request body is too large", code: "request_too_large" }, { status: 413 }); } if (error instanceof SyntaxError) { - return NextResponse.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); + return Response.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); } // A host link failure keeps its status: 503 offline, 504 timeout. if (error instanceof HostOpError) return apiErrorResponse(error); console.error("[api/sessions]", error); - return NextResponse.json({ error: "Session request failed", code: "session_request_failed" }, { status: 500 }); + return Response.json({ error: "Session request failed", code: "session_request_failed" }, { status: 500 }); } export async function GET( @@ -59,7 +58,7 @@ export async function GET( } } - return NextResponse.json({ + return Response.json({ sessionId: id, ...read.value, ...(agent ? { agent } : {}), @@ -78,7 +77,7 @@ export async function PATCH( try { const { name } = await parseJsonWithinLimit<{ name?: string }>(req, 64 * 1024); if (typeof name !== "string" || !name.trim()) { - return NextResponse.json({ error: "name is required", code: "session_name_required" }, { status: 400 }); + return Response.json({ error: "name is required", code: "session_name_required" }, { status: 400 }); } // A running omp process owns its session file; route the rename through it // so the in-memory title cannot clobber ours on the next flush. This runs @@ -106,10 +105,10 @@ export async function PATCH( const result = await resolved.host.sessionOps.renameSessionFile(id, name.trim()); if (!result.ok) return opErrorResponse(result); invalidateHostSessionList(resolved.host.id); - return NextResponse.json({ ok: true }); + return Response.json({ ok: true }); } invalidateSessionCaches(); - return NextResponse.json({ ok: true }); + return Response.json({ ok: true }); } catch (error) { return sessionsErrorResponse(error); } @@ -136,7 +135,7 @@ export async function DELETE( if (!result.ok) return opErrorResponse(result); invalidateHostSessionList(resolved.host.id); clearExitedRpcSession(id); - return NextResponse.json({ ok: true, ...result.value }); + return Response.json({ ok: true, ...result.value }); } catch (error) { return sessionsErrorResponse(error); } diff --git a/app/api/sessions/[id]/state/route.ts b/app/api/sessions/[id]/state/route.ts index 7872564f3..ade9d889e 100644 --- a/app/api/sessions/[id]/state/route.ts +++ b/app/api/sessions/[id]/state/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { getExitedRpcSession, getRpcSession, WebRpcError } from "@/lib/rpc-manager"; import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; @@ -15,22 +14,22 @@ export async function GET( if (rpc?.isAlive()) { try { const state = await rpc.send({ type: "get_state" }); - return NextResponse.json({ running: true, state }); + return Response.json({ running: true, state }); } catch (error) { if (error instanceof WebRpcError && error.code === "session_unresponsive") { - return NextResponse.json({ running: false, recovered: true }); + return Response.json({ running: false, recovered: true }); } throw error; } } const exited = getExitedRpcSession(id); - if (exited) return NextResponse.json({ running: false, exited }); + if (exited) return Response.json({ running: false, exited }); const resolved = await resolveSessionHostOr404(id); if ("response" in resolved) return resolved.response; const result = await resolved.host.sessionOps.readSessionState(id); - return result.ok ? NextResponse.json(result.value) : opErrorResponse(result); + return result.ok ? Response.json(result.value) : opErrorResponse(result); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/sessions/[id]/subagents/[subagentId]/route.ts b/app/api/sessions/[id]/subagents/[subagentId]/route.ts index ca34600d5..a49f73d5f 100644 --- a/app/api/sessions/[id]/subagents/[subagentId]/route.ts +++ b/app/api/sessions/[id]/subagents/[subagentId]/route.ts @@ -1,10 +1,7 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; import { HostOpError } from "@/lib/hosts/link-protocol"; import { isValidSubagentId } from "@/lib/hosts/session-ops"; -export const dynamic = "force-dynamic"; - /** * GET /api/sessions/[id]/subagents/[subagentId]?fromByte=N * @@ -23,7 +20,7 @@ export async function GET( const { id, subagentId } = await params; try { if (!isValidSubagentId(subagentId)) { - return NextResponse.json({ error: "Invalid subagent id", code: "invalid_subagent_id" }, { status: 400 }); + return Response.json({ error: "Invalid subagent id", code: "invalid_subagent_id" }, { status: 400 }); } const resolved = await resolveSessionHostOr404(id); if ("response" in resolved) return resolved.response; @@ -35,10 +32,10 @@ export async function GET( searchParams.get("mode") === "completion" ? "completion" : "page", fromByteRaw !== null ? Number(fromByteRaw) : 0, ); - return result.ok ? NextResponse.json(result.value) : opErrorResponse(result); + return result.ok ? Response.json(result.value) : opErrorResponse(result); } catch (error) { if (error instanceof HostOpError) return apiErrorResponse(error); - return NextResponse.json( + return Response.json( { error: error instanceof Error ? error.message : String(error) }, { status: 500 }, ); diff --git a/app/api/sessions/[id]/subagents/route.ts b/app/api/sessions/[id]/subagents/route.ts index f63dc1303..6de054a5e 100644 --- a/app/api/sessions/[id]/subagents/route.ts +++ b/app/api/sessions/[id]/subagents/route.ts @@ -1,10 +1,7 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; import { HostOpError } from "@/lib/hosts/link-protocol"; import { getRpcSession } from "@/lib/rpc-manager"; -export const dynamic = "force-dynamic"; - /** * GET /api/sessions/[id]/subagents * @@ -24,15 +21,15 @@ export async function GET( // history yet", not "unknown session". The client treats an empty // roster the same as a 404, so answer 200 to keep the console clean. if (getRpcSession(id)?.isAlive()) { - return NextResponse.json({ subagents: [] }); + return Response.json({ subagents: [] }); } return resolved.response; } const result = await resolved.host.sessionOps.readSubagentHistory(id); - return result.ok ? NextResponse.json(result.value) : opErrorResponse(result); + return result.ok ? Response.json(result.value) : opErrorResponse(result); } catch (error) { if (error instanceof HostOpError) return apiErrorResponse(error); - return NextResponse.json( + return Response.json( { error: error instanceof Error ? error.message : String(error) }, { status: 500 }, ); diff --git a/app/api/sessions/archive/route.ts b/app/api/sessions/archive/route.ts index 09eec963b..8eb0726d4 100644 --- a/app/api/sessions/archive/route.ts +++ b/app/api/sessions/archive/route.ts @@ -1,12 +1,9 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse } from "@/lib/api-utils"; import { listArchivedSessions, restoreArchivedSession } from "@/lib/omp/archive"; import { invalidateLocalSessionLists } from "@/lib/hosts/session-index"; import { invalidateSessionListCache } from "@/lib/session-reader"; import type { ArchivedSessionInfo } from "@/lib/types"; -export const runtime = "nodejs"; - export async function GET() { try { const archives = await listArchivedSessions(); @@ -22,7 +19,7 @@ export async function GET() { size: archive.size, status: archive.status, })); - return NextResponse.json({ archives: response }, { headers: { "Cache-Control": "no-store" } }); + return Response.json({ archives: response }, { headers: { "Cache-Control": "no-store" } }); } catch (error) { return apiErrorResponse(error); } @@ -32,15 +29,15 @@ export async function POST(req: Request) { try { const body = await req.json() as { key?: unknown }; if (typeof body.key !== "string" || !body.key.trim()) { - return NextResponse.json({ error: "Archive key is required", code: "archive_key_required" }, { status: 400 }); + return Response.json({ error: "Archive key is required", code: "archive_key_required" }, { status: 400 }); } const sessionId = restoreArchivedSession(body.key); invalidateSessionListCache(); invalidateLocalSessionLists(); - return NextResponse.json({ ok: true, sessionId }); + return Response.json({ ok: true, sessionId }); } catch (error) { const message = error instanceof Error ? error.message : String(error); const status = message.includes("Invalid archive key") || message.includes("required") ? 400 : message.includes("not found") ? 404 : message.includes("already exists") ? 409 : 500; - return NextResponse.json({ error: message, code: "archive_restore_failed" }, { status }); + return Response.json({ error: message, code: "archive_restore_failed" }, { status }); } } diff --git a/app/api/sessions/import/route.ts b/app/api/sessions/import/route.ts index 82ee4349c..0e142c228 100644 --- a/app/api/sessions/import/route.ts +++ b/app/api/sessions/import/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse } from "@/lib/api-utils"; import { mkdirSync, writeFileSync } from "fs"; import path from "path"; @@ -29,13 +28,13 @@ export async function POST(req: Request) { const fileName = typeof body.fileName === "string" ? body.fileName.trim() : ""; const content = typeof body.content === "string" ? body.content : ""; if (!fileName || fileName.includes("/") || fileName.includes("\\")) { - return NextResponse.json({ error: "Invalid file name", code: "invalid_file_name" }, { status: 400 }); + return Response.json({ error: "Invalid file name", code: "invalid_file_name" }, { status: 400 }); } if (!content.trim()) { - return NextResponse.json({ error: "Empty session file", code: "empty_session_file" }, { status: 400 }); + return Response.json({ error: "Empty session file", code: "empty_session_file" }, { status: 400 }); } if (Buffer.byteLength(content, "utf8") > MAX_IMPORT_BYTES) { - return NextResponse.json({ error: "Session file is too large (max 10 MB)", code: "session_file_too_large" }, { status: 400 }); + return Response.json({ error: "Session file is too large (max 10 MB)", code: "session_file_too_large" }, { status: 400 }); } // Every line must parse as a JSON object, and one of them must be the @@ -76,15 +75,15 @@ export async function POST(req: Request) { return line; }); if (rewritten.some((line) => line === null)) { - return NextResponse.json({ error: "Not a valid omp session file (malformed JSON line)", code: "invalid_session_file" }, { status: 400 }); + return Response.json({ error: "Not a valid omp session file (malformed JSON line)", code: "invalid_session_file" }, { status: 400 }); } if (!cwd) { - return NextResponse.json({ error: "Not a valid omp session file (missing session header with cwd)", code: "invalid_session_file" }, { status: 400 }); + return Response.json({ error: "Not a valid omp session file (missing session header with cwd)", code: "invalid_session_file" }, { status: 400 }); } const allowedRoots = await getAllowedFileRoots(); if (!isExistingFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Imported session workspace is not authorized", code: "import_cwd_not_authorized" }, { status: 403 }); + return Response.json({ error: "Imported session workspace is not authorized", code: "import_cwd_not_authorized" }, { status: 403 }); } const sessionDir = path.join(getSessionsDir(), getSessionDirNameForCwd(cwd)); @@ -99,10 +98,10 @@ export async function POST(req: Request) { // The sidebar lists this machine's sessions through its daemon. invalidateLocalSessionLists(); - return NextResponse.json({ success: true, sessionFile }); + return Response.json({ success: true, sessionFile }); } catch (error) { if (error instanceof RequestBodyTooLargeError) { - return NextResponse.json({ error: "Session import request is too large", code: "session_import_request_too_large" }, { status: 413 }); + return Response.json({ error: "Session import request is too large", code: "session_import_request_too_large" }, { status: 413 }); } return apiErrorResponse(error); } diff --git a/app/api/sessions/route.ts b/app/api/sessions/route.ts index 257aecdc0..628cf9121 100644 --- a/app/api/sessions/route.ts +++ b/app/api/sessions/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { createHash } from "crypto"; import { listSessionsAllHosts } from "@/lib/hosts/session-index"; import { getRunningRpcSessions } from "@/lib/rpc-manager"; @@ -22,11 +21,11 @@ export async function GET(req: Request) { const bodyJson = JSON.stringify(body); const etag = `"${createHash("sha1").update(bodyJson).digest("hex").slice(0, 16)}"`; if (req.headers.get("if-none-match") === etag) { - return new NextResponse(null, { status: 304, headers: { ETag: etag, ...SESSION_LIST_HEADERS } }); + return new Response(null, { status: 304, headers: { ETag: etag, ...SESSION_LIST_HEADERS } }); } - return new NextResponse(bodyJson, { headers: { ETag: etag, "Content-Type": "application/json", ...SESSION_LIST_HEADERS } }); + return new Response(bodyJson, { headers: { ETag: etag, "Content-Type": "application/json", ...SESSION_LIST_HEADERS } }); } catch (error) { - return NextResponse.json( + return Response.json( { error: error instanceof Error ? error.message : String(error), code: "internal_error" }, { status: 500, headers: { "Cache-Control": "no-store" } }, ); diff --git a/app/api/sessions/search/route.ts b/app/api/sessions/search/route.ts index d565dd693..0c2ae391d 100644 --- a/app/api/sessions/search/route.ts +++ b/app/api/sessions/search/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { searchSessions } from "@/lib/session-content-search"; const MAX_QUERY_LENGTH = 500; @@ -6,10 +5,10 @@ const MAX_QUERY_LENGTH = 500; // GET /api/sessions/search?q= — NDJSON, one `{ scores }` line per batch of // scanned sessions (empty batches too, so the scan keeps reaching the reader). // Closing the request stops the scan after the batch being read (no resume). -export async function GET(req: Request) { +export async function GET(req: Request, { disableIdleTimeout }: { disableIdleTimeout: () => void }) { const q = new URL(req.url).searchParams.get("q") ?? ""; if (q.length > MAX_QUERY_LENGTH) { - return NextResponse.json({ error: "Query too long", code: "query_too_long" }, { status: 400 }); + return Response.json({ error: "Query too long", code: "query_too_long" }, { status: 400 }); } const batches = searchSessions(q); const encoder = new TextEncoder(); @@ -24,6 +23,7 @@ export async function GET(req: Request) { await batches.return(undefined); }, }); + disableIdleTimeout(); // X-Accel-Buffering: nginx must pass batches through as they arrive. return new Response(stream, { headers: { "Content-Type": "application/x-ndjson; charset=utf-8", "Cache-Control": "no-store", "X-Accel-Buffering": "no" } }); } diff --git a/app/api/skills/check/route.ts b/app/api/skills/check/route.ts index 789e1b5f6..d7ceef839 100644 --- a/app/api/skills/check/route.ts +++ b/app/api/skills/check/route.ts @@ -1,11 +1,8 @@ -import { NextResponse } from "next/server"; import type { SkillInstallScope } from "@/lib/api-types"; import { checkSkillUpdates } from "@/lib/skill-updates"; import { loadSkillsWithInstallInfo } from "@/lib/skills-service"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; -export const dynamic = "force-dynamic"; - export async function POST(req: Request) { try { const body = await req.json() as { @@ -14,10 +11,10 @@ export async function POST(req: Request) { scope?: unknown; }; const cwd = typeof body.cwd === "string" ? body.cwd : ""; - if (!cwd) return NextResponse.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); + if (!cwd) return Response.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); const allowedRoots = await getAllowedFileRoots(); if (!isExistingFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } const pkg = typeof body.package === "string" ? body.package : undefined; @@ -25,7 +22,7 @@ export async function POST(req: Request) { ? body.scope as SkillInstallScope : undefined; if ((pkg && !scope) || (!pkg && scope)) { - return NextResponse.json({ error: "package and scope must be provided together", code: "package_scope_together" }, { status: 400 }); + return Response.json({ error: "package and scope must be provided together", code: "package_scope_together" }, { status: 400 }); } const { skills } = await loadSkillsWithInstallInfo(cwd); @@ -35,15 +32,15 @@ export async function POST(req: Request) { .filter((install) => !pkg || (install.package === pkg && install.scope === scope)); if (pkg && installs.length === 0) { - return NextResponse.json({ error: "Installed skill not found", code: "skill_not_installed" }, { status: 404 }); + return Response.json({ error: "Installed skill not found", code: "skill_not_installed" }, { status: 404 }); } const updates = await checkSkillUpdates(installs, { githubToken: process.env.GITHUB_TOKEN || process.env.GH_TOKEN, }); - return NextResponse.json({ updates }); + return Response.json({ updates }); } catch (error) { - return NextResponse.json( + return Response.json( { error: error instanceof Error ? error.message : String(error) }, { status: 500 }, ); diff --git a/app/api/skills/install/route.ts b/app/api/skills/install/route.ts index 34af995d8..35f1747b2 100644 --- a/app/api/skills/install/route.ts +++ b/app/api/skills/install/route.ts @@ -1,30 +1,27 @@ -import { NextResponse } from "next/server"; import { runNpx } from "@/lib/npx"; import { createChildProcessEnvironment } from "@/lib/project-command-env"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; -export const dynamic = "force-dynamic"; - const ANSI_RE = /\x1B\[[0-9;]*m/g; // POST /api/skills/install body: { package: string; scope: "global" | "project"; cwd?: string } export async function POST(req: Request) { try { const { package: pkg, scope, cwd } = await req.json() as { package?: string; scope?: string; cwd?: string }; - if (!pkg?.trim()) return NextResponse.json({ error: "package required", code: "package_required" }, { status: 400 }); + if (!pkg?.trim()) return Response.json({ error: "package required", code: "package_required" }, { status: 400 }); // npm package-name grammar: scope-optional, URL-safe segments. Rejecting // leading dashes/`-` prefixes stops a value like `--force` from being // interpreted as npx/CLI options instead of a package name. const name = pkg.trim(); if (name.startsWith("-") || !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i.test(name)) { - return NextResponse.json({ error: "Invalid package name", code: "package_invalid" }, { status: 400 }); + return Response.json({ error: "Invalid package name", code: "package_invalid" }, { status: 400 }); } const isGlobal = scope !== "project"; if (!isGlobal) { - if (!cwd) return NextResponse.json({ error: "cwd required for project install", code: "cwd_required_for_project_install" }, { status: 400 }); + if (!cwd) return Response.json({ error: "cwd required for project install", code: "cwd_required_for_project_install" }, { status: 400 }); const allowedRoots = await getAllowedFileRoots(); if (!isExistingFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } } // The skills.sh CLI has no omp agent entry; "universal" installs into the @@ -43,15 +40,15 @@ export async function POST(req: Request) { const success = /Installation complete|Installed \d+ skill/.test(output); if (!success) { const detail = output.slice(-300); - return NextResponse.json( + return Response.json( detail ? { error: detail } : { error: "Install failed", code: "skill_install_failed" }, { status: 500 }, ); } - return NextResponse.json({ success: true, output }); + return Response.json({ success: true, output }); } catch (e: unknown) { const err = e as { stdout?: string; stderr?: string; message?: string }; const output = ((err.stdout ?? "") + (err.stderr ?? "")).replace(ANSI_RE, ""); - return NextResponse.json({ error: output || (err.message ?? String(e)) }, { status: 500 }); + return Response.json({ error: output || (err.message ?? String(e)) }, { status: 500 }); } } diff --git a/app/api/skills/route.ts b/app/api/skills/route.ts index 2df37184e..9d48f6e4b 100644 --- a/app/api/skills/route.ts +++ b/app/api/skills/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { existsSync, readFileSync, realpathSync, writeFileSync } from "fs"; import { basename } from "path"; import { @@ -10,8 +9,6 @@ import { } from "@/lib/skills-service"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; -export const dynamic = "force-dynamic"; - // GET /api/skills?cwd= // Lists what omp resolves (`omp skill list --json`), falling back to a scan // of omp's skill roots on binaries that predate the command. Each skill @@ -19,16 +16,16 @@ export const dynamic = "force-dynamic"; export async function GET(req: Request) { const { searchParams } = new URL(req.url); const cwd = searchParams.get("cwd"); - if (!cwd) return NextResponse.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); + if (!cwd) return Response.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); try { const allowedRoots = await getAllowedFileRoots(); if (!isExistingFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } - return NextResponse.json(await loadSkillsWithInstallInfo(cwd)); + return Response.json(await loadSkillsWithInstallInfo(cwd)); } catch (e) { - return NextResponse.json({ error: String(e) }, { status: 500 }); + return Response.json({ error: String(e) }, { status: 500 }); } } @@ -37,11 +34,11 @@ export async function PATCH(req: Request) { try { const body = await req.json() as { filePath: string; disableModelInvocation: boolean; cwd?: string }; const { filePath, disableModelInvocation, cwd } = body; - if (!filePath) return NextResponse.json({ error: "filePath required", code: "file_path_required" }, { status: 400 }); + if (!filePath) return Response.json({ error: "filePath required", code: "file_path_required" }, { status: 400 }); if (basename(filePath) !== "SKILL.md") { - return NextResponse.json({ error: "not a SKILL.md file", code: "not_a_skill_file" }, { status: 400 }); + return Response.json({ error: "not a SKILL.md file", code: "not_a_skill_file" }, { status: 400 }); } - if (!existsSync(filePath)) return NextResponse.json({ error: "file not found", code: "file_not_found" }, { status: 404 }); + if (!existsSync(filePath)) return Response.json({ error: "file not found", code: "file_not_found" }, { status: 404 }); // Every user-owned root the scanner reads must be writable here, or skills // in the compat dirs (~/.agents/skills — where the app's own global // installs land, ~/.claude/skills, ~/.codex/skills, managed-skills) could @@ -55,7 +52,7 @@ export async function PATCH(req: Request) { // it outside the checked roots. const resolvedFilePath = realpathSync(filePath); if (!isExistingFilePathAllowed(resolvedFilePath, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } const content = readFileSync(resolvedFilePath, "utf8"); @@ -64,8 +61,8 @@ export async function PATCH(req: Request) { // Report what the file now says rather than what was asked for. const { frontmatter } = parseSkillFrontmatter(updated); - return NextResponse.json({ success: true, disableModelInvocation: readDisableModelInvocation(frontmatter) }); + return Response.json({ success: true, disableModelInvocation: readDisableModelInvocation(frontmatter) }); } catch (e) { - return NextResponse.json({ error: String(e) }, { status: 500 }); + return Response.json({ error: String(e) }, { status: 500 }); } } diff --git a/app/api/skills/search/route.ts b/app/api/skills/search/route.ts index 95458be6c..01f264ce7 100644 --- a/app/api/skills/search/route.ts +++ b/app/api/skills/search/route.ts @@ -1,10 +1,7 @@ -import { NextResponse } from "next/server"; import { runNpx } from "@/lib/npx"; import { createChildProcessEnvironment } from "@/lib/project-command-env"; import type { SkillSearchResult } from "@/lib/api-types"; -export const dynamic = "force-dynamic"; - const ANSI_RE = /\x1B\[[0-9;]*m/g; const DEFAULT_LIMIT = 50; const MIN_LIMIT = 1; @@ -57,7 +54,8 @@ function parseSearchOutput(raw: string): SkillSearchResult[] { async function searchSkillsApi(query: string, limit: number): Promise { const url = `${SEARCH_API_BASE}/api/search?q=${encodeURIComponent(query)}&limit=${limit}`; - const res = await fetch(url, { cache: "no-store" }); + // A stalled skills.sh falls through to the CLI search instead of hanging the request. + const res = await fetch(url, { cache: "no-store", signal: AbortSignal.timeout(10_000) }); if (!res.ok) throw new Error(`skills.sh search failed: HTTP ${res.status}`); const data = (await res.json()) as SkillsApiResponse; @@ -92,12 +90,12 @@ function parseInstallCount(installs: string): number { export async function POST(req: Request) { try { const { query, limit: rawLimit } = await req.json() as { query?: string; limit?: unknown }; - if (!query?.trim()) return NextResponse.json({ error: "query required", code: "query_required" }, { status: 400 }); + if (!query?.trim()) return Response.json({ error: "query required", code: "query_required" }, { status: 400 }); const limit = parseLimit(rawLimit); try { const results = await searchSkillsApi(query.trim(), limit); - return NextResponse.json({ results }); + return Response.json({ results }); } catch { const { stdout, stderr } = await runNpx(["skills", "find", query.trim()], { timeout: 20000, @@ -105,13 +103,13 @@ export async function POST(req: Request) { }); const results = parseSearchOutput(stdout + stderr).slice(0, limit); - return NextResponse.json({ results }); + return Response.json({ results }); } } catch (e: unknown) { const err = e as { stdout?: string; stderr?: string; message?: string }; const raw = (err.stdout ?? "") + (err.stderr ?? ""); const results = raw ? parseSearchOutput(raw) : []; - if (results.length > 0) return NextResponse.json({ results }); - return NextResponse.json({ error: err.message ?? String(e) }, { status: 500 }); + if (results.length > 0) return Response.json({ results }); + return Response.json({ error: err.message ?? String(e) }, { status: 500 }); } } diff --git a/app/api/skills/update/route.ts b/app/api/skills/update/route.ts index ee8a2c01b..cb0ffa0fe 100644 --- a/app/api/skills/update/route.ts +++ b/app/api/skills/update/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { runNpx } from "@/lib/npx"; import { createChildProcessEnvironment } from "@/lib/project-command-env"; import type { SkillInstallScope } from "@/lib/api-types"; @@ -6,8 +5,6 @@ import { buildSkillUpdateArgs } from "@/lib/skill-updates"; import { loadSkillsWithInstallInfo } from "@/lib/skills-service"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; -export const dynamic = "force-dynamic"; - export async function POST(req: Request) { try { const body = await req.json() as { @@ -21,11 +18,11 @@ export async function POST(req: Request) { ? body.scope as SkillInstallScope : undefined; if (!cwd || !pkg || !scope) { - return NextResponse.json({ error: "cwd, package, and scope are required", code: "cwd_package_scope_required" }, { status: 400 }); + return Response.json({ error: "cwd, package, and scope are required", code: "cwd_package_scope_required" }, { status: 400 }); } const allowedRoots = await getAllowedFileRoots(); if (!isExistingFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } const { skills } = await loadSkillsWithInstallInfo(cwd); @@ -33,10 +30,10 @@ export async function POST(req: Request) { (item) => item.install?.package === pkg && item.install.scope === scope, ); if (!skill?.install) { - return NextResponse.json({ error: "Installed skill not found", code: "skill_not_installed" }, { status: 404 }); + return Response.json({ error: "Installed skill not found", code: "skill_not_installed" }, { status: 404 }); } if (!skill.install.canCheckForUpdates) { - return NextResponse.json({ error: "This skill cannot be updated automatically", code: "skill_update_unsupported" }, { status: 400 }); + return Response.json({ error: "This skill cannot be updated automatically", code: "skill_update_unsupported" }, { status: 400 }); } const { stdout, stderr } = await runNpx(buildSkillUpdateArgs(skill.install), { @@ -49,7 +46,7 @@ export async function POST(req: Request) { const updatedSkill = refreshed.skills.find( (item) => item.install?.package === pkg && item.install.scope === scope, ); - return NextResponse.json({ + return Response.json({ success: true, skill: updatedSkill, output: `${stdout}${stderr}`.slice(-500), @@ -57,7 +54,7 @@ export async function POST(req: Request) { } catch (error: unknown) { const detail = error as { stdout?: string; stderr?: string; message?: string }; const output = `${detail.stdout ?? ""}${detail.stderr ?? ""}`; - return NextResponse.json( + return Response.json( { error: output || detail.message || String(error) }, { status: 500 }, ); diff --git a/app/api/stt/[jobId]/audio/route.ts b/app/api/stt/[jobId]/audio/route.ts index 60ee5f35a..c3e2ee7ee 100644 --- a/app/api/stt/[jobId]/audio/route.ts +++ b/app/api/stt/[jobId]/audio/route.ts @@ -1,13 +1,10 @@ -import { NextResponse } from "next/server"; import { getSttJobAudio } from "@/lib/stt-jobs"; -export const dynamic = "force-dynamic"; - /** GET /api/stt/[jobId]/audio — the recording kept with a live job, for playback in any browser. */ export async function GET(_req: Request, { params }: { params: Promise<{ jobId: string }> }) { const audio = getSttJobAudio((await params).jobId); if (!audio) { - return NextResponse.json({ error: "Transcription job not found", code: "stt_job_not_found" }, { status: 404 }); + return Response.json({ error: "Transcription job not found", code: "stt_job_not_found" }, { status: 404 }); } // The type came from the uploading browser: serve only a bare audio/* type // so a crafted upload cannot render as HTML on this origin. diff --git a/app/api/stt/[jobId]/route.ts b/app/api/stt/[jobId]/route.ts index 80847985b..605029c91 100644 --- a/app/api/stt/[jobId]/route.ts +++ b/app/api/stt/[jobId]/route.ts @@ -1,13 +1,9 @@ -import { NextResponse } from "next/server"; -import { readSttConfig } from "@/lib/stt"; -import { closeSttJob, getSttJob, retrySttJob } from "@/lib/stt-jobs"; - -export const dynamic = "force-dynamic"; +import { closeSttJob, getSttJob, readSttConfig, retrySttJob } from "@/lib/stt-jobs"; type Params = { params: Promise<{ jobId: string }> }; const notFound = () => - NextResponse.json({ error: "Transcription job not found", code: "stt_job_not_found" }, { status: 404 }); + Response.json({ error: "Transcription job not found", code: "stt_job_not_found" }, { status: 404 }); /** * GET /api/stt/[jobId] — { id, status: "pending" | "done" | "error" | "gone", error? }, @@ -18,21 +14,21 @@ const notFound = () => */ export async function GET(_req: Request, { params }: Params) { const job = getSttJob((await params).jobId); - return job ? NextResponse.json(job) : notFound(); + return job ? Response.json(job) : notFound(); } /** POST /api/stt/[jobId]?owner= — retry a failed job with the audio the server kept. */ export async function POST(req: Request, { params }: Params) { const config = readSttConfig(); if (!config) { - return NextResponse.json({ error: "STT not configured. Set OMP_WEB_STT_ENDPOINT or OMP_WEB_STT_MODEL." }, { status: 501 }); + return Response.json({ error: "STT not configured. Set OMP_WEB_STT_ENDPOINT or OMP_WEB_STT_MODEL." }, { status: 501 }); } const owner = new URL(req.url).searchParams.get("owner")?.slice(0, 128) || undefined; const job = retrySttJob(config, (await params).jobId, owner); if (job === "busy") { - return NextResponse.json({ error: "Too many transcriptions in progress", code: "stt_busy" }, { status: 429 }); + return Response.json({ error: "Too many transcriptions in progress", code: "stt_busy" }, { status: 429 }); } - return job ? NextResponse.json(job) : notFound(); + return job ? Response.json(job) : notFound(); } /** @@ -48,5 +44,5 @@ export async function DELETE(req: Request, { params }: Params) { const claim = query.get("claim")?.slice(0, 128) || undefined; const owner = query.get("owner")?.slice(0, 128) || undefined; const job = closeSttJob((await params).jobId, claim, owner); - return job ? NextResponse.json(job) : notFound(); + return job ? Response.json(job) : notFound(); } diff --git a/app/api/stt/route.ts b/app/api/stt/route.ts index dbbf7fe6b..62c3032cf 100644 --- a/app/api/stt/route.ts +++ b/app/api/stt/route.ts @@ -1,9 +1,6 @@ -import { NextResponse } from "next/server"; import { parseFormDataWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; -import { isSttAfter, MAX_STT_AUDIO_BYTES, MAX_STT_REQUEST_BYTES, readSttConfig } from "@/lib/stt"; -import { listSttJobs, startSttJob } from "@/lib/stt-jobs"; - -export const dynamic = "force-dynamic"; +import { isSttAfter, MAX_STT_AUDIO_BYTES, MAX_STT_REQUEST_BYTES } from "@/lib/stt"; +import { listSttJobs, readSttConfig, startSttJob } from "@/lib/stt-jobs"; const MAX_SCOPE_LENGTH = 1024; @@ -11,9 +8,9 @@ const MAX_SCOPE_LENGTH = 1024; export async function GET(request: Request) { const scope = new URL(request.url).searchParams.get("scope"); if (!scope || scope.length > MAX_SCOPE_LENGTH) { - return NextResponse.json({ error: "scope is required", code: "missing_scope" }, { status: 400 }); + return Response.json({ error: "scope is required", code: "missing_scope" }, { status: 400 }); } - return NextResponse.json({ jobs: listSttJobs(scope) }); + return Response.json({ jobs: listSttJobs(scope) }); } /** @@ -25,7 +22,7 @@ export async function POST(request: Request) { try { const config = readSttConfig(); if (!config) { - return NextResponse.json( + return Response.json( { error: "STT not configured. Set OMP_WEB_STT_ENDPOINT or OMP_WEB_STT_MODEL." }, { status: 501 } ); @@ -34,27 +31,27 @@ export async function POST(request: Request) { const formData = await parseFormDataWithinLimit(request, MAX_STT_REQUEST_BYTES); const file = formData.get("file"); if (!file || typeof file === "string" || file.size === 0) { - return NextResponse.json( + return Response.json( { error: "Audio file is required", code: "missing_audio_file" }, { status: 400 } ); } if (file.size > MAX_STT_AUDIO_BYTES) { - return NextResponse.json( + return Response.json( { error: "Audio file too large (max 25MB)", code: "audio_too_large" }, { status: 413 } ); } const scope = formData.get("scope"); if (scope !== null && (typeof scope !== "string" || scope.length > MAX_SCOPE_LENGTH)) { - return NextResponse.json({ error: "Invalid scope", code: "invalid_scope" }, { status: 400 }); + return Response.json({ error: "Invalid scope", code: "invalid_scope" }, { status: 400 }); } // The uploader's claim token: it gets first claim on the transcript. const owner = formData.get("owner"); // What to do with the transcript (send/steer/followup); absent = insert. const after = formData.get("after"); if (after !== null && !isSttAfter(after)) { - return NextResponse.json({ error: "Invalid after", code: "invalid_after" }, { status: 400 }); + return Response.json({ error: "Invalid after", code: "invalid_after" }, { status: 400 }); } const jobId = startSttJob(config, { @@ -64,19 +61,19 @@ export async function POST(request: Request) { after: after ?? undefined, }); if (!jobId) { - return NextResponse.json( + return Response.json( { error: "Too many transcriptions in progress", code: "stt_busy" }, { status: 429 } ); } - return NextResponse.json({ jobId }, { status: 202 }); + return Response.json({ jobId }, { status: 202 }); } catch (error) { if (error instanceof RequestBodyTooLargeError) { - return NextResponse.json( + return Response.json( { error: "Audio file too large (max 25MB)", code: "audio_too_large" }, { status: 413 } ); } - return NextResponse.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); + return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); } } diff --git a/app/api/usage/route.ts b/app/api/usage/route.ts index 5ce53fbb0..4e353ece4 100644 --- a/app/api/usage/route.ts +++ b/app/api/usage/route.ts @@ -1,10 +1,7 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse } from "@/lib/api-utils"; import { getUsageReport } from "@/lib/usage-service"; import type { UsageGranularity, UsageTimeRange } from "@/lib/usage-types"; -export const dynamic = "force-dynamic"; - export async function GET(req: Request) { try { const url = new URL(req.url); @@ -38,7 +35,7 @@ export async function GET(req: Request) { forceRefresh, }); - return NextResponse.json(report); + return Response.json(report); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/web-auth/session/route.ts b/app/api/web-auth/session/route.ts index e432eaef4..a9faa96ae 100644 --- a/app/api/web-auth/session/route.ts +++ b/app/api/web-auth/session/route.ts @@ -1,5 +1,5 @@ -import { NextResponse } from "next/server"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; +import { requestProtocol } from "@/lib/request-security"; import { createWebSession, isValidWebPassword, @@ -12,7 +12,7 @@ const MAX_PASSWORD_REQUEST_BYTES = 8 * 1024; export async function POST(request: Request) { if (!isWebPasswordEnabled()) { - return NextResponse.json({ error: "Password protection is disabled" }, { status: 404 }); + return Response.json({ error: "Password protection is disabled" }, { status: 404 }); } let body: { password?: unknown }; @@ -20,22 +20,19 @@ export async function POST(request: Request) { body = await parseJsonWithinLimit(request, MAX_PASSWORD_REQUEST_BYTES); } catch (error) { const status = error instanceof RequestBodyTooLargeError ? 413 : 400; - return NextResponse.json({ error: "Invalid password request" }, { status }); + return Response.json({ error: "Invalid password request" }, { status }); } if (typeof body.password !== "string" || !isValidWebPassword(body.password)) { - return NextResponse.json({ error: "Incorrect password" }, { status: 401 }); + return Response.json({ error: "Incorrect password" }, { status: 401 }); } - const response = NextResponse.json({ ok: true }); - const secure = new URL(request.url).protocol === "https:" || request.headers.get("x-forwarded-proto") === "https"; - response.cookies.set({ - name: OMP_WEB_SESSION_COOKIE, - value: createWebSession(), + const secure = requestProtocol(request) === "https:"; + const cookie = new Bun.Cookie(OMP_WEB_SESSION_COOKIE, createWebSession(), { httpOnly: true, secure, sameSite: "lax", maxAge: OMP_WEB_SESSION_MAX_AGE_SECONDS, path: "/", }); - return response; + return Response.json({ ok: true }, { headers: { "set-cookie": cookie.serialize() } }); } diff --git a/app/api/web-settings/route.ts b/app/api/web-settings/route.ts index 391a860f8..79438745e 100644 --- a/app/api/web-settings/route.ts +++ b/app/api/web-settings/route.ts @@ -1,14 +1,11 @@ -import { NextResponse } from "next/server"; import { syncInterruptibleSessions } from "@/lib/rpc-manager"; import { parseAgentEnvText, sanitizeAgentEnvValues, type AgentEnvParseResult } from "@/lib/omp/agent-env"; import { loadWebServerSettings, saveWebServerSettings, type WebServerSettings } from "@/lib/web-settings"; import { isRecord } from "@/lib/type-guards"; -export const dynamic = "force-dynamic"; - /** GET/PUT /api/web-settings - omp-web's own server-side settings. */ export async function GET() { - return NextResponse.json(readSettings()); + return Response.json(readSettings()); } /** Never surface a variable lib/omp/agent-env.ts would refuse to spawn with. */ @@ -22,10 +19,10 @@ export async function PUT(req: Request) { try { body = await req.json(); } catch { - return NextResponse.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); + return Response.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); } if (!isRecord(body)) { - return NextResponse.json({ error: "Request body must be a settings object", code: "invalid_settings" }, { status: 400 }); + return Response.json({ error: "Request body must be a settings object", code: "invalid_settings" }, { status: 400 }); } const payload = body as { autoResumeSessions?: unknown; agentToolsEnabled?: unknown; agentEnv?: unknown }; const patch: Partial = {}; @@ -35,7 +32,7 @@ export async function PUT(req: Request) { let resumeProvided = false; if (payload.autoResumeSessions !== undefined) { if (typeof payload.autoResumeSessions !== "boolean") { - return NextResponse.json({ error: "autoResumeSessions must be a boolean", code: "invalid_settings" }, { status: 400 }); + return Response.json({ error: "autoResumeSessions must be a boolean", code: "invalid_settings" }, { status: 400 }); } patch.autoResumeSessions = payload.autoResumeSessions; resumeProvided = true; @@ -43,7 +40,7 @@ export async function PUT(req: Request) { if (payload.agentToolsEnabled !== undefined) { if (typeof payload.agentToolsEnabled !== "boolean") { - return NextResponse.json({ error: "agentToolsEnabled must be a boolean", code: "invalid_settings" }, { status: 400 }); + return Response.json({ error: "agentToolsEnabled must be a boolean", code: "invalid_settings" }, { status: 400 }); } patch.agentToolsEnabled = payload.agentToolsEnabled; } @@ -56,13 +53,13 @@ export async function PUT(req: Request) { } else if (isRecord(payload.agentEnv)) { parsed = sanitizeAgentEnvValues(payload.agentEnv); } else { - return NextResponse.json( + return Response.json( { error: "agentEnv must be KEY=VALUE text or an object of variables", code: "invalid_agent_env" }, { status: 400 }, ); } if (parsed.errors.length > 0) { - return NextResponse.json( + return Response.json( { error: "agentEnv contains invalid or reserved variable names", code: "invalid_agent_env", errors: parsed.errors }, { status: 400 }, ); @@ -74,5 +71,5 @@ export async function PUT(req: Request) { // Apply to sessions that are already running, not only the next run. Only when the // flag was part of this save — an agentEnv-only write must not touch live sessions. if (resumeProvided) syncInterruptibleSessions(); - return NextResponse.json({ ...settings, agentEnv: sanitizeAgentEnvValues(settings.agentEnv).values }); + return Response.json({ ...settings, agentEnv: sanitizeAgentEnvValues(settings.agentEnv).values }); } \ No newline at end of file diff --git a/app/api/windows-service/route.ts b/app/api/windows-service/route.ts index eb5c13b66..9ed4414ea 100644 --- a/app/api/windows-service/route.ts +++ b/app/api/windows-service/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { getWebServiceStatus, installTrayShortcuts, @@ -7,11 +6,8 @@ import { startTrayService, stopTrayService, restartTrayService, - WebServiceStatus, } from "@/lib/windows-service"; -export const dynamic = "force-dynamic"; - interface WindowsServiceRequestBody { action?: "install" | "uninstall" | "toggle-autostart" | "start" | "stop" | "restart"; port?: number; @@ -22,20 +18,20 @@ interface WindowsServiceRequestBody { cleanConfig?: boolean; } -export async function GET(): Promise> { +export async function GET(): Promise { const status = await getWebServiceStatus(); - return NextResponse.json(status, { + return Response.json(status, { headers: { "Cache-Control": "no-store" }, }); } -export async function POST(request: Request): Promise { +export async function POST(request: Request): Promise { try { const body = (await request.json()) as WindowsServiceRequestBody; const { action } = body; if (!action) { - return NextResponse.json( + return Response.json( { error: "Missing required 'action' parameter.", code: "missing_action" }, { status: 400 } ); @@ -79,7 +75,7 @@ export async function POST(request: Request): Promise { break; default: - return NextResponse.json( + return Response.json( { error: `Unknown action '${String(action)}'.`, code: "invalid_action" }, { status: 400 } ); @@ -88,7 +84,7 @@ export async function POST(request: Request): Promise { const updatedStatus = await getWebServiceStatus(); if (!result.success) { - return NextResponse.json( + return Response.json( { error: result.message || `Action '${action}' failed.`, code: "action_failed", @@ -98,13 +94,13 @@ export async function POST(request: Request): Promise { ); } - return NextResponse.json({ + return Response.json({ success: true, message: result.message, status: updatedStatus, }); } catch (error) { const message = error instanceof Error ? error.message : String(error); - return NextResponse.json({ error: message, code: "server_error" }, { status: 500 }); + return Response.json({ error: message, code: "server_error" }, { status: 500 }); } } diff --git a/app/api/worktrees/route.ts b/app/api/worktrees/route.ts index 2d564cc22..051a819f6 100644 --- a/app/api/worktrees/route.ts +++ b/app/api/worktrees/route.ts @@ -1,4 +1,3 @@ -import { NextResponse } from "next/server"; import { apiErrorResponse } from "@/lib/api-utils"; import { existsSync } from "fs"; import { join } from "path"; @@ -10,10 +9,10 @@ import { invalidateSessionListCache } from "@/lib/session-reader"; /** Same gate as /api/files: only session cwds / project roots / explicitly * allowed dirs may be inspected or mutated through this endpoint. */ -async function checkCwdAllowed(cwd: string): Promise { +async function checkCwdAllowed(cwd: string): Promise { const allowedRoots = await getAllowedFileRoots(); if (!isFilePathAllowed(cwd, allowedRoots) || !isExistingFilePathAllowed(cwd, allowedRoots)) { - return NextResponse.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } return null; } @@ -34,7 +33,7 @@ export async function GET(req: Request) { try { const cwd = new URL(req.url).searchParams.get("cwd"); if (!cwd) { - return NextResponse.json({ error: "cwd is required", code: "cwd_required" }, { status: 400 }); + return Response.json({ error: "cwd is required", code: "cwd_required" }, { status: 400 }); } const denied = await checkCwdAllowed(cwd); if (denied) return denied; @@ -57,7 +56,7 @@ export async function GET(req: Request) { // file explorer to browse them even before they have any session (the // in-memory allowlist from addWorktree does not survive server restarts). for (const w of worktrees) allowFileRoot(w.path); - return NextResponse.json({ + return Response.json({ projectRoot: project.projectRoot, projectKey: projectIdentityKey(project.projectRoot), isGit, @@ -75,24 +74,24 @@ export async function POST(req: Request) { try { const body = await req.json() as { cwd?: string; branch?: string }; if (!body.cwd || typeof body.cwd !== "string") { - return NextResponse.json({ error: "cwd is required", code: "cwd_required" }, { status: 400 }); + return Response.json({ error: "cwd is required", code: "cwd_required" }, { status: 400 }); } if (!body.branch || typeof body.branch !== "string") { - return NextResponse.json({ error: "branch is required", code: "branch_required" }, { status: 400 }); + return Response.json({ error: "branch is required", code: "branch_required" }, { status: 400 }); } const denied = await checkCwdAllowed(body.cwd); if (denied) return denied; if (!existsSync(body.cwd)) { - return NextResponse.json({ error: `Directory does not exist: ${body.cwd}`, code: "directory_not_found" }, { status: 400 }); + return Response.json({ error: `Directory does not exist: ${body.cwd}`, code: "directory_not_found" }, { status: 400 }); } const result = await addWorktree(body.cwd, body.branch); invalidateSessionListCache(); invalidateLocalSessionLists(); - return NextResponse.json(result); + return Response.json(result); } catch (error) { const message = error instanceof Error ? error.message : String(error); - return NextResponse.json({ error: message, code: worktreeErrorCode(message) }, { status: 400 }); + return Response.json({ error: message, code: worktreeErrorCode(message) }, { status: 400 }); } } @@ -101,10 +100,10 @@ export async function DELETE(req: Request) { try { const body = await req.json() as { cwd?: string; path?: string; force?: boolean }; if (!body.cwd || typeof body.cwd !== "string") { - return NextResponse.json({ error: "cwd is required", code: "cwd_required" }, { status: 400 }); + return Response.json({ error: "cwd is required", code: "cwd_required" }, { status: 400 }); } if (!body.path || typeof body.path !== "string") { - return NextResponse.json({ error: "path is required", code: "path_required" }, { status: 400 }); + return Response.json({ error: "path is required", code: "path_required" }, { status: 400 }); } const denied = await checkCwdAllowed(body.cwd); if (denied) return denied; @@ -112,13 +111,13 @@ export async function DELETE(req: Request) { await removeWorktree(body.cwd, body.path, body.force === true); invalidateSessionListCache(); invalidateLocalSessionLists(); - return NextResponse.json({ success: true }); + return Response.json({ success: true }); } catch (error) { const message = error instanceof Error ? error.message : String(error); // git refuses to remove dirty worktrees without --force; surface that so // the UI can offer a force-remove confirmation. const dirty = /contains modified or untracked files|is dirty/i.test(message); const code = dirty ? "worktree_dirty" : worktreeErrorCode(message); - return NextResponse.json({ error: message, code, dirty }, { status: dirty ? 409 : 400 }); + return Response.json({ error: message, code, dirty }, { status: dirty ? 409 : 400 }); } } diff --git a/app/boot.ts b/app/boot.ts new file mode 100644 index 000000000..bf3410ba6 --- /dev/null +++ b/app/boot.ts @@ -0,0 +1,6 @@ +// Imported first by client.tsx so it runs before AppShell's module evaluates and registers its own popstate listeners. +import { SIDEBAR_HISTORY_BRIDGE_SCRIPT } from "@/lib/sidebar-history-bridge"; + +const script = document.createElement("script"); +script.textContent = SIDEBAR_HISTORY_BRIDGE_SCRIPT; +document.head.append(script); diff --git a/app/client.test.mjs b/app/client.test.mjs new file mode 100644 index 000000000..817f41354 --- /dev/null +++ b/app/client.test.mjs @@ -0,0 +1,23 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test from "node:test"; +import { act, createElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { LoginForm } from "../components/LoginForm"; + +test("a password typed into the static sign-in form is in LoginForm's field once the bundle runs", async () => { + window.history.replaceState(null, "", "/login"); + Object.defineProperty(globalThis, "location", { configurable: true, value: window.location }); + // What app/index.html's inline script puts in #root on /login (LoginForm.test.mjs keeps the two identical). + document.body.innerHTML = `
${renderToStaticMarkup(createElement(LoginForm))}
`; + const staticField = document.querySelector("#root #web-password"); + staticField.value = "typed before the bundle"; + + await act(async () => { + await import("./client.tsx"); + }); + + const field = document.querySelector("#root #web-password"); + assert.ok(field && field !== staticField, "LoginForm did not replace the static form"); + assert.equal(field.value, "typed before the bundle"); +}); diff --git a/app/client.tsx b/app/client.tsx new file mode 100644 index 000000000..a988daa36 --- /dev/null +++ b/app/client.tsx @@ -0,0 +1,26 @@ +import "./boot"; +import { StrictMode, Suspense } from "react"; +import { createRoot } from "react-dom/client"; +import { AppErrorBoundary } from "@/components/AppErrorBoundary"; +import { AppShell } from "@/components/AppShell"; +import { IosFocusZoomGuard } from "@/components/IosFocusZoomGuard"; +import { LoginForm } from "@/components/LoginForm"; +import { RouteLoadingFallback } from "@/components/RouteLoadingFallback"; + +// createRoot (not hydrateRoot) replaces the static skeleton or sign-in form that app/index.html puts in #root; a +// password typed into the static form carries over. +const typedPassword = document.querySelector("#root #web-password")?.value; +createRoot(document.getElementById("root")!).render( + + + + {location.pathname === "/login" ? ( + + ) : ( + }> + + + )} + + , +); diff --git a/app/fonts/Geist-OFL.txt b/app/fonts/Geist-OFL.txt new file mode 100644 index 000000000..98835ac3f --- /dev/null +++ b/app/fonts/Geist-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font) Geist-Italic[wght].ttf: Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/fonts/JetBrainsMono-OFL.txt b/app/fonts/JetBrainsMono-OFL.txt new file mode 100644 index 000000000..8f7ed6711 --- /dev/null +++ b/app/fonts/JetBrainsMono-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) JetBrainsMono-Italic[wght].ttf: Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/fonts/NotoSansMono-OFL.txt b/app/fonts/NotoSansMono-OFL.txt new file mode 100644 index 000000000..50107b8ca --- /dev/null +++ b/app/fonts/NotoSansMono-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/fonts/SourceSerif4-OFL.txt b/app/fonts/SourceSerif4-OFL.txt new file mode 100644 index 000000000..046fc6649 --- /dev/null +++ b/app/fonts/SourceSerif4-OFL.txt @@ -0,0 +1,93 @@ +Google Inc. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/fonts/geist-latin-wght-normal.woff2 b/app/fonts/geist-latin-wght-normal.woff2 new file mode 100644 index 000000000..991445d78 Binary files /dev/null and b/app/fonts/geist-latin-wght-normal.woff2 differ diff --git a/app/fonts/jetbrains-mono-latin-wght-normal.woff2 b/app/fonts/jetbrains-mono-latin-wght-normal.woff2 new file mode 100644 index 000000000..cd5102a44 Binary files /dev/null and b/app/fonts/jetbrains-mono-latin-wght-normal.woff2 differ diff --git a/app/fonts/noto-sans-mono-cyrillic-wght-normal.woff2 b/app/fonts/noto-sans-mono-cyrillic-wght-normal.woff2 new file mode 100644 index 000000000..c0ff49e26 Binary files /dev/null and b/app/fonts/noto-sans-mono-cyrillic-wght-normal.woff2 differ diff --git a/app/fonts/noto-sans-mono-latin-wght-normal.woff2 b/app/fonts/noto-sans-mono-latin-wght-normal.woff2 new file mode 100644 index 000000000..76c9c2638 Binary files /dev/null and b/app/fonts/noto-sans-mono-latin-wght-normal.woff2 differ diff --git a/app/fonts/source-serif-4-latin-wght-normal.woff2 b/app/fonts/source-serif-4-latin-wght-normal.woff2 new file mode 100644 index 000000000..4c3e6b90c Binary files /dev/null and b/app/fonts/source-serif-4-latin-wght-normal.woff2 differ diff --git a/app/global-error.tsx b/app/global-error.tsx deleted file mode 100644 index 14ba12257..000000000 --- a/app/global-error.tsx +++ /dev/null @@ -1,63 +0,0 @@ -"use client"; - -import { useEffect } from "react"; - -// Global error boundary — this must NOT import from @/lib/* because the error -// may be caused by a module loading failure. Use inline minimal styles and -// hardcoded English text (this is the absolute fallback). -export default function GlobalError({ - error, - reset, -}: { - error: Error & { digest?: string }; - reset: () => void; -}) { - useEffect(() => { - console.error("Global application error:", error); - }, [error]); - - return ( - - -
-

- Something went wrong -

-

- An unexpected error occurred. Try reloading the page. -

- -
- - - ); -} diff --git a/app/globals.css b/app/globals.css index f60f6f629..07cd54a68 100644 --- a/app/globals.css +++ b/app/globals.css @@ -52,7 +52,7 @@ unicode-range: U+E000-F8FF, U+F0000-FFFFD; } /* CJK display serif for headings, bundled instead of fetched from Google - Fonts (whose extensionless /l/font?kit= URLs crashed next/font builds). + Fonts (whose extensionless /l/font?kit= URLs crashed the font build). A GB2312 + kana subset of Noto Serif SC, weights 600-700; unicode-range keeps Latin-only pages from downloading it. See fonts/NotoSerifSC-README.md. */ @font-face { @@ -62,6 +62,89 @@ font-display: swap; unicode-range: U+3000-30FF, U+4E00-9FFF, U+FF00-FFEF; } +/* Variable UI faces from @fontsource-variable (SIL OFL 1.1; licenses in fonts/*-OFL.txt), + latin subsets (plus cyrillic for Noto Sans Mono) as before. unicode-range keeps + cyrillic from downloading until needed. */ +@font-face { + font-family: 'Geist Variable'; + font-style: normal; + font-display: swap; + font-weight: 100 900; + src: url("./fonts/geist-latin-wght-normal.woff2") format('woff2-variations'); + unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; +} +@font-face { + font-family: 'JetBrains Mono Variable'; + font-style: normal; + font-display: swap; + font-weight: 100 800; + src: url("./fonts/jetbrains-mono-latin-wght-normal.woff2") format('woff2-variations'); + unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; +} +@font-face { + font-family: 'Noto Sans Mono Variable'; + font-style: normal; + font-display: swap; + font-weight: 100 900; + src: url("./fonts/noto-sans-mono-cyrillic-wght-normal.woff2") format('woff2-variations'); + unicode-range: U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116; +} +@font-face { + font-family: 'Noto Sans Mono Variable'; + font-style: normal; + font-display: swap; + font-weight: 100 900; + src: url("./fonts/noto-sans-mono-latin-wght-normal.woff2") format('woff2-variations'); + unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; +} +@font-face { + font-family: 'Source Serif 4 Variable'; + font-style: normal; + font-display: swap; + font-weight: 200 900; + src: url("./fonts/source-serif-4-latin-wght-normal.woff2") format('woff2-variations'); + unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; +} +/* Metric-adjusted local fallbacks, the values next/font (adjustFontFallback) generated: until a + webfont swaps in, text set in the fallback takes the same space, so the swap reflows less. */ +@font-face { + font-family: "Geist Fallback"; + src: local("Arial"); + ascent-override: 95.94%; + descent-override: 28.16%; + line-gap-override: 0.00%; + size-adjust: 104.76%; +} +@font-face { + font-family: "JetBrains Mono Fallback"; + src: local("Arial"); + ascent-override: 75.79%; + descent-override: 22.29%; + line-gap-override: 0.00%; + size-adjust: 134.59%; +} +@font-face { + font-family: "Noto Sans Mono Fallback"; + src: local("Arial"); + ascent-override: 79.43%; + descent-override: 21.77%; + line-gap-override: 0.00%; + size-adjust: 134.59%; +} +@font-face { + font-family: "Source Serif 4 Fallback"; + src: local("Times New Roman"); + ascent-override: 87.87%; + descent-override: 28.41%; + line-gap-override: 0.00%; + size-adjust: 117.91%; +} +:root { + --font-geist: "Geist Variable", "Geist Fallback"; + --font-jb-mono: "JetBrains Mono Variable", "JetBrains Mono Fallback"; + --font-noto-mono: "Noto Sans Mono Variable", "Noto Sans Mono Fallback"; + --font-source-serif: "Source Serif 4 Variable", "Source Serif 4 Fallback"; +} @theme { --color-bg: var(--bg); --color-bg-panel: var(--bg-panel); diff --git a/app/index.html b/app/index.html new file mode 100644 index 000000000..cf2b0588d --- /dev/null +++ b/app/index.html @@ -0,0 +1,76 @@ + + + + + + omp web + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + + +
+ + + diff --git a/app/layout.tsx b/app/layout.tsx deleted file mode 100644 index 332597e00..000000000 --- a/app/layout.tsx +++ /dev/null @@ -1,117 +0,0 @@ -import type { Metadata, Viewport } from "next"; -import { headers } from "next/headers"; -import Script from "next/script"; -import { Geist, JetBrains_Mono, Noto_Sans_Mono, Source_Serif_4 } from "next/font/google"; -import { ThemeColor } from "@/hooks/useTheme"; -import { IosFocusZoomGuard } from "@/components/IosFocusZoomGuard"; -import { SIDEBAR_HISTORY_BRIDGE_SCRIPT } from "@/lib/sidebar-history-bridge"; -import { getInstallName } from "@/lib/install-name"; -import "./globals.css"; - -const geist = Geist({ - subsets: ["latin"], - variable: "--font-geist", - display: "swap", -}); - -const jetbrainsMono = JetBrains_Mono({ - subsets: ["latin"], - weight: ["400", "500", "600"], - variable: "--font-jb-mono", - display: "swap", -}); - -const notoSansMono = Noto_Sans_Mono({ - subsets: ["latin", "cyrillic"], - variable: "--font-noto-mono", - display: "swap", -}); - -// Display serif for the warm-humanistic heading voice. Source Serif 4 covers -// latin; CJK uses a bundled Noto Serif SC subset declared in globals.css, not -// next/font/google: Google Fonts sometimes serves it through extensionless -// `/l/font?kit=` URLs that next/font cannot parse, which failed builds at random. -const sourceSerif = Source_Serif_4({ - subsets: ["latin"], - variable: "--font-source-serif", - display: "swap", -}); - -export async function generateMetadata(): Promise { - const title = getInstallName(await headers()); - return { - title, - description: "Web UI for the oh-my-pi (omp) coding agent", - // PWA-like behavior on iOS: standalone chrome, no telephone autodetect. - appleWebApp: { - capable: true, - title, - statusBarStyle: "default", - }, - formatDetection: { - telephone: false, - }, - }; -} - -// `viewportFit: cover` honors safe-area-inset on notched devices. -// `interactiveWidget: resizes-content` makes the soft keyboard shrink the -// layout viewport, keeping the composer above the keyboard. -export const viewport: Viewport = { - width: "device-width", - initialScale: 1, - viewportFit: "cover", - interactiveWidget: "resizes-content", -}; - -export default function RootLayout({ - children, -}: { - children: React.ReactNode; -}) { - return ( - - - - - - {/* Register before Next's router. Owned sidebar traversals must be handled - before the router can synchronously restore an older session URL. */} - - {/* Apply the stored theme and its CSS background to browser chrome before - first paint. The hydrated hook keeps both in sync afterward. */} - "; await link("Hostile", { listSessions: () => [entry(OTHER)], exportSession: () => ({ ok: true, value: { html, fileName: "x.html" } }) }); - const routeJiti = createJiti(import.meta.url, { tryNative: false, alias: { "@/": fileURLToPath(new URL("../../", import.meta.url)) } }); - const { GET } = await routeJiti.import("../../app/api/sessions/[id]/export/route.ts"); + const { GET } = await import("../../app/api/sessions/[id]/export/route.ts"); const response = await GET(new Request(`http://main.test/api/sessions/${OTHER}/export?inline=1`), { params: Promise.resolve({ id: OTHER }) }); assert.equal(response.status, 200); assert.match(response.headers.get("content-disposition"), /^attachment;/); diff --git a/lib/hosts/session-index.ts b/lib/hosts/session-index.ts index 33c1fe164..e18c5427f 100644 --- a/lib/hosts/session-index.ts +++ b/lib/hosts/session-index.ts @@ -29,7 +29,7 @@ declare global { var __ompHostLists: Map | undefined; } -// globalThis, like the hub: survives Next.js hot reload. +// globalThis, like the hub: survives a `bun --hot` re-evaluation. function hostLists(hostId: string): HostLists { if (!globalThis.__ompHostLists) { globalThis.__ompHostLists = new Map(); diff --git a/lib/hosts/session-ops.test.mjs b/lib/hosts/session-ops.test.mjs index 865d61899..db6a886b1 100644 --- a/lib/hosts/session-ops.test.mjs +++ b/lib/hosts/session-ops.test.mjs @@ -3,11 +3,9 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { sessionOps } = await jiti.import("./session-ops.ts"); -const { invalidateSessionListCache } = await jiti.import("../session-reader.ts"); +const { sessionOps } = await import("./session-ops.ts"); +const { invalidateSessionListCache } = await import("../session-reader.ts"); const SESSION_ID = "11111111-2222-4333-8444-555555555555"; diff --git a/lib/http-dispatcher.ts b/lib/http-dispatcher.ts deleted file mode 100644 index e525a6268..000000000 --- a/lib/http-dispatcher.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { EventEmitter } from "node:events"; -import * as undici from "undici"; - -export const DEFAULT_HTTP_IDLE_TIMEOUT_MS = 300_000; - -type DispatcherGlobal = typeof globalThis & { - __ompWebHttpDispatcherConfigured?: boolean; -}; - -const dispatcherGlobal = globalThis as DispatcherGlobal; -const originalGlobalFetch = globalThis.fetch; -const ignoreUndiciDispatcherError = (): void => {}; - -function parseHttpIdleTimeoutMs(value: unknown): number | undefined { - if (typeof value === "string") { - const trimmed = value.trim(); - if (trimmed.toLowerCase() === "disabled") return 0; - if (trimmed.length === 0) return undefined; - return parseHttpIdleTimeoutMs(Number(trimmed)); - } - - if (typeof value !== "number" || !Number.isFinite(value) || value < 0) { - return undefined; - } - return Math.floor(value); -} - -// Undici can emit an internal Client error while terminating a response body. -// The body stream still rejects; this prevents the EventEmitter error from -// terminating the Next.js process first. -function withUndiciErrorListener(dispatcher: T): T { - if (dispatcher instanceof EventEmitter) { - EventEmitter.prototype.on.call(dispatcher, "error", ignoreUndiciDispatcherError); - } - return dispatcher; -} - -function createUndiciClient(origin: string | URL, options: object): undici.Dispatcher { - return withUndiciErrorListener( - new undici.Client(origin, options as undici.Client.Options), - ); -} - -function createUndiciOriginDispatcher(origin: string | URL, options: object): undici.Dispatcher { - const dispatcherOptions = options as undici.Pool.Options; - if (dispatcherOptions.connections === 1) { - return createUndiciClient(origin, dispatcherOptions); - } - - return withUndiciErrorListener( - new undici.Pool(origin, { - ...dispatcherOptions, - factory: createUndiciClient, - }), - ); -} - -export function configureHttpDispatcher( - timeoutMs: number = DEFAULT_HTTP_IDLE_TIMEOUT_MS, -): void { - if (dispatcherGlobal.__ompWebHttpDispatcherConfigured) return; - - const normalizedTimeoutMs = parseHttpIdleTimeoutMs(timeoutMs); - if (normalizedTimeoutMs === undefined) { - throw new Error(`Invalid HTTP idle timeout: ${String(timeoutMs)}`); - } - - const dispatcher = withUndiciErrorListener( - new undici.EnvHttpProxyAgent({ - allowH2: false, - bodyTimeout: normalizedTimeoutMs, - headersTimeout: normalizedTimeoutMs, - clientFactory: createUndiciClient, - factory: createUndiciOriginDispatcher, - }), - ); - undici.setGlobalDispatcher(dispatcher); - - // Keep fetch and the dispatcher on the same undici implementation. Preserve - // an intentional fetch override installed after this module was loaded. - if (globalThis.fetch === originalGlobalFetch) { - undici.install?.(); - } - - dispatcherGlobal.__ompWebHttpDispatcherConfigured = true; -} diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 100ad63ad..bb10bca87 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -140,6 +140,7 @@ "settingsConfig.checkOmpUpdates": "Check OMP updates", "settingsConfig.refresh": "Refresh", "settingsConfig.runAppUpdateCommand": "Run this command in terminal to update ompweb:", + "settingsConfig.downloadAppUpdate": "Download the new release for this platform from this page, stop ompweb and ompweb host, and replace the ompweb folder with the new one:", "settingsConfig.appUpdateAction": "Update and restart", "appUpdateDialog.title": "ompweb update available", "appUpdateDialog.description": "A new version can be installed automatically.", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 9974090bf..7afd76408 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -137,6 +137,7 @@ "settingsConfig.checkOmpUpdates": "OMP の更新を確認", "settingsConfig.refresh": "更新", "settingsConfig.runAppUpdateCommand": "ターミナルで次のコマンドを実行して ompweb を更新してください:", + "settingsConfig.downloadAppUpdate": "このページからお使いのプラットフォーム向けの新しいリリースをダウンロードし、ompweb と ompweb host を停止してから、ompweb フォルダーを新しいものに置き換えてください:", "settingsConfig.appUpdateAction": "更新して再起動", "appUpdateDialog.title": "ompweb の更新があります", "appUpdateDialog.description": "新しいバージョンを自動でインストールできます。", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 0724a782b..ae44e7b38 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -137,6 +137,7 @@ "settingsConfig.checkOmpUpdates": "检查 OMP 更新", "settingsConfig.refresh": "刷新", "settingsConfig.runAppUpdateCommand": "请在终端运行以下命令更新 ompweb:", + "settingsConfig.downloadAppUpdate": "请从此页面下载适用于本平台的新版本,停止 ompweb 和 ompweb host,然后用新版本替换 ompweb 文件夹:", "settingsConfig.appUpdateAction": "更新并重启", "appUpdateDialog.title": "ompweb 有可用更新", "appUpdateDialog.description": "可以自动安装新版本。", diff --git a/lib/instrumentation-crash-policy.test.mjs b/lib/instrumentation-crash-policy.test.mjs index 39f566e7e..cf00ed172 100644 --- a/lib/instrumentation-crash-policy.test.mjs +++ b/lib/instrumentation-crash-policy.test.mjs @@ -16,21 +16,18 @@ const readOrEmpty = (file) => { } }; -// Runs instrumentation.node.ts's register() in a child, then throws `error` -// uncaught. Returns the exit status (0 = kept serving) plus the journals under -// the agent dir and under ~/.omp (the default, un-isolated location). -function throwAfterRegister(errorExpr, { agentDir = "agent" } = {}) { +// Runs instrumentation.node.ts's register() in a child, then `then`. Returns +// the exit status plus the journals under the agent dir and under ~/.omp (the +// default, un-isolated location). +function runAfterRegister(then, { agentDir = "agent" } = {}) { const home = mkdtempSync(join(tmpdir(), "omp-web-crash-policy-")); try { const script = ` - const { createJiti } = await import("jiti"); - const jiti = createJiti(${JSON.stringify(join(root, "lib/"))}, { tsconfigPaths: true }); - const { register } = await jiti.import(${JSON.stringify(join(root, "instrumentation.node.ts"))}); + const { register } = await import(${JSON.stringify(join(root, "instrumentation.node.ts"))}); await register(); - setTimeout(() => { throw ${errorExpr}; }, 0); - setTimeout(() => process.exit(0), 300); + ${then} `; - const result = spawnSync(process.execPath, ["--input-type=module", "-e", script], { + const result = spawnSync(process.execPath, ["-e", script], { cwd: root, env: { ...process.env, @@ -53,6 +50,26 @@ function throwAfterRegister(errorExpr, { agentDir = "agent" } = {}) { } } +// Throws `error` uncaught after register(); status 0 = kept serving. +const throwAfterRegister = (errorExpr, options) => runAfterRegister(` + setTimeout(() => { throw ${errorExpr}; }, 0); + setTimeout(() => process.exit(0), 300); +`, options); + +// Windows has no signals: process.kill(pid, "SIGINT") terminates the process outright (status 1), so no handler runs. +test("SIGINT and SIGTERM end the server even though modules listen for them", { skip: process.platform === "win32" && "Windows kills on SIGINT/SIGTERM without running handlers" }, () => { + for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143]]) { + // The first listener stands in for a module's cleanup (lib/rpc-manager.ts), + // which on its own cancels the default exit. + const { status, stderr } = runAfterRegister(` + process.once("${signal}", () => {}); + process.kill(process.pid, "${signal}"); + setTimeout(() => process.exit(0), 2000); + `); + assert.equal(status, code, `${signal}\n${stderr}`); + } +}); + test("a client disconnect surfacing as uncaught `aborted` is journaled without exiting", () => { const { status, journal, stderr } = throwAfterRegister(`Object.assign(new Error("aborted"), { code: "ECONNRESET" })`); assert.equal(status, 0, stderr); diff --git a/lib/manifest-route.test.mjs b/lib/manifest-route.test.mjs new file mode 100644 index 000000000..481ebd042 --- /dev/null +++ b/lib/manifest-route.test.mjs @@ -0,0 +1,24 @@ +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +test("the manifest icons come from the package dir, not the working directory", async (t) => { + const packageDir = mkdtempSync(path.join(tmpdir(), "omp-web-manifest-")); + const previous = process.env.OMP_WEB_PACKAGE_DIR; + t.after(() => { + if (previous === undefined) delete process.env.OMP_WEB_PACKAGE_DIR; + else process.env.OMP_WEB_PACKAGE_DIR = previous; + rmSync(packageDir, { recursive: true, force: true }); + }); + mkdirSync(path.join(packageDir, "public")); + writeFileSync(path.join(packageDir, "public", "icon-192.png"), "small"); + writeFileSync(path.join(packageDir, "public", "icon.png"), "large"); + // The launcher sets OMP_WEB_PACKAGE_DIR; the server's working directory is wherever ompweb was started. + process.env.OMP_WEB_PACKAGE_DIR = packageDir; + // The route reads the icons when it loads, so it is imported after the variable is set. + const { GET } = await import("../app/api/manifest/route.ts"); + const { icons } = await GET(new Request("http://localhost/api/manifest")).json(); + assert.deepEqual(icons.map((icon) => atob(icon.src.slice("data:image/png;base64,".length))), ["small", "large"]); +}); diff --git a/lib/markdown-katex-css.test.mjs b/lib/markdown-katex-css.test.mjs new file mode 100644 index 000000000..8d42a505e --- /dev/null +++ b/lib/markdown-katex-css.test.mjs @@ -0,0 +1,41 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test, { afterEach } from "node:test"; + +let freshImport = 0; +const loadFresh = async () => (await import(`./markdown.ts?fresh=${freshImport++}`)).loadMathMarkdownPlugins; +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +async function katexLink() { + for (let attempt = 0; attempt < 200; attempt++) { + const link = document.querySelector("link[data-katex]"); + if (link) return link; + await sleep(10); + } + throw new Error("the KaTeX stylesheet link was never appended"); +} + +afterEach(() => { + document.head.replaceChildren(); +}); + +for (const event of ["load", "error"]) { + test(`math plugins wait for the KaTeX stylesheet to ${event} and link it once`, async () => { + const loadMathMarkdownPlugins = await loadFresh(); + let settled = false; + const first = loadMathMarkdownPlugins().then((plugins) => { + settled = true; + return plugins; + }); + const link = await katexLink(); + assert.equal(link.getAttribute("href"), "/katex/katex.min.css"); + await sleep(20); + assert.equal(settled, false); + + link.dispatchEvent(new window.Event(event)); + const plugins = await first; + + assert.equal(await loadMathMarkdownPlugins(), plugins); + assert.equal(document.querySelectorAll("link[data-katex]").length, 1); + }); +} diff --git a/lib/markdown.ts b/lib/markdown.ts index b9b39497c..b3492e754 100644 --- a/lib/markdown.ts +++ b/lib/markdown.ts @@ -59,7 +59,23 @@ function getRawCodeClosePattern(tag: string): RegExp { return RAW_CODE_CLOSE_PATTERNS[tag] ?? new RegExp(``, "i"); } -/** Loads remark-math + rehype-katex + the KaTeX CSS once, caching module-level. */ +let katexCssPromise: Promise | undefined; + +/** Links the KaTeX CSS (served at /katex/, kept out of the entry chunk) once; settles on load or error so a failed fetch never blocks rendering. */ +function loadKatexCss(): Promise { + katexCssPromise ??= new Promise((resolve) => { + const link = document.createElement("link"); + link.rel = "stylesheet"; + link.href = "/katex/katex.min.css"; + link.dataset.katex = ""; + link.addEventListener("load", () => resolve()); + link.addEventListener("error", () => resolve()); + document.head.append(link); + }); + return katexCssPromise; +} + +/** Loads remark-math + rehype-katex once (module-level cache) and waits for the KaTeX CSS in the browser. */ export function loadMathMarkdownPlugins(): Promise { if (!mathMarkdownPluginsPromise) { mathMarkdownPluginsPromise = (async () => { @@ -67,10 +83,7 @@ export function loadMathMarkdownPlugins(): Promise { import("remark-math").then((m) => m.default), import("rehype-katex").then((m) => m.default), ]); - if (typeof window !== "undefined") { - // KaTeX styles are only needed (and only loadable) in the browser. - await import("katex/dist/katex.min.css"); - } + if (typeof document !== "undefined") await loadKatexCss(); mathMarkdownPlugins = { remarkPlugins: [...baseMarkdownPlugins.remarkPlugins, remarkMath], rehypePlugins: [ diff --git a/lib/media-cache.ts b/lib/media-cache.ts index 81bd864e9..72a041d34 100644 --- a/lib/media-cache.ts +++ b/lib/media-cache.ts @@ -31,7 +31,7 @@ function fileSize(file: string): number | undefined { return statSync(file, { throwIfNoEntry: false })?.size; } -function writeAtomic(file: string, data: Buffer): void { +function writeAtomic(file: string, data: Uint8Array): void { sweepMediaCache(); mkdirSync(path.dirname(file), { recursive: true }); const tmp = `${file}.${randomUUID()}.tmp`; @@ -100,7 +100,7 @@ export function storeInlineImage(base64: string): string { /** Keep a copy of an image another host sent, so later requests are served locally. */ export function storeMediaCopy(hash: string, bytes: Uint8Array): void { - if (HASH_RE.test(hash)) writeAtomic(path.join(mediaDir(), hash), Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)); + if (HASH_RE.test(hash)) writeAtomic(path.join(mediaDir(), hash), bytes); } function imageBlockAsUrl(block: unknown): unknown { @@ -205,19 +205,11 @@ export function existingThumbnail(hash: string): string | null { return HASH_RE.test(hash) && existsSync(thumb) ? thumb : null; } -/** Generate and cache a small WebP preview; null when sharp is unavailable or fails. */ -export async function createThumbnail(hash: string, image: Buffer): Promise { - let thumb: Buffer; +/** Generate and cache a small WebP preview (Bun.Image applies EXIF orientation); null when the bytes are not a decodable image. */ +export async function createThumbnail(hash: string, image: Buffer): Promise { + let thumb: Uint8Array; try { - // Dynamic on purpose: sharp's native binary is platform-specific and may be - // missing, and this module is also loaded by the session reader and RPC - // manager, which must not fail or load libvips just to rewrite URLs. - const { default: sharp } = await import("sharp"); - thumb = await sharp(image) - .rotate() // apply EXIF orientation; WebP output drops the tag - .resize(THUMB_PX, THUMB_PX, { fit: "inside", withoutEnlargement: true }) - .webp({ quality: 80 }) - .toBuffer(); + thumb = await new Bun.Image(image).resize(THUMB_PX, THUMB_PX, { fit: "inside", withoutEnlargement: true }).webp({ quality: 80 }).bytes(); } catch { return null; } diff --git a/lib/media-route.test.mjs b/lib/media-route.test.mjs index 32958a5f6..5323be41d 100644 --- a/lib/media-route.test.mjs +++ b/lib/media-route.test.mjs @@ -4,9 +4,6 @@ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node: import { tmpdir } from "node:os"; import { join } from "node:path"; import test, { after } from "node:test"; -import { fileURLToPath } from "node:url"; -import { createJiti } from "jiti"; -import sharp from "sharp"; // Real GET /api/media/[hash] against a throwaway agent dir. const agentDir = mkdtempSync(join(tmpdir(), "omp-web-media-route-")); @@ -18,12 +15,8 @@ after(() => { rmSync(agentDir, { recursive: true, force: true }); }); -const jiti = createJiti(import.meta.url, { - tryNative: false, - alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, -}); -const route = await jiti.import("../app/api/media/[hash]/route.ts"); -const { eventWithToolResultImageUrls } = await jiti.import("./media-cache.ts"); +const route = await import("../app/api/media/[hash]/route.ts"); +const { eventWithToolResultImageUrls } = await import("./media-cache.ts"); const blobs = join(agentDir, "blobs"); const media = join(agentDir, "omp-web", "media"); @@ -31,7 +24,15 @@ mkdirSync(blobs, { recursive: true }); const sha = (bytes) => createHash("sha256").update(bytes).digest("hex"); const get = (hash, query = "") => route.GET(new Request(`http://localhost/api/media/${hash}${query}`), { params: Promise.resolve({ hash }) }); -const screenshot = await sharp({ create: { width: 1600, height: 1000, channels: 3, background: "#336699" } }).png().toBuffer(); +// public/icon-192.png scaled to any size: a real PNG without a native image dependency. +const sourceIcon = await Bun.file("public/icon-192.png").bytes(); +const png = async (width, height) => Buffer.from(await new Bun.Image(sourceIcon).resize(width, height, { fit: "fill" }).png().bytes()); +const dimensions = async (bytes) => { + const { width, height } = await new Bun.Image(bytes).metadata(); + return [width, height]; +}; + +const screenshot = await png(1600, 1000); const screenshotHash = sha(screenshot); writeFileSync(join(blobs, screenshotHash), screenshot); @@ -44,27 +45,45 @@ test("serves the full image with its real type, and a small cached WebP preview" const thumb = await get(screenshotHash, "?thumb=1"); assert.equal(thumb.headers.get("content-type"), "image/webp"); const bytes = Buffer.from(await thumb.arrayBuffer()); - const { width, height } = await sharp(bytes).metadata(); - assert.deepEqual([width, height], [480, 300]); + assert.equal(bytes.subarray(0, 4).toString("latin1"), "RIFF"); + assert.deepEqual(await dimensions(bytes), [480, 300]); assert.ok(bytes.length < screenshot.length); assert.ok(existsSync(join(media, `${screenshotHash}.thumb.webp`)), "preview is generated once and kept"); }); +/** `jpeg` with an EXIF APP1 segment (big-endian TIFF, one Orientation entry) right after SOI. */ +function withExifOrientation(jpeg, orientation) { + const tiff = Buffer.from([0x4d, 0x4d, 0, 0x2a, 0, 0, 0, 8, 0, 1, 0x01, 0x12, 0, 3, 0, 0, 0, 1, 0, orientation, 0, 0, 0, 0, 0, 0]); + const body = Buffer.concat([Buffer.from("Exif\0\0", "latin1"), tiff]); + const header = Buffer.from([0xff, 0xe1, (body.length + 2) >> 8, (body.length + 2) & 0xff]); + return Buffer.concat([jpeg.subarray(0, 2), header, body, jpeg.subarray(2)]); +} + +test("previews are never enlarged and keep the aspect ratio", async () => { + const wide = await png(800, 400); + writeFileSync(join(blobs, sha(wide)), wide); + assert.deepEqual(await dimensions(Buffer.from(await (await get(sha(wide), "?thumb=1")).arrayBuffer())), [480, 240]); +}); + test("previews are reused and follow EXIF orientation", async () => { // Cached: served even after the source is gone. - const portrait = await sharp({ create: { width: 800, height: 400, channels: 3, background: "#123456" } }) - .jpeg().withMetadata({ orientation: 6 }).toBuffer(); + const plain = Buffer.from(await new Bun.Image(sourceIcon).resize(40, 20, { fit: "fill" }).jpeg().bytes()); + const portrait = withExifOrientation(plain, 6); const hash = sha(portrait); writeFileSync(join(blobs, hash), portrait); const first = Buffer.from(await (await get(hash, "?thumb=1")).arrayBuffer()); - const { width, height } = await sharp(first).metadata(); - assert.deepEqual([width, height], [240, 480], "a phone photo stays upright in the preview"); + assert.deepEqual(await dimensions(first), [20, 40], "a phone photo stays upright in the preview"); rmSync(join(blobs, hash)); const again = await get(hash, "?thumb=1"); assert.equal(again.status, 200); assert.deepEqual(Buffer.from(await again.arrayBuffer()), first); }); +test("a source that is not an image gets no preview", async () => { + const { createThumbnail } = await import("./media-cache.ts"); + assert.equal(await createThumbnail(sha(Buffer.from("x")), Buffer.from("not an image")), null); +}); + test("never serves non-images or files outside the store", async () => { const text = Buffer.from("data:text/html,"); writeFileSync(join(blobs, sha(text)), text); @@ -78,7 +97,7 @@ test("never serves non-images or files outside the store", async () => { }); test("live tool output is served from omp-web's copy until omp has written the whole blob", async () => { - const live = await sharp({ create: { width: 64, height: 64, channels: 3, background: "#ff0000" } }).png().toBuffer(); + const live = await png(64, 64); const hash = sha(live); const event = { type: "tool_execution_end", @@ -103,7 +122,7 @@ test("live tool output is served from omp-web's copy until omp has written the w }); test("a live image arriving while omp is still writing its blob is kept and served whole", async () => { - const live = await sharp({ create: { width: 48, height: 48, channels: 3, background: "#00ff00" } }).png().toBuffer(); + const live = await png(48, 48); const hash = sha(live); writeFileSync(join(blobs, hash), live.subarray(0, 30)); eventWithToolResultImageUrls({ type: "tool_execution_end", result: { content: [{ type: "image", data: live.toString("base64") }] } }); @@ -111,7 +130,7 @@ test("a live image arriving while omp is still writing its blob is kept and serv }); test("an image seen again after its copy was swept is stored again", async () => { - const live = await sharp({ create: { width: 40, height: 40, channels: 3, background: "#0000ff" } }).png().toBuffer(); + const live = await png(40, 40); const hash = sha(live); const frame = () => eventWithToolResultImageUrls({ type: "tool_execution_end", result: { content: [{ type: "image", data: live.toString("base64") }] } }); frame(); diff --git a/lib/message-overflow.test.mjs b/lib/message-overflow.test.mjs index 2e60d2b72..6a193b94c 100644 --- a/lib/message-overflow.test.mjs +++ b/lib/message-overflow.test.mjs @@ -1,9 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); -const { isMessageOverflowing } = await jiti.import("./message-overflow.ts"); +const { isMessageOverflowing } = await import("./message-overflow.ts"); test("does not mark a message as overflowing at the capped height", () => { assert.equal(isMessageOverflowing({ scrollHeight: 300, clientHeight: 300 }), false); diff --git a/lib/model-catalog.test.mjs b/lib/model-catalog.test.mjs index 44cc5f6ee..c91a2e002 100644 --- a/lib/model-catalog.test.mjs +++ b/lib/model-catalog.test.mjs @@ -1,10 +1,8 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); async function loadSubject() { - return jiti.import("./model-catalog.ts"); + return import("./model-catalog.ts"); } // Minimal models.dev/api.json-shaped fixture. diff --git a/lib/navigation.test.mjs b/lib/navigation.test.mjs new file mode 100644 index 000000000..abab77a76 --- /dev/null +++ b/lib/navigation.test.mjs @@ -0,0 +1,30 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test, { afterEach } from "node:test"; +const { act, cleanup, renderHook } = await import("@testing-library/react/pure.js"); + +const { useRouter, useSearchParams } = await import("./navigation.ts"); + +const renderNav = () => renderHook(() => ({ router: useRouter(), params: useSearchParams() })); + +afterEach(() => { + cleanup(); + window.history.replaceState(null, "", "/"); +}); + +test("replace updates the search params without adding a history entry", () => { + const { result } = renderNav(); + const length = window.history.length; + act(() => result.current.router.replace("/?session=b")); + assert.equal(result.current.params.get("session"), "b"); + assert.equal(window.history.length, length); +}); + +test("popstate re-renders with the new search", () => { + const { result } = renderNav(); + window.history.replaceState(null, "", "/?session=d"); + act(() => { + window.dispatchEvent(new window.Event("popstate")); + }); + assert.equal(result.current.params.get("session"), "d"); +}); diff --git a/lib/navigation.ts b/lib/navigation.ts new file mode 100644 index 000000000..4d32b65bb --- /dev/null +++ b/lib/navigation.ts @@ -0,0 +1,28 @@ +// useRouter and useSearchParams (the two hooks AppShell uses), over the History API. +import { useMemo, useSyncExternalStore } from "react"; + +const EVENT = "omp:navigate"; +const subscribe = (notify: () => void) => { + window.addEventListener("popstate", notify); + window.addEventListener(EVENT, notify); + return () => { + window.removeEventListener("popstate", notify); + window.removeEventListener(EVENT, notify); + }; +}; + +export function useSearchParams(): URLSearchParams { + const search = useSyncExternalStore(subscribe, () => window.location.search); + return useMemo(() => new URLSearchParams(search), [search]); +} + +const router = { + replace: (url: string) => { + window.history.replaceState(window.history.state, "", url); + window.dispatchEvent(new Event(EVENT)); + }, +}; + +export function useRouter() { + return router; +} diff --git a/lib/notification-events.test.mjs b/lib/notification-events.test.mjs index 440480bc6..1fbd8fcf8 100644 --- a/lib/notification-events.test.mjs +++ b/lib/notification-events.test.mjs @@ -1,9 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); -const { createNotificationDetector, parseNotificationPrefs, renderNotification } = await jiti.import("./notification-events.ts"); +const { createNotificationDetector, parseNotificationPrefs, renderNotification } = await import("./notification-events.ts"); const session = { sessionId: "s1", sessionName: "Refactor auth" }; diff --git a/lib/notification-history-route.test.mjs b/lib/notification-history-route.test.mjs index 23e3c7f94..624e7f1ff 100644 --- a/lib/notification-history-route.test.mjs +++ b/lib/notification-history-route.test.mjs @@ -3,27 +3,20 @@ import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test, { after, beforeEach } from "node:test"; -import { fileURLToPath } from "node:url"; -import { createJiti } from "jiti"; // Real /api/notifications/history against a throwaway agent dir. const agentDir = mkdtempSync(join(tmpdir(), "omp-web-history-route-")); const previousAgentDir = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = agentDir; after(() => { - globalThis.__ompNotificationStore?.db.close(); - globalThis.__ompNotificationStore = undefined; + store.closeNotificationStore(); if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; else process.env.PI_CODING_AGENT_DIR = previousAgentDir; rmSync(agentDir, { recursive: true, force: true }); }); -const jiti = createJiti(import.meta.url, { - tryNative: false, - alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, -}); -const route = await jiti.import("../app/api/notifications/history/route.ts"); -const store = await jiti.import("./notification-store.ts"); +const route = await import("../app/api/notifications/history/route.ts"); +const store = await import("./notification-store.ts"); const URL_ = "http://localhost/api/notifications/history"; const patch = (body) => route.PATCH(new Request(URL_, { method: "PATCH", headers: { "content-type": "application/json" }, body: typeof body === "string" ? body : JSON.stringify(body) })); diff --git a/lib/notification-history.test.mjs b/lib/notification-history.test.mjs index 37eb29e1f..b1aef7474 100644 --- a/lib/notification-history.test.mjs +++ b/lib/notification-history.test.mjs @@ -1,9 +1,7 @@ import assert from "node:assert/strict"; import test, { beforeEach } from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); -const { notificationHistory } = await jiti.import("./notification-history.ts"); +const { notificationHistory } = await import("./notification-history.ts"); const event = (sessionId, type = "completed") => ({ type, sessionId, sessionName: sessionId }); const entry = (sessionId, read = false) => ({ id: `${sessionId}:completed`, event: event(sessionId), at: 1, read }); diff --git a/lib/notification-hub.test.mjs b/lib/notification-hub.test.mjs index 98e654eff..850771a4b 100644 --- a/lib/notification-hub.test.mjs +++ b/lib/notification-hub.test.mjs @@ -2,15 +2,13 @@ import assert from "node:assert/strict"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { DatabaseSync } from "node:sqlite"; +import { Database } from "bun:sqlite"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); -const hub = await jiti.import("./notification-hub.ts"); -const { DEFAULT_NOTIFICATION_PREFS } = await jiti.import("./notification-events.ts"); -const store = await jiti.import("./notification-store.ts"); -const webpush = (await jiti.import("web-push")).default; +const hub = await import("./notification-hub.ts"); +const { DEFAULT_NOTIFICATION_PREFS } = await import("./notification-events.ts"); +const store = await import("./notification-store.ts"); +const webpush = (await import("web-push")).default; const event = { type: "completed", sessionId: "s1", sessionName: "Session" }; const prefs = (patch = {}) => ({ ...DEFAULT_NOTIFICATION_PREFS, enabled: true, ...patch }); @@ -73,10 +71,7 @@ test("push subscriptions must use an HTTPS endpoint and real key sizes", () => { assert.deepEqual(store.parsePushSubscription(subscription), subscription); }); -function reopenStore() { - globalThis.__ompNotificationStore?.db.close(); - globalThis.__ompNotificationStore = undefined; -} +const reopenStore = store.closeNotificationStore; function isolatedStore(t) { const dir = mkdtempSync(join(tmpdir(), "omp-notify-")); @@ -155,7 +150,7 @@ test("test notifications are never recorded", (t) => { test("a failed history write does not stop delivery", (t) => { const dir = isolatedStore(t); store.saveDevice("desk-0001", prefs({ whenActive: "system" })); - const raw = new DatabaseSync(join(dir, "omp-web", "notifications.db")); + const raw = new Database(join(dir, "omp-web", "notifications.db")); raw.exec("DROP TABLE history"); raw.close(); const received = []; diff --git a/lib/notification-store.test.mjs b/lib/notification-store.test.mjs index 4222495df..1b40f513d 100644 --- a/lib/notification-store.test.mjs +++ b/lib/notification-store.test.mjs @@ -1,31 +1,35 @@ import assert from "node:assert/strict"; import { execFile } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readlinkSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; import test from "node:test"; import { promisify } from "node:util"; -import { createJiti } from "jiti"; const run = promisify(execFile); -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); -const store = await jiti.import("./notification-store.ts"); -const { DEFAULT_NOTIFICATION_PREFS } = await jiti.import("./notification-events.ts"); +const store = await import("./notification-store.ts"); +const { DEFAULT_NOTIFICATION_PREFS } = await import("./notification-events.ts"); const prefs = (patch = {}) => ({ ...DEFAULT_NOTIFICATION_PREFS, enabled: true, ...patch }); const subscription = (id = "abc") => ({ endpoint: `https://push.example/${id}`, keys: { p256dh: `B${"A".repeat(86)}`, auth: "A".repeat(22) } }); const event = (sessionId, type = "completed") => ({ type, sessionId, sessionName: `Session ${sessionId}` }); const keys = { publicKey: "pub", privateKey: "priv" }; +// Descriptors this process holds on `file` or its -wal/-shm (Linux): Windows cannot remove a file that stays open. +const openHandles = (file) => readdirSync("/proc/self/fd").filter((fd) => { + try { + return readlinkSync(join("/proc/self/fd", fd)).startsWith(file); + } catch { + return false; + } +}).length; /** A fresh agent dir; `reopen()` drops the cached handle, as a restart or a second omp-web instance would. */ function isolated(t) { const dir = mkdtempSync(join(tmpdir(), "omp-notify-store-")); const previous = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = dir; - const reopen = () => { - globalThis.__ompNotificationStore?.db.close(); - globalThis.__ompNotificationStore = undefined; - }; + const reopen = store.closeNotificationStore; reopen(); t.after(() => { reopen(); @@ -52,6 +56,35 @@ test("the database is owner-only", (t) => { if (process.platform !== "win32") assert.equal(statSync(join(dir, "omp-web", "notifications.db")).mode & 0o077, 0); }); +test("the database and its WAL file are owner-only", (t) => { + const { dir } = isolated(t); + store.getVapidKeys(() => keys); + if (process.platform === "win32") return; + for (const name of ["notifications.db", "notifications.db-wal"]) assert.equal(statSync(join(dir, "omp-web", name)).mode & 0o777, 0o600, name); +}); + +test("a store file written by node:sqlite opens with the same VAPID keys and device", (t) => { + const { dir } = isolated(t); + mkdirSync(join(dir, "omp-web"), { recursive: true }); + const legacy = new DatabaseSync(join(dir, "omp-web", "notifications.db")); + legacy.exec("PRAGMA journal_mode = WAL"); + legacy.exec(` + CREATE TABLE vapid (id INTEGER PRIMARY KEY CHECK (id = 1), public_key TEXT NOT NULL, private_key TEXT NOT NULL); + CREATE TABLE devices (device_id TEXT PRIMARY KEY, prefs TEXT NOT NULL, subscription TEXT, updated_at INTEGER NOT NULL); + CREATE TABLE history (id TEXT PRIMARY KEY, event TEXT NOT NULL, at INTEGER NOT NULL, read INTEGER NOT NULL DEFAULT 0); + `); + legacy.prepare("INSERT INTO vapid (id, public_key, private_key) VALUES (1, ?, ?)").run(keys.publicKey, keys.privateKey); + legacy.prepare("INSERT INTO devices (device_id, prefs, subscription, updated_at) VALUES (?, ?, ?, ?)") + .run("phone-0001", JSON.stringify(prefs({ locale: "ja" })), JSON.stringify(subscription()), 7); + legacy.close(); + + assert.deepEqual(store.getVapidKeys(() => assert.fail("keys exist")), keys); + const device = store.getDevice("phone-0001"); + assert.equal(device.prefs.locale, "ja"); + assert.deepEqual(device.subscription, subscription()); + assert.equal(device.updatedAt, 7); +}); + test("saving a device without a subscription keeps the stored one", (t) => { isolated(t); store.saveDevice("phone-0001", prefs(), subscription()); @@ -99,6 +132,21 @@ test("changing PI_CODING_AGENT_DIR moves the cached handle to the new location a assert.equal(store.getDevice("desk-0001").deviceId, "desk-0001"); }); +test("a store it moved away from or closed no longer holds its database file open", { skip: !existsSync("/proc/self/fd") && "needs /proc/self/fd" }, (t) => { + const { dir: first } = isolated(t); + const firstFile = join(first, "omp-web", "notifications.db"); + store.saveDevice("desk-0001", prefs()); + store.recordHistory(event("s1")); + assert.ok(openHandles(firstFile) > 0); + const second = mkdtempSync(join(tmpdir(), "omp-notify-store-")); + t.after(() => rmSync(second, { recursive: true, force: true })); + process.env.PI_CODING_AGENT_DIR = second; + store.listDevices(); + assert.equal(openHandles(firstFile), 0); + store.closeNotificationStore(); + assert.equal(openHandles(join(second, "omp-web", "notifications.db")), 0); +}); + test("a location that cannot be opened does not break the store once it is valid again", (t) => { const { dir: good } = isolated(t); store.saveDevice("desk-0001", prefs()); @@ -192,8 +240,7 @@ test("a corrupt notifications.json stays in place and the store starts empty", ( // An installed omp-web and `npm run dev` can open a fresh agent dir at the same moment. test("processes racing to open a fresh store all succeed and share one key pair", async () => { - const opener = `const { createJiti } = await import("jiti"); - const store = await createJiti(${JSON.stringify(import.meta.url)}, { tsconfigPaths: true }).import("./notification-store.ts"); + const opener = `const store = await import(${JSON.stringify(new URL("./notification-store.ts", import.meta.url).href)}); const at = Number(process.argv[1]); while (Date.now() < at); process.stdout.write(store.getVapidKeys(() => ({ publicKey: "pub-" + process.pid, privateKey: "x" })).publicKey);`; @@ -202,7 +249,7 @@ test("processes racing to open a fresh store all succeed and share one key pair" try { const at = String(Date.now() + 1500); const results = await Promise.allSettled(Array.from({ length: 8 }, () => - run(process.execPath, ["--input-type=module", "-e", opener, at], { env: { ...process.env, PI_CODING_AGENT_DIR: dir } }))); + run(process.execPath, ["-e", opener, at], { env: { ...process.env, PI_CODING_AGENT_DIR: dir } }))); for (const result of results) assert.equal(result.status, "fulfilled", `round ${round}: ${result.reason?.stderr ?? ""}`); assert.equal(new Set(results.map((result) => result.value.stdout)).size, 1, `round ${round}: one key pair`); } finally { diff --git a/lib/notification-store.ts b/lib/notification-store.ts index 161853517..66828425b 100644 --- a/lib/notification-store.ts +++ b/lib/notification-store.ts @@ -1,6 +1,6 @@ import { chmodSync, closeSync, mkdirSync, openSync, readFileSync, rmSync } from "fs"; import { join } from "path"; -import { DatabaseSync } from "node:sqlite"; +import { Database } from "bun:sqlite"; import type { PushSubscription } from "web-push"; import { getAgentDir } from "./omp/paths"; import { @@ -54,7 +54,7 @@ export function parsePushSubscription(value: unknown): PushSubscription | null { } declare global { - var __ompNotificationStore: { path: string; db: DatabaseSync } | undefined; + var __ompNotificationStore: { path: string; db: Database } | undefined; } const SCHEMA = ` @@ -63,7 +63,7 @@ CREATE TABLE IF NOT EXISTS devices (device_id TEXT PRIMARY KEY, prefs TEXT NOT N CREATE TABLE IF NOT EXISTS history (id TEXT PRIMARY KEY, event TEXT NOT NULL, at INTEGER NOT NULL, read INTEGER NOT NULL DEFAULT 0); `; -function transaction(db: DatabaseSync, run: () => T): T { +function transaction(db: Database, run: () => T): T { db.exec("BEGIN IMMEDIATE"); try { const result = run(); @@ -71,7 +71,7 @@ function transaction(db: DatabaseSync, run: () => T): T { return result; } catch (error) { // SQLite has already rolled back after some errors (a full disk, an I/O error); the original error is what matters. - if (db.isTransaction) db.exec("ROLLBACK"); + if (db.inTransaction) db.exec("ROLLBACK"); throw error; } } @@ -86,7 +86,7 @@ const parseJson = (text: unknown): unknown => { }; /** Imports the pre-SQLite notifications.json once, into an empty store. Runs inside the schema transaction. */ -function importLegacy(db: DatabaseSync, file: string): boolean { +function importLegacy(db: Database, file: string): boolean { let text: string; try { text = readFileSync(file, "utf8"); @@ -114,24 +114,30 @@ function importLegacy(db: DatabaseSync, file: string): boolean { } /** The store for the current agent directory; reopened when PI_CODING_AGENT_DIR changes. */ -function db(): DatabaseSync { +function db(): Database { const dir = join(getAgentDir(), "omp-web"); const path = join(dir, "notifications.db"); const cached = globalThis.__ompNotificationStore; if (cached?.path === path) return cached.db; const database = open(dir, path); // Only a working store replaces the cached one; a failed open leaves it usable. - cached?.db.close(); + closeNotificationStore(); globalThis.__ompNotificationStore = { path, db: database }; return database; } -function open(dir: string, path: string): DatabaseSync { +/** Closes the cached store. `close(true)` finalizes the statements still alive: without it the file stays open until GC, and Windows keeps it locked. */ +export function closeNotificationStore(): void { + globalThis.__ompNotificationStore?.db.close(true); + globalThis.__ompNotificationStore = undefined; +} + +function open(dir: string, path: string): Database { mkdirSync(dir, { recursive: true }); // Owner-only before SQLite opens it: it holds the VAPID private key. SQLite gives its -wal/-shm files the same mode. closeSync(openSync(path, "a", 0o600)); chmodSync(path, 0o600); - const database = new DatabaseSync(path); + const database = new Database(path); try { database.exec("PRAGMA busy_timeout = 5000"); // Switching a new database to WAL takes an exclusive lock that ignores busy_timeout; another omp-web may hold it. @@ -140,7 +146,7 @@ function open(dir: string, path: string): DatabaseSync { database.exec("PRAGMA journal_mode = WAL"); break; } catch (error) { - if (!isRecord(error) || error.errcode !== 5 || attempt >= 250) throw error; + if (!isRecord(error) || error.errno !== 5 || attempt >= 250) throw error; Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20); } } @@ -158,7 +164,7 @@ function open(dir: string, path: string): DatabaseSync { } return database; } catch (error) { - database.close(); + database.close(true); throw error; } } @@ -168,7 +174,7 @@ function open(dir: string, path: string): DatabaseSync { /** The installation's VAPID key pair, generated on first use. */ export function getVapidKeys(generate: () => VapidKeys): VapidKeys { const database = db(); - const read = () => database.prepare("SELECT public_key, private_key FROM vapid WHERE id = 1").get() as { public_key: string; private_key: string } | undefined; + const read = () => database.prepare("SELECT public_key, private_key FROM vapid WHERE id = 1").get() as { public_key: string; private_key: string } | null; const row = read() ?? transaction(database, () => { // Re-read under the write lock: another instance may have generated them meanwhile. if (!read()) { @@ -196,8 +202,8 @@ export function listDevices(): NotificationDevice[] { } export function getDevice(deviceId: string): NotificationDevice | undefined { - const row = db().prepare("SELECT device_id, prefs, subscription, updated_at FROM devices WHERE device_id = ?").get(deviceId) as DeviceRow | undefined; - return row && toDevice(row); + const row = db().prepare("SELECT device_id, prefs, subscription, updated_at FROM devices WHERE device_id = ?").get(deviceId) as DeviceRow | null; + return row ? toDevice(row) : undefined; } /** Store a device's prefs, and its push subscription when given (otherwise the stored one is kept). */ diff --git a/lib/npm-update.test.mjs b/lib/npm-update.test.mjs index ba27ed607..eab46098d 100644 --- a/lib/npm-update.test.mjs +++ b/lib/npm-update.test.mjs @@ -1,9 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { isNewerVersion, detectInstallMethod } = jiti("./npm-update.ts"); +const { isNewerVersion, detectInstallMethod } = await import("./npm-update.ts"); test("recognizes newer npm package versions", () => { assert.equal(isNewerVersion("0.2.1", "0.2.0"), true); diff --git a/lib/npm-update.ts b/lib/npm-update.ts index 5e6ad303e..b2221cadd 100644 --- a/lib/npm-update.ts +++ b/lib/npm-update.ts @@ -4,12 +4,16 @@ import { homedir } from "os"; import { join, normalize, sep } from "path"; const NPM_PACKAGE = "@kahme247/ompweb"; +const RELEASES_URL = "https://github.com/kahme247/ompweb/releases/latest"; const CHECK_TTL_MS = 60 * 60 * 1000; export interface NpmUpdateStatus { currentVersion: string; availableVersion: string | null; updateAvailable: boolean; + /** "binary": the compiled release (scripts/build-binary.ts), which updates by download, not by a package manager. */ + installMethod: "npm" | "bun" | "binary"; + /** The terminal command that updates this install; for "binary", the release download page. */ updateCommand: string; updatesDisabled?: boolean; } @@ -38,11 +42,11 @@ export function isNewerVersion(availableVersion: string, currentVersion: string) export async function checkNpmUpdate(force = false): Promise { const currentVersion = packageJson.version; const packageDir = process.env.OMP_WEB_PACKAGE_DIR ?? process.cwd(); - const method = detectInstallMethod(packageDir); - const updateCommand = method === "bun" ? "bun add -g @kahme247/ompweb" : "npm install -g @kahme247/ompweb"; + const installMethod = Bun.isStandaloneExecutable ? "binary" : detectInstallMethod(packageDir); + const updateCommand = installMethod === "binary" ? RELEASES_URL : installMethod === "bun" ? "bun add -g @kahme247/ompweb" : "npm install -g @kahme247/ompweb"; if (isUpdateDisabled()) { - return { currentVersion, availableVersion: null, updateAvailable: false, updateCommand, updatesDisabled: true }; + return { currentVersion, availableVersion: null, updateAvailable: false, installMethod, updateCommand, updatesDisabled: true }; } if (!force && cached && Date.now() - cached.checkedAt < CHECK_TTL_MS) return cached.status; @@ -57,12 +61,13 @@ export async function checkNpmUpdate(force = false): Promise { currentVersion, availableVersion, updateAvailable: Boolean(availableVersion && isNewerVersion(availableVersion, currentVersion)), + installMethod, updateCommand, }; cached = { checkedAt: Date.now(), status }; return status; } catch { - return { currentVersion, availableVersion: null, updateAvailable: false, updateCommand }; + return { currentVersion, availableVersion: null, updateAvailable: false, installMethod, updateCommand }; } } diff --git a/lib/omp-web-options.test.mjs b/lib/omp-web-options.test.mjs index 077fe32bb..454a4785c 100644 --- a/lib/omp-web-options.test.mjs +++ b/lib/omp-web-options.test.mjs @@ -1,6 +1,8 @@ import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; import { createRequire } from "node:module"; import test from "node:test"; +import { fileURLToPath } from "node:url"; const require = createRequire(import.meta.url); const { parseLaunchOptions } = require("../bin/omp-web-options.js"); @@ -35,6 +37,21 @@ test("preserves port and hostname options", () => { assert.equal(parsed.openBrowser, true); }); +test("a port that is not an integer from 0 to 65535 is an error, from the flag or PORT", () => { + for (const port of ["abc", "80x", "1.5", "-1", "65536", ""]) { + assert.equal(parseLaunchOptions(["-p", port], {}).error, `Invalid port: ${port}. Use an integer from 0 to 65535.`, port); + assert.equal(parseLaunchOptions([], { PORT: port }).error, `Invalid port: ${port}. Use an integer from 0 to 65535.`, `PORT=${port}`); + } + for (const port of ["0", "30177", "65535"]) assert.equal(parseLaunchOptions(["-p", port], {}).error, undefined, port); +}); + +test("ompweb with a bad port says so in one line and exits 2", () => { + const launcher = fileURLToPath(new URL("../bin/omp-web.js", import.meta.url)); + const result = spawnSync("node", [launcher, "-p", "abc", "--no-open"], { encoding: "utf8", timeout: 20_000 }); + assert.equal(result.stderr.trim(), "Invalid port: abc. Use an integer from 0 to 65535."); + assert.equal(result.status, 2); +}); + test("supports OMP_WEB_HOSTNAME without trusting the ambient system HOSTNAME", () => { assert.equal( parseLaunchOptions([], { HOSTNAME: "container-id" }).hostname, diff --git a/lib/omp/agent-env-policy.ts b/lib/omp/agent-env-policy.ts index cecd502ee..2c85ec97b 100644 --- a/lib/omp/agent-env-policy.ts +++ b/lib/omp/agent-env-policy.ts @@ -6,7 +6,7 @@ * * Users only ever get to add variables, never to rewrite the plumbing omp-web itself * depends on. Two rules enforce that: - * 1. `lib/project-command-env.ts` strips PORT / NODE_ENV / NEXT_* from every child + * 1. `lib/project-command-env.ts` strips PORT / NODE_ENV from every child * spawn (`sanitizeProjectCommandEnvironment`, called in `spawnOmpTransport` in lib/omp/rpc-process.ts * AFTER the merge). Letting a user set them would be a silent no-op, so they are * denied here too — the policy is deliberately mirrored, not re-invented. @@ -59,7 +59,6 @@ const DENIED_NAMES: ReadonlySet = new Set([ /** Prefixes that may never be overridden (compared uppercased). */ const DENIED_PREFIXES: readonly string[] = [ "OMP_WEB_", // omp-web's own plumbing (auth, ports, binary overrides) - "NEXT_", // stripped by sanitizeProjectCommandEnvironment "_", // shell-internal namespace ]; diff --git a/lib/omp/agent-env.test.mjs b/lib/omp/agent-env.test.mjs index c169db6b8..f3856e5f4 100644 --- a/lib/omp/agent-env.test.mjs +++ b/lib/omp/agent-env.test.mjs @@ -3,11 +3,9 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); const { formatAgentEnvText, getAgentEnvOverrides, isDeniedAgentEnvName, parseAgentEnvText, sanitizeAgentEnvValues } = - await jiti.import("./agent-env.ts"); + await import("./agent-env.ts"); /** Points getAgentDir() (and therefore the settings file) at a throwaway directory. */ function withAgentDir(run) { @@ -70,7 +68,7 @@ test("denies the plumbing omp-web and the spawner rely on", () => { const required = [ "PATH", "NODE_OPTIONS", "SystemRoot", "SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT", "PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "PORT", "NODE_ENV", "HOME", "USERPROFILE", - "OMP_WEB_PASSWORD", "NEXT_PUBLIC_FOO", "_PRIVATE", + "OMP_WEB_PASSWORD", "_PRIVATE", ]; for (const name of required) { assert.equal(isDeniedAgentEnvName(name), true, name); @@ -81,6 +79,7 @@ test("denies the plumbing omp-web and the spawner rely on", () => { } assert.equal(isDeniedAgentEnvName("path"), true, "Windows names are case-insensitive"); assert.equal(isDeniedAgentEnvName("OBSIDIAN_API_KEY"), false); + assert.equal(isDeniedAgentEnvName("NEXT_TELEMETRY_DISABLED"), false); }); test("a denied line is reported but never reaches values", () => { diff --git a/lib/omp/agents-service.test.mjs b/lib/omp/agents-service.test.mjs index 351d82ea8..3b4b3a20f 100644 --- a/lib/omp/agents-service.test.mjs +++ b/lib/omp/agents-service.test.mjs @@ -3,10 +3,8 @@ import { link, mkdtemp, readdir, realpath, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { parseAgentFrontmatter, writeAgent } = await jiti.import("./agents-service.ts"); +const { parseAgentFrontmatter, writeAgent } = await import("./agents-service.ts"); const payload = { description: "A test agent", body: "Do the task." }; diff --git a/lib/omp/archive.test.mjs b/lib/omp/archive.test.mjs index db68d493f..a34cd6af6 100644 --- a/lib/omp/archive.test.mjs +++ b/lib/omp/archive.test.mjs @@ -4,10 +4,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { gzipSync } from "node:zlib"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { listArchivedSessions, restoreArchivedSession } = await jiti.import("./archive.ts"); +const { listArchivedSessions, restoreArchivedSession } = await import("./archive.ts"); function sessionBody(id = "archived-id") { return [ diff --git a/lib/omp/mcp-config.test.mjs b/lib/omp/mcp-config.test.mjs index 49c0df2dc..8b1afc4f5 100644 --- a/lib/omp/mcp-config.test.mjs +++ b/lib/omp/mcp-config.test.mjs @@ -3,10 +3,8 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync, openSync, closeSync, uti import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { deleteMcpServer, parseMcpListOutput, readMcpConfig, readUserMcpConfig, redactMcpServer, validateMcpServer, writeMcpServer } = await jiti.import("./mcp-config.ts"); +const { deleteMcpServer, parseMcpListOutput, readMcpConfig, readUserMcpConfig, redactMcpServer, validateMcpServer, writeMcpServer } = await import("./mcp-config.ts"); function withWorkspace(run) { const dir = mkdtempSync(join(tmpdir(), "omp-web-mcp-config-")); diff --git a/lib/omp/models-config.test.mjs b/lib/omp/models-config.test.mjs index 9e907d969..c3cd4e0bc 100644 --- a/lib/omp/models-config.test.mjs +++ b/lib/omp/models-config.test.mjs @@ -3,16 +3,14 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); const { ModelsConfigParseError, readModelsConfigFile, serializeModelsConfig, validateModelsConfig, writeModelsConfig, -} = await jiti.import("./models-config.ts"); +} = await import("./models-config.ts"); // A hand-edited models.yml: comments, blank lines and quoting that a // parse+stringify round trip would silently throw away. diff --git a/lib/omp/omp-cli.test.mjs b/lib/omp/omp-cli.test.mjs index 42bcdada0..b1c1eff24 100644 --- a/lib/omp/omp-cli.test.mjs +++ b/lib/omp/omp-cli.test.mjs @@ -1,12 +1,14 @@ import assert from "node:assert/strict"; -import childProcess from "node:child_process"; import { mkdtempSync, readFileSync, renameSync, rmSync, statSync, symlinkSync, mkdirSync, utimesSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; +import { mockBuiltin } from "../../tests/mock-builtin.mjs"; -function setup(t, execute) { +// Each setup imports omp-cli fresh so it binds the mocked child_process and starts with an empty version cache. +let freshImport = 0; + +async function setup(t, execute) { const dir = mkdtempSync(join(tmpdir(), "omp-version-")); const bin = join(dir, "omp"); writeFileSync(bin, "omp/18.1.19\n"); @@ -17,18 +19,17 @@ function setup(t, execute) { else process.env.OMP_WEB_OMP_BIN = previousBin; rmSync(dir, { recursive: true, force: true }); }); - t.mock.method(childProcess, "execFile", (path, _args, _options, callback) => { + await mockBuiltin(t, "node:child_process", { execFile: (path, _args, _options, callback) => { if (execute) execute(callback); else callback(null, readFileSync(path, "utf8")); - }); - // Keep builtin mocks on the same CJS path across supported Node versions. - const jiti = createJiti(import.meta.url, { moduleCache: false, tryNative: false }); - return { dir, bin, getOmpVersion: jiti("./omp-cli.ts").getOmpVersion }; + } }); + const { getOmpVersion } = await import(`./omp-cli.ts?fresh=${freshImport++}`); + return { dir, bin, getOmpVersion }; } test("unchanged executables reuse the version without launching another process", async (t) => { let launches = 0; - const { bin, getOmpVersion } = setup(t, (callback) => { + const { bin, getOmpVersion } = await setup(t, (callback) => { launches++; callback(null, readFileSync(bin, "utf8")); }); @@ -41,7 +42,7 @@ test("unchanged executables reuse the version without launching another process" }); test("atomic replacement invalidates even with the same size and modification time", async (t) => { - const { dir, bin, getOmpVersion } = setup(t); + const { dir, bin, getOmpVersion } = await setup(t); const original = statSync(bin); // Normalize both mtimes to the same precision before taking the cache snapshot. utimesSync(bin, original.atime, original.mtime); @@ -55,7 +56,7 @@ test("atomic replacement invalidates even with the same size and modification ti }); test("retargeting the release directory invalidates the cached version", async (t) => { - const { dir, bin, getOmpVersion } = setup(t); + const { dir, bin, getOmpVersion } = await setup(t); const first = join(dir, "first"); const second = join(dir, "second"); mkdirSync(first); @@ -75,7 +76,7 @@ test("unchanged launchers are re-probed after the five-minute safety expiry", as let now = Date.now(); t.mock.method(Date, "now", () => now); let installedVersion = "omp/18.1.19\n"; - const { getOmpVersion } = setup(t, (callback) => callback(null, installedVersion)); + const { getOmpVersion } = await setup(t, (callback) => callback(null, installedVersion)); assert.equal(await getOmpVersion(), "omp/18.1.19"); installedVersion = "omp/18.1.21\n"; now += 5 * 60_000 - 1; @@ -86,7 +87,7 @@ test("unchanged launchers are re-probed after the five-minute safety expiry", as test("overlapping version lookups share a result instead of racing failure backoff", async (t) => { const callbacks = []; - const { bin, getOmpVersion } = setup(t, (callback) => callbacks.push(callback)); + const { bin, getOmpVersion } = await setup(t, (callback) => callbacks.push(callback)); const first = getOmpVersion(); const second = getOmpVersion(); if (callbacks.length > 1) { @@ -105,7 +106,7 @@ test("overlapping version lookups share a result instead of racing failure backo test("an update during a probe does not cache its old result", async (t) => { const callbacks = []; - const { bin, getOmpVersion } = setup(t, (callback) => callbacks.push(callback)); + const { bin, getOmpVersion } = await setup(t, (callback) => callbacks.push(callback)); const first = getOmpVersion(); writeFileSync(bin, "omp/18.1.210\n"); callbacks[0](null, "omp/18.1.19\n"); @@ -117,7 +118,7 @@ test("an update during a probe does not cache its old result", async (t) => { test("changed executables recover immediately from a failed-probe backoff", async (t) => { let fail = true; - const { bin, getOmpVersion } = setup(t, (callback) => { + const { bin, getOmpVersion } = await setup(t, (callback) => { callback(fail ? new Error("update in progress") : null, "omp/18.1.21\n"); }); assert.equal(await getOmpVersion(), null); @@ -127,7 +128,7 @@ test("changed executables recover immediately from a failed-probe backoff", asyn }); test("removing an executable never serves its cached version", async (t) => { - const { bin, getOmpVersion } = setup(t); + const { bin, getOmpVersion } = await setup(t); assert.equal(await getOmpVersion(), "omp/18.1.19"); rmSync(bin); assert.equal(await getOmpVersion(), null); diff --git a/lib/omp/omp-cli.ts b/lib/omp/omp-cli.ts index c4fddc6df..8ac499071 100644 --- a/lib/omp/omp-cli.ts +++ b/lib/omp/omp-cli.ts @@ -62,7 +62,7 @@ function probeOmpBin(): string | null { * miss is re-probed after MISS_TTL_MS. */ export function resolveOmpBin(): string | null { // A global Bun/npm update can replace or remove its launcher while this - // Next.js process is still alive. Never keep returning a stale cache entry. + // server process is still alive. Never keep returning a stale cache entry. if (cachedBin && existsSync(cachedBin)) return cachedBin; cachedBin = null; if (Date.now() - binMissAt < MISS_TTL_MS) return null; diff --git a/lib/omp/rpc-frame.test.mjs b/lib/omp/rpc-frame.test.mjs index 7a1182d74..cce770f19 100644 --- a/lib/omp/rpc-frame.test.mjs +++ b/lib/omp/rpc-frame.test.mjs @@ -1,14 +1,12 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); const { encodeRpcCommand, MAX_INBOUND_COMMAND_BYTES, MAX_RPC_FRAME_BYTES, RpcFrameDecoder, -} = await jiti.import("./rpc-frame.ts"); +} = await import("./rpc-frame.ts"); /** Outbound v2 chunk records exactly as OMP emits them. */ function chunkRecords(frame, chunkId, payloadBytes = 256 * 1024) { diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index bd36717fa..66fe46bc6 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -2,11 +2,9 @@ import assert from "node:assert/strict"; import { EventEmitter } from "node:events"; import { PassThrough } from "node:stream"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { RpcProcess, RpcCommandTimeoutError } = jiti("./rpc-process.ts"); -const { AgentSessionWrapper } = jiti("../rpc-manager.ts"); +const { RpcProcess, RpcCommandTimeoutError } = await import("./rpc-process.ts"); +const { AgentSessionWrapper } = await import("../rpc-manager.ts"); // Wrappers built directly need an online host; this one never spawns or reads files. const onlineHost = { id: "local", @@ -388,7 +386,7 @@ test("a response naming another command does not settle a command with its id", }); test("an adopted RpcProcess whose output outgrows the hold cap fails its commands and its replay", async () => { - const { LINK_LIMITS } = jiti("../hosts/link-protocol.ts"); + const { LINK_LIMITS } = await import("../hosts/link-protocol.ts"); const saved = LINK_LIMITS.channelBufferBytes; LINK_LIMITS.channelBufferBytes = 1_000; try { diff --git a/lib/omp/session-archive.test.mjs b/lib/omp/session-archive.test.mjs index 12c18c007..14c0a0700 100644 --- a/lib/omp/session-archive.test.mjs +++ b/lib/omp/session-archive.test.mjs @@ -4,10 +4,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { gunzipSync } from "node:zlib"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { archiveSessionFileWithArtifacts } = await jiti.import("./session-files.ts"); +const { archiveSessionFileWithArtifacts } = await import("./session-files.ts"); test("archives native JSONL and sibling artifacts with an exact gzip round trip", () => { const root = mkdtempSync(join(tmpdir(), "omp-web-archive-test-")); diff --git a/lib/omp/session-edit.native.test.mjs b/lib/omp/session-edit.native.test.mjs index 4209126e5..373a24eb8 100644 --- a/lib/omp/session-edit.native.test.mjs +++ b/lib/omp/session-edit.native.test.mjs @@ -7,16 +7,14 @@ import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; -import { createJiti } from "jiti"; import { SESSION_EDIT_COMMAND, SESSION_EDIT_RESPONSE_PREFIX } from "./session-edit-extension.mjs"; -const jiti = createJiti(import.meta.url); -const { editSessionHistory } = await jiti.import("./session-edit.ts"); +const { editSessionHistory } = await import("./session-edit.ts"); const SESSION_EDIT_EXTENSION_PATH = fileURLToPath(new URL("./session-edit-extension.mjs", import.meta.url)); -const { RpcProcess, RpcCommandTimeoutError } = await jiti.import("./rpc-process.ts"); -const { resolveOmpBin } = await jiti.import("./omp-cli.ts"); -const { buildSessionContext } = await jiti.import("../session-reader.ts"); -const { loadSessionFile } = await jiti.import("./session-files.ts"); +const { RpcProcess, RpcCommandTimeoutError } = await import("./rpc-process.ts"); +const { resolveOmpBin } = await import("./omp-cli.ts"); +const { buildSessionContext } = await import("../session-reader.ts"); +const { loadSessionFile } = await import("./session-files.ts"); // Deliberately opt-in: the normal npm test glob discovers this file without // launching an installed executable or inspecting the user's credentials. diff --git a/lib/omp/session-edit.test.mjs b/lib/omp/session-edit.test.mjs index 87f3f0a94..71da8f586 100644 --- a/lib/omp/session-edit.test.mjs +++ b/lib/omp/session-edit.test.mjs @@ -1,11 +1,9 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; import registerSessionEdit, { SESSION_EDIT_COMMAND, SESSION_EDIT_RESPONSE_PREFIX } from "./session-edit-extension.mjs"; -const jiti = createJiti(import.meta.url); -const { editSessionHistory } = await jiti.import("./session-edit.ts"); -const { RpcCommandTimeoutError } = await jiti.import("./rpc-process.ts"); +const { editSessionHistory } = await import("./session-edit.ts"); +const { RpcCommandTimeoutError } = await import("./rpc-process.ts"); const immediate = () => new Promise((resolve) => setImmediate(resolve)); const editReply = (result) => ({ diff --git a/lib/omp/session-files.ts b/lib/omp/session-files.ts index 42c7dc49d..c239657f3 100644 --- a/lib/omp/session-files.ts +++ b/lib/omp/session-files.ts @@ -41,8 +41,8 @@ import { sessionPathKey } from "../paths"; * Pure-Node reader/writer for oh-my-pi's session JSONL files (format v3). * Ported from oh-my-pi packages/coding-agent/src/session/ (session-entries, * session-title-slot, session-listing, session-loader, session-migrations, - * blob-store) because the @oh-my-pi packages are Bun-only and cannot run - * inside the Node-hosted Next.js server. + * blob-store) because the @oh-my-pi packages are Bun-only and the server ran + * on Node (Next.js) when this was written. * * File layout: optional fixed-width 256-byte title-slot line, then the * {"type":"session"} header line, then entries forming a tree via @@ -392,7 +392,7 @@ const SESSION_READ_CHUNK_BYTES = 1024 * 1024; * Ceiling on the on-disk size omp-web will materialize into memory. omp streams * sessions, so this is not an omp limit — it is the point past which parsing a * session into JS objects (and serializing it into one HTTP response) would OOM - * the whole Next.js server. Refusing loudly beats taking the process down. + * the whole server. Refusing loudly beats taking the process down. */ export const MAX_SESSION_LOAD_BYTES = 1024 * 1024 * 1024; diff --git a/lib/omp/settings-config.test.mjs b/lib/omp/settings-config.test.mjs index ee78887e8..f4b5a874f 100644 --- a/lib/omp/settings-config.test.mjs +++ b/lib/omp/settings-config.test.mjs @@ -3,10 +3,8 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "no import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { readNativeSettings, writeNativeSettings } = await jiti.import("./settings-config.ts"); +const { readNativeSettings, writeNativeSettings } = await import("./settings-config.ts"); function withAgentDir(run) { const dir = mkdtempSync(join(tmpdir(), "omp-web-settings-config-")); diff --git a/lib/omp/updates.test.mjs b/lib/omp/updates.test.mjs index db82847e3..3a2c3b184 100644 --- a/lib/omp/updates.test.mjs +++ b/lib/omp/updates.test.mjs @@ -1,13 +1,11 @@ import assert from "node:assert/strict"; -import childProcess from "node:child_process"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; +import { mockBuiltin } from "../../tests/mock-builtin.mjs"; -const jiti = createJiti(import.meta.url); -const { parseOmpUpdateStatus, createCachedOmpUpdateCheck, OMP_UPDATE_CHECK_TTL_MS } = jiti("./updates.ts"); +const { parseOmpUpdateStatus, createCachedOmpUpdateCheck, OMP_UPDATE_CHECK_TTL_MS } = await import("./updates.ts"); test("parses OMP update availability without assuming an update exists", () => { assert.deepEqual(parseOmpUpdateStatus("Current version: 17.2.11\nNew version available: 17.2.12"), { currentVersion: "17.2.11", @@ -103,9 +101,8 @@ test("createCachedOmpUpdateCheck does not cache failures and allows retry", asyn // win32 cmd-wrap coverage for runOmpUpdate (third spawn site — see D5) // ============================================================================ -// moduleCache:false + tryNative:false keep t.mock.method(childProcess, ...) on -// the same CJS module instance the TypeScript import resolves (see omp-cli.test.mjs). -const mockSafeJiti = createJiti(import.meta.url, { moduleCache: false, tryNative: false }); +// Each test imports updates.ts fresh so it binds the mocked child_process. +let freshImport = 0; function withPlatform(t, platform) { const original = process.platform; @@ -119,6 +116,8 @@ function withOmpBin(t, bin) { t.after(() => { if (previousBin === undefined) delete process.env.OMP_WEB_OMP_BIN; else process.env.OMP_WEB_OMP_BIN = previousBin; + // omp-cli keeps the resolved path while it exists; ./updates.ts shares that module across fresh imports. + rmSync(dirname(bin), { recursive: true, force: true }); }); } @@ -129,11 +128,11 @@ test("runOmpUpdate routes .cmd launchers through cmd.exe on win32", async (t) => writeFileSync(bin, "stub\n"); withOmpBin(t, bin); let captured = null; - t.mock.method(childProcess, "execFile", (file, args, options, callback) => { + await mockBuiltin(t, "node:child_process", { execFile: (file, args, options, callback) => { captured = { file, args, options }; queueMicrotask(() => callback(null, "Current version: 18.2.7\nOMP is up to date")); - }); - const { runOmpUpdate } = mockSafeJiti("./updates.ts"); + } }); + const { runOmpUpdate } = await import(`./updates.ts?fresh=${freshImport++}`); const output = await runOmpUpdate(["--check"]); assert.match(output, /Current version: 18\.2\.7/); assert.equal(captured.file, "cmd.exe"); @@ -147,11 +146,11 @@ test("runOmpUpdate leaves .exe binaries untouched", async (t) => { writeFileSync(bin, "stub\n"); withOmpBin(t, bin); let captured = null; - t.mock.method(childProcess, "execFile", (file, args, options, callback) => { + await mockBuiltin(t, "node:child_process", { execFile: (file, args, options, callback) => { captured = { file, args, options }; queueMicrotask(() => callback(null, "Current version: 18.2.7\nOMP is up to date")); - }); - const { runOmpUpdate } = mockSafeJiti("./updates.ts"); + } }); + const { runOmpUpdate } = await import(`./updates.ts?fresh=${freshImport++}`); await runOmpUpdate(["--check"]); assert.equal(captured.file, bin); assert.deepEqual(captured.args, ["update", "--check"]); @@ -164,11 +163,11 @@ test("runOmpUpdate never wraps .cmd on non-win32 platforms", async (t) => { writeFileSync(bin, "stub\n"); withOmpBin(t, bin); let captured = null; - t.mock.method(childProcess, "execFile", (file, args, options, callback) => { + await mockBuiltin(t, "node:child_process", { execFile: (file, args, options, callback) => { captured = { file, args, options }; queueMicrotask(() => callback(null, "Current version: 18.2.7\nOMP is up to date")); - }); - const { runOmpUpdate } = mockSafeJiti("./updates.ts"); + } }); + const { runOmpUpdate } = await import(`./updates.ts?fresh=${freshImport++}`); await runOmpUpdate(["--check"]); assert.equal(captured.file, bin); assert.deepEqual(captured.args, ["update", "--check"]); @@ -185,7 +184,7 @@ test("real .cmd launcher through the real update path returns its stdout", { ski "", ].join("\r\n")); withOmpBin(t, bin); - const { runOmpUpdate, parseOmpUpdateStatus } = mockSafeJiti("./updates.ts"); + const { runOmpUpdate, parseOmpUpdateStatus } = await import(`./updates.ts?fresh=${freshImport++}`); const output = await runOmpUpdate(["--check"]); assert.match(output, /OMP is up to date/); const status = parseOmpUpdateStatus(output); diff --git a/lib/omp/win32-spawn.test.mjs b/lib/omp/win32-spawn.test.mjs index 9cce24929..e0386ae75 100644 --- a/lib/omp/win32-spawn.test.mjs +++ b/lib/omp/win32-spawn.test.mjs @@ -1,16 +1,15 @@ import assert from "node:assert/strict"; -import childProcess from "node:child_process"; import { EventEmitter } from "node:events"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; +import { mockBuiltin } from "../../tests/mock-builtin.mjs"; import { PassThrough } from "node:stream"; -import { createJiti } from "jiti"; -// moduleCache:false + tryNative:false keep t.mock.method(childProcess, ...) on -// the same CJS module instance the TypeScript import resolves (see omp-cli.test.mjs). -const jiti = createJiti(import.meta.url, { moduleCache: false, tryNative: false }); +// Each test that mocks child_process imports omp-cli fresh so it binds the fake. +let freshImport = 0; +const { RpcProcess } = await import("./rpc-process.ts"); /** Replace process.platform for the duration of one test (helper reads it at call time). */ function withPlatform(t, platform) { @@ -39,7 +38,7 @@ function makeSpawnHarness() { function startProcess(bin, cwd, extraArgs = []) { const harness = makeSpawnHarness(); - const proc = new (jiti("./rpc-process.ts").RpcProcess)({ + const proc = new RpcProcess({ cwd, extraArgs, dependencies: { resolveOmpBin: () => bin, spawn: harness.spawn }, @@ -119,11 +118,11 @@ test("probeOmpVersion routes .cmd launchers through cmd.exe on win32", async (t) rmSync(dir, { recursive: true, force: true }); }); let captured = null; - t.mock.method(childProcess, "execFile", (file, args, options, callback) => { + await mockBuiltin(t, "node:child_process", { execFile: (file, args, options, callback) => { captured = { file, args, options }; queueMicrotask(() => callback(null, "omp/18.2.4\n")); - }); - const { getOmpVersion } = jiti("./omp-cli.ts"); + } }); + const { getOmpVersion } = await import(`./omp-cli.ts?fresh=${freshImport++}`); assert.equal(await getOmpVersion(), "omp/18.2.4"); assert.equal(captured.file, "cmd.exe"); assert.deepEqual(captured.args, ["/c", bin, "--version"]); @@ -142,11 +141,11 @@ test("probeOmpVersion leaves .exe binaries untouched", async (t) => { rmSync(dir, { recursive: true, force: true }); }); let captured = null; - t.mock.method(childProcess, "execFile", (file, args, options, callback) => { + await mockBuiltin(t, "node:child_process", { execFile: (file, args, options, callback) => { captured = { file, args, options }; queueMicrotask(() => callback(null, "omp/18.2.4\n")); - }); - const { getOmpVersion } = jiti("./omp-cli.ts"); + } }); + const { getOmpVersion } = await import(`./omp-cli.ts?fresh=${freshImport++}`); assert.equal(await getOmpVersion(), "omp/18.2.4"); assert.equal(captured.file, bin); assert.deepEqual(captured.args, ["--version"]); @@ -165,11 +164,11 @@ test("probeOmpVersion never wraps .cmd on non-win32 platforms", async (t) => { rmSync(dir, { recursive: true, force: true }); }); let captured = null; - t.mock.method(childProcess, "execFile", (file, args, options, callback) => { + await mockBuiltin(t, "node:child_process", { execFile: (file, args, options, callback) => { captured = { file, args, options }; queueMicrotask(() => callback(null, "omp/18.2.4\n")); - }); - const { getOmpVersion } = jiti("./omp-cli.ts"); + } }); + const { getOmpVersion } = await import(`./omp-cli.ts?fresh=${freshImport++}`); assert.equal(await getOmpVersion(), "omp/18.2.4"); assert.equal(captured.file, bin); assert.deepEqual(captured.args, ["--version"]); @@ -194,7 +193,7 @@ test("real .cmd launcher through the real spawn path receives spaced arguments i mkdirSync(spacedCwd); const { promise: exited, resolve: resolveExit } = Promise.withResolvers(); - new (jiti("./rpc-process.ts").RpcProcess)({ + new RpcProcess({ cwd: spacedCwd, dependencies: { resolveOmpBin: () => bin }, // real child_process.spawn — no seam onExit: (info) => resolveExit(info), @@ -225,7 +224,7 @@ test("real .cmd launcher through the real version probe returns its stdout", { s if (previousBin === undefined) delete process.env.OMP_WEB_OMP_BIN; else process.env.OMP_WEB_OMP_BIN = previousBin; }); - const { getOmpVersion } = jiti("./omp-cli.ts"); + const { getOmpVersion } = await import(`./omp-cli.ts?fresh=${freshImport++}`); assert.equal(await getOmpVersion(), "omp/99.9.9-win"); const rawArgs = readFileSync(argsFile, "utf8").replace(/\r\n/g, "\n").trim(); assert.equal(rawArgs, "--version"); diff --git a/lib/paths.test.mjs b/lib/paths.test.mjs index 78dafb7ba..60aefad23 100644 --- a/lib/paths.test.mjs +++ b/lib/paths.test.mjs @@ -1,10 +1,8 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { isWindowsAbsolutePath, normalizeForComparison, samePath } = await jiti.import("./paths.ts"); -const { projectIdentityKey } = await jiti.import("./paths.ts"); +const { isWindowsAbsolutePath, normalizeForComparison, samePath } = await import("./paths.ts"); +const { projectIdentityKey } = await import("./paths.ts"); test("detects Windows absolute paths and UNC paths", () => { assert.equal(isWindowsAbsolutePath("C:\\Users\\me"), true); diff --git a/lib/project-command-env.test.mjs b/lib/project-command-env.test.mjs index e04540017..f0902b69f 100644 --- a/lib/project-command-env.test.mjs +++ b/lib/project-command-env.test.mjs @@ -1,21 +1,20 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); const { createChildProcessEnvironment, isHostRuntimeVariable, isOmpWebSecretVariable, sanitizeProjectCommandEnvironment, OMP_WEB_SECRET_ENV_VARS, -} = await jiti.import("./project-command-env.ts"); +} = await import("./project-command-env.ts"); -test("strips the Next.js host runtime variables", () => { +test("strips the host runtime variables", () => { assert.equal(isHostRuntimeVariable("PORT", "linux"), true); assert.equal(isHostRuntimeVariable("port", "win32"), true); assert.equal(isHostRuntimeVariable("NODE_ENV", "linux"), true); - assert.equal(isHostRuntimeVariable("NEXT_PUBLIC_FOO", "linux"), true); + // A user's own NEXT_* settings are meant for the project's tools, not the omp-web server. + assert.equal(isHostRuntimeVariable("NEXT_PUBLIC_FOO", "linux"), false); assert.equal(isHostRuntimeVariable("PATH", "linux"), false); assert.equal(isHostRuntimeVariable("NEXTTLS", "linux"), false); @@ -26,7 +25,7 @@ test("strips the Next.js host runtime variables", () => { NEXT_TELEMETRY_DISABLED: "1", PROJECT: "keep-me", }, "linux"); - assert.deepEqual(env, { PATH: "/usr/bin", PROJECT: "keep-me" }); + assert.deepEqual(env, { PATH: "/usr/bin", NEXT_TELEMETRY_DISABLED: "1", PROJECT: "keep-me" }); }); test("strips omp-web's own secrets from a child environment", () => { diff --git a/lib/project-command-env.ts b/lib/project-command-env.ts index b08450001..0ac8dd246 100644 --- a/lib/project-command-env.ts +++ b/lib/project-command-env.ts @@ -2,8 +2,8 @@ * Remove variables owned by the omp-web host before starting any child * process. Two groups are stripped: * - * - Host runtime variables (PORT, NODE_ENV, NEXT_*): these describe the - * Next.js server, not the selected project, and can make project commands + * - Host runtime variables (PORT, NODE_ENV): these describe the + * omp-web server, not the selected project, and can make project commands * behave as if they were running inside the web app. * - omp-web's own secrets. Every `omp` session inherits this environment, so * an agent that runs `env` would otherwise print the web password hash into @@ -31,9 +31,6 @@ export const OMP_WEB_SECRET_ENV_VARS: readonly string[] = [ "OMP_WEB_TRUSTED_HEADER_SHA256", ]; -/** Prefixes that never reach a child process. */ -const HOST_RUNTIME_PREFIXES: readonly string[] = ["NEXT_"]; - function comparableName(name: string, platform: NodeJS.Platform): string { return platform === "win32" ? name.toUpperCase() : name; } @@ -45,9 +42,7 @@ function matches(name: string, candidates: readonly string[], platform: NodeJS.P /** True when the variable belongs to the omp-web host rather than the child. */ export function isHostRuntimeVariable(name: string, platform: NodeJS.Platform = process.platform): boolean { - const comparable = comparableName(name, platform); - return matches(name, HOST_RUNTIME_NAMES, platform) - || HOST_RUNTIME_PREFIXES.some((prefix) => comparable.startsWith(prefix)); + return matches(name, HOST_RUNTIME_NAMES, platform); } /** True when the variable is one of omp-web's secrets. */ diff --git a/lib/project-ordering.test.mjs b/lib/project-ordering.test.mjs index eb3f5cd53..04e0ae534 100644 --- a/lib/project-ordering.test.mjs +++ b/lib/project-ordering.test.mjs @@ -1,8 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); const { foldedHostProjectKey, groupProjectsByHost, @@ -12,8 +10,8 @@ const { nextPinOrder, orderProjects, sortManagedProjects, -} = await jiti.import("./project-ordering.ts"); -const { comparableProjectPath } = await jiti.import("./comparable-path.ts"); +} = await import("./project-ordering.ts"); +const { comparableProjectPath } = await import("./comparable-path.ts"); function session(id, overrides = {}) { return { diff --git a/lib/project-registry.test.mjs b/lib/project-registry.test.mjs index 6db188b74..e399e91f8 100644 --- a/lib/project-registry.test.mjs +++ b/lib/project-registry.test.mjs @@ -4,10 +4,8 @@ import { existsSync, mkdtempSync, mkdirSync, readdirSync, rmSync, writeFileSync import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { comparableProjectPath } = await jiti.import("./comparable-path.ts"); +const { comparableProjectPath } = await import("./comparable-path.ts"); const { hideProject, isReservedLaunchArg, @@ -18,8 +16,8 @@ const { upsertProject, updateProjectsPresentation, validateProjectPath, -} = await jiti.import("./project-registry.ts"); -const { resolveProject, addWorktree } = await jiti.import("./worktree.ts"); +} = await import("./project-registry.ts"); +const { resolveProject, addWorktree } = await import("./worktree.ts"); /** Absolute POSIX-looking test paths become platform-native via resolve(). */ const P = (p) => resolve(p); diff --git a/lib/provider-accounts.test.mjs b/lib/provider-accounts.test.mjs index 37c095a80..073be1b0b 100644 --- a/lib/provider-accounts.test.mjs +++ b/lib/provider-accounts.test.mjs @@ -1,9 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { summarizeProviderAccounts, planForStoredAccount } = await jiti.import("./provider-accounts.ts"); +const { summarizeProviderAccounts, planForStoredAccount } = await import("./provider-accounts.ts"); test("distinct accounts are listed once even when usage is split per model/tier", () => { const reports = [ diff --git a/lib/provider-usage.test.mjs b/lib/provider-usage.test.mjs index 32bb2fadc..0ba8147c3 100644 --- a/lib/provider-usage.test.mjs +++ b/lib/provider-usage.test.mjs @@ -1,12 +1,10 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; import { mkdtemp, writeFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -const jiti = createJiti(import.meta.url); -const { parseProviderUsageOutput, getProviderUsage } = await jiti.import("./provider-usage.ts"); +const { parseProviderUsageOutput, getProviderUsage } = await import("./provider-usage.ts"); test("parseProviderUsageOutput selects matching model windows", () => { const now = Date.UTC(2026, 7, 27, 12, 0, 0); const output = JSON.stringify({ diff --git a/lib/reconcile-guard.test.mjs b/lib/reconcile-guard.test.mjs index cc01ef877..2571569aa 100644 --- a/lib/reconcile-guard.test.mjs +++ b/lib/reconcile-guard.test.mjs @@ -1,9 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { createReconcileGuard } = await jiti.import("./reconcile-guard.ts"); +const { createReconcileGuard } = await import("./reconcile-guard.ts"); test("first acquire wins, concurrent acquires coalesce into one re-issue", async () => { const guard = createReconcileGuard(); diff --git a/lib/request-security.test.mjs b/lib/request-security.test.mjs index 1702229fd..5d429f0f0 100644 --- a/lib/request-security.test.mjs +++ b/lib/request-security.test.mjs @@ -14,7 +14,7 @@ test("allows same-origin and non-browser API requests", async () => { assert.equal(isApiRequestOriginAllowed(new Request("http://localhost:30141/api/test", { method: "POST" })), true); }); -test("allows LAN same-origin requests when Next.js uses an internal localhost URL", async () => { +test("allows LAN same-origin requests when request.url names an internal localhost URL", async () => { const { isApiRequestOriginAllowed } = await loadSubject(); const request = new Request("http://localhost:30141/api/test", { method: "POST", @@ -27,6 +27,22 @@ test("allows LAN same-origin requests when Next.js uses an internal localhost UR assert.equal(isApiRequestOriginAllowed(request), true); }); +test("allows a same-origin https request behind a TLS-terminating proxy", async () => { + const { isApiRequestOriginAllowed } = await loadSubject(); + // Bun's request.url is always http://; the proxy's first X-Forwarded-Proto value is the browser's scheme. + const request = (origin, proto) => new Request("http://127.0.0.1:30141/api/web-auth/session", { + method: "POST", + headers: { host: "ai.example.com", origin, "x-forwarded-proto": proto, "sec-fetch-site": "same-origin" }, + }); + assert.equal(isApiRequestOriginAllowed(request("https://ai.example.com", "https")), true); + assert.equal(isApiRequestOriginAllowed(request("https://ai.example.com", "https, http")), true); + assert.equal(isApiRequestOriginAllowed(request("http://ai.example.com", "https")), false); + assert.equal(isApiRequestOriginAllowed(request("https://ai.example.com", "http")), false); + // Traefik sends `wss` on a WebSocket upgrade; the page's Origin is still https. + assert.equal(isApiRequestOriginAllowed(request("https://ai.example.com", "wss")), true); + assert.equal(isApiRequestOriginAllowed(request("http://ai.example.com", "wss")), false); +}); + test("allows a matching Origin even when Sec-Fetch-Site is cross-site", async () => { const { isApiRequestOriginAllowed } = await loadSubject(); assert.equal(isApiRequestOriginAllowed(new Request("http://localhost:30141/api/test", { diff --git a/lib/request-security.ts b/lib/request-security.ts index 89da4bd84..0f0fd7815 100644 --- a/lib/request-security.ts +++ b/lib/request-security.ts @@ -6,10 +6,15 @@ function canonicalOrigin(value: string): string | null { } } +/** `https:` when the first X-Forwarded-Proto value says so (`wss` on a WebSocket upgrade, as Traefik sends): behind a TLS-terminating proxy Bun's request.url is still http://. */ +export function requestProtocol(request: Request): string { + const forwarded = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(); + return forwarded === "https" || forwarded === "wss" ? "https:" : new URL(request.url).protocol; +} + function getRequestOrigin(request: Request): string | null { - const requestUrl = new URL(request.url); const host = request.headers.get("host"); - return host ? canonicalOrigin(`${requestUrl.protocol}//${host}`) : requestUrl.origin; + return host ? canonicalOrigin(`${requestProtocol(request)}//${host}`) : new URL(request.url).origin; } /** Reject browser cross-site API requests while preserving non-browser clients. */ diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 7411e9226..53684d3cd 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -4,26 +4,25 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; import childProcess from "node:child_process"; -import { syncBuiltinESMExports } from "node:module"; +import { mockBuiltin } from "../tests/mock-builtin.mjs"; import { fileURLToPath } from "node:url"; import { EventEmitter } from "node:events"; import { PassThrough } from "node:stream"; +let isolatedFresh = 0; // Wrappers publish notifications, which the notification store records: never in the real agent dir. const isolatedAgentDir = mkdtempSync(join(tmpdir(), "omp-rpc-manager-test-")); process.env.PI_CODING_AGENT_DIR = isolatedAgentDir; +const { closeNotificationStore } = await import("./notification-store.ts"); test.after(() => { - globalThis.__ompNotificationStore?.db.close(); - globalThis.__ompNotificationStore = undefined; + closeNotificationStore(); rmSync(isolatedAgentDir, { recursive: true, force: true }); }); -const runtimeJiti = createJiti(import.meta.url); -const { AgentSessionWrapper: SnapshotWrapper, subscribeHostToolCalls } = await runtimeJiti.import("./rpc-manager.ts"); +const { AgentSessionWrapper: SnapshotWrapper, subscribeHostToolCalls } = await import("./rpc-manager.ts"); // Wrappers built directly need an online host; the daemon's machine host is one. -const { localHost } = await runtimeJiti.import("./hosts/local-host.ts"); +const { localHost } = await import("./hosts/local-host.ts"); function snapshotSession(t, sendCommand = async () => ({}), Wrapper = SnapshotWrapper, sessionId = "", disconnectDestroyMs) { const frameListeners = new Set(); @@ -314,9 +313,7 @@ test("auto-compaction results carry the same estimatedTokensAfter as manual comp test("resolveSpawnCwd uses the recorded directory when it exists, falls back otherwise", async () => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { resolveSpawnCwd, resolveSpawnCwdResult } = jiti("./hosts/local-host.ts"); + const { resolveSpawnCwd, resolveSpawnCwdResult } = await import("./hosts/local-host.ts"); const { existsSync } = await import("node:fs"); // A live recorded cwd is used verbatim — no fallback. @@ -345,9 +342,7 @@ test("resolveSpawnCwd uses the recorded directory when it exists, falls back oth }); test("missing terminal agent_end clears isPromptRunning on raw idle get_state", async () => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { AgentSessionWrapper } = jiti("./rpc-manager.ts"); + const { AgentSessionWrapper } = await import("./rpc-manager.ts"); let frameListener = null; const fakeProc = { @@ -387,9 +382,7 @@ test("missing terminal agent_end clears isPromptRunning on raw idle get_state", }); test("prompt ack pending does not let raw idle get_state clear promptRunning", async () => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { AgentSessionWrapper } = jiti("./rpc-manager.ts"); + const { AgentSessionWrapper } = await import("./rpc-manager.ts"); let resolvePromptAck; const fakeProc = { @@ -429,9 +422,7 @@ test("prompt ack pending does not let raw idle get_state clear promptRunning", a }); test("isTerminal:false respects 2-second grace period before raw idle can clear prompt", async () => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { AgentSessionWrapper } = jiti("./rpc-manager.ts"); + const { AgentSessionWrapper } = await import("./rpc-manager.ts"); let frameListener = null; const fakeProc = { @@ -480,9 +471,7 @@ test("isTerminal:false respects 2-second grace period before raw idle can clear }); test("abort_and_prompt images go through the same server-side validation as prompt", async () => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { AgentSessionWrapper } = jiti("./rpc-manager.ts"); + const { AgentSessionWrapper } = await import("./rpc-manager.ts"); let forwarded = false; const fakeProc = { @@ -505,10 +494,8 @@ test("abort_and_prompt images go through the same server-side validation as prom }); test("get_state timeout preserves the process and reports a transient status error", async () => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { AgentSessionWrapper, WebRpcError } = jiti("./rpc-manager.ts"); - const { RpcCommandTimeoutError } = jiti("./omp/rpc-process.ts"); + const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); let disposed = false; const fakeProc = { @@ -543,8 +530,7 @@ test("get_state timeout preserves the process and reports a transient status err }); test("a running task survives a slow status query and later state reads recover", async (t) => { - const jiti = createJiti(import.meta.url); - const { RpcCommandTimeoutError } = jiti("./omp/rpc-process.ts"); + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); let reads = 0; let running = true; const { wrapper, emit } = snapshotSession(t, async (command) => { @@ -567,10 +553,8 @@ test("a running task survives a slow status query and later state reads recover" }); test("prompt ack timeout recycles a child that accepts the frame but withholds its response", async (t) => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { AgentSessionWrapper, WebRpcError } = jiti("./rpc-manager.ts"); - const { RpcCommandTimeoutError } = jiti("./omp/rpc-process.ts"); + const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); t.mock.timers.enable({ apis: ["setTimeout"] }); let acceptedPrompt = null; @@ -618,9 +602,7 @@ test("prompt ack timeout recycles a child that accepts the frame but withholds i }); test("getRunningRpcSessions and getRunningRpcSessionIds export running sessions with their originating cwd", async () => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { getRunningRpcSessions, getRunningRpcSessionIds } = jiti("./rpc-manager.ts"); + const { getRunningRpcSessions, getRunningRpcSessionIds } = await import("./rpc-manager.ts"); assert.equal(typeof getRunningRpcSessions, "function"); assert.equal(typeof getRunningRpcSessionIds, "function"); @@ -632,13 +614,11 @@ test("getRunningRpcSessions and getRunningRpcSessionIds export running sessions }); test("unexpected child exit is retained until a replacement session clears it", async (t) => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); const { AgentSessionWrapper, clearExitedRpcSession, getExitedRpcSession, - } = jiti("./rpc-manager.ts"); + } = await import("./rpc-manager.ts"); globalThis.__ompExitedSessions = new Map(); t.after(() => { delete globalThis.__ompExitedSessions; }); @@ -689,9 +669,7 @@ test("unexpected child exit is retained until a replacement session clears it", }); test("a resumed session crash is retained before its initial handshake", async (t) => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { AgentSessionWrapper, getExitedRpcSession } = jiti("./rpc-manager.ts"); + const { AgentSessionWrapper, getExitedRpcSession } = await import("./rpc-manager.ts"); globalThis.__ompExitedSessions = new Map(); t.after(() => { delete globalThis.__ompExitedSessions; }); @@ -714,7 +692,7 @@ async function notifyingSession(t) { const { mkdtempSync, rmSync } = await import("node:fs"); const { tmpdir } = await import("node:os"); const { join } = await import("node:path"); - const { saveDevice } = await runtimeJiti.import("./notification-store.ts"); + const { saveDevice } = await import("./notification-store.ts"); const previousHub = globalThis.__ompNotificationHub; const previousExited = globalThis.__ompExitedSessions; const previousDir = process.env.PI_CODING_AGENT_DIR; @@ -749,8 +727,7 @@ async function notifyingSession(t) { if (previousDir === undefined) delete process.env.PI_CODING_AGENT_DIR; else process.env.PI_CODING_AGENT_DIR = previousDir; // Windows cannot delete the directory while the store's database is open. - globalThis.__ompNotificationStore?.db.close(); - globalThis.__ompNotificationStore = undefined; + closeNotificationStore(); rmSync(dir, { recursive: true, force: true }); }); return { wrapper, feed, delivered, ompState }; @@ -814,9 +791,7 @@ test("a crash of an idle session does not notify", async (t) => { }); test("buildSessionSpawnArgs maps tool presets to spawn flags", async () => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { buildSessionSpawnArgs } = jiti("./hosts/local-host.ts"); + const { buildSessionSpawnArgs } = await import("./hosts/local-host.ts"); // "full" must omit --tools entirely so omp keeps its complete default // toolset (task/hub included); any other list becomes an explicit --tools @@ -831,9 +806,7 @@ test("buildSessionSpawnArgs maps tool presets to spawn flags", async () => { ); }); test("buildSessionSpawnArgs applies workspace launch config safely", async () => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { buildSessionSpawnArgs } = jiti("./hosts/local-host.ts"); + const { buildSessionSpawnArgs } = await import("./hosts/local-host.ts"); assert.deepEqual( buildSessionSpawnArgs("", undefined, false, { profile: "work", advisor: true, extraArgs: ["--verbose"] }), @@ -849,9 +822,7 @@ test("buildSessionSpawnArgs applies workspace launch config safely", async () => }); test("buildSessionSpawnArgs binds an explicit model on resume only (#277)", async () => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { buildSessionSpawnArgs } = jiti("./hosts/local-host.ts"); + const { buildSessionSpawnArgs } = await import("./hosts/local-host.ts"); // A cold set_model must reach omp before the saved model is restored, so // the spawn carries --model alongside --resume. @@ -906,10 +877,8 @@ test("fresh spawns force a new session when omp resumes the cwd's latest session }); test("mcp list ack timeout recycles a child that accepts the frame but withholds its response", async (t) => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { AgentSessionWrapper, WebRpcError } = jiti("./rpc-manager.ts"); - const { RpcCommandTimeoutError } = jiti("./omp/rpc-process.ts"); + const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); t.mock.timers.enable({ apis: ["setTimeout"] }); let acceptedFrame = null; @@ -954,10 +923,8 @@ test("mcp list ack timeout recycles a child that accepts the frame but withholds }); test("mcp list ack timeout clears the waiter so a retry is not blocked as busy", async (t) => { - const { createJiti } = await import("jiti"); - const jiti = createJiti(import.meta.url); - const { AgentSessionWrapper } = jiti("./rpc-manager.ts"); - const { RpcCommandTimeoutError } = jiti("./omp/rpc-process.ts"); + const { AgentSessionWrapper } = await import("./rpc-manager.ts"); + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); t.mock.timers.enable({ apis: ["setTimeout"] }); const fakeProc = { @@ -1165,12 +1132,8 @@ test("reload replaces the native stream epoch and subscribes to replacement even queueMicrotask(() => child.stdout.write('{"type":"ready"}\n')); return child; }; - // Builtins bypass jiti virtual modules; synchronize Node's ESM bindings. - const spawnMock = t.mock.method(childProcess, "spawn", spawnReplacement); - syncBuiltinESMExports(); - t.after(() => { spawnMock.mock.restore(); syncBuiltinESMExports(); }); - const isolated = createJiti(import.meta.url, { moduleCache: false, tryNative: false }); - const { AgentSessionWrapper: ReloadWrapper } = await isolated.import("./rpc-manager.ts"); + await mockBuiltin(t, "node:child_process", { spawn: spawnReplacement }); + const { AgentSessionWrapper: ReloadWrapper } = await import(`./rpc-manager.ts?fresh=${isolatedFresh++}`); const { wrapper, emit } = snapshotSession(t, undefined, ReloadWrapper); emit({ type: "agent_start" }); emit({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: "old child" }] } }); @@ -1627,12 +1590,11 @@ test("reaping is disabled when the disconnect window is 0", async (t) => { test("neither cleanup timer keeps the event loop alive", async () => { // The reaper and the idle timer are cleanup deadlines, not work: an unref'd - // timer is what lets `next dev` and a test runner exit. A ref'd one pins a + // timer is what lets the dev server and a test runner exit. A ref'd one pins a // process that has nothing else pending for the full window. const moduleUrl = new URL("./rpc-manager.ts", import.meta.url).href; const script = ` - import { createJiti } from "jiti"; - const { AgentSessionWrapper } = await createJiti(import.meta.url).import(${JSON.stringify(moduleUrl)}); + const { AgentSessionWrapper } = await import(${JSON.stringify(moduleUrl)}); const wrapper = new AgentSessionWrapper( { isAlive: true, onFrame: () => () => {}, sendCommand: async () => ({}), sendFrame: () => {}, dispose: async () => {} }, process.cwd(), null, false, "", 10 * 60 * 1000, @@ -2009,8 +1971,8 @@ async function editableSession(t, onEdit) { } test("same-ID edit clears live evidence, invalidates only its own history, and refreshes all observers", async (t) => { - const { sessionPathKey } = await runtimeJiti.import("./paths.ts"); - const { subscribeRunningSessions } = await runtimeJiti.import("./rpc-manager.ts"); + const { sessionPathKey } = await import("./paths.ts"); + const { subscribeRunningSessions } = await import("./rpc-manager.ts"); const { wrapper, emit, state, commands } = await editableSession(t); const observed = [[], []]; for (const events of observed) wrapper.onEvent((event) => events.push(event)); @@ -2467,7 +2429,7 @@ test("a timed-out navigation disposes the old child before releasing the edit fe for (const timeoutAt of ["prompt-ack", "handler-result"]) { test(`a persistence notice cannot release Edit before timed-out child teardown (${timeoutAt})`, async (t) => { - const { RpcCommandTimeoutError } = await runtimeJiti.import("./omp/rpc-process.ts"); + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); const notice = { type: "notice", source: "session-persistence", level: "error", message: "Native append failed before edit handler completion" }; const { promise: disposal, resolve: finishDisposal } = Promise.withResolvers(); t.after(finishDisposal); @@ -2554,7 +2516,7 @@ test("initial spawn and reload both keep same-session editing available through const sessionFile = join(isolatedAgentDir, "edit-spawn-and-reload.jsonl"); writeFileSync(sessionFile, JSON.stringify({ type: "session", version: 3, id: sessionId, cwd: isolatedAgentDir }) + "\n"); t.after(() => rmSync(sessionFile, { force: true })); - const { SESSION_EDIT_EXTENSION_PATH } = await runtimeJiti.import("./hosts/local-host.ts"); + const { SESSION_EDIT_EXTENSION_PATH } = await import("./hosts/local-host.ts"); const spawns = []; let editCount = 0; const spawnReplacement = (file, args) => { @@ -2592,13 +2554,10 @@ test("initial spawn and reload both keep same-session editing available through queueMicrotask(() => child.stdout.write('{"type":"ready"}\n')); return child; }; - const spawnMock = t.mock.method(childProcess, "spawn", spawnReplacement); - syncBuiltinESMExports(); - t.after(() => { spawnMock.mock.restore(); syncBuiltinESMExports(); }); - const isolated = createJiti(import.meta.url, { moduleCache: false, tryNative: false }); - const { startRpcSession } = await isolated.import("./rpc-manager.ts"); + await mockBuiltin(t, "node:child_process", { spawn: spawnReplacement }); + const { startRpcSession } = await import(`./rpc-manager.ts?fresh=${isolatedFresh++}`); // The daemon's machine host spawns the (mocked) omp in this process. - const { localHost: spawningHost } = await isolated.import("./hosts/local-host.ts"); + const { localHost: spawningHost } = await import(`./hosts/local-host.ts?fresh=${isolatedFresh++}`); const { session, realSessionId } = await startRpcSession(sessionId, sessionFile, isolatedAgentDir, undefined, undefined, undefined, undefined, spawningHost); t.after(() => session.destroyAndWait()); const events = []; @@ -2697,7 +2656,7 @@ test("waitForTurnEnd resolves on terminal agent_end and rejects on timeout (#275 }); test("wrapper spawns through its host", async (t) => { - const { startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { startRpcSession } = await import("./rpc-manager.ts"); const requests = []; const invalidated = []; let emitLine; @@ -2741,7 +2700,7 @@ test("wrapper spawns through its host", async (t) => { }); test("reload keeps the live child when its host cannot check the session file", async (t) => { - const { startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { startRpcSession } = await import("./rpc-manager.ts"); let emitLine; let stopped = false; const transport = { @@ -2789,7 +2748,7 @@ test("reload keeps the live child when its host cannot check the session file", }); test("a session whose host is offline refuses sends with host_offline and reports the link state", async () => { - const { startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { startRpcSession } = await import("./rpc-manager.ts"); let emitLine; const transport = { write(line, callback) { @@ -2839,7 +2798,7 @@ test("a session whose host is offline refuses sends with host_offline and report }); test("a running remote session is listed with its host, so the sidebar groups its placeholder there", async () => { - const { getRunningRpcSessions, startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { getRunningRpcSessions, startRpcSession } = await import("./rpc-manager.ts"); let emitLine; const transport = { write(line, callback) { @@ -2871,7 +2830,7 @@ test("a running remote session is listed with its host, so the sidebar groups it }); test("a reload whose host drops while the old child exits fails host_offline and spawns nothing beside it", async () => { - const { getRpcSession, startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { getRpcSession, startRpcSession } = await import("./rpc-manager.ts"); let emitLine; const transport = { write(line, callback) { @@ -2929,8 +2888,8 @@ test("a reload whose host drops while the old child exits fails host_offline and }); test("a command written before the host link dropped resolves once the link returns", async (t) => { - const { startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); - const hub = await runtimeJiti.import("./hosts/hub.ts"); + const { startRpcSession } = await import("./rpc-manager.ts"); + const hub = await import("./hosts/hub.ts"); const { linkHost, until } = await import("./hosts/link-driver.test-helper.mjs"); const timings = { ...hub.linkTimings }; const link = await linkHost("Flaky box"); @@ -2999,10 +2958,10 @@ test("a command written before the host link dropped resolves once the link retu }); test("a run whose remote child vanished while the link was down resumes on that host", async (t) => { - const { getRpcSession, startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); - const { RESUME_PROMPT } = await runtimeJiti.import("./session-resume.ts"); - const { saveWebServerSettings } = await runtimeJiti.import("./web-settings.ts"); - const hub = await runtimeJiti.import("./hosts/hub.ts"); + const { getRpcSession, startRpcSession } = await import("./rpc-manager.ts"); + const { RESUME_PROMPT } = await import("./session-resume.ts"); + const { saveWebServerSettings } = await import("./web-settings.ts"); + const hub = await import("./hosts/hub.ts"); const { linkHost, until } = await import("./hosts/link-driver.test-helper.mjs"); const id = "11111111-2222-4333-8444-777777777777"; const sessionFile = `/remote/sessions/${id}.jsonl`; @@ -3086,8 +3045,8 @@ function spawnOverLink(link, spawns = []) { } test("a session the host still runs an orphan child for spawns only after the orphan exits", async (t) => { - const { startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); - const hub = await runtimeJiti.import("./hosts/hub.ts"); + const { startRpcSession } = await import("./rpc-manager.ts"); + const hub = await import("./hosts/hub.ts"); const { linkHost } = await import("./hosts/link-driver.test-helper.mjs"); const id = "11111111-2222-4333-8444-888888888888"; const sessionFile = `/remote/sessions/${id}.jsonl`; @@ -3110,8 +3069,8 @@ test("a session the host still runs an orphan child for spawns only after the or }); test("a prompt whose ack is lost to a quiet link answers host_offline and keeps the child", async (t) => { - const { startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); - const hub = await runtimeJiti.import("./hosts/hub.ts"); + const { startRpcSession } = await import("./rpc-manager.ts"); + const hub = await import("./hosts/hub.ts"); const { linkHost } = await import("./hosts/link-driver.test-helper.mjs"); const link = await linkHost("Lidded laptop"); let session; @@ -3155,8 +3114,8 @@ test("a prompt whose ack is lost to a quiet link answers host_offline and keeps }); test("an edit that times out with no uplink since dispatch answers host_offline and sends no kill", async (t) => { - const { startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); - const hub = await runtimeJiti.import("./hosts/hub.ts"); + const { startRpcSession } = await import("./rpc-manager.ts"); + const hub = await import("./hosts/hub.ts"); const { linkHost } = await import("./hosts/link-driver.test-helper.mjs"); const link = await linkHost("Editing box"); let session; @@ -3189,8 +3148,8 @@ test("an edit that times out with no uplink since dispatch answers host_offline }); test("a prompt that times out after the host sent uplink traffic is recycled as before", async (t) => { - const { startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); - const hub = await runtimeJiti.import("./hosts/hub.ts"); + const { startRpcSession } = await import("./rpc-manager.ts"); + const hub = await import("./hosts/hub.ts"); const { linkHost } = await import("./hosts/link-driver.test-helper.mjs"); const link = await linkHost("Wedged omp box"); let session; @@ -3228,7 +3187,7 @@ test("a prompt that times out after the host sent uplink traffic is recycled as /** A wrapper whose host link starts down; `linkReturns()` brings it back. */ async function wrapperBehindDownLink(sessionId, disconnectDestroyMs) { - const { AgentSessionWrapper } = await runtimeJiti.import("./rpc-manager.ts"); + const { AgentSessionWrapper } = await import("./rpc-manager.ts"); let status = "offline"; let statusChanged; const host = { @@ -3274,7 +3233,7 @@ test("the disconnect reaper waits while the host link is down and runs once it r }); test("the idle timer waits while the host link is down and runs once it returns", async (t) => { - await runtimeJiti.import("./rpc-manager.ts"); + await import("./rpc-manager.ts"); t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: Date.now() }); // Reaping off (0): only the idle timer (IDLE_DESTROY_MS, 10 minutes) can dispose it. const { wrapper, linkReturns } = await wrapperBehindDownLink("s-idle", 0); @@ -3334,7 +3293,7 @@ function scriptedHost(id, transport) { /** A running session on `host`; `events` collects the types it emits. */ async function runningRemoteSession(t, sessionId, transport, host) { - const { startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { startRpcSession } = await import("./rpc-manager.ts"); const { until } = await import("./hosts/link-driver.test-helper.mjs"); const { session } = await startRpcSession(sessionId, "", "/w", undefined, false, null, undefined, host); t.after(() => session.destroyAndWait()); @@ -3373,7 +3332,7 @@ test("a resync from the host reconciles the session", async (t) => { }); test("restartAllRpcSessions restarts only this machine's sessions", async (t) => { - const { restartAllRpcSessions, startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { restartAllRpcSessions, startRpcSession } = await import("./rpc-manager.ts"); const localTransport = scriptedTransport("s-restart-local"); const remoteTransport = scriptedTransport("s-restart-remote"); const local = await startRpcSession("s-restart-local", "", "/w", undefined, false, null, undefined, scriptedHost("local", localTransport)); @@ -3385,7 +3344,7 @@ test("restartAllRpcSessions restarts only this machine's sessions", async (t) => }); test("disposing a session whose host goes offline mid-wait returns instead of waiting for the link", async (t) => { - const { startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { startRpcSession } = await import("./rpc-manager.ts"); const transport = scriptedTransport("s-bounded"); // The kill waits in the link outbox: the child exits only once the link returns. transport.endInput = () => {}; @@ -3402,7 +3361,7 @@ test("disposing a session whose host goes offline mid-wait returns instead of wa }); test("a resume that failed while its host went offline blocks a retry until its child exits", async (t) => { - const { startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { startRpcSession } = await import("./rpc-manager.ts"); const id = "11111111-2222-4333-8444-aaaaaaaaaaaa"; const sessionFile = `/remote/sessions/${id}.jsonl`; const first = scriptedTransport(id); @@ -3505,7 +3464,7 @@ const hostToolResults = (transport) => transport.frames.filter((frame) => frame. const flushWrites = () => new Promise((resolve) => setImmediate(resolve)); test("adoptRpcSession re-syncs a live child with no spawn and no ready wait", async (t) => { - const { adoptRpcSession, getExitedRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { adoptRpcSession, getExitedRpcSession, getRpcSession } = await import("./rpc-manager.ts"); const id = "11111111-2222-4333-8444-adadadadad01"; // A crash record from before the restart. globalThis.__ompExitedSessions ??= new Map(); @@ -3526,7 +3485,7 @@ test("adoptRpcSession re-syncs a live child with no spawn and no ready wait", as }); test("an adopted child's open requests come back: an ask for the next tab, a host tool call for an open tab", async (t) => { - const { adoptRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { adoptRpcSession } = await import("./rpc-manager.ts"); const id = "11111111-2222-4333-8444-adadadadad02"; const transport = adoptedTransport(id); const calls = []; @@ -3556,7 +3515,7 @@ test("an adopted child's open requests come back: an ask for the next tab, a hos }); test("with no tab open at hello, host tool calls wait for the first tab to attach until a tab registers its tools", async (t) => { - const { adoptRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { adoptRpcSession } = await import("./rpc-manager.ts"); const id = "11111111-2222-4333-8444-adadadadad04"; const transport = adoptedTransport(id); const call = { type: "host_tool_call", id: "h1", toolName: "open_url", arguments: { url: "https://a.test" } }; @@ -3589,7 +3548,7 @@ test("with no tab open at hello, host tool calls wait for the first tab to attac }); test("a replayed host tool call no tab comes back for is settled after the disconnect window", async (t) => { - const { adoptRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { adoptRpcSession } = await import("./rpc-manager.ts"); const id = "11111111-2222-4333-8444-adadadadad05"; const transport = adoptedTransport(id); t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: Date.now() }); @@ -3606,7 +3565,7 @@ test("a replayed host tool call no tab comes back for is settled after the disco }); test("replayed server agent tools that change things are not run twice; list_sessions is", async (t) => { - const { adoptRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { adoptRpcSession } = await import("./rpc-manager.ts"); const { until } = await import("./hosts/link-driver.test-helper.mjs"); globalThis.__ompWebSettingsCache = undefined; const settingsPath = join(isolatedAgentDir, "omp-web-settings.json"); @@ -3634,7 +3593,7 @@ test("replayed server agent tools that change things are not run twice; list_ses }); test("an agent tool omp called during the adoption handshake is live, not replayed", async (t) => { - const { adoptRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { adoptRpcSession } = await import("./rpc-manager.ts"); // The gate is off: a live call gets the gate's answer, a replayed one "outcome unknown". globalThis.__ompWebSettingsCache = undefined; t.after(() => { globalThis.__ompWebSettingsCache = undefined; }); @@ -3652,7 +3611,7 @@ test("an agent tool omp called during the adoption handshake is live, not replay }); test("an internal turn waiter neither takes an adopted session's parked host calls nor settles them", async (t) => { - const { adoptRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { adoptRpcSession } = await import("./rpc-manager.ts"); const id = "11111111-2222-4333-8444-adadadadad0b"; const transport = adoptedTransport(id); const call = { type: "host_tool_call", id: "h1", toolName: "open_url", arguments: {} }; @@ -3672,7 +3631,7 @@ test("an internal turn waiter neither takes an adopted session's parked host cal }); test("a start during adoption joins it; an adopted child is not replaced over --advisor, and a second child is refused", async (t) => { - const { adoptRpcSession, getRpcSession, startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { adoptRpcSession, getRpcSession, startRpcSession } = await import("./rpc-manager.ts"); const { until } = await import("./hosts/link-driver.test-helper.mjs"); const id = "11111111-2222-4333-8444-adadadadad07"; const sessionFile = `/nonexistent/${id}.jsonl`; @@ -3699,7 +3658,7 @@ test("a start during adoption joins it; an adopted child is not replaced over -- }); test("an adopted child that turns out to run a session another wrapper holds is killed, not registered", async (t) => { - const { adoptRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { adoptRpcSession, getRpcSession } = await import("./rpc-manager.ts"); const holderId = "11111111-2222-4333-8444-adadadadad0c"; const listedId = "11111111-2222-4333-8444-adadadadad0d"; const first = adoptedTransport(holderId); @@ -3717,7 +3676,7 @@ test("an adopted child that turns out to run a session another wrapper holds is }); test("an adoption whose get_state times out rejects and kills the child", async (t) => { - const { adoptRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { adoptRpcSession, getRpcSession } = await import("./rpc-manager.ts"); const id = "11111111-2222-4333-8444-adadadadad03"; const transport = adoptedTransport(id, { silent: ["get_state"] }); const asked = Promise.withResolvers(); @@ -3736,7 +3695,7 @@ test("an adoption whose get_state times out rejects and kills the child", async }); test("an adoption that failed while its host went offline blocks a start until its child exits", async (t) => { - const { adoptRpcSession, getRpcSession, startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { adoptRpcSession, getRpcSession, startRpcSession } = await import("./rpc-manager.ts"); const { until } = await import("./hosts/link-driver.test-helper.mjs"); const id = "11111111-2222-4333-8444-adadadadad08"; const sessionFile = `/nonexistent/${id}.jsonl`; @@ -3770,8 +3729,8 @@ test("an adoption that failed while its host went offline blocks a start until i }); test("an adoption whose output outgrows channelBufferBytes before the replay fails and kills the child", async (t) => { - const { adoptRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); - const { LINK_LIMITS } = await runtimeJiti.import("./hosts/link-protocol.ts"); + const { adoptRpcSession, getRpcSession } = await import("./rpc-manager.ts"); + const { LINK_LIMITS } = await import("./hosts/link-protocol.ts"); const saved = LINK_LIMITS.channelBufferBytes; LINK_LIMITS.channelBufferBytes = 1_000; t.after(() => { LINK_LIMITS.channelBufferBytes = saved; }); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 160e6235e..0306941da 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -510,7 +510,7 @@ export class AgentSessionWrapper { } /** A remote link that dropped this child's buffered output asks for a reconcile. - * Duck-typed: route bundles and instrumentation load separate hub modules. */ + * Duck-typed: a `bun --hot` re-evaluation can leave live transports on an older class. */ private watchResync(proc: RpcProcess): void { proc.transport?.onResync?.(() => { if (this.proc === proc) void this.reconcileAfterGap(); @@ -2545,7 +2545,7 @@ export async function restartAllRpcSessions(): Promise { // Pushes the current set of running session ids to subscribers whenever any // session's running state may have changed. This lets the sidebar receive live // updates over SSE instead of polling. Listeners live on globalThis so they -// survive Next.js hot-reload. +// survive a `bun --hot` re-evaluation. // ---------------------------------------------------------------------------- function getRunningListeners(): Set<(update: RunningSessionUpdate) => void> { diff --git a/lib/security-headers.test.mjs b/lib/security-headers.test.mjs deleted file mode 100644 index 049470a00..000000000 --- a/lib/security-headers.test.mjs +++ /dev/null @@ -1,73 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { createRequire } from "node:module"; -import { createJiti } from "jiti"; - -// The effective policy for a response is decided by next.config's headers() -// rules, not by the route handler: Next applies config headers last, so a -// config rule matching the same key overwrites what a handler set. These tests -// resolve the rules the way Next does (its own path matcher, later rule wins -// per key), so a regression that re-broadens the global rule fails here instead -// of silently disabling the per-content-type policy in the files route. -const require = createRequire(import.meta.url); -// Same matcher and options Next uses for header rules, see -// node_modules/next/dist/server/lib/router-utils/filesystem.js buildCustomRoute. -// The expectations below were cross-checked against a running dev server: an -// SVG file response carries only the handler policy, while / and -// /api/file-index carry the global one. -const { getPathMatch } = require("next/dist/shared/lib/router/utils/path-match"); -// next.config.ts resolves bare specifiers such as `next/constants` the CommonJS -// way, which plain Node ESM cannot do, so load it through jiti like the -// component tests do. -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); -const { PHASE_DEVELOPMENT_SERVER, PHASE_PRODUCTION_BUILD } = await jiti.import("next/constants"); -const nextConfig = await jiti.import("../next.config.ts", { default: true }); - -async function effectiveHeaders(phase, pathname) { - const rules = await nextConfig(phase).headers(); - const resolved = new Map(); - for (const rule of rules) { - const matches = getPathMatch(rule.source, { removeUnnamedParams: true, strict: true })(pathname); - if (matches === false) continue; - for (const { key, value } of rule.headers) resolved.set(key.toLowerCase(), value); - } - return resolved; -} - -const FILE_RESPONSE_PATHS = [ - "/api/files/home/user/project/logo.svg", - "/api/files/home/user/project/docs/report.docx", - "/api/files/C%3A/Users/me/project/logo.svg", -]; - -for (const phase of [PHASE_PRODUCTION_BUILD, PHASE_DEVELOPMENT_SERVER]) { - test(`config leaves the document policy of file responses to the route handler (${phase})`, async () => { - for (const pathname of FILE_RESPONSE_PATHS) { - const headers = await effectiveHeaders(phase, pathname); - // A config-level CSP here would overwrite the script-blocking policy the - // route handler sets for SVG, and the DOCX preview policy with it. - assert.equal( - headers.get("content-security-policy"), - undefined, - `${pathname} must not receive a config-level Content-Security-Policy`, - ); - // Handler-agnostic protections must still arrive. - assert.equal(headers.get("x-content-type-options"), "nosniff", pathname); - assert.equal(headers.get("referrer-policy"), "no-referrer", pathname); - assert.match(headers.get("permissions-policy") ?? "", /camera=\(\)/, pathname); - // The app frames its own DOCX/PDF previews; DENY would block them. - assert.equal(headers.get("x-frame-options"), "SAMEORIGIN", pathname); - } - }); - - test(`every other route keeps the global security headers (${phase})`, async () => { - for (const pathname of ["/", "/login", "/api/file-index", "/api/sessions", "/api/files"]) { - const headers = await effectiveHeaders(phase, pathname); - const csp = headers.get("content-security-policy"); - assert.ok(csp, `${pathname} must keep the global Content-Security-Policy`); - assert.match(csp, /default-src 'self'/, pathname); - assert.match(csp, /frame-ancestors 'none'/, pathname); - assert.equal(headers.get("x-content-type-options"), "nosniff", pathname); - } - }); -} diff --git a/lib/self-update.test.mjs b/lib/self-update.test.mjs index ec0841c94..9a536e61c 100644 --- a/lib/self-update.test.mjs +++ b/lib/self-update.test.mjs @@ -3,20 +3,16 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod import { join } from "node:path"; import { tmpdir } from "node:os"; import test from "node:test"; -import { createJiti } from "jiti"; +import { promisify } from "node:util"; +import { mockBuiltin } from "../tests/mock-builtin.mjs"; -const jiti = createJiti(import.meta.url, { - alias: { - "@/": new URL("../", import.meta.url).pathname, - }, -}); const { getSelfUpdateStatus, markSelfUpdateStopping, parseSystemdServiceCgroup, resolveSelfUpdateTempRoot, validateCommitSelfUpdate, -} = await jiti.import("./self-update.ts"); +} = await import("./self-update.ts"); test("parseSystemdServiceCgroup finds system and user services, and nothing outside one", () => { assert.deepEqual(parseSystemdServiceCgroup("0::/system.slice/ompweb-api.service\n"), { unit: "ompweb-api.service", user: false }); @@ -114,3 +110,55 @@ test("starting a commit renews the lease, so a late commit is not reported as lo assert.ok(JSON.parse(readFileSync(leaseFile, "utf8")).expiresAt > Date.now() + 10 * 60_000); assert.equal(getSelfUpdateStatus("app").state, "running"); }); + +// commitSelfUpdate spawns its worker detached: record the spawn instead of running one. +let freshImport = 0; + +async function commitAndCaptureSpawn(t, { nodeBin, systemd = false }) { + const { attemptId } = withUpdateState(t, { state: "prepared", leaseExpiresAt: Date.now() + 60_000 }); + const previous = process.env.OMP_WEB_NODE_BIN; + if (nodeBin === undefined) delete process.env.OMP_WEB_NODE_BIN; + else process.env.OMP_WEB_NODE_BIN = nodeBin; + t.after(() => { + if (previous === undefined) delete process.env.OMP_WEB_NODE_BIN; + else process.env.OMP_WEB_NODE_BIN = previous; + }); + const spawns = []; + const spawn = (command, args) => { + spawns.push({ command, args }); + return { once() {}, unref() {}, pid: 2 ** 30 }; + }; + // The execFile fake reports this process as the unit's MainPID, so the systemd branch applies to it. + const execFile = Object.assign(() => { throw new Error("execFile without promisify"); }, { + [promisify.custom]: async (command) => ({ stdout: command === "systemctl" ? `${process.pid}\n` : "" }), + }); + await mockBuiltin(t, "node:child_process", { spawn, execFile }); + // Pin the cgroup: the test may itself run inside a systemd service. + const cgroup = systemd ? "0::/system.slice/ompweb-api.service\n" : "0::/user.slice/user-1000.slice/session-3.scope\n"; + const { readFileSync: realReadFileSync } = await import("node:fs"); + await mockBuiltin(t, "node:fs", { + readFileSync: (path, ...rest) => (path === "/proc/self/cgroup" ? cgroup : realReadFileSync(path, ...rest)), + }); + const { commitSelfUpdate } = await import(`./self-update.ts?fresh=${freshImport++}`); + await commitSelfUpdate(attemptId, "app"); + assert.equal(spawns.length, 1); + return spawns[0]; +} + +test("the update worker runs on OMP_WEB_NODE_BIN, not on the server's own runtime", async (t) => { + const { command } = await commitAndCaptureSpawn(t, { nodeBin: "/opt/node/bin/node" }); + assert.equal(command, "/opt/node/bin/node"); +}); + +test("the update worker falls back to the server's runtime without OMP_WEB_NODE_BIN", async (t) => { + const { command } = await commitAndCaptureSpawn(t, {}); + assert.equal(command, process.execPath); +}); + +test("the update worker inside systemd-run's scope runs on OMP_WEB_NODE_BIN", { skip: process.platform !== "linux" }, async (t) => { + const { command, args } = await commitAndCaptureSpawn(t, { nodeBin: "/opt/node/bin/node", systemd: true }); + assert.equal(command, "systemd-run"); + assert.ok(args.includes("--scope")); + assert.equal(args[args.indexOf("--no-ask-password") + 1], "/opt/node/bin/node"); + assert.ok(!args.includes(process.execPath)); +}); diff --git a/lib/self-update.ts b/lib/self-update.ts index 09c5c72d1..dc40d2f0a 100644 --- a/lib/self-update.ts +++ b/lib/self-update.ts @@ -345,10 +345,11 @@ async function detectSystemdService(launcherPid: number): Promise { assertUpdatesEnabled(); + // The compiled binary has no npm install to replace and no runtime for the worker: its updates run from a terminal. + if (Bun.isStandaloneExecutable) { + throw new SelfUpdateError("self_update_unsupported", "In-app updates are not available in the ompweb binary: update from a terminal", 409); + } cleanupStaleSelfUpdate(Date.now(), kind); ensureSecureRoot(kind, true); const leaseFile = leasePath(kind); @@ -409,12 +414,7 @@ export async function prepareSelfUpdate(kind: Kind = "app"): Promise { + await mockBuiltin(t, "node:fs", { watch: (watchedDir, options, callback) => { assert.equal(watchedDir, sessionsDir); assert.deepEqual(options, { recursive: true, persistent: false }); onChange = callback; return watcher; - }); - syncBuiltinESMExports(); - t.after(() => { watchMock.mock.restore(); syncBuiltinESMExports(); }); - const isolated = createJiti(import.meta.url, { moduleCache: false, tryNative: false }); - const { subscribeSessionFileChanges: subscribeKnownChanges } = await isolated.import("./session-watcher.ts"); + } }); + const { subscribeSessionFileChanges: subscribeKnownChanges } = await import(`./session-watcher.ts?fresh=${isolatedFresh++}`); t.mock.timers.enable({ apis: ["setTimeout"] }); const notified = []; @@ -1194,6 +1190,8 @@ test("native watcher refreshes a session after content appends", { timeout: 1500 writeFileSync(filePath, fixture); await setImmediate(undefined, { signal: t.signal }); } + // Bun drops a native event that follows the previous one within a few milliseconds. + await new Promise((resolve) => setTimeout(resolve, 50)); getSessionEntries(filePath); assert.equal(globalThis.__ompSessionEntriesCache?.has(sessionPathKey(filePath)), true); const changed = (async () => { @@ -1364,14 +1362,11 @@ test("history catch-up pages persisted IDs contiguously without resolving old bl ]); const blobReads = []; const originalRead = fs.readFileSync; - const readMock = t.mock.method(fs, "readFileSync", (path, ...args) => { + await mockBuiltin(t, "node:fs", { readFileSync: (path, ...args) => { if (String(path) === blobPath) blobReads.push(String(path)); return originalRead(path, ...args); - }); - syncBuiltinESMExports(); - t.after(() => { readMock.mock.restore(); syncBuiltinESMExports(); }); - const isolated = createJiti(import.meta.url, { moduleCache: false, tryNative: false }); - const { getSessionHistoryPage: readPage } = await isolated.import("./session-reader.ts"); + } }); + const { getSessionHistoryPage: readPage } = await import(`./session-reader.ts?fresh=${isolatedFresh++}`); const first = readPage(filePath, null, 1); assert.deepEqual(blobReads, [blobPath], "positive control: the observer sees a real image-page blob read"); blobReads.length = 0; @@ -1448,27 +1443,28 @@ test("history pages seek only new bodies even above the raw-cache budget", async // Report a >256 MiB file, but perform every observed read on the small // physical fixture. Both stat paths describe the same artificial version. const reported = (stat) => Object.assign(stat, { size: 256 * 1024 * 1024 + 1 }); - const mocks = [ - t.mock.method(fs, "openSync", (path, ...args) => { + await mockBuiltin(t, "node:fs", { + openSync: (path, ...args) => { const fd = original.open(path, ...args); if (String(path) === filePath) fds.add(fd); return fd; - }), - t.mock.method(fs, "closeSync", (fd) => { fds.delete(fd); return original.close(fd); }), - t.mock.method(fs, "statSync", (path, ...args) => { + }, + closeSync: (fd) => { fds.delete(fd); return original.close(fd); }, + statSync: (path, ...args) => { const stat = original.stat(path, ...args); return String(path) === filePath ? reported(stat) : stat; - }), - t.mock.method(fs, "fstatSync", (fd, ...args) => { + }, + fstatSync: (fd, ...args) => { const stat = original.fstat(fd, ...args); return fds.has(fd) ? reported(stat) : stat; - }), - t.mock.method(fs, "readSync", (fd, buffer, offset, length, position) => { + }, + readSync: (fd, buffer, offset, length, position) => { const count = original.read(fd, buffer, offset, length, position); if (fds.has(fd) && count > 0) reads.push({ position, count, text: buffer.subarray(offset, offset + count).toString("utf8") }); return count; - }), - t.mock.method(JSON, "parse", (text, ...args) => { + }, + }); + const parseMock = t.mock.method(JSON, "parse", (text, ...args) => { const value = original.parse(text, ...args); if (value?.type === "message" && entryIds.has(value.id)) { const content = value.message.content; @@ -1478,12 +1474,9 @@ test("history pages seek only new bodies even above the raw-cache budget", async }); } return value; - }), - ]; - syncBuiltinESMExports(); - t.after(() => { for (const mock of mocks) mock.mock.restore(); syncBuiltinESMExports(); }); - const isolated = createJiti(import.meta.url, { moduleCache: false, tryNative: false }); - const { getSessionHistoryPage: readPage } = await isolated.import("./session-reader.ts"); + }); + t.after(() => parseMock.mock.restore()); + const { getSessionHistoryPage: readPage } = await import(`./session-reader.ts?fresh=${isolatedFresh++}`); const first = readPage(filePath, null, 1); assert.ok(reads.some((read) => read.position === null && read.text.includes('"page-three"')), "positive control: index construction scanned the real fixture"); assert.deepEqual([...touchedBodies], ["page-one"], "indexing does not transform off-page bodies"); @@ -1537,23 +1530,24 @@ test("active-context boundaries reuse the history index without reading or hydra const blobReads = []; const touchedBodies = new Set(); const original = { open: fs.openSync, close: fs.closeSync, read: fs.readSync, readFile: fs.readFileSync, parse: JSON.parse }; - const mocks = [ - t.mock.method(fs, "openSync", (path, ...args) => { + await mockBuiltin(t, "node:fs", { + openSync: (path, ...args) => { const fd = original.open(path, ...args); if (String(path) === filePath) fds.add(fd); return fd; - }), - t.mock.method(fs, "closeSync", (fd) => { fds.delete(fd); return original.close(fd); }), - t.mock.method(fs, "readSync", (fd, buffer, offset, length, position) => { + }, + closeSync: (fd) => { fds.delete(fd); return original.close(fd); }, + readSync: (fd, buffer, offset, length, position) => { const count = original.read(fd, buffer, offset, length, position); if (fds.has(fd) && count > 0) reads.push({ position, count }); return count; - }), - t.mock.method(fs, "readFileSync", (path, ...args) => { + }, + readFileSync: (path, ...args) => { if (String(path) === blobPath) blobReads.push(String(path)); return original.readFile(path, ...args); - }), - t.mock.method(JSON, "parse", (text, ...args) => { + }, + }); + const parseMock = t.mock.method(JSON, "parse", (text, ...args) => { const value = original.parse(text, ...args); if (value?.type === "message" && entries.some((entry) => entry.id === value.id)) { const content = value.message.content; @@ -1563,12 +1557,9 @@ test("active-context boundaries reuse the history index without reading or hydra }); } return value; - }), - ]; - syncBuiltinESMExports(); - t.after(() => { for (const mock of mocks) mock.mock.restore(); syncBuiltinESMExports(); }); - const isolated = createJiti(import.meta.url, { moduleCache: false, tryNative: false }); - const { getSessionContextBoundary: readBoundary, getSessionHistoryPage: readPage } = await isolated.import("./session-reader.ts"); + }); + t.after(() => parseMock.mock.restore()); + const { getSessionContextBoundary: readBoundary, getSessionHistoryPage: readPage } = await import(`./session-reader.ts?fresh=${isolatedFresh++}`); assert.deepEqual(readBoundary(filePath), { entryIds: expected }); assert.ok(reads.some((read) => read.position === null), "positive control: a cold boundary scans the real file"); assert.deepEqual([...touchedBodies], [], "index projection does not hydrate message content"); @@ -1770,15 +1761,12 @@ test("an over-budget metadata index is not retained and does not evict cached pe ]); let scannedBytes = 0; const originalRead = fs.readSync; - const readMock = t.mock.method(fs, "readSync", (fd, buffer, offset, length, position) => { + await mockBuiltin(t, "node:fs", { readSync: (fd, buffer, offset, length, position) => { const count = originalRead(fd, buffer, offset, length, position); if (position === null) scannedBytes += count; return count; - }); - syncBuiltinESMExports(); - t.after(() => { readMock.mock.restore(); syncBuiltinESMExports(); }); - const isolated = createJiti(import.meta.url, { moduleCache: false, tryNative: false }); - const { getSessionHistoryPage: readPage } = await isolated.import("./session-reader.ts"); + } }); + const { getSessionHistoryPage: readPage } = await import(`./session-reader.ts?fresh=${isolatedFresh++}`); const peerFirst = readPage(peer, null, 1); scannedBytes = 0; const first = readPage(filePath, null, 1); @@ -1802,18 +1790,15 @@ test("history never advances a cursor through offsets invalidated during a real const first = getSessionHistoryPage(filePath, null, 1); const originalRead = fs.readSync; let changed = false; - const readMock = t.mock.method(fs, "readSync", (fd, buffer, offset, length, position) => { + await mockBuiltin(t, "node:fs", { readSync: (fd, buffer, offset, length, position) => { const count = originalRead(fd, buffer, offset, length, position); if (!changed && position !== null && buffer.subarray(offset, offset + count).toString("utf8").includes('"id":"two"')) { changed = true; appendFileSync(filePath, JSON.stringify(userEntry("three", "two", "newer")) + "\n"); } return count; - }); - syncBuiltinESMExports(); - t.after(() => { readMock.mock.restore(); syncBuiltinESMExports(); }); - const isolated = createJiti(import.meta.url, { moduleCache: false, tryNative: false }); - const { getSessionHistoryPage: readPage } = await isolated.import("./session-reader.ts"); + } }); + const { getSessionHistoryPage: readPage } = await import(`./session-reader.ts?fresh=${isolatedFresh++}`); assert.throws(() => readPage(filePath, first.history.cursor, 1), /Session changed/); assert.equal(changed, true, "positive control: mutation happened inside the actual page read"); const recovered = readPage(filePath, first.history.cursor, 2); diff --git a/lib/session-resume.test.mjs b/lib/session-resume.test.mjs index d4758622a..55df36082 100644 --- a/lib/session-resume.test.mjs +++ b/lib/session-resume.test.mjs @@ -5,20 +5,18 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; import { setTimeout as sleep } from "node:timers/promises"; -import { createJiti } from "jiti"; import { LinkDriver, linkLocalHost, listedSession, ompChild, until } from "./hosts/link-driver.test-helper.mjs"; -const jiti = createJiti(import.meta.url); /** A new omp-web process: fresh tracker, same agent dir. */ function restart() { globalThis.__ompResumeTracker = undefined; } -const { EXIT_GRACE_MS, markShuttingDown, recordRunningSessions, RESUME_PROMPT, resumeOnHostLink, takeInterruptedSessions } = await jiti.import("./session-resume.ts"); -const { saveWebServerSettings } = await jiti.import("./web-settings.ts"); -const hub = await jiti.import("./hosts/hub.ts"); -const { createHost } = await jiti.import("./hosts/registry.ts"); -const { getRpcSession, resumeInterruptedSessions } = await jiti.import("./rpc-manager.ts"); +const { EXIT_GRACE_MS, markShuttingDown, recordRunningSessions, RESUME_PROMPT, resumeOnHostLink, takeInterruptedSessions } = await import("./session-resume.ts"); +const { saveWebServerSettings } = await import("./web-settings.ts"); +const hub = await import("./hosts/hub.ts"); +const { createHost } = await import("./hosts/registry.ts"); +const { getRpcSession, resumeInterruptedSessions } = await import("./rpc-manager.ts"); /** Fresh agent dir and tracker per test; the resume setting starts as given. */ function setup(t, { enabled }) { diff --git a/lib/session-resume.ts b/lib/session-resume.ts index 2c1911e6c..e4db46094 100644 --- a/lib/session-resume.ts +++ b/lib/session-resume.ts @@ -37,9 +37,9 @@ declare global { var __ompResumeTracker: TrackerState | undefined; } -// On globalThis so it survives Next.js hot-reload and is shared by every -// bundle that imports this module. Created on first use, which claims the -// previous runs' lists before anything in this run can overwrite them. +// On globalThis so it survives a `bun --hot` re-evaluation. Created on first +// use, which claims the previous runs' lists before anything in this run can +// overwrite them. function tracker(): TrackerState { globalThis.__ompResumeTracker ??= { leftover: readLeftover(), sessions: new Map(), drops: new Map(), shuttingDown: false }; return globalThis.__ompResumeTracker; diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index a35871d2a..936502819 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -4,27 +4,20 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { gzipSync } from "node:zlib"; import test from "node:test"; -import { createJiti } from "jiti"; -import { fileURLToPath } from "node:url"; import { linkLocalDaemon } from "./hosts/link-driver.test-helper.mjs"; -const jiti = createJiti(import.meta.url, { - alias: { - "@/": fileURLToPath(new URL("../", import.meta.url)), - }, -}); -const sessionRoute = await jiti.import("../app/api/sessions/[id]/route.ts"); -const contextRoute = await jiti.import("../app/api/sessions/[id]/context/route.ts"); -const importRoute = await jiti.import("../app/api/sessions/import/route.ts"); -const archiveRoute = await jiti.import("../app/api/sessions/archive/route.ts"); -const exportRoute = await jiti.import("../app/api/sessions/[id]/export/route.ts"); -const stateRoute = await jiti.import("../app/api/sessions/[id]/state/route.ts"); -const autoNameRoute = await jiti.import("../app/api/sessions/[id]/auto-name/route.ts"); -const { cacheSessionPath, invalidateSessionListCache, listAllSessions, resolveSessionPath } = await jiti.import("./session-reader.ts"); -const { allowFileRoot, normalizeSlashes } = await jiti.import("./file-access.ts"); -const { AgentSessionWrapper, WebRpcError } = await jiti.import("./rpc-manager.ts"); -const { closeHostLink, getHost } = await jiti.import("./hosts/hub.ts"); -const { listSessionsAllHosts } = await jiti.import("./hosts/session-index.ts"); +const sessionRoute = await import("../app/api/sessions/[id]/route.ts"); +const contextRoute = await import("../app/api/sessions/[id]/context/route.ts"); +const importRoute = await import("../app/api/sessions/import/route.ts"); +const archiveRoute = await import("../app/api/sessions/archive/route.ts"); +const exportRoute = await import("../app/api/sessions/[id]/export/route.ts"); +const stateRoute = await import("../app/api/sessions/[id]/state/route.ts"); +const autoNameRoute = await import("../app/api/sessions/[id]/auto-name/route.ts"); +const { cacheSessionPath, invalidateSessionListCache, listAllSessions, resolveSessionPath } = await import("./session-reader.ts"); +const { allowFileRoot, normalizeSlashes } = await import("./file-access.ts"); +const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); +const { closeHostLink, getHost } = await import("./hosts/hub.ts"); +const { listSessionsAllHosts } = await import("./hosts/session-index.ts"); const getContext = (id, query = "") => contextRoute.GET( new Request(`http://localhost/api/sessions/${id}/context${query ? `?${query}` : ""}`), @@ -503,7 +496,7 @@ test("boundary preserves malformed-header and oversized-file errors", async () = }); test("sync samples current live output after the history read and excludes pinned historical views", async () => { - const { sessionOps } = await jiti.import("./hosts/session-ops.ts"); + const { sessionOps } = await import("./hosts/session-ops.ts"); let emit; let emittedDuringRead = false; // The history read is this machine's daemon op: output arriving while it runs must reach the response. @@ -674,7 +667,7 @@ test("sidebar rename cannot fall back to disk while Edit owns the session", asyn const commands = []; const state = { sessionId: id, sessionFile: filePath, isStreaming: false, isCompacting: false, queuedMessageCount: 0, isSettled: true }; const { promise: started, resolve: didStart } = Promise.withResolvers(); - const { setSessionTitle } = await jiti.import("./omp/session-files.ts"); + const { setSessionTitle } = await import("./omp/session-files.ts"); let editRequest; const wrapper = new AgentSessionWrapper({ isAlive: true, diff --git a/lib/session-search.test.mjs b/lib/session-search.test.mjs index 20a60b08f..41d2a61b7 100644 --- a/lib/session-search.test.mjs +++ b/lib/session-search.test.mjs @@ -3,11 +3,9 @@ import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { compileSearchQuery, scoreSearchFields, searchField, TITLE_WEIGHT, CONTENT_WEIGHT } = await jiti.import("./session-search.ts"); -const { MAX_CONTENT_CACHE_ENTRIES, transcriptField } = await jiti.import("./session-content-search.ts"); +const { compileSearchQuery, scoreSearchFields, searchField, TITLE_WEIGHT, CONTENT_WEIGHT } = await import("./session-search.ts"); +const { MAX_CONTENT_CACHE_ENTRIES, transcriptField } = await import("./session-content-search.ts"); const score = (query, title, content = "") => scoreSearchFields([searchField(title, TITLE_WEIGHT), searchField(content, CONTENT_WEIGHT)], compileSearchQuery(query)); diff --git a/lib/session-title.test.mjs b/lib/session-title.test.mjs index dcb899947..641554ba0 100644 --- a/lib/session-title.test.mjs +++ b/lib/session-title.test.mjs @@ -1,10 +1,8 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); const { deriveSessionTitleFromFirstMessage, sanitizeSessionTitle } = - await jiti.import("./session-title.ts"); + await import("./session-title.ts"); test("sanitizes titles to a single clean line", () => { assert.equal(sanitizeSessionTitle("Fix the race\nin SSE reconnect"), "Fix the race"); diff --git a/lib/sidebar-history-bridge.ts b/lib/sidebar-history-bridge.ts index af8e74971..eb81efdbe 100644 --- a/lib/sidebar-history-bridge.ts +++ b/lib/sidebar-history-bridge.ts @@ -1,7 +1,6 @@ /** - * Injected with `beforeInteractive` (see app/layout.tsx) so it runs before - * hydration, and therefore before the App Router registers its own `popstate` - * listener. + * Injected by app/boot.ts before the app's modules evaluate, so it registers + * before any other `popstate` listener (lib/navigation.ts included). * * The re-dispatch is synchronous and carries the original event as `detail`, * so the sidebar hook can call `stopImmediatePropagation()` on the native event diff --git a/lib/skill-diagnostics.test.mjs b/lib/skill-diagnostics.test.mjs index 143355992..45e657051 100644 --- a/lib/skill-diagnostics.test.mjs +++ b/lib/skill-diagnostics.test.mjs @@ -1,9 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { parseSkillDiagnosticsSnapshot } = await jiti.import("./skill-diagnostics.ts"); +const { parseSkillDiagnosticsSnapshot } = await import("./skill-diagnostics.ts"); const publicSnapshot = { cwd: "/workspace", diff --git a/lib/skill-lock.test.mjs b/lib/skill-lock.test.mjs index d6270a7d4..e94677d2b 100644 --- a/lib/skill-lock.test.mjs +++ b/lib/skill-lock.test.mjs @@ -3,11 +3,9 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); const { annotateSkillsWithInstallInfo, getGlobalSkillsLockPath } = - await jiti.import("./skill-lock.ts"); + await import("./skill-lock.ts"); function writeJson(path, value) { writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, "utf8"); diff --git a/lib/skill-updates.test.mjs b/lib/skill-updates.test.mjs index a052491a2..05298d5c1 100644 --- a/lib/skill-updates.test.mjs +++ b/lib/skill-updates.test.mjs @@ -1,14 +1,12 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); const { buildSkillUpdateArgs, checkSkillUpdate, checkSkillUpdates, skillUpdateKey, -} = await jiti.import("./skill-updates.ts"); +} = await import("./skill-updates.ts"); function install(overrides = {}) { return { diff --git a/lib/skills-service.test.mjs b/lib/skills-service.test.mjs index 10f028a9c..3618598fa 100644 --- a/lib/skills-service.test.mjs +++ b/lib/skills-service.test.mjs @@ -3,12 +3,8 @@ import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSy import { homedir, tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; import { parse as parseYaml } from "yaml"; -// skills-service.ts imports via the "@/" path alias, which jiti resolves only -// when it is told the project root. -const jiti = createJiti(import.meta.url, { alias: { "@": new URL("..", import.meta.url).pathname.replace(/\/$/, "") } }); const { discoverSkills, getSkillScanRootDirs, @@ -18,10 +14,10 @@ const { readDisableModelInvocation, setDisableModelInvocation, skillsFromCliPayload, -} = await jiti.import("./skills-service.ts"); +} = await import("./skills-service.ts"); // The toggle route authorizes existing files through the consolidated facade. -const { allowFileRoot, getAllowedFileRoots, isExistingFilePathAllowed } = await jiti.import("./file-access.ts"); -const { PATCH } = await jiti.import("../app/api/skills/route.ts"); +const { allowFileRoot, getAllowedFileRoots, isExistingFilePathAllowed } = await import("./file-access.ts"); +const { PATCH } = await import("../app/api/skills/route.ts"); /** Fake omp: a shell script (POSIX) or .cmd launcher (Windows). */ function writeStubOmp(dir, posixBody, cmdBody) { diff --git a/lib/speech-sanitizer.test.mjs b/lib/speech-sanitizer.test.mjs index 5ca043ff0..1de25c36c 100644 --- a/lib/speech-sanitizer.test.mjs +++ b/lib/speech-sanitizer.test.mjs @@ -1,9 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { sanitizeTextForSpeech } = await jiti.import("./speech-sanitizer.ts"); +const { sanitizeTextForSpeech } = await import("./speech-sanitizer.ts"); test("sanitizeTextForSpeech handles empty or falsy inputs", () => { assert.equal(sanitizeTextForSpeech(""), ""); diff --git a/lib/stt-jobs.ts b/lib/stt-jobs.ts index 1aa991173..9b7f536ea 100644 --- a/lib/stt-jobs.ts +++ b/lib/stt-jobs.ts @@ -1,7 +1,27 @@ import { randomUUID } from "node:crypto"; -import type { SttAfter, SttConfig } from "@/lib/stt"; +import type { SttAfter } from "@/lib/stt"; import { authGatewayRequest } from "@/lib/omp/auth-gateway"; +function cleanEnvVar(val?: string): string | undefined { + const cleaned = val?.replace(/\\n|[\r\n]/g, "").trim(); + return cleaned || undefined; +} + +export interface SttConfig { + /** Unset: transcribe with `model` (an omp model selector) through omp's auth gateway. */ + endpoint: string | undefined; + apiKey: string | undefined; + model: string | undefined; +} + +/** STT settings from OMP_WEB_STT_*; null when neither an endpoint nor a model is configured. Server-only: lib/stt.ts is shared with the browser. */ +export function readSttConfig(): SttConfig | null { + const endpoint = cleanEnvVar(process.env.OMP_WEB_STT_ENDPOINT); + const model = cleanEnvVar(process.env.OMP_WEB_STT_MODEL); + if (!endpoint && !model) return null; + return { endpoint, apiKey: cleanEnvVar(process.env.OMP_WEB_STT_KEY), model }; +} + /** * Server-owned transcription jobs. POST /api/stt starts one and returns its id * at once; browsers poll GET /api/stt/[jobId]. The server holds the slow @@ -44,9 +64,8 @@ export interface SttClaim extends SttJobView { } /** - * Cap on how long the server waits on the STT endpoint. Kept under undici's - * default 300s headersTimeout so a slow upstream ends as "timed out", not - * an opaque "fetch failed". + * Cap on how long the server waits on the STT endpoint, so a slow upstream + * ends as "timed out", not an opaque "fetch failed". */ const STT_UPSTREAM_TIMEOUT_MS = 290_000; /** Unclaimed results and failures (with their audio) stay retrievable this long. */ @@ -71,8 +90,7 @@ const MAX_LIVE_JOBS = 20; const MAX_TOMBSTONES = 20; declare global { - // globalThis survives Next.js hot reload and is shared by the separately - // bundled /api/stt route handlers; a module-level Map is neither. + // globalThis survives a `bun --hot` re-evaluation; a module-level Map does not. var __ompSttJobs: Map | undefined; } diff --git a/lib/stt-omp-gateway.test.mjs b/lib/stt-omp-gateway.test.mjs index b226a14aa..2c16d4779 100644 --- a/lib/stt-omp-gateway.test.mjs +++ b/lib/stt-omp-gateway.test.mjs @@ -3,16 +3,10 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test, { after } from "node:test"; -import { fileURLToPath } from "node:url"; -import { createJiti } from "jiti"; // With no OMP_WEB_STT_ENDPOINT, OMP_WEB_STT_MODEL names an omp model and the // job runs through `omp auth-gateway stdio`. The omp binary is a stub speaking // that JSON-lines protocol and logging every launch and request it sees. -const jiti = createJiti(import.meta.url, { - tryNative: false, - alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, -}); const dir = mkdtempSync(join(tmpdir(), "omp-web-stt-gateway-")); const log = join(dir, "gateway.log"); @@ -49,9 +43,9 @@ require("node:readline").createInterface({ input: process.stdin }).on("line", (l const originalEnv = { ...process.env }; delete process.env.OMP_WEB_STT_ENDPOINT; process.env.OMP_WEB_OMP_BIN = fakeOmp; -const { POST } = await jiti.import("../app/api/stt/route.ts"); -const { GET, DELETE } = await jiti.import("../app/api/stt/[jobId]/route.ts"); -const { disposeAuthGateway } = await jiti.import("./omp/auth-gateway.ts"); +const { POST } = await import("../app/api/stt/route.ts"); +const { GET, DELETE } = await import("../app/api/stt/[jobId]/route.ts"); +const { disposeAuthGateway } = await import("./omp/auth-gateway.ts"); after(() => { disposeAuthGateway(); diff --git a/lib/stt-route.test.mjs b/lib/stt-route.test.mjs index 928c9c11f..4d773da86 100644 --- a/lib/stt-route.test.mjs +++ b/lib/stt-route.test.mjs @@ -1,17 +1,11 @@ import assert from "node:assert/strict"; import { createServer } from "node:http"; import test, { afterEach } from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { - alias: { - "@/": new URL("../", import.meta.url).pathname, - }, -}); -const { POST } = await jiti.import("../app/api/stt/route.ts"); -const { GET } = await jiti.import("../app/api/stt/[jobId]/route.ts"); +const { POST } = await import("../app/api/stt/route.ts"); +const { GET } = await import("../app/api/stt/[jobId]/route.ts"); -const { DELETE } = await jiti.import("../app/api/stt/[jobId]/route.ts"); +const { DELETE } = await import("../app/api/stt/[jobId]/route.ts"); const ctx = (jobId) => ({ params: Promise.resolve({ jobId }) }); const pollJob = async (jobId) => (await GET(new Request("http://localhost"), ctx(jobId))).json(); const claimJob = async (jobId, token, owner = token) => @@ -40,7 +34,7 @@ async function transcribeViaJob(req) { // The job store is process-global; start every test from an empty one. afterEach(() => globalThis.__ompSttJobs?.clear()); -const { MAX_STT_AUDIO_BYTES } = await jiti.import("./stt.ts"); +const { MAX_STT_AUDIO_BYTES } = await import("./stt.ts"); test("stt route returns 501 when neither an endpoint nor a model is configured", async () => { const originalEnv = { ...process.env }; @@ -304,9 +298,9 @@ test("stt POST refuses new jobs with 429 while four are already pending", async test("a scoped job keeps its audio for any browser: list, play, retry, claim once", async () => { const originalEnv = { ...process.env }; - const { GET: LIST } = await jiti.import("../app/api/stt/route.ts"); - const { POST: RETRY } = await jiti.import("../app/api/stt/[jobId]/route.ts"); - const { GET: AUDIO } = await jiti.import("../app/api/stt/[jobId]/audio/route.ts"); + const { GET: LIST } = await import("../app/api/stt/route.ts"); + const { POST: RETRY } = await import("../app/api/stt/[jobId]/route.ts"); + const { GET: AUDIO } = await import("../app/api/stt/[jobId]/audio/route.ts"); const uploads = []; const server = createServer((req, res) => { const chunks = []; @@ -403,7 +397,7 @@ test("an empty transcript settles as a retryable error that keeps the audio", as }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); process.env.OMP_WEB_STT_ENDPOINT = `http://127.0.0.1:${server.address().port}/v1/audio/transcriptions`; - const { GET: AUDIO } = await jiti.import("../app/api/stt/[jobId]/audio/route.ts"); + const { GET: AUDIO } = await import("../app/api/stt/[jobId]/audio/route.ts"); try { const formData = new FormData(); @@ -548,7 +542,7 @@ test("a scope lists its jobs newest first", async () => { const server = createServer(() => {}); // never answers: both jobs stay pending await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); process.env.OMP_WEB_STT_ENDPOINT = `http://127.0.0.1:${server.address().port}/v1/audio/transcriptions`; - const { GET: LIST } = await jiti.import("../app/api/stt/route.ts"); + const { GET: LIST } = await import("../app/api/stt/route.ts"); const upload = async () => { const formData = new FormData(); formData.append("file", new Blob(["audio"], { type: "audio/webm" }), "audio.webm"); diff --git a/lib/stt.ts b/lib/stt.ts index e85c12671..c24752d05 100644 --- a/lib/stt.ts +++ b/lib/stt.ts @@ -12,23 +12,3 @@ export type SttAfter = "send" | "steer" | "followup"; export function isSttAfter(value: unknown): value is SttAfter { return value === "send" || value === "steer" || value === "followup"; } - -function cleanEnvVar(val?: string): string | undefined { - const cleaned = val?.replace(/\\n|[\r\n]/g, "").trim(); - return cleaned || undefined; -} - -export interface SttConfig { - /** Unset: transcribe with `model` (an omp model selector) through omp's auth gateway. */ - endpoint: string | undefined; - apiKey: string | undefined; - model: string | undefined; -} - -/** STT settings from OMP_WEB_STT_*; null when neither an endpoint nor a model is configured. */ -export function readSttConfig(): SttConfig | null { - const endpoint = cleanEnvVar(process.env.OMP_WEB_STT_ENDPOINT); - const model = cleanEnvVar(process.env.OMP_WEB_STT_MODEL); - if (!endpoint && !model) return null; - return { endpoint, apiKey: cleanEnvVar(process.env.OMP_WEB_STT_KEY), model }; -} diff --git a/lib/subagent-history.test.mjs b/lib/subagent-history.test.mjs index 2e60f6c2e..2dc361b67 100644 --- a/lib/subagent-history.test.mjs +++ b/lib/subagent-history.test.mjs @@ -3,12 +3,10 @@ import test from "node:test"; import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "fs"; import { tmpdir } from "os"; import { join } from "path"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); const { extractSubagentHistory, readCompletionArtifact, readSubagentTranscriptPage, resolveSubagentArtifact, siblingDirForSession, MAX_SUBAGENT_COMPLETION_BYTES } = - await jiti.import("./subagent-history.ts"); + await import("./subagent-history.ts"); function makeSessionFixture() { const dir = mkdtempSync(join(tmpdir(), "ompweb-subagent-history-")); diff --git a/lib/subagent-types.test.mjs b/lib/subagent-types.test.mjs index 17617d289..5e5439f33 100644 --- a/lib/subagent-types.test.mjs +++ b/lib/subagent-types.test.mjs @@ -1,15 +1,13 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); const { mergeSubagentRoster, parseSubagentProgress, parseSubagentSnapshot, parseSubagentActivityEvent, -} = await jiti.import("./subagent-types.ts"); +} = await import("./subagent-types.ts"); /** `index` restarts per `task` call, so every batch numbers its own children. */ const batch = (call, agents, status = "started") => diff --git a/lib/syntax-highlight.ts b/lib/syntax-highlight.ts index 8ec69e440..5da6a6ed6 100644 --- a/lib/syntax-highlight.ts +++ b/lib/syntax-highlight.ts @@ -4,20 +4,13 @@ // registered here; unknown fence languages fall back to plain text without // console noise (the highlighter catches the unknown-language error itself). // -// IMPORTANT: every grammar is registered EAGERLY via static imports. The old -// design lazy-loaded rarer grammars with `() => import(...)`; Turbopack split -// those ESM-only refractor chains into async chunks and intermittently failed -// with: -// -// Module .../languages/prism/c.js [app-client] (ecmascript) was instantiated -// because it was required from module .../lib/syntax-highlight.ts , -// but the module factory is not available. -// -// The async grammar chunk either raced with HMR or referenced a module factory -// in a chunk that was never evaluated, taking down the whole page. Static -// imports keep every grammar in the main client chunk, so no split/race -// exists. Grammars are small regex-based objects, so the eager cost is a few -// KB on top of what the core set already shipped. +// IMPORTANT: every grammar is registered EAGERLY via static imports. An earlier +// design lazy-loaded the rarer grammars with `() => import(...)`; under the +// former Next.js (Turbopack) build those ESM-only refractor chains were split into async +// chunks that intermittently failed to instantiate ("module factory is not +// available"), taking down the whole page. Static imports keep every grammar in +// the entry chunk: nothing is split, so nothing can race. Grammars are small +// regex-based objects, so the eager cost is a few KB on top of the core set. import type { CSSProperties } from "react"; import createSyntaxElement from "react-syntax-highlighter/dist/esm/create-element"; import PrismLight from "react-syntax-highlighter/dist/esm/prism-light"; diff --git a/lib/table-chart.test.mjs b/lib/table-chart.test.mjs index 0956c4d7d..37b60bf8b 100644 --- a/lib/table-chart.test.mjs +++ b/lib/table-chart.test.mjs @@ -1,7 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const { parseChartValue, chartSeriesFromRows, chartSeriesFromHast, chartDomain, chartGeometry, tableChartSvg } = await createJiti(import.meta.url).import("./table-chart.ts"); +const { parseChartValue, chartSeriesFromRows, chartSeriesFromHast, chartDomain, chartGeometry, tableChartSvg } = await import("./table-chart.ts"); test("an approximate multilingual token table produces the same six magnitudes", () => { const labels = ["MCP 서버 지시문", "xd:// 디바이스 카탈로그", "MCP Tool Routes", "코어 툴 스키마 13개", "시스템 프롬프트", "memory 요약 + skills 2개"]; diff --git a/lib/thinking-levels.test.mjs b/lib/thinking-levels.test.mjs index 57857ff5f..f4be792eb 100644 --- a/lib/thinking-levels.test.mjs +++ b/lib/thinking-levels.test.mjs @@ -1,9 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); -const { resolveAvailableThinkingLevels, selectableThinkingLevels, thinkingLevelsForMeta } = await jiti.import("./thinking-levels.ts"); +const { resolveAvailableThinkingLevels, selectableThinkingLevels, thinkingLevelsForMeta } = await import("./thinking-levels.ts"); const LUNA = { provider: "openai", modelId: "gpt-5.6-luna" }; const LIVE_LUNA = { provider: "openai", modelId: "gpt-5.6-luna", reasoning: true, thinking: { efforts: ["low", "medium", "high", "xhigh", "max"] } }; diff --git a/lib/tool-preset-preference.test.mjs b/lib/tool-preset-preference.test.mjs index b27cba065..68789d771 100644 --- a/lib/tool-preset-preference.test.mjs +++ b/lib/tool-preset-preference.test.mjs @@ -1,10 +1,8 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); -const { getPreferredToolPreset, setPreferredToolPreset } = await jiti.import("./tool-preset-preference.ts"); -const { getToolNamesForPreset } = await jiti.import("./tool-presets.ts"); +const { getPreferredToolPreset, setPreferredToolPreset } = await import("./tool-preset-preference.ts"); +const { getToolNamesForPreset } = await import("./tool-presets.ts"); function createStorage(values = {}) { const entries = new Map(Object.entries(values)); diff --git a/lib/transcript.test.mjs b/lib/transcript.test.mjs index f107ad7f7..a2e320612 100644 --- a/lib/transcript.test.mjs +++ b/lib/transcript.test.mjs @@ -1,11 +1,9 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); async function loadSubject() { - return jiti.import("./transcript.ts"); + return import("./transcript.ts"); } test("a generic aborted request is not attributed to the user", async () => { diff --git a/lib/update-policy.test.mjs b/lib/update-policy.test.mjs index 758a98711..57aa810e5 100644 --- a/lib/update-policy.test.mjs +++ b/lib/update-policy.test.mjs @@ -1,25 +1,20 @@ import assert from "node:assert/strict"; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { - alias: { - "@/": new URL("../", import.meta.url).pathname, - }, -}); -const { checkNpmUpdate } = await jiti.import("./npm-update.ts"); -const { checkOmpUpdate } = await jiti.import("./omp/updates.ts"); -const { DISABLE_AUTOUPDATE_ENV_VAR, isUpdateDisabled } = await jiti.import("./update-policy.ts"); +const { checkNpmUpdate } = await import("./npm-update.ts"); +const { checkOmpUpdate } = await import("./omp/updates.ts"); +const { DISABLE_AUTOUPDATE_ENV_VAR, isUpdateDisabled } = await import("./update-policy.ts"); const { getSelfUpdateSupport, prepareSelfUpdate, commitSelfUpdate, validateCommitSelfUpdate, -} = await jiti.import("./self-update.ts"); -const { GET: getAppUpdate, POST: postAppUpdate } = await jiti.import("../app/api/app-update/route.ts"); -const { POST: postOmpUpdate } = await jiti.import("../app/api/omp-update/route.ts"); +} = await import("./self-update.ts"); +const { GET: getAppUpdate, POST: postAppUpdate } = await import("../app/api/app-update/route.ts"); +const { POST: postOmpUpdate } = await import("../app/api/omp-update/route.ts"); const ENV_VAR = DISABLE_AUTOUPDATE_ENV_VAR; @@ -76,6 +71,7 @@ test("update opt-out skips external checks and self-update actions", async (t) = const ompBody = await ompResponse.json(); assert.equal(ompBody.updatesDisabled, true); assert.equal(ompBody.updateAvailable, false); + assert.equal(ompBody.selfUpdateSupported, false); const appPrepareResponse = await postAppUpdate(new Request("http://localhost/api/app-update", { method: "POST", @@ -111,3 +107,31 @@ test("update opt-out skips external checks and self-update actions", async (t) = return true; }); }); + +test("the omp update check says whether this server can run the update itself", async (t) => { + const originalEnv = { ...process.env }; + const scratch = mkdtempSync(join(tmpdir(), "omp-web-update-check-")); + t.after(() => { + process.env = originalEnv; + rmSync(scratch, { recursive: true, force: true }); + }); + // An omp whose `update --check` reports a newer version. + const fakeOmp = join(scratch, process.platform === "win32" ? "omp.cmd" : "omp"); + writeFileSync(fakeOmp, process.platform === "win32" + ? "@echo Current version: 1.0.0\r\n@echo New version available: 1.1.0\r\n" + : "#!/bin/sh\nprintf 'Current version: 1.0.0\\nNew version available: 1.1.0\\n'\n"); + chmodSync(fakeOmp, 0o755); + delete process.env[ENV_VAR]; + process.env.OMP_WEB_OMP_BIN = fakeOmp; + + const response = await postOmpUpdate(new Request("http://localhost/api/omp-update", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ action: "check", force: true }), + })); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.updateAvailable, true); + // The npm install (not the compiled binary, which answers false) runs the update worker. + assert.equal(body.selfUpdateSupported, true); +}); diff --git a/lib/usage-db.test.mjs b/lib/usage-db.test.mjs index 291457692..5853de548 100644 --- a/lib/usage-db.test.mjs +++ b/lib/usage-db.test.mjs @@ -1,16 +1,37 @@ import assert from "node:assert/strict"; -import { mkdirSync, rmSync, statSync, writeFileSync } from "node:fs"; -import { DatabaseSync } from "node:sqlite"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readlinkSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { Database } from "bun:sqlite"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); async function loadSubject() { - return jiti.import("./usage-db.ts"); + return import("./usage-db.ts"); } +// Descriptors this process holds on `file` or its -wal/-shm (Linux): Windows cannot remove a file that stays open. +const openHandles = (file) => readdirSync("/proc/self/fd").filter((fd) => { + try { + return readlinkSync(join("/proc/self/fd", fd)).startsWith(file); + } catch { + return false; + } +}).length; + +test("a usage database it moved away from or closed no longer holds its file open", { skip: !existsSync("/proc/self/fd") && "needs /proc/self/fd" }, async (t) => { + const { closeUsageDatabase, getUsageDatabase } = await loadSubject(); + const dir = mkdtempSync(join(tmpdir(), "omp-test-db-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const first = join(dir, "first.db"); + const second = join(dir, "second.db"); + getUsageDatabase(first).prepare("SELECT COUNT(*) FROM usage_records").get(); + assert.ok(openHandles(first) > 0); + getUsageDatabase(second); + assert.equal(openHandles(first), 0); + closeUsageDatabase(); + assert.equal(openHandles(second), 0); +}); + async function withTempDbDir(run) { const dir = join(tmpdir(), `omp-test-db-${Date.now()}-${Math.random().toString(36).slice(2)}`); mkdirSync(dir, { recursive: true }); @@ -226,7 +247,7 @@ test("a usage.db written with the previous table layout is rebuilt and syncs", a await withTempDbDir(async (dir) => { closeUsageDatabase(); const path = join(dir, "old-layout.db"); - const old = new DatabaseSync(path); + const old = new Database(path); old.exec(`${PREVIOUS_LAYOUT} PRAGMA user_version = ${userVersion};`); old.close(); @@ -237,6 +258,26 @@ test("a usage.db written with the previous table layout is rebuilt and syncs", a } }); +test("a migration that fails is rolled back and leaves the old database untouched", async () => { + const { closeUsageDatabase, getUsageDatabase } = await loadSubject(); + + await withTempDbDir(async (dir) => { + closeUsageDatabase(); + const path = join(dir, "blocked.db"); + const old = new Database(path); + // A view named synced_files: DROP TABLE usage_records succeeds, then DROP TABLE synced_files fails. + old.exec(`${PREVIOUS_LAYOUT.replace("CREATE TABLE synced_files (", "CREATE TABLE unrelated (")} CREATE VIEW synced_files AS SELECT 1 AS file_path;`); + old.close(); + + assert.throws(() => getUsageDatabase(path)); + + const after = new Database(path); + assert.equal(inputTokens(after), 999999, "the rebuild was rolled back: the old rows are still there"); + assert.equal(after.inTransaction, false); + after.close(true); + }); +}); + test("a connection the previous build left open on the old layout is migrated before it is reused", async () => { const { closeUsageDatabase, getUsageDatabase, syncSessionFilesToDb } = await loadSubject(); @@ -244,7 +285,7 @@ test("a connection the previous build left open on the old layout is migrated be closeUsageDatabase(); const path = join(dir, "hot-reload.db"); // Before a dev hot reload, the previous module opened usage.db and left the connection on globalThis. - const previous = new DatabaseSync(path); + const previous = new Database(path); previous.exec(PREVIOUS_LAYOUT); globalThis.__ompUsageDatabase = previous; globalThis.__ompUsageDatabasePath = path; diff --git a/lib/usage-db.ts b/lib/usage-db.ts index 128857d28..1e7b045ec 100644 --- a/lib/usage-db.ts +++ b/lib/usage-db.ts @@ -1,5 +1,5 @@ import { existsSync, mkdirSync, statSync } from "fs"; -import { DatabaseSync } from "node:sqlite"; +import { Database } from "bun:sqlite"; import { basename, dirname, join } from "path"; import { readModelsConfig, type ModelsFileConfig } from "./omp/models-config"; import { getAgentDir, getSessionsDir } from "./omp/paths"; @@ -27,7 +27,7 @@ import type { } from "./usage-types"; declare global { - var __ompUsageDatabase: DatabaseSync | undefined; + var __ompUsageDatabase: Database | undefined; var __ompUsageDatabasePath: string | undefined; } @@ -56,9 +56,9 @@ export function getUsageDbPath(): string { * processes opening an old database cannot interleave a drop with the other's * rebuild. Throws, after rolling back, when the migration cannot run. */ -function migrateUsageDatabase(db: DatabaseSync): void { +function migrateUsageDatabase(db: Database): void { const readSchemaVersion = (): number => { - const row = db.prepare("PRAGMA user_version").get(); + const row = db.prepare("PRAGMA user_version").get() as { user_version?: unknown } | null; return typeof row?.user_version === "number" ? row.user_version : 0; }; if (readSchemaVersion() >= USAGE_DB_SCHEMA_VERSION) return; @@ -111,7 +111,7 @@ function migrateUsageDatabase(db: DatabaseSync): void { } db.exec("COMMIT;"); } catch (err) { - if (db.isTransaction) db.exec("ROLLBACK;"); + if (db.inTransaction) db.exec("ROLLBACK;"); throw err; } } @@ -119,7 +119,7 @@ function migrateUsageDatabase(db: DatabaseSync): void { /** * Open or reuse the persistent SQLite database for usage tracking. */ -export function getUsageDatabase(customPath?: string): DatabaseSync { +export function getUsageDatabase(customPath?: string): Database { const targetPath = customPath || getUsageDbPath(); const cached = globalThis.__ompUsageDatabase; @@ -135,27 +135,26 @@ export function getUsageDatabase(customPath?: string): DatabaseSync { return cached; } - if (cached) { - try { - cached.close(); - } catch { - // Ignore close error on re-init - } - } + closeUsageDatabase(); const dir = dirname(targetPath); if (!existsSync(dir)) { mkdirSync(dir, { recursive: true }); } - const db = new DatabaseSync(targetPath); + const db = new Database(targetPath); db.exec("PRAGMA journal_mode = WAL;"); db.exec("PRAGMA busy_timeout = 5000;"); db.exec("PRAGMA synchronous = NORMAL;"); try { migrateUsageDatabase(db); } catch (err) { - db.close(); + // A failing close must not hide the migration error. + try { + db.close(true); + } catch { + // Ignore + } throw err; } @@ -164,11 +163,11 @@ export function getUsageDatabase(customPath?: string): DatabaseSync { return db; } -/** Close the usage database instance. */ +/** Close the usage database instance. `close(true)` finalizes the statements still alive: without it the file stays open until GC, and Windows keeps it locked. */ export function closeUsageDatabase(): void { if (globalThis.__ompUsageDatabase) { try { - globalThis.__ompUsageDatabase.close(); + globalThis.__ompUsageDatabase.close(true); } catch { // Ignore } @@ -194,7 +193,7 @@ export interface SyncStats { export function syncSessionFilesToDb( sessionFiles: string[], customModelsConfig: ModelsFileConfig = readModelsConfig(), - customDb?: DatabaseSync, + customDb?: Database, ): SyncStats { const db = customDb || getUsageDatabase(); const now = Date.now(); @@ -347,7 +346,7 @@ export function syncSessionFilesToDb( * (possible in a branch, which does not copy artifacts) does not cover it. * Computed once per report so the report's queries share it. */ -function collectUncountedUsage(db: DatabaseSync): void { +function collectUncountedUsage(db: Database): void { db.exec(` DROP TABLE IF EXISTS temp.uncounted_usage; CREATE TEMP TABLE uncounted_usage AS @@ -385,7 +384,7 @@ const COUNTED_ROWS = "id NOT IN (SELECT id FROM temp.uncounted_usage)"; */ export async function getUsageReportFromDb( options: UsageQueryOptions = {}, - customDb?: DatabaseSync, + customDb?: Database, ): Promise { const startTime = Date.now(); const timeRange = options.range || "30d"; diff --git a/lib/usage-rates.test.mjs b/lib/usage-rates.test.mjs index 6b2efad90..e1838f264 100644 --- a/lib/usage-rates.test.mjs +++ b/lib/usage-rates.test.mjs @@ -1,10 +1,8 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); async function loadSubject() { - return jiti.import("./usage-rates.ts"); + return import("./usage-rates.ts"); } test("resolves default rates for major models", async () => { diff --git a/lib/usage-service.test.mjs b/lib/usage-service.test.mjs index 420e9238d..c3a1b537e 100644 --- a/lib/usage-service.test.mjs +++ b/lib/usage-service.test.mjs @@ -3,11 +3,9 @@ import { mkdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); async function loadSubject() { - return jiti.import("./usage-service.ts"); + return import("./usage-service.ts"); } async function withTempSessionDir(run) { @@ -16,7 +14,7 @@ async function withTempSessionDir(run) { const prevAgentDir = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = dir; - const { closeUsageDatabase } = await jiti.import("./usage-db.ts"); + const { closeUsageDatabase } = await import("./usage-db.ts"); try { await run(dir); diff --git a/lib/web-auth.test.mjs b/lib/web-auth.test.mjs index bba59d8a3..563955701 100644 --- a/lib/web-auth.test.mjs +++ b/lib/web-auth.test.mjs @@ -4,26 +4,22 @@ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); -const { NextRequest } = await import("next/server.js"); -const { unstable_doesMiddlewareMatch } = await import("next/experimental/testing/server.js"); const { createWebSession, isValidWebPassword, isValidWebSession, isWebPasswordEnabled, webPasswordConfigurationProblem, -} = await jiti.import("./web-auth.ts"); -const { hashPassword } = await jiti.import("./web-password-hash.ts"); +} = await import("./web-auth.ts"); +const { hashPassword } = await import("./web-password-hash.ts"); const { deriveSessionSigningKey, resetWebAuthSecretCache, pinWebAuthSecretForTests, webAuthSecretPath, -} = await jiti.import("./web-auth-secret.ts"); -const { config, proxy } = await jiti.import("../proxy.ts"); +} = await import("./web-auth-secret.ts"); +const { proxy } = await import("../proxy.ts"); const PASSWORD = "correct horse battery staple"; // N = 2^12 for the test suite: the format and code path are identical, only @@ -31,7 +27,8 @@ const PASSWORD = "correct horse battery staple"; const PASSWORD_HASH = hashPassword(PASSWORD, { logN: 12 }); const TEST_SECRET = { salt: "a".repeat(43), key: "b".repeat(43) }; -function withEnvVars(values, run) { +/** Sets the password variables and pins the secret; returns the undo. */ +function setEnvVars(values) { const saved = new Map(); for (const name of ["OMP_WEB_PASSWORD_HASH", "OMP_WEB_PASSWORD"]) { saved.set(name, process.env[name]); @@ -39,17 +36,27 @@ function withEnvVars(values, run) { } for (const [name, value] of Object.entries(values)) process.env[name] = value; pinWebAuthSecretForTests(TEST_SECRET); - try { - return run(); - } finally { + return () => { for (const [name, value] of saved) { if (value === undefined) delete process.env[name]; else process.env[name] = value; } pinWebAuthSecretForTests(); + }; +} + +function withEnvVars(values, run) { + const restore = setEnvVars(values); + try { + return run(); + } finally { + restore(); } } +/** proxy() for a URL. */ +const gate = (url, init) => proxy(new Request(url, init)); + test("accepts only the hashed password and validates signed sessions", () => { withEnvVars({ OMP_WEB_PASSWORD_HASH: PASSWORD_HASH }, () => { assert.equal(isWebPasswordEnabled(), true); @@ -158,29 +165,51 @@ test("creates and reuses an installation secret with restrictive permissions", ( test("redirects browser requests to the password screen and blocks unauthenticated APIs", () => { withEnvVars({ OMP_WEB_PASSWORD_HASH: PASSWORD_HASH }, () => { - const pageResponse = proxy(new NextRequest("http://localhost:30177/")); + const pageResponse = gate("http://localhost:30177/"); assert.equal(pageResponse.status, 307); - assert.equal(pageResponse.headers.get("location"), "http://localhost:30177/login"); + assert.equal(pageResponse.headers.get("location"), "/login"); + + const deepLink = gate("http://localhost:30177/?session=x"); + assert.equal(deepLink.status, 307); + assert.equal(deepLink.headers.get("location"), "/login?next=%2F%3Fsession%3Dx"); + + // Relative, so a TLS proxy in front keeps https (Bun's request.url is always http://). + const behindTls = gate("http://ai-web.example.com/?session=x", { headers: { "x-forwarded-proto": "https" } }); + assert.equal(behindTls.headers.get("location"), "/login?next=%2F%3Fsession%3Dx"); - const crossSitePageResponse = proxy(new NextRequest("http://localhost:30177/", { + const crossSitePageResponse = gate("http://localhost:30177/", { headers: { "sec-fetch-site": "cross-site" }, - })); + }); assert.equal(crossSitePageResponse.status, 307); - const apiResponse = proxy(new NextRequest("http://localhost:30177/api/sessions")); + const apiResponse = gate("http://localhost:30177/api/sessions"); assert.equal(apiResponse.status, 401); - const signedInResponse = proxy(new NextRequest("http://localhost:30177/", { + assert.equal(gate("http://localhost:30177/", { headers: { cookie: `omp_web_session=${createWebSession()}` }, - })); - assert.equal(signedInResponse.status, 200); + }), "authenticated"); + assert.equal(gate("http://localhost:30177/login", { + headers: { cookie: `omp_web_session=${createWebSession()}` }, + }).headers.get("location"), "/"); + assert.equal(gate("http://localhost:30177/login"), "public"); + assert.equal(gate("http://localhost:30177/api/web-auth/session", { method: "POST" }), "public"); + }); +}); + +test("without a password every request continues and /login leads home", () => { + withEnvVars({}, () => { + assert.equal(gate("http://localhost:30177/"), "authenticated"); + assert.equal(gate("http://localhost:30177/api/sessions"), "authenticated"); + const login = gate("http://localhost:30177/login"); + assert.equal(login.status, 307); + assert.equal(login.headers.get("location"), "/"); }); }); test("refuses every request while the password configuration is broken", () => { withEnvVars({ OMP_WEB_PASSWORD: "legacy-plaintext" }, () => { for (const url of ["http://localhost:30177/", "http://localhost:30177/api/sessions", "http://localhost:30177/login"]) { - const response = proxy(new NextRequest(url)); + const response = gate(url); assert.equal(response.status, 503, url); } }); @@ -189,15 +218,15 @@ test("refuses every request while the password configuration is broken", () => { test("accepts the trusted proxy header only when its SHA-256 matches the configured digest", () => { const previousDigest = process.env.OMP_WEB_TRUSTED_HEADER_SHA256; const digest = createHash("sha256").update("proxy-secret").digest("hex"); - const request = (path, value) => proxy(new NextRequest(`http://localhost:30177${path}`, { + const request = (path, value) => gate(`http://localhost:30177${path}`, { headers: value === undefined ? {} : { "x-omp-web-auth": value }, - })); + }); withEnvVars({ OMP_WEB_PASSWORD_HASH: PASSWORD_HASH }, () => { try { process.env.OMP_WEB_TRUSTED_HEADER_SHA256 = digest; - assert.equal(request("/", "proxy-secret").status, 200); - assert.equal(request("/api/sessions", "proxy-secret").status, 200); - assert.equal(request("/login", "proxy-secret").headers.get("location"), "http://localhost:30177/"); + assert.equal(request("/", "proxy-secret"), "authenticated"); + assert.equal(request("/api/sessions", "proxy-secret"), "authenticated"); + assert.equal(request("/login", "proxy-secret").headers.get("location"), "/"); assert.equal(request("/api/sessions", "wrong").status, 401); assert.equal(request("/api/sessions", "proxy-secretX").status, 401); assert.equal(request("/api/sessions", "proxy-secre").status, 401); @@ -208,7 +237,7 @@ test("accepts the trusted proxy header only when its SHA-256 matches the configu assert.equal(request("/api/sessions", digest).status, 401); process.env.OMP_WEB_TRUSTED_HEADER_SHA256 = digest.toUpperCase(); - assert.equal(request("/api/sessions", "proxy-secret").status, 200, "uppercase digest"); + assert.equal(request("/api/sessions", "proxy-secret"), "authenticated", "uppercase digest"); // Unset, empty or malformed digest disables the header; nginx's empty value never matches. for (const value of [undefined, "", "proxy-secret", digest.slice(1), `${digest}0`, `${digest.slice(2)}zz`]) { @@ -224,17 +253,66 @@ test("accepts the trusted proxy header only when its SHA-256 matches the configu }); }); -test("leaves Next.js build assets outside password protection", () => { - assert.equal(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url: "/_next/static/chunks/app.js" }), false); - assert.equal(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url: "/api/sessions" }), true); +test("leaves the login page's assets, the icons and the service worker outside password protection", () => { + withEnvVars({ OMP_WEB_PASSWORD_HASH: PASSWORD_HASH }, () => { + for (const path of ["/sw.js", "/assets/a.js", "/favicon.ico", "/icon.svg", "/icon.png", "/icon-192.png", "/badge-96.png"]) { + assert.equal(gate(`http://localhost:30177${path}`), "public", path); + } + assert.equal(gate("http://localhost:30177/api/sessions").status, 401); + assert.equal(gate("http://localhost:30177/event-stream-worker.js").status, 307); + // The names are exact: a path below or beside one is gated. + for (const path of ["/icon.svg/foo", "/sw.js/x", "/favicon.icox", "/badge-96.png.map"]) { + assert.equal(gate(`http://localhost:30177${path}`).status, 307, path); + } + }); +}); + +test("leaves Bun's dev bundles under /_bun/ public in dev only", () => { + withEnvVars({ OMP_WEB_PASSWORD_HASH: PASSWORD_HASH }, () => { + const bundle = "http://localhost:30177/_bun/client/index.js"; + assert.equal(gate(bundle).status, 307); + const previous = process.env.NODE_ENV; + process.env.NODE_ENV = "development"; + try { + assert.equal(gate(bundle), "public"); + } finally { + if (previous === undefined) delete process.env.NODE_ENV; + else process.env.NODE_ENV = previous; + } + }); }); test("leaves the host link to its own bearer check, and nothing else under /api/hosts", () => { - // The proxy would truncate host link uploads over 10 MB; the route authenticates them. - assert.equal(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url: "/api/hosts/link" }), false); - assert.equal(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url: "/api/hosts/link/blob/0b6f2c9e-1d2a-4c55-9a3e-7f1e2d3c4b5a" }), false); - assert.equal(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url: "/api/hosts" }), true); - assert.equal(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url: "/api/hosts/abc" }), true); - assert.equal(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url: "/api/hosts/links" }), true); - assert.equal(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url: "/api/hosts/link-settings" }), true); + withEnvVars({ OMP_WEB_PASSWORD_HASH: PASSWORD_HASH }, () => { + assert.equal(gate("http://localhost:30177/api/hosts/link"), "public"); + assert.equal(gate("http://localhost:30177/api/hosts/link/blob/x"), "public"); + assert.equal(gate("http://localhost:30177/api/hosts/link/blob/0b6f2c9e-1d2a-4c55-9a3e-7f1e2d3c4b5a"), "public"); + for (const path of ["/api/hosts", "/api/hosts/abc", "/api/hosts/links", "/api/hosts/linkx", "/api/hosts/link-settings"]) { + assert.equal(gate(`http://localhost:30177${path}`).status, 401, path); + } + }); +}); + +test("signing in sets an HttpOnly, SameSite=Lax session cookie, Secure only over https", async (t) => { + const { POST } = await import("../app/api/web-auth/session/route.ts"); + t.after(setEnvVars({ OMP_WEB_PASSWORD_HASH: PASSWORD_HASH })); + const signIn = async (headers) => { + const response = await POST(new Request("http://localhost:30177/api/web-auth/session", { + method: "POST", + headers: { "content-type": "application/json", ...headers }, + body: JSON.stringify({ password: PASSWORD }), + })); + assert.equal(response.status, 200); + return response.headers.get("set-cookie"); + }; + + const plain = await signIn({}); + assert.match(plain, /^omp_web_session=[^;]+;/); + assert.equal(isValidWebSession(/^omp_web_session=([^;]+)/.exec(plain)[1]), true); + for (const attribute of [/; HttpOnly(;|$)/i, /; Path=\/(;|$)/i, /; Max-Age=2592000(;|$)/i, /; SameSite=Lax(;|$)/i]) { + assert.match(plain, attribute); + } + assert.doesNotMatch(plain, /; Secure(;|$)/i); + assert.match(await signIn({ "x-forwarded-proto": "https" }), /; Secure(;|$)/i); + assert.match(await signIn({ "x-forwarded-proto": "https, http" }), /; Secure(;|$)/i); }); diff --git a/lib/web-password-hash.test.mjs b/lib/web-password-hash.test.mjs index 3c0b36457..1f9b1e0ab 100644 --- a/lib/web-password-hash.test.mjs +++ b/lib/web-password-hash.test.mjs @@ -1,9 +1,7 @@ import assert from "node:assert/strict"; import { createRequire } from "node:module"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); const require = createRequire(import.meta.url); const { @@ -12,7 +10,7 @@ const { parsePasswordHash, verifyPassword, PASSWORD_HASH_MIN_LOG_N, -} = await jiti.import("./web-password-hash.ts"); +} = await import("./web-password-hash.ts"); // The shipped implementation, used by the launcher and the service installers. const launcherImpl = require("../bin/omp-web-password-hash.js"); diff --git a/lib/web-password-hash.ts b/lib/web-password-hash.ts index f17f58bbe..cf0fe246d 100644 --- a/lib/web-password-hash.ts +++ b/lib/web-password-hash.ts @@ -1,6 +1,6 @@ // The `OMP_WEB_PASSWORD_HASH` format lives in bin/omp-web-password-hash.js: // the packaged launcher and the service installers must hash and validate a -// password before Next.js (and this module) exists. This file is the typed +// password before the server (and this module) exists. This file is the typed // view of it for the server — never a second implementation. import * as passwordHash from "../bin/omp-web-password-hash.js"; diff --git a/lib/web-settings.test.mjs b/lib/web-settings.test.mjs index 7828be1b7..1775b5890 100644 --- a/lib/web-settings.test.mjs +++ b/lib/web-settings.test.mjs @@ -3,10 +3,8 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { loadWebServerSettings, saveWebServerSettings } = await jiti.import("./web-settings.ts"); +const { loadWebServerSettings, saveWebServerSettings } = await import("./web-settings.ts"); function withAgentDir(run) { const dir = mkdtempSync(join(tmpdir(), "omp-web-web-settings-")); diff --git a/lib/web-settings.ts b/lib/web-settings.ts index f1ffa3cab..fae15a612 100644 --- a/lib/web-settings.ts +++ b/lib/web-settings.ts @@ -40,7 +40,7 @@ function settingsPath(): string { } declare global { - // Shared across module instances (instrumentation and route bundles). + // Survives `bun --hot` re-evaluation, which creates fresh module instances. var __ompWebSettingsCache: { path: string; settings: WebServerSettings } | undefined; } diff --git a/lib/windows-service.test.mjs b/lib/windows-service.test.mjs index bc31a3abf..edde606ce 100644 --- a/lib/windows-service.test.mjs +++ b/lib/windows-service.test.mjs @@ -2,9 +2,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import path from "node:path"; import { existsSync, readFileSync } from "node:fs"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); const { DEFAULT_WEB_SERVICE_CONFIG, sanitizePort, @@ -25,7 +23,7 @@ const { getWindowsExecutionEnv, isTrayProcessRunning, invalidateTrayRunningCache, -} = await jiti.import("./windows-service.ts"); +} = await import("./windows-service.ts"); test("DEFAULT_WEB_SERVICE_CONFIG has correct production ports and settings", () => { assert.equal(DEFAULT_WEB_SERVICE_CONFIG.port, 30177); diff --git a/lib/windows-service.ts b/lib/windows-service.ts index e927b0554..4e70e2a7f 100644 --- a/lib/windows-service.ts +++ b/lib/windows-service.ts @@ -653,12 +653,12 @@ export async function stopTrayService(): Promise<{ success: boolean; message?: s foreach ($p in $nativeProcs) { Start-Process -FilePath '${taskkillExe.replace(/'/g, "''")}' -ArgumentList "/PID $($p.ProcessId) /T /F" -WindowStyle Hidden -Wait -ErrorAction SilentlyContinue | Out-Null } - # Also kill orphaned node servers on the service port + # Also kill orphaned node or bun servers on the service port $port = if ($cfg -and $cfg.port) { [int]$cfg.port } else { 30177 } $conns = Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue | Where-Object { $_.State -eq "Listen" } foreach ($c in $conns) { $owner = Get-CimInstance Win32_Process -Filter "ProcessId = $($c.OwningProcess)" -ErrorAction SilentlyContinue - if ($owner -and $owner.Name -like "node*") { + if ($owner -and ($owner.Name -like "node*" -or $owner.Name -like "bun*")) { Start-Process -FilePath '${taskkillExe.replace(/'/g, "''")}' -ArgumentList "/PID $($c.OwningProcess) /T /F" -WindowStyle Hidden -Wait -ErrorAction SilentlyContinue | Out-Null } } diff --git a/lib/workspace-memory.test.mjs b/lib/workspace-memory.test.mjs index 66685b04e..7a0be516a 100644 --- a/lib/workspace-memory.test.mjs +++ b/lib/workspace-memory.test.mjs @@ -1,14 +1,12 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); const { clearLastOpenSession, getLastOpenSession, setLastOpenSession, workspaceKeyOf, -} = await jiti.import("./workspace-memory.ts"); +} = await import("./workspace-memory.ts"); function createStorage(values = {}) { const entries = new Map(Object.entries(values)); diff --git a/lib/worktree.test.mjs b/lib/worktree.test.mjs index 2a57a9013..0b3f5558d 100644 --- a/lib/worktree.test.mjs +++ b/lib/worktree.test.mjs @@ -4,11 +4,9 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "no import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { createJiti } from "jiti"; -const jiti = createJiti(import.meta.url); -const { addWorktree, listWorktrees, removeWorktree, repairWorktreeGitdirs, resolveProject } = await jiti.import("./worktree.ts"); -const { samePath } = await jiti.import("./paths.ts"); +const { addWorktree, listWorktrees, removeWorktree, repairWorktreeGitdirs, resolveProject } = await import("./worktree.ts"); +const { samePath } = await import("./paths.ts"); function git(cwd, args) { return execFileSync("git", ["-C", cwd, "-c", "safe.directory=*", ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); } diff --git a/next.config.ts b/next.config.ts deleted file mode 100644 index 021b63d53..000000000 --- a/next.config.ts +++ /dev/null @@ -1,138 +0,0 @@ -import type { NextConfig } from "next"; -import { createHash } from "crypto"; -import { readFileSync } from "fs"; -import { dirname, join } from "path"; -import { fileURLToPath } from "url"; -import { PHASE_DEVELOPMENT_SERVER } from "next/constants.js"; - -// The WASM SWC build used on wasm-first targets (e.g. aarch64-linux-android) -// does not transpile ESM to CJS, so this file loads as ESM there and -// `__dirname` is undefined. `typeof` on an undeclared identifier is safe. -const packageDir = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url)); - -const { version } = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8")) as { version: string }; -// public/event-stream-worker.js is served as-is (not bundled). SharedWorkers -// are keyed by URL, so hash its content into the URL: a changed worker gets a -// fresh instance instead of tabs attaching to a stale copy still running. -const eventStreamWorkerVersion = createHash("sha256") - .update(readFileSync(join(packageDir, "public", "event-stream-worker.js"))) - .digest("hex") - .slice(0, 12); - -// Function form: `phase` is authoritative even when the host environment -// carries a stray NODE_ENV (e.g. NODE_ENV=production inherited by `next dev` -// processes). Relying on process.env.NODE_ENV here would apply the immutable -// chunk rule in development, make the browser cache dev chunks forever, and -// produce stale "module factory is not available" / hydration errors after -// every restart. -const nextConfig = (phase: string): NextConfig => { - const isDev = phase === PHASE_DEVELOPMENT_SERVER; - return { - // Keep standalone/server tracing inside this package. Without this explicit - // root, Next can choose a parent lockfile on Windows and traverse protected - // user-profile junctions while compiling. - outputFileTracingRoot: process.cwd(), - // undici is loaded from a runtime dependency (lib/http-dispatcher.ts) to - // honor HTTP(S)_PROXY for server-side fetch; keep it external so the - // bundler does not inline a second copy next to the global dispatcher. - serverExternalPackages: ["undici"], - webpack(config: Parameters>[0]) { - // Next's entrypoint tracer does not automatically reject dynamic paths - // outside the project root. Add parent/profile patterns to its ignore list - // so user filesystem discovery remains request-time only during builds. - for (const plugin of config.plugins ?? []) { - const candidate = plugin as unknown as { - constructor?: { name?: string }; - traceIgnores?: string[]; - }; - if (candidate.constructor?.name === "TraceEntryPointsPlugin") { - candidate.traceIgnores ??= []; - candidate.traceIgnores.push( - "**/../**", - "**/Users/**", - "**/Application Data/**", - "**/omp-web-bundled-agents/**", - ); - } - } - return config; - }, - allowedDevOrigins: [ - "127.0.0.1", - // RFC1918 private IPv4 ranges. Next.js accepts hostname patterns, not CIDRs. - "10.*.*.*", - ...Array.from({ length: 16 }, (_, i) => `172.${16 + i}.*.*`), - "192.168.*.*", - ...(process.env.OMP_WEB_DEV_ORIGIN ? [process.env.OMP_WEB_DEV_ORIGIN] : []), - ], - // Security: stop advertising the runtime, and surface dev-mode problems - // earlier. Source maps in the browser bundle leak server path layout and - // bloat downloads without helping end users of a published app. - poweredByHeader: false, - reactStrictMode: true, - productionBrowserSourceMaps: false, - // Next.js enables gzip/brotli compression for `next start` by default; no - // custom compression middleware is needed (and would require a custom server). - async headers() { - const securityHeaders = [ - { key: "X-Content-Type-Options", value: "nosniff" }, - { key: "X-Frame-Options", value: "DENY" }, - { key: "Referrer-Policy", value: "no-referrer" }, - { key: "Permissions-Policy", value: "camera=(), microphone=(self), geolocation=()" }, - { key: "Content-Security-Policy", value: "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; object-src 'none'; img-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self' ws: wss:; font-src 'self' data:; media-src 'self' blob:" }, - ]; - // /api/files streams workspace files whose document policy depends on the - // content type (strict CSP for SVG, the DOCX preview policy, none for - // media the browser renders natively). Config-level headers overwrite - // same-key headers set by route handlers, so the global CSP must not - // match these paths — it would both reopen script execution for SVG - // documents and block the same-origin