diff --git a/AGENTS.md b/AGENTS.md index 8a453d20f..7593b18c1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -106,7 +106,9 @@ app/api/ 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/[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) | DELETE leave; 409 `{ error, code }` for offline/old daemon/`cluster_changed`, 503 if `pools.json` is unreadable + 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) @@ -123,11 +125,11 @@ app/api/ 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 - plugins/route.ts GET/POST plugin management (shells out to `omp plugin`) + 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 + 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) @@ -141,6 +143,7 @@ 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`; `SESSION_EDIT_EXTENSION_PATH` (from the module's own location: the daemon runs in HOME). Never imported by main, nor is `daemon.ts` (`no-direct-local.test.mjs`) @@ -157,6 +160,10 @@ lib/ 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 @@ -456,12 +463,13 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri 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: - `MIN_LINK_PROTOCOL_VERSION` is 4 and `LINK_PROTOCOL_VERSION` 9 (literal + `MIN_LINK_PROTOCOL_VERSION` is 4 and `LINK_PROTOCOL_VERSION` 10 (literal one-liners: the deploy script parses them with `sed`); a v4 daemon gets no `part`, whole lines and no unacked window (`link.sender.parts`); a v4/v5 daemon gets 426 for uploads. v8 (host pool) adds `capacity` reports, `creationId` and `preparePoolProject`; v9 adds `open.launch.shareCredentials` (see "Shared - credentials" below). Main keeps at least N-1, and + credentials" below); v10 adds `open.launch.configVersion`, the `config_state` + report and the `clusterConfig` op (see "Cluster configuration" below). 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 @@ -529,17 +537,24 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri 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) and the prefix - `/api/hosts/broker/v1/` (below): the daemon has no + (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 second - ungated path (the `UNGATED` pattern names that prefix; anything else under + `/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. + 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 @@ -597,11 +612,80 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri 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. - - **Not mirrored to members:** `models.yml` custom providers, - environment-variable API keys and omp settings; a cluster session's models - depend on the member chosen. + - **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; a member + below v10 is refused 426 `host_upgrade_required`. 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 hub ignores it below v10. The + `clusterConfig` op is `{ action: "apply", version }` or `{ action: "restore" }` and answers `{ state, owned }`. + **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 cluster member needs a daemon at protocol 10 (`CLUSTER_CONFIG_SINCE_VERSION`; also the + join rule `CLUSTER_SINCE_VERSION`). Until then starts there are refused and placement skips it. + - **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 (below v10), 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 @@ -831,7 +915,8 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri 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; transcript search reads +- **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 reads this machine's files. #### Local daemon (`docs/specs/2026-10-29-local-daemon-design.md`) @@ -1616,6 +1701,7 @@ during the wait. the RPC 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. @@ -1623,6 +1709,7 @@ during the wait. - 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** owns the web server's settings and application update. `GET /api/app-update` and its prepare/commit flow remain web-server-only; a compiled web server still links to the release download page. diff --git a/CHANGELOG.md b/CHANGELOG.md index 89dc4917e..bce17c30e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,10 +8,14 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Added -- **Cluster membership in Settings.** There is one cluster, the first pool in `pools.json`, and this machine is its master. Each linked host has an **In the cluster** switch in **Settings → Hosts**; turning it on asks for the folder on that host where the cluster keeps the checkouts it creates and says what changes, turning it off asks for confirmation. A host can join while it is online, on link protocol 9, answering `gitOrigins` and running omp 15.13.1 or newer (a member always uses this machine's provider logins); otherwise the switch is disabled and says why. While this machine is not a member yet, any join adds it too: the switch then also needs this machine's daemon ready, and the dialog says that this machine's Git projects become cluster projects whose new sessions start on any member with capacity (currently Linux hosts only, so a macOS or Windows master runs none itself). Joining matches the host's Git projects to cluster projects by repository, so the same repository on several members is one project and its sessions are listed together (`git@github.com:a/b.git` and `https://github.com/a/b` match); adding a cluster project by another URL form of a repository it already has returns that project. A created cluster project keeps the name and alias the host showed (its folder name when it had none), and a visible checkout makes a matching hidden cluster project visible again. Projects without a single Git `origin`, subfolders and linked worktrees stay on their node. A host too slow to report its Git remotes within the time limit keeps the remaining projects on its node; leaving and joining again retries them. Leaving unbinds the matched projects, so they are listed under the host again, and keeps the checkouts the cluster created and the projects it gained from the host; hide any you do not want. Revoking a member removes it from the cluster the same way; while `pools.json` cannot be read, the revoke is refused. A pool disabled through the API takes no new sessions, so this machine's Git projects moved into it cannot start any. Custom providers in `models.yml`, environment-variable API keys and omp settings are not mirrored to members yet. New: `PUT`/`DELETE /api/hosts/[id]/cluster`, and the host operation `gitOrigins`. +- **Cluster members use this machine's omp configuration.** + **Before upgrading:** every cluster member needs an ompweb host daemon at link protocol 10. Until a member's daemon is updated, sessions cannot start there (the start is refused and names the update), cluster placement skips it, a host below protocol 10 cannot join, 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, and its own omp configuration is replaced until it leaves the cluster; it is kept in `/omp-web/own-config/` on the member and put back on leaving. To avoid that for a host, remove it from the first pool (`PUT /api/hosts`, or editing `~/.omp/agent/omp-web/pools.json`) before updating its daemon. Update the web server first, then the members. + A cluster session now runs with this machine's settings (`config.yml`, without the machine-specific keys), `models.yml`, MCP servers, skills, task agents, rules and context files, commands, prompts, hooks, extensions, custom tools, `secrets.yml`, `.env`, the agent environment variables of Settings → System, and the installed plugins, whichever member it runs on. A change made here, in Settings or on disk, reaches the members within about a minute and before every session start on a member. Every cluster session start carries this machine's version: a start that must run on one member is refused with the reason when its files cannot be applied, and new sessions are placed only on members with the 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, and running sessions are not restarted. A mirrored directory becomes equal to this machine's. The member's backup holds only what the host had when it joined: a file it adds or edits afterwards is deleted at the next apply, not backed up. Settings that describe the machine itself stay the member's own as they were when the host joined (see the README). A host holds one ompweb server's configuration: a host already in another server's cluster cannot join (409 `host_in_other_cluster`), and a member that also runs sessions for another server runs them on this one's configuration. The configuration contains secrets, which are written to every member's disk, readable by the daemon's user only; the hooks, extensions, tools and plugins in it run on every member, and this machine can already start omp with full tool access there. Each file is limited to 5 MiB and the configuration to 50 MiB; a configuration over a limit, or one that cannot be read, is not mirrored at all, a cluster session start on a member is refused (409 `cluster_config_invalid`), placement skips every member, and Settings names the file. Each download has a 30 s limit including the body (a 5 MiB file needs roughly 1.4 Mbit/s). An apply is refused on a member where `~/.agents` is a symbolic link, and the mirrored directories and the backup must be on one filesystem. The reverse proxy must pass `/api/hosts/cluster-config/manifest` and `/api/hosts/cluster-config/file/` without its own authentication, at exactly these paths (unlike the broker's prefix). + Plugins are installed (this needs `bun` and network access on the member), removed and enabled or disabled on each member by `omp plugin`: npm plugins are pinned to this machine's version, marketplace plugins have no version pin in omp, and a failing install leaves the member not current and is retried. Leaving puts the member's own configuration and plugins back; if that fails Settings says so, and it is retried while the host is linked. Revoking a member does the same: its daemon puts its own configuration back at once if it is connected, otherwise the next time it reaches this machine. **Settings → Hosts** shows each member's state (same as the master, updating, failed with the reason, held by another server, needs an update) and the MCP server commands that are not installed there, and names the file when this machine's configuration cannot be mirrored (the member lines then do not say updating). For a session on another member, the MCP, Skills, Plugins and Agents screens act on this machine's user-level configuration, and say they apply to every member, as does Settings → System next to the agent environment variables in a cluster session; MCP shows that session's live status read-only, and the session's MCP switches, reload and Skills diagnostics are not available there. `GET /api/plugins`, `POST /api/plugins`, `GET /api/skills`, `POST /api/skills/check` and `POST /api/skills/update` now accept a request without `cwd` for the user level, and `GET /api/mcp?attach=1` reads a running session's live MCP status without starting one. A provider in `models.yml` that points at this machine's own address, MCP servers started by a command, and API keys written as an environment-variable name or `!command` need what they refer to on each member. +- **Cluster membership in Settings.** There is one cluster, the first pool in `pools.json`, and this machine is its master. Each linked host has an **In the cluster** switch in **Settings → Hosts**; turning it on asks for the folder on that host where the cluster keeps the checkouts it creates and says what changes, turning it off asks for confirmation. A host can join while it is online, on link protocol 10, answering `gitOrigins` and running omp 15.13.1 or newer (a member always uses this machine's provider logins); otherwise the switch is disabled and says why. While this machine is not a member yet, any join adds it too: the switch then also needs this machine's daemon ready, and the dialog says that this machine's Git projects become cluster projects whose new sessions start on any member with capacity (currently Linux hosts only, so a macOS or Windows master runs none itself). Joining matches the host's Git projects to cluster projects by repository, so the same repository on several members is one project and its sessions are listed together (`git@github.com:a/b.git` and `https://github.com/a/b` match); adding a cluster project by another URL form of a repository it already has returns that project. A created cluster project keeps the name and alias the host showed (its folder name when it had none), and a visible checkout makes a matching hidden cluster project visible again. Projects without a single Git `origin`, subfolders and linked worktrees stay on their node. A host too slow to report its Git remotes within the time limit keeps the remaining projects on its node; leaving and joining again retries them. Leaving unbinds the matched projects, so they are listed under the host again, and keeps the checkouts the cluster created and the projects it gained from the host; hide any you do not want. Revoking a member removes it from the cluster the same way; while `pools.json` cannot be read, the revoke is refused. A pool disabled through the API takes no new sessions, so this machine's Git projects moved into it cannot start any. The rest of this machine's omp configuration is mirrored to members too (see the entry above). New: `PUT`/`DELETE /api/hosts/[id]/cluster`, and the host operation `gitOrigins`. - **The sidebar groups the cluster.** The cluster is one group: its projects first, then the projects of its members that could not join, each marked with its node's name; a new session there starts on that node. Members no longer have a group of their own, and standalone hosts keep theirs. - **Cluster members use this machine's provider logins.** A member always runs its sessions with this machine's provider logins, whatever its own **Use this server's provider logins** setting says; Settings shows that toggle on and disabled. It is computed from membership, so leaving brings the host's own setting back. If `pools.json` cannot be read, session starts on a host are refused rather than started with other logins. Cluster placement skips a member whose daemon cannot take these logins (below link protocol 9, or a link that does not share) before preparing a checkout there. - **Before upgrading:** 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`. Each linked member needs an updated ompweb host daemon (link protocol 9) and omp 15.13.1 or newer; until its 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. + **Before upgrading:** 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`. Each linked member needs an updated ompweb host daemon (link protocol 9 at that release; cluster members now need link protocol 10, see the first entry) and omp 15.13.1 or newer; until its 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. - **Hosts can use the server's provider logins.** **Settings → Hosts** has a per-host toggle, **Use this server's provider logins**, off by default; turning it on asks for confirmation. Sessions started on that host then use the logins stored on the ompweb server instead of the host's own, through `omp auth-broker serve` on the server and a loopback forwarder in the host daemon. The host token never enters an omp process's environment, and OAuth refresh tokens never leave the server machine; the host can read current access tokens and stored API keys. Starting a session on a sharing host needs a daemon on link protocol v9 and omp 15.13.1 or newer, and is refused otherwise rather than falling back to the host's own logins. Custom providers in `models.yml`, environment-variable API keys and omp settings are not shared. A reverse proxy must let `/api/hosts/broker/` through without its own authentication, response buffering or redirects. - **Windows hosts can be pool workers and accept local maintenance controls.** `ompweb host status`, `drain` and `resume` now work on Windows through a named pipe with a random name and a per-start token, kept in `/omp-web/host-control.json`; requests without the current token are refused. Windows hosts also report CPU busy time and available memory, so pools can place sessions on them. Windows reports no load average, so CPU pressure there comes from busy time alone. - **Archive and restore sessions on linked hosts.** Archiving now works for sessions on any linked machine, not only this one. The Archived Sessions browser lists every host's archive, shows which host each session is on, and restores it on that host. A host that is offline or runs an older ompweb host is named in the browser instead of hiding its archive silently. Restore rejects a session ID already active on any registered host, so every registered host must be online to restore, even an archive on this machine; the browser names the offline host that blocks it. A per-session claim stops web-server processes that share one agent directory from restoring the same session together; it does not coordinate separate web servers that share a daemon. A restore on another host keeps running when the web server stops waiting for it (after 30 s, or when the link drops), so the session stays claimed until that host's daemon process confirms it stopped: restoring the same ID again, on any host, is refused until then instead of creating a second active copy. Only the daemon process that took the restore can confirm that, so if the daemon was replaced, restarted or shut down meanwhile, or its host was unregistered, the session stays blocked: there is no timeout and no automatic clearing, and recovery is manual (see AGENTS.md). A restored session's attachments and other files are put back before the session becomes visible, so a file attached from another tab at that moment can no longer fail the restore or block retrying it. Restore streams archives with fixed 256 MiB compressed and expanded limits and rejects unsupported session IDs before consuming the archive. diff --git a/README.md b/README.md index 223ee47e1..b7236c674 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,8 @@ Forward WebSocket upgrades on `/api/events/link` (browsers) and `/api/hosts/link 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`, @@ -236,7 +238,7 @@ 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 9 with the `gitOrigins` operation, and omp 15.13.1 or newer (a member always +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 @@ -246,7 +248,7 @@ its own daemon needs the same, and the switch asks to restart the host service o 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. Nothing on the host's disk changes. A + 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 @@ -268,10 +270,10 @@ its own daemon needs the same, and the switch asks to restart the host service o 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. Only provider - logins are shared: `models.yml` custom providers, environment-variable API keys and omp - settings are not mirrored to members yet, so the models a cluster session can use depend on - the member it runs on. + 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 @@ -286,12 +288,24 @@ machine's provider logins (it can read their access tokens and stored API keys), 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) and omp 15.13.1 or newer; until the daemon is updated, cluster +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 @@ -299,6 +313,117 @@ on another worker or on the Mac. Dirty files and unpublished work remain on that 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 @@ -615,7 +740,7 @@ 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; see [Behind a reverse proxy](#behind-a-reverse-proxy). +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. @@ -659,8 +784,10 @@ Notes: 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:** session archiving and the Skills, - Plugins, Agents and MCP settings. Transcript search still scans this machine. +- **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** @@ -673,7 +800,7 @@ By default a host uses its own omp logins. Turn on **Use this server's provider - **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. +- **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. diff --git a/app/api/hosts/[id]/cluster/route.ts b/app/api/hosts/[id]/cluster/route.ts index 08141d69e..c70cc97ec 100644 --- a/app/api/hosts/[id]/cluster/route.ts +++ b/app/api/hosts/[id]/cluster/route.ts @@ -3,8 +3,8 @@ import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-fo 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 type { Host } from "@/lib/hosts/host"; -import { getHost, getHostLinkProtocol, getHostOmpVersion, notifyHostsChange } from "@/lib/hosts/hub"; -import { HostOpError } from "@/lib/hosts/link-protocol"; +import { clusterConfigOp, getHost, getHostLinkProtocol, getHostOmpVersion, listHosts, masterConfigVersion, notifyHostsChange } from "@/lib/hosts/hub"; +import { CLUSTER_CONFIG_SINCE_VERSION, 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 type { OpResult } from "@/lib/hosts/session-ops"; @@ -108,6 +108,11 @@ export async function PUT(request: Request, { params }: Context) { const addLocal = !isClusterMember(pools, LOCAL_HOST_ID); const joining = addLocal ? [getHost(LOCAL_HOST_ID), host] : [host]; joining.forEach(requireReady); + // One cluster per host: its daemon would refuse this server's configuration, and every session start with it. + const held = listHosts().find((row) => row.id === id)?.clusterConfig; + if (held && held.version !== null && !held.owned) { + return fail(`${host.label} runs another server's cluster configuration; it must leave that cluster first`, "host_in_other_cluster", 409); + } // The host round trips come first. pools.json is then read again, joined and saved with no await between, so a change // made meanwhile (a leave, another join, a pool edit) is kept. const gathered: { member: { hostId: string; projectsRoot: string }; facts: HostProjectFacts[] }[] = []; @@ -115,6 +120,9 @@ export async function PUT(request: Request, { params }: Context) { const root = target === host ? projectsRoot : await localProjectsRoot(target); gathered.push({ member: { hostId: target.id, projectsRoot: root }, facts: await hostFacts(target) }); } + // The master's version comes first: nothing may wait between the save and the apply, so a leave cannot come before it. + // A master configuration that cannot be served sends none now; the 30 s sync sends it once it can. + const version = await masterConfigVersion().catch(() => null); try { pools = loadPools(); } catch { @@ -133,6 +141,8 @@ export async function PUT(request: Request, { params }: Context) { } savePools(pools); notifyHostsChange(); + // The joined host only: this machine is the master. A failure shows in the state the host reports; the join stands. + if (version !== null) await clusterConfigOp(host.id, { action: "apply", version }).catch(() => undefined); return Response.json({ pools }, { headers: noStore }); } catch (error) { return errorResponse(error); @@ -153,7 +163,21 @@ export async function DELETE(request: Request, { params }: Context) { savePools(pools); if (loadHosts().find((record) => record.id === id)?.shareCredentials !== true) abortBrokerRequests(id); notifyHostsChange(); - return Response.json({ pools }, { headers: noStore }); + // 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. A daemon below protocol 10 never applied one; + // one that held it before a downgrade reports it once it is updated, and the sync restores it then. + let restoreError: string | undefined; + if ((getHostLinkProtocol(id) ?? CLUSTER_CONFIG_SINCE_VERSION) >= CLUSTER_CONFIG_SINCE_VERSION) { + try { + const answer = await clusterConfigOp(id, { action: "restore" }); + // Still holding a version that is not this server's: one this server cannot put back (another server's, or this + // server's recorded at an address the host still links to). + if (answer.state.version !== null && !answer.owned) restoreError = `${getHost(id)?.label ?? id} still runs a cluster configuration this server cannot put back`; + } catch (error) { + restoreError = error instanceof Error ? error.message : String(error); + } + } + return Response.json({ pools, ...(restoreError === undefined ? {} : { restoreError }) }, { headers: noStore }); } catch (error) { return errorResponse(error); } diff --git a/app/api/hosts/broker/[...path]/route.ts b/app/api/hosts/broker/[...path]/route.ts index fca246111..7ad99e909 100644 --- a/app/api/hosts/broker/[...path]/route.ts +++ b/app/api/hosts/broker/[...path]/route.ts @@ -1,7 +1,8 @@ import { readBodyWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { sharesCredentials } from "@/lib/hosts/cluster"; import { loadPools } from "@/lib/hosts/pools"; -import { hostForToken, HostRegistryUnreadableError, LOCAL_HOST_ID, type HostRecord } from "@/lib/hosts/registry"; +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 @@ -39,17 +40,8 @@ function only(source: Headers, names: readonly string[]): Headers { /** 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 header = request.headers.get("authorization"); - const token = header?.startsWith("Bearer ") ? header.slice("Bearer ".length).trim() : ""; - let host: HostRecord | null; - try { - host = token ? hostForToken(token) : null; - } catch (error) { - if (!(error instanceof HostRegistryUnreadableError)) throw error; - // Never 401: a daemon told its token is unknown stops every omp child. - return fail("The host registry cannot be read", 503); - } - if (!host) return fail("Unknown host token", 401); + 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 { diff --git a/app/api/hosts/cluster-config/file/[hash]/route.ts b/app/api/hosts/cluster-config/file/[hash]/route.ts new file mode 100644 index 000000000..1771a1bdb --- /dev/null +++ b/app/api/hosts/cluster-config/file/[hash]/route.ts @@ -0,0 +1,21 @@ +import { admitClusterMember, configErrorResponse, configFail, currentClusterConfig } from "@/lib/hosts/cluster-config-server"; + +// One file of the current manifest by content hash; a hash of an older configuration is 404. +export async function GET(request: Request, { params }: { params: Promise<{ hash: string }> }) { + const host = admitClusterMember(request); + if (host instanceof Response) return host; + const { hash } = await params; + if (!/^[0-9a-f]{64}$/.test(hash)) return configFail("Not found", 404); + try { + const current = await currentClusterConfig(); + // Admitted again: the host may have been revoked or left the cluster while the configuration was built. + const again = admitClusterMember(request); + if (again instanceof Response) return again; + const bytes = current.content(hash); + if (!bytes) return configFail("Not found", 404); + // buildManifest's bytes are Buffers (never SharedArrayBuffer-backed), which BodyInit accepts. + return new Response(bytes as Uint8Array, { headers: { "content-type": "application/octet-stream", "cache-control": "no-store" } }); + } catch (error) { + return configErrorResponse(host.id, error); + } +} diff --git a/app/api/hosts/cluster-config/manifest/route.ts b/app/api/hosts/cluster-config/manifest/route.ts new file mode 100644 index 000000000..829970c05 --- /dev/null +++ b/app/api/hosts/cluster-config/manifest/route.ts @@ -0,0 +1,16 @@ +import { admitClusterMember, configErrorResponse, currentClusterConfig } from "@/lib/hosts/cluster-config-server"; + +// The master's mirrored configuration for a cluster member: bearer-authenticated, outside the password gate (proxy.ts `UNGATED`). +export async function GET(request: Request) { + const host = admitClusterMember(request); + if (host instanceof Response) return host; + try { + const current = await currentClusterConfig(); + // Admitted again: the host may have been revoked or left the cluster while the configuration was built. + const again = admitClusterMember(request); + if (again instanceof Response) return again; + return Response.json(current.manifest, { headers: { "cache-control": "no-store" } }); + } catch (error) { + return configErrorResponse(host.id, error); + } +} diff --git a/app/api/mcp/route.ts b/app/api/mcp/route.ts index dc88a511c..a3454c352 100644 --- a/app/api/mcp/route.ts +++ b/app/api/mcp/route.ts @@ -85,12 +85,16 @@ export async function GET(request: Request) { // /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); diff --git a/app/api/plugins/route.ts b/app/api/plugins/route.ts index 30fec1f7f..c3a1ed1eb 100644 --- a/app/api/plugins/route.ts +++ b/app/api/plugins/route.ts @@ -1,7 +1,9 @@ import { execFile } from "child_process"; import { existsSync, promises as fs } from "fs"; import { basename, extname, join } from "path"; +import { ANSI_RE, parseJsonLoose } from "@/lib/omp/plugins-cli"; import { resolveOmpBin } from "@/lib/omp/omp-cli"; +import { ensureAgentDir } from "@/lib/omp/paths"; import { createChildProcessEnvironment } from "@/lib/project-command-env"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; import type { @@ -58,8 +60,6 @@ interface OmpPluginList { marketplace?: OmpMarketplacePlugin[]; } -const ANSI_RE = /\x1B\[[0-9;]*m/g; - function emptyCounts(): PluginResourceCounts { return { extensions: 0, skills: 0, prompts: 0, themes: 0 }; } @@ -95,18 +95,6 @@ function runOmp( }); } -/** Parse `--json` stdout, tolerating stray non-JSON lines before the payload. */ -function parseJsonLoose(stdout: string): T | null { - const cleaned = stdout.replace(ANSI_RE, ""); - const start = cleaned.search(/[{[]/); - if (start < 0) return null; - try { - return JSON.parse(cleaned.slice(start)) as T; - } catch { - return null; - } -} - /** 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. */ async function scanPluginSkills(pluginPath: string): Promise { @@ -212,13 +200,15 @@ async function toMarketplacePackageInfo(plugin: OmpMarketplacePlugin): Promise

