diff --git a/.github/workflows/omp-runner.yml b/.github/workflows/omp-runner.yml deleted file mode 100644 index 56c17e66..00000000 --- a/.github/workflows/omp-runner.yml +++ /dev/null @@ -1,97 +0,0 @@ -name: omp runner binaries - -on: - push: - branches: - - main - pull_request: - paths: - - "runner/**" - - ".github/workflows/omp-runner.yml" - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -permissions: - contents: read - -jobs: - test: - name: Typecheck and test - runs-on: ubuntu-latest - defaults: - run: - working-directory: runner - steps: - - name: Checkout repository - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - - - name: Setup Bun - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - with: - bun-version: 1.4.4 - - - name: Fetch the pinned omp packages - run: bun scripts/use-omp-build.ts - - - name: Install dependencies - run: bun install --frozen-lockfile - - - name: Typecheck - run: bunx tsc -p . - - - name: Test - run: bun test - - build: - name: Build (${{ matrix.target }}) - # Bun cross-compiles every target from Linux, as omp's own release does. - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - include: - - { target: linux-x64, os: linux, cpu: x64, binary: ompweb-omp-linux-x64 } - - { target: linux-arm64, os: linux, cpu: arm64, binary: ompweb-omp-linux-arm64 } - - { target: darwin-x64, os: darwin, cpu: x64, binary: ompweb-omp-darwin-x64 } - - { target: darwin-arm64, os: darwin, cpu: arm64, binary: ompweb-omp-darwin-arm64 } - - { target: windows-x64, os: win32, cpu: x64, binary: ompweb-omp-windows-x64.exe } - defaults: - run: - working-directory: runner - - steps: - - name: Checkout repository - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - - - name: Setup Bun - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - with: - bun-version: 1.4.4 - - - name: Fetch the pinned omp packages - run: bun scripts/use-omp-build.ts - - # The host's own addon package is not needed; the target's is what gets embedded. - - name: Install dependencies - run: bun install --frozen-lockfile --os=${{ matrix.os }} --cpu=${{ matrix.cpu }} - - - name: Build binary - run: bun scripts/build-binary.ts ${{ matrix.target }} - - - name: Smoke test - if: matrix.target == 'linux-x64' - run: | - set -euo pipefail - runtime_dir="$(mktemp -d)" - HOME="$runtime_dir/home" XDG_DATA_HOME="$runtime_dir/xdg" release/${{ matrix.binary }} --version - HOME="$runtime_dir/home" XDG_DATA_HOME="$runtime_dir/xdg" release/${{ matrix.binary }} --smoke-test - - - name: Upload binary - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: ${{ matrix.binary }} - path: runner/release/${{ matrix.binary }} - if-no-files-found: error diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index 13b2a4ab..d8d99d1e 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -26,6 +26,7 @@ jobs: runs-on: ubuntu-latest env: SHA: ${{ github.event.workflow_run.head_sha || github.sha }} + PI_VERSION: 1.5.2 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: @@ -40,24 +41,8 @@ jobs: - run: npm ci - run: npm run build - # The omp the runners compile against: the fork's newest integration build, not runner/omp-build.json's pin - # (not committed back). No such release or a runner that fails tsc against it fails the release. - - name: Find the newest omp integration build - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - sha=$(gh api repos/ompweb-dev/oh-my-pi/commits/integration-release --jq .sha) - tag=$(gh api --paginate 'repos/ompweb-dev/oh-my-pi/releases?per_page=100' --jq '.[].tag_name' \ - | grep -E "^v[0-9]+\.[0-9]+\.[0-9]+-int\.[0-9]{12}\.g${sha:0:7}\$" | head -n 1 || true) - if [ -z "$tag" ]; then - echo "::error::ompweb-dev/oh-my-pi has no integration release for integration-release ($sha)" - exit 1 - fi - echo "OMP_TAG=$tag" >> "$GITHUB_ENV" - # Without GH_TOKEN: bun install runs the omp packages' scripts. - - name: Pin the runner to it - run: npx bun runner/scripts/use-omp-build.ts "$OMP_TAG" && (cd runner && npx bun x tsc -p .) + - name: Install pi + run: npm install --global "@earendil-works/pi-coding-agent@$PI_VERSION" - name: Pin the binary release identity run: | now=$(date -u +%s) @@ -65,9 +50,9 @@ jobs: echo "RELEASE_TAG=$(date -u -d "@$now" +%Y%m%dT%H%M%SZ)-$(git rev-parse --short=10 "$SHA")" >> "$GITHUB_ENV" - name: Build the release binaries env: - OMP_WEB_RELEASE_TAG: ${{ env.RELEASE_TAG }} + TAU_RELEASE_TAG: ${{ env.RELEASE_TAG }} run: sh scripts/build-release-binaries.sh - - run: npm run smoke -- --binary release/ompweb-linux-x64/ompweb + - run: npm run smoke -- --binary release/tau-linux-x64/tau - name: Publish the prerelease env: @@ -77,7 +62,7 @@ jobs: tag="$RELEASE_TAG" subject=$(git log -1 --format=%s "$SHA") # A draft first, so a failed upload never leaves a published prerelease missing archives. - gh release create "$tag" release/ompweb-*.tar.gz release/ompweb-*.zip \ + gh release create "$tag" release/tau-*.tar.gz release/tau-*.zip \ --repo "$GITHUB_REPOSITORY" --target "$SHA" --draft --prerelease --title "$title" \ - --notes "Binaries built from $GITHUB_REPOSITORY@$SHA ($subject), omp: ompweb-dev/oh-my-pi $OMP_TAG. Not a release: no npm package, no update notice." + --notes "Binaries built from $GITHUB_REPOSITORY@$SHA ($subject), tested with pi $PI_VERSION. Not a release: no npm package, no update notice." gh release edit "$tag" --repo "$GITHUB_REPOSITORY" --draft=false diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 1fb840be..cdca70f2 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -7,6 +7,7 @@ on: env: TAG: ${{ github.ref_name }} + PI_VERSION: 1.5.2 permissions: contents: write @@ -34,40 +35,21 @@ jobs: - run: npm install --global npm@^11.5.1 - run: npm ci - # The omp the runners compile against: the fork's newest integration build, not runner/omp-build.json's pin - # (not committed back). No such release or a runner that fails tsc against it fails the release. Pinned before - # the tests: they import the runner (lib/hosts/omp-socket.test.mjs), and must run against the omp that ships. - - name: Find the newest omp integration build - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - sha=$(gh api repos/ompweb-dev/oh-my-pi/commits/integration-release --jq .sha) - tag=$(gh api --paginate 'repos/ompweb-dev/oh-my-pi/releases?per_page=100' --jq '.[].tag_name' \ - | grep -E "^v[0-9]+\.[0-9]+\.[0-9]+-int\.[0-9]{12}\.g${sha:0:7}\$" | head -n 1 || true) - if [ -z "$tag" ]; then - echo "::error::ompweb-dev/oh-my-pi has no integration release for integration-release ($sha)" - exit 1 - fi - echo "OMP_TAG=$tag" >> "$GITHUB_ENV" - # Without GH_TOKEN: bun install runs the omp packages' scripts. - - name: Pin the runner to it - run: npx bun runner/scripts/use-omp-build.ts "$OMP_TAG" && (cd runner && npx bun x tsc -p .) + # The pi tau drives (`pi --mode rpc`), on PATH for the tests' live sessions, the smoke tests and preflight. + - name: Install pi + run: npm install --global "@earendil-works/pi-coding-agent@$PI_VERSION" # Match Verify PR: allow isolated fixtures, never control of the runner's service. - name: Allow isolated native fixture scopes run: | rule="polkit.addRule(function(action, subject) { if (action.id === 'org.freedesktop.systemd1.manage-units' && subject.user === '$(id -un)' && /\\.scope$/.test(action.lookup('unit') || '')) { return polkit.Result.YES; } });" - printf '%s\n' "$rule" | sudo tee /etc/polkit-1/rules.d/49-ompweb-fixture-scopes.rules >/dev/null + printf '%s\n' "$rule" | sudo tee /etc/polkit-1/rules.d/49-tau-fixture-scopes.rules >/dev/null systemd-run --scope --quiet --collect --no-ask-password true - run: npm test - run: npm run build - # Builds the omp runners too, which the source smoke spawns from runner/release/. The archives leave them out: - # every install fetches its runner from this release (lib/omp/runner-fetch.ts), attached below. - name: Build the release binaries - run: sh scripts/build-release-binaries.sh --no-runner + run: sh scripts/build-release-binaries.sh - run: npm run smoke - # --omp: the draft release cannot serve the runner to the binary yet. - - run: npm run smoke -- --binary release/ompweb-linux-x64/ompweb --omp runner/release/ompweb-omp-linux-x64 + - run: npm run smoke -- --binary release/tau-linux-x64/tau - name: Create draft GitHub Release env: @@ -75,22 +57,15 @@ jobs: run: | if ! gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then node bin/generate-release-notes.js --tag "$TAG" --output release-notes.md - printf '\nomp: ompweb-dev/oh-my-pi %s\n' "$OMP_TAG" >> release-notes.md + printf '\nTested with pi %s (@earendil-works/pi-coding-agent).\n' "$PI_VERSION" >> release-notes.md gh release create "$TAG" --repo "$GITHUB_REPOSITORY" --verify-tag --title "$TAG" --notes-file release-notes.md --draft fi - # The runners, by the names and checksum listing lib/omp/runner-fetch.ts fetches (OMP_RUNNER_ASSET, - # OMP_RUNNER_CHECKSUMS), for binary and npm installs alike. - - name: Attach the binaries and the omp runners to the draft release + - name: Attach the binaries to the draft release env: GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - runners=(ompweb-omp-linux-x64 ompweb-omp-linux-arm64 ompweb-omp-darwin-x64 ompweb-omp-darwin-arm64 ompweb-omp-windows-x64.exe) - (cd runner/release && sha256sum "${runners[@]}" > ompweb-omp.sha256) - gh release upload "$TAG" release/ompweb-*.tar.gz release/ompweb-*.zip "${runners[@]/#/runner/release/}" runner/release/ompweb-omp.sha256 --repo "$GITHUB_REPOSITORY" --clobber + run: gh release upload "$TAG" release/tau-*.tar.gz release/tau-*.zip --repo "$GITHUB_REPOSITORY" --clobber - # Before npm: an npm install fetches its runner from this release, which a draft does not serve. - name: Publish GitHub Release env: GH_TOKEN: ${{ github.token }} @@ -125,10 +100,10 @@ jobs: jq -n \ --arg body "$(jq -r '.body' <<<"$RELEASE_JSON")" \ - --arg title "OMPWEB $TAG" \ + --arg title "tau $TAG" \ --arg url "$(jq -r '.url' <<<"$RELEASE_JSON")" \ '{ - username: "OMPWEB Releases", + username: "tau Releases", embeds: [{ title: $title, url: $url, diff --git a/.github/workflows/verify-pr.yml b/.github/workflows/verify-pr.yml index 168ac2c7..52fc8642 100644 --- a/.github/workflows/verify-pr.yml +++ b/.github/workflows/verify-pr.yml @@ -18,6 +18,9 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true +env: + PI_VERSION: 1.5.2 + permissions: contents: read pull-requests: read @@ -46,12 +49,12 @@ jobs: node-version-file: .nvmrc cache: npm - # The runner's own deps too: lib/hosts/omp-socket.test.mjs checks the host against runner/src/channel.ts. - name: Install dependencies - run: | - npm ci - npx bun runner/scripts/use-omp-build.ts - npx bun install --cwd runner --frozen-lockfile + run: npm ci + + # The pi tau drives (`pi --mode rpc`), on PATH for the tests' live sessions, the smoke tests and preflight. + - name: Install pi + run: npm install --global "@earendil-works/pi-coding-agent@$PI_VERSION" - name: TypeScript typecheck run: npm run typecheck @@ -64,7 +67,7 @@ jobs: if: runner.os == 'Linux' run: | rule="polkit.addRule(function(action, subject) { if (action.id === 'org.freedesktop.systemd1.manage-units' && subject.user === '$(id -un)' && /\\.scope$/.test(action.lookup('unit') || '')) { return polkit.Result.YES; } });" - printf '%s\n' "$rule" | sudo tee /etc/polkit-1/rules.d/49-ompweb-fixture-scopes.rules >/dev/null + printf '%s\n' "$rule" | sudo tee /etc/polkit-1/rules.d/49-tau-fixture-scopes.rules >/dev/null systemd-run --scope --quiet --collect --no-ask-password true # Do not pass pwsh's Core module search path to Windows PowerShell children used by the native tests. @@ -86,69 +89,64 @@ jobs: - name: Verify production build run: npm run build - - name: Build the omp runner - run: npx bun runner/scripts/build-binary.ts - - 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). + # own `tau 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 - bin=release/ompweb-windows-x64/ompweb.exe - archive=release/ompweb-windows-x64.zip + bin=release/tau-windows-x64/tau.exe + archive=release/tau-windows-x64.zip elif [ "$RUNNER_OS" = macOS ]; then arch=$(node -p process.arch) target="bun-darwin-$arch" if [ "$arch" = x64 ]; then target="$target-baseline"; fi npx bun scripts/build-binary.ts --target "$target" - bin="release/ompweb-darwin-$arch/ompweb" - archive="release/ompweb-darwin-$arch.tar.gz" + bin="release/tau-darwin-$arch/tau" + archive="release/tau-darwin-$arch.tar.gz" else npx bun scripts/build-binary.ts --target bun-linux-x64-baseline - bin=release/ompweb-linux-x64/ompweb - archive=release/ompweb-linux-x64.tar.gz + bin=release/tau-linux-x64/tau + archive=release/tau-linux-x64.tar.gz fi # The archive a host downloads must pass the updater's own size limits and checks. npx bun scripts/check-host-release-archive.ts "$archive" npm run smoke -- --binary "$bin" # What the host updater checks on a new release before it switches (lib/hosts/update-worker.ts): the marker - # it finds the command by, then the command itself against the bundled ompweb-omp. - grep -qa ompweb-preflight-scratch- "$bin" + # it finds the command by, then the command itself against the pi on PATH. + grep -qa tau-preflight-scratch- "$bin" node -e 'require("node:child_process").execFileSync(process.argv[1], ["preflight"], {stdio:"inherit",timeout:120000})' "$bin" # Required on every supported runner, including macOS foreground. A skip fails the job. - name: Native compiled coordinated upgrade and rollback shell: bash env: - OMPWEB_COMPILED_UPGRADE_E2E: "1" - run: | - export OMPWEB_UPGRADE_E2E_RUNNER="$(node -p "require('node:path').resolve('runner', 'release', 'ompweb-omp-' + (process.platform === 'win32' ? 'windows' : process.platform) + '-' + process.arch + (process.platform === 'win32' ? '.exe' : ''))")" - npx bun test --parallel --timeout 900000 lib/compiled-upgrade.integration.test.mjs + TAU_COMPILED_UPGRADE_E2E: "1" + run: npx bun test --parallel --timeout 900000 lib/compiled-upgrade.integration.test.mjs - 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 -- --omp "$(ls runner/release/ompweb-omp-*)" --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix")/@kahme247/ompweb" + npm install -g --prefix "$RUNNER_TEMP/tau-prefix" ./ompweb-dev-tau-*.tgz + npm run smoke -- --package "$(npm root -g --prefix "$RUNNER_TEMP/tau-prefix")/@ompweb-dev/tau" # 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 -- --omp "$(ls runner/release/ompweb-omp-*)" --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix-no-scripts")/@kahme247/ompweb" + npm install -g --ignore-scripts --prefix "$RUNNER_TEMP/tau-prefix-no-scripts" ./ompweb-dev-tau-*.tgz + npm run smoke -- --package "$(npm root -g --prefix "$RUNNER_TEMP/tau-prefix-no-scripts")/@ompweb-dev/tau" - 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') { + foreach ($f in 'scripts/windows/tau-service.ps1', 'scripts/windows/tau-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 } @@ -157,10 +155,10 @@ jobs: - name: Verify Windows System Tray & Shortcuts (Windows only) if: runner.os == 'Windows' run: | - node bin/omp-web-tray.js --status - node bin/omp-web-tray.js --install - node bin/omp-web-tray.js --status - node bin/omp-web-tray.js --uninstall + node bin/tau-tray.js --status + node bin/tau-tray.js --install + node bin/tau-tray.js --status + node bin/tau-tray.js --uninstall pr-rules: name: PR Rules & Quality Gates diff --git a/.serena/project.yml b/.serena/project.yml index b0471a36..705fe87d 100644 --- a/.serena/project.yml +++ b/.serena/project.yml @@ -1,5 +1,5 @@ # the name by which the project can be referenced within Serena/when chatting with the LLM. -project_name: "ompweb" +project_name: "tau" # list of language servers to start when using the LSP backend; choose from: # ada al angular ansible astro diff --git a/AGENTS.md b/AGENTS.md index 5ec4b946..020d304a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,86 +1,121 @@ -# omp-web - Development Notes +# tau - Development Notes + +tau is a web UI for the pi coding agent (`@earendil-works/pi-coding-agent`, developed against 1.5.2). It is a fork of +ompweb, but a separate product: it shares no state, protocol history or installation with ompweb. ## Quick Start ```bash -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 dev # Bun server with hot reload (HMR for the SPA), 127.0.0.1:30188 (dev:lan: 0.0.0.0) +npm run build # bundle the SPA into dist/ (scripts/build-client.ts) +npm start # serve dist/ + the API, 127.0.0.1:30187 (start:lan: 0.0.0.0) +npm test # bun test --parallel --timeout 30000 over app bin components hooks lib scripts server tests +npm run smoke # start the built server and its local host and check them (-- --package | --binary ; --pi ) +npm run build:binary # build, then compile release/tau--/ and its .tar.gz/.zip (-- --target bun--) npm run typecheck && npm run lint +npm run release:check # typecheck, lint, test, build, smoke ``` -The dev server needs ompweb's omp build (`runner/`). Fetch the pinned omp packages first, then install -(`npm test` needs this too): -`bun runner/scripts/use-omp-build.ts && cd runner && bun install --frozen-lockfile`; then build -`runner/release/ompweb-omp--` (`bun runner/scripts/build-binary.ts`, this machine's target), which a source checkout -finds by itself, or point `OMP_WEB_OMP_BIN` at it or at a wrapper running `bun runner/src/cli.ts`. -All live-agent features go through it; session browsing works without it. +Live sessions need pi: `npm i -g @earendil-works/pi-coding-agent`, or point `TAU_PI_BIN` at a pi binary or wrapper +script (`lib/pi/pi-cli.ts`: `TAU_PI_BIN`, else `pi` on `PATH`; a miss is re-probed after 30 s). Without it a host +reports `pi-missing` and live commands fail with `pi_not_found`; session browsing still works. --- ## Architecture -omp-web never imports `@oh-my-pi/*` or `@earendil-works/*` packages, even -though the server now runs on Bun: live work goes through the `ompweb-omp` -child (`runner/`, ompweb's own omp build). See `DESIGN.md` for the full porting contract. +tau never imports pi's SDK (or any `@earendil-works/*` package): every live session is a `pi --mode rpc` child, +started with tau's companion extension `--extension lib/pi/tau-extension.ts`. See `DESIGN.md` for the porting contract. ``` -Browser Bun server (server/app.ts) omp child process - │ │ │ - ├─ GET /api/sessions ────▶ reads ~/.omp/agent/sessions/ │ - ├─ GET /api/sessions/[id] reads .jsonl file directly │ - ├─ SharedWorker ── GET /api/events ──▶ ONE multiplexed SSE per browser │ - │ (all tabs) POST /api/events ─▶ subscribe running/session/file │ - │ │ │ - ├─ send message ─────────▶ POST /api/agent/[id] │ - │ │ startRpcSession() ── spawn ─────▶│ ompweb-omp --headless - │ │ sendCommand({type:"prompt"}) ───▶│ (channel, NDJSON stdio) - │ │ │ - ├─ session subscription ─▶ event-stream-hub onEvent() │ - │ │ onFrame() ◀── event frames ──────│ - │◀── event: s data: {...} ──│ │ +Browser Bun server (server/app.ts) tau host daemon (Node) pi child + │ │ │ │ + ├─ GET /api/sessions ──────────▶ listSessions op ─────── host link (WS) ───▶ reads ~/.pi/agent/sessions │ + ├─ SharedWorker ─ GET /api/events ▶ ONE multiplexed SSE per browser │ │ + │ (all tabs) POST /api/events ▶ subscribe running/session/file/... │ │ + ├─ send message ──────────────▶ POST /api/agent/[id] │ │ + │ │ startRpcSession() ── open/spawn ────────▶ │ pi --mode rpc ─────────▶│ + │ │ sendCommand({type:"prompt"}) ───────────▶ │ --extension tau-extension.ts + │ │ onFrame() ◀── stdout JSONL frames ──────── │ ◀──────────────────────│ + │◀── 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 -session's `Host` (`lib/hosts/host.ts`; `localHost` in `lib/hosts/local-host.ts`) -to spawn `ompweb-omp --headless` (one process per active session) and runs -`lib/omp/rpc-process.ts` over the returned transport. Every machine-local -action of a session wrapper (spawn, session-file checks, list invalidation) -goes through that host. - -Shared foundations in `lib/omp/`: - -- `paths.ts` — Node port of omp's directory resolution (`~/.omp/agent`, - XDG, session dir slugs) and `sessionLocalRoot`, omp's `local://` root rule. -- `omp-cli.ts` — locate/probe the `ompweb-omp` binary (`resolveOmpBin`, - `getOmpVersion`): `OMP_WEB_OMP_BIN`, else a source checkout's `runner/release/`, else the fetched copy - (`fetchedOmpBin`: beside a compiled binary, otherwise `/omp-web/omp//`). -- `runner-fetch.ts` — `fetchOmpRunner`/`ensureOmpRunner`/`ompweb fetch-omp`: downloads this version's - `ompweb-omp-` from its own GitHub release (repo from `package.json` `repository`, `lib/release-repo.ts`), - checks it against the release's `ompweb-omp.sha256` and writes it atomically. The web server and the daemon run it in - the background at start when the runner is missing. There are no runner npm packages. -- `rpc-process.ts` — process + NDJSON channel layer (`RpcProcess`; `rpc-*` names are historical, the wire is the `ompweb-omp` channel of `docs/specs/2026-11-12-omp-runner-design.md`). -- `rpc-transport.ts` — `RpcTransport`: the byte pipe under `RpcProcess` - (`spawnLocalRpcTransport` for a local child; `RemoteRpcTransport` in - `lib/hosts/hub.ts` for a remote one). -- `auth-gateway.ts` — shared, idle-killed `omp auth-gateway stdio` child: - omp's own credentials and models behind JSON-line gateway requests. -- `auth-broker.ts` — idle-stopped `omp auth-broker serve` child of the web - server (started on the first forwarded request, stopped after 5 minutes with - none in flight): `brokerFetch`, `abortBrokerRequests`. +- The launcher (`bin/tau.js`), the host daemon (`bin/tau-host.js`, `tau host`) and the tray run on Node. The launcher + spawns `bun server/main.ts` (Bun from `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. The daemon and tray must + not use Bun APIs. The compiled binary (`server/binary.ts`) is one Bun program: the server in its own process, plus + `tau host`, `tau preflight` and `tau hash-password`. +- **Every machine runs sessions through a daemon**, this one included: main never spawns a session pi. The web server + links to this machine's own `tau host` daemon like to any remote host (see "Remote hosts"). `startRpcSession()` + (`lib/rpc-manager.ts`) asks the session's `Host` (`getHost(id)`, `lib/hosts/hub.ts`) for an `RpcTransport`; the + daemon spawns pi with `localHost` (`lib/hosts/local-host.ts`), and `lib/pi/rpc-process.ts` (`RpcProcess`) speaks + pi's RPC over it. The one deliberate pi child on main is the utility process (`lib/pi/rpc-utility.ts`: + `--no-session --no-skills --no-mcp`, idle-killed after 5 min) for global reads such as `get_available_models`. +- **Session browsing** is pure Node parsing of session `.jsonl` files (`lib/session-reader.ts`, + `lib/pi/session-files.ts`), run in the owning host's daemon (`host.sessionOps`), never a pi process. +- The `rpc` in `rpc-manager.ts`/`RpcProcess`/`RpcTransport` is pi's RPC mode. + +### pi's RPC and what tau adds + +pi speaks JSON lines on stdin/stdout: commands answered by `{type:"response", id, success, data|error}`, and events +(`agent_start`, `agent_end`, `turn_start/end`, `message_start/update/end`, `tool_execution_start/update/end`, +`queue_update`, `agent_settled`, `extension_ui_request`, ...). `RpcProcess` normalizes them: + +- `agent_settled` is re-emitted as tau's `session_settled` (the end of a run and everything it continued into). +- `get_state` answers are completed with what tau reads and pi does not report (`withQueueAndSettlement`): + `queuedMessages` (from the last `queue_update`), `queuedMessageCount` (pi's `pendingMessageCount`), `isSettled`, + `supportsClientMessageIds`. +- Extension UI dialogs (`select`, `confirm`, `input`, `editor`) become tau `ui_request` frames and their answers + `extension_ui_response`; `notify` becomes a `notice`. `input` dialogs titled `__tau_host_tool__` / `__tau_ask__` + become `host_tool_call` / `ui_request{method:"askDialog"}`. +- The extension talks back through `setWidget("tau", [])` frames: `tau_hello`, `tau_message_identity`, + `tau_queue`, `tau_reply` (the answer to a `callExtension`), `btw_*`, `tau_auth_event`. +- tau calls the extension with `prompt` commands `/tau_ ` (`callExtension`; the daemon recognizes them, + `isExtensionCommand`, and never treats them as user messages): + - `/tau_host_tools`: register the server's host tools (`set_host_tools`). + - `/tau_meta`: message identity and origin (`name`, `status`, `clear`), journaled as `client-message-entry` and + `client-message-resolution` custom entries. + - `/tau_btw`: side questions (ask, cancel, history; records persisted as `tau_btw` custom entries). + - `/tau_edit`: history Edit (`navigateTree(entryId, {summarize:false})`). + - `/tau_auth`: provider logins through pi's `ModelRuntime` (`providers`, `login`, `api_key`, `logout`). +- pi's wire `message_update` is delta-only and carries no message or id: the daemon shapes it (`piStreamFrame`, see + "Streaming message updates"). +- pi-subagents (the pi package) needs no extension bridge: `lib/pi/subagent-bridge.ts` turns its `subagent` tool + progress and `subagent-async` widget snapshots into tau's `subagent_lifecycle`/`subagent_progress` frames and + answers `get_subagents`. +- `TAU_NO_EXTENSION=1` starts pi without the extension (tests only). `resolveTauExtensionPath` looks under + `TAU_PACKAGE_DIR`, then beside `rpc-process.ts`, never in the session's cwd. Without that flag a missing extension + refuses the spawn (`TAU_EXTENSION_MISSING`): pi would read every `/tau_*` call as a prompt and send it, an API key + included, to the model. With the flag `RpcProcess.callExtension` refuses every call for the same reason; it reads the + calling process's environment, so the flag is for single-process tests and never for a daemon. + +### `lib/pi/` (pi foundations) + +- `paths.ts`: pi's directory rules. Agent dir `~/.pi/agent` (`PI_CODING_AGENT_DIR` overrides it); sessions `/sessions/----/` (`getSessionDirNameForCwd`); archive + `/../archive/sessions`; `settings.json`, `models.json`; `getTauDataDir()` (`/tau`); `sessionLocalRoot` + (a session's local directory, where uploads land: `/local`, Windows long paths + `/tau-local/`). +- `pi-cli.ts`: `resolvePiBin`, `getPiVersion` (cached by binary fingerprint), `wrapWindowsScript` (`.cmd`/`.bat` via + `cmd.exe /c`), `PI_NOT_FOUND`. +- `rpc-process.ts` / `rpc-transport.ts`: `RpcProcess` (see above) over an `RpcTransport` byte pipe + (`spawnLocalRpcTransport` in the daemon, `RemoteRpcTransport` in `hub.ts` on main). +- `tau-extension.ts`: the companion extension (loaded by pi, not by tau's server). +- `rpc-utility.ts`: the utility pi (`runUtilityCommand`, `runUtilityExtension`). +- `session-files.ts`: session file reading/writing, listing walk (`listSessionFiles`), migrations; `archive.ts`: + archive and restore. +- `settings-config.ts` (allow-listed keys of pi's global `settings.json`), `models-config.ts` (`models.json`), + `mcp-config.ts` (MCP configuration files), `plugins-cli.ts` (`pi list` parsing), `agent-env.ts` / + `agent-env-policy.ts` (extra environment variables for pi children), `subagent-bridge.ts`. + +### tau's own files + +- `/tau/`: `hosts.json`, `pools.json`, `pool-starts.json`, `host.json` (the daemon's links), + `host-control.json`, `host-running.json`, `uploads/`, `upload-retention.json`, `outbox.db`, the notification + store, `github-watches.sqlite`, Actions receipts, `archive-restore-locks.sqlite`, `server-upgrades/`, + `web-auth-secret.json`, `transport-metrics.jsonl`, `cluster-config/`, `own-config/`. +- `/tau-settings.json` (+ `tau-settings.lock.sqlite`): server settings (`lib/web-settings.ts`). +- `/projects.json`: managed projects. `/tau-interrupted-sessions-.json`: auto-resume lists. +- `/tau/media/`: tool-result image copies and thumbnails; `/tau/diagnostics.log`: crash/stall journal. --- @@ -88,217 +123,134 @@ Shared foundations in `lib/omp/`: ``` 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) + main.ts production entry: sets NODE_ENV, then `startProduction` (app.ts); prints the `Ready on` line the launcher waits for + binary.ts the compiled `tau`: launcher checks and `startProduction` in-process, `host` (host-cli.ts), `preflight`, `hash-password` + dev.ts dev entry (`bun --hot`): HTML import with HMR; re-runs itself once with TAU_PUBLIC_* set so bunfig.toml can inline them + app.ts `startServer`: Bun.serve + route table + gate + SPA fallback + the one websocket handler; `startProduction` + 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`, `renderIndex` + client-env.ts build-time constants for the browser bundle; `buildEventStreamWorker` 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 + index.html SPA shell and bundler entry; #root holds static copies of RouteLoadingFallback and LoginForm's first render + client.tsx browser entry: `LoginForm` on /login, else `AppShell` (a path check, no router) + boot.ts runs first: installs the sidebar history bridge before AppShell registers popstate listeners + globals.css design tokens and global styles 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 - sessions/[id]/route.ts GET/PATCH/DELETE session - sessions/[id]/context/route.ts GET ?leafId= — context for a specific leaf - sessions/[id]/matches/route.ts GET ?q=&limit= — best `limit` search hits in the active conversation (best match, then newest); Load more asks for a longer prefix - sessions/[id]/export/route.ts GET exported HTML for a session - sessions/[id]/local-file/route.ts GET ?uri=local:// → `{ path, sessionId }`: the absolute path of a file in the session's own local:// directory, resolved on the owning host's daemon, and the canonical session that owns it (a live alias resolves to its current id; the tab must store that, since the alias goes with its wrapper). The open_file host tool then reads it through /api/files with that `sessionId`; 400 `invalid_local_uri` / `not_a_file`, 404 `session_not_found` / `file_not_found`, 403 on a symlink out, 501 `workspace_unsupported` for a host daemon that predates `resolveLocalFile` - agent/new/route.ts POST { cwd, message, toolNames?, provider?, modelId? } - agent/[id]/route.ts GET state | POST any channel command - events/route.ts GET multiplexed SSE | POST subscribe/unsubscribe channels - events/link/route.ts GET WebSocket upgrade: the browser link (lib/browser-link.ts), bound to the request's web session; gated like every API route, 426 without an upgrade - transport-metrics/route.ts GET { now } (the SSE clock probe) | POST { samples } → /omp-web/transport-metrics.jsonl - hosts/route.ts GET hosts (this machine first) | POST { label } → token once + login command | PATCH { id, label?, allowAgentStart?, shareCredentials? } (`local`: label only, empty resets to "This machine"; `shareCredentials` on `local` is 400) | DELETE ?id= revoke (registry first, then close the link); 503 if hosts.json is unreadable - hosts/link/route.ts GET WebSocket upgrade (the `ompweb host` daemon; bearer checked before the upgrade, skipped by the `proxy.ts` gate) | POST 426 for pre-WebSocket daemons - hosts/broker/[...path]/route.ts allow-listed forwarding of an omp auth broker's endpoints for a host that shares credentials (`sharesCredentials`: its `shareCredentials` flag or cluster membership); authenticated by the host token, outside the password gate (`proxy.ts` `UNGATED`); see "Remote hosts → Shared credentials" - hosts/cluster-config/manifest/route.ts GET the master's mirrored-configuration manifest (`{ version, files, agentEnv, plugins }`) for a cluster member; host token, members only (`admitClusterMember`: 401 unknown token, 403 `local`/not a member, 503 unreadable `hosts.json`/`pools.json`), 409 `{ error, code }` when the configuration cannot be built (`ClusterConfigError`); outside the password gate (`proxy.ts` `UNGATED`); see "Remote hosts → Cluster configuration" - hosts/cluster-config/file/[hash]/route.ts GET one file of the current manifest by its sha256 (404 for any other hash, an older version's included); same admission and gate as the manifest - hosts/[id]/cluster/route.ts PUT { projectsRoot } join the cluster (the host's Git projects bind to cluster projects by repository, `gitOrigins`; this machine is added too by any join while it is not a member; the host needs link protocol 10; 409 `host_in_other_cluster` when it holds another server's configuration), then sends the host its configuration (`clusterConfigOp` `apply`) | DELETE leave, then `restore` (none to a daemon below protocol 10, which never applied one); the body carries `restoreError` when the host could not put its own configuration back; 409 `{ error, code }` for offline/old daemon/`cluster_changed`, 503 if `pools.json` is unreadable - notifications/devices/route.ts GET VAPID key + subscribed | PUT { deviceId, prefs, subscription? } - notifications/presence/route.ts POST { clientId, deviceId, visible, sessionId, seq } - notifications/test/route.ts POST { deviceId } send a test push (502 on push-service refusal) - notifications/history/route.ts GET entries | PATCH { ids } mark read | DELETE ?id= remove one, ?all=1 clear - auth/** provider list, login/logout, API keys (via channel commands) - cwd/validate/route.ts POST validate/select a cwd - default-cwd/route.ts POST create ~/omp-cwd-YYYYMMDD - files/[...path]/route.ts GET file contents for viewer - github-repo/route.ts GET ?cwd= — GitHub owner/repo of the checkout (for #N links) - media/[hash]/route.ts GET tool-result image by sha256 (?thumb=1 → 480px WebP preview) - home/route.ts GET user home directory - models/route.ts GET { models, modelList, defaultModel } - models-config/route.ts GET/PUT — read/write ~/.omp/agent/models.yml - models-config/test/route.ts POST test a configured model/provider - omp-settings/route.ts GET/PUT native config.yml settings (allow-listed) - web-settings/route.ts GET/PUT omp-web's own server settings (auto-resume, agent tools, agent env, browser transport; a transport change is pushed to every open browser) - mcp/route.ts GET/POST/PUT/DELETE project MCP servers; `GET ?sessionId=&attach=1` reads a running session's live MCP status and never starts one (a cluster session on another member) - plugins/route.ts GET/POST plugin management (shells out to `omp plugin`); without `cwd`, the user level only (omp runs in the agent directory; a `project` scope POST without `cwd` is 400 `cwd_required`) - projects/route.ts GET registered+discovered projects | POST add | DELETE hide - projects/clone/route.ts POST clone a git URL into a new workspace (NDJSON progress) | DELETE cancel - skills/route.ts GET/PATCH loaded skills and disable-model-invocation; GET without `cwd` lists the user level only (`skills/check` and `skills/update` likewise; project scope needs a `cwd`: 400 `cwd_required` from check, `cwd_package_scope_required` from update) - skills/install/route.ts POST install skills through npx skills add - skills/search/route.ts GET/POST skills.sh search - stt/route.ts POST audio (+scope) → 202 { jobId } | GET ?scope= live jobs (lib/stt-jobs.ts) - stt/[jobId]/route.ts GET job state | POST retry with kept audio | DELETE ?claim= claim/discard - stt/[jobId]/audio/route.ts GET the kept recording (audio/* only) for playback - uploads/route.ts POST { id, host, name, size, type } start/resume a composer upload (SSE-mode path of the browser link's `up_start`) → { received, done } - uploads/[id]/route.ts PUT ?offset=N raw body ≤ 1 MiB, answered once the host acked it (409 `upload_offset` with { received }) | DELETE abort - worktrees/route.ts GET/POST/DELETE git worktrees + sessions/route.ts GET all sessions, every host + sessions/search/route.ts GET ?q= NDJSON { scores } batches (titles + per-host transcripts) + sessions/import/route.ts POST import a session .jsonl + sessions/archive/route.ts GET archives of every host | POST restore (see "Session archive and restore") + sessions/[id]/route.ts GET/PATCH/DELETE a session + sessions/[id]/state/route.ts GET live state; always carries `outbox`, `outboxSettledIds`, `outboxScope` + sessions/[id]/context/route.ts GET ?leafId= context of one leaf (read-only branch view) + sessions/[id]/entries/[entryId]/thinking/route.ts GET one deferred thinking block + sessions/[id]/matches/route.ts GET ?q=&limit= best search hits in the active conversation + sessions/[id]/export/route.ts GET exported HTML (`tau-session-.html`; a remote session's always as an attachment) + sessions/[id]/archive/route.ts POST stop the live child, then archive on the session's host + sessions/[id]/auto-name/route.ts POST stored title, else one derived from the first user message (`generated` always false) + sessions/[id]/subagents/route.ts, subagents/[subagentId]/route.ts subagent roster history and transcripts + agent/new/route.ts POST start a session (host, pool or cluster target) + agent/[id]/route.ts GET state | POST any agent command (`runAgentCommand`) + agent/[id]/bash-output/route.ts GET streamed `!` command output + events/route.ts GET the multiplexed SSE | POST subscribe/unsubscribe channels + transport-metrics/route.ts GET { now } (clock probe) | POST { samples } → /tau/transport-metrics.jsonl + hosts/route.ts GET hosts | POST { label } → token once | PUT { pools } | PATCH { id, label?, allowAgentStart? } or { poolId, label } | DELETE ?id= revoke + hosts/link/route.ts GET the application link WebSocket (bearer checked before the upgrade; ungated) + hosts/maintenance/route.ts GET maintenance API v1 discovery and WebSocket (bearer; ungated) + hosts/[id]/maintenance/route.ts GET a host's maintenance status (gated) + hosts/[id]/updates/route.ts GET update status | POST { target: "tau", version, force? } + hosts/[id]/cluster/route.ts PUT { projectsRoot } join the cluster, then `apply` | DELETE leave, then `restore` + hosts/cluster-config/manifest/route.ts, file/[hash]/route.ts the master's configuration for members (host token; ungated) + auth/providers, auth/all-providers, auth/login/[provider], auth/api-key/[provider], auth/accounts/[provider] per-host pi logins (?hostId=) + models/route.ts GET models (utility pi) | models-config/route.ts GET/PUT models.json | models-config/catalog/route.ts GET models.dev search + pi-settings/route.ts GET/PUT allow-listed keys of pi's settings.json + pi-version/route.ts GET the installed pi version + web-settings/route.ts GET/PUT tau's server settings + web-auth/session/route.ts POST password login session + app-update/route.ts, app-update/notes/route.ts coordinated server upgrade (prepare/commit) and release notes + windows-service/route.ts Windows service status/actions + mcp/route.ts GET/POST/PUT/DELETE MCP server configuration (no live status) + plugins/route.ts GET/POST pi packages (`pi list/install/remove/update`) + skills/route.ts, check, update, install, search skill listing, disable-model-invocation toggle, updates, `npx skills add`, skills.sh search + projects/route.ts GET registered+discovered projects | POST add | DELETE hide + projects/clone/route.ts POST clone (NDJSON progress) | DELETE cancel + worktrees/route.ts GET/POST/DELETE git worktrees on the owning daemon + files/[...path], file-index, git/status, git/diff, cwd/browse, cwd/validate, default-cwd, home, github-repo workspace reads (daemon-owned) + media/[hash]/route.ts GET tool-result image by sha256 (?thumb=1 → 480px WebP) + notifications/devices, presence, history push devices, presence reports, notification history + stt/route.ts, stt/[jobId]/route.ts, stt/[jobId]/audio/route.ts transcription jobs + uploads/route.ts, uploads/[id]/route.ts composer uploads (start/resume, chunks, abort) + usage/route.ts, manifest/route.ts usage report; web app manifest lib/ - dynamic.tsx `dynamic()` over `React.lazy` + `Suspense` - navigation.ts `useRouter`/`useSearchParams` over the History API - omp/ shared omp foundations (paths, CLI probe, RpcProcess) - plugins-cli.ts `runOmpCli`, `listPlugins` (`omp plugin list --json` as `PluginEntry[]`), `parseJsonLoose`, `ANSI_RE`; loaded by the daemon too (relative imports only); used by `app/api/plugins/route.ts`, `cluster-config-server.ts` and `daemon-cluster-config.ts` - 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`. 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`) - host-login.ts `host.json` (`loginHost`, `readHostLogin`) and `isLoopbackHost`, shared by the daemon and local-bootstrap - session-ops.ts file-reading half of the session/project routes, run on the owning host's daemon (this machine's too) - uploads.ts daemon side of composer uploads: `StagedUploads` (staging dir `/omp-web/uploads/`, offset writes, 24 h sweep, attach into the session's `local/uploads/`), `sanitizeUploadName` - upload-retention.ts daemon side of sent-upload retention: `UploadRetention` (op `setUploadRetention`, `/omp-web/upload-retention.json`, sweep at start and every 24 h), `sweepSentUploads`; `upload-retention-sync.ts` is main's side (`startUploadRetentionSync` on every hello, `pushUploadRetention` when the setting changes) - link-protocol.ts link messages, codec, binary blob frames, close codes, size limits, `HOST_OP_NAMES`, `SeqWindow`/`Outbox`, `LinkSender`/`PartJoiner` (pieces, fair sending) - hub.ts main side: the link's upgrade and `websocket` handler (`handleLinkUpgrade`, `hostLinkSocket`), `RemoteHost`, `getHost`, `listHosts`, adoption of live children (`reattach`/`adopt`), orphans, `freezeHostLinks`, `hosts` change events - daemon.ts daemon side: `runHostDaemon` (reconnect, buffering, op dispatch, hello with each child's `{sessionId, cwd, pending}`; follows a `host.json` url or token change when a dial fails; loopback redials at most 3 s apart) - pending-requests.ts daemon side: `PendingRequests`, a channel's still-open blocking requests and current session id for the hello - daemon-broker.ts daemon side: the loopback forwarder that gives a sharing host's omp processes `OMP_AUTH_BROKER_URL`/`OMP_AUTH_BROKER_TOKEN` (`credentialsEnv`); forwards to the link's server with the link's host token - registry.ts `/omp-web/hosts.json`: create/update/revoke, token hashing and lookup; the `local` record (`rotateLocalHostToken`, `customLocalLabel`) - session-index.ts sessions and projects across hosts, cached per host; `hostForSessionId`, `sessionSpawnTarget`, `invalidateLocalSessionLists` - cluster.ts pure cluster rules: `clusterOf` (= `pools[0]`), `isClusterMember`, `sharesCredentials`, `joinCluster`/`leaveCluster`, `clusterJoinBlock`, `ompSharesCredentials` (also the daemon's spawn check); browser-importable (Settings uses it) - cluster-config.ts pure, daemon-safe: what a cluster member mirrors from the master (`MIRRORED`, `LOCAL_SETTINGS`, `CONFIG_LIMITS`), `buildManifest`, `stripLocalSettings`/`mergeLocalSettings`, `isManagedPath`, `ClusterConfigError` - cluster-config-server.ts main side: `currentClusterConfig` (the manifest cached per fingerprint, one build at a time, `omp plugin list` cached 120 s), `clusterConfigVersion`, `admitClusterMember`, `configErrorResponse`; used by the two `app/api/hosts/cluster-config/` routes and `hub.ts` - daemon-cluster-config.ts daemon side: `createClusterConfig` (`ensure`/`apply`/`restore`/`state`/`holds`/`stop`): download, verify, apply whole or not at all, the member's backup (`own-config/`), plugins, leaving; Node only, relative imports - host-bearer.ts `hostFromBearer`: the host an `Authorization: Bearer ` request names, or the 401/503 answer; used by `admitClusterMember` - update-types.ts shared per-host software status and operation contract - updates.ts daemon-side version checks, compatibility gate and durable update state - update-worker.ts host-only install/restart helper; never starts or stops the web-server service - github/ GitHub agent tools (server only; spec `docs/specs/2026-11-13-github-watch-tool-design.md`) - gh.ts the server's `gh` runner: `GhRunner`, `checkGh` (60 s login cache), target parsing; env from `createChildProcessEnvironment` - api.ts GitHub data over `gh api`: metadata snapshots; `readItem` is the one path that returns GitHub text - events.ts pure diff of a snapshot against a watch's cursor; words metadata-only updates - watch-store.ts `/omp-web/github-watches.sqlite` (WAL): watches, cursors, pending updates, posted comment ids, read grants; `removeSessionWatches`/`renameSession` do nothing when the file does not exist (a session delete never creates, or on Windows holds open, a store) - watcher.ts 60 s poller: pending row, then a `prompt` outbox add, then the cursor on acceptance - tools.ts the five tools (`GITHUB_TOOL_NAMES`, `GITHUB_REPLAY_SAFE_TOOLS`), run after agent-tools' enabled and rate checks - provider-accounts.ts distinct omp accounts per provider from `omp usage` reports (Models → provider detail) - agent-client.ts agent commands from the tab: POST /api/agent/[id], or the worker's browser link in the `ws` transport; records each command's `action` sample - agent-command.ts `runAgentCommand`: the one command path behind POST /api/agent/[id] and a browser link's `cmd` - browser-link.ts `/api/events/link`: Bun `websocket` handler for the browser link (sequencing, pieces, resume, `(session, rid)` dedupe) - btw.ts /btw side-question records + pure frame/snapshot merge (order-safe) - draft-store.ts local draft persistence helpers - event-stream.ts tab-side EventSource-shaped streams over the shared worker - event-stream-worker.ts the shared worker: the one EventSource or browser link per browser (bundled by server/client-env.ts) - event-stream-hub.ts server connections + running/session/file channels for /api/events (SSE) and the browser link (`FrameSink`); `broadcastBrowserTransport` - event-stream-protocol.ts wire contract shared by hub, route, and facade - file-access.ts allowed file roots for /api/files and worktrees - file-authorization.ts single allow-list gate for /api/files and the file channel: allowed roots, the session's own `local://` directory (confined, symlinks included) or the session transcript's references - media-cache.ts tool-result images → /api/media URLs; media copies + thumbnails - file-paths.ts client/server path encoding helpers; `getFileApiUrl`, the one builder of a file tab's `/api/files` URLs - local-uri.ts `local://` parsing exactly as omp's local-protocol.ts reads it (pure; browser and server) - session-local-files.ts daemon side: a session's `local://` root (`sessionLocalRootFor`: verified live-file hint, else the daemon's session index, then `sessionLocalRoot`), a path resolved inside it, and the file gate's check - github-refs.ts remark plugin linking #N / owner/repo#N + GithubRepoContext - git-clone.ts pure clone helpers: URL→directory name (https/ssh only), \r-aware progress log - github-repo.ts server: pick the gh-default GitHub remote from git config - markdown.ts shared markdown helpers - remark-pandoc-math.ts remark-math with Pandoc's single-dollar rule, so prices ("$5 and $10", "R$5") stay text; chat and search listing - npx.ts npx runner used by skill install - pi-types.ts local structural types for agent/RPC objects - project-command-env.ts child-process environments: strips PORT/NODE_ENV/NEXT_* and omp-web's secrets - project-ordering.ts pure project sort/group/activity helpers (client + tests) - project-registry.ts on-disk managed-project registry (~/.omp/agent/projects.json) - notification-events.ts shared: event/prefs/history-entry types, frame→event detector, renderNotification() - notification-hub.ts server: presence, routing, Web Push, recording published notifications - notification-store.ts server: SQLite store for VAPID keys, devices and the notification history - notification-history.ts browser: mirror of the server's notification history (Notifications tab) - notification-client.ts browser: device id, prefs store, service worker + push subscription - rpc-manager.ts session registry + startRpcSession over RpcProcess (spawn via a Host) - session-reader.ts session .jsonl parsing + path cache + buildSessionContext - session-search.ts shared fuzzy/phrase query scorer for sidebar search (title weights ≫ transcript) - session-content-search.ts server: per-file transcript text cache (size+mtime) + searchSessions() - session-search-matches.ts shared types/constants of the sidebar's per-session search hits - session-match-listing.ts server: lists a session's search hits counted per rendered text node (remark parse) - session-resume.ts running-session list for auto-resume after a restart - web-auth.ts password-hash check + session cookie signing - web-auth-secret.ts per-installation session-signing key (~/.omp/agent/omp-web/web-auth-secret.json) - web-password-hash.ts typed view of bin/omp-web-password-hash.js (the scrypt hash format) - web-settings.ts omp-web server settings (~/.omp/agent/omp-web-settings.json) - transport-metrics.ts transport samples → `/omp-web/transport-metrics.jsonl` (renamed to `.jsonl.1` above 20 MiB) - transport-stats.ts durations of transport samples (percentiles, per-metric derivation) shared by the worker's Connection tab stats and scripts/transport-metrics.ts - skills-service.ts skill listing via `omp skill list --json`; pure-Node replica scan as fallback - tool-presets.ts PRESET_NONE/DEFAULT/FULL + getToolNamesForPreset() - types.ts shared TypeScript types - normalize.ts normalizeToolCalls() — field name mismatch between file format and our types - navigation-history.ts pure back/forward view-history stack + shortcut matcher (⌘[/⌘], Alt+←/→) - word-prediction.ts pure ghost-text arithmetic (advance/accept) for composer word prediction - worktree.ts project/worktree resolution and git worktree operations - -components/ - AppShell.tsx layout + URL state + tab management - SessionSidebar.tsx session tree + FileExplorer; with a linked host the workspaces group per host (`HostGroup`), keyed by `hostProjectKey` (`lib/project-ordering.ts`: bare path on this machine, `:` elsewhere) - ChatWindow.tsx chat composition + completion sound wrapper - ChatInput.tsx input bar + model/thinking/tools/compact controls - ComposerPanels.tsx composer-attached /btw + todo + subagent panels (collapsible, live states) - BtwPanel.tsx /btw side-question panel (stream, cancel, copy, follow-up) + history dialog - SessionSearchMatches.tsx a search result's hits under its sidebar row (10 at a time + "Load more…") - TodoList.tsx todo phase grid with preview/show-all (used by ComposerPanels) - SubagentTranscriptDialog.tsx task + final output summary dialog (wide, screen-adaptive) - MessageView.tsx renders one message (user/assistant/toolCall/toolResult) - CommandPalette.tsx ⌘K/Ctrl+K palette (cmdk): session switch, new session, theme - ImageLightbox.tsx click-to-preview lightbox for chat images (ClickableImage) - BranchNavigator.tsx in-session branch switcher - NotificationList.tsx notification history list + Mark all read/Clear actions (mobile right-panel tab, desktop bell popover) - NotificationBell.tsx desktop top-bar bell: unread badge + floating NotificationList popover - ConnectionDiagnostics.tsx right-panel Connection tab: transport in use, status, latency stats (opt-in, Settings → Interface & Behavior) - ChatMinimap.tsx scroll minimap alongside the message list - MarkdownBody.tsx markdown renderer - ModelsConfig.tsx modal for models/auth configuration - McpConfig.tsx project MCP server editor (Settings → MCP tab) - HostsConfig.tsx linked hosts: add (token shown once), rename, revoke, allowAgentStart (Settings → Hosts tab) - HostUpdates.tsx per-host ompweb/OMP versions, update checks, blocked reasons and update actions - LocalDaemonBanner.tsx production-only hint with the install command while no local daemon has linked (90 s grace) - host-status.ts host name, status text and dot colour shared by Settings → Hosts and the sidebar - PluginsConfig.tsx modal for installed plugins - SkillsConfig.tsx modal for loaded/search/installable skills - FileExplorer.tsx file tree inside sidebar - FileViewer.tsx file content in a tab - GhostMirror.tsx textarea overlay painting ghost-text word completion - TabBar.tsx tab bar (Chat + open file tabs) - WorktreesPanel.tsx file-panel Worktrees tab: list/switch/create/remove the active repo's worktrees - ui/ shared primitives: Dialog/Tooltip/Collapsible, fields, toast - -hooks/ - useAgentSession.ts messages + streaming + SSE + fork/navigate/reconciliation logic - useHostRows.ts the `hosts` channel as React state (status of every host; sidebar, new-session picker, Settings → Hosts) - useAudio.ts completion sound + browser AudioContext unlock - useNotifications.ts presence reports, toast/system delivery, notification clicks - useDragDrop.ts shared drag/drop state - useIsMobile.ts responsive breakpoint hook - usePrefersReducedMotion.ts OS reduce-motion preference (SMIL-safe) - useTheme.ts theme state (localStorage key "omp-theme"; top bar color → theme-color meta, "omp-theme-color" cookie and the manifest link's ?theme=, see lib/manifest-theme.ts) - useNavigationHistory.ts in-app back/forward stack (record/peek/commit/drop) for visited chat views - useWordPrediction.ts debounced omp predict_word ghost text + feedback - useBtw.ts /btw records/active panel/history dialog fed by btw_* SSE frames - useChatSearchHighlights.ts find-in-page for the sidebar search: CSS Custom Highlight API paint + jump to a picked hit + pi/ pi foundations (above) + rpc-manager.ts session wrappers (`AgentSessionWrapper`), registry, `startRpcSession`, command handling + agent-command.ts `runAgentCommand`: the one command path behind POST /api/agent/[id] + agent-client.ts agent commands from the tab (POST /api/agent/[id]); records `action` samples + agent-tools.ts, agent-tool-hosts.ts server-run agent tools (new_session, send_to_session, list_sessions, ...) and the host-confirm rule + github/ GitHub agent tools: gh.ts, api.ts, events.ts, watch-store.ts, watcher.ts, tools.ts, actions.ts, action-tools.ts, action-receipts.ts + hosts/ hosts, link, maintenance API, daemon (see "Remote hosts"); notable: hub.ts, daemon.ts, daemon-link.ts, + daemon-channels.ts, channel-lifecycle.ts, shared-requests.ts, stream-snapshot.ts, pending-requests.ts, + maintenance-protocol.ts, maintenance-hub.ts, daemon-maintenance.ts, daemon-auth.ts, preflight.ts, + cluster*.ts, daemon-cluster-config.ts, pools.ts, pool-starts.ts, capacity.ts, host-control.ts, + local-daemon-start.ts, local-daemon-supervisor.ts, workspace-*.ts, updates.ts, update-worker.ts + event-stream.ts tab side: EventSource-shaped streams over the shared worker; `uploadFile`; `addToOutbox` + event-stream-worker.ts the SharedWorker: one /api/events EventSource per browser, the outbox's IndexedDB leg, metrics + event-stream-hub.ts server channels for /api/events; backpressure merging + event-stream-protocol.ts wire contract shared by hub, route and facade; `NO_SPAWN_REPLIES` + message-outbox.ts, message-outbox-schema.ts, outbox-handoff.ts, client-message-ids.ts, message-origin.ts message outbox and identity + message-delta.ts, message-update-coalescer.ts streaming deltas (server and browser) + session-reader.ts session parsing, path cache, `buildSessionContext`, `listAllSessions` + session-search.ts, session-content-search.ts, session-search-matches.ts, session-match-listing.ts sidebar search + session-resume.ts per-web-server auto-resume (transports without host-owned lifecycle) + session-local-files.ts daemon side: a session's local directory and whether a path lies in it (the file gate) + file-access.ts, file-authorization.ts allowed roots and the file gate; `isPiSecretFile` + file-paths.ts `getFileApiUrl` and path encoding + media-cache.ts tool-result images → /api/media URLs + uploads.ts main side of composer uploads (registry, relay to the daemon) + upload-limits.ts upload limits (browser-safe) + btw.ts /btw records and order-safe merging + subagent-types.ts, subagent-history.ts, subagent-format.ts, task-result-details.ts subagents + notification-events.ts, notification-hub.ts, notification-store.ts, notification-history.ts, notification-client.ts notifications + host-auth.ts server side of the auth routes (per-host `auth` op) + models-cache.ts, model-catalog.ts, model-scope.ts models list cache, models.dev catalog + skills-service.ts, skill-lock.ts, skill-updates.ts skill discovery mirroring pi + project-registry.ts, project-ordering.ts, pooled-projects.ts, worktree.ts, git-clone.ts, project-clone.ts projects + web-settings.ts, web-auth.ts, web-auth-secret.ts, web-password-hash.ts, request-security.ts settings and auth gate + self-update.ts, server-update-worker.ts, upgrade-plan.ts, upgrade-process.ts, upgrade-types.ts, npm-update.ts, update-policy.ts server upgrades + stt.ts, stt-jobs.ts speech-to-text (stt-jobs.ts is server-only) + transport-metrics.ts, transport-stats.ts transport samples and statistics + usage-db.ts, usage-service.ts, usage-rates.ts usage report + archive-restore-lock.ts restore claims (SQLite) + dynamic.tsx, navigation.ts `dynamic()` over React.lazy; `useRouter`/`useSearchParams` over the History API + navigation-history.ts back/forward stack and shortcut matcher + chat-fork.ts, chat-transcript-plan.ts, normalize.ts, types.ts, pi-types.ts chat helpers and shared types + project-command-env.ts child environments (`createChildProcessEnvironment`, `sanitizeProjectCommandEnvironment`) + +components/ React UI (AppShell, ChatWindow, ChatInput, MessageView, SessionSidebar, ComposerPanels, BtwPanel, + HostsConfig, HostUpdates, ModelsConfig, ProviderAccounts, McpConfig, PluginsConfig, SkillsConfig, + SettingsConfig, ConnectionDiagnostics, NotificationBell/List, LocalDaemonBanner, ExtensionDialog, ...) +components/ui/ shared primitives on @base-ui/react: primitives.tsx, field.tsx, toast.tsx, ToggleSwitch.tsx +hooks/ useAgentSession(-stream/-sync/-queue/-notices), useBtw, useHostRows, useNotifications, useTheme, + useNavigationHistory, useChatSearchHighlights, useDictation, useSpeechSynthesis, ... bin/ - 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 + tau.js launcher (Node); `tau preflight` through jiti + tau-host.js `tau host [login|logout|status|drain|resume]`: loads lib/hosts/host-cli.ts through jiti; token from stdin, never argv + bun-runtime.js resolves Bun (npm `@oven/bun-*`, else PATH, minimum version) + tau-tray.js, linux-tray.js, tau-systemd.js, tau-launchd.js tray and service installers 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 `) with a throwaway HOME, verifies automatic local-host startup, the SPA, assets, session access and SSE, then stops its own processes - transport-metrics.ts `bun scripts/transport-metrics.ts [--since 2h|] [--until ] [--client ] [--session ] [--file ]`: per-transport summary of the browser transport samples and per host and direction of the host link samples (`--session`: link samples of one session; default: the last 24 h of the agent dir's file) - link-hol-probe.ts `bun scripts/link-hol-probe.ts --host --model `: head-of-line load on one host link (large prompts down, large session reads up, get_state beside them) for the link samples; usage at its top - 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 omp runner (`ompweb-omp`, built first by `runner/scripts/build-binary.ts`; not with `--no-runner`, which releases use: they attach the runners as separate assets) and the licenses; archives it - build-release-binaries.sh the five release targets (one list), run by publish.yml and prerelease.yml (a prerelease per verified `main` commit, titled by build time; one concurrency group per commit, so no commit's run is dropped) - 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 + build-client.ts, tailwind-plugin.ts SPA bundle (bun-plugin-tailwind minus its color-mix() polyfill) + build-binary.ts, build-release-binaries.sh, licenses.ts, check-host-release-archive.ts compiled releases + smoke.ts `npm run smoke`: built server (or package/binary) + its local host + a live `pi --mode rpc` session + SSE + transport-metrics.ts summary of transport and link samples (`--since 2h`, `--until`, `--client`, `--session`, `--file`) + link-hol-probe.ts head-of-line load on one host link + +tests/ setup-dom.mjs, mock-builtin.mjs, fake-indexeddb.mjs, isolate-tmp.mjs (preload), fixtures +proxy.ts the password gate (`UNGATED`) +instrumentation.node.ts server startup: local host link, cluster sync, auto-resume, shutdown +bunfig.toml dev bundling plugins, TAU_PUBLIC_* inlining, test preload ``` --- @@ -310,1803 +262,354 @@ bunfig.toml Bun dev-server bundling: tailwind plugin and the OMP_WEB_P 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. +The table is static imports, not a runtime glob, so `bun build --compile` bundles every handler. `dispatch` answers HEAD from `GET`, OPTIONS and a missing method (405 with `allow`), passes `params` as a promise (plus `disableIdleTimeout` and `upgrade`), 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 no longer an idle-lift stream: it is a WebSocket, and an upgraded socket is outside the HTTP idle timeout (so is the browser link, `/api/events/link`). `server/app.ts` passes `upgrade` in the route context (`server.upgrade(request, { data })`) and one `websocket` handler: a socket whose `ws.data.kind` is `"browser"` goes to `browserLink` (`lib/browser-link.ts`, with the close code: 1000/1001 end the link, anything else keeps it for a resume), any other to `hostLinkSocket`. Bun's WebSocket limits (`maxPayloadLength`, `backpressureLimit`, `idleTimeout`) are per server, so browser links share the host link's; `browserLink` caps its own frames at a piece (256 KiB). A handler that upgraded returns `undefined`, which `dispatch` and `handle` pass through without `finalizeResponse` or the idle-timeout restore. `maxRequestBodySize` is left at Bun's 128 MiB default, above the 101 MB upload cap; do not lower it. +- Bun's 10 s `idleTimeout` stays on: it reaps stalled sockets, 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 restores the 10 s 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, clone/search/bash-output/file streams) calls `disableIdleTimeout` from the route context; a new stream must do the same, or it is cut after 10 s idle. +- WebSockets: the route context carries `upgrade` (`server.upgrade(request, { data })`), and `server/app.ts` has one `websocket` handler: `ws.data.kind === "maintenance"` goes to `maintenanceSocket` (`maintenance-hub.ts`), anything else to `hostLinkSocket` (`hub.ts`). An upgraded socket is outside the HTTP idle timeout. A handler that upgraded returns `undefined`, which passes through without `finalizeResponse` or the idle-timeout restore. Browsers get no WebSocket: the browser connection is SSE only. +- `maxRequestBodySize` stays at Bun's 128 MiB default, above the upload chunk and command caps; 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. +- Redirects carry a relative `Location` (`request.url` is always `http://` under Bun). +- `Response.redirect()` headers are immutable; `finalizeResponse` copies every answer into a fresh `Response` for 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. -- Server updates use `self-update.ts` and `server-update-worker.ts`: a package builds a self-contained Node worker, while a compiled release runs a private binary copy outside the install. The server worker also owns a shared local-host transition; independent hosts retain `hosts/update-worker.ts`. All workers use the verified native lifecycle in `upgrade-process.ts`. -- Stage and digest-check the candidate, run `ompweb fetch-omp` and `ompweb preflight` in its environment, then stop anything. `PREFLIGHT_MARKER` identifies the preflight command. Server completion needs an expected-version boot nonce and live process proof, not a launcher's former IPC/restart marker protocol. A failed cutover retains the prior tree and reports rollback status. -- The daemon-owned watcher (`lib/hosts/workspace-watch.ts`) re-stats ~50 ms after every event to catch burst saves (Bun may drop native events within ~2 ms); main only routes its sequenced watch events. -- `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`). +- Dev serves the SPA from the HTML import with HMR and re-runs itself once with `TAU_PUBLIC_*` set, because `bunfig.toml` inlines them from the environment Bun started with. Dev pages carry `script-src blob:` in their CSP (HMR); production does not. +- `TAU_PACKAGE_DIR` (set by the launcher) is the root for `dist/`, `public/`, KaTeX and the companion extension; `process.cwd()` is the fallback for dev and tests. The compiled binary sets it to its own directory before any server module loads: `import.meta.url` there is Bun's virtual `/$bunfs/`, which no other process (pi included) can read. A new file the server, daemon or pi reads at runtime also goes into `scripts/build-binary.ts`'s copy list. +- The binary needs `NODE_ENV` defined as `"production"` at build time (`scripts/build-binary.ts`); otherwise the server never writes the daemon's link. `npm run smoke -- --binary` catches that. +- `Bun.serve` turns on `SO_REUSEPORT` when `development` is false, so `startServer` passes `reusePort: false`; `startProduction` reports `EADDRINUSE` in one line. +- The daemon-owned watcher (`lib/hosts/workspace-watch.ts`) re-stats ~50 ms after every event to catch burst saves; main only routes its sequenced watch events. +- `bun:sqlite` `.get()` returns `null` for no row. `close()` keeps the file open while prepared statements live (Windows cannot replace it): stores close with `close(true)`. - `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 (`npm test`, or `bun test --parallel`) -- `--parallel` is required, not just faster: Bun gives each file a fresh global/module registry. The transport singleton (`lib/event-stream.ts`) and each file's `SharedWorker`/fetch/DOM fakes otherwise leak into the next file; a shared-process run can send commands to another file's fake worker. These fixtures are deliberately file-isolated rather than reset between files. Use `--parallel` even for a multi-file subset. -- DOM tests import `tests/setup-dom.mjs` first and then import Testing Library dynamically, so its queries bind to that document. 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 `bun --hot` re-evaluation; a plain module-level Map does not. -- For v7 hosts, the daemon owns idle/disconnect cleanup and startup settings. - Wrappers report tab/command interest and protected preparation through transport - capabilities; disposal closes membership, while explicit delete/reload can kill. - Reconciliation failure never kills a process another server uses. -- Every link is host-owned since link v11, so the backstops below run only for a transport without - `hostOwnedLifecycle` (test fakes): concurrent `startRpcSession()` calls share one start promise. - Two cleanup backstops remain on the server, both unref'd: - `IDLE_DESTROY_MS` (10 min) and `DISCONNECT_DESTROY_MS` - (`OMP_WEB_DISCONNECT_DESTROY_MS`, 2 min, `0` disables). The shorter one only - fires once a session has been genuinely abandoned — no `onEvent` listener, no - run in flight, no startup handshake, no unanswered `send()` or command preparation. - The last `onEvent` detach *starts* that window rather than exposing the last frame's, - so a reload reattaching seconds later does not 409. Both are fed by - `resetIdleTimer()`, the single activity choke point for `send()` and every - child frame: adding a new call path must route activity through it. - -### Auto-resume after a restart (`lib/session-resume.ts`) -- **v7 hosts:** `lib/hosts/host-resume.ts` records unsettled sessions and launch - parameters in `omp-web/host-running.json`; the daemon resumes them once after - its restart. Web-server restarts just rejoin. The first v6 → v7 daemon upgrade - requires a quiescent host: the old daemon has no recovery manifest. -- The per-web-server recovery mechanism below runs only for a transport without `hostOwnedLifecycle`. -- Off by default (`autoResumeSessions` in `omp-web-settings.json`). When on, - `notifyRunningChange()` keeps `omp-web-interrupted-sessions-.json` in - the agent dir listing sessions that are mid-run; startup - (`instrumentation.node.ts`) consumes it, restarts each session and sends - `RESUME_PROMPT`. -- Each instance writes only its own pid's list, so a second omp-web sharing - the agent dir (e.g. `npm run dev` beside an installed one) never resumes or - overwrites sessions the other is running. Startup claims a list only when its - pid is dead or the file predates the last boot, plus the legacy unsuffixed - list. Same-boot pid reuse or a zombie writer leaves that list unresumed. -- The omp children run under the daemon, so stopping the web service does not - reach them: the next server adopts the ones still running and drops their - entries from this list (`adoptedChild`, see "Local daemon"). Only sessions - whose child died (daemon restart, crash, failed adoption) resume, after the - daemon's hello (`resumeOnHostLink`). A session whose process died stays - listed for `EXIT_GRACE_MS`; the shutdown handler freezes the list - (`markShuttingDown`) so deaths during a shutdown count as interrupted, while - a crash with omp-web still up is dropped after the window. -- Only session ids are stored; paths are re-resolved on resume. -- Known limit: resume does not detect a terminal `omp --resume ` started - on the same session while omp-web was down; both would write the file. - -### Remote hosts (`lib/hosts/`, `app/api/hosts/`, `bin/omp-web-host.js`) -- **Shared v7 hosts** (`docs/specs/2026-11-06-multi-server-host-design.md`): - one daemon links every configured server in `host.json.links`. `open` joins - one session process; events fan out, command replies return only to their sender. - The daemon owns lifecycle, streaming snapshots and first-answer dialog settlement. - Web callbacks choose the last-active eligible server and are not blindly retried. - `channels_changed` discovers background runs; `sessions_changed` invalidates lists; - one link is the automatic notification publisher. - Cross-server fences live in the daemon: a history edit takes the acknowledged - `editLease` op before preflight, and a `peer_message_command` marker makes another server's identical echo - ambiguous (`watchReplacement`). An open's preparation lease passes only to the - command that asked for it (`withPendingCommand(run, true)`); a command timeout - that recycles the child stops the shared process (`destroyAndWait(reason, true)`). -- **Host seam** (`lib/hosts/host.ts`). Every host, this machine included, is - reached over the link: `getHost(id)` (`hub.ts`) returns a `RemoteHost` whose - calls go to a daemon. `getHost("local")` is the link of this machine's own - `ompweb host` daemon (see "Local daemon"); there is no direct spawn or file path - on main. `localHost` (`id: "local"`, `local-host.ts`) is the daemon's side: it spawns - and reads files on the machine the daemon runs on. `startRpcSession(..., host)` - asks `host.spawnRpc` for an `RpcTransport`; `RpcProcess`, the wrapper, the - event hub, notifications, the queue and `/btw` never see where omp runs. - Session and project file reads are `host.sessionOps` (`session-ops.ts`, run in - the daemon), addressed by session id, never by path: routes use `resolveSessionHostOr404` - (`lib/api-utils.ts`) and the host resolves the file itself. New route code - must not open a session file on main for a session that may be remote or local. - `SessionInfo.hostId` and `ManagedProject.hostId` carry the host; sidebar and - project state key on `hostProjectKey` (bare path on this machine, `:`). -- **Link = one WebSocket per host per web server, dialled by the daemon** (`/api/hosts/link`; - design `docs/specs/2026-10-31-websocket-link-design.md`). **Text frames** - carry the messages (hub → daemon one per frame; daemon → hub newline-separated - batches flushed every 16 ms or at one 256 KiB piece), **binary frames** carry large op - results (daemon → hub, before the `res` naming them) and, from v6, upload bytes - (hub → daemon, `up:`). Every line except - `hello`/`welcome`/`ack`/`ping`/`pong` has a per-direction `seq`; `ack {ack}` - is a message: the first line of every daemon frame, and the hub answers every - uplink frame (v5: binary ones too) with exactly one. **Pieces and fair sending - (v5, design D7):** a - line over `LINK_LIMITS.pieceBytes` (256 KiB) goes as sequenced `part {at, end, - data}` messages (`PartJoiner` joins them, one partial line at a time, ≤ 512 - parts) and a - result as binary frames of at most 256 KiB; both sides queue per key (channel, - or request id) in `LinkSender`, send round-robin and number each line as it - goes out, so wire order stays `seq` order. **Unacked window:** each side sends - queued units only while less than `LINK_LIMITS.unackedBytes` (512 KiB; ≤ 768 KiB in - flight with the last unit, ~3.1 s at 2 Mbit; ~512 KiB per round trip of throughput) is - unacked, since kernel/proxy buffers hide megabytes from `bufferedAmount` and - Bun's `send`: the hub counts outbox lines written (`unacked`, shrunk by the - daemon's `ack` line), the daemon counts frames the hub has not answered (one - `ack` per frame) and also waits for `bufferedAmount` under two pieces. The - daemon acks applied downlink lines within 16 ms (ack-only frame if need be). - A small message waits behind at most that window plus about one piece per - busy key; control lines skip both. The - `hello` is the first text frame of a socket. Each `hello.channels` - entry carries `pending`: the raw stdout lines of that child's - still-open `host_tool_call`s, `host_uri_request`s and blocking `ui_request`s - (`PendingRequests`), or null past `LINK_LIMITS.pendingBytes`. Each side keeps unacked - lines, resends after a reconnect and drops any `seq` it already applied. The - hub decodes a whole frame before applying any of it (a bad line closes 1007). - `hello.ack === 0` means a fresh daemon: main restarts that host's uplink - window. The hub paces the downlink from its outbox (`drain`): the 16 MiB send - buffer limit (`closeOnBackpressureLimit`) is only a backstop, and the outbox - holds the unacked backlog in server memory. A v4 daemon still gets whole - lines, so for it a multi-MiB line slower than `offlineMs` is retried (below - roughly 280 KiB/s for an 8 MiB line). Close codes: 1000 revoke, - 1001 freeze (a real SIGTERM exits first, so daemons usually see 1006 or - ECONNREFUSED), 1007 bad frame, 1008 bad first frame, 1009 too big, 4409 - replaced, - 4426 version (`LINK_CLOSE`). Wire shapes and size limits live in - `lib/hosts/link-protocol.ts` (one op allow-list, `HOST_OP_NAMES`, shared by - both sides); the summary spec is `docs/specs/2026-10-28-remote-hosts-design.md`. -- **Link head-of-line samples** (`metric: "link"` in `/omp-web/transport-metrics.jsonl`, measurement - only). Each side samples every sequenced message once, when it is queued: time, UTF-8 size, session (a session - op's `id`, else the channel's child as its `get_state` answers name it) and `bytesAhead`, the bytes queued or - unacked on that link then (`LinkSender.queuedBytes` plus an unacked counter, never a scan; a queued line counts at - its size before its seq is filled in, up to 15 bytes over). The sample is made when the message is acked: a line - sent in parts at its last part, with the joined size; a `res` counts its result bytes as its own. The hub writes - its `down` samples; the daemon reports its `up` ones in sequenced `stats` messages of at most - `LINK_LIMITS.statsSamples`, queued under their own sender key (fair and inside the unacked window like any - message). The samples are advisory: the hub keeps the valid ones, drops a malformed one (logged once per host) without - failing the frame, and writes at most 8 × `statsSamples` `up` samples per host per `statsFlushMs` (the excess is - written as one `{dropped}` record when the next window starts, or when the link ends or the hub freezes). `ackMs` is monotonic (`performance.now()`) on both - sides, `at` the wall clock. Both sides batch (`statsSamples` or `statsFlushMs`, 30 s): the hub's batch lives in its - `globalThis` state, resolves its file when it starts and is written in `freezeHostLinks`; the daemon queues what it - holds when it stops (best effort). Tests that drive the hub call - `flushLinkSamples()` before they restore `PI_CODING_AGENT_DIR`. `ackMs` is a round trip: a v5 daemon acks the - downlink within `flushMs` (an ack-only frame if need be) and the hub's ack rides the downlink. - `bun scripts/link-hol-probe.ts` makes the load; `scripts/transport-metrics.ts` prints `link small ackMs` (`clear` - vs `behind-large`, 64 KiB ahead), `link bytesAhead` and `link dropped` per host and direction (`--session` for one - session's link samples). -- **Link protocol versions** (spec "Protocol versions and compatibility"). A - released `LINK_PROTOCOL_VERSION` changes only compatibly: an added optional - field or a message type receivers skip is fine; a changed type or meaning, or - a newly required field, needs a new version. Receivers skip unknown message - types (acking their `seq`) and answer unknown ops 501 `unknown_op`, from v3 on. - v4 (the WebSocket link) dropped v3 before any release. v5 (pieces) keeps v4; - v6 (uploads: hub → daemon binary frames, `upload_ack`, `uploadStart`/ - `uploadAbort`/`uploadAttach`) keeps v4 and v5. v7 adds multi-server joins, - host-owned lifecycle, callback routing and channel/list discovery. - v8 (host pool) adds `capacity` reports, `creationId` - and `preparePoolProject`; v9 adds `open.launch.shareCredentials` (see "Shared - credentials" below); v10 adds `open.launch.configVersion`, the `config_state` - report and the `clusterConfig` op (see "Cluster configuration" below). v11 (the omp runner) makes channel - lines the runner's `{t}` frames instead of omp RPC frames and drops v4–v10: `MIN_LINK_PROTOCOL_VERSION` and - `LINK_PROTOCOL_VERSION` are both 11 (literal one-liners: the deploy script parses them with `sed`). Main keeps at least N-1, and - dropping one is an explicit decision (a hello - outside the range gets close 4426 with `{"serverVersion":N}`, a pre-WebSocket - daemon's POST gets 426). Once the WebSocket experiments end, the first version - released after them is a floor: the handshake, version report and an update op - keep working for every daemon on it or newer, and `MIN_LINK_PROTOCOL_VERSION` - never goes above it (spec, "Decided: backward compatibility"). Upgrade order: web app - first, then hosts; a daemon need not support a newer main (a v5 daemon gets - 4426 from a v4 server and exits 1). A daemon dialing a pre-WebSocket server - keeps redialing with a hint. -- **One socket per host per web server.** A new hello on the same server with - the same token closes its previous socket 4409; on v7 only that link ends. - One daemon may link multiple servers; two daemons must never run - competing `omp --resume` children on one agent dir. A frame belongs to the - socket it arrived on: the hub ignores frames from a socket that is no longer - the host's link, so no nonce is needed. A revoked host is refused at the - upgrade (401) and at the hello (close 1000). -- **Transport down is not exited.** While the link is down the omp child keeps - running on its machine. A wrapper on a host whose `isLinkUp(status)` is false - is "transport down": no `process_exit`, idle and disconnect timers paused - until the link returns; frames carry `host_status` for the offline banner; - sends answer 503 `{hostOffline: true, delivery}`: `"refused"` when nothing - left (the composer keeps the draft), `"unknown"` when the link dropped after - the command was sent (it may still run; the composer drops the draft so it - is never sent twice). A fresh chat adopts the `sessionId` a 503 from - `/api/agent/new` carries. A child missing from `hello.channels` - gets a synthesized `process_exit`. Use `isLinkUp` (`host.ts`, client-safe) as - the one link predicate; do not compare `status === "online"` (an `omp-missing` - host is linked). -- **A failed op never runs later.** An op that times out (504) or whose - downlink ends or host goes offline (503, at once, not at the 30 s timeout) - drops its `req` from the outbox (`failOp` in `hub.ts`), so a delete the user - saw fail is never applied after a redial. The 30 s op deadline counts silence: - each binary result frame restarts it, so a large result at a slow ack round - trip is no 504 (a timeout still drops the `req` as above). `destroyAndWait` returns once the - session's host is offline (`untilHostDown`); the kill stays queued for the - link. A wrapper therefore stays in the registry until its child really exits - (a resume whose handshake failed is registered in the catch for this), so a - retry awaits its `destroyPromise` instead of spawning a second `--resume` - child. A reload (`restart`) waits for the old child the same way: if the - host drops first, it fails `host_offline`, the wrapper answers - `host_offline` until that child's exit arrives (or `lost` on the next - 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. 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`, - `linkLostDuring` in `rpc-manager.ts`); a quiet or dropped link answers - `host_offline` (503), queues no kill and leaves the run to - `reconcileAfterGap`. A kill through a dead link only waits in the outbox. -- **Orphans and resume.** On `hello`, listed channels with no wrapper are children - of a previous server run: they are adopted (see "Local daemon"), and killed - (`kill`, escalating to force after 5 s, registered until their `exit`) only when - adoption is impossible. A cold spawn for a session - awaits `orphanExit(hostId, sessionId)` first so two children never write one - file; the wait rejects 503 as soon as the link goes down. A buffer overflow on - the daemon (32 MB per channel, two image-prompt echoes) drops the channel's - backlog and sends `resync {ch}`; main's `RpcProcess` discards any partial - chunked frame, skips leftover chunks until the next frame start, and reruns - 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.** The `proxy.ts` gate lets exactly `/api/hosts/link` through - (the `UNGATED` pattern names that path, no subpaths), the prefix - `/api/hosts/broker/v1/` (below) and the two exact cluster configuration paths (below): the daemon has no - session cookie, so it authenticates with its bearer token instead. The hub - verifies the `Authorization: Bearer ` header before the upgrade - (401 unknown token, 503 unreadable `hosts.json` or frozen server). Keep - `/api/hosts` itself behind the proxy. `/api/hosts/broker/v1/` is the next ungated - path (the `UNGATED` pattern names that prefix; anything else under - `/api/hosts/broker/` stays gated): the daemon authenticates there with its - host token too. A reverse proxy must pass it without its own authentication, - without response buffering (the snapshot stream stays open) and - without redirects. The last ungated paths are the one alternation - `api\/hosts\/cluster-config\/(?:manifest|file\/[0-9a-f]{64})$` of `UNGATED`: exactly - `/api/hosts/cluster-config/manifest` and `/api/hosts/cluster-config/file/<64 hex digits>`, nothing - below or beside them (`/api/hosts/[id]/cluster` and `/api/hosts/[id]/updates` answer to the id - `cluster-config` and stay gated); each route checks the host token and membership itself - (`admitClusterMember`, again after the configuration is built, so a host revoked or removed meanwhile - gets 401/403), and a reverse proxy passes them without its own authentication and - without redirects (exact paths, unlike the broker's prefix). -- **Shared credentials** (`docs/specs/2026-11-10-shared-credentials-design.md`). - A linked host's `shareCredentials` (default off; `local` never has it) makes the - omp processes its daemon spawns use the credentials of the server machine - through `omp auth-broker serve`; ompweb still never reads `agent.db`. - - **Route.** `app/api/hosts/broker/[...path]/route.ts` checks the host token - before reading a body (401 unknown token, 403 `local` or sharing off, 503 - unreadable `hosts.json` or no broker), then forwards only an allow-list of - broker endpoints (snapshot, its stream, health, `refresh`, `disable`, - `block`, `blocks`, usage), body at most 1 MiB, with a handful of request - and response headers. Everything else answers 404, `POST /v1/credential` - included: a host cannot upload a credential. It turns the idle timeout off - after authenticating. Turning sharing off or revoking the host calls - `abortBrokerRequests` for it and later requests get 403 or 401. - - **Daemon.** `open.launch.shareCredentials` (link v9) makes the daemon start omp - with the loopback forwarder's URL and a secret it generates at each start. The - host token never enters an omp environment: the forwarder adds the link's - current token to each request, sends it to that link's server and refuses - redirects. - - **No fallback.** The hub answers 426 `host_upgrade_required` for a sharing - host on a v4–v8 daemon, and the daemon refuses to spawn on an omp older than - 15.13.1. Starting a session is refused; it never uses the host's own stored - logins. Joining a running session is never refused. - - **Which server decides.** The server whose `open` starts a process decides - its credentials, an advisor replacement included (`withCredentials` in - `lib/hosts/daemon-channels.ts`); a server that joins a running process does - not change them. The resume manifest keeps the server URL - (`launch.credentialsServer`). A launch whose link is no longer in `host.json` - is refused with 409 `credentials_link_gone`, on resume as on a new start. - - **Scope.** The host can read current access tokens and stored API keys; - refresh tokens stay on the server. Not shared: `models.yml` custom providers, - environment-variable API keys, omp settings. -- **Cluster** (`docs/specs/2026-11-11-cluster-membership-design.md`). The - cluster is `pools[0]`; `local` is its master, added on creation or on the next - join if an existing first pool lacks it. The rest of `pools.json` is ignored - by the interface. - - **Membership computes credential sharing; it is never stored.** A member - other than `local` shares regardless of its `shareCredentials` flag - (`sharesCredentials(record, pools)`), so leaving restores the host's own - setting. An unreadable `pools.json` refuses a start (503 - `pool_storage_unavailable`) rather than starting with other logins. - - **Every writer of `pools.json` that can end a host's sharing aborts that - host's broker requests** (`abortBrokerRequests`): `PUT /api/hosts` and the - cluster `DELETE`. A flag change or revoke writes `hosts.json` and likewise - aborts requests when sharing ends. - - **Membership, not the confirmation or `enabled`, grants sharing.** A host - added to `pools[0]` through `PUT /api/hosts` (or a `pools.json` edit) shares - without the join dialog, and so do members of a disabled first pool. - - **Placement skips members that cannot share.** `startPooledSession` leaves - out a member that `sharesCredentials` forces to share unless its link is - shared (`hostOwnsLifecycle`) at `SHARED_CREDENTIALS_SINCE_VERSION`, before - preparation; `spawnRpc`'s 426 stays the last guard. Other pools' members - keep their own eligibility. - - **Join keeps what the host showed.** A created cluster project takes the - host project's name, else its folder name (split on `/` and `\`), and its - alias; binding a visible checkout un-hides a hidden cluster project. - `POST /api/projects` pool registration matches by `repositoryKey` (or the - identical text) and keeps the stored origin. - - **Mirrored to members:** this machine's omp configuration, see "Cluster - configuration" below. Not mirrored: programs (an MCP command, a language server, a local - model engine), `.omp/` in a repository, named omp profiles. - - **Only grouping passes `pools` to `projectTargetId`.** Selection, expand - keys, reorder, pin and drag use the project's own target. -- **Cluster configuration** (`docs/specs/2026-11-11-cluster-configuration-design.md`). - A member runs omp on this machine's configuration, and its daemon applies it, never omp. - - **Master.** `buildManifest` (`lib/hosts/cluster-config.ts`) lists the `MIRRORED` files (from the - agent directory, and `~/.agents/skills`), `config.yml` without the `LOCAL_SETTINGS` keys (one - constant, read by the master when it builds and by the member when it merges), with - the agent environment variables and the plugin set. `version` is a sha256 over all of it. Limits: 5 MiB per file, - 50 MiB per bundle, 5 MiB for the serialized manifest, which is what a member reads (`CONFIG_LIMITS`, shared - with the daemon; too many files is `bundle_too_large`); a configuration over one is not served at all - (`ClusterConfigError`, which names a file and never its content; it reaches Settings as `masterConfigError` - in the `hosts` snapshot). `currentClusterConfig` rebuilds only when its fingerprint changes - (an async stat of every file, agent environment, plugin list, which is read at most every 120 s, so a - plugin change reaches members within about two minutes, and keeps the - last good list when `omp plugin list` fails: a member removes the plugins the manifest lacks); a read - error in the fingerprint walk makes the fingerprint unique, so the build reports it instead of a cached manifest standing. - `startClusterConfigSync` (`instrumentation.node.ts`) runs `syncClusterConfig` at start, every 30 s, and - whenever `masterConfigVersion` finds a new version after a known one (a member start reads it too): - `clusterConfig apply` to each online v10 member that is not `configCurrent`, `restore` to a host outside - the cluster whose link is up (`omp-missing` too) and that still reports a configuration of this server or has - not reported since its link came up (a dropped `config_state`; the answer says); never while one of that - link's ops is unanswered. Join sends `apply` after it saves `pools.json`, leave `restore` - after it saves; neither may await between reading the pools and saving. - - **Protocol 10.** `open.launch.configVersion` is the master's version (64 hex digits, - `CONFIG_VERSION_RE`). The hub sets it for a cluster member's process start (not for a join of a - running channel), after reading `pools.json` a second time so a host that left meanwhile gets none. The daemon strips `shareCredentials`, - `credentialsServer` and `configVersion` from every wire launch and sets them only for the opening link - (`forStart`); a launch with a version needs `credentialsServer` and applies it first - (`createClusterConfig.ensure`) or the start is refused 409 `cluster_config_failed`. `config_state - { state, owned }` is an unsequenced daemon report (like `capacity`, never replayed), at link up, on each - change and after each `host.json` reload; one that finds the send window full is not dropped: the latest goes at - the link's next flush (main's ack, or the poll of a full socket buffer). The - `clusterConfig` op is `{ action: "apply", version }` or `{ action: "restore" }` and answers `{ state, owned }`; - the hub keeps that answer's state only until the link's first `config_state` since it came up (a report goes - ahead of the sequenced answer, so it can be newer). - **The version is never persisted in the resume manifest:** `ChannelTable.running()` drops it and - `host-running.json` has no field for it, so a recovered session starts on the version already applied. - - **Daemon.** Per version: manifest, then each file the member lacks by hash from the link's server - (`/omp-web/cluster-config/objects/`, verified by hash), then one transaction: files are - staged, the member's own entries move aside (first apply: `own-config/`, with `plugins.json`, - `agent-env.json`, `absent.json`, `server.json` and `settings.yml`, a plain copy of its own `config.yml` - or `config.yaml` read through a link, which later applies merge from; later: `trash/`), the staged ones move in, the agent - environment and `state.json` are written; any failure puts everything back and the previous - version stays. Renames move links as links and cannot cross filesystems (`EXDEV` fails with both - directories named); a link above an entry (`~/.agents`) is refused. Every request to the master, - its body included, must finish within 30 s (`clusterConfigTimings.fetchMs`); `stop()` aborts it and a - running `omp plugin` command (`halt`). Plugins run after the - files in the same queue without the start waiting (`syncPlugins`, `omp plugin`; npm pinned by - version, a marketplace plugin has no pin); a new version with the same plugin list keeps `plugins: "current"` - while the step re-checks it; a failure keeps `plugins: "failed"` and is retried at most - every 30 s (`pluginRetryMs`). Applies, restores and plugin jobs run one at a time. - - **Ownership.** `own-config/server.json` records the server whose configuration the host holds: one - server at a time. Another server's `ensure`/`apply` is refused while the recorded one is still in - `host.json` (`foreign`); a recorded server that is no longer linked is taken over by the next apply. `owned` - in `config_state` and in the op's answer is `holds(link server)`. A join of a host that reports - another server's configuration is 409 `host_in_other_cluster`. Only the server that `holds` the configuration - puts it back: another server's `restore` answers at once and changes nothing (`owned: false`; a backup nobody - holds, such as a kept plugin list, waits for the next start), and a session start sent before that server's restore is refused - after it (`left`), as is any start while the holder's restore runs. A link that ends `"revoked"` while its server - `holds` the configuration awaits `restore` before the daemon shuts down: no other server could put it back. - - **Placement.** `isHostConfigCurrent`: `local` and hosts outside the cluster always; a member only when it reports - this server's version, `files` and `plugins` current. `selectPoolHost` skips a member that is not; - `startPooledSession` says why: "still receiving the configuration" or "Update - ompweb on the pool's workers". A start pinned to one member applies first and is refused with the reason; a - plugin difference does not refuse it. - - **Upgrade.** Every linked daemon speaks protocol 11 or newer (`MIN_LINK_PROTOCOL_VERSION`; an older one is refused - at the link), so every member takes the configuration; joining also needs the `gitOrigins` op and an omp that - shares credentials (`clusterJoinBlock`). - - **Settings.** Rows carry `clusterConfig { …state, owned, current }` (`listHosts`); the member line shows - current, updating (none while `masterConfigError` is set), failed (reason), held by another server, needs update (`clusterJoinBlock` says "upgrade"), and the MCP commands - missing there. For a cluster session on another member (`isClusterTarget` with a member host) the MCP, - Skills, Plugins and Agents panels use no cwd and no session (the user-level routes above); MCP alone keeps - the session for `?attach=1`, read-only (`McpConfig liveOnly`). -- **Remote paths never reach `allowFileRoot`** or any other main-side - filesystem check: they mean nothing on main. `startNewRpcSession` calls - `allowFileRoot` and the local session-list invalidation only for the local - host; remote cwd validation is the host's `validateCwd` op. Daemon input is - untrusted: blob hashes must match `^[0-9a-f]{64}$`, results are shape-checked - 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 `@/` 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 - only `sha256(token)`; the token is shown once. Mutations use the strict - reader and throw `HostRegistryUnreadableError` (503) instead of rewriting a - file they could not parse. Revoke deletes the record first, then closes the - link (the daemon sees 401 and stops its children). The `hosts` event channel - carries the `GET /api/hosts` body. A missing `hosts.json` (an agent-dir - mismatch, say) answers 401 to every daemon, and a daemon told its token is - unknown stops all its omp children: check `PI_CODING_AGENT_DIR` before - starting main. -- **Agent tools.** Calls carry the caller's host (`sourceHostId`); - `new_session`'s `host` defaults to it. A host with `allowAgentStart` off asks - a server-owned `confirm` through the normal extension-UI path - (`confirmFromServer`). Local callers never ask for this machine. A remote - caller asks before any other host unless that host allows agent starts, and - always before this machine, for `new_session` and `send_to_session` alike. -- **Message origin.** Messages created by `send_to_session`, a `new_session` - first prompt, or the GitHub watcher remain native user messages for model - authority, but carry server-authored `origin` metadata. The runner stores it - in the existing `client-message-entry` correlation journal; the reader joins - it only on the active branch, and the outbox stores it beside held entries. - Browser/HTTP commands cannot supply `origin` (`origin_not_allowed`), and - readers drop malformed or over-4096-byte metadata. The chat renders trusted - origins as left-aligned source cards; matching text without metadata remains - an ordinary user bubble. Older runners ignore the optional command field and - show the explicit model-facing source header as plain text. -- **Workspace operations are daemon-owned** (`lib/workspace-types.ts`, - `lib/hosts/workspace-ops.ts`; design `docs/specs/2026-11-03-remote-workspaces-design.md`). - Files/index/shell output/watch, Git/worktrees, browsing/default cwd and clone - APIs use `Host.workspaceOps` for every host, including local. Optional hello - capabilities gate old daemons; unavailable operations never fall back to main. - File tabs retain host/cwd/session ownership. Upload publication extends the - existing staged 2 GiB uploader; its workspace receipts are not session attachments. -- **Session archive is per host.** `POST /api/sessions/[id]/archive` archives on the - session's host. `/api/sessions/archive` lists this machine's archive (read on main) - plus each linked host's (`listArchives` op), every entry tagged `hostId`; an - offline or older host is reported in `unavailableHosts`. Restore sends `hostId` - and runs on that host (`restoreArchive` op). Restore requires fresh successful - session discovery from all registered hosts and blocks any already-active ID, - including a same-host session at a different path. So every registered host must - be online, deliberately: an offline laptop blocks even a local restore (503 - `host_offline` with the blocking host's `host` label; the browser names it). - Restore preflight uses the separate `listSessionIdsForRestore` host op, not - `listSessions`: the sidebar's ordinary scanner intentionally skips unreadable - projects and caches best-effort results, which cannot prove a UUID absent. - The strict op shares the one-level session-file walker but bypasses all walk, - metadata and sidebar caches, propagates access/I/O failures at root or project - depth, reads each bounded header strictly and refuses unidentifiable headers. - It neither populates nor invalidates general listing caches. Only a sessions root - absent from the outset is an empty inventory. Once the root/project was observed, - even ENOENT is uncertainty (the directory may have been renamed with active - sessions inside). Project symlinks and `.jsonl` file symlinks, which ordinary - listing skips but cached paths can still use, reject strict discovery instead of - disappearing. Strict header reads reject non-regular paths and symlinked parents, - open with `O_NOFOLLOW` where available, and compare the opened descriptor's - device/inode with before/after pathname checks, refusing replacement during open. - A file vanishing while reading likewise blocks this attempt. Any incomplete - inventory or malformed wire result blocks restore with - 503 `host_sessions_unavailable`, before reserve/restore/consumption. Older daemons - answer 501 for the new op, which is also surfaced as that 503: update/restart - them before restoring; never fall back to their best-effort lists or use an - optional strict argument they could silently ignore. Normal listing semantics, - cache behavior and older-host browsing compatibility are unchanged. - `withArchiveRestoreLock` (`lib/archive-restore-lock.ts`) is a per-session SQLite - lease in `/omp-web/`, renewed every 10 s and reclaimable once its - renewal time is over 30 s away from now, past or future (never by PID, which can be reused). It only coordinates web - processes that share one agent directory, not separate web servers sharing a - daemon. A remote restore outlives its request: the daemon keeps restoring after the - 30 s op deadline, a lost link or a web restart, and a sender suspended after its - claim may send its restore long after another request took the ID over. No lease - clock or "status false" may free the ID meanwhile, so the claim is fenced at the - daemon, which is the only authority on whether a restore can still start, and - **bound to the daemon process** that took it. The daemon starts `restoreArchive` - only under a claim token (the lock row's owner) that main reserved with - `restoreReserve` and nothing has since spent or revoked (`session-ops.ts`, an - in-memory set capped at 256: an evicted token's restore is refused, never run). - Every daemon process has a random `instance`, which `restoreReserve` and - `restoreFence` return and the claim row records (`instance` column). The route - reserves (an op answer or error ends a restore that never left: no claim kept), - then `hold`s the claim with that instance (the row gains host and instance; a held - row never lapses by time), then sends `restoreArchive`. It `release`s only on a - result that proves this claim's restore ended: `ok`, or `archive_restore_failed`, - which only the process that admitted the token produces. Everything else keeps the - claim held and answers `archive_restore_unconfirmed`: silence or a lost link - (504/503), any other error, and **a refusal to admit (`archive_restore_not_admitted`)**, - because a replacement daemon that never saw the token refuses a resent request - while the original may still be running it. A held claim whose request still - renews it is `archive_restore_busy`; one that stopped renewing is resolved by the - next restore of that ID, on any host: main sends the holding host `restoreFence - {claim}`, which revokes the token (a request still in a suspended sender is then - refused) and answers with its `instance` and whether that restore runs. Main - takes the claim over only when the answering `instance` is the one recorded **and** - `running` is false. A fence answered by another process proves nothing: link - replacement (the same host id and token dialed by another daemon) ends only that - link in the replaced daemon, which keeps running an admitted restore while it has - another link (another server), and the replacement knows no token. So a - replaced, restarted or shut-down daemon, a still-running restore, offline, a daemon - that answers 501 (no restore is sent to a daemon that cannot reserve either), a - host unregistered since, and a row an earlier build wrote with no instance all keep - it blocked (409 `archive_restore_unconfirmed`, naming the session, the host and - when the claim was last seen alive). **Recovery limitation:** unregistering a host - does not stop its daemon, and a daemon that was replaced or restarted (a reboot - after a lost link included) cannot be shown stopped from here, so such a claim - stays blocked for good: there is deliberately no timeout and no automatic or blind - clearing, and registering the machine again gives it a new id, which does not - help. Only an operator who has verified on that machine that no `ompweb host` - daemon process that could have taken the restore is running (the claim names the - host and its last-alive time) may delete that session's row from `restore_claims` - in `/omp-web/archive-restore-locks.sqlite`; deleting it while that - daemon could still run lets a duplicate publish. A daemon-side proof of death (a - machine-wide token registry, a PID with its start identity) would remove this - limit for a restart; it is not built. **Restore commit order** - (`commitRestore`, `lib/omp/archive.ts`, used by every restore, daemon and local): - the archived artifacts directory moves into place first, then the transcript is - hard-linked, then the `.gz` is removed, all with synchronous calls, so the session - is never visible without its artifacts. The reverse order let another tab's upload - attach (`StagedUploads.attach` creates `/local/uploads/` the moment the - session is visible) take the artifacts path between the steps; the restore then - rolled the transcript back and left that directory behind, refusing every retry. - No `await` between the steps covers only this process. A filesystem-exclusive - directory claim, `.restore-lock`, owns the whole commit across - web and daemon processes, from before source/destination observations through - rollback. Without it a competitor can snapshot artifacts absent while another - process has moved them; if that mover rolls back, the competitor can publish a - transcript without its artifacts. Staging pins the compressed source with a - private `.restore-pin` hard link beside the archive and reads that link, retaining - its inode so replacement/reuse cannot masquerade as the staged generation. - After ownership is acquired the source must match that generation (device, inode, - size and nanosecond mtime); mere existence is insufficient when another server - has restored, updated and re-archived the session meanwhile. The source pathname - is then atomically captured as a unique `.restore-consume` sibling and checked - again before any artifacts move. Only that captured name is consumed, never the - original pathname: a replacement installed between comparison and capture is - rejected with 409 `generation changed` and returned by exclusive link, and a - replacement installed after capture is left untouched. If exclusive return is - blocked, the captured generation is retained at the reported recovery name. - **Discovery during capture:** `collectArchives` also recognizes strictly named - `.jsonl.gz..restore-consume` basenames (including valid POSIX stems/parents - containing newlines) and parses their actual compressed header. - Artifact trees are not archive-entry trees: in each enumerated directory, - `.jsonl.gz` (or its valid capture name) identifies the sibling - `.jsonl/` as that session's artifacts, and discovery never recurses into it. - Uploaded files inside may have arbitrary names, including non-gzip `.jsonl.gz` - attachments or capture lookalikes; they must not become archive evidence or - fail the host's archive scan. Unpaired `.jsonl` project directories, hidden - directories and genuine nested archives are still traversed. Actual archive - entries outside paired artifact trees retain the fail-closed read/error policy. - Each capture keeps its unique physical key and carries `restorePending: true`; - it is exact-session archive evidence, never an alias of the original `.gz` key. - The browser disables Restore for capture evidence, and the API independently - refuses it with 409 before claiming a session. A capture A and replacement archive - B therefore remain separately discoverable without selecting A while restoring B. - `restore-pin` files and malformed capture lookalikes are not listed. Discovery - verifies file names and generation signatures (device/inode/size/mtime) in a - fresh snapshot after reading, even if every read succeeded: replacement B at an - enumerated pathname must not hide capture A added after enumeration. One changed - snapshot retries; repeated churn throws rather than proving absence. - `collectArchives` treats only `ENOENT` from root/subdirectory enumeration as - absence; access-denied, disk I/O and other traversal failures propagate through - local and daemon discovery. An unreadable subtree cannot prove any ID absent. - A corrupt gzip also rejects the whole host's archive-list answer, unlike the old - best-effort scanner that silently skipped it. Its session ID cannot be established, - so skipping it would let outbox discovery falsely prove that session absent and - permanently fail a held message. This deliberately favors retention over - availability: other sessions on that host may wait too, and archive browsing may - report the host unavailable until an operator repairs or removes the corrupt - entry. No files are removed automatically and no unrelated ID is marked archived. - The aggregate browser GET isolates failure per host, including this machine: - local corruption/unreadability adds `local` with its configured label to - `unavailableHosts` while healthy linked archives remain visible in a 200 response. - This UI aggregation does not catch errors for direct outbox discovery, which - still receives the scanner rejection and retains messages conservatively. - Outbox discovery keeps the captured session's messages held without marking unrelated - IDs archived. Missing-source lookup AND an ENOENT while pinning both check for the - destination's orphan `.restore-lock`, reporting 409 with its path/manual recovery - instead of 404. Once the owner is verified dead, return the capture to its original - name and inspect artifact moves before removing the orphan claim and retrying. - Normal cleanup removes the pin; process death may leave a pin or captured entry - requiring inspection alongside an orphaned commit claim. The pin requires hard - links on the archive filesystem, independently of the sessions filesystem. - Ownership is never time-expired, - and cleanup checks the claim directory's device/inode before removing it. - Orphaned claims report their path and manual-recovery requirement in the 409. - An operator must first verify that every restorer using this session directory - is stopped, inspect/repair any partial commit, then remove the orphaned claim; - removing a live or suspended owner's claim reintroduces the data-loss race. - Individual filesystem steps remain exclusive or identity-checked. Directories move with - `moveDirectoryNoReplace`: POSIX `rename(2)` replaces an *empty* directory at its - target, so the target is first taken with `mkdir` (exclusive) and the rename then - replaces only that empty directory of its own, failing ENOTEMPTY, and removing - nothing, if anything was put into it; Windows' rename never replaces a directory. - The same helper undoes the move, so an archive path retaken meanwhile is not - replaced either (the artifacts then stay at the destination and the error says the - undo failed). The transcript is published by an exclusive hard link, and undone by - `takeBackTranscript`, which renames whatever is at the destination to a name of its - own first and deletes it only if it is still this restore's link (device and inode), - linking any other file back. The commit starts with a synchronous - `validateRestorePathSync` of every path it touches, as the async checks before it - can be a thread-pool turn stale; a path that vanishes while `validateRestorePath` - checks it (a concurrent restore moved it) counts as absent, and a source consumed - between the existence check and the read is "not found". A transcript or artifacts - directory found at the destination fails the restore with 409 and is never merged - into or removed. **Crash limitation:** a process killed inside the commit (SIGKILL, - an OOM kill) leaves the commit claim in place and can leave the artifacts at the - destination with no transcript, or an empty destination directory; the kernel keeps every rename and link that had - completed, so nothing already moved is lost. If the archive was not consumed it - stays listed; retries stay blocked until the partial commit is repaired and the - orphaned claim is removed as described above. A power loss or kernel - crash is not covered: the commit calls no fsync and keeps no journal (none is added - on purpose), so which of its directory operations reached the disk is not - guaranteed, and no recovery is promised for that. - A local restore (in this process) is fenced at the same step: the claim's `publish` - runs the whole commit inside `BEGIN IMMEDIATE`, refusing unless the row is still - this request's, so a web process suspended past its lease cannot move artifacts or - publish over a request that took the session over, and one that takes over after - sees the published session. The step must stay synchronous: SQLite waits for a - lock by blocking the whole process, so a lock held across an await would freeze the - event loop for the 5 s busy timeout. The store is `restore_claims`, written with - `synchronous = FULL` so a power loss cannot forget a held claim. A migration gated - by `PRAGMA user_version` (2) runs once: it renames an earlier build's - `restore_leases` table into `restore_claims` (keeping its claims), adds `host_id` - and `instance` where missing (a held row from a build that lacked `instance` keeps - none and so stays blocked), and leaves `restore_leases` as a read-only view, so a - build that still uses the old name reads but fails every claim, delete and update - instead of lapsing a held row by its clock (later opens only read the version). - Async restore streams archives with fixed 256 MiB compressed and - expanded limits, rejecting unsupported IDs before archive consumption. -- **Not yet remote:** Skills/Plugins/Agents/MCP settings for a host outside the cluster (cluster - members run this machine's, see "Cluster configuration"). -- **Transcript search is per host.** `/api/sessions/search` asks each linked daemon to score only - its own active conversations, then streams the score maps in sidebar host order. An offline, - failing or older daemon contributes no transcript scores; explicit title/name search still works. +### Environment variables +`TAU_PI_BIN` (pi binary), `TAU_NO_EXTENSION`, `TAU_PACKAGE_DIR`, `TAU_PORT`, `TAU_HOSTNAME`, `TAU_PASSWORD_HASH` / +`TAU_PASSWORD`, `TAU_TRUSTED_HEADER` / `TAU_TRUSTED_HEADER_SECRET` / `TAU_TRUSTED_HEADER_SHA256`, `TAU_SESSION_COOKIE`, +`TAU_SESSION_MAX_AGE_SECONDS`, `TAU_SECRET_ENV_VARS`, `TAU_DISABLE_AUTOUPDATE`, `TAU_DISCONNECT_DESTROY_MS`, +`TAU_STT_ENDPOINT` / `TAU_STT_KEY` / `TAU_STT_MODEL`, `TAU_PUBLIC_*` (inlined into the browser bundle). pi's own: +`PI_CODING_AGENT_DIR`. `lib/project-command-env.ts` strips tau's secrets, `PORT` and +`NODE_ENV` from every child environment. + +### Tests (`npm test`, or `bun test --parallel `) +- `--parallel` is required: Bun gives each file a fresh global/module registry. The transport singleton (`lib/event-stream.ts`) and each file's `SharedWorker`/fetch/DOM fakes would otherwise leak into the next file. Use `--parallel` even for a multi-file subset. +- `bunfig.toml` `[test] preload` runs `tests/isolate-tmp.mjs` in every test process: `TMPDIR`/`TEMP`/`TMP` point at a fresh per-process directory (mode 1777) removed in `afterAll`, so state a test writes after restoring its environment (a body past its timeout, a late timer) never lands in the machine's temp directory, where a running server would read it (e.g. `/tau-self-update-`). +- DOM tests import `tests/setup-dom.mjs` first and then import Testing Library dynamically, so its queries bind to that document. +- A module that must see a fake builtin is imported with a fresh query (`?fresh=N`) after `mockBuiltin(t, name, overrides)` (`tests/mock-builtin.mjs`; Bun's `mock.restore()` does not undo `mock.module`, so the helper restores by hand). +- Tests that drive the hub call `flushLinkSamples()` before they restore `PI_CODING_AGENT_DIR`. + +### Session lifecycle (`lib/rpc-manager.ts`) +- One wrapper per session id, keyed in a `globalThis` registry (a plain module-level Map does not survive `bun --hot`). +- Every link is host-owned (`hostOwnedLifecycle`): the daemon owns idle/disconnect cleanup and process-wide settings (`lib/hosts/channel-lifecycle.ts`). Wrappers report tab/command interest and protected preparation through transport capabilities (`setInterest`, `setPreparing`); disposal closes membership, while explicit delete/reload can kill. Reconciliation failure never kills a process another server uses. +- The server-side backstops run only for a transport without `hostOwnedLifecycle` (test fakes): concurrent `startRpcSession()` calls share one start promise; `IDLE_DESTROY_MS` (10 min) and `DISCONNECT_DESTROY_MS` (`TAU_DISCONNECT_DESTROY_MS`, 2 min, `0` disables) fire only once a session is genuinely abandoned (no `onEvent` listener, no run, no startup handshake, no unanswered `send()` or preparation). The last `onEvent` detach *starts* that window. Both are fed by `resetIdleTimer()`, the single activity choke point: a new call path must route activity through it. +- **Project trust.** The daemon starts pi with `--approve` (load the project's `.pi` and `.agents` resources) only when the cwd lies in a workspace registered on that host (`projectTrustArgs`, `local-host.ts`; `registeredProjectFor`, `lib/worktree.ts`: the project, a directory in it, or a linked worktree; pool clones are registered by `pool-starts.ts`). Elsewhere pi's rpc-mode rules decide: the nearest `trust.json` entry, then `defaultProjectTrust: "always"`, else untrusted. pi's flags that pick a session or its storage, leave RPC mode or end the process, change extension loading or override project trust (bare, short or `--flag=value`) are reserved and cannot be set in a project's launch configuration (`RESERVED_LAUNCH_ARGS`, `project-registry.ts`). +- **Session identity.** pi never moves a session to another file on its own. Branch/new/switch/fork drop every key the wrapper had; `startRpcSession` reuses a live wrapper reporting the requested session file instead of spawning a second `--resume` child. +- **Titles.** pi has no title generator. `POST /api/sessions/[id]/auto-name` answers the stored title, else one derived from the first user message, saved through the live process (`set_session_name`) when there is one, else as a `session_info` entry in the file; it never starts a process. + +### Auto-resume after a restart +- **Hosts:** `lib/hosts/host-resume.ts` records unsettled sessions and their launch in `/tau/host-running.json`; the daemon resumes them once after its own restart (`RESUME_PROMPT`). A web-server restart just rejoins the running children. +- **Per web server** (`lib/session-resume.ts`, only for a transport without `hostOwnedLifecycle`): off by default (`autoResumeSessions`). When on, `notifyRunningChange()` keeps `/tau-interrupted-sessions-.json`; startup (`instrumentation.node.ts`) consumes lists whose pid is dead or that predate the last boot, restarts each session and sends `RESUME_PROMPT`. Each instance writes only its own pid's list. Sessions whose child died resume after the host's hello (`resumeOnHostLink`); a death is kept for `EXIT_GRACE_MS`, and `markShuttingDown` freezes the list during shutdown. Only ids are stored. +- Known limit: a terminal `pi --resume` of the same session while tau was down is not detected; both would write the file. + +### Remote hosts (`lib/hosts/`, `app/api/hosts/`, `bin/tau-host.js`) +- **Host seam** (`lib/hosts/host.ts`). Every host, this machine included, is reached over its daemon's link: `getHost(id)` returns a `RemoteHost`. `getHost("local")` is this machine's own `tau host`. `localHost` (`local-host.ts`) is the daemon's side. `RpcProcess`, the wrapper, the event hub, notifications, the queue and `/btw` never see where pi runs. Session and project file reads are `host.sessionOps` (`session-ops.ts`, run in the daemon), addressed by session id, never by path: routes use `resolveSessionHostOr404` (`lib/api-utils.ts`). New route code must not open a session file on main. Workspace operations (files, index, shell output, watch, Git/worktrees, browsing, default cwd `~/tau-cwd-YYYYMMDD`, clone) are `Host.workspaceOps` (`lib/workspace-types.ts`, `workspace-ops.ts`) for every host; they never fall back to main. `SessionInfo.hostId` and `ManagedProject.hostId` carry the host; sidebar/project state keys on `hostProjectKey` (bare path here, `:` elsewhere). +- **Shared hosts** (`docs/specs/2026-11-06-multi-server-host-design.md`): one daemon links every server in `host.json` (the top-level pair is its primary link, `links` the others). `open` joins one session process; events fan out, command replies return only to their sender. The daemon owns lifecycle, streaming snapshots (`stream-snapshot.ts`) and first-answer dialog settlement (`shared-requests.ts`). Web callbacks (host tools) go to the last-active eligible server and are not blindly retried. `channels_changed` announces background runs; `sessions_changed` invalidates lists; one link is the notification publisher (`notifier`). Cross-server fences live in the daemon: a history edit takes the `editLease` op before preflight, and a `peer_message_command` marker makes another server's identical echo ambiguous (`watchReplacement`). An open's preparation lease passes only to the command that asked for it (`withPendingCommand(run, true)`); a command timeout that recycles the child stops the shared process (`destroyAndWait(reason, true)`). Two daemons must never run competing `pi --resume` children on one agent dir. +- **Application link** (`/api/hosts/link`, `link-protocol.ts`, `hub.ts`, `daemon-link.ts`, `daemon-channels.ts`): one WebSocket per host per web server, dialled by the daemon. Text frames carry messages (hub → daemon one per frame; daemon → hub newline-separated batches flushed every `flushMs` (16 ms) or at one piece); binary frames carry large op results (before the `res` naming them) and upload bytes (hub → daemon, `up:`). Every line except `hello`/`welcome`/`ack`/`ping`/`pong` has a per-direction `seq`; each side keeps unacked lines, resends after a reconnect and drops a `seq` it already applied. The daemon's first line of every frame is an `ack`; the hub answers every uplink frame with exactly one. Lines over `pieceBytes` (256 KiB) go as sequenced `part` messages (`PartJoiner`), results as binary frames of at most a piece; both sides queue per key (channel or request) in `LinkSender` and send round-robin. Each side sends queued units only while less than `unackedBytes` (512 KiB) is unacked (the daemon also waits for `bufferedAmount` under two pieces); control lines skip the window. The hub decodes a whole frame before applying any of it. `hello.ack === 0` means a fresh daemon. Each `hello.channels` entry carries `pending`: the raw stdout lines of that child's still-open `host_tool_call`s and blocking `ui_request`s (`pending-requests.ts`), or null past `pendingBytes`. Close codes (`LINK_CLOSE`): 1001 going away (shutdown), 1007 bad frame, 1008 bad first frame, 1009 too big, 4409 replaced, 4426 version; a revoked or unknown host's hello gets a plain close. +- **Protocol versions.** The application link is v1 (`MIN_LINK_PROTOCOL_VERSION` = `LINK_PROTOCOL_VERSION` = 1, literal one-liners that deploy scripts parse with `sed`). A released version changes only compatibly: an added optional field or a message type receivers skip is fine; a changed type or meaning, or a newly required field, needs a new version. Receivers skip unknown message types (acking their `seq`) and answer unknown ops 501 `unknown_op`. A hello outside the range gets 4426 with `{"serverVersion":N}`. Once versions are released, main keeps at least N-1, and the first released version is a floor `MIN_LINK_PROTOCOL_VERSION` never goes above. Upgrade order: web app first, then hosts. +- **Maintenance API v1** (`maintenance-protocol.ts`, `maintenance-hub.ts`, `daemon-maintenance.ts`, `/api/hosts/maintenance`): a separate request/reply WebSocket the daemon dials with the same bearer token, versioned apart (`MAINTENANCE_API_VERSION`) and kept stable so a host whose application protocol differs can still be inspected and updated. Ops: `status`, `listSessions`, `checkUpdates`, `updateSoftware`. Frames ≤ 1 MiB, 8 requests in flight, 30 s per request; a hello with another API version gets 4426 `{"apiVersion":N}`. Its hello reports `protocolVersion` (advisory), `tauVersion`, `piVersion`, platform and capabilities. Nothing it meets (no API on the server, another version, a refused token) stops the daemon or its pi children. Host updates use only this API (see "Updates"). +- **Link samples** (`metric: "link"` in `/tau/transport-metrics.jsonl`, measurement only): each side samples every sequenced message once (size, session, `bytesAhead`) and records `ackMs` when it is acked; the daemon reports its `up` samples in sequenced `stats` messages (≤ `statsSamples`), batched per `statsFlushMs` (30 s). The hub drops malformed samples without failing the frame and caps `up` samples per host per window (excess as one `{dropped}` record). `bun scripts/link-hol-probe.ts` makes load; `scripts/transport-metrics.ts` prints the summary. +- **One socket per host per web server.** A new hello with the same token on the same server closes the previous socket 4409 (only that link ends). A frame belongs to the socket it arrived on: the hub ignores frames from a socket that is no longer the host's link. A revoked host is refused at the upgrade (401) and at the hello. +- **Transport down is not exited.** While the link is down the pi child keeps running. A wrapper whose host is not `isLinkUp(status)` is "transport down": no `process_exit`, idle/disconnect timers paused; frames carry `host_status`; sends answer 503 `{hostOffline: true, delivery}` (`"refused"`: nothing left, the composer keeps the draft; `"unknown"`: sent before the drop, the composer drops the draft so it is never sent twice). A child missing from `hello.channels` gets a synthesized `process_exit`. Use `isLinkUp` (client-safe) as the one link predicate; never compare `status === "online"` (a `pi-missing` host is linked). +- **A failed op never runs later.** An op that times out (504) or whose link drops (503, at once) is removed from the outbox (`failOp`), so a delete the user saw fail is never applied after a redial. The 30 s op deadline counts silence: each binary result frame restarts it. `destroyAndWait` returns once the host is offline (`untilHostDown`); the kill stays queued. A wrapper stays registered until its child really exits, so a retry awaits its `destroyPromise` instead of spawning a second `--resume` child; a reload waits for the old child the same way (`host_offline` until that exit or `lost`). Remote-only transport members (`onResync`, `lost`) are duck-typed: never `instanceof RemoteRpcTransport` (`bun --hot` may re-create the class). +- **Live-link recycle rule.** A prompt, history-edit or MCP command that times out normally recycles the child; on a remote host only if the host sent uplink traffic after dispatch (`lastUplinkAt`, `linkLostDuring`). A quiet or dropped link answers `host_offline` (503), queues no kill and leaves the run to `reconcileAfterGap`. +- **Orphans and adoption.** On `hello`, listed channels with no wrapper are adopted (`reattach`/`adopt`): servers `open` each, restore pending requests and the current streaming message, request state/subagents/side-question snapshots, then release held frames (`RpcProcess.release` skips requests the replay already delivered). Adopted wrappers feed replayed requests through `handleFrame` (`replaying`; agent tools are not re-run), so dialogs reappear and browser tool calls wait for the next tab (`hostToolsUnknown`, `parkHostTool`). Only when adoption is impossible is a child killed (escalating to force after 5 s). A cold spawn awaits `orphanExit(hostId, sessionId)` first; the wait rejects 503 when the link drops. A daemon buffer overflow (`channelBufferBytes`, 32 MiB per channel) drops the backlog and sends `resync {ch}`; main reruns the `get_state` reconcile. +- **Proxy exclusion.** `proxy.ts` `UNGATED` lets through exactly `/api/hosts/link`, `/api/hosts/maintenance`, `/api/hosts/cluster-config/manifest` and `/api/hosts/cluster-config/file/<64 hex>` (plus static assets, icons and `sw.js`). The daemon has no cookie; each of these checks `Authorization: Bearer ` itself (the link before the upgrade: 401 unknown token, 503 unreadable `hosts.json` or frozen server; the cluster routes through `admitClusterMember`, again after the build). `/api/hosts` and `/api/hosts/[id]/*` (an id of `cluster-config` included) stay gated. A reverse proxy passes the ungated paths without its own authentication and without redirects. +- **Remote paths never reach `allowFileRoot`** or any other main-side filesystem check. `startNewRpcSession` calls `allowFileRoot` and the local list invalidation only for the local host; remote cwd validation is the host's `validateCwd`. Daemon input is untrusted: blob hashes must match `^[0-9a-f]{64}$`, results are shape-checked (`hub.ts`, `workspace-results.ts`), and `sessionFileExists`/`spawn` accept only paths under the daemon's sessions directory. A remote session export is always an attachment. +- **Daemon-loaded modules must not import `@/` or use Bun APIs.** `bin/tau-host.js` loads `lib/hosts/host-cli.ts` through plain `jiti` on Node (no `@/` alias, no `Bun` global); that covers everything the daemon pulls in (`daemon*.ts`, `link-protocol.ts`, `maintenance-protocol.ts`, `local-host.ts`, `session-ops.ts`, `workspace-*.ts`, `preflight.ts`, the `lib/pi/*` they import). Use relative imports. +- **Registry.** `/tau/hosts.json` (0600, atomic) stores only `sha256(token)`; the token is shown once. Mutations use the strict reader and throw `HostRegistryUnreadableError` (503) instead of rewriting a file they could not parse. Revoke deletes the record first, then closes the link (the daemon stops its children). A missing `hosts.json` (an agent-dir mismatch) answers 401 to every daemon, and a daemon told its token is unknown stops all its pi children: check `PI_CODING_AGENT_DIR` before starting main. +- **Agent tools.** Calls carry the caller's host (`sourceHostId`); `new_session`'s `host` defaults to it. A host with `allowAgentStart` off asks a server-owned `confirm` (`confirmFromServer`). Local callers never ask for this machine; a remote caller asks before any other host unless that host allows agent starts, and always before this machine, for `new_session` and `send_to_session`. +- **Message origin** (`docs/specs/2026-11-14-message-origin-design.md`). Messages from `send_to_session`, a `new_session` first prompt or the GitHub watcher stay native user messages but carry server-authored `origin`. The extension journals it with the message's `client-message-entry` (`/tau_meta name`); the reader joins it only on the active branch, and the outbox stores it beside held entries. Browser/HTTP commands cannot supply `origin` (`origin_not_allowed`); readers drop malformed or over-4096-byte metadata. The chat renders trusted origins as source cards (`OriginMessageView`). +- **Transcript search is per host.** `/api/sessions/search` asks each daemon to score its own conversations and streams the score maps in sidebar host order. An offline or failing daemon contributes no transcript scores; title search still works. + +#### Cluster (`lib/hosts/cluster.ts`, `pools.ts`, `pool-starts.ts`; `docs/specs/2026-11-11-cluster-membership-design.md`) +- The cluster is `pools[0]` of `/tau/pools.json`; `local` is its master, added on creation or on the next join. The rest of `pools.json` is ignored by the interface. An unreadable `pools.json` refuses a start (503 `pool_storage_unavailable`). +- **No credential sharing.** Every host, members included, uses its own pi logins (`auth.json` is never mirrored). Placement (`pool-starts.ts`) skips a member that has no login for the requested provider (`canAuthenticate`, from the host's `auth` op) and a member not on the master's current configuration (`isHostConfigCurrent`); `startPooledSession` says "still receiving the cluster's configuration" when that is why. +- **Join keeps what the host showed.** The host's Git projects bind to cluster projects by repository (`gitOrigins`); a created cluster project takes the host project's name, else its folder name, and its alias; binding a visible checkout un-hides a hidden cluster project. `POST /api/projects` pool registration matches by `repositoryKey` and keeps the stored origin. A join of a host holding another server's configuration is 409 `host_in_other_cluster`; a host joins once it is online (`clusterJoinBlock`). +- **Only grouping passes `pools` to `projectTargetId`.** Selection, expand keys, reorder, pin and drag use the project's own target. +- For a cluster session on another member (`isClusterTarget`), the MCP, Skills and Plugins panels use no cwd and no session (the user-level routes). + +#### Cluster configuration (`cluster-config.ts`, `cluster-config-server.ts`, `daemon-cluster-config.ts`; `docs/specs/2026-11-11-cluster-configuration-design.md`) +A member runs pi on the master's configuration; its daemon applies it, never pi. +- **Mirrored** (`MIRRORED`): from the agent dir `settings.json`, `models.json`, `mcp.json`, every context-file candidate (`AGENTS.override.md`, `AGENTS.md`, `CLAUDE.md`), `SYSTEM.md`, `APPEND_SYSTEM.md`, and the `skills`, `prompts`, `themes`, `extensions` directories; from home `~/.agents/skills`. Never credentials (`auth.json`, `mcp-auth.json`), sessions or caches (`npm/`, `git/`, `bin/`), nor `.pi/` in a repository. pi packages travel as `settings.json` `packages`, which pi installs at startup; there is no separate plugin step. +- **`settings.json`** is mirrored without the `LOCAL_SETTINGS` key paths (local paths and programs, installation identity, terminal: `shellPath`, `npmCommand`, `sessionDir`, `httpProxy`, `extensions`, `skills`, `deviceId`, `terminal`, ...); the member merges its own values back (`mergeLocalSettings`). One constant serves both sides. +- **Master.** `buildManifest` lists the files with hashes, the agent environment variables and a `version` (sha256 over all of it). Limits (`CONFIG_LIMITS`): 5 MiB per file, 50 MiB per bundle, 5 MiB manifest; a configuration over one is not served (`ClusterConfigError`, naming a path and never content; Settings shows it as `masterConfigError`). `currentClusterConfig` rebuilds only when its fingerprint (a stat walk, skipping `.git`/`node_modules`) changes; a read error makes the fingerprint unique so the error is reported. `syncClusterConfig` (`hub.ts`) runs at start, every 30 s and on a new version: `clusterConfig apply` to each online member that is not current, `restore` to a host outside the cluster that still holds this server's configuration; never while one of that link's ops is unanswered. Join sends `apply` after it saves `pools.json`, leave `restore`; neither awaits between reading and saving the pools. +- **Launch.** The hub sets `open.launch.configVersion` (64 hex) for a member's process start (not a join), after re-reading `pools.json`. The daemon strips `configVersion`/`configServer` from every wire launch and sets them only for the opening link (`forStart`); a launch with a version applies it first (`ensure`) or is refused 409 `cluster_config_failed`. The version is never written to the resume manifest. +- **Daemon.** Per version: manifest, then each missing file by hash (`/tau/cluster-config/objects/`, verified), then one transaction: stage, move the member's own entries aside (first apply: `own-config/` with its `settings.json`, `agent-env.json`, `server.json`; later: `trash/`), move the staged ones in, write the agent environment and `state.json`. Any failure puts everything back. Renames move links as links and cannot cross filesystems (`EXDEV` names both directories). Requests to the master must finish within 30 s (`clusterConfigTimings.fetchMs`). Applies and restores run one at a time. +- **Ownership.** `own-config/server.json` records the one server whose configuration the host holds. Another server's apply is refused while that one is still in `host.json`; one no longer linked is taken over. Only the holder's `restore` puts the member's own configuration back; a start sent before its restore is refused after it. A link that ends revoked while its server holds the configuration awaits `restore` before the daemon stops. +- **Reports.** `config_state { state, owned }` is an unsequenced daemon report (like `capacity`): at link up, on change and after each `host.json` reload. `ConfigState` is `{ version, files, error, missingCommands }`; Settings shows current, updating, failed, held by another server, and the MCP commands missing on the member. #### Local daemon (`docs/specs/2026-10-29-local-daemon-design.md`) -- **Independent host lifetime.** Installers still install web and host services together; ordinary web restarts leave the daemon's sessions running. Production also starts a missing local host independently through `local-daemon-start.ts`, after preparing its link and probing private control. The singleton prevents duplicates. A coordinated upgrade may restart a shared-installation or incompatible host only after plan approval, with explicit Force approval when sessions may end. -- **Local link bootstrap** (`lib/hosts/local-bootstrap.ts`, `instrumentation.node.ts`): async `ensureLocalHostLink()` atomically upserts this server's `{url, token}` in `host.json.links` under the same lock as token selection, preserving the primary pair and other links. Files stay 0600. The directory watch reconciles added/removed links without restarting the daemon; malformed configuration is not overwritten. `ompweb host login --add --url ` adds a remote server (token from stdin); `host logout --url ` removes its link. A remote primary remains protected from local bootstrap replacement. -- **Dev mode does not take the daemon.** With `NODE_ENV=development` `ensureLocalHostLink` is skipped, so the daemon stays linked to production and the dev server shows "This machine" offline. The local row of `GET /api/hosts` carries `daemonManaged: false` there, which hides the install banner. -- **`local` is a registry record like any host**, with three exceptions: it is listed first, `PATCH` takes `label` only (`allowAgentStart` is fixed), and it cannot be revoked. Renaming "This machine" is a `PATCH /api/hosts {id: "local", label}`; an empty label resets it (`registry.ts` stores `""`; `customLocalLabel()` / `DEFAULT_LOCAL_LABEL` map it). `getHost("local")` works without the record: it is the daemon link, offline while none is linked, and "needs upgrade" on a protocol mismatch (`hostVersion` in the row is the daemon's). -- **Joining on hello** (`reattach`/`adopt` in `hub.ts`): servers call `open` to join each listed channel, restore pending requests and the current whole streaming message, then request state/subagents/side-question snapshots before releasing held frames. They also join `channels_changed` announcements with no tab open, preserving background badges/notifications. The daemon has already negotiated and set process-global subscriptions; servers do not change those settings. -- **The daemon replays open blocking requests** (`pending-requests.ts`): `host_tool_call`, `host_uri_request` and blocking `ui_request` lines, until answered or cancelled, capped at `LINK_LIMITS.pendingBytes` per channel. An adopted wrapper feeds them through `handleFrame` (`replaying`; agent tools are not re-run), so dialogs reappear and browser tool calls wait for the next tab (`hostToolsUnknown`, `parkHostTool`). A request opened while the old server stopped is also resent unacked: `RpcProcess.release` skips held requests the replay already delivered, so it is handled once. The hello also carries `autoApproveExtension`, which an adopted run has no spawn result for. -- **Adoption failure** or disposal closes the server's membership; the host decides abandonment and continues any peer's run. Explicit delete/archive is fenced on the host against a concurrent open, even before this server has a wrapper. -- **Shutdown freezes the links and never kills daemon children.** The `cleanup` in `rpc-manager.ts` runs `markShuttingDown()` and `freezeHostLinks()`: link sockets are closed 1001 and from then on a link neither sends nor applies anything (no kill, no rejection of open host tool calls as tabs close); new upgrades get 503 "omp-web is shutting down". A real SIGTERM exits in the same tick (`process.exit` in `instrumentation.node.ts`), before Bun writes the close frame, so daemons usually see 1006 or ECONNREFUSED rather than 1001 and redial the same way. The daemon keeps the output unacked and redials for the next server. An adoption that fails after the freeze leaves its child to the next server instead of killing it. -- **Failed-start guidance** (`components/LocalDaemonBanner.tsx`). Production first attempts automatic host startup without installing services. If no daemon links within the existing 90 s grace, the banner and Settings → Hosts retain start/install guidance. Development never starts or takes the production daemon. An unknown or unsafe existing control endpoint is an error, not permission to launch another host. -- **No direct local path.** `local-host.ts` is the daemon's; `lib/hosts/no-direct-local.test.mjs` fails when anything outside its allow-list spawns omp or imports it. The utility omp (`rpc-utility.ts`, login) is the one deliberate exception: it is not a session. - -### Session moves (omp >= 18.5 ownership) and title generation -- Only the first omp process to write a session file owns it; a non-owner moves - to a sibling file with a new id on its first write and emits a - `notice` with `source: "session-persistence"` (the runner sends it before the - new `session` frame, which the daemon's `ChannelTable` reads the same way). `handleFrame` answers it with - `followSessionMove()`: the pending flag makes the next `applyIdentity` treat - the id change as the same conversation (stream/run state kept, **old id kept - as a registry alias**, new id registered via `onIdentityChange({keepOldId})`). - Branch/new/switch drop every key the wrapper had (aliases included), since it now serves another conversation. `startRpcSession` also reuses any - live wrapper reporting the requested session file instead of spawning a second - `--resume` child (which would fork again). A move during startup (before the - first `get_state`) is aliased too, so the requested id stays routable. - `onDestroy` removes every key that points at the wrapper. -- `POST /api/sessions/[id]/auto-name` asks omp to generate the title - (`AgentSessionWrapper.generateTitle()`: native `generate_title`, else - argument-less `/rename`, never while a run is in flight). Only when omp cannot - does it fall back to the stored/derived title (`generated:false`), saved - through the live process when there is one. +- **Independent lifetime.** Installers install web and host services together; web restarts leave the daemon's sessions running. Production also starts a missing local host itself (`local-daemon-start.ts`) after preparing its link and probing its private control endpoint (`host-control.ts`: an owned 0600 socket, or a random named pipe with a per-start token on Windows; `tau host status|drain|resume`). An unknown or unsafe existing endpoint is an error, not permission to start another host. `local-daemon-supervisor.ts` knows the installed services (`tau-host.service`, launchd `dev.ompweb.tau-host`, task `tau-host`). +- **Local link bootstrap** (`local-bootstrap.ts`): `ensureLocalHostLink()` upserts this server's `{url, token}` in `host.json` under the same lock as token selection, preserving the primary pair and other links (0600). The daemon's directory watch reconciles added/removed links without a restart. `tau host login [--add] --url ` (token from stdin) and `tau host logout --url ` manage links; a remote primary is never replaced by local bootstrap. +- **Dev mode does not take the daemon.** With `NODE_ENV=development` `ensureLocalHostLink` is skipped, so the daemon stays with production and the dev server shows "This machine" offline (`daemonManaged: false` hides the install banner). +- **`local` is a registry record like any host**, except that it is listed first, `PATCH` takes `label` only, and it cannot be revoked; an empty label resets it to "This machine" (`customLocalLabel`). `getHost("local")` works without the record. +- **Shutdown freezes the links and never kills daemon children.** `cleanup` runs `markShuttingDown()` and `freezeHostLinks()`: sockets close 1001, and a link then neither sends nor applies anything; new upgrades get 503. A real SIGTERM exits in the same tick, so daemons usually see 1006 and redial; they keep their output unacked for the next server. +- **Failed-start guidance** (`LocalDaemonBanner.tsx`): if no daemon links within 90 s, the banner and Settings → Hosts show start/install guidance. +- `tau preflight` (`preflight.ts`) starts pi the way a host starts one for a new session (`--no-session`, scratch cwd, `PREFLIGHT_MARKER`) and waits for `get_state`; updaters run it on a candidate release and grep its `preflight ok:` line. ### Browser compatibility -Client code (`components/`, `hooks/`) must not call `AbortSignal.timeout`, -`AbortSignal.any` or `Promise.withResolvers` — older mobile browsers throw and -the whole tree shows the "unexpected error" screen. Use `AbortController` + timers and -executor-style promises instead. Server code may use them freely. +Client code (`components/`, `hooks/`, the worker) must not call `AbortSignal.timeout`, `AbortSignal.any` or `Promise.withResolvers`: older mobile browsers throw and the whole tree shows the error screen. Use `AbortController` + timers and executor-style promises. Server code may use them. + +### Browser storage and events +Browser keys use `tau-` / `tau:` (`tau-theme`, the `tau-theme-color` cookie, `tau-draft-*`, `tau:expand-thinking`, `tau:submit-during-run`, ...); window events are `tau-*` / `tau:*` (`tau-open-session`, `tau:connection-diagnostics`, ...); IndexedDB is `tau-outbox`. ### Editing and branching — don't confuse them -- **Fork** ("Fork a new session from this point" button, `messageView.newSessionTitle`, on user and assistant messages; only offered while the session is idle — ChatWindow gates it on `!sessionBusy && !isNew`): creates a new independent `.jsonl` file via omp's `branch` RPC. Shown as a child in the sidebar tree via `parentSession` header field. `branch` only takes a user entry and keeps the history *before* it, so `lib/chat-fork.ts` maps rows: a user prompt forks at itself and its returned text prefills the fork's composer (edit-and-resend, text only — attached images are not restored); an assistant reply forks at the next user prompt so the reply is kept; the newest reply falls back to its own prompt with the prefill. Rows that would edit the very first prompt (an empty fork) offer no fork. - The button only opens a `ConfirmDialog` (`ForkSessionButton`); `onFork` runs on confirm, so a stray tap while scrolling never forks. -- **Edit** (`edit_message`, user-message button): moves the live conversation's history to before that user entry; it is not a read-only historical view or an explicit Fork. The runner's `edit_message` command (`runner/src/commands/session.ts`) calls omp's `navigateTree(entryId, { summarize: false })` and appends a non-message `omp-web-history-navigation` entry. The web server never imports the Bun-only SDK or rewrites the JSONL. - - The button only opens a `ConfirmDialog` in `UserMessageView`; `onEdit` runs on confirm, so a stray tap never rewinds the live session. - - Require authoritative `get_state.isSettled === true` and reject pending background work; runtimes without settlement reporting fail explicitly. Preserve run/edit fencing, including rename and automatic-title fallbacks, and do not report success after an observed edit-time native persistence error. - - `SessionEditResult` remains `{ sessionId: string, cancelled: boolean, leafId: string | null }`. The returned ID identifies the confirmed post-edit conversation. Single-owner Edit keeps ID/file; a non-owner's native copy-on-write relocation is expected. Server persistence notices feed `applyIdentity` and registry aliases; the HTTP result drives client identity adoption (there is no public identity-change frame). Reload the confirmed target before text prefill, reject unrelated switches, and preserve the original file and old branches. - - The private `/omp-web-edit` transport uses `prompt`, so installed input hooks must pass the internal command through unchanged. OMP v18.12.6 invokes input hooks before command dispatch; registration checks alone do not bypass them. A temporary-hook probe confirmed consumption can intercept the command without an agent run. No input-handler registrations were found in the 20 official hook/extension TypeScript examples examined, and the official RPC fixture matches `consume:`, `transform:` and `slow:` rather than slash commands. Conflict probability is unmeasured and no known shipped third-party conflict is established. This is an explicit compatibility boundary, not a promise of arbitrary plugin support or a requirement for universal hook-free upstream RPC. - - Preserve ordinary native storage/error semantics: appends commonly reach the OS page cache synchronously, persistence failures latch and emit `source: "session-persistence"`, `level: "error"` notices, and native `flush()` throws latched errors. An append returning alone does not prove error-free persistence; surface observed edit-time write failures rather than claim success. Edit does not introduce a stronger fsync guarantee or require a new global durability API. - - A native `prompt` acknowledgement may have no data; only the request-correlated extension result confirms Edit. An observed persistence-error notice is not handler completion: keep the operation fence until the handler completes, or await child teardown on uncertain completion before unlocking. If an input hook invokes an agent, an observed run must retain run ownership; an acknowledged but not-yet-started agent cannot leave an unfenced startup gap and requires awaited teardown. - - Prefill only the selected message's text, not its original images. Preserve existing drafts, newer typing and composer attachments through pending edits, cancellation, errors and genuine navigation. `submissionBlocked` keeps asynchronous dictation from submitting or clearing the composer without disabling recording pause/resume/discard. `session_history_changed` carries the leaf marker; the initiating tab deduplicates its own delayed echo without resetting a newer view or run. Editing does not undo filesystem/tool side effects. - - Legal identity moves keep the hook and composer mounted. Transfer drafts capacity-neutrally and carry the exact source snapshot so input completed in the same React batch is merged, not overwritten or duplicated. Pending attachment reads, recordings and recovery operations retain their owner across the move; genuine navigation remains isolated. Draft text survives full-page reload via sessionStorage; attachment payloads remain memory-only. - - The confirmed-move callback synchronously calls `ChatInputHandle.retargetPendingRecovery(from, to)` before state updates or parent callbacks. This advances only captured queue-recovery ownership, closing the acknowledgement-to-commit gap; layout hydration still owns the live composer key/state. Do not turn this pre-commit ownership handoff into eager draft hydration. - - Pending transcription keeps its original server scope/job/claim ownership. Confirmed moves record a tab-local recovery association so the target can rediscover that job after navigation/remount; other clients' drafts and server scopes are not migrated. A hard reload before an upload acknowledgement can leave multiple possible source jobs; retain recovery and report ambiguity rather than guess or reupload. - - Event connections own their readiness waits: replacement and unmount settle the old wait as closed, clear its timers/coalesced work and close its observer. Late continuations must not attach streams to an unmounted hook or let a stale connection authorize a new operation. Keep lifetime cleanup separate from the mount-load latch so StrictMode setup/cleanup replay still cleans up observers attached afterward. - A new chat's first prompt is the exception to "abandoned readiness": when its chat unmounts while omp spawns, `handleSend` still sends the prompt, opens no observer, skips host-tool/roster setup and returns `accepted`. An existing session's messages need no exception: they go through the message outbox (below), which delivers them with no tab involved. - Ordinary `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` (an existing session) the composer clears only once `onSend` (or `onSteer`/`onFollowUp`) reports the message stored in the browser's outbox, and only if it still holds what was sent; a refusal leaves it in place. For a new chat only rejection restores composed text/file contents and images through `recoverDraft`; its receipt supplies the promoted real-session draft key when the new chat became a session, otherwise the composer uses the originating key captured before submission. Superseded failures must not reinsert a processed turn or reset a newer run. The composer owns recovery; `useAgentSession.handleSend` must not separately insert failed-send text and duplicate it. - Retry roots may be server-known or browser-only. Server-known roots are hidden only on a server-confirmed `replaces`; a browser-only failed root is retired only after a valid accepted receipt for its committed, same-session exact-intent copy, even if a lost-response replay is an empty tombstone without `replaces`. Concurrent same-root holds share one IndexedDB copy and each caller gets its durable-add acknowledgement. Refusals preserve the root; cross-session and unrelated same-text entries remain. -- **In-session branch** (Continue button / BranchNavigator): reads a historical view of the entry tree within the same file; it does not change the live agent's context. Multiple entries share the same `parentId`. Switching between them calls `/api/sessions/[id]/context?leafId=` through `handleLeafChange`; never use that read-only path to implement Edit. +- **Fork** ("Fork a new session from this point", user and assistant messages; only while idle: `!sessionBusy && !isNew`): pi's `fork` RPC writes a new `.jsonl` with the history before a user entry and switches the live process to it; the sidebar shows it as a child via `parentSession`. `lib/chat-fork.ts` maps rows: a user prompt forks at itself and its returned `text` prefills the composer (text only); an assistant reply forks at the next user prompt so the reply is kept; the newest reply falls back to its own prompt with the prefill. Rows that would fork before the very first prompt offer no fork. The button only opens a `ConfirmDialog`. +- **Edit** (`edit_message`, user-message button, confirm first): moves the live conversation's leaf to before that user entry through `/tau_edit` (`navigateTree(entryId, { summarize: false })`); the old branch stays in the file. The server never imports pi's SDK or rewrites the JSONL. + - Requires authoritative `get_state.isSettled === true` and no pending work (`session_edit_unsupported` without settlement reporting, `session_busy` otherwise). Preserve run/edit fencing, including rename and title fallbacks; do not report success after an observed edit-time persistence error notice. + - `SessionEditResult` is `{ sessionId, cancelled, leafId }`; the wrapper checks it against a fresh `get_state` and refuses any other id or file (`session_changed`: pi never moves a session to a new id). Reload the history before the text prefill. + - `/tau_edit` arrives as a `prompt`, so an installed input hook must pass it through unchanged; this is an explicit compatibility boundary. + - Prefill only the selected message's text, never its images. Preserve drafts, newer typing and attachments through pending edits, cancellation, errors and navigation. `submissionBlocked` keeps asynchronous dictation from submitting or clearing the composer. `session_history_changed` carries the leaf marker; the initiating tab deduplicates its own echo. Editing does not undo tool side effects. + - Draft text survives reload via sessionStorage; attachment payloads stay in memory. + - Event connections own their readiness waits: replacement and unmount settle the old wait as closed and close its observer; stale continuations must not attach streams or authorize operations. A new chat's first prompt is the exception: when its chat unmounts while pi spawns, `handleSend` still sends it and returns `accepted`. Existing sessions' messages go through the outbox. + - `ChatInput.onSend` returns `Promise` (`accepted` / `rejected` / `superseded`). With `outbox` the composer clears only once the message is stored in the browser's outbox and only if it still holds what was sent. For a new chat only rejection restores the draft (`recoverDraft`; the composer owns recovery); superseded failures never reinsert a processed turn. +- **In-session branch** (Continue / BranchNavigator): a read-only historical view of the entry tree through `/api/sessions/[id]/context?leafId=` (`handleLeafChange`); it does not change the live agent. Never implement Edit with it. ### ToolCall field normalization -Sessions store toolCall blocks as `{type:"toolCall", id, name, arguments}` but `ToolCallContent` uses `{toolCallId, toolName, input}`. `normalizeToolCalls()` in `lib/normalize.ts` handles this — called in both `session-reader.ts` (file load) and streaming event handling. +Session files store toolCall blocks as `{type:"toolCall", id, name, arguments}`; `ToolCallContent` uses `{toolCallId, toolName, input}`. `normalizeToolCalls()` (`lib/normalize.ts`) converts, in `session-reader.ts` and in stream handling. ### Live tool execution (`tool_execution_start/update/end`) -omp announces a tool the moment it starts, streams the tool's output while it -runs, and only commits the `toolResult` message at the end. The UI must not -wait for that commit: -- `useAgentSession` keeps a `liveToolResults` map keyed by `toolCallId` - (seeded on `tool_execution_start` with `partial: true`, refreshed on - `tool_execution_update` — omp sends the FULL accumulated partial result per - chunk, latest wins — and released on `_end`/the committed toolResult). - Committed results always win over live entries (`ChatWindow` merges them), so - a reload never shows a stale snapshot. -- `ToolCallBlock` renders a `partial` result as **running** (spinner, and - "Running tool…" instead of the "(no output)" marker when nothing has been - printed yet), and opens the row while it runs when the "Keep tool calls - collapsed" setting is off — that is what that setting means. `AppShell` must - pass `toolCallsDefaultCollapsed` into `ChatWindow`; without it the setting is - inert (the chat then always collapses). -- `CommittedTranscript` renders the newest turn flat only while the UI "Hide - tool activity while working" setting is off; with it on (the default) the - running turn folds into one **Process details** row per activity run, like a - finished turn. `AppShell` must pass `hideToolActivity` into `ChatWindow` for - the switch to do anything. The fold row is the expand affordance, so a hidden - tool call is one click away rather than gone. -- Two more UI switches shape the fold, both planned in - `planTurnSegments` (`lib/chat-transcript-plan.ts`): `showThinking` - (driven by "Expand thinking blocks by default") and `showToolCalls` ("Show - tool calls outside Process details", `omp-web:show-tool-calls-unfolded`) - treat those blocks like text, so they never fold. A text segment can - therefore carry thinking, and `ChatWindow` passes its `sourceBlockIndices` - so deferred thinking loads the right block. "Never fold tool activity" - (`omp-web:never-fold-activity`, planner option `neverFold`) plans every turn - as standalone message rows, so the render window still counts messages and a - long turn never mounts at once; it overrides "Hide tool activity while working". -- `tool_execution_update` is coalesced per tool call at display rate in - `lib/message-update-coalescer.ts` (chatty commands emit ~10-100+ frames/s), - like `message_update` (which carries omp deltas, see "Streaming message - updates"). - `message_end` drops the pending `message_update` (the committed message - supersedes it) but must NOT drop buffered tool updates. -- Live entries are cleared on `agent_start`, terminal `agent_end`, prompt - send/settlement failure — a tool must never leak into the next run. - -### Reasoning display ("Expand thinking blocks by default") -- `ThinkingBlock` (`components/MessageView.tsx`) seeds `expanded` from - `expandThinkingByDefault`, plumbed and stored exactly like - `toolCallsDefaultCollapsed` (`omp-web:expand-thinking` in `AppShell`, off by - default). It is an initial value only: manual collapse/expand keeps working - per block, and a reload remounts from the preference. -- The preference deliberately covers a **streaming** block too. A "completed - only" rule would have to flip the state mid-stream (fighting a manual - collapse), and remounts start from the preference either way, so streaming and - completed blocks stay consistent. -- Auto-expanded historical blocks are `deferred` (thinking text is fetched on - demand), so a mount effect loads their content through the same loader the - click path uses — one request per mount, cached per (session, entry, block). -- While the preference is on, thinking never folds into **Process details**: - a streamed block mounts expanded, and folding it when the step commits would - hide it in a closed row, which reads as the block collapsing on its own. +pi announces a tool when it starts, streams its partial result while it runs, and commits the `toolResult` message at the end. The UI must not wait for the commit: +- `useAgentSession` keeps `liveToolResults` by `toolCallId` (seeded on `_start` with `partial: true`, replaced on each `_update`, which carries the whole accumulated partial result, released on `_end`/the committed result). Committed results always win (`ChatWindow` merges them). +- `ToolCallBlock` renders a `partial` result as running ("Running tool…" while nothing is printed), and opens the row while it runs when "Keep tool calls collapsed" is off. `AppShell` must pass `toolCallsDefaultCollapsed`, `hideToolActivity` and the display options into `ChatWindow`, or the settings are inert. +- `CommittedTranscript` folds the running turn into **Process details** rows while "Hide tool activity while working" is on (default). `planTurnSegments` (`lib/chat-transcript-plan.ts`) also honors `showThinking` ("Expand thinking blocks by default"), `showToolCalls` (`tau:show-tool-calls-unfolded`) and `neverFold` (`tau:never-fold-activity`: every turn as standalone message rows; overrides the hide setting). +- `tool_execution_update` is coalesced per tool call at display rate (`lib/message-update-coalescer.ts`). `message_end` drops the pending `message_update` but never buffered tool updates. +- Live entries are cleared on `agent_start`, terminal `agent_end` and prompt failure. + +### Reasoning display +`ThinkingBlock` seeds `expanded` from `expandThinkingByDefault` (`tau:expand-thinking`, off by default), an initial value only; it covers streaming blocks too, so no state flips mid-stream. Auto-expanded historical blocks are deferred: a mount effect loads them through `/api/sessions/[id]/entries/[entryId]/thinking`, cached per (session, entry, block). While on, thinking never folds into Process details. ### Tool-result images (`lib/media-cache.ts`, `/api/media/[hash]`) -- Tool-result images never reach the browser as base64. History (`deferMedia`) - and live frames (`AgentSessionWrapper.emit`, which also feeds the replay - snapshot) replace each image with `{type:"image", mimeType, url:"/api/media/"}`. - User-message and custom-message images stay inline. -- The hash is omp's blob address (sha256 of the bytes): blob refs map directly - (a missing blob becomes the `[image unavailable …]` text), inline images are - hashed and copied to `/media/`. omp writes blobs in place, so the - 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 `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. - -### Streaming message updates (omp deltas) -A full `message_update` carries the whole message twice (`message` and -`assistantMessageEvent.partial`), 7-11 KB per frame at several frames per -second. omp >= 18.13.2 sends rebuildable deltas instead, and omp-web uses them -end to end: -- Every session start (spawn, restart, adoption) sends `set_event_filter` - `{ events: null, messageUpdates: "delta" }`. omp accepts the option since - 18.4.5 and sends rebuildable deltas (with block shells) since 18.13.2; an omp - that rejects or ignores it keeps full updates, which every consumer below - still handles (a frame is a delta when its `message` has no `content`). The - reply is not read: the first delta that does not fit tells. -- `lib/message-delta.ts` is the one reducer, shared by server and browser: a - `*_start` carries the opened block, `*_delta` appends at `contentIndex`, - `*_end` carries the final block, `start` restarts from a whole message. - `toolcall_delta` text accumulates in the block's `partialJson`; the arguments - are parsed from it only for display and snapshots (`withStreamedArguments`, - read as omp's `parseStreamingJson` does). It returns null for anything it - cannot place, and nobody renders a guess. `message_end` stays authoritative - (omp adds `intent` there; block kinds with no start event arrive only there). -- The wrapper (`rpc-manager.ts`) keeps each open assistant message by - `messageId` and rebuilds it. Only `message_start` and a rebuilt delta set that - base: a full update drops it (its tool calls have no streamed JSON, and its - snapshot can be ahead of the next delta). `getStreamSnapshot()` (HTTP catch-up) carries it - with `streamingMessageId`, and `onEvent` replays it as one whole - `message_update` to a tab that attaches mid-message, before any later delta. -- No base (adopted child after a server restart, frames lost on the host link — - `reconcileAfterGap` drops every base): the delta is not forwarded and the - wrapper switches omp to full updates until that assistant message ends (or the - run ends), then back to deltas. A delta that does not fit a message the - wrapper does have (an omp from 18.4.5 to 18.13.1 sends no block shells), or a - `set_event_filter` switch that fails, leaves the session on full updates for - good; after a failed switch the next lost delta asks for full updates again. -- Backpressure (`event-stream-hub.ts`, SSE and WebSocket sinks): a behind socket - queues `message_update` frames; consecutive deltas of one block concatenate, - a whole message replaces the queued updates of its message, and nothing is - dropped or reordered. Merged frames keep the latest frame's sequence and emit - time and carry `web.first`, their first piece's sequence. Deltas of different - blocks never merge past each other: that would break the sequence order. -- Browser (`lib/message-update-coalescer.ts`): applies each delta on arrival and - dispatches the whole message at display rate, so `useAgentSession` only ever - sees whole messages. A delta with no base is held and triggers a catch-up; the - HTTP live snapshot (`seed`) re-bases the coalescer whenever it is applied, and - otherwise completes held deltas newer than it when it is not older than them. - At most 1000 deltas are held; past that they are dropped, and only a snapshot - that covers them takes the deltas held afterwards. - A snapshot at S already holds delta S, so catch-up drops that frame as stale - (`useAgentSession-sync.ts`); a merged frame with `web.first <= S < sequence` - is held for the next snapshot instead of applied. Streamed tool arguments are - re-parsed for display only after 2 KB more JSON or 100 ms. - -### Event protocol differences vs pi -omp emits no `prompt_done` / `prompt_error` / `compaction_start` / -`compaction_end` events. Completion is `agent_end` (`isTerminal !== false`), -errors surface as failed command results (`res`) plus `notice` events. -New frame types (`turn_start/end`, `notice`, `todo_reminder`, ...) must be -handled or safely ignored. - -### Queued messages are omp-owned -The queue panel renders omp's snapshot only: `get_state.queuedMessages` on -load/reconcile/stream open and live `queue_update` frames. Never track chips -client-side — every client viewing the session must show the same queue. -The one exception is what omp does not have yet: the message outbox's held -bubbles (below), never omp's queue. -One sequence (`queueSeqRef`) orders every source: a get_state snapshot takes -a number when requested and applies only if no newer snapshot or -`queue_update` was applied (HTTP and SSE can reorder). Edit/Delete use -`remove_queued_message` (act only on `removed: true`; newer omp also returns -the message's `images`, which Edit restores), Steer uses -`promote_queued_message`; the chip changes when omp's next snapshot arrives. -`handleAbort` coalesces overlapping Stops, then sends `abort_and_restore_queue`: -omp's Esc (`clearQueue({ forInterrupt: true })`, then abort) in one step, -returning the withdrawn user messages, whose texts and images go to the -session draft via `recoverDraft`. omp labels an image-only message `[Image]`; -that label is never restored as text. It covers what a client snapshot cannot: a steer promoted -after the last `queue_update`, and live-steered input the run claimed but never -recorded (omp would otherwise requeue it and drain it into a new turn right -after the abort). Never reimplement this client-side. A failed request is -retried once (omp returns whatever is still queued) and only while the run -captured at the click is current; texts lost with a response that never -arrived cannot be recovered, so the hook warns (`queueRestoreUncertain`). -Fallback ONLY when omp answers "Unknown command" (omp without the command): -withdraw each listed message with `remove_queued_message` BEFORE sending -`abort` (bounded by `WITHDRAW_BEFORE_ABORT_MS`), saved as each removal -confirms. A follow-up that answers `removed: false` is retried on `steering` -(a concurrent promotion moved it); never the reverse. Every abort is fenced to -the prompt run id captured at the click, so it cannot kill a prompt started -during the wait. -- Submitting during a run defaults to **Queue follow-up** - (`lib/composer-prefs.ts`, `omp-web:submit-during-run`); only an explicitly - stored choice overrides it, and an absent key yields `queue`. -- omp-web's own `!!` shell command (`bashRunning`, set for the whole `bash` - command) is the one state omp refuses a prompt in. The wrapper degrades instead - of throwing (`queueWhileShellRunning` in `lib/rpc-manager.ts`): the frame is - forwarded as omp's `follow_up` — never aborted, never reimplemented here — - and the reply reports it (`{queued:true, queue:"followUp", - reason:"shellRunning"}`). For an outbox entry the dispatcher treats it as a - follow-up (its held bubble becomes the chip); a new chat's first prompt - surfaces it as a notice while rolling the phantom optimistic turn back. The - chip still comes from omp's snapshot. This applies only with no turn - streaming: during a turn, prompts and steers reach omp unchanged. -- A `!cmd` submitted during a run is never queued as text: `sendQueued` hands - it to `handleSend`, which runs it at once beside the turn, as omp's terminal - does. omp holds such a result back until a later prompt starts (with omp - 18.15 it was seen landing one prompt later than the next); the wrapper marks the reply - `deferred`: its `streaming` read by `sendCommand`'s `onReply` as the reply - is read (omp's own `isStreaming`; after the await, an `agent_end` from the - same link batch would already have cleared it). The hook shows it from - `heldBash` (after the transcript) until the transcript has a run of that - command stamped after the newest omp stamp the tab had seen when the command - was sent (`newestStampRef`, which only grows, so a history view cannot lower - it; both omp's clock, so an older run revealed by the pre-compaction view - never matches; never compare counts, they change with the view). Each - recorded run settles one held entry (`settledRunsRef`). It then retires it - for good (compaction or a branch view without it must not bring it back). Never clear it on a client - event such as sending a prompt: the result may reach the transcript one - prompt later. Other tabs see it only from then on. Stop (`handleAbort`) - stops a running turn first, as omp's Esc does; `abort_bash` only when no - turn runs. +Tool-result images never reach the browser as base64: history (`deferMedia`) and live frames (`AgentSessionWrapper.emit`, which also feeds the replay snapshot) replace each with `{type:"image", mimeType, url:"/api/media/"}`; user-message images stay inline. pi stores images inline in the session file, so they are hashed and copied to `/tau/media/`. A daily sweep deletes copies older than 30 days. `?thumb=1` serves a 480px WebP (`Bun.Image`, EXIF-oriented, cached). Only PNG/JPEG/GIF/WebP by magic bytes. + +### Streaming message updates +pi's wire `message_update` is delta-only (pi `docs/json.md`): `usage` and `assistantMessageEvent`, never the message, an id or a `partial`. +- The daemon (`piStreamFrame`, `daemon-channels.ts`) gives each assistant message a `messageId` at `message_start` (and on `message_end`), and each update that id, `message: { role }` and, on `text_start`/`thinking_start`/`toolcall_start`, the empty block they open. Everything after it reads that shape. +- `lib/message-delta.ts` is the one reducer, shared by server and browser: `*_start` carries the opened block, `*_delta` appends at `contentIndex`, `*_end` carries the final block. `toolcall_delta` text accumulates in `partialJson`; arguments are parsed only for display and snapshots (`withStreamedArguments`). It returns null for anything it cannot place; nobody renders a guess. `message_end` is authoritative. +- The wrapper keeps each open assistant message by `messageId`. `getStreamSnapshot()` (HTTP catch-up) carries it with `streamingMessageId`; `onEvent` replays it as one whole `message_update` to a tab that attaches mid-message. With no base (frames lost on the link; `reconcileAfterGap` drops every base) a delta is not forwarded and the wrapper asks the link for a resync, once per message or run. +- Backpressure (`event-stream-hub.ts`): a behind sink queues `message_update`s; consecutive deltas of one block concatenate, a whole message replaces its queued updates, nothing is dropped or reordered. Merged frames keep the latest sequence and carry `web.first`. Deltas of different blocks never merge past each other. +- Browser (`message-update-coalescer.ts`): applies each delta on arrival and dispatches whole messages at display rate. A delta with no base is held (≤ 1000) and triggers a catch-up; the HTTP snapshot (`seed`) re-bases the coalescer. A snapshot at S already holds delta S (`useAgentSession-sync.ts`); a merged frame with `web.first <= S < sequence` waits for the next snapshot. Streamed tool arguments re-parse only after 2 KB more JSON or 100 ms. + +### Queue (pi-owned) +- The queue panel renders pi's queue only: `get_state.queuedMessages` (filled from the last `queue_update`) on load/reconcile/stream open and live `queue_update` frames, with client ids and origins from the extension's `tau_queue` names when they line up. Never track chips client-side; the outbox's held bubbles are the only exception. One sequence (`queueSeqRef`) orders every source. +- pi takes its queue back only whole: `clear_queue` answers `{ steering: string[], followUp: string[] }` (texts, never images). Chip edits and deletes use it (`clearQueuedMessages`, one at a time per session) and the chips leave with pi's next snapshot; the wrapper then tells the extension (`/tau_meta clear`), which journals the withdrawn ids as resolved. +- Stop (`handleAbort`) coalesces overlapping clicks and sends `abort_and_restore_queue`, which the wrapper runs as the TUI's Esc: `clear_queue`, then `abort` (pi would otherwise run a queued message as soon as the abort lands). The withdrawn texts return as `{ steering, followUp }` of `{ text }` and go to the draft (`recoverDraft`), even when the abort fails. A failed request is retried once while the captured run is current; otherwise the hook warns (`queueRestoreUncertain`). +- Submitting during a run defaults to **Queue follow-up** (`tau:submit-during-run`). +- pi takes a prompt while tau's `!!` shell command (`bashRunning`) runs, and a `follow_up` queued with no turn running waits for the next run: the outbox decides prompt versus follow-up with `isRunning(true)`, which leaves the shell command out. +- A `!cmd` during a run runs at once beside the turn. pi holds its result back until a later prompt; the wrapper marks the reply `deferred` (read in `sendCommand`'s `onReply`). The hook shows it from `heldBash` until the transcript has a run of that command stamped after the newest stamp the tab had seen (`newestStampRef`; never compare counts); each recorded run settles one entry (`settledRunsRef`), for good. Stop stops a running turn first; `abort_bash` only when no turn runs. ### Message outbox (`lib/message-outbox.ts`, `lib/event-stream-worker.ts`, `docs/specs/2026-11-04-message-outbox-design.md`) -- **Every message to an existing session is held until acceptance is confirmed**: - an idle prompt, follow-up or steer (slash commands too; `!cmd` and `/btw` - retain their own paths). Send ends once browser storage commits. Retain - unconfirmed outcomes visibly across reconnects, restarts and host outages; - uncertain host delivery is not independently retried. Native process crashes - preclude an unconditional exactly-once guarantee. New chats keep their first - `ensureNewSession` + prompt path (phase 1). -- **Browser leg.** `addToOutbox` (`lib/event-stream.ts`) hands the entry to the - event-stream worker, which commits it to IndexedDB (`omp-web-outbox`/`entries`) - and only then answers, so the composer clears only then. Missing IndexedDB - or a failed transaction rejects the add and preserves the draft. The worker sends `outbox_add` over its current transport - (a link `cmd`, or POST `/api/agent/[id]` in SSE mode), one entry per session at - a time, oldest first; 401/408/429/5xx/network retry with backoff (1 s → 30 s, - at once on a wake), other 4xx mark it failed. Delete its browser copy only - after a matching successful outbox receipt, not an arbitrary HTTP 200, and - wait for the IndexedDB transaction to complete. Allocate logical enqueue - order and insert a unique ID atomically; clock ties and worker restarts must - not reorder entries or overwrite a held intent. An entry still unsent seven - days after `createdAt` fails instead (server IDs live eight days); an - unscoped one fails too. Every sender, Background Sync included, persists - that failure before moving on, so a stale head never blocks the session's - later entries. Pagehide - sends each session's head only (64 KiB total, no incomplete ordering view). - Background Sync registers `omp-outbox` only after the active service worker - proves outbox capability; an old push-only worker is not sufficient. - A transient initial IndexedDB read failure must not latch the SharedWorker - unusable: later list/add/delete operations retry the existing shared load, - with one retry attempt shared by concurrent tabs. Persistent failures still - preserve drafts and stored rows rather than claiming successful storage. -- **Idempotent by id.** `outbox_add`/`outbox_remove` are agent - commands in `runAgentCommand`, before any wrapper spawn; a repeat of a known - id answers the stored entry. These and `outbox_scope` are in - `isIdempotentCommand`, so the link's `(session, rid)` dedupe never remembers - them and a resync resends them. -- **Scope follows the installation, not the cookie.** The state route's - `outboxScope` (or `outbox_scope` command) is a nonsecret installation/auth - fingerprint, cached for offline enqueue. Every browser entry persists it - unchanged; worker, keepalive and SW sends never rebind an old row. - Replacement installation/credentials refuse it permanently with - `outbox_scope_changed`; normal same-owner re-login keeps it. With no cached - scope, a first-ever offline send must retain its draft until the server can - identify itself. -- **Server leg.** SQLite and a per-conversation FIFO dispatcher (aliases share - the same claim) send through the wrapper. Acceptance is bounded by the - per-alias 16 MiB limit and the global 256 MiB/1,000-active-row pool; overflow - is retryable 429 while the browser keeps its copy. Never trim accepted rows. - Storage startup failure remains retryable without a new send or hello; - successful initialization installs hooks once and shutdown cancels retries. - Startup recovery fails a same-PID `delivering` row (a reused PID from the - last run) unless this process holds that claim in memory: an add accepted - before a delayed startup retry may already be in flight. - A steer waits (`held`) while an ask (`askDialog`/`formDialog`) is open, since - omp's ask tool aborts on a user steer; the wrapper's `onAskClosed` (answered, - cancelled, expired or child gone) pumps it. The composer is hidden meanwhile, - and a `send_to_session` steer goes as a follow-up (its result says so). - Host offline → `waiting_host`; uncertain replies/child exits while delivering - → `failed` with `mayHaveBeenSent`, never independently resent. Anything that - stops an entry before its native write (an error before the claim, omp exiting - during preparation, attachment copies or a send fence inside `runAgentCommand`) - leaves it unsent, never marked possibly sent: a gone child is retried after - `RETRY_MS`, and any other refusal (an attach op's `host_offline` included) is - classified as not sent (`waiting_host` for an outage). The boundary is - `nativeWriteStarted(command)`, set by whichever wrapper's - `sendNativeMessageCommand` begins writing that submitted command object, never - inferred from one wrapper's generation (a respawned child may write it); test - fakes record their write in the same `__ompNativeWrites` registry. An - `outbox_add` for an archived session is accepted and held until it is restored - (the restore route pumps it); only a session neither listed nor archived is a - 404. Internal `/rename` and `/mcp` prompts stay counted as message - commands, so an outbox watch never claims an echo they cause. Host tool and URI - scheme registrations apply in `sendCommand`'s `onReply` (success only), so a - call omp sends in the same batch as the reply is routed. The session carries - `outbox_update {entries,settledIds}` (every non-delivered entry plus the latest - 256 delivered/removed ids, retained 8 days) on subscribe and on every - change, and opens without a wrapper while held entries exist. Observe the - session-registry lifecycle too: an explicit command can create the ready - wrapper without another outbox mutation; attach/rebind then announce `connected`. - Internal handoff observers protect lifetime but do not count as browser tabs - for host-tool/URI routing or disconnect cleanup. Only the submitted command's - own reply proves rejection; an older run's session-wide error cannot reject it. - `GET /api/sessions/[id]/state` carries `outbox`, `outboxSettledIds` and - `outboxScope` on every answer, an offline host's error included, so a reload - subscribes to follow them. Upload completion receipts persist privately - before the completion ACK, so upload ids survive a restart even before - outbox_add reaches the server. - Completion replies also carry upload-specific `proof`; browser-held entries - retain it as `uploadProofs` across re-login. The dispatcher receives accepted - original-owner receipts out of band, never from client JSON. Private proof - columns and other schema migrations share one immediate discovery/ALTER - transaction so concurrent instances cannot race the upgrade. - Upload authority is revalidated inside the same immediate transaction as - outbox insertion, after asynchronous lookups. Private completion fingerprints - bind later preparation to the original file generation. A UUID still referenced - by a retained outbox entry cannot be repurposed after its canonical upload - registration is canceled or consumed; cancellation must never substitute bytes. - Canonical completion records refresh stale main-side caches. Every attachment - replay still asks the daemon to validate its real file; a missing completed - file never resumes as replacement bytes under the old proof. Delayed native - replies retire only their captured completion generation. - First proof issuance atomically binds matching retained legacy receipts too. - Original-owner preparation captures that private generation before awaiting - another command, so a completion replay cannot invalidate unchanged legacy files. - Consecutive unsent outbox snapshots replace each other in the session - backpressure queue. Resume and heartbeat do not serialize them while the sink - is still behind; native events remain ordering fences, with genuine overflow - handled by the existing resync limits. Never rewrite numbered or partial lines. -- **Held bubbles** (`HeldMessageView`, after the live turn, delivery order: - server-held entries in arrival order, then this browser's first-leg entries - in submission order; browser and server `createdAt` are never compared): - the hook merges the worker's entries (`subscribeOutbox`) with the server's - snapshot by id; a server confirmation (`{stored}`) bridges until the server - lists or settles its id (an older empty snapshot cannot hide it); seen and - settled ids prevent late ACKs from resurrecting delivered entries. States: - Sending (browser, locked while its first-leg command may be in flight), - Waiting to send / Waiting for (Delete), Delivering (locked), - Not sent (Retry, Delete). Retry (`retryHeldMessage`) holds a new entry with the same text, images, uploads and - mode and `replaces: `, persisted in IndexedDB and sent with `outbox_add`. The server retires a failed - original of the same session in the transaction that stores the copy, and the worker (or `sw.js`) deletes the - browser's row of it in the commit that deletes the stored copy; a refused copy leaves it. The `outboxStored` it - posts carries `replaces`, and the hook marks that original represented at once. Retry holds no copy while one - naming the id waits in IndexedDB (true after a remount, a reload or a closed page) or once one was stored, and - never sends `outbox_remove`. A `mayHaveBeenSent` entry asks first. The delivery mode is a read-only label. Delete - (`deleteHeldMessage`) awaits the IndexedDB delete commit for a browser-held - entry; a server entry sends `outbox_remove`, refused with 409 - `outbox_dispatched` once delivering. A late commit consumes only the original - draft's unchanged content and edit generation, including after remount. - Equal text after newer typing is not unchanged; hydration is not a user edit. - Active submission ownership lives in the shared draft store, not a composer - mount. Confirmed identity moves transfer it synchronously before React commits; - live draft hydration and source-snapshot merging still belong to layout. - Mark accepted attachment reads as edits before asynchronous completion, not - only when their chips appear. During pre-commit identity handoff, do not - recreate the obsolete draft key or consume capacity belonging to other drafts. -- **Run state comes from omp's frames**, never from Send: `agent_start` starts - the run. The server captures `previousEntryIds` before dispatch and publishes - it only on the active delivering entry, before omp frames; recovery must use - this authoritative boundary, not cached/late-fetched history that could - mistake the previous saved answer for a new response. The boundary is - cleared after handoff/failure, never kept in tombstones. - Active replacement inference also requires unambiguous message admission: - an intervening message command from another origin cannot supply this - attempt's identical echo. Retain uncertainty instead of guessing ownership. - The taint lifts on the same child, never by a restart: only a `get_state` - issued after every message command was answered, reporting native settlement - with no active/queued/background work, plus no dialog, history mutation or - unrelated pending command and stable admission generation, peer admissions and - identity across that read (`clearMessageProofTaintIfSettled`, one read at a time, - joined by a dispatch arriving during it; at an idle dispatch and on `session_settled`). - Never infer old acceptance from time or settlement events, and never replay - old uncertain entries. - A prompt's bubble leaves when the server sees omp's reply and echo; - the hook shows omp's echoed user message (`echoedUserMessage`) until the - transcript catch-up has its saved copy (same timestamp and text), so there is - no gap. A follow-up or steer becomes omp's queue chip. Stream connections - opened for held messages (`connectEvents(sid, "connected")`) talk to omp only - after `connected`, since any command would start a wrapper. - -### GitHub agent tools (lib/github/, docs/specs/2026-11-13-github-watch-tool-design.md) -- **Server login only.** Every GitHub call uses the web server's `gh` login. The runner pins API requests to `github.com`, removes `GH_TOKEN` and `GITHUB_TOKEN` from its child environment, and uses `createChildProcessEnvironment` to exclude omp-web's secrets. omp-web never reads, stores or forwards a GitHub token. Missing or logged-out `gh` returns a tool error naming the required installation or login step. -- **Updates are metadata only.** A watch update is a `prompt`-mode outbox entry that names `OWNER/REPO#N` and the URL, and carries metadata: logins and author association, ids, URLs, review states, comment counts, thread line numbers, and CI counts by conclusion. Check names and thread file paths are left out: whoever writes the branch, a fork included, names them. `capName` (one line, no `\p{C}`, 100 characters) is only for the path in a resolve confirm, which the user reads. Pending (draft) reviews and their inline comments are left out of snapshots, so the submitted review arrives as new. Only `github_read` (`readItem`) returns GitHub-written prose, such as bodies and titles. -- **Crash idempotency.** `claimPending` atomically checks the watch's UUID registration, base cursor, pending state and posting fences before persisting deterministic bounded batches. Batch ids include the registration identity. Progress and final cursor commits are fenced by registration, pending identity and expected batch index; a restart replays the same batch id, which the outbox collapses. Final updates remove the watch only after every batch completes. Retryable delivery failures and unexpected 413s retain pending work; a 404 ends the session's watches, while other permanent refusals are logged and consumed according to `deliveryOf`. -- **Own posts.** `recordPosted` stores exact comment and associated review identities, including `review:` aliases for REST replies. Snapshots suppress only those identities, preserving other comments and reviews from the same account. A shared expiring posting lease spans the write and identity recording; pending claims also check the lease and recorded identities. An uncertain write is neither retried nor inferred successful from matching login/body. A crash after GitHub accepts a post but before its identity is recorded can still produce one metadata-only update. -- **Confirmations.** Reads from a local session never ask. A remote session's read, watch, unwatch and comment (on its `target`), and resolve (on the thread's item), ask once per session and repository (`hasReadGrant`/`grantRead`) unless that host's `allowAgentStart` is on. Writes (`github_comment`, `github_resolve_thread`) ask every time, from any host, unless `githubWritesUnasked` is on. omp's `host_tool_cancel` aborts the server call's `AgentToolContext.signal` (`serverToolCalls` in rpc-manager); a write checks it after its confirm, right before posting. The host rule (`startsUnasked`) lives in the leaf `lib/agent-tool-hosts.ts`; rpc-manager builds the GitHub ops with `createGithubToolOps(listHosts)`. A `PRRT_` reply and `github_resolve_thread` first look the thread up (`fetchThread`): a reply whose thread is on another item than `target` is refused, and a resolve's confirm names `OWNER/REPO#N path:line` and, from a remote session, needs that repository's read grant. -- **Replay after a restart.** `rpc-manager.ts` has two replay guards. The host-owned callback guard (`hostOwnedLifecycle` with `deliveredCallbacks`) runs again only `list_sessions` and `GITHUB_REPLAY_SAFE_TOOLS` (`watch_github`, `unwatch_github`, `github_read`). The agent-tool branch of `host_tool_call` (ahead of `answerServerAgentTool`) also runs `new_session` again while Agent tools is enabled. `github_comment` and `github_resolve_thread` never run again on either: they answer the unknown-outcome error (`unknownOutcome`), which for GitHub tools says to check with `github_read` (comments or threads) before retrying, because the post may already have happened. -- **Limits.** At most 20 watches per session (`MAX_WATCHES_PER_SESSION`). A poll cycle is 60 s, or 1.5 s per distinct watched item past 40 items (`ITEM_SPACING_MS`), with all watched items (across all sessions, one entry per item) spread across it. A snapshot costs about 1 GraphQL point, so the poller spends at most about 2400 of the login's 5000 points an hour, shared with the user's own `gh`. Each snapshot reads `rateLimit { remaining resetAt }`; below 200 points left (`BUDGET_FLOOR`) polling waits for the reset and logs once. -- **CI is reported once per head.** A head's result is sent once, when its checks visible at that poll have all completed. Workflows that start later on the same head (chained `workflow_run`) and re-runs of that head are not reported. -- **Agent tools off pauses watches.** The poller checks `agentToolsEnabled` each cycle. With **Agent tools** off, polling stops and watches are kept; turning it back on resumes from the stored cursors, so what happened meanwhile is delivered then. - -### Live event stream: one socket per browser (`/api/events`) -- Browsers cap HTTP/1.1 at **6 connections per host across all tabs**, and an - SSE response pins one for its lifetime. Per-stream SSE (sidebar + host - tools + chat + file watch per tab) froze everything after ~2 tabs, so - **never add a new `EventSource`** for live data: add a channel instead. -- `lib/event-stream-worker.ts` (SharedWorker; dedicated Worker where - SharedWorker is missing) holds the browser's one connection: by default the browser link below, one WebSocket; - the only `/api/events` EventSource is the fallback (a stored `sse` setting, or a proxy that refuses the upgrade). It multiplexes every tab's subscriptions: - frames arrive as `event: `, control frames as `event: mux` - (`hello`/`open`/`end`). Subscriptions are attached with `POST /api/events`. - `buildEventStreamWorker` (`server/client-env.ts`) bundles it into one classic - script (`dist/event-stream-worker.js`; the dev server serves it from memory), - and its URL carries the bundle's content hash 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 - retries with backoff). Dead tabs are detected with a lifetime Web Lock — - MessagePort has no close event. -- Channels (`lib/event-stream-hub.ts`): `running` (sidebar badges + - session-list hints), `notifications` (one tab's toasts and in-page system - notifications, keyed by its `clientId`), `hosts` (the `GET /api/hosts` body on - subscribe and on every link or registry change), `host-tools` (cross-session - `open_url`/`notify`/`open_file` calls), `session` (observer-only, never - spawns omp; queues and merges `message_update` frames under backpressure, - see "Streaming message updates"), `file` (viewer watch, same allow-list as `/api/files`). A - failing frame ends only its own subscription, never the shared socket. -- Split channels by consumer, lifetime, key and access check, not by which - stream happens to be open: a subscription costs one `POST`, not a socket, so - never piggyback a frame type on another consumer's channel. `notifications` - and `host-tools` are subscribed from `AppShell`, so they outlive the sidebar - (which unmounts while Settings is open). -- **Browser link** (`browserTransport: "ws"`; `docs/specs/2026-11-01-browser-link-design.md`). The server's - setting (`omp-web-settings.json`, `lib/web-settings.ts`; `"ws"` default, any other stored value except `"sse"`, the - old `ws-*` experiment modes included, reads as `"ws"`) picks the worker's connection. With `sse` everything - above holds and the worker opens no WebSocket. Switch it in Settings → Interface & Behavior → "Browser - connection" or with `PUT /api/web-settings {"browserTransport":"ws"|"sse"}`; a change - broadcasts a `transport` control frame on every connection and every `hello` carries it. From a shell - (production on 127.0.0.1:30185, the trusted header from the pr-watcher env file; no `Origin`, so no - origin check): - ```bash - curl -sS -X PUT http://127.0.0.1:30185/api/web-settings \ - -H "x-omp-web-auth: $(sed -n 's/^OMP_WEB_TRUSTED_HEADER_SECRET=//p' /opt/omp-deployment/pr-watcher.env)" \ - -H 'content-type: application/json' -d '{"browserTransport":"ws"}' - ``` - - **One WebSocket per browser** at `GET /api/events/link` (`lib/browser-link.ts`), gated like every API - route, carries every subscription and every agent command and reply. Reconcile polls, `POST - /api/agent/new`, files, settings and the metrics POST stay HTTP. - - **The host link's delivery, reused** from `lib/hosts/link-protocol.ts`: sequenced lines both ways - (`LinkSender`, `SeqWindow`, `Outbox`), acked and resent after a reconnect; lines over 256 KiB as `part`s - (`PartJoiner`); per-key queues served round-robin (a subscription's frames, a session's commands or - replies, `mux`); a session's commands stay in order, so Stop never overtakes the prompt it stops. The - server keeps at most about 1 s of the measured ack rate unacked below the socket (64 KiB to 512 KiB, - `measure` in `lib/browser-link.ts`; only a stretch where the window or the socket's backpressure held lines back resizes it), the - worker at most 512 KiB. `welcome`/`ack`/`ping`/`pong` skip the queues. So a command's reply waits behind - about a second of the link plus a piece per busy key, never behind a snapshot. The pacing loops - are the browser link's own copies: the server's mirrors the hub's (`send` → `-1` → `drain`), the - worker's the daemon's (`bufferedAmount` under 2 pieces); a fix to either original must be carried over - (`lib/browser-link.integration.test.mjs` runs the real worker against the real server end). A socket - that has not said hello within 10 s is closed 1008. - - **Liveness:** the server pings every 15 s; each side drops a socket after 30 s without any frame. - Command delivery additionally watches sequence-ack progress, including multipart uploads: initially - 5–6 s without progress redials with trigger `command`, even while updates arrive. Each such redial - doubles the deadline up to 30 s; an advancing ack on the current socket covering all watched - command pieces resets it to 5 s (a resume welcome does not). Acknowledged commands waiting for - their results never cause this redial. Replay and resync retain the rules below. - Wakes: `online` and a network change redial at once and reset dial backoff to 1 s; `visible` - pings and redials a socket silent for 3 s. - - **Resume.** The link outlives its socket for 2 min (`LINK_RESUME_MS`): the worker's `hello` carries - its token and `ack`, the server (same web session only: SHA-256 of the session cookie, else - `trusted`/`open`) reattaches and both sides resend what the other missed. Subscriptions stay open on - the server, so the tabs see nothing: no `error`, no second `open`, no snapshot. While the socket is - gone or lines wait for the window, `message_update`s merge (`queueUpdate`) and go on the next ack. A socket that holds unacked bytes and gets no ack for 120 s (`ackMs`; pings do not count) is closed: its link detaches, resumable, and falls under the total budget. A link slower than about 17 kbit/s cannot finish a 256 KiB piece before that deadline. - - **Resync** when the gap is gone (2 min passed, the backlog passed 32 MiB and the socket closed 4410, - all links together passed 256 MiB and this one's socket was gone longest, or the server restarted): - `welcome {resumed: false}`, both sides start over, every stream gets CONNECTING and subscribes again - (fresh snapshots, as an SSE reconnect). Sent commands go again (same `rid`) when idempotent - (`isIdempotentCommand`: `get_*`, `predict_word`, `predict_word_feedback`, `set_host_tools`, - `set_host_uri_schemes`; never `abort`; the server does not remember those) or when the - server is the same and their first send was within `COMMAND_DEDUPE_MS` (10 min; the server's - `(session, rid)` dedupe answers a repeat with `deduped: true`), else 503 `transport_lost` - (`TransportLostError`). A command with no link for 15 s answers 503 `transport_unavailable`. A worker - done with its link closes it 1000 (the server drops it at once); 4000 is its own redial. - The server answers a command whose JSON is over the route's 8 MiB body cap (UTF-8 bytes; the worker - checks first, the server again for a joined line, whose cap leaves room for the envelope) 413 - `request_too_large`, and a command that changes something 429 `too_many_commands` while `DEDUPE_MAX` - (500) remembered ones are all still inside `COMMAND_DEDUPE_MS`: neither runs, neither is remembered. - - **Fallback.** A socket that closes before it opens gets a plain `GET /api/events/link`: offline, 401, - 502, 503 or 504 redial. Any other answer (426: a proxy that drops Upgrade, but also a healthy server's - answer to a dial that failed as the network came back) is a refusal: 3 in a row, with no open between - and none while `navigator.onLine` is false, put this worker on SSE for 5 min. Close 4426 (another link - version) falls back at once. - - **One command path.** `runAgentCommand` (`lib/agent-command.ts`) is what `POST /api/agent/[id]` runs - after parsing and what a link `cmd` runs, so both answer identically. Command logic goes there. - - **Metrics** (both transports). Tabs and the worker record `action`, `event`, `reconnect` (with - `resumed` on the link), `hang` (HTTP only) and `dropped` samples tagged `transport` (`sse`/`ws`), - `socket`/`conn` (`sse`, `link`, `http`, `worker`) and `sockets`; the worker POSTs them to - `/api/transport-metrics` every 30 s or 200 samples (a probe not answered within 10 s is abandoned, a POST within 10 s plus its body at 2 KB/s; a failed POST keeps its samples, so a timeout after the server processed it can duplicate them). The route appends JSONL to `/omp-web/transport-metrics.jsonl` (`.jsonl.1` above 20 MiB). One worker-wide clock (the - lowest-RTT of the last 20 link pings and SSE probes, at most 5 min old unless it is the newest sample) times every sample. - `bun scripts/transport-metrics.ts --since 2h` prints the per-transport summary (also `--until`, - `--client`, `--file`). - - **Connection tab** (right panel, both layouts, shown while Settings → Interface & Behavior → "Show connection - diagnostics" is on, `omp-web:connection-diagnostics`, per browser). It polls the worker (`diag` op, - `requestConnectionDiagnostics`) once a second while visible: the mode in effect, fallback, status (`idle` when - no connection is needed, `down` after `SEND_DEADLINE_MS` without a connection), the last reconnect, and - per-transport stats (mean, p50, p95, p99.9 from 1000 values, max) of the worker's last 30 min of samples (at most - 20 000, kept beside the POST buffer). Command rows include confirmed successful replies only; app ↔ omp and round-trip rows skip commands whose reply does not confirm omp got them (`NO_OMP_REPLY_COMMANDS`: the `NO_SPAWN_REPLIES` the web app answers itself, a test keeps them included, plus the results `dispatchCommand` forwards without awaiting omp). A new command of either kind belongs there. Shared durations - come from `lib/transport-stats.ts`; one-way estimates use clock correction and assume symmetric latency. - Without a SharedWorker (Chrome for Android) each tab has its own worker, so the numbers are that tab's. - - **Worker rules.** Browser code: no `AbortSignal.timeout`/`any` or `Promise.withResolvers` (a test checks - the bundle). Every global the worker uses must be injectable into the `vm` context of - `lib/event-stream-worker.test.mjs`. The link URL is absolute (`new URL(path, self.location.href)`, - `http`→`ws`). Ids are `Math.random().toString(36).slice(2, 12) + Date.now().toString(36)`: insecure LAN - origins have no `crypto.randomUUID`. - - **Limits:** a socket stays authorized after logout until it closes; Bun buffers a browser frame up to the host - link's 64 MiB `maxPayloadLength` (per server) before the handler refuses it; a notification routed to a tab whose - link then resyncs is not shown there. - -### Running state + reconciliation -- The sidebar subscribes to the `running` channel, backed by `subscribeRunningSessions()` in `lib/rpc-manager.ts`, so running badges update without polling. -- An open chat subscribes to `running` too: when its session shows up there while the chat has no `session` stream (the run started after the chat loaded: another tab or device, or a send from a chat instance the user switched away from), it reads `GET /api/agent/[id]` and attaches exactly as on load (`attachLiveRun`). Without it the chat stayed idle beside a running badge until a reload. - - The lookup waits for the chat's own work: its mount load while in flight (a stream attached before that load lands would make its `agent_start` drop the load), a stream of its own still connecting (its readiness wait can still fail and close it), and a local send, `!` command, Edit or manual compaction until it settles. The frame is kept meanwhile, and the operation's release rechecks it (`runningRecheckRef`). A local operation that starts during the lookup makes its answer stale (one generation per operation kind). A failed lookup is retried after 1, 2 and 4 s. - - Compaction state has one owner at a time. A manual compaction this tab sends holds it until its command settles (`localCompactionsRef`): omp may not have the command yet, so an idle snapshot cannot release it; when it settles during an auto-compaction (`autoCompactingRef`), the control stays with the auto-compaction. Native snapshots (state polls, catch-up, attach, mount) apply only if no compaction started or ended since they were requested (`compactionGenRef`); `setCompacting` keeps `isCompactingRef` and the rendered state together. -- `useAgentSession` still treats its `session` channel as primary for chat events, but while a run is active it periodically calls `GET /api/agent/[id]` and also reconciles on `visibilitychange`/`online`. This fixes missed `agent_end` events from background tabs or half-open connections. -- Prompt runs use a monotonic run id; late SSE or slow reconciliation responses from an old run must be ignored so they cannot resurrect stale streaming bubbles. - -### Composer-attached panels (`components/ComposerPanels.tsx`) -- The live todo plan (`TodoList`) and the subagent roster live **pinned above - the chat input**, not inside the scrollable message list. `ComposerPanels` - renders both, each independently collapsible via its header row (`chevron`); - panels start collapsed (headers always show live progress / running-summary). - Non-running chips (terminal or history) nest under a `Completed (N)` toggle - inside the roster, collapsed on every mount (not persisted). - Subagent chips carry live state (pulsing dot while `started`, check/alert/ban - for terminal states) fed by the same `subagent_lifecycle`/`subagent_progress` - SSE frames; clicking a chip opens the transcript dialog. `TodoList` keeps a - non-collapsible default (`collapsible` prop) for SSR tests. - -### Side questions (`/btw`, `lib/btw.ts`, `hooks/useBtw.ts`, `components/BtwPanel.tsx`) -- `btw` / `btw_cancel` / `get_btw_history` are passthrough channel commands; - answers stream as `btw_delta` (text appended to the latest turn) and - `btw_record` (full snapshot per lifecycle change) frames. omp persists the - history per session (and re-reads it from disk when idle), so the TUI and - omp-web share topics. omp answers `btw` before that turn's frames; the - running `btw_record` comes first. -- `/btw ` and `/btw` are client builtins (`handleBuiltinSlashCommand` - case `"btw"`). `ChatInput.sendSideQuestion` routes them there from both the - idle and the streaming submit path, *before* attachments are folded in: - never sent as a prompt, never queued, and refused with a toast (draft and - attachments kept) while attachments are attached. Asking starts the wrapper - (`get_state`) and attaches SSE first when it is not open, so no early delta - is lost; a second ask while one is starting is ignored. -- The `btw` response, history snapshots and frames race (HTTP vs SSE): merge - only through `lib/btw.ts`, which never lets a stale snapshot drop streamed - text, a turn, or a finished status. A record that was running before a - history read and is missing from it becomes `interrupted` (omp lost it). -- `btw_*` frames skip the message-update coalescer (each would flush the main - stream's pending update) and are batched in `useBtw` with the coalescer's - `scheduleAtDisplayRate` (rAF, 50ms timer in hidden tabs). Pending frames are - flushed before a history snapshot is merged, never after it. -- `btw_*` frames are routed to `useBtw` BEFORE `catchUp.observe(event)`, never - after: `observe()` classifies a frame on its `streamId`, and its `"epoch"` - branch resets the whole transcript (`dispatch({type:"reset"})` + - `clearLiveToolResults()`). A side question must never be able to wipe the - live view of the run happening beside it. -- `get_btw_history` and `btw_cancel` never spawn or replace omp: the agent - route answers them like `predict_word` (`NO_SPAWN_REPLIES`: empty history, - `cancelled:false`) when no child is alive. History is re-read on every SSE - open, from the visibility/online reconcile while a record runs, and after a - cancel that found nothing running. `/btw` alone sends `get_state` first, so - it may start omp. An omp without the commands answers `Unknown command: - btw` → localized "requires a newer omp" toast (`toastBtwError`); background - reads stay silent and pause for `UNSUPPORTED_RETRY_MS`. omp's "cancelled - before it started" failure is the user's own Cancel: no toast. -- The panel sits first in `ComposerPanels` (also rendered in the empty - new-chat layout) and is keyed by record id: each new topic starts expanded, - unlike todo/subagents. A running record this tab did not know yet opens it - (another tab, reconnect); a known topic never reopens a closed panel. - -### Subagent integration (`lib/subagent-types.ts`, `lib/subagent-history.ts`) -- **Live detail**: `subagent_progress` frames carry the full `AgentProgress` - object — `lib/subagent-types.ts` parses it defensively into - `SubagentInfo.progress` (current tool/intent, tokens, cost, context - gauge, resolved model, retry state, detached flag, agentSource). The - composer chips surface the current activity + telemetry line; retry - (`⟳ retrying N/M`) takes precedence over the tool line. `subagent_event` - frames also feed a bounded per-subagent activity buffer shown in the - transcript dialog. -- **Roster hydration**: `get_subagents` snapshots (which carry progress) - rehydrate the roster after SSE reconnect (`refreshSubagentRoster`, wired - into mount, send, and the reconcile poll). Terminal subagents vanish from - the live registry — history fills that gap. -- **On-disk history** (`lib/subagent-history.ts`, `/api/sessions/[id]/subagents*`): - omp persists each subagent's transcript to the parent session's sibling - artifacts dir (`/.jsonl`) and the parent file's - task toolResults keep `progress[]`/`results[]` snapshots. omp-web recovers - the roster from disk (`extractSubagentHistory`, result fields win over the - mid-run snapshot), so past/finished runs show in the composer panel after a - reload. The host-backed transcript route pages the sibling file byte-wise - without waiting for a live process. The dialog reads final output from - `.md` via `?mode=completion` (a bounded tail read that also works for - transcripts beyond the 16MB paging cap), uses a live `get_subagents` - snapshot only for header enrichment, and pages the raw transcript through - that route when the user opens it. Subagent ids are - `[A-Za-z0-9_-]+` segments joined by `.`, because omp names a nested spawn - `Parent.Child` (`SUBAGENT_ID_RE` in `lib/subagent-types.ts`, which also - keeps `/`, `\` and `..` out of the joined path). The transcript route caps - them at 100 characters and validates before joining to confine reads to the - sibling dir. -- **`agent://` links** (`lib/agent-links.ts`): `MarkdownBody` linkifies bare - handles and inline code that is exactly a handle (remark plugin), keeps the - `agent:` protocol through rehype-sanitize and `urlTransform`, and opens - the handle through `AgentLinkContext`, which `ChatWindow` provides with - `agentLinkTarget` (dotted nested id first, then the base id; unknown ids - open a disk-backed stub). Without a provider the handle renders as plain - text. The plugin runs after `remarkGithubRefs` (so `agent://Foo#12` is not an - issue link) and never links omp's write-only `agent://all`. Because the - shared sanitizer admits `agent:`, every `ReactMarkdown` host must drop - rejected hrefs (`defaultUrlTransform(url) || undefined`) — a blank `href=""` - links to omp-web itself; `FileViewer` does this. - Tool rows (`ToolCallBlock` in `MessageView`) open an `agent://` `path` - through the same context. -- **In-message task summary** (`components/MessageView.tsx` TaskResultPanel): - the session reader allowlists a SIZE-BOUNDED subset of `task` toolResult - details (telemetry only — no `output`/`stderr`, long text truncated to - 240 chars, `lib/session-reader.ts` `keepTaskToolResultDetails`), and - expanded `task` tool calls render a per-subagent summary (status, agent, - task, tokens/cost/duration/model, async marker) above the raw result text. -- **Chip extras**: agent-source labels (`user`/`project`), nested-subagent - count (`inflightTaskDetails`/`extractedToolData.task` progress), and the - `⤴` async marker (live `detached` flag or history `details.async` - presence). Shared formatters live in `lib/subagent-format.ts`. +- **Every message to an existing session is held until acceptance is confirmed**: prompt, follow-up or steer (slash commands too; `!cmd` and `/btw` keep their own paths). Send ends once browser storage commits. Unconfirmed outcomes stay visible across reconnects, restarts and outages; uncertain host delivery is never resent. New chats keep the `ensureNewSession` + prompt path. +- **Browser leg.** `addToOutbox` hands the entry to the worker, which commits it to IndexedDB (`tau-outbox`) and only then answers, so the composer clears only then; a missing IndexedDB or failed transaction keeps the draft. The worker POSTs `outbox_add` to `/api/agent/[id]`, one entry per session at a time, oldest first; 401/408/429/5xx/network retry with backoff (1 s → 30 s, at once on a wake), other 4xx fail it. The browser copy is deleted only after a matching successful outbox receipt, once the IndexedDB transaction completes. Enqueue order and unique ids are allocated atomically. An entry unsent seven days after `createdAt` fails (server ids live eight days), as does an unscoped one; every sender persists that failure before moving on. Pagehide sends each session's head only (64 KiB total). Background Sync registers only after the active service worker proves outbox capability (`tau-outbox-capability`). A transient initial IndexedDB read failure must not latch the worker unusable. +- **Idempotent by id.** `outbox_add`/`outbox_remove` run in `runAgentCommand` before any wrapper spawn; a repeat answers the stored entry. +- **Scope follows the installation, not the cookie.** `outboxScope` (state route or `outbox_scope`) is a nonsecret installation/auth fingerprint, cached for offline enqueue and persisted unchanged on each entry; a replaced installation or credentials refuse it with `outbox_scope_changed`. Without a cached scope a first offline send keeps its draft. +- **Server leg.** SQLite (`/tau/outbox.db`) and a per-conversation FIFO dispatcher (aliases share the claim). Acceptance is bounded per alias (16 MiB) and globally (256 MiB / 1,000 active rows); overflow is retryable 429 while the browser keeps its copy. Never trim accepted rows. Startup recovery fails a same-PID `delivering` row unless this process holds its claim. + - A steer is not held while an ask is open: pi queues it until the turn ends and tau's ask tool keeps waiting. + - Host offline → `waiting_host`; uncertain replies or child exits while delivering → `failed` with `mayHaveBeenSent`, never resent. Anything that stops an entry before its native write leaves it unsent (a gone child retries after `RETRY_MS`). The boundary is `nativeWriteStarted(command)`, set by whichever wrapper's `sendNativeMessageCommand` writes that command object (test fakes record theirs in `__tauNativeWrites`). + - An `outbox_add` for an archived session is held until restore (the restore route pumps it); only a session neither listed nor archived is 404. + - Host tool registrations apply in `sendCommand`'s `onReply` (success only), so a call in the same batch as the reply is routed. Only the submitted command's own reply proves rejection. + - The session carries `outbox_update {entries, settledIds}` on subscribe and every change, and opens without a wrapper while held entries exist; `GET /api/sessions/[id]/state` carries `outbox`, `outboxSettledIds` and `outboxScope` on every answer, an offline host's error included. + - **Upload proofs.** Upload completion receipts persist privately before the completion ACK and carry an upload-specific `proof`; browser-held entries keep it as `uploadProofs`. Authority is revalidated inside the same immediate transaction as the outbox insert. Proofs never reach the daemon, pi, public snapshots or logs; a completion replay never substitutes bytes. + - **Message-proof taint.** The server captures `previousEntryIds` before dispatch and publishes it only on the active delivering entry. Replacement inference requires unambiguous admission. The taint lifts only through `clearMessageProofTaintIfSettled`: a `get_state` issued after every message command was answered, reporting settlement with no active/queued/background work, no dialog, history mutation or unrelated pending command, and stable admission generation and identity. +- **Held bubbles** (`HeldMessageView`, after the live turn: server-held entries in arrival order, then this browser's first-leg entries): the hook merges the worker's entries with the server's snapshot by id; `{stored}` bridges until the server lists or settles the id; seen/settled ids stop late ACKs from resurrecting entries. States: Sending, Waiting to send / Waiting for (Delete), Delivering (locked), Not sent (Retry, Delete). Retry (`retryHeldMessage`) holds a new entry with the same content and `replaces: `; the server retires the failed original in the transaction that stores the copy, and the worker deletes the browser's row in the same commit. Retry holds no second copy while one naming the id waits; a `mayHaveBeenSent` entry asks first. Delete (`deleteHeldMessage`) awaits the IndexedDB delete; a server entry sends `outbox_remove` (409 `outbox_dispatched` once delivering). +- **Run state comes from pi's frames**, never from Send. A prompt's bubble leaves when the server sees pi's reply and echo; the hook shows pi's echoed user message (`echoedUserMessage`) until the transcript has its saved copy. A follow-up or steer becomes pi's queue chip. Streams opened for held messages (`connectEvents(sid, "connected")`) talk to pi only after `connected`. + +### GitHub agent tools (`lib/github/`, `docs/specs/2026-11-13-github-watch-tool-design.md`) +- **Server login only.** Every call uses the web server's `gh` login (`createChildProcessEnvironment`; `GH_TOKEN`/`GITHUB_TOKEN` removed, API pinned to `github.com`). tau never reads, stores or forwards a GitHub token. Missing or logged-out `gh` returns a tool error naming the step. +- **Tools.** `watch_github`, `unwatch_github`, `github_read`, `github_comment`, `github_resolve_thread`, and the Actions tools `github_workflow_list`, `github_workflow_read`, `github_run_list` (reads), `github_workflow_dispatch`, `github_run_cancel`, `github_run_rerun` (writes, each governed by `githubActionsPermissions`, `ask` by default; reserved before sending in `action-receipts.ts`, never replayed on an unknown outcome). +- **Updates are metadata only.** A watch update is a `prompt`-mode outbox entry naming `OWNER/REPO#N` and the URL, with metadata (logins, ids, URLs, review states, counts, thread line numbers, CI counts by conclusion). Check names and file paths are left out (a fork's author names them); `capName` bounds names in confirms. Pending reviews are left out. Only `github_read` returns GitHub prose. +- **Crash idempotency.** `claimPending` checks the watch's registration, cursor, pending state and posting fences before persisting deterministic batches; a restart replays the same batch id, which the outbox collapses. A 404 ends the session's watches. +- **Own posts.** `recordPosted` stores exact comment/review identities (with `review:` aliases); snapshots suppress only those. A crash after GitHub accepted a post but before it was recorded can still produce one update. +- **Confirmations.** Local reads never ask. A remote session's read, watch, unwatch, comment and resolve ask once per session and repository (`hasReadGrant`/`grantRead`) unless that host's `allowAgentStart` is on. Comment and resolve ask every time unless `githubWritesUnasked` is on. `host_tool_cancel` aborts the call's signal; a write checks it right before posting. +- **Replay after a restart.** Only `GITHUB_REPLAY_SAFE_TOOLS` (watch, unwatch, read, the Actions reads) and `list_sessions` run again (`new_session` too while Agent tools is enabled); writes answer the unknown-outcome error telling the agent to check first. +- **Limits.** 20 watches per session; a 60 s cycle (1.5 s per item past 40); about 1 GraphQL point per snapshot; below 200 points (`BUDGET_FLOOR`) polling waits for the reset. CI is reported once per head. With Agent tools off, polling pauses and resumes from the stored cursors. + +### Live event stream: one connection per browser (`/api/events`) +- Browsers cap HTTP/1.1 at **6 connections per host across all tabs**, and an SSE response pins one. **Never add a new `EventSource`**: add a channel. +- `lib/event-stream-worker.ts` (SharedWorker; dedicated Worker where SharedWorker is missing) holds the browser's one `/api/events` 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`. Tabs POST their agent commands and uploads themselves. `buildEventStreamWorker` bundles it into `dist/event-stream-worker.js`, whose URL carries the content hash. +- Tabs use `openEventStream(channel)` (`lib/event-stream.ts`) with EventSource semantics: `onerror` + CONNECTING = reconnecting, CLOSED = fatal (e.g. 409 for a wrapper-less session). Dead tabs are detected with a lifetime Web Lock. +- Channels (`event-stream-hub.ts`): `running` (badges + list hints), `notifications` (one tab's, by `clientId`), `hosts` (the `GET /api/hosts` body), `host-tools` (cross-session `open_url`/`notify`/`open_file`), `session` (observer-only, never spawns pi; merges `message_update`s under backpressure), `file` (viewer watch, same allow-list as `/api/files`). A failing frame ends only its own subscription. Split channels by consumer, lifetime, key and access check; `notifications` and `host-tools` are subscribed from `AppShell`. +- **Metrics.** Tabs and the worker record `action`, `event`, `reconnect`, `hang` and `dropped` samples; the worker POSTs them to `/api/transport-metrics` every 30 s or 200 samples. One worker-wide clock (lowest RTT of recent probes) times them. +- **Connection tab** (right panel, while "Show connection diagnostics" is on, `tau:connection-diagnostics`): polls the worker (`diag`) once a second; status, last reconnect and per-transport stats (`lib/transport-stats.ts`) over the last 30 min. Command rows include confirmed replies only; app ↔ pi rows skip commands the web app answers itself (`NO_SPAWN_REPLIES` and friends). +- **Worker rules.** No `AbortSignal.timeout`/`any` or `Promise.withResolvers` (a test checks the bundle). Every global it uses must be injectable into the `vm` context of `lib/event-stream-worker.test.mjs`. Ids use `Math.random().toString(36).slice(2, 12) + Date.now().toString(36)` (insecure LAN origins lack `crypto.randomUUID`). + +### Running state and reconciliation +- The sidebar subscribes to `running` (`subscribeRunningSessions()`), so badges update without polling. +- An open chat subscribes too: when its session appears there without a `session` stream (a run started elsewhere), it reads `GET /api/agent/[id]` and attaches as on load (`attachLiveRun`). The lookup waits for the chat's own work (mount load, a connecting stream, a local send, `!` command, Edit or compaction) and rechecks after it (`runningRecheckRef`); a failed lookup retries after 1, 2 and 4 s. +- Compaction state has one owner at a time: a manual compaction holds it until its command settles (`localCompactionsRef`); snapshots apply only if no compaction started or ended since they were requested (`compactionGenRef`). +- While a run is active `useAgentSession` polls `GET /api/agent/[id]` and reconciles on `visibilitychange`/`online`, so a missed `agent_end` cannot leave the chat running. A monotonic prompt run id keeps late frames or polls from resurrecting old streaming bubbles. + +### Composer panels (`components/ComposerPanels.tsx`) +The todo plan (`TodoList`) and subagent roster sit pinned above the input, each collapsible (collapsed by default; headers show live progress). Non-running chips nest under `Completed (N)`. Subagent chips carry live state from `subagent_lifecycle`/`subagent_progress`; a click opens the transcript dialog. The `/btw` panel comes first and is keyed by record id: each new topic starts expanded. + +### Side questions (`/btw`; `lib/btw.ts`, `hooks/useBtw.ts`, `components/BtwPanel.tsx`) +- `btw` / `btw_cancel` / `get_btw_history` are agent commands the wrapper runs through `/tau_btw`; the extension answers from the conversation with the session's model (never added to it), streams `btw_delta` and `btw_record` frames and persists records as `tau_btw` custom entries. +- `/btw ` and `/btw` are client builtins (`handleBuiltinSlashCommand`), routed before attachments are folded in: never a prompt, never queued, refused with a toast while attachments are attached. Asking starts the wrapper (`get_state`) and attaches SSE first. +- The response, history snapshots and frames race: merge only through `lib/btw.ts`. A record running before a history read and missing from it becomes `interrupted`. +- `btw_*` frames skip the message-update coalescer, are batched in `useBtw` with `scheduleAtDisplayRate`, and are routed **before** `catchUp.observe(event)`, whose `"epoch"` branch would reset the transcript. +- `get_btw_history` and `btw_cancel` never spawn pi (`NO_SPAWN_REPLIES`: empty history, `cancelled:false`). A refused explicit ask or history read shows a toast (`toastBtwError`); background reads stay silent. + +### Subagents (`lib/pi/subagent-bridge.ts`, `lib/subagent-types.ts`, `lib/subagent-history.ts`) +- pi-subagents reports foreground runs as progress on its `subagent` tool call (`details.progress[]`) and background runs on its `subagent-async` widget; `SubagentBridge` turns both into roster frames and answers `get_subagents`. `subagent-types.ts` parses progress defensively (current tool, tokens, cost, model, retry, detached flag). +- **Roster hydration:** `get_subagents` snapshots rehydrate the roster after reconnect (`refreshSubagentRoster`); history from disk fills in finished runs (`extractSubagentHistory`, result fields win over mid-run snapshots). +- **Transcripts:** the host-backed route pages the subagent's session file byte-wise without a live process; `?mode=completion` reads its final output (bounded tail). Ids match `SUBAGENT_ID_RE` (`[A-Za-z0-9_-]+` segments joined by `.`, ≤ 100 characters), validated before any path join. +- **`agent://` links** (`lib/agent-links.ts`): `MarkdownBody` linkifies handles and opens them through `AgentLinkContext` (`agentLinkTarget`); without a provider they render as text; `agent://all` is never linked. Every `ReactMarkdown` host must drop rejected hrefs (`defaultUrlTransform(url) || undefined`). +- **In-message task summary** (`MessageView-task-panel.tsx`): the reader keeps a size-bounded telemetry subset of task results (`keepTaskToolResultDetails`: no output/stderr, text ≤ 240 characters). ### Worktrees and project grouping -- `lib/worktree.ts` resolves linked worktree top-levels back to the main repo `projectRoot`; `listAllSessions()` attaches that to each `SessionInfo` so all worktrees for one repo are grouped together in the sidebar. -- `/api/worktrees` delegates authorized operations and root grants to the owning daemon; only that host's session-list cache is invalidated on main. -- New worktrees are created under `-worktrees/`. Existing branches are reused; otherwise `git worktree add -b` creates the branch. -- Removing a dirty worktree returns `409` with `{ dirty: true }` so the UI can ask before retrying with `force`. -- The file panel's **Worktrees** tab (`components/WorktreesPanel.tsx`) switches, creates, and removes worktrees; the new-session screen's worktree `` only switches. `SessionSidebar` owns the cache and emits a `WorktreeContext`. Switching moves where a new session starts, not the open session. Explorer, Git and every file tab keep their owning host (and a tab its cwd and session). ### Managed projects sidebar (`lib/project-registry.ts`, `/api/projects`) -- The sidebar lists **managed projects**: explicitly added directories (registered in - `~/.omp/agent/projects.json`, written atomically as temp-file + rename) plus - session-discovered ones — hidden entries excluded. Removing a project only - marks it hidden (reversible via re-adding); hidden entries suppress session - re-discovery. -- Registry paths are canonical `projectRoot`s: `POST` resolves worktrees to - their main repo via `resolveProject`, and `resolveProject` returns the - symlink-free on-disk form for plain directories so registered and - session-discovered paths compare equal on Windows casing. -- `GET /api/projects` re-authorizes registered roots with `allowFileRoot()` — - the in-memory browse allowlist does not survive restarts, and empty managed - projects derive no root from sessions. -- By default (sort "None") the client orders the merged list manually - (`sortOrder`, set by drag/Move up/down), then most-recently-added, then by - path (`lib/project-ordering.ts`), so rows never jump while sessions refresh. - The header sort button (`omp-web:project-sort` in `localStorage`, per - browser) switches to Alphabetical (label A→Z) or Last updated (newest last - message first: `lastMessageAt` from the session tail scan, else the file - mtime) — the latter deliberately reorders on activity. While a - sort is active, rows get a pin toggle: pinned projects (`pinOrder` in the - registry, pinned to the end of the group) lead in their own manual order and - alone keep Move up/down and drag; pins are ignored under "None". - Expanded project paths live - in `localStorage` (`omp-web:expanded-projects`), defaulting to only the - active/restored project expanded, and stale keys are pruned against the - current project list (only after the first project fetch — an empty - still-loading list must never wipe storage). -- Each project's session tree is capped at 5 roots with a show-more toggle; - project rows are cards matching the session items' height/margins/accent - treatment. Rows show no worktree/branch selector (see the Worktrees tab). - -### Clone a repository as a new workspace (`/api/projects/clone`) -- The Add-workspace `DirectoryPicker` takes an optional Git URL; "Clone here" - clones into `/`, then registers that directory - through the normal `POST /api/projects` path. -- Only `https://`, `ssh://` and scp-like `user@host:path` URLs are accepted - (`cloneDirectoryName`); git also runs with `GIT_ALLOW_PROTOCOL=https:ssh` - and `GIT_TERMINAL_PROMPT=0`, so credentials must come from helpers/agents. -- The POST streams NDJSON from daemon-owned jobs (`lib/hosts/workspace-clone.ts`); - DELETE carries `{ id, hostId }` and waits for process exit and identity-checked - cleanup. Cleanup captures into a private quarantine, verifies identity there, - and removes only the owned clone. A raced replacement is preserved and its - recovery location is shown. Existing targets are refused (409). Link/main - restarts leave jobs alive, but the UI reports uncertain - outcomes on a lost stream. Unobserved jobs cancel after two minutes; an unknown - job on a replacement daemon never means successful cancellation. +- The sidebar lists registered projects (`/projects.json`, atomic) plus session-discovered ones, minus hidden entries. Removing only hides (re-adding restores); hidden entries suppress rediscovery. Registry paths are canonical `projectRoot`s (`resolveProject`). +- `GET /api/projects` re-authorizes registered roots with `allowFileRoot()` (the allowlist does not survive restarts). +- Sort "None" orders by manual `sortOrder`, then most-recently-added, then path, so rows never jump. The sort button (`tau:project-sort`) switches to Alphabetical or Last updated; while a sort is active, pinned projects (`pinOrder`) lead and alone keep Move/drag. Expanded projects live in `tau:expanded-projects`, pruned only after the first project fetch. Each project shows at most 5 roots before "show more". + +### Clone a repository (`/api/projects/clone`) +"Clone here" in the Add-workspace picker clones into `/` and registers it through `POST /api/projects`. Only `https://`, `ssh://` and scp-like URLs (`cloneDirectoryName`); git runs with `GIT_ALLOW_PROTOCOL=https:ssh` and `GIT_TERMINAL_PROMPT=0`. Jobs are daemon-owned (`workspace-clone.ts`): POST streams NDJSON, DELETE `{ id, hostId }` waits for exit and identity-checked cleanup (quarantine first; a raced replacement is preserved and its location reported). Existing targets are 409. Unobserved jobs cancel after two minutes. ### File access allow-list -- `/api/files` is not a general filesystem browser. `workspace-roots.ts` discovers - that daemon's sessions/projects, explicit validated grants, scratch directories - and instruction roots. Reads and watches share explicit-root authorization; - session references grant reads only, not listing or writes. Credential exclusions - apply to canonical targets too. - Credential ownership checks resolve configured symlinks even when the final target is missing, without collapsing native `link/..` traversal. Profile config roots visible in a requested or canonical path remain protected when `profiles/` cannot be listed. Compare inode identities through original configured paths, not only potentially lossy string realpaths. - Record failures inspecting requested paths separately from owned credential directories and files. Known-secret matches remain denied first. Otherwise, a requested metadata failure terminates that operation with 404 `file_not_found`, even if a later lookup would succeed; never continue with an unclassified path. If the request metadata is sound but ownership metadata is unavailable, return 503 `credential_policy_unavailable` until it is accessible. Missing paths remain ordinary absence. Never change user filesystem permissions automatically. - Read owned directory entries and unresolved symlink targets as bytes: an undecodable protected filename, profile or target makes ownership metadata unavailable, while unrelated byte-named assets do not. For missing macOS targets, account for Unicode normalization and calibrate case aliases through existing directory metadata without creating files or crossing filesystem devices. This is not a portable filesystem-equivalence guarantee: prospective aliases on Linux casefold mounts and legacy HFS+ ignorable-character rules lack native coverage. -- Successful selection, default cwd and worktree operations grant roots on the - owning daemon. Browsing alone grants nothing. Main's `getAllowedFileRoots()` - remains for the unrelated local config/import/skills readers, not workspace APIs. -- The Explorer's `type=list` hides nothing by name and there is no "show hidden" switch (no ignore lists here or in `/api/file-index`, which follows `.gitignore` in a Git repo and otherwise indexes regular files under its caps, skipping symlinks to both files and directories; when `git ls-files` fails it falls back to that walk, ignored files included). The tree sends `&root=` to the owning daemon: the listed directory's realpath must be inside the root's realpath (403 `outside_root`, also for an unknown or relative root; the root needs no allow-list check of its own, since the listed path already passed `authorizeFileAccess` and a root can only narrow it), and each symlink entry gets `linkTarget` (raw `readlink`) and, when it leaves the root or dangles, `outsideRoot: true` (the UI dims it and will not expand or open it; `flattenVisibleRows` never descends into a flagged dir). This limits the tree only; `read`/`download` keep the allow-list and session-reference rules. - The non-Git index walk uses asynchronous directory reads so other daemon requests can progress during a scan. Preserve breadth-first ordering, the existing depth/file/directory caps, truncation reporting and shared in-flight scans when changing this path. -- The Explorer calls the additive daemon capability `listFilesInRoot(input, root)`. Missing capability returns 501 `workspace_unsupported` with upgrade advice; never fall back to an unconfined listing. Keep the original `listFiles(input, showHidden: boolean)` wire contract for older web servers; it validates the flag but follows the current all-names listing policy. Both operations share one daemon-side listing implementation. -- The session-id → file path cache (`cacheSessionPath`, `lib/session-reader.ts`) on main is filled by main's own scans and by wrappers on the local host; it only serves the readers listed under "Session list caching". +- `/api/files` is not a filesystem browser. `workspace-roots.ts` discovers each daemon's sessions/projects, explicit validated grants, scratch directories and instruction roots. Session references grant reads only. Successful selection, default cwd and worktree operations grant roots on the owning daemon; browsing grants nothing. Main's `getAllowedFileRoots()` serves only local config/import/skills readers. +- Credential exclusions (`isPiSecretFile`, `lib/file-access.ts`) cover pi's `auth.json`, `mcp-auth.json`, legacy `oauth.json`, `models.json` and `mcp.json` (with copies and editor files) directly in an agent dir, tau's `tau-settings.json` (agent environment), and the whole `/tau/` tree (its key files also by hard-link identity). They apply to canonical targets and link aliases. Known secrets are denied first; a requested-path metadata failure answers 404 `file_not_found`; unavailable ownership metadata answers 503 `credential_policy_unavailable`. Never change user permissions automatically. +- The Explorer's listing hides nothing by name. It calls `listFilesInRoot(input, root)`: the listed directory's realpath must be inside the root's (403 `outside_root`), and symlinks that leave the root or dangle are flagged `outsideRoot` (dimmed, never expanded). The old `listFiles(input, showHidden)` op shares the implementation. `/api/file-index` follows `.gitignore` in a Git repo, else walks regular files under caps (breadth-first, asynchronous reads). +- **Workspace writes never touch pi's agent directory.** Every user-requested mutating workspace op (Files-panel upload check and publication, clone, worktree add/remove) runs `authorizeWritableDirectory`/`assertOutsideAgentDir` (`workspace-roots.ts`) on the daemon: a target that is, or after canonicalizing its nearest existing ancestor lies under, `getAgentDir()` or `~/.pi` (ancestors compared by device and inode, so symlinks, `..`, case and bind-mount aliases match) is refused 403 `agent_dir_read_only`. Reads are unchanged. The daemon's own composer `uploadAttach` into `/local/uploads/` does not pass through it. A new mutating op must call it for every path it writes. +- `cacheSessionPath` (`session-reader.ts`) on main is filled by main's scans and local wrappers and only serves main-side readers. ### Session list caching — new sessions must appear immediately -- The sidebar and command palette list sessions per host: `listSessionsAllHosts()` (`lib/hosts/session-index.ts`) calls each host's `listSessions` op and caches it 30 s per host (`LIST_TTL_MS`, the daemon's own TTL). **This machine's list is its daemon's**; a host that fails or is offline keeps its last list. Nothing on main parses session files to build it. -- **A lookup miss is not deletion while any host's list is unavailable.** `hostForSessionId()` returns no host only after successful current-generation discovery across all registered hosts; offline or failed-refresh lists produce retryable 503, including a cold remote cache after main restarts while the local daemon is already online. Cached positive mappings remain usable. Outbox acceptance retains validated messages during unknown ownership and normal host-hello dispatch resolves them later; never guess a local owner or trust a caller's host hint. -- The daemon's `listSessions` is `listAllSessions()` (`lib/session-reader.ts`): a 30 s TTL list cache plus an mtime-keyed directory walk in `lib/omp/session-files.ts` (`listSessionFiles`), both in the daemon process. -- The walk cache keys on the **sessions root** mtime. On Windows/NTFS a new - `.jsonl` inside an existing project subdirectory does NOT bump the root - mtime, so the walk stays stale indefinitely. -- `invalidateSessionListCache()` (fired on `agent_end`, `session_info_update`, - compaction, renames) must therefore ALSO clear the walk cache via - `invalidateSessionFileListCache()` — never add a session-mutation path that - forgets this. Regression test: `session-reader.test.mjs`. -- A mutation that main triggers calls `invalidateLocalSessionLists()`: it clears main's per-host entry and sends the daemon `invalidateSessionLists` (the daemon runs the invalidation above). A route that changes this machine's session files and does not call it leaves the sidebar stale for up to 30 s. -- **Still read on main, from this machine's own files:** transcript search (`session-content-search.ts`, `/api/sessions/search`), the session watcher (`session-watcher.ts`), this machine's archive list/restore (linked hosts' go through their daemons), import, usage (`usage-db.ts`), subagent history and local file-reference readers. Their main-side session caches are invalidated separately. Workspace shell-output authorization and bytes now come from the owning daemon; new remote-capable readers must use the host seam. +- `listSessionsAllHosts()` (`lib/hosts/session-index.ts`) calls each host's `listSessions` op and caches it 30 s per host (`LIST_TTL_MS`). This machine's list is its daemon's; an offline host keeps its last list. +- **A lookup miss is not deletion while any host's list is unavailable.** `hostForSessionId()` returns no host only after successful current discovery across all registered hosts; otherwise retryable 503. Never guess a local owner or trust a caller's host hint. +- The daemon's `listAllSessions()` uses a 30 s list cache plus an mtime-keyed walk (`listSessionFiles`) keyed on the sessions root mtime, which NTFS does not bump for a new file in an existing subdirectory: `invalidateSessionListCache()` must also call `invalidateSessionFileListCache()` (regression test `lib/session-reader.test.mjs`). +- A mutation main triggers calls `invalidateLocalSessionLists()` (main's entry plus the daemon's `invalidateSessionLists` op); a route that changes session files without it leaves the sidebar stale for up to 30 s. +- Still read on main from this machine's files: `session-watcher.ts`, import, usage (`usage-db.ts`) and local file-reference readers, each with its own cache invalidation. + +### Session archive and restore (`lib/pi/archive.ts`, `/api/sessions/archive`, `/api/sessions/[id]/archive`) +- Archive and restore run on the session's host (`archiveSession`, `listArchives`, `restoreArchive` ops); archives are `.jsonl.gz` under `/../archive/sessions` with their artifacts directory. The aggregate GET isolates failures per host (`unavailableHosts`, this machine included). +- **Restore needs proof the id is not active anywhere:** fresh strict discovery from every registered host (`listSessionIdsForRestore`, which bypasses caches and fails closed on any unreadable project, symlink or header). Any offline host blocks it (503 `host_offline` naming it); an incomplete inventory is 503 `host_sessions_unavailable`. +- **Claims** (`withArchiveRestoreLock`, `/tau/archive-restore-locks.sqlite`, table `restore_claims`, `synchronous = FULL`): a per-session lease renewed every 10 s. A remote restore is fenced at the daemon: main `restoreReserve`s a claim token, `hold`s it with the daemon's `instance`, then sends `restoreArchive`; it releases only on `ok` or `archive_restore_failed`. Everything else (silence, link loss, any other error, `archive_restore_not_admitted`) keeps the claim held (`archive_restore_unconfirmed`). A stale held claim is resolved by `restoreFence` only when the same `instance` answers with `running: false`. **Recovery limitation:** a claim whose daemon was replaced or restarted stays blocked for good; only an operator who verified that no daemon that could have taken it is running may delete that session's row. +- **Commit order** (`commitRestore`): under a filesystem-exclusive `.restore-lock`, the source generation is pinned (`.restore-pin`) and captured (`.restore-consume`), artifacts move in first (`moveDirectoryNoReplace`), then the transcript is hard-linked, then the source is consumed; undo uses `takeBackTranscript`. `validateRestorePathSync` runs right before the moves. A transcript or artifacts already at the destination fails with 409 and is never merged or removed. A local restore runs the commit inside `BEGIN IMMEDIATE` on its claim row, synchronously. Discovery lists captures as `restorePending` evidence (Restore disabled), never as aliases; artifact trees are never scanned as archive entries; a corrupt gzip rejects the host's whole list (retention over availability). A process killed inside the commit leaves the claim and possibly partial moves for manual repair; power loss is not covered (no fsync, no journal, on purpose). ### Chat scroll-follow -- `useAgentSession` follows the conversation: the effect depends on both - `messages` (boundaries) and `streamState` (every token batch) and throttles - to one `requestAnimationFrame` while a run is active (`followScrollFrameRef`). -- A manual scroll-up sets `completionScrollAllowedRef = false` and disables - following until the next prompt; `scrollUserMsgToTop` handles the - pending-scroll after sending. -- A `ResizeObserver` on the chat scroller (`ChatWindow`, beside `nearBottom`) - keeps a reader whose previous view reached the bottom there when the - scroller changes height (phone keyboard, composer or ask panel growing). It - judges by the previous height, so content that grew below the reader (an - expanded tool call) does not count as being at the bottom. -- Programmatic smooth scrolling must respect `prefers-reduced-motion` - (`usePrefersReducedMotion` in `hooks/usePrefersReducedMotion.ts` — also the - only way to stop SVG SMIL animations, which CSS cannot). -- A jump to a sidebar search hit calls `holdScrollPosition()` (`useAgentSession`): - it marks the initial scroll done and stops following, as a manual scroll-up - would, so the next frame does not pull the reader back to the bottom. +`useAgentSession` follows the conversation on `messages` and `streamState`, throttled to one animation frame while running. A manual scroll-up disables following until the next prompt (`completionScrollAllowedRef`). A `ResizeObserver` (`ChatWindow`) keeps a reader at the bottom when the scroller changes height, judged by the previous height. Smooth scrolling respects `prefers-reduced-motion` (`usePrefersReducedMotion`). A jump to a search hit calls `holdScrollPosition()`. ### Search hits in the chat (`/api/sessions/[id]/matches`, `hooks/useChatSearchHighlights.ts`) -- While the sidebar search has a query, each session row's chevron lists its - hits (`SessionSearchMatches`, 10 at a time). The server ranks hits of the - active conversation's user text and assistant text blocks (quality, then - newest message) and builds snippets for the returned hits only. "Load more" - asks for a longer prefix (`limit`), never an offset: a running session - re-ranks between requests, so offsets would repeat or skip hits. -- A hit is addressed as `(entryId, ordinal)`: its index among that message's - hits, counted per rendered text node in rendered order on both sides. The - server (`lib/session-match-listing.ts`) parses each body that has a hit in its - source (a user message's text blocks joined with `\n`, each assistant text - block separately) with the chat's remark parser and counts in text, inline - code and code nodes; link targets, image alt text, raw HTML and math render - no searchable text, and footnote definitions come last in reference order. - The chat counts in the rendered `[data-message-text][data-entry-id]` text, - skipping code-block headers, buttons, line numbers, KaTeX, Mermaid notes, - table charts and generated footnote labels (`NOT_MESSAGE_TEXT`). New chrome - inside message text must be excluded there too, and new markdown syntax - that renders text must be counted in `renderedTextNodes`, or later ordinals - shift. Known gaps: a phrase across syntax-highlighting tokens or a linked - `#123`/`agent://` ref, and block-level raw HTML; the jump then lands near it. -- Painting uses the CSS Custom Highlight API (`omp-search`, - `omp-search-current` in `globals.css`), repainted on DOM mutations; browsers - without it still jump. A jump widens the lazy render window - (`revealMessage`) first. Each click is a new target object used once: - `onSearchTargetHandled` drops it in AppShell, so reopening the session later - does not jump again. AppShell also drops a pending target when the query - changes or another session opens, and the hook drops one whose entry the - loaded branch lacks. An empty query clears the highlights and the target. - -### MCP configuration (`lib/omp/mcp-config.ts`, `/api/mcp`, `components/McpConfig.tsx`) -- Project MCP config resolution order: `.omp/mcp.json`, `.omp/.mcp.json`, - `mcp.json`, `.mcp.json` at the git top level (falls back to cwd for - non-git dirs). Server definitions support `stdio`, `http`, and `sse`; - exactly one of `command`/`url` is required and validated before any write. -- Writes are atomic (temp file + rename), preserve unrelated top-level keys - (`disabledServers`, `$schema`, ...), and support rename via `previousName`. -- The MCP settings live in their own Settings tab (`SettingsTabs` id `"mcp"`, - workspace-gated). Server list rows show a config-derived status dot - (valid+enabled / disabled / invalid) — no live-connectivity probe exists in - the channel protocol, so failures surface as toasts (`toast.error`) from the - editor actions, not inline text. -- The endpoint is guarded by the same allowed-root rules as `/api/files`. -- `GET /api/mcp?sessionId=…&attach=1` returns the live status of a session this server already has running (a remote one included), and otherwise answers `liveError: "The session is not running"` instead of starting one (a cluster session on another member is read where it runs; `McpConfig liveOnly` shows it read-only). - -### Plugins and skills -- `/api/plugins` shells out to the user's `omp plugin` CLI (`list/install/uninstall/enable/disable/upgrade`, `--json` where available) — never the Bun-only SDK. -- `/api/skills` lists through `lib/skills-service.ts`, which execs `omp skill list --json` with the project as the process cwd (omp ≥ 18.3.3; never pass the directory as an argument — Windows `.cmd` launchers run through `cmd.exe`, which would interpret `&` in it). That is the same discovery sessions use, including `namespace/name` collision aliases and plugin/registry/custom-directory skills. A pure-Node replica scan (project `.omp/skills` walk-up, `~/.omp/agent/skills`, the `.claude` / `.agent(s)` / `.codex` / `.github` compat dirs, managed skills) is only the fallback for older binaries and failed or malformed output. A failed run is negative-cached per binary fingerprint **and cwd** (5 min) so old installs don't spawn per request while one broken project config cannot degrade the others. Listing runs omp's normal startup, so it has omp's side effects (e.g. omp renames an unparseable `config.yml` aside, as a session would). -- Skill toggling edits only the `disable-model-invocation` frontmatter key on the target `SKILL.md`; keep that surgical so user formatting survives. omp reports it back as `hide` (it reads `hide`/`disableModelInvocation`/`disable-model-invocation`). Frontmatter is omp's only per-skill "hide from model, keep `/skill:`" knob; `disabledExtensions: ["skill:"]` removes the skill entirely. -- Only user-owned skills are togglable: `getSkillToggleRoots()` (allowed file roots — workspaces the user opened — plus replica scan roots) is the single allowlist for both PATCH and the `togglable` flag GET returns; it is `main`'s pre-CLI allowlist, unchanged. Skills omp lists from anywhere else (the plugin cache, registry installs, custom directories outside a workspace) render a disabled toggle — their files belong to an installer and an update would discard the edit. Never widen PATCH to whatever omp lists. -- `/api/skills/install` shells through `npx skills add ... --agent universal`, which installs into the ecosystem-standard `.agents/skills` dirs omp reads; project installs run with the selected cwd. -- `GET /api/plugins`, `POST /api/plugins`, `GET /api/skills`, `POST /api/skills/check` and `POST /api/skills/update` take no `cwd` for the user level (`loadUserSkillsWithInstallInfo`; omp runs in the agent directory, `ensureAgentDir`; the replica scan reads the user roots only, before names are deduplicated, so an agent directory below a project keeps its user skills). The GET routes have no project scope; a project-scope `POST /api/plugins` or `/api/skills/check` without a `cwd` answers 400 `cwd_required`, and `/api/skills/update` answers 400 `cwd_package_scope_required`. Settings uses this for a cluster session on another member, whose project is not on this machine. - -### Updates: web server versus host software -- **Settings → System** prepares and reviews a durable server-and-host upgrade plan, including owned compiled releases. `POST /api/app-update {action:"prepare"}` returns the plan; commit requires `{action:"commit",attemptId,approval:{planId,force}}`. Approval is bound to release identity and the registered-host/session snapshot. An incompatible host without a verified recovery path blocks server cutover. -- **Settings → Hosts** manages individual daemons, including **This machine**; omp updates with ompweb. Normal `POST {target:"ompweb",version}` does not interrupt activity. `force:true` requires distinct GUI confirmation and may end sessions/subagents. Machine-readable `canForceUpdate` and blockers govern the action, never English message parsing. Force does not waive integrity, ownership, process identity, disabled updates, local drains or service permissions. -- **Recovery plane.** Modern candidates may acknowledge an approved future server protocol through an operation-bound preflight nonce and maintenance receipt. Legacy recovery admits only a fixed bootstrap on one operation-bound runner channel, never general old application traffic. Windows uses native process/service/task handling. Old daemons copy only `update-worker.ts`; its startup must work without sibling modules and load shared lifecycle code from verified sources before replacing an install. -- **Completion and rollback.** `upgrade-plan.ts`, `self-update.ts` and `server-update-worker.ts` persist progress; POST acceptance and shell output are not success. Verify the expected release, live process identity and operation/boot receipt after reconnect. Retain the prior install until healthy, and report partial recovery explicitly. See `docs/superpowers/specs/2026-11-14-coordinated-gui-upgrades-design.md` when changing upgrade or bootstrap contracts. -- `/api/omp-update` keeps only `restart`, an explicit server-side maintenance API for existing callers. The settings UI and AppShell no longer use it as a global update control or send a server-wide session restart after a host update. +- With a sidebar query, each row lists its hits (`SessionSearchMatches`, 10 at a time). "Load more" asks for a longer prefix (`limit`), never an offset: a running session re-ranks. +- A hit is `(entryId, ordinal)`, counted per rendered text node in rendered order on both sides: the server (`session-match-listing.ts`) parses with the chat's remark parser; the chat counts in `[data-message-text][data-entry-id]`, skipping chrome (`NOT_MESSAGE_TEXT`). New chrome inside message text must be excluded there, and new text-rendering markdown counted in `renderedTextNodes`. +- Painting uses the CSS Custom Highlight API (`tau-search`, `tau-search-current` in `globals.css`). Each click target is used once (`onSearchTargetHandled`); an empty query clears everything. + +### MCP configuration (`lib/pi/mcp-config.ts`, `/api/mcp`, `components/McpConfig.tsx`) +- The project file is `/.pi/mcp.json` (pi reads it only for a trusted project, and from the session cwd, not the git top level); the user file is `/mcp.json`. Other apps' configurations are listed read-only as such; pi reads none of them. Server definitions support `stdio`, `http` and `sse` with exactly one of `command`/`url`, validated before any write. Writes are atomic under a cross-process lock and preserve unrelated keys; `previousName` renames. +- The endpoint follows the `/api/files` root rules and never exposes environment variables or headers. +- Configuration only: no live status or actions. tau never sends `/mcp` as a prompt; changes apply when a session starts or reloads. + +### Plugins (pi packages) and skills +- `/api/plugins` shells out to the user's pi (`lib/pi/plugins-cli.ts`, `app/api/plugins/route.ts`): `pi list` (text, parsed by `parsePiListOutput`: "User packages:" / "Project packages:"), `pi install [-l]`, `pi remove [-l]`, `pi update [|--extensions]`. There is no enable/disable. It runs in the project cwd, or the agent dir for the user level; a project-scope POST without `cwd` is 400 `cwd_required`. +- `/api/skills` lists through `lib/skills-service.ts`, a pure-Node scan of what pi 1.5.2 loads, in pi's precedence order: project `.pi/settings.json` `skills` paths, `/.pi/skills`, `.agents/skills` from cwd up to the git root, user `settings.json` `skills`, `/skills`, `~/.agents/skills`, then package skills of the packages `pi list` prints (run with the project as the process cwd, never as an argument: `cmd.exe` would interpret `&`). The first name wins. Project skills are listed only when the project is trusted by the same rule as `--approve` (`projectTrusted`); settings/package filter patterns and ignore files are not replicated. +- Skill toggling edits only the `disable-model-invocation` frontmatter key (pi reads only that key, only a YAML `true`). Only user-owned skills are togglable (`getSkillToggleRoots()`, the one allowlist for PATCH and the `togglable` flag); never widen PATCH to whatever is listed. +- `/api/skills/install` runs `npx skills add ... --agent universal` (`.agents/skills`). Without `cwd`, `GET /api/plugins`, `GET /api/skills`, `POST /api/skills/check` and `/update` act on the user level only. ### Auth and model config -- Auth flows go through `ompweb-omp` commands (`get_login_providers`, `login`, `get_logout_accounts`, `logout`) against the omp child process; credentials live in omp's `agent.db` (SQLite) which omp-web never touches directly. `/api/auth/accounts/[provider]` lists stored accounts and removes one by `credentialId`; omp without those commands reports `supported: false` and the UI falls back to the read-only `omp usage` account list. -- Linked hosts with `shareCredentials` read this machine's credentials through `lib/omp/auth-broker.ts`, the `omp auth-broker serve` child (the token comes from `omp auth-broker token` and stays in the server process; a refused token stops the child and the next request starts a new one). The broker reloads the store on every snapshot, so a login or logout in Settings reaches every omp process a sharing host starts afterwards; a running process picks it up the next time it is used (omp stops listening for updates after 20 seconds without activity and resumes on its next use) and keeps the access tokens and API keys it has already loaded until it ends. -- The Models panel reads and writes `models.yml` in the omp agent directory (`~/.omp/agent/models.yml`, `.yaml` fallback). -- API-key status endpoints must never return the raw key. +- Every host keeps its own pi logins in its `/auth.json`, which tau never reads. The auth routes (`app/api/auth/**`, `?hostId=`, default this machine) go through `lib/host-auth.ts` to that host's daemon (`auth` op, `lib/hosts/daemon-auth.ts`), which runs a pi of its own and calls `/tau_auth` (`providers`, `login`, `api_key`, `logout`). Logins stream steps (`tau_auth_event`) and ask for codes through `__tau_auth_prompt__` dialogs; the login SSE keeps pi-web's event names. Raw keys and tokens never leave pi; a typed key travels in as one command argument. `afterAuthChange` invalidates placement and the models cache. +- `/api/models` asks the utility pi (`get_available_models`, `/tau_auth providers`) on this machine; the cache is global (a `?cwd=` is ignored) and refreshed when `models.json` changes. +- The Models panel reads and writes `/models.json` (`lib/pi/models-config.ts`, unknown fields preserved; an unparseable file is never overwritten without an explicit opt-in). `models-config/catalog` searches models.dev for presets. +- `/api/pi-settings` edits allow-listed keys of pi's global `settings.json` (`lib/pi/settings-config.ts`). +- API-key status endpoints never return the raw key. + +### Updates: web server and host software +- **Settings → System** prepares and reviews a durable server-and-host upgrade plan. `POST /api/app-update {action:"prepare"}` returns the plan; commit requires `{action:"commit",attemptId,approval:{planId,force}}`. Approval is bound to release identity and the registered-host/session snapshot. An incompatible host without a verified path blocks server cutover. The server worker (`self-update.ts`, `server-update-worker.ts`; a package builds a self-contained Node worker, a compiled release runs a private binary copy) stages and digest-checks the candidate, runs `tau preflight` in its environment, and only then stops anything (`upgrade-process.ts`). Completion needs an expected-version boot nonce and live process proof; a failed cutover keeps the prior tree and reports rollback status. See `docs/superpowers/specs/2026-11-14-coordinated-gui-upgrades-design.md`. +- **Settings → Hosts** updates individual daemons, this machine included, **only over the maintenance API**: without a maintenance connection `/api/hosts/[id]/updates` answers 503 `maintenance_unavailable`, and the application link has no update ops. The only target is `tau` (`HostUpdateTarget`); pi's version is shown, never updated (update pi with npm on the host). Normal `POST {target:"tau",version}` does not interrupt activity; `force:true` needs a distinct confirmation and may end sessions. `canForceUpdate` and machine-readable blockers govern the action. Force never waives integrity, ownership, process identity, `TAU_DISABLE_AUTOUPDATE`, local drains or service permissions. A candidate release without the `preflight` command fails the update and keeps the prior install. A daemon copies only `update-worker.ts`, whose startup must work without sibling modules; it accepts only tau descriptors (`process` and `releaseRepo` required). Source checkouts are manual-only. +- Persisted progress (`upgrade-plan.ts`, `self-update.ts`, `server-update-worker.ts`, `hosts/updates.ts`) decides success, never POST acceptance or shell output. ### Navigate back / forward (`lib/navigation-history.ts`, `hooks/useNavigationHistory.ts`) -- Browser-style back/forward over visited chat views (sessions + the new-chat - composer), in-memory per page load. It is **omp-web's own stack**, never the - browser History API — the app only ever `router.replace`s `?session=`, and - the real history stack belongs to the mobile back-gesture / exit-guard - machinery (`useSidebarHistory` + the popstate bridge). -- AppShell records views from one effect keyed on - `(selectedSession?.id, newSessionCwd)`: recording the entry the cursor - already sits on is a no-op, which is what makes back/forward - self-suppressing — `navigateInHistory` commits the step, the view lands, the - effect re-records the target, nothing is pushed. Any other view change - (sidebar/palette select, new chat, session created, fork, project-switch - close) pushes normally and truncates the forward branch, browser-style. -- Applying a step: peek → resolve the session id via `/api/sessions` → - commit + `handleSelectSession`, or `handleNewSession` for new-chat entries. - A dead id (deleted session) drops that entry and tries the next one in the - same direction; a failed list fetch aborts without dropping. A view change - during the await (versioned ref) aborts the navigation so a slow fetch - never yanks the chat away. -- Shortcuts live in `useGlobalKeyboardShortcuts`: ⌘[/⌘] (macOS standard), - Alt+←/Alt+→ (Windows/Linux standard; on macOS Alt+Arrow stays free — it is - word-wise caret movement), plus the mouse back/forward buttons - (`BrowserBack`/`BrowserForward`). The keystroke is always swallowed while a - handler is registered — an exhausted stack stops dead rather than falling - through to the browser's own back/forward, so the app is never backed out - of by accident — and shortcuts are skipped entirely while a - `[role="dialog"]` modal is open. The sidebar header buttons (before Archived - Sessions, wrapped in `.sidebar-nav-buttons`) disable on stack bounds, show - the platform shortcut in their tooltip, and hide below a 240px sidebar via - the `.sidebar-shell` container query (the keyboard shortcuts still work). - -### Composer word prediction (`hooks/useWordPrediction.ts`, `components/GhostMirror.tsx`) -- Ghost text comes from omp's `predict_word` command (engine = omp's - `spelling.autocomplete` setting; omp applies the prose gates). Tab or → - accepts; accept/typed-past outcomes go back as `predict_word_feedback`. -- Keystroke predictions never spawn or replace an omp child: the agent route - answers `{ suffix: null }` when no process is alive, so sessions that are not - running show no ghost text until the first send. -- Ghost text paints only when the caret ends its line (the mirror overlay would - otherwise overlap typed text). Settings → Interface & Behavior → Word - completion (`lib/composer-prefs.ts`, localStorage `omp-web:word-completion`): - Auto (default) enables it only when the primary pointer is fine - (`(pointer: fine)` — mouse/trackpad; browsers cannot detect an on-screen - keyboard), Enabled/Disabled force it. Also skipped for - drafts past 20k chars (omp's prose-gate cap); an omp without `predict_word` - ("Unknown command") pauses requests for a minute. -- Ghost state lives in a small external store (`useSyncExternalStore` in - `GhostMirror`), not ChatInput state: re-rendering the composer per ghost - change was the dominant per-keystroke cost. +- Browser-style back/forward over visited chat views, in memory per page load. It is tau's own stack, never the History API (the app only `router.replace`s `?session=`; real history belongs to the mobile back-gesture machinery, `useSidebarHistory`). +- AppShell records views from one effect keyed on `(selectedSession?.id, newSessionCwd)`; recording the current entry is a no-op, which makes back/forward self-suppressing. A step peeks, resolves the id via `/api/sessions`, then commits; a dead id is dropped and the next tried; a view change during the await aborts. +- Shortcuts (`useGlobalKeyboardShortcuts`): ⌘[/⌘], Alt+←/→ (not on macOS), mouse back/forward. The keystroke is always swallowed while a handler is registered, and skipped while a `[role="dialog"]` is open. Sidebar buttons hide below a 240px sidebar (`.sidebar-shell` container query). ### Composer file uploads (`docs/specs/2026-11-02-file-uploads-design.md`) -- Images and text files go inline while they fit the inline budgets - (`lib/image-attachments.ts`, `lib/chat-attachments.ts`); every other file, - an image switched to **As file**, and anything over a budget is uploaded - (2 GiB per file, 20 per message, `lib/upload-limits.ts`, browser-safe). - The composer re-checks the inline budget per chip on every render, so an - image's decoded size comes from `attachedImageBytes` (scanned once per - image object), never a fresh base64 scan. -- Uploads land in a staging dir on the **session's host** (the daemon), not on - main: a new chat has no session yet. The prompt command carries - `uploads: [id]`; `runAgentCommand` (`lib/agent-command.ts`) attaches each - through the host op `uploadAttach` (hard link into - `/local/uploads/`, never overwriting; copy on EXDEV) and appends - the "Attached files" block with `local://` URL and absolute path. Ids stay - registered until the prompt reaches omp, so a retried send reuses the attach. - Attachment preparation uses the wrapper's pending-command protection too, so - disconnect and idle cleanup cannot dispose a submitted prompt's session while - a slow copy is still running. Later commands await the send fence before - selecting/replacing the wrapper, so Stop and an Advisor change cannot overtake it; - a command through any registry alias of the same wrapper (`getRpcSessionKeys`) - waits too. The Attached files block can push a prompt past the host link's - line cap: the transport then refuses it before queueing with 413 - `request_too_large`, and the uploads stay registered for a shorter resend. -- Bytes are forwarded, never re-encoded: the browser sends binary frames - `[n][id][payload]` (≤ `pieceBytes`) as `LinkSender` blob units keyed - `up:`; `lib/browser-link.ts` accepts them only for uploads that link - started and hands the same bytes to `forwardUploadFrame` (`lib/uploads.ts`) with - that link's sink; frames are forwarded only while it is the upload's current - sink, so a WS sender superseded by an HTTP resume or newer start is refused; - `forwardUploadFrame` queues them as blob units on the host link (link v6; `hostVersion < 6` - → 426 `host_upgrade_required` on a remote host, `host_restart_required` on - `local`: an in-place upgrade keeps a running v4/v5 daemon, which is inside - `[MIN, LINK]`, so "This machine" needs `ompweb-host` restarted). Blob units - are outside both links' line windows; the worker's per-upload - `UPLOAD_WINDOW_BYTES` credit, refilled by the daemon's `upload_ack`, is the - flow control, and main enforces it: a frame putting `sent - received` over - `UPLOAD_WINDOW_BYTES + pieceBytes` stops the upload with 429 - `upload_window_exceeded` (frames dropped until the next start; the socket - stays open). Binary frames are not resent: after a browser-link drop or a - web-server restart the worker re-sends `up_start {id, n, …}` (same id, `n` = - a worker-wide increasing sequence) and continues from the host's `received` in - the answer `up_ack {…, start: n}`. Each start has a fresh sink whose progress, - completion and errors retain `start: n`, including messages already queued - before a Retry. The worker ignores any mismatched generation before applying - an ack or error. On main the latest concurrent start wins; earlier starts - still answer their callers. - Each host `uploadStart` also carries a fresh UUIDv4 `attempt`; the daemon - echoes it on progress, completion and error `upload_ack`s. Main discards - superseded-attempt acks even if they arrive after the newer start's reply. - Receipt replay and a start of an already-attached upload both require a - regular-file target; a missing or directory target gets `upload_missing`. - Receipt publication is atomic, and start/attach/abort controls share one - per-id queue so an abort cannot be undone by an earlier attach's receipt. - A start that finds the upload aborted sends - `uploadAbort` to the host and answers 404 `upload_missing`. A host-link drop - fails each in-flight upload with 503 `host_offline`. `uploadFile` - (`lib/event-stream.ts`) resumes 502/503/504 and HTTP network failures by - itself (same id, back-off restarting after new bytes, chip shows - "Reconnecting…") until an outage reaches 5 min, timed from its first - failure; other failures, and a bfcache pagehide (410), show Retry. - Back-off and in-flight retries share the remaining outage budget; their - watchdog resets only when acknowledged bytes advance. Expiry aborts the - HTTP request or sends tab-scoped `up_pause` to stop the worker without - deleting staged bytes, then settles with `upload_stalled` so Retry is usable. - Checks after waking and before applying an ack prevent expired work reviving. - HTTP body-read network errors propagate to the retry classifier (only JSON - syntax errors use the fallback body). Network `TypeError`s use the existing - localized network-error explanation in upload chip tooltips. -- Limits on main: at most 32 unfinished uploads per owner (429 - `too_many_uploads`); an unfinished entry idle 10 min (no start, frame or ack) - is dropped from the registry (a later `up_start` re-registers it). The worker - fails an upload no start answer or ack advances for `UPLOAD_STALL_MS` (120 s) - with 504 `upload_stalled` and forgets it without aborting it on the host, so - the tab's automatic resume continues it. Page navigation settles pending - WebSocket-upload promises before the worker's `bye`: a composer retained by - bfcache shows Retry after restoration, not a permanently uploading chip. That - failure (410) gives the chip a new upload id, so its Retry starts over and the - old id's pending cancel (worker, HTTP DELETE or host) can never delete it. - The daemon's `sweep` deletes staged files older than 24 h and aborts open uploads - idle (no start/write) over 24 h (`STAGED_MAX_AGE_MS`): at start, on every - `uploadStart`, and every hour (`UPLOAD_SWEEP_INTERVAL_MS`). It never rejects - (a file it cannot delete is logged and tried again next sweep): a rejection - from its timer would stop the daemon, and one before `uploadStart` would fail - every new upload. - Sent uploads expire by the `uploadRetentionDays` web setting (default 30, `null` = never; `lib/web-settings.ts`, spec U6): main sends it to each daemon with the op `setUploadRetention` at sync startup, on every hello and when the setting changes (an older daemon's 501 is ignored, no protocol bump; other live-link failures retry with capped backoff). The daemon sweeps at startup and every 24 h, deleting regular files older than that by mtime from `local/uploads/` of active and archived sessions, and from only its own namespace under Windows' `/omp-local//uploads/`. It skips symlinked project, session, `local`, `uploads` and namespace directories as checked; concurrent directory swaps are outside this same-user threat model (U6). A running sweep re-reads the policy before unlink, so Never or a longer retention spares remaining files. `uploadAttach` stamps the hard link's mtime at attach time, or copies if stamping fails, so age counts from the send. Staged files keep the separate 24 h expiry and hourly sweep above. - Only Windows fallback attachments use `local://uploads//`; `uploadOwnerNamespace` derives the namespace from the canonical agent-directory path. Copied session UUIDs cannot share cleanup ownership, and archival/deletion of session metadata does not disable cleanup. Legacy flat files and foreign namespaces are preserved; moving the agent directory leaves the old namespace untouched (U6). This namespace is provenance for retention, not an authentication capability. - Retention also covers Files-panel uploads placed in those selected session-upload folders; workspace publication receipts do not exempt a destination from its folder's policy. - Stamp the staged inode before publishing any hard link of it (attach and Files-panel publication), so a concurrent retention sweep cannot capture its old age and delete the newly sent file. If timestamping fails, publish only a fresh exclusive copy; never expose an unstamped hard link. The sweep's per-file `lstat`→`unlink` and every step that puts a file at a name (attach link/exclusive create, publication rename/link) run under `withUploadNameLock` (`lib/hosts/uploads.ts`), so an overwrite cannot land between a stale stat and its unlink. The lock is per daemon process; a different process writing the same folder is not covered. - `uploadAttach` has a 10-minute op timeout (a 2 GiB EXDEV copy), not - `opTimeoutMs`. -- Cancels are durable (spec U4 "Durable cancel"): the tab always hands - `{op: "up_abort", id, host}` to the worker, which keeps it until the server - has it (link line until acked and resent on a resync; in `sse` mode a - `DELETE …?host=` with a 40 s deadline, retried until a 2xx or a 4xx other - than 408/429). Main keeps an `uploadAbort` its host could not take (503/504) - per host and resends it on that host's next hello (`onHostHello`). A Retry of - the same id supersedes it on every layer: a new `uploadStart` drops a kept - abort, an in-flight one that fails after the id is registered again is not - kept, and the worker drops its own pending cancel on a new upload of the id. - An id main does not register goes to the browser's `host` - if known. All of it is in memory: the hourly sweep is the backstop. -- Error codes: composer uploads use `upload_id_conflict` (another upload has - this id); `upload_conflict` stays the file manager's. -- SSE mode uses the same registry over HTTP (`/api/uploads`). `requestOwner(req)` - (`lib/web-auth.ts`) still binds upload start, chunks and cancel to the original - login, and still binds browser-link resume; it is not made stable across login. - Attachment is also allowed by a server-issued, upload-specific completion proof - in the same installation/auth scope and within the existing 24-hour lifetime. - Main stores it privately before reporting completion; completion replays reuse - it without renewing expiry. Never accept caller-supplied owners or receipts, - and never send proofs to the daemon/omp, public outbox snapshots or logs. -- `uploadFile().promise` returns `{proof?}`. Finished chips/drafts retain the proof; - Send/steer/follow-up pass the optional fourth `uploadProofs` argument through - IndexedDB, keepalive and Background Sync. The server validates that authority - and privately snapshots each upload's actual original owner for accepted - dispatch, including mixed owners and main restarts. Host/session/file checks - and submission fences remain. Legacy no-proof files remain original-owner-only. -- The live upload registry is in memory, but completed receipts/proofs are durable - until their existing expiry. A main restart no longer loses a finished-but-unsent - attachment. Switching chats aborts in-flight uploads; drafts keep only finished - ones and their proofs (`sessionStorage`). - -### open_file and `local://` -- The `open_file` host tool takes an absolute path, a workspace-relative path or a `local://` URL. `runHostTool` (`hooks/useAgentSession-stream.ts`) resolves a `local://` URL **before** a tab exists, with the id of the session that called (`useAgentSession` for the viewed session, `AppShell` for a call from another one), through `GET /api/sessions/[id]/local-file`: the tab, its de-duplication and the cross-session confirmation all see the absolute path and `sourceSessionId`, so two sessions' `local://note.md` are two files. -- `lib/session-local-files.ts` resolves on the **owning Node daemon**, without consulting main's live-session or host state. Main's `GET /api/sessions/[id]/local-file` checks shared URI syntax (early 400), uses `resolveWorkspaceHost(undefined, id, { followAlias: true })` to canonicalize a live alias to its current ID and file, and calls the additive `resolveLocalFile(id, uri, sessionFile)` workspace op. An older daemon answers 501 `workspace_unsupported`; there is no main-disk fallback. The daemon applies its native URI rules and uses a live-file hint only after checking realpath containment in its sessions directory and the header's session ID; otherwise its own `resolveSessionPath` decides, including any custom file its index knows. `sessionLocalRoot` (`lib/omp/paths.ts`) retains omp's Windows temp fallback. File GET and watch carry the tab's own ID (and the live file hint only while the wrapper still reports that ID) to `authorizeFileAccess` and `sessionLocalRootContaining`. Never derive the root from cwd or the viewed session, and never read artifact contents in the resolver. The response path must be absolute, and confinement compares native paths without rewriting literal POSIX backslashes. -- `lib/local-uri.ts` reads the URL as omp 18.3.1+'s `extractRelativePath`/`validateRelativePath` do: the authority is the first path segment and is decoded once, with the rest (`local://100%25.md` is `100%.md`; a second decode would open another file); query and fragment are dropped; a segment that is `..` or starts with `..` (`..hidden.md`, `a/..b`), and an absolute suffix (`/x`, `\x`; on Windows also `C:x`), are refused. A colon is an ordinary character off Windows. The resolver answers in this order, so the agent hears it before any tab opens: 503 `local_root_unavailable` when the session's existing local root cannot be canonicalized (only a missing root counts as having nothing to escape), 403 for a path that leaves the root through a symlink (or a link loop), 404 `file_not_found` for a file that is not there, 400 `not_a_file` for a directory (`local://.`, `local://dir/`) or other non-file. -- `runHostTool` bounds the lookup with `LOCAL_FILE_LOOKUP_TIMEOUT_MS` (an `AbortController` and timer, not `AbortSignal.timeout`): a stalled lookup reports an error to the agent. Viewed-chat and global handlers own request-scoped controllers; native `host_tool_cancel`, request withdrawal and unmount abort pending lookups and suppress late open/confirmation and result callbacks. Cross-session cancellation uses the privately captured original source alias, keyed with the request ID, so another session's identical ID is unaffected. Confirmed identity moves keep the mounted request valid. The shell rechecks the committed session and Settings view at completion before using its existing confirmation. A thrown opener becomes `isError`, never a false “Opened” result. - A resolved `local://` tab stores the route's returned `sessionId` (the canonical owner) as `sourceSessionId`; the `host_tool_result` still goes to the calling id. A subscription error (the viewed chat's `session` stream or AppShell's `host-tools` stream) also aborts pending lookups: the server already rejected those calls when the subscription left, and the `host_tool_cancel` it emitted had no listener. - File reads, downloads and watches (`/api/files`, the `file` channel) keep the tab's own `sessionId` and never follow an alias: a tab opened for A stays confined to A's root after omp later moves A to B, and the live wrapper's file is passed as a hint only while it still reports that id. Only the `local://` lookup uses `resolveWorkspaceHost(..., { followAlias: true })`. -- Every file-tab URL uses `getFileApiUrl` with that tab's host ID and source session ID, including both Download controls. `authorizeFileAccess` grants session-local access only for reads, downloads and file watch, never listing. It confines realpaths even when the transcript names the path. Both it and the resolver apply `isOmpSecretFile`: owned credentials and symlink/hard-link aliases stay private, while independent `agent.db` or `models.yml` artifacts remain usable. -- The daemon file watch re-authorizes its target and rejects a pathname swapped for an outside symlink without reporting the outside file's metadata. Its error ends the subscription; a fresh subscription performs authorization again. -- A session-local absolute target takes precedence over workspace-relative fallback, even if a workspace contains a file mirroring its entire pathname or the artifact is missing. Apply its local-root realpath restriction even when a broader config/workspace root also admits the path. - -### Voice transcription jobs (`lib/stt-jobs.ts`, `/api/stt`, `hooks/useDictation.ts`) -- The browser never waits on the STT endpoint: `POST /api/stt` keeps the - recording in memory and starts a job; the hook polls `GET /api/stt/[jobId]` - (proxies with ~30s timeouts would otherwise return HTML 504s). Job failures - are 200 payloads for the same reason. -- Jobs carry the composer scope (`draftKey`: session id, or `newChatDraftKey`: - `new:` here, `new::` for a fresh chat on a remote host). The - hook adopts the newest job for its scope on mount, focus, visibility and - every 4s while visible and idle, so another browser can play (`/audio`), - retry (`POST`) or discard it. Leaving the scope stops following without - discarding. -- A finished job is delivered only by claim: - `DELETE ?claim=&owner=` returns the text to the - first claim token (repeatable with the same token); polls never carry text, - and other composers see `gone` and stand down silently. A claim on an - unfinished job is a no-op; a `DELETE` without `claim` discards and aborts - the upstream request. -- Two tokens, never merged. The tab token (sessionStorage) identifies the - job owner: it survives genuine-navigation composer remounts (a confirmed - Edit identity move keeps the composer mounted), gets the 15s first claim, - and alone gets the send/queue choice back. A duplicated tab copies it, so - exclusivity comes from the claim token, which is per hook instance. -- The send/queue choice (`after`: send | steer | followup) is uploaded with - the recording, kept on the job, and returned with the owner's claim. Never - keep it only in component state: a session switch remounts the composer and - loses it. A non-owner claim only inserts, since that composer holds its own - draft and attachments. -- Store is per process (`globalThis` map) with caps (4 pending, 20 live) and - TTLs; a server restart loses jobs, and the hook then re-uploads its local - copy if it has one. -- Without `OMP_WEB_STT_ENDPOINT`, `OMP_WEB_STT_MODEL` names an omp STT model - (e.g. `openai-codex/codex-transcribe`, the ChatGPT subscription) and jobs - go through `lib/omp/auth-gateway.ts` as base64 JSON — so the gateway's 25MB - body cap limits audio to 18MB there. omp-web never reads omp credentials. +- Images and text files go inline within the inline budgets (`lib/image-attachments.ts`, `lib/chat-attachments.ts`); everything else, an image switched to **As file**, and anything over a budget is uploaded (2 GiB per file, 20 per message, `lib/upload-limits.ts`). +- Uploads land in a staging dir on the **session's host** (`lib/hosts/uploads.ts`, `/tau/uploads/`), never on main. The prompt carries `uploads: [id]`; `runAgentCommand` attaches each through `uploadAttach` (hard link into `/local/uploads/`, never overwriting; copy on EXDEV; 10-minute op timeout) and appends an "Attached files" block naming each file by its absolute path. Ids stay registered until the prompt reaches pi. Attachment preparation holds the wrapper's pending-command protection, and later commands await the send fence (any alias of the wrapper). A prompt pushed past the link's line cap is refused 413 `request_too_large` and the uploads stay registered. +- **Transfer:** HTTP only. `POST /api/uploads` starts or resumes (`{ received, done }`), `PUT /api/uploads/[id]?offset=N` sends a chunk of at most 1 MiB, answered once the host acked it (409 `upload_offset` with `received`). Main relays the bytes as blob units on the host link (`putUploadChunk`, `lib/uploads.ts`); the host's `upload_ack`s are the flow control, and main stops an upload that runs too far ahead (429 `upload_window_exceeded`). Each host `uploadStart` carries a fresh `attempt`; superseded-attempt acks are discarded. Start/attach/abort share one per-id queue. +- `uploadFile` (`lib/event-stream.ts`) resumes 502/503/504 and network failures itself (same id, back-off, "Reconnecting…") until an outage reaches 5 min (`RESUME_GIVE_UP_MS`), then settles `upload_stalled` so Retry is usable. A bfcache pagehide fails with 410 and a new upload id. +- Limits on main: 32 unfinished uploads per owner (429 `too_many_uploads`); an entry idle 10 min leaves the registry (a later start re-registers it). The daemon's `sweep` deletes staged files and aborts open uploads idle over 24 h (`STAGED_MAX_AGE_MS`), at start, on every `uploadStart` and hourly; it never rejects. +- **Sent-upload retention** (`uploadRetentionDays`, default 30, `null` = never): main sends it with `setUploadRetention` at start, on every hello and on change (`upload-retention-sync.ts`); the daemon (`upload-retention.ts`) sweeps at start and every 24 h, deleting regular files older than that from `local/uploads/` of active and archived sessions, and from its own namespace of Windows' `/tau-local//uploads/` (`uploadOwnerNamespace`). It skips symlinked directories and re-reads the policy before each unlink. Attach stamps the staged inode before hard-linking it; otherwise it writes only an exclusive copy. Sweep unlinks and every attach step that puts a file at a name run under `withUploadNameLock` (per daemon process). Files-panel publication cannot reach session upload folders (they are under the agent directory), so it neither stamps nor locks. +- **Durable cancels:** the tab hands `{op:"up_abort", id, host}` to the worker, which sends `DELETE /api/uploads/[id]?host=` (40 s deadline) until a 2xx or a 4xx other than 408/429. Main keeps an abort its host could not take and resends it on that host's next hello. A Retry of the same id supersedes it everywhere. +- Codes: `upload_id_conflict` (composer), `upload_conflict` (file manager). +- **Ownership:** `requestOwner(req)` (`lib/web-auth.ts`) binds start, chunks and cancel to the login. Attachment also accepts a server-issued completion proof (see the outbox) in the same installation/auth scope within 24 h; never caller-supplied owners or receipts. `uploadFile().promise` returns `{proof?}`; finished chips and drafts keep it. Completed receipts are durable until expiry, so a main restart does not lose a finished, unsent attachment. Switching chats aborts in-flight uploads. + +### open_file +- The `open_file` host tool takes an absolute or workspace-relative path. pi has no `local://` scheme, and tau hands the agent none: the "Attached files" block names each upload by its absolute path. +- File reads, downloads and watches carry the tab's own `sessionId` and never follow an alias. Every file-tab URL uses `getFileApiUrl` with the tab's host and source session. `authorizeFileAccess` also admits the session's own local directory (`sessionLocalRootContaining`, `lib/session-local-files.ts`, on the owning daemon) for reads, downloads and watch only (never listing), confined by realpath, and applies `isPiSecretFile`. The watch re-authorizes its target and ends on a swap. + +### Voice transcription (`lib/stt-jobs.ts`, `/api/stt`, `hooks/useDictation.ts`) +- Configured only by `TAU_STT_ENDPOINT` (with `TAU_STT_KEY`, `TAU_STT_MODEL`); without it dictation is off. +- The browser never waits on the endpoint: `POST /api/stt` keeps the recording in memory and starts a job; the hook polls `GET /api/stt/[jobId]` (job failures are 200 payloads, so proxy timeouts never surface as HTML). +- Jobs carry the composer scope (`draftKey`; `new:` or `new::` for new chats); the hook adopts the newest job of its scope on mount, focus, visibility and every 4 s while visible, so another browser can play, retry or discard it. +- Delivery is by claim: `DELETE ?claim=&owner=` returns the text to the first claim token; polls never carry text. The tab token (sessionStorage) identifies the owner, which gets a 15 s first claim and the stored send/queue choice (`after`, kept on the job, never only in component state). A `DELETE` without `claim` discards and aborts. +- The store is per process (caps: 4 pending, 20 live, TTLs); a restart loses jobs and the hook re-uploads its local copy. ### Completion sound -- `hooks/useAudio.ts` stores the toggle in `localStorage` and reuses one `AudioContext`. -- Browser autoplay policy means sound must be unlocked from a user gesture; `ChatInput` calls the unlock hook from interactive controls, and `ChatWindow` plays the tone from `onAgentEnd`. +`hooks/useAudio.ts` stores the toggle (`tau-sound-enabled`) and reuses one `AudioContext`, unlocked from a user gesture in `ChatInput`; `ChatWindow` plays the tone from `onAgentEnd`. ### Notifications (`lib/notification-*.ts`, `public/sw.js`, Settings → Notifications) -- Detection runs on the server in `AgentSessionWrapper.handleFrame` (and - `handleProcessExit` for crashes), so sessions no tab watches still notify. - `createNotificationDetector()` only inspects top-level frames; subagent - activity is wrapped in `subagent_*` frames and never notifies. "Completed" - fires on `session_settled` (not `prompt_result`), so background work started - by the prompt is done too; a failed or aborted last prompt suppresses it. - On a shared daemon channel the other servers get that prompt's outcome as - `peer_prompt_outcome` (no command id), which only feeds their detector, so the - elected notifier hears a failure whichever server prompted. - Auto-approved tool confirmations return before the hook and never notify. - omp sends `retry_fallback_applied` before the `auto_retry_start` of the same - failure, so the detector holds a reason-less fallback until that frame. - Failures also arrive as omp-web's own `prompt_error` (failed `response`) and - `process_exit` frames; the detector reports one failure per run. -- A session omp moved to a new file keeps its old ids as `aliases` on the - event, so a tab still showing an old id counts as viewing it. -- Presence and streams are separate on purpose. Presence: each tab reports - `{clientId, deviceId, visible, sessionId}` to `/api/notifications/presence` - (visibility/session change, input after idling, every 30 s while present; - expires 60 s after receipt). `visible` means visible AND input within 3 min. - `sessionId` is null while full-page Settings hides the chat. Streams: the - tab's open SSE connections (`attachNotificationClient`), which reconnect and - overlap independently of presence. `clientId` is per page load, `deviceId` - per browser (`localStorage`). Reports carry a per-page `seq`; the server - drops one older than the stored report (requests can arrive out of order). - Prefs PUTs run one at a time and read the prefs when sent, for the same reason. -- Routing (`routeNotification`, unit-tested): a visible tab on the session - drops the event everywhere (presence only, so a reconnecting stream cannot - leak it); else if a visible tab with an open stream exists, `whenActive: - "toast"` devices get a toast on their active tabs only; else push (subscribed - devices) or in-page `showNotification` (tabs with an open stream). -- The server decides before pushing: iOS revokes push permission for pushes - that display nothing, so `public/sw.js` always shows what it receives. -- Notifications have their own `notifications` channel (`clientId` = the - tab's notification client id), opened by `useNotifications` in `AppShell`, - so a tab stays reachable on every view, Settings included. A tab on - Settings is visible, so it also counts as active. -- Prefs and push subscriptions are per device, in `localStorage` and mirrored to - the SQLite notification store in omp-web's data dir - (`lib/notification-store.ts`, server-only; mode 0600 because it also holds - the VAPID private key; WAL with a busy timeout). It also keeps the - notification history. An installed server and `npm run dev` sharing the agent - dir share it safely; the first open imports and deletes the old - `notifications.json`. Push text is - rendered server-side in the device's locale. Browsers with saved settings (enabled or not) sync on load; never-configured browsers do not. -- A crash notifies "Run failed" while a run is live or while background work - started by it has not settled yet (`unsettled`, cleared by `session_settled`). -- The Settings test button pushes through the server for subscribed devices - (502 with the push service's answer on failure) and shows a local - notification otherwise, or a toast where none are allowed. -- `/sw.js` and `/badge-96.png` are exempt from the password gate (`proxy.ts`): - browsers re-fetch the worker for updates without the session cookie. -- Notification clicks survive an expired sign-in: `proxy.ts` sends `/?session=…` - to `/login?next=/?session=…`, and `LoginForm` returns there (only `/?…` - targets are accepted). The worker navigates non-app windows to the session - URL; the app falls back to that URL when `/api/sessions` cannot be read. +- Detection runs on the server in `AgentSessionWrapper.handleFrame` (and `handleProcessExit`), so unwatched sessions notify. `createNotificationDetector()` inspects top-level frames only (subagent frames never notify). "Completed" fires on `session_settled`; a failed or aborted last prompt suppresses it. Other servers on a shared channel get the prompt's outcome as `peer_prompt_outcome`. Failures arrive as `prompt_error` and `process_exit`; one failure per run. A crash notifies "Run failed" while a run or its background work is unsettled. +- **Presence vs streams.** Tabs report `{clientId, deviceId, visible, sessionId, seq}` to `/api/notifications/presence` (on change, input after idling, every 30 s; expires 60 s after receipt; `visible` = visible and input within 3 min; `sessionId` null while Settings hides the chat; an older `seq` is dropped). Streams are the tab's open `notifications` subscriptions. Prefs PUTs run one at a time. +- **Routing** (`routeNotification`): a visible tab on the session drops the event everywhere; else, with a visible connected tab, `whenActive: "toast"` devices get a toast on their active tabs; else push (subscribed devices) or in-page `showNotification`. The server decides before pushing (iOS revokes permission for silent pushes; `sw.js` always shows what it receives). +- Prefs and subscriptions are per device (`localStorage`, mirrored to the SQLite store in `/tau/`, 0600, WAL; it holds the VAPID key and the history). Push text is rendered server-side in the device's locale. +- `/sw.js` and `/badge-96.png` are ungated. Clicks survive an expired sign-in: `proxy.ts` sends `/?session=…` to `/login?next=…`, and `LoginForm` accepts only `/?…` targets. +- The history (`lib/notification-history.ts`, `/api/notifications/history`) keeps the newest 100 of every type some device enabled, already read when a visible tab shows that session; shown by `NotificationBell` (desktop popover) and the right panel's Notifications tab (mobile). Entries become read when the list closes, on Mark all as read or when opened (`OPEN_SESSION_EVENT`, `tau-open-session`); a reused id (`:`) is unread again. ## Git history and PR landing rules -- **Never rewrite `main`'s history** — no force-push, `filter-branch`, rebase - of already-pushed commits, or `reset --hard` followed by a force-push — unless - the user explicitly asks for exactly that, after being told what it affects - (every rewritten commit gets a new hash, forks and clones diverge). A cosmetic - flaw such as a badly worded commit title is not worth it; leave it. -- Never push or rewrite someone else's branch. Contributors' commits keep their - original hashes and authorship. -- Land PRs with a squash or rebase merge so each change is one commit with a - normal title (`fix(scope): ...`, matching the surrounding log). Do not create - throwaway integration branches (`scratch`, `pr-NNN`) and merge PR branches - into them: git's auto-titles (`Merge branch 'pr-200' into scratch`) end up in - the permanent history. If PRs conflict with each other (usually - `CHANGELOG.md`), ask the authors to rebase, or resolve on a properly named - branch and write real commit messages. -- Before merging a PR: CI green on the current head, mergeable, and diff read. - Pass the head SHA to the merge so a late push is not merged unseen. - -## omp Session File Format (v3) - -Location: `~/.omp/agent/sessions//_.jsonl` +- **Never rewrite `main`'s history** (no force-push, `filter-branch`, rebase of pushed commits, or `reset --hard` plus force-push) unless the user explicitly asks for exactly that after being told what it affects. A badly worded commit title is not worth it. +- Never push or rewrite someone else's branch. Contributors' commits keep their hashes and authorship. +- Land PRs with a squash or rebase merge so each change is one commit with a normal title (`fix(scope): ...`). No throwaway integration branches (`scratch`, `pr-NNN`): their auto-titles end up in history. If PRs conflict (usually `CHANGELOG.md`), ask the authors to rebase, or resolve on a properly named branch. +- Before merging: CI green on the current head, mergeable, diff read. Pass the head SHA to the merge. + +## Session File Format (pi, version 3) + +Location: `/sessions/----/_.jsonl` +(timestamp: ISO-8601 with `:` and `.` replaced by `-`). ```jsonl -{"type":"title","v":1,"title":"...","source":"...","updatedAt":"...","pad":" ..."} ← fixed 256-byte slot {"type":"session","version":3,"id":"","timestamp":"...","cwd":"/path","parentSession":"/abs/path/to/parent.jsonl"} -{"type":"model_change","id":"<8hex>","parentId":null,"provider":"...","modelId":"...","timestamp":"..."} -{"type":"message","id":"<8hex>","parentId":"<8hex>","message":{"role":"user","content":"..."}} -{"type":"message","id":"<8hex>","parentId":"<8hex>","message":{"role":"assistant","content":[...],...}} -{"type":"message","id":"<8hex>","parentId":"<8hex>","message":{"role":"toolResult","toolCallId":"...","content":[...]}} +{"type":"model_change","id":"<8hex>","parentId":null,"timestamp":"...","provider":"...","modelId":"..."} +{"type":"message","id":"<8hex>","parentId":"<8hex>","timestamp":"...","message":{"role":"user","content":"..."}} +{"type":"message","id":"<8hex>","parentId":"<8hex>","timestamp":"...","message":{"role":"assistant","content":[...],...}} +{"type":"message","id":"<8hex>","parentId":"<8hex>","timestamp":"...","message":{"role":"toolResult","toolCallId":"...","content":[...]}} {"type":"compaction","id":"<8hex>","parentId":"<8hex>","summary":"...","firstKeptEntryId":"<8hex>","tokensBefore":N} +{"type":"session_info","id":"<8hex>","parentId":"<8hex>","timestamp":"...","name":"..."} +{"type":"custom","id":"<8hex>","parentId":"<8hex>","customType":"client-message-entry","data":{...}} ``` -- Line 1 is a fixed-width 256-byte padded title slot, rewritable in place. - Old pi files may lack it — the `{"type":"session"}` header is then line 1. -- Entries form a tree via `(id, parentId)`. Additional entry types - (`title_change`, `session_init`, `mode_change`, `ttsr_injection`, ...) must - be tolerated by readers. -- Large payloads (images) are externalized to the content-addressed blob store - at `~/.omp/agent/blobs` and referenced from entries. - -`entryIds[]` in `SessionContext` is a parallel array to `messages[]` — maps each displayed message back to its `.jsonl` entry id, used for fork and navigate_tree calls. +- The `{"type":"session"}` header is pi's first line; pi's session listing skips a file whose first entry is not a + header. `lib/pi/session-files.ts` migrates v1/v2 files in memory (`CURRENT_SESSION_VERSION` = 3). +- Entries form a tree via `(id, parentId)`; the leaf is the last entry. Other types (`thinking_level_change`, `label`, + `branch_summary`, `custom_message`, `custom`, `session_info`, ...) must be tolerated; `session-reader.ts` renders + `message` and `custom_message` and ignores the rest. +- pi names a session with `session_info` entries (the latest wins, an empty name clears it). tau renames a live + session through pi's `set_session_name`; a file no pi holds gets one appended `session_info` entry under the last + entry (`setSessionTitle`), never anything before the header. The listing scans the file for the latest one (resumed + from the old end when the file grew); archived sessions are named from the first 128 KiB only. +- tau's own entries: `custom` `client-message-entry` / `client-message-resolution` (message identity and origin) and + `custom` `tau_btw` (side questions). +- A session's artifacts (subagent transcripts, `local/`) live in the sibling directory `/`. + +`entryIds[]` in `SessionContext` is parallel to `messages[]`: each displayed message's entry id, used for fork and Edit. --- ## Design Tokens & UI Kit (`app/globals.css`, `components/ui/`) -Warm-paper (light) / warm-ember (dark) palettes; every text/background pair is -WCAG AA-verified (measured ratios noted in `globals.css` comments). Components -must consume these variables — no hardcoded colors. +Warm-paper (light) / warm-ember (dark) palettes; every text/background pair is WCAG AA-verified (ratios noted in +`globals.css`). Components must consume these variables, never hardcoded colors. ``` color: --bg --bg-panel --bg-hover --bg-selected --border --bg-subtle @@ -2119,41 +622,10 @@ depth: --shadow-card --shadow-pop --shadow-modal motion: --dur-fast (150ms) --dur-med (220ms) --dur-slow (320ms) --ease-out-warm ``` -`components/ui/` holds the shared primitives (built on `@base-ui/react`): -`primitives.tsx` (Dialog/Tooltip/Collapsible), `field.tsx` (form fields + -ConfirmDialog), `toast.tsx` (`toast.success/error/info`, mounted in AppShell). -Toasts are not stored. The notification list (`NotificationList`: the desktop -top-bar bell's popover, `NotificationBell`; the right panel's Notifications tab -on mobile only, `isMobile`) lists the server's -notification history (`lib/notification-history.ts`, a mirror of -`/api/notifications/history`): `publishNotification` records every -notification type some device has turned on (completed, input, error, model -switch), whether or not any tab or push receives it, already read when a -visible tab shows that session; the newest 100, so entries survive reloads and restarts and -every device sees the same list. The mirror loads on mount and when the tab -becomes visible (read marks and removals from other devices), adds events this -tab receives over SSE without a refetch, and reloads when the service worker -reports a push it showed. Entries store the `NotificationEvent` and render in -the viewer's language; clicking one, or Enter, marks it read and opens its -session (`OPEN_SESSION_EVENT`). -On desktop the bell carries the unread badge and its popover (base-ui Popover, -380px wide, at most 480px tall, the list scrolls) closes when a notification -opens a session. On mobile unread entries badge the right-panel toggle, which -then opens the Notifications tab. Entries become read when the user closes the -popover or leaves that tab (only the entries it -showed), uses Mark all as read, or opens the notification from its toast or -row, and a reused id (`:`) is unread again. Mark-read, remove -and clear update the list at once, then the server; a failed request reloads -it. Unread rows show a leading accent dot and a bold title; read -rows are dimmed. Toasts and Notifications entries dismiss on -a sideways touch/pen swipe (base-ui's toast swipe; `NotificationRow` for the -list) and carry `data-swipe-dismiss`, which the mobile sidebar gesture skips. -`useDragClickGuard` swallows the click that ends any drag on them, judged by -the whole travel. `createSwipeTracker` cancels a swipe the finger turned back -(16px from its farthest point), as on Android; for toasts the release is -converted into the `pointercancel` base-ui treats as "snap back". -The `onClick` option makes the whole card the action: a click outside its -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`. +`components/ui/` holds the shared primitives on `@base-ui/react`: `primitives.tsx` (Dialog/Tooltip/Collapsible), +`field.tsx` (form fields + ConfirmDialog), `toast.tsx` (`toast.success/error/info`, mounted in AppShell), +`ToggleSwitch.tsx`. Toasts are not stored. Toasts and notification rows dismiss on a sideways touch/pen swipe +(`data-swipe-dismiss`, skipped by the mobile sidebar gesture); `useDragClickGuard` swallows the click that ends a +drag; `createSwipeTracker` cancels a swipe the finger turned back (16px). The `onClick` option makes the whole card +the action. Icons come from `lucide-react`; do not add inline SVGs. The command palette (`CommandPalette.tsx`, +⌘K/Ctrl+K) is built on `cmdk`. diff --git a/CHANGELOG.md b/CHANGELOG.md index ec584eb1..3ac8ab75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,18 @@ # Changelog -All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this file. +All notable changes to **tau** (`@ompweb-dev/tau`) are documented in this file. Entries before the pi port describe ompweb, the omp-based product tau was forked from. --- ## [Unreleased] +### Changed + +- **tau runs sessions on pi.** Every session is a `pi --mode rpc` child (`@earendil-works/pi-coding-agent`, found on `PATH` or through `TAU_PI_BIN`) loaded with tau's companion extension (`lib/pi/tau-extension.ts`), which adds host tools, the `ask` dialog, message origins, `/btw`, history Edit and per-host provider logins. The ompweb omp runner, its pinned release and `fetch-omp` are gone. tau keeps pi's state in `~/.pi/agent` (sessions, `settings.json`, `models.json`), lists and installs pi packages and skills instead of omp plugins, and mirrors pi's configuration to cluster members. The host link starts again at protocol v1, and host software updates go through a separately versioned maintenance API. tau shares no state with ompweb: hosts, settings and sessions are set up anew. The routes `/api/omp-settings` and `/api/omp-version` are now `/api/pi-settings` and `/api/pi-version`, a host without pi reports `pi-missing`, and the unused `/api/omp-update` route is removed. +- **Browsers connect over server-sent events only.** The browser WebSocket link (`/api/events/link`) and the Settings → Interface & Behavior → **Browser connection** choice are gone; chat commands and uploads go over HTTP. A stored `browserTransport` setting is ignored. +- **pi trusts a project's files only inside a registered workspace.** Sessions in a workspace added in tau start with pi's `--approve`; elsewhere pi's own trust rules apply, and the Skills list leaves out the project skills pi would not load. +- **Removed controls pi has no command for:** the Fast and Slow composer toggles, interrupt-and-reply, and the MCP panel's live status, switches and Reload (pi's `/mcp` is never sent as a chat message). + ### Fixed - **Windows updates no longer fail when the update status is read while it is written.** Host update state, the server worker's status and upgrade plans retry their atomic replacement for a moment when a concurrent reader holds the file, as the server's own update state already did. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 69247457..7769bea3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,65 +1,92 @@ -# Contributing to omp-web +# Contributing to tau Thanks for your interest in contributing! +tau is a web UI for the [pi coding agent](https://www.npmjs.com/package/@earendil-works/pi-coding-agent). Read +`AGENTS.md` (development notes) and `DESIGN.md` (the porting contract) before larger changes. + ## Setup -- Node.js 24 or newer (the server runs on [Bun](https://bun.sh), which `npm install` provides) +- Node.js 24 or newer. The server runs on [Bun](https://bun.sh), which `npm install` provides (the `bun` npm package). +- pi, for live sessions: `npm i -g @earendil-works/pi-coding-agent` (tau is developed against pi 1.5.2). ```bash npm install -npx bun runner/scripts/use-omp-build.ts && (cd runner && npx bun install --frozen-lockfile) # ompweb's omp build; npm test needs it too -npm run dev # http://127.0.0.1:30178, Bun hot reload +npm run dev # http://127.0.0.1:30188, Bun hot reload (npm run dev:lan listens on 0.0.0.0) ``` -For live sessions, build the runner for this machine with `npx bun runner/scripts/build-binary.ts`: ompweb finds -`runner/release/ompweb-omp--` by itself (`OMP_WEB_OMP_BIN` overrides it). A stock `omp` does not -speak ompweb's channel. +tau finds pi through `TAU_PI_BIN` (a pi binary or a wrapper script), else `pi` on `PATH`. Without pi, session +browsing still works, the host reports `pi-missing` and live commands fail with `pi_not_found`. Tests that need a +real pi skip themselves when none is found. + +The dev server leaves this machine's host daemon to the production server, so "This machine" shows offline in dev. +See "Local daemon" in `AGENTS.md`. ## Checks (must pass before submitting) ```bash -npm run typecheck # type check -npm run lint # ESLint, zero warnings -npm test # unit tests (bun test --parallel) +npm run typecheck # tsc --noEmit +npm run lint # ESLint, no errors +npm test # bun test --parallel over app bin components hooks lib scripts server tests ``` -`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/`. +Run a subset with `bun test --parallel `. `--parallel` is required even for a few files: each file gets a +fresh module registry, and the test fixtures rely on that. -### React tests +`npm run build` bundles the browser app into `dist/`; the dev server never reads `dist/`. `npm run smoke` starts +the built server and its local host and checks them (`-- --package `, `-- --binary `, `-- --pi `). +`npm run build:binary` compiles a standalone release into `release/tau--/`. `npm run release:check` runs +typecheck, lint, tests, build and smoke in one go. -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` (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. +### Tests -Static HTML tests can continue using `react-dom/server`. Layout, scrolling, -and native browser navigation still require real-browser verification. -The jsdom dependency stays on 29.x for now; moving to a newer major is a separate change. +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. A test that touches pi's files sets `PI_CODING_AGENT_DIR` to a +private temporary directory before it imports the modules under test. + +For interactive components and hooks, import `tests/setup-dom.mjs` before `@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. + +Static HTML tests can continue using `react-dom/server`. Layout, scrolling and native browser navigation still +require real-browser verification. The jsdom dependency stays on 29.x for now; moving to a newer major is a +separate change. + +## Architecture rules + +- **No pi packages in tau's code.** The server and the host daemon never import pi's SDK or any `@earendil-works/*` + package. Every live session is a `pi --mode rpc` child that the session's host daemon spawns, and tau speaks pi's + RPC (JSON lines on stdio) through `RpcProcess` (`lib/pi/rpc-process.ts`). Session browsing parses pi's `.jsonl` + files directly (`lib/session-reader.ts`, `lib/pi/session-files.ts`). +- **The companion extension.** What pi's RPC lacks (host tools, the ask dialog, message identity, `/btw`, history + Edit, provider logins) lives in `lib/pi/tau-extension.ts`, which pi loads with `--extension`. It runs inside pi, + never in tau's server, and declares the pi types it uses locally. tau calls it with `/tau_` prompt commands + and it answers through `setWidget("tau", ...)` frames; see "pi's RPC and what tau adds" in `AGENTS.md`. +- **Every session runs through a host daemon**, this machine's included: the web server never spawns a session pi + (the one exception is the idle-killed utility pi in `lib/pi/rpc-utility.ts`). File and Git operations go through + `Host.workspaceOps` and run on the daemon that owns the files. +- **The daemon runs on Node.** `bin/tau-host.js` loads `lib/hosts/host-cli.ts` through `jiti`: modules the daemon + loads use relative imports (no `@/` alias) and no Bun APIs. The server (`server/`) runs on Bun. +- **Browser code** must not import `next/*` (use `lib/dynamic.tsx` and `lib/navigation.ts`) and must not call + `AbortSignal.timeout`, `AbortSignal.any` or `Promise.withResolvers`. +- **New API routes** are registered in `server/routes.ts` (see "Adding an API route" in `AGENTS.md`). ## Conventions -- **Styling**: use the design tokens in `app/globals.css` (colors, radius, - shadow, motion) — no hardcoded colors. Shared primitives live in - `components/ui/` (Dialog/Tooltip/Collapsible/field/toast, built on Base UI); - icons come from `lucide-react`. +- **Styling**: use the design tokens in `app/globals.css` (colors, radius, shadow, motion), no hardcoded colors. + Shared primitives live in `components/ui/` (Dialog/Tooltip/Collapsible/field/toast, built on Base UI); icons come + from `lucide-react`. - **i18n**: every user-facing string needs entries in all four dictionaries: - `lib/i18n/locales/{en,zh-CN,zh-TW,ja}.json`. -- **Architecture**: the ompweb server and daemon never import `@oh-my-pi/*` or `@earendil-works/*` - packages (Bun-only). Live agent features go through the `ompweb-omp` child process - (`runner/`) over ompweb's channel; see `DESIGN.md` and `AGENTS.md` for the full contract. + `lib/i18n/locales/{en,zh-CN,zh-TW,ja}.json`. An API error with a stable `code` is shown through `errors.`. ## Pull requests - Keep PRs focused; describe the user-visible change and how you verified it. -- For UI changes, include before/after screenshots in both light and dark - themes when practical. +- For UI changes, include before/after screenshots in both light and dark themes when practical. ## Reporting issues -Please use the issue templates and include your OS, Node version, omp version, -and browser. +Please use the issue templates and include your OS, Node version, tau version, pi version (`pi --version`) and +browser. diff --git a/DESIGN.md b/DESIGN.md index c2d1e12b..f50b2d46 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1,171 +1,190 @@ -# ompweb — Product & Architecture Contract +# tau — Product & Architecture Contract ## Purpose -ompweb is a local, browser-based workspace for the -[oh-my-pi](https://github.com/can1357/oh-my-pi) (`omp`) coding agent. It lets a -user browse the same local sessions they use in the terminal, continue live -work, configure supported OMP settings, and inspect project files without -creating a second agent runtime or a second source of truth. +tau is a local, browser-based workspace for the +[pi](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) coding agent +(`@earendil-works/pi-coding-agent`, tested with 1.5.2). It lets a user browse the +same local sessions they use in the terminal, continue live work, configure +supported pi settings, and inspect project files without creating a second agent +runtime or a second source of truth. -The project originated from [agegr/pi-web](https://github.com/agegr/pi-web) -(MIT), but it is maintained as an OMP-focused downstream. We preserve the -license and attribution, and selectively learn from upstream improvements; we -do not assume that Pi-specific implementation changes can be merged unchanged. +tau is forked from ompweb, the browser UI for oh-my-pi, which itself originated +from [agegr/pi-web](https://github.com/agegr/pi-web) (MIT). We preserve the +license and attribution. Upstream changes are ported for their behavior, not +merged unchanged. ## Product principles -1. **OMP remains authoritative.** Sessions, credentials, providers, and agent - behavior belong to omp (run as ompweb's own build of it, `runner/`). ompweb - must not invent a parallel data format or credential store. +1. **pi remains authoritative.** Sessions, credentials, providers, packages and + agent behavior belong to pi. tau must not invent a parallel data format or + credential store. 2. **Local-first by default.** The server binds to `127.0.0.1`; remote access 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. 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 - speculatively. +3. **Node-first installation.** A normal user installs Node.js 24+ and pi, then + runs `tau` from the npm package (`@ompweb-dev/tau`) or a release binary. The + npm package brings its own Bun for the web server, so users do not install Bun + themselves. tau never ships pi: it runs the `pi` on `PATH`. +4. **Native compatibility over imitation.** Prefer pi's RPC mode, its extension + API, its CLI and its 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 speculatively. 5. **A calm, capable workspace.** The UI should make active work, session - history, configuration, and project context understandable without hiding - the agent's state or expanding the app into a general remote-control plane. + history, configuration, and project context understandable without hiding the + agent's state or expanding the app into a general remote-control plane. ## Distribution and identity -- npm package and CLI command: `ompweb`. -- Default server address: `http://127.0.0.1:30177`. -- Existing `OMP_WEB_*` environment variables remain the configuration prefix - for compatibility: `OMP_WEB_HOSTNAME`, `OMP_WEB_NO_OPEN`, and - `OMP_WEB_OMP_BIN`. `OMP_WEB_PASSWORD` is accepted only as a migration step - (see the security contract). -- `PI_CODING_AGENT_DIR` and OMP's own directory conventions are - respected because they identify the user's existing OMP state. -- The web UI displays its own package version separately from the detected - installed OMP version; those versions may legitimately differ. +- npm package `@ompweb-dev/tau`; CLI command `tau` (plus the `tau-tray`, + `tau-launchd` and `tau-systemd` service helpers). Release binaries + `tau--` hold the server, `tau host` and `tau hash-password`. +- Default server address: `http://127.0.0.1:30187` (`-p`/`PORT`). +- Configuration uses the `TAU_*` prefix: `TAU_HOSTNAME`, `TAU_NO_OPEN`, + `TAU_PI_BIN` (the `pi` binary; default `pi` on `PATH`), `TAU_PASSWORD_HASH`, + `TAU_TRUSTED_HEADER_SHA256`, `TAU_STT_*`, `TAU_DISABLE_AUTOUPDATE`. + `TAU_PASSWORD` is accepted only as a migration step (see the security contract). +- `PI_CODING_AGENT_DIR` (default `~/.pi/agent`) is respected + because it identifies the user's existing pi state. tau's own state lives in + `/tau/` and `/tau-settings.json`. +- The UI displays its own version separately from the detected pi version; those + versions may legitimately differ. ## Runtime architecture ``` Browser - │ HTTP / Server-Sent Events + │ HTTP / Server-Sent Events (one SharedWorker EventSource per browser) ▼ -ompweb (Bun server, started by the Node launcher) - ├─ reads native OMP session files and selected configuration - ├─ serves allow-listed project files - └─ starts one `ompweb-omp --headless` child per active session - │ ompweb channel, NDJSON over stdio +tau (Bun server, started by the Node launcher) + ├─ serves the SPA, the API and the password gate + └─ reaches every machine through its `tau host` daemon (the link) + │ ▼ - ompweb's own omp build (runner/) and the existing ~/.omp/agent state + tau host ── one `pi --mode rpc --extension …/tau-extension.ts` child per active session + │ (pi's RPC JSONL over stdio) + ▼ + pi and the existing ~/.pi/agent state ``` -### The omp boundary - -OMP SDK packages are Bun-only TypeScript and import Bun APIs. Importing -`@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, the ompweb server and daemon must not add those runtime dependencies. - -Live work goes through ompweb's own omp build, `runner/`, compiled against the -fork's integration build: an `ompweb-dev/oh-my-pi` release that is an upstream omp -release plus the PRs the fork carries (among them `runSessionHost`, which the -headless mode needs), pinned to one release in `runner/omp-build.json` and -re-pinned to the newest one by each ompweb release. The runner replaces omp's -launch command: its session factory connects every session to `ompweb host` -over ompweb's channel. The host receives the same `AgentSession` events and -calls the same session methods omp's TUI does, so nothing depends on omp's RPC -mode. A session started from the runner's TUI connects to the daemon's Unix -socket and shows up live in the web; dialogs open on both sides and the first -answer wins. Each ompweb release attaches its runners (`ompweb-omp-`), -and every install downloads the one of its own version -(`lib/omp/runner-fetch.ts`), so omp updates with ompweb. The design and the wire are in -`docs/specs/2026-11-12-omp-runner-design.md`; the fork build in -`docs/specs/2026-11-12-omp-build-in-ompweb-design.md`. +### The pi boundary + +pi's SDK packages are TypeScript tied to pi's internals. Importing +`@earendil-works/*` (or `@oh-my-pi/*`) into the tau server or daemon would tie tau +to those internals and make the application unreliable, so neither process may +depend on them at runtime. Rules tau needs from pi (agent-directory resolution, +skill discovery, `settings.json` and `models.json` shapes) are replicated in +`lib/pi/` and `lib/skills-service.ts`, pinned to the pi version they mirror. + +Live work goes through pi's own RPC mode: `spawnPiTransport` +(`lib/pi/rpc-process.ts`) runs `pi --mode rpc --extension ` +with the sanitized child environment, and `RpcProcess` speaks pi's NDJSON +commands, responses and events. What pi's RPC mode does not cover goes through +tau's companion extension, `lib/pi/tau-extension.ts`, which pi loads from tau's +package directory (`TAU_PACKAGE_DIR`, never the session's cwd) and which uses +only pi's public extension API: host tools and the `ask` dialog bridged over +`extension_ui_request` input dialogs (`__tau_host_tool__`, `__tau_ask__`), message +identity and origin (`/tau_meta`, recorded as `client-message-entry` custom +entries), `/btw` side questions (`/tau_btw`), history Edit (`/tau_edit`, +`navigateTree`) and provider logins (`/tau_auth`, through pi's own model +runtime). `lib/rpc-manager.ts` maps tau's command set onto these (for example +`abort_and_restore_queue`, `get_btw_history`). Package operations (`pi list`, +`pi install`, ...) run the installed `pi` CLI (`lib/pi/plugins-cli.ts`); skills +are listed by a pure-Node scan that mirrors pi's discovery, plus `pi list` for +package skills (`lib/skills-service.ts`). ### The Host seam -Every machine-local action of a session goes through one interface, -`Host` (`lib/hosts/host.ts`): spawning `ompweb-omp --headless`, checking that a -session file exists, invalidating cached session lists, and the -file-reading operations behind the session and project routes. The web server -has no direct path to any machine, its own included: it reaches every host -through the link described below. The implementation on the web server is -`RemoteHost`; the daemon (`ompweb host`) runs the other side, `LocalHost`, on -the machine whose omp it owns. +Every machine-local action of a session goes through one interface, `Host` +(`lib/hosts/host.ts`): spawning pi, checking that a session file exists, +invalidating cached session lists, and the file-reading operations behind the +session, project and workspace routes. The web server has no direct path to any +machine, its own included: it reaches every host through the link described +below. The implementation on the web server is `RemoteHost` (`hub.ts`); the +daemon (`tau host`) runs the other side, `localHost` (`local-host.ts`), on the +machine whose pi it owns. ``` -Browser ─▶ ompweb ◀── link (loopback) ── ompweb host ── spawn ompweb-omp --headless (stdio) - ◀── link (WebSocket) ── ompweb host on another machine - └─ spawn ompweb-omp --headless +Browser ─▶ tau ◀── link (loopback WebSocket) ── tau host ── spawn pi --mode rpc (stdio) + ◀── link (WebSocket) ── tau host on another machine + └─ spawn pi --mode rpc ``` -"This machine" is the host with the fixed id `local`, linked to the daemon -that the service installers set up next to the web service. Because the daemon -owns the omp processes, restarting or redeploying the web server does not end -a run: the restarted server adopts the live children from the daemon's hello, -with their open blocking requests replayed. A direct spawn path would tie -every run to the web server's lifetime, which is why none exists. - -The omp boundary above holds on every machine: a remote machine runs its own -runner build, its own `~/.omp/agent` and its own credentials, unless sharing is -turned on for that host (Settings → Hosts): then its sessions use the server's -provider logins through `omp auth-broker serve`, and the host never gets a -refresh token. ompweb only routes. `RpcProcess` takes its byte pipe -(`RpcTransport`) from the host, so the -session wrapper, event streams, notifications and queue handle frames without -knowing where omp runs. Session routes address a session by id; the owning -host resolves the file path, so a remote path never reaches the serving -machine's filesystem. - -The link is one WebSocket that the `ompweb host` daemon opens to the -server: text frames carry the messages in both directions and binary frames -carry large op results (daemon → server). 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 -a shell on that host. Tokens are stored hashed, shown once, and revocable, and -the daemon requires `https://` except for loopback or an explicit -`--allow-http`. The full protocol is in -`docs/specs/2026-10-28-remote-hosts-design.md`. +"This machine" is the host with the fixed id `local`, linked to the daemon that +the service installers set up next to the web service (production also starts a +missing one itself, `local-daemon-start.ts`). Because the daemon owns the pi +processes, restarting or redeploying the web server does not end a run: the +restarted server joins the live children from the daemon's hello, with their open +blocking requests replayed. One daemon may link several web servers; it owns +session lifecycle and fans events out to every joined server. A direct spawn path +would tie every run to the web server's lifetime, which is why none exists; the +short-lived utility pi (`lib/pi/rpc-utility.ts`) is the one deliberate exception, +and it is not a session. + +The pi boundary holds on every machine: a remote machine runs its own pi, its own +`~/.pi/agent` and its own credentials. A host that joins the cluster (Settings → +Hosts) additionally receives this machine's pi configuration +(`settings.json` minus machine-local keys, `models.json`, `mcp.json`, context +files, skills; `lib/hosts/cluster-config.ts`), applied by its daemon; credentials +are never mirrored. tau only routes. `RpcProcess` takes its byte pipe +(`RpcTransport`) from the host, so the session wrapper, event streams, +notifications and queue handle frames without knowing where pi runs. Session +routes address a session by id; the owning host resolves the file path, so a +remote path never reaches the serving machine's filesystem. + +The application link is one WebSocket that the `tau host` daemon opens to the +server (`/api/hosts/link`, link protocol v1, `lib/hosts/link-protocol.ts`): text +frames carry sequenced, acked messages in both directions, large lines travel in +pieces, and binary frames carry large op results (daemon → server) and upload +bytes (server → daemon). The daemon forwards pi's NDJSON unchanged and answers a +fixed allow-list of host operations (`HOST_OP_NAMES`); there is no generic exec +or file-read operation. Updates and inventory use a second, separately versioned +WebSocket, the maintenance API v1 (`/api/hosts/maintenance`, +`lib/hosts/maintenance-protocol.ts`: `status`, `listSessions`, `checkUpdates`, +`updateSoftware`), so an upgrade still reaches a host whose application protocol +differs. A host is trusted like the serving machine: control of the server or of +a host token is a shell on that host. Tokens are stored hashed, shown once, and +revocable, and the daemon requires `https://` except for loopback or an explicit +`--allow-http`. The full protocol is in `docs/specs/2026-10-28-remote-hosts-design.md`. ## Data and mutation boundaries -### OMP-owned state +### pi-owned state -- `~/.omp/agent` is the source of - truth for sessions, configuration, models, skills, plugins, and blobs. -- `agent.db` contains authentication data. ompweb never reads or writes it; - authentication actions go through the `ompweb-omp` process. -- A live OMP process owns writes to its session file. ompweb routes supported - live actions through the runner's channel and never races a live file rewrite. +- `~/.pi/agent` (or `PI_CODING_AGENT_DIR`) is the source of truth for sessions, + `settings.json`, `models.json`, skills, packages and blobs. +- `auth.json` holds credentials. tau never reads or writes it itself; + authentication actions go through pi (`/tau_auth` in the companion extension, + run by a pi process). +- A live pi process owns writes to its session file. tau routes supported live + actions through RPC and the extension and never races a live file rewrite. ### Direct file access -Session browsing is implemented in pure Node against OMP JSONL files. The -reader tolerates the fixed title slot and older session shapes, resolves blob -references when needed, and builds the active branch context from the entry -tree. The session and project routes run it in the daemon of the session's host -(`session-ops.ts`), so the same code serves this machine and every linked one. +Session browsing is implemented in pure Node against pi's JSONL files. The reader +tolerates older session shapes, resolves blob references when needed, and builds +the active branch context from the entry tree. The session and project routes run +it in the daemon of the session's host (`session-ops.ts`), so the same code serves +this machine and every linked one. Direct session mutation is deliberately narrow and explicit: rename/title, archive, deletion, and required branch-parent maintenance. These writes are atomic where possible; archive or deletion stops the associated live process -first. ompweb does not provide a general editor for session JSONL or opaque OMP +first. tau does not provide a general editor for session JSONL or opaque pi state. -Models and allow-listed OMP settings use surgical YAML updates that preserve -unrelated content. Plugin operations run the installed `omp plugin` CLI. MCP +Models (`models.json`) and allow-listed pi settings (`settings.json`) use +surgical JSON updates that preserve unrelated keys (`lib/pi/models-config.ts`, +`lib/pi/settings-config.ts`). Package operations run the installed `pi` CLI. MCP configuration is project-local, validated before writing, and saved atomically. ### Reconnect and foreground catch-up Completed conversation history is identified by persisted session entry IDs. -Live `message_end` frames have no durable ID and can arrive before OMP writes -the entry, so they trigger catch-up rather than append an unidentified copy. -Streaming text, active tool output, and an optimistic user prompt remain -separate from confirmed history. +Live `message_end` frames have no durable ID and can arrive before pi writes the +entry, so they trigger catch-up rather than append an unidentified copy. +Streaming text, active tool output, and an optimistic user prompt remain separate +from confirmed history. `GET /api/sessions/:id/context?sync=1` returns a `SessionSyncResponse`: @@ -177,92 +196,91 @@ separate from confirmed history. - `context.messages` and `context.entryIds` remain aligned. `limit` is an integer from 1 to 200 (default 200); follow `hasMore` with the returned cursor. Only the selected page's image blobs are resolved. -- Existing `leafId`, `includePreCompaction`, `deferThinking`, and `deferMedia` - view parameters remain available. A historical view excludes live output. +- `leafId`, `includePreCompaction`, `deferThinking`, and `deferMedia` view + parameters remain available. A historical view excludes live output. - `live` contains the web-owned process's current partial message, active tool snapshots, and lifecycle flags, or null for a file-only session. Reading - history never starts an OMP process. A live process can supply its first - partial before its session file exists, but a missing file cannot erase a - nonempty confirmed cursor. + history never starts a pi process. A live process can supply its first partial + before its session file exists, but a missing file cannot erase a nonempty + confirmed cursor. - `live.responseObserved` retains positive visible-answer evidence for the - current run after completion, even before its entry is readable on disk. - New runs and process/session changes reset it; tool calls alone do not count. - -`GET /api/sessions/:id/context?boundary=1` returns only `{ entryIds }` for -the current active context. Prompt and interrupt dispatch use this fresh -ID-only boundary instead of downloading the transcript. It shares the history -index without hydrating message bodies or blobs and cannot be combined with -sync, pagination, or historical-view parameters. - -SSE events carry `web: { streamId, sequence }`. The stream epoch changes when -the native process or session identity changes. These values order live -snapshots; they are not a persisted replay journal or `Last-Event-ID` support. -Subscription precedes the `connected` cursor announcement. The client keeps -processing live events while history loads and applies snapshot fields only -when they cannot overwrite newer message, tool, or lifecycle state. + current run after completion, even before its entry is readable on disk. New + runs and process/session changes reset it; tool calls alone do not count. + +`GET /api/sessions/:id/context?boundary=1` returns only `{ entryIds }` for the +current active context. Prompt and interrupt dispatch use this fresh ID-only +boundary instead of downloading the transcript. It shares the history index +without hydrating message bodies or blobs and cannot be combined with sync, +pagination, or historical-view parameters. + +SSE events carry `web: { streamId, sequence }`. The stream epoch changes when the +native process or session identity changes. These values order live snapshots; +they are not a persisted replay journal or `Last-Event-ID` support. Subscription +precedes the `connected` cursor announcement. The client keeps processing live +events while history loads and applies snapshot fields only when they cannot +overwrite newer message, tool, or lifecycle state. Open/reopen, foreground/online, message completion, and persisted-file notifications share one coalesced catch-up loop. Pages are accumulated privately -and published only when the selected history is complete. Failed reads retain -the last complete cursor and displayed history. Overlapping full loads preserve -newer complete history rather than treating an intermediate page as authoritative. -Full initial loads and terminal metadata refreshes still update the branch tree. -A completion or persistence notification during an in-flight read schedules -one follow-up read from the newly returned cursor. Raw SSE completions never -append a second copy of an entry that the history response already includes. +and published only when the selected history is complete. Failed reads retain the +last complete cursor and displayed history. Overlapping full loads preserve newer +complete history rather than treating an intermediate page as authoritative. Full +initial loads and terminal metadata refreshes still update the branch tree. A +completion or persistence notification during an in-flight read schedules one +follow-up read from the newly returned cursor. Raw SSE completions never append a +second copy of an entry that the history response already includes. Unchanged history pages reuse a file-versioned offset index and seek only the requested message bodies. The in-memory index cache is bounded to 32 views and -32 MiB of charged metadata; it does not retain transcript bodies or increase -the existing 256 MiB raw-file cache budget or 1 GiB load ceiling. Cold indexes -and changed files require a full metadata scan. Growth alone is not proof of -an append: the same inode can be rewritten and then extended, so any file -version change invalidates offsets rather than trusting an unchecked prefix. -Failed reads never advance the confirmed cursor. +32 MiB of charged metadata; it does not retain transcript bodies or increase the +256 MiB raw-file cache budget or 1 GiB load ceiling. Cold indexes and changed +files require a full metadata scan. Growth alone is not proof of an append: the +same inode can be rewritten and then extended, so any file version change +invalidates offsets rather than trusting an unchecked prefix. Failed reads never +advance the confirmed cursor. File-only catch-up also refreshes model and thinking metadata without replacing -newer or pending channel choices. Replacement observer connections restore browser +newer or pending choices. Replacement observer connections restore browser registrations and the subagent roster only after successfully connecting. -Deploy the frontend and API support together; no native OMP upgrade is required. - ## Security contract - Bind loopback-only by default. A non-loopback hostname is an explicit opt-in. -- `OMP_WEB_PASSWORD_HASH` protects every route with a password-only sign-in - screen. Only a scrypt hash reaches the server (`ompweb hash-password`), - because every `omp` session inherits the server's environment and an agent - could print the password into its transcript, session file and - model-provider traffic. `--password`, or a plaintext `OMP_WEB_PASSWORD` next - to a hash, refuses to start. A lone `OMP_WEB_PASSWORD` is hashed by the - launcher, removed from the server's environment, and logged as a warning with - the hash to use instead; the server itself still refuses a plaintext. - Successful sign-in creates an HTTP-only, signed cookie with a 30-day expiry; - the signing key is a per-installation random value mixed with the hash, so a - copied password hash cannot forge a session and changing the password still - invalidates existing sessions. Exposed deployments require HTTPS through a - trusted reverse proxy or VPN. With `OMP_WEB_TRUSTED_HEADER_SHA256` set, a - request whose `X-Omp-Web-Auth` header hashes to that digest counts as signed - in; omp-web never holds the secret itself. Deciding which clients get the - header is the reverse proxy's job, because omp-web has no client address it - can trust. -- omp-web's own secrets (`OMP_WEB_PASSWORD`, `OMP_WEB_PASSWORD_HASH`, - `OMP_WEB_TRUSTED_HEADER_SHA256` and its legacy name - `OMP_WEB_TRUSTED_HEADER_SECRET`) are stripped from every child process - environment through `createChildProcessEnvironment` - (`lib/project-command-env.ts`). `OMP_WEB_*` values that are configuration - rather than secrets (`OMP_WEB_PACKAGE_DIR`, `OMP_WEB_OMP_BIN`, ...) are kept. +- `TAU_PASSWORD_HASH` protects every route with a password-only sign-in screen. + Only a scrypt hash reaches the server (`tau hash-password`), because every pi + session inherits the server's environment and an agent could print the password + into its transcript, session file and model-provider traffic. `--password`, or a + plaintext `TAU_PASSWORD` next to a hash, refuses to start. A lone + `TAU_PASSWORD` is hashed by the launcher, removed from the server's + environment, and logged as a warning with the hash to use instead; the server + itself still refuses a plaintext. Successful sign-in creates an HTTP-only, + signed cookie with a 30-day expiry; the signing key is a per-installation + random value mixed with the hash, so a copied password hash cannot forge a + session and changing the password still invalidates existing sessions. Exposed + deployments require HTTPS through a trusted reverse proxy or VPN. With + `TAU_TRUSTED_HEADER_SHA256` set, a request whose `X-Tau-Auth` header hashes to + that digest counts as signed in; tau never holds the secret itself. Deciding + which clients get the header is the reverse proxy's job, because tau has no + client address it can trust. +- tau's own secrets (`TAU_SECRET_ENV_VARS`: `TAU_PASSWORD`, `TAU_PASSWORD_HASH`, + `TAU_TRUSTED_HEADER_SHA256`, and defensively `TAU_TRUSTED_HEADER_SECRET`, which + the server never reads) are stripped from every child process environment through + `createChildProcessEnvironment` (`lib/project-command-env.ts`). `TAU_*` values + that are configuration rather than secrets (`TAU_PACKAGE_DIR`, `TAU_PI_BIN`, + ...) are kept. - API requests are origin-checked. Do not add browser-to-host execution paths that bypass this boundary. -- Host tools (`host_tool_call`) come from a fixed set: the browser's own tools - (open a URL or file, notify) and the server's session tools in `lib/agent-tools.ts`; - none runs a host command. A browser request must - not become arbitrary host command execution through an extension callback. -- File APIs are not a general filesystem browser. They are restricted to - selected workspaces, valid Git worktrees, session-referenced directories, and - explicitly selected roots. Paths are canonicalized to reject traversal and - symlink escapes. -- Secrets, raw API keys, and auth database contents never appear in API +- Host tools come from a fixed set: the browser's own tools (open a URL or file, + notify) and the server's session tools in `lib/agent-tools.ts` + (`list_sessions`, `new_session`, `send_to_session`, the GitHub tools); none runs + a host command. A browser request must not become arbitrary host command + execution through an extension callback. +- File APIs are not a general filesystem browser. They are restricted to selected + workspaces, valid Git worktrees, session-referenced files, a session's own + `local/` directory (uploads), and explicitly selected roots. Paths are canonicalized to + reject traversal and symlink escapes, and the agent directory's credential and + model files stay private (`isPiSecretFile`, `lib/file-access.ts`). +- Secrets, raw API keys, and credential store contents never appear in API responses, logs, or the browser. ## UX contract @@ -273,34 +291,31 @@ Deploy the frontend and API support together; no native OMP upgrade is required. session's state so a background tab cannot remain falsely “running”. - Desktop and mobile share the same core workflow. Mobile controls keep usable touch targets and a visible loading state rather than a blank shell. -- Accessibility and motion preferences are first-class. Components use the - shared design tokens and UI primitives rather than one-off colors or controls. -- Expensive rendering is deferred until needed; responsiveness and initial - bundle size are part of the product contract. +- Accessibility and motion preferences are first-class. Components use the shared + design tokens and UI primitives rather than one-off colors or controls. +- Expensive rendering is deferred until needed; responsiveness and initial bundle + size are part of the product contract. ## Upstream and release strategy -`agegr/pi-web` is the historical source and a useful source of UI ideas, -bug fixes, and tests. Before adopting an upstream change, verify that it does -not depend on Pi runtime behavior or Bun-only APIs. Port the user-visible -behavior, not blindly the implementation. - -Releases are independent: +ompweb and `agegr/pi-web` are historical sources of UI ideas, bug fixes, and +tests. Before adopting a change from either, verify that it does not depend on +oh-my-pi runtime behavior (ompweb's runner, omp-only RPC commands) or on SDK +internals. Port the user-visible behavior, not blindly the implementation. -1. Run typecheck, lint, relevant tests, and a production build. -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. -4. Tag and release the repository that owns this downstream project. +Releases are independent; `docs/release.md` holds the checklist. Each `v*` tag +runs the tests, the production build and the smoke tests against the pinned pi +(`PI_VERSION` in the workflows), builds the five release binaries +(`scripts/build-release-binaries.sh`), publishes the GitHub Release and then the +npm package through trusted publishing. ## Non-goals -- Reimplementing OMP, its provider registry, or its credential database. -- Embedding Bun-only OMP SDK packages in the omp-web server. +- Reimplementing pi, its provider registry, or its credential store. +- Embedding pi SDK packages in the tau server or daemon. - 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`. +- Automatic bulk synchronization from ompweb or `agegr/pi-web`. When a proposed feature conflicts with one of these boundaries, preserve the boundary unless the design is intentionally revised first. diff --git a/README.ja.md b/README.ja.md index ccd14910..e33878d5 100644 --- a/README.ja.md +++ b/README.ja.md @@ -1,174 +1,334 @@
-ompweb logo +tau logo -

ompweb

- -

- npm version - node version - license - npm downloads - GitHub stars - PRs Welcome -

+

tau

[English](./README.md) | [简体中文](./README.zh-CN.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) -コミュニティ:[OMPWEB Discord に参加](https://discord.gg/evqgGzRfM5) +tau は [pi coding agent](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) のためのブラウザワークスペースです。 +pi のセッションを読み込み、コンパニオンの pi 拡張とともに `pi --mode rpc` でライブセッションを実行します。どのブラウザからでもエージェントとのチャット、プロジェクトとファイルの閲覧、pi の設定管理ができます。1 台の tau サーバーから、リンクした別のマシン上でセッションを実行することもできます。 -[oh-my-pi (omp)](https://github.com/can1357/oh-my-pi) コーディングエージェント向けのモダンな Web UI です。ローカルの omp セッションを読み込み、ブラウザから対話、プロジェクト閲覧、設定管理、ファイルプレビューを行えるワークスペースを提供します。 +## 機能 -![ompweb — デモ](docs/demo.gif) +- **チャット**: ストリーミング応答、ライブ出力付きのツール呼び出し、思考ブロック、フォローアップのキューとステアリング、停止、`ask` ツールの質問のダイアログ表示。 +- **セッション**: プロジェクトごとの過去セッションの閲覧、セッションのフォーク、セッション内ブランチの切り替え、過去メッセージの編集、アーカイブと復元、タイトルとトランスクリプトの検索。 +- **中断に強いメッセージ**: 既存セッションへのメッセージは、pi が受け付けるまでブラウザとサーバーに保持され、再接続や再起動をまたいで届きます。 +- **ファイルと Git**: チャットの横のファイルエクスプローラーとプレビュー、セッションへのアップロード、Git worktree。 +- **サブエージェント**: pi に `pi-subagents` パッケージが入っている場合、その実行の進捗とトランスクリプト。 +- **リモートホストとクラスター**: リンクしたマシンでセッションを実行。マシンをクラスターにまとめ、プロジェクトとこのサーバーの pi 設定を共有。 +- **通知**: 実行の完了、質問、失敗をページ内、デスクトップ、Web Push(HTTPS 経由)で通知。 +- **エージェントツール**(既定でオフ): セッション横断ツールと、サーバーの `gh` ログインを使う GitHub ツール。 +- **音声入力**: 設定したエンドポイントによる任意の文字起こし。 -
-スクリーンショット(ライト / ダークテーマ) +## 動作要件 -![ompweb — ライトテーマ](docs/screenshot-light.png) +- npm パッケージには **Node.js 24 以降**。ランチャー(`tau`)は Node で動き、サーバーは [Bun](https://bun.sh) 1.4.4 以降で動きます。Bun はパッケージの依存としてインストールされます(同梱の Bun がない場合は、`PATH` 上のそのバージョン以上の `bun` を使います)。[単一バイナリ](#単一バイナリ)はどちらも不要です。 +- セッションを実行するすべてのマシンに **pi** をインストールします: -![ompweb — ダークテーマ](docs/screenshot-dark.png) + ```bash + npm install -g @earendil-works/pi-coding-agent + ``` -
+ tau は `PATH` 上の `pi` を実行します。別の pi を使うには `TAU_PI_BIN` にそのパスを設定します。tau は pi 1.5.2 を対象に開発されています。pi がなくても過去セッションの閲覧はできますが、セッションは開始できません。 -## 必要条件 +## インストール -- omp を別途インストールする必要はありません。ompweb は独自の [omp](https://github.com/can1357/oh-my-pi) ビルド `ompweb-omp` を使い、`~/.omp` の設定、認証、セッションをそのまま使います。どのインストール(npm、npx、単一バイナリ)も、初回起動時に同じバージョンの `ompweb-omp` をそのバージョンの [GitHub リリース](https://github.com/ompweb-dev/ompweb/releases)からダウンロードし、SHA-256 を確認して保存します(単一バイナリでは同じディレクトリ、それ以外は `~/.omp/agent/omp-web/omp//`)。`ompweb fetch-omp` でも取得できます。対応プラットフォームは linux-x64、linux-arm64、darwin-x64、darwin-arm64、windows-x64 です。それ以外(musl の Linux、Arm 版 Windows、FreeBSD)ではセッションを開始できません。GitHub に接続できないマシンでは、`OMP_WEB_OMP_BIN` にそのリリースの `ompweb-omp--` のコピーを指定してください -- Node.js `>= 24`。サーバーは [Bun](https://bun.sh) で動作し、npm パッケージの依存関係として自動的にインストールされます(同梱の Bun が見つからない場合は `PATH` 上の Bun を使用します) +### npm または Bun -キュー内のメッセージに対する **Steer**、**Delete**、**Edit** 操作は `ompweb-omp` チャネルのコマンド(`promote_queued_message`、`remove_queued_message`)です。omp がキャンセルを確認してから表示を削除し、編集時はキャンセル成功後にテキストを入力欄へ戻します。すでにキューに存在しないメッセージでは、キューを変更せず通知を表示します。ompweb が重複したステアリングメッセージを送信することはありません。 +```bash +npm install -g @ompweb-dev/tau +tau +``` -キューパネルは omp 自身のキュー(`get_state` の `queuedMessages` と `queue_update` イベント)を表示するため、同じセッションを開いているすべての端末に同じキューが表示されます。**Stop** は、まだキューで待機中のメッセージをエージェントに実行させず、そのテキストを入力欄に戻します。ただし、ライブステアリングでモデルがすでに受け取ったステアは実行されます。 +`bun add -g @ompweb-dev/tau` でも同じパッケージをインストールできますが、`tau` ランチャーには `PATH` 上の Node.js 24 が必要です。`npx @ompweb-dev/tau@latest` ならグローバルインストールなしで実行できます。 -## クイックスタート +tau はブラウザで `http://127.0.0.1:30187` を開きます。**Settings → API Keys & Providers** でモデルプロバイダーにログインし([設定](#設定)を参照)、ワークスペースを選んでセッションを開始します。 -**インストールせずに直接実行:** +### 単一バイナリ + +各リリースには、tau を 1 つのコンパイル済みプログラムにし、配信するファイルを横に置いたものも含まれます: +`tau-linux-x64.tar.gz`、`tau-linux-arm64.tar.gz`、`tau-darwin-x64.tar.gz`、`tau-darwin-arm64.tar.gz`、`tau-windows-x64.zip`。Node.js、npm、Bun は不要です。pi は同梱されておらず、`PATH` 上の `pi`(または `TAU_PI_BIN`)を実行します。CI を通過した `main` の各コミットも、同じアーカイブ付きのプレリリースとして公開されます。 ```bash -npx @kahme247/ompweb@latest +tar -xzf tau-linux-x64.tar.gz -C ~/.local/share # unpacks tau-linux-x64/ +~/.local/share/tau-linux-x64/tau # same options and environment variables as the npm launcher ``` -**またはグローバルにインストール:** +- `tau` はそのディレクトリに置いたままにしてください。`dist/`、`public/`、pi 拡張をそこから配信します(`PATH` 上のシンボリックリンクは可)。`TAU_PACKAGE_DIR` が設定されていればそこから配信します。 +- バイナリには `tau host` と `tau hash-password` がありますが、トレイとサービスインストーラーはありません。サービスのユニットは[サービス](#サービス)の例のように自分で書きます。 +- macOS はダウンロードを隔離します。初回起動前に `xattr -dr com.apple.quarantine tau-darwin-arm64` を一度実行してください。 +- macOS 15 以降は、アプリがローカルネットワークに接続する前に確認を求めます。`curl` では届くのに `tau host` が LAN 上のサーバーに対して `ECONNREFUSED` を報告する場合は、システム設定 → プライバシーとセキュリティ → ローカルネットワークでターミナル(または `tau`)を許可してください。 + +### ソースから ```bash -npm install -g @kahme247/ompweb -ompweb +git clone https://github.com/ompweb-dev/tau.git +cd tau +npm install +npm run build +node bin/tau.js ``` -**Node や npm を使わない単一バイナリ**もリリースごとに配布しています。手順は英語版 README の [Single binary](README.md#single-binary) を参照してください。 +## 実行 + +```text +tau [options] + + -p, --port Server port (default 30187, env PORT) + -H, --hostname Bind hostname (default 127.0.0.1, env TAU_HOSTNAME) + --no-open Do not open the browser automatically + --install-tray Install the tray, background service and shortcuts (Windows; Linux SNI tray) + --uninstall-tray Uninstall them + --tray Start the background tray manager + -h, --help Show help + --version Show the version + +tau hash-password Read a password from stdin and print the value for TAU_PASSWORD_HASH +tau host ... The host daemon (see "Hosts and cluster") +tau systemd ... | tau launchd ... Forward to tau-systemd / tau-launchd +``` -ブラウザで [http://127.0.0.1:30177](http://127.0.0.1:30177) を開きます。 +本番サーバーは、このマシンのホストデーモン(`tau host`)が動いていなければ起動します。ローカルのものを含むすべてのセッションはこのデーモンの下で動くため、Web サーバーを再起動しても実行中のセッションは止まりません。 -### CLI オプション +### 環境変数 + +| 変数 | 意味 | +| --- | --- | +| `PORT` | サーバーのポート(既定 `30187`)。 | +| `TAU_HOSTNAME` | バインドするアドレス(既定 `127.0.0.1`)。 | +| `TAU_NO_OPEN` | `1`、`true`、`yes`、`on`: ブラウザを開かない。 | +| `TAU_PASSWORD_HASH` | `tau hash-password` が出力するパスワードハッシュ。サインインページを有効にします。 | +| `TAU_TRUSTED_HEADER_SHA256` | 信頼できるリバースプロキシが `X-Tau-Auth` で送るシークレットの SHA-256 ダイジェスト(16 進)。[下記](#信頼できるプロキシでのパスワード省略)を参照。 | +| `TAU_PI_BIN` | `PATH` 上のものの代わりに実行する `pi` のパス。 | +| `PI_CODING_AGENT_DIR` | pi のエージェントディレクトリ(既定 `~/.pi/agent`)。tau も同じものを読み書きします。 | +| `TAU_NAME` | ブラウザのタイトルに出す表示名。`url`、`host`、`domain` ならリクエストのホスト名から作ります。 | +| `TAU_DISABLE_AUTOUPDATE` | `1`、`true`、`yes`、`on`: サーバーとホストのアプリ内更新を拒否します。 | +| `TAU_STT_ENDPOINT`、`TAU_STT_KEY`、`TAU_STT_MODEL` | 音声の文字起こし。エンドポイントはマルチパートの `file`(と `model`)を受け取り、`TAU_STT_KEY` は Bearer トークンとして送られます。エンドポイントがなければ音声入力はオフです。 | +| `TAU_DISCONNECT_DESTROY_MS` | 誰も見ていないセッションプロセスを停止するまでの時間(既定 2 分、`0` で無効)。 | + +### パスワード + +`127.0.0.1` にバインドしている間、tau はパスワードを必要としません。それ以外のアドレスで待ち受けるにはパスワードハッシュが必須で、ないと起動を拒否します: ```bash -ompweb --port 8080 # ポート番号指定 -ompweb --hostname 0.0.0.0 # ネットワーク公開 -ompweb hash-password # OMP_WEB_PASSWORD_HASH 用の値を出力 -ompweb fetch-omp # このバージョンの ompweb-omp を GitHub リリースからダウンロード(SHA-256 確認、未取得の場合のみ) -ompweb preflight # 新しいセッションと同じように omp を一度起動して hello を待つ。失敗時は理由を表示して終了コード 1 -ompweb --no-open # ブラウザ自動起動を無効化 +tau hash-password # prompts, input hidden +echo "a-long-random-password" | tau hash-password +TAU_PASSWORD_HASH='scrypt$15$8$1$...' tau --hostname 0.0.0.0 ``` -### パスワード保護 +tau が受け付けるのはハッシュだけです。`--password` フラグは拒否されます。平文の `TAU_PASSWORD` は検出されます。tau は起動時にそれをハッシュ化して自分の環境から削除し、代わりに使うハッシュを警告に表示します(`TAU_PASSWORD_HASH` と同時に設定すると拒否されます)。理由は、すべての pi セッションが tau の環境を引き継ぐため、エージェントが平文のパスワードをトランスクリプトに出力しうるからです。ブラウザのサインインは 30 日間有効です。 + +### リバースプロキシの背後で + +TLS なしで非ループバックアドレスを待ち受けると、tau は警告を出します。リバースプロキシまたは VPN を通して HTTPS で配信し、tau 自体は `127.0.0.1` にバインドしてください。プロキシは WebSocket のアップグレードを通す必要があります(ホストは `/api/hosts/link` と `/api/hosts/maintenance` を使います)。ホストがトークンで認証するパス(`/api/hosts/link`、`/api/hosts/maintenance`、`/api/hosts/cluster-config/…`)には、プロキシ独自の認証を加えないでください。 -omp-web は**平文パスワードをサーバーに渡しません**。すべての `omp` セッションは -サーバーの環境変数を引き継ぐため、エージェントが `env` を実行するだけで -パスワードがセッションファイルに記録され、モデルプロバイダーにも送信されて -しまうからです。`--password` を指定すると起動を拒否します。`OMP_WEB_PASSWORD` -は当面使えます。`ompweb` が起動時にハッシュ化してサーバーの環境変数から除き、 -`OMP_WEB_PASSWORD_HASH` に設定すべきハッシュを警告としてログに出力します。 -早めに切り替えてください。エージェントは `ompweb` ランチャープロセスから平文を -読み取れるうえ、起動のたびに新しいハッシュが作られるため、再起動ごとにすべての -ブラウザがサインアウトされます。両方の変数を設定すると起動を拒否するので、 -`OMP_WEB_PASSWORD` を削除してください。 +#### 信頼できるプロキシでのパスワード省略 -代わりにハッシュを生成して渡します。 +tau 自身はクライアントのアドレスを見られないため、リバースプロキシにリクエストを保証させることができます。プロキシは `X-Tau-Auth` ヘッダーでシークレットを送り、tau はそのシークレットの SHA-256 ダイジェストだけを `TAU_TRUSTED_HEADER_SHA256` に持ちます。ヘッダーのハッシュがダイジェストと一致するリクエストはサインイン済みとして扱われます。パスワードハッシュがなければ、省略するものはありません。 + +長いランダムなシークレットを、コマンドラインに書かずに生成します。次の例はシークレットを nginx のインクルードファイルに書き込み、ダイジェストだけを表示します: ```bash -ompweb hash-password # 二度入力(非表示) -echo "a-long-random-password" | ompweb hash-password # パイプでも可 +secret=$(openssl rand -hex 32) +printf 'map $tau_trusted $tau_auth {\n 1 "%s";\n default "";\n}\n' "$secret" \ + | sudo install -m 0640 -o root -g www-data /dev/stdin /etc/nginx/tau-auth.conf +printf %s "$secret" | sha256sum | cut -d' ' -f1 +unset secret +``` -OMP_WEB_PASSWORD_HASH='scrypt$15$8$1$…' ompweb +```nginx +# http {} context +geo $tau_trusted { + default 0; + 10.0.0.0/16 1; +} +include /etc/nginx/tau-auth.conf; + +# the location that proxies to tau +proxy_set_header X-Tau-Auth $tau_auth; ``` -`ompweb hash-password` はパスワードを標準入力から読み取るため(コマンドライン -引数には決して渡しません)、シェル履歴や `ps` に残りません。ハッシュは scrypt -(N = 2^15、r = 8、p = 1)と 16 バイトのソルトで生成し、 -`scrypt$$$

$$` 形式で出力します。ハッシュを読んでも -サインインには使えず、パスワードへ戻すこともできません。 - -セッションの署名にパスワードハッシュは使いません。初回起動時に -`~/.omp/agent/omp-web/web-auth-secret.json`(モード `0600`)へランダムな鍵を -生成し、ハッシュと混ぜて署名鍵にします。パスワードを変更すれば既存の -セッションは無効になりますが、保存されたハッシュだけではセッションを -偽造できません。 - -サービスインストーラー(`ompweb systemd install`、`ompweb-launchd install`、 -Linux トレイ、Windows サービス)はインストール時に `OMP_WEB_PASSWORD` を -受け付け、設定ファイルへ書き込む前にハッシュ化します。保存されるのは -ハッシュだけです。 - -## 主な機能 - -- **リアルタイムチャット**: ローカルの `omp` エージェントとストリーミング対話。 -- **キュー削除の確認**: OMP にキュー登録されたフォローアップやステアメッセージをキャンセルする前に、内容を表示して確認します。ネイティブの `remove_queued_message` 対応が必要です。配信済みのメッセージは取り消せません。 -- **セッション管理**: プロジェクトごとに履歴を一覧表示、分岐やフォークにも対応。 -- **下書きの復元**: 未送信のテキストを会話または新規セッションのワークスペースごとに保存し、ブラウザストレージが利用可能な場合は、同じタブでの「戻る」「進む」や再読み込み後に復元します(最大 50 件)。画像と添付ファイルはメモリ内にのみ保持されます。 -- **ライブタスク&サブエージェント**: Todo リストと稼働中サブエージェントの進捗を折りたたみパネルでリアルタイム表示。 -- **ファイル閲覧・プレビュー**: チャットと並べてファイルを閲覧、コード・Markdown・画像・音声・PDF をプレビュー。 -- **各ホストのファイル**: エクスプローラー、検索、プレビュー、ダウンロード、ライブ更新は、そのホストのデーモンを使用します。アップロードは 1 ファイル 2 GiB までで、合計 100 MiB 制限はありません。プレビュー上限はテキスト 256 KiB、画像・DOCX 10 MiB のままです。チャットを切り替えてもファイルタブのホストは変わりません。 -- **各ホストのワークスペース**: Git の差分とワークツリー操作、ディレクトリの移動、HTTPS/SSH リポジトリのクローンも、そのホストで実行します。クローンのキャンセルはプロセス終了と安全な削除を確認してから完了し、接続が切れた場合は結果が不明であることを表示します。 -- クローンの削除中に保存先が置き換わった場合、退避したデータは非公開ディレクトリに保持され、エラーに保存場所が表示されます。削除や復元の前に内容を確認してください。 -- **Git Worktree サポート**: サイドバーから直接 Git ワークツリーを切り替え・管理。 -- **GUI 設定管理**: 設定ファイルを直接編集することなく、モデル、API キー、MCP サーバー、スキル、プラグイン、OMP 設定を変更可能。 -- **スラッシュコマンド・ショートカット**: `/plan`、`/review`、`/fix`、`/test` などの定型プロンプトと `⌘K` / `Ctrl+K` コマンドパレット。 -- **テーマと多言語対応**: ペーパー調のライト/ダークテーマ、英語・簡体字中国語・日本語に完全対応。 - -## 環境変数 - -| 変数名 | 説明 | デフォルト値 | -| --- | --- | --- | -| `PORT` | サーバーポート | `30177` | -| `OMP_WEB_HOSTNAME` | バインドホスト | `127.0.0.1` | -| `OMP_WEB_PASSWORD_HASH` | Web ログイン用パスワードの scrypt ハッシュ(`ompweb hash-password` で生成)。非ループバックバインドには必須 | _なし(認証無効)_ | -| `OMP_WEB_TRUSTED_HEADER_SHA256` | 信頼できるリバースプロキシが `X-Omp-Web-Auth` ヘッダーで送るシークレットの SHA-256 ダイジェスト(16 進)。ヘッダーのハッシュが一致したリクエストはパスワードなしで通ります。omp-web はシークレット自体を保持しません。生成方法と nginx の設定例は英語版 README の「Skipping the password on trusted networks」を参照してください | _なし(無効)_ | -| `OMP_WEB_NO_OPEN` | `1` でブラウザ自動起動を無効化 | `0` | -| `OMP_WEB_DISABLE_AUTOUPDATE` | `1` で更新チェックとアプリ内更新を無効化(変更後は再起動) | `0` | -| `OMP_WEB_NAME` | ブラウザのタブとインストールしたアプリに表示する名前。`url`・`host`・`domain`(大文字小文字を区別しない)を指定すると、ブラウザが接続したホスト名(ポートなし)を使用します(localhost と IP アドレスは `omp web` のまま)。それ以外の値はそのまま使用します(変更後は再起動) | `omp web` | -| `OMP_WEB_OMP_BIN` | ダウンロード版の代わりに使う `ompweb-omp` ビルドのパス(GitHub に接続できないマシンではリリースの `ompweb-omp--` のコピー、ソースチェックアウトでは `runner/release/ompweb-omp--`)。通常の `omp` は ompweb のチャネルを話さないため使えません。サービスのインストーラーは、これを設定したときだけサービス環境に書き込みます | _ダウンロードした `ompweb-omp`_ | -| `PI_CODING_AGENT_DIR` | カスタム omp エージェントディレクトリ | `~/.omp/agent` | -| `OMP_WEB_STT_ENDPOINT` | OpenAI 互換の音声認識エンドポイント URL。未設定の場合は `OMP_WEB_STT_MODEL` を omp 自身の認証情報で使って文字起こしします | _なし_ | -| `OMP_WEB_STT_KEY` | STT エンドポイント用の API キー | _なし_ | -| `OMP_WEB_STT_MODEL` | STT エンドポイント用のモデル名。エンドポイント未設定時は、omp のログインで実行する omp の音声認識モデル(例: `openai-codex/codex-transcribe`。ChatGPT サブスクリプション、このモデルを含む omp バージョンが必要) | _なし(エンドポイント未設定時は無効)_ | - -**`OMP_WEB_NAME` とインストールしたアプリ。** インストールしたアプリ(PWA)の名前は、通常インストール元のページの名前になります。あとで `OMP_WEB_NAME` を変更した場合や、`OMP_WEB_NAME` が `url`・`host`・`domain` のときに別のアドレスで omp-web にアクセスした場合、OS がインストール済みアプリの名前も変更することがあります。`OMP_WEB_NAME` は空のままにするか、どのドメイン名やアドレスでアクセスしてもこの omp-web サーバーを識別できる名前を設定することをおすすめします。 +ヘッダーは常に設定してください。そうすれば、クライアント自身が送る `X-Tau-Auth` は空の値で置き換えられます。tau の `server` ブロックには明示的な `server_name` を付け、他のホスト名には `default_server` ブロックで `return 444;` を返してください。そうしないと、DNS リバインディングで nginx が他サイトのリクエストにシークレットを付けてしまいます。tau が保存するのは高速な SHA-256 ダイジェストだけで、これが安全なのは長いランダムなシークレットの場合に限られます。パスワードを流用しないでください。 -## 開発 +## サービス + +どのインストーラーも 2 つのサービスを動かします: Web サーバーとホストデーモン(`tau host`)です。 + +### Linux(systemd ユーザーサービス) ```bash -git clone https://github.com/ompweb-dev/ompweb.git -cd ompweb -npm install -npx bun runner/scripts/use-omp-build.ts && (cd runner && npx bun install --frozen-lockfile) -npx bun runner/scripts/build-binary.ts # このマシン用の ompweb の omp ビルド: runner/release/ompweb-omp-- -npm run dev +TAU_PASSWORD_HASH='scrypt$...' tau-systemd install # or: npx --yes --package=@ompweb-dev/tau@latest tau-systemd install +tau-systemd status +``` + +`install` はユニット `tau.service` と `tau-host.service` を `~/.config/systemd/user/` に書き、`~/.pi/agent/web-service.env`(ポート、ホスト名、パスワードハッシュ。再インストールなしで編集可)を作成し、両方を有効にします。その他のコマンド: `uninstall`(`--clean-config` で env ファイルも削除)、`start`、`stop`、`restart`(Web サービスのみ)、`open`。オプション: `--port`、`--hostname`、`--no-autostart`、`--json`。ログ: `journalctl --user -u tau -u tau-host -f`。 + +KDE Plasma など StatusNotifierItem 対応のデスクトップでは、`tau --install-tray` でこれらの systemd サービスを操作するトレイアイコンを追加できます。 + +### macOS(launchd) + +```bash +TAU_PASSWORD_HASH='scrypt$...' tau-launchd install # or: npx -p @ompweb-dev/tau@latest tau-launchd install +tau-launchd status +tau-launchd uninstall +``` + +`install` は LaunchAgent `dev.ompweb.tau` と `dev.ompweb.tau-host` を作成します。どちらもログイン時に起動し、クラッシュ時に再起動します。実行時の環境から `PORT`、`TAU_HOSTNAME`、`TAU_PASSWORD_HASH`、`TAU_TRUSTED_HEADER_SHA256`、`TAU_PI_BIN`、`TAU_NAME`、`TAU_DISABLE_AUTOUPDATE`、`PI_CODING_AGENT_DIR` を読み取ります。ログは `~/Library/Logs/tau` に出力されます。 + +### Windows(トレイとバックグラウンドサービス) + +```powershell +tau --install-tray +``` + +バックグラウンドサービス、ホストデーモン(スケジュールされたタスク `tau-host`)、トレイアイコン、ログオン時の自動起動、デスクトップとスタートメニューのショートカットをインストールします。管理は `tau-tray status|start|stop|restart|open|uninstall` で行います。サービスは設定を `%USERPROFILE%\.pi\agent\web-service.json` から、`TAU_PASSWORD_HASH` をユーザーまたはシステムの環境変数から読み取ります。 + +### 単一バイナリをサービスとして + +2 つのユニットを自分で書きます。systemd の例(パスは適宜変更): + +```ini +# ~/.config/systemd/user/tau.service +[Unit] +Description=tau web service + +[Service] +WorkingDirectory=%h +ExecStart=%h/.local/share/tau-linux-x64/tau --no-open +Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin +# TAU_PASSWORD_HASH, PORT and TAU_HOSTNAME go here. +EnvironmentFile=-%h/.pi/agent/web-service.env +Restart=on-failure +RestartSec=3 + +[Install] +WantedBy=default.target +``` + +```ini +# ~/.config/systemd/user/tau-host.service +[Unit] +Description=tau host daemon +# It exits until the web server has written its link: keep restarting. +StartLimitIntervalSec=0 + +[Service] +WorkingDirectory=%h +ExecStart=%h/.local/share/tau-linux-x64/tau host +Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin +EnvironmentFile=-%h/.pi/agent/web-service.env +Restart=always +RestartSec=10 + +[Install] +WantedBy=default.target +``` + +```bash +systemctl --user daemon-reload +systemctl --user enable --now tau tau-host ``` -ローカル開発サーバーは [http://127.0.0.1:30178](http://127.0.0.1:30178) で起動します。`runner/release/` のランナーは自動的に見つかります。`npm test` と `npm run build:binary` にもランナーのセットアップが必要です。 +`PATH` には `pi` のディレクトリ(と pi が動く Node.js のディレクトリ)を含める必要があります。macOS では `…/tau --no-open` と `…/tau host` を `RunAtLoad` と `KeepAlive` 付きで実行する 2 つの launchd エージェント、Windows ではログオン時に `tau.exe --no-open` と `tau.exe host` を実行する 2 つのタスクスケジューラのタスクで同じことができます。 + +## ホストとクラスター + +### ホストデーモン + +`tau host` は、マシン上で pi セッションを実行し、そのセッションファイルを読むプロセスです。1 つ以上の tau サーバーへ WebSocket で外向きに接続するため、NAT の内側にあっても動きます。リンクや Web サーバーが落ちてもセッションは動き続け、リンクが戻るとサーバーが再びセッションに参加します。サーバー自身のマシンでは、デーモンは自動的にリンクされます(**Settings → Hosts** の「This machine」)。 + +```text +tau host login [--add] --url save a link; the host token is read from stdin +tau host logout --url remove a link +tau host [--allow-http] run the daemon +tau host status|drain|resume control the running daemon +``` + +デーモンが受け付けるサーバー URL は `https://` のみで、`http://` はループバックアドレスに限られます。`--allow-http` は他のアドレスへの平文 HTTP を許可します。ホストトークンが暗号化されずに流れるため、信頼できるネットワークでのみ使ってください。 + +### 別のマシンをリンクする + +別のマシンには pi と、npm 版の tau(Node.js 24)または単一バイナリが必要です。 + +1. tau サーバーで **Settings → Hosts → Add host** を開き、名前を入力してトークンをコピーします。トークンは一度だけ表示され、サーバーはそのハッシュだけを保存します。 +2. 別のマシンでリンクを保存します。求められたらトークンを貼り付けるか、パイプで渡します。`ps` に表示されることはありません: + + ```bash + npx @ompweb-dev/tau@latest host login --url https://tau.example.com + ``` + + リンクはモード `600` で `~/.pi/agent/tau/host.json` に保存されます。`--add` を付けると、最初のリンクを置き換えずに別のサーバーへのリンクを追加します。 +3. デーモンを起動し、動かし続けます(サービスとして。[サービス](#サービス)を参照): + + ```bash + npx @ompweb-dev/tau@latest host + ``` -`npm run dev` は Bun のホットリロード付きでサーバーを起動します。`npm run build` はブラウザアプリを `dist/` にバンドルし、`npm start` はそれをポート 30177 で配信します(`npm run smoke` で結果を確認できます)。`npm run dev:lan` は開発サーバーをすべてのインターフェースにバインドします。 +するとホストがオンラインと表示され、サイドバーにそのワークスペースのグループができ、新規セッション画面で選べるようになります。各ホストは自分の `~/.pi/agent`、セッション、プロバイダーのログインを持ちます。**Settings → Hosts** ではホストの名前変更と取り消し、各ホストの tau バージョンと更新の表示、エージェントが確認なしでそこでセッションを開始できるかどうかの設定もできます。取り消されたホストのデーモンは自分のセッションを停止します。 -### チェックコマンド +### クラスター + +**Settings → Hosts** では、リンク済みのホストをクラスターに追加できます。このマシンがマスターで、最初のホストと一緒に参加します。参加するホストはオンラインである必要があり、クラスターのチェックアウト用にプロジェクトフォルダーを指定します。そのホストの Git プロジェクトは、リポジトリの origin によってクラスターのプロジェクトに結び付けられます。以後、クラスターのセッションはどのメンバーでも開始できます。 + +メンバーはマスターの pi 設定でセッションを実行します。マスターは次のもののバージョン付きマニフェストを作ります: + +- pi エージェントディレクトリから: `settings.json`、`models.json`、`mcp.json`、`AGENTS.override.md`、`AGENTS.md`、`CLAUDE.md`、`SYSTEM.md`、`APPEND_SYSTEM.md`、およびディレクトリ `skills/`、`prompts/`、`themes/`、`extensions/` +- `~/.agents/skills/` +- **Settings → System** のエージェント環境変数 + +各メンバーのデーモンは不足しているファイルをダウンロードしてハッシュを確認し、バージョンを丸ごと適用するか、まったく適用しないかのどちらかです。マスターは 30 秒ごとに確認し、メンバーでのセッション開始時には先に現在のバージョンを適用します。ミラーされたディレクトリはマスターのものと同一になります(`node_modules` と `.git` は除外)。上限: 1 ファイル 5 MiB、合計 50 MiB。 + +ミラーされないもの: 認証情報(`auth.json`、`mcp-auth.json`)、セッション、キャッシュ、リポジトリ内の設定、そしてプログラム(MCP サーバーのコマンドや、`settings.json` が指定するパッケージ。後者は pi がメンバー上で自らインストールします)。メンバーは `settings.json` の次のキーについて自分の値を保ちます: `shellPath`、`shellCommandPrefix`、`npmCommand`、`selfUpdateCommand`、`externalEditor`、`sessionDir`、`httpProxy`、`extensions`、`skills`、`prompts`、`themes`、`deviceId`、`trackingId`、`lastChangelogVersion`、`extensionChangelogVersions`、`terminal`。 + +最初の適用時に、メンバー自身の設定は `~/.pi/agent/tau/own-config/` に移され、クラスターを離れると元に戻ります。1 台のホストが保持できるのは一度に 1 つのサーバーの設定だけです。プロバイダーのログインはミラーされないため、各メンバーでログインしてください(下記参照)。 + +## 設定 + +tau は pi 自身のファイルを使い、いくつか独自のファイルを加えます: + +| パス | 内容 | +| --- | --- | +| `~/.pi/agent/settings.json` | pi の設定。**Settings** では既定の思考レベル、思考ブロックの表示、有効なモデル、リトライ、コンパクションを編集します。 | +| `~/.pi/agent/models.json` | カスタムのプロバイダーとモデル。**Settings → API Keys & Providers** で編集します。 | +| `~/.pi/agent/auth.json` | pi のプロバイダーログインと API キー。pi が書き込みます。 | +| `~/.pi/agent/sessions/` | pi のセッションファイル。tau が一覧表示して読み込みます。 | +| `~/.pi/agent/tau-settings.json` | tau サーバーの設定: 再起動後の自動再開、エージェントツール、GitHub の書き込みと Actions の権限、エージェント環境変数、アップロードの保持期間。 | +| `~/.pi/agent/projects.json` | サイドバーに追加した、または非表示にしたワークスペース。 | +| `~/.pi/agent/tau/` | tau の状態: ホスト登録(`hosts.json`)、デーモンのリンク(`host.json`)、クラスター(`pools.json`)、サインイン鍵、通知、メッセージのアウトボックス、アップロード。 | +| `~/.pi/agent/web-service.env` | `tau-systemd` が書くサービス設定(Windows では `web-service.json`)。 | + +すべてのパスは `PI_CODING_AGENT_DIR` に従います。 + +**プロバイダーのログインはホストごとです。** tau 自身は `auth.json` を読みません。ログイン(OAuth と API キー)は、選択したホストのデーモン上で、tau のコンパニオン拡張(`lib/pi/tau-extension.ts` の `/tau_auth` コマンド)を通して pi の中で行われます。生のキーやトークンはそのホストの pi にとどまります。そのホストでログインするには、**Settings → API Keys & Providers** でホストを選んでください。 + +**エージェント環境変数**(**Settings → System**)は、保存後に起動するすべての pi プロセスに追加されます。pi の状態や tau の内部を変えてしまう名前は拒否されます: `PATH`、`PATHEXT`、`COMSPEC`、`SYSTEMROOT`、`WINDIR`、`NODE_OPTIONS`、`HOME`、`USERPROFILE`、`HOMEDRIVE`、`HOMEPATH`、`XDG_DATA_HOME`、`XDG_CONFIG_HOME`、`PI_CODING_AGENT_DIR`、`PI_CODING_AGENT_SESSION_DIR`、`PORT`、`NODE_ENV`、および `TAU_` または `_` で始まるすべての名前。 + +## セキュリティに関する注意 + +- **エージェントはあなたのユーザー権限で動きます。** pi のツールは、あなたのユーザーが扱えるあらゆるファイルを読み書きし、コマンドを実行できます。tau はサンドボックス化しません。tau にサインインできる人は誰でも、リンクされたすべてのホストでエージェントにそれをさせられます。 +- **パスワードゲート。** `TAU_PASSWORD_HASH` を設定すると、サインインページ、静的アセット、Service Worker、ホストが認証するパスを除くすべてのページと API ルートで、セッション Cookie(または信頼できるプロキシのヘッダー)が必要になります。パスワードハッシュなしで非ループバックアドレスを待ち受けることを tau は拒否します。 +- **HTTPS。** tau は平文の HTTP を話します。リモートからアクセスする場合は HTTPS(リバースプロキシまたは VPN)の背後に置き、パスワード、セッション Cookie、ホストトークンを保護してください。Web Push 通知にも HTTPS が必要です。 +- **シークレットはセッションに渡りません。** `TAU_PASSWORD`、`TAU_PASSWORD_HASH`、`TAU_TRUSTED_HEADER_SECRET`、`TAU_TRUSTED_HEADER_SHA256`、`TAU_STT_KEY`、`PORT`、`NODE_ENV` は、すべての pi プロセスとプロジェクトコマンドの環境から削除されます。 +- **ホストトークン。** サーバーは各ホストトークンの SHA-256 だけを保存します。ホストのデーモンはトークンを標準入力から読み、モード `600` のファイルに保存します。取り消されたトークンは即座に拒否されます。 +- **ブラウザからのファイルアクセス。** ファイルビューアーとエクスプローラーが配信するのは許可されたルートだけです: 追加または開いたワークスペース、セッションの作業ディレクトリと検証済みの worktree、そしてセッションのトランスクリプトが参照するファイル(読み取りのみ)。pi ディレクトリ内の既知の認証情報ファイル(`models.json`、`.env` ファイル)は、許可されたルート内でも拒否されます。これらの制限はブラウザに対するもので、エージェントには適用されません。 +- **エージェントツールは既定でオフです。** 有効にすると、どのセッションもセッションの一覧表示、セッションの開始、別のセッションへのメッセージ送信ができ、サーバーの `gh` ログインで GitHub ツールを使えます。コメントとスレッドへの書き込みは、**Allow agent GitHub writes without asking** がオンでない限りセッション内で確認され、Actions の dispatch、cancel、rerun はそれぞれ既定で確認されます。ホストでのセッション開始は、そのホストがエージェントによる開始を許可していない限り確認されます。 + +## 開発 ```bash -npm run typecheck # 型チェック (TypeScript) -npm run lint # ESLint -npm test # テスト実行 (bun test) +npm install +npm run dev # Bun hot reload at http://127.0.0.1:30188 +npm run build # bundle the browser app into dist/ +npm start # serve dist/ at http://127.0.0.1:30187 +npm run build:binary # single binary for this machine into release/ (-- --target bun-linux-arm64 for another) +npm run typecheck && npm run lint && npm test ``` -## クレジットとライセンス +開発サーバーはホストデーモンを引き継ぎません。開発中は「This machine」がオフラインと表示され、デーモンはインストール済みの tau にリンクされたままです。 + +## ライセンス -- [agegr/pi-web](https://github.com/agegr/pi-web) (MIT) をベースに [can1357/oh-my-pi](https://github.com/can1357/oh-my-pi) 向けに適合・拡張したフォークです。 -- [MIT ライセンス](./LICENSE) のもとで公開されています。 +MIT。[LICENSE](./LICENSE) を参照してください。tau は [ompweb](https://github.com/ompweb-dev/ompweb) からフォークされ、ompweb は [agegr/pi-web](https://github.com/agegr/pi-web) からフォークされました。 diff --git a/README.md b/README.md index bcdedbe7..0602daa1 100644 --- a/README.md +++ b/README.md @@ -1,935 +1,268 @@

-ompweb logo +tau logo -

ompweb

- -

- npm version - node version - license - npm downloads - GitHub stars - PRs Welcome -

+

tau

[English](./README.md) | [简体中文](./README.zh-CN.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) -Community: [Join the OMPWEB Discord](https://discord.gg/evqgGzRfM5) - -A clean, modern web UI for the [oh-my-pi (omp)](https://github.com/can1357/oh-my-pi) coding agent. It reads your local omp sessions and gives you a browser workspace to chat with the agent, browse projects, manage settings, and preview files. - -![ompweb — live session demo](docs/demo.gif) - -
-Screenshots (light / dark) +tau is a browser workspace for the [pi coding agent](https://www.npmjs.com/package/@earendil-works/pi-coding-agent). +It reads your pi sessions, runs live sessions through `pi --mode rpc` together with its companion pi extension, and +lets you chat with the agent, browse projects and files, and manage pi settings from any browser. One tau server can +also run sessions on other machines that you link to it. -![ompweb — light theme](docs/screenshot-light.png) - -![ompweb — dark theme](docs/screenshot-dark.png) +## Features -
+- **Chat**: streaming replies, tool calls with live output, thinking blocks, queued follow-ups and steering, stop, + and the `ask` tool's questions as dialogs. +- **Sessions**: browse past sessions per project, fork a session, switch between branches of a session, edit an + earlier message, archive and restore, search titles and transcripts. +- **Messages survive interruptions**: a message to an existing session is held in the browser and on the server until + pi has accepted it, across reconnects and restarts. +- **Files and Git**: file explorer and previews beside the chat, uploads into a session, Git worktrees. +- **Subagents**: progress and transcripts of `pi-subagents` runs, when + that package is installed in pi. +- **Remote hosts and cluster**: run sessions on linked machines; group machines into a cluster that shares projects + and this server's pi configuration. +- **Notifications**: in-page, desktop and Web Push (over HTTPS) for finished runs, questions and failures. +- **Agent tools** (off by default): cross-session tools and GitHub tools that use the server's `gh` login. +- **Voice input**: optional transcription through an endpoint you configure. ## Requirements -- Nothing else for omp: ompweb runs its own [omp](https://github.com/can1357/oh-my-pi) build, `ompweb-omp`, which reads your `~/.omp` settings, auth and sessions. Every install (npm, npx or the single binary) downloads the `ompweb-omp` of its exact version from that version's [GitHub release](https://github.com/ompweb-dev/ompweb/releases) the first time it starts, checks its SHA-256 and keeps it (beside the single binary, otherwise in `~/.omp/agent/omp-web/omp//`); `ompweb fetch-omp` does the same on demand. Sessions start once it is there. It exists for linux-x64, linux-arm64, darwin-x64, darwin-arm64 and windows-x64; on any other platform (Linux on musl, Windows on Arm, FreeBSD) ompweb cannot start sessions. A machine that cannot reach GitHub needs `OMP_WEB_OMP_BIN` pointing at a copy of that release's `ompweb-omp--` -- 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**, **Delete** and **Edit** actions on a queued message are commands of the `ompweb-omp` channel (`promote_queued_message`, `remove_queued_message`). Deletion is confirmed by omp before the chip disappears; editing recalls text only after cancellation succeeds. A message that is no longer pending leaves the queue unchanged and displays a notice; ompweb does not send a duplicate steering message. - -The queue panel shows omp's own queue (`queuedMessages` in `get_state` and `queue_update` events), so every device viewing a session sees the same queued messages. **Stop** moves the text of messages still waiting in the queue back into the composer instead of letting the agent run them; a steer the model already picked up through live steering still runs. - -## App installation behind authentication - -To install the web app, sign in first and use your browser's installation menu. -The single manifest link requests `/api/manifest` with credentials; that endpoint -uses the existing web-password guard and private, revalidating caching. Its -192×192 and 512×512 PNG icons are embedded from the packaged assets because -Android's native installer fetches ordinary icon URLs without authentication -cookies. The app still launches at `/` with scope `/`. Its `theme_color` and -`background_color` come from the manifest link's `?theme=` parameter: Chrome -refreshes an installed app's manifest without cookies, so the server renders the -selected theme's color (remembered in the `omp-theme-color` cookie) into the -link. Chrome 153 and later color an installed app's Android navigation bar from -it after Chrome next checks the app for manifest updates. - -Keep Cloudflare Access and application authentication enabled; no public -manifest exception or Access bypass rule is needed. This does not add offline -support. Local Chromium verification covered cookie-gated metadata with HTTP -icon URLs blocked (zero installability errors). The owner also confirmed that -installation on a physical phone works as expected behind Cloudflare Access. - -## Notifications - -Turn on notifications in **Settings → Notifications**. Each browser keeps its own -settings: which events notify (task finished, waiting for input, run failed, -model switched automatically) and what happens while you use omp-web in another -tab (an in-app toast, or always a system notification). Nothing is shown for the -session you are viewing. Clicking a notification opens its session. - -- **Push** reaches the browser even when no omp-web tab is open. It needs a - secure context (HTTPS through your reverse proxy, or `localhost`), and the - omp-web server needs outbound HTTPS access to the browser vendors' push - services. omp-web generates its push (VAPID) keys on first use and stores them, - with the device list and the notification history, in its data directory - (owner-only), so they survive restarts. -- On **iPhone and iPad** (iOS 16.4 or later), push works only in the app added - to the Home Screen. -- In a secure context without push support, system notifications appear while - an omp-web tab is open. Over plain HTTP on a non-localhost address, browsers - allow no system notifications: only the in-app toasts shown while you use - omp-web remain. -- Desktop browsers show notifications through the operating system's - notification center. Push delivery needs the browser process running. - -Completion notifications use the `ompweb-omp` channel's `prompt_result` and -`session_settled` frames. - -## GitHub agent tools - -With **Agent tools** enabled and `gh` logged in on the web server, agents can -watch pull requests, issues and specific GitHub Actions runs. Pass a run URL such -as `https://github.com/OWNER/REPO/actions/runs/ID` to `watch_github`; status and -attempt changes arrive in the session, followed by the final conclusion. The -watch ends after completion. Runs that already completed are not registered. -Watches survive server restarts and use the existing 20-watch limit per session. - -Automatic updates contain metadata only, not workflow names, job names or logs. -Use `github_read` with the same URL for run details (`include: ["summary"]`) or -jobs (`include: ["checks"]`), and `unwatch_github` to stop watching. Run comments, -other read parts, and subscriptions to future runs of a workflow are not supported. -Remote sessions use the same per-repository read confirmation as PRs and issues. - -For manual runs, use `github_workflow_list` to discover workflows and -`github_workflow_read` with a branch or tag to inspect dispatch inputs. -`github_workflow_dispatch` takes `repo`, `workflow`, `ref` and optional `inputs`, -and returns the exact created run ID and URL. Pass that URL to `watch_github`. -`github_run_list` finds existing runs; `github_run_cancel` requests cancellation; -`github_run_rerun` requests all or failed jobs, or a specific job and its dependents. -A rerun retains its run ID: read until the new attempt appears before watching it. - -Settings → System controls dispatch, cancellation and rerun independently: -**Blocked**, **Ask each time** (default), or **Allow without asking**. -The comment-writing switch does not authorize these operations. These controls -limit agent actions through omp-web, not the server account's GitHub privileges. -GitHub refusals retain the reported reason and available permission, SSO or -rate-limit evidence; a 403 alone is not treated as a missing token scope. -Fine-grained credentials need Actions write for these mutations; classic/OAuth -credentials use `repo`. The classic `workflow` scope is for editing workflow -files, not dispatching them. omp-web does not change credentials automatically. - -Mutation requests are recorded before sending and are never automatically -replayed after an uncertain result. Inspect the existing runs before issuing a -new dispatch or rerun. Confirmation inputs and explicit workflow reads are not -secret channels: do not pass credentials as workflow inputs. - -## Quick Start - -**Run directly without installing:** - -```bash -npx @kahme247/ompweb@latest -``` - -or -```bash -nix run github:ompweb-dev/ompweb -``` - -**Or install globally:** - -```bash -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. +- **Node.js 24 or newer** for the npm package. The launcher (`tau`) runs on Node; the server runs on + [Bun](https://bun.sh) 1.4.4 or newer, which the package installs as a dependency (a `bun` on your `PATH` of at + least that version is used if the bundled one is missing). The [single binary](#single-binary) needs neither. +- **pi**, installed on every machine that runs sessions: -### CLI Options - -```bash -ompweb --port 8080 # Custom port -ompweb --hostname 0.0.0.0 # Listen on network -ompweb hash-password # Print the value for OMP_WEB_PASSWORD_HASH -ompweb fetch-omp # Download this version's ompweb-omp from its GitHub release (SHA-256-checked) if it is missing -ompweb preflight # Start the session omp once (as a new session would) and wait for its hello; exit 1 says why it failed -ompweb --no-open # Don't auto-open the browser -ompweb --install-tray # Install Windows System Tray service & Desktop shortcuts -ompweb --uninstall-tray # Uninstall Windows System Tray service & shortcuts -ompweb --tray # Start background System Tray manager -ompweb systemd install # Install Linux systemd user services (web + ompweb-host daemon) -ompweb launchd install # Install the macOS launchd agents (web + ompweb-host daemon) -ompweb --help # Show help -ompweb --version # Show version -``` + ```bash + npm install -g @earendil-works/pi-coding-agent + ``` -### Password protection + tau runs the `pi` found on `PATH`. To use another one, set `TAU_PI_BIN` to its path. tau is developed against pi + 1.5.2. Without pi, browsing past sessions works, but no session can start. -omp-web **never passes a plaintext password to the server**, because every -`omp` session inherits the server's environment: an agent running `env` would -print the password into its session file and send it to the model provider. -`--password` stops `ompweb` at startup. An `OMP_WEB_PASSWORD` still works for -now: `ompweb` hashes it at startup, keeps it out of the server's environment, -and logs a warning with the hash to put in `OMP_WEB_PASSWORD_HASH` instead. -Switch soon: agents can still read the plaintext from the `ompweb` launcher -process, and each start makes a new hash, so every restart signs all browsers -out. Setting both variables stops `ompweb`; remove `OMP_WEB_PASSWORD`. +## Install -Generate a hash instead and give that to the server: +### npm or Bun ```bash -ompweb hash-password # asks twice, input hidden -echo "a-long-random-password" | ompweb hash-password # or pipe it in - -OMP_WEB_PASSWORD_HASH='scrypt$15$8$1$…' ompweb +npm install -g @ompweb-dev/tau +tau ``` -`ompweb hash-password` reads the password from stdin — never from a command -line argument — so it stays out of your shell history and out of `ps` output. -The hash is scrypt (N = 2^15, r = 8, p = 1) with a fresh 16-byte salt, printed -in the self-describing form `scrypt$$$

$$`. Anyone who -reads the hash cannot sign in with it, and it cannot be turned back into the -password. - -Sessions are not signed with the password hash. A random signing key is created -on first start in `~/.omp/agent/omp-web/web-auth-secret.json` (mode `0600`) and -mixed with the hash, so changing the password still signs everyone out while the -stored hash alone is never enough to forge a session. - -The service installers (`ompweb systemd install`, `ompweb-launchd install`, the -Linux tray, and the Windows service) still accept `OMP_WEB_PASSWORD` at install -time and hash it before writing it to their configuration. Only the hash is -stored. - -On Windows, the tray and background service read `OMP_WEB_PASSWORD_HASH` from -your user or system environment (for example `setx OMP_WEB_PASSWORD_HASH -"scrypt$…"`) each time they start the server, not from the environment they were -started with. Changing or removing the hash takes effect at the next server -restart, without signing out of Windows. - -### Behind a reverse proxy +`bun add -g @ompweb-dev/tau` installs the same package; the `tau` launcher still needs Node.js 24 on `PATH`. +`npx @ompweb-dev/tau@latest` runs it without a global install. -Forward WebSocket upgrades on `/api/events/link` (browsers), `/api/hosts/link` (application traffic) and `/api/hosts/maintenance` (host management and recovery); without the browser upgrade, the browser falls back to server-sent events after a few seconds. In nginx that means `proxy_http_version 1.1;`, `proxy_set_header Upgrade $http_upgrade;`, `proxy_set_header Connection "upgrade";`, and a `proxy_read_timeout` well above 30 s. - -Hosts that [use the server's provider logins](#use-the-servers-provider-logins-on-a-host) also call `/api/hosts/broker/`, authenticated by their host token. That path must reach ompweb without the proxy's own authentication (a proxy login page or `auth_request` would block the daemon), without response buffering (it carries a long-lived event stream; in nginx, `proxy_buffering off;`) and without redirects. - -Cluster members also fetch this machine's omp configuration from `/api/hosts/cluster-config/manifest` and `/api/hosts/cluster-config/file/` (exactly these two paths, `` being 64 hexadecimal digits), authenticated by their host token and answering members only. Unlike the broker's prefix, they must be reachable at exactly these paths, without the proxy's own authentication and without redirects. - -### Two services: the web server and the local daemon - -ompweb runs this machine's `omp` sessions through a small daemon, `ompweb host`, -linked to the web server over loopback. The service installers (`ompweb systemd install`, -`ompweb launchd install`, `ompweb --install-tray`) install both: the web -service and `ompweb-host`. Uninstall removes both. - -**Running ompweb in the foreground** (`ompweb` in a terminal, or -`npx @kahme247/ompweb@latest`) installs no service. The production server prepares -the local link and starts an independent `ompweb host` if none answers its private -control endpoint. It reuses an existing daemon, including an older one awaiting -recovery; concurrent starts cannot create two hosts. A configured native host -supervisor keeps ownership even when startup is slow: the web server does not -replace it with an unmanaged daemon after a fixed grace period. - -- **Restarting or redeploying the web server does not interrupt runs.** The daemon - keeps the omp processes running; the restarted web server takes them over, with - no resume prompt, and dialogs or tool calls omp was waiting on reappear. -- **Restarting the daemon does end runs** (it owns the omp processes). With auto-resume - on, sessions that were running resume once. `ompweb systemd restart` restarts the - web service only. A coordinated upgrade shows any required daemon restart before - asking for approval. -- **A failed local start stays visible.** The web server never installs services - itself. If the daemon cannot start or its endpoint cannot be verified, "This - machine" remains offline and the install/start guidance remains available. -- **It is a host like any other.** Rename "This machine" in **Settings → Hosts** - (clear the name to reset it); it cannot be revoked. The web server writes the - daemon's link (`~/.omp/agent/omp-web/host.json`, mode `600`) at startup, only - for a loopback bind address. -- **Development:** `npm run dev` does not take the daemon (see - [Development](#development)). - -### Coordinated upgrades - -**Settings → System → Update** updates the server, including an owned single-binary -release. It first prepares a plan showing the target version, required host -upgrades, affected sessions and any compatibility or recovery blocker. Compatible -remote hosts keep running; the local host is included when its installation must -be replaced or its protocol upgraded. - -Review the plan, then approve it. An update that must interrupt sessions or use -legacy recovery requires a separate, unchecked **Force** confirmation. Force may -terminate sessions and subagents; it never bypasses release digests, installation -ownership, process identity, service permissions or the update-disable setting. -An unreachable incompatible host blocks a server-only cutover instead of being -silently left behind. -Approval pins the selected release and its artifacts. Changing either requires -a new plan and approval; a later registry `latest` does not replace an approved -target. Required service stop/start permissions are checked before any -incompatible host moves. - -**Settings → Hosts** retains per-host Update and offers **Force update** when a -verified recovery path is available. For old daemons without the maintenance API, -the server uses an isolated, fixed recovery bootstrap through their existing -runner command channel. Windows uses native PowerShell and Windows process/service -APIs; Linux and macOS use their own supervisor controls. A broken legacy runner or -an uncontrollable service is reported, not treated as an updated host. -For systemd, verified user units and elevated system-service control are supported. -A non-root system service with custom polkit grants is refused when its exact -stop/start authority cannot be proved without changing service state; use a user -unit rather than relying on an unverifiable grant. - -All required participants download, verify and preflight their pinned release -before the coordinator authorizes any host to stop. A failed preparation cancels -the other preparations without changing their installations. Host version, -protocol and session inventory are checked again before committing and before -server cutover; an unrelated change invalidates the approved plan. -Progress survives web-server restarts; completion requires the expected release, -approved protocol receipt and connection to the specific server being upgraded. A failed -cutover restores the previous installation where possible and reports any -participant still requiring recovery. An uncertain shutdown or maintenance reply -retains its update claim and displays the recovery error instead of permitting a -second update. Closing the dialog does not cancel a committed update. - -### Transparent host pools - -ompweb has at most one cluster: the first pool in `pools.json`. This machine is its master. -Creating the cluster adds this machine; an existing first pool that lacks it gains it on the -next join. The cluster appears in the sidebar as one group with one entry per Git repository. -Choose the cluster rather than a member; new independent sessions are placed on an eligible -member and receive an isolated local worktree. Adding a cluster project registers -its Git origin, not a central clone; adding another URL form of a repository the cluster -already has returns that project, unhidden, and keeps its stored origin. The selected member -prepares its checkout when the session starts and reports authentication, preparation, or -repository conflicts explicitly. -Standalone hosts, including the Mac, keep their own groups with typed paths and local clone -progress/cancellation. Resolving the owner for a new chat's attachment does not replace its -live composer or discard its draft and uploads. Placement and preparation failures are also -shown when command discovery or system-prompt inspection starts a session lazily; retrying -remains an explicit user action. - -**Joining and leaving.** Each linked host has an **In the cluster** switch in **Settings → -Hosts**. Turning it on asks for a folder on that host for the checkouts the cluster creates -(default `/ompweb-cluster`) and shows what changes. It needs the host online, its daemon -on link protocol 10 with the `gitOrigins` operation, and omp 15.13.1 or newer (a member always -uses this machine's provider logins); otherwise the disabled switch asks for an update of -ompweb or omp, or shows the host's unavailable status. While this machine is not a member yet, -its own daemon needs the same, and the switch asks to restart the host service on this machine -(or to update its omp). - -- **Joining:** the host's Git projects are matched by repository: the same repository on - several members is one cluster project, and its sessions are listed together. `git@github.com:a/b.git` - and `https://github.com/a/b` are the same repository. Projects without a single Git `origin`, - subfolders and linked worktrees stay on their node; the cluster shows them with the node's - name, and a new session there starts on that node. No project files on the host change. A - cluster project created from a host project keeps the name and alias it showed (the folder - name when it had no name of its own). A visible checkout that matches a hidden cluster project - makes that project visible again. This machine joins with the first host added while it is - not a member (when the cluster is created, or on the next join of an older first pool without - it): its Git projects then become cluster projects too, and new sessions in them start on any - member with capacity, not in its own checkout. - A second checkout of a repository already bound on that host also stays on its node. - Projects inside, or containing, the chosen checkout folder stay on their node too; pick an - empty folder that is not a parent of existing projects. -- **Leaving:** the host takes no new cluster sessions. Its matched projects are listed under - the host again. Checkouts the cluster created inside the host's folder stay bound, so - sessions the cluster started there stay under the cluster's projects. The cluster keeps the - projects it gained from the host, so they may now be listed twice; hide any you do not want. - This machine cannot leave, and the cluster stays when the last linked host does. Revoking a - member removes it from the cluster the same way; while `pools.json` cannot be read, the revoke - is refused. -- **Provider logins:** a member always uses this machine's provider logins, whatever its own - [**Use this server's provider logins**](#use-the-servers-provider-logins-on-a-host) setting - says; Settings shows it on and disabled. This is computed from membership, so leaving brings - the host's own setting back. A member can read this machine's access tokens and stored API - keys. Cluster placement skips a member that cannot take these logins (daemon below link - protocol 9, or a link that does not share) before preparing a checkout there. The rest of - this machine's omp configuration (`models.yml`, settings, MCP servers, skills, plugins and - more) is mirrored to members too; see [Cluster members use this machine's omp - configuration](#cluster-members-use-this-machines-omp-configuration). -- **Limits:** a host that is too slow to report its Git remotes within the time limit keeps - the remaining projects on its node; leaving and joining again retries them. Only Linux hosts - report capacity, so a macOS or Windows master never runs cluster sessions itself: its Git - projects start only on other members, and a start fails with "No pool worker currently has - eligible capacity" when none has capacity. A pool disabled through the API takes no new - sessions, including this machine's Git projects moved into it, which then cannot start - anywhere; its members still use this machine's provider logins. Settings cannot enable it - again. - -**Upgrade note.** After this update, every linked host already in the first pool uses this -machine's provider logins (it can read their access tokens and stored API keys), without a -confirmation having been shown. This includes a first pool disabled through the API, and a -host added to the first pool later through `PUT /api/hosts` or by editing `pools.json`: -membership, not scheduling, grants the logins. Each linked member needs an updated ompweb host -daemon (link protocol 9 at that release; cluster members now need link protocol 10, see the next -note) and omp 15.13.1 or newer; until the daemon is updated, cluster -placement skips that member, and a start fails when no other member is eligible. Before -updating, remove a host that should not receive the logins from the first pool using -`PUT /api/hosts` or editing `~/.omp/agent/omp-web/pools.json`; the old version has no -membership switch. - -**Upgrade note (configuration).** Joining the cluster, and every cluster session on a member, -now need an ompweb host daemon at link protocol 10 on that member. Until a member's daemon is -updated, session starts there are refused ("Update ompweb on the host…"), cluster placement -skips it, and Settings → Hosts says it needs an update. Once its daemon is updated, every host -already in the first pool receives this machine's configuration, secrets included (API keys, -MCP environments and headers, tokens), automatically and without a confirmation having been -shown, within about a minute, and its own configuration is replaced until it leaves (see -below). To avoid that for a host, remove it from the first pool before updating its daemon, -using `PUT /api/hosts` or editing `~/.omp/agent/omp-web/pools.json`. Update the web server -first, then the members. - -Creation retries reuse the same intent and creation identity. Once a real session is known, -its owner remains authoritative for resume, files, terminal, uploads, artifacts, rename, and -delete, even if pool membership changes. An unavailable owner does not trigger replacement -on another worker or on the Mac. Dirty files and unpublished work remain on that owner; -there is no live migration or unpublished-work failover. After an uncertain response, -inspect the retained session before explicitly retrying a command that may have run. - -### Cluster members use this machine's omp configuration - -A cluster session can run on any member, and each member runs it with this machine's omp -configuration: the models, MCP servers, skills, task agents, rules and plugins do not depend on -the member chosen. A change made here, in Settings or on disk, reaches the members within about -a minute without any action on them, and before every session start on a member. A host outside -the cluster keeps its own configuration, managed on that machine. - -- **What is mirrored:** from this machine's omp agent directory (`~/.omp/agent`): `config.yml` - (without the keys below), `models.yml`, `mcp.json`, `.mcp.json`, `AGENTS.md`, `RULES.md`, - `SYSTEM.md`, `APPEND_SYSTEM.md`, `TITLE_SYSTEM.md`, `secrets.yml`, `.env`, and the directories - `skills/`, `agents/`, `rules/`, `instructions/`, `commands/`, `prompts/`, `hooks/`, - `extensions/` and `tools/`. Also `~/.agents/skills/` (where Settings installs skills), the - agent environment variables of **Settings → System**, and the set of installed plugins with - whether each is enabled. A mirrored directory becomes equal to this machine's: a file that - exists only on the member is removed from it. `node_modules` and `.git` directories are left - out. The member's backup holds only what the host had when it joined; a file added or edited - on the member afterwards is deleted at the next apply, not backed up. -- **What is not mirrored:** `lsp.json`, `ssh.json`, themes, key bindings, sessions, history, - `agent.db`, caches and `secret-placeholder.key`; configuration inside a repository (`.omp/` - travels with the checkout); named omp profiles (a cluster project that names a profile runs - with that profile's own files on each member); and programs: an MCP server's command, a - language server or a local model engine that exists only on this machine is not installed on - members. -- **Settings that stay the member's own:** `shellPath`, `python.interpreter`, `browser.*`, - `worktree.base`, `plan.autosaveDir`, `shellMinimizer.settingsPath`, `mnemopi.dbPath`, - `workspace.additionalDirectories`, `skills.customDirectories`, `extensions`, `images.urls.*`, - `providers.tinyModelDevice`, `providers.tinyModelDtype`, `tts.*`, `stt.*`, `tui.*`, - `terminal.*`, `lsp.*` and `auth.broker.*`. A member keeps its own value for each of them as - it was when the host joined, or none; a change made on the member afterwards is reset at the - next apply. -- **Limits:** a file over 5 MiB, a configuration over 50 MiB in all, or so many files that their - list is over 5 MiB, is not mirrored at all: this machine serves no configuration, a cluster - session start on a member is refused (409 `cluster_config_invalid`), placement skips every - member, and **Settings → Hosts** names the file that is over, or says there are too many - files. A `config.yml` that is not a YAML map or a file that cannot be read does - the same. Each download a member makes (the list of files, and each file) must finish within - 30 s, body included; a 5 MiB file needs roughly 1.4 Mbit/s, and a member on a slower link - does not update. -- **When a member applies it:** after joining; when it is behind this machine's version - (checked every 30 s and at each cluster session start on a member; a new version found - either way is sent to every member at once); and before every session start on the member, which waits for it. The - files are written whole or not at all: a failure leaves the previous version in place. Every - cluster session start carries this machine's version, and a start that must run on that - member (a resumed session, a project pinned to its node) is refused with the reason when the - files cannot be applied; new cluster sessions are placed only on members that have this - machine's current configuration and plugins. A session recovered after a daemon restart, or - started by another ompweb server, runs on whatever is on the member's disk at that moment. - Sessions already running are not restarted. The applied files are readable by the daemon's - user only. -- **Plugins:** after the files, the member runs `omp plugin` itself to install what it lacks - (this needs `bun` and network access on the member), uninstall what this machine does not - have, and match each plugin's enabled state. npm plugins - are pinned to this machine's version; a marketplace plugin has no version pin in omp, so one - already installed counts as matching. A session start does not wait for its own version's - plugins, but a start that needs a new version waits behind a plugin job that is still running - (up to 5 minutes for each install). A new version with the same plugins keeps the member - current while its plugins are checked again. A failed install - leaves the member not current, so placement skips it; it is retried about every 30 s and - Settings shows omp's message. -- **Joining:** needs link protocol 10 on the host. Before the first apply, the host's own - version of every mirrored file and directory moves to `/omp-web/own-config/` on - the host, with its plugin list and agent environment variables; the join dialog says the host - receives this machine's configuration, API keys and environment values included, in place of - its own until it leaves. A host holds one ompweb server's configuration at - a time: a host already in another server's cluster cannot join (409 `host_in_other_cluster`) - and must leave that cluster first. If the host also runs sessions for another ompweb server - (as a standalone host there), they run on this server's configuration for as long as the host - is a member here. -- **Changes made on a member** to a mirrored file are overwritten at the next apply; change the - configuration here. An apply is refused when `~/.agents` is a symbolic link on the member: - replace it with a real directory. The - mirrored directories, the staging area and the backup must be on one filesystem. -- **Leaving:** the daemon removes the mirrored files, moves its backup into place, puts back - its agent environment variables, and reinstalls its own plugins as far as omp allows. Its own - `config.yml` is its own file again. If putting its configuration back fails, Settings says so - and the restore is retried while the host is linked, also for a host that was offline when it - left. A member that is revoked gets its own omp configuration back from its daemon: at once if - the daemon is connected, otherwise the next time it reaches this machine (and is refused). A session start - that races a leave is refused. This machine is the master: nothing is - mirrored to it and nothing of it is backed up. -- **Settings:** each member's line in **Settings → Hosts** shows *same as the master*, - *updating…*, *failed* with the reason, *held by another ompweb server*, or that the host needs - an update, and the MCP server commands in the mirrored files that are not installed there. - When this machine's configuration cannot be mirrored, one message names the file, and no - member line says *updating…*. For a session or project of the cluster, the Models, settings, MCP, Skills, Plugins and Agents - screens say that changes apply to every member, and so does **Settings → System** next to the - agent environment variables. For a session on another member they act on - this machine's user-level configuration, which the member runs; that session's and project's - own configuration is not shown there. MCP shows that session's live status, read from the - process where it runs, and cannot change it; MCP toggles, reload and Skills diagnostics for - the session are not available there. -- **API:** `GET /api/plugins`, `POST /api/plugins`, `GET /api/skills`, `POST /api/skills/check` - and `POST /api/skills/update` accept a request without `cwd` and then act on the user level - only (a project-scope change still needs a `cwd`). `GET /api/mcp?sessionId=…&attach=1` reads - the live MCP status of a session that is already running and never starts one. -- **Security:** the configuration contains secrets: API keys in `models.yml` and `.env`, MCP - server environments and headers, tokens in `config.yml` and the values in `secrets.yml`. They - are written to every member's disk, readable by the daemon's user only; a member can already - read this machine's provider logins, and this adds the rest. Hooks, extensions, custom tools - and plugins are code: this machine's code runs on every member; this machine can already - start omp with full tool access there. Nothing flows the other way: - a member cannot change this machine's configuration, and the routes only serve members, - checked on every request, and stop answering a host the moment it leaves or is revoked. -- **Differences that remain:** a provider in `models.yml` that points at this machine's own - address (for example `http://127.0.0.1:11434`) points at the member's own address there, so a - local engine has to run on each member or be given an address they can all reach. An API key - written as an environment-variable name or as a `!command` resolves on the member: the - variable or command must exist there (variables set in Settings → System or in the mirrored - `.env` do). MCP servers started by a command need that command on each member. - - -### Local worker maintenance - -`ompweb host status` prints daemon PID, native version/protocol, welcomed-link readiness, -executable/entrypoint identity and maintenance state without credentials. -`ompweb host drain` synchronously checks children (idle included), preparations, -uploads/controls, pending operations and reliable results, and closes new-work admission -only when idle. A busy refusal never kills work or changes admission. -`ompweb host resume` reopens the live daemon. Controls run inside the existing daemon, not -TCP or a separate service: a private Unix socket on Linux and macOS, and on Windows a named -pipe with a random name and a per-start token. Windows keeps both in -`/omp-web/host-control.json`, which only the daemon's user can read through the -agent directory; a request without the current token is refused. A disconnected deployer -cannot release a live drain. Windows hosts report CPU and memory capacity too, so they can be -pool workers. -Disable central member admission before worker rollout; native drain is the final race-free guard. - -Worker service cutovers can additionally start drained through `OMP_WEB_HOST_DRAINED=1` -in their protected temporary unit environment. Live resume does not remove that startup -setting. After a deployer crash or lost final resume reply, verify the selected release, -PID and welcomed-link health, and remove the known worker maintenance flag before explicit -resume. Never infer from a missing acknowledgement that admission stayed closed, and never -stop or roll back a candidate after its deployment commit point. +tau opens `http://127.0.0.1:30187` in your browser. Sign in to your model providers in **Settings → API Keys & +Providers** (see [Configuration](#configuration)), pick a workspace and start a session. ### Single binary -Each [release](https://github.com/ompweb-dev/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, and no omp: on its first start it downloads its own omp build, `ompweb-omp`, from the same release -(SHA-256-checked) and keeps it beside itself (prerelease archives already carry it). 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/`. Every commit on `main` that passes CI is also published as a -[prerelease](https://github.com/ompweb-dev/ompweb/releases) named after the time it was -built (for example `2026-11-01T10:30:00Z`), with the same five archives. +Each release also ships tau as one compiled program with the files it serves beside it: +`tau-linux-x64.tar.gz`, `tau-linux-arm64.tar.gz`, `tau-darwin-x64.tar.gz`, `tau-darwin-arm64.tar.gz` and +`tau-windows-x64.zip`. It needs no Node.js, npm or Bun of its own. It does not ship pi: it runs the `pi` on `PATH` +(or `TAU_PI_BIN`). Every commit on `main` that passes CI is also published as a prerelease with the same archives. ```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 -``` - -- **Keep `ompweb` in its directory.** It runs the `ompweb-omp` beside it and 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. -- **GUI updates, without a tray or service installer.** **Settings → System** - prepares and confirms an update of the owned release directory and any required - host migration. **Settings → Hosts** manages individual daemons. Keep the release - directory writable only by its owner and retain permission to control its service - or scheduled task. Sessions and settings live in `~/.omp`, outside that directory. -- **As systemd user services**, write the two units yourself (adjust the paths): - -```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 +tar -xzf tau-linux-x64.tar.gz -C ~/.local/share # unpacks tau-linux-x64/ +~/.local/share/tau-linux-x64/tau # same options and environment variables as the npm launcher ``` -```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 +- Keep `tau` in its directory: it serves `dist/`, `public/` and its pi extension from there (a symlink on your `PATH` + works), or from `TAU_PACKAGE_DIR` when that is set. +- The binary has `tau host` and `tau hash-password`, but no tray and no service installer. Write service units + yourself, as shown under [Services](#services). +- macOS quarantines downloads: run `xattr -dr com.apple.quarantine tau-darwin-arm64` once before the first start. +- macOS 15 and later ask before an app may reach your local network. If `tau host` reports `ECONNREFUSED` for a + server on your LAN while `curl` reaches it, allow your terminal (or `tau`) under System Settings → Privacy & + Security → Local Network. -[Install] -WantedBy=default.target -``` +### From source ```bash -systemctl --user daemon-reload -systemctl --user enable --now ompweb ompweb-host +git clone https://github.com/ompweb-dev/tau.git +cd tau +npm install +npm run build +node bin/tau.js ``` - 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 -### Run as a Windows Service (System Tray) - -Install ompweb as a Windows background service with a system tray icon and autostart at login: - -```bash -ompweb --install-tray -``` +```text +tau [options] -Manage it from **Settings → System → Windows Background Service**, or via CLI: + -p, --port Server port (default 30187, env PORT) + -H, --hostname Bind hostname (default 127.0.0.1, env TAU_HOSTNAME) + --no-open Do not open the browser automatically + --install-tray Install the tray, background service and shortcuts (Windows; Linux SNI tray) + --uninstall-tray Uninstall them + --tray Start the background tray manager + -h, --help Show help + --version Show the version -```bash -ompweb --tray # Start the tray manager -ompweb --uninstall-tray +tau hash-password Read a password from stdin and print the value for TAU_PASSWORD_HASH +tau host ... The host daemon (see "Hosts and cluster") +tau systemd ... | tau launchd ... Forward to tau-systemd / tau-launchd ``` -Shortcuts are created on the Desktop and Start Menu. The service restarts automatically and shows the current port and status in the tray. The install also registers the [local daemon](#two-services-the-web-server-and-the-local-daemon) as a second scheduled task (`ompweb host`); the tray shows both states. +The production server also starts this machine's host daemon (`tau host`) if none is running: every session, local +ones included, runs under that daemon, so restarting the web server does not stop running sessions. -### Run as a macOS Service (launchd) +### Environment variables -Install ompweb as a launchd user agent that starts at login and restarts on crash: +| Variable | Meaning | +| --- | --- | +| `PORT` | Server port (default `30187`). | +| `TAU_HOSTNAME` | Bind address (default `127.0.0.1`). | +| `TAU_NO_OPEN` | `1`, `true`, `yes` or `on`: do not open a browser. | +| `TAU_PASSWORD_HASH` | Password hash from `tau hash-password`. Enables the sign-in page. | +| `TAU_TRUSTED_HEADER_SHA256` | SHA-256 hex digest of a secret that a trusted reverse proxy sends in `X-Tau-Auth` (see [below](#skipping-the-password-behind-a-trusted-proxy)). | +| `TAU_PI_BIN` | Path of the `pi` binary to run instead of the one on `PATH`. | +| `PI_CODING_AGENT_DIR` | pi's agent directory (default `~/.pi/agent`); tau reads and writes the same one. | +| `TAU_NAME` | Display name in the browser title. `url`, `host` or `domain` derive it from the request's host name. | +| `TAU_DISABLE_AUTOUPDATE` | `1`, `true`, `yes` or `on`: refuse in-app updates of the server and hosts. | +| `TAU_STT_ENDPOINT`, `TAU_STT_KEY`, `TAU_STT_MODEL` | Voice transcription: the endpoint receives a multipart `file` (and `model`), with `TAU_STT_KEY` as a bearer token. Without an endpoint, voice input is off. | +| `TAU_DISCONNECT_DESTROY_MS` | How long a session process may stay unwatched before it is stopped (default 2 minutes, `0` disables). | -```bash -npx --yes @kahme247/ompweb@latest ompweb-launchd install -``` +### Password -Manage it with: +Bound to `127.0.0.1`, tau needs no password. To listen on any other address, tau requires a password hash and +refuses to start without one: ```bash -npx --yes @kahme247/ompweb@latest ompweb-launchd status # Show service state -npx --yes @kahme247/ompweb@latest ompweb-launchd uninstall # Stop and remove +tau hash-password # prompts, input hidden +echo "a-long-random-password" | tau hash-password +TAU_PASSWORD_HASH='scrypt$15$8$1$...' tau --hostname 0.0.0.0 ``` -The service runs `npx --yes @kahme247/ompweb@latest`; pass a package spec to pin a -version, e.g. `ompweb-launchd install @kahme247/ompweb@0.3.6`. All -[environment variables](#environment-variables) are read at install time and baked -into the plist, plus `OMP_WEB_PKG` (package spec, same as the positional argument). -As a service, the browser is **not** auto-opened by default — install with -`OMP_WEB_NO_OPEN=0` to restore that. - -```bash -OMP_WEB_PASSWORD=secret npx --yes @kahme247/ompweb@latest ompweb-launchd install -``` +tau accepts only the hash. The `--password` flag is refused. A plaintext `TAU_PASSWORD` is still detected: tau hashes +it at startup, removes it from its environment and prints a warning with the hash to use instead (set together with +`TAU_PASSWORD_HASH`, it is refused). The reason: every pi session inherits tau's environment, so an agent could print a +plaintext password into its transcript. Browser sign-ins last 30 days. -`OMP_WEB_PASSWORD` is hashed at install time; the plist holds the hash, never -the password. Pass `OMP_WEB_PASSWORD_HASH` to install a hash you generated with -`ompweb hash-password`. +### Behind a reverse proxy -When binding to a non-loopback host, require authentication (`OMP_WEB_PASSWORD_HASH` -or equivalent access control) and HTTPS through a trusted reverse proxy or VPN. -Never expose the unauthenticated web UI or send its password/session cookie over -plaintext HTTP. +Without TLS, tau warns when it listens on a non-loopback address. Serve it over HTTPS through a reverse proxy or a +VPN, and keep tau itself bound to `127.0.0.1`. The proxy must pass WebSocket upgrades (hosts use +`/api/hosts/link` and `/api/hosts/maintenance`). It must not add its own authentication +on the paths that hosts authenticate with their token: `/api/hosts/link`, `/api/hosts/maintenance` and +`/api/hosts/cluster-config/…`. -Logs go to `~/Library/Logs/ompweb/ompweb.log` (web) and -`~/Library/Logs/ompweb/ompweb-host.log` (the -[local daemon](#two-services-the-web-server-and-the-local-daemon)). The plists live at -`~/Library/LaunchAgents/com.kahme247.ompweb.plist` (mode 600; the password -hash — not the password — is stored there) and -`~/Library/LaunchAgents/com.kahme247.ompweb-host.plist`. +#### Skipping the password behind a trusted proxy -### Run as a Linux Service (systemd) +tau cannot see client addresses itself, so a reverse proxy can vouch for requests instead. The proxy sends a secret in +the `X-Tau-Auth` header, and tau holds only the secret's SHA-256 digest in `TAU_TRUSTED_HEADER_SHA256`. A request whose +header hashes to that digest counts as signed in. Without a password hash there is nothing to skip. -Install ompweb as a systemd **user** service that starts at login and restarts -on crash: +Generate a long random secret without putting it on a command line. This writes it into an nginx include file and +prints only the digest: ```bash -npx --yes --package=@kahme247/ompweb@latest ompweb-systemd install +secret=$(openssl rand -hex 32) +printf 'map $tau_trusted $tau_auth {\n 1 "%s";\n default "";\n}\n' "$secret" \ + | sudo install -m 0640 -o root -g www-data /dev/stdin /etc/nginx/tau-auth.conf +printf %s "$secret" | sha256sum | cut -d' ' -f1 +unset secret ``` -The installer creates `~/.omp/agent/web-service.env` automatically with mode -`600`; no manual file creation is required. The explicit `--package` form makes -`npx` run the systemd executable from the selected package. -To bind the service to all IPv4 interfaces for LAN access, set a password while -installing: +```nginx +# http {} context +geo $tau_trusted { + default 0; + 10.0.0.0/16 1; +} +include /etc/nginx/tau-auth.conf; -```bash -OMP_WEB_HOSTNAME=0.0.0.0 OMP_WEB_PASSWORD='change-me' \ - npx --yes --package=@kahme247/ompweb@latest ompweb-systemd install +# the location that proxies to tau +proxy_set_header X-Tau-Auth $tau_auth; ``` -The password is hashed before it is written to `web-service.env`. +Always set the header, so the empty value replaces any `X-Tau-Auth` a client sends. Give tau's `server` block an +explicit `server_name` and answer other host names with `return 444;` in a `default_server` block, so DNS rebinding +cannot make nginx add the secret to another site's requests. tau stores only a fast SHA-256 digest, which is safe only +for a long random secret: never reuse a password here. -Manage it with: +## Services -```bash -npx --yes --package=@kahme247/ompweb@latest ompweb-systemd status # Show service state -npx --yes --package=@kahme247/ompweb@latest ompweb-systemd restart # start / stop / restart -npx --yes --package=@kahme247/ompweb@latest ompweb-systemd uninstall # Stop and remove -``` +Each installer runs two services: the web server and the host daemon (`tau host`). -The service runs the locally installed `ompweb` binary resolved at install time -(override with `OMP_WEB_SYSTEMD_BIN`). Runtime configuration lives in -`~/.omp/agent/web-service.env` — the tray (or any editor) can change the port, -hostname, and password hash there and just restart the service; no reinstall -needed. -Install-time [environment variables](#environment-variables) are baked into -that file. As a service, the browser is **not** auto-opened by default. The -units live at `~/.config/systemd/user/ompweb.service` and -`~/.config/systemd/user/ompweb-host.service` (the -[local daemon](#two-services-the-web-server-and-the-local-daemon)); logs go to -the journal: +### Linux (systemd user services) ```bash -journalctl --user -u ompweb -u ompweb-host -f +TAU_PASSWORD_HASH='scrypt$...' tau-systemd install # or: npx --yes --package=@ompweb-dev/tau@latest tau-systemd install +tau-systemd status ``` -On a headless server, enable user lingering if the service must keep running -after the last login session ends: - -```bash -loginctl enable-linger "$USER" -``` +`install` writes the units `tau.service` and `tau-host.service` to `~/.config/systemd/user/`, creates +`~/.pi/agent/web-service.env` (port, hostname, password hash; edit it without reinstalling) and enables both. Other +commands: `uninstall` (`--clean-config` also removes the env file), `start`, `stop`, `restart` (web service only), +`open`. Options: `--port`, `--hostname`, `--no-autostart`, `--json`. Logs: +`journalctl --user -u tau -u tau-host -f`. -### Linux System Tray (KDE Plasma and compatible) +On KDE Plasma and other StatusNotifierItem desktops, `tau --install-tray` adds a tray icon that controls these +systemd services. -On Linux, `ompweb-tray` registers a StatusNotifierItem tray icon with a context -menu: open the web UI, copy its URL, start/stop/restart the systemd service, -view logs, expose the web UI to the network, change the port, set the web -password, toggle autostart, and quit the tray. +### macOS (launchd) ```bash -npx --yes @kahme247/ompweb@latest ompweb-tray --install # Icons + autostart + start tray -npx --yes @kahme247/ompweb@latest ompweb-tray --status # Tray and service status -npx --yes @kahme247/ompweb@latest ompweb-tray --uninstall # Remove autostart, stop tray +TAU_PASSWORD_HASH='scrypt$...' tau-launchd install # or: npx -p @ompweb-dev/tau@latest tau-launchd install +tau-launchd status +tau-launchd uninstall ``` -**Expose to Network** rebinds the service from `127.0.0.1` to `0.0.0.0` so the -web UI is reachable from your LAN or VPN (e.g. Tailscale). Leaving loopback -requires a web password — the tray prompts for one via `kdialog`/`zenity` when -needed, and stores its hash. **Change Port…** and **Set Web Password…** edit -`~/.omp/agent/web-service.env` and restart the service. When binding to a -non-loopback host, use HTTPS through a trusted reverse proxy or VPN for remote -access. - -"Start with Plasma" in the tray menu toggles a desktop autostart entry at -`~/.config/autostart/ompweb-tray.desktop`. Requires a running StatusNotifierItem -host (KDE Plasma, and most Wayland/X11 desktops). +`install` creates the LaunchAgents `dev.ompweb.tau` and `dev.ompweb.tau-host`, which start at login and restart on +crash. It reads `PORT`, `TAU_HOSTNAME`, `TAU_PASSWORD_HASH`, `TAU_TRUSTED_HEADER_SHA256`, `TAU_PI_BIN`, `TAU_NAME`, +`TAU_DISABLE_AUTOUPDATE` and `PI_CODING_AGENT_DIR` from the environment it runs in. Logs go to `~/Library/Logs/tau`. -## Run sessions on another machine +### Windows (tray and background service) -One ompweb can start and watch omp sessions on other machines. Each machine keeps -its own ompweb (with its `ompweb-omp`), `~/.omp/agent` directory, sessions, and credentials (unless you -[share the server's provider logins](#use-the-servers-provider-logins-on-a-host)); -ompweb only routes. The remote machine needs either Node 24 (for `npx`) or -the [single binary](#single-binary), and must be able to reach the ompweb server over -HTTP(S). It dials out, so it can sit behind NAT. +```powershell +tau --install-tray +``` -1. On the ompweb server, open **Settings → Hosts → Add host**, enter a name, and copy - the token. The token is shown once; only its hash is stored. -2. On the remote machine, save the link. The token is read from stdin, never from - an argument, so it does not show up in `ps`: +This installs the background service, the host daemon (scheduled task `tau-host`), a tray icon, logon autostart and +Desktop/Start Menu shortcuts. `tau-tray status|start|stop|restart|open|uninstall` manage it. The service reads its +settings from `%USERPROFILE%\.pi\agent\web-service.json`, and `TAU_PASSWORD_HASH` from your user or system environment. - ```bash - npx @kahme247/ompweb@latest host login --url https://your-ompweb.example.com - ``` +### Single binary as a service - Paste the token when prompted (or pipe it in). It is saved to - `~/.omp/agent/omp-web/host.json` with mode `600`. -3. Start the link and leave it running: +Write the two units yourself. For systemd (adjust the paths): - ```bash - npx @kahme247/ompweb@latest host - ``` +```ini +# ~/.config/systemd/user/tau.service +[Unit] +Description=tau web service - The host shows **online** in Settings → Hosts, the sidebar gets a group for it, - and the new-session screen gets a host picker. - -**Settings → Hosts** also shows each machine's ompweb daemon and omp versions, -available updates and update actions, including **This machine**. -Checks and installations run on the selected host, not on the web server. A host -update whose link protocol is incompatible with the current web app stays visible -but is blocked with a reason; update the web server first. An unverifiable target -protocol is blocked too. omp is part of each ompweb release and updates with it. -Before updating a daemon, close its session processes: the updater refuses to -interrupt sessions or subagents. **Settings → System** keeps the web server's -own application update and service settings. - -**From 0.7.1 onward, maintenance API v1 is separate from application Protocol v12.** -The daemon connects to `/api/hosts/maintenance` with the same host token; status, -session inventory and activity, capabilities, update checks and installation do not -require a compatible application connection. An application mismatch still blocks -chat, workspace operations and session attachment, not maintenance. - -**Upgrading v10 and v11 daemons:** update the web server to 0.7.1 first, then use -**Settings → Hosts → Update**. An upgrade-only shim welcomes each old daemon using -its own protocol and speaks only its existing updater's requests. It never adopts -or stops its sessions, and the old updater still refuses a busy host. Close those -session processes before the cutover. If server and daemon share an installation, -the server update puts the new files in place and the host update only restarts -the daemon. A daemon that already exited after an earlier version rejection needs -starting once; an exited process cannot be reached by the shim. - -Reverse proxies must forward WebSocket upgrades for `/api/hosts/maintenance` -without an additional authentication prompt, just as for `/api/hosts/link`. -Daemons below v10 or without the existing update operations need one manual update. -Unsupported service wrappers and detected restart -scripts show a manual-update reason. Stop external restart loops before updating -a foreground daemon. - -A daemon update is carried out by a separate updater process on the host. It -stops the daemon, swaps in the new release and starts it again, and on a failure -it restores the previous release. If that updater is itself killed after stopping -the daemon (a reboot, an out-of-memory kill), nothing restarts the host, which -stays offline. Recover on the host: in the folder containing the installation, -`.ompweb-backup-` is the previous release. If it is there, move the -installation aside and rename the backup back to the installation's name; then -start `ompweb host` (or its service) again. Settings → Hosts reports the update -as interrupted. - -`https://` is required. Plain `http://` is accepted only for loopback addresses, or -with `--allow-http` (for example on a tailnet): +[Service] +WorkingDirectory=%h +ExecStart=%h/.local/share/tau-linux-x64/tau --no-open +Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin +# TAU_PASSWORD_HASH, PORT and TAU_HOSTNAME go here. +EnvironmentFile=-%h/.pi/agent/web-service.env +Restart=on-failure +RestartSec=3 -```bash -npx @kahme247/ompweb@latest host login --url http://100.64.0.1:30177 -npx @kahme247/ompweb@latest host --allow-http +[Install] +WantedBy=default.target ``` -If the connection drops, the daemon reconnects by itself (1 s backoff doubling to -60 s; 3 s at most for the web server on the same machine). After a failed dial it -re-reads its saved link, so a web server that came back on another port is found -without restarting the daemon. After a network drop, runs keep going on the remote machine; the chat shows -an offline banner and the runs reattach when the link returns. A laptop that goes -to sleep (closing the lid, usually) pauses the daemon and its omp runs along with -everything else on it: they resume when it wakes, and the link returns then. A -docked or no-sleep setup keeps running with the lid closed. Revoking a host in -Settings closes its link and the daemon stops its omp processes. - -A reverse proxy must forward the upgrade on `/api/hosts/link`. For hosts that share the server's logins it must also pass `/api/hosts/broker/` without the proxy's own authentication and without response buffering; for cluster members, likewise `/api/hosts/cluster-config/manifest` and `/api/hosts/cluster-config/file/` without the proxy's own authentication. See [Behind a reverse proxy](#behind-a-reverse-proxy). - -Update ompweb on the server before its hosts: a host from before this version shows **needs upgrade** until it is updated. - -Notes: - -- **Service helpers:** `ompweb systemd install` and `ompweb launchd install` set up - this machine's own daemon next to its web server (see - [Two services](#two-services-the-web-server-and-the-local-daemon)). On the other - machine you only need the daemon, so use - [Keep a host running as a service](#keep-a-host-running-as-a-service) instead. - The daemon exits with code `1` when the server revokes its token or when its - link protocol version is outside the range the server supports (older than the - server's oldest supported version, or newer than the server: update ompweb on - the older side), and `0` when a newer link for the same host replaces it. - SIGTERM or SIGINT stops the daemon and its omp processes. - A link is one-per-host, so never run two daemons with the same token. -- **The server's agent directory holds the host list** (`omp-web/hosts.json`). - Starting the ompweb server with a different `PI_CODING_AGENT_DIR`, or losing - that file, makes every host token unknown: each daemon is told it was revoked, - stops its omp processes and exits. -- **Trust:** a linked host runs omp with full tool access on that machine for - whoever controls the ompweb server or the token. Keep the token private and - revoke it when a machine is retired. -- **Workspace files on every host:** Explorer, previews, downloads, file search, - @-mentions and live file watching use the owning machine's daemon, including - This machine. Explorer uploads accept up to 2 GiB per file with no 100 MiB batch - cap; preview limits remain 256 KiB for text and 10 MiB for images/DOCX. - File tabs retain their source session, host and workspace when you switch chats; - paths from another conversation cannot be mentioned into the selected chat. - An unavailable or older daemon reports offline or asks for an update; main - never substitutes its own filesystem. Unprepared pool chats have no guessed - filesystem to browse. -- **Git and worktrees on every host:** status, diffs, GitHub issue links, and - worktree creation, selection and removal run on the owning daemon. Dirty - worktrees still require explicit force confirmation. Switching a worktree - changes where new sessions start, not an open conversation. -- **Directory browsing and cloning on every host:** the Add workspace picker - navigates that host's directories and clones HTTPS/SSH repositories there. - Cancelling waits for the clone process and safe cleanup; interrupted connections - report an unknown outcome rather than pretending the clone was cancelled. - If the destination changes during cleanup, captured data is preserved in a - private quarantine and the error gives its location; inspect it before removing - or restoring anything. -- **Not available on remote hosts yet:** the Skills, - Plugins, Agents and MCP settings, for a host outside the cluster (a cluster member uses - this machine's: see [above](#cluster-members-use-this-machines-omp-configuration)). - Transcript search still scans this machine. -- **Agent-started sessions:** with agent tools enabled, an agent can pass a `host` - to `new_session` (it defaults to the agent's own host). A remote host asks for - confirmation each time unless **Agents can start sessions here without asking** - is switched on for it in Settings → Hosts. An agent running on a remote host - always asks before it starts or messages a session on this machine. - -### Use the server's provider logins on a host - -By default a host uses its own omp logins. Turn on **Use this server's provider logins** for a host in **Settings → Hosts** and the sessions started there use the logins stored on the ompweb server instead, so you log in to a provider once. The setting is per host and off by default; turning it on asks for confirmation. This machine does not have it, because it already uses the server's logins. - -- **What is shared:** the provider logins stored on the server (OAuth logins and stored API keys). The server runs `omp auth-broker serve` for this and starts it on the first request; it stops after 5 minutes without one. -- **When a change reaches a host:** every omp process started after a login or logout on the server uses it. A running process picks it up the next time it is used, because omp stops listening for updates after 20 seconds without activity and resumes on its next use. A running process keeps the access tokens and API keys it has already loaded until it ends. -- **What is not shared:** custom providers in `models.yml`, API keys set through environment variables (a host's own environment keys still apply there), and omp settings. A cluster member does get these from this machine: see [Cluster members use this machine's omp configuration](#cluster-members-use-this-machines-omp-configuration). -- **Requirements:** the server's own `omp` must provide `omp auth-broker`. The host's daemon must speak link protocol 9 and its `omp` must be 15.13.1 or newer; otherwise starting a session on that host is refused with a message naming what to update. It never falls back to the host's own stored logins. Joining a session that is already running is not refused. The setting applies to omp processes started after you change it. -- **What the host can read:** the current access token of every OAuth login and every stored API key, in full. A process running as the daemon's user can do the same. OAuth refresh tokens never leave the server machine, and the host cannot add or replace a login. It can mark a login disabled or rate-limited for every machine. -- **Turning it off:** turning sharing off, or revoking the host, aborts the host's open requests to the server and refuses later ones. Access tokens the host already read stay valid until they expire, and API keys until you rotate them at the provider. -- **Dependence on the server:** a running session asks the server whenever an access token needs a refresh, so it fails to authenticate once its token expires while the server is unreachable. An `omp` you run yourself in the host's terminal is unaffected. -- **Troubleshooting:** when sessions on a sharing host fail at startup, check the server log for `[omp-web] broker` lines and that the reverse proxy lets `/api/hosts/broker/` through. - -The host token is not put in an omp process's environment. The daemon listens on a loopback port with a secret it generates at each start, gives omp that address and secret, and forwards the requests to the server with the host token. - -### Keep a host running as a service - -These run the [single binary](#single-binary) in host mode. On Linux and Windows a -service keeps the link up across logouts and reboots; on macOS a script keeps it -running in a terminal (see below for why). Unpack the release for the machine first, -then save the link once with `ompweb host login --url …` as in step 2 (with the -binary's path in place of `npx @kahme247/ompweb@latest`). Each setup starts -`ompweb host` again 10 seconds after it fails, but not after exit 0: that means a -newer link with the same token replaced it, and restarting would take the link back -every 10 seconds. Add `--allow-http` after `host` if -the server URL is plain `http://`, and set `PI_CODING_AGENT_DIR` in the service too -if you saved the link with it set. A machine links to one server: do not also run an -ompweb web server on it, which writes the same link file for its own daemon. To -update, stop the service, replace the release directory, and start it again. After -revoking a host, stop and remove its service: it otherwise keeps retrying. - -**Linux (systemd user service).** Create `~/.config/systemd/user/ompweb-host.service` -(adjust the release path): - ```ini +# ~/.config/systemd/user/tau-host.service [Unit] -Description=ompweb host +Description=tau 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 +ExecStart=%h/.local/share/tau-linux-x64/tau host +Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin +EnvironmentFile=-%h/.pi/agent/web-service.env Restart=always -# Exit 0: a newer link for this host replaced it. Restarting would take the link back. -RestartPreventExitStatus=0 RestartSec=10 [Install] @@ -938,256 +271,149 @@ WantedBy=default.target ```bash systemctl --user daemon-reload -systemctl --user enable --now ompweb-host -loginctl enable-linger "$USER" # keep it running while you are logged out -journalctl --user -u ompweb-host -f # logs +systemctl --user enable --now tau tau-host ``` -**macOS (from a terminal).** No launchd job can run a host that omp sessions can -fully use: a LaunchDaemon has no login keychain or SSH agent, which sessions need -for SSH keys and commit signing, and a LaunchAgent cannot reach LAN addresses. A -process started from a terminal inherits the terminal's keychain and SSH agent, so -run the host there, in tmux so it outlives the window. - -tmux does not keep the terminal's Local Network permission, though: the tmux server -detaches from the terminal app, and macOS Local Network privacy then blocks the -ad-hoc signed `ompweb` binary from LAN addresses (`connect` fails with "No route to -host", which the daemon reports as `ECONNREFUSED`; Apple's own tools such as `curl` -are not blocked, so a `curl` test passes). Link the host to a URL that does not -resolve to a LAN address, for example the server's public URL, or its VPN or -tailnet name (a Tailscale MagicDNS name served by your reverse proxy with its own -certificate). Save this as `~/.local/bin/ompweb-host-run` (adjust `DIR`) and make -it executable with `chmod +x`: - -```sh -#!/bin/sh -# Keeps `ompweb host` running in this terminal, which lends it its keychain and SSH agent. -# Restarts it 10 s after a crash; stops when the token is revoked or the link protocol is -# unsupported (exit 1), or on exit 0: a newer link replaced it, or it was stopped (Ctrl-C). -DIR=${OMPWEB_DIR:-$HOME/.local/share/ompweb-darwin-arm64} -# A tmux started over SSH sees the login keychain locked: unlock it while a terminal can ask. -security show-keychain-info login.keychain-db 2>/dev/null || security unlock-keychain login.keychain-db || exit 1 -while :; do - (cd "$DIR" && exec ./ompweb host) - rc=$? - case $rc in 0 | 1) exit "$rc" ;; esac - echo "ompweb host exited $rc; restarting in 10 s" >&2 - sleep 10 -done -``` +`PATH` must contain the directory of `pi` (and of the Node.js that pi runs on). On macOS, two launchd agents running +`…/tau --no-open` and `…/tau host` with `RunAtLoad` and `KeepAlive` do the same; on Windows, two Task Scheduler tasks +running `tau.exe --no-open` and `tau.exe host` at logon. -Run `ompweb-host-run` in a tmux window; Ctrl-C stops the daemon and its sessions. -Start it again after a reboot or logout. If the login keychain locks itself after -inactivity or on sleep, SSH key passphrases and signing fail until you restart it. +## Hosts and cluster -**Windows (scheduled task at logon).** In PowerShell, with `$dir` set to the -unpacked release: +### The host daemon -```powershell -$dir = "$env:LOCALAPPDATA\ompweb-windows-x64" -New-Item -ItemType Directory -Force "$env:USERPROFILE\.omp\agent\logs" | Out-Null -Set-Content "$dir\ompweb-host.ps1" @' -# Starts `ompweb host` again 10 s after it fails, and stops on exit 0 (a newer link replaced it). -# Output goes to ~\.omp\agent\logs\ompweb-host.log, moved to .log.1 past 10 MB (checked between restarts). -# For a plain http:// server URL, put --allow-http after `host` below. -$log = "$env:USERPROFILE\.omp\agent\logs\ompweb-host.log" -while ($true) { - if ((Test-Path $log) -and (Get-Item $log).Length -gt 10MB) { Move-Item $log "$log.1" -Force } - & "$PSScriptRoot\ompweb.exe" host 2>&1 | ForEach-Object { "$_" } | Out-File -Append -Encoding utf8 $log - if ($LASTEXITCODE -eq 0) { break } - Start-Sleep 10 -} -'@ -Register-ScheduledTask -TaskName ompweb-host -Force ` - -Trigger (New-ScheduledTaskTrigger -AtLogOn -User "$env:USERDOMAIN\$env:USERNAME") ` - -Action (New-ScheduledTaskAction -Execute powershell.exe -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$dir\ompweb-host.ps1`"") ` - -Settings (New-ScheduledTaskSettingsSet -ExecutionTimeLimit 0 -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries) -Start-ScheduledTask ompweb-host -``` - -Stop it with `Stop-ScheduledTask ompweb-host`, then end the running host with -`Get-Process ompweb | Where-Object Path -eq "$env:LOCALAPPDATA\ompweb-windows-x64\ompweb.exe" | Stop-Process` -(only this release's `ompweb.exe`; adjust the path as for `$dir`). Remove it with -`Unregister-ScheduledTask ompweb-host`. +`tau host` is the process that runs pi sessions on a machine and reads its session files. It dials out to one or more +tau servers over a WebSocket, so it can sit behind NAT. Sessions keep running when the link or the web server goes +away, and the server rejoins them when the link returns. On the server's own machine the daemon is linked +automatically ("This machine" in **Settings → Hosts**). -## Features - -- **Interactive Chat**: Real-time streaming conversation with your local `omp` agent — tool calls, thinking levels, token counts, cost, context gauge, queue controls, and interrupt & retry. -- **Message Copy**: Copy user messages and completed assistant replies as rendered plain text or original Markdown using the buttons below each message. Thinking, tool output, and message controls are excluded. Oversized messages that use the raw-text viewer copy their full source in either format. -- **Queue Deletion Confirmation**: Preview and confirm before cancelling queued follow-ups or steered messages in OMP. Requires native `remove_queued_message` support; already-delivered messages cannot be recalled. -- **Session Management**: Browse past conversations by project, fork sessions, branch within a session, archive/restore, import session files, and deep-link via URL. -- **Draft Recovery**: Unsent text stays scoped to its conversation or new-session workspace and is restored after Back/Forward navigation or reload in the same tab when browser storage is available (up to 50 drafts). Images and file attachments remain in memory only. -- **Live Plans & Subagents**: Collapsible panels pinned above the composer track live todo phases and running subagents (status, tool, retries, tokens/cost, nested tasks) with transcript dialogs and history recovery. -- **Tool Preset Picker**: Choose the toolset for new sessions in the composer — `none` / `default` (`read,bash,edit,write`) / `full` (all tools including subagents). Persists to localStorage. -- **File Explorer & Previews**: Browse workspaces side-by-side with chat; preview code, markdown, Mermaid, images, audio, PDFs, and diffs with allow-listed access. -- **Git Worktree Support**: Create, switch, and manage Git worktrees directly from the sidebar; sessions and file roots stay grouped by project. -- **Remote Hosts**: Link other machines (for example a MacBook) and run sessions there from one ompweb. The sidebar groups sessions by host. See [Run sessions on another machine](#run-sessions-on-another-machine). -- **Usage & Analytics**: Dashboard in **Settings → Usage** for tokens, costs, cache savings, and breakdowns by provider / model / day / project with SQLite persistence. -- **Windows System Tray & Service**: Background service, tray icon, logon autostart, and Desktop/Start Menu shortcuts (Windows). -- **macOS launchd Service**: LaunchAgent that starts at login, restarts on crash, and logs under `~/Library/Logs/ompweb`. -- **Linux systemd Service & Tray**: User service that starts at login and restarts on crash, plus a StatusNotifierItem tray icon with service controls (KDE Plasma and compatible desktops). -- **Notifications**: Desktop and mobile (PWA) notifications for finished tasks, questions waiting for an answer, failed runs, and automatic model switches, with Web Push when served over HTTPS. See [Notifications](#notifications). -- **Web-based Settings** (11 tabs): Interface & Behavior, Safety & Approvals, AI Model Defaults, API Keys & Providers, Usage, Agent & Intelligence (advisor, memory, compaction), Agents, Extensions & Tools (MCP, skills, plugins), Hosts, Notifications, System. -- **Slash Commands & Shortcuts**: Quick prompts (`/plan`, `/review`, `/fix`, `/test`, etc.), `⌘K` / `Ctrl+K` palette, and model/reasoning cycling. -- **UI Themes & Localization**: Warm paper light/dark themes plus an omp.sh-inspired midnight (`omp`) theme, chat font size & interface scale, with full English, Chinese (简体中文), and Japanese (日本語) translations. - -## Environment Variables - -| Variable | Description | Default | -| --- | --- | --- | -| `PORT` | Server port | `30177` | -| `OMP_WEB_HOSTNAME` | Server bind host | `127.0.0.1` | -| `OMP_WEB_PASSWORD_HASH` | Optional scrypt hash of the web login password, from `ompweb hash-password`. Required for a non-loopback bind | _None (auth disabled)_ | -| `OMP_WEB_TRUSTED_HEADER_SHA256` | SHA-256 hex digest of the secret a trusted reverse proxy sends in `X-Omp-Web-Auth` to skip the password for that request; see [Skipping the password on trusted networks](#skipping-the-password-on-trusted-networks) | _None (disabled)_ | -| `OMP_WEB_NO_OPEN` | Set to `1` to prevent auto-opening browser | `0` | -| `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 an `ompweb-omp` build to use instead of the downloaded one: a copy of the release's `ompweb-omp--` on a machine that cannot reach GitHub, or `runner/release/ompweb-omp--` from a source checkout. A stock `omp` does not work: it does not speak ompweb's channel. The service installers write it into the service environment only when you set it | _the downloaded `ompweb-omp`_ | -| `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_ | -| `OMP_WEB_STT_MODEL` | Model name for the STT endpoint. Without an endpoint: an omp speech-to-text model run with omp's logins, such as `openai-codex/codex-transcribe` (ChatGPT subscription; needs an omp version with that model) | _None (disabled without an endpoint)_ | - -**`OMP_WEB_NAME` and installed apps.** An installed app (PWA) is usually named after the page it was installed from. If you later change `OMP_WEB_NAME`, or reach omp-web through a different address while `OMP_WEB_NAME` is `url`, `host` or `domain`, your operating system may rename the installed app as well. Leave `OMP_WEB_NAME` empty, or set a name that identifies this omp-web server whatever domain name or address is used to reach it. - -## Skipping the password on trusted networks - -omp-web cannot see the client's address itself, so it leaves the decision to -your reverse proxy. The proxy sends a secret in the `X-Omp-Web-Auth` header, -and omp-web holds only that secret's SHA-256 digest in -`OMP_WEB_TRUSTED_HEADER_SHA256`. A request whose header hashes to that digest -is treated as signed in. Everyone else still signs in with the password whose -hash is in `OMP_WEB_PASSWORD_HASH`; without a password there is nothing to -skip, and the header is ignored. Keep omp-web bound to `127.0.0.1` so only the -proxy reaches it. - -Generate the secret and its digest without typing the secret on a command line, -so it never lands in your shell history. This writes a random secret straight -into an nginx include file readable only by root and nginx, and prints only the -digest: - -```bash -secret=$(openssl rand -hex 32) -printf 'map $ompweb_trusted $ompweb_auth {\n 1 "%s";\n default "";\n}\n' "$secret" \ - | sudo install -m 0640 -o root -g www-data /dev/stdin /etc/nginx/ompweb-auth.conf -printf %s "$secret" | sha256sum | cut -d' ' -f1 -unset secret +```text +tau host login [--add] --url save a link; the host token is read from stdin +tau host logout --url remove a link +tau host [--allow-http] run the daemon +tau host status|drain|resume control the running daemon ``` -Use your nginx group in place of `www-data` (`nginx` on some distributions). -Set the printed digest as `OMP_WEB_TRUSTED_HEADER_SHA256`. The command history -holds only the commands, never the secret. On Windows, the tray and background -service read it from your user or system environment, like -`OMP_WEB_PASSWORD_HASH`. +The daemon accepts only `https://` server URLs, or `http://` for a loopback address. `--allow-http` allows plain HTTP +to other addresses; use it only on a network you trust, since the host token then travels unencrypted. -Always generate the secret this way; do not reuse a password or another chosen -value. omp-web stores only a fast, unsalted SHA-256 digest, which is safe only -for a long random secret: anyone who reads the digest could recover a short or -guessable one with a dictionary attack. +### Link another machine -With nginx, send the secret only to the address ranges you trust: +The other machine needs pi, and tau from npm (Node.js 24) or the single binary. -```nginx -# http {} context -geo $ompweb_trusted { - default 0; - 10.0.0.0/16 1; -} -include /etc/nginx/ompweb-auth.conf; # the map written above +1. On the tau server, open **Settings → Hosts → Add host**, enter a name and copy the token. It is shown once; the + server stores only its hash. +2. On the other machine, save the link. Paste the token when asked, or pipe it in; it never appears in `ps`: -# the location that proxies to omp-web -proxy_set_header X-Omp-Web-Auth $ompweb_auth; -``` - -Always set the header, as above: the empty value for other clients replaces any -`X-Omp-Web-Auth` a client sends itself. nginx only inherits `proxy_set_header` -from outer blocks when a block sets none of its own, so put this line next to -the location's other `proxy_set_header` lines. - -Serve omp-web only for its own hostname: give its `server` block an explicit -`server_name`, and add a `default_server` block that answers every other -hostname with `return 444;`. Otherwise a web page that a trusted browser visits -can point its own domain name at your nginx (DNS rebinding) and have nginx add -the secret to its requests. - -`geo` checks `$remote_addr`, the address that connected to nginx. When clients -reach nginx through another proxy, use the -[`realip` module](https://nginx.org/en/docs/http/ngx_http_realip_module.html) to -replace it with the real client address. It does so only for connections from -addresses you list in `set_real_ip_from`: - -- **Cloudflare (proxied DNS):** trust `CF-Connecting-IP`, and only from - Cloudflare. List every range from and - , and keep them up to date. Use this only - when Cloudflare is really in front. - - ```nginx - set_real_ip_from 173.245.48.0/20; # ...one line per Cloudflare range - real_ip_header CF-Connecting-IP; - ``` + ```bash + npx @ompweb-dev/tau@latest host login --url https://tau.example.com + ``` - Also refuse connections that come neither from Cloudflare nor from your - trusted ranges. `$realip_remote_addr` is the address that actually - connected, before `realip` replaced it: - - ```nginx - geo $realip_remote_addr $ompweb_peer_allowed { - default 0; - 173.245.48.0/20 1; # ...every Cloudflare range - 10.0.0.0/16 1; - } - # in the server block - if ($ompweb_peer_allowed = 0) { return 403; } - ``` + The link is saved in `~/.pi/agent/tau/host.json` with mode `600`. `--add` adds a link to a further server instead + of replacing the first one. +3. Run the daemon and keep it running (as a service, see [Services](#services)): -- **Cloudflare Tunnel (`cloudflared`):** the tunnel connects to nginx from - `cloudflared`'s address (`127.0.0.1` when it runs on the same machine), so - trust `CF-Connecting-IP` from there: `set_real_ip_from 127.0.0.1;` and - `real_ip_header CF-Connecting-IP;`. Any local process can then send its own - `CF-Connecting-IP` to nginx and claim a trusted address, and a local - connection without that header keeps `127.0.0.1`, so listing `127.0.0.1` in - `$ompweb_trusted` trusts every local process that connects to nginx. -- **Any other proxy or load balancer:** - - ```nginx - set_real_ip_from ; - real_ip_header X-Forwarded-For; - real_ip_recursive on; - ``` + ```bash + npx @ompweb-dev/tau@latest host + ``` - `real_ip_recursive on` reads `X-Forwarded-For` from the right and skips the - hops listed in `set_real_ip_from`. Addresses a client adds itself are - ignored. +The host then shows as online, the sidebar groups its workspaces, and the new-session screen offers it. Each host keeps +its own `~/.pi/agent`, sessions and provider logins. **Settings → Hosts** also renames and revokes hosts, shows each +host's tau version and offers updates, and sets whether agents may start sessions there without asking. A revoked +host's daemon stops its sessions. + +### Cluster + +**Settings → Hosts** can add linked hosts to a cluster; this machine is its master and joins with the first host. A +host must be online to join, and gives a projects folder for the cluster's checkouts. Its Git projects are bound to +cluster projects by their repository origin. A cluster session can then start on any member. + +Members run sessions with the master's pi configuration. The master builds a versioned manifest of: + +- from its pi agent directory: `settings.json`, `models.json`, `mcp.json`, `AGENTS.override.md`, `AGENTS.md`, + `CLAUDE.md`, `SYSTEM.md`, `APPEND_SYSTEM.md`, and the directories `skills/`, `prompts/`, `themes/` and + `extensions/`; +- `~/.agents/skills/`; +- the agent environment variables of **Settings → System**. + +Each member's daemon downloads the files it lacks, checks their hashes and applies the version whole or not at all. The +master checks every 30 seconds, and a session start on a member applies the current version first. A mirrored +directory becomes equal to the master's (`node_modules` and `.git` are left out). Limits: 5 MiB per file, 50 MiB in all. + +Not mirrored: credentials (`auth.json`, `mcp-auth.json`), sessions, caches, configuration inside a repository, and +programs (an MCP server's command, or a package that `settings.json` names, which pi installs on the member itself). A +member keeps its own values of these `settings.json` keys: `shellPath`, `shellCommandPrefix`, `npmCommand`, +`selfUpdateCommand`, `externalEditor`, `sessionDir`, `httpProxy`, `extensions`, `skills`, `prompts`, `themes`, +`deviceId`, `trackingId`, `lastChangelogVersion`, `extensionChangelogVersions` and `terminal`. + +On first apply the member's own configuration moves to `~/.pi/agent/tau/own-config/`; leaving the cluster puts it back. +A host holds one server's configuration at a time. Provider logins are never mirrored: log in on each member (see +below). + +## Configuration + +tau uses pi's own files and adds a few of its own: + +| Path | Contents | +| --- | --- | +| `~/.pi/agent/settings.json` | pi settings; **Settings** edits default thinking level, thinking-block display, enabled models, retry and compaction. | +| `~/.pi/agent/models.json` | Custom providers and models; edited in **Settings → API Keys & Providers**. | +| `~/.pi/agent/auth.json` | pi's provider logins and API keys, written by pi. | +| `~/.pi/agent/sessions/` | pi session files, which tau lists and reads. | +| `~/.pi/agent/tau-settings.json` | tau server settings: auto-resume after restart, agent tools, GitHub write and Actions permissions, agent environment variables, upload retention. | +| `~/.pi/agent/projects.json` | Workspaces added to or hidden from the sidebar. | +| `~/.pi/agent/tau/` | tau state: host registry (`hosts.json`), the daemon's links (`host.json`), cluster (`pools.json`), sign-in key, notifications, message outbox, uploads. | +| `~/.pi/agent/web-service.env` | Service settings written by `tau-systemd` (`web-service.json` on Windows). | + +All paths follow `PI_CODING_AGENT_DIR`. + +**Provider logins are per host.** tau never reads `auth.json` itself. Logins (OAuth and API keys) run inside pi through +tau's companion extension (the `/tau_auth` command of `lib/pi/tau-extension.ts`), on the selected host's daemon; raw +keys and tokens stay with pi on that host. Choose the host in **Settings → API Keys & Providers** to log in there. + +**Agent environment variables** (**Settings → System**) are added to every pi process started afterwards. Names that +would redirect pi's state or tau's plumbing are refused: `PATH`, `PATHEXT`, `COMSPEC`, `SYSTEMROOT`, `WINDIR`, +`NODE_OPTIONS`, `HOME`, `USERPROFILE`, `HOMEDRIVE`, `HOMEPATH`, `XDG_DATA_HOME`, `XDG_CONFIG_HOME`, +`PI_CODING_AGENT_DIR`, `PI_CODING_AGENT_SESSION_DIR`, `PORT`, `NODE_ENV`, and anything starting with `TAU_` or `_`. + +## Security notes + +- **An agent runs with your user's rights.** pi's tools can read and write any file your user can and run commands. + tau does not sandbox it. Anyone who can sign in to tau can make an agent do that on every linked host. +- **Password gate.** With `TAU_PASSWORD_HASH` set, every page and API route except the sign-in page, static assets, + the service worker and the host-authenticated paths needs a session cookie (or the trusted proxy header). tau + refuses to listen on a non-loopback address without a password hash. +- **HTTPS.** tau speaks plain HTTP. Put it behind HTTPS (reverse proxy or VPN) for any remote access, so the password, + the session cookie and host tokens stay private. Web Push notifications also need HTTPS. +- **Secrets stay out of sessions.** `TAU_PASSWORD`, `TAU_PASSWORD_HASH`, `TAU_TRUSTED_HEADER_SECRET`, + `TAU_TRUSTED_HEADER_SHA256`, `TAU_STT_KEY`, `PORT` and `NODE_ENV` are removed from the environment of every pi + process and project command. +- **Host tokens.** The server stores only the SHA-256 of each host token. A host's daemon reads its token from stdin + and keeps it in a mode-`600` file. A revoked token is refused at once. +- **File access in the browser.** The file viewer and explorer serve only allowed roots: workspaces you added or + opened, session working directories and validated worktrees, and the files a session's transcript references (read + only). Known credential files in pi's directory (`models.json`, `.env` files) are refused even inside an allowed + root. These limits apply to the browser, not to the agent. +- **Agent tools are off by default.** When enabled, any session can list sessions, start a session or send a message + to another one, and use the GitHub tools with the server's `gh` login. Comments and thread writes ask in the session + unless **Allow agent GitHub writes without asking** is on, and Actions dispatch, cancel and rerun each ask by default. + Starting a session on a host asks unless that host allows agent starts. ## Development ```bash -git clone https://github.com/ompweb-dev/ompweb.git -cd ompweb npm install -npx bun runner/scripts/use-omp-build.ts && (cd runner && npx bun install --frozen-lockfile) -npx bun runner/scripts/build-binary.ts # ompweb's omp build for this machine: runner/release/ompweb-omp-- -npm run dev +npm run dev # Bun hot reload at http://127.0.0.1:30188 +npm run build # bundle the browser app into dist/ +npm start # serve dist/ at http://127.0.0.1:30187 +npm run build:binary # single binary for this machine into release/ (-- --target bun-linux-arm64 for another) +npm run typecheck && npm run lint && npm test ``` -The dev server runs at [http://127.0.0.1:30178](http://127.0.0.1:30178). It finds the runner in -`runner/release/` by itself; `npm test` and `npm run build:binary` need the runner set up too. - -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. - -`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 (bun test) -``` +The dev server does not take over the host daemon: "This machine" shows offline in dev, and the daemon stays linked to +your installed tau. -## License & Credits +## License -- 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). -- Released under the [MIT License](./LICENSE). +MIT, see [LICENSE](./LICENSE). tau is forked from [ompweb](https://github.com/ompweb-dev/ompweb), which was forked from +[agegr/pi-web](https://github.com/agegr/pi-web). diff --git a/README.zh-CN.md b/README.zh-CN.md index 876e0437..0fe3105d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,167 +1,334 @@

-ompweb logo +tau logo -

ompweb

- -

- npm version - node version - license - npm downloads - GitHub stars - PRs Welcome -

+

tau

[English](./README.md) | [简体中文](./README.zh-CN.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) -社区:[加入 OMPWEB Discord](https://discord.gg/evqgGzRfM5) +tau 是 [pi coding agent](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) 的浏览器工作区。 +它读取你的 pi 会话,通过 `pi --mode rpc` 加上配套的 pi 扩展运行实时会话,让你在任何浏览器中与智能体对话、浏览项目和文件、管理 pi 设置。一台 tau 服务器还可以在你链接给它的其他机器上运行会话。 -[oh-my-pi (omp)](https://github.com/can1357/oh-my-pi) 编程智能体的现代 Web UI。它读取本地的 omp 会话,在浏览器中提供实时对话、项目会话浏览、配置管理和文件预览等功能。 +## 功能 -![ompweb — 演示](docs/demo.gif) +- **对话**:流式回复、带实时输出的工具调用、思考块、排队的后续消息与引导(steer)、停止,以及以对话框显示的 `ask` 工具问题。 +- **会话**:按项目浏览历史会话、分叉会话、在会话内切换分支、编辑之前的消息、归档与恢复、搜索标题和对话记录。 +- **消息不怕中断**:发给已有会话的消息会保存在浏览器和服务器上,直到 pi 接收为止,可跨越重连和重启。 +- **文件与 Git**:对话旁的文件浏览器与预览、上传文件到会话、Git worktree。 +- **子智能体**:如果 pi 中安装了 `pi-subagents` 包,显示其运行进度和对话记录。 +- **远程主机与集群**:在已链接的机器上运行会话;把机器组成集群,共享项目和本服务器的 pi 配置。 +- **通知**:运行完成、等待回答的问题和失败时,通过页内、桌面和 Web Push(需 HTTPS)通知。 +- **智能体工具**(默认关闭):跨会话工具,以及使用服务器 `gh` 登录的 GitHub 工具。 +- **语音输入**:可选,通过你配置的端点转写。 -
-截图(浅色 / 深色主题) +## 环境要求 -![ompweb — 浅色主题](docs/screenshot-light.png) +- npm 包需要 **Node.js 24 或更高版本**。启动器(`tau`)运行在 Node 上;服务器运行在 [Bun](https://bun.sh) 1.4.4 或更高版本上,Bun 作为包的依赖自动安装(若内置的 Bun 不存在,则使用 `PATH` 上不低于该版本的 `bun`)。[单一可执行文件](#单一可执行文件)两者都不需要。 +- 每台运行会话的机器都要安装 **pi**: -![ompweb — 深色主题](docs/screenshot-dark.png) + ```bash + npm install -g @earendil-works/pi-coding-agent + ``` -
+ tau 运行 `PATH` 上的 `pi`。要使用其他 pi,把 `TAU_PI_BIN` 设为它的路径。tau 基于 pi 1.5.2 开发。没有 pi 时仍可浏览历史会话,但无法启动会话。 -## 环境要求 +## 安装 -- 无需另行安装 omp:ompweb 使用自己的 [omp](https://github.com/can1357/oh-my-pi) 构建 `ompweb-omp`,直接使用 `~/.omp` 中的设置、认证和会话。每种安装方式(npm、npx 或单一可执行文件)都会在首次启动时从该版本的 [GitHub 发布](https://github.com/ompweb-dev/ompweb/releases)下载同一版本的 `ompweb-omp`,校验 SHA-256 后保存(单一可执行文件放在同一目录,其他方式放在 `~/.omp/agent/omp-web/omp//`);也可用 `ompweb fetch-omp` 手动获取。支持的平台为 linux-x64、linux-arm64、darwin-x64、darwin-arm64 和 windows-x64;在其他平台(musl 的 Linux、Arm 版 Windows、FreeBSD)上无法启动会话。无法访问 GitHub 的机器请将 `OMP_WEB_OMP_BIN` 指向该发布的 `ompweb-omp--` 副本 -- Node.js `>= 24`。服务器运行在 [Bun](https://bun.sh) 上,Bun 会作为 npm 包的依赖自动安装(找不到随包安装的 Bun 时使用 `PATH` 中的 Bun) +### npm 或 Bun + +```bash +npm install -g @ompweb-dev/tau +tau +``` -排队消息的 **Steer**、**Delete** 和 **Edit** 操作是 `ompweb-omp` 通道的命令(`promote_queued_message`、`remove_queued_message`)。只有 omp 确认取消后才会移除消息;编辑时也必须先取消成功,再将文本恢复到输入框。消息已不在队列中时,界面保留队列并显示提示;ompweb 不会重复发送一条引导消息。 +`bun add -g @ompweb-dev/tau` 安装的是同一个包;`tau` 启动器仍需要 `PATH` 上的 Node.js 24。`npx @ompweb-dev/tau@latest` 无需全局安装即可运行。 -队列面板显示 omp 自身的队列(`get_state` 中的 `queuedMessages` 和 `queue_update` 事件),因此查看同一会话的所有设备都会看到相同的排队消息。**Stop** 会将仍在队列中等待的消息文本放回输入框,而不是让智能体运行它们;但模型已通过实时引导接收的引导消息仍会运行。 +tau 会在浏览器中打开 `http://127.0.0.1:30187`。在 **Settings → API Keys & Providers** 中登录你的模型提供商(见[配置](#配置)),选择工作区并开始会话。 -## 快速开始 +### 单一可执行文件 -**免安装直接运行:** +每个版本还提供编译成单个程序的 tau,它要提供的文件放在旁边: +`tau-linux-x64.tar.gz`、`tau-linux-arm64.tar.gz`、`tau-darwin-x64.tar.gz`、`tau-darwin-arm64.tar.gz` 和 `tau-windows-x64.zip`。它自身不需要 Node.js、npm 或 Bun。它不包含 pi:它运行 `PATH` 上的 `pi`(或 `TAU_PI_BIN`)。`main` 上每个通过 CI 的提交也会发布为带有相同压缩包的预发布版本。 ```bash -npx @kahme247/ompweb@latest +tar -xzf tau-linux-x64.tar.gz -C ~/.local/share # unpacks tau-linux-x64/ +~/.local/share/tau-linux-x64/tau # same options and environment variables as the npm launcher ``` -**或全局安装:** +- 把 `tau` 留在它的目录中:它从那里提供 `dist/`、`public/` 和它的 pi 扩展(可以在 `PATH` 上放一个符号链接),设置了 `TAU_PACKAGE_DIR` 时则从该目录提供。 +- 该程序有 `tau host` 和 `tau hash-password`,但没有托盘和服务安装器。服务单元需要自己编写,见[服务](#服务)中的示例。 +- macOS 会隔离下载的文件:首次启动前运行一次 `xattr -dr com.apple.quarantine tau-darwin-arm64`。 +- macOS 15 及以后版本会在应用访问本地网络前询问。如果 `curl` 能访问局域网中的服务器,而 `tau host` 报告 `ECONNREFUSED`,请在“系统设置 → 隐私与安全性 → 本地网络”中允许你的终端(或 `tau`)。 + +### 从源码运行 ```bash -npm install -g @kahme247/ompweb -ompweb +git clone https://github.com/ompweb-dev/tau.git +cd tau +npm install +npm run build +node bin/tau.js ``` -每个版本也提供**无需 Node 或 npm 的单一可执行文件**,用法见英文 README 的 [Single binary](README.md#single-binary)。 +## 运行 -在浏览器中打开 [http://127.0.0.1:30177](http://127.0.0.1:30177)。 +```text +tau [options] -### CLI 选项 + -p, --port Server port (default 30187, env PORT) + -H, --hostname Bind hostname (default 127.0.0.1, env TAU_HOSTNAME) + --no-open Do not open the browser automatically + --install-tray Install the tray, background service and shortcuts (Windows; Linux SNI tray) + --uninstall-tray Uninstall them + --tray Start the background tray manager + -h, --help Show help + --version Show the version + +tau hash-password Read a password from stdin and print the value for TAU_PASSWORD_HASH +tau host ... The host daemon (see "Hosts and cluster") +tau systemd ... | tau launchd ... Forward to tau-systemd / tau-launchd +``` + +生产服务器在本机的主机守护进程(`tau host`)未运行时会启动它:所有会话(包括本地会话)都在这个守护进程下运行,因此重启 Web 服务器不会停止正在运行的会话。 + +### 环境变量 + +| 变量 | 含义 | +| --- | --- | +| `PORT` | 服务器端口(默认 `30187`)。 | +| `TAU_HOSTNAME` | 绑定地址(默认 `127.0.0.1`)。 | +| `TAU_NO_OPEN` | `1`、`true`、`yes` 或 `on`:不打开浏览器。 | +| `TAU_PASSWORD_HASH` | `tau hash-password` 输出的密码哈希。启用登录页。 | +| `TAU_TRUSTED_HEADER_SHA256` | 受信任的反向代理在 `X-Tau-Auth` 中发送的密钥的 SHA-256 摘要(十六进制),见[下文](#在受信任的代理后跳过密码)。 | +| `TAU_PI_BIN` | 用来代替 `PATH` 上那个 `pi` 的可执行文件路径。 | +| `PI_CODING_AGENT_DIR` | pi 的 agent 目录(默认 `~/.pi/agent`);tau 读写同一个目录。 | +| `TAU_NAME` | 浏览器标题中的显示名称。`url`、`host` 或 `domain` 表示取自请求的主机名。 | +| `TAU_DISABLE_AUTOUPDATE` | `1`、`true`、`yes` 或 `on`:拒绝服务器和主机的应用内更新。 | +| `TAU_STT_ENDPOINT`、`TAU_STT_KEY`、`TAU_STT_MODEL` | 语音转写:端点接收 multipart 的 `file`(和 `model`),`TAU_STT_KEY` 作为 Bearer 令牌发送。未设置端点时语音输入关闭。 | +| `TAU_DISCONNECT_DESTROY_MS` | 无人查看的会话进程在多久后停止(默认 2 分钟,`0` 表示禁用)。 | + +### 密码 + +绑定到 `127.0.0.1` 时,tau 不需要密码。要监听其他地址,tau 必须有密码哈希,否则拒绝启动: ```bash -ompweb --port 8080 # 自定义端口 -ompweb --hostname 0.0.0.0 # 监听网络地址 -ompweb hash-password # 输出 OMP_WEB_PASSWORD_HASH 的值 -ompweb fetch-omp # 从 GitHub 发布下载本版本的 ompweb-omp(校验 SHA-256,仅在缺失时) -ompweb preflight # 像新会话一样启动一次 omp 并等待其 hello;失败时说明原因并以 1 退出 -ompweb --no-open # 不自动打开浏览器 +tau hash-password # prompts, input hidden +echo "a-long-random-password" | tau hash-password +TAU_PASSWORD_HASH='scrypt$15$8$1$...' tau --hostname 0.0.0.0 ``` -### 密码保护 +tau 只接受哈希。`--password` 参数会被拒绝。明文的 `TAU_PASSWORD` 仍会被检测到:tau 在启动时对它做哈希,从自己的环境中删除它,并在警告中打印应改用的哈希(与 `TAU_PASSWORD_HASH` 同时设置则会被拒绝)。原因是每个 pi 会话都继承 tau 的环境,智能体可能把明文密码打印到对话记录中。浏览器登录有效期为 30 天。 -omp-web **绝不把明文密码交给服务器**:每个 `omp` 会话都会继承服务器的环境变量, -智能体只要运行 `env` 就会把密码写入会话文件并发送给模型提供商。使用 -`--password` 会导致启动被拒绝。`OMP_WEB_PASSWORD` 暂时仍可使用:`ompweb` -会在启动时将其哈希、使其不进入服务器的环境变量,并在日志中输出警告,附上应设置为 -`OMP_WEB_PASSWORD_HASH` 的哈希值。请尽快切换:智能体仍能从 `ompweb` 启动器进程中 -读取明文,而且每次启动都会生成新的哈希,每次重启都会让所有浏览器退出登录。 -同时设置两个变量会导致启动被拒绝,请删除 `OMP_WEB_PASSWORD`。 +### 在反向代理之后 -请改用哈希: +在非回环地址上无 TLS 监听时,tau 会发出警告。请通过反向代理或 VPN 以 HTTPS 提供服务,并让 tau 本身绑定到 `127.0.0.1`。代理必须转发 WebSocket 升级(主机使用 `/api/hosts/link` 和 `/api/hosts/maintenance`)。对于主机用令牌认证的路径(`/api/hosts/link`、`/api/hosts/maintenance` 和 `/api/hosts/cluster-config/…`),代理不得再加自己的认证。 + +#### 在受信任的代理后跳过密码 + +tau 自己看不到客户端地址,因此可以由反向代理为请求担保。代理在 `X-Tau-Auth` 请求头中发送一个密钥,tau 只在 `TAU_TRUSTED_HEADER_SHA256` 中保存该密钥的 SHA-256 摘要。请求头哈希与摘要一致的请求视为已登录。没有密码哈希时,就没有可跳过的东西。 + +生成一个长的随机密钥,且不要把它写在命令行上。下面的命令把它写入 nginx 的 include 文件,只打印摘要: ```bash -ompweb hash-password # 输入两次,内容不回显 -echo "a-long-random-password" | ompweb hash-password # 也可通过管道输入 +secret=$(openssl rand -hex 32) +printf 'map $tau_trusted $tau_auth {\n 1 "%s";\n default "";\n}\n' "$secret" \ + | sudo install -m 0640 -o root -g www-data /dev/stdin /etc/nginx/tau-auth.conf +printf %s "$secret" | sha256sum | cut -d' ' -f1 +unset secret +``` -OMP_WEB_PASSWORD_HASH='scrypt$15$8$1$…' ompweb +```nginx +# http {} context +geo $tau_trusted { + default 0; + 10.0.0.0/16 1; +} +include /etc/nginx/tau-auth.conf; + +# the location that proxies to tau +proxy_set_header X-Tau-Auth $tau_auth; ``` -`ompweb hash-password` 从标准输入读取密码(绝不作为命令行参数),因此不会 -留在 shell 历史或 `ps` 输出中。哈希使用 scrypt(N = 2^15、r = 8、p = 1) -与 16 字节随机盐,输出格式为 `scrypt$$$

$$`。 -即使读到哈希也无法用它登录,更无法还原出密码。 - -会话签名不使用密码哈希。首次启动时会生成随机签名密钥并保存到 -`~/.omp/agent/omp-web/web-auth-secret.json`(权限 `0600`),再与哈希混合得到 -签名密钥:修改密码会让已有会话失效,而仅凭保存的哈希无法伪造会话。 - -服务安装脚本(`ompweb systemd install`、`ompweb-launchd install`、Linux 托盘、 -Windows 服务)仍在安装时接受 `OMP_WEB_PASSWORD`,但在写入配置前会先做哈希, -最终只保存哈希。 - -## 功能特性 - -- **实时对话**:与本地 `omp` 智能体进行低延迟流式交互。 -- **队列删除确认**:取消 OMP 中排队的后续消息或引导消息前,先预览内容并确认。需要原生支持 `remove_queued_message`;已发送的消息无法撤回。 -- **会话管理**:按项目浏览历史会话,支持会话分叉与分支回溯。 -- **草稿恢复**:未发送的文本按会话或新会话的工作区分别保存;浏览器存储可用时,在同一标签页后退、前进或重新加载后可恢复(最多 50 份草稿)。图片和文件附件仅保留在内存中。 -- **实时任务与子智能体**:可折叠面板实时展示任务清单(todo)与子智能体进度,并支持查看完整转录。 -- **文件管理与预览**:与对话并排浏览文件,支持代码、Markdown、图片、音频及 PDF 预览。 -- **各主机的文件**:文件浏览、搜索、预览、下载和实时更新都通过文件所属主机的守护进程执行。上传每个文件最多 2 GiB,不再限制批次总大小为 100 MiB。预览限制仍为文本 256 KiB、图片及 DOCX 10 MiB。切换对话不会改变文件标签页所属的主机。 -- **各主机的工作区**:Git 差异、工作树操作、目录浏览以及 HTTPS/SSH 仓库克隆均在所属主机执行。取消克隆会等待进程退出和安全清理;连接中断时会明确提示结果未知。 -- 若清理克隆时目标目录被替换,捕获的数据会保存在私有隔离目录中,错误信息会显示其位置。删除或恢复前请先检查内容。 -- **Git Worktree 支持**:直接在侧边栏切换与管理 Git 工作树。 -- **可视化设置**:在 Web 界面中直接配置模型、API 密钥、MCP 服务器、技能、插件及 OMP 原生设置。 -- **快捷指令与命令面板**:内置常用指令(`/plan`、`/review`、`/fix`、`/test` 等)及 `⌘K` / `Ctrl+K` 全局面板。 -- **主题与多语言**:温暖纸感深浅主题,完整支持英语、简体中文及日本語。 - -## 环境变量 - -| 变量 | 说明 | 默认值 | -| --- | --- | --- | -| `PORT` | 服务端口 | `30177` | -| `OMP_WEB_HOSTNAME` | 绑定主机名 | `127.0.0.1` | -| `OMP_WEB_PASSWORD_HASH` | Web 登录密码的 scrypt 哈希(由 `ompweb hash-password` 生成)。绑定非回环地址时必须设置 | _无(未启用验证)_ | -| `OMP_WEB_TRUSTED_HEADER_SHA256` | 受信任的反向代理在 `X-Omp-Web-Auth` 请求头中发送的密钥的 SHA-256 摘要(十六进制);请求头哈希匹配的请求无需密码。omp-web 不保存密钥本身。生成方法和 nginx 配置示例见英文 README 的 “Skipping the password on trusted networks” 一节 | _无(未启用)_ | -| `OMP_WEB_NO_OPEN` | 设为 `1` 时禁止自动打开浏览器 | `0` | -| `OMP_WEB_DISABLE_AUTOUPDATE` | 设为 `1` 时禁用更新检查和应用内更新;修改后需重启 | `0` | -| `OMP_WEB_NAME` | 浏览器标签页和已安装应用中显示的名称。设为 `url`、`host` 或 `domain`(不区分大小写)时使用浏览器所连接的主机名(不含端口),localhost 和 IP 地址仍显示 `omp web`;其他值按原样使用。修改后需重启 | `omp web` | -| `OMP_WEB_OMP_BIN` | 用于替代下载版本的 `ompweb-omp` 构建路径(无法访问 GitHub 的机器上为发布中 `ompweb-omp--` 的副本,源码检出中为 `runner/release/ompweb-omp--`)。普通的 `omp` 不支持 ompweb 的通道,无法使用。服务安装程序仅在你设置了它时才写入服务环境 | _下载的 `ompweb-omp`_ | -| `PI_CODING_AGENT_DIR` | 自定义 omp agent 目录 | `~/.omp/agent` | -| `OMP_WEB_STT_ENDPOINT` | OpenAI 兼容的语音转文字接口 URL。不设置时使用 `OMP_WEB_STT_MODEL` 通过 omp 自身的凭据转录 | _无_ | -| `OMP_WEB_STT_KEY` | STT 接口对应的 API Key | _无_ | -| `OMP_WEB_STT_MODEL` | STT 接口的模型名称。未设置接口时:使用 omp 登录凭据运行的 omp 语音转文字模型,例如 `openai-codex/codex-transcribe`(ChatGPT 订阅;需要包含该模型的 omp 版本) | _无(未设置接口时禁用)_ | - -**`OMP_WEB_NAME` 与已安装应用。** 已安装应用(PWA)通常以安装时所在页面的名称命名。如果之后修改了 `OMP_WEB_NAME`,或在 `OMP_WEB_NAME` 为 `url`、`host` 或 `domain` 时通过其他地址访问 omp-web,操作系统可能也会重命名已安装的应用。建议将 `OMP_WEB_NAME` 留空,或设置一个无论通过哪个域名或地址访问都能识别这台 omp-web 服务器的名称。 - -## 本地开发 +始终设置该请求头,这样客户端自己发送的 `X-Tau-Auth` 会被空值替换。给 tau 的 `server` 块设置明确的 `server_name`,并在 `default_server` 块中对其他主机名 `return 444;`,以免 DNS 重绑定让 nginx 把密钥加到其他站点的请求上。tau 只保存快速的 SHA-256 摘要,这只对长的随机密钥安全:不要在这里复用密码。 + +## 服务 + +每个安装器都运行两个服务:Web 服务器和主机守护进程(`tau host`)。 + +### Linux(systemd 用户服务) ```bash -git clone https://github.com/ompweb-dev/ompweb.git -cd ompweb -npm install -npx bun runner/scripts/use-omp-build.ts && (cd runner && npx bun install --frozen-lockfile) -npx bun runner/scripts/build-binary.ts # 为本机构建 ompweb 的 omp:runner/release/ompweb-omp-- -npm run dev +TAU_PASSWORD_HASH='scrypt$...' tau-systemd install # or: npx --yes --package=@ompweb-dev/tau@latest tau-systemd install +tau-systemd status ``` -本地开发服务器运行在 [http://127.0.0.1:30178](http://127.0.0.1:30178)。它会自动找到 `runner/release/` 中的 runner;`npm test` 和 `npm run build:binary` 也需要先准备好 runner。 +`install` 把单元 `tau.service` 和 `tau-host.service` 写入 `~/.config/systemd/user/`,创建 `~/.pi/agent/web-service.env`(端口、主机名、密码哈希;修改后无需重新安装),并启用两者。其他命令:`uninstall`(`--clean-config` 同时删除 env 文件)、`start`、`stop`、`restart`(仅 Web 服务)、`open`。选项:`--port`、`--hostname`、`--no-autostart`、`--json`。日志:`journalctl --user -u tau -u tau-host -f`。 -`npm run dev` 以 Bun 热重载方式运行服务器。`npm run build` 将浏览器端应用打包到 `dist/`,`npm start` 在 30177 端口提供该产物(可用 `npm run smoke` 检查结果)。`npm run dev:lan` 会将开发服务器绑定到所有网络接口。 +在 KDE Plasma 等支持 StatusNotifierItem 的桌面上,`tau --install-tray` 会添加一个控制这些 systemd 服务的托盘图标。 -### 代码检查 +### macOS(launchd) ```bash -npm run typecheck # TypeScript 类型检查 -npm run lint # ESLint 检查 -npm test # 运行测试套件 (bun test) +TAU_PASSWORD_HASH='scrypt$...' tau-launchd install # or: npx -p @ompweb-dev/tau@latest tau-launchd install +tau-launchd status +tau-launchd uninstall ``` -## 致谢与许可证 +`install` 创建 LaunchAgent `dev.ompweb.tau` 和 `dev.ompweb.tau-host`,它们在登录时启动,崩溃后重启。它从运行时的环境中读取 `PORT`、`TAU_HOSTNAME`、`TAU_PASSWORD_HASH`、`TAU_TRUSTED_HEADER_SHA256`、`TAU_PI_BIN`、`TAU_NAME`、`TAU_DISABLE_AUTOUPDATE` 和 `PI_CODING_AGENT_DIR`。日志写入 `~/Library/Logs/tau`。 + +### Windows(托盘和后台服务) + +```powershell +tau --install-tray +``` + +这会安装后台服务、主机守护进程(计划任务 `tau-host`)、托盘图标、登录时自启动以及桌面和开始菜单快捷方式。用 `tau-tray status|start|stop|restart|open|uninstall` 管理。服务从 `%USERPROFILE%\.pi\agent\web-service.json` 读取设置,从用户或系统环境变量读取 `TAU_PASSWORD_HASH`。 + +### 把单一可执行文件作为服务 + +自己编写两个单元。以 systemd 为例(按需调整路径): + +```ini +# ~/.config/systemd/user/tau.service +[Unit] +Description=tau web service + +[Service] +WorkingDirectory=%h +ExecStart=%h/.local/share/tau-linux-x64/tau --no-open +Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin +# TAU_PASSWORD_HASH, PORT and TAU_HOSTNAME go here. +EnvironmentFile=-%h/.pi/agent/web-service.env +Restart=on-failure +RestartSec=3 + +[Install] +WantedBy=default.target +``` + +```ini +# ~/.config/systemd/user/tau-host.service +[Unit] +Description=tau host daemon +# It exits until the web server has written its link: keep restarting. +StartLimitIntervalSec=0 + +[Service] +WorkingDirectory=%h +ExecStart=%h/.local/share/tau-linux-x64/tau host +Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin +EnvironmentFile=-%h/.pi/agent/web-service.env +Restart=always +RestartSec=10 + +[Install] +WantedBy=default.target +``` + +```bash +systemctl --user daemon-reload +systemctl --user enable --now tau tau-host +``` + +`PATH` 必须包含 `pi` 所在目录(以及 pi 所用 Node.js 的目录)。在 macOS 上,两个以 `RunAtLoad` 和 `KeepAlive` 运行 `…/tau --no-open` 与 `…/tau host` 的 launchd agent 可以实现同样效果;在 Windows 上,则是两个在登录时运行 `tau.exe --no-open` 与 `tau.exe host` 的任务计划程序任务。 + +## 主机与集群 + +### 主机守护进程 + +`tau host` 是在一台机器上运行 pi 会话并读取其会话文件的进程。它通过 WebSocket 主动连接一个或多个 tau 服务器,因此可以位于 NAT 之后。链接或 Web 服务器断开时会话继续运行,链接恢复后服务器重新加入这些会话。在服务器自己的机器上,守护进程会自动链接(**Settings → Hosts** 中的“This machine”)。 + +```text +tau host login [--add] --url save a link; the host token is read from stdin +tau host logout --url remove a link +tau host [--allow-http] run the daemon +tau host status|drain|resume control the running daemon +``` + +守护进程只接受 `https://` 服务器地址,`http://` 仅限回环地址。`--allow-http` 允许对其他地址使用明文 HTTP;此时主机令牌以未加密方式传输,只应在受信任的网络中使用。 + +### 链接另一台机器 + +另一台机器需要 pi,以及 npm 版 tau(Node.js 24)或单一可执行文件。 + +1. 在 tau 服务器上打开 **Settings → Hosts → Add host**,输入名称并复制令牌。令牌只显示一次;服务器只保存其哈希。 +2. 在另一台机器上保存链接。按提示粘贴令牌,或通过管道传入;它不会出现在 `ps` 中: + + ```bash + npx @ompweb-dev/tau@latest host login --url https://tau.example.com + ``` + + 链接以 `600` 权限保存到 `~/.pi/agent/tau/host.json`。`--add` 会添加到另一台服务器的链接,而不是替换第一个。 +3. 运行守护进程并保持运行(作为服务运行,见[服务](#服务)): + + ```bash + npx @ompweb-dev/tau@latest host + ``` + +之后该主机显示为在线,侧边栏为它的工作区分组,新建会话界面也可以选择它。每台主机保留自己的 `~/.pi/agent`、会话和提供商登录。**Settings → Hosts** 还可以重命名和撤销主机、显示每台主机的 tau 版本并提供更新,以及设置智能体能否无需询问就在该主机上启动会话。被撤销主机的守护进程会停止它的会话。 + +### 集群 + +在 **Settings → Hosts** 中可以把已链接的主机加入集群;本机是主节点(master),随第一台主机一起加入。加入的主机必须在线,并提供一个用于集群检出的项目文件夹。它的 Git 项目按仓库 origin 绑定到集群项目。之后集群会话可以在任一成员上启动。 + +成员使用主节点的 pi 配置运行会话。主节点构建一个带版本的清单,包括: + +- 来自其 pi agent 目录:`settings.json`、`models.json`、`mcp.json`、`AGENTS.override.md`、`AGENTS.md`、`CLAUDE.md`、`SYSTEM.md`、`APPEND_SYSTEM.md`,以及目录 `skills/`、`prompts/`、`themes/` 和 `extensions/`; +- `~/.agents/skills/`; +- **Settings → System** 中的智能体环境变量。 + +每个成员的守护进程下载缺少的文件,校验其哈希,并整体应用该版本,要么全部应用,要么完全不应用。主节点每 30 秒检查一次,在成员上启动会话时会先应用当前版本。被镜像的目录会变得与主节点的完全相同(排除 `node_modules` 和 `.git`)。限制:单个文件 5 MiB,总计 50 MiB。 + +不镜像的内容:凭据(`auth.json`、`mcp-auth.json`)、会话、缓存、仓库内的配置,以及程序(MCP 服务器的命令,或 `settings.json` 指定的包,后者由 pi 在成员上自行安装)。成员对 `settings.json` 中的以下键保留自己的值:`shellPath`、`shellCommandPrefix`、`npmCommand`、`selfUpdateCommand`、`externalEditor`、`sessionDir`、`httpProxy`、`extensions`、`skills`、`prompts`、`themes`、`deviceId`、`trackingId`、`lastChangelogVersion`、`extensionChangelogVersions` 和 `terminal`。 + +首次应用时,成员自己的配置会移到 `~/.pi/agent/tau/own-config/`;离开集群时再放回去。一台主机同一时间只持有一个服务器的配置。提供商登录永远不会被镜像:请在每个成员上分别登录(见下文)。 + +## 配置 + +tau 使用 pi 自己的文件,并增加几个自己的文件: + +| 路径 | 内容 | +| --- | --- | +| `~/.pi/agent/settings.json` | pi 设置;**Settings** 可编辑默认思考级别、思考块显示、启用的模型、重试和压缩(compaction)。 | +| `~/.pi/agent/models.json` | 自定义提供商和模型;在 **Settings → API Keys & Providers** 中编辑。 | +| `~/.pi/agent/auth.json` | pi 的提供商登录和 API 密钥,由 pi 写入。 | +| `~/.pi/agent/sessions/` | pi 会话文件,tau 列出并读取它们。 | +| `~/.pi/agent/tau-settings.json` | tau 服务器设置:重启后自动恢复、智能体工具、GitHub 写入和 Actions 权限、智能体环境变量、上传保留期。 | +| `~/.pi/agent/projects.json` | 添加到侧边栏或从侧边栏隐藏的工作区。 | +| `~/.pi/agent/tau/` | tau 状态:主机注册表(`hosts.json`)、守护进程的链接(`host.json`)、集群(`pools.json`)、登录签名密钥、通知、消息发件箱、上传。 | +| `~/.pi/agent/web-service.env` | `tau-systemd` 写入的服务设置(Windows 上为 `web-service.json`)。 | + +所有路径都遵循 `PI_CODING_AGENT_DIR`。 + +**提供商登录按主机分别保存。** tau 自己从不读取 `auth.json`。登录(OAuth 和 API 密钥)在所选主机的守护进程上、通过 tau 的配套扩展(`lib/pi/tau-extension.ts` 中的 `/tau_auth` 命令)在 pi 内部完成;原始密钥和令牌留在该主机的 pi 中。要在某台主机上登录,请在 **Settings → API Keys & Providers** 中选择该主机。 + +**智能体环境变量**(**Settings → System**)会加到之后启动的每个 pi 进程中。会改变 pi 状态位置或 tau 内部机制的名称会被拒绝:`PATH`、`PATHEXT`、`COMSPEC`、`SYSTEMROOT`、`WINDIR`、`NODE_OPTIONS`、`HOME`、`USERPROFILE`、`HOMEDRIVE`、`HOMEPATH`、`XDG_DATA_HOME`、`XDG_CONFIG_HOME`、`PI_CODING_AGENT_DIR`、`PI_CODING_AGENT_SESSION_DIR`、`PORT`、`NODE_ENV`,以及所有以 `TAU_` 或 `_` 开头的名称。 + +## 安全说明 + +- **智能体以你的用户权限运行。** pi 的工具可以读写你的用户能访问的任何文件并执行命令。tau 不对其做沙箱隔离。任何能登录 tau 的人,都能让智能体在每台已链接的主机上这样做。 +- **密码门。** 设置 `TAU_PASSWORD_HASH` 后,除登录页、静态资源、Service Worker 和主机认证的路径外,所有页面和 API 路由都需要会话 Cookie(或受信任代理的请求头)。没有密码哈希时,tau 拒绝监听非回环地址。 +- **HTTPS。** tau 使用明文 HTTP。任何远程访问都应放在 HTTPS(反向代理或 VPN)之后,以保护密码、会话 Cookie 和主机令牌。Web Push 通知也需要 HTTPS。 +- **密钥不会进入会话。** `TAU_PASSWORD`、`TAU_PASSWORD_HASH`、`TAU_TRUSTED_HEADER_SECRET`、`TAU_TRUSTED_HEADER_SHA256`、`TAU_STT_KEY`、`PORT` 和 `NODE_ENV` 会从每个 pi 进程和项目命令的环境中移除。 +- **主机令牌。** 服务器只保存每个主机令牌的 SHA-256。主机守护进程从标准输入读取令牌,并保存在权限为 `600` 的文件中。被撤销的令牌会立即被拒绝。 +- **浏览器中的文件访问。** 文件查看器和浏览器只提供允许的根目录:你添加或打开过的工作区、会话的工作目录和经过验证的 worktree,以及会话对话记录引用的文件(只读)。即使在允许的根目录内,pi 目录中已知的凭据文件(`models.json`、`.env` 文件)也会被拒绝。这些限制针对浏览器,不针对智能体。 +- **智能体工具默认关闭。** 启用后,任何会话都可以列出会话、启动会话或向另一个会话发送消息,并使用服务器 `gh` 登录的 GitHub 工具。除非开启 **Allow agent GitHub writes without asking**,评论和讨论串写入会在会话中询问;Actions 的 dispatch、cancel 和 rerun 默认各自询问。在某台主机上启动会话时,除非该主机允许智能体启动,否则会询问。 + +## 开发 + +```bash +npm install +npm run dev # Bun hot reload at http://127.0.0.1:30188 +npm run build # bundle the browser app into dist/ +npm start # serve dist/ at http://127.0.0.1:30187 +npm run build:binary # single binary for this machine into release/ (-- --target bun-linux-arm64 for another) +npm run typecheck && npm run lint && npm test +``` + +开发服务器不会接管主机守护进程:开发时“This machine”显示为离线,守护进程仍链接到你已安装的 tau。 + +## 许可证 -- 分叉自 [agegr/pi-web](https://github.com/agegr/pi-web)(MIT),针对 [can1357/oh-my-pi](https://github.com/can1357/oh-my-pi) 进行适配。 -- 采用 [MIT 许可证](./LICENSE) 开源。 +MIT,见 [LICENSE](./LICENSE)。tau 派生自 [ompweb](https://github.com/ompweb-dev/ompweb),而 ompweb 派生自 [agegr/pi-web](https://github.com/agegr/pi-web)。 diff --git a/README.zh-TW.md b/README.zh-TW.md index 16fcb934..7cd0cdec 100644 --- a/README.zh-TW.md +++ b/README.zh-TW.md @@ -1,386 +1,226 @@

-ompweb logo +tau logo -

ompweb

- -

- npm version - node version - license - npm downloads - GitHub stars - PRs Welcome -

+

tau

[English](./README.md) | [简体中文](./README.zh-CN.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) -社群交流:[加入 OMPWEB Discord](https://discord.gg/evqgGzRfM5) - -專為 [oh-my-pi (omp)](https://github.com/can1357/oh-my-pi) 程式設計代理打造的簡潔、現代化 Web UI。它能直接讀取本機 omp 對話紀錄,提供瀏覽器工作區讓你與代理交談、瀏覽專案、管理設定與預覽檔案。 - -![ompweb — 即時對話示範](docs/demo.gif) - -
-畫面截圖(淺色/深色模式) - -![ompweb — 淺色主題](docs/screenshot-light.png) +tau 是 [pi coding agent](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) 的瀏覽器工作區。 +它讀取你的 pi 工作階段,透過 `pi --mode rpc` 搭配隨附的 pi 擴充功能執行即時工作階段,讓你在任何瀏覽器中與代理對話、瀏覽專案和檔案、管理 pi 設定。一台 tau 伺服器也能在你連結給它的其他機器上執行工作階段。 -![ompweb — 深色主題](docs/screenshot-dark.png) +## 功能 -
+- **對話**:串流回覆、帶即時輸出的工具呼叫、思考區塊、排入佇列的後續訊息與引導(steer)、停止,以及以對話框顯示的 `ask` 工具問題。 +- **工作階段**:依專案瀏覽過往工作階段、分叉工作階段、在工作階段內切換分支、編輯先前的訊息、封存與還原、搜尋標題和對話紀錄。 +- **訊息不怕中斷**:傳給既有工作階段的訊息會保存在瀏覽器和伺服器上,直到 pi 接收為止,可跨越重新連線和重新啟動。 +- **檔案與 Git**:對話旁的檔案總管與預覽、上傳檔案到工作階段、Git worktree。 +- **子代理**:若 pi 中安裝了 `pi-subagents` 套件,顯示其執行進度和對話紀錄。 +- **遠端主機與叢集**:在已連結的機器上執行工作階段;把機器組成叢集,共用專案和本伺服器的 pi 設定。 +- **通知**:執行完成、等待回答的問題和失敗時,透過頁內、桌面和 Web Push(需 HTTPS)通知。 +- **代理工具**(預設關閉):跨工作階段工具,以及使用伺服器 `gh` 登入的 GitHub 工具。 +- **語音輸入**:選用,透過你設定的端點轉寫。 ## 系統需求 -- 無需另行安裝 omp:ompweb 使用自己的 [omp](https://github.com/can1357/oh-my-pi) 建置版本 `ompweb-omp`,直接使用 `~/.omp` 中的設定、認證與對話。每種安裝方式(npm、npx 或單一二進位檔)都會在首次啟動時從該版本的 [GitHub 發行版本](https://github.com/ompweb-dev/ompweb/releases)下載同一版本的 `ompweb-omp`,驗證 SHA-256 後保存(單一二進位檔放在同一資料夾,其他方式放在 `~/.omp/agent/omp-web/omp//`);也可用 `ompweb fetch-omp` 手動取得。支援的平台為 linux-x64、linux-arm64、darwin-x64、darwin-arm64 與 windows-x64;在其他平台(musl 的 Linux、Arm 版 Windows、FreeBSD)上無法啟動對話。無法連線至 GitHub 的機器請將 `OMP_WEB_OMP_BIN` 指向該發行版本 `ompweb-omp--` 的副本 -- Node.js `>= 24`。伺服器運作於 [Bun](https://bun.sh) 上,Bun 會作為 npm 套件的相依套件自動安裝(找不到隨套件安裝的 Bun 時會使用 `PATH` 中的 Bun) - -佇列中訊息的**引導(Steer)**、**刪除(Delete)**與**編輯(Edit)**操作皆為 `ompweb-omp` 通道的指令(`promote_queued_message`、`remove_queued_message`)。刪除操作會先經 omp 確認後,標籤才會自畫面消失;編輯操作則在成功取消佇列後,才會將文字取回輸入框。若該訊息已不再處於等待狀態,佇列將維持原狀並顯示提示;ompweb 不會重複傳送引導訊息。 - -佇列面板會顯示 omp 自身的佇列狀態(`get_state` 中的 `queuedMessages` 與 `queue_update` 事件),因此所有檢視該對話的裝置皆能看到一致的排隊訊息。點選**停止(Stop)**會將仍在佇列中等待的訊息文字退回輸入框,而非任由代理繼續執行;但若模型已經透過即時引導接收了該操作,該次引導仍會繼續執行。 - -## 在密碼保護下安裝應用程式(PWA) - -若要安裝此 Web 應用程式,請先登入後使用瀏覽器的安裝選單。 -網頁中單一的 manifest 連結會附帶認證資訊向 `/api/manifest` 發出請求;該端點使用現有的網頁密碼防護與 private、重新驗證(revalidating)快取機制。 -其 192×192 與 512×512 PNG 圖示直接以內嵌方式包含在打包資源中,因為 Android 原生安裝程式在抓取一般圖示網址時不會攜帶驗證 Cookie。安裝後應用程式仍會於 `/` 啟動,作用範圍(scope)為 `/`。其 `theme_color` 與 `background_color` 來自清單連結的 `?theme=` 參數:Chrome 在重新整理已安裝應用程式的清單時不會附帶 Cookie,因此伺服器會將所選主題的色彩(記錄於 `omp-theme-color` Cookie 中)渲染至該連結。Chrome 153 及更新版本在下次檢查清單更新後,會據此為已安裝應用程式的 Android 導覽列著色。 - -請保持 Cloudflare Access 與應用程式驗證處於啟用狀態;無需為 manifest 設定公開存取例外或 Access 略過規則。此機制並未加入離線支援。本機 Chromium 驗證已涵蓋受 Cookie 保護的中繼資料並封鎖 HTTP 圖示網址的情境(未產生任何安裝性錯誤)。專案維護者亦確認在 Cloudflare Access 保護下,實體手機安裝皆可正常運作。 +- npm 套件需要 **Node.js 24 或更新版本**。啟動器(`tau`)在 Node 上執行;伺服器在 [Bun](https://bun.sh) 1.4.4 或更新版本上執行,Bun 會作為套件的相依項目自動安裝(若內建的 Bun 不存在,則使用 `PATH` 上不低於該版本的 `bun`)。[單一執行檔](#單一執行檔)兩者都不需要。 +- 每台執行工作階段的機器都要安裝 **pi**: -## 通知功能 - -在**設定 → 通知**中開啟通知。每個瀏覽器皆各自保留其獨立設定:包含哪些事件需發出通知(任務完成、等待輸入、執行失敗、模型已自動切換),以及當你在另一個分頁使用 omp-web 時的通知方式(應用程式內浮動提示,或一律顯示系統通知)。目前正在檢視中的對話不會顯示通知。點選通知可直接開啟該對話。 - -- **推播(Push)**即使在未開啟任何 omp-web 分頁時也能送達瀏覽器。此功能需要安全環境(透過反向代理的 HTTPS,或 `localhost`),且 omp-web 伺服器需具備存取瀏覽器廠商推播服務的對外 HTTPS 連線能力。omp-web 會在初次使用時自動產生推播(VAPID)金鑰,並連同裝置清單與通知歷程記錄儲存在其資料目錄中(僅限擁有者存取),因此重新啟動後設定不會遺失。 -- 在 **iPhone 與 iPad** 上(iOS 16.4 或更新版本),推播功能僅支援已加入主畫面的應用程式。 -- 若在具備安全環境但未支援推播的環境下,只要 omp-web 分頁保持開啟,系統通知依然有效。若在非 localhost 位址透過純 HTTP 連線,瀏覽器會禁止所有系統通知:此時僅會保留在操作 omp-web 時顯示的應用程式內浮動提示。 -- 桌面瀏覽器會透過作業系統的通知中心顯示通知。若要接收背景推播,需保持瀏覽器處理程序執行中。 - -完成通知採用 `ompweb-omp` 通道的 `prompt_result` 與 `session_settled` 訊框。 - -## 快速開始 - -**無需安裝直接執行:** + ```bash + npm install -g @earendil-works/pi-coding-agent + ``` -```bash -npx @kahme247/ompweb@latest -``` + tau 執行 `PATH` 上的 `pi`。要使用其他 pi,請把 `TAU_PI_BIN` 設為它的路徑。tau 以 pi 1.5.2 為開發基準。沒有 pi 時仍可瀏覽過往工作階段,但無法啟動工作階段。 -或 -```bash -nix run github:ompweb-dev/ompweb -``` +## 安裝 -**或是全域安裝:** +### npm 或 Bun ```bash -npm install -g @kahme247/ompweb -ompweb +npm install -g @ompweb-dev/tau +tau ``` -**或下載單一二進位檔**(無需 Node 或 npm):請參閱[單一二進位檔](#單一二進位檔)。 - - -在瀏覽器中開啟 [http://127.0.0.1:30177](http://127.0.0.1:30177)。 -### 命令列選項 - -```bash -ompweb --port 8080 # 自訂連接埠 -ompweb --hostname 0.0.0.0 # 監聽網路介面 -ompweb hash-password # 輸出供 OMP_WEB_PASSWORD_HASH 使用的雜湊值 -ompweb fetch-omp # 從 GitHub 發行版本下載此版本的 ompweb-omp(驗證 SHA-256,僅在缺少時) -ompweb preflight # 如同新對話般啟動一次 omp 並等待其 hello;失敗時說明原因並以 1 結束 -ompweb --no-open # 不自動開啟瀏覽器 -ompweb --install-tray # 安裝 Windows 系統匣服務與桌面捷徑 -ompweb --uninstall-tray # 解除安裝 Windows 系統匣服務與捷徑 -ompweb --tray # 啟動背景系統匣管理工具 -ompweb systemd install # 安裝 Linux systemd 使用者服務(網頁 + ompweb-host 守護行程) -ompweb launchd install # 安裝 macOS launchd 代理程式(網頁 + ompweb-host 守護行程) -ompweb --help # 顯示說明 -ompweb --version # 顯示版本資訊 -``` +`bun add -g @ompweb-dev/tau` 安裝的是同一個套件;`tau` 啟動器仍需要 `PATH` 上的 Node.js 24。`npx @ompweb-dev/tau@latest` 不必全域安裝即可執行。 -### 密碼保護 +tau 會在瀏覽器中開啟 `http://127.0.0.1:30187`。在 **Settings → API Keys & Providers** 中登入你的模型供應商(見[設定](#設定)),選擇工作區並開始工作階段。 -omp-web **絕不會將明文密碼傳遞給伺服器**,因為每個 `omp` 對話都會繼承伺服器的環境變數:若代理執行 `env` 指令,將會把密碼列印至對話檔案中並傳送給模型供應商。 -使用 `--password` 參數會在啟動時直接阻止 `ompweb` 執行。目前仍暫時支援 `OMP_WEB_PASSWORD` 環境變數:`ompweb` 會在啟動時計算其雜湊值,避免將其留在伺服器環境中,並記錄警告訊息提示應改用 `OMP_WEB_PASSWORD_HASH`。 -建議儘速轉換:代理仍有機會自 `ompweb` 啟動處理程序中讀取明文,且每次啟動都會產生新的雜湊值,導致每次重新啟動皆會將所有瀏覽器登出。若同時設定這兩個變數會阻止 `ompweb` 啟動;請移除 `OMP_WEB_PASSWORD`。 +### 單一執行檔 -請改為產生雜湊值並提供給伺服器: +每個版本也提供編譯成單一程式的 tau,它要提供的檔案放在旁邊: +`tau-linux-x64.tar.gz`、`tau-linux-arm64.tar.gz`、`tau-darwin-x64.tar.gz`、`tau-darwin-arm64.tar.gz` 和 `tau-windows-x64.zip`。它本身不需要 Node.js、npm 或 Bun。它不包含 pi:它執行 `PATH` 上的 `pi`(或 `TAU_PI_BIN`)。`main` 上每個通過 CI 的提交也會發布為帶有相同壓縮檔的預先發布版本。 ```bash -ompweb hash-password # 詢問兩次密碼,輸入內容自動隱藏 - -OMP_WEB_PASSWORD_HASH='scrypt$15$8$1$…' ompweb +tar -xzf tau-linux-x64.tar.gz -C ~/.local/share # unpacks tau-linux-x64/ +~/.local/share/tau-linux-x64/tau # same options and environment variables as the npm launcher ``` -`ompweb hash-password` 會從標準輸入(stdin)讀取密碼——絕不透過命令列引數傳遞——以確保密碼不會出現在 Shell 歷程記錄與 `ps` 行程輸出中。 -該雜湊採用帶有全新 16 位元組鹽值(salt)的 scrypt(N = 2^15, r = 8, p = 1),並以自我描述格式 `scrypt$$$

$$` 輸出。任何讀取該雜湊的人皆無法直接拿來登入,且無法將其還原為原始密碼。 - -對話工作階段並非直接以密碼雜湊簽章。首次啟動時會在 `PI_CODING_AGENT_DIR` 指定的代理目錄下(未設定時為 `~/.omp/agent`)建立 `omp-web/web-auth-secret.json`(權限 `0600`),並與雜湊值混淆計算,因此變更密碼依然能將所有人登出,同時單憑儲存的雜湊值絕對無法偽造登入工作階段。 - -各項服務安裝程式(`ompweb systemd install`、`ompweb-launchd install`、Linux 系統匣以及 Windows 服務)在安裝時仍接受傳入 `OMP_WEB_PASSWORD`,並會在寫入設定檔前先行雜湊處理。設定檔中僅會儲存雜湊值。 - -在 Windows 上,系統匣與背景服務每次啟動伺服器時,都會直接從使用者或系統環境變數(例如 `setx OMP_WEB_PASSWORD_HASH "scrypt$…"`)讀取 `OMP_WEB_PASSWORD_HASH`,而非從當初啟動服務時的環境變數讀取。變更或移除雜湊值會在下次伺服器重新啟動時生效,無需將 Windows 登出。 +- 把 `tau` 留在它的目錄中:它從那裡提供 `dist/`、`public/` 和它的 pi 擴充功能(可以在 `PATH` 上放一個符號連結),設定了 `TAU_PACKAGE_DIR` 時則從該目錄提供。 +- 此執行檔有 `tau host` 和 `tau hash-password`,但沒有系統匣和服務安裝程式。服務單元需要自行撰寫,見[服務](#服務)中的範例。 +- macOS 會隔離下載的檔案:首次啟動前執行一次 `xattr -dr com.apple.quarantine tau-darwin-arm64`。 +- macOS 15 及之後的版本會在應用程式存取本機網路前詢問。如果 `curl` 能連到區域網路中的伺服器,而 `tau host` 回報 `ECONNREFUSED`,請在「系統設定 → 隱私權與安全性 → 本機網路」中允許你的終端機(或 `tau`)。 -### 位於反向代理後方 - -請在 `/api/events/link`(瀏覽器)與 `/api/hosts/link`(主機)上轉發 WebSocket 升級請求;若未轉發升級請求,瀏覽器會在幾秒鐘後自動改用伺服器傳送事件(SSE)。在 nginx 中,這表示需設定 `proxy_http_version 1.1;`、`proxy_set_header Upgrade $http_upgrade;`、`proxy_set_header Connection "upgrade";`,並將 `proxy_read_timeout` 設定為遠高於 30 秒。 - -### 兩項服務:網頁伺服器與本機守護行程 - -ompweb 透過一個輕量的守護行程 `ompweb host` 來執行這台機器的 `omp` 對話,該守護行程透過 loopback 與網頁伺服器連結。各服務安裝程式(`ompweb systemd install`、`ompweb launchd install`、`ompweb --install-tray`)都會同時安裝兩項服務:網頁服務與 `ompweb-host`。解除安裝時也會一併移除兩者。 - -**在前台執行 ompweb**(在終端機中執行 `ompweb`,或使用 `npx @kahme247/ompweb@latest`)不會安裝任何服務,因此不會自動執行守護行程:請在第二個終端機中保持執行 `ompweb host`(使用 npx 時:`npx @kahme247/ompweb@latest host`)。若未執行它,「本機」將保持離線狀態。網頁伺服器在啟動時會寫入守護行程的連線設定,因此請先啟動網頁伺服器。 - -- **重新啟動或重新部署網頁伺服器不會中斷執行中的作業。** 守護行程會保持 omp 程序持續運作;重新啟動後的網頁伺服器會直接接管它們,不會跳出繼續提示,omp 正在等待的對話方塊或工具呼叫也會重新顯示。 -- **重新啟動守護行程則會結束執行作業**(因為它擁有 omp 程序)。若開啟了自動繼續,原本正在執行的對話會自動繼續一次。`ompweb systemd restart` 僅會重新啟動網頁服務;升級版本時,只有在守護行程的連線協定版本超出新版本支援的範圍時,才會重新啟動守護行程。 -- **升級後的首次啟動:** 若約 90 秒後仍未連結任何守護行程,ompweb 會顯示橫幅提示您平台的安裝指令。它絕不會自動自行安裝服務。在守護行程執行之前,「本機」會顯示為離線,且無法在上面啟動新的對話。 -- **它就像其他任何主機一樣。** 您可以在**設定 → 主機**中重新命名「本機」(清空名稱即可重設);它無法被撤銷。網頁伺服器僅會在 loopback 繫結位址啟動時,寫入守護行程的連線設定(`~/.omp/agent/omp-web/host.json`,權限 `600`)。 -- **開發環境:** `npm run dev` 不會接管守護行程(請參閱[本機開發](#本機開發))。 - -### 單一二進位檔 - -每個[發行版本](https://github.com/ompweb-dev/ompweb/releases/latest)亦提供編譯完成的單一執行檔,隨附其所提供服務的相關檔案: -`ompweb-linux-x64.tar.gz`、`ompweb-linux-arm64.tar.gz`、`ompweb-darwin-x64.tar.gz`、 -`ompweb-darwin-arm64.tar.gz` 以及 `ompweb-windows-x64.zip`。無需安裝 Node、npm -或 Bun,也無需安裝 omp:首次啟動時,它會從同一個發行版本下載其 omp 建置版本 `ompweb-omp`(驗證 SHA-256),並保存在同一資料夾中(預先發行版的封存檔已內含)。x64 建置版本採用 Bun 的基準執行階段,因此亦可在不具備 AVX2 指令集的 CPU 上運作。每個封存檔皆於 `licenses/` 包含其打包內容的授權條款。`main` 分支上通過 CI 的每次提交亦會發布為以建置時間命名的[預先發行版(prerelease)](https://github.com/ompweb-dev/ompweb/releases)(例如 `2026-11-01T10:30:00Z`),同樣包含上述五種封存檔。 +### 從原始碼執行 ```bash -tar -xzf ompweb-linux-x64.tar.gz -C ~/.local/share # 解壓縮出 ompweb-linux-x64/ -~/.local/share/ompweb-linux-x64/ompweb # 網頁伺服器:選項與環境變數同上 -~/.local/share/ompweb-linux-x64/ompweb host # 本機守護行程,於第二個終端機執行 -``` - -- **將 `ompweb` 保留在其資料夾內。** 它會執行同一資料夾中的 `ompweb-omp`,並從所在目錄提供 `dist/`、`public/` 與其他檔案(在系統 `PATH` 中建立指向它的符號連結可正常運作),若設定了 `OMP_WEB_PACKAGE_DIR` 則從該路徑提供。 -- **macOS** 會對下載檔案加上隔離屬性(quarantine):首次啟動前請先執行一次 `xattr -dr com.apple.quarantine ompweb-darwin-arm64`。 -- **macOS 15 或更新版本** 在應用程式存取區域網路前會先詢問權限。若 Mac 上的 `ompweb host` 對區網上的伺服器回報 `ECONNREFUSED`,但 `curl` 卻能正常連線,請前往「系統設定 → 隱私權與安全性 → 區域網路」允許你的終端機(或 `ompweb`)。透過 Tailscale 等 VPN 連線的伺服器,或從 SSH 工作階段啟動的 host 則不受影響。 -- **不提供系統匣、服務安裝程式或應用程式內更新。** 若要更新,請停止 `ompweb` 與 `ompweb host`,以新發行版本替換該目錄,然後再次啟動兩者;當有新版本釋出時,**設定 → 系統** 會提供發行頁面連結。你的對話與設定皆儲存於 `~/.omp`,不在該目錄中。 -- **作為 systemd 使用者服務**,請自行編寫這兩個單元(請調整路徑): - -```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 與 OMP_WEB_HOSTNAME 放置於此,如同 ompweb-systemd。 -EnvironmentFile=-%h/.omp/agent/web-service.env -Restart=on-failure -RestartSec=3 - -[Install] -WantedBy=default.target +git clone https://github.com/ompweb-dev/tau.git +cd tau +npm install +npm run build +node bin/tau.js ``` -```ini -# ~/.config/systemd/user/ompweb-host.service -[Unit] -Description=ompweb host daemon -# 在網頁伺服器寫入連線設定前它會結束:保持重新啟動。 -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 -RestartPreventExitStatus=0 -RestartSec=10 +```text +tau [options] -[Install] -WantedBy=default.target -``` + -p, --port Server port (default 30187, env PORT) + -H, --hostname Bind hostname (default 127.0.0.1, env TAU_HOSTNAME) + --no-open Do not open the browser automatically + --install-tray Install the tray, background service and shortcuts (Windows; Linux SNI tray) + --uninstall-tray Uninstall them + --tray Start the background tray manager + -h, --help Show help + --version Show the version -```bash -systemctl --user daemon-reload -systemctl --user enable --now ompweb ompweb-host +tau hash-password Read a password from stdin and print the value for TAU_PASSWORD_HASH +tau host ... The host daemon (see "Hosts and cluster") +tau systemd ... | tau launchd ... Forward to tau-systemd / tau-launchd ``` - 在 macOS 上,編寫兩個 launchd agent(`ProgramArguments` 為 `…/ompweb --no-open` 與 `…/ompweb host`,搭配 `RunAtLoad` 與 `KeepAlive`)可達到相同效果;在 Windows 上,則可建立兩個在登入時執行 `ompweb.exe --no-open` 與 `ompweb.exe host` 的工作排程器工作。 +正式環境的伺服器在本機的主機常駐程式(`tau host`)未執行時會啟動它:所有工作階段(包括本機的)都在這個常駐程式下執行,因此重新啟動 Web 伺服器不會停止正在執行的工作階段。 +### 環境變數 -### 作為 Windows 服務執行(系統匣) +| 變數 | 意義 | +| --- | --- | +| `PORT` | 伺服器連接埠(預設 `30187`)。 | +| `TAU_HOSTNAME` | 繫結位址(預設 `127.0.0.1`)。 | +| `TAU_NO_OPEN` | `1`、`true`、`yes` 或 `on`:不開啟瀏覽器。 | +| `TAU_PASSWORD_HASH` | `tau hash-password` 輸出的密碼雜湊。啟用登入頁。 | +| `TAU_TRUSTED_HEADER_SHA256` | 受信任的反向代理在 `X-Tau-Auth` 中傳送的密鑰的 SHA-256 摘要(十六進位),見[下文](#在受信任的代理後略過密碼)。 | +| `TAU_PI_BIN` | 用來取代 `PATH` 上那個 `pi` 的執行檔路徑。 | +| `PI_CODING_AGENT_DIR` | pi 的 agent 目錄(預設 `~/.pi/agent`);tau 讀寫同一個目錄。 | +| `TAU_NAME` | 瀏覽器標題中的顯示名稱。`url`、`host` 或 `domain` 表示取自請求的主機名稱。 | +| `TAU_DISABLE_AUTOUPDATE` | `1`、`true`、`yes` 或 `on`:拒絕伺服器和主機的應用程式內更新。 | +| `TAU_STT_ENDPOINT`、`TAU_STT_KEY`、`TAU_STT_MODEL` | 語音轉寫:端點接收 multipart 的 `file`(和 `model`),`TAU_STT_KEY` 作為 Bearer 權杖傳送。未設定端點時語音輸入關閉。 | +| `TAU_DISCONNECT_DESTROY_MS` | 無人檢視的工作階段程序在多久後停止(預設 2 分鐘,`0` 表示停用)。 | -將 ompweb 安裝為 Windows 背景服務,包含系統匣圖示與開機登入時自動啟動: +### 密碼 -```bash -ompweb --install-tray -``` - -可自**設定 → 系統 → Windows 背景服務**管理,或透過命令列操作: +繫結到 `127.0.0.1` 時,tau 不需要密碼。要監聽其他位址,tau 必須有密碼雜湊,否則拒絕啟動: ```bash -ompweb --tray # 啟動系統匣管理工具 -ompweb --uninstall-tray +tau hash-password # prompts, input hidden +echo "a-long-random-password" | tau hash-password +TAU_PASSWORD_HASH='scrypt$15$8$1$...' tau --hostname 0.0.0.0 ``` -安裝程式會在桌面與開始功能表建立捷徑。服務發生異常時會自動重新啟動,並在系統匣顯示目前連接埠與運作狀態。安裝時也會將[本機守護行程](#兩項服務網頁伺服器與本機守護行程)註冊為第二個排程工作(`ompweb host`);系統匣會同時顯示兩者的狀態。 - -### 作為 macOS 服務執行(launchd) +tau 只接受雜湊。`--password` 參數會被拒絕。明文的 `TAU_PASSWORD` 仍會被偵測到:tau 在啟動時將它雜湊,從自己的環境中刪除它,並在警告中印出應改用的雜湊(與 `TAU_PASSWORD_HASH` 同時設定則會被拒絕)。原因是每個 pi 工作階段都繼承 tau 的環境,代理可能把明文密碼印到對話紀錄中。瀏覽器登入有效期為 30 天。 -將 ompweb 安裝為 launchd 使用者代理程式(User Agent),於登入時自動啟動並在異常終止時自動重新啟動: +### 在反向代理之後 -```bash -npx --yes @kahme247/ompweb@latest ompweb-launchd install -``` +在非迴路位址上無 TLS 監聽時,tau 會發出警告。請透過反向代理或 VPN 以 HTTPS 提供服務,並讓 tau 本身繫結到 `127.0.0.1`。代理必須轉送 WebSocket 升級(主機使用 `/api/hosts/link` 和 `/api/hosts/maintenance`)。對於主機以權杖驗證的路徑(`/api/hosts/link`、`/api/hosts/maintenance` 和 `/api/hosts/cluster-config/…`),代理不得再加上自己的驗證。 -管理指令如下: +#### 在受信任的代理後略過密碼 -```bash -npx --yes @kahme247/ompweb@latest ompweb-launchd status # 顯示服務狀態 -npx --yes @kahme247/ompweb@latest ompweb-launchd uninstall # 停止並移除服務 -``` +tau 自己看不到用戶端位址,因此可以由反向代理為請求擔保。代理在 `X-Tau-Auth` 標頭中傳送一個密鑰,tau 只在 `TAU_TRUSTED_HEADER_SHA256` 中保存該密鑰的 SHA-256 摘要。標頭雜湊與摘要相符的請求視為已登入。沒有密碼雜湊時,就沒有可略過的東西。 -該服務執行 `npx --yes @kahme247/ompweb@latest`;若要鎖定特定版本,可傳入套件規格,例如 `ompweb-launchd install @kahme247/ompweb@0.3.6`。安裝時會讀取所有[環境變數](#環境變數)並寫入 plist 檔案,此外還包含 `OMP_WEB_PKG`(套件規格,等同於位置引數)。作為服務執行時,預設**不會**自動開啟瀏覽器——安裝時帶入 `OMP_WEB_NO_OPEN=0` 可恢復自動開啟行為。 +產生一個長的隨機密鑰,且不要把它寫在命令列上。下面的指令把它寫入 nginx 的 include 檔案,只印出摘要: ```bash -npx --yes @kahme247/ompweb@latest hash-password # 以互動方式輸入密碼並產生雜湊值 -OMP_WEB_PASSWORD_HASH='' npx --yes @kahme247/ompweb@latest ompweb-launchd install +secret=$(openssl rand -hex 32) +printf 'map $tau_trusted $tau_auth {\n 1 "%s";\n default "";\n}\n' "$secret" \ + | sudo install -m 0640 -o root -g www-data /dev/stdin /etc/nginx/tau-auth.conf +printf %s "$secret" | sha256sum | cut -d' ' -f1 +unset secret ``` -請先執行 `npx --yes @kahme247/ompweb@latest hash-password` 以互動方式產生密碼雜湊,再透過 `OMP_WEB_PASSWORD_HASH` 傳入,避免將密碼明文留在 shell 歷史紀錄中;plist 內只會儲存雜湊值,絕不包含密碼明文。 - -當繫結至非回呼(non-loopback)主機時,請務必設定 `OMP_WEB_PASSWORD_HASH`(反向代理或 VPN 僅提供額外防護),並透過受信任的反向代理或 VPN 使用 HTTPS。切勿將未經驗證的 Web UI 暴露在公開網路中,或在明文 HTTP 連線下傳送密碼與工作階段 Cookie。 - -記錄檔位於 `~/Library/Logs/ompweb/ompweb.log`(網頁)與 `~/Library/Logs/ompweb/ompweb-host.log`([本機守護行程](#兩項服務網頁伺服器與本機守護行程))。plist 檔案存放於 `~/Library/LaunchAgents/com.kahme247.ompweb.plist`(權限 600;其中儲存的是密碼雜湊,而非密碼明文)以及 `~/Library/LaunchAgents/com.kahme247.ompweb-host.plist`。 - -### 作為 Linux 服務執行(systemd) - -將 ompweb 安裝為 systemd **使用者(user)**服務,於登入時自動啟動並在異常終止時自動重新啟動: +```nginx +# http {} context +geo $tau_trusted { + default 0; + 10.0.0.0/16 1; +} +include /etc/nginx/tau-auth.conf; -```bash -npx --yes --package=@kahme247/ompweb@latest ompweb-systemd install +# the location that proxies to tau +proxy_set_header X-Tau-Auth $tau_auth; ``` -安裝程式會自動建立權限為 `600` 的 `~/.omp/agent/web-service.env`;無需手動建立檔案。明確指定 `--package` 參數可確保 `npx` 執行所選套件內的 systemd 執行檔。 -若要將服務繫結至所有 IPv4 介面以供區網存取,請先以互動方式產生密碼雜湊,並於安裝時透過 `OMP_WEB_PASSWORD_HASH` 設定(避免將密碼明文留在 shell 歷史紀錄中): +一律設定此標頭,這樣用戶端自己傳送的 `X-Tau-Auth` 會被空值取代。為 tau 的 `server` 區塊設定明確的 `server_name`,並在 `default_server` 區塊中對其他主機名稱 `return 444;`,以免 DNS 重新繫結讓 nginx 把密鑰加到其他網站的請求上。tau 只保存快速的 SHA-256 摘要,這只對長的隨機密鑰安全:不要在這裡重複使用密碼。 -```bash -npx --yes @kahme247/ompweb@latest hash-password # 以互動方式輸入密碼並產生雜湊值 -OMP_WEB_HOSTNAME=0.0.0.0 OMP_WEB_PASSWORD_HASH='' \ - npx --yes --package=@kahme247/ompweb@latest ompweb-systemd install -``` +## 服務 -密碼雜湊會直接寫入 `web-service.env`。 +每個安裝程式都執行兩個服務:Web 伺服器和主機常駐程式(`tau host`)。 -管理指令如下: +### Linux(systemd 使用者服務) ```bash -npx --yes --package=@kahme247/ompweb@latest ompweb-systemd status # 顯示服務狀態 -npx --yes --package=@kahme247/ompweb@latest ompweb-systemd restart # start / stop / restart -npx --yes --package=@kahme247/ompweb@latest ompweb-systemd uninstall # 停止並移除服務 +TAU_PASSWORD_HASH='scrypt$...' tau-systemd install # or: npx --yes --package=@ompweb-dev/tau@latest tau-systemd install +tau-systemd status ``` -該服務會執行在安裝時解析出的本機 `ompweb` 二進位檔(可透過 `OMP_WEB_SYSTEMD_BIN` 覆寫)。執行階段組態位於 `~/.omp/agent/web-service.env`——透過系統匣(或任何文字編輯器)皆可直接修改連接埠、主機名稱與密碼雜湊,並只需重新啟動服務即可生效,無需重新安裝。 -安裝時指定的[環境變數](#環境變數)會直接寫入該檔案。作為服務執行時,預設**不會**自動開啟瀏覽器。服務單元檔位於 `~/.config/systemd/user/ompweb.service` 與 `~/.config/systemd/user/ompweb-host.service`([本機守護行程](#兩項服務網頁伺服器與本機守護行程));記錄檔會輸出至 journal: +`install` 把單元 `tau.service` 和 `tau-host.service` 寫入 `~/.config/systemd/user/`,建立 `~/.pi/agent/web-service.env`(連接埠、主機名稱、密碼雜湊;修改後不必重新安裝),並啟用兩者。其他指令:`uninstall`(`--clean-config` 一併刪除 env 檔案)、`start`、`stop`、`restart`(僅 Web 服務)、`open`。選項:`--port`、`--hostname`、`--no-autostart`、`--json`。記錄:`journalctl --user -u tau -u tau-host -f`。 -```bash -journalctl --user -u ompweb -u ompweb-host -f -``` +在 KDE Plasma 等支援 StatusNotifierItem 的桌面上,`tau --install-tray` 會加入一個控制這些 systemd 服務的系統匣圖示。 -在無外接顯示器的伺服器(headless server)上,若希望在所有登入階段皆結束後服務仍持續運作,請啟用使用者常駐(lingering): +### macOS(launchd) ```bash -loginctl enable-linger "$USER" +TAU_PASSWORD_HASH='scrypt$...' tau-launchd install # or: npx -p @ompweb-dev/tau@latest tau-launchd install +tau-launchd status +tau-launchd uninstall ``` -### Linux 系統匣(KDE Plasma 及相容環境) +`install` 建立 LaunchAgent `dev.ompweb.tau` 和 `dev.ompweb.tau-host`,它們在登入時啟動,當機後重新啟動。它從執行時的環境讀取 `PORT`、`TAU_HOSTNAME`、`TAU_PASSWORD_HASH`、`TAU_TRUSTED_HEADER_SHA256`、`TAU_PI_BIN`、`TAU_NAME`、`TAU_DISABLE_AUTOUPDATE` 和 `PI_CODING_AGENT_DIR`。記錄寫入 `~/Library/Logs/tau`。 -在 Linux 上,`ompweb-tray` 會註冊一個具備快顯功能表的 StatusNotifierItem 系統匣圖示:可開啟 Web UI、複製網址、啟動/停止/重新啟動 systemd 服務、檢視記錄、將 Web UI 暴露至網路、變更連接埠、設定網頁密碼、切換開機自動啟動,以及結束系統匣程式。 +### Windows(系統匣和背景服務) -```bash -npx --yes --package=@kahme247/ompweb@latest ompweb-tray --install # 圖示 + 自動啟動 + 啟動系統匣 -npx --yes --package=@kahme247/ompweb@latest ompweb-tray --status # 檢視系統匣與服務狀態 -npx --yes --package=@kahme247/ompweb@latest ompweb-tray --uninstall # 移除自動啟動並停止系統匣 +```powershell +tau --install-tray ``` -**暴露至網路(Expose to Network)**會將服務從 `127.0.0.1` 重新繫結至 `0.0.0.0`,讓 Web UI 能自區網或 VPN(例如 Tailscale)存取。離開回呼介面時必須設定網頁密碼——必要時系統匣會透過 `kdialog`/`zenity` 跳出提示詢問密碼,並儲存其雜湊值。**變更連接埠…**與**設定網頁密碼…**會修改 `~/.omp/agent/web-service.env` 並重新啟動服務。當繫結至非回呼主機時,請務必透過受信任的反向代理或 VPN 使用 HTTPS 進行遠端連線。 - -系統匣選單中的「隨 Plasma 啟動」可切換位於 `~/.config/autostart/ompweb-tray.desktop` 的桌面自動啟動項目。需要執行中的 StatusNotifierItem 主機支援(KDE Plasma 以及多數 Wayland/X11 桌面環境)。 - -## 在其他機器上執行對話 - -單一 ompweb 可以啟動並監看其他機器上的 omp 對話。每台機器保留其各自的 ompweb(及其 `ompweb-omp`)、`~/.omp/agent` 目錄、對話與認證資訊;ompweb 僅負責路由。遠端機器需要 Node 24(用於 `npx`)或[單一二進位檔](#單一二進位檔),並且必須能透過 HTTP(S) 連線至 ompweb 伺服器。遠端機器向外連線,因此可以位於 NAT 後方。 - -### 透明主機集區 - -設定完成的主機集區會顯示為一個目標,每個已註冊的儲存庫各有一個項目。請選取集區,而非個別工作節點;新的獨立對話會配置到符合條件的工作節點,並取得隔離的本機工作樹。新增集區專案只會註冊其 Git 來源,不會建立中央工作副本。所選工作節點會在對話開始時準備工作副本,並明確回報身分驗證、準備作業或儲存庫衝突。獨立主機(包含 Mac)仍支援輸入路徑,以及本機複製進度與取消操作。 - -成員主機上既有的非集區工作區仍可從側邊欄存取;這些主機不會列為一般的集區建立目標。為新對話的附件解析所屬主機時,不會替換目前的輸入框,也不會丟棄草稿或上傳內容。若指令探索或系統提示檢視延後啟動對話,配置與準備失敗也會顯示;重試仍須由使用者明確操作。 +這會安裝背景服務、主機常駐程式(排程工作 `tau-host`)、系統匣圖示、登入時自動啟動以及桌面和開始功能表捷徑。以 `tau-tray status|start|stop|restart|open|uninstall` 管理。服務從 `%USERPROFILE%\.pi\agent\web-service.json` 讀取設定,從使用者或系統環境變數讀取 `TAU_PASSWORD_HASH`。 -重試建立時會沿用相同的建立意圖與識別碼。一旦確認實際對話,其所屬主機便是繼續對話、檔案、終端機、上傳、產物、重新命名與刪除操作的唯一依據,即使集區成員變更也不例外。所屬主機無法使用時,不會在其他工作節點或 Mac 上建立替代對話。已修改但尚未提交的檔案與未發布的工作仍留在原主機;不支援即時遷移或未發布工作的容錯移轉。若回應結果不確定,請先檢查保留的對話,再明確重試可能已執行的指令。 +### 把單一執行檔作為服務 -### 連結獨立主機 +自行撰寫兩個單元。以 systemd 為例(依需要調整路徑): -1. 在 ompweb 伺服器上,開啟**設定 → 主機 → 新增主機**,輸入名稱,並複製權杖。權杖僅會顯示一次;系統只會儲存其雜湊值。 -2. 在遠端機器上儲存連線資訊。權杖是從 stdin 讀取,絕不會作為引數傳遞,因此不會出現在 `ps` 中: - - ```bash - npx @kahme247/ompweb@latest host login --url https://your-ompweb.example.com - ``` - - 出現提示時貼上權杖(或透過管道輸入)。設定會以 `600` 權限儲存至 `~/.omp/agent/omp-web/host.json`。 -3. 啟動連線並保持其持續執行: - - ```bash - npx @kahme247/ompweb@latest host - ``` - - 主機會在「設定 → 主機」中顯示為**線上**,側邊欄會為其建立群組,而在新對話畫面中也會出現主機選取器。 - -**設定 → 主機**也會顯示每台機器的 ompweb 守護行程與 omp 版本、可用更新與更新操作(包含**本機**)。檢查與安裝會在所選主機上執行,而非在網頁伺服器上執行。若某個主機更新的連線協定與目前的網頁應用程式不相容,該更新仍會顯示,但會被封鎖並說明原因;請先更新網頁伺服器。無法驗證目標連線協定的更新同樣會被封鎖。omp 隨附於每個 ompweb 發行版本,並隨之一起更新。在更新守護行程之前,請先關閉其對話行程:更新程式拒絕中斷執行中的對話或子代理。**設定 → 系統**則保留網頁伺服器自身的應用程式更新與服務設定。主機需要支援這些更新操作的守護行程版本;較舊的版本會顯示不支援訊息,需先手動更新一次。若守護行程與網頁伺服器共用同一個安裝目錄,請先更新伺服器,再使用主機的「僅重新啟動」更新。不支援的服務封裝程式與偵測到的外部重新啟動指令碼會顯示需手動更新的原因。更新前景執行的守護行程前,請先停止外部的自動重新啟動迴圈。 - -守護行程更新是由主機上獨立的更新程式行程執行。它會停止守護行程、替換為新發行版並再次啟動;若失敗則會還原先前的發行版。若該更新程式在停止守護行程後本身遭到強制終止(例如重新開機或記憶體不足 OOM 終止),將不會有任何程序重新啟動主機,主機便會維持離線。在主機上手動復原方式:在包含安裝目錄的資料夾中,`.ompweb-backup-` 即為先前的發行版。若該目錄存在,請將目前的安裝目錄移開,並將備份重新命名回原本的安裝目錄名稱,然後再次啟動 `ompweb host`(或其服務)。「設定 → 主機」會將該次更新回報為已中斷。 +```ini +# ~/.config/systemd/user/tau.service +[Unit] +Description=tau web service -連線必須使用 `https://`。僅在 loopback 位址或指定 `--allow-http` 時(例如在 tailnet 網路中)才接受純 `http://`: +[Service] +WorkingDirectory=%h +ExecStart=%h/.local/share/tau-linux-x64/tau --no-open +Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin +# TAU_PASSWORD_HASH, PORT and TAU_HOSTNAME go here. +EnvironmentFile=-%h/.pi/agent/web-service.env +Restart=on-failure +RestartSec=3 -```bash -npx @kahme247/ompweb@latest host login --url http://100.64.0.1:30177 -npx @kahme247/ompweb@latest host --allow-http +[Install] +WantedBy=default.target ``` -若連線中斷,常駐程式(daemon)會自動重新連線(從 1 秒退避重試,加倍遞增至 60 秒;在同一台機器上的網頁伺服器最多 3 秒)。連線失敗後它會重新讀取儲存的連線資訊,因此即使網頁伺服器在不同連接埠上恢復,也無需重新啟動常駐程式即可自動找到。網路中斷後,遠端機器上的執行作業仍會繼續;聊天介面會顯示離線橫幅,當連線恢復時執行作業會重新連結。筆記型電腦進入睡眠狀態(通常是闔上螢幕)時,會將常駐程式及其 omp 執行作業與其上的其他作業一併暫停:喚醒時會自動恢復,連線也會在當時恢復。接上擴充底座或設定不休眠的裝置則可在闔上螢幕時繼續執行。在設定中撤銷主機會關閉其連線,常駐程式也會停止其 omp 程序。 - -反向代理必須在 `/api/hosts/link` 上轉發升級請求;請參閱[位於反向代理後方](#位於反向代理後方)。 - -請先更新伺服器上的 ompweb,再更新其主機:此版本之前的主機在更新前會顯示為**需要升級**。 - -注意事項: - -- **服務輔助程式:** `ompweb systemd install` 與 `ompweb launchd install` 會在網頁伺服器旁同時設定本機自己的守護行程(請參閱[兩項服務](#兩項服務網頁伺服器與本機守護行程))。在另一台機器上您只需要守護行程,因此請改用[讓主機作為服務持續執行](#讓主機作為服務持續執行)。當伺服器撤銷其權杖,或其連線協定版本超出伺服器支援的範圍時(舊於伺服器支援的最舊版本,或新於伺服器:請在較舊的一方更新 ompweb),守護行程會以結束代碼 `1` 結束;若同一個主機有較新的連線取代它,則以 `0` 結束。SIGTERM 或 SIGINT 會停止守護行程及其 omp 程序。每個主機僅能有一個連線,切勿使用相同權杖執行兩個守護行程。 -- **伺服器的代理目錄保存主機清單**(`omp-web/hosts.json`)。若以不同的 `PI_CODING_AGENT_DIR` 啟動 ompweb 伺服器,或遺失該檔案,會導致所有主機權杖失效:每個常駐程式都會收到已遭撤銷的通知,停止其 omp 程序並結束。 -- **信任機制:** 已連結的主機會在該機器上為掌控 ompweb 伺服器或權杖的人員執行具備完整工具存取權限的 omp。請妥善保護權杖隱私,並在機器淘汰時將其撤銷。 -- **每台主機上的工作區檔案:** 檔案總管、預覽、下載、檔案搜尋、@-提及與即時檔案監聽皆使用所屬機器的守護行程,包括這台機器。檔案總管上傳每個檔案支援最高 2 GiB,且無 100 MiB 批次總上限;預覽限制仍為文字 256 KiB、圖片與 DOCX 10 MiB。切換對話時,檔案分頁會保留其來源主機。無法連線或版本較舊的守護行程會回報離線或提示需要更新;主伺服器絕不會以本機檔案系統代為取代。 -- **每台主機上的 Git 與工作樹:** 狀態、差異(diff)、GitHub Issue 連結,以及工作樹的建立、選擇與移除皆在所屬守護行程上執行。包含未提交變更(dirty)的工作樹仍需要明確的強制確認。切換工作樹只會改變新對話啟動的位置,不會影響已開啟的對話。 -- **每台主機上的目錄瀏覽與複製:** 「新增工作區」挑選器可巡覽該主機的目錄並在該處複製(clone)HTTPS/SSH 儲存庫。取消複製會等待複製程序退出並進行安全清理;連線中斷時會回報未知的結果,而非假定複製已取消。若清理期間目標路徑發生變更,擷取的資料會保存在私有隔離目錄中,錯誤訊息會顯示其位置;在移除或還原任何內容前請先檢查該目錄。 -- **遠端主機尚不支援:** 技能、外掛程式、代理與 MCP 設定。對話紀錄文字搜尋目前仍僅掃描這台機器。對話工作階段可以在已連結主機上封存及還原。 -- **由代理發起的對話:** 在啟用代理工具時,代理可傳遞 `host` 給 `new_session`(預設為該代理自身所在的主機)。遠端主機每次都會要求確認,除非在「設定 → 主機」中為其開啟了**代理可在此處直接開始對話,無需詢問**。在遠端主機上執行的代理在於本機開始對話或傳送訊息之前,一定會先詢問確認。 - -### 讓主機作為服務持續執行 - -以下方式皆以主機模式執行[單一二進位檔](#單一二進位檔)。在 Linux 上,服務可在登出與重新開機後持續維持連線;Windows 排程工作會在使用者登入後啟動,因此重新開機後必須先登入;在 macOS 上,則透過指令碼在終端機中保持執行(原因詳見下方)。請先解壓縮適用於該機器的發行版,接著依照步驟 2 執行一次 `ompweb host login --url …` 以儲存連線資訊(將 `npx @kahme247/ompweb@latest` 替換為二進位檔路徑)。每種設定都會在 `ompweb host` 失敗 10 秒後重新啟動,但結束代碼為 `0` 時不會重新啟動:那代表有使用相同權杖的較新連線取代了它,若重新啟動會導致每 10 秒互相搶奪連線。若伺服器網址為純 `http://`,請在 `host` 後方加上 `--allow-http`;若儲存連線資訊時有設定 `PI_CODING_AGENT_DIR`,請在服務中也一併設定。獨立主機可同時連結至多台伺服器,並在伺服器支援連線協定 v7 時共用即時對話:請從每台額外的伺服器取得權杖,並執行 `ompweb host login --add --url `。請勿在同一台機器上同時執行本機 ompweb 網頁伺服器,因為它會為自己的守護行程寫入同一個連線設定檔。若要更新,請先停止服務、替換發行版目錄,然後重新啟動服務。撤銷主機後,請停止並移除其服務,否則它會持續重試。 - -**Linux(systemd 使用者服務)。** 建立 `~/.config/systemd/user/ompweb-host.service`(請調整發行版路徑): - ```ini +# ~/.config/systemd/user/tau-host.service [Unit] -Description=ompweb host +Description=tau 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 +ExecStart=%h/.local/share/tau-linux-x64/tau host +Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin +EnvironmentFile=-%h/.pi/agent/web-service.env Restart=always -# Exit 0: a newer link for this host replaced it. Restarting would take the link back. -RestartPreventExitStatus=0 RestartSec=10 [Install] @@ -389,198 +229,106 @@ WantedBy=default.target ```bash systemctl --user daemon-reload -systemctl --user enable --now ompweb-host -loginctl enable-linger "$USER" # 登出後仍保持執行 -journalctl --user -u ompweb-host -f # 檢視記錄 +systemctl --user enable --now tau tau-host ``` -**macOS(從終端機執行)。** 任何 launchd 工作都無法執行可供 omp 對話完整使用的主機:LaunchDaemon 沒有登入鑰匙圈(login keychain)或 SSH agent(對話需要它們來存取 SSH 金鑰與簽署提交),而 LaunchAgent 則無法連線至區網(LAN)位址。從終端機啟動的程序會繼承終端機的鑰匙圈與 SSH agent,因此請在終端機的 tmux 中執行主機,讓它在視窗關閉後仍持續運作。 - -不過,tmux 不會保留終端機的「區域網路(Local Network)」權限:tmux 伺服器會與終端機應用程式分離,接著 macOS 的區域網路隱私保護便會封鎖採用臨時簽章(ad-hoc signed)的 `ompweb` 二進位檔存取區網位址(`connect` 會因「No route to host」而失敗,守護行程會回報為 `ECONNREFUSED`;Apple 內建工具如 `curl` 不受封鎖,因此 `curl` 測試會通過)。請將主機連結至不會解析為區網位址的網址,例如伺服器的公開網址,或其 VPN/tailnet 名稱(由您的反向代理搭配自有憑證提供的 Tailscale MagicDNS 名稱)。將以下內容儲存為 `~/.local/bin/ompweb-host-run`(請調整 `DIR`)並以 `chmod +x` 設為可執行: - -```sh -#!/bin/sh -# Keeps `ompweb host` running in this terminal, which lends it its keychain and SSH agent. -# Restarts it 10 s after a crash; stops when the token is revoked or the link protocol is -# unsupported (exit 1), or on exit 0: a newer link replaced it, or it was stopped (Ctrl-C). -DIR=${OMPWEB_DIR:-$HOME/.local/share/ompweb-darwin-arm64} -# A tmux started over SSH sees the login keychain locked: unlock it while a terminal can ask. -security show-keychain-info login.keychain-db 2>/dev/null || security unlock-keychain login.keychain-db || exit 1 -while :; do - (cd "$DIR" && exec ./ompweb host) - rc=$? - case $rc in 0 | 1) exit "$rc" ;; esac - echo "ompweb host exited $rc; restarting in 10 s" >&2 - sleep 10 -done -``` +`PATH` 必須包含 `pi` 所在目錄(以及 pi 使用的 Node.js 的目錄)。在 macOS 上,兩個以 `RunAtLoad` 和 `KeepAlive` 執行 `…/tau --no-open` 與 `…/tau host` 的 launchd agent 可達到相同效果;在 Windows 上,則是兩個在登入時執行 `tau.exe --no-open` 與 `tau.exe host` 的工作排程器工作。 -在 tmux 視窗中執行 `ompweb-host-run`;按下 Ctrl-C 可停止守護行程及其對話。重新開機或登出後請再次啟動。若登入鑰匙圈因閒置或睡眠而自動上鎖,SSH 金鑰通行碼與簽署功能將會失敗,直到您重新啟動它為止。 +## 主機與叢集 -**Windows(登入時執行的排程工作)。** 在 PowerShell 中,將 `$dir` 設定為解壓縮後的發行版路徑: +### 主機常駐程式 -```powershell -$dir = "$env:LOCALAPPDATA\ompweb-windows-x64" -New-Item -ItemType Directory -Force "$env:USERPROFILE\.omp\agent\logs" | Out-Null -Set-Content "$dir\ompweb-host.ps1" @' -# Starts `ompweb host` again 10 s after it fails, and stops on exit 0 (a newer link replaced it). -# Output goes to ~\.omp\agent\logs\ompweb-host.log, moved to .log.1 past 10 MB (checked between restarts). -# For a plain http:// server URL, put --allow-http after `host` below. -$log = "$env:USERPROFILE\.omp\agent\logs\ompweb-host.log" -while ($true) { - if ((Test-Path $log) -and (Get-Item $log).Length -gt 10MB) { Move-Item $log "$log.1" -Force } - & "$PSScriptRoot\ompweb.exe" host 2>&1 | ForEach-Object { "$_" } | Out-File -Append -Encoding utf8 $log - if ($LASTEXITCODE -eq 0) { break } - Start-Sleep 10 -} -'@ -Register-ScheduledTask -TaskName ompweb-host -Force ` - -Trigger (New-ScheduledTaskTrigger -AtLogOn -User "$env:USERDOMAIN\$env:USERNAME") ` - -Action (New-ScheduledTaskAction -Execute powershell.exe -Argument "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$dir\ompweb-host.ps1`"") ` - -Settings (New-ScheduledTaskSettingsSet -ExecutionTimeLimit 0 -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries) -Start-ScheduledTask ompweb-host +`tau host` 是在一台機器上執行 pi 工作階段並讀取其工作階段檔案的程序。它透過 WebSocket 主動連線到一台或多台 tau 伺服器,因此可以位於 NAT 之後。連結或 Web 伺服器中斷時工作階段繼續執行,連結恢復後伺服器重新加入這些工作階段。在伺服器自己的機器上,常駐程式會自動連結(**Settings → Hosts** 中的「This machine」)。 + +```text +tau host login [--add] --url save a link; the host token is read from stdin +tau host logout --url remove a link +tau host [--allow-http] run the daemon +tau host status|drain|resume control the running daemon ``` -使用 `Stop-ScheduledTask ompweb-host` 停止排程工作,接著透過 `Get-Process ompweb | Where-Object Path -eq "$env:LOCALAPPDATA\ompweb-windows-x64\ompweb.exe" | Stop-Process` 結束執行中的主機(僅結束此發行版的 `ompweb.exe`;請依 `$dir` 調整路徑)。使用 `Unregister-ScheduledTask ompweb-host` 即可將其移除。 - -## 功能特色 - -- **互動式聊天**:與本機 `omp` 代理進行即時串流交談——完整呈現工具呼叫、思考深度等級、Token 計數、成本花費、上下文容量量表、佇列控制,以及中斷與重試功能。 -- **複製訊息內容**:透過每則訊息下方的按鈕,將使用者訊息或已完成的助理回覆複製為渲染後的純文字或原始 Markdown。思考過程、工具輸出與訊息控制項皆會自動排除。使用原始文字檢視器顯示的過長超大訊息,在兩種格式下皆會複製完整原始來源。 -- **佇列刪除確認**:在取消 OMP 中排隊的後續訊息或引導訊息之前,提供預覽與確認對話方塊。需具備原生 `remove_queued_message` 支援;已送達的訊息無法撤回。 -- **對話管理**:依專案瀏覽歷史對話、建立對話分支(fork)、在對話內部建立分支(branch)、封存/還原對話、匯入對話檔案,並支援透過網址深層連結(deep-link)。 -- **草稿復原**:未傳送的輸入文字會保留在對應的對話或新對話工作區內;在瀏覽器儲存空間允許的情況下,於同一個分頁中執行上一頁/下一頁巡覽或重新整理後皆能自動還原(最多保留 50 份草稿)。圖片與檔案附件則僅保留於記憶體中。 -- **即時計畫與子代理**:固定於輸入框上方的可摺疊面板,可即時追蹤待辦事項階段與執行中的子代理(狀態、工具、重試次數、Token/成本、巢狀任務),並提供對話紀錄檢視視窗與歷程還原功能。 -- **工具組合挑選器**:在輸入框中為新對話選擇工具組合——`none` / `default`(`read,bash,edit,write`)/ `full`(包含子代理在內的所有工具)。設定會持久化儲存在 localStorage 中。 -- **檔案總管與預覽**:與聊天介面並列瀏覽工作區檔案;在安全許可清單限制下預覽程式碼、Markdown、Mermaid、圖片、音訊、PDF 與差異比對(diff)。 -- **各主機的檔案**:檔案總管、搜尋、預覽、下載與即時更新皆使用該主機的守護行程。上傳每個檔案最高 2 GiB,無 100 MiB 批次總限制。預覽上限維持文字 256 KiB、圖片與 DOCX 10 MiB。切換對話不會改變檔案分頁所屬的主機。 -- **各主機的工作區**:Git 差異比對與工作樹操作、目錄巡覽、HTTPS/SSH 儲存庫複製皆在該主機上執行。取消複製會確認程序終止並完成安全清理,連線中斷則會顯示結果未知。 -- 複製清理期間若目標目錄遭替換,隔離資料會保存在私有目錄中,錯誤訊息會顯示保存位置。在刪除或還原前請先檢查其內容。 -- **Git Worktree 支援**:直接從側邊欄建立、切換與管理 Git 工作樹(worktree);對話與檔案根目錄會持續依專案妥善分組。 -- **遠端主機**:連結其他機器(例如 MacBook)並從單一 ompweb 在該機器上執行對話。側邊欄會依主機將對話分組。請參閱[在其他機器上執行對話](#在其他機器上執行對話)。 -- **使用量與分析**:位於**設定 → 使用量**的儀表板,提供 Token 數、花費、快取節省分析,並依供應商/模型/日期/專案細分統計,具備 SQLite 資料持久化儲存。 -- **Windows 系統匣與服務**:背景服務、系統匣圖示、登入自動啟動,以及桌面/開始功能表捷徑(Windows)。 -- **macOS launchd 服務**:LaunchAgent 服務,於登入時啟動、異常終止時自動重新啟動,並在 `~/Library/Logs/ompweb` 下記錄記錄檔。 -- **Linux systemd 服務與系統匣**:使用者服務,於登入時啟動、異常終止時自動重新啟動,並附帶具備服務控制功能的 StatusNotifierItem 系統匣圖示(支援 KDE Plasma 與相容桌面環境)。 -- **通知功能**:針對任務完成、等待使用者回覆、執行失敗與自動切換模型提供桌面與行動裝置(PWA)通知,在 HTTPS 環境下支援 Web Push 推播。請參閱[通知功能](#通知功能)。 -- **Web 設定介面**(11 個分頁):介面與行為、安全性與核准、AI 模型預設值、API 金鑰與供應商、使用量、代理與智慧功能(顧問、記憶、壓縮)、代理、擴充功能與工具(MCP、技能、外掛程式)、主機、通知、系統。 -- **斜線指令與快速鍵**:快捷提示詞(`/plan`、`/review`、`/fix`、`/test` 等)、`⌘K` / `Ctrl+K` 指令面板,以及模型/推論模式輪替切換。 -- **UI 主題與在地化語言**:溫潤紙質風格的淺色/深色主題,加上靈感源自 omp.sh 的午夜黑(`omp`)主題;支援聊天字型大小與介面縮放比例調整,並提供完整的英文、中文(簡體中文/繁體中文)與日文(日本語)翻譯。 - -## 環境變數 - -| 變數 | 說明 | 預設值 | -| --- | --- | --- | -| `PORT` | 伺服器連線埠 | `30177` | -| `OMP_WEB_HOSTNAME` | 伺服器繫結主機位址 | `127.0.0.1` | -| `OMP_WEB_PASSWORD_HASH` | 選用,來自 `ompweb hash-password` 的網頁登入密碼 scrypt 雜湊值。繫結至非 loopback 位址時為必填 | _無(停用身分驗證)_ | -| `OMP_WEB_TRUSTED_HEADER_SHA256` | 受信任反向代理於 `X-Omp-Web-Auth` 標頭中傳遞的金鑰 SHA-256 十六進位雜湊摘要,用於略過該請求的密碼驗證;請參閱[在受信任的網路中略過密碼驗證](#在受信任的網路中略過密碼驗證) | _無(已停用)_ | -| `OMP_WEB_NO_OPEN` | 設為 `1` 可防止自動開啟瀏覽器 | `0` | -| `OMP_WEB_DISABLE_AUTOUPDATE` | 設為 `1` 可停用更新檢查與應用程式內更新;變更後需重新啟動 | `0` | -| `OMP_WEB_NAME` | 顯示於瀏覽器分頁與已安裝應用程式的名稱。若設為 `url`、`host` 或 `domain`(不分大小寫),則採用瀏覽器連線的主機名稱(不含連接埠);localhost 與 IP 位址仍會保持 `omp web`。其他任何值將原樣採用。變更後需重新啟動 | `omp web` | -| `OMP_WEB_OMP_BIN` | 用於取代下載版本的 `ompweb-omp` 建置版本路徑(無法連線至 GitHub 的機器上為發行版本中 `ompweb-omp--` 的副本,原始碼檢出中為 `runner/release/ompweb-omp--`)。一般的 `omp` 不支援 ompweb 的通道,無法使用。服務安裝程式僅在你設定它時才會寫入服務環境 | _下載的 `ompweb-omp`_ | -| `PI_CODING_AGENT_DIR` | 自訂 omp 代理目錄 | `~/.omp/agent` | -| `OMP_WEB_STT_ENDPOINT` | 相容於 OpenAI 的語音轉文字(STT)端點網址。若保留未設定,則會透過 omp 自身的憑證搭配 `OMP_WEB_STT_MODEL` 進行轉錄 | _無_ | -| `OMP_WEB_STT_KEY` | STT 端點的選用 API 金鑰 | _無_ | -| `OMP_WEB_STT_MODEL` | STT 端點的模型名稱。未設定端點時:使用 omp 登入身分執行的語音轉文字模型,例如 `openai-codex/codex-transcribe`(ChatGPT 訂閱方案;需搭配支援該模型的 omp 版本) | _無(未設定端點時為停用)_ | - -**`OMP_WEB_NAME` 與已安裝的應用程式。** 已安裝的應用程式(PWA)名稱通常取自安裝時的頁面名稱。若你之後修改了 `OMP_WEB_NAME`,或者在 `OMP_WEB_NAME` 設為 `url`、`host` 或 `domain` 的情況下從不同位址連入 omp-web,作業系統可能會連帶重新命名該已安裝的應用程式。建議將 `OMP_WEB_NAME` 保留為空,或是設定一個無論透過何種網域名稱或位址連入皆能辨識此 omp-web 伺服器的固定名稱。 - -## 在受信任的網路中略過密碼驗證 - -omp-web 本身無法直接得知客戶端的實際位址,因此將此項判斷交由你的反向代理負責。反向代理會在 `X-Omp-Web-Auth` 標頭中傳送一組金鑰,而 omp-web 僅在 `OMP_WEB_TRUSTED_HEADER_SHA256` 中儲存該金鑰的 SHA-256 摘要。 -若傳入請求的標頭經雜湊計算後與該摘要相符,即視為已驗證登入。其餘所有連線依然必須透過 `OMP_WEB_PASSWORD_HASH` 中設定的密碼雜湊進行登入;若未設定密碼,則不存在略過驗證的情境,此標頭會被直接忽略。請確保 omp-web 僅繫結至 `127.0.0.1`,以便僅有代理伺服器能夠連線存取。 - -請依照以下方式產生金鑰及其摘要,避免在命令列中輸入金鑰本體,以防其進入 Shell 歷程記錄。此指令會將隨機金鑰直接寫入僅限 root 與 nginx 讀取的 nginx 設定檔中,且終端機僅會輸出摘要內容: +常駐程式只接受 `https://` 伺服器網址,`http://` 僅限迴路位址。`--allow-http` 允許對其他位址使用明文 HTTP;此時主機權杖以未加密方式傳輸,只應在受信任的網路中使用。 -```bash -secret=$(openssl rand -hex 32) -printf 'map $ompweb_trusted $ompweb_auth {\n 1 "%s";\n default "";\n}\n' "$secret" \ - | sudo install -m 0640 -o root -g www-data /dev/stdin /etc/nginx/ompweb-auth.conf -printf %s "$secret" | sha256sum | cut -d' ' -f1 -unset secret -``` +### 連結另一台機器 -請將 `www-data` 替換為你的 nginx 群組名稱(在部分 Linux 發行版上為 `nginx`)。 -將輸出的摘要設定為 `OMP_WEB_TRUSTED_HEADER_SHA256`。此時命令歷程記錄中僅包含執行指令,絕不留存金鑰。在 Windows 上,系統匣與背景服務會自使用者或系統環境變數讀取此值,如同 `OMP_WEB_PASSWORD_HASH`。 +另一台機器需要 pi,以及 npm 版 tau(Node.js 24)或單一執行檔。 -務必始終以此方式產生金鑰;切勿重複使用密碼或其他自訂字串。omp-web 儲存的是計算快速且無鹽值的純 SHA-256 摘要,此機制僅對長度充足的隨機金鑰安全:若使用過短或易猜測的字串,任何讀取到摘要的人皆可透過字典攻擊還原原始內容。 +1. 在 tau 伺服器上開啟 **Settings → Hosts → Add host**,輸入名稱並複製權杖。權杖只顯示一次;伺服器只保存其雜湊。 +2. 在另一台機器上儲存連結。依提示貼上權杖,或透過管線傳入;它不會出現在 `ps` 中: -搭配 nginx 使用時,請僅向你信任的 IP 範圍傳送該金鑰: + ```bash + npx @ompweb-dev/tau@latest host login --url https://tau.example.com + ``` -```nginx -# http {} 區塊 -geo $ompweb_trusted { - default 0; - 10.0.0.0/16 1; -} -include /etc/nginx/ompweb-auth.conf; # 上述步驟建立的 map 設定檔 + 連結以 `600` 權限儲存到 `~/.pi/agent/tau/host.json`。`--add` 會新增到另一台伺服器的連結,而不是取代第一個。 +3. 執行常駐程式並讓它持續執行(作為服務執行,見[服務](#服務)): -# 轉發至 omp-web 的 location 區塊 -proxy_set_header X-Omp-Web-Auth $ompweb_auth; -``` + ```bash + npx @ompweb-dev/tau@latest host + ``` -務必如上所示一律設定此標頭:針對其他客戶端所帶入的空字串值,會覆蓋掉客戶端自行傳入的任何 `X-Omp-Web-Auth` 標頭內容。當某個區塊未自行設定任何 `proxy_set_header` 時,nginx 才會自外層區塊繼承設定,因此請將此行與該 location 的其他 `proxy_set_header` 放在一起。 +之後該主機顯示為上線,側邊欄為它的工作區分組,新增工作階段畫面也可以選擇它。每台主機保留自己的 `~/.pi/agent`、工作階段和供應商登入。**Settings → Hosts** 還可以重新命名和撤銷主機、顯示每台主機的 tau 版本並提供更新,以及設定代理能否不經詢問就在該主機上啟動工作階段。被撤銷主機的常駐程式會停止它的工作階段。 -請嚴格僅針對專屬主機名稱提供 omp-web 服務:為其 `server` 區塊明確指定 `server_name`,並加入一個以 `return 444;` 回應所有其他主機名稱的 `default_server` 區塊。否則,受信任瀏覽器所瀏覽的任何惡意網頁皆可能將其網域名稱指向你的 nginx(DNS 重新綁定攻擊,DNS rebinding),進而促使 nginx 在轉發請求時附帶該金鑰。 +### 叢集 -`geo` 檢查的是連線至 nginx 的直接位址 `$remote_addr`。當客戶端透過另一層代理存取 nginx 時,請使用 [`realip` 模組](https://nginx.org/en/docs/http/ngx_http_realip_module.html) 將其替換為真實的客戶端位址。此模組僅會針對你在 `set_real_ip_from` 中列出的來源位址進行替換: +在 **Settings → Hosts** 中可以把已連結的主機加入叢集;本機是主節點(master),隨第一台主機一起加入。加入的主機必須上線,並提供一個用於叢集簽出的專案資料夾。它的 Git 專案依儲存庫 origin 繫結到叢集專案。之後叢集工作階段可以在任一成員上啟動。 -- **Cloudflare(Proxy DNS 模式):** 信任 `CF-Connecting-IP`,且僅限來自 Cloudflare 的連線。請列出 與 中的所有 IP 範圍,並保持更新。請僅在確實透過 Cloudflare 代理時使用此設定。 +成員使用主節點的 pi 設定執行工作階段。主節點建立一份帶版本的清單,包括: - ```nginx - set_real_ip_from 173.245.48.0/20; # ...每個 Cloudflare 範圍各佔一行 - real_ip_header CF-Connecting-IP; - ``` +- 來自其 pi agent 目錄:`settings.json`、`models.json`、`mcp.json`、`AGENTS.override.md`、`AGENTS.md`、`CLAUDE.md`、`SYSTEM.md`、`APPEND_SYSTEM.md`,以及目錄 `skills/`、`prompts/`、`themes/` 和 `extensions/`; +- `~/.agents/skills/`; +- **Settings → System** 中的代理環境變數。 - 同時拒絕既非來自 Cloudflare 亦非來自受信任範圍的連線。`$realip_remote_addr` 為在 `realip` 替換前的實際連線來源位址: +每個成員的常駐程式下載缺少的檔案,驗證其雜湊,並整體套用該版本,要麼全部套用,要麼完全不套用。主節點每 30 秒檢查一次,在成員上啟動工作階段時會先套用目前版本。被鏡像的目錄會變得與主節點的完全相同(排除 `node_modules` 和 `.git`)。限制:單一檔案 5 MiB,總計 50 MiB。 - ```nginx - geo $realip_remote_addr $ompweb_peer_allowed { - default 0; - 173.245.48.0/20 1; # ...所有 Cloudflare 範圍 - 10.0.0.0/16 1; - } - # 放在 server 區塊內 - if ($ompweb_peer_allowed = 0) { return 403; } - ``` +不鏡像的內容:憑證(`auth.json`、`mcp-auth.json`)、工作階段、快取、儲存庫內的設定,以及程式(MCP 伺服器的指令,或 `settings.json` 指定的套件,後者由 pi 在成員上自行安裝)。成員對 `settings.json` 中的以下鍵保留自己的值:`shellPath`、`shellCommandPrefix`、`npmCommand`、`selfUpdateCommand`、`externalEditor`、`sessionDir`、`httpProxy`、`extensions`、`skills`、`prompts`、`themes`、`deviceId`、`trackingId`、`lastChangelogVersion`、`extensionChangelogVersions` 和 `terminal`。 -- **Cloudflare Tunnel(`cloudflared`):** 通道會從 `cloudflared` 的位址連線至 nginx(當在同一台主機執行時為 `127.0.0.1`),因此請信任來自該處的 `CF-Connecting-IP`:`set_real_ip_from 127.0.0.1;` 以及 `real_ip_header CF-Connecting-IP;`。然而請注意,任何本機行程皆能自行傳送偽造的 `CF-Connecting-IP` 給 nginx 並宣稱其為受信任位址,且未攜帶該標頭的本機連線仍會保有 `127.0.0.1`,因此在 `$ompweb_trusted` 中列出 `127.0.0.1` 將會信任連線至 nginx 的所有本機行程。 -- **任何其他反向代理或負載平衡器:** +首次套用時,成員自己的設定會移到 `~/.pi/agent/tau/own-config/`;離開叢集時再放回去。一台主機同一時間只持有一台伺服器的設定。供應商登入永遠不會被鏡像:請在每個成員上分別登入(見下文)。 - ```nginx - set_real_ip_from <代理位址或網段>; - real_ip_header X-Forwarded-For; - real_ip_recursive on; - ``` +## 設定 - `real_ip_recursive on` 會從最右側開始解析 `X-Forwarded-For`,並略過所有列在 `set_real_ip_from` 中的中繼節點。客戶端自行附加的位址將會被直接忽略。 +tau 使用 pi 自己的檔案,並增加幾個自己的檔案: -## 本機開發 +| 路徑 | 內容 | +| --- | --- | +| `~/.pi/agent/settings.json` | pi 設定;**Settings** 可編輯預設思考層級、思考區塊顯示、啟用的模型、重試和壓縮(compaction)。 | +| `~/.pi/agent/models.json` | 自訂供應商和模型;在 **Settings → API Keys & Providers** 中編輯。 | +| `~/.pi/agent/auth.json` | pi 的供應商登入和 API 金鑰,由 pi 寫入。 | +| `~/.pi/agent/sessions/` | pi 工作階段檔案,tau 列出並讀取它們。 | +| `~/.pi/agent/tau-settings.json` | tau 伺服器設定:重新啟動後自動恢復、代理工具、GitHub 寫入和 Actions 權限、代理環境變數、上傳保留期限。 | +| `~/.pi/agent/projects.json` | 加入側邊欄或從側邊欄隱藏的工作區。 | +| `~/.pi/agent/tau/` | tau 狀態:主機登錄表(`hosts.json`)、常駐程式的連結(`host.json`)、叢集(`pools.json`)、登入簽章金鑰、通知、訊息寄件匣、上傳。 | +| `~/.pi/agent/web-service.env` | `tau-systemd` 寫入的服務設定(Windows 上為 `web-service.json`)。 | -```bash -git clone https://github.com/ompweb-dev/ompweb.git -cd ompweb -npm install -npx bun runner/scripts/use-omp-build.ts && (cd runner && npx bun install --frozen-lockfile) -npx bun runner/scripts/build-binary.ts # 為本機建置 ompweb 的 omp:runner/release/ompweb-omp-- -npm run dev -``` +所有路徑都遵循 `PI_CODING_AGENT_DIR`。 -開發伺服器將執行於 [http://127.0.0.1:30178](http://127.0.0.1:30178)。它會自動找到 `runner/release/` 中的 runner;`npm test` 與 `npm run build:binary` 也需要先準備好 runner。 -開發伺服器不會接管本機守護行程:只有正式環境的網頁伺服器會寫入守護行程的 `host.json`,因此「本機」在開發環境中會顯示為離線,而守護行程會保持與您已安裝的 ompweb 連結。 +**供應商登入依主機分別保存。** tau 自己從不讀取 `auth.json`。登入(OAuth 和 API 金鑰)在所選主機的常駐程式上、透過 tau 的隨附擴充功能(`lib/pi/tau-extension.ts` 中的 `/tau_auth` 指令)在 pi 內部完成;原始金鑰和權杖留在該主機的 pi 中。要在某台主機上登入,請在 **Settings → API Keys & Providers** 中選擇該主機。 -`npm run dev` 以 Bun 熱重載(hot reload)方式執行伺服器。`npm run build` 將瀏覽器端應用打包至 `dist/`,`npm start` 則在 30177 連接埠提供該產物(可用 `npm run smoke` 檢查結果)。`npm run dev:lan` 會將開發伺服器繫結至所有網路介面。`npm run build:binary` 會將適用於本機的[單一二進位檔](#單一二進位檔)建置到 `release/`(可使用 `-- --target bun-linux-arm64` 等參數為其他平台建置;`npm run smoke -- --binary release/ompweb-linux-x64/ompweb` 進行檢查)。 +**代理環境變數**(**Settings → System**)會加到之後啟動的每個 pi 程序中。會改變 pi 狀態位置或 tau 內部機制的名稱會被拒絕:`PATH`、`PATHEXT`、`COMSPEC`、`SYSTEMROOT`、`WINDIR`、`NODE_OPTIONS`、`HOME`、`USERPROFILE`、`HOMEDRIVE`、`HOMEPATH`、`XDG_DATA_HOME`、`XDG_CONFIG_HOME`、`PI_CODING_AGENT_DIR`、`PI_CODING_AGENT_SESSION_DIR`、`PORT`、`NODE_ENV`,以及所有以 `TAU_` 或 `_` 開頭的名稱。 -### 檢查與測試 +## 安全性說明 + +- **代理以你的使用者權限執行。** pi 的工具可以讀寫你的使用者能存取的任何檔案並執行指令。tau 不對其做沙箱隔離。任何能登入 tau 的人,都能讓代理在每台已連結的主機上這麼做。 +- **密碼閘門。** 設定 `TAU_PASSWORD_HASH` 後,除登入頁、靜態資源、Service Worker 和主機驗證的路徑外,所有頁面和 API 路由都需要工作階段 Cookie(或受信任代理的標頭)。沒有密碼雜湊時,tau 拒絕監聽非迴路位址。 +- **HTTPS。** tau 使用明文 HTTP。任何遠端存取都應放在 HTTPS(反向代理或 VPN)之後,以保護密碼、工作階段 Cookie 和主機權杖。Web Push 通知也需要 HTTPS。 +- **密鑰不會進入工作階段。** `TAU_PASSWORD`、`TAU_PASSWORD_HASH`、`TAU_TRUSTED_HEADER_SECRET`、`TAU_TRUSTED_HEADER_SHA256`、`TAU_STT_KEY`、`PORT` 和 `NODE_ENV` 會從每個 pi 程序和專案指令的環境中移除。 +- **主機權杖。** 伺服器只保存每個主機權杖的 SHA-256。主機常駐程式從標準輸入讀取權杖,並保存在權限為 `600` 的檔案中。被撤銷的權杖會立即被拒絕。 +- **瀏覽器中的檔案存取。** 檔案檢視器和檔案總管只提供允許的根目錄:你加入或開啟過的工作區、工作階段的工作目錄和經過驗證的 worktree,以及工作階段對話紀錄引用的檔案(唯讀)。即使在允許的根目錄內,pi 目錄中已知的憑證檔案(`models.json`、`.env` 檔案)也會被拒絕。這些限制針對瀏覽器,不針對代理。 +- **代理工具預設關閉。** 啟用後,任何工作階段都可以列出工作階段、啟動工作階段或傳送訊息給另一個工作階段,並使用伺服器 `gh` 登入的 GitHub 工具。除非開啟 **Allow agent GitHub writes without asking**,留言和討論串寫入會在工作階段中詢問;Actions 的 dispatch、cancel 和 rerun 預設各自詢問。在某台主機上啟動工作階段時,除非該主機允許代理啟動,否則會詢問。 + +## 開發 ```bash -npm run typecheck # 型別檢查(TypeScript) -npm run lint # ESLint 程式碼檢查 -npm test # 執行測試套件(bun test) +npm install +npm run dev # Bun hot reload at http://127.0.0.1:30188 +npm run build # bundle the browser app into dist/ +npm start # serve dist/ at http://127.0.0.1:30187 +npm run build:binary # single binary for this machine into release/ (-- --target bun-linux-arm64 for another) +npm run typecheck && npm run lint && npm test ``` -## 授權條款與致謝 +開發伺服器不會接管主機常駐程式:開發時「This machine」顯示為離線,常駐程式仍連結到你已安裝的 tau。 + +## 授權 -- 分支(fork)自 [agegr/pi-web](https://github.com/agegr/pi-web)(MIT 授權)並針對 [can1357/oh-my-pi](https://github.com/can1357/oh-my-pi) 進行調整。 -- 採用 [MIT 授權條款](./LICENSE)釋出。 +MIT,見 [LICENSE](./LICENSE)。tau 衍生自 [ompweb](https://github.com/ompweb-dev/ompweb),而 ompweb 衍生自 [agegr/pi-web](https://github.com/agegr/pi-web)。 diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index c7ee9319..dde692b5 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -7,8 +7,8 @@ import { requestOwner } from "@/lib/web-auth"; /** Stamp when the handler had the request and when it answered, so the browser * can split network time from server time. */ function timed(receivedAt: number, res: Response): Response { - res.headers.set("x-omp-received-at", String(receivedAt)); - res.headers.set("x-omp-replied-at", String(Date.now())); + res.headers.set("x-tau-received-at", String(receivedAt)); + res.headers.set("x-tau-replied-at", String(Date.now())); return res; } @@ -25,11 +25,7 @@ export async function POST( try { const body = await parseJsonWithinLimit(req, MAX_AGENT_COMMAND_REQUEST_BYTES); receivedAt = Date.now(); - // The per-chat advisor choice rides on the query string (never the RPC - // body, which is forwarded to omp verbatim) and only matters when this - // request spawns or replaces the session's omp process. - const advisor = new URL(req.url).searchParams.get("advisor") === "1"; - return timed(receivedAt, await runAgentCommand(id, body, advisor, requestOwner(req))); + return timed(receivedAt, await runAgentCommand(id, body, requestOwner(req))); } catch (error) { return timed(receivedAt ?? Date.now(), commandErrorResponse(error)); } diff --git a/app/api/agent/new/route.ts b/app/api/agent/new/route.ts index 8c9578c4..bcba59f2 100644 --- a/app/api/agent/new/route.ts +++ b/app/api/agent/new/route.ts @@ -1,10 +1,10 @@ import { apiErrorResponse, opErrorResponse, resolveHostOrError } from "@/lib/api-utils"; import { WebRpcError, startNewRpcSession, type AgentSessionWrapper } from "@/lib/rpc-manager"; -import { RpcCommandError } from "@/lib/omp/rpc-process"; +import { RpcCommandError } from "@/lib/pi/rpc-process"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { MAX_AGENT_COMMAND_REQUEST_BYTES } from "@/lib/image-attachments"; import { validateAgentImages } from "@/lib/image-attachments"; -import { PoolStartError, startPooledSession } from "@/lib/hosts/pool-starts"; +import { PoolStartError, requireProviderLogin, startPooledSession } from "@/lib/hosts/pool-starts"; import { HostOpError } from "@/lib/hosts/link-protocol"; import { isRecord } from "@/lib/type-guards"; @@ -42,7 +42,7 @@ export async function POST(req: Request) { if (pooled && (hostId !== undefined || requestedCwd !== undefined || typeof poolId !== "string" || typeof projectId !== "string" || typeof creationId !== "string" || (ref !== undefined && typeof ref !== "string"))) { return Response.json({ error: "Pool creation requires creationId, poolId and projectId, without hostId or cwd", code: "invalid_pool_target" }, { status: 400 }); } - const { provider, modelId, toolNames, thinkingLevel, advisor, name, ...promptCommand } = command as { provider?: string; modelId?: string; toolNames?: string[]; thinkingLevel?: string; advisor?: boolean; name?: string; [key: string]: unknown }; + const { provider, modelId, toolNames, thinkingLevel, name, ...promptCommand } = command as { provider?: string; modelId?: string; toolNames?: string[]; thinkingLevel?: string; name?: string; [key: string]: unknown }; // A session id has no meaning for a fresh spawn and must never reach the // child RPC: a stale or forged id would address the wrong session. delete promptCommand.sessionId; @@ -51,7 +51,6 @@ export async function POST(req: Request) { } if ([provider, modelId, thinkingLevel, name].some((value) => value !== undefined && (typeof value !== "string" || !value.trim())) || (toolNames !== undefined && (!Array.isArray(toolNames) || toolNames.some((value) => typeof value !== "string" || !value.trim()))) - || (advisor !== undefined && typeof advisor !== "boolean") || (promptCommand.message !== undefined && typeof promptCommand.message !== "string")) { return Response.json({ error: "Invalid session initialization fields", code: "invalid_creation_intent" }, { status: 400 }); } @@ -69,9 +68,9 @@ export async function POST(req: Request) { if (pooled) { // The hash is derived here from every effectful field, including unknown command options. - const intent = { ...promptCommand, provider, modelId, toolNames, thinkingLevel, advisor, name }; + const intent = { ...promptCommand, provider, modelId, toolNames, thinkingLevel, name }; const result = await startPooledSession({ creationId: creationId as string, poolId: poolId as string, projectId: projectId as string, ...(ref === undefined ? {} : { ref: ref as string }), intent }, async (host, prepared, id, onStarted) => { - const started = await startNewRpcSession(host, prepared.cwd, toolNames, advisor === true, preparing, id); + const started = await startNewRpcSession(host, prepared.cwd, toolNames, preparing, id); if (!started.ok) throw new HostOpError(started.status, started.code, started.error); const { session, realSessionId } = started.value; await onStarted(realSessionId); @@ -86,7 +85,8 @@ export async function POST(req: Request) { } const target = resolveHostOrError(hostId); if ("response" in target) return target.response; - const started = await startNewRpcSession(target.host, requestedCwd, toolNames, advisor === true, preparing); + await requireProviderLogin(target.host, provider); + const started = await startNewRpcSession(target.host, requestedCwd, toolNames, preparing); if (!started.ok) return opErrorResponse(started); const { session, realSessionId } = started.value; try { diff --git a/app/api/agents/route.ts b/app/api/agents/route.ts deleted file mode 100644 index c6b3e60e..00000000 --- a/app/api/agents/route.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { existsSync, statSync } from "fs"; -import { dirname, resolve } from "path"; -import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; -import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; -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"; - -// 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; - -type Scope = "all" | "user" | "project" | "bundled"; - -async function allowedCwd(value: unknown, required = true): Promise { - if (typeof value !== "string" || !value.trim()) { - if (required) throw new Error("cwd is required"); - return undefined; - } - const roots = await getAllowedFileRoots(); - try { - if (!statSync(value).isDirectory()) throw new Error("Workspace is not allowed"); - } catch { - throw new Error("Workspace is not allowed"); - } - if (!isExistingFilePathAllowed(value, roots)) throw new Error("Workspace is not allowed"); - return value; -} - -async function allowedProjectScope(value: unknown): Promise<{ cwd: string; dir: string }> { - const cwd = await allowedCwd(value); - if (!cwd) throw new Error("cwd is required"); - const dir = getProjectAgentsDir(cwd); - const roots = await getAllowedFileRoots(); - let probe = resolve(dir); - while (!existsSync(probe)) { - const parent = dirname(probe); - if (parent === probe) throw new Error("Workspace is not allowed"); - probe = parent; - } - if (!isExistingFilePathAllowed(probe, roots)) throw new Error("Workspace is not allowed"); - return { cwd, dir }; -} - -function parseScope(value: string | null | undefined, allowBundled = true): Scope { - const scope = value ?? "all"; - if (scope === "user" || scope === "project" || (allowBundled && scope === "bundled") || scope === "all") return scope as Scope; - throw new Error("scope must be all, user, project, or bundled"); -} - -export async function GET(request: Request) { - try { - const params = new URL(request.url).searchParams; - const scope = parseScope(params.get("scope")); - const cwdParam = params.get("cwd"); - if (scope === "project" && !cwdParam) throw new Error("cwd is required for project scope"); - // A workspace is needed to discover project agents (and for the default - // all-scope view), but user/bundled-only reads do not depend on it. - const project = scope === "project" || (scope === "all" && cwdParam) - ? await allowedProjectScope(cwdParam) - : undefined; - const cwd = project?.cwd; - const result = await discoverAgents(cwd); - const agents = scope === "all" ? result.agents : result.agents.filter((agent) => agent.scope === scope); - return Response.json({ - agents, - diagnostics: result.diagnostics, - userPath: getUserAgentsDir(), - projectPath: project?.dir ?? null, - bundledPath: result.bundledPath, - }); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - return Response.json({ error: message }, { status: /not allowed/i.test(message) ? 403 : 400 }); - } -} - -export async function POST(request: Request) { - try { - const body = await parseJsonWithinLimit<{ action?: unknown; cwd?: unknown; scope?: unknown; name?: unknown; previousName?: unknown; agent?: unknown }>(request, MAX_AGENT_REQUEST_BYTES); - if (body.action === "unpack") { - 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; - const cwd = project?.cwd; - const targetDir = project?.dir ?? resolveAgentsScope(cwd, body.scope); - 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; - const cwd = project?.cwd; - if (typeof body.name !== "string" || !body.name.trim()) throw new Error("name is required"); - if (!AGENT_NAME_RE.test(body.name.trim())) throw new Error(`name must match ${AGENT_NAME_RE.source}`); - if (body.previousName !== undefined && typeof body.previousName !== "string") throw new Error("previousName must be a string"); - 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); - const agent = readAgentFile(written.path); - return Response.json({ success: true, ...written, agent }); - } catch (error) { - 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 Response.json({ error: message }, { status: /not allowed/i.test(message) ? 403 : 400 }); - } -} - -export async function PUT(request: Request) { - try { - const body = await parseJsonWithinLimit<{ cwd?: unknown; scope?: unknown; name?: unknown; previousName?: unknown; agent?: unknown }>(request, MAX_AGENT_REQUEST_BYTES); - 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; - const cwd = project?.cwd; - if (typeof body.name !== "string" || !body.name.trim()) throw new Error("name is required"); - if (!AGENT_NAME_RE.test(body.name.trim())) throw new Error(`name must match ${AGENT_NAME_RE.source}`); - if (body.previousName !== undefined && typeof body.previousName !== "string") throw new Error("previousName must be a string"); - 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 Response.json({ success: true, ...written, agent: readAgentFile(written.path) }); - } catch (error) { - 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 Response.json({ error: message }, { status: /not allowed/i.test(message) ? 403 : 400 }); - } -} - -export async function DELETE(request: Request) { - try { - const body = await parseJsonWithinLimit<{ cwd?: unknown; scope?: unknown; name?: unknown }>(request, MAX_AGENT_REQUEST_BYTES); - 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; - const cwd = project?.cwd; - 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 Response.json({ success: true, ...deleteAgent(scopeDir, body.name.trim()) }); - } catch (error) { - 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 Response.json({ error: message }, { status }); - } -} diff --git a/app/api/auth/accounts/[provider]/route.ts b/app/api/auth/accounts/[provider]/route.ts index ba9a2173..41766098 100644 --- a/app/api/auth/accounts/[provider]/route.ts +++ b/app/api/auth/accounts/[provider]/route.ts @@ -1,54 +1,37 @@ -import { invalidateModelsCache } from "@/lib/models-cache"; -import { runUtilityCommand } from "@/lib/omp/rpc-utility"; +import { apiErrorResponse } from "@/lib/api-utils"; +import { afterAuthChange, hostIdOf, hostProviders, providerIdOr400 } from "@/lib/host-auth"; +import { authOp } from "@/lib/hosts/hub"; -/** Entry of omp's `get_logout_accounts` response. Labels never carry a raw key. */ -interface OmpProviderAccount { - credentialId: number; - label: string; - detail: string; - type: "api_key" | "oauth"; -} - -function isAccount(value: unknown): value is OmpProviderAccount { - if (typeof value !== "object" || value === null) return false; - const a = value as Record; - return Number.isInteger(a.credentialId) && typeof a.label === "string" && typeof a.detail === "string" - && (a.type === "api_key" || a.type === "oauth"); -} +type Params = { params: Promise<{ provider: string }> }; -// omp's `active` flag is relative to the utility process's own throwaway -// session, not to any chat, so it is deliberately not passed on. -/** Stored credentials omp holds for one provider. */ -export async function GET(_req: Request, { params }: { params: Promise<{ provider: string }> }) { +/** The credential pi stores for one provider on `?hostId=`: at most one (auth.json keeps one per provider), id 0. */ +export async function GET(req: Request, { params }: Params) { const { provider } = await params; + const invalid = providerIdOr400(provider); + if (invalid) return invalid; try { - const { accounts } = await runUtilityCommand<{ accounts?: unknown }>( - { type: "get_logout_accounts", providerId: provider }, - 30_000, - ); - const list = Array.isArray(accounts) ? accounts.filter(isAccount) : []; - return Response.json({ - supported: true, - accounts: list.map(({ credentialId, label, detail, type }) => ({ credentialId, label, detail, type })), - }); + const entry = (await hostProviders(hostIdOf(req))).find((p) => p.id === provider); + const accounts = entry?.stored ? [{ credentialId: 0, label: entry.name, detail: entry.stored === "oauth" ? "OAuth" : "API key", type: entry.stored }] : []; + return Response.json({ supported: true, accounts }); } catch (error) { - return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); + return apiErrorResponse(error); } } -/** Remove one stored credential (`?credentialId=`); omp picks the next account. */ -export async function DELETE(req: Request, { params }: { params: Promise<{ provider: string }> }) { - const raw = new URL(req.url).searchParams.get("credentialId") ?? ""; - const credentialId = Number(raw); - if (!/^\d+$/.test(raw) || !Number.isSafeInteger(credentialId)) { - return Response.json({ error: "credentialId must be an integer" }, { status: 400 }); +/** Remove the stored credential (`?credentialId=0`). */ +export async function DELETE(req: Request, { params }: Params) { + if (new URL(req.url).searchParams.get("credentialId") !== "0") { + return Response.json({ error: "credentialId must be 0", code: "invalid_request" }, { status: 400 }); } const { provider } = await params; + const invalid = providerIdOr400(provider); + if (invalid) return invalid; + const hostId = hostIdOf(req); try { - await runUtilityCommand({ type: "logout", providerId: provider, credentialId }, 60_000); - invalidateModelsCache(); + await authOp(hostId, { action: "logout", provider }, 60_000); + afterAuthChange(hostId); return Response.json({ ok: true }); } catch (error) { - return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); + return apiErrorResponse(error); } } diff --git a/app/api/auth/all-providers/route.ts b/app/api/auth/all-providers/route.ts index 166e399f..f5f016de 100644 --- a/app/api/auth/all-providers/route.ts +++ b/app/api/auth/all-providers/route.ts @@ -1,63 +1,17 @@ -import { readModelsConfig } from "@/lib/omp/models-config"; -import { type OmpLoginProvider, type OmpModel, runUtilityCommand } from "@/lib/omp/rpc-utility"; +import { hostIdOf, hostProviders, listErrorResponse } from "@/lib/host-auth"; -// 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) -// via get_available_models — so this endpoint lists configured providers only. -// Unconfigured API-key providers cannot be set up from the web UI (see the -// api-key route), so they are intentionally absent. -export async function GET() { +// API-key providers on `?hostId=` (default this machine): those pi can store a key for, and those already configured +// some other way (an environment variable). Providers logged in by account show in the subscription list instead; +// models.json providers are managed in the editor tree. +export async function GET(req: Request) { try { - const modelsResponse = await runUtilityCommand<{ models?: unknown }>( - { type: "get_available_models" }, - 120_000, - ); - const models = Array.isArray(modelsResponse.models) - ? modelsResponse.models.filter((model): model is OmpModel => ( - typeof model === "object" && model !== null - && typeof (model as OmpModel).provider === "string" - )) - : []; - const loginResponse = await runUtilityCommand<{ providers?: unknown }>( - { type: "get_login_providers" }, - 30_000, - ); - const loginProviders = Array.isArray(loginResponse.providers) - ? loginResponse.providers.filter((provider): provider is OmpLoginProvider => ( - typeof provider === "object" && provider !== null - && typeof (provider as OmpLoginProvider).id === "string" - && typeof (provider as OmpLoginProvider).name === "string" - && typeof (provider as OmpLoginProvider).authenticated === "boolean" - )) - : []; - - // OAuth-authenticated providers show in the subscription section instead; - // custom models.yml providers are managed in the editor tree. - const oauthAuthenticated = new Set(loginProviders.filter((p) => p.authenticated).map((p) => p.id)); - const loginNames = new Map(loginProviders.map((p) => [p.id, p.name])); - const customProviders = new Set(Object.keys(readModelsConfig().providers ?? {})); - - const counts = new Map(); - for (const model of models) { - counts.set(model.provider, (counts.get(model.provider) ?? 0) + 1); - } - - const result: { id: string; displayName: string; configured: boolean; modelCount: number }[] = []; - for (const [id, modelCount] of counts) { - if (oauthAuthenticated.has(id) || customProviders.has(id)) continue; - result.push({ - id, - displayName: loginNames.get(id) ?? id, - configured: true, - modelCount, - }); - } - result.sort((a, b) => a.displayName.localeCompare(b.displayName)); - + const providers = await hostProviders(hostIdOf(req)); + const result = providers + .filter((p) => p.stored !== "oauth" && !p.custom && (p.apiKeyLogin || p.configured)) + .map((p) => ({ id: p.id, displayName: p.name, configured: p.configured, modelCount: p.models, apiKeyLogin: p.apiKeyLogin, stored: p.stored })) + .sort((a, b) => a.displayName.localeCompare(b.displayName)); return Response.json({ providers: result }); } catch (error) { - const message = error instanceof Error ? error.message : String(error); - return Response.json({ providers: [], error: message }, { status: 500 }); + return listErrorResponse(error); } } diff --git a/app/api/auth/api-key/[provider]/route.ts b/app/api/auth/api-key/[provider]/route.ts index f786d56e..d971f102 100644 --- a/app/api/auth/api-key/[provider]/route.ts +++ b/app/api/auth/api-key/[provider]/route.ts @@ -1,57 +1,52 @@ import { apiErrorResponse } from "@/lib/api-utils"; -import { type OmpLoginProvider, type OmpModel, runUtilityCommand } from "@/lib/omp/rpc-utility"; +import { afterAuthChange, hostIdOf, hostProviders, providerIdOr400 } from "@/lib/host-auth"; +import { authOp } from "@/lib/hosts/hub"; +import { isRecord } from "@/lib/type-guards"; type Params = { params: Promise<{ provider: string }> }; -// omp stores API keys in its encrypted SQLite credential store (agent.db), -// which omp-web must never write from Node, and the omp RPC login command only -// bridges browser-based flows (providers that prompt for a key before opening -// a URL are rejected by omp's RPC mode). Keys therefore cannot be stored or -// removed from the web UI. -const API_KEY_WRITE_GUIDANCE = - "tau cannot manage stored API keys directly. Run `pi` in a terminal and use /login (or /logout), " + - "set the provider's environment variable (e.g. OPENAI_API_KEY), or configure an apiKey on a " + - "custom provider in ~/.pi/agent/models.json."; - -// GET /api/auth/api-key/[provider] — returns auth status (never returns the actual key) -export async function GET(_req: Request, { params }: Params) { +// GET /api/auth/api-key/[provider]?hostId= — auth status on that host (never the key) +export async function GET(req: Request, { params }: Params) { const { provider } = await params; + const invalid = providerIdOr400(provider); + if (invalid) return invalid; try { - const { models } = await runUtilityCommand<{ models: OmpModel[] }>( - { type: "get_available_models" }, - 120_000, - ); - const { providers: loginProviders } = await runUtilityCommand<{ providers: OmpLoginProvider[] }>( - { type: "get_login_providers" }, - 30_000, - ); - const loginProvider = loginProviders.find((p) => p.id === provider); - const modelCount = models.filter((m) => m.provider === provider).length; - return Response.json({ - provider, - displayName: loginProvider?.name ?? provider, - configured: modelCount > 0 || loginProvider?.authenticated === true, - models: modelCount, - }); + const entry = (await hostProviders(hostIdOf(req))).find((p) => p.id === provider); + return Response.json({ provider, displayName: entry?.name ?? provider, configured: entry?.configured === true, models: entry?.models ?? 0, stored: entry?.stored ?? null }); } catch (error) { return apiErrorResponse(error); } } -// POST /api/auth/api-key/[provider] — not supported against omp's credential store -export async function POST(_req: Request, { params }: Params) { +// POST /api/auth/api-key/[provider]?hostId= { key } — store the key in that host's pi auth.json +export async function POST(req: Request, { params }: Params) { const { provider } = await params; - 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 }, - ); + const invalid = providerIdOr400(provider); + if (invalid) return invalid; + const body: unknown = await req.json().catch(() => null); + const key = isRecord(body) && typeof body.key === "string" ? body.key.trim() : ""; + if (!key) return Response.json({ error: "key is required", code: "invalid_request" }, { status: 400 }); + const hostId = hostIdOf(req); + try { + await authOp(hostId, { action: "setApiKey", provider, key }, 60_000); + afterAuthChange(hostId); + return Response.json({ ok: true }); + } catch (error) { + return apiErrorResponse(error); + } } -// DELETE /api/auth/api-key/[provider] — not supported against omp's credential store -export async function DELETE(_req: Request, { params }: Params) { +// DELETE /api/auth/api-key/[provider]?hostId= — remove the stored credential (environment variables and models.json stay) +export async function DELETE(req: Request, { params }: Params) { const { provider } = await params; - 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 }, - ); + const invalid = providerIdOr400(provider); + if (invalid) return invalid; + const hostId = hostIdOf(req); + try { + await authOp(hostId, { action: "logout", provider }, 60_000); + afterAuthChange(hostId); + return Response.json({ ok: true }); + } catch (error) { + return apiErrorResponse(error); + } } diff --git a/app/api/auth/login/[provider]/route.ts b/app/api/auth/login/[provider]/route.ts index 920ce265..65535c24 100644 --- a/app/api/auth/login/[provider]/route.ts +++ b/app/api/auth/login/[provider]/route.ts @@ -1,48 +1,43 @@ -import { homedir } from "os"; -import { invalidateModelsCache } from "@/lib/models-cache"; -import { enableProvider } from "@/lib/omp/model-roles"; -import { RpcProcess, type RpcFrame } from "@/lib/omp/rpc-process"; -import { disposeUtilityRpc } from "@/lib/omp/rpc-utility"; +import { afterAuthChange, hostIdOf, providerIdOr400 } from "@/lib/host-auth"; +import { authOp } from "@/lib/hosts/hub"; +import { isRecord } from "@/lib/type-guards"; /** - * Interactive login over a dedicated headless runner. The runner drives the - * flow with login frames (runner/src/commands/agents.ts): `login_open_url` - * carries the OAuth URL, `login_input` asks for the pasted code/redirect URL, - * `login_progress` reports progress. The SSE stream keeps pi-web's event names - * (auth, prompt_request, progress, success, error, cancelled) so the client - * flow is unchanged; the POST handler feeds the user's pasted value back as a - * `login_input_response` frame. + * Interactive account login on `?hostId=` (default this machine), run by that host's daemon in a pi of its own + * (lib/hosts/daemon-auth.ts). The SSE stream keeps pi-web's event names (auth, device_code, prompt_request, + * select_request, progress, success, error, cancelled) so the client flow is unchanged; the POST handler feeds the + * user's pasted code or chosen option back to the daemon. */ -const LOGIN_EXTRA_ARGS = ["--no-session", "--no-extensions", "--no-skills", "--no-lsp"]; -const READY_TIMEOUT_MS = 60_000; -const LOGIN_TIMEOUT_MS = 15 * 60_000; const HEARTBEAT_MS = 30_000; +/** A long poll waits up to 15 s on the daemon; this leaves room for the link. */ +const POLL_TIMEOUT_MS = 25_000; interface PendingLogin { provider: string; - submit: (value: string) => void; + hostId: string; + loginId: string; } -// Registry survives dev-server hot reload; the SSE stream registers its token, -// the POST handler resolves it. +// Registry survives dev-server hot reload; the SSE stream registers its token, the POST handler resolves it. declare global { - var __ompLoginRegistry: Map | undefined; + var __tauLoginRegistry: Map | undefined; } function getLoginRegistry(): Map { - if (!globalThis.__ompLoginRegistry) globalThis.__ompLoginRegistry = new Map(); - return globalThis.__ompLoginRegistry; + if (!globalThis.__tauLoginRegistry) globalThis.__tauLoginRegistry = new Map(); + return globalThis.__tauLoginRegistry; } -// POST /api/auth/login/[provider] — frontend sends redirect URL or auth code +// POST /api/auth/login/[provider] — frontend sends redirect URL, auth code or chosen option export async function POST( req: Request, { params }: { params: Promise<{ provider: string }> } ) { const { provider } = await params; - const { token, code } = (await req.json()) as { token?: string; code?: string }; - + const body: unknown = await req.json().catch(() => null); + const token = isRecord(body) && typeof body.token === "string" ? body.token : ""; + const code = isRecord(body) && typeof body.code === "string" ? body.code : ""; if (!token || !code) { return Response.json({ error: "token and code required", code: "login_token_code_required" }, { status: 400 }); } @@ -50,25 +45,28 @@ export async function POST( if (!pending) { return Response.json({ error: "No pending login for token", code: "login_no_pending" }, { status: 404 }); } - // Exact provider association: the registry records the provider a token was - // created for. A prefix check on the token alone is unsafe because provider - // ids may share prefixes (e.g. "openai" vs "openai-codex"), which would let - // a token for one provider be submitted against another provider's route. + // Exact provider association: provider ids may share prefixes ("openai" vs "openai-codex"). if (pending.provider !== provider) { return Response.json({ error: "Token does not match provider", code: "login_token_mismatch" }, { status: 400 }); } - - pending.submit(code); + try { + await authOp(pending.hostId, { action: "loginInput", loginId: pending.loginId, value: code }); + } catch (error) { + return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 502 }); + } return Response.json({ ok: true, provider }); } -// GET /api/auth/login/[provider] — SSE stream for the login flow +// GET /api/auth/login/[provider]?hostId= — SSE stream for the login flow export async function GET( req: Request, { params, disableIdleTimeout }: { params: Promise<{ provider: string }>; disableIdleTimeout: () => void } ) { - disableIdleTimeout(); const { provider } = await params; + const invalid = providerIdOr400(provider); + if (invalid) return invalid; + disableIdleTimeout(); + const hostId = hostIdOf(req); const token = `${provider}-${Date.now()}-${Math.random().toString(36).slice(2)}`; const registry = getLoginRegistry(); const encoder = new TextEncoder(); @@ -84,8 +82,7 @@ export async function GET( closed = true; } }; - // OAuth flows sit idle while the user is in the browser; keep the SSE - // connection alive past reverse-proxy idle timeouts. + // OAuth flows sit idle while the user is in the browser; keep the SSE connection alive past proxy idle timeouts. const heartbeat = setInterval(() => { if (closed) return; try { @@ -95,85 +92,39 @@ export async function GET( } }, HEARTBEAT_MS); - // The user may paste the code before the runner's input request arrives - // (the auth event shows the paste box immediately) — buffer one value. - let pendingInputId: number | null = null; - let bufferedValue: string | null = null; - - let proc: RpcProcess | null = null; - const handleFrame = (frame: RpcFrame) => { - if (frame.type === "login_open_url") { - send({ - type: "auth", - url: String(frame.url ?? ""), - instructions: typeof frame.instructions === "string" ? frame.instructions : null, - token, - }); - } else if (frame.type === "login_input" && typeof frame.id === "number") { - if (bufferedValue !== null) { - const value = bufferedValue; - bufferedValue = null; - proc?.sendFrame({ type: "login_input_response", id: frame.id, value }); - } else { - pendingInputId = frame.id; - send({ - type: "prompt_request", - message: typeof frame.prompt === "string" ? frame.prompt : "Enter the authorization code", - placeholder: typeof frame.placeholder === "string" ? frame.placeholder : null, - token, - }); - } - } else if (frame.type === "login_progress") { - if (typeof frame.message === "string") send({ type: "progress", message: frame.message }); - } + let loginId: string | null = null; + const cancel = () => { + if (loginId) void authOp(hostId, { action: "loginCancel", loginId }).catch(() => {}); }; - + req.signal.addEventListener("abort", cancel); try { - proc = new RpcProcess({ cwd: homedir(), extraArgs: LOGIN_EXTRA_ARGS, onFrame: handleFrame }); - } catch (error) { - send({ type: "error", message: error instanceof Error ? error.message : String(error) }); - clearInterval(heartbeat); - closed = true; - try { controller.close(); } catch {} - return; - } - const child = proc; - - registry.set(token, { - provider, - submit: (value: string) => { - if (pendingInputId !== null) { - const id = pendingInputId; - pendingInputId = null; - child.sendFrame({ type: "login_input_response", id, value }); - } else { - bufferedValue = value; + const started = await authOp(hostId, { action: "loginStart", provider }); + if (!isRecord(started) || typeof started.loginId !== "string") throw new Error("The host sent an invalid login"); + loginId = started.loginId; + if (req.signal.aborted) cancel(); + registry.set(token, { provider, hostId, loginId }); + let after = 0; + let outcome: string | null = null; + while (!outcome && !req.signal.aborted) { + const polled = await authOp(hostId, { action: "loginPoll", loginId, after }, POLL_TIMEOUT_MS); + if (!isRecord(polled) || !Array.isArray(polled.events)) throw new Error("The host sent an invalid login step"); + after += polled.events.length; + for (const event of polled.events) { + if (!isRecord(event) || typeof event.type !== "string") continue; + if (event.type === "success" || event.type === "error" || event.type === "cancelled") outcome = event.type; + // The browser answers a prompt with this stream's token. + send(event.type === "auth" || event.type === "prompt_request" || event.type === "select_request" ? { ...event, token } : event); } - }, - }); - - const cleanup = () => { - registry.delete(token); - clearInterval(heartbeat); - void child.dispose(); - }; - req.signal.addEventListener("abort", cleanup); - - try { - await child.waitReady(READY_TIMEOUT_MS); - await child.sendCommand({ type: "login", providerId: provider }, LOGIN_TIMEOUT_MS); - enableProvider(provider); - invalidateModelsCache(); - disposeUtilityRpc(); - send({ type: "success" }); - } catch (error) { - if (req.signal.aborted) { - send({ type: "cancelled" }); - } else { - send({ type: "error", message: error instanceof Error ? error.message : String(error) }); } + if (outcome === "success") afterAuthChange(hostId); + if (!outcome) send({ type: "cancelled" }); + } catch (error) { + if (req.signal.aborted) send({ type: "cancelled" }); + else send({ type: "error", message: error instanceof Error ? error.message : String(error) }); } finally { - cleanup(); + req.signal.removeEventListener("abort", cancel); + registry.delete(token); + clearInterval(heartbeat); closed = true; try { controller.close(); } catch {} } diff --git a/app/api/auth/providers/route.ts b/app/api/auth/providers/route.ts index 501844d6..8f0baf33 100644 --- a/app/api/auth/providers/route.ts +++ b/app/api/auth/providers/route.ts @@ -1,33 +1,13 @@ -import { type OmpLoginProvider, runUtilityCommand } from "@/lib/omp/rpc-utility"; +import { hostIdOf, hostProviders, listErrorResponse } from "@/lib/host-auth"; -// 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. -export async function GET() { +// Providers with an account (OAuth) login on `?hostId=` (default this machine), as that host's pi lists them. +export async function GET(req: Request) { try { - const response = await runUtilityCommand<{ providers?: unknown }>( - { type: "get_login_providers" }, - 30_000, - ); - const providers = Array.isArray(response.providers) - ? response.providers.filter((provider): provider is OmpLoginProvider => ( - typeof provider === "object" && provider !== null - && typeof (provider as OmpLoginProvider).id === "string" - && typeof (provider as OmpLoginProvider).name === "string" - && typeof (provider as OmpLoginProvider).authenticated === "boolean" - )) - : []; - const result = providers - .filter((p) => p.available !== false) - .map((p) => ({ - id: p.id, - name: p.name, - usesCallbackServer: false, - loggedIn: p.authenticated, - })); - return Response.json({ providers: result }); + const providers = await hostProviders(hostIdOf(req)); + return Response.json({ + providers: providers.filter((p) => p.oauth).map((p) => ({ id: p.id, name: p.name, usesCallbackServer: false, loggedIn: p.stored === "oauth" })), + }); } catch (error) { - const message = error instanceof Error ? error.message : String(error); - return Response.json({ providers: [], error: message }, { status: 500 }); + return listErrorResponse(error); } } diff --git a/app/api/events/link/route.ts b/app/api/events/link/route.ts deleted file mode 100644 index 4f8166fe..00000000 --- a/app/api/events/link/route.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { handleBrowserLinkUpgrade, type BrowserLinkData } from "@/lib/browser-link"; - -// GET /api/events/link — the browser link (lib/browser-link.ts); undefined once upgraded (server/app.ts). Gated like -// every API route: the password gate and origin check run before the upgrade, which binds the socket to its web session. -export function GET(req: Request, { upgrade }: { upgrade: (data: BrowserLinkData) => boolean }) { - return handleBrowserLinkUpgrade(req, upgrade); -} diff --git a/app/api/hosts/[id]/cluster/route.ts b/app/api/hosts/[id]/cluster/route.ts index fb7efe06..003fd6ef 100644 --- a/app/api/hosts/[id]/cluster/route.ts +++ b/app/api/hosts/[id]/cluster/route.ts @@ -1,15 +1,14 @@ import { randomUUID } from "node:crypto"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { comparableProjectPath } from "@/lib/comparable-path"; -import { CLUSTER_ID, CLUSTER_LABEL, CLUSTER_PROJECTS_DIR, ClusterError, clusterJoinBlock, isClusterMember, joinCluster, leaveCluster, MIN_SHARED_CREDENTIALS_OMP, type HostProjectFacts } from "@/lib/hosts/cluster"; +import { CLUSTER_ID, CLUSTER_LABEL, CLUSTER_PROJECTS_DIR, ClusterError, clusterJoinBlock, isClusterMember, joinCluster, leaveCluster, type HostProjectFacts } from "@/lib/hosts/cluster"; import type { Host } from "@/lib/hosts/host"; -import { clusterConfigOp, getHost, getHostOmpVersion, listHosts, masterConfigVersion, notifyHostsChange } from "@/lib/hosts/hub"; +import { clusterConfigOp, getHost, listHosts, masterConfigVersion, notifyHostsChange } from "@/lib/hosts/hub"; import { HostOpError } from "@/lib/hosts/link-protocol"; import { loadPools, poolProjectBindings, savePools, validatePools, type HostPool, type PoolMember, type PoolProject } from "@/lib/hosts/pools"; -import { LOCAL_HOST_ID, loadHosts } from "@/lib/hosts/registry"; +import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; import type { OpResult } from "@/lib/hosts/session-ops"; import { hostSessions } from "@/lib/hosts/session-index"; -import { abortBrokerRequests } from "@/lib/omp/auth-broker"; import { mergeProjects } from "@/lib/project-registry"; import { isApiRequestOriginAllowed, shouldCheckApiRequestOrigin } from "@/lib/request-security"; import { isRecord } from "@/lib/type-guards"; @@ -21,7 +20,7 @@ const MAX_ORIGIN_PATHS = 500; const MAX_ORIGIN_PATH_LENGTH = 4096; const noStore = { "cache-control": "no-store" }; const fail = (error: string, code: string, status: number) => Response.json({ error, code }, { status, headers: noStore }); -const storageFailure = () => fail("The pool registry (omp-web/pools.json) cannot be read or written; fix it before changing the cluster", "pool_storage_unavailable", 503); +const storageFailure = () => fail("The pool registry (tau/pools.json) cannot be read or written; fix it before changing the cluster", "pool_storage_unavailable", 503); function errorResponse(error: unknown): Response { if (error instanceof HostOpError) return fail(error.message, error.code, error.status); if (error instanceof ClusterError) return fail(error.message, error.code, 409); @@ -48,13 +47,7 @@ function valueOf(result: OpResult): T { } function requireReady(host: Host): void { - const block = clusterJoinBlock({ status: host.status(), ompVersion: getHostOmpVersion(host.id), supports: (operation) => host.supportsWorkspaceOp(operation) }); - if (block === null) return; - if (block === "omp-old") throw new HostOpError(409, "host_omp_too_old", `Update omp on ${host.label} to ${MIN_SHARED_CREDENTIALS_OMP} or newer first`); - if (block !== "upgrade") throw new HostOpError(409, "host_offline", `${host.label} is offline`); - throw host.id === LOCAL_HOST_ID - ? new HostOpError(409, "host_restart_required", "Restart this machine's ompweb host daemon to join the cluster") - : new HostOpError(409, "host_upgrade_required", `Update ompweb on ${host.label} to join the cluster`); + if (clusterJoinBlock({ status: host.status() }) !== null) throw new HostOpError(409, "host_offline", `${host.label} is offline`); } /** The host's projects in its own order (mergeProjects: the order the user sees), then its hidden registry entries, which move too. */ @@ -161,7 +154,6 @@ export async function DELETE(request: Request, { params }: Context) { } pools = leaveCluster(pools, id); savePools(pools); - if (loadHosts().find((record) => record.id === id)?.shareCredentials !== true) abortBrokerRequests(id); notifyHostsChange(); // After the save, so no apply follows it (spec K6). A host that cannot take it now (offline or timed out) gets it // from the sync once it reports holding this server's configuration. diff --git a/app/api/hosts/[id]/updates/route.ts b/app/api/hosts/[id]/updates/route.ts index 0d6f7429..df1f4081 100644 --- a/app/api/hosts/[id]/updates/route.ts +++ b/app/api/hosts/[id]/updates/route.ts @@ -28,7 +28,7 @@ export async function POST(request: Request, { params }: Context) { if (request.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase() !== "application/json") return fail("Content-Type must be application/json", "unsupported_media_type", 415); try { const body = await parseJsonWithinLimit(request, 4096); - if (!isRecord(body) || Object.keys(body).some((key) => !["target", "version", "force"].includes(key)) || body.target !== "ompweb" + if (!isRecord(body) || Object.keys(body).some((key) => !["target", "version", "force"].includes(key)) || body.target !== "tau" || (body.force !== undefined && typeof body.force !== "boolean") || typeof body.version !== "string" || body.version.length > 100 || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(body.version)) { return fail("target and a release version are required", "invalid_host_update", 400); diff --git a/app/api/hosts/broker/[...path]/route.ts b/app/api/hosts/broker/[...path]/route.ts deleted file mode 100644 index 7ad99e90..00000000 --- a/app/api/hosts/broker/[...path]/route.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { readBodyWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; -import { sharesCredentials } from "@/lib/hosts/cluster"; -import { loadPools } from "@/lib/hosts/pools"; -import { hostFromBearer } from "@/lib/hosts/host-bearer"; -import { LOCAL_HOST_ID, type HostRecord } from "@/lib/hosts/registry"; -import { AuthBrokerUnavailableError, brokerFetch } from "@/lib/omp/auth-broker"; - -// A linked host's daemon forwards omp's auth-broker calls here (lib/omp/auth-broker.ts runs the broker). proxy.ts does -// not gate the /v1/ paths: the host's bearer token is checked before anything else is read. - -const MAX_BODY_BYTES = 1024 * 1024; -const noStore = { "cache-control": "no-store" }; -const fail = (error: string, status: number) => Response.json({ error }, { status, headers: noStore }); - -// Anything not listed is 404, including POST /v1/credential: a host cannot add or replace a credential. -const ALLOWED: readonly (readonly [method: string, path: RegExp])[] = [ - ["GET", /^\/v1\/(?:healthz|snapshot|snapshot\/stream|credentials\/disabled|usage|usage\/history|usage\/clients)$/], - ["POST", /^\/v1\/credential\/\d+\/(?:refresh|disable|block)$/], - ["DELETE", /^\/v1\/credential\/\d+\/blocks?$/], - ["POST", /^\/v1\/usage\/(?:observed|stale)$/], -]; -const REQUEST_HEADERS = ["content-type", "accept", "if-none-match", "omp-auth-broker-capabilities"]; -const RESPONSE_HEADERS = ["content-type", "etag", "cache-control", "vary"]; -// A path the allow-list has not vetted reaches the log only as plain `/v1/` text. -const PLAIN_PATH = /^\/v1\/[A-Za-z0-9/_-]*$/; - -/** Never a token, a query, a body or an error message: a broker failure names only its class. */ -function log(hostId: string, method: string, path: string, status: number, reason?: string) { - console.log(`[omp-web] broker ${hostId} ${method} ${path} ${status}${reason ? ` ${reason}` : ""}`); -} - -function only(source: Headers, names: readonly string[]): Headers { - const picked = new Headers(); - for (const name of names) { - const value = source.get(name); - if (value !== null) picked.set(name, value); - } - return picked; -} - -/** The sharing host (own flag or cluster member) the bearer token names, or the refusal to answer with (a 403 and a pool 503 are logged; a 401 has no host to name). */ -function admit(request: Request, path: string): HostRecord | Response { - const host = hostFromBearer(request); - if (host instanceof Response) return host; - // `local` is refused by id: a hand-edited hosts.json can give its record the flag. - let shares: boolean; - try { - shares = host.id !== LOCAL_HOST_ID && sharesCredentials(host, loadPools()); - } catch { - log(host.id, request.method, PLAIN_PATH.test(path) ? path : "-", 503, "pools_unreadable"); - return fail("The host pool configuration cannot be read", 503); - } - if (!shares) { - log(host.id, request.method, PLAIN_PATH.test(path) ? path : "-", 403); - return fail("Credential sharing is off for this host", 403); - } - return host; -} - -async function forward(request: Request, { params, disableIdleTimeout }: { params: Promise<{ path: string[] }>; disableIdleTimeout: () => void }) { - const path = `/${(await params).path.join("/")}`; - const first = admit(request, path); - if (first instanceof Response) return first; - if (!ALLOWED.some(([method, allowed]) => method === request.method && allowed.test(path))) { - log(first.id, request.method, PLAIN_PATH.test(path) ? path : "-", 404); - return fail("Not found", 404); - } - - // Public to proxy.ts, so Bun's idle timeout is still on: the snapshot stream and the long poll stay open without traffic. - disableIdleTimeout(); - let body: ArrayBuffer | undefined; - if (request.method !== "GET") { - try { - body = (await readBodyWithinLimit(request, MAX_BODY_BYTES)).buffer; - } catch (error) { - if (error instanceof RequestBodyTooLargeError) return fail("Request body is too large", 413); - throw error; - } - } - - // The body can take as long as the sender likes, and no request of this host is abortable (abortBrokerRequests) until - // brokerFetch registers it: a host revoked or switched off meanwhile must not get through. No await from here to that call. - const host = admit(request, path); - if (host instanceof Response) return host; - - let upstream: Response; - try { - upstream = await brokerFetch(host.id, path + new URL(request.url).search, { - method: request.method, - headers: only(request.headers, REQUEST_HEADERS), - body, - signal: request.signal, - }); - } catch (error) { - const unavailable = error instanceof AuthBrokerUnavailableError; - const reason = unavailable ? (error.reason ?? "fetch_failed") - // The host disconnected, or abortBrokerRequests cut it off. - : request.signal.aborted || (error instanceof Error && error.name === "AbortError") ? "aborted" : "fetch_failed"; - log(host.id, request.method, path, unavailable ? 503 : 502, reason); - return unavailable ? fail("The auth broker is unavailable", 503) : fail("The auth broker request failed", 502); - } - log(host.id, request.method, path, upstream.status); - return new Response(upstream.body, { status: upstream.status, headers: only(upstream.headers, RESPONSE_HEADERS) }); -} - -export const GET = forward; -export const POST = forward; -export const DELETE = forward; diff --git a/app/api/hosts/link/route.ts b/app/api/hosts/link/route.ts index 09a94a79..bf426b56 100644 --- a/app/api/hosts/link/route.ts +++ b/app/api/hosts/link/route.ts @@ -1,14 +1,9 @@ -import { handleLinkUpgrade, handleOutdatedLinkPost, type LinkSocketData } from "@/lib/hosts/hub"; +import { handleLinkUpgrade, type LinkSocketData } from "@/lib/hosts/hub"; -// The `ompweb host` daemon's link (lib/hosts/hub.ts). proxy.ts does not run +// The `tau 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 it upgrades. // GET /api/hosts/link — the link's WebSocket; undefined once upgraded (server/app.ts). export function GET(req: Request, { upgrade }: { upgrade: (data: LinkSocketData) => boolean }) { return handleLinkUpgrade(req, upgrade); } - -// POST /api/hosts/link — only refuses a daemon from before the WebSocket (its hello POST) with 426. -export function POST(req: Request) { - return handleOutdatedLinkPost(req); -} diff --git a/app/api/hosts/maintenance/route.ts b/app/api/hosts/maintenance/route.ts index b3174f4b..03649f4f 100644 --- a/app/api/hosts/maintenance/route.ts +++ b/app/api/hosts/maintenance/route.ts @@ -4,5 +4,5 @@ import packageJson from "@/package.json"; /** API v1 discovery and its independent host-token-authenticated WebSocket. */ export function GET(request: Request, { upgrade }: { upgrade: (data: MaintenanceSocketData) => boolean }) { - return handleMaintenanceUpgrade(request, upgrade, { protocolVersion: LINK_PROTOCOL_VERSION, ompwebVersion: packageJson.version }); + return handleMaintenanceUpgrade(request, upgrade, { protocolVersion: LINK_PROTOCOL_VERSION, tauVersion: packageJson.version }); } diff --git a/app/api/hosts/route.ts b/app/api/hosts/route.ts index 64ad1d07..0ca81729 100644 --- a/app/api/hosts/route.ts +++ b/app/api/hosts/route.ts @@ -1,15 +1,14 @@ -import { isClusterMember, leaveCluster, sharesCredentials } from "@/lib/hosts/cluster"; +import { isClusterMember, leaveCluster } from "@/lib/hosts/cluster"; import { closeHostLink, hostsSnapshot, listHosts, notifyHostsChange } from "@/lib/hosts/hub"; import { loadPools, savePools, type HostPool } from "@/lib/hosts/pools"; import { createHost, HostRegistryUnreadableError, readHosts, revokeHost, UnknownHostError, updateHost, type HostRecord } from "@/lib/hosts/registry"; -import { abortBrokerRequests } from "@/lib/omp/auth-broker"; import { isRecord } from "@/lib/type-guards"; const MAX_LABEL_LENGTH = 100; const noStore = { "cache-control": "no-store" }; const fail = (error: string, status: number) => Response.json({ error }, { status, headers: noStore }); -const poolStorageFailure = () => fail("The pool registry (omp-web/pools.json) cannot be read or written; fix it before changing pools", 503); +const poolStorageFailure = () => fail("The pool registry (tau/pools.json) cannot be read or written; fix it before changing pools", 503); function hasOnlyKeys(value: unknown, keys: readonly string[]): value is Record { return isRecord(value) && Object.keys(value).every((key) => keys.includes(key)); @@ -17,21 +16,12 @@ function hasOnlyKeys(value: unknown, keys: readonly string[]): value is Record | null> { try { const body: unknown = await req.json(); @@ -92,14 +82,14 @@ export async function PUT(req: Request) { } for (const project of pool.projects) { if (!hasOnlyKeys(project, ["id", "name", "origin", "defaultRef", "clonePaths", "addedAt", "hidden", "alias", "sortOrder", "pinOrder", "launchConfig"]) - || (project.launchConfig !== undefined && !hasOnlyKeys(project.launchConfig, ["profile", "advisor", "extraArgs"]))) { + || (project.launchConfig !== undefined && !hasOnlyKeys(project.launchConfig, ["extraArgs"]))) { return fail("Invalid pool project configuration", 400); } } } - let before: HostPool[]; + // A damaged registry is never replaced: fix it first. try { - before = loadPools(); + loadPools(); } catch { return poolStorageFailure(); } @@ -112,10 +102,6 @@ export async function PUT(req: Request) { return fail("Invalid pool configuration", 400); } notifyHostsChange(); - // Leaving the first pool, or no longer being in it, can end a host's sharing: cut off what it already has open. - for (const host of hosts) { - if (sharesCredentials(host, before) && !sharesCredentials(host, after)) abortBrokerRequests(host.id); - } return Response.json({ pools: after }, { headers: noStore }); } @@ -130,7 +116,7 @@ export async function POST(req: Request) { { host: listHosts().find((h) => h.id === host.id), token, - command: `ompweb host login --url ${requestOrigin(req)}`, + command: `tau host login --url ${requestOrigin(req)}`, }, { headers: noStore }, ); @@ -145,17 +131,14 @@ export async function PATCH(req: Request) { if (!body || typeof body.id !== "string" || !body.id) return fail("id is required", 400); const isLocal = body.id === "local"; if (isLocal && body.allowAgentStart !== undefined) return fail("This machine's agent-start setting cannot be changed", 400); - if (isLocal && body.shareCredentials !== undefined) return fail("This machine's credential sharing cannot be changed", 400); // An empty name resets this machine to its default name. const label = isLocal && typeof body.label === "string" && !body.label.trim() ? "" : parseLabel(body.label); if (label === null) return fail(`label must be a non-empty string of at most ${MAX_LABEL_LENGTH} characters`, 400); - const { allowAgentStart, shareCredentials } = body; + const { allowAgentStart } = body; if (allowAgentStart !== undefined && typeof allowAgentStart !== "boolean") return fail("allowAgentStart must be a boolean", 400); - if (shareCredentials !== undefined && typeof shareCredentials !== "boolean") return fail("shareCredentials must be a boolean", 400); - if (label === undefined && allowAgentStart === undefined && shareCredentials === undefined) return fail("Nothing to update", 400); + if (label === undefined && allowAgentStart === undefined) return fail("Nothing to update", 400); try { - const updated = updateHost(body.id, { label, allowAgentStart, shareCredentials }); - if (shareCredentials === false && !stillShares(updated)) abortBrokerRequests(body.id); + updateHost(body.id, { label, allowAgentStart }); notifyHostsChange(); return Response.json({ host: hostsSnapshot().hosts.find((h) => h.id === body.id) }, { headers: noStore }); } catch (error) { @@ -207,7 +190,6 @@ export async function DELETE(req: Request) { // Registry first: with the record gone a daemon that redials gets 401 instead of reconnecting. if (!revokeHost(id)) return fail("Unknown host", 404); closeHostLink(id); - abortBrokerRequests(id); notifyHostsChange(); return Response.json({ ok: true }, { headers: noStore }); } catch (error) { diff --git a/app/api/manifest/route.ts b/app/api/manifest/route.ts index 59bfbc42..ce3e68f2 100644 --- a/app/api/manifest/route.ts +++ b/app/api/manifest/route.ts @@ -6,10 +6,10 @@ import { parseThemeColor } from "@/lib/manifest-theme"; // 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, +// tau 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.env.OMP_WEB_PACKAGE_DIR ?? process.cwd(), "public", filename)).toString("base64")}`; + `data:image/png;base64,${readFileSync(join(process.env.TAU_PACKAGE_DIR ?? process.cwd(), "public", filename)).toString("base64")}`; const manifest = { description: "Web UI for the pi coding agent", diff --git a/app/api/mcp/route.ts b/app/api/mcp/route.ts index a3454c35..643fbd36 100644 --- a/app/api/mcp/route.ts +++ b/app/api/mcp/route.ts @@ -1,12 +1,7 @@ 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"; -import { getHost } from "@/lib/hosts/hub"; -import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; -import { sessionSpawnTarget } from "@/lib/hosts/session-index"; -import { RpcCommandError } from "@/lib/omp/rpc-process"; +import { deleteMcpServer, readDiscoveredMcpServers, readMcpConfig, readUserMcpConfig, type McpLiveServer, validateMcpServer, writeMcpServer } from "@/lib/pi/mcp-config"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; -import { redactMcpServer } from "@/lib/omp/mcp-config"; +import { redactMcpServer } from "@/lib/pi/mcp-config"; const MAX_MCP_REQUEST_BYTES = 1024 * 1024; @@ -15,26 +10,6 @@ function mcpErrorResponse(error: unknown) { 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 - * errors (spawn failures, stderr tails) must not reach the browser. */ -function sanitizeMcpLiveError(error: unknown): string { - if (error instanceof WebRpcError || error instanceof RpcCommandError) { - return error.message; - } - console.error("[api/mcp] live server list failed:", error); - return "Could not load live MCP server states"; -} - -function mergeMcpServers(primary: McpLiveServer[], secondary: McpLiveServer[]): McpLiveServer[] { - const result: McpLiveServer[] = primary.map((server) => ({ ...server, sourcePath: secondary.find((other) => other.name === server.name && other.source === server.source)?.sourcePath })); - const seen = new Set(primary.map((server) => `${server.source}:${server.name}`)); - for (const server of secondary) { - const key = `${server.source}:${server.name}`; - if (!seen.has(key)) { result.push(server); seen.add(key); } - } - return result; -} - async function allowedCwd(cwd: unknown): Promise { if (typeof cwd !== "string" || !cwd.trim()) throw new Error("cwd is required"); const allowedRoots = await getAllowedFileRoots(); @@ -51,16 +26,14 @@ export async function GET(request: Request) { const user = readUserMcpConfig(); const inventory: McpLiveServer[] = [ ...user.servers.map(({ name, config }) => ({ name, source: "User level", sourcePath: user.path, status: config.enabled === false ? "disabled" as const : "configured" as const, type: typeof config.type === "string" ? config.type : typeof config.url === "string" ? "http" : "stdio" })), - ...user.disabledServers.map((name) => ({ name, source: "Disabled", sourcePath: user.path, status: "disabled" as const })), ...Object.entries(file?.config.mcpServers ?? {}).map(([name, config]) => ({ name, source: "Project level", sourcePath: file?.path, status: config.enabled === false ? "disabled" as const : "configured" as const, type: typeof config.type === "string" ? config.type : typeof config.url === "string" ? "http" : "stdio" })), - ...readDiscoveredMcpServers(cwd ?? undefined, user.disabledServers), + ...readDiscoveredMcpServers(cwd ?? undefined), ]; // The user-level config may carry bearer tokens/API keys in `headers` and // credentials in `env`. The UI only renders name/status/type/enabled — // never serialize the raw user-level server configs to the client. const safeUser = { path: user.path, - disabledServers: user.disabledServers, error: user.error, servers: user.servers.map(({ name, config }) => { const type = typeof config.type === "string" && config.type !== "stdio" ? config.type @@ -79,37 +52,7 @@ export async function GET(request: Request) { }; }), }; - const sessionId = params.get("sessionId"); - const includeLive = params.get("live") !== "0"; - // Advisor opinion for a fresh spawn only (same ?advisor=1 convention as - // /api/agent/[id]): an alive child is reused as-is below, never replaced — - // listing servers must stay side-effect-free. - const advisor = params.get("advisor") === "1"; - // `attach=1`: live status from a process already running, never one started here. A cluster session on another - // member is read where it runs (spec K7); its file is not this machine's to start. - const attachOnly = params.get("attach") === "1"; - let liveServers: ReturnType | undefined; - let liveError: string | undefined; - if (includeLive && sessionId) { - try { - let session = getRpcSession(sessionId); - if (!session?.isAlive()) { - if (attachOnly) throw new WebRpcError("The session is not running", "session_not_running"); - // MCP settings are this machine's only. - const host = getHost(LOCAL_HOST_ID); - const target = await sessionSpawnTarget(sessionId, host); - if (!target) throw new Error("Session not found"); - // Fresh spawn only (an alive child is reused above): apply the - // caller's advisor opinion so a racing prompt doesn't inherit a - // wrong-flag child for its whole turn. - ({ session } = await startRpcSession(sessionId, target.sessionFile, target.cwd, undefined, advisor, target.recordedCwd, undefined, host)); - } - liveServers = mergeMcpServers(parseMcpListOutput(await session.getMcpList()), inventory); - } catch (error) { - liveError = sanitizeMcpLiveError(error); - } - } - 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 }); + 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 }); } catch (error) { return mcpErrorResponse(error); } @@ -147,27 +90,3 @@ export async function DELETE(request: Request) { return mcpErrorResponse(error); } } - -/** Native local commands only: never a model prompt or shell command. */ -export async function PATCH(request: Request) { - try { - const body = await parseJsonWithinLimit<{ sessionId?: unknown; action?: unknown; name?: unknown }>(request, MAX_MCP_REQUEST_BYTES); - if (typeof body.sessionId !== "string" || !body.sessionId) throw new Error("Select a session first"); - if (body.action !== "enable" && body.action !== "disable" && body.action !== "reload") throw new Error("Invalid MCP action"); - if (body.action !== "reload" && (typeof body.name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(body.name))) throw new Error("Invalid MCP server name"); - // Load the selected session through the same validated path as inventory. - // Do not create a different session or apply the caller's arbitrary cwd. - let session = getRpcSession(body.sessionId); - if (!session?.isAlive()) { - const host = getHost(LOCAL_HOST_ID); - const target = await sessionSpawnTarget(body.sessionId, host); - 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 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 Response.json({ success: true }); - } catch (error) { - 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 8ef48935..ae1b9345 100644 --- a/app/api/media/[hash]/route.ts +++ b/app/api/media/[hash]/route.ts @@ -31,14 +31,8 @@ export async function GET(req: Request, { params }: { params: Promise<{ hash: st const cachedBytes = cached ? await readIfPresent(cached) : null; if (cachedBytes) return image(cachedBytes, "image/webp"); - // The sweep can delete our copy between lookup and read once omp's blob is - // complete; one more lookup then finds the blob. - let bytes: Buffer | null = null; - for (let attempt = 0; attempt < 2 && !bytes; attempt++) { - const file = mediaFilePath(hash); - if (!file) break; - bytes = await readIfPresent(file); - } + const file = mediaFilePath(hash); + let bytes = file ? await readIfPresent(file) : null; // A remote session's image: ask the linked hosts (only bytes that hash to `hash` come back). const remote = bytes ? null : await fetchMediaFromHosts(hash); if (remote) bytes = Buffer.from(remote.buffer, remote.byteOffset, remote.byteLength); diff --git a/app/api/model-roles/route.ts b/app/api/model-roles/route.ts deleted file mode 100644 index 4bfcbb63..00000000 --- a/app/api/model-roles/route.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { invalidateModelsCache } from "@/lib/models-cache"; -import { readModelRoles, writeModelRoles } from "@/lib/omp/model-roles"; - -export function GET() { - try { - return Response.json(readModelRoles()); - } catch (error) { - return Response.json({ error: String(error) }, { status: 400 }); - } -} - -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 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 Response.json({ success: true, roles }); - } catch (error) { - 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 a4448731..696f3016 100644 --- a/app/api/models-config/catalog/route.ts +++ b/app/api/models-config/catalog/route.ts @@ -16,7 +16,7 @@ interface CatalogCache { } declare global { - var __ompWebModelsDevCatalogCache: CatalogCache | undefined; + var __tauModelsDevCatalogCache: CatalogCache | undefined; } async function fetchCatalog(): Promise { @@ -32,9 +32,9 @@ async function fetchCatalog(): Promise { } async function loadCatalog(): Promise { - let cache = globalThis.__ompWebModelsDevCatalogCache; + let cache = globalThis.__tauModelsDevCatalogCache; if (!cache) { - cache = globalThis.__ompWebModelsDevCatalogCache = { entries: [], expiresAt: 0 }; + cache = globalThis.__tauModelsDevCatalogCache = { entries: [], expiresAt: 0 }; } if (cache.entries.length > 0 && cache.expiresAt > Date.now()) return cache.entries; if (!cache.inFlight) { diff --git a/app/api/models-config/route.ts b/app/api/models-config/route.ts index a9ecb4b3..01f2c633 100644 --- a/app/api/models-config/route.ts +++ b/app/api/models-config/route.ts @@ -1,13 +1,13 @@ import { apiErrorResponse } from "@/lib/api-utils"; import { invalidateModelsCache } from "@/lib/models-cache"; -import { disposeUtilityRpc } from "@/lib/omp/rpc-utility"; +import { disposeUtilityRpc } from "@/lib/pi/rpc-utility"; import { ModelsConfigParseError, readModelsConfigFile, validateModelsConfig, writeModelsConfig, type ModelsFileConfig, -} from "@/lib/omp/models-config"; +} from "@/lib/pi/models-config"; export async function GET() { const file = readModelsConfigFile(); @@ -40,7 +40,7 @@ export async function PUT(req: Request) { } catch (error) { if (error instanceof ModelsConfigParseError) { return Response.json( - { error: `${error.message} — fix it by hand; omp-web will not overwrite it`, code: "models_config_unparseable" }, + { error: `${error.message} — fix it by hand; tau will not overwrite it`, code: "models_config_unparseable" }, { status: 409 }, ); } diff --git a/app/api/models-config/test/route.ts b/app/api/models-config/test/route.ts index e576c109..c8dbbc47 100644 --- a/app/api/models-config/test/route.ts +++ b/app/api/models-config/test/route.ts @@ -6,12 +6,12 @@ import { type ProviderConfig, serializeModelsConfig, validateModelsConfig, -} from "@/lib/omp/models-config"; -import { type OmpModel, runIsolatedUtilityCommand } from "@/lib/omp/rpc-utility"; +} from "@/lib/pi/models-config"; +import { type PiModel, runIsolatedUtilityCommand } from "@/lib/pi/rpc-utility"; import { isRecord } from "@/lib/type-guards"; // Registry resolution (spawn + model discovery), not a completion round-trip: -// omp-web cannot send test prompts without going through a full agent session. +// tau cannot send test prompts without going through a full agent session. const TEST_TIMEOUT_MS = 60_000; function errorMessage(error: unknown): string { @@ -45,18 +45,16 @@ export async function POST(req: Request) { return Response.json({ ok: false, error: errorMessage(error) }); } - // Isolated throwaway agent dir: the spawned omp sees only this candidate - // config (no stored credentials, no models.db cache) and never touches - // ~/.omp. Profile/XDG overrides are cleared so the redirect always wins - // (the omp child still honors profiles even though omp-web ignores them). - tempDir = mkdtempSync(join(tmpdir(), "omp-web-model-test-")); - writeFileSync(join(tempDir, "models.yml"), serializeModelsConfig(config), "utf8"); + // Isolated throwaway agent dir: the spawned pi sees only this candidate + // config (no stored credentials) and never touches ~/.pi. + tempDir = mkdtempSync(join(tmpdir(), "tau-model-test-")); + writeFileSync(join(tempDir, "models.json"), serializeModelsConfig(config), "utf8"); const startedAt = Date.now(); - const { models } = await runIsolatedUtilityCommand<{ models: OmpModel[] }>( + const { models } = await runIsolatedUtilityCommand<{ models: PiModel[] }>( { type: "get_available_models" }, { - env: { PI_CODING_AGENT_DIR: tempDir, OMP_PROFILE: "", PI_PROFILE: "", XDG_DATA_HOME: "" }, + env: { PI_CODING_AGENT_DIR: tempDir }, timeoutMs: TEST_TIMEOUT_MS, signal: req.signal, }, diff --git a/app/api/models/route.ts b/app/api/models/route.ts index da870d50..202cb516 100644 --- a/app/api/models/route.ts +++ b/app/api/models/route.ts @@ -1,17 +1,16 @@ import { statSync } from "fs"; import { invalidateModelsCache, loadModelsWithCache, withModelRuntimeError, withSafeModelLoadFailure, type ModelsData } from "@/lib/models-cache"; -import { disposeUtilityRpc, runUtilityCommand, type OmpModel } from "@/lib/omp/rpc-utility"; -import { getModelsConfigPath } from "@/lib/omp/paths"; -import { readDisabledProviders } from "@/lib/omp/model-roles"; -import { readAnthropicSlowMode } from "@/lib/omp/settings-config"; +import { disposeUtilityRpc, runUtilityCommand, runUtilityExtension, type PiModel } from "@/lib/pi/rpc-utility"; +import { getModelsConfigPath } from "@/lib/pi/paths"; +import { thinkingLevelsForMeta } from "@/lib/thinking-levels"; -// The omp model registry (auth + models.yml) is global, not per-cwd, so one +// The pi model registry (auth + models.json) 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. const MODELS_CACHE_KEY = "global"; declare global { - var __ompModelsConfigFingerprint: string | undefined; + var __tauModelsConfigFingerprint: string | undefined; } function refreshModelsIfConfigChanged(): void { @@ -25,8 +24,8 @@ function refreshModelsIfConfigChanged(): void { // its later creation. } - const previous = globalThis.__ompModelsConfigFingerprint; - globalThis.__ompModelsConfigFingerprint = fingerprint; + const previous = globalThis.__tauModelsConfigFingerprint; + globalThis.__tauModelsConfigFingerprint = fingerprint; if (previous !== undefined && previous !== fingerprint) { // The utility process reads models.yml once at startup. External edits // therefore need the same invalidation as the web editor's PUT route. @@ -46,25 +45,6 @@ function compareModelEntries( || modelNameCollator.compare(a.id, b.id); } -// "off" is always a valid selector; the concrete efforts come from the model's -// baked thinking metadata (omp: getSupportedEfforts = reasoning ? efforts : []). -function thinkingLevelsFor(model: OmpModel): string[] { - if (!model.reasoning) return ["off"]; - return ["off", ...(model.thinking?.efforts ?? [])]; -} - -// OMP's /fast maps to a priority service tier. These are the provider families -// OMP currently resolves for that control (ModelControls.setFastMode). -function supportsFastMode(model: OmpModel): boolean { - return model.provider === "anthropic" || model.provider === "openai" || model.provider === "google"; -} - -// Copy of omp's AgentSession#slowModeTarget for the composer's Slow toggle -// before omp runs: Claude low priority on `anthropic`, else the flex tier of -// the OpenAI/Google service-tier families. Live get_state wins once omp runs. -// ponytail: provider-only; OpenRouter's openai/google ids need omp's model identity. -const SLOW_MODE_PROVIDERS: Record = { anthropic: true, openai: true, "openai-codex": true, google: true, "google-vertex": true }; - async function loadModels(): Promise { const availableResponse = await runUtilityCommand<{ models?: unknown }>( { type: "get_available_models" }, @@ -72,10 +52,10 @@ async function loadModels(): Promise { ); const available = Array.isArray(availableResponse.models) ? availableResponse.models - .filter((model): model is OmpModel => ( + .filter((model): model is PiModel => ( typeof model === "object" && model !== null - && typeof (model as OmpModel).id === "string" - && typeof (model as OmpModel).provider === "string" + && typeof (model as PiModel).id === "string" + && typeof (model as PiModel).provider === "string" )) .map((model) => ({ ...model, @@ -85,32 +65,28 @@ async function loadModels(): Promise { const nameMap = new Map(); const thinkingLevels: Record = {}; + const thinkingLevelMaps: Record> = {}; const modelList = available - .map((m) => ({ id: m.id, name: m.name, provider: m.provider, thinkingLevels: thinkingLevelsFor(m), supportsFastMode: supportsFastMode(m), supportsSlowMode: SLOW_MODE_PROVIDERS[m.provider] === true, contextWindow: m.contextWindow ?? undefined, maxTokens: m.maxTokens ?? undefined })) + .map((m) => ({ id: m.id, name: m.name, provider: m.provider, thinkingLevels: thinkingLevelsForMeta(m), contextWindow: m.contextWindow ?? undefined, maxTokens: m.maxTokens ?? undefined })) .sort(compareModelEntries); - const loginResponse = await runUtilityCommand<{ providers?: unknown }>( - { type: "get_login_providers" }, - 30_000, - ); - const loginProviders = Array.isArray(loginResponse.providers) - ? loginResponse.providers.filter((provider): provider is { id: string; name: string; authenticated: boolean } => ( + // tau's companion extension reports pi's providers (lib/hosts/daemon-auth.ts reads the same list per host). + const loginResponse = await runUtilityExtension<{ providers?: unknown }>("tau_auth", { action: "providers" }, 30_000); + const connectedProviders = (Array.isArray(loginResponse.providers) ? loginResponse.providers : []) + .filter((provider): provider is { id: string; name: string; configured: boolean } => ( typeof provider === "object" && provider !== null && typeof (provider as { id?: unknown }).id === "string" && typeof (provider as { name?: unknown }).name === "string" - && typeof (provider as { authenticated?: unknown }).authenticated === "boolean" + && (provider as { configured?: unknown }).configured === true )) - : []; - const disabledProviders = readDisabledProviders(); - const connectedProviders = loginProviders - .filter((provider) => provider.authenticated) - .map((provider) => ({ id: provider.id, name: provider.name, disabled: disabledProviders.has(provider.id) })); + .map((provider) => ({ id: provider.id, name: provider.name })); for (const m of available) { const key = `${m.provider}:${m.id}`; nameMap.set(key, m.name); - thinkingLevels[key] = thinkingLevelsFor(m); + thinkingLevels[key] = thinkingLevelsForMeta(m); + if (m.thinkingLevelMap) thinkingLevelMaps[key] = m.thinkingLevelMap; } - // omp resolves the default model at session start; a --no-session utility + // pi resolves the default model at session start; a --no-session utility // process reports it via get_state. let defaultModel: { provider: string; modelId: string } | null = null; try { @@ -128,7 +104,7 @@ async function loadModels(): Promise { } return withModelRuntimeError( - { models: Object.fromEntries(nameMap), modelList, defaultModel, thinkingLevels, connectedProviders }, + { models: Object.fromEntries(nameMap), modelList, defaultModel, thinkingLevels, thinkingLevelMaps, connectedProviders }, undefined, ); } @@ -142,11 +118,9 @@ const EMPTY_MODELS: ModelsData = { export async function GET() { refreshModelsIfConfigChanged(); - // Outside the cache: `/slow` on a Claude model rewrites config.yml. - const anthropicSlowMode = readAnthropicSlowMode(); try { - return Response.json({ ...await loadModelsWithCache(MODELS_CACHE_KEY, () => loadModels()), anthropicSlowMode }); + return Response.json(await loadModelsWithCache(MODELS_CACHE_KEY, () => loadModels())); } catch { - return Response.json({ ...withSafeModelLoadFailure(EMPTY_MODELS), anthropicSlowMode }); + return Response.json(withSafeModelLoadFailure(EMPTY_MODELS)); } } diff --git a/app/api/omp-update/route.ts b/app/api/omp-update/route.ts deleted file mode 100644 index 055518e8..00000000 --- a/app/api/omp-update/route.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { isApiRequestOriginAllowed, shouldCheckApiRequestOrigin } from "@/lib/request-security"; -import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; -import { restartAllRpcSessions } from "@/lib/rpc-manager"; - -/** Restarts every running omp session. omp itself updates with ompweb: its release ships the runner. */ -export async function POST(request: Request) { - if (shouldCheckApiRequestOrigin(request) && !isApiRequestOriginAllowed(request)) { - 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 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) || body.action !== "restart" || Object.keys(body).length !== 1) { - return Response.json({ error: "action must be restart", code: "invalid_action" }, { status: 400 }); - } - const sessionsRestarted = await restartAllRpcSessions(); - return Response.json({ success: true, sessionsRestarted }); - } catch (error) { - if (error instanceof RequestBodyTooLargeError) return Response.json({ error: error.message, code: "body_too_large" }, { status: 413 }); - if (error instanceof SyntaxError) return Response.json({ error: "Request body must be valid JSON", code: "invalid_json" }, { status: 400 }); - return Response.json({ error: "The OMP sessions could not be restarted", code: "restart_failed" }, { status: 500 }); - } -} diff --git a/app/api/omp-version/route.ts b/app/api/omp-version/route.ts deleted file mode 100644 index 976e8051..00000000 --- a/app/api/omp-version/route.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { getOmpVersion } from "@/lib/omp/omp-cli"; - -/** 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 Response.json({ version }); -} diff --git a/app/api/omp-settings/route.ts b/app/api/pi-settings/route.ts similarity index 76% rename from app/api/omp-settings/route.ts rename to app/api/pi-settings/route.ts index 60973924..7df51dd9 100644 --- a/app/api/omp-settings/route.ts +++ b/app/api/pi-settings/route.ts @@ -1,6 +1,6 @@ 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 { disposeUtilityRpc, runUtilityCommand, type PiModel } from "@/lib/pi/rpc-utility"; +import { readNativeSettings, writeNativeSettings, type NativeSettings } from "@/lib/pi/settings-config"; import { assertNoAmbiguousModelScopes } from "@/lib/model-scope"; export function GET() { @@ -19,14 +19,14 @@ export async function PUT(request: Request) { } if (body.settings.enabledModels !== undefined) { // The utility process is best-effort here: settings remain editable when - // omp is unavailable, but an available catalog rejects ambiguous bare IDs. + // pi is unavailable, but an available catalog rejects ambiguous bare IDs. try { const response = await runUtilityCommand<{ models?: unknown }>({ type: "get_available_models" }, 120_000); if (Array.isArray(response.models)) { - const models = response.models.filter((model): model is OmpModel => ( + const models = response.models.filter((model): model is PiModel => ( typeof model === "object" && model !== null - && typeof (model as OmpModel).id === "string" - && typeof (model as OmpModel).provider === "string" + && typeof (model as PiModel).id === "string" + && typeof (model as PiModel).provider === "string" )); assertNoAmbiguousModelScopes(body.settings.enabledModels, models); } @@ -35,7 +35,7 @@ export async function PUT(request: Request) { } } writeNativeSettings(body.settings); - if (body.settings.enabledModels !== undefined || body.settings.disabledProviders !== undefined || body.settings.modelProviderOrder !== undefined) { + if (body.settings.enabledModels !== undefined) { invalidateModelsCache(); disposeUtilityRpc(); } diff --git a/app/api/pi-version/route.ts b/app/api/pi-version/route.ts new file mode 100644 index 00000000..534c3bfe --- /dev/null +++ b/app/api/pi-version/route.ts @@ -0,0 +1,8 @@ +import { getPiVersion } from "@/lib/pi/pi-cli"; + +/** Runtime probe of the installed pi binary ("1.5.2"), separate from the + * build-time tau version — the two can legitimately drift. */ +export async function GET() { + const version = await getPiVersion(); + return Response.json({ version }); +} diff --git a/app/api/plugins/route.ts b/app/api/plugins/route.ts index c869eaa6..4a305a09 100644 --- a/app/api/plugins/route.ts +++ b/app/api/plugins/route.ts @@ -1,9 +1,9 @@ import { execFile } from "child_process"; import { existsSync, promises as fs } from "fs"; -import { basename, extname, join } from "path"; -import { ANSI_RE, parseJsonLoose, parsePiListOutput } from "@/lib/omp/plugins-cli"; -import { OMP_NOT_FOUND, resolveOmpBin } from "@/lib/omp/omp-cli"; -import { ensureAgentDir } from "@/lib/omp/paths"; +import { basename, join } from "path"; +import { ANSI_RE, parsePiListOutput } from "@/lib/pi/plugins-cli"; +import { PI_NOT_FOUND, resolvePiBin } from "@/lib/pi/pi-cli"; +import { ensureAgentDir } from "@/lib/pi/paths"; import { createChildProcessEnvironment } from "@/lib/project-command-env"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; import type { @@ -15,62 +15,22 @@ import type { PluginsResponse, } from "@/lib/api-types"; -// 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. +// Package management is delegated to the user's pi binary (`pi install/remove/update/list`); tau never embeds its SDK. +// `pi list` prints text only (parsePiListOutput) and has no enable/disable command. -type PluginAction = "install" | "remove" | "update" | "disable" | "enable"; - -interface OmpPluginManifest { - name?: string; - version?: string; - description?: string; - tools?: string; - hooks?: string; - extensions?: string[]; - commands?: string[]; - features?: Record; -} - -interface OmpNpmPlugin { - name: string; - version: string; - path: string; - manifest?: OmpPluginManifest; - enabledFeatures?: string[] | null; - enabled: boolean; -} - -interface OmpMarketplaceEntry { - scope?: "user" | "project"; - installPath?: string; - version?: string; - enabled?: boolean; -} - -interface OmpMarketplacePlugin { - id: string; - scope?: "user" | "project"; - entries?: OmpMarketplaceEntry[]; - shadowedBy?: string; -} - -interface OmpPluginList { - npm?: OmpNpmPlugin[]; - marketplace?: OmpMarketplacePlugin[]; -} +type PluginAction = "install" | "remove" | "update"; function emptyCounts(): PluginResourceCounts { return { extensions: 0, skills: 0, prompts: 0, themes: 0 }; } -function runOmp( +function runPi( args: string[], opts: { cwd?: string; timeout?: number } = {}, ): Promise<{ stdout: string; stderr: string }> { - const bin = resolveOmpBin(); + const bin = resolvePiBin(); if (!bin) { - return Promise.reject(new Error(OMP_NOT_FOUND)); + return Promise.reject(new Error(PI_NOT_FOUND)); } return new Promise((resolve, reject) => { execFile( @@ -86,7 +46,7 @@ function runOmp( (error, stdout, stderr) => { if (error) { const detail = (stderr || stdout || error.message).replace(ANSI_RE, "").trim(); - reject(new Error(detail.slice(-600) || `omp ${args.join(" ")} failed`)); + reject(new Error(detail.slice(-600) || `pi ${args.join(" ")} failed`)); } else { resolve({ stdout, stderr }); } @@ -95,8 +55,7 @@ function runOmp( }); } -/** Best-effort scan of a plugin's skills/ directory (omp discovers plugin-root - * skills the same way) so the UI can show a resource count. */ +/** Best-effort scan of a package's skills/ directory so the UI can show a resource count. */ async function scanPluginSkills(pluginPath: string): Promise { const skillsDir = join(pluginPath, "skills"); let entries; @@ -122,85 +81,7 @@ async function scanPluginSkills(pluginPath: string): Promise { - const file = basename(rel); - const ext = extname(file); - resources.push({ - kind, - name: ext ? file.slice(0, -ext.length) : file, - path: join(pluginPath, rel), - relativePath: rel, - }); - }; - for (const rel of manifest?.extensions ?? []) push("extension", rel); - if (manifest?.tools) push("extension", manifest.tools); - if (manifest?.hooks) push("extension", manifest.hooks); - // omp "commands" (slash commands) are the closest analog of pi prompts. - for (const rel of manifest?.commands ?? []) push("prompt", rel); - return resources; -} - -async function toNpmPackageInfo(plugin: OmpNpmPlugin): Promise { - const resources = [ - ...manifestResources(plugin.path, plugin.manifest), - ...(await scanPluginSkills(plugin.path)), - ]; - const counts = emptyCounts(); - for (const resource of resources) { - if (resource.kind === "extension") counts.extensions += 1; - else if (resource.kind === "skill") counts.skills += 1; - else if (resource.kind === "prompt") counts.prompts += 1; - else counts.themes += 1; - } - const installed = Boolean(plugin.path && existsSync(plugin.path)); - const resourceCount = counts.extensions + counts.skills + counts.prompts + counts.themes; - return { - source: plugin.name, - scope: "global", - filtered: Array.isArray(plugin.enabledFeatures), - disabled: plugin.enabled === false, - installedPath: plugin.path || undefined, - packageName: plugin.name, - version: plugin.version || plugin.manifest?.version, - configuredVersion: undefined, - counts, - resources, - status: plugin.enabled === false - ? "disabled" - : resourceCount > 0 - ? "loaded" - : installed - ? "installed" - : "missing", - }; -} - -async function toMarketplacePackageInfo(plugin: OmpMarketplacePlugin): Promise { - const entry = plugin.entries?.[0]; - const installedPath = entry?.installPath; - const installed = Boolean(installedPath && existsSync(installedPath)); - const resources = installedPath ? await scanPluginSkills(installedPath) : []; - const counts = emptyCounts(); - counts.skills = resources.length; - const disabled = entry?.enabled === false; - return { - source: plugin.id, - scope: plugin.scope === "project" ? "project" : "global", - filtered: false, - disabled, - installedPath: installedPath || undefined, - packageName: plugin.id, - version: entry?.version, - configuredVersion: undefined, - counts, - resources, - status: disabled ? "disabled" : resources.length > 0 ? "loaded" : installed ? "installed" : "missing", - }; -} - -/** Without a cwd, the user level only (a cluster member's settings act on this machine's, spec K7): omp runs in its +/** Without a cwd, the user level only (a cluster member's settings act on this machine's, spec K7): pi runs in its * agent directory, where no project lies, and a project-scope entry is left out all the same. */ async function readPlugins(cwd: string | null): Promise { const diagnostics: PluginDiagnostic[] = []; @@ -208,46 +89,27 @@ async function readPlugins(cwd: string | null): Promise { const totals = emptyCounts(); try { - const { stdout } = await runOmp(["list"], { cwd: cwd ?? ensureAgentDir(), timeout: 60_000 }); - const list = parseJsonLoose(stdout); - if (list) { - for (const plugin of list.npm ?? []) { - packages.push(await toNpmPackageInfo(plugin)); - } - for (const plugin of list.marketplace ?? []) { - if (!cwd && plugin.scope === "project") continue; - const info = await toMarketplacePackageInfo(plugin); - if (plugin.shadowedBy) { - diagnostics.push({ - type: "warning", - source: plugin.id, - message: `Shadowed by a ${plugin.shadowedBy}-scoped install of the same plugin.`, - }); - } - packages.push(info); - } - } else { - const piPackages = parsePiListOutput(stdout); - for (const pkg of piPackages) { - if (!cwd && pkg.scope === "project") continue; - const installed = Boolean(pkg.path && existsSync(pkg.path)); - const resources = pkg.path ? await scanPluginSkills(pkg.path) : []; - const counts = emptyCounts(); - counts.skills = resources.length; - packages.push({ - source: pkg.source, - scope: pkg.scope, - filtered: false, - disabled: false, - installedPath: pkg.path || undefined, - packageName: basename(pkg.path) || pkg.source, - version: undefined, - configuredVersion: undefined, - counts, - resources, - status: resources.length > 0 ? "loaded" : installed ? "installed" : "missing", - }); - } + const { stdout } = await runPi(["list"], { cwd: cwd ?? ensureAgentDir(), timeout: 60_000 }); + const piPackages = parsePiListOutput(stdout); + for (const pkg of piPackages) { + if (!cwd && pkg.scope === "project") continue; + const installed = Boolean(pkg.path && existsSync(pkg.path)); + const resources = pkg.path ? await scanPluginSkills(pkg.path) : []; + const counts = emptyCounts(); + counts.skills = resources.length; + packages.push({ + source: pkg.source, + scope: pkg.scope, + filtered: false, + disabled: false, + installedPath: pkg.path || undefined, + packageName: basename(pkg.path) || pkg.source, + version: undefined, + configuredVersion: undefined, + counts, + resources, + status: resources.length > 0 ? "loaded" : installed ? "installed" : "missing", + }); } for (const pkg of packages) { totals.extensions += pkg.counts.extensions; @@ -269,12 +131,12 @@ function readScope(scope: unknown): PluginScope { return scope === "project" ? "project" : "global"; } -/** Dynamic CLI failures keep their message; a missing omp binary is the one +/** Dynamic CLI failures keep their message; a missing pi binary is the one * known cause worth a stable code for client-side localization. */ function pluginErrorResponse(error: unknown): Response { const message = error instanceof Error ? error.message : String(error); - if (message.includes(OMP_NOT_FOUND)) { - return Response.json({ error: message, code: "omp_not_found" }, { status: 500 }); + if (message.includes(PI_NOT_FOUND)) { + return Response.json({ error: message, code: "pi_not_found" }, { status: 500 }); } return Response.json({ error: message }, { status: 500 }); } @@ -316,14 +178,13 @@ export async function POST(req: Request) { if (body.action === "install") { if (!source) return Response.json({ error: "source required", code: "source_required" }, { status: 400 }); - await runOmp(["install", source, ...scopeArgs], { cwd: dir, timeout: 300_000 }); + await runPi(["install", source, ...scopeArgs], { cwd: dir, timeout: 300_000 }); } else if (body.action === "remove") { if (!source) return Response.json({ error: "source required", code: "source_required" }, { status: 400 }); - await runOmp(["remove", source, ...scopeArgs], { cwd: dir, timeout: 120_000 }); + await runPi(["remove", source, ...scopeArgs], { cwd: dir, timeout: 120_000 }); } else if (body.action === "update") { - await runOmp(["update", ...(source ? [source] : [])], { cwd: dir, timeout: 300_000 }); - } else if (body.action === "disable" || body.action === "enable") { - return Response.json({ error: `pi packages do not support ${body.action} via CLI; use remove/install instead.`, code: "plugin_unsupported_action" }, { status: 400 }); + // A bare `pi update` updates pi itself: without a source, the packages only. + await runPi(["update", ...(source ? [source] : ["--extensions"])], { cwd: dir, timeout: 300_000 }); } else { return Response.json({ error: `Unsupported action: ${body.action}`, code: "plugin_unsupported_action" }, { status: 400 }); } diff --git a/app/api/projects/route.ts b/app/api/projects/route.ts index 9fffbd7e..058b66fc 100644 --- a/app/api/projects/route.ts +++ b/app/api/projects/route.ts @@ -1,6 +1,5 @@ import { randomUUID } from "node:crypto"; import { apiErrorResponse, opErrorResponse, resolveHostOrError } from "@/lib/api-utils"; -import { isValidOmpProfile } from "@/lib/omp-profile"; import { allowFileRoot } from "@/lib/file-access"; import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; import { isValidPoolOrigin, loadPools, pathApi, poolManagedProject, savePools } from "@/lib/hosts/pools"; @@ -13,23 +12,17 @@ import type { ProjectLaunchConfig } from "@/lib/types"; const MAX_EXTRA_ARGS = 32; const MAX_EXTRA_ARG_LENGTH = 256; -/** Validate the workspace-level omp launch config; reject overrides of web-managed session-boundary args. */ +/** Validate the workspace-level pi launch config; reject overrides of web-managed session-boundary args. */ function parseLaunchConfig(value: unknown): ProjectLaunchConfig | undefined { if (value === undefined || value === null) return undefined; if (!value || typeof value !== "object" || Array.isArray(value)) throw new ProjectPathError("invalid_launch_config", "Launch config must be an object"); const raw = value as Record; - const profile = raw.profile === undefined ? undefined : typeof raw.profile === "string" && raw.profile.trim() ? raw.profile.trim() : undefined; - if (raw.profile !== undefined && !profile) throw new ProjectPathError("invalid_profile", "Profile must be a non-empty string"); - if (profile !== undefined && !isValidOmpProfile(profile)) throw new ProjectPathError("invalid_profile", "Profile names must match ^[a-z0-9][a-z0-9._-]{0,63}$, cannot end with '.', and cannot be a Windows reserved device name (CON, PRN, AUX, NUL, COM0-9, LPT0-9, or any of those with an extension)"); - const advisor = raw.advisor === undefined ? undefined : raw.advisor; - if (advisor !== undefined && typeof advisor !== "boolean") throw new ProjectPathError("invalid_advisor", "Advisor must be a boolean"); if (raw.extraArgs !== undefined && (!Array.isArray(raw.extraArgs) || raw.extraArgs.length > MAX_EXTRA_ARGS)) throw new ProjectPathError("invalid_extra_args", "Extra args must contain at most 32 arguments"); const extraArgs = raw.extraArgs === undefined ? undefined : (raw.extraArgs as unknown[]).map((arg) => { if (typeof arg !== "string" || !arg || arg.length > MAX_EXTRA_ARG_LENGTH || isReservedLaunchArg(arg)) throw new ProjectPathError("invalid_extra_args", "Extra args contain an invalid or reserved argument"); return arg; }); - if (!profile && advisor === undefined && (!extraArgs || extraArgs.length === 0)) return undefined; - return { profile, advisor, extraArgs }; + return extraArgs && extraArgs.length > 0 ? { extraArgs } : undefined; } function parsePresentation(entry: Record): ProjectPresentationUpdate { diff --git a/app/api/provider-usage/route.ts b/app/api/provider-usage/route.ts deleted file mode 100644 index 9f749fe8..00000000 --- a/app/api/provider-usage/route.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { getProviderUsage } from "@/lib/provider-usage"; - -const IDENTIFIER_RE = /^[A-Za-z0-9._:/-]{1,200}$/; - -function readIdentifier(value: string | null): string | undefined { - if (value === null) return undefined; - const trimmed = value.trim(); - if (!trimmed) return undefined; - return IDENTIFIER_RE.test(trimmed) ? trimmed : undefined; -} - -export async function GET(request: Request) { - const searchParams = new URL(request.url).searchParams; - const rawProvider = searchParams.get("provider"); - const rawModel = searchParams.get("model"); - const provider = readIdentifier(rawProvider); - const modelId = readIdentifier(rawModel); - - if ((rawProvider !== null && !provider) || (rawModel !== null && !modelId)) { - return Response.json( - { error: "Invalid provider or model identifier", code: "invalid_usage_query" }, - { status: 400 }, - ); - } - - try { - return Response.json(await getProviderUsage({ provider, modelId }, searchParams.get("refresh") === "true")); - } catch { - 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 deleted file mode 100644 index f99e7eea..00000000 --- a/app/api/providers/enable/route.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { invalidateModelsCache } from "@/lib/models-cache"; -import { enableProvider } from "@/lib/omp/model-roles"; -import { disposeUtilityRpc } from "@/lib/omp/rpc-utility"; - -export async function POST(request: Request) { - try { - const body = await request.json() as { provider?: unknown }; - if (typeof body.provider !== "string" || !body.provider.trim()) { - return Response.json({ error: "provider is required" }, { status: 400 }); - } - enableProvider(body.provider); - invalidateModelsCache(); - disposeUtilityRpc(); - return Response.json({ success: true }); - } catch (error) { - 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 9165945a..6103af78 100644 --- a/app/api/sessions/[id]/archive/route.ts +++ b/app/api/sessions/[id]/archive/route.ts @@ -4,7 +4,7 @@ import { invalidateHostSessionList } from "@/lib/hosts/session-index"; import { clearExitedRpcSession, getRpcSession } from "@/lib/rpc-manager"; /** POST /api/sessions/[id]/archive — stop the live child, then archive the - * native OMP JSONL and its sibling artifacts using OMP's gc layout. */ + * native pi JSONL and its sibling artifacts (lib/pi/archive.ts). */ export async function POST( _req: Request, { params }: { params: Promise<{ id: string }> }, @@ -25,7 +25,7 @@ export async function POST( ); } - // OMP owns writes while a child is live; wait for its final flush before + // pi owns writes while a child is live; wait for its exit before // moving the file so the archive contains the complete native transcript. // Disposing a child behind a down link would wait for the link to return. const offline = hostOfflineResponse(resolved.host); diff --git a/app/api/sessions/[id]/auto-name/route.ts b/app/api/sessions/[id]/auto-name/route.ts index c37afa57..de8f78d5 100644 --- a/app/api/sessions/[id]/auto-name/route.ts +++ b/app/api/sessions/[id]/auto-name/route.ts @@ -1,20 +1,15 @@ import { deriveSessionTitleFromFirstMessage, sanitizeSessionTitle } from "@/lib/session-title"; -import { getRpcSession, startRpcSession, WebRpcError } from "@/lib/rpc-manager"; -import { invalidateHostSessionList, sessionSpawnTarget } from "@/lib/hosts/session-index"; +import { getRpcSession } from "@/lib/rpc-manager"; +import { invalidateHostSessionList } from "@/lib/hosts/session-index"; import { HostOpError } from "@/lib/hosts/link-protocol"; -import { invalidateSessionCaches } from "@/lib/session-reader"; import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; /** * POST /api/sessions/[id]/auto-name * - * Generates a title with omp's own title generator (the native `generate_title` - * command, else argument-less `/rename`) through the session's omp process, - * starting one when the session is not live. omp persists the title itself. - * When omp cannot generate one (older omp, a run in flight, spawn failure) the - * endpoint falls back to the existing title, else a title derived from the - * first user message, and saves that fallback (through the live process when - * there is one). `generated` tells the caller which path produced the title. + * pi has no title generator: answers the existing title, else a title derived + * from the first user message, which it saves (through the live process when + * there is one, else as a session_info entry in the file). `generated` is always false. */ export async function POST( _req: Request, @@ -23,38 +18,6 @@ export async function POST( const { id } = await params; try { - // This runs before the path check because omp does not create the session - // file until the history holds an assistant message. - let rpc = getRpcSession(id); - if (!rpc?.isAlive?.()) { - const resolved = await resolveSessionHostOr404(id); - if ("response" in resolved) return resolved.response; - try { - const target = await sessionSpawnTarget(id, resolved.host); - if (target) { - rpc = (await startRpcSession(id, target.sessionFile, target.cwd, undefined, undefined, target.recordedCwd, undefined, resolved.host)).session; - } - } catch { - rpc = undefined; // Fall through to the fallback title. - } - } - - if (rpc?.isAlive?.()) { - try { - const generated = sanitizeSessionTitle((await rpc.generateTitle()) ?? undefined); - if (generated) { - invalidateSessionCaches(rpc.sessionFile); - 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 Response.json({ error: error.message, code: error.code }, { status: 409 }); - } - } - } - const resolved = await resolveSessionHostOr404(id); if ("response" in resolved) return resolved.response; const { sessionOps } = resolved.host; @@ -73,22 +36,27 @@ export async function POST( ); } - // Title generation/path resolution yielded; Edit may now own this session. + // The session list read yielded; Edit may now own this session. if (getRpcSession(id)?.isEditingHistory()) { 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. - const renamed = await sessionOps.renameSessionFile(id, derived, "auto"); - if (!renamed.ok) return opErrorResponse(renamed); - invalidateHostSessionList(resolved.host.id); + // A live pi holds the session: name it there. Otherwise append to the file. + const rpc = getRpcSession(id); + let named = false; if (rpc?.isAlive?.()) { try { await rpc.send({ type: "set_session_name", name: derived }); + named = true; } catch { - // Saved on disk; ignore RPC sync failure. + // Fall back to the file. } } + if (!named) { + const renamed = await sessionOps.renameSessionFile(id, derived); + if (!renamed.ok) return opErrorResponse(renamed); + } + invalidateHostSessionList(resolved.host.id); return Response.json({ title: derived, generated: false, usage: null }); } catch (error) { if (error instanceof HostOpError) return apiErrorResponse(error); diff --git a/app/api/sessions/[id]/context/route.ts b/app/api/sessions/[id]/context/route.ts index 713155f9..d0bc36a6 100644 --- a/app/api/sessions/[id]/context/route.ts +++ b/app/api/sessions/[id]/context/route.ts @@ -55,8 +55,8 @@ export async function GET( sync: sync === "1" ? { cursor, limit } : null, }); if ("response" in result || !result.ok) { - // OMP may not create the file until the first assistant message is - // committed. A live wrapper can still recover that first partial reply, + // pi does not create the file until the first user or assistant + // message is committed. A live wrapper can still recover that first partial reply, // and its persisted boundary is empty (the next prompt must not 404). // Never replace previously confirmed history when its file is missing. const notFound = "response" in result ? result.response.status === 404 : result.status === 404; diff --git a/app/api/sessions/[id]/export/route.ts b/app/api/sessions/[id]/export/route.ts index 657016bd..32205592 100644 --- a/app/api/sessions/[id]/export/route.ts +++ b/app/api/sessions/[id]/export/route.ts @@ -2,7 +2,7 @@ import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/li import { getContentDisposition } from "@/lib/content-disposition"; import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; -/** Render a session to self-contained HTML with the omp binary on its host (`omp --export`). */ +/** Render a session to self-contained HTML with the pi binary on its host (`pi --export`). */ export async function GET( req: Request, { params }: { params: Promise<{ id: string }> } diff --git a/app/api/sessions/[id]/local-file/route.ts b/app/api/sessions/[id]/local-file/route.ts deleted file mode 100644 index daa49b54..00000000 --- a/app/api/sessions/[id]/local-file/route.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { apiErrorResponse, opErrorResponse, resolveWorkspaceHost } from "@/lib/api-utils"; -import { parseLocalUri } from "@/lib/local-uri"; - -/** GET ?uri=local:// — the absolute path of a file in the session's own `local://` directory, for the file - * viewer (open_file). The owning host's daemon resolves and confines it (its machine, its platform rules); the file - * is stat'ed, not read: 404 `file_not_found` when it is not there, so the agent hears it. */ -export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) { - const { id } = await params; - const uri = new URL(request.url).searchParams.get("uri") ?? ""; - // Main checks only shared URI syntax; the owning daemon applies its platform's filename rules. - const parsed = parseLocalUri(uri, null); - if (!parsed.ok) return Response.json({ error: parsed.error, code: "invalid_local_uri" }, { status: 400 }); - try { - const resolved = await resolveWorkspaceHost(undefined, id, { followAlias: true }); - if ("response" in resolved) return resolved.response; - const owner = resolved.sessionId ?? id; - const result = await resolved.host.workspaceOps.resolveLocalFile(owner, uri, resolved.sessionFile); - if (!result.ok) return opErrorResponse(result); - // The live conversation owns the file: a tab authorized through the alias the request named would lose access once - // that alias is dropped with its wrapper. - return Response.json({ path: result.value.path, sessionId: owner }, { headers: { "Cache-Control": "no-store" } }); - } catch (error) { - return apiErrorResponse(error); - } -} diff --git a/app/api/sessions/[id]/route.ts b/app/api/sessions/[id]/route.ts index d3099a23..c67b2a77 100644 --- a/app/api/sessions/[id]/route.ts +++ b/app/api/sessions/[id]/route.ts @@ -81,10 +81,10 @@ export async function PATCH( if (typeof name !== "string" || !name.trim()) { 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 - // before the path check because omp does not create the session file until - // the history holds an assistant message. + // A running pi holds its session: rename through it (`set_session_name`), so + // its in-memory leaf and name stay in step with the file. This runs before + // the path check because pi does not create the session file until the + // history holds an assistant message. let renamed = false; const rpc = getRpcSession(id); if (rpc?.isAlive?.() && typeof rpc.send === "function") { @@ -93,7 +93,7 @@ export async function PATCH( renamed = true; } catch (error) { if (error instanceof WebRpcError && error.code === "session_busy") throw error; - // Fall back to the on-disk title slot below. + // Fall back to a session_info entry in the file below. } } if (!renamed) { @@ -125,22 +125,22 @@ export async function DELETE( try { const resolved = await resolveSessionHostOr404(id); if ("response" in resolved) return resolved.response; - // Await the child's exit before unlinking: omp flushes session state on - // shutdown and would recreate the file if it were still running. + // Await the child's exit before unlinking: a running pi would + // recreate the file on its next append. // Disposing a child behind a down link would wait for the link to return. const offline = hostOfflineResponse(resolved.host); if (offline) return offline; const live = getRpcSession(id); if (!live?.hostOwnedLifecycle) await live?.destroyAndWait?.("delete", true); - // Live children are skipped by the re-parent rewrite: their omp process - // owns the file and would clobber it on its next flush. + // Live children are skipped by the re-parent rewrite: their pi process + // owns the file and would clobber it on its next write. const result = await resolved.host.sessionOps.deleteSession(id, getLiveRpcSessionIds()); if (!result.ok) return opErrorResponse(result); // Remove only this deleted session's content-free retry-lineage metadata. try { forgetSessionReplacementMappings(id); } catch (error) { - console.warn(`[omp-web] could not clear deleted-session retry metadata: ${error instanceof Error ? error.message : String(error)}`); + console.warn(`[tau] could not clear deleted-session retry metadata: ${error instanceof Error ? error.message : String(error)}`); } invalidateHostSessionList(resolved.host.id); clearExitedRpcSession(id); @@ -148,7 +148,7 @@ export async function DELETE( removeSessionWatches(id); } catch (error) { // The delete succeeded; a watch left behind ends at the outbox's 404 for this session. - console.warn(`[omp-web] GitHub watches of ${id} were not removed: ${error instanceof Error ? error.message : String(error)}`); + console.warn(`[tau] GitHub watches of ${id} were not removed: ${error instanceof Error ? error.message : String(error)}`); } return Response.json({ ok: true, ...result.value }); } catch (error) { diff --git a/app/api/sessions/[id]/state/route.ts b/app/api/sessions/[id]/state/route.ts index 4960a2b5..ad2a9c29 100644 --- a/app/api/sessions/[id]/state/route.ts +++ b/app/api/sessions/[id]/state/route.ts @@ -3,7 +3,7 @@ import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/li import { outboxScope, outboxSnapshot } from "@/lib/message-outbox"; /** Every answer, an offline host's 503 included, carries the session's held messages (`outbox`): a tab opening a - * session with no omp running learns from it that there is an outbox to subscribe to. */ + * session with no pi running learns from it that there is an outbox to subscribe to. */ export async function GET( _req: Request, { params }: { params: Promise<{ id: string }> }, @@ -22,8 +22,8 @@ export async function GET( async function sessionState(id: string): Promise { try { - // A live process proves the session exists: omp does not create the session - // file until the history holds an assistant message, so the path check + // A live process proves the session exists: pi does not create the session + // file until the history holds a user or assistant message, so the path check // below would 404 a brand-new running session. const rpc = getRpcSession(id); if (rpc?.isAlive()) { diff --git a/app/api/sessions/[id]/subagents/[subagentId]/route.ts b/app/api/sessions/[id]/subagents/[subagentId]/route.ts index b6c6a71b..15c5a75f 100644 --- a/app/api/sessions/[id]/subagents/[subagentId]/route.ts +++ b/app/api/sessions/[id]/subagents/[subagentId]/route.ts @@ -11,6 +11,9 @@ import { isValidSubagentId } from "@/lib/hosts/session-ops"; * * ?mode=completion: the subagent's final output (`.md`), without loading * the transcript — works even for transcripts beyond the readable size cap. + * + * &file=: a pi-subagents child's own session file (from its progress or the history); the host reads it only + * inside the parent session's artifacts dir. Its completion is the last assistant message. */ export async function GET( req: Request, @@ -30,6 +33,7 @@ export async function GET( subagentId, searchParams.get("mode") === "completion" ? "completion" : "page", fromByteRaw !== null ? Number(fromByteRaw) : 0, + searchParams.get("file") ?? undefined, ); return result.ok ? Response.json(result.value) : opErrorResponse(result); } catch (error) { diff --git a/app/api/sessions/archive/route.ts b/app/api/sessions/archive/route.ts index fe8d0628..8d3a81b8 100644 --- a/app/api/sessions/archive/route.ts +++ b/app/api/sessions/archive/route.ts @@ -1,5 +1,5 @@ import { apiErrorResponse, opErrorResponse, resolveHostOrError } from "@/lib/api-utils"; -import { listArchivedSessionInfos, restoreArchivedSession, restoreFailureStatus } from "@/lib/omp/archive"; +import { listArchivedSessionInfos, restoreArchivedSession, restoreFailureStatus } from "@/lib/pi/archive"; import { HostOpError } from "@/lib/hosts/link-protocol"; import { getHost, listHosts } from "@/lib/hosts/hub"; import { isLinkUp } from "@/lib/hosts/host"; diff --git a/app/api/sessions/import/route.ts b/app/api/sessions/import/route.ts index 0e142c22..90796bb7 100644 --- a/app/api/sessions/import/route.ts +++ b/app/api/sessions/import/route.ts @@ -2,10 +2,10 @@ import { apiErrorResponse } from "@/lib/api-utils"; import { mkdirSync, writeFileSync } from "fs"; import path from "path"; import { randomUUID } from "crypto"; -import { getSessionsDir, getSessionDirNameForCwd } from "@/lib/omp/paths"; +import { getSessionsDir, getSessionDirNameForCwd } from "@/lib/pi/paths"; import { invalidateLocalSessionLists } from "@/lib/hosts/session-index"; import { invalidateSessionListCache } from "@/lib/session-reader"; -import { invalidateSessionFileListCache } from "@/lib/omp/session-files"; +import { invalidateSessionFileListCache } from "@/lib/pi/session-files"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; const MAX_IMPORT_BYTES = 10 * 1024 * 1024; @@ -14,12 +14,12 @@ const MAX_IMPORT_BYTES = 10 * 1024 * 1024; // separately while preserving the 10 MB limit for decoded session content. const MAX_IMPORT_REQUEST_BYTES = MAX_IMPORT_BYTES * 2 + 64 * 1024; -/** omp session file timestamps: ISO-8601 with `:` and `.` replaced by `-`. */ +/** pi session file timestamps: ISO-8601 with `:` and `.` replaced by `-`. */ function isoSessionTimestamp(): string { return new Date().toISOString().replace(/[:.]/g, "-"); } -// POST /api/sessions/import — import a native omp session .jsonl file. +// POST /api/sessions/import — import a native pi session .jsonl file. // The session keeps its original entries but can only target a workspace the // user previously authorized through projects, sessions, or cwd selection. export async function POST(req: Request) { @@ -75,10 +75,10 @@ export async function POST(req: Request) { return line; }); if (rewritten.some((line) => line === null)) { - return Response.json({ error: "Not a valid omp session file (malformed JSON line)", code: "invalid_session_file" }, { status: 400 }); + return Response.json({ error: "Not a valid pi session file (malformed JSON line)", code: "invalid_session_file" }, { status: 400 }); } if (!cwd) { - return Response.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 pi session file (missing session header with cwd)", code: "invalid_session_file" }, { status: 400 }); } const allowedRoots = await getAllowedFileRoots(); diff --git a/app/api/skills/install/route.ts b/app/api/skills/install/route.ts index 35f1747b..f45123cf 100644 --- a/app/api/skills/install/route.ts +++ b/app/api/skills/install/route.ts @@ -24,9 +24,9 @@ export async function POST(req: Request) { return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } } - // The skills.sh CLI has no omp agent entry; "universal" installs into the + // The skills.sh CLI has no pi agent entry; "universal" installs into the // ecosystem-standard ~/.agents/skills (global) / /.agents/skills - // (project), both of which omp discovers via its agent-dirs provider. + // (project), both of which pi discovers. const args = ["skills", "add", name, "-y", "--agent", "universal"]; if (isGlobal) args.push("-g"); diff --git a/app/api/skills/route.ts b/app/api/skills/route.ts index 27358cf4..abed6fc6 100644 --- a/app/api/skills/route.ts +++ b/app/api/skills/route.ts @@ -11,8 +11,8 @@ import { import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; // 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 +// Lists the skills a pi session in cwd loads (discoverSkills scans the +// directories pi reads, and `pi list` for package skills). Each skill // carries `togglable`, the same check PATCH applies. Without a cwd: the user // level only. export async function GET(req: Request) { @@ -48,9 +48,8 @@ export async function PATCH(req: Request) { } 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 - // be listed but never toggled. Session cwds cover the project-scope roots; + // in ~/.agents/skills (where the app's own global installs land) could be + // listed but never toggled. Session cwds cover the project-scope roots; // an optional cwd (already an allowed root) adds the project walk-up roots. // Plugin/registry skills stay read-only (see getSkillToggleRoots). const allowedRoots = await getSkillToggleRoots(cwd); diff --git a/app/api/stt/[jobId]/route.ts b/app/api/stt/[jobId]/route.ts index 605029c9..4a927c38 100644 --- a/app/api/stt/[jobId]/route.ts +++ b/app/api/stt/[jobId]/route.ts @@ -21,7 +21,7 @@ export async function GET(_req: Request, { params }: Params) { export async function POST(req: Request, { params }: Params) { const config = readSttConfig(); if (!config) { - return Response.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 TAU_STT_ENDPOINT or TAU_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); diff --git a/app/api/stt/route.ts b/app/api/stt/route.ts index caae0883..ea6ad375 100644 --- a/app/api/stt/route.ts +++ b/app/api/stt/route.ts @@ -23,7 +23,7 @@ export async function POST(request: Request) { const config = readSttConfig(); if (!config) { return Response.json( - { error: "STT not configured. Set OMP_WEB_STT_ENDPOINT." }, + { error: "STT not configured. Set TAU_STT_ENDPOINT." }, { status: 501 } ); } diff --git a/app/api/transport-metrics/route.ts b/app/api/transport-metrics/route.ts index 753d4775..dc32baf1 100644 --- a/app/api/transport-metrics/route.ts +++ b/app/api/transport-metrics/route.ts @@ -10,7 +10,7 @@ export function GET() { return Response.json({ now: Date.now() }, { headers: { "cache-control": "no-store" } }); } -// POST /api/transport-metrics { samples } — appended to /omp-web/transport-metrics.jsonl. +// POST /api/transport-metrics { samples } — appended to /tau/transport-metrics.jsonl. export async function POST(req: Request) { let body: unknown; try { diff --git a/app/api/web-auth/session/route.ts b/app/api/web-auth/session/route.ts index a9faa96a..3fd05d7f 100644 --- a/app/api/web-auth/session/route.ts +++ b/app/api/web-auth/session/route.ts @@ -4,8 +4,8 @@ import { createWebSession, isValidWebPassword, isWebPasswordEnabled, - OMP_WEB_SESSION_COOKIE, - OMP_WEB_SESSION_MAX_AGE_SECONDS, + TAU_SESSION_COOKIE, + TAU_SESSION_MAX_AGE_SECONDS, } from "@/lib/web-auth"; const MAX_PASSWORD_REQUEST_BYTES = 8 * 1024; @@ -27,11 +27,11 @@ export async function POST(request: Request) { } const secure = requestProtocol(request) === "https:"; - const cookie = new Bun.Cookie(OMP_WEB_SESSION_COOKIE, createWebSession(), { + const cookie = new Bun.Cookie(TAU_SESSION_COOKIE, createWebSession(), { httpOnly: true, secure, sameSite: "lax", - maxAge: OMP_WEB_SESSION_MAX_AGE_SECONDS, + maxAge: TAU_SESSION_MAX_AGE_SECONDS, path: "/", }); 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 daec0072..3db96aaa 100644 --- a/app/api/web-settings/route.ts +++ b/app/api/web-settings/route.ts @@ -1,13 +1,11 @@ -import { broadcastBrowserTransport } from "@/lib/event-stream-hub"; -import { BROWSER_TRANSPORTS } from "@/lib/event-stream-protocol"; import { syncInterruptibleSessions } from "@/lib/rpc-manager"; -import { parseAgentEnvText, sanitizeAgentEnvValues, type AgentEnvParseResult } from "@/lib/omp/agent-env"; +import { parseAgentEnvText, sanitizeAgentEnvValues, type AgentEnvParseResult } from "@/lib/pi/agent-env"; import { pushUploadRetention } from "@/lib/hosts/upload-retention-sync"; -import { browserTransportState, loadWebServerSettings, readWebServerSettingsFromDisk, saveWebServerSettings, type GithubActionsOperation, type GithubActionsPermission, type WebServerSettings } from "@/lib/web-settings"; +import { loadWebServerSettings, readWebServerSettingsFromDisk, saveWebServerSettings, type GithubActionsOperation, type GithubActionsPermission, type WebServerSettings } from "@/lib/web-settings"; import { isRecord } from "@/lib/type-guards"; import { isUploadRetentionDays } from "@/lib/upload-limits"; -/** GET/PUT /api/web-settings - omp-web's own server-side settings. */ +/** GET/PUT /api/web-settings - tau's own server-side settings. */ export async function GET() { try { return Response.json(readSettings()); @@ -16,7 +14,7 @@ export async function GET() { } } -/** Never surface a variable lib/omp/agent-env.ts would refuse to spawn with. */ +/** Never surface a variable lib/pi/agent-env.ts would refuse to spawn with. */ function readSettings(): WebServerSettings { const settings = readWebServerSettingsFromDisk(); return { ...settings, agentEnv: sanitizeAgentEnvValues(settings.agentEnv).values }; @@ -81,14 +79,6 @@ export async function PUT(req: Request) { patch.githubActionsPermissions = permissions; } - if (payload.browserTransport !== undefined) { - const transport = BROWSER_TRANSPORTS.find((value) => value === payload.browserTransport); - if (!transport) { - return Response.json({ error: `browserTransport must be one of ${BROWSER_TRANSPORTS.map((value) => `"${value}"`).join(", ")}`, code: "invalid_settings" }, { status: 400 }); - } - patch.browserTransport = transport; - } - if (payload.uploadRetentionDays !== undefined) { if (!isUploadRetentionDays(payload.uploadRetentionDays)) { return Response.json({ error: "uploadRetentionDays must be a whole number of days from 1 to 3650, or null", code: "invalid_settings" }, { status: 400 }); @@ -118,15 +108,11 @@ export async function PUT(req: Request) { patch.agentEnv = parsed.values; } - const previousTransport = JSON.stringify(browserTransportState()); const previousRetention = loadWebServerSettings().uploadRetentionDays; const settings = saveWebServerSettings(patch); // 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(); - // Every open browser converges on the new state; an unchanged one is not sent (the worker ignores it anyway). - const transport = browserTransportState(settings); - if (JSON.stringify(transport) !== previousTransport) broadcastBrowserTransport(transport); // Every host daemon deletes sent uploads by this value: the ones linked now are told at once, the others when they link. if (settings.uploadRetentionDays !== previousRetention) pushUploadRetention(settings.uploadRetentionDays); return Response.json({ ...settings, agentEnv: sanitizeAgentEnvValues(settings.agentEnv).values }); diff --git a/app/globals.css b/app/globals.css index 2b734e31..905a46ae 100644 --- a/app/globals.css +++ b/app/globals.css @@ -1,4 +1,4 @@ -/* Keep Tailwind's content scan inside the omp-web package. This is important +/* Keep Tailwind's content scan inside the tau package. This is important on Windows, where a parent user-profile package can make the scanner walk protected junctions such as "My Documents" during production builds. */ @import "tailwindcss" source(none); @@ -57,12 +57,11 @@ @source "../components"; @source "../hooks"; -/* Nerd Font icons (Private Use Area) sent by omp when its symbol preset is - "nerd": ask options, status text, tool output. unicode-range keeps this +/* Nerd Font icons (Private Use Area) in ask options, status text and tool + output. unicode-range keeps this face out of every other character and defers the download until a page actually shows one of these glyphs. The full Symbols Only set is kept on - purpose: tool output and model text can carry any Nerd Font icon, not just - the ones omp's own UI uses. Font: Nerd Fonts v3.5.1 Symbols Only, SIL OFL + purpose: tool output and model text can carry any Nerd Font icon. Font: Nerd Fonts v3.5.1 Symbols Only, SIL OFL 1.1; see fonts/SymbolsNerdFont-LICENSE.md and fonts/SymbolsNerdFont-README.md. */ @font-face { font-family: "Symbols Nerd Font Mono"; @@ -215,12 +214,12 @@ --overlay-backdrop: color-mix(in srgb, var(--text) 24%, transparent); } -/* omp.sh midnight theme (dark). Pure-black terminal look with a magenta/cyan +/* Midnight theme (dark). Pure-black terminal look with a magenta/cyan dual accent, ported from https://omp.sh. Text/background pairs verified WCAG AA (≥4.5:1 for small text) — measured values noted per token. - --text-dim is deliberately lighter than omp.sh's faint gray (which fails + --text-dim is deliberately lighter than the original's faint gray (which fails on panels) to hold AA. */ -html.omp { +html.midnight { color-scheme: dark; --bg: #000000; --bg-panel: #0A0A0C; @@ -256,34 +255,34 @@ html.omp { --shadow-modal: 0 8px 32px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.07); } -/* omp.sh dotted-grid canvas + magenta selection + cyan focus ring. */ -html.omp body { +/* Midnight dotted-grid canvas + magenta selection + cyan focus ring. */ +html.midnight body { background: conic-gradient(rgba(255,255,255,0.03) 90deg, transparent 90deg 180deg, rgba(255,255,255,0.03) 180deg 270deg, transparent 270deg) 0 0 / 2px 2px, #000000; } -html.omp ::selection { +html.midnight ::selection { background: rgba(236,91,171,0.32); color: var(--text); } -html.omp :focus-visible { +html.midnight :focus-visible { outline-color: var(--accent-2); } -/* omp.sh type voice: Geist for UI text, JetBrains Mono for code. Scoped to - the omp theme so the warm themes keep their system/serif identity. */ -html.omp, -html.omp body { +/* Midnight type voice: Geist for UI text, JetBrains Mono for code. Scoped to + the midnight theme so the warm themes keep their system/serif identity. */ +html.midnight, +html.midnight body { font-family: "Symbols Nerd Font Mono", var(--font-geist), ui-sans-serif, system-ui, sans-serif; } -html.omp { +html.midnight { --font-mono: "Symbols Nerd Font Mono", var(--font-jb-mono), "JetBrains Mono", ui-monospace, "Cascadia Mono", Consolas, monospace; } -/* omp.sh link sweep: underline draws itself left-to-right on hover/focus. */ -html.omp .markdown-body a { +/* Midnight link sweep: underline draws itself left-to-right on hover/focus. */ +html.midnight .markdown-body a { text-decoration: none; position: relative; } -html.omp .markdown-body a::after { +html.midnight .markdown-body a::after { content: ""; position: absolute; left: 0; @@ -295,14 +294,14 @@ html.omp .markdown-body a::after { transform-origin: 0; transition: transform 0.32s cubic-bezier(0.2, 0.8, 0.2, 1); } -html.omp .markdown-body a:hover::after, -html.omp .markdown-body a:focus-visible::after { +html.midnight .markdown-body a:hover::after, +html.midnight .markdown-body a:focus-visible::after { transform: scaleX(1); } -/* omp.sh sunray signature for the empty-state wordmark: a cyan→white sheen +/* Midnight sunray signature for the empty-state wordmark: a cyan→white sheen that sweeps across every 9s. Static gradient text when reduced motion. */ -html.omp .omp-wordmark { +html.midnight .tau-wordmark { background: linear-gradient(105deg, var(--accent-2) 38%, var(--text) 50%, var(--accent-2) 62%); background-position: 100% 0; background-size: 320% 100%; @@ -311,18 +310,18 @@ html.omp .omp-wordmark { color: transparent; } @media (prefers-reduced-motion: no-preference) { - html.omp .omp-wordmark { - animation: omp-sunray-sweep 9s cubic-bezier(0.4, 0, 0.2, 1) infinite; + html.midnight .tau-wordmark { + animation: tau-sunray-sweep 9s cubic-bezier(0.4, 0, 0.2, 1) infinite; } } -@keyframes omp-sunray-sweep { +@keyframes tau-sunray-sweep { 0% { text-shadow: none; background-position: 100% 0; } 8% { text-shadow: 0 0 16px color-mix(in srgb, var(--accent-2) 65%, transparent); } 18%, to { text-shadow: none; background-position: 0 0; } } /* Warm-ember palette (dark). Same AA verification as light. */ -html.dark:not([data-theme]):not(.omp), +html.dark:not([data-theme]):not(.midnight), html[data-theme="dark"], html.theme-dark { color-scheme: dark; @@ -1768,8 +1767,7 @@ html[data-touch-targets="accessible"] :is(.image-lightbox-stepper button, .image cursor: pointer; } .session-item-button:focus-visible, -.session-item-icon-button:focus-visible, -.provider-usage-row:focus-visible { +.session-item-icon-button:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; border-radius: 4px; @@ -2324,22 +2322,6 @@ html[data-touch-targets="accessible"] :is(.image-lightbox-stepper button, .image color: ButtonText; } } -.composer-usage-limit-badge { - flex: 0 1 auto; - min-width: 0; - max-width: 260px; - height: var(--control-height-sm); - line-height: var(--control-height-sm); - padding: 0 8px; - border-radius: 7px; - background: color-mix(in srgb, var(--status-warning) 12%, transparent); - color: var(--status-warning); - font-size: var(--text-sm); - font-weight: 600; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} .composer-primary-action { flex-shrink: 0; min-width: 7em; @@ -2351,9 +2333,7 @@ html[data-touch-targets="accessible"] :is(.image-lightbox-stepper button, .image } @container (max-width: 400px) { .composer-thinking-control > button > svg, - .composer-thinking-glyph[data-level] + .composer-thinking-label, - .composer-fast-control > span, - .composer-slow-control > span { + .composer-thinking-glyph[data-level] + .composer-thinking-label { display: none; } /* Glyph-only trigger: size up to read level with the 14px lucide icons. */ @@ -2363,16 +2343,6 @@ html[data-touch-targets="accessible"] :is(.image-lightbox-stepper button, .image .picker-thinking-card > .composer-thinking-glyph { font-size: 16px; } - .composer-slow-control > svg { - width: 14px; - height: 14px; - } - .composer-fast-control, - .composer-slow-control { - justify-content: center; - width: 28px; - padding-inline: 0 !important; - } } @container (max-width: 300px) { .composer-model-control, @@ -2411,10 +2381,6 @@ html[data-touch-targets="accessible"] :is(.image-lightbox-stepper button, .image .picker-thinking-card > .composer-thinking-glyph { font-size: 16px; } - .composer-slow-control > svg { - width: 14px; - height: 14px; - } } .composer-control-shelf { animation: ui-slide-up var(--dur-fast) var(--ease-out-warm) both; @@ -2455,7 +2421,6 @@ html[data-touch-targets="accessible"] :is(.image-lightbox-stepper button, .image } .composer-toolbar { flex-wrap: wrap !important; row-gap: 6px; } /* Own row above the controls, so it never squeezes the model picker. */ - .composer-usage-limit-badge { order: -1; flex-basis: 100%; max-width: none; } .sidebar-icon-button, .sidebar-project-action, @@ -4906,10 +4871,7 @@ html[data-touch-targets="accessible"] :is( .settings-close-btn, .settings-header input, .settings-nav-item, - .providers-segmented-btn, - .agent-config-action, - .agent-config-search, - .agent-config-row + .providers-segmented-btn ) { min-height: 44px; } @@ -4990,7 +4952,7 @@ html[data-touch-targets="accessible"] .extension-dialog-footer > button { } } -/* omp's ask dialogs: one choice-row look for select, approve, ask and the +/* Ask dialogs: one choice-row look for select, approve, ask and the agent's own forms. A chosen or pre-checked row is tinted; Recommended stays a text tag so it never reads as a selection. */ .extension-dialog-header { padding: 12px 16px; border-bottom: 1px solid var(--border); } @@ -5033,9 +4995,9 @@ html[data-touch-targets="accessible"] .extension-dialog-footer > button { } /* The Other row's text box has no frame of its own, so the row shows its focus. */ .extension-choice:has(textarea:focus-visible) { outline: 2px solid var(--accent); outline-offset: 2px; } -html.omp .extension-choice:has(textarea:focus-visible) { outline-color: var(--accent-2); } +html.midnight .extension-choice:has(textarea:focus-visible) { outline-color: var(--accent-2); } .extension-choice:disabled { cursor: default; opacity: 0.6; } -/* omp's trailing "Done selecting" row is an action, not one more answer. */ +/* The ask's trailing "Done selecting" row is an action, not one more answer. */ .extension-choice-action { justify-content: center; border-style: dashed; background: transparent; color: var(--text-muted); font-weight: 600; } .extension-choice textarea::placeholder, .extension-field::placeholder { color: var(--text-dim); opacity: 1; } @@ -5044,7 +5006,7 @@ html.omp .extension-choice:has(textarea:focus-visible) { outline-color: var(--ac min-width: 0; min-height: 36px; padding: 7px 12px; - /* At least 3:1 against the fill on the darkest themes (omp, warm dark). */ + /* At least 3:1 against the fill on the darkest themes (midnight, warm dark). */ border: 1px solid color-mix(in srgb, var(--text-muted) 55%, var(--border)); border-radius: 8px; background: var(--bg-panel); @@ -5054,25 +5016,8 @@ html.omp .extension-choice:has(textarea:focus-visible) { outline-color: var(--ac line-height: 20px; } .extension-field:focus-visible { border-radius: 8px; outline-offset: 1px; } -.extension-dialog-form { - display: grid; - grid-template-columns: minmax(0, 1fr); - gap: 6px; - color: var(--text); - font-size: 13px; - line-height: 20px; -} -.extension-dialog-form p { margin: 0 0 4px; color: var(--text-muted); } -.extension-dialog-form pre { margin: 0; max-width: 100%; overflow-x: auto; } -.extension-dialog-form fieldset { display: grid; grid-template-columns: minmax(0, 1fr); gap: 6px; min-width: 0; margin: 0; padding: 0; border: 0; } -.extension-dialog-form legend { margin-bottom: 8px; padding: 0; font-weight: 600; } -/* A field's own label opens a new block: more room above it than below it. */ -.extension-dialog-form label:not(.extension-choice, .extension-choice > label) { margin-top: 8px; color: var(--text-muted); font-size: 12px; font-weight: 600; } -.extension-dialog-form fieldset + fieldset, -.extension-dialog-form .extension-field + .extension-choice { margin-top: 10px; } .extension-choice > label { flex: 1; min-width: 0; cursor: pointer; } .extension-choice-text { flex: 1; min-width: 0; } -.extension-dialog-form :user-invalid { border-color: var(--status-error); } .extension-dialog-button { min-height: 32px; padding: 6px 14px; @@ -5102,16 +5047,11 @@ html[data-touch-targets="accessible"] :is(.extension-choice, .extension-field) { /* MCP management follows the native settings card and switch vocabulary. */ .mcp-management { display: flex; flex-direction: column; gap: 14px; margin-top: 16px; min-width: 0; } -.mcp-management-header, .mcp-management-title, .mcp-toolbar, .mcp-source-title, .mcp-server-title, .mcp-server-control { display: flex; align-items: center; gap: 8px; } +.mcp-management-header, .mcp-management-title, .mcp-source-title, .mcp-server-title { display: flex; align-items: center; gap: 8px; } .mcp-management-header { justify-content: space-between; flex-wrap: wrap; gap: 12px; } .mcp-management-title h3 { margin: 0; color: var(--text); font-size: 14px; font-weight: 600; } .mcp-management-description { margin: 0; color: var(--text-muted); font-size: var(--text-sm); line-height: 1.6; } .mcp-chip { display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; padding: 2px 7px; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--bg-subtle); color: var(--text-muted); font-size: 10.5px; font-weight: 500; line-height: 1.4; } -.mcp-toolbar { gap: 6px; } -.mcp-toolbar-button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; min-height: 36px; padding: 7px 11px; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--bg-panel); color: var(--text); font-size: 12px; font-weight: 500; cursor: pointer; transition: background var(--dur-fast), border-color var(--dur-fast); } -.mcp-toolbar-button:hover:not(:disabled) { background: var(--bg-hover); border-color: var(--text-dim); } -.mcp-toolbar-button:disabled { opacity: .5; cursor: not-allowed; } -.mcp-icon-button { width: 36px; padding: 0; color: var(--text-muted); } .mcp-management-note { display: flex; align-items: flex-start; gap: 7px; color: var(--text-dim); font-size: 11px; line-height: 1.5; } .mcp-management-note svg { flex-shrink: 0; margin-top: 1px; } .mcp-source-card { overflow: hidden; } @@ -5132,8 +5072,6 @@ html[data-touch-targets="accessible"] :is(.extension-choice, .extension-field) { .mcp-server-status[data-status="connected"] { color: var(--status-success); } .mcp-server-status[data-status="connected"] > span { background: var(--status-success); } .mcp-server-status[data-status="disabled"], .mcp-server-status[data-status="inactive"] { color: var(--text-dim); } -.mcp-server-control { color: var(--text-muted); flex-shrink: 0; } -.mcp-server-control button:disabled { opacity: .55; } .mcp-readonly { flex-shrink: 0; color: var(--text-dim); font-size: 10.5px; } .mcp-other-configs > summary { display: flex; align-items: center; gap: 8px; padding: 14px 18px; color: var(--text-muted); font-size: 12px; cursor: pointer; list-style: none; border-radius: var(--radius-card); } .mcp-other-configs > summary::-webkit-details-marker { display: none; } @@ -5144,19 +5082,19 @@ html[data-touch-targets="accessible"] :is(.extension-choice, .extension-field) { .mcp-empty { display: flex; align-items: center; justify-content: center; gap: 8px; padding: 24px; color: var(--text-dim); font-size: 12px; border: 1px dashed var(--border); border-radius: var(--radius-card); } .mcp-spin { animation: mcp-rotate 1s linear infinite; } @keyframes mcp-rotate { to { transform: rotate(360deg); } } -@media (max-width: 640px) { .mcp-source-header, .mcp-server-row, .mcp-other-configs > summary { padding-left: 14px; padding-right: 14px; } .mcp-toolbar-button { min-height: 40px; } .mcp-icon-button { width: 40px; } } +@media (max-width: 640px) { .mcp-source-header, .mcp-server-row, .mcp-other-configs > summary { padding-left: 14px; padding-right: 14px; } } @media (prefers-reduced-motion: reduce) { .mcp-spin { animation: none; } .mcp-management * { transition: none !important; } } .settings-card.mcp-source-card, .settings-card.mcp-other-configs, .settings-card.mcp-editor-card { display: block; padding: 0; margin-bottom: 0; } /* Sidebar search hits in the chat (CSS Custom Highlight API, set by useChatSearchHighlights) and in the sidebar's match list. */ -::highlight(omp-search), +::highlight(tau-search), .session-search-match-hit { background-color: color-mix(in srgb, var(--status-warning) 32%, transparent); color: inherit; } -::highlight(omp-search-current) { +::highlight(tau-search-current) { background-color: var(--status-warning); color: var(--bg); } diff --git a/app/index.html b/app/index.html index 1e006ffe..397afa1c 100644 --- a/app/index.html +++ b/app/index.html @@ -13,11 +13,11 @@ - - - - - + + + + + diff --git a/bin/bun-runtime.js b/bin/bun-runtime.js index 1434e850..188bed4e 100644 --- a/bin/bun-runtime.js +++ b/bin/bun-runtime.js @@ -8,7 +8,7 @@ const path = process.getBuiltinModule("node:path"); const MIN_BUN_VERSION = "1.4.4"; // The postinstall replaces bin/bun.exe (a 450-byte placeholder) with the real ~100 MB binary. const PLACEHOLDER_LIMIT = 1024 * 1024; -const REINSTALL = "npm install -g @kahme247/ompweb"; +const REINSTALL = "npm install -g @ompweb-dev/tau"; // bun@1.4.4's optionalDependencies, by `${process.platform}-${process.arch}` (Android uses the linux-*-android builds). const PLATFORM_PACKAGES = { "darwin-arm64": ["@oven/bun-darwin-aarch64"], @@ -71,7 +71,7 @@ function resolveBunBinary(packageDir, env = process.env) { if (onPath && versionAtLeast(onPath, MIN_BUN_VERSION)) return "bun"; const found = onPath ? ` (bun ${onPath} on PATH is older than ${MIN_BUN_VERSION})` : ""; - throw new Error(`Bun runtime not found${found}. Reinstall ompweb with: ${REINSTALL}`); + throw new Error(`Bun runtime not found${found}. Reinstall tau with: ${REINSTALL}`); } module.exports = { MIN_BUN_VERSION, PLATFORM_PACKAGES, resolveBunBinary }; diff --git a/bin/generate-release-notes.js b/bin/generate-release-notes.js index 336ee288..b4f0caaf 100644 --- a/bin/generate-release-notes.js +++ b/bin/generate-release-notes.js @@ -161,7 +161,7 @@ function formatReleaseNotes({ for (const c of commits) { const s = c.subject.trim(); - if (/^(?:chore: )?release( ompweb)? v?[0-9]/i.test(s) || /^v?[0-9]+\.[0-9]+\.[0-9]+$/i.test(s)) { + if (/^(?:chore: )?release( tau)? v?[0-9]/i.test(s) || /^v?[0-9]+\.[0-9]+\.[0-9]+$/i.test(s)) { continue; } @@ -213,7 +213,7 @@ function formatReleaseNotes({ if (!lines.join("\n").includes("## Upgrade")) { lines.push("\n## Upgrade\n"); lines.push("```bash"); - lines.push(`npm install -g @kahme247/ompweb@${version}`); + lines.push(`npm install -g @ompweb-dev/tau@${version}`); lines.push("```"); } diff --git a/bin/generate-release-notes.test.mjs b/bin/generate-release-notes.test.mjs index f173a8fa..2c5caaa8 100644 --- a/bin/generate-release-notes.test.mjs +++ b/bin/generate-release-notes.test.mjs @@ -107,6 +107,6 @@ Older release notes. assert.match(notes, /## Contributors/); assert.match(notes, /@alice/); assert.match(notes, /@bob/); - assert.match(notes, /npm install -g @kahme247\/ompweb@0\.4\.0/); + assert.match(notes, /npm install -g @ompweb-dev\/tau@0\.4\.0/); }); }); diff --git a/bin/linux-tray.js b/bin/linux-tray.js index 2d44cb1f..633f3bbb 100644 --- a/bin/linux-tray.js +++ b/bin/linux-tray.js @@ -3,19 +3,19 @@ // eslint-disable-next-line @typescript-eslint/no-require-imports require("./node-version").exitIfUnsupportedNode(); -// Linux system tray for ompweb (KDE Plasma and any StatusNotifierItem host). +// Linux system tray for tau (KDE Plasma and any StatusNotifierItem host). // // Registers a StatusNotifierItem on the session bus with a DBusMenu context // menu mirroring the Windows tray: open, copy URL, start/stop/restart the // systemd user service, view logs, autostart toggle, quit. // // CLI: -// ompweb-tray --install [--no-autostart] install icons/autostart, start tray -// ompweb-tray --uninstall remove autostart and stop the tray -// ompweb-tray --start run the tray (foreground) -// ompweb-tray --stop | --restart stop/restart a running tray -// ompweb-tray --status [--json] tray + service status -// ompweb-tray --open open the web UI in the browser +// tau-tray --install [--no-autostart] install icons/autostart, start tray +// tau-tray --uninstall remove autostart and stop the tray +// tau-tray --start run the tray (foreground) +// tau-tray --stop | --restart stop/restart a running tray +// tau-tray --status [--json] tray + service status +// tau-tray --open open the web UI in the browser // -p, --port / -H, --hostname override status endpoint // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -36,9 +36,9 @@ const path = require("node:path"); const { readServiceEnv, writeServiceEnv } = require("./service-env");// eslint-disable-next-line @typescript-eslint/no-require-imports const { getAccessibleAddresses, isLoopbackHost } = require("./network-addresses"); // eslint-disable-next-line @typescript-eslint/no-require-imports -const { hashPassword } = require("./omp-web-password-hash"); +const { hashPassword } = require("./tau-password-hash"); -// dbus-next is intentionally NOT a dependency of ompweb (see #268): it +// dbus-next is intentionally NOT a dependency of tau (see #268): it // pulled in usocket/node-gyp@7 and ten deprecated packages on every // install, while only the Linux tray uses it. It is loaded on demand // below, and the tray installs it (or tells the user how to) at setup @@ -46,9 +46,9 @@ const { hashPassword } = require("./omp-web-password-hash"); // via FallbackVariant, which only needs the .value the tests and the // menu code read; the real D-Bus path always uses the real Variant. const DBUS_MISSING_MESSAGE = - "The Linux tray requires dbus-next, which is not bundled with ompweb. " + + "The Linux tray requires dbus-next, which is not bundled with tau. " + "Install it with: npm install dbus-next@^0.10.2 " + - "(in the ompweb install directory, or globally with npm install -g dbus-next@^0.10.2), " + + "(in the tau install directory, or globally with npm install -g dbus-next@^0.10.2), " + "then run the tray command again."; class FallbackVariant { @@ -111,7 +111,7 @@ function getDbusClasses() { return [ "", this.state.running ? buildIconPixmap(true) : buildIconPixmap(false), - "ompweb", + "tau", this.state.running ? `Running — ${this.state.serviceUrl}` : "Service stopped", ]; } @@ -169,8 +169,8 @@ function getDbusClasses() { }); StatusNotifierItem.prototype.Category = "ApplicationStatus"; - StatusNotifierItem.prototype.Id = "ompweb"; - StatusNotifierItem.prototype.Title = "ompweb"; + StatusNotifierItem.prototype.Id = "tau"; + StatusNotifierItem.prototype.Title = "tau"; // Status, IconName, IconPixmap, and ToolTip stay as class getters (dynamic). StatusNotifierItem.prototype.WindowId = 0; StatusNotifierItem.prototype.AttentionIconName = ""; @@ -247,7 +247,7 @@ function getDbusClasses() { class TrayControl extends Interface { constructor(state) { - super("org.kde.ompweb.Tray"); + super("org.kde.tau.Tray"); this.state = state; } @@ -267,13 +267,13 @@ function getDbusClasses() { const execFileAsync = promisify(execFile); -const BUS_NAME = "org.kde.ompweb.tray"; +const BUS_NAME = "org.kde.tau.tray"; const ITEM_PATH = "/StatusNotifierItem"; const MENU_PATH = "/MenuBar"; -const TRAY_PATH = "/ompweb/tray"; -const SERVICE_UNIT = "ompweb.service"; -const DAEMON_UNIT = "ompweb-host.service"; -const AUTOSTART_FILE = path.join(os.homedir(), ".config", "autostart", "ompweb-tray.desktop"); +const TRAY_PATH = "/tau/tray"; +const SERVICE_UNIT = "tau.service"; +const DAEMON_UNIT = "tau-host.service"; +const AUTOSTART_FILE = path.join(os.homedir(), ".config", "autostart", "tau-tray.desktop"); const ICON_DIR = path.join(os.homedir(), ".local", "share", "icons", "hicolor", "scalable", "apps"); const POLL_INTERVAL_MS = 5000; @@ -385,9 +385,9 @@ function buildIconPixmap(running) { } function printHelp() { - console.log(`Usage: ompweb-tray [command] [options] + console.log(`Usage: tau-tray [command] [options] -Linux system tray icon (StatusNotifierItem) for the ompweb web service. +Linux system tray icon (StatusNotifierItem) for the tau web service. Commands: --install, install Install icons + autostart entry, then start the tray @@ -421,7 +421,7 @@ function readPackageVersion() { // Pure helpers (unit-tested) // --------------------------------------------------------------------------- -function sanitizePort(val, fallback = 30177) { +function sanitizePort(val, fallback = 30187) { const port = parseInt(val, 10); return Number.isInteger(port) && port >= 0 && port <= 65535 ? port : fallback; } @@ -435,7 +435,7 @@ function sanitizeHostname(val, fallback = "127.0.0.1") { // (the source the tray edits), then the Windows-style JSON config, then // defaults. function readTrayConfig(overrides = {}, env = process.env, home = os.homedir()) { - const agentDir = (env.PI_CODING_AGENT_DIR ?? path.join(home, ".omp", "agent")).replace(/^~(?=\/|$)/, home); + const agentDir = (env.PI_CODING_AGENT_DIR ?? path.join(home, ".pi", "agent")).replace(/^~(?=\/|$)/, home); const configFile = path.join(agentDir, "web-service.json"); const serviceEnv = readServiceEnv(path.join(agentDir, "web-service.env")); let jsonConfig = {}; @@ -445,23 +445,23 @@ function readTrayConfig(overrides = {}, env = process.env, home = os.homedir()) jsonConfig = {}; } const port = overrides.port ?? sanitizePort(serviceEnv.PORT ?? jsonConfig.port); - const hostname = overrides.hostname ?? sanitizeHostname(serviceEnv.OMP_WEB_HOSTNAME ?? jsonConfig.hostname); + const hostname = overrides.hostname ?? sanitizeHostname(serviceEnv.TAU_HOSTNAME ?? jsonConfig.hostname); return { port, hostname, configFile, serviceUrl: `http://${hostname}:${port}` }; } // Menu item table. `separator` items render as dividers; `checkmark` items // carry a toggle state; `disabled` items are inert status rows. -// `daemon` is "running", "stopped" or "not installed" (the ompweb-host unit). +// `daemon` is "running", "stopped" or "not installed" (the tau-host unit). function buildMenuItems({ running, version, autostart, hasService, exposed, hasDialogTool, daemon = "not installed" }) { return [ - { id: 1, label: `ompweb (v${version})`, enabled: false }, + { id: 1, label: `tau (v${version})`, enabled: false }, { id: 2, label: running ? " Status: Running" : " Status: Stopped", enabled: false }, { id: 19, label: ` Daemon: ${daemon[0].toUpperCase()}${daemon.slice(1)}`, enabled: false }, { id: 3, separator: true }, { id: 4, label: "Open in Browser", action: "open" }, { id: 5, label: "Copy Web URL", action: "copy" }, { id: 6, separator: true }, - { id: 7, label: running ? "Stop Server (omp runs keep going)" : "Start Server", action: "toggle", enabled: hasService }, + { id: 7, label: running ? "Stop Server (pi runs keep going)" : "Start Server", action: "toggle", enabled: hasService }, { id: 8, label: "Restart Server", action: "restart", enabled: hasService }, { id: 9, separator: true }, { id: 10, label: "View Logs", action: "logs" }, @@ -528,11 +528,11 @@ function buildAutostartDesktop(execLine) { return [ "[Desktop Entry]", "Type=Application", - "Name=ompweb Tray", - "GenericName=ompweb tray icon", - "Comment=ompweb web service tray icon and controls", + "Name=tau Tray", + "GenericName=tau tray icon", + "Comment=tau web service tray icon and controls", `Exec=${execLine}`, - "Icon=ompweb", + "Icon=tau", "Terminal=false", "Categories=Network;", "X-GNOME-Autostart-enabled=true", @@ -552,7 +552,7 @@ function buildAutostartExec() { // Terminal used to open logs; ordered candidates, first hit wins. function terminalCandidates(env = process.env) { return [ - ...(env.OMP_WEB_TERMINAL ? [env.OMP_WEB_TERMINAL] : []), + ...(env.TAU_TERMINAL ? [env.TAU_TERMINAL] : []), ...(env.TERMINAL ? [env.TERMINAL] : []), "konsole", "alacritty", @@ -603,7 +603,7 @@ function dialogCandidates() { } function resolveDialogTool(env = process.env) { - const override = env.OMP_WEB_DIALOG; + const override = env.TAU_DIALOG; if (override) { return override.includes(path.sep) ? (isExecutable(override) ? override : null) : which(override); } @@ -704,7 +704,7 @@ function viewLogs() { const resolved = candidateBinPath(terminal); if (!resolved) return false; const prefix = terminalPrefix(terminal).slice(1); - const child = spawn(resolved, [...prefix, `journalctl --user -u ompweb -u ompweb-host -f`], { + const child = spawn(resolved, [...prefix, `journalctl --user -u tau -u tau-host -f`], { stdio: "ignore", detached: true, env: process.env, @@ -779,12 +779,12 @@ function createTrayState(config, { log = console.log } = {}) { try { writeServiceEnv(merged); } catch (err) { - state.notify("ompweb", `Config write failed: ${err.message}`); + state.notify("tau", `Config write failed: ${err.message}`); return false; } const result = systemctlUser(["restart", SERVICE_UNIT]); if (!result.ok) { - state.notify("ompweb", `Service restart failed: ${result.stderr || result.stdout || "unknown error"}`); + state.notify("tau", `Service restart failed: ${result.stderr || result.stdout || "unknown error"}`); return false; } state.reloadConfig(); @@ -801,7 +801,7 @@ function createTrayState(config, { log = console.log } = {}) { getDbusClasses().Interface.emitPropertiesChanged(state.sni, { IconName: "", IconPixmap: buildIconPixmap(state.running), - ToolTip: ["", buildIconPixmap(state.running), "ompweb", state.running ? `Running — ${state.serviceUrl}` : "Service stopped"], + ToolTip: ["", buildIconPixmap(state.running), "tau", state.running ? `Running — ${state.serviceUrl}` : "Service stopped"], }); state.sni.NewIcon(); state.sni.NewToolTip(); @@ -816,7 +816,7 @@ function createTrayState(config, { log = console.log } = {}) { openUrl(state.serviceUrl); break; case "copy": - if (!copyToClipboard(state.serviceUrl)) state.notify("ompweb", "No clipboard tool found (install wl-clipboard)"); + if (!copyToClipboard(state.serviceUrl)) state.notify("tau", "No clipboard tool found (install wl-clipboard)"); break; case "toggle": systemctlUser([state.running ? "stop" : "start", SERVICE_UNIT]); @@ -825,33 +825,33 @@ function createTrayState(config, { log = console.log } = {}) { systemctlUser(["restart", SERVICE_UNIT]); break; case "logs": - if (!viewLogs()) state.notify("ompweb", "No terminal emulator found for logs"); + if (!viewLogs()) state.notify("tau", "No terminal emulator found for logs"); break; case "autostart": state.setAutostart(!state.autostart); break; case "expose": { const exposing = !state.exposed; - const updates = { OMP_WEB_HOSTNAME: exposing ? "0.0.0.0" : "127.0.0.1" }; - if (exposing && !readServiceEnv().OMP_WEB_PASSWORD_HASH) { + const updates = { TAU_HOSTNAME: exposing ? "0.0.0.0" : "127.0.0.1" }; + if (exposing && !readServiceEnv().TAU_PASSWORD_HASH) { const password = await dialogPrompt({ tool: state.dialogTool, - title: "ompweb", + title: "tau", text: "A password is required to expose the web UI.\nWeb sign-in password:", password: true, }); if (!password) { - state.notify("ompweb", "Expose cancelled: a password is required to leave loopback"); + state.notify("tau", "Expose cancelled: a password is required to leave loopback"); break; } - updates.OMP_WEB_PASSWORD_HASH = hashPassword(password); + updates.TAU_PASSWORD_HASH = hashPassword(password); } if (state.applyServiceEnv(updates)) { const urls = getAccessibleAddresses({ hostname: state.hostname, port: state.port }).entries .filter((entry) => entry.label !== "Local") .map((entry) => entry.url); state.notify( - "ompweb", + "tau", exposing ? `Exposed to the network: ${urls[0] ?? `http://0.0.0.0:${state.port}`}` : `Restricted to loopback (${state.serviceUrl})`, @@ -862,38 +862,38 @@ function createTrayState(config, { log = console.log } = {}) { case "port": { const input = await dialogPrompt({ tool: state.dialogTool, - title: "ompweb", + title: "tau", text: `Server port (current: ${state.port}):`, value: String(state.port), }); if (input === null) break; const port = parseInt(input.trim(), 10); if (!Number.isInteger(port) || port < 1 || port > 65535) { - state.notify("ompweb", `Invalid port: ${input.trim()}`); + state.notify("tau", `Invalid port: ${input.trim()}`); break; } if (state.applyServiceEnv({ PORT: String(port) })) { - state.notify("ompweb", `Port updated: ${state.serviceUrl}`); + state.notify("tau", `Port updated: ${state.serviceUrl}`); } break; } case "password": { const password = await dialogPrompt({ tool: state.dialogTool, - title: "ompweb", + title: "tau", text: "Web sign-in password (empty disables auth):", password: true, }); if (password === null) break; const updates = {}; if (password) { - updates.OMP_WEB_PASSWORD_HASH = hashPassword(password); + updates.TAU_PASSWORD_HASH = hashPassword(password); } else { - updates.OMP_WEB_PASSWORD_HASH = null; - if (!isLoopbackHost(state.hostname)) updates.OMP_WEB_HOSTNAME = "127.0.0.1"; + updates.TAU_PASSWORD_HASH = null; + if (!isLoopbackHost(state.hostname)) updates.TAU_HOSTNAME = "127.0.0.1"; } if (state.applyServiceEnv(updates)) { - state.notify("ompweb", password ? "Password updated" : "Password disabled (loopback only)"); + state.notify("tau", password ? "Password updated" : "Password disabled (loopback only)"); } break; } @@ -916,7 +916,7 @@ function createTrayState(config, { log = console.log } = {}) { state.autostart = enable; state.refreshMenu(); } catch (err) { - state.notify("ompweb", `Autostart update failed: ${err.message}`); + state.notify("tau", `Autostart update failed: ${err.message}`); } }; @@ -925,7 +925,7 @@ function createTrayState(config, { log = console.log } = {}) { try { const obj = await state.bus.getProxyObject("org.freedesktop.Notifications", "/org/freedesktop/Notifications"); const iface = obj.getInterface("org.freedesktop.Notifications"); - await iface.Notify("ompweb", 0, "ompweb", summary, body, [], {}, 5000); + await iface.Notify("tau", 0, "tau", summary, body, [], {}, 5000); } catch { // Notifications are best-effort. } @@ -1005,7 +1005,7 @@ async function startTray(config, { log = console.log, error = console.error } = } // 1 = primary owner, 4 = already ours; anything else means another tray runs. if (nameReply !== 1 && nameReply !== 4) { - log("ompweb tray is already running"); + log("tau tray is already running"); return state; } @@ -1025,15 +1025,15 @@ async function startTray(config, { log = console.log, error = console.error } = await state.registerWithWatcher(); state.registerTimer = setInterval(() => state.registerWithWatcher(), 60000); state.pollTimer = setInterval(() => state.poll(), POLL_INTERVAL_MS); - log(`ompweb tray started (${state.serviceUrl})`); + log(`tau tray started (${state.serviceUrl})`); return state; } function installIcons({ log = console.log } = {}) { try { fs.mkdirSync(ICON_DIR, { recursive: true }); - fs.writeFileSync(path.join(ICON_DIR, "ompweb.svg"), ICON_RUNNING, { mode: 0o644 }); - fs.writeFileSync(path.join(ICON_DIR, "ompweb-off.svg"), ICON_STOPPED, { mode: 0o644 }); + fs.writeFileSync(path.join(ICON_DIR, "tau.svg"), ICON_RUNNING, { mode: 0o644 }); + fs.writeFileSync(path.join(ICON_DIR, "tau-off.svg"), ICON_STOPPED, { mode: 0o644 }); } catch (err) { log(`warning: could not install tray icons: ${err.message}`); } @@ -1079,7 +1079,7 @@ async function quitRunningTray() { } try { const obj = await bus.getProxyObject(BUS_NAME, TRAY_PATH); - const iface = obj.getInterface("org.kde.ompweb.Tray"); + const iface = obj.getInterface("org.kde.tau.Tray"); await iface.Quit(); return true; } catch { @@ -1124,7 +1124,7 @@ async function readStatus(overrides) { // Best-effort on-demand install of dbus-next, used only by --install: // the user explicitly opted into tray setup, so installing the tray's -// own dependency into the ompweb install directory is in scope there. +// own dependency into the tau install directory is in scope there. // --start/--restart never auto-install (they can run unattended from // autostart); they fail with DBUS_MISSING_MESSAGE instead. function defaultNpmInstallDbus() { @@ -1192,7 +1192,7 @@ async function runCli(argv = process.argv.slice(2)) { }); if (process.platform !== "linux") { - console.error("error: the Linux tray is only supported on Linux (see omp-web-tray for Windows)"); + console.error("error: the Linux tray is only supported on Linux (see tau-tray for Windows)"); return { exitCode: 1 }; } @@ -1283,7 +1283,7 @@ async function runCli(argv = process.argv.slice(2)) { if (cliArgs.json) { console.log(JSON.stringify(status, null, 2)); } else { - console.log(`=== ompweb Linux tray status ===`); + console.log(`=== tau Linux tray status ===`); console.log(` Tray running : ${status.trayRunning ? "Yes" : "No"}`); console.log(` Service unit : ${status.serviceInstalled ? "installed" : "not installed"} (${status.serviceRunning ? "active" : "inactive"})`); console.log(` Host daemon : ${status.daemon}`); diff --git a/bin/linux-tray.test.mjs b/bin/linux-tray.test.mjs index a02bac13..50a97abd 100644 --- a/bin/linux-tray.test.mjs +++ b/bin/linux-tray.test.mjs @@ -39,10 +39,10 @@ const { } = require("./service-env.js"); test("sanitizePort accepts valid ports and falls back otherwise", () => { - assert.equal(sanitizePort("30177"), 30177); + assert.equal(sanitizePort("30187"), 30187); assert.equal(sanitizePort(8080), 8080); - assert.equal(sanitizePort("nope"), 30177); - assert.equal(sanitizePort("70000"), 30177); + assert.equal(sanitizePort("nope"), 30187); + assert.equal(sanitizePort("70000"), 30187); assert.equal(sanitizePort(undefined, 4000), 4000); }); @@ -53,9 +53,9 @@ test("sanitizeHostname trims strings and rejects empties", () => { }); test("readTrayConfig prefers CLI overrides over the service config file", () => { - const home = mkdtempSync(path.join(tmpdir(), "ompweb-tray-")); + const home = mkdtempSync(path.join(tmpdir(), "tau-tray-")); try { - const agentDir = path.join(home, ".omp", "agent"); + const agentDir = path.join(home, ".pi", "agent"); mkdirSync(agentDir, { recursive: true }); writeFileSync(path.join(agentDir, "web-service.json"), JSON.stringify({ port: 40001, hostname: "0.0.0.0" })); @@ -73,10 +73,10 @@ test("readTrayConfig prefers CLI overrides over the service config file", () => }); test("readTrayConfig falls back to defaults without a config file", () => { - const home = mkdtempSync(path.join(tmpdir(), "ompweb-tray-")); + const home = mkdtempSync(path.join(tmpdir(), "tau-tray-")); try { const config = readTrayConfig({}, {}, home); - assert.equal(config.port, 30177); + assert.equal(config.port, 30187); assert.equal(config.hostname, "127.0.0.1"); } finally { rmSync(home, { recursive: true, force: true }); @@ -86,7 +86,7 @@ test("readTrayConfig falls back to defaults without a config file", () => { test("buildMenuItems reflects running state and service availability", () => { const running = buildMenuItems({ running: true, version: "0.4.2", autostart: true, hasService: true, exposed: false, hasDialogTool: true }); assert.equal(itemById(running, 2).label, " Status: Running"); - assert.equal(itemById(running, 7).label, "Stop Server (omp runs keep going)"); + assert.equal(itemById(running, 7).label, "Stop Server (pi runs keep going)"); assert.equal(itemById(running, 12).label, "Expose to Network"); assert.equal(itemById(running, 12).state, 0); assert.equal(itemById(running, 16).label, "Start with Plasma"); @@ -108,7 +108,7 @@ test("buildMenuItems reflects running state and service availability", () => { assert.equal(itemById(noDialog, 13).enabled, false); assert.equal(itemById(noDialog, 14).enabled, false); - // The ompweb-host daemon state sits under the web status. + // The tau-host daemon state sits under the web status. assert.equal(itemById(running, 19).label, " Daemon: Not installed"); assert.equal(itemById(running, 19).enabled, false); const withDaemon = buildMenuItems({ running: true, version: "0.4.2", autostart: false, hasService: true, exposed: false, hasDialogTool: true, daemon: "running" }); @@ -152,9 +152,9 @@ test("buildLayout nests all items under the root with the given revision", () => }); test("autostart desktop file references the tray script", () => { - const desktop = buildAutostartDesktop("/usr/bin/node /opt/ompweb/bin/linux-tray.js --start"); + const desktop = buildAutostartDesktop("/usr/bin/node /opt/tau/bin/linux-tray.js --start"); assert.match(desktop, /^\[Desktop Entry\]/); - assert.match(desktop, /^Exec=\/usr\/bin\/node \/opt\/ompweb\/bin\/linux-tray\.js --start$/m); + assert.match(desktop, /^Exec=\/usr\/bin\/node \/opt\/tau\/bin\/linux-tray\.js --start$/m); assert.match(desktop, /^Terminal=false$/m); assert.match(desktop, /^X-KDE-autostart-after=panel$/m); }); @@ -169,7 +169,7 @@ test("buildAutostartExec quotes paths containing spaces", () => { }); test("terminal candidates honor explicit env overrides first", () => { - const candidates = terminalCandidates({ OMP_WEB_TERMINAL: "foot", TERMINAL: "wezterm" }); + const candidates = terminalCandidates({ TAU_TERMINAL: "foot", TERMINAL: "wezterm" }); assert.deepEqual(candidates.slice(0, 2), ["foot", "wezterm"]); assert.ok(candidates.includes("konsole")); }); @@ -223,10 +223,10 @@ test("buildIconPixmap returns sized structs with matching byte counts", () => { test("service env file round-trips quoted and escaped values", () => { const entries = { - PORT: "30177", - OMP_WEB_HOSTNAME: "0.0.0.0", - OMP_WEB_PASSWORD: 'pa"ss\\word', - OMP_WEB_OMP_BIN: "/home/u/.bun/bin/omp", + PORT: "30187", + TAU_HOSTNAME: "0.0.0.0", + TAU_PASSWORD: 'pa"ss\\word', + TAU_PI_BIN: "/home/u/.bun/bin/omp", }; const parsed = parseServiceEnv(serializeServiceEnv(entries)); assert.deepEqual(parsed, entries); @@ -238,24 +238,24 @@ test("parseServiceEnv tolerates comments, blanks, and unquoted values", () => { ; also a comment PORT=40001 -OMP_WEB_HOSTNAME="0.0.0.0" +TAU_HOSTNAME="0.0.0.0" broken line without equals 1BAD=skipped `); - assert.deepEqual(parsed, { PORT: "40001", OMP_WEB_HOSTNAME: "0.0.0.0" }); + assert.deepEqual(parsed, { PORT: "40001", TAU_HOSTNAME: "0.0.0.0" }); }); test("writeServiceEnv writes atomically with mode 600 and readServiceEnv round-trips", () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-env-")); + const dir = mkdtempSync(path.join(tmpdir(), "tau-env-")); try { const file = path.join(dir, "web-service.env"); - writeServiceEnv({ PORT: "40100", OMP_WEB_PASSWORD: "s3cret" }, file); + writeServiceEnv({ PORT: "40100", TAU_PASSWORD: "s3cret" }, file); // Windows has no Unix permission bits (chmod is best-effort there), so // the mode assertion only applies elsewhere. if (process.platform !== "win32") { assert.equal(statSync(file).mode & 0o777, 0o600); } - assert.deepEqual(readServiceEnv(file), { PORT: "40100", OMP_WEB_PASSWORD: "s3cret" }); + assert.deepEqual(readServiceEnv(file), { PORT: "40100", TAU_PASSWORD: "s3cret" }); assert.ok(escapeEnvValue("a\nb").includes(" ")); } finally { rmSync(dir, { recursive: true, force: true }); @@ -263,12 +263,12 @@ test("writeServiceEnv writes atomically with mode 600 and readServiceEnv round-t }); test("readTrayConfig prefers the env file over the JSON config", () => { - const home = mkdtempSync(path.join(tmpdir(), "ompweb-tray-")); + const home = mkdtempSync(path.join(tmpdir(), "tau-tray-")); try { - const agentDir = path.join(home, ".omp", "agent"); + const agentDir = path.join(home, ".pi", "agent"); mkdirSync(agentDir, { recursive: true }); writeFileSync(path.join(agentDir, "web-service.json"), JSON.stringify({ port: 40001, hostname: "0.0.0.0" })); - writeFileSync(path.join(agentDir, "web-service.env"), serializeServiceEnv({ PORT: "40200", OMP_WEB_HOSTNAME: "127.0.0.1" })); + writeFileSync(path.join(agentDir, "web-service.env"), serializeServiceEnv({ PORT: "40200", TAU_HOSTNAME: "127.0.0.1" })); const config = readTrayConfig({}, {}, home); assert.equal(config.port, 40200); @@ -281,7 +281,7 @@ test("readTrayConfig prefers the env file over the JSON config", () => { test("dialog candidates put kdialog first and resolve via override", () => { assert.deepEqual(dialogCandidates(), ["kdialog", "zenity"]); - assert.equal(resolveDialogTool({ OMP_WEB_DIALOG: "definitely-not-on-path-xyz" }), null); + assert.equal(resolveDialogTool({ TAU_DIALOG: "definitely-not-on-path-xyz" }), null); }); test("dialogPrompt returns null on cancel and text on success", async () => { @@ -289,10 +289,10 @@ test("dialogPrompt returns null on cancel and text on success", async () => { if (args.includes("--password")) { throw new Error("cancelled"); } - return { stdout: "30178\n" }; + return { stdout: "30188\n" }; }; const tool = "/usr/bin/kdialog"; - assert.equal(await dialogPrompt({ tool, title: "t", text: "port", value: "1" }, fakeRun), "30178"); + assert.equal(await dialogPrompt({ tool, title: "t", text: "port", value: "1" }, fakeRun), "30188"); assert.equal(await dialogPrompt({ tool, title: "t", text: "pw", password: true }, fakeRun), null); assert.equal(await dialogPrompt({ tool: null, title: "t", text: "x" }, fakeRun), null); }); @@ -318,7 +318,7 @@ test("ensureDbusInstalled reports failure without throwing when the installer fa }); test("tray --start fails gracefully with an install hint when dbus-next is absent (#268)", { skip: dbusIsInstalled() || process.platform !== "linux" }, () => { - const home = mkdtempSync(path.join(tmpdir(), "ompweb-tray-nodbus-")); + const home = mkdtempSync(path.join(tmpdir(), "tau-tray-nodbus-")); try { const script = path.join(path.dirname(fileURLToPath(import.meta.url)), "linux-tray.js"); const res = spawnSync("node", [script, "--start"], { diff --git a/bin/network-addresses.js b/bin/network-addresses.js index 62805f5e..0da3a754 100644 --- a/bin/network-addresses.js +++ b/bin/network-addresses.js @@ -172,7 +172,7 @@ function formatAddressBanner({ const lines = []; lines.push(""); - lines.push(` ${bold("ompweb")} ${dim(`v${version}`)} ${green("is ready")}`); + lines.push(` ${bold("tau")} ${dim(`v${version}`)} ${green("is ready")}`); lines.push(""); const maxLabelLen = Math.max(...entries.map((e) => e.label.length), hint ? 7 : 5); @@ -188,12 +188,12 @@ function formatAddressBanner({ if (passwordEnabled) { lines.push(""); - lines.push(` ${dim("🔒 Password protection enabled (OMP_WEB_PASSWORD_HASH)")}`); + lines.push(` ${dim("🔒 Password protection enabled (TAU_PASSWORD_HASH)")}`); } - if (process.platform === "win32" && !process.env.OMP_WEB_SERVICE) { + if (process.platform === "win32" && !process.env.TAU_SERVICE) { lines.push(""); - lines.push(` ${dim("💡 Windows Tray: Run 'ompweb --install-tray' to enable background startup & Desktop shortcut.")}`); + lines.push(` ${dim("💡 Windows Tray: Run 'tau --install-tray' to enable background startup & Desktop shortcut.")}`); } lines.push(""); diff --git a/bin/node-version-gate.test.mjs b/bin/node-version-gate.test.mjs index 4df38be3..b6871871 100644 --- a/bin/node-version-gate.test.mjs +++ b/bin/node-version-gate.test.mjs @@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url"; const root = fileURLToPath(new URL("..", import.meta.url)); const { bin } = JSON.parse(readFileSync(join(root, "package.json"), "utf8")); // Pretend to be Node 22 before the entry point runs. -const preload = join(mkdtempSync(join(tmpdir(), "ompweb-node-gate-")), "old-node.cjs"); +const preload = join(mkdtempSync(join(tmpdir(), "tau-node-gate-")), "old-node.cjs"); writeFileSync(preload, `Object.defineProperty(process, "versions", { value: { ...process.versions, node: "22.19.0" } });\n`); for (const [name, script] of Object.entries(bin)) { diff --git a/bin/node-version.js b/bin/node-version.js index 8674edcd..a60321df 100644 --- a/bin/node-version.js +++ b/bin/node-version.js @@ -22,7 +22,7 @@ function isNodeVersionSupported(version) { function getUnsupportedNodeVersionMessage(version) { return [ - `ompweb requires Node.js ${MIN_NODE_VERSION} or newer.`, + `tau requires Node.js ${MIN_NODE_VERSION} or newer.`, `Current Node.js version: ${version}.`, "Upgrade Node.js and try again: https://nodejs.org/", ].join("\n"); diff --git a/bin/omp-web-host.js b/bin/omp-web-host.js deleted file mode 100755 index 25c7f8e5..00000000 --- a/bin/omp-web-host.js +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env node -"use strict"; - -// `ompweb host`: link this machine to a main omp-web so sessions can run here (lib/hosts/host-cli.ts). -// ompweb host login --url reads the host token from stdin -// ompweb host [--allow-http] dials the saved server and keeps the link up (http:// is accepted without the flag for loopback) - -// eslint-disable-next-line @typescript-eslint/no-require-imports -require("./node-version").exitIfUnsupportedNode(); - -// The daemon finds its runner from here (lib/omp/omp-cli.ts), not from whatever cwd it was started in. -process.env.OMP_WEB_PACKAGE_DIR ??= module.require("node:path").join(__dirname, ".."); -// eslint-disable-next-line @typescript-eslint/no-require-imports -const jiti = require("jiti").createJiti(__filename); -jiti.import("../lib/hosts/host-cli.ts").then( - ({ runHostCli }) => runHostCli(process.argv.slice(2)).then((code) => process.exit(code)), - (error) => { - console.error(`ompweb host: ${error instanceof Error ? error.message : String(error)}`); - process.exit(1); - }, -); diff --git a/bin/process-lifecycle.js b/bin/process-lifecycle.js index 2124aa30..f12b7232 100644 --- a/bin/process-lifecycle.js +++ b/bin/process-lifecycle.js @@ -9,7 +9,7 @@ const forwardedSignals = ["SIGINT", "SIGTERM"]; // SIGHUP arrives when a CLI-run launcher loses its terminal (window closed, // session ended). The child must die gracefully, not verbatim: a verbatim // SIGHUP terminates Node without running exit handlers, orphaning the detached -// omp children it spawned. Translate it to a graceful SIGTERM tree kill. +// pi children it spawned. Translate it to a graceful SIGTERM tree kill. const translatedSignals = { SIGHUP: "SIGTERM" }; const shutdownTimeoutMs = 5_000; // Time to wait for a terminated process tree to actually exit (used as the diff --git a/bin/service-env.js b/bin/service-env.js index dc0ddfd5..0dab5a86 100644 --- a/bin/service-env.js +++ b/bin/service-env.js @@ -1,7 +1,7 @@ "use strict"; -// Shared systemd EnvironmentFile helpers for the ompweb Linux service. -// Runtime settings live in ~/.omp/agent/web-service.env so changing the +// Shared systemd EnvironmentFile helpers for the tau Linux service. +// Runtime settings live in ~/.pi/agent/web-service.env so changing the // port, bind address, or password does not require regenerating the unit. // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -13,7 +13,7 @@ const path = require("node:path"); function getServiceEnvPath(home = os.homedir()) { const configuredDir = process.env.PI_CODING_AGENT_DIR?.replace(/^~(?=\/|$)/, home); - return path.join(configuredDir || path.join(home, ".omp", "agent"), "web-service.env"); + return path.join(configuredDir || path.join(home, ".pi", "agent"), "web-service.env"); } // Escape a value for a double-quoted systemd env-file assignment. diff --git a/bin/omp-web-hash-password.js b/bin/tau-hash-password.js similarity index 89% rename from bin/omp-web-hash-password.js rename to bin/tau-hash-password.js index 842028f7..29107c4d 100644 --- a/bin/omp-web-hash-password.js +++ b/bin/tau-hash-password.js @@ -1,11 +1,11 @@ "use strict"; -// `ompweb hash-password` plus the password prompt the launcher and the service +// `tau hash-password` plus the password prompt the launcher and the service // installers use. The password is read from stdin, never from argv, so it // stays out of shell history and out of `ps` output (issue #239). // eslint-disable-next-line @typescript-eslint/no-require-imports -const { hashPassword, isPasswordHash } = require("./omp-web-password-hash"); +const { hashPassword, isPasswordHash } = require("./tau-password-hash"); /** Key sent when the user presses Ctrl+C at a prompt. */ const INTERRUPT_KEY = Buffer.from([0x03]); @@ -109,7 +109,7 @@ async function promptPassword(options = {}) { } /** - * `ompweb hash-password`: print the `OMP_WEB_PASSWORD_HASH` value for the + * `tau hash-password`: print the `TAU_PASSWORD_HASH` value for the * password read from stdin. * @returns {Promise} process exit code */ @@ -136,21 +136,21 @@ async function runHashPasswordCommand(options = {}) { /** * Resolve the password hash an installer should write: an existing - * `OMP_WEB_PASSWORD_HASH`, or a plaintext `OMP_WEB_PASSWORD` hashed here. + * `TAU_PASSWORD_HASH`, or a plaintext `TAU_PASSWORD` hashed here. * Reading a plaintext password is allowed on this side only — the hash is what * gets stored, and the plaintext never reaches a service definition or a child * process. Returns null when neither is configured, and throws when a hash was * given but is unusable (silently dropping it would disable auth). */ function resolvePasswordHash(env = process.env) { - const existing = typeof env.OMP_WEB_PASSWORD_HASH === "string" ? env.OMP_WEB_PASSWORD_HASH.trim() : ""; + const existing = typeof env.TAU_PASSWORD_HASH === "string" ? env.TAU_PASSWORD_HASH.trim() : ""; if (existing) { if (!isPasswordHash(existing)) { - throw new Error("OMP_WEB_PASSWORD_HASH is not a valid password hash; generate one with: ompweb hash-password"); + throw new Error("TAU_PASSWORD_HASH is not a valid password hash; generate one with: tau hash-password"); } return existing; } - const plaintext = env.OMP_WEB_PASSWORD; + const plaintext = env.TAU_PASSWORD; return typeof plaintext === "string" && plaintext.length > 0 ? hashPassword(plaintext) : null; } diff --git a/bin/omp-web-hash-password.test.mjs b/bin/tau-hash-password.test.mjs similarity index 90% rename from bin/omp-web-hash-password.test.mjs rename to bin/tau-hash-password.test.mjs index 32a86b60..e0a7b9ae 100644 --- a/bin/omp-web-hash-password.test.mjs +++ b/bin/tau-hash-password.test.mjs @@ -5,8 +5,8 @@ import { fileURLToPath } from "node:url"; import test from "node:test"; const require = createRequire(import.meta.url); -const { verifyPassword } = require("./omp-web-password-hash.js"); -const launcher = fileURLToPath(new URL("./omp-web.js", import.meta.url)); +const { verifyPassword } = require("./tau-password-hash.js"); +const launcher = fileURLToPath(new URL("./tau.js", import.meta.url)); // util-linux `script` gives the command a real terminal, so the prompt runs in raw mode. const hasScript = process.platform === "linux" && spawnSync("script", ["--version"]).status === 0; diff --git a/bin/tau-host.js b/bin/tau-host.js new file mode 100755 index 00000000..387d4d54 --- /dev/null +++ b/bin/tau-host.js @@ -0,0 +1,21 @@ +#!/usr/bin/env node +"use strict"; + +// `tau host`: link this machine to a main tau so sessions can run here (lib/hosts/host-cli.ts). +// tau host login --url reads the host token from stdin +// tau host [--allow-http] dials the saved server and keeps the link up (http:// is accepted without the flag for loopback) + +// eslint-disable-next-line @typescript-eslint/no-require-imports +require("./node-version").exitIfUnsupportedNode(); + +// The daemon finds its runner from here (lib/pi/pi-cli.ts), not from whatever cwd it was started in. +process.env.TAU_PACKAGE_DIR ??= module.require("node:path").join(__dirname, ".."); +// eslint-disable-next-line @typescript-eslint/no-require-imports +const jiti = require("jiti").createJiti(__filename); +jiti.import("../lib/hosts/host-cli.ts").then( + ({ runHostCli }) => runHostCli(process.argv.slice(2)).then((code) => process.exit(code)), + (error) => { + console.error(`tau host: ${error instanceof Error ? error.message : String(error)}`); + process.exit(1); + }, +); diff --git a/bin/omp-web-host.test.mjs b/bin/tau-host.test.mjs similarity index 88% rename from bin/omp-web-host.test.mjs rename to bin/tau-host.test.mjs index 799369b0..59226a2c 100644 --- a/bin/omp-web-host.test.mjs +++ b/bin/tau-host.test.mjs @@ -7,15 +7,15 @@ import test from "node:test"; import { setTimeout as sleep } from "node:timers/promises"; import { fileURLToPath } from "node:url"; -const bin = fileURLToPath(new URL("./omp-web.js", import.meta.url)); +const bin = fileURLToPath(new URL("./tau.js", import.meta.url)); // Windows has no signals: child.kill("SIGTERM") terminates the process outright, so the daemon's handler never runs. -test("SIGTERM to `ompweb host` stops the daemon itself, leaving no orphan", { skip: process.platform === "win32" && "Windows kills on SIGTERM without running handlers" }, async (t) => { - const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-cli-")); +test("SIGTERM to `tau host` stops the daemon itself, leaving no orphan", { skip: process.platform === "win32" && "Windows kills on SIGTERM without running handlers" }, async (t) => { + const scratch = mkdtempSync(join(tmpdir(), "tau-host-cli-")); const agentDir = join(scratch, "agent"); - mkdirSync(join(agentDir, "omp-web"), { recursive: true }); + mkdirSync(join(agentDir, "tau"), { recursive: true }); // Nothing listens on this loopback port: the daemon redials until it is stopped. - writeFileSync(join(agentDir, "omp-web", "host.json"), JSON.stringify({ url: "http://127.0.0.1:9", token: "t" }), { mode: 0o600 }); + writeFileSync(join(agentDir, "tau", "host.json"), JSON.stringify({ url: "http://127.0.0.1:9", token: "t" }), { mode: 0o600 }); const child = spawn("node", [bin, "host"], { env: { ...process.env, HOME: scratch, USERPROFILE: scratch, PI_CODING_AGENT_DIR: agentDir }, stdio: ["ignore", "pipe", "pipe"], @@ -43,9 +43,9 @@ test("SIGTERM to `ompweb host` stops the daemon itself, leaving no orphan", { sk assert.deepEqual(stopped, { code: 0, signal: null }, "the daemon's own stop handled the signal"); }); -/** Run `ompweb host login` with `input` on stdin (left open unless `end`). */ +/** Run `tau host login` with `input` on stdin (left open unless `end`). */ async function login(t, input, { end = true } = {}) { - const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-login-")); + const scratch = mkdtempSync(join(tmpdir(), "tau-host-login-")); const agentDir = join(scratch, "agent"); t.after(() => rmSync(scratch, { recursive: true, force: true })); const child = spawn("node", [bin, "host", "login", "--url", "http://127.0.0.1:9"], { @@ -59,17 +59,17 @@ async function login(t, input, { end = true } = {}) { child.stdin.write(input); if (end) child.stdin.end(); const code = await Promise.race([closed, sleep(10_000, "timeout", { ref: false })]); - const file = join(agentDir, "omp-web", "host.json"); + const file = join(agentDir, "tau", "host.json"); return { code, stderr, saved: existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null }; } -test("`ompweb host login` saves the first stdin line as the token", async (t) => { +test("`tau host login` saves the first stdin line as the token", async (t) => { const { code, saved } = await login(t, " tok-123 \nignored\n"); assert.equal(code, 0); assert.equal(saved?.token, "tok-123"); }); -test("`ompweb host login` refuses a token line over 4096 bytes without waiting for more input", async (t) => { +test("`tau host login` refuses a token line over 4096 bytes without waiting for more input", async (t) => { const { code, stderr, saved } = await login(t, "a".repeat(5000), { end: false }); assert.equal(code, 1); assert.match(stderr, /4096 bytes/); @@ -90,7 +90,7 @@ async function hostCommand(env, ...args) { } function controlFixture(t, { url, longRoot = false } = {}) { - const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-control-cli-")); + const scratch = mkdtempSync(join(tmpdir(), "tau-host-control-cli-")); const agentDir = join(scratch, ...(longRoot ? ["long-agent-directory-".repeat(10), "agent"] : ["agent"])); const omp = join(scratch, "fixture-omp"); writeFileSync(omp, `#!${process.execPath}\nconsole.log("18.0.0-cli-fixture");\n`, { mode: 0o700 }); @@ -98,10 +98,10 @@ function controlFixture(t, { url, longRoot = false } = {}) { ...process.env, HOME: scratch, USERPROFILE: scratch, PI_CODING_AGENT_DIR: agentDir, XDG_CONFIG_HOME: join(scratch, "config"), XDG_DATA_HOME: join(scratch, "data"), XDG_STATE_HOME: join(scratch, "state"), XDG_CACHE_HOME: join(scratch, "cache"), - OMP_WEB_OMP_BIN: omp, OMP_WEB_DISABLE_AUTOUPDATE: "1", + TAU_PI_BIN: omp, TAU_DISABLE_AUTOUPDATE: "1", }; - mkdirSync(join(agentDir, "omp-web"), { recursive: true, mode: 0o700 }); - writeFileSync(join(agentDir, "omp-web", "host.json"), JSON.stringify({ url: url ?? "http://127.0.0.1:9", token: "private-cli-fixture-token" }), { mode: 0o600 }); + mkdirSync(join(agentDir, "tau"), { recursive: true, mode: 0o700 }); + writeFileSync(join(agentDir, "tau", "host.json"), JSON.stringify({ url: url ?? "http://127.0.0.1:9", token: "private-cli-fixture-token" }), { mode: 0o600 }); t.after(() => rmSync(scratch, { recursive: true, force: true })); return { scratch, agentDir, env }; } @@ -220,7 +220,7 @@ test("Windows: status/drain/resume reach the real daemon over its pipe; a duplic test("worker maintenance startup is drained before linking and can be explicitly resumed", async (t) => { const f = controlFixture(t); - const daemon = launchHost(t, { ...f.env, OMP_WEB_HOST_DRAINED: "1" }); + const daemon = launchHost(t, { ...f.env, TAU_HOST_DRAINED: "1" }); if (process.platform !== "win32") { const { hostControlPath } = await import("../lib/hosts/host-control.ts"); t.after(() => rmSync(join(hostControlPath(f.agentDir), ".."), { recursive: true, force: true })); @@ -233,11 +233,11 @@ test("worker maintenance startup is drained before linking and can be explicitly assert.equal(JSON.parse(resumed.stdout).drained, false); }); -test("`ompweb host login --add` and logout change only the selected URL without argv tokens", async (t) => { - const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-multi-login-")); +test("`tau host login --add` and logout change only the selected URL without argv tokens", async (t) => { + const scratch = mkdtempSync(join(tmpdir(), "tau-host-multi-login-")); const agentDir = join(scratch, "agent"); - const file = join(agentDir, "omp-web", "host.json"); - mkdirSync(join(agentDir, "omp-web"), { recursive: true }); + const file = join(agentDir, "tau", "host.json"); + mkdirSync(join(agentDir, "tau"), { recursive: true }); const primary = { url: "https://production.example", token: "production-secret" }; const staging = { url: "http://127.0.0.1:40000", token: "staging-secret" }; writeFileSync(file, JSON.stringify(primary)); diff --git a/bin/omp-web-launchd.js b/bin/tau-launchd.js similarity index 71% rename from bin/omp-web-launchd.js rename to bin/tau-launchd.js index 79cecd8e..8c74796b 100644 --- a/bin/omp-web-launchd.js +++ b/bin/tau-launchd.js @@ -4,11 +4,11 @@ // eslint-disable-next-line @typescript-eslint/no-require-imports require("./node-version").exitIfUnsupportedNode(); -// Install ompweb as a macOS launchd user agent (starts at login, restarts on crash). +// Install tau as a macOS launchd user agent (starts at login, restarts on crash). // -// Usage (installed as the `ompweb-launchd` bin, or run via npx / node directly): -// ompweb-launchd [install [package-spec]|uninstall|status] -// npx -p @kahme247/ompweb@latest ompweb-launchd install +// Usage (installed as the `tau-launchd` bin, or run via npx / node directly): +// tau-launchd [install [package-spec]|uninstall|status] +// npx -p @ompweb-dev/tau@latest tau-launchd install // eslint-disable-next-line @typescript-eslint/no-require-imports const { spawnSync } = require("node:child_process"); @@ -19,15 +19,15 @@ const os = require("node:os"); // eslint-disable-next-line @typescript-eslint/no-require-imports const path = require("node:path"); // eslint-disable-next-line @typescript-eslint/no-require-imports -const { resolvePasswordHash } = require("./omp-web-hash-password"); +const { resolvePasswordHash } = require("./tau-hash-password"); -const LABEL = "com.kahme247.ompweb"; -// The host daemon links this machine to an omp-web (`ompweb host`); it runs next to the web agent. -const HOST_LABEL = "com.kahme247.ompweb-host"; +const LABEL = "dev.ompweb.tau"; +// The host daemon links this machine to an tau (`tau host`); it runs next to the web agent. +const HOST_LABEL = "dev.ompweb.tau-host"; const HOME = os.homedir(); const PLIST = path.join(HOME, "Library", "LaunchAgents", `${LABEL}.plist`); const HOST_PLIST = path.join(HOME, "Library", "LaunchAgents", `${HOST_LABEL}.plist`); -const LOG_DIR = path.join(HOME, "Library", "Logs", "ompweb"); +const LOG_DIR = path.join(HOME, "Library", "Logs", "tau"); const DOMAIN = `gui/${process.getuid?.() ?? 0}`; function fail(message) { @@ -93,11 +93,11 @@ ${envXml} `; } -// The daemon needs the web agent's PATH, omp binary and agent dir (host.json), not its password. -function buildHostEnv({ svcPath, ompBin, agentDir }) { +// The daemon needs the web agent's PATH, pi binary and agent dir (host.json), not its password. +function buildHostEnv({ svcPath, piBin, agentDir }) { return { PATH: svcPath, - ...(ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}), + ...(piBin ? { TAU_PI_BIN: piBin } : {}), ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}), }; } @@ -107,36 +107,36 @@ function install(pkgArg) { const siblingNpx = path.join(path.dirname(nodeBin), "npx"); const npxBin = isExecutableFile(siblingNpx) ? siblingNpx : (which("npx") ?? fail("npx not found on PATH")); - // Only an explicit override: ompweb runs its own omp (ompweb-omp). A stock omp on PATH cannot run its sessions. - const ompBin = process.env.OMP_WEB_OMP_BIN || null; - if (ompBin) { + // An explicit pi for the service; without it the service finds pi on PATH. + const piBin = process.env.TAU_PI_BIN || null; + if (piBin) { try { - fs.accessSync(ompBin, fs.constants.X_OK); + fs.accessSync(piBin, fs.constants.X_OK); } catch { - fail(`OMP_WEB_OMP_BIN=${ompBin} is not executable`); + fail(`TAU_PI_BIN=${piBin} is not executable`); } } - const pkg = pkgArg ?? process.env.OMP_WEB_PKG ?? "@kahme247/ompweb@latest"; - const port = process.env.PORT ?? "30177"; - const hostname = process.env.OMP_WEB_HOSTNAME ?? "127.0.0.1"; - const noOpen = process.env.OMP_WEB_NO_OPEN ?? "1"; - const disableAutoUpdate = process.env.OMP_WEB_DISABLE_AUTOUPDATE; - const installName = process.env.OMP_WEB_NAME; - // Only a hash is stored in the plist: omp-web never forwards a plaintext - // password, and `OMP_WEB_PASSWORD` set for this install is hashed here. + const pkg = pkgArg ?? process.env.TAU_PKG ?? "@ompweb-dev/tau@latest"; + const port = process.env.PORT ?? "30187"; + const hostname = process.env.TAU_HOSTNAME ?? "127.0.0.1"; + const noOpen = process.env.TAU_NO_OPEN ?? "1"; + const disableAutoUpdate = process.env.TAU_DISABLE_AUTOUPDATE; + const installName = process.env.TAU_NAME; + // Only a hash is stored in the plist: tau never forwards a plaintext + // password, and `TAU_PASSWORD` set for this install is hashed here. let passwordHash; try { passwordHash = resolvePasswordHash(); } catch (error) { fail(error instanceof Error ? error.message : String(error)); } - const trustedHeaderDigest = process.env.OMP_WEB_TRUSTED_HEADER_SHA256; + const trustedHeaderDigest = process.env.TAU_TRUSTED_HEADER_SHA256; const agentDir = process.env.PI_CODING_AGENT_DIR?.replace(/^~(?=\/|$)/, HOME); const asdfBin = which("asdf"); const svcPath = [ - ...(ompBin ? [path.dirname(ompBin)] : []), + ...(piBin ? [path.dirname(piBin)] : []), ...(asdfBin ? [path.dirname(asdfBin)] : []), path.dirname(npxBin), path.dirname(nodeBin), @@ -149,21 +149,21 @@ function install(pkgArg) { const env = { PATH: svcPath, PORT: port, - OMP_WEB_HOSTNAME: hostname, - OMP_WEB_NO_OPEN: noOpen, - ...(disableAutoUpdate ? { OMP_WEB_DISABLE_AUTOUPDATE: disableAutoUpdate } : {}), - ...(installName ? { OMP_WEB_NAME: installName } : {}), - ...(passwordHash ? { OMP_WEB_PASSWORD_HASH: passwordHash } : {}), - ...(trustedHeaderDigest ? { OMP_WEB_TRUSTED_HEADER_SHA256: trustedHeaderDigest } : {}), - ...(ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}), + TAU_HOSTNAME: hostname, + TAU_NO_OPEN: noOpen, + ...(disableAutoUpdate ? { TAU_DISABLE_AUTOUPDATE: disableAutoUpdate } : {}), + ...(installName ? { TAU_NAME: installName } : {}), + ...(passwordHash ? { TAU_PASSWORD_HASH: passwordHash } : {}), + ...(trustedHeaderDigest ? { TAU_TRUSTED_HEADER_SHA256: trustedHeaderDigest } : {}), + ...(piBin ? { TAU_PI_BIN: piBin } : {}), ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}), }; - const web = buildPlist({ label: LABEL, args: [npxBin, "--yes", pkg], env, logName: "ompweb" }); + const web = buildPlist({ label: LABEL, args: [npxBin, "--yes", pkg], env, logName: "tau" }); const host = buildPlist({ label: HOST_LABEL, args: [npxBin, "--yes", pkg, "host"], - env: buildHostEnv({ svcPath, ompBin, agentDir }), - logName: "ompweb-host", + env: buildHostEnv({ svcPath, piBin, agentDir }), + logName: "tau-host", // host.json does not exist until the web server first starts; the daemon exits until then. throttleInterval: 10, }); @@ -171,7 +171,7 @@ function install(pkgArg) { fs.mkdirSync(LOG_DIR, { recursive: true }); fs.mkdirSync(path.dirname(PLIST), { recursive: true }); for (const [file, xml, label] of [[PLIST, web, LABEL], [HOST_PLIST, host, HOST_LABEL]]) { - // Reloading the daemon ends every omp run on this machine: leave it alone when nothing changed. + // Reloading the daemon ends every pi run on this machine: leave it alone when nothing changed. const unchanged = label === HOST_LABEL && fs.existsSync(file) && fs.readFileSync(file, "utf8") === xml; if (unchanged && spawnSync("launchctl", ["print", `${DOMAIN}/${label}`], { stdio: "ignore" }).status === 0) continue; fs.writeFileSync(file, xml, { mode: 0o600 }); @@ -184,7 +184,7 @@ function install(pkgArg) { console.log(`installed: ${HOST_PLIST}`); console.log(`package: ${pkg} (via npx --yes)`); console.log(`url: http://${hostname}:${port}`); - console.log(`logs: ${path.join(LOG_DIR, "ompweb.log")}, ${path.join(LOG_DIR, "ompweb-host.log")}`); + console.log(`logs: ${path.join(LOG_DIR, "tau.log")}, ${path.join(LOG_DIR, "tau-host.log")}`); if (passwordHash) console.log("note: the password hash is stored in the plist (mode 600)"); } @@ -220,7 +220,7 @@ function main() { else if (command === "uninstall") uninstall(); else if (command === "status") status(); else { - console.error("usage: ompweb-launchd [install [package-spec]|uninstall|status]"); + console.error("usage: tau-launchd [install [package-spec]|uninstall|status]"); process.exit(2); } } diff --git a/bin/omp-web-launchd.test.mjs b/bin/tau-launchd.test.mjs similarity index 58% rename from bin/omp-web-launchd.test.mjs rename to bin/tau-launchd.test.mjs index f780eeee..58470e21 100644 --- a/bin/omp-web-launchd.test.mjs +++ b/bin/tau-launchd.test.mjs @@ -3,29 +3,29 @@ import { createRequire } from "node:module"; import test from "node:test"; const require = createRequire(import.meta.url); -const { HOST_LABEL, LABEL, buildHostEnv, buildPlist } = require("./omp-web-launchd.js"); +const { HOST_LABEL, LABEL, buildHostEnv, buildPlist } = require("./tau-launchd.js"); const env = { PATH: "/usr/bin", PI_CODING_AGENT_DIR: "/Users/u/agent" }; -test("the host daemon plist runs `ompweb host`, restarts with KeepAlive, and is throttled", () => { +test("the host daemon plist runs `tau host`, restarts with KeepAlive, and is throttled", () => { const plist = buildPlist({ label: HOST_LABEL, - args: ["/usr/local/bin/npx", "--yes", "@kahme247/ompweb@latest", "host"], + args: ["/usr/local/bin/npx", "--yes", "@ompweb-dev/tau@latest", "host"], env, - logName: "ompweb-host", + logName: "tau-host", throttleInterval: 10, }); - assert.equal(HOST_LABEL, "com.kahme247.ompweb-host"); - assert.match(plist, /Label<\/key>com\.kahme247\.ompweb-host<\/string>/); - assert.match(plist, /@kahme247\/ompweb@latest<\/string>\n host<\/string>\n <\/array>/); + assert.equal(HOST_LABEL, "dev.ompweb.tau-host"); + assert.match(plist, /Label<\/key>dev\.ompweb\.tau-host<\/string>/); + assert.match(plist, /@ompweb-dev\/tau@latest<\/string>\n host<\/string>\n <\/array>/); assert.match(plist, /KeepAlive<\/key>/); assert.match(plist, /ThrottleInterval<\/key>10<\/integer>/); assert.match(plist, /PI_CODING_AGENT_DIR<\/key>\/Users\/u\/agent<\/string>/); - assert.match(plist, /ompweb-host\.log<\/string>/); + assert.match(plist, /tau-host\.log<\/string>/); }); test("the web plist keeps its arguments and has no throttle", () => { - const plist = buildPlist({ label: LABEL, args: ["/usr/local/bin/npx", "--yes", "pkg & co"], env, logName: "ompweb" }); + const plist = buildPlist({ label: LABEL, args: ["/usr/local/bin/npx", "--yes", "pkg & co"], env, logName: "tau" }); assert.match(plist, /pkg & co<\/string>\n <\/array>/); assert.match(plist, /KeepAlive<\/key>/); assert.doesNotMatch(plist, /ThrottleInterval/); @@ -33,7 +33,7 @@ test("the web plist keeps its arguments and has no throttle", () => { }); test("the host env carries PATH, the omp binary and the agent dir, but no web settings", () => { - const all = buildHostEnv({ svcPath: "/usr/bin", ompBin: "/opt/omp/bin/omp", agentDir: "/Users/u/agent" }); - assert.deepEqual(all, { PATH: "/usr/bin", OMP_WEB_OMP_BIN: "/opt/omp/bin/omp", PI_CODING_AGENT_DIR: "/Users/u/agent" }); + const all = buildHostEnv({ svcPath: "/usr/bin", piBin: "/opt/omp/bin/omp", agentDir: "/Users/u/agent" }); + assert.deepEqual(all, { PATH: "/usr/bin", TAU_PI_BIN: "/opt/omp/bin/omp", PI_CODING_AGENT_DIR: "/Users/u/agent" }); assert.deepEqual(buildHostEnv({ svcPath: "/usr/bin" }), { PATH: "/usr/bin" }); }); diff --git a/bin/omp-web-options.js b/bin/tau-options.js similarity index 66% rename from bin/omp-web-options.js rename to bin/tau-options.js index af13f322..40cd49bc 100644 --- a/bin/omp-web-options.js +++ b/bin/tau-options.js @@ -3,7 +3,7 @@ // eslint-disable-next-line @typescript-eslint/no-require-imports const { parseArgs } = require("util"); // eslint-disable-next-line @typescript-eslint/no-require-imports -const { hashPassword, isPasswordHash } = require("./omp-web-password-hash"); +const { hashPassword, isPasswordHash } = require("./tau-password-hash"); // eslint-disable-next-line @typescript-eslint/no-require-imports const { isLoopbackHost } = require("./network-addresses"); // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -15,7 +15,7 @@ function isEnabled(value) { return typeof value === "string" && TRUE_VALUES.has(value.trim().toLowerCase()); } -/** Legacy plaintext credential: detected so `ompweb` can migrate (env) or refuse (flag) it. */ +/** Legacy plaintext credential: detected so `tau` can migrate (env) or refuse (flag) it. */ function legacyPassword(args, env) { const flagIndex = args.findIndex((arg) => arg === "--password" || arg.startsWith("--password=")); if (flagIndex !== -1) { @@ -24,17 +24,17 @@ function legacyPassword(args, env) { const value = inline !== undefined ? inline : (args[flagIndex + 1] ?? ""); return { value, source: "flag" }; } - const fromEnv = env.OMP_WEB_PASSWORD; + const fromEnv = env.TAU_PASSWORD; if (typeof fromEnv === "string" && fromEnv.length > 0) return { value: fromEnv, source: "env" }; return undefined; } function printHelp() { - console.log(`Usage: ompweb [options] + console.log(`Usage: tau [options] Options: - -p, --port Server port (default 30177, env PORT) - -H, --hostname Bind hostname (default 127.0.0.1, env OMP_WEB_HOSTNAME) + -p, --port Server port (default 30187, env PORT) + -H, --hostname Bind hostname (default 127.0.0.1, env TAU_HOSTNAME) --no-open Do not open the browser automatically --install-tray Install system tray service & shortcuts (Windows tray / Linux SNI tray) --uninstall-tray Uninstall system tray service & shortcuts @@ -44,16 +44,16 @@ Options: Commands: hash-password Read a password from stdin and print the value for - OMP_WEB_PASSWORD_HASH + TAU_PASSWORD_HASH Password: - ompweb hash-password # prompts, input hidden - echo "a-long-random-password" | ompweb hash-password - OMP_WEB_PASSWORD_HASH='scrypt$15$8$1$...' ompweb + tau hash-password # prompts, input hidden + echo "a-long-random-password" | tau hash-password + TAU_PASSWORD_HASH='scrypt$15$8$1$...' tau - ompweb never passes a plaintext password on: --password is rejected, and an - OMP_WEB_PASSWORD is hashed at startup with a warning that prints its hash - (set alongside OMP_WEB_PASSWORD_HASH, it is rejected), because every omp + tau never passes a plaintext password on: --password is rejected, and an + TAU_PASSWORD is hashed at startup with a warning that prints its hash + (set alongside TAU_PASSWORD_HASH, it is rejected), because every pi session inherits the environment and an agent could print the password into its transcript. @@ -85,17 +85,17 @@ function parseLaunchOptions(args = process.argv.slice(2), env = process.env) { strict: false, }); - const passwordHash = typeof env.OMP_WEB_PASSWORD_HASH === "string" ? env.OMP_WEB_PASSWORD_HASH.trim() : undefined; + const passwordHash = typeof env.TAU_PASSWORD_HASH === "string" ? env.TAU_PASSWORD_HASH.trim() : undefined; const legacy = legacyPassword(args, env); - const port = String(cliArgs.port ?? env.PORT ?? "30177"); + const port = String(cliArgs.port ?? env.PORT ?? "30187"); const shared = { port, - hostname: cliArgs.hostname ?? env.OMP_WEB_HOSTNAME ?? "127.0.0.1", + hostname: cliArgs.hostname ?? env.TAU_HOSTNAME ?? "127.0.0.1", passwordHash, legacyPassword: legacy?.value, legacyPasswordSource: legacy?.source, - openBrowser: !cliArgs["no-open"] && !isEnabled(env.OMP_WEB_NO_OPEN), + openBrowser: !cliArgs["no-open"] && !isEnabled(env.TAU_NO_OPEN), installTray: Boolean(cliArgs["install-tray"] || cliArgs["install-service"]), uninstallTray: Boolean(cliArgs["uninstall-tray"]), tray: Boolean(cliArgs.tray), @@ -110,7 +110,7 @@ function parseLaunchOptions(args = process.argv.slice(2), env = process.env) { } catch { console.log("0.0.0"); } return { ...shared, version: true }; } - // Expose help flag without exiting here — caller (bin/omp-web.js) decides + // Expose help flag without exiting here — caller (bin/tau.js) decides // whether to exit, keeping parseLaunchOptions testable. Print here so // --help works even when the caller is a test. if (cliArgs.help) { @@ -121,8 +121,8 @@ function parseLaunchOptions(args = process.argv.slice(2), env = process.env) { } /** - * The password and bind checks before a server starts (bin/omp-web.js, server/binary.ts). Only a password hash reaches - * the server (issue #239): a plaintext OMP_WEB_PASSWORD alone is migrated, hashed into OMP_WEB_PASSWORD_HASH and + * The password and bind checks before a server starts (bin/tau.js, server/binary.ts). Only a password hash reaches + * the server (issue #239): a plaintext TAU_PASSWORD alone is migrated, hashed into TAU_PASSWORD_HASH and * removed from process.env before any child can inherit it. The removed --password flag, a plaintext set next to a * hash, an invalid hash, or a non-loopback bind without a password print why and exit 1. * @returns {string | undefined} the password hash, if any @@ -130,59 +130,59 @@ function parseLaunchOptions(args = process.argv.slice(2), env = process.env) { function checkLaunchSecurity(launchOptions) { let passwordHash = launchOptions.passwordHash; if (launchOptions.legacyPasswordSource === "env" && !passwordHash) { - passwordHash = hashPassword(process.env.OMP_WEB_PASSWORD); - process.env.OMP_WEB_PASSWORD_HASH = passwordHash; - delete process.env.OMP_WEB_PASSWORD; + passwordHash = hashPassword(process.env.TAU_PASSWORD); + process.env.TAU_PASSWORD_HASH = passwordHash; + delete process.env.TAU_PASSWORD; console.warn([ - "Warning: OMP_WEB_PASSWORD holds a plaintext password. This option has been deprecated and is marked for removal.", + "Warning: TAU_PASSWORD holds a plaintext password. This option has been deprecated and is marked for removal.", "", - "Every omp session inherits omp-web's environment, so an agent could print", - "the password into its transcript. ompweb hashed it and kept it out of the", + "Every pi session inherits tau's environment, so an agent could print", + "the password into its transcript. tau hashed it and kept it out of the", "server's environment, but agents can still read it from this launcher", "process, and a new hash is made on every start, which signs every browser", "out on each restart.", "", - "Remove OMP_WEB_PASSWORD and set this instead:", + "Remove TAU_PASSWORD and set this instead:", "", - ` OMP_WEB_PASSWORD_HASH='${passwordHash}'`, + ` TAU_PASSWORD_HASH='${passwordHash}'`, ].join("\n")); } else if (launchOptions.legacyPasswordSource === "env") { - console.error("OMP_WEB_PASSWORD_HASH and the plaintext OMP_WEB_PASSWORD are both set. Remove OMP_WEB_PASSWORD."); + console.error("TAU_PASSWORD_HASH and the plaintext TAU_PASSWORD are both set. Remove TAU_PASSWORD."); process.exit(1); } else if (launchOptions.legacyPassword !== undefined) { console.error([ - "ompweb no longer accepts a plaintext password: the --password flag was removed.", - "Every omp session inherits this process's environment, so an agent could", + "tau no longer accepts a plaintext password: the --password flag was removed.", + "Every pi session inherits this process's environment, so an agent could", "print the password into its transcript.", "", "Create a hash and use that instead:", "", - " ompweb hash-password", - " OMP_WEB_PASSWORD_HASH='scrypt$...' ompweb", + " tau hash-password", + " TAU_PASSWORD_HASH='scrypt$...' tau", ].join("\n")); process.exit(1); } if (passwordHash !== undefined && !isPasswordHash(passwordHash)) { - console.error(`OMP_WEB_PASSWORD_HASH is not a valid password hash.\n\nGenerate one with: ompweb hash-password`); + console.error(`TAU_PASSWORD_HASH is not a valid password hash.\n\nGenerate one with: tau hash-password`); process.exit(1); } const { hostname } = launchOptions; if (!isLoopbackHost(hostname)) { if (passwordHash === undefined) { - console.error(`Refusing to listen on ${hostname} without a password hash. Run: ompweb hash-password, then set OMP_WEB_PASSWORD_HASH. Or bind to 127.0.0.1.`); + console.error(`Refusing to listen on ${hostname} without a password hash. Run: tau hash-password, then set TAU_PASSWORD_HASH. Or bind to 127.0.0.1.`); process.exit(1); } - console.warn(`Warning: ompweb is listening on ${hostname} over HTTP. Use HTTPS or a trusted VPN to protect the password and session cookie in transit.`); + console.warn(`Warning: tau is listening on ${hostname} over HTTP. Use HTTPS or a trusted VPN to protect the password and session cookie in transit.`); } return passwordHash; } // The server must not start inside the installation: on Windows a live process whose working // directory is the package blocks the rename an in-place update performs -// (ERROR_SHARING_VIOLATION). The entry point and OMP_WEB_PACKAGE_DIR are absolute, so the +// (ERROR_SHARING_VIOLATION). The entry point and TAU_PACKAGE_DIR are absolute, so the // server does not need the installation as its directory. function serverWorkingDirectory(home = os.homedir()) { - if (!home) throw new Error("Cannot start ompweb: the home directory is empty, and the server must not run inside its installation."); + if (!home) throw new Error("Cannot start tau: the home directory is empty, and the server must not run inside its installation."); return home; } diff --git a/bin/omp-web-password-hash.js b/bin/tau-password-hash.js similarity index 96% rename from bin/omp-web-password-hash.js rename to bin/tau-password-hash.js index 54a18048..ab0b1ec0 100644 --- a/bin/omp-web-password-hash.js +++ b/bin/tau-password-hash.js @@ -1,8 +1,8 @@ "use strict"; -// The `OMP_WEB_PASSWORD_HASH` format, in one place. This file must stay plain +// The `TAU_PASSWORD_HASH` format, in one place. This file must stay plain // CJS JS with no dependencies beyond node:crypto: the packaged launcher -// (bin/omp-web.js) validates and hashes before the server exists, lib/web-password-hash.ts +// (bin/tau.js) validates and hashes before the server exists, lib/web-password-hash.ts // is the typed view of it for the server, and the service installers hash the // password they write. See issue #239. diff --git a/bin/omp-web-security.test.mjs b/bin/tau-security.test.mjs similarity index 72% rename from bin/omp-web-security.test.mjs rename to bin/tau-security.test.mjs index 8c623ed1..24eed356 100644 --- a/bin/omp-web-security.test.mjs +++ b/bin/tau-security.test.mjs @@ -8,12 +8,12 @@ import { fileURLToPath } from "node:url"; import test from "node:test"; const require = createRequire(import.meta.url); -const { verifyPassword } = require("./omp-web-password-hash.js"); +const { verifyPassword } = require("./tau-password-hash.js"); const binDir = fileURLToPath(new URL(".", import.meta.url)); /** Run the launcher against a stub `server/main.ts` that records the environment it was started with. */ async function launch(env, args = []) { - const pkg = await mkdtemp(join(tmpdir(), "ompweb-launch-")); + const pkg = await mkdtemp(join(tmpdir(), "tau-launch-")); try { await mkdir(join(pkg, "bin")); for (const name of await readdir(binDir)) { @@ -26,7 +26,7 @@ async function launch(env, args = []) { // The package has no bun dependency, so the launcher runs this under the Bun on PATH: this test's own, // as on Windows npm puts only a bun.cmd shim there, which a spawn without a shell cannot run. await writeFile(join(pkg, "server", "main.ts"), `require("fs").writeFileSync(${JSON.stringify(dump)}, JSON.stringify(process.env));`); - const result = spawnSync("node", [join(pkg, "bin", "omp-web.js"), "--no-open", "-p", "0", ...args], { + const result = spawnSync("node", [join(pkg, "bin", "tau.js"), "--no-open", "-p", "0", ...args], { env: { PATH: [dirname(process.execPath), process.env.PATH].join(delimiter), HOME: pkg, ...env }, encoding: "utf8", timeout: 20_000, @@ -45,19 +45,19 @@ test("launcher refuses unauthenticated non-loopback binds", async () => { assert.equal(serverEnv, null); }); -test("launcher hands the server a hash of a plaintext OMP_WEB_PASSWORD, never the plaintext", async () => { - const { stderr, serverEnv } = await launch({ OMP_WEB_PASSWORD: "s3cret pw" }); +test("launcher hands the server a hash of a plaintext TAU_PASSWORD, never the plaintext", async () => { + const { stderr, serverEnv } = await launch({ TAU_PASSWORD: "s3cret pw" }); assert.ok(serverEnv, stderr); - assert.equal(serverEnv.OMP_WEB_PASSWORD, undefined); - const hash = serverEnv.OMP_WEB_PASSWORD_HASH; + assert.equal(serverEnv.TAU_PASSWORD, undefined); + const hash = serverEnv.TAU_PASSWORD_HASH; assert.equal(verifyPassword("s3cret pw", hash), true); - assert.ok(stderr.includes(`OMP_WEB_PASSWORD_HASH='${hash}'`), stderr); + assert.ok(stderr.includes(`TAU_PASSWORD_HASH='${hash}'`), stderr); assert.ok(!stderr.includes("s3cret pw"), stderr); }); -test("launcher refuses a plaintext OMP_WEB_PASSWORD next to a hash", async () => { - const { hashPassword } = require("./omp-web-password-hash.js"); - const { status, serverEnv } = await launch({ OMP_WEB_PASSWORD: "s3cret pw", OMP_WEB_PASSWORD_HASH: hashPassword("other") }); +test("launcher refuses a plaintext TAU_PASSWORD next to a hash", async () => { + const { hashPassword } = require("./tau-password-hash.js"); + const { status, serverEnv } = await launch({ TAU_PASSWORD: "s3cret pw", TAU_PASSWORD_HASH: hashPassword("other") }); assert.equal(status, 1); assert.equal(serverEnv, null); }); diff --git a/bin/omp-web-systemd.js b/bin/tau-systemd.js similarity index 78% rename from bin/omp-web-systemd.js rename to bin/tau-systemd.js index 7f7afd79..aed9c7f1 100644 --- a/bin/omp-web-systemd.js +++ b/bin/tau-systemd.js @@ -4,14 +4,14 @@ // eslint-disable-next-line @typescript-eslint/no-require-imports require("./node-version").exitIfUnsupportedNode(); -// Install ompweb as a Linux systemd user service. +// Install tau as a Linux systemd user service. // // Usage: -// ompweb-systemd [install|uninstall|start|stop|restart|status|open] -// npx --yes --package=@kahme247/ompweb@latest ompweb-systemd install +// tau-systemd [install|uninstall|start|stop|restart|status|open] +// npx --yes --package=@ompweb-dev/tau@latest tau-systemd install // -// `install` creates ~/.omp/agent/web-service.env. The file is deliberately -// separate from the unit so port, hostname, password, and omp path can be +// `install` creates ~/.pi/agent/web-service.env. The file is deliberately +// separate from the unit so port, hostname, password, and pi path can be // edited without reinstalling the service. // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -27,24 +27,24 @@ const path = require("node:path"); // eslint-disable-next-line @typescript-eslint/no-require-imports const { getServiceEnvPath, readServiceEnv, writeServiceEnv } = require("./service-env"); // eslint-disable-next-line @typescript-eslint/no-require-imports -const { resolvePasswordHash } = require("./omp-web-hash-password"); +const { resolvePasswordHash } = require("./tau-hash-password"); -const UNIT_NAME = "ompweb"; +const UNIT_NAME = "tau"; const UNIT = `${UNIT_NAME}.service`; const HOME = os.homedir(); const UNIT_DIR = path.join(HOME, ".config", "systemd", "user"); const UNIT_PATH = path.join(UNIT_DIR, UNIT); -// The host daemon links this machine to an omp-web (`ompweb host`); it runs next to the web unit. -const HOST_UNIT_NAME = "ompweb-host"; +// The host daemon links this machine to an tau (`tau host`); it runs next to the web unit. +const HOST_UNIT_NAME = "tau-host"; const HOST_UNIT = `${HOST_UNIT_NAME}.service`; const HOST_UNIT_PATH = path.join(UNIT_DIR, HOST_UNIT); const UNITS = [UNIT, HOST_UNIT]; const ENV_PATH = getServiceEnvPath(); -const DEFAULT_PORT = "30177"; +const DEFAULT_PORT = "30187"; const DEFAULT_HOSTNAME = "127.0.0.1"; function printHelp() { - console.log(`Usage: ompweb-systemd [command] [options] + console.log(`Usage: tau-systemd [command] [options] Commands: install Install the web and host-daemon user services, create the env file, and enable them @@ -58,7 +58,7 @@ Commands: Options: -p, --port Server port (default ${DEFAULT_PORT}, env PORT) - -H, --hostname Bind address (default ${DEFAULT_HOSTNAME}, env OMP_WEB_HOSTNAME) + -H, --hostname Bind address (default ${DEFAULT_HOSTNAME}, env TAU_HOSTNAME) --no-autostart Install and start, but do not enable at login --clean-config Also remove web-service.env on uninstall --json Output status as JSON @@ -66,7 +66,7 @@ Options: -v, --version Show version For LAN access, install with: - OMP_WEB_HOSTNAME=0.0.0.0 OMP_WEB_PASSWORD='change-me' ompweb-systemd install + TAU_HOSTNAME=0.0.0.0 TAU_PASSWORD='change-me' tau-systemd install (the plaintext password is hashed before it is written to the env file) `); } @@ -93,11 +93,11 @@ function which(name, env = process.env) { } // Read the interpreter of a launcher script (e.g. `#!/usr/bin/env bun`). -// Bun/npm global installs of omp are scripts that need their interpreter on +// npm global installs of pi are scripts that need their interpreter on // PATH at service runtime; the generated unit must include its directory // (issue #116). Returns the raw interpreter token (e.g. `bun` or // `/opt/bun/bin/bun`), or null when the file is a native binary, -// unreadable, or has no shebang. Symlinks are resolved first: the `omp` on +// unreadable, or has no shebang. Symlinks are resolved first: the `pi` on // PATH is usually a link to the real launcher. function readLauncherInterpreter(binPath) { let target = binPath; @@ -198,21 +198,21 @@ function formatExecStart(value) { return /\s/.test(String(value)) ? `"${escaped}"` : escaped; } -// Resolve the ompweb binary the unit will run. An explicit override wins, +// Resolve the tau binary the unit will run. An explicit override wins, // followed by the sibling of node (npm/bun global installs), then PATH. -function resolveOmpwebBin(env = process.env) { - const override = env.OMP_WEB_SYSTEMD_BIN; +function resolveTauBin(env = process.env) { + const override = env.TAU_SYSTEMD_BIN; if (override) { - if (!isExecutableFile(override)) throw new Error(`OMP_WEB_SYSTEMD_BIN=${override} is not executable`); + if (!isExecutableFile(override)) throw new Error(`TAU_SYSTEMD_BIN=${override} is not executable`); return override; } - const sibling = path.join(path.dirname(process.execPath), "ompweb"); + const sibling = path.join(path.dirname(process.execPath), "tau"); if (isExecutableFile(sibling)) return sibling; - const onPath = which("ompweb", env); + const onPath = which("tau", env); if (onPath) return onPath; - throw new Error("ompweb binary not found (next to node or on PATH); set OMP_WEB_SYSTEMD_BIN"); + throw new Error("tau binary not found (next to node or on PATH); set TAU_SYSTEMD_BIN"); } function validatePort(value) { const port = Number(value); @@ -231,17 +231,17 @@ function validateHostname(value) { // Build the unit file text. Runtime settings belong in EnvironmentFile so the // tray or an editor can change them without reinstalling the unit. The web and // host units share the env file: same user, same HOME and PI_CODING_AGENT_DIR, -// so both read the same /omp-web/host.json. -function buildUnitText({ description, execArgs, restart, ompwebBin, env: extraEnv, home, envPath }) { - const ompBin = extraEnv.OMP_WEB_OMP_BIN ?? null; - const interpreterDir = ompBin ? launcherInterpreterDir(ompBin) : null; +// so both read the same /tau/host.json. +function buildUnitText({ description, execArgs, restart, tauBin, env: extraEnv, home, envPath }) { + const piBin = extraEnv.TAU_PI_BIN ?? null; + const interpreterDir = piBin ? launcherInterpreterDir(piBin) : null; const pathDirs = [ - ...(ompBin ? [path.dirname(ompBin)] : []), - // Launcher scripts (e.g. Bun/npm global installs of omp) run through an + ...(piBin ? [path.dirname(piBin)] : []), + // Launcher scripts (e.g. npm global installs of pi) run through an // interpreter resolved via `env`; without its directory the service // fails with exit 127 even though the binary itself is on PATH (#116). ...(interpreterDir ? [interpreterDir] : []), - path.dirname(ompwebBin), + path.dirname(tauBin), path.dirname(process.execPath), path.join(home, ".local", "bin"), "/usr/local/bin", @@ -249,7 +249,7 @@ function buildUnitText({ description, execArgs, restart, ompwebBin, env: extraEn "/bin", ].filter((dir, index, all) => all.indexOf(dir) === index); - return `# Generated by ompweb-systemd — edits are overwritten on reinstall. + return `# Generated by tau-systemd — edits are overwritten on reinstall. [Unit] Description=${description} Documentation=${readPackageHomepage()} @@ -259,7 +259,7 @@ ${restart.startLimit} [Service] Type=simple WorkingDirectory=%h -ExecStart=${formatExecStart(ompwebBin)}${execArgs} +ExecStart=${formatExecStart(tauBin)}${execArgs} Environment=${environmentLine([["PATH", pathDirs.join(path.delimiter)]])} EnvironmentFile=${escapeUnitPath(envPath)} Restart=${restart.policy} @@ -270,12 +270,12 @@ WantedBy=default.target `; } -function buildUnit({ ompwebBin, env = {}, home = HOME, envPath = getServiceEnvPath(home) }) { +function buildUnit({ tauBin, env = {}, home = HOME, envPath = getServiceEnvPath(home) }) { return buildUnitText({ - description: "ompweb web service (oh-my-pi web UI)", + description: "tau web service (oh-my-pi web UI)", execArgs: "", restart: { policy: "on-failure", delay: 3, startLimit: "StartLimitIntervalSec=60\nStartLimitBurst=5\n" }, - ompwebBin, env, home, envPath, + tauBin, env, home, envPath, }); } @@ -283,12 +283,12 @@ function buildUnit({ ompwebBin, env = {}, home = HOME, envPath = getServiceEnvPa // server writes it at startup) and when the server revokes or outdates its // token. Restart=always with a 10 s delay covers all of those, and // StartLimitIntervalSec=0 keeps systemd from giving up while it waits. -function buildHostUnit({ ompwebBin, env = {}, home = HOME, envPath = getServiceEnvPath(home) }) { +function buildHostUnit({ tauBin, env = {}, home = HOME, envPath = getServiceEnvPath(home) }) { return buildUnitText({ - description: "ompweb host daemon (links this machine to an ompweb server)", + description: "tau host daemon (links this machine to an tau server)", execArgs: " host", restart: { policy: "always", delay: 10, startLimit: "StartLimitIntervalSec=0\n" }, - ompwebBin, env, home, envPath, + tauBin, env, home, envPath, }); } @@ -313,31 +313,31 @@ function systemdQuery(args) { } function install(options = {}) { - let ompwebBin; + let tauBin; try { - ompwebBin = resolveOmpwebBin(); + tauBin = resolveTauBin(); } catch (error) { fail(error instanceof Error ? error.message : String(error)); } - // Only an explicit override: ompweb runs its own omp (ompweb-omp). A stock omp on PATH cannot run its sessions. - const ompBin = process.env.OMP_WEB_OMP_BIN || null; - if (ompBin && !isExecutableFile(ompBin)) fail(`OMP_WEB_OMP_BIN=${ompBin} is not executable`); + // An explicit pi for the service; without it the service finds pi on PATH. + const piBin = process.env.TAU_PI_BIN || null; + if (piBin && !isExecutableFile(piBin)) fail(`TAU_PI_BIN=${piBin} is not executable`); // Note: the missing-interpreter check lives in runCli (before the Linux // gate) so it fails loudly on every platform; install() only reuses the - // resolved ompBin for the unit + env file. + // resolved piBin for the unit + env file. let port; let hostname; try { port = validatePort(options.port ?? process.env.PORT ?? DEFAULT_PORT); - hostname = validateHostname(options.hostname ?? process.env.OMP_WEB_HOSTNAME ?? DEFAULT_HOSTNAME); + hostname = validateHostname(options.hostname ?? process.env.TAU_HOSTNAME ?? DEFAULT_HOSTNAME); } catch (error) { fail(error instanceof Error ? error.message : String(error)); } - // Only the hash reaches the env file: omp-web never forwards a plaintext - // password, and `OMP_WEB_PASSWORD` set for this install is hashed here. + // Only the hash reaches the env file: tau never forwards a plaintext + // password, and `TAU_PASSWORD` set for this install is hashed here. let passwordHash; try { passwordHash = resolvePasswordHash(); @@ -347,8 +347,8 @@ function install(options = {}) { const agentDir = process.env.PI_CODING_AGENT_DIR?.replace(/^~(?=\/|$)/, HOME); const envPath = getServiceEnvPath(); const unitOptions = { - ompwebBin, - env: ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}, + tauBin, + env: piBin ? { TAU_PI_BIN: piBin } : {}, home: HOME, envPath, }; @@ -357,18 +357,18 @@ function install(options = {}) { // read by systemd on every start/restart, and is safe to edit by hand. writeServiceEnv({ PORT: port, - OMP_WEB_HOSTNAME: hostname, - OMP_WEB_NO_OPEN: process.env.OMP_WEB_NO_OPEN ?? "1", - ...(process.env.OMP_WEB_DISABLE_AUTOUPDATE ? { OMP_WEB_DISABLE_AUTOUPDATE: process.env.OMP_WEB_DISABLE_AUTOUPDATE } : {}), - ...(process.env.OMP_WEB_NAME ? { OMP_WEB_NAME: process.env.OMP_WEB_NAME } : {}), - ...(passwordHash ? { OMP_WEB_PASSWORD_HASH: passwordHash } : {}), - ...(process.env.OMP_WEB_TRUSTED_HEADER_SHA256 ? { OMP_WEB_TRUSTED_HEADER_SHA256: process.env.OMP_WEB_TRUSTED_HEADER_SHA256 } : {}), - ...(ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}), + TAU_HOSTNAME: hostname, + TAU_NO_OPEN: process.env.TAU_NO_OPEN ?? "1", + ...(process.env.TAU_DISABLE_AUTOUPDATE ? { TAU_DISABLE_AUTOUPDATE: process.env.TAU_DISABLE_AUTOUPDATE } : {}), + ...(process.env.TAU_NAME ? { TAU_NAME: process.env.TAU_NAME } : {}), + ...(passwordHash ? { TAU_PASSWORD_HASH: passwordHash } : {}), + ...(process.env.TAU_TRUSTED_HEADER_SHA256 ? { TAU_TRUSTED_HEADER_SHA256: process.env.TAU_TRUSTED_HEADER_SHA256 } : {}), + ...(piBin ? { TAU_PI_BIN: piBin } : {}), ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}), }, envPath); const wasActive = Object.fromEntries(UNITS.map((unit) => [unit, systemdQuery(["is-active", "--quiet", unit]).ok])); - // Restarting the daemon ends every omp run on this machine: only do it when its unit changed. + // Restarting the daemon ends every pi run on this machine: only do it when its unit changed. const hostUnitText = buildHostUnit(unitOptions); const hostUnitChanged = readFileOrNull(HOST_UNIT_PATH) !== hostUnitText; fs.mkdirSync(UNIT_DIR, { recursive: true }); @@ -385,7 +385,7 @@ function install(options = {}) { console.log(`installed: ${UNIT_PATH}`); console.log(`installed: ${HOST_UNIT_PATH}`); - console.log(`binary: ${ompwebBin}`); + console.log(`binary: ${tauBin}`); console.log(`config: ${envPath} (port/hostname/password — no reinstall needed)`); console.log(`url: http://${hostname}:${port}`); console.log(`logs: journalctl --user -u ${UNIT_NAME} -u ${HOST_UNIT_NAME} -f`); @@ -400,9 +400,6 @@ function uninstall(options = {}) { fs.rmSync(HOST_UNIT_PATH, { force: true }); systemctl(["daemon-reload"], { ignoreFailure: true }); if (options.cleanConfig) { - const legacyConfig = path.join(HOME, ".omp", "agent", "web-service.json"); - fs.rmSync(legacyConfig, { force: true }); - console.log(`removed: ${legacyConfig}`); fs.rmSync(ENV_PATH, { force: true }); console.log(`removed: ${ENV_PATH}`); } @@ -436,7 +433,7 @@ function stop() { console.log(`stopped: ${unitNames(units)}`); } -// Web unit only: restarting the daemon would end every omp run on this machine. +// Web unit only: restarting the daemon would end every pi run on this machine. function restart() { systemctl(["restart", UNIT]); console.log(`restarted: ${UNIT_NAME}`); @@ -461,7 +458,7 @@ function readStatus() { const envConfig = readServiceEnv(); const configuredPort = Number.parseInt(envConfig.PORT ?? process.env.PORT ?? DEFAULT_PORT, 10); const port = Number.isInteger(configuredPort) ? configuredPort : Number(DEFAULT_PORT); - const hostname = envConfig.OMP_WEB_HOSTNAME ?? process.env.OMP_WEB_HOSTNAME ?? DEFAULT_HOSTNAME; + const hostname = envConfig.TAU_HOSTNAME ?? process.env.TAU_HOSTNAME ?? DEFAULT_HOSTNAME; return { isLinux: process.platform === "linux", ...web, @@ -480,7 +477,7 @@ function printStatus(asJson) { console.log(JSON.stringify(status, null, 2)); return status; } - console.log(`=== ompweb systemd service status (${process.platform}) ===`); + console.log(`=== tau systemd service status (${process.platform}) ===`); console.log(` Unit : ${status.unit} (${status.isInstalled ? status.unitPath : "not installed"})`); console.log(` Version : v${readPackageVersion()}`); console.log(` Active : ${status.isActive ? `Yes (pid ${status.pid})` : "No"}`); @@ -496,7 +493,7 @@ function printStatus(asJson) { function openInBrowser() { const status = readStatus(); - const openBin = process.env.OMP_WEB_OPEN ?? which("xdg-open") ?? "xdg-open"; + const openBin = process.env.TAU_OPEN ?? which("xdg-open") ?? "xdg-open"; const child = spawnSync(openBin, [status.serviceUrl], { stdio: "ignore", detached: true }); if (child.error) console.error(`Failed to open browser: ${child.error.message}`); else console.log(`Opening ${status.serviceUrl}...`); @@ -536,23 +533,23 @@ async function runCli(argv = process.argv.slice(2)) { // Validate the install inputs before the platform gate so misconfigured // launchers fail loudly on any platform (and stay testable on Windows). - // An OMP_WEB_OMP_BIN launcher script whose interpreter is nowhere on PATH + // An TAU_PI_BIN launcher script whose interpreter is nowhere on PATH // would install a unit that can only fail later with exit 127 (issue #116) — fail now. if (command === "install") { - const ompBin = process.env.OMP_WEB_OMP_BIN || null; - if (ompBin && !isExecutableFile(ompBin)) { - fail(`OMP_WEB_OMP_BIN=${ompBin} is not executable`); - } else if (ompBin && readLauncherInterpreter(ompBin) && !launcherInterpreterDir(ompBin)) { + const piBin = process.env.TAU_PI_BIN || null; + if (piBin && !isExecutableFile(piBin)) { + fail(`TAU_PI_BIN=${piBin} is not executable`); + } else if (piBin && readLauncherInterpreter(piBin) && !launcherInterpreterDir(piBin)) { fail( - `omp at ${ompBin} is a launcher script whose interpreter ` + - `(${readLauncherInterpreter(ompBin)}) was not found on PATH; ` + - `install that runtime (or point OMP_WEB_OMP_BIN at a standalone binary) and reinstall`, + `pi at ${piBin} is a launcher script whose interpreter ` + + `(${readLauncherInterpreter(piBin)}) was not found on PATH; ` + + `install that runtime (or point TAU_PI_BIN at a standalone binary) and reinstall`, ); } } if (process.platform !== "linux") { - fail("systemd services are Linux-only (use ompweb-launchd on macOS or ompweb --install-tray on Windows)"); + fail("systemd services are Linux-only (use tau-launchd on macOS or tau --install-tray on Windows)"); } const installOptions = { @@ -615,7 +612,7 @@ module.exports = { launcherInterpreterDir, readLauncherInterpreter, readStatus, - resolveOmpwebBin, + resolveTauBin, runCli, validateHostname, validatePort, diff --git a/bin/omp-web-systemd.test.mjs b/bin/tau-systemd.test.mjs similarity index 66% rename from bin/omp-web-systemd.test.mjs rename to bin/tau-systemd.test.mjs index ceb2ae8b..8651b215 100644 --- a/bin/omp-web-systemd.test.mjs +++ b/bin/tau-systemd.test.mjs @@ -17,41 +17,41 @@ const { formatExecStart, launcherInterpreterDir, readLauncherInterpreter, - resolveOmpwebBin, + resolveTauBin, runCli, validateHostname, validatePort, -} = require("./omp-web-systemd.js"); +} = require("./tau-systemd.js"); const { parseServiceEnv, serializeServiceEnv, writeServiceEnv, } = require("./service-env.js"); -const { hashPassword, verifyPassword } = require("./omp-web-password-hash.js"); +const { hashPassword, verifyPassword } = require("./tau-password-hash.js"); test("service env files round-trip quoted values", () => { const serialized = serializeServiceEnv({ - PORT: "30177", - OMP_WEB_HOSTNAME: "0.0.0.0", - OMP_WEB_PASSWORD: 'secret\\with"quotes', + PORT: "30187", + TAU_HOSTNAME: "0.0.0.0", + TAU_PASSWORD: 'secret\\with"quotes', }); - assert.match(serialized, /OMP_WEB_PASSWORD="secret\\\\with\\"quotes"/); + assert.match(serialized, /TAU_PASSWORD="secret\\\\with\\"quotes"/); assert.deepEqual(parseServiceEnv(serialized), { - PORT: "30177", - OMP_WEB_HOSTNAME: "0.0.0.0", - OMP_WEB_PASSWORD: 'secret\\with"quotes', + PORT: "30187", + TAU_HOSTNAME: "0.0.0.0", + TAU_PASSWORD: 'secret\\with"quotes', }); }); test("writeServiceEnv creates the parent directory and a private file", () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-service-env-")); + const dir = mkdtempSync(path.join(tmpdir(), "tau-service-env-")); try { const envPath = path.join(dir, "nested", "web-service.env"); - writeServiceEnv({ PORT: "40100", OMP_WEB_HOSTNAME: "127.0.0.1" }, envPath); + writeServiceEnv({ PORT: "40100", TAU_HOSTNAME: "127.0.0.1" }, envPath); assert.deepEqual(parseServiceEnv(readFileSync(envPath, "utf8")), { PORT: "40100", - OMP_WEB_HOSTNAME: "127.0.0.1", + TAU_HOSTNAME: "127.0.0.1", }); if (process.platform !== "win32") assert.equal(statSync(envPath).mode & 0o777, 0o600); } finally { @@ -61,18 +61,18 @@ test("writeServiceEnv creates the parent directory and a private file", () => { test("buildUnit points at the generated env file and keeps runtime settings out of the unit", () => { const unit = buildUnit({ - ompwebBin: "/usr/local/bin/ompweb", - env: { OMP_WEB_OMP_BIN: "/home/u/.bun/bin/omp" }, + tauBin: "/usr/local/bin/tau", + env: { TAU_PI_BIN: "/home/u/.bun/bin/omp" }, home: "/home/u", envPath: "/home/u/.omp/agent/web-service.env", }); - assert.match(unit, /ExecStart=\/usr\/local\/bin\/ompweb\n/); + assert.match(unit, /ExecStart=\/usr\/local\/bin\/tau\n/); assert.match(unit, /WorkingDirectory=%h/); assert.match(unit, /EnvironmentFile=\/home\/u\/\.omp\/agent\/web-service\.env/); assert.doesNotMatch(unit, /PORT=/); - assert.doesNotMatch(unit, /OMP_WEB_PASSWORD_HASH/); - assert.doesNotMatch(unit, /OMP_WEB_PASSWORD=/); + assert.doesNotMatch(unit, /TAU_PASSWORD_HASH/); + assert.doesNotMatch(unit, /TAU_PASSWORD=/); assert.match(unit, /Restart=on-failure/); assert.match(unit, /StartLimitIntervalSec=60/); assert.match(unit, /StartLimitBurst=5/); @@ -82,16 +82,16 @@ test("buildUnit points at the generated env file and keeps runtime settings out } }); -test("buildHostUnit runs `ompweb host` with the web unit's env file and never gives up restarting", () => { +test("buildHostUnit runs `tau host` with the web unit's env file and never gives up restarting", () => { const options = { - ompwebBin: "/usr/local/bin/ompweb", - env: { OMP_WEB_OMP_BIN: "/home/u/.bun/bin/omp" }, + tauBin: "/usr/local/bin/tau", + env: { TAU_PI_BIN: "/home/u/.bun/bin/omp" }, home: "/home/u", envPath: "/home/u/.omp/agent/web-service.env", }; const unit = buildHostUnit(options); - assert.match(unit, /^ExecStart=\/usr\/local\/bin\/ompweb host$/m); + assert.match(unit, /^ExecStart=\/usr\/local\/bin\/tau host$/m); assert.match(unit, /EnvironmentFile=\/home\/u\/\.omp\/agent\/web-service\.env/); assert.match(unit, /^Restart=always$/m); assert.match(unit, /^RestartSec=10$/m); @@ -102,11 +102,11 @@ test("buildHostUnit runs `ompweb host` with the web unit's env file and never gi // Same PATH as the web unit, so omp resolves the same way in both. const envLine = (text) => text.match(/^Environment=.*$/m)[0]; assert.equal(envLine(unit), envLine(buildUnit(options))); - assert.equal(buildHostUnit({ ...options, ompwebBin: "/opt/my tools/ompweb" }).match(/^ExecStart=(.*)$/m)[1], '"/opt/my tools/ompweb" host'); + assert.equal(buildHostUnit({ ...options, tauBin: "/opt/my tools/tau" }).match(/^ExecStart=(.*)$/m)[1], '"/opt/my tools/tau" host'); }); test("buildUnit adds the launcher interpreter dir for Bun/npm installs of omp", () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-systemd-bun-")); + const dir = mkdtempSync(path.join(tmpdir(), "tau-systemd-bun-")); try { const fakeBinDir = path.join(dir, "local", "bin"); const fakeBunDir = path.join(dir, "mise", "shims"); @@ -125,8 +125,8 @@ test("buildUnit adds the launcher interpreter dir for Bun/npm installs of omp", assert.equal(launcherInterpreterDir(path.join(fakeBinDir, "omp"), { PATH: "/usr/bin" }), null); const unit = buildUnit({ - ompwebBin: "/usr/local/bin/ompweb", - env: { OMP_WEB_OMP_BIN: path.join(fakeBinDir, "omp") }, + tauBin: "/usr/local/bin/tau", + env: { TAU_PI_BIN: path.join(fakeBinDir, "omp") }, home: "/home/u", envPath: "/home/u/.omp/agent/web-service.env", }); @@ -146,23 +146,23 @@ test("unit helpers escape systemd values and paths", () => { assert.equal(escapeUnitValue('quo"te\\'), 'quo\\"te\\\\'); assert.equal(escapeUnitPath("/home/user name/web-service.env"), "/home/user\\x20name/web-service.env"); assert.equal(escapeUnitPath("/home/100%name/web-service.env"), "/home/100%%name/web-service.env"); - assert.equal(formatExecStart("/usr/local/bin/ompweb"), "/usr/local/bin/ompweb"); - assert.equal(formatExecStart("/home/user name/ompweb"), '"/home/user name/ompweb"'); + assert.equal(formatExecStart("/usr/local/bin/tau"), "/usr/local/bin/tau"); + assert.equal(formatExecStart("/home/user name/tau"), '"/home/user name/tau"'); }); -test("resolveOmpwebBin honors an executable override", () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-systemd-")); +test("resolveTauBin honors an executable override", () => { + const dir = mkdtempSync(path.join(tmpdir(), "tau-systemd-")); try { - const fake = path.join(dir, "ompweb"); + const fake = path.join(dir, "tau"); writeFileSync(fake, "#!/bin/sh\n", { mode: 0o755 }); - assert.equal(resolveOmpwebBin({ OMP_WEB_SYSTEMD_BIN: fake }), fake); + assert.equal(resolveTauBin({ TAU_SYSTEMD_BIN: fake }), fake); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("port and hostname validation rejects unsafe values", () => { - assert.equal(validatePort("30177"), "30177"); + assert.equal(validatePort("30187"), "30187"); assert.equal(validateHostname("0.0.0.0"), "0.0.0.0"); assert.throws(() => validatePort("0"), /invalid port/); assert.throws(() => validatePort("65536"), /invalid port/); @@ -171,63 +171,63 @@ test("port and hostname validation rejects unsafe values", () => { }); test("install creates the env file and unit with LAN settings", { skip: process.platform !== "linux" }, () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-systemd-install-")); + const dir = mkdtempSync(path.join(tmpdir(), "tau-systemd-install-")); try { const home = path.join(dir, "home"); const binDir = path.join(dir, "bin"); - const fakeOmpweb = path.join(binDir, "ompweb"); + const fakeTau = path.join(binDir, "tau"); const fakeSystemctl = path.join(binDir, "systemctl"); mkdirSync(home, { recursive: true }); mkdirSync(binDir, { recursive: true }); - writeFileSync(fakeOmpweb, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + writeFileSync(fakeTau, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); writeFileSync(fakeSystemctl, "#!/bin/sh\ncase \"$*\" in *is-active*) exit 3 ;; *) exit 0 ;; esac\n", { mode: 0o755 }); - // A stock omp on PATH: pinning the services to it would replace ompweb's own omp, which its sessions need. + // A stock omp on PATH: pinning the services to it would replace tau's own omp, which its sessions need. writeFileSync(path.join(binDir, "omp"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); const childEnv = { ...process.env, HOME: home, PATH: binDir, - OMP_WEB_SYSTEMD_BIN: fakeOmpweb, - OMP_WEB_HOSTNAME: "0.0.0.0", - OMP_WEB_PASSWORD: "test-password", - OMP_WEB_NO_OPEN: "0", - OMP_WEB_TRUSTED_HEADER_SHA256: "a".repeat(64), - OMP_WEB_DISABLE_AUTOUPDATE: "1", - OMP_WEB_NAME: "My Box", + TAU_SYSTEMD_BIN: fakeTau, + TAU_HOSTNAME: "0.0.0.0", + TAU_PASSWORD: "test-password", + TAU_NO_OPEN: "0", + TAU_TRUSTED_HEADER_SHA256: "a".repeat(64), + TAU_DISABLE_AUTOUPDATE: "1", + TAU_NAME: "My Box", PORT: "40123", }; delete childEnv.PI_CODING_AGENT_DIR; - delete childEnv.OMP_WEB_OMP_BIN; + delete childEnv.TAU_PI_BIN; - const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "omp-web-systemd.js"), "install", "--no-autostart"], { + const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "tau-systemd.js"), "install", "--no-autostart"], { env: childEnv, encoding: "utf8", }); assert.equal(result.status, 0, result.stderr); - const envPath = path.join(home, ".omp", "agent", "web-service.env"); - const unitPath = path.join(home, ".config", "systemd", "user", "ompweb.service"); + const envPath = path.join(home, ".pi", "agent", "web-service.env"); + const unitPath = path.join(home, ".config", "systemd", "user", "tau.service"); const written = parseServiceEnv(readFileSync(envPath, "utf8")); - // The installer hashes OMP_WEB_PASSWORD: only the hash may reach the env - // file, and omp-web refuses to start on a plaintext password (issue #239). - assert.match(written.OMP_WEB_PASSWORD_HASH, /^scrypt\$15\$8\$1\$[A-Za-z0-9_-]{22}\$[A-Za-z0-9_-]{43}$/); - assert.equal(written.OMP_WEB_PASSWORD, undefined); - assert.equal(verifyPassword("test-password", written.OMP_WEB_PASSWORD_HASH), true); - assert.equal(verifyPassword("not-the-password", written.OMP_WEB_PASSWORD_HASH), false); - delete written.OMP_WEB_PASSWORD_HASH; + // The installer hashes TAU_PASSWORD: only the hash may reach the env + // file, and tau refuses to start on a plaintext password (issue #239). + assert.match(written.TAU_PASSWORD_HASH, /^scrypt\$15\$8\$1\$[A-Za-z0-9_-]{22}\$[A-Za-z0-9_-]{43}$/); + assert.equal(written.TAU_PASSWORD, undefined); + assert.equal(verifyPassword("test-password", written.TAU_PASSWORD_HASH), true); + assert.equal(verifyPassword("not-the-password", written.TAU_PASSWORD_HASH), false); + delete written.TAU_PASSWORD_HASH; assert.deepEqual(written, { PORT: "40123", - OMP_WEB_HOSTNAME: "0.0.0.0", - OMP_WEB_NO_OPEN: "0", - OMP_WEB_DISABLE_AUTOUPDATE: "1", - OMP_WEB_NAME: "My Box", - OMP_WEB_TRUSTED_HEADER_SHA256: "a".repeat(64), + TAU_HOSTNAME: "0.0.0.0", + TAU_NO_OPEN: "0", + TAU_DISABLE_AUTOUPDATE: "1", + TAU_NAME: "My Box", + TAU_TRUSTED_HEADER_SHA256: "a".repeat(64), }); assert.match(readFileSync(unitPath, "utf8"), /EnvironmentFile=.*web-service\.env/); - assert.doesNotMatch(readFileSync(unitPath, "utf8"), /OMP_WEB_OMP_BIN/); - const hostUnit = readFileSync(path.join(path.dirname(unitPath), "ompweb-host.service"), "utf8"); - assert.match(hostUnit, /^ExecStart=.*\/ompweb host$/m); + assert.doesNotMatch(readFileSync(unitPath, "utf8"), /TAU_PI_BIN/); + const hostUnit = readFileSync(path.join(path.dirname(unitPath), "tau-host.service"), "utf8"); + assert.match(hostUnit, /^ExecStart=.*\/tau host$/m); assert.match(hostUnit, /EnvironmentFile=.*web-service\.env/); assert.match(result.stdout, /config:.*web-service\.env/); } finally { @@ -236,40 +236,40 @@ test("install creates the env file and unit with LAN settings", { skip: process. }); test("install writes a pre-hashed password unchanged and rejects a broken one", { skip: process.platform !== "linux" }, () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-systemd-hash-")); + const dir = mkdtempSync(path.join(tmpdir(), "tau-systemd-hash-")); try { const home = path.join(dir, "home"); const binDir = path.join(dir, "bin"); - const fakeOmpweb = path.join(binDir, "ompweb"); + const fakeTau = path.join(binDir, "tau"); const fakeSystemctl = path.join(binDir, "systemctl"); mkdirSync(home, { recursive: true }); mkdirSync(binDir, { recursive: true }); - writeFileSync(fakeOmpweb, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + writeFileSync(fakeTau, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); writeFileSync(fakeSystemctl, "#!/bin/sh\ncase \"$*\" in *is-active*) exit 3 ;; *) exit 0 ;; esac\n", { mode: 0o755 }); const base = { ...process.env, HOME: home, PATH: binDir, - OMP_WEB_SYSTEMD_BIN: fakeOmpweb, - OMP_WEB_HOSTNAME: "0.0.0.0", + TAU_SYSTEMD_BIN: fakeTau, + TAU_HOSTNAME: "0.0.0.0", }; delete base.PI_CODING_AGENT_DIR; - delete base.OMP_WEB_OMP_BIN; - delete base.OMP_WEB_PASSWORD; + delete base.TAU_PI_BIN; + delete base.TAU_PASSWORD; const provided = hashPassword("preset-password"); - const ok = spawnSync(NODE, [path.join(process.cwd(), "bin", "omp-web-systemd.js"), "install", "--no-autostart"], { - env: { ...base, OMP_WEB_PASSWORD_HASH: provided }, + const ok = spawnSync(NODE, [path.join(process.cwd(), "bin", "tau-systemd.js"), "install", "--no-autostart"], { + env: { ...base, TAU_PASSWORD_HASH: provided }, encoding: "utf8", }); assert.equal(ok.status, 0, ok.stderr); assert.equal( - parseServiceEnv(readFileSync(path.join(home, ".omp", "agent", "web-service.env"), "utf8")).OMP_WEB_PASSWORD_HASH, + parseServiceEnv(readFileSync(path.join(home, ".pi", "agent", "web-service.env"), "utf8")).TAU_PASSWORD_HASH, provided, ); - const broken = spawnSync(NODE, [path.join(process.cwd(), "bin", "omp-web-systemd.js"), "install", "--no-autostart"], { - env: { ...base, OMP_WEB_PASSWORD_HASH: "definitely-not-a-hash" }, + const broken = spawnSync(NODE, [path.join(process.cwd(), "bin", "tau-systemd.js"), "install", "--no-autostart"], { + env: { ...base, TAU_PASSWORD_HASH: "definitely-not-a-hash" }, encoding: "utf8", }); assert.notEqual(broken.status, 0); @@ -280,12 +280,12 @@ test("install writes a pre-hashed password unchanged and rejects a broken one", }); test("install fails loudly when the omp launcher interpreter is missing", () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-systemd-missing-interp-")); + const dir = mkdtempSync(path.join(tmpdir(), "tau-systemd-missing-interp-")); try { const binDir = path.join(dir, "bin"); - const fakeOmpweb = path.join(binDir, "ompweb"); + const fakeTau = path.join(binDir, "tau"); mkdirSync(binDir, { recursive: true }); - writeFileSync(fakeOmpweb, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + writeFileSync(fakeTau, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); // Launcher script needing an interpreter that is nowhere on PATH. writeFileSync(path.join(binDir, "omp"), "#!/usr/bin/env bun\n", { mode: 0o755 }); @@ -294,11 +294,11 @@ test("install fails loudly when the omp launcher interpreter is missing", () => // No node dir: the spawn uses an absolute process.execPath, and adding // it breaks the premise when node and bun share a directory. PATH: binDir, - OMP_WEB_SYSTEMD_BIN: fakeOmpweb, - OMP_WEB_OMP_BIN: path.join(binDir, "omp"), + TAU_SYSTEMD_BIN: fakeTau, + TAU_PI_BIN: path.join(binDir, "omp"), PORT: "40123", }; - const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "omp-web-systemd.js"), "install", "--no-autostart"], { + const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "tau-systemd.js"), "install", "--no-autostart"], { env: childEnv, encoding: "utf8", }); @@ -310,8 +310,8 @@ test("install fails loudly when the omp launcher interpreter is missing", () => } }); -test("main ompweb bin forwards the systemd subcommand", () => { - const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "omp-web.js"), "systemd", "--version"], { +test("main tau bin forwards the systemd subcommand", () => { + const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "tau.js"), "systemd", "--version"], { encoding: "utf8", }); assert.equal(result.status, 0, result.stderr); @@ -325,27 +325,27 @@ test("runCli handles help and unknown commands without systemd", async () => { // Runs the CLI against a fake systemctl that logs its arguments; `hostUnit: false` mimics an install from before the daemon. function runWithFakeSystemctl(command, { hostUnit = true, active = false, dir: sharedDir, hostFails = !hostUnit } = {}) { - // A shared dir keeps HOME and the fake ompweb path, so a repeated install generates identical units. - const dir = sharedDir ?? mkdtempSync(path.join(tmpdir(), "ompweb-systemd-cmd-")); + // A shared dir keeps HOME and the fake tau path, so a repeated install generates identical units. + const dir = sharedDir ?? mkdtempSync(path.join(tmpdir(), "tau-systemd-cmd-")); const home = path.join(dir, "home"); const binDir = path.join(dir, "bin"); const log = path.join(dir, "systemctl.log"); - const fakeOmpweb = path.join(binDir, "ompweb"); + const fakeTau = path.join(binDir, "tau"); mkdirSync(binDir, { recursive: true }); const unitDir = path.join(home, ".config", "systemd", "user"); mkdirSync(unitDir, { recursive: true }); - writeFileSync(path.join(unitDir, "ompweb.service"), "[Service]\n"); - if (hostUnit && !existsSync(path.join(unitDir, "ompweb-host.service"))) writeFileSync(path.join(unitDir, "ompweb-host.service"), "[Service]\n"); - writeFileSync(fakeOmpweb, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + writeFileSync(path.join(unitDir, "tau.service"), "[Service]\n"); + if (hostUnit && !existsSync(path.join(unitDir, "tau-host.service"))) writeFileSync(path.join(unitDir, "tau-host.service"), "[Service]\n"); + writeFileSync(fakeTau, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); // A missing host unit makes systemctl fail, as the real one does. writeFileSync( path.join(binDir, "systemctl"), - `#!/bin/sh\necho "$*" >> "${log}"\n${hostFails ? 'case "$*" in *ompweb-host*) exit 5 ;; esac\n' : ""}case "$*" in *is-active*) exit ${active ? 0 : 3} ;; *) exit 0 ;; esac\n`, + `#!/bin/sh\necho "$*" >> "${log}"\n${hostFails ? 'case "$*" in *tau-host*) exit 5 ;; esac\n' : ""}case "$*" in *is-active*) exit ${active ? 0 : 3} ;; *) exit 0 ;; esac\n`, { mode: 0o755 }, ); - const env = { ...process.env, HOME: home, PATH: binDir, OMP_WEB_SYSTEMD_BIN: fakeOmpweb, OMP_WEB_DISABLE_AUTOUPDATE: "1" }; - for (const key of ["PI_CODING_AGENT_DIR", "OMP_WEB_OMP_BIN", "OMP_WEB_PASSWORD"]) delete env[key]; - const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "omp-web-systemd.js"), command], { env, encoding: "utf8" }); + const env = { ...process.env, HOME: home, PATH: binDir, TAU_SYSTEMD_BIN: fakeTau, TAU_DISABLE_AUTOUPDATE: "1" }; + for (const key of ["PI_CODING_AGENT_DIR", "TAU_PI_BIN", "TAU_PASSWORD"]) delete env[key]; + const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "tau-systemd.js"), command], { env, encoding: "utf8" }); const calls = existsSync(log) ? readFileSync(log, "utf8").trim().split("\n") : []; rmSync(log, { force: true }); return { result, calls, dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) }; @@ -355,7 +355,7 @@ test("restart restarts the web unit only: restarting the daemon would end every const { result, calls, cleanup } = runWithFakeSystemctl("restart"); try { assert.equal(result.status, 0, result.stderr); - assert.deepEqual(calls, ["--user restart ompweb.service"]); + assert.deepEqual(calls, ["--user restart tau.service"]); } finally { cleanup(); } @@ -366,7 +366,7 @@ test("start and stop cover both units when the host unit exists", { skip: proces const { result, calls, cleanup } = runWithFakeSystemctl(command); try { assert.equal(result.status, 0, result.stderr); - assert.deepEqual(calls, [`--user ${command} ompweb.service ompweb-host.service`]); + assert.deepEqual(calls, [`--user ${command} tau.service tau-host.service`]); } finally { cleanup(); } @@ -378,7 +378,7 @@ test("start, stop and restart work on an install without the host unit", { skip: const { result, calls, cleanup } = runWithFakeSystemctl(command, { hostUnit: false }); try { assert.equal(result.status, 0, result.stderr); - assert.deepEqual(calls, [`--user ${command} ompweb.service`]); + assert.deepEqual(calls, [`--user ${command} tau.service`]); } finally { cleanup(); } @@ -390,13 +390,13 @@ test("install restarts a running host unit only when its unit text changed", { s const first = runWithFakeSystemctl("install", { hostUnit: false, hostFails: false, active: true }); try { assert.equal(first.result.status, 0, first.result.stderr); - assert.ok(first.calls.includes("--user restart ompweb.service")); - assert.ok(first.calls.includes("--user restart ompweb-host.service")); + assert.ok(first.calls.includes("--user restart tau.service")); + assert.ok(first.calls.includes("--user restart tau-host.service")); // Same install again: identical unit text, so only the web unit restarts. const second = runWithFakeSystemctl("install", { active: true, dir: first.dir }); assert.equal(second.result.status, 0, second.result.stderr); - assert.ok(second.calls.includes("--user restart ompweb.service")); - assert.ok(!second.calls.includes("--user restart ompweb-host.service"), second.calls.join("\n")); + assert.ok(second.calls.includes("--user restart tau.service")); + assert.ok(!second.calls.includes("--user restart tau-host.service"), second.calls.join("\n")); } finally { first.cleanup(); } diff --git a/bin/omp-web-tray.exe b/bin/tau-tray.exe similarity index 100% rename from bin/omp-web-tray.exe rename to bin/tau-tray.exe diff --git a/bin/omp-web-tray.js b/bin/tau-tray.js similarity index 94% rename from bin/omp-web-tray.js rename to bin/tau-tray.js index 58e7fab9..bc76d814 100644 --- a/bin/omp-web-tray.js +++ b/bin/tau-tray.js @@ -14,12 +14,12 @@ const fs = require("fs"); const path = require("path"); function printHelp() { - console.log(`Usage: node bin/omp-web-tray.js [command] [options] - ompweb-tray [command] [options] + console.log(`Usage: node bin/tau-tray.js [command] [options] + tau-tray [command] [options] Platform notes: Windows System Tray shortcuts and background service - Linux StatusNotifierItem tray (KDE Plasma and compatible) — see ompweb-systemd + Linux StatusNotifierItem tray (KDE Plasma and compatible) — see tau-systemd for the systemd user service this tray manages Commands: @@ -32,12 +32,12 @@ Commands: --open, open Open the background web service in default browser Options: - -p, --port Server port for background service (default 30177) + -p, --port Server port for background service (default 30187) -H, --hostname Bind address (default 127.0.0.1) -m, --mode Execution mode: "start" or "dev" (default "start", Windows only) --no-autostart Disable automatic startup on logon --start Start tray manager immediately after installation (Windows) - --clean-config Also delete ~/.omp/agent/web-service.json on uninstallation + --clean-config Also delete ~/.pi/agent/web-service.json on uninstallation --json Output status as JSON -h, --help Show this help -v, --version Show version @@ -144,7 +144,7 @@ async function runCli(argv = process.argv.slice(2)) { } if (isStart) { - console.log("Starting omp-web background system tray service..."); + console.log("Starting tau background system tray service..."); const res = await windowsService.startTrayService({ openBrowser: cliArgs.open }); if (res.success) { console.log("Tray service launched in background."); @@ -156,7 +156,7 @@ async function runCli(argv = process.argv.slice(2)) { } if (isStop) { - console.log("Stopping omp-web background system tray service..."); + console.log("Stopping tau background system tray service..."); const res = await windowsService.stopTrayService(); if (res.success) { console.log("Background system tray service stopped."); @@ -168,7 +168,7 @@ async function runCli(argv = process.argv.slice(2)) { } if (isRestart) { - console.log("Restarting omp-web background system tray service..."); + console.log("Restarting tau background system tray service..."); const res = await windowsService.restartTrayService(); if (res.success) { console.log("Background system tray service restarted."); @@ -201,7 +201,7 @@ async function runCli(argv = process.argv.slice(2)) { if (cliArgs.json) { console.log(JSON.stringify(status, null, 2)); } else { - console.log("=== omp-web Windows Service Status ==="); + console.log("=== tau Windows Service Status ==="); console.log(` Platform : ${process.platform === "win32" ? "Windows" : process.platform}`); console.log(` Version : v${status.version}`); console.log(` Installed : ${status.isInstalled ? "Yes" : "No"}`); diff --git a/bin/omp-web-tray.test.mjs b/bin/tau-tray.test.mjs similarity index 93% rename from bin/omp-web-tray.test.mjs rename to bin/tau-tray.test.mjs index 3af5b9ca..0439276c 100644 --- a/bin/omp-web-tray.test.mjs +++ b/bin/tau-tray.test.mjs @@ -3,8 +3,8 @@ import { createRequire } from "node:module"; import test from "node:test"; const require = createRequire(import.meta.url); -const { parseLaunchOptions } = require("./omp-web-options.js"); -const { runCli } = require("./omp-web-tray.js"); +const { parseLaunchOptions } = require("./tau-options.js"); +const { runCli } = require("./tau-tray.js"); test("parseLaunchOptions parses --install-tray and --install-service flags", () => { const opts1 = parseLaunchOptions(["--install-tray"], {}); diff --git a/bin/omp-web.js b/bin/tau.js similarity index 77% rename from bin/omp-web.js rename to bin/tau.js index 155c43d3..6999c52b 100755 --- a/bin/omp-web.js +++ b/bin/tau.js @@ -5,24 +5,22 @@ require("./node-version").exitIfUnsupportedNode(); // Forward service subcommands from the main bin. This makes both -// `npx @kahme247/ompweb@latest ompweb-launchd ...` and -// `npx @kahme247/ompweb@latest ompweb-systemd ...` work without requiring +// `npx @ompweb-dev/tau@latest tau-launchd ...` and +// `npx @ompweb-dev/tau@latest tau-systemd ...` work without requiring // callers to know the path of the secondary executable. const forwardedServiceScripts = { - launchd: "omp-web-launchd.js", - "tau-launchd": "omp-web-launchd.js", - "ompweb-launchd": "omp-web-launchd.js", - systemd: "omp-web-systemd.js", - "tau-systemd": "omp-web-systemd.js", - "ompweb-systemd": "omp-web-systemd.js", + launchd: "tau-launchd.js", + "tau-launchd": "tau-launchd.js", + systemd: "tau-systemd.js", + "tau-systemd": "tau-systemd.js", }; -// `ompweb hash-password` reads the password on stdin and prints the value for -// OMP_WEB_PASSWORD_HASH. Handled first so it works with no build artifacts, no +// `tau hash-password` reads the password on stdin and prints the value for +// TAU_PASSWORD_HASH. Handled first so it works with no build artifacts, no // port, and no agent directory. if (process.argv[2] === "hash-password" || process.argv[2] === "hash_password") { // eslint-disable-next-line @typescript-eslint/no-require-imports - const { runHashPasswordCommand } = require("./omp-web-hash-password"); + const { runHashPasswordCommand } = require("./tau-hash-password"); runHashPasswordCommand() .then((exitCode) => { process.exit(exitCode); }) .catch((error) => { @@ -34,9 +32,9 @@ if (process.argv[2] === "hash-password" || process.argv[2] === "hash_password") } function startLauncher() { -// `ompweb preflight` (lib/hosts/preflight.ts): what an updater runs on a candidate release; it prints "preflight ok: ". +// `tau preflight` (lib/hosts/preflight.ts): what an updater runs on a candidate release; it prints "preflight ok: ". if (process.argv[2] === "preflight") { - process.env.OMP_WEB_PACKAGE_DIR ??= module.require("node:path").join(__dirname, ".."); + process.env.TAU_PACKAGE_DIR ??= module.require("node:path").join(__dirname, ".."); module.require("jiti").createJiti(__filename).import("../lib/hosts/preflight.ts").then( ({ runPreflight }) => runPreflight().then((code) => process.exit(code)), (error) => { @@ -46,22 +44,11 @@ if (process.argv[2] === "preflight") { ); return; } -if (process.argv[2] === "recover-host") { - process.env.OMP_WEB_PACKAGE_DIR ??= module.require("node:path").join(__dirname, ".."); - module.require("jiti").createJiti(__filename).import("../lib/hosts/recovery.ts").then( - ({ runHostRecoveryCli }) => runHostRecoveryCli(process.argv.slice(3)).then((code) => process.exit(code)), - (error) => { - console.error(`Host recovery failed: ${error instanceof Error ? error.message : String(error)}`); - process.exit(1); - }, - ); - return; -} -// `ompweb host` runs in this process: a supervisor's SIGTERM must reach the daemon, not a wrapper. +// `tau host` runs in this process: a supervisor's SIGTERM must reach the daemon, not a wrapper. if (process.argv[2] === "host") { process.argv.splice(2, 1); // eslint-disable-next-line @typescript-eslint/no-require-imports - require("./omp-web-host.js"); + require("./tau-host.js"); return; } const forwardedServiceScript = forwardedServiceScripts[process.argv[2]]; @@ -85,7 +72,7 @@ const path = require("node:path"); // eslint-disable-next-line @typescript-eslint/no-require-imports const fs = require("node:fs"); // eslint-disable-next-line @typescript-eslint/no-require-imports -const { checkLaunchSecurity, parseLaunchOptions, serverWorkingDirectory } = require("./omp-web-options"); +const { checkLaunchSecurity, parseLaunchOptions, serverWorkingDirectory } = require("./tau-options"); // eslint-disable-next-line @typescript-eslint/no-require-imports const { isPortAvailable } = require("./port-availability"); // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -108,7 +95,7 @@ if (launchOptions.error) { if (launchOptions.installTray || launchOptions.uninstallTray || launchOptions.tray) { // eslint-disable-next-line @typescript-eslint/no-require-imports - const { runCli } = require("./omp-web-tray"); + const { runCli } = require("./tau-tray"); const trayArgs = []; if (launchOptions.installTray) { trayArgs.push("--install"); @@ -178,16 +165,16 @@ function attachOutput(child) { function serverEnvironment() { return { ...process.env, - OMP_WEB_PACKAGE_DIR: pkgDir, - OMP_WEB_LAUNCHER_PID: String(process.pid), - OMP_WEB_NODE_BIN: process.execPath, - OMP_WEB_PORT: port, - OMP_WEB_HOSTNAME: hostname, + TAU_PACKAGE_DIR: pkgDir, + TAU_LAUNCHER_PID: String(process.pid), + TAU_NODE_BIN: process.execPath, + TAU_PORT: port, + TAU_HOSTNAME: hostname, }; } function trackServer(child) { - child.once("error", (error) => console.error(`Could not start ompweb: ${error.message}`)); + child.once("error", (error) => console.error(`Could not start tau: ${error.message}`)); attachOutput(child); wireChildProcessLifecycle(child, process); return child; @@ -197,7 +184,7 @@ function spawnServer(command) { return trackServer(spawn(command[0], command.slice(1), { // Never the installation: on Windows a working directory there blocks the rename an // in-place update performs, and the server needs no relative path (the entry point and - // OMP_WEB_PACKAGE_DIR below are absolute). + // TAU_PACKAGE_DIR below are absolute). cwd: serverWorkingDirectory(), stdio: ["inherit", "pipe", "inherit"], env: serverEnvironment(), @@ -212,7 +199,7 @@ async function main() { } if (!await isPortAvailable(port, hostname)) { console.error(`Port ${port} on ${hostname} is already in use.`); - console.error(`If ompweb is already running, open ${browserUrl}. Otherwise, stop the process using it or run: ompweb --port ${Number(port) + 1}`); + console.error(`If tau is already running, open ${browserUrl}. Otherwise, stop the process using it or run: tau --port ${Number(port) + 1}`); process.exitCode = 1; return; } diff --git a/bunfig.toml b/bunfig.toml index 3caa0370..ae5067dc 100644 --- a/bunfig.toml +++ b/bunfig.toml @@ -1,4 +1,7 @@ # Bun's dev server (server/dev.ts HTML import) bundles the SPA with these; scripts/build-client.ts passes its own. [serve.static] plugins = ["./scripts/tailwind-plugin.ts"] -env = "OMP_WEB_PUBLIC_*" +env = "TAU_PUBLIC_*" + +[test] +preload = ["./tests/isolate-tmp.mjs"] diff --git a/components/AgentsConfig.tsx b/components/AgentsConfig.tsx deleted file mode 100644 index 9461d18d..00000000 --- a/components/AgentsConfig.tsx +++ /dev/null @@ -1,429 +0,0 @@ -"use client"; - -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { AlertCircle, Bot, Check, Copy, Plus, RefreshCw, Search, Trash2 } from "lucide-react"; -import { Alert } from "@/components/ui/field"; -import { ThemedSelect } from "@/components/ui/primitives"; -import { toast } from "@/components/ui/toast"; -import { useI18n } from "@/lib/i18n"; - -type AgentInfo = { - name: string; - description: string; - model?: string[]; - tools?: string[]; - spawns?: string[] | "*"; - thinkingLevel?: string; - source: "bundled" | "user" | "project"; - scope: string; - filePath: string; - valid: boolean; - enabled: boolean; - body?: string; - rawFrontmatter?: Record; -}; - -type AgentsResponse = { - agents?: AgentInfo[]; - diagnostics?: Array<{ type?: string; message?: string }>; - error?: string; -}; - -const inputStyle = { width: "100%", padding: "7px 9px", border: "1px solid var(--border)", borderRadius: "var(--radius-control)", background: "var(--bg)", color: "var(--text)", font: "12px var(--font-mono)" } as const; -const textareaStyle = { width: "100%", padding: "7px 9px", border: "1px solid var(--border)", borderRadius: "var(--radius-control)", background: "var(--bg)", color: "var(--text)", font: "12px var(--font-mono)", lineHeight: "1.45" } as const; -const nativeSelectStyle = { minHeight: 32, padding: "4px 28px 4px 10px", border: "1px solid var(--border)", borderRadius: "var(--radius-control)", background: "var(--bg)", color: "var(--text)", fontSize: 12 } as const; -const THINKING_LEVELS = ["", "auto", "off", "minimal", "low", "medium", "high", "xhigh", "max"] as const; - -function shorten(p: string) { - const h = p.replace(/^[^:]*:/, ""); - if (h.length > 48) return "…" + h.slice(-47); - return h; -} -function splitCsv(v: string): string[] { return v.split(",").map((s) => s.trim()).filter(Boolean); } -function toCsv(arr?: string[] | string): string { if (!arr) return ""; if (typeof arr === "string") return arr; return arr.join(", "); } -function fileStem(filePath: string): string { - const normalized = filePath.replace(/\\/g, "/"); - const fileName = normalized.slice(normalized.lastIndexOf("/") + 1); - return fileName.toLowerCase().endsWith(".md") ? fileName.slice(0, -3) : fileName; -} - -/** `userOnly`: the user level alone (a cluster member's settings, spec K7), with no project scope to offer. */ -export function AgentsConfig({ cwd, userOnly = false }: { cwd: string | null; userOnly?: boolean }) { - const { t, tn } = useI18n(); - const [agents, setAgents] = useState([]); - const [loading, setLoading] = useState(true); - const [saving, setSaving] = useState(false); - const [message, setMessage] = useState(null); - const [diagnostics, setDiagnostics] = useState>([]); - const [search, setSearch] = useState(""); - const [selected, setSelected] = useState(null); - const [creating, setCreating] = useState(false); - const [createScope, setCreateScope] = useState<"user" | "project">("user"); - const [workspaceUnavailable, setWorkspaceUnavailable] = useState(false); - const [workspaceCheckPending, setWorkspaceCheckPending] = useState(Boolean(cwd)); - const selectedRef = useRef(null); - const loadGenerationRef = useRef(0); - const cwdRef = useRef(cwd); - cwdRef.current = cwd; - const [name, setName] = useState(""); - const [description, setDescription] = useState(""); - const [modelCsv, setModelCsv] = useState(""); - const [toolsCsv, setToolsCsv] = useState(""); - const [spawnsCsv, setSpawnsCsv] = useState(""); - const [thinkingLevel, setThinkingLevel] = useState(""); - const [body, setBody] = useState(""); - - const load = useCallback(async (forceSelect = false) => { - const generation = ++loadGenerationRef.current; - const requestCwd = cwd; - const isCurrent = () => loadGenerationRef.current === generation && cwdRef.current === requestCwd; - setLoading(true); - setMessage(null); - setWorkspaceCheckPending(Boolean(requestCwd)); - try { - const params = new URLSearchParams(); - if (cwd) params.set("cwd", cwd); - let res = await fetch(`/api/agents?${params.toString()}`); - let data = (await res.json()) as AgentsResponse; - if (!isCurrent()) return; - if (!res.ok || data.error) { - if (!requestCwd || res.status !== 403) throw new Error(data.error || `HTTP ${res.status}`); - // A project can remain in the sidebar after its directory is moved or - // deleted. Keep global agents usable while the API continues to reject - // writes against that missing workspace. - res = await fetch("/api/agents"); - data = (await res.json()) as AgentsResponse; - if (!isCurrent()) return; - if (!res.ok || data.error) throw new Error(data.error || `HTTP ${res.status}`); - setWorkspaceUnavailable(true); - setWorkspaceCheckPending(false); - setMessage(t("agentsConfig.workspaceUnavailableWarning")); - } else { - setWorkspaceUnavailable(false); - setWorkspaceCheckPending(false); - } - const list = Array.isArray(data.agents) ? data.agents : []; - if (!isCurrent()) return; - setAgents(list); - const nextDiagnostics = Array.isArray(data.diagnostics) ? data.diagnostics : []; - setDiagnostics(nextDiagnostics); - const diagnosticErrors = nextDiagnostics - .filter((diagnostic) => diagnostic.type === "error" && typeof diagnostic.message === "string") - .map((diagnostic) => diagnostic.message as string); - if (diagnosticErrors.length > 0 && list.length === 0) setMessage(diagnosticErrors.join("; ")); - if (forceSelect || !creating) { - const currentName = selectedRef.current; - const chosen = (currentName ? list.find((a) => a.name === currentName) : undefined) ?? list[0] ?? null; - selectedRef.current = chosen?.name ?? null; - setSelected(chosen?.name ?? null); - if (chosen) fillForm(chosen); - else clearForm(); - } - } catch (e) { - if (!isCurrent()) return; - const msg = e instanceof Error ? e.message : String(e); - setWorkspaceCheckPending(false); - setMessage(msg); - } finally { if (isCurrent()) { setLoading(false); setWorkspaceCheckPending(false); } } - }, [cwd, creating, t]); - useEffect(() => { void load(); }, [load]); - useEffect(() => { - setWorkspaceUnavailable(false); - setWorkspaceCheckPending(Boolean(cwd)); - setSaving(false); - }, [cwd]); - const canEditProject = Boolean(cwd && !workspaceUnavailable && !workspaceCheckPending); - useEffect(() => { setCreateScope(canEditProject ? "project" : "user"); }, [canEditProject]); - const counts = useMemo(() => { - let bundled = 0, user = 0, project = 0; - for (const a of agents) { - if (a.scope === "bundled") bundled += 1; - else if (a.scope === "user") user += 1; - else if (a.scope === "project") project += 1; - } - return { total: agents.length, bundled, user, project }; - }, [agents]); - const filtered = useMemo(() => { - const q = search.trim().toLowerCase(); - if (!q) return agents; - return agents.filter((a) => a.name.toLowerCase().includes(q) || a.description.toLowerCase().includes(q)); - }, [agents, search]); - const active = useMemo(() => (creating || !selected ? null : agents.find((a) => a.name === selected) ?? null), [agents, selected, creating]); - const isBundledActive = active?.scope === "bundled"; - const activeProjectUnavailable = active?.scope === "project" && !canEditProject; - function fillForm(a: AgentInfo) { - setName(a.name); - setDescription(a.description); - setModelCsv(toCsv(a.model)); - setToolsCsv(toCsv(a.tools)); - setSpawnsCsv(toCsv(a.spawns as string[] | string | undefined)); - setThinkingLevel(a.thinkingLevel ?? ""); - setBody(a.body ?? ""); - } - function clearForm() { - setName(""); setDescription(""); setModelCsv(""); setToolsCsv(""); - setSpawnsCsv(""); setThinkingLevel(""); setBody(""); - } - const pick = (a: AgentInfo) => { selectedRef.current = a.name; setCreating(false); setSelected(a.name); fillForm(a); setMessage(null); }; - const startCreate = () => { selectedRef.current = null; setCreating(true); setSelected(null); clearForm(); setMessage(null); setCreateScope(canEditProject ? "project" : "user"); }; - const cancelCreate = () => { - setCreating(false); setMessage(null); - if (agents[0]) { selectedRef.current = agents[0].name; setSelected(agents[0].name); fillForm(agents[0]); } - else { selectedRef.current = null; clearForm(); setSelected(null); } - }; - const unpack = async () => { - const requestGeneration = loadGenerationRef.current; - const requestCwd = cwd; - const isCurrent = () => loadGenerationRef.current === requestGeneration && cwdRef.current === requestCwd; - setSaving(true); setMessage(null); - try { - const scope: "user" | "project" = canEditProject ? "project" : "user"; - const res = await fetch("/api/agents", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "unpack", scope, cwd: scope === "project" ? cwd : undefined }) }); - const data = (await res.json()) as { error?: string; total?: number; written?: number }; - if (!res.ok || data.error) { - if (isCurrent() && res.status === 403 && scope === "project") setWorkspaceUnavailable(true); - throw new Error(data.error || `HTTP ${res.status}`); - } - if (!isCurrent()) return; - const count = data.written ?? data.total ?? 0; - toast.success(t("agentsConfig.unpackedToast", { count })); - await load(); - } catch (e) { if (!isCurrent()) return; const msg = e instanceof Error ? e.message : String(e); setMessage(msg); } - }; - const save = async () => { - const trimmedName = name.trim(); - if (!trimmedName) { setMessage(t("agentsConfig.nameRequired")); return; } - if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(trimmedName)) { setMessage(t("agentsConfig.namePatternError")); return; } - if (!description.trim()) { setMessage(t("agentsConfig.descriptionRequired")); return; } - const requestGeneration = loadGenerationRef.current; - const requestCwd = cwd; - const isCurrent = () => loadGenerationRef.current === requestGeneration && cwdRef.current === requestCwd; - setSaving(true); setMessage(null); - try { - const payload: Record = { description: description.trim(), body: body || undefined }; - // Preserve OMP frontmatter that this compact editor does not expose; - // the service overlays the fields edited below and always rewrites name. - if (!creating && active?.rawFrontmatter) payload.existingFrontmatter = active.rawFrontmatter; - if (modelCsv.trim()) payload.model = splitCsv(modelCsv); - if (toolsCsv.trim()) payload.tools = splitCsv(toolsCsv); - if (spawnsCsv.trim()) payload.spawns = spawnsCsv.trim() === "*" ? "*" : splitCsv(spawnsCsv); - if (thinkingLevel) payload.thinkingLevel = thinkingLevel; - const scope: "user" | "project" = creating ? createScope : active && active.scope !== "bundled" ? (active.scope as "user" | "project") : canEditProject ? "project" : "user"; - if (scope === "project" && !canEditProject) { - setMessage(t("agentsConfig.selectWorkspaceRequired")); - return; - } - const previousName = creating || isBundledActive || !active ? undefined : fileStem(active.filePath); - const res = await fetch("/api/agents", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ cwd: scope === "project" ? cwd : undefined, scope, name: trimmedName, previousName, agent: payload }) }); - const data = (await res.json()) as { error?: string }; - if (!res.ok || data.error) { - if (isCurrent() && res.status === 403 && scope === "project") setWorkspaceUnavailable(true); - throw new Error(data.error || `HTTP ${res.status}`); - } - if (!isCurrent()) return; - toast.success(creating ? t("agentsConfig.agentCreatedToast", { name: trimmedName }) : t("agentsConfig.agentSavedToast", { name: trimmedName })); - selectedRef.current = trimmedName; setCreating(false); setSelected(trimmedName); await load(true); - } catch (e) { if (!isCurrent()) return; const msg = e instanceof Error ? e.message : String(e); setMessage(msg); } - }; - const remove = async () => { - if (!active || active.scope === "bundled" || activeProjectUnavailable) return; - const requestGeneration = loadGenerationRef.current; - const requestCwd = cwd; - const isCurrent = () => loadGenerationRef.current === requestGeneration && cwdRef.current === requestCwd; - setSaving(true); setMessage(null); - try { - const res = await fetch("/api/agents", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ cwd: active.scope === "project" ? cwd : undefined, scope: active.scope, name: fileStem(active.filePath) }) }); - const data = (await res.json()) as { error?: string }; - if (!res.ok || data.error) { - if (isCurrent() && res.status === 403 && active.scope === "project") setWorkspaceUnavailable(true); - throw new Error(data.error || `HTTP ${res.status}`); - } - if (!isCurrent()) return; - toast.success(t("agentsConfig.agentRemovedToast", { name: active.name })); - selectedRef.current = null; setSelected(null); clearForm(); await load(); - } catch (e) { if (!isCurrent()) return; const msg = e instanceof Error ? e.message : String(e); setMessage(msg); } - }; - const copyPath = async (p: string) => { - try { await navigator.clipboard.writeText(p); toast.success(t("agentsConfig.pathCopied")); } - catch { setMessage(p); } - }; - - return ( -

-
-
-
-
- - - -
-
- {workspaceUnavailable ? ( -
-
- ) : null} - {diagnostics.length > 0 ? ( -
diagnostic.type === "error") ? "alert" : "status"} style={{ padding: "7px 10px", border: "1px solid var(--border)", borderRadius: "var(--radius-control)", background: "var(--bg-subtle)", color: "var(--text-muted)", fontSize: 11, lineHeight: 1.4 }}> - {diagnostics.map((diagnostic, index) => ( -
{diagnostic.type === "error" ? t("agentsConfig.diagnosticError") : diagnostic.type === "warning" ? t("agentsConfig.diagnosticWarning") : ""}{diagnostic.message ?? t("agentsConfig.diagnosticIssue")}
- ))} -
- ) : null} -
-
-
-
-
- {tn("agentsConfig.agentsCount", filtered.length)} - {loading ? {t("agentsConfig.loadingAgents")} : null} -
-
- {filtered.length === 0 ? ( -
- {loading ? t("agentsConfig.loadingAgents") : search ? t("agentsConfig.noMatch") : t("agentsConfig.noAgentsFound")} -
- ) : ( - filtered.map((a) => { - const isSelected = !creating && selected === a.name; - const dot = !a.valid ? "var(--status-error, #e5484d)" : a.enabled ? "var(--accent)" : "var(--border)"; - const badgeBg = a.scope === "bundled" ? "var(--bg-subtle)" : "color-mix(in srgb, var(--accent) 12%, transparent)"; - return ( - - ); - }) - )} -
-
-
- {creating || active ? ( - <> - {isBundledActive ? ( -
-
- ) : null} -
-
-
-
-
- {!creating && active ? ( -
- {shorten(active.filePath)} - -
- ) : ( -
{t("agentsConfig.createAgentDesc")}
- )} -
- {creating ? ( - - ) : null} -
- - - -`; - -test("a form submits its pre-checked and prefilled defaults untouched; checkbox groups give arrays", async () => { - const user = userEvent.setup(); - const responses = renderForm(html); - assert.ok(screen.getByText(/Choose how to deploy/), "paragraph text is shown"); - assert.ok(screen.getByText("Database"), "legend text is shown"); - assert.equal(screen.getByRole("radio", { name: /Postgres/ }).checked, true); - await user.click(screen.getByRole("button", { name: "Submit" })); - assert.deepEqual(responses, [{ data: { db: "pg", extras: ["cache", "metrics"], region: "eu", replicas: 3, notes: "keep it" } }]); -}); - -test("agent markup never becomes live HTML: scripts, handlers and buttons are dropped", () => { - renderForm(html); - const dialog = screen.getByRole("dialog"); - assert.equal(dialog.querySelector("script, img, [onerror], [onclick]"), null); - assert.equal(screen.queryByRole("button", { name: "Do it" }), null); - assert.equal(window.pwned, undefined); -}); - -test("form options preserve preformatted text and indentation", () => { - renderForm(`
`); - const pre = screen.getByRole("radio", { name: /Example/ }).closest("label").querySelector("pre"); - assert.ok(pre); - assert.equal(pre.textContent, "first line\n indented second line"); - assert.equal(pre.tabIndex, 0); - assert.ok(screen.getByRole("radio", { name: /indented second line/ })); -}); - -test("changed answers are submitted, an unchecked radio group is omitted", async () => { - const user = userEvent.setup(); - const responses = renderForm(`
- - - - -
`); - await user.click(screen.getByRole("checkbox", { name: /A$/ })); - await user.click(screen.getByRole("checkbox", { name: /B$/ })); - await user.click(screen.getByRole("checkbox", { name: /Agree/ })); - await user.click(screen.getByRole("button", { name: "Submit" })); - assert.deepEqual(responses, [{ data: { extras: ["b"], agree: "on" } }]); -}); - -test("a radio group's Other text is its value, and picking an option afterwards sets it aside", async () => { - const user = userEvent.setup(); - const responses = renderForm(`
`); - const other = screen.getByRole("textbox", { name: /Other/ }); - await user.click(screen.getByRole("radio", { name: /Red/ })); - await user.type(other, " Green "); - assert.equal(screen.getByRole("radio", { name: /Red/ }).checked, false, "typing drops the picked option"); - await user.click(screen.getByRole("button", { name: "Submit" })); - assert.deepEqual(responses, [{ data: { c: "Green" } }]); - await user.click(screen.getByRole("radio", { name: /Blue/ })); - await user.click(screen.getByRole("button", { name: "Submit" })); - assert.deepEqual(responses[1], { data: { c: "b" } }); -}); - -test("a checkbox group's Other text is appended to its array; blank adds nothing", async () => { - const user = userEvent.setup(); - const responses = renderForm(`
`); - await user.click(screen.getByRole("button", { name: "Submit" })); - await user.type(screen.getByRole("textbox", { name: /Other/ }), "mine"); - await user.click(screen.getByRole("button", { name: "Submit" })); - assert.deepEqual(responses, [{ data: { x: ["a"] } }, { data: { x: ["a", "mine"] } }]); -}); - -test("no Other box when an option is already labelled Other or the group has one option", () => { - renderForm(`
`); - assert.equal(screen.queryByRole("textbox"), null); -}); - -test("a required group is satisfied by its Other text", async () => { - const user = userEvent.setup(); - const responses = renderForm(`
`); - await user.click(screen.getByRole("button", { name: "Submit" })); - assert.deepEqual(responses, [], "nothing answered yet"); - await user.type(screen.getByRole("textbox", { name: /Other/ }), "Green"); - await user.click(screen.getByRole("button", { name: "Submit" })); - assert.deepEqual(responses, [{ data: { c: "Green" } }]); -}); - -test("controls named like HTMLFormElement members still submit", async () => { - const user = userEvent.setup(); - const responses = renderForm(`
`); - await user.click(screen.getByRole("button", { name: "Submit" })); - assert.deepEqual(responses, [{ data: { elements: "a", reportValidity: "b", querySelectorAll: "c", submit: "d", checkValidity: "e" } }]); -}); - -test("a choice's label keeps its text and inline markup in one block beside the control", () => { - // The row is a flex container: without the wrapper every text run and became its own column. - renderForm(`
Get omp - - -
`); - const label = screen.getByRole("radio", { name: /Download the matching/ }).closest("label"); - const [control, text, ...rest] = label.children; - assert.equal(control.type, "radio"); - assert.equal(rest.length, 0, "the label has exactly two flex items: the control and one text block"); - assert.equal(text.className, "extension-choice-text"); - assert.ok(text.querySelector("code"), "inline markup stays inside the text block"); - assert.equal(text.textContent.trim(), "Download the matching ompweb-omp and check its sha256."); -}); diff --git a/components/ExtensionDialog.test.mjs b/components/ExtensionDialog.test.mjs index dcb7b51d..00d7bc3d 100644 --- a/components/ExtensionDialog.test.mjs +++ b/components/ExtensionDialog.test.mjs @@ -64,7 +64,7 @@ test("question selection survives request replay but is cleared for the next que }); test("confirm answers true, and cancel answers with no value", async () => { - const request = { type: "ui_request", id: "omp-web:abc", method: "confirm", args: ["Delete it?", "This cannot be undone."] }; + const request = { type: "ui_request", id: "tau:abc", method: "confirm", args: ["Delete it?", "This cannot be undone."] }; const responses = []; const onRespond = (current, value) => responses.push({ id: current.id, value }); const view = render(React.createElement(ExtensionDialog, { request, onRespond, attached: true })); @@ -72,7 +72,7 @@ test("confirm answers true, and cancel answers with no value", async () => { screen.getByText("This cannot be undone."); fireEvent.click(screen.getByRole("button", { name: "Confirm" })); fireEvent.click(screen.getByRole("button", { name: "Cancel" })); - assert.deepEqual(responses, [{ id: "omp-web:abc", value: true }, { id: "omp-web:abc", value: undefined }]); + assert.deepEqual(responses, [{ id: "tau:abc", value: true }, { id: "tau:abc", value: undefined }]); } finally { view.unmount(); } @@ -81,7 +81,7 @@ test("confirm answers true, and cancel answers with no value", async () => { test("server-owned send confirmation shows named endpoints and escaped message text", () => { const request = { type: "ui_request", - id: "omp-web:send", + id: "tau:send", method: "confirm", args: ["Allow this session to send a message?", ""], serverPayload: { @@ -112,34 +112,6 @@ test("server-owned send confirmation shows named endpoints and escaped message t } }); -test("approve offers omp's choices and answers with the chosen ExtensionApprovalAnswer", async () => { - const request = { - type: "ui_request", - id: 7, - method: "approve", - args: [{ - full: "Run bash?\nrm -rf build", - compact: "Run bash? rm -rf build", - session: "Approve for this session", - grants: [{ scope: "folder", label: "Approve Directory: ~/src", alwaysLabel: "Always Approve Directory: ~/src" }], - }], - }; - const responses = []; - const onRespond = (_request, value) => responses.push(value); - const view = render(React.createElement(ExtensionDialog, { request, onRespond, attached: true })); - try { - screen.getByText("Run bash?"); - screen.getByText("rm -rf build"); - for (const name of ["Allow", "Approve for this session", "Approve Directory: ~/src", "Always Approve Directory: ~/src", "Deny"]) { - fireEvent.click(screen.getByRole("button", { name })); - } - assert.deepEqual(responses, ["once", "session", { grant: "folder", always: false }, { grant: "folder", always: true }, "deny"]); - assert.equal(screen.queryByRole("button", { name: "Submit" }), null); - } finally { - view.unmount(); - } -}); - test("omp's checkbox select shows which options are already checked", async () => { const request = { type: "ui_request", diff --git a/components/ExtensionDialog.tsx b/components/ExtensionDialog.tsx index 44b6eb75..56a303b6 100644 --- a/components/ExtensionDialog.tsx +++ b/components/ExtensionDialog.tsx @@ -1,9 +1,8 @@ "use client"; -import { createElement, Fragment, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode, type RefObject } from "react"; +import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode, type RefObject } from "react"; import { Eye, EyeOff } from "lucide-react"; -import type { HtmlFormData } from "@/lib/pi-types"; -import type { AgentConfirmPayload, UiApprovalAnswer, UiDialogRequest, UiDialogValue } from "@/lib/types"; +import type { AgentConfirmPayload, UiDialogRequest, UiDialogValue } from "@/lib/types"; import { useI18n } from "@/lib/i18n"; import { useModalDialog } from "@/hooks/useModalDialog"; import { matchMobileViewport } from "@/hooks/useIsMobile"; @@ -211,235 +210,12 @@ function initialAskDrafts(request: UiDialogRequest): AskDraft[] { function dialogTitle(request: UiDialogRequest, askTitle: string): string { switch (request.method) { case "askDialog": - case "formDialog": return askTitle; - case "approve": - return request.args[0].full.split("\n", 1)[0]; default: return request.args[0]; } } -/** omp's approval choices, in its order: this call, the session, each grant, then no. */ -function approvalChoices(request: Extract, allow: string, deny: string): { label: string; value: UiApprovalAnswer }[] { - const [prompt] = request.args; - return [ - { label: allow, value: "once" }, - ...(prompt.session ? [{ label: prompt.session, value: "session" as const }] : []), - ...(prompt.grants ?? []).flatMap((grant) => [ - { label: grant.label, value: { grant: grant.scope, always: false } }, - { label: grant.alwaysLabel, value: { grant: grant.scope, always: true } }, - ]), - { label: deny, value: "deny" }, - ]; -} - -// The agent's form markup becomes React elements: these tags render as themselves with only the -// attributes copied below; others contribute just their text, and dropped ones nothing at all. -const FORM_TAGS: Record = { - fieldset: true, legend: true, p: true, label: true, div: true, span: true, section: true, strong: true, em: true, b: true, i: true, - code: true, pre: true, small: true, br: true, hr: true, ul: true, ol: true, li: true, h1: true, h2: true, h3: true, h4: true, h5: true, h6: true, - input: true, select: true, option: true, optgroup: true, textarea: true, -}; -const DROPPED_TAGS: Record = { - script: true, style: true, template: true, noscript: true, button: true, iframe: true, object: true, embed: true, img: true, svg: true, math: true, -}; -const INPUT_TYPES: Record = { - radio: true, checkbox: true, text: true, number: true, range: true, email: true, url: true, tel: true, search: true, date: true, time: true, hidden: true, -}; - -/** A radio/checkbox group that offers a free-text "Other" answer, as omp's html-form adds one. */ -interface OtherGroup { type: string; name: string; required: boolean } -interface FormCtx { - prefix: string; - otherLabel: string; - /** Option element after which a group's Other box is rendered. */ - others: Map; - /** Options of those groups: their `required` moves to the Other box (see syncOtherValidity). */ - grouped: Set; - /** Bare radio/checkbox inputs mapped to their `
@@ -962,7 +696,7 @@ export function ExtensionDialog({ - ) : request.method !== "select" && request.method !== "approve" ? ( + ) : request.method !== "select" ? ( diff --git a/components/FileExplorer.tsx b/components/FileExplorer.tsx index 6150760e..b6ffe95c 100644 --- a/components/FileExplorer.tsx +++ b/components/FileExplorer.tsx @@ -18,6 +18,7 @@ import { import { getFileIcon } from "./FileIcons"; import { Tooltip } from "./ui/primitives"; import { translate, useI18n } from "@/lib/i18n"; +import { formatApiError } from "@/lib/i18n/api-error"; import { useIsMobile } from "@/hooks/useIsMobile"; import { encodeFilePathForApi, @@ -98,6 +99,7 @@ interface UploadResponse { conflicts?: string[]; nonReplaceable?: string[]; error?: string; + code?: string; } interface UploadSummary { @@ -913,7 +915,7 @@ export const FileExplorer = forwardRef(function FileE signal: operation.controller.signal, }); const data = await response.json() as UploadResponse; - if (!response.ok) throw new Error(data.error ?? translate("fileExplorer.uploadFailed", { status: response.status })); + if (!response.ok) throw new Error(data.error || data.code ? formatApiError(data) : translate("fileExplorer.uploadFailed", { status: response.status })); summary.uploaded.push(...data.uploaded ?? []); summary.skipped.push(...data.skipped ?? []); summary.errors.push(...data.errors ?? []); @@ -957,7 +959,7 @@ export const FileExplorer = forwardRef(function FileE }); const data = await response.json() as UploadResponse; if (!current() || operation.controller.signal.aborted) return; - if (!response.ok) throw new Error(data.error ?? translate("fileExplorer.uploadCheckFailed", { status: response.status })); + if (!response.ok) throw new Error(data.error || data.code ? formatApiError(data) : translate("fileExplorer.uploadCheckFailed", { status: response.status })); if (data.conflicts?.length) { setPendingConflict({ operation, conflicts: data.conflicts, nonReplaceable: data.nonReplaceable ?? [] }); return; diff --git a/components/FileViewer.markdown-links.test.mjs b/components/FileViewer.markdown-links.test.mjs index df918d83..379dc96b 100644 --- a/components/FileViewer.markdown-links.test.mjs +++ b/components/FileViewer.markdown-links.test.mjs @@ -48,7 +48,7 @@ async function renderPreview(filePath, opened) { return view; } -test("preview links never navigate omp-web away, and unservable images show their alt text", async () => { +test("preview links never navigate tau away, and unservable images show their alt text", async () => { const opened = []; const { container, getByText } = await renderPreview("/var/tmp/out/docs/guide.md", opened); diff --git a/components/FileViewer.tsx b/components/FileViewer.tsx index ed15792f..9be2bafb 100644 --- a/components/FileViewer.tsx +++ b/components/FileViewer.tsx @@ -1225,7 +1225,7 @@ function TextFileViewer({ filePath, hostId, cwd, sourceSessionId, onOpenFile, on ? resolveLocalFileHref(href, markdownDirectory, cwd ?? markdownDirectory) : null; if (!linkedFile || !onOpenFile) { - // Never let a preview link replace omp-web itself: in-page anchors stay, + // Never let a preview link replace tau itself: in-page anchors stay, // web links open a new tab, and a path the panel cannot open (such as a // relative link in a Markdown file outside the workspace) is plain text. if (href?.startsWith("#")) return {children}; diff --git a/components/HostUpdates.test.mjs b/components/HostUpdates.test.mjs index c7ac8ddf..cf628355 100644 --- a/components/HostUpdates.test.mjs +++ b/components/HostUpdates.test.mjs @@ -7,19 +7,18 @@ import { HostUpdates } from "./HostUpdates"; const endpoint = "/api/hosts/box/updates"; const info = { - ompweb: { currentVersion: "0.7.0", availableVersion: "0.7.1", updateAvailable: true, canUpdate: true, blockedReason: null, updateCommand: "npm install -g @kahme247/ompweb", installMethod: "npm", protocolVersion: 12 }, - omp: { currentVersion: "18.20.0" }, + tau: { currentVersion: "0.7.0", availableVersion: "0.7.1", updateAvailable: true, canUpdate: true, blockedReason: null, updateCommand: "npm install -g @ompweb-dev/tau", installMethod: "npm", protocolVersion: 12 }, operation: null, }; /** Render the real host row and record every request it sends. */ -async function renderHost(t, host, ompweb = {}, operation = null) { +async function renderHost(t, host, tau = {}, operation = null) { const requests = []; const originalFetch = globalThis.fetch; globalThis.fetch = async (url, init) => { requests.push({ url: String(url), method: init?.method ?? "GET", body: init?.body }); - if (init?.method === "POST") return Response.json({ accepted: true, operation: { state: "running", target: "ompweb", version: "0.7.1" } }); - return Response.json({ ...info, operation, ompweb: { ...info.ompweb, ...ompweb } }); + if (init?.method === "POST") return Response.json({ accepted: true, operation: { state: "running", target: "tau", version: "0.7.1" } }); + return Response.json({ ...info, operation, tau: { ...info.tau, ...tau } }); }; const container = document.createElement("div"); document.body.append(container); @@ -38,8 +37,8 @@ async function renderHost(t, host, ompweb = {}, operation = null) { const button = (root, label) => [...root.querySelectorAll("button")].find((candidate) => candidate.textContent.trim() === label); -test("an upgrade-only legacy host can check for and submit an ompweb update", async (t) => { - const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "needs-upgrade", upgradeOnly: true, ompVersion: "omp/18.20.0", ompwebVersion: "0.7.0" }); +test("an upgrade-only legacy host can check for and submit an tau update", async (t) => { + const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "needs-upgrade", upgradeOnly: true, apiVersion: 1, piVersion: "omp/18.20.0", tauVersion: "0.7.0" }); assert.equal(requests[0]?.url, endpoint, "the status is read on mount"); assert.equal(button(container, "Check updates").disabled, false); @@ -54,18 +53,18 @@ test("an upgrade-only legacy host can check for and submit an ompweb update", as await act(() => new Promise((resolve) => setTimeout(resolve, 20))); const post = requests.find((request) => request.method === "POST"); assert.ok(post, "the update was not submitted"); - assert.deepEqual(JSON.parse(post.body), { target: "ompweb", version: "0.7.1" }); + assert.deepEqual(JSON.parse(post.body), { target: "tau", version: "0.7.1" }); }); test("a connected maintenance API can update a compatible host while its application connection is offline", async (t) => { - const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "offline", apiVersion: 1, hostVersion: 12, ompwebVersion: "0.7.0" }); + const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "offline", apiVersion: 1, hostVersion: 12, tauVersion: "0.7.0" }); assert.equal(requests[0]?.url, endpoint); assert.equal(button(container, "Check updates").disabled, false); assert.ok(button(container, "Update")); }); test("an ordinary incompatible host cannot be checked or updated", async (t) => { - const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "needs-upgrade", ompVersion: "omp/18.20.0", ompwebVersion: "0.6.0" }); + const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "needs-upgrade", piVersion: "omp/18.20.0", tauVersion: "0.6.0" }); assert.deepEqual(requests, [], "an unavailable host must not be read"); const check = button(container, "Check updates"); assert.equal(check.disabled, true); @@ -75,14 +74,22 @@ test("an ordinary incompatible host cannot be checked or updated", async (t) => assert.deepEqual(requests, []); }); +test("an online host without its maintenance connection cannot be checked or updated, and says why", async (t) => { + const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "online", piVersion: "18.20.0", tauVersion: "0.7.0" }); + assert.deepEqual(requests, [], "updates never go over the application link"); + assert.equal(button(container, "Check updates").disabled, true); + assert.ok(container.textContent.includes("Updates need this host's maintenance connection"), container.textContent); + assert.ok(container.textContent.includes("18.20.0"), "the pi version still shows"); +}); + test("an offline host stays unavailable", async (t) => { - const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "offline", ompVersion: "omp/18.20.0", ompwebVersion: "0.7.0" }); + const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "offline", piVersion: "omp/18.20.0", tauVersion: "0.7.0" }); assert.deepEqual(requests, []); assert.equal(button(container, "Check updates").disabled, true); assert.ok(container.textContent.includes("Updates unavailable while this host is offline."), container.textContent); }); -const modern = { id: "box", label: "Box", status: "online", apiVersion: 1, hostVersion: 12, ompwebVersion: "0.7.0" }; +const modern = { id: "box", label: "Box", status: "online", apiVersion: 1, hostVersion: 12, tauVersion: "0.7.0" }; const blocked = { canUpdate: false, canForceUpdate: true, blockedReason: "Sessions are running on this host" }; const posts = (requests) => requests.filter((request) => request.method === "POST"); // A closing dialog may linger briefly; the newest one is the one on screen. @@ -105,7 +112,7 @@ test("a normally blocked host offers a distinct Force update that posts nothing await act(async () => dialogButton("Terminate sessions and update").click()); await act(() => new Promise((resolve) => setTimeout(resolve, 20))); assert.equal(posts(requests).length, 1); - assert.deepEqual(JSON.parse(posts(requests)[0].body), { target: "ompweb", version: "0.7.1", force: true }); + assert.deepEqual(JSON.parse(posts(requests)[0].body), { target: "tau", version: "0.7.1", force: true }); }); test("force is never inferred from a blocker's wording", async (t) => { @@ -120,7 +127,7 @@ test("a host that can be updated normally offers no force and the normal payload act(() => button(container, "Update").click()); await act(async () => dialogButton("Update").click()); await act(() => new Promise((resolve) => setTimeout(resolve, 20))); - assert.deepEqual(JSON.parse(posts(requests)[0].body), { target: "ompweb", version: "0.7.1" }); + assert.deepEqual(JSON.parse(posts(requests)[0].body), { target: "tau", version: "0.7.1" }); }); test("a forced update outlives the old 5-minute wait, and giving up later only asks for a status check", async (t) => { @@ -129,12 +136,12 @@ test("a forced update outlives the old 5-minute wait, and giving up later only a Date.now = () => realNow() + skewMs; const requests = []; let posted = false; - const running = { id: "op", target: "ompweb", version: "0.7.1", state: "running", force: true }; + const running = { id: "op", target: "tau", version: "0.7.1", state: "running", force: true }; const originalFetch = globalThis.fetch; globalThis.fetch = async (url, init) => { requests.push({ url: String(url), method: init?.method ?? "GET", body: init?.body }); if (init?.method === "POST") { posted = true; return Response.json({ accepted: true, operation: running }); } - return Response.json({ ...info, ompweb: { ...info.ompweb, ...blocked }, operation: posted ? running : null }); + return Response.json({ ...info, tau: { ...info.tau, ...blocked }, operation: posted ? running : null }); }; const container = document.createElement("div"); document.body.append(container); @@ -156,7 +163,7 @@ test("a forced update outlives the old 5-minute wait, and giving up later only a skewMs = 6 * 60_000; // past the old 5-minute limit, inside the 15-minute lease await settle(1200); - assert.ok(container.textContent.includes("Updating ompweb host to 0.7.1"), container.textContent); + assert.ok(container.textContent.includes("Updating tau host to 0.7.1"), container.textContent); assert.ok(!container.textContent.includes("Stopped waiting"), "gave up inside the backend lease"); skewMs = 21 * 60_000; // beyond the wait @@ -169,7 +176,7 @@ test("a forced update outlives the old 5-minute wait, and giving up later only a }); test("uncertain shutdown recovery shows its durable error instead of polling Updating forever", async (t) => { - const operation = { id: "pending-stop", target: "ompweb", version: "0.7.1", state: "running", committing: true, recoveryRequired: true, error: "Recovery required: the daemon's shutdown could not be reconciled" }; + const operation = { id: "pending-stop", target: "tau", version: "0.7.1", state: "running", committing: true, recoveryRequired: true, error: "Recovery required: the daemon's shutdown could not be reconciled" }; const { container, requests } = await renderHost(t, modern, blocked, operation); assert.ok(container.querySelector('[role="alert"]').textContent.includes(operation.error)); assert.equal(button(container, "Check updates").disabled, false); diff --git a/components/HostUpdates.tsx b/components/HostUpdates.tsx index d084d9b8..b7ddf02b 100644 --- a/components/HostUpdates.tsx +++ b/components/HostUpdates.tsx @@ -32,8 +32,8 @@ export function HostUpdates({ host }: { host: HostRow }) { const mounted = useRef(true); const postController = useRef(null); const endpoint = `/api/hosts/${encodeURIComponent(host.id)}/updates`; - const upgradeOnly = host.status === "needs-upgrade" && host.upgradeOnly === true; - const unavailable = (host.status === "offline" || host.status === "needs-upgrade") && !upgradeOnly && host.apiVersion !== 1; + // Updates go only through the host's maintenance connection (apiVersion is present while it is up). + const unavailable = host.apiVersion !== 1; useEffect(() => { mounted.current = true; @@ -83,7 +83,7 @@ export function HostUpdates({ host }: { host: HostRow }) { } if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`); // A successful status read, not POST acceptance, establishes the result. - if (!data.ompweb || !data.omp) throw new Error(t("hostUpdates.invalidResponse")); + if (!data.tau) throw new Error(t("hostUpdates.invalidResponse")); const next = data as HostUpdateInfo; setInfo(next); setError(null); @@ -169,7 +169,7 @@ export function HostUpdates({ host }: { host: HostRow }) { const busy = loading || posting || monitoring; const disabled = busy || unavailable || unsupported; - const unavailableReason = (host.status === "needs-upgrade" && unavailable) || unsupported ? t("hostUpdates.unsupported") : host.status === "offline" && unavailable ? t("hostUpdates.offline") : null; + const unavailableReason = (host.status === "needs-upgrade" && unavailable) || unsupported ? t("hostUpdates.unsupported") : host.status === "offline" && unavailable ? t("hostUpdates.offline") : unavailable ? t("hostUpdates.maintenanceUnavailable") : null; const operation = info?.operation; return (
@@ -179,10 +179,11 @@ export function HostUpdates({ host }: { host: HostRow }) {
- {(["ompweb", "omp"] as const).map((target) => { - const software = info?.[target]; + {/* pi is shown, not updated: host updates install tau only. */} + {(["tau", "pi"] as const).map((target) => { + const software = target === "tau" ? info?.tau : undefined; const label = t(`hostUpdates.${target}`); - const fallbackVersion = target === "ompweb" ? host.ompwebVersion : host.ompVersion?.replace(/^(?:omp|pi)\//, ""); + const fallbackVersion = target === "tau" ? host.tauVersion : host.piVersion?.replace(/^pi\//, ""); const updateDisabled = disabled || needsStatus || operation?.recoveryRequired === true || !software?.canUpdate; const forceable = operation?.recoveryRequired !== true && software?.updateAvailable === true && !software.canUpdate && software.canForceUpdate === true; return ( @@ -197,8 +198,8 @@ export function HostUpdates({ host }: { host: HostRow }) { {forceable &&
{t("hostUpdates.forceAvailable")}
}
- {software?.updateAvailable && software.availableVersion && } - {forceable && software.availableVersion && } + {software?.updateAvailable && software.availableVersion && } + {forceable && software.availableVersion && }
); diff --git a/components/HostsConfig.cluster.test.mjs b/components/HostsConfig.cluster.test.mjs index 2640799b..5fee84c8 100644 --- a/components/HostsConfig.cluster.test.mjs +++ b/components/HostsConfig.cluster.test.mjs @@ -23,13 +23,13 @@ afterEach(() => { globalThis.Worker = originalWorker; }); -const member = (hostId) => ({ hostId, projectsRoot: `/srv/${hostId}/ompweb-cluster`, provisioned: true, draining: false }); +const member = (hostId) => ({ hostId, projectsRoot: `/srv/${hostId}/tau-cluster`, provisioned: true, draining: false }); const cluster = (...hostIds) => [{ id: "cluster", label: "Cluster", enabled: true, members: hostIds.map(member), projects: [] }]; const hostRow = (overrides = {}) => ({ - id: "local", label: "", status: "online", ompVersion: "omp/15.13.1", platform: "linux", - hostVersion: 10, serverVersion: 10, lastSeenAt: null, workspaceOps: ["gitOrigins"], ...overrides, + id: "local", label: "", status: "online", piVersion: "1.5.2", platform: "linux", + hostVersion: 10, serverVersion: 10, lastSeenAt: null, ...overrides, }); -const linked = (id, label, overrides = {}) => hostRow({ id, label, allowAgentStart: false, shareCredentials: false, ...overrides }); +const linked = (id, label, overrides = {}) => hostRow({ id, label, allowAgentStart: false, ...overrides }); /** `pools: null` makes GET /api/hosts fail, `"pending"` never answers it, a promise answers it once settled (null failing), and a function * is asked on every request (null failing); `home: null` makes GET /api/home fail. Other requests go to `respond`. */ @@ -48,7 +48,7 @@ async function showHosts(t, { hosts, pools = [], home = "/home/andre", respond = calls.push({ method, url: String(url) }); return home === null ? Response.json({ error: "Host offline" }, { status: 409 }) : Response.json({ home }); } - if (String(url).includes("/updates")) return Response.json({ ompweb: null, omp: null, operation: null }); + if (String(url).includes("/updates")) return Response.json({ tau: null, omp: null, operation: null }); calls.push({ method, url: String(url), body: init?.body === undefined ? undefined : JSON.parse(init.body) }); return respond(url, init); }); @@ -91,9 +91,6 @@ test("a first pool without this machine gives its row no master label", async (t const RESTART = "Restart the host service on this machine first"; for (const [label, local, pools, reason] of [ ["offline", { status: "offline" }, [], RESTART], - ["without gitOrigins", { workspaceOps: [] }, cluster("h1"), RESTART], - // A restart does not update omp: the reason names what this machine needs. - ["on an omp too old to share credentials", { ompVersion: "omp/15.13.0" }, [], "Update omp on This machine to 15.13.1 or newer first"], ]) { test(`while this machine must join too and is ${label}, a non-member cannot join and says why; a member can still leave`, async (t) => { await showHosts(t, { hosts: [hostRow(local), linked("h1", "Laptop"), linked("h2", "Desk")], pools }); @@ -112,13 +109,8 @@ test("once this machine is a member, its own readiness no longer blocks a join", for (const [label, row, reason] of [ ["offline", { status: "offline" }, "The host is offline"], - ["no gitOrigins operation", { workspaceOps: [] }, "Update ompweb on this host first"], - ["flagged needs-upgrade by the hub", { status: "needs-upgrade", hostVersion: 9 }, "Update ompweb on this host first"], - // Members always share credentials; the daemon refuses that below omp 15.13.1, and on an omp it cannot read. - ["on an omp too old to share credentials", { ompVersion: "omp/15.13.0" }, "Update omp on Laptop to 15.13.1 or newer first"], - ["on an unknown omp", { ompVersion: "omp/next" }, "Update omp on Laptop to 15.13.1 or newer first"], - ["on an outdated daemon and an old omp (the daemon first)", { workspaceOps: [], ompVersion: "omp/15.13.0" }, "Update ompweb on this host first"], - ["without omp (its own status text is the reason)", { status: "omp-missing" }, "omp not installed"], + ["flagged needs-upgrade by the hub", { status: "needs-upgrade", hostVersion: 9 }, "Update tau on this host first"], + ["without omp (its own status text is the reason)", { status: "pi-missing" }, "pi not installed"], ]) { test(`a host that is ${label} cannot join and says why`, async (t) => { await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop", row)], pools: cluster("local") }); @@ -139,7 +131,7 @@ test("when the pools cannot be loaded every switch is disabled with poolsUnavail test("a member can always leave: offline or outdated never disables its switch", async (t) => { await showHosts(t, { - hosts: [hostRow(), linked("h1", "Laptop", { status: "offline" }), linked("h2", "Desk", { workspaceOps: [] })], + hosts: [hostRow(), linked("h1", "Laptop", { status: "offline" }), linked("h2", "Desk", { status: "needs-upgrade" })], pools: cluster("local", "h1", "h2"), }); for (const name of ["Laptop", "Desk"]) { @@ -150,31 +142,20 @@ test("a member can always leave: offline or outdated never disables its switch", } }); -test("a member's provider-login toggle is on and disabled, described by the reason", async (t) => { - await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop"), linked("h2", "Desk")], pools: cluster("local", "h1") }); - const forced = screen.getByRole("switch", { name: "Use this server's provider logins on Laptop" }); - assert.equal(forced.getAttribute("aria-checked"), "true"); - assert.equal(forced.disabled, true); - assert.equal(reasonOf(forced), "On while the host is in the cluster"); - const other = screen.getByRole("switch", { name: "Use this server's provider logins on Desk" }); - assert.equal(other.getAttribute("aria-checked"), "false"); - assert.equal(other.disabled, false); -}); - test("joining asks for the folder, prefilled from the host's home, and sends it", async (t) => { const { calls, user } = await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop")], pools: cluster("local") }); await user.click(clusterSwitch("Laptop")); const dialog = await screen.findByRole("dialog", { name: "Add Laptop to the cluster?" }); const folder = within(dialog).getByLabelText("Folder on Laptop for the cluster's checkouts"); - await waitFor(() => assert.equal(folder.value, "/home/andre/ompweb-cluster")); + await waitFor(() => assert.equal(folder.value, "/home/andre/tau-cluster")); assert.deepEqual(calls.filter((call) => call.url.startsWith("/api/home")), [{ method: "GET", url: "/api/home?hostId=h1" }]); assert.ok(within(dialog).getByText(/Its Git projects that match a cluster repository or can be added as one become cluster projects, unless they are inside or contain the cluster folder/)); - assert.ok(within(dialog).getByText(/Laptop will use this machine's provider logins/)); - assert.ok(within(dialog).getByText("It receives this machine's omp configuration (settings, models, MCP servers, skills, plugins, rules), API keys and environment values included, in place of its own until it leaves; its own is kept and put back then.")); + assert.ok(within(dialog).getByText(/Laptop keeps its own provider logins/)); + assert.ok(within(dialog).getByText("It receives this machine's pi configuration (settings and packages, models, MCP servers, skills, prompts, extensions, context files), API keys and environment values included, in place of its own until it leaves; its own is kept and put back then.")); assert.equal(calls.some((call) => call.method === "PUT"), false); await user.click(within(dialog).getByRole("button", { name: "Add to cluster" })); - await waitFor(() => assert.deepEqual(calls.find((call) => call.method === "PUT"), { method: "PUT", url: "/api/hosts/h1/cluster", body: { projectsRoot: "/home/andre/ompweb-cluster" } })); + await waitFor(() => assert.deepEqual(calls.find((call) => call.method === "PUT"), { method: "PUT", url: "/api/hosts/h1/cluster", body: { projectsRoot: "/home/andre/tau-cluster" } })); await waitFor(() => assert.equal(screen.queryByRole("dialog"), null)); }); @@ -185,7 +166,7 @@ for (const [label, pools, says] of [["no cluster", [], true], ["a first pool wit const dialog = await screen.findByRole("dialog", { name: "Add Laptop to the cluster?" }); const note = within(dialog).queryByText(/^This machine joins too: its Git projects that match a cluster repository or can be added as one become cluster projects/); assert.equal(note !== null, says); - if (says) assert.match(note.textContent, /unless they are inside or contain the ompweb-cluster folder in its home folder.*any member with capacity \(currently Linux hosts only\)/); + if (says) assert.match(note.textContent, /unless they are inside or contain the tau-cluster folder in its home folder.*any member with capacity \(currently Linux hosts only\)/); }); } @@ -253,7 +234,7 @@ test("a relative folder is refused in the dialog without a request", async (t) = const folder = within(dialog).getByLabelText(/Folder on Laptop/); await waitFor(() => assert.notEqual(folder.value, "")); await user.clear(folder); - await user.type(folder, "ompweb-cluster"); + await user.type(folder, "tau-cluster"); await user.click(within(dialog).getByRole("button", { name: "Add to cluster" })); assert.equal(calls.some((call) => call.method === "PUT"), false); assert.ok(within(dialog).getByRole("alert")); @@ -264,7 +245,7 @@ test("leaving is confirmed, then sends DELETE", async (t) => { const { calls, user } = await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop")], pools: cluster("local", "h1") }); await user.click(clusterSwitch("Laptop")); const dialog = await screen.findByRole("dialog", { name: "Remove Laptop from the cluster?" }); - assert.ok(within(dialog).getByText(/The cluster keeps the projects it gained from Laptop; hide any you do not want\. Laptop gets its own omp configuration back\./)); + assert.ok(within(dialog).getByText(/The cluster keeps the projects it gained from Laptop; hide any you do not want\. Laptop gets its own pi configuration back\./)); assert.equal(calls.some((call) => call.method === "DELETE"), false); await user.click(within(dialog).getByRole("button", { name: "Cancel" })); await waitFor(() => assert.equal(screen.queryByRole("dialog"), null)); @@ -280,22 +261,22 @@ test("a leave whose own configuration could not be put back says so and why", as t.mock.method(toast, "error", (message) => { errors.push(message); }); const { user } = await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop")], pools: cluster("local", "h1"), - respond: async () => Response.json({ pools: cluster("local"), restoreError: "omp-web/own-config/agent is not readable" }), + respond: async () => Response.json({ pools: cluster("local"), restoreError: "tau/own-config/agent is not readable" }), }); await user.click(clusterSwitch("Laptop")); await user.click(within(await screen.findByRole("dialog")).getByRole("button", { name: "Remove" })); - await waitFor(() => assert.deepEqual(errors, ["Laptop left the cluster, but its own omp configuration could not be put back: omp-web/own-config/agent is not readable. It is retried automatically while the host is linked."])); + await waitFor(() => assert.deepEqual(errors, ["Laptop left the cluster, but its own pi configuration could not be put back: tau/own-config/agent is not readable. It is retried automatically while the host is linked."])); }); -const configState = (fields = {}) => ({ version: "a".repeat(64), files: "current", plugins: "current", error: null, missingCommands: [], owned: true, current: true, ...fields }); -const configLines = (name) => within(rowOf(name)).queryAllByText(/^(Configuration:|Not installed on this host:|Update ompweb on this host first)/).map((line) => line.textContent); +const configState = (fields = {}) => ({ version: "a".repeat(64), files: "current", error: null, missingCommands: [], owned: true, current: true, ...fields }); +const configLines = (name) => within(rowOf(name)).queryAllByText(/^(Configuration:|Not installed on this host:|Update tau on this host first)/).map((line) => line.textContent); for (const [label, overrides, lines] of [ ["current", { clusterConfig: configState() }, ["Configuration: same as the master"]], - ["updating", { clusterConfig: configState({ plugins: "pending", current: false }) }, ["Configuration: updating…"]], + ["updating", { clusterConfig: configState({ version: "b".repeat(64), current: false }) }, ["Configuration: updating…"]], ["not reported yet", {}, ["Configuration: updating…"]], ["failed", { clusterConfig: configState({ files: "failed", error: "the master answered 500 for the manifest", current: false }) }, ["Configuration: failed — the master answered 500 for the manifest"]], - ["held by another server", { clusterConfig: configState({ owned: false, current: false }) }, ["Configuration: held by another ompweb server; remove it from that server's cluster first"]], + ["held by another server", { clusterConfig: configState({ owned: false, current: false }) }, ["Configuration: held by another tau server; remove it from that server's cluster first"]], ["current, with commands it lacks", { clusterConfig: configState({ missingCommands: ["uvx", "docker"] }) }, ["Configuration: same as the master", "Not installed on this host: uvx, docker"]], ["offline, with its last report", { status: "offline", clusterConfig: configState({ missingCommands: ["uvx"] }) }, []], ["offline, never reported", { status: "offline" }, []], @@ -306,7 +287,7 @@ for (const [label, overrides, lines] of [ }); } -const MASTER_ERROR = { code: "file_too_large", message: "rules/big.md is 6000000 bytes, over the 5242880 byte limit" }; +const MASTER_ERROR = { code: "file_too_large", message: "skills/big.md is 6000000 bytes, over the 5242880 byte limit" }; const masterErrors = () => screen.queryAllByText(/^Members cannot get this machine's configuration/).map((line) => line.textContent); test("a master configuration the members cannot get is said once, above the member rows, until it works again", async (t) => { @@ -329,7 +310,7 @@ test("without linked members the master configuration error is not shown", async }); test("while members cannot get this machine's configuration, no member row says it is updating", async (t) => { - const hosts = [hostRow(), linked("h1", "Laptop"), linked("h2", "Desk", { clusterConfig: configState({ plugins: "pending", current: false }) })]; + const hosts = [hostRow(), linked("h1", "Laptop"), linked("h2", "Desk", { clusterConfig: configState({ version: "b".repeat(64), current: false }) })]; const { frame } = await showHosts(t, { hosts, pools: cluster("local", "h1", "h2") }); assert.deepEqual([configLines("Laptop"), configLines("Desk")], [["Configuration: updating…"], ["Configuration: updating…"]]); frame({ hosts, masterConfigError: MASTER_ERROR }); @@ -370,36 +351,24 @@ for (const [label, saved, reloads] of LOST) { await waitFor(() => assert.equal(remove.disabled, false)); }); } -test("while the pools load, every switch and share toggle is disabled and nothing is sent", async (t) => { - const { calls, user } = await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop"), linked("h2", "Desk", { shareCredentials: true })], pools: "pending" }); +test("while the pools load, every switch is disabled and nothing is sent", async (t) => { + const { calls, user } = await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop"), linked("h2", "Desk")], pools: "pending" }); for (const name of ["Laptop", "Desk"]) { const toggle = clusterSwitch(name); assert.equal(toggle.disabled, true); assert.equal(toggle.getAttribute("aria-describedby"), null, "no error text while still loading"); - const share = screen.getByRole("switch", { name: `Use this server's provider logins on ${name}` }); - assert.equal(share.disabled, true); - assert.equal(share.getAttribute("aria-describedby"), null); await user.click(toggle); - await user.click(share); } assert.deepEqual(calls.filter((call) => call.method !== "GET"), []); assert.equal(screen.queryByRole("dialog"), null); }); -test("when the pools failed to load, share toggles are disabled with poolsUnavailable", async (t) => { - await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop")], pools: null }); - const share = screen.getByRole("switch", { name: "Use this server's provider logins on Laptop" }); - assert.equal(share.disabled, true); - assert.equal(reasonOf(share), "The cluster configuration could not be loaded"); -}); - test("a hosts frame that carries pools recovers from a failed first request", async (t) => { const { frame } = await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop")], pools: null }); assert.equal(clusterSwitch("Laptop").disabled, true); frame({ hosts: [hostRow(), linked("h1", "Laptop")], pools: cluster("local") }); await waitFor(() => assert.equal(clusterSwitch("Laptop").disabled, false)); assert.equal(clusterSwitch("Laptop").getAttribute("aria-describedby"), null); - assert.equal(screen.getByRole("switch", { name: "Use this server's provider logins on Laptop" }).disabled, false); }); for (const [label, late] of [["answers", []], ["fails", null]]) { @@ -419,17 +388,6 @@ for (const [label, late] of [["answers", []], ["fails", null]]) { }); } -test("a frame that removes a member returns its share toggle to the stored flag", async (t) => { - const { frame } = await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop")], pools: cluster("local", "h1") }); - const share = () => screen.getByRole("switch", { name: "Use this server's provider logins on Laptop" }); - assert.equal(share().getAttribute("aria-checked"), "true"); - assert.equal(share().disabled, true); - frame({ hosts: [hostRow(), linked("h1", "Laptop")], pools: cluster("local") }); - await waitFor(() => assert.equal(share().getAttribute("aria-checked"), "false")); - assert.equal(share().disabled, false); - assert.equal(share().getAttribute("aria-describedby"), null); -}); - test("the folder field is required", async (t) => { const { user } = await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop")], pools: cluster("local") }); await user.click(clusterSwitch("Laptop")); diff --git a/components/HostsConfig.test.mjs b/components/HostsConfig.test.mjs index 662f3d79..ae926098 100644 --- a/components/HostsConfig.test.mjs +++ b/components/HostsConfig.test.mjs @@ -33,7 +33,7 @@ function mockHostRequests(t, respond) { test("the one-time host token survives Escape; only Done closes it", async (t) => { // The hosts list rides the shared event-stream worker; a silent one keeps it idle. globalThis.Worker = FakeWorker; - mockHostRequests(t, async () => Response.json({ host: { id: "h1", label: "Laptop" }, token: "tok-once", command: "ompweb host login --url https://omp.test" })); + mockHostRequests(t, async () => Response.json({ host: { id: "h1", label: "Laptop" }, token: "tok-once", command: "tau host login --url https://omp.test" })); render(createElement(HostsConfig)); const user = userEvent.setup(); await user.click(screen.getByRole("button", { name: "Add host" })); @@ -58,7 +58,7 @@ test("this machine can be renamed but not revoked", async (t) => { return Response.json({}); }); render(createElement(HostsConfig)); - const row = (fields) => ({ status: "online", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, workspaceOps: [], ...fields }); + const row = (fields) => ({ status: "online", piVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, ...fields }); const hosts = [row({ id: "local", label: "" }), row({ id: "h1", label: "Laptop", allowAgentStart: false })]; await waitFor(() => assert.ok(workers[0].posted.some((message) => message.op === "open" && message.channel.kind === "hosts"))); const { id } = workers[0].posted.findLast((message) => message.op === "open" && message.channel.kind === "hosts"); @@ -84,29 +84,29 @@ test("an offline this-machine row says to start the service, with the server's i globalThis.Worker = FakeWorker; mockHostRequests(t, async () => Response.json({})); render(createElement(HostsConfig)); - const row = (fields) => ({ id: "local", label: "", status: "offline", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, workspaceOps: [], serverPlatform: "darwin", daemonManaged: true, ...fields }); + const row = (fields) => ({ id: "local", label: "", status: "offline", piVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, serverPlatform: "darwin", daemonManaged: true, ...fields }); await waitFor(() => assert.ok(workers[0].posted.some((message) => message.op === "open" && message.channel.kind === "hosts"))); const { id } = workers[0].posted.findLast((message) => message.op === "open" && message.channel.kind === "hosts"); const send = (hosts) => act(() => workers[0].onmessage({ data: { id, type: "message", data: JSON.stringify({ hosts }) } })); send([row({})]); - const hint = await screen.findByText(/ompweb-host service/); - assert.deepEqual([...hint.closest("li").querySelectorAll("code")].map((code) => code.textContent), ["ompweb launchd install", "ompweb host"]); + const hint = await screen.findByText(/tau-host service/); + assert.deepEqual([...hint.closest("li").querySelectorAll("code")].map((code) => code.textContent), ["tau launchd install", "tau host"]); assert.match(hint.closest("li").textContent, /in a terminal or with npx/); // The commands are copyable; the local row still has no Revoke. assert.equal(within(hint.closest("li")).queryByRole("button", { name: "Revoke" }), null); send([row({ serverPlatform: "linux" })]); - assert.equal((await screen.findByText(/ompweb-host service/)).closest("li").querySelector("code").textContent, "ompweb systemd install"); + assert.equal((await screen.findByText(/tau-host service/)).closest("li").querySelector("code").textContent, "tau systemd install"); send([row({ serverPlatform: "win32" })]); - assert.equal((await screen.findByText(/ompweb-host service/)).closest("li").querySelector("code").textContent, "ompweb-tray install"); + assert.equal((await screen.findByText(/tau-host service/)).closest("li").querySelector("code").textContent, "tau-tray install"); // Dev mode: offline by design, nothing to install. send([row({ daemonManaged: false })]); - await waitFor(() => assert.equal(screen.queryByText(/ompweb-host service/), null)); + await waitFor(() => assert.equal(screen.queryByText(/tau-host service/), null)); send([row({ status: "online", hostVersion: 2, serverVersion: 3 })]); - await waitFor(() => assert.equal(screen.queryByText(/ompweb-host service/), null)); + await waitFor(() => assert.equal(screen.queryByText(/tau-host service/), null)); // The daemon's protocol on its row, the web app's in the header; a needs-upgrade status already names both. assert.match(screen.getByRole("button", { name: "Rename This machine" }).closest("li").textContent, /link protocol v2/); screen.getByText("This web app expects link protocol v3."); @@ -118,7 +118,7 @@ test("the local name hint is the input's description, not part of its label", as globalThis.Worker = FakeWorker; mockHostRequests(t, async () => Response.json({})); render(createElement(HostsConfig)); - const row = { id: "local", label: "", status: "online", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: 3, serverVersion: 3, workspaceOps: [], serverPlatform: "linux", daemonManaged: true }; + const row = { id: "local", label: "", status: "online", piVersion: null, platform: null, lastSeenAt: null, hostVersion: 3, serverVersion: 3, serverPlatform: "linux", daemonManaged: true }; await waitFor(() => assert.ok(workers[0].posted.some((message) => message.op === "open" && message.channel.kind === "hosts"))); const { id } = workers[0].posted.findLast((message) => message.op === "open" && message.channel.kind === "hosts"); act(() => workers[0].onmessage({ data: { id, type: "message", data: JSON.stringify({ hosts: [row] }) } })); @@ -133,13 +133,12 @@ const software = (overrides = {}) => ({ canUpdate: true, blockedReason: null, updateCommand: "fixture update", ...overrides, }); const updateInfo = (overrides = {}) => ({ - ompweb: software({ installMethod: "npm", protocolVersion: 3 }), - omp: { currentVersion: "2.0.0" }, + tau: software({ installMethod: "npm", protocolVersion: 3 }), operation: null, ...overrides, }); const hostRow = (overrides = {}) => ({ - id: "local", label: "", status: "online", ompVersion: "1.0.0", platform: "linux", - hostVersion: 3, serverVersion: 3, lastSeenAt: null, workspaceOps: [], ...overrides, + id: "local", label: "", status: "online", piVersion: "2.0.0", platform: "linux", + hostVersion: 3, serverVersion: 3, lastSeenAt: null, apiVersion: 1, ...overrides, }); async function showHosts(hosts) { globalThis.Worker = FakeWorker; @@ -155,16 +154,16 @@ test("local host shows both installed versions and a blocked candidate with its mockHostRequests(t, async (url) => { urls.push(String(url)); return Response.json(updateInfo({ - ompweb: software({ installMethod: "npm", protocolVersion: 3, canUpdate: false, blockedReason: "Update the web server first: protocol 4 is not supported." }), + tau: software({ installMethod: "npm", protocolVersion: 3, canUpdate: false, blockedReason: "Update the web server first: protocol 4 is not supported." }), })); }); await showHosts([hostRow()]); const row = screen.getByRole("button", { name: "Rename This machine" }).closest("li"); await within(row).findByText(/Update the web server first: protocol 4 is not supported\./); - assert.ok(within(row).getByRole("button", { name: "Update ompweb host" }).disabled); - // omp is read-only: it updates with ompweb. - assert.equal(within(row).queryByRole("button", { name: "Update omp runtime" }), null); - within(row).getByText("Updated with ompweb"); + assert.ok(within(row).getByRole("button", { name: "Update tau host" }).disabled); + // pi is shown, never updated: host updates install tau only. + assert.equal(within(row).queryByRole("button", { name: "Update pi runtime" }), null); + assert.equal(within(row).queryByText("Updated with tau"), null); assert.match(row.textContent, /Current: 1\.0\.0/); assert.match(row.textContent, /Current: 2\.0\.0/); assert.match(row.textContent, /Available: 1\.1\.0/); @@ -177,24 +176,24 @@ test("remote daemon update requires closing host sessions and targets only that mockHostRequests(t, async (url, init) => { if (init?.method === "POST") { posts.push([String(url), JSON.parse(init.body)]); - operation = { id: "op1", target: "ompweb", version: "1.1.0", state: "running" }; + operation = { id: "op1", target: "tau", version: "1.1.0", state: "running" }; return Response.json({ accepted: true, operation }, { status: 202 }); } return Response.json(updateInfo({ operation, - ...(operation?.state === "succeeded" ? { ompweb: software({ currentVersion: "1.1.0", availableVersion: null, updateAvailable: false, installMethod: "npm", protocolVersion: 3 }) } : {}), + ...(operation?.state === "succeeded" ? { tau: software({ currentVersion: "1.1.0", availableVersion: null, updateAvailable: false, installMethod: "npm", protocolVersion: 3 }) } : {}), })); }); const view = await showHosts([hostRow({ id: "h/remote", label: "Laptop", allowAgentStart: false })]); const user = userEvent.setup(); - await user.click(await screen.findByRole("button", { name: "Update ompweb host" })); + await user.click(await screen.findByRole("button", { name: "Update tau host" })); assert.equal(posts.length, 0); assert.match(screen.getByRole("dialog").textContent, /Close all sessions and stop subagents on Laptop first/i); assert.match(screen.getByRole("dialog").textContent, /restarts the host daemon/i); assert.match(screen.getByRole("dialog").textContent, /sessions will not resume automatically/i); await user.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Update" })); - await screen.findByText("Updating ompweb host to 1.1.0…"); - assert.deepEqual(posts, [["/api/hosts/h%2Fremote/updates", { target: "ompweb", version: "1.1.0" }]]); + await screen.findByText("Updating tau host to 1.1.0…"); + assert.deepEqual(posts, [["/api/hosts/h%2Fremote/updates", { target: "tau", version: "1.1.0" }]]); assert.equal(screen.queryByText("Update completed."), null); operation = { ...operation, state: "succeeded" }; await screen.findByText("Update completed.", {}, { timeout: 3500 }); @@ -205,9 +204,9 @@ test("remote daemon update requires closing host sessions and targets only that test("offline and protocol-incompatible hosts render unavailable rows without requesting updates", async (t) => { const calls = []; mockHostRequests(t, async (url) => { calls.push(url); return Response.json({}); }); - await showHosts([hostRow({ status: "offline" }), hostRow({ id: "old", label: "Old", status: "needs-upgrade", allowAgentStart: false })]); - assert.equal(screen.getAllByText("ompweb host").length, 2); - assert.equal(screen.getAllByText("omp runtime").length, 2); + await showHosts([hostRow({ status: "offline", apiVersion: undefined }), hostRow({ id: "old", label: "Old", status: "needs-upgrade", allowAgentStart: false, apiVersion: undefined })]); + assert.equal(screen.getAllByText("tau host").length, 2); + assert.equal(screen.getAllByText("pi runtime").length, 2); screen.getByText("Updates unavailable while this host is offline."); screen.getByText("This host daemon does not support updates. Upgrade it manually first."); assert.deepEqual(calls, []); @@ -229,7 +228,7 @@ test("a failed manual check keeps known versions but never claims up to date", a let fail = false; mockHostRequests(t, async () => fail ? Response.json({ error: "Registry unavailable" }, { status: 503 }) - : Response.json(updateInfo({ ompweb: software({ updateAvailable: false, availableVersion: null, installMethod: "npm", protocolVersion: 3 }) }))); + : Response.json(updateInfo({ tau: software({ updateAvailable: false, availableVersion: null, installMethod: "npm", protocolVersion: 3 }) }))); await showHosts([hostRow()]); await screen.findAllByText("Up to date"); fail = true; @@ -251,14 +250,14 @@ for (const [lost, answer] of [ calls.push(init?.method ?? "GET"); if (init?.method === "POST") { // The host received the request and started the update; only its answer was lost. - operation = { id: "lost", target: "ompweb", version: "1.1.0", state: "failed", error: "Install failed; restored previous host" }; + operation = { id: "lost", target: "tau", version: "1.1.0", state: "failed", error: "Install failed; restored previous host" }; return answer(); } return Response.json(updateInfo({ operation })); }); await showHosts([hostRow()]); const user = userEvent.setup(); - await user.click(await screen.findByRole("button", { name: "Update ompweb host" })); + await user.click(await screen.findByRole("button", { name: "Update tau host" })); await user.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Update" })); await screen.findByText(/Install failed; restored previous host/, {}, { timeout: 3500 }); assert.deepEqual(calls, ["GET", "POST", "GET"]); @@ -280,8 +279,8 @@ test("an unknown update outcome keeps Update disabled until a status read succee }); await showHosts([hostRow()]); const user = userEvent.setup(); - const updateButton = () => screen.getByRole("button", { name: "Update ompweb host" }); - assert.equal((await screen.findByRole("button", { name: "Update ompweb host" })).disabled, false); + const updateButton = () => screen.getByRole("button", { name: "Update tau host" }); + assert.equal((await screen.findByRole("button", { name: "Update tau host" })).disabled, false); await user.click(updateButton()); await user.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Update" })); @@ -317,7 +316,7 @@ test("idle host checks stop, and a manual check bypasses cached release data", a return Response.json(updateInfo()); }); await showHosts([hostRow()]); - await screen.findByRole("button", { name: "Update ompweb host" }); + await screen.findByRole("button", { name: "Update tau host" }); await act(() => new Promise((resolve) => setTimeout(resolve, 1100))); assert.deepEqual(urls, ["/api/hosts/local/updates"]); await userEvent.setup().click(screen.getByRole("button", { name: "Check updates" })); @@ -331,20 +330,20 @@ test("reconnect polling is bounded and requires a status check before any retry" let calls = 0; mockHostRequests(t, async () => { calls++; - return Response.json(updateInfo({ operation: { id: "running", target: "ompweb", version: "1.1.0", state: "running" } })); + return Response.json(updateInfo({ operation: { id: "running", target: "tau", version: "1.1.0", state: "running" } })); }); await showHosts([hostRow()]); - await screen.findByText("Updating ompweb host to 1.1.0…"); + await screen.findByText("Updating tau host to 1.1.0…"); offset = 24 * 60 * 60 * 1000; await act(() => new Promise((resolve) => setTimeout(resolve, 1100))); - assert.ok(screen.getByRole("button", { name: "Update ompweb host" }).disabled); + assert.ok(screen.getByRole("button", { name: "Update tau host" }).disabled); assert.equal(calls, 1); assert.ok(screen.getByRole("button", { name: "Retry" })); }); test("unavailable discovery retains versions advertised by the host", async (t) => { mockHostRequests(t, async () => Response.json({ error: "unknown_op", code: "unknown_op" }, { status: 501 })); - await showHosts([hostRow({ ompwebVersion: "0.6.7", ompVersion: "20.0.1" })]); + await showHosts([hostRow({ tauVersion: "0.6.7", piVersion: "20.0.1" })]); await screen.findByText("This host daemon does not support updates. Upgrade it manually first."); screen.getByText("Current: 0.6.7"); screen.getByText("Current: 20.0.1"); @@ -352,66 +351,33 @@ test("unavailable discovery retains versions advertised by the host", async (t) test("per-software discovery failure or unknown installed version never claims up to date", async (t) => { mockHostRequests(t, async () => Response.json(updateInfo({ - ompweb: software({ availableVersion: null, updateAvailable: false, canUpdate: false, blockedReason: "Registry metadata could not be loaded", installMethod: "npm", protocolVersion: 3 }), - omp: { currentVersion: null }, + tau: software({ availableVersion: null, updateAvailable: false, canUpdate: false, blockedReason: "Registry metadata could not be loaded", installMethod: "npm", protocolVersion: 3 }), }))); - await showHosts([hostRow()]); + await showHosts([hostRow({ piVersion: null })]); await screen.findByText(/Registry metadata could not be loaded/); assert.equal(screen.queryByText("Up to date"), null); }); test("a registry version that is not newer is not shown as an available candidate", async (t) => { mockHostRequests(t, async () => Response.json(updateInfo({ - ompweb: software({ currentVersion: "18.14.0", availableVersion: "18.14.0", updateAvailable: false, canUpdate: false, installMethod: "npm", protocolVersion: 3 }), - omp: { currentVersion: "20.1.0-beta.1" }, + tau: software({ currentVersion: "18.14.0", availableVersion: "18.14.0", updateAvailable: false, canUpdate: false, installMethod: "npm", protocolVersion: 3 }), }))); - await showHosts([hostRow()]); + await showHosts([hostRow({ piVersion: "20.1.0-beta.1" })]); await screen.findByText("Current: 18.14.0"); screen.getByText("Current: 20.1.0-beta.1"); - screen.getByText("Up to date"); + assert.equal(screen.getAllByText("Up to date").length, 1); assert.equal(screen.queryByText(/^Available:/), null); - assert.equal(screen.queryByRole("button", { name: /^Update (ompweb host|omp runtime)$/ }), null); + assert.equal(screen.queryByRole("button", { name: /^Update (tau host|pi runtime)$/ }), null); }); -test("resident-session blocking stays readable with a disabled daemon update; the omp row stays read-only", async (t) => { +test("resident-session blocking stays readable with a disabled daemon update; the pi row offers no update", async (t) => { mockHostRequests(t, async () => Response.json(updateInfo({ - ompweb: software({ canUpdate: false, blockedReason: "Close all sessions on Laptop before updating the host daemon.", installMethod: "npm", protocolVersion: 3 }), + tau: software({ canUpdate: false, blockedReason: "Close all sessions on Laptop before updating the host daemon.", installMethod: "npm", protocolVersion: 3 }), }))); await showHosts([hostRow({ id: "laptop", label: "Laptop", allowAgentStart: false })]); await screen.findByText(/Close all sessions on Laptop before updating the host daemon/); - assert.ok(screen.getByRole("button", { name: "Update ompweb host" }).disabled); - assert.equal(screen.queryByRole("button", { name: "Update omp runtime" }), null); - screen.getByText("Updated with ompweb"); + assert.ok(screen.getByRole("button", { name: "Update tau host" }).disabled); + assert.equal(screen.queryByRole("button", { name: "Update pi runtime" }), null); + assert.equal(screen.queryByText("Updated with tau"), null); }); -test("sharing credentials is confirmed before it is turned on, and turned off at once", async (t) => { - const patches = []; - mockHostRequests(t, async (url, init) => { - if (String(url).includes("/updates")) return Response.json(updateInfo()); - patches.push(JSON.parse(init?.body ?? "null")); - return Response.json({}); - }); - const user = userEvent.setup(); - await showHosts([ - hostRow(), - hostRow({ id: "h1", label: "Laptop", allowAgentStart: false, shareCredentials: false }), - hostRow({ id: "h2", label: "Desk", allowAgentStart: false, shareCredentials: true }), - ]); - const localRow = (await screen.findByRole("button", { name: "Rename This machine" })).closest("li"); - assert.equal(within(localRow).queryByRole("switch", { name: /provider logins/ }), null); - - await user.click(screen.getByRole("switch", { name: "Use this server's provider logins on Laptop" })); - const dialog = await screen.findByRole("dialog", { name: "Share credentials with Laptop?" }); - assert.deepEqual(patches, []); - await user.click(within(dialog).getByRole("button", { name: "Cancel" })); - await waitFor(() => assert.equal(screen.queryByRole("dialog"), null)); - assert.deepEqual(patches, []); - - await user.click(screen.getByRole("switch", { name: "Use this server's provider logins on Laptop" })); - await user.click(within(await screen.findByRole("dialog")).getByRole("button", { name: "Share" })); - await waitFor(() => assert.deepEqual(patches, [{ id: "h1", shareCredentials: true }])); - - await user.click(screen.getByRole("switch", { name: "Use this server's provider logins on Desk" })); - await waitFor(() => assert.deepEqual(patches.at(-1), { id: "h2", shareCredentials: false })); - assert.equal(screen.queryByRole("dialog"), null); -}); diff --git a/components/HostsConfig.tsx b/components/HostsConfig.tsx index 8dac8059..2478f9a5 100644 --- a/components/HostsConfig.tsx +++ b/components/HostsConfig.tsx @@ -185,24 +185,22 @@ function JoinDialog({ host, localJoins, reload, onClose }: { host: HostRow; loca /** `localReason`: this machine is not a member yet, so a join adds it too, and why its own daemon is not ready for that. */ type ClusterState = { pools: HostPool[]; poolsLoaded: boolean; poolsFailed: boolean; localReason: string | null; masterFailed: boolean }; -const joinBlock = (row: HostRow) => clusterJoinBlock({ status: row.status, ompVersion: row.ompVersion, supports: (operation) => row.workspaceOps.includes(operation) }); +const joinBlock = (row: HostRow) => clusterJoinBlock({ status: row.status }); -function HostCard({ host, cluster, onRename, onRevoke, onShare, onJoin, onLeave }: { host: HostRow; cluster: ClusterState; onRename: () => void; onRevoke: () => void; onShare: () => void; onJoin: () => void; onLeave: () => void }) { +function HostCard({ host, cluster, onRename, onRevoke, onJoin, onLeave }: { host: HostRow; cluster: ClusterState; onRename: () => void; onRevoke: () => void; onJoin: () => void; onLeave: () => void }) { const { t } = useI18n(); const name = hostName(t, host); const linked = "allowAgentStart" in host ? host : null; const member = isClusterMember(cluster.pools, host.id); - // Unknown membership (pools not loaded) disables every switch and every share toggle; the reason is only shown once the load failed. + // Unknown membership (pools not loaded) disables every switch; the reason is only shown once the load failed. // Otherwise only a non-member needs a ready host, and this machine too while it is not a member: leaving always works. const unavailable = !cluster.poolsLoaded && cluster.poolsFailed ? t("hostsConfig.poolsUnavailable") : null; const block = cluster.poolsLoaded && !member && linked ? joinBlock(host) : null; - const joinReason = unavailable ?? (block === "upgrade" || block === "needs-upgrade" ? t("hostsConfig.joinUpgrade") - : block === "omp-old" ? t("hostsConfig.joinOmpOld", { name }) - : block === "omp-missing" ? hostStatusText(t, host) + const joinReason = unavailable ?? (block === "needs-upgrade" ? t("hostsConfig.joinUpgrade") + : block === "pi-missing" ? hostStatusText(t, host) : block !== null ? t("hostsConfig.joinOffline") : !member ? cluster.localReason : null); const reasonId = useId(); - const forcedId = useId(); const details = [ host.platform, host.hostVersion !== null && host.status !== "needs-upgrade" && t("hostsConfig.protocol", { version: host.hostVersion }), @@ -212,7 +210,7 @@ function HostCard({ host, cluster, onRename, onRevoke, onShare, onJoin, onLeave // so it needs an update; a member without a report yet is still being brought up to date, unless this machine cannot // serve its configuration, which the message above the rows says once. const memberBlock = member && linked ? joinBlock(host) : null; - const outdated = memberBlock === "upgrade" || memberBlock === "needs-upgrade"; + const outdated = memberBlock === "needs-upgrade"; const config = member && !outdated ? linked?.clusterConfig : undefined; const updating = cluster.masterFailed ? null : t("hostsConfig.configUpdating"); const configLine = !member || !linked || host.status === "offline" ? null @@ -238,7 +236,7 @@ function HostCard({ host, cluster, onRename, onRevoke, onShare, onJoin, onLeave {t("hostsConfig.localOfflineHint")} {t("hostsConfig.localForegroundHint")} - + )} @@ -267,19 +265,6 @@ function HostCard({ host, cluster, onRename, onRevoke, onShare, onJoin, onLeave /> )} - {linked && ( -
- {t("hostsConfig.shareCredentials")} - { if (shareCredentials) onShare(); else void call("PATCH", "/api/hosts", { id: host.id, shareCredentials }).catch(failure); }} - /> - {member && {t("hostsConfig.shareForced")}} -
- )} @@ -299,31 +284,16 @@ export function HostsConfig() { const { hosts, pools, poolsLoaded, poolsFailed, failed: loadFailed, masterConfigError, reload } = useHostRows(); const [dialog, setDialog] = useState(null); const [revoking, setRevoking] = useState(null); - const [sharing, setSharing] = useState(null); const [joining, setJoining] = useState(null); const [leaving, setLeaving] = useState(null); const [busy, setBusy] = useState(false); const local = hosts?.find(isLocalRow); const localJoins = !isClusterMember(pools, LOCAL_HOST_ID); const localBlock = poolsLoaded && localJoins && local ? joinBlock(local) : null; - const localReason = !local || localBlock === null ? null - : localBlock === "omp-old" ? t("hostsConfig.joinOmpOld", { name: hostName(t, local) }) : t("hostsConfig.joinLocalRestart"); + const localReason = !local || localBlock === null ? null : t("hostsConfig.joinLocalRestart"); const cluster = clusterOf(pools); const linkedMembers = cluster?.members.some((member) => member.hostId !== LOCAL_HOST_ID) ?? false; - const share = async () => { - if (!sharing) return; - setBusy(true); - try { - await call("PATCH", "/api/hosts", { id: sharing.id, shareCredentials: true }); - setSharing(null); - } catch (error) { - failure(error); - } finally { - setBusy(false); - } - }; - const leave = async () => { if (!leaving) return; setBusy(true); @@ -384,7 +354,7 @@ export function HostsConfig() { ) : (
    {hosts.map((host) => ( - setDialog({ kind: "rename", host })} onRevoke={() => setRevoking(host)} onShare={() => setSharing(host)} onJoin={() => setJoining(host)} onLeave={() => setLeaving(host)} /> + setDialog({ kind: "rename", host })} onRevoke={() => setRevoking(host)} onJoin={() => setJoining(host)} onLeave={() => setLeaving(host)} /> ))} {hosts.length === 1 &&
  • {t("hostsConfig.empty")}
  • }
@@ -412,16 +382,6 @@ export function HostsConfig() { busy={busy} onConfirm={() => void revoke()} /> - { if (!open) setSharing(null); }} - title={t("hostsConfig.shareCredentialsTitle", { name: sharing?.label ?? "" })} - description={t("hostsConfig.shareCredentialsDescription", { name: sharing?.label ?? "" })} - confirmLabel={t("hostsConfig.shareCredentialsConfirm")} - cancelLabel={t("hostsConfig.cancel")} - busy={busy} - onConfirm={() => void share()} - /> ); } diff --git a/components/ImageLightbox.test.mjs b/components/ImageLightbox.test.mjs index 95e584a5..3a9888ee 100644 --- a/components/ImageLightbox.test.mjs +++ b/components/ImageLightbox.test.mjs @@ -34,7 +34,7 @@ test("custom message images render as click-to-preview thumbnails", () => { const html = renderToStaticMarkup(React.createElement(MessageView, { message: { role: "custom", - customType: "advisor", + customType: "note", content: [{ type: "image", data: "QUJD", mimeType: "image/png" }], }, })); diff --git a/components/LocalDaemonBanner.test.mjs b/components/LocalDaemonBanner.test.mjs index eaa3c899..63a287b2 100644 --- a/components/LocalDaemonBanner.test.mjs +++ b/components/LocalDaemonBanner.test.mjs @@ -21,7 +21,7 @@ afterEach(() => { globalThis.Worker = originalWorker; }); -const local = (fields) => ({ id: "local", label: "", status: "offline", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, serverPlatform: "linux", daemonManaged: true, ...fields }); +const local = (fields) => ({ id: "local", label: "", status: "offline", piVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, serverPlatform: "linux", daemonManaged: true, ...fields }); const send = (hosts) => { const { id } = workers[0].posted.findLast((message) => message.op === "open" && message.channel.kind === "hosts"); act(() => workers[0].onmessage({ data: { id, type: "message", data: JSON.stringify({ hosts }) } })); @@ -33,7 +33,7 @@ const mount = async () => { render(createElement(LocalDaemonBanner)); await waitFor(() => assert.ok(opens() > before)); }; -const text = /needs the ompweb-host service/; +const text = /needs the tau-host service/; test("the install banner appears after 90 s offline, once: dismissing it keeps it away", async (t) => { await mount(); @@ -42,9 +42,9 @@ test("the install banner appears after 90 s offline, once: dismissing it keeps i act(() => t.mock.timers.tick(89_999)); assert.equal(screen.queryByText(text), null); act(() => t.mock.timers.tick(1)); - assert.ok(screen.getByText(text).textContent.startsWith("This machine needs the ompweb-host service. Install it with:")); - // A foreground ompweb (terminal or npx) has no service: it needs `ompweb host` running beside it. - assert.deepEqual([...screen.getByRole("status").querySelectorAll("code")].map((code) => code.textContent), ["ompweb systemd install", "ompweb host"]); + assert.ok(screen.getByText(text).textContent.startsWith("This machine needs the tau-host service. Install it with:")); + // A foreground tau (terminal or npx) has no service: it needs `tau host` running beside it. + assert.deepEqual([...screen.getByRole("status").querySelectorAll("code")].map((code) => code.textContent), ["tau systemd install", "tau host"]); assert.match(screen.getByRole("status").textContent, /in a terminal or with npx/); fireEvent.click(screen.getByRole("button", { name: "Dismiss" })); diff --git a/components/LocalDaemonBanner.tsx b/components/LocalDaemonBanner.tsx index 524ac641..0556f005 100644 --- a/components/LocalDaemonBanner.tsx +++ b/components/LocalDaemonBanner.tsx @@ -7,11 +7,11 @@ import { useI18n } from "@/lib/i18n"; import { CopyField } from "./HostsConfig"; import { hostName, isLocalRow, localInstallCommand } from "./host-status"; -export const LOCAL_DAEMON_BANNER_DISMISSED_KEY = "omp-web:local-daemon-banner-dismissed"; +export const LOCAL_DAEMON_BANNER_DISMISSED_KEY = "tau:local-daemon-banner-dismissed"; // Well past the daemon's redial wait (at most 3 s on loopback), so a restarting daemon does not trip it. export const LOCAL_DAEMON_GRACE_MS = 90_000; -/** One-time hint to install the ompweb-host service: this machine has not linked since this server started and 90 s have passed. */ +/** One-time hint to install the tau-host service: this machine has not linked since this server started and 90 s have passed. */ export function LocalDaemonBanner() { const { t } = useI18n(); const { hosts } = useHostRows(); @@ -55,7 +55,7 @@ export function LocalDaemonBanner() { {t("hostsConfig.localDaemonBanner", { host: hostName(t, local) })} {t("hostsConfig.localForegroundHint")} - + - - -

{t(liveOnly ? "mcpConfig.clusterLiveHint" : sessionId ? "mcpConfig.applyHint" : "mcpConfig.selectSessionHint")}

- {liveError && } {userConfig?.error && } {message && setMessage(null)} />} {groups.filter((group) => group.managed).map(groupView)} {loading && displayedServers.length === 0 &&
} - {!loading && managedCount === 0 &&
{t("mcpConfig.noOmpServers")}
} + {!loading && managedCount === 0 &&
{t("mcpConfig.noPiServers")}
} {otherGroups.length > 0 &&

{t("mcpConfig.otherSourcesHint")}

{otherGroups.map(groupView)}
diff --git a/components/MessageView.test.mjs b/components/MessageView.test.mjs index 8e07bb44..dcbe747a 100644 --- a/components/MessageView.test.mjs +++ b/components/MessageView.test.mjs @@ -57,7 +57,7 @@ test("Delete confirmation never claims omp has not seen a message that may have return text; }; const uncertain = await dialogText({ ...base, mayHaveBeenSent: true }); - assert.match(uncertain, /may already have reached omp/); + assert.match(uncertain, /may already have reached pi/); assert.match(uncertain, /cannot cancel or undo/); assert.doesNotMatch(uncertain, /has not reached|will not be sent/); for (const state of ["held", "failed"]) { @@ -83,7 +83,7 @@ const sessionOrigin = { tool: "send_to_session", delivery: "followUp", }, }; -const sessionHeader = `[Message from omp-web session "Incident review" (session id source-session, host Worker 1, delivery follow-up).\nIt was sent by another agent session, not by the user. Reply with send_to_session to that session id.]`; +const sessionHeader = `[Message from tau session "Incident review" (session id source-session, host Worker 1, delivery follow-up).\nIt was sent by another agent session, not by the user. Reply with send_to_session to that session id.]`; test("trusted session origins render as left-side source cards with raw text on demand", () => { const view = render(React.createElement(MessageView, { @@ -146,7 +146,7 @@ test("GitHub watcher origins render a linked automated update card", () => { const view = render(React.createElement(MessageView, { message: { role: "user", - content: "GitHub update (omp-web): ompweb-dev/ompweb#503 https://github.com/ompweb-dev/ompweb/pull/503", + content: "GitHub update (tau): ompweb-dev/ompweb#503 https://github.com/ompweb-dev/ompweb/pull/503", origin: { v: 1, kind: "github", sentAt: "2026-11-15T12:42:00.000Z", github: { @@ -691,15 +691,6 @@ test("hub jobs without structured details keeps the raw result", () => { assert.match(html, /Still Running/); }); -test("advisor custom messages use the localized advisor label", () => { - const html = renderToStaticMarkup(React.createElement(MessageView, { - message: { role: "custom", customType: "advisor", content: "Consider handling the edge case.", display: true }, - })); - assert.match(html, /Advisor/); - assert.match(html, /Consider handling the edge case/); - assert.doesNotMatch(html, /customType/); -}); - test("async-result notices start collapsed to their first line and expand to the exact line layout", () => { const view = render(React.createElement(MessageView, { message: { diff --git a/components/MessageView.tsx b/components/MessageView.tsx index 2ac5e7d8..7a10155e 100644 --- a/components/MessageView.tsx +++ b/components/MessageView.tsx @@ -166,7 +166,7 @@ interface Props { cwd?: string; onOpenFile?: (filePath: string) => void; entryId?: string; - /** Branch point omp's `branch` command accepts for this message (a user entry; see lib/chat-fork.ts). */ + /** Fork point pi's `fork` command accepts for this message (a user entry; see lib/chat-fork.ts). */ forkEntryId?: string; /** Forking puts the branched prompt back into the composer (edit-and-resend). */ forkEditsPrompt?: boolean; @@ -182,12 +182,10 @@ interface Props { toolCallsDefaultCollapsed?: boolean; /** Open thinking blocks on mount ("Expand thinking blocks by default" in Settings). */ expandThinkingByDefault?: boolean; - /** omp `hideThinkingBlock`: omit thinking blocks. */ + /** pi `hideThinkingBlock`: omit thinking blocks. */ hideThinking?: boolean; /** Source `content` index of each block when `message` carries a subset of an entry's blocks, so deferred thinking loads the right block. */ sourceBlockIndices?: number[]; - /** omp-reported output throughput (get_state.tokensPerSecond), live while streaming. */ - liveTokensPerSecond?: number | null; } function formatTime(ts: number | undefined, locale: Locale): string | null { @@ -245,18 +243,17 @@ export function areMessageViewPropsEqual(prev: Props, next: Props): boolean { && Object.is(prev.toolCallsDefaultCollapsed, next.toolCallsDefaultCollapsed) && Object.is(prev.expandThinkingByDefault, next.expandThinkingByDefault) && Object.is(prev.hideThinking, next.hideThinking) - && prev.sourceBlockIndices?.join() === next.sourceBlockIndices?.join() - && (!prev.isStreaming || Object.is(prev.liveTokensPerSecond, next.liveTokensPerSecond)); + && prev.sourceBlockIndices?.join() === next.sourceBlockIndices?.join(); } -export const MessageView = memo(function MessageView({ message, isStreaming, toolResults, modelNames, cwd, onOpenFile, entryId, forkEntryId, forkEditsPrompt, onFork, forking, forkDisabled, onEdit, editing, editDisabled, showTimestamp, prevTimestamp, sessionId, toolCallsDefaultCollapsed = true, expandThinkingByDefault = false, hideThinking = false, sourceBlockIndices, liveTokensPerSecond }: Props) { +export const MessageView = memo(function MessageView({ message, isStreaming, toolResults, modelNames, cwd, onOpenFile, entryId, forkEntryId, forkEditsPrompt, onFork, forking, forkDisabled, onEdit, editing, editDisabled, showTimestamp, prevTimestamp, sessionId, toolCallsDefaultCollapsed = true, expandThinkingByDefault = false, hideThinking = false, sourceBlockIndices }: Props) { if (message.role === "user") { const user = message as UserMessage; if (user.origin) return ; return ; } if (message.role === "assistant") { - return ; + return ; } if (message.role === "toolResult") { // Rendered inline under its toolCall — skip standalone rendering if paired @@ -297,8 +294,8 @@ function imageBlockSrc(img: ImageContent): string { /** * "New session" (fork) action, shared by user and assistant messages. * - * omp's `branch` command accepts a user-message entry only (an assistant entry - * answers "Invalid entry ID for branching"), so `entryId` is the branch point + * pi's `fork` command accepts a user-message entry only (an assistant entry + * answers "Invalid entry ID for forking"), so `entryId` is the fork point * resolved by `resolveForkTargets` — for an assistant reply, the next user * prompt, so the reply stays in the fork's history. */ @@ -536,8 +533,8 @@ const heldActionStyle = { fontSize: 11, whiteSpace: "nowrap", } as const; -/** A message omp-web holds until omp has it (docs/specs/2026-11-04-message-outbox-design.md O1): dimmed, after the - * live turn, naming the leg it waits on. Delete only while nothing of it can have reached omp; Retry a failed one. */ +/** A message tau holds until pi has it (docs/specs/2026-11-04-message-outbox-design.md O1): dimmed, after the + * live turn, naming the leg it waits on. Delete only while nothing of it can have reached pi; Retry a failed one. */ export function HeldMessageView({ held, hostLabel, onDelete, onRetry }: { held: HeldMessage; hostLabel?: string; @@ -678,7 +675,6 @@ function AssistantMessageView({ expandThinkingByDefault, hideThinking, sourceBlockIndices, - liveTokensPerSecond, }: { message: AssistantMessage; isStreaming?: boolean; @@ -690,7 +686,7 @@ function AssistantMessageView({ prevTimestamp?: number; sessionId?: string; entryId?: string; - /** User entry omp's `branch` command accepts for this reply (see lib/chat-fork.ts). */ + /** User entry pi's `fork` command accepts for this reply (see lib/chat-fork.ts). */ forkEntryId?: string; forkEditsPrompt?: boolean; onFork?: (entryId: string, editPrompt: boolean) => void; @@ -700,7 +696,6 @@ function AssistantMessageView({ expandThinkingByDefault: boolean; hideThinking: boolean; sourceBlockIndices?: number[]; - liveTokensPerSecond?: number | null; }) { const { t, locale } = useI18n(); const { isSupported: ttsSupported, isSpeaking: ttsSpeaking, speakingId: ttsSpeakingId, toggle: ttsToggle } = useSpeechContext(); @@ -843,18 +838,6 @@ function AssistantMessageView({ {est} - {liveTokensPerSecond != null && (() => { - // Speed tiers use the semantic status tokens as TEXT color - // (theme-adaptive, AA-verified) over a subtle tint — the - // old hardcoded palette failed AA for white-on-fill. - const tier = liveTokensPerSecond >= 50 ? "success" : liveTokensPerSecond >= 30 ? "renamed" : liveTokensPerSecond >= 15 ? "warning" : "error"; - const tone = `var(--status-${tier})`; - return ( - - {t("messageView.tokensPerSecond", { tps: liveTokensPerSecond.toFixed(1) })} - - ); - })()} )} @@ -1126,7 +1109,7 @@ const ToolCallBlock = memo(function ToolCallBlock({ }) { const { t } = useI18n(); const openAgentLink = useContext(AgentLinkContext); - // `partial` results are omp's live snapshots for a tool that is still + // `partial` results are pi's live snapshots for a tool that is still // executing (see lib/types.ts); the committed toolResult replaces them. const isRunning = result?.partial === true; // A running tool opens its row when the interface keeps tool calls expanded @@ -1230,7 +1213,7 @@ const ToolCallBlock = memo(function ToolCallBlock({ ? String((block.input as Record).path).trim() : null; const agentIds = agentLinkIds(rawFilePath ?? undefined); - // `history://`, `proc://`, `local://`, ... are resolved by omp, not files the viewer can open. + // A URL (`https://`, `skill://`, ...) is no file the viewer can open. const hasUrlScheme = rawFilePath !== null && /^[a-z][a-z0-9+.-]*:\/\//i.test(rawFilePath); const webUrl = hasUrlScheme && /^https?:\/\//i.test(rawFilePath) ? readTargetWebUrl(rawFilePath) : null; // Strip only a trailing : suffix. Splitting on the first ":" broke @@ -1448,12 +1431,8 @@ function CompactionMessageView({ message, sessionId }: { message: CustomMessage; const summary = getMessageText(message.content); const parsedSummary = useMemo(() => parseCompactionSummary(summary), [summary]); const time = formatTime(message.timestamp, locale); - // omp ≥17.4 compaction entries carry the maintenance method and the real - // post-compaction token count; older sessions only have tokensBefore. - const details = (message.details ?? null) as { tokensBefore?: unknown; tokensAfter?: unknown; method?: unknown } | null; + const details = (message.details ?? null) as { tokensBefore?: unknown } | null; const tokensBefore = typeof details?.tokensBefore === "number" ? details.tokensBefore : null; - const tokensAfter = typeof details?.tokensAfter === "number" ? details.tokensAfter : null; - const method = typeof details?.method === "string" && details.method ? details.method : null; return (
@@ -1464,21 +1443,9 @@ function CompactionMessageView({ message, sessionId }: { message: CustomMessage;
{t("messageView.conversationCompacted")}
- {(method || (tokensBefore !== null && tokensAfter !== null)) && ( -
- {method && ( - - {method} - - )} - {tokensBefore !== null && tokensAfter !== null && ( - - {t("messageView.compactionTokenDelta", { - before: formatCompactNumber(tokensBefore, locale), - after: formatCompactNumber(tokensAfter, locale), - })} - - )} + {tokensBefore !== null && ( +
+ {t("messageView.compactionTokensBefore", { before: formatCompactNumber(tokensBefore, locale) })}
)}
{t("messageView.compactionDescription")}
@@ -1802,9 +1769,7 @@ function CustomMessageView({ message, cwd, onOpenFile, sessionId }: { message: C ? wrapperTitle(wrapper) : isIrc ? (ircEnvelope?.sender ?? formatCustomType(message.customType)) - : message.customType === "advisor" - ? t("messageView.advisorLabel") - : formatCustomType(message.customType); + : formatCustomType(message.customType); const time = formatTime(message.timestamp, locale); diff --git a/components/ModelCatalogPicker.tsx b/components/ModelCatalogPicker.tsx index 0c0010f5..b46ffd84 100644 --- a/components/ModelCatalogPicker.tsx +++ b/components/ModelCatalogPicker.tsx @@ -48,8 +48,8 @@ function formatContext(n: number): string { } function toPickedModel(entry: CatalogModelEntry): CatalogPickedModel { - // omp's models.yml schema requires ALL FOUR cost fields when cost is - // present (models-config-schema-bundle.ts); default missing cache fields to + // pi's models.json requires ALL FOUR cost fields when cost is + // present; default missing cache fields to // 0 exactly like the catalog recommendation does, and skip cost entirely // when the catalog entry has no usable input/output price. const hasPrice = entry.cost.input !== undefined && entry.cost.output !== undefined; diff --git a/components/ModelsConfig-panels.tsx b/components/ModelsConfig-panels.tsx index 4f1ec7b3..112629cd 100644 --- a/components/ModelsConfig-panels.tsx +++ b/components/ModelsConfig-panels.tsx @@ -8,13 +8,12 @@ import { DialogTitle, ThemedSelect, } from "@/components/ui/primitives"; -import { Plus, Trash2, ArrowDown, ArrowUp } from "lucide-react"; +import { Plus } from "lucide-react"; import { toast } from "@/components/ui/toast"; +import { formatApiError } from "@/lib/i18n/api-error"; import { - NATIVE_MODEL_ROLES, providerInitials, type ApiKeyProvider, - type ConnectedProvider, type IconComponent, type NativeRegistrySettings, type OAuthProvider, @@ -82,16 +81,13 @@ export function TreeNavButton({ icon: Icon, label, selected, onClick }: { icon: ); } -export function RetryFallbackDetail({ models }: { models: RuntimeModelEntry[] }) { +export function RetryFallbackDetail() { const { t } = useI18n(); const [settings, setSettings] = useState(null); - const [role, setRole] = useState("default"); - const [candidate, setCandidate] = useState(""); - const [candidateEffort, setCandidateEffort] = useState(""); const [error, setError] = useState(null); useEffect(() => { - fetch("/api/omp-settings") + fetch("/api/pi-settings") .then((response) => response.ok ? response.json() : Promise.reject(new Error(`HTTP ${response.status}`))) .then((data: { settings?: RetrySettings }) => { const loaded = data.settings ?? {}; @@ -120,7 +116,7 @@ export function RetryFallbackDetail({ models }: { models: RuntimeModelEntry[] }) const snapshot = latestRef.current; latestRef.current = null; try { - const response = await fetch("/api/omp-settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ settings: snapshot }) }); + const response = await fetch("/api/pi-settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ settings: snapshot }) }); const data = await response.json() as { settings?: RetrySettings; error?: string }; if (!response.ok || data.error) throw new Error(data.error || `HTTP ${response.status}`); const confirmed = data.settings ?? snapshot; @@ -141,54 +137,24 @@ export function RetryFallbackDetail({ models }: { models: RuntimeModelEntry[] }) if (!settings) return
{t("modelsConfig.retryLoading")}
; const retry = settings.retry ?? {}; - const chain = retry.fallbackChains?.[role] ?? []; - const modelOptions = models.map((model) => `${model.provider}/${model.id}`); - const candidateModel = models.find((model) => `${model.provider}/${model.id}` === candidate); - const candidateSelector = candidate ? `${candidate}${candidateEffort ? `:${candidateEffort}` : ""}` : ""; - const updateChain = (next: string[]) => void save({ ...settings, retry: { ...retry, fallbackChains: { ...(retry.fallbackChains ?? {}), [role]: next } } }); return
{t("modelsConfig.retryFallbackTitle")}

{t("modelsConfig.retryFallbackDesc")}

- - - +
-
-
{t("modelsConfig.fallbackChainFor")} setRole(nextValue)} style={{ padding: "4px 8px", border: "1px solid var(--border)", borderRadius: "var(--radius-control)", background: "var(--bg)", color: "var(--text)" }} options={[...NATIVE_MODEL_ROLES.map((value) => ({ value: value, label: value }))]} />
-
- { setCandidate(nextValue); setCandidateEffort(""); }} style={{ flex: 1, minWidth: 0, padding: "6px 8px", border: "1px solid var(--border)", borderRadius: "var(--radius-control)", background: "var(--bg)", color: "var(--text)" }} options={[{ value: "", label: t("modelsConfig.selectFallbackModel") }, ...modelOptions.map((value) => ({ value: value, label: value }))]} /> - ({ value: level, label: level }))]} /> - -
- {chain.length === 0 ? ( -
{t("modelsConfig.noExplicitChain")}
- ) : ( -
- {chain.map((selector, index) => ( -
- {index + 1} - {selector} - - - -
- ))} -
- )} -
{error &&
{error}
}
; } -export function NativeRegistryDetail({ models, connectedProviders, onChanged }: { models: RuntimeModelEntry[]; connectedProviders: ConnectedProvider[]; onChanged: () => Promise }) { +export function NativeRegistryDetail({ models, onChanged }: { models: RuntimeModelEntry[]; onChanged: () => Promise }) { const { t } = useI18n(); const [settings, setSettings] = useState(null); const [error, setError] = useState(null); const [saving, setSaving] = useState(false); useEffect(() => { - fetch("/api/omp-settings") + fetch("/api/pi-settings") .then((response) => response.ok ? response.json() : Promise.reject(new Error(`HTTP ${response.status}`))) .then((data: { settings?: NativeRegistrySettings }) => setSettings(data.settings ?? {})) .catch((reason) => setError(reason instanceof Error ? reason.message : String(reason))); @@ -213,7 +179,7 @@ export function NativeRegistryDetail({ models, connectedProviders, onChanged }: const snapshot = latestRef.current; latestRef.current = null; try { - const response = await fetch("/api/omp-settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ settings: snapshot }) }); + const response = await fetch("/api/pi-settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ settings: snapshot }) }); const data = await response.json() as { settings?: NativeRegistrySettings; error?: string }; if (!response.ok || data.error) throw new Error(data.error || `HTTP ${response.status}`); if (latestRef.current === null) setSettings(data.settings ?? snapshot); @@ -231,14 +197,9 @@ export function NativeRegistryDetail({ models, connectedProviders, onChanged }: }; if (!settings) return
{t("modelsConfig.registryLoading")}
; - const isReadOnly = settings.registryHasScopedEntries === true; const allModelKeys = models.map((model) => `${model.provider}/${model.id}`); const allowListEnabled = (settings.enabledModels?.length ?? 0) > 0; const enabledModels = new Set(settings.enabledModels ?? allModelKeys); - const providers = [...new Set([...models.map((model) => model.provider), ...connectedProviders.map((provider) => provider.id), ...(settings.disabledProviders ?? [])])].sort(); - const disabledProviders = new Set(settings.disabledProviders ?? []); - const providerOrder = settings.modelProviderOrder ?? []; - const orderedProviders = [...providerOrder, ...providers.filter((provider) => !providerOrder.includes(provider))]; return
@@ -246,111 +207,43 @@ export function NativeRegistryDetail({ models, connectedProviders, onChanged }:

{t("modelsConfig.nativeRegistryDesc")}

- +

{allowListEnabled ? t("modelsConfig.uncheckedUnavailable") : t("modelsConfig.allModelsAllowed")}

{allowListEnabled &&
{models.map((model) => { const key = `${model.provider}/${model.id}`; - return ; + return ; })}
}
-
-
{t("modelsConfig.disabledProviders")}
-

{t("modelsConfig.disabledProvidersDesc")}

-
{providers.map((provider) => )}
-
-
-
{t("modelsConfig.providerPreference")}
-

{t("modelsConfig.providerPreferenceDesc")}

-
{orderedProviders.map((provider, index) =>
{provider}
)}
-
- {isReadOnly &&
{t("modelsConfig.pathScopedNotice")}
} {error &&
{error}
}
; } -export function ModelRolesDetail({ models }: { models: RuntimeModelEntry[] }) { - const { t } = useI18n(); - const [roles, setRoles] = useState>({}); - const [loading, setLoading] = useState(true); - const [saving, setSaving] = useState(false); - const [error, setError] = useState(null); - - useEffect(() => { - fetch("/api/model-roles") - .then((response) => response.ok ? response.json() : Promise.reject(new Error(`HTTP ${response.status}`))) - .then((data: { roles?: Record }) => setRoles(data.roles ?? {})) - .catch((reason) => setError(reason instanceof Error ? reason.message : String(reason))) - .finally(() => setLoading(false)); - }, []); +// ── API Key detail ──────────────────────────────────────────────────────────── +// The key goes to the selected host's pi, which stores it in that host's auth.json; it is never read back. - const save = async () => { - setSaving(true); +export function ApiKeyDetail({ provider, hostId, onRefresh }: { provider: ApiKeyProvider; hostId: string; onRefresh: () => void }) { + const { t, tn } = useI18n(); + const [key, setKey] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const call = async (method: "POST" | "DELETE") => { + setBusy(true); setError(null); try { - const response = await fetch("/api/model-roles", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ roles }) }); - const data = await response.json() as { error?: string }; - if (!response.ok || data.error) throw new Error(data.error || `HTTP ${response.status}`); - toast.success(t("modelsConfig.rolesSaved")); - } catch (reason) { - setError(reason instanceof Error ? reason.message : String(reason)); + const res = await fetch(`/api/auth/api-key/${encodeURIComponent(provider.id)}?hostId=${encodeURIComponent(hostId)}`, { + method, + ...(method === "POST" ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ key }) } : {}), + }); + const d = await res.json().catch(() => ({})) as { error?: string; code?: string }; + if (!res.ok) throw new Error(d.error || d.code ? formatApiError(d) : t("modelsConfig.serverError", { status: res.status })); + setKey(""); + if (method === "POST") toast.success(t("modelsConfig.apiKeySaved", { name: provider.displayName })); + onRefresh(); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); } finally { - setSaving(false); + setBusy(false); } }; - - const updateRoleModel = (role: string, modelValue: string) => { - const current = roles[role] ?? ""; - const effort = current.match(/:([^,:]+)$/)?.[1] ?? ""; - setRoles((values) => ({ ...values, [role]: modelValue ? `${modelValue}${effort ? `:${effort}` : ""}` : "" })); - }; - - const updateRoleThinking = (role: string, effort: string) => { - const current = roles[role] ?? ""; - const modelValue = current.replace(/:([^,:]+)$/, ""); - setRoles((values) => ({ ...values, [role]: modelValue ? `${modelValue}${effort ? `:${effort}` : ""}` : "" })); - }; - - return
-
- {t("modelsConfig.modelRolesTitle")} -

{t("modelsConfig.modelRolesDesc")}

-
- {loading ?
{t("modelsConfig.loadingRoles")}
: NATIVE_MODEL_ROLES.map((role) => ( -
- {role} - {(() => { - const raw = roles[role] ?? ""; - const selectedModel = raw.replace(/:([^,:]+)$/, ""); - const selectedThinking = raw.match(/:([^,:]+)$/)?.[1] ?? ""; - const model = models.find((item) => `${item.provider}/${item.id}` === selectedModel); - const modelKnown = !selectedModel || Boolean(model); - return <> - updateRoleModel(role, nextValue)} style={{ minWidth: 0, padding: "7px 9px", border: "1px solid var(--border)", borderRadius: "var(--radius-control)", background: "var(--bg)", color: "var(--text)", fontSize: 12 }} - options={[ - { value: "", label: t("modelsConfig.noOverride") }, - ...(!modelKnown && [{ value: selectedModel, label: <>{selectedModel} (not currently available) }] || []), - ...models.map((item) => ({ value: `${item.provider}/${item.id}`, label: <>{item.name || item.id} ({item.provider}/{item.id}) })), - ]} - /> - updateRoleThinking(role, nextValue)} style={{ minWidth: 0, padding: "7px 9px", border: "1px solid var(--border)", borderRadius: "var(--radius-control)", background: "var(--bg)", color: "var(--text)", fontSize: 12, opacity: model ? 1 : 0.55 }} - options={[ - { value: "", label: t("modelsConfig.modelDefault") }, - ...(model?.thinkingLevels ?? []).filter((level) => level !== "off").map((level) => ({ value: level, label: level })), - ]} - /> - ; - })()} -
- ))} - {error &&
{error}
} - -
; -} -// ── API Key detail ──────────────────────────────────────────────────────────── -// omp keeps API keys in its own encrypted credential store (agent.db), which -// omp-web never reads or writes — this panel is status-only. - -export function ApiKeyDetail({ provider }: { provider: ApiKeyProvider }) { - const { t, tn } = useI18n(); return (
@@ -369,9 +262,35 @@ export function ApiKeyDetail({ provider }: { provider: ApiKeyProvider }) { : t("modelsConfig.providerNotConfigured", { name: provider.displayName })}

-

- -

+ {provider.apiKeyLogin ? ( +
{ event.preventDefault(); if (key.trim()) void call("POST"); }} + style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }} + > + setKey(event.target.value)} + aria-label={t("modelsConfig.apiKeyFor", { name: provider.displayName })} + placeholder={t("modelsConfig.apiKey")} + style={{ flex: "1 1 220px", minWidth: 0, padding: "6px 10px", border: "1px solid var(--border)", borderRadius: "var(--radius-control)", background: "var(--bg-panel)", color: "var(--text)", fontSize: 12, fontFamily: "var(--font-mono)" }} + /> + + {provider.stored === "api_key" && ( + + )} +
+ ) : ( +

+ +

+ )} + {error &&
{error}
}
); } diff --git a/components/ModelsConfig-types.ts b/components/ModelsConfig-types.ts index 3b2a6203..89e3c626 100644 --- a/components/ModelsConfig-types.ts +++ b/components/ModelsConfig-types.ts @@ -1,10 +1,10 @@ -// Shared models.yml types, constants, and pure helpers extracted from +// Shared models.json types, constants, and pure helpers extracted from // ModelsConfig.tsx (pure extraction, no behavior change). export type IconComponent = React.ComponentType<{ size?: number | string; style?: React.CSSProperties }>; // Provider glyphs are derived from the provider id. Provider ids come from -// OMP/models.yml at runtime, so adding one never requires a UI registry entry. +// pi's models.json at runtime, so adding one never requires a UI registry entry. // ── Types ───────────────────────────────────────────────────────────────────── @@ -20,6 +20,10 @@ export interface ApiKeyProvider { displayName: string; configured: boolean; modelCount: number; + /** pi can store a key for it (`/api/auth/api-key/[provider]`). */ + apiKeyLogin?: boolean; + /** The credential type stored in the host's auth.json, if any. */ + stored?: "api_key" | "oauth" | null; } export type OAuthLoginState = @@ -33,21 +37,16 @@ export type OAuthLoginState = | { phase: "success" } | { phase: "error"; message: string }; -// Mirrors the ModelThinkingSchema subset of omp's models.yml -// (oh-my-pi/packages/coding-agent/src/config/models-config-schema.ts). -export interface ThinkingConfig { - mode?: string; - efforts?: string[]; - defaultLevel?: string; - effortMap?: Record; -} +// pi's `thinkingLevelMap`: the value sent for a level, null when the model does not support it; an absent level +// keeps pi's default (supported through high; xhigh and max unsupported). +export type ThinkingLevelMap = Record; export interface ModelEntry { id: string; name?: string; api?: string; reasoning?: boolean; - thinking?: ThinkingConfig; + thinkingLevelMap?: ThinkingLevelMap; input?: string[]; contextWindow?: number; maxTokens?: number; @@ -81,7 +80,6 @@ export type Selection = | { type: "model"; providerName: string; index: number } | { type: "oauth"; providerId: string } | { type: "apikey"; providerId: string } - | { type: "roles" } | { type: "picker" } | { type: "registry" } | { type: "fallbacks" }; @@ -95,22 +93,17 @@ export interface RuntimeModelEntry { export interface ConnectedProvider { id: string; name: string; - disabled: boolean; } export type NativeRegistrySettings = { enabledModels?: string[]; - disabledProviders?: string[]; - modelProviderOrder?: string[]; - registryHasScopedEntries?: boolean; }; export type RetrySettings = { - retry?: { enabled?: boolean; maxRetries?: number; modelFallback?: boolean; fallbackRevertPolicy?: "cooldown-expiry" | "never"; fallbackChains?: Record }; + retry?: { enabled?: boolean; maxRetries?: number }; }; -export const COMPOSER_MODELS_STORAGE_KEY = "omp-composer-models"; -export const NATIVE_MODEL_ROLES = ["default", "smol", "slow", "vision", "plan", "designer", "commit", "tiny", "task", "advisor"]; -// omp's models.yml ApiSchema (config/models-config-schema.ts) +export const COMPOSER_MODELS_STORAGE_KEY = "tau-composer-models"; +// APIs a models.json provider or model can name. export const API_OPTIONS = [ "openai-completions", "openai-responses", @@ -154,10 +147,11 @@ export const presetButtonStyle = { color: "var(--text)", cursor: "pointer", } as const; -export const THINKING_LEVELS = ["minimal", "low", "medium", "high", "xhigh", "max"] as const; +export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const; export type ThinkingLevel = typeof THINKING_LEVELS[number]; export const LEVEL_COLORS: Record = { + off: "var(--text-dim)", minimal: "var(--text-dim)", low: "color-mix(in srgb, var(--accent) 45%, var(--text-muted))", medium: "var(--accent)", diff --git a/components/ModelsConfig.test.mjs b/components/ModelsConfig.test.mjs index 23d0b1d9..03383238 100644 --- a/components/ModelsConfig.test.mjs +++ b/components/ModelsConfig.test.mjs @@ -6,24 +6,10 @@ import { createElement } from "react"; const { cleanup, render, screen, waitFor } = await import("@testing-library/react/pure.js"); const { default: userEvent } = await import("@testing-library/user-event"); const { providerInitials } = await import("./ModelsConfig.tsx"); -const { RetryFallbackDetail } = await import("./ModelsConfig-panels.tsx"); +const { ApiKeyDetail } = await import("./ModelsConfig-panels.tsx"); afterEach(cleanup); -const runtimeModel = { - provider: "openai-codex", - id: "gpt-5.6-sol", - name: "GPT 5.6 Sol", - thinkingLevels: ["off", "low", "medium", "high"], -}; - -async function chooseFallback(user, effort) { - await user.click(await screen.findByRole("combobox", { name: "Select a fallback model" })); - await user.click(await screen.findByRole("option", { name: "openai-codex/gpt-5.6-sol" })); - await user.click(screen.getByRole("combobox", { name: "Thinking levels" })); - await user.click(await screen.findByRole("option", { name: effort })); -} - test("provider glyphs derive from arbitrary runtime provider ids", () => { assert.equal(providerInitials("acme-provider"), "AP"); assert.equal(providerInitials("my_custom_gateway"), "MC"); @@ -31,99 +17,22 @@ test("provider glyphs derive from arbitrary runtime provider ids", () => { assert.equal(providerInitials(""), "?"); }); -test("fallback chains can select a model effort", async (t) => { - const writes = []; - t.mock.method(globalThis, "fetch", async (_url, init) => { - if (init?.method === "PUT") { - writes.push(JSON.parse(init.body)); - return Response.json(JSON.parse(init.body)); - } - return Response.json({ settings: {} }); - }); - - render(createElement(RetryFallbackDetail, { models: [runtimeModel] })); - const user = userEvent.setup(); - await chooseFallback(user, "high"); - await user.click(screen.getByRole("button", { name: "Add" })); - - await waitFor(() => assert.deepEqual( - writes.at(-1).settings.retry.fallbackChains.default, - ["openai-codex/gpt-5.6-sol:high"], - )); -}); - -test("fallback chains expose the runtime off effort", async (t) => { - const writes = []; - t.mock.method(globalThis, "fetch", async (_url, init) => { - if (init?.method === "PUT") { - writes.push(JSON.parse(init.body)); - return Response.json(JSON.parse(init.body)); - } - return Response.json({ settings: {} }); - }); - - render(createElement(RetryFallbackDetail, { models: [runtimeModel] })); - const user = userEvent.setup(); - await chooseFallback(user, "off"); - await user.click(screen.getByRole("button", { name: "Add" })); - - await waitFor(() => assert.deepEqual( - writes.at(-1).settings.retry.fallbackChains.default, - ["openai-codex/gpt-5.6-sol:off"], - )); -}); - -test("fallback chains allow an effort variant after the model default", async (t) => { - const writes = []; - t.mock.method(globalThis, "fetch", async (_url, init) => { - if (init?.method === "PUT") { - writes.push(JSON.parse(init.body)); - return Response.json(JSON.parse(init.body)); - } - return Response.json({ settings: { retry: { fallbackChains: { default: ["openai-codex/gpt-5.6-sol"] } } } }); +test("an API key is saved to and removed from the selected host's pi", async (t) => { + const calls = []; + t.mock.method(globalThis, "fetch", async (url, init) => { + calls.push([String(url), init?.method, init?.body ? JSON.parse(init.body) : undefined]); + return Response.json({ ok: true }); }); - - render(createElement(RetryFallbackDetail, { models: [runtimeModel] })); - const user = userEvent.setup(); - await chooseFallback(user, "high"); - await user.click(screen.getByRole("button", { name: "Add" })); - - await waitFor(() => assert.deepEqual( - writes.at(-1).settings.retry.fallbackChains.default, - ["openai-codex/gpt-5.6-sol", "openai-codex/gpt-5.6-sol:high"], - )); -}); - -test("fallback chains reject an exact duplicate selector", async (t) => { - const writes = []; - t.mock.method(globalThis, "fetch", async (_url, init) => { - if (init?.method === "PUT") { - writes.push(JSON.parse(init.body)); - return Response.json(JSON.parse(init.body)); - } - return Response.json({ settings: { retry: { fallbackChains: { default: ["openai-codex/gpt-5.6-sol:high"] } } } }); - }); - - render(createElement(RetryFallbackDetail, { models: [runtimeModel] })); + let refreshed = 0; + const provider = { id: "groq", displayName: "Groq", configured: true, modelCount: 3, apiKeyLogin: true, stored: "api_key" }; + render(createElement(ApiKeyDetail, { provider, hostId: "box", onRefresh: () => refreshed++ })); const user = userEvent.setup(); - await chooseFallback(user, "high"); - - assert.equal(screen.getByRole("button", { name: "Add" }).disabled, true); - assert.deepEqual(writes, []); -}); - -test("a failed fallback save restores the confirmed chain", async (t) => { - t.mock.method(globalThis, "fetch", async (_url, init) => { - if (init?.method === "PUT") return Response.json({ error: "save failed" }, { status: 500 }); - return Response.json({ settings: {} }); - }); - - render(createElement(RetryFallbackDetail, { models: [runtimeModel] })); - const user = userEvent.setup(); - await chooseFallback(user, "high"); - await user.click(screen.getByRole("button", { name: "Add" })); - - await screen.findByRole("alert"); - assert.equal(screen.queryByText("openai-codex/gpt-5.6-sol:high"), null); - assert.ok(screen.getByText("No explicit chain. OMP uses the default chain when available.")); + await user.type(screen.getByLabelText("API key for Groq"), "gsk-1"); + await user.click(screen.getByRole("button", { name: "Save key" })); + await waitFor(() => assert.equal(refreshed, 1)); + assert.deepEqual(calls[0], ["/api/auth/api-key/groq?hostId=box", "POST", { key: "gsk-1" }]); + assert.equal(screen.getByLabelText("API key for Groq").value, "", "the typed key is not kept"); + await user.click(screen.getByRole("button", { name: "Remove stored key" })); + await waitFor(() => assert.equal(refreshed, 2)); + assert.deepEqual(calls[1], ["/api/auth/api-key/groq?hostId=box", "DELETE", undefined]); }); diff --git a/components/ModelsConfig.tsx b/components/ModelsConfig.tsx index dd82b983..bca0400f 100644 --- a/components/ModelsConfig.tsx +++ b/components/ModelsConfig.tsx @@ -1,7 +1,9 @@ "use client"; import { useState, useEffect, useCallback, useRef } from "react"; +import { useHostRows } from "@/hooks/useHostRows"; import { useIsMobile } from "@/hooks/useIsMobile"; +import { isLinkUp } from "@/lib/hosts/host"; import { useI18n } from "@/lib/i18n"; import { isSafeExternalUrl } from "@/lib/safe-url"; import { omitUntouchedModelDrafts } from "@/lib/models-config-drafts"; @@ -20,10 +22,11 @@ import { ConfirmDialog, useFieldValidation, } from "@/components/ui/field"; -import { Plus, Trash2, RefreshCw, AlertCircle, Cpu, Settings, Sparkles, Check as CheckIcon, Layers, RotateCcw, SlidersHorizontal, BookOpen, Search, KeyRound, ArrowLeft } from "lucide-react"; +import { Plus, Trash2, RefreshCw, AlertCircle, Cpu, Settings, Sparkles, Check as CheckIcon, Layers, RotateCcw, BookOpen, Search, KeyRound, ArrowLeft } from "lucide-react"; import { toast } from "@/components/ui/toast"; import { SettingsTabs, type SettingsTab } from "./SettingsTabs"; import { ModelCatalogPicker } from "./ModelCatalogPicker"; +import { hostName } from "./host-status"; import { ProviderAccounts } from "./ProviderAccounts"; import { API_OPTIONS, @@ -44,14 +47,13 @@ import { type ConnectedProvider, type RuntimeModelEntry, type Selection, - type ThinkingConfig, + type ThinkingLevelMap, type ThinkingLevel, } from "./ModelsConfig-types"; import { AddProviderPicker, ApiKeyDetail, CodeText, - ModelRolesDetail, ModelsConfigSurface, NativeRegistryDetail, ProviderIcon, @@ -315,55 +317,33 @@ function ProviderDetail({ name, provider, onChange, onRename, onDelete }: { } // ── Thinking levels editor ──────────────────────────────────────────────────── -// Edits omp's `thinking` config: `efforts` lists the enabled levels, and -// `effortMap` overrides the string sent on the wire for a level. When every -// row is Default the config is omitted and omp derives the ladder itself. +// Edits a model's `thinkingLevelMap`: Default leaves a level out, Disabled +// maps it to null, Custom to the value sent on the wire. When every row is +// Default the map is omitted. function ThinkingEditor({ value, onChange, }: { - value: ThinkingConfig | undefined; - onChange: (v: ThinkingConfig | undefined) => void; + value: ThinkingLevelMap | undefined; + onChange: (v: ThinkingLevelMap | undefined) => void; }) { const { t } = useI18n(); - const efforts = value?.efforts; - const effortMap = value?.effortMap ?? {}; const setLevel = (level: ThinkingLevel, entry: string | null | "omit") => { - // entry: "omit" → enabled with the default wire value; null → level - // disabled (excluded from efforts); string → enabled with a custom value. - const included = new Set(efforts ?? [...THINKING_LEVELS]); - const map: Record = { ...effortMap }; - if (entry === null) { - included.delete(level); - delete map[level]; - } else { - included.add(level); - if (entry === "omit") delete map[level]; - else map[level] = entry; - } - const ordered = THINKING_LEVELS.filter((l) => included.has(l)); - if (ordered.length === 0 || (ordered.length === THINKING_LEVELS.length && Object.keys(map).length === 0)) { - onChange(undefined); - return; - } - onChange({ - ...(value ?? {}), - mode: value?.mode ?? "effort", - efforts: ordered, - effortMap: Object.keys(map).length ? map : undefined, - }); + const map: ThinkingLevelMap = { ...value }; + if (entry === "omit") delete map[level]; + else map[level] = entry; + onChange(Object.keys(map).length ? map : undefined); }; return (
{THINKING_LEVELS.map((level) => { - const disabled = efforts !== undefined && !efforts.includes(level); - const raw = disabled ? null : effortMap[level]; + const raw = value?.[level]; const state: "omit" | "null" | "string" = - disabled ? "null" : typeof raw === "string" ? "string" : "omit"; + raw === null ? "null" : typeof raw === "string" ? "string" : "omit"; const strVal = typeof raw === "string" ? raw : ""; const color = LEVEL_COLORS[level]; @@ -608,10 +588,10 @@ function ModelDetail({ } >
- {model.thinking && ( + {model.thinkingLevelMap && (
set("thinking", v)} + value={model.thinkingLevelMap} + onChange={(v) => set("thinkingLevelMap", v)} /> )} @@ -780,7 +760,7 @@ function ModelDetail({ // ── OAuth detail ────────────────────────────────────────────────────────────── -function OAuthDetail({ provider, onRefresh }: { provider: OAuthProvider; onRefresh: () => void }) { +function OAuthDetail({ provider, hostId, onRefresh }: { provider: OAuthProvider; hostId: string; onRefresh: () => void }) { const { t, tn } = useI18n(); const [loginState, setLoginState] = useState({ phase: "idle" }); const [inputValue, setInputValue] = useState(""); @@ -812,7 +792,7 @@ function OAuthDetail({ provider, onRefresh }: { provider: OAuthProvider; onRefre setLoginState({ phase: "connecting" }); setInputValue(""); - const es = new EventSource(`/api/auth/login/${encodeURIComponent(provider.id)}`); + const es = new EventSource(`/api/auth/login/${encodeURIComponent(provider.id)}?hostId=${encodeURIComponent(hostId)}`); eventSourceRef.current = es; es.onmessage = (e) => { @@ -863,7 +843,7 @@ function OAuthDetail({ provider, onRefresh }: { provider: OAuthProvider; onRefre es.close(); setLoginState((prev) => prev.phase === "success" ? prev : { phase: "error", message: t("modelsConfig.connectionLost") }); }; - }, [provider.id, onRefresh, t]); + }, [provider.id, hostId, onRefresh, t]); const submitCode = useCallback(async (token: string, code: string) => { if (!code.trim()) return; @@ -1007,7 +987,7 @@ function OAuthDetail({ provider, onRefresh }: { provider: OAuthProvider; onRefre )}
- + {/* Actions */}
@@ -1046,7 +1026,7 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } const [saveError, setSaveError] = useState(null); const [savedOk, setSavedOk] = useState(false); const [subTab, setSubTab] = useState<"connected" | "custom" | "system">("connected"); - const [systemTab, setSystemTab] = useState<"registry" | "picker" | "roles" | "fallbacks">("registry"); + const [systemTab, setSystemTab] = useState<"registry" | "picker" | "fallbacks">("registry"); const [selection, setSelection] = useState(null); const [oauthProviders, setOauthProviders] = useState([]); const [apiKeyProviders, setApiKeyProviders] = useState([]); @@ -1063,24 +1043,31 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } // instead of an empty form, and saving stays blocked so the hand-written file // is never overwritten with nothing. const [parseError, setParseError] = useState<{ message: string; path?: string } | null>(null); + // Logins are per host: each one keeps its own pi credentials. Only hosts whose link is up can be asked. + const { hosts } = useHostRows(); + const authHosts = (hosts ?? []).filter((host) => isLinkUp(host.status)); + const [chosenAuthHost, setAuthHost] = useState("local"); + const authHost = authHosts.some((host) => host.id === chosenAuthHost) ? chosenAuthHost : "local"; const loadOAuthProviders = useCallback(() => { - fetch("/api/auth/providers") + setOauthProviders([]); + fetch(`/api/auth/providers?hostId=${encodeURIComponent(authHost)}`) .then((r) => r.json()) .then((d: { providers?: OAuthProvider[] }) => { if (Array.isArray(d.providers)) setOauthProviders(d.providers); }) .catch(() => {}); - }, []); + }, [authHost]); const loadApiKeyProviders = useCallback(() => { - fetch("/api/auth/all-providers") + setApiKeyProviders([]); + fetch(`/api/auth/all-providers?hostId=${encodeURIComponent(authHost)}`) .then((r) => r.json()) .then((d: { providers?: ApiKeyProvider[] }) => { if (Array.isArray(d.providers)) setApiKeyProviders(d.providers); }) .catch(() => {}); - }, []); + }, [authHost]); const loadRuntimeModels = useCallback(async () => { setRuntimeModelsLoading(true); @@ -1120,10 +1107,14 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } useEffect(() => { loadConfig(); + loadRuntimeModels(); + }, [loadConfig, loadRuntimeModels]); + + // Again whenever another host is chosen. + useEffect(() => { loadOAuthProviders(); loadApiKeyProviders(); - loadRuntimeModels(); - }, [loadConfig, loadOAuthProviders, loadApiKeyProviders, loadRuntimeModels]); + }, [loadOAuthProviders, loadApiKeyProviders]); useEffect(() => { try { @@ -1138,7 +1129,7 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } if (visibleModelKeys === null) return; try { localStorage.setItem(COMPOSER_MODELS_STORAGE_KEY, JSON.stringify([...visibleModelKeys])); - window.dispatchEvent(new Event("omp-composer-models-change")); + window.dispatchEvent(new Event("tau-composer-models-change")); } catch { // Storage is optional UI state; a disabled or full store must not break settings. } @@ -1166,13 +1157,6 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } }, [runtimeModels]); - const enableConnectedProvider = useCallback(async (provider: string) => { - const response = await fetch("/api/providers/enable", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider }) }); - const data = await response.json() as { error?: string }; - if (!response.ok || data.error) throw new Error(data.error || `HTTP ${response.status}`); - await loadRuntimeModels(); - }, [loadRuntimeModels]); - const addCustomProvider = useCallback(() => { let finalName = "new-provider"; let n = 1; @@ -1315,16 +1299,15 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } if (selection.type === "oauth") { const p = oauthProviders.find((p) => p.id === selection.providerId); if (!p) return null; - return { loadOAuthProviders(); loadApiKeyProviders(); void loadRuntimeModels(); }} />; + return { loadOAuthProviders(); loadApiKeyProviders(); void loadRuntimeModels(); }} />; } if (selection.type === "apikey") { const p = apiKeyProviders.find((p) => p.id === selection.providerId); if (!p) return null; - return ; + return { loadApiKeyProviders(); void loadRuntimeModels(); }} />; } - if (selection.type === "roles") return ; - if (selection.type === "registry") return ; - if (selection.type === "fallbacks") return ; + if (selection.type === "registry") return ; + if (selection.type === "fallbacks") return ; if (selection.type === "picker") { const pickerQuery = composerPickerSearch.trim().toLowerCase(); const matchesPicker = (model: RuntimeModelEntry) => @@ -1344,7 +1327,7 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } {t("modelsConfig.composerPickerTitle")}

{t("modelsConfig.composerPickerDesc")}

- {/* Refresh OMP runtime models */} + {/* Refresh pi runtime models */}
@@ -1393,8 +1376,7 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } {!runtimeModelsLoading && connectedProviders.filter((provider) => !runtimeModelsByProvider[provider.id]).map((provider) => (
{provider.name}
-

{provider.disabled ? t("modelsConfig.connectedDisabledDesc") : t("modelsConfig.connectedNoModelsDesc")}

- {provider.disabled && } +

{t("modelsConfig.connectedNoModelsDesc")}

))}
@@ -1437,7 +1419,7 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } {!embedded && (
{t("modelsConfig.title")} - ~/.omp/agent/models.yml + ~/.pi/agent/models.json
)} @@ -1494,10 +1476,22 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } onClick={() => { setSubTab("system"); setSelection({ type: systemTab }); }} >
+ {subTab === "connected" && authHosts.length > 1 && ( + + )} {subTab === "connected" && !selection && (
- - ); -} - function SegmentedScope({ value, onChange, @@ -463,33 +413,14 @@ function PackageDetail({ const key = packageKey(pkg); const busy = busyKey?.endsWith(key) ?? false; const reloadBusy = busyKey === "reload"; - const enabled = !pkg.disabled; const [confirmRemove, setConfirmRemove] = useState(false); return (
- onAction(pkg.disabled ? "enable" : "disable", pkg)} - label={pkg.disabled ? t("pluginsConfig.enablePackage") : t("pluginsConfig.disablePackage")} - /> - {pkg.disabled ? ( - - {t("pluginsConfig.badgeDisabled")} - - ) : pkg.filtered && ( + {pkg.filtered && ( , string> = { install: "pluginsConfig.packageInstalled", update: "pluginsConfig.packageUpdated", - disable: "pluginsConfig.packageDisabledMsg", - enable: "pluginsConfig.packageEnabledMsg", }; setActionMessage(t(messageKeys[action])); toast.success(t(messageKeys[action])); diff --git a/components/ProjectLaunchConfigDialog.test.mjs b/components/ProjectLaunchConfigDialog.test.mjs index 2e685fa7..c5648e4e 100644 --- a/components/ProjectLaunchConfigDialog.test.mjs +++ b/components/ProjectLaunchConfigDialog.test.mjs @@ -9,22 +9,16 @@ afterEach(cleanup); test("the launch editor exposes legacy values and saves an explicit correction or clear", async () => { const saved = []; - const props = { projectPath: "/workspace", initialConfig: { profile: "nova insight", extraArgs: ["--profile", "work"] }, onClose() {}, onSave: async (config) => { saved.push(config); } }; + const props = { projectPath: "/workspace", initialConfig: { extraArgs: ["--fork", "/elsewhere"] }, onClose() {}, onSave: async (config) => { saved.push(config); } }; const view = render(React.createElement(ProjectLaunchConfigDialog, props)); - const profile = view.getByDisplayValue("nova insight"); const args = view.getByRole("textbox", { name: translate("projectLaunchConfig.extraArgsLabel") }); - assert.equal(args.value, "--profile\nwork"); + assert.equal(args.value, "--fork\n/elsewhere"); const save = view.getByRole("button", { name: translate("projectLaunchConfig.save") }); - assert.equal(profile.getAttribute("aria-invalid"), "true"); - assert.equal(save.disabled, true); - fireEvent.change(profile, { target: { value: "work" } }); fireEvent.change(args, { target: { value: "--verbose" } }); fireEvent.click(save); - await waitFor(() => assert.deepEqual(saved[0], { profile: "work", advisor: undefined, extraArgs: ["--verbose"] })); + await waitFor(() => assert.deepEqual(saved[0], { extraArgs: ["--verbose"] })); await waitFor(() => assert.equal(save.disabled, false)); - fireEvent.change(profile, { target: { value: "" } }); fireEvent.change(args, { target: { value: "" } }); - await waitFor(() => assert.equal(save.disabled, false)); fireEvent.click(save); await waitFor(() => assert.equal(saved[1], null)); }); diff --git a/components/ProjectLaunchConfigDialog.tsx b/components/ProjectLaunchConfigDialog.tsx index b9ef2444..3f61ff47 100644 --- a/components/ProjectLaunchConfigDialog.tsx +++ b/components/ProjectLaunchConfigDialog.tsx @@ -1,7 +1,6 @@ "use client"; import { useState } from "react"; -import { isValidOmpProfile } from "@/lib/omp-profile"; import { useI18n } from "@/lib/i18n"; import type { ProjectLaunchConfig } from "@/lib/types"; import { Dialog, DialogContent, DialogTitle } from "./ui/primitives"; @@ -13,25 +12,17 @@ interface Props { onSave: (config: ProjectLaunchConfig | null) => Promise; } -/** Edit the workspace-specific OMP launch configuration, storing extra args as an array. */ +/** Edit the workspace-specific pi launch configuration, storing extra args as an array. */ export function ProjectLaunchConfigDialog({ projectPath, initialConfig, onClose, onSave }: Props) { const { t } = useI18n(); - const [profile, setProfile] = useState(initialConfig?.profile ?? ""); - const [advisor, setAdvisor] = useState(initialConfig?.advisor === true); const [extraArgs, setExtraArgs] = useState(initialConfig?.extraArgs?.join("\n") ?? ""); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); - const profileInvalid = profile !== "" && !isValidOmpProfile(profile); /** Shape the form contents into the structured config the API uses. */ const buildConfig = (): ProjectLaunchConfig | null => { const args = extraArgs.split("\n").map((arg) => arg.trim()).filter(Boolean); - const config: ProjectLaunchConfig = { - profile: profile.trim() || undefined, - advisor: advisor || undefined, - extraArgs: args.length > 0 ? args : undefined, - }; - return config.profile || config.advisor || config.extraArgs ? config : null; + return args.length > 0 ? { extraArgs: args } : null; }; /** Save the config, keeping the dialog contents on failure for easy correction. */ @@ -56,29 +47,18 @@ export function ProjectLaunchConfigDialog({ projectPath, initialConfig, onClose,
{projectPath}
- -