{ +/** Without a cwd, the user level only (a cluster member's settings act on this machine's, spec K7): omp 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[] = []; const packages: PluginPackageInfo[] = []; const totals = emptyCounts(); try { - const { stdout } = await runOmp(["plugin", "list", "--json"], { cwd, timeout: 60_000 }); + const { stdout } = await runOmp(["plugin", "list", "--json"], { cwd: cwd ?? ensureAgentDir(), timeout: 60_000 }); const list = parseJsonLoose(stdout); if (!list) { diagnostics.push({ @@ -230,6 +220,7 @@ async function readPlugins(cwd: string): Promise { 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({ @@ -274,11 +265,9 @@ function pluginErrorResponse(error: unknown): Response { export async function GET(req: Request) { const { searchParams } = new URL(req.url); const cwd = searchParams.get("cwd"); - if (!cwd) return Response.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); try { - const allowedRoots = await getAllowedFileRoots(); - if (!isExistingFilePathAllowed(cwd, allowedRoots)) { + if (cwd && !isExistingFilePathAllowed(cwd, await getAllowedFileRoots())) { return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } return Response.json(await readPlugins(cwd)); @@ -287,7 +276,7 @@ export async function GET(req: Request) { } } -// POST /api/plugins body: { action, source?, scope?, cwd } +// POST /api/plugins body: { action, source?, scope?, cwd? }; without a cwd, global changes only. export async function POST(req: Request) { try { const body = await req.json() as { @@ -296,32 +285,34 @@ export async function POST(req: Request) { scope?: PluginScope; cwd?: string; }; - if (!body.cwd) return Response.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); + const cwd = body.cwd || null; + const scope = readScope(body.scope); + if (!cwd && scope === "project") return Response.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); if (!body.action) return Response.json({ error: "action required", code: "action_required" }, { status: 400 }); - const allowedRoots = await getAllowedFileRoots(); - if (!isExistingFilePathAllowed(body.cwd, allowedRoots)) { + if (cwd && !isExistingFilePathAllowed(cwd, await getAllowedFileRoots())) { return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); } const source = body.source?.trim(); - const scopeArgs = readScope(body.scope) === "project" ? ["--scope", "project"] : []; + const scopeArgs = scope === "project" ? ["--scope", "project"] : []; + const dir = cwd ?? ensureAgentDir(); if (body.action === "install") { if (!source) return Response.json({ error: "source required", code: "source_required" }, { status: 400 }); - await runOmp(["plugin", "install", source, "--json", ...scopeArgs], { cwd: body.cwd, timeout: 300_000 }); + await runOmp(["plugin", "install", source, "--json", ...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(["plugin", "uninstall", source, "--json", ...scopeArgs], { cwd: body.cwd, timeout: 120_000 }); + await runOmp(["plugin", "uninstall", source, "--json", ...scopeArgs], { cwd: dir, timeout: 120_000 }); } else if (body.action === "update") { - await runOmp(["plugin", "upgrade", ...(source ? [source, ...scopeArgs] : [])], { cwd: body.cwd, timeout: 300_000 }); + await runOmp(["plugin", "upgrade", ...(source ? [source, ...scopeArgs] : [])], { cwd: dir, timeout: 300_000 }); } else if (body.action === "disable" || body.action === "enable") { if (!source) return Response.json({ error: "source required", code: "source_required" }, { status: 400 }); - await runOmp(["plugin", body.action, source, "--json", ...scopeArgs], { cwd: body.cwd, timeout: 60_000 }); + await runOmp(["plugin", body.action, source, "--json", ...scopeArgs], { cwd: dir, timeout: 60_000 }); } else { return Response.json({ error: `Unsupported action: ${body.action}`, code: "plugin_unsupported_action" }, { status: 400 }); } - return Response.json(await readPlugins(body.cwd)); + return Response.json(await readPlugins(cwd)); } catch (error) { return pluginErrorResponse(error); } diff --git a/app/api/skills/check/route.ts b/app/api/skills/check/route.ts index d7ceef839..689316c0e 100644 --- a/app/api/skills/check/route.ts +++ b/app/api/skills/check/route.ts @@ -1,6 +1,6 @@ import type { SkillInstallScope } from "@/lib/api-types"; import { checkSkillUpdates } from "@/lib/skill-updates"; -import { loadSkillsWithInstallInfo } from "@/lib/skills-service"; +import { loadSkillsWithInstallInfo, loadUserSkillsWithInstallInfo } from "@/lib/skills-service"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; export async function POST(req: Request) { @@ -11,10 +11,11 @@ export async function POST(req: Request) { scope?: unknown; }; const cwd = typeof body.cwd === "string" ? body.cwd : ""; - if (!cwd) return Response.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); - const allowedRoots = await getAllowedFileRoots(); - if (!isExistingFilePathAllowed(cwd, allowedRoots)) { - return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + if (cwd) { + const allowedRoots = await getAllowedFileRoots(); + if (!isExistingFilePathAllowed(cwd, allowedRoots)) { + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + } } const pkg = typeof body.package === "string" ? body.package : undefined; @@ -24,8 +25,10 @@ export async function POST(req: Request) { if ((pkg && !scope) || (!pkg && scope)) { return Response.json({ error: "package and scope must be provided together", code: "package_scope_together" }, { status: 400 }); } + // Without a cwd: the user level only; a project install needs its project. + if (!cwd && scope === "project") return Response.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); - const { skills } = await loadSkillsWithInstallInfo(cwd); + const { skills } = await (cwd ? loadSkillsWithInstallInfo(cwd) : loadUserSkillsWithInstallInfo()); const installs = skills .map((skill) => skill.install) .filter((install): install is NonNullable => Boolean(install)) diff --git a/app/api/skills/route.ts b/app/api/skills/route.ts index 9d48f6e4b..27358cf4d 100644 --- a/app/api/skills/route.ts +++ b/app/api/skills/route.ts @@ -3,6 +3,7 @@ import { basename } from "path"; import { getSkillToggleRoots, loadSkillsWithInstallInfo, + loadUserSkillsWithInstallInfo, parseSkillFrontmatter, readDisableModelInvocation, setDisableModelInvocation, @@ -12,11 +13,18 @@ import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-acces // 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 -// carries `togglable`, the same check PATCH applies. +// carries `togglable`, the same check PATCH applies. Without a cwd: the user +// level only. export async function GET(req: Request) { const { searchParams } = new URL(req.url); const cwd = searchParams.get("cwd"); - if (!cwd) return Response.json({ error: "cwd required", code: "cwd_required" }, { status: 400 }); + if (!cwd) { + try { + return Response.json(await loadUserSkillsWithInstallInfo()); + } catch (e) { + return Response.json({ error: String(e) }, { status: 500 }); + } + } try { const allowedRoots = await getAllowedFileRoots(); diff --git a/app/api/skills/update/route.ts b/app/api/skills/update/route.ts index cb0ffa0fe..0bb5be8e6 100644 --- a/app/api/skills/update/route.ts +++ b/app/api/skills/update/route.ts @@ -2,7 +2,7 @@ import { runNpx } from "@/lib/npx"; import { createChildProcessEnvironment } from "@/lib/project-command-env"; import type { SkillInstallScope } from "@/lib/api-types"; import { buildSkillUpdateArgs } from "@/lib/skill-updates"; -import { loadSkillsWithInstallInfo } from "@/lib/skills-service"; +import { loadSkillsWithInstallInfo, loadUserSkillsWithInstallInfo } from "@/lib/skills-service"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; export async function POST(req: Request) { @@ -17,15 +17,18 @@ export async function POST(req: Request) { const scope = body.scope === "global" || body.scope === "project" ? body.scope as SkillInstallScope : undefined; - if (!cwd || !pkg || !scope) { + // Without a cwd: the user level only; a project install needs its project. + if (!pkg || !scope || (!cwd && scope === "project")) { return Response.json({ error: "cwd, package, and scope are required", code: "cwd_package_scope_required" }, { status: 400 }); } - const allowedRoots = await getAllowedFileRoots(); - if (!isExistingFilePathAllowed(cwd, allowedRoots)) { - return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + if (cwd) { + const allowedRoots = await getAllowedFileRoots(); + if (!isExistingFilePathAllowed(cwd, allowedRoots)) { + return Response.json({ error: "Access denied", code: "access_denied" }, { status: 403 }); + } } - const { skills } = await loadSkillsWithInstallInfo(cwd); + const { skills } = await (cwd ? loadSkillsWithInstallInfo(cwd) : loadUserSkillsWithInstallInfo()); const skill = skills.find( (item) => item.install?.package === pkg && item.install.scope === scope, ); @@ -42,7 +45,7 @@ export async function POST(req: Request) { env: createChildProcessEnvironment({ FORCE_COLOR: "0" }), }); - const refreshed = await loadSkillsWithInstallInfo(cwd); + const refreshed = await (cwd ? loadSkillsWithInstallInfo(cwd) : loadUserSkillsWithInstallInfo()); const updatedSkill = refreshed.skills.find( (item) => item.install?.package === pkg && item.install.scope === scope, ); diff --git a/bin/omp-web-host.test.mjs b/bin/omp-web-host.test.mjs index 3e3aa4864..a42c2301a 100644 --- a/bin/omp-web-host.test.mjs +++ b/bin/omp-web-host.test.mjs @@ -145,7 +145,7 @@ test("status/drain/resume consume the real CLI daemon endpoint and SIGTERM remov const frame = JSON.parse(line); if (frame.type === "hello") { hellos += 1; - ws.send(JSON.stringify({ type: "welcome", v: 9, hostId: "cli-fixture" })); + ws.send(JSON.stringify({ type: "welcome", v: 10, hostId: "cli-fixture" })); } else if (typeof frame.seq === "number") ws.send(JSON.stringify({ type: "ack", ack: frame.seq })); } }, @@ -164,7 +164,7 @@ test("status/drain/resume consume the real CLI daemon endpoint and SIGTERM remov status = JSON.parse((await hostCommand(f.env, "status")).stdout); } assert.equal(status.pid, daemon.child.pid, "the launcher must not leave a wrapper PID"); - assert.equal(status.protocol, 9); + assert.equal(status.protocol, 10); assert.equal(status.drained, false); assert.equal(hellos, 1); assert.equal(JSON.stringify(status).includes("private-cli-fixture-token"), false); diff --git a/components/AgentsConfig.tsx b/components/AgentsConfig.tsx index 29b60bc00..6a5951799 100644 --- a/components/AgentsConfig.tsx +++ b/components/AgentsConfig.tsx @@ -46,7 +46,8 @@ function fileStem(filePath: string): string { return fileName.toLowerCase().endsWith(".md") ? fileName.slice(0, -3) : fileName; } -export function AgentsConfig({ cwd }: { cwd: string | null }) { +/** `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); @@ -353,7 +354,7 @@ export function AgentsConfig({ cwd }: { cwd: string | null }) { {t("agentsConfig.scope")} ) : null} diff --git a/components/AppShell.tsx b/components/AppShell.tsx index 3768c12fb..d85afcddc 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -40,6 +40,7 @@ import { buildAtMentionText, buildFileAtMentionsText, buildFileLineMentionText } import { getInitialNavigation } from "@/lib/initial-navigation"; import { comparableProjectPath } from "@/lib/comparable-path"; import { foldedHostProjectKey, hostProjectKey, LOCAL_HOST_ID, remoteHostId, projectIdentity, projectTargetId } from "@/lib/project-ordering"; +import { isClusterTarget } from "@/lib/hosts/cluster"; import { useHostRows } from "@/hooks/useHostRows"; import { LocalDaemonBanner } from "./LocalDaemonBanner"; import { hostName } from "./host-status"; @@ -1785,6 +1786,9 @@ export function AppShell({ appName }: { appName: string }) { const creationTargets = [...(hosts ?? []).filter((host) => !memberIds.has(host.id) && (poolsLoaded || host.id === LOCAL_HOST_ID)).map((host) => ({ id: host.id, label: hostName(t, host) })), ...pools.map((pool) => ({ id: `pool:${pool.id}`, label: pool.label }))]; const chatHost = remoteHost ? hosts?.find((host) => host.id === currentHostId) : undefined; const settingsHostId = activeCwd ? activeHostId : currentHostId; + // What Settings act for, as settingsHostId picks it: the sidebar's project, else the open session, the new chat, the pool project. + const settingsTarget = activeCwd ? { hostId: activeHostId } : selectedSession ?? (newSessionCwd !== null ? { hostId: newSessionHostId } : effectivePoolProject); + const clusterSettings = isClusterTarget(settingsTarget, settingsHostId, pools); const showChat = selectedSession !== null || effectiveNewSessionCwd !== null || effectivePoolProject !== null; const currentRate = generationSpeed?.current; const rate = currentRate ?? generationSpeed?.average; @@ -2125,6 +2129,7 @@ export function AppShell({ appName }: { appName: string }) { onOpenUrlAutomaticallyChange={handleOpenUrlAutomaticallyChange} cwd={activeCwd ?? selectedSession?.cwd ?? newSessionCwd} remoteHost={settingsHostId !== undefined} + cluster={clusterSettings} sessionId={selectedSession?.id ?? null} onModelsSaved={() => setModelsRefreshKey((k) => k + 1)} onPluginsReloaded={() => setSessionKey((k) => k + 1)} diff --git a/components/HostsConfig.cluster.test.mjs b/components/HostsConfig.cluster.test.mjs index 8cca7d32a..7b0db7be8 100644 --- a/components/HostsConfig.cluster.test.mjs +++ b/components/HostsConfig.cluster.test.mjs @@ -27,7 +27,7 @@ const member = (hostId) => ({ hostId, projectsRoot: `/srv/${hostId}/ompweb-clust 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: 9, serverVersion: 9, lastSeenAt: null, workspaceOps: ["gitOrigins"], ...overrides, + hostVersion: 10, serverVersion: 10, lastSeenAt: null, workspaceOps: ["gitOrigins"], ...overrides, }); const linked = (id, label, overrides = {}) => hostRow({ id, label, allowAgentStart: false, shareCredentials: false, ...overrides }); @@ -172,6 +172,7 @@ test("joining asks for the folder, prefilled from the host's home, and sends it" 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.equal(calls.some((call) => call.method === "PUT"), false); await user.click(within(dialog).getByRole("button", { name: "Add to cluster" })); @@ -190,18 +191,20 @@ for (const [label, pools, says] of [["no cluster", [], true], ["a first pool wit }); } -test("a refused join shows the server's message and keeps the dialog open", async (t) => { - const { user } = await showHosts(t, { - hosts: [hostRow(), linked("h1", "Laptop")], pools: cluster("local"), - respond: async () => Response.json({ error: "The cluster changed during the join; try again", code: "cluster_changed" }, { status: 409 }), +for (const [code, message] of [["cluster_changed", "The cluster changed during the join; try again"], ["host_in_other_cluster", "Laptop runs another server's cluster configuration; it must leave that cluster first"]]) { + test(`a refused join (${code}) shows the server's message and keeps the dialog open`, async (t) => { + const { user } = await showHosts(t, { + hosts: [hostRow(), linked("h1", "Laptop")], pools: cluster("local"), + respond: async () => Response.json({ error: message, code }, { status: 409 }), + }); + await user.click(clusterSwitch("Laptop")); + const dialog = await screen.findByRole("dialog", { name: "Add Laptop to the cluster?" }); + await waitFor(() => assert.notEqual(within(dialog).getByLabelText(/Folder on Laptop/).value, "")); + await user.click(within(dialog).getByRole("button", { name: "Add to cluster" })); + assert.equal((await within(dialog).findByRole("alert")).textContent, message); + assert.ok(screen.getByRole("dialog", { name: "Add Laptop to the cluster?" })); }); - await user.click(clusterSwitch("Laptop")); - const dialog = await screen.findByRole("dialog", { name: "Add Laptop to the cluster?" }); - await waitFor(() => assert.notEqual(within(dialog).getByLabelText(/Folder on Laptop/).value, "")); - await user.click(within(dialog).getByRole("button", { name: "Add to cluster" })); - assert.equal((await within(dialog).findByRole("alert")).textContent, "The cluster changed during the join; try again"); - assert.ok(screen.getByRole("dialog", { name: "Add Laptop to the cluster?" })); -}); +} /** A join or leave whose answer is lost: the server saved it or not, and the reload after it answers or fails. */ const LOST = [["saved", true, true], ["not saved", false, true], ["of unknown outcome, the reload failing", true, false]]; @@ -263,7 +266,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\./)); + 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.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)); @@ -274,6 +277,74 @@ test("leaving is confirmed, then sends DELETE", async (t) => { await waitFor(() => assert.deepEqual(calls.find((call) => call.method === "DELETE"), { method: "DELETE", url: "/api/hosts/h1/cluster", body: undefined })); }); +test("a leave whose own configuration could not be put back says so and why", async (t) => { + const errors = []; + 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" }), + }); + 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."])); +}); + +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); + +for (const [label, overrides, lines] of [ + ["current", { clusterConfig: configState() }, ["Configuration: same as the master"]], + ["updating", { clusterConfig: configState({ plugins: "pending", 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"]], + ["current, with commands it lacks", { clusterConfig: configState({ missingCommands: ["uvx", "docker"] }) }, ["Configuration: same as the master", "Not installed on this host: uvx, docker"]], + ["below link protocol 10, never reporting", { hostVersion: 9 }, ["Update ompweb on this host first"]], + ["offline, with its last report", { status: "offline", clusterConfig: configState({ missingCommands: ["uvx"] }) }, []], + ["offline, never reported", { status: "offline" }, []], +]) { + test(`a member's row states its configuration: ${label}`, async (t) => { + await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop", overrides)], pools: cluster("local", "h1") }); + assert.deepEqual(configLines("Laptop"), lines); + }); +} + +const MASTER_ERROR = { code: "file_too_large", message: "rules/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) => { + const hosts = [hostRow(), linked("h1", "Laptop"), linked("h2", "Desk")]; + const { frame } = await showHosts(t, { hosts, pools: cluster("local", "h1", "h2") }); + assert.deepEqual(masterErrors(), []); + frame({ hosts, masterConfigError: MASTER_ERROR }); + assert.deepEqual(masterErrors(), [`Members cannot get this machine's configuration: ${MASTER_ERROR.message}`]); + const [line] = screen.getAllByText(/^Members cannot get/); + assert.ok(line.compareDocumentPosition(rowOf("Laptop")) & 4, "before the rows"); + frame({ hosts }); + assert.deepEqual(masterErrors(), []); +}); + +test("without linked members the master configuration error is not shown", async (t) => { + const hosts = [hostRow(), linked("h1", "Laptop")]; + const { frame } = await showHosts(t, { hosts, pools: cluster("local") }); + frame({ hosts, masterConfigError: MASTER_ERROR }); + assert.deepEqual(masterErrors(), []); +}); + +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 { 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 }); + assert.deepEqual([configLines("Laptop"), configLines("Desk")], [[], []]); +}); + +test("a standalone host shows no configuration line, even with a report", async (t) => { + await showHosts(t, { hosts: [hostRow(), linked("h1", "Laptop", { clusterConfig: configState({ owned: false, missingCommands: ["uvx"] }) })], pools: cluster("local") }); + assert.deepEqual(configLines("Laptop"), []); + assert.deepEqual(configLines("This machine"), []); +}); + for (const [label, saved, reloads] of LOST) { test(`a leave whose answer is lost, ${label}, shows what the reload finds before Remove is enabled again`, async (t) => { const errors = []; @@ -302,7 +373,6 @@ 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" }); for (const name of ["Laptop", "Desk"]) { diff --git a/components/HostsConfig.tsx b/components/HostsConfig.tsx index 6d64a149a..cf887a34b 100644 --- a/components/HostsConfig.tsx +++ b/components/HostsConfig.tsx @@ -7,7 +7,7 @@ import { Dialog, DialogContent, DialogTitle } from "@/components/ui/primitives"; import { ToggleSwitch } from "@/components/ui/ToggleSwitch"; import { toast } from "@/components/ui/toast"; import { copyText } from "@/lib/clipboard"; -import { CLUSTER_PROJECTS_DIR, clusterJoinBlock, isClusterMember } from "@/lib/hosts/cluster"; +import { CLUSTER_PROJECTS_DIR, clusterJoinBlock, clusterOf, isClusterMember } from "@/lib/hosts/cluster"; import type { HostRow } from "@/lib/hosts/hub"; import type { HostPool } from "@/lib/hosts/pools"; import { useI18n } from "@/lib/i18n"; @@ -167,6 +167,7 @@ function JoinDialog({ host, localJoins, reload, onClose }: { host: HostRow; loca

{t("hostsConfig.joinProjectsNote", { name })}

{localJoins &&

{t("hostsConfig.joinLocalNote")}

}

{t("hostsConfig.joinCredentialsNote", { name })}

+

{t("hostsConfig.joinConfigNote")}

{error && }
@@ -179,7 +180,7 @@ 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 }; +type ClusterState = { pools: HostPool[]; poolsLoaded: boolean; poolsFailed: boolean; localReason: string | null; masterFailed: boolean }; const joinBlock = (row: HostRow) => clusterJoinBlock({ status: row.status, protocol: row.hostVersion, ompVersion: row.ompVersion, supports: (operation) => row.workspaceOps.includes(operation) }); @@ -204,6 +205,19 @@ function HostCard({ host, cluster, onRename, onRevoke, onShare, onJoin, onLeave host.hostVersion !== null && host.status !== "needs-upgrade" && t("hostsConfig.protocol", { version: host.hostVersion }), linked && (host.lastSeenAt ? t("hostsConfig.lastSeen", { time: new Date(host.lastSeenAt).toLocaleString() }) : t("hostsConfig.neverSeen")), ].filter(Boolean).join(" · "); + // A member's configuration (spec K4): no line while it is offline; a daemon below link protocol 10 never applies it, + // 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 config = member && !outdated ? linked?.clusterConfig : undefined; + const updating = cluster.masterFailed ? null : t("hostsConfig.configUpdating"); + const configLine = !member || !linked || host.status === "offline" ? null + : outdated ? t("hostsConfig.joinUpgrade") + : !config ? updating + : config.version !== null && !config.owned ? t("hostsConfig.configHeldElsewhere") + : config.error ? t("hostsConfig.configFailed", { reason: config.error }) + : config.current ? t("hostsConfig.configCurrent") : updating; return (
  • @@ -214,6 +228,8 @@ function HostCard({ host, cluster, onRename, onRevoke, onShare, onJoin, onLeave {hostStatusText(t, host)}
  • {details &&
    {details}
    } + {configLine &&
    {configLine}
    } + {configLine && config?.missingCommands.length ?
    {t("hostsConfig.configMissing", { commands: config.missingCommands.join(", ") })}
    : null} {isLocalRow(host) && host.daemonManaged && host.status === "offline" && (
    {t("hostsConfig.localOfflineHint")} @@ -277,7 +293,7 @@ function HostCard({ host, cluster, onRename, onRevoke, onShare, onJoin, onLeave export function HostsConfig() { const { t } = useI18n(); - const { hosts, pools, poolsLoaded, poolsFailed, failed: loadFailed, reload } = useHostRows(); + 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); @@ -289,6 +305,7 @@ export function HostsConfig() { 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 linkedMembers = clusterOf(pools)?.members.some((member) => member.hostId !== LOCAL_HOST_ID) ?? false; const share = async () => { if (!sharing) return; @@ -307,7 +324,9 @@ export function HostsConfig() { if (!leaving) return; setBusy(true); try { - await call("DELETE", `/api/hosts/${encodeURIComponent(leaving.id)}/cluster`); + const { restoreError } = await call("DELETE", `/api/hosts/${encodeURIComponent(leaving.id)}/cluster`); + // It left; only putting its own configuration back failed (spec K6), which the server retries while the host is linked. + if (typeof restoreError === "string") toast.error(t("hostsConfig.leaveRestoreFailed", { name: leaving.label, reason: restoreError })); setLeaving(null); } catch (error) { // As for a join: the leave may have been saved before its answer was lost. @@ -346,12 +365,14 @@ export function HostsConfig() {
    {loadFailed &&
    {t("hostsConfig.loadFailed")}
    } + {/* Once for every member: none of them can get this machine's configuration (spec K1). */} + {masterConfigError && linkedMembers &&
    {t("hostsConfig.masterConfigFailed", { reason: masterConfigError.message })}
    } {hosts === null ? ( !loadFailed &&
    {t("hostsConfig.loading")}
    ) : (
      {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)} onShare={() => setSharing(host)} onJoin={() => setJoining(host)} onLeave={() => setLeaving(host)} /> ))} {hosts.length === 1 &&
    • {t("hostsConfig.empty")}
    • }
    diff --git a/components/McpConfig.tsx b/components/McpConfig.tsx index 5de2cc16c..325fa263d 100644 --- a/components/McpConfig.tsx +++ b/components/McpConfig.tsx @@ -35,7 +35,9 @@ function serverSummary(config: Record): { type: string; target: }; } -export function McpConfig({ cwd, sessionId }: { cwd: string | null; sessionId?: string | null }) { +/** `liveOnly`: the session runs on another cluster member. Its live status is read from its running process (never one + * started here); servers are changed in the master's configuration, so the switches stay off (spec K7). */ +export function McpConfig({ cwd, sessionId, liveOnly = false }: { cwd: string | null; sessionId?: string | null; liveOnly?: boolean }) { const { t } = useI18n(); const [servers, setServers] = useState([]); const [userConfig, setUserConfig] = useState(null); @@ -62,13 +64,17 @@ export function McpConfig({ cwd, sessionId }: { cwd: string | null; sessionId?: if (cwd) params.set("cwd", cwd); if (sessionId) { params.set("sessionId", sessionId); - // Fresh-spawn opinion for the MCP route (same localStorage key the - // chat-switch effect reads): without it a spawn here plants a - // non-advisor child that a concurrent prompt then reuses. - try { - if (localStorage.getItem(`omp-advisor-enabled:${sessionId}`) === "true") params.set("advisor", "1"); - } catch { - // Private mode: omit the opinion, spawn defaults apply. + if (liveOnly) { + params.set("attach", "1"); + } else { + // Fresh-spawn opinion for the MCP route (same localStorage key the + // chat-switch effect reads): without it a spawn here plants a + // non-advisor child that a concurrent prompt then reuses. + try { + if (localStorage.getItem(`omp-advisor-enabled:${sessionId}`) === "true") params.set("advisor", "1"); + } catch { + // Private mode: omit the opinion, spawn defaults apply. + } } } @@ -109,13 +115,13 @@ export function McpConfig({ cwd, sessionId }: { cwd: string | null; sessionId?: } finally { if (generation === loadGeneration.current) setLoading(false); } - }, [cwd, sessionId]); + }, [cwd, sessionId, liveOnly]); const invalidateLoad = useCallback(() => { loadGeneration.current++; }, []); useEffect(() => { void load(); return invalidateLoad; }, [load, invalidateLoad]); const change = async (action: "enable" | "disable" | "reload", name?: string) => { - if (!sessionId || changing) return; + if (!sessionId || liveOnly || changing) return; setChanging(name ?? "reload"); setMessage(null); try { @@ -235,7 +241,7 @@ export function McpConfig({ cwd, sessionId }: { cwd: string | null; sessionId?: {manageable ?
    {changing === server.name &&
    : {t(shadowed ? "mcpConfig.shadowed" : "mcpConfig.readOnly")}} ; })} @@ -248,13 +254,13 @@ export function McpConfig({ cwd, sessionId }: { cwd: string | null; sessionId?:

    {t("mcpConfig.configuredServers")}

    {managedCount}
    -
    -

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

    +

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

    {liveError && } {userConfig?.error && } diff --git a/components/PluginsConfig.tsx b/components/PluginsConfig.tsx index 4d40f701a..7585a86be 100644 --- a/components/PluginsConfig.tsx +++ b/components/PluginsConfig.tsx @@ -59,8 +59,8 @@ function versionSummary(pkg: PluginPackageInfo, t: (key: string, vars?: Record
    - + {cwd && }
    -
    {t("pluginsConfig.cwd")}
    -
    - {shortenPath(cwd)} -
    + {cwd && <> +
    {t("pluginsConfig.cwd")}
    +
    + {shortenPath(cwd)} +
    + }
    @@ -618,7 +621,8 @@ export function PluginsConfig({ onSelectTab, embedded = false, }: { - cwd: string; + /** null: the user level only, as a request without a cwd lists and changes it. */ + cwd: string | null; sessionId: string | null; onClose: () => void; onReloaded?: () => void; @@ -651,7 +655,7 @@ export function PluginsConfig({ setLoading(true); setError(null); try { - const res = await fetch(`/api/plugins?cwd=${encodeURIComponent(cwd)}`); + const res = await fetch(cwd ? `/api/plugins?cwd=${encodeURIComponent(cwd)}` : "/api/plugins"); const next = (await res.json()) as PluginsResponse & { error?: string; code?: string }; if (!res.ok || next.error) throw new Error(formatApiError(next.error ? next : `HTTP ${res.status}`)); setData(next); @@ -782,7 +786,7 @@ export function PluginsConfig({ whiteSpace: "nowrap", }} > - {shortenPath(cwd)} + {cwd && shortenPath(cwd)}
    } + {cwd && (!remoteHost || cluster) && } - {cwd && !remoteHost && ( + {cwd && (!remoteHost || cluster) && (
    )} - {remoteHost ? remoteUnavailable : } + {panelsUnavailable ? remoteUnavailable : } {!cwd &&

    {t("settingsConfig.selectWorkspaceForMcp")}

    } )} @@ -1763,14 +1779,14 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal {/* SKILLS SUB-PANEL CONTRACT MATCH */} {cwd && currentTab === "skills" && (
    - {remoteHost ? remoteUnavailable : } + {panelsUnavailable ? remoteUnavailable : }
    )} {/* PLUGINS SUB-PANEL CONTRACT MATCH */} {cwd && currentTab === "plugins" && (
    - {remoteHost ? remoteUnavailable : } + {panelsUnavailable ? remoteUnavailable : }
    )} @@ -1800,7 +1816,7 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal {t("settingsConfig.agentsDesc")}

    - {remoteHost ? remoteUnavailable : } + {panelsUnavailable ? remoteUnavailable : } )} @@ -1841,7 +1857,7 @@ export function SettingsConfig({ activeTab, toolCallsDefaultCollapsed, onToolCal - + {/* ompweb app update card */}
    diff --git a/components/SkillsConfig.tsx b/components/SkillsConfig.tsx index abee8bed7..0fb74d237 100644 --- a/components/SkillsConfig.tsx +++ b/components/SkillsConfig.tsx @@ -130,7 +130,7 @@ function SkillDetail({ onUpdate, }: { skill: Skill; - cwd: string; + cwd: string | null; onToggle: (skill: Skill) => void; toggling: boolean; saveError: string | null; @@ -146,7 +146,7 @@ function SkillDetail({ const enabled = !skill.disableModelInvocation; function displayPath(p: string): string { - if (label === "project" && p.startsWith(cwd)) { + if (label === "project" && cwd && p.startsWith(cwd)) { const rel = p.slice(cwd.length).replace(/^[/\\]/, ""); return `./${rel}`; } @@ -382,7 +382,8 @@ function AddSkillPanel({ installedPackages, onInstalled, }: { - cwd: string; + /** null: the user level only (no project scope). */ + cwd: string | null; installedPackages: Record>; onInstalled: () => void; }) { @@ -461,9 +462,9 @@ function AddSkillPanel({ ); const installPath = - scope === "global" - ? "~/.agents/skills/" - : `${shortenPath(cwd)}/.agents/skills/`; + scope === "project" && cwd + ? `${shortenPath(cwd)}/.agents/skills/` + : "~/.agents/skills/"; return (
    @@ -533,7 +534,7 @@ function AddSkillPanel({ flexShrink: 0, }} > - {(["global", "project"] as const).map((s) => ( + {(cwd ? ["global", "project"] as const : ["global"] as const).map((s) => (