diff --git a/AGENTS.md b/AGENTS.md index e6130cf52..8a453d20f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -105,7 +105,8 @@ app/api/ transport-metrics/route.ts GET { now } (the SSE clock probe) | POST { samples } → /omp-web/transport-metrics.jsonl hosts/route.ts GET hosts (this machine first) | POST { label } → token once + login command | PATCH { id, label?, allowAgentStart?, shareCredentials? } (`local`: label only, empty resets to "This machine"; `shareCredentials` on `local` is 400) | DELETE ?id= revoke (registry first, then close the link); 503 if hosts.json is unreadable hosts/link/route.ts GET WebSocket upgrade (the `ompweb host` daemon; bearer checked before the upgrade, skipped by the `proxy.ts` gate) | POST 426 for pre-WebSocket daemons - hosts/broker/[...path]/route.ts allow-listed forwarding of an omp auth broker's endpoints for a host with `shareCredentials`; authenticated by the host token, outside the password gate (`proxy.ts` `UNGATED`); see "Remote hosts → Shared credentials" + 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 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) @@ -155,6 +156,7 @@ lib/ daemon-broker.ts daemon side: the loopback forwarder that gives a sharing host's omp processes `OMP_AUTH_BROKER_URL`/`OMP_AUTH_BROKER_TOKEN` (`credentialsEnv`); forwards to the link's server with the link's host token registry.ts `/omp-web/hosts.json`: create/update/revoke, token hashing and lookup; the `local` record (`rotateLocalHostToken`, `customLocalLabel`) session-index.ts sessions and projects across hosts, cached per host; `hostForSessionId`, `sessionSpawnTarget`, `invalidateLocalSessionLists` + cluster.ts pure cluster rules: `clusterOf` (= `pools[0]`), `isClusterMember`, `sharesCredentials`, `joinCluster`/`leaveCluster`, `clusterJoinBlock`, `ompSharesCredentials` (also the daemon's spawn check); browser-importable (Settings uses it) 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 @@ -569,6 +571,37 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri - **Scope.** The host can read current access tokens and stored API keys; refresh tokens stay on the server. Not shared: `models.yml` custom providers, environment-variable API keys, omp settings. +- **Cluster** (`docs/specs/2026-11-11-cluster-membership-design.md`). The + cluster is `pools[0]`; `local` is its master, added on creation or on the next + join if an existing first pool lacks it. The rest of `pools.json` is ignored + by the interface. + - **Membership computes credential sharing; it is never stored.** A member + other than `local` shares regardless of its `shareCredentials` flag + (`sharesCredentials(record, pools)`), so leaving restores the host's own + setting. An unreadable `pools.json` refuses a start (503 + `pool_storage_unavailable`) rather than starting with other logins. + - **Every writer of `pools.json` that can end a host's sharing aborts that + host's broker requests** (`abortBrokerRequests`): `PUT /api/hosts` and the + cluster `DELETE`. A flag change or revoke writes `hosts.json` and likewise + aborts requests when sharing ends. + - **Membership, not the confirmation or `enabled`, grants sharing.** A host + added to `pools[0]` through `PUT /api/hosts` (or a `pools.json` edit) shares + without the join dialog, and so do members of a disabled first pool. + - **Placement skips members that cannot share.** `startPooledSession` leaves + out a member that `sharesCredentials` forces to share unless its link is + shared (`hostOwnsLifecycle`) at `SHARED_CREDENTIALS_SINCE_VERSION`, before + preparation; `spawnRpc`'s 426 stays the last guard. Other pools' members + keep their own eligibility. + - **Join keeps what the host showed.** A created cluster project takes the + host project's name, else its folder name (split on `/` and `\`), and its + alias; binding a visible checkout un-hides a hidden cluster project. + `POST /api/projects` pool registration matches by `repositoryKey` (or the + identical text) and keeps the stored origin. + - **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. + - **Only grouping passes `pools` to `projectTargetId`.** Selection, expand + keys, reorder, pin and drag use the project's own target. - **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 diff --git a/CHANGELOG.md b/CHANGELOG.md index c6ea47c84..89dc4917e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ 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`. +- **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. - **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 82b7fe7c3..223ee47e1 100644 --- a/README.md +++ b/README.md @@ -218,17 +218,79 @@ the daemon's link when it starts, so start the web server first. ### Transparent host pools -A configured host pool appears as one target with one entry per registered repository. -Choose the pool rather than a worker; new independent sessions are placed on an eligible -worker and receive an isolated local worktree. Adding a pool project registers its Git -origin, not a central clone. The selected worker prepares its checkout when the session -starts and reports authentication, preparation, or repository conflicts explicitly. -Standalone hosts, including the Mac, retain typed paths and local clone progress/cancellation. -Existing non-pooled workspaces on member hosts remain accessible in the sidebar; those -hosts are not offered as ordinary pool-creation targets. Resolving the owner for a new -chat's attachment does not replace its live composer or discard its draft and uploads. -Placement and preparation failures are also shown when command discovery or system-prompt -inspection starts a session lazily; retrying remains an explicit user action. +ompweb has at most one cluster: the first pool in `pools.json`. This machine is its master. +Creating the cluster adds this machine; an existing first pool that lacks it gains it on the +next join. The cluster appears in the sidebar as one group with one entry per Git repository. +Choose the cluster rather than a member; new independent sessions are placed on an eligible +member and receive an isolated local worktree. Adding a cluster project registers +its Git origin, not a central clone; adding another URL form of a repository the cluster +already has returns that project, unhidden, and keeps its stored origin. The selected member +prepares its checkout when the session starts and reports authentication, preparation, or +repository conflicts explicitly. +Standalone hosts, including the Mac, keep their own groups with typed paths and local clone +progress/cancellation. Resolving the owner for a new chat's attachment does not replace its +live composer or discard its draft and uploads. Placement and preparation failures are also +shown when command discovery or system-prompt inspection starts a session lazily; retrying +remains an explicit user action. + +**Joining and leaving.** Each linked host has an **In the cluster** switch in **Settings → +Hosts**. Turning it on asks for a folder on that host for the checkouts the cluster creates +(default `/ompweb-cluster`) and shows what changes. It needs the host online, its daemon +on link protocol 9 with the `gitOrigins` operation, and omp 15.13.1 or newer (a member always +uses this machine's provider logins); otherwise the disabled switch asks for an update of +ompweb or omp, or shows the host's unavailable status. While this machine is not a member yet, +its own daemon needs the same, and the switch asks to restart the host service on this machine +(or to update its omp). + +- **Joining:** the host's Git projects are matched by repository: the same repository on + several members is one cluster project, and its sessions are listed together. `git@github.com:a/b.git` + and `https://github.com/a/b` are the same repository. Projects without a single Git `origin`, + subfolders and linked worktrees stay on their node; the cluster shows them with the node's + name, and a new session there starts on that node. Nothing on the host's disk changes. A + cluster project created from a host project keeps the name and alias it showed (the folder + name when it had no name of its own). A visible checkout that matches a hidden cluster project + makes that project visible again. This machine joins with the first host added while it is + not a member (when the cluster is created, or on the next join of an older first pool without + it): its Git projects then become cluster projects too, and new sessions in them start on any + member with capacity, not in its own checkout. + A second checkout of a repository already bound on that host also stays on its node. + Projects inside, or containing, the chosen checkout folder stay on their node too; pick an + empty folder that is not a parent of existing projects. +- **Leaving:** the host takes no new cluster sessions. Its matched projects are listed under + the host again. Checkouts the cluster created inside the host's folder stay bound, so + sessions the cluster started there stay under the cluster's projects. The cluster keeps the + projects it gained from the host, so they may now be listed twice; hide any you do not want. + This machine cannot leave, and the cluster stays when the last linked host does. Revoking a + member removes it from the cluster the same way; while `pools.json` cannot be read, the revoke + is refused. +- **Provider logins:** a member always uses this machine's provider logins, whatever its own + [**Use this server's provider logins**](#use-the-servers-provider-logins-on-a-host) setting + says; Settings shows it on and disabled. This is computed from membership, so leaving brings + the host's own setting back. A member can read this machine's access tokens and stored API + keys. Cluster placement skips a member that cannot take these logins (daemon below link + protocol 9, or a link that does not share) before preparing a checkout there. 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. +- **Limits:** a host that is too slow to report its Git remotes within the time limit keeps + the remaining projects on its node; leaving and joining again retries them. Only Linux hosts + report capacity, so a macOS or Windows master never runs cluster sessions itself: its Git + projects start only on other members, and a start fails with "No pool worker currently has + eligible capacity" when none has capacity. A pool disabled through the API takes no new + sessions, including this machine's Git projects moved into it, which then cannot start + anywhere; its members still use this machine's provider logins. Settings cannot enable it + again. + +**Upgrade note.** After this update, every linked host already in the first pool uses this +machine's provider logins (it can read their access tokens and stored API keys), without a +confirmation having been shown. This includes a first pool disabled through the API, and a +host added to the first pool later through `PUT /api/hosts` or by editing `pools.json`: +membership, not scheduling, grants the logins. Each linked member needs an updated ompweb host +daemon (link protocol 9) 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. 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 diff --git a/app/api/hosts/[id]/cluster/route.ts b/app/api/hosts/[id]/cluster/route.ts new file mode 100644 index 000000000..08141d69e --- /dev/null +++ b/app/api/hosts/[id]/cluster/route.ts @@ -0,0 +1,160 @@ +import { randomUUID } from "node:crypto"; +import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; +import { comparableProjectPath } from "@/lib/comparable-path"; +import { CLUSTER_ID, CLUSTER_LABEL, CLUSTER_PROJECTS_DIR, ClusterError, clusterJoinBlock, isClusterMember, joinCluster, leaveCluster, MIN_SHARED_CREDENTIALS_OMP, type HostProjectFacts } from "@/lib/hosts/cluster"; +import type { Host } from "@/lib/hosts/host"; +import { getHost, getHostLinkProtocol, getHostOmpVersion, notifyHostsChange } from "@/lib/hosts/hub"; +import { HostOpError } from "@/lib/hosts/link-protocol"; +import { loadPools, poolProjectBindings, savePools, validatePools, type HostPool, type PoolMember, type PoolProject } from "@/lib/hosts/pools"; +import { LOCAL_HOST_ID, loadHosts } from "@/lib/hosts/registry"; +import type { OpResult } from "@/lib/hosts/session-ops"; +import { hostSessions } from "@/lib/hosts/session-index"; +import { abortBrokerRequests } from "@/lib/omp/auth-broker"; +import { mergeProjects } from "@/lib/project-registry"; +import { isApiRequestOriginAllowed, shouldCheckApiRequestOrigin } from "@/lib/request-security"; +import { isRecord } from "@/lib/type-guards"; +import type { GitOrigin } from "@/lib/workspace-types"; + +type Context = { params: Promise<{ id: string }> }; +/** gitOrigins' input bounds: it refuses the whole call beyond them. */ +const MAX_ORIGIN_PATHS = 500; +const MAX_ORIGIN_PATH_LENGTH = 4096; +const noStore = { "cache-control": "no-store" }; +const fail = (error: string, code: string, status: number) => Response.json({ error, code }, { status, headers: noStore }); +const storageFailure = () => fail("The pool registry (omp-web/pools.json) cannot be read or written; fix it before changing the cluster", "pool_storage_unavailable", 503); +function errorResponse(error: unknown): Response { + if (error instanceof HostOpError) return fail(error.message, error.code, error.status); + if (error instanceof ClusterError) return fail(error.message, error.code, 409); + if (error instanceof RequestBodyTooLargeError) return fail(error.message, "body_too_large", 413); + if (error instanceof SyntaxError) return fail("Request body must be valid JSON", "invalid_json", 400); + // A failed pools.json write: filesystem errors name their syscall. + if (isRecord(error) && typeof error.syscall === "string") return storageFailure(); + return fail("The cluster change failed", "cluster_change_failed", 500); +} + +/** The pool rules, applied to one member or one project. */ +function passes(members: PoolMember[], projects: PoolProject[]): boolean { + try { + validatePools([{ id: CLUSTER_ID, label: CLUSTER_LABEL, enabled: true, members, projects }]); + return true; + } catch { + return false; + } +} + +function valueOf(result: OpResult): T { + if (!result.ok) throw new HostOpError(result.status, result.code, result.error); + return result.value; +} + +function requireReady(host: Host): void { + const block = clusterJoinBlock({ status: host.status(), protocol: getHostLinkProtocol(host.id), ompVersion: getHostOmpVersion(host.id), supports: (operation) => host.supportsWorkspaceOp(operation) }); + if (block === null) return; + if (block === "omp-old") throw new HostOpError(409, "host_omp_too_old", `Update omp on ${host.label} to ${MIN_SHARED_CREDENTIALS_OMP} or newer first`); + if (block !== "upgrade") throw new HostOpError(409, "host_offline", `${host.label} is offline`); + throw host.id === LOCAL_HOST_ID + ? new HostOpError(409, "host_restart_required", "Restart this machine's ompweb host daemon to join the cluster") + : new HostOpError(409, "host_upgrade_required", `Update ompweb on ${host.label} to join the cluster`); +} + +/** The host's projects in its own order (mergeProjects: the order the user sees), then its hidden registry entries, which move too. */ +async function hostFacts(host: Host): Promise { + const registry = await host.sessionOps.listProjects(); + const discovered = (await hostSessions(host.id)).map((session) => session.projectRoot ?? session.cwd); + // As listProjectsAllHosts: only this machine's paths resolve here. + const projects: HostProjectFacts["project"][] = mergeProjects({ version: 1, projects: registry }, discovered, host.id === LOCAL_HOST_ID ? undefined : (path) => path); + const seen = new Set(projects.map((project) => comparableProjectPath(project.path))); + for (const entry of registry) { + const key = comparableProjectPath(entry.path); + if (!entry.hidden || seen.has(key)) continue; + seen.add(key); + projects.push(entry); + } + // Longer paths are not sent: they stay pinned. + const sendable = projects.map((project) => project.path).filter((path) => path.length <= MAX_ORIGIN_PATH_LENGTH); + const origins = new Map(); + for (let start = 0; start < sendable.length; start += MAX_ORIGIN_PATHS) { + const paths = sendable.slice(start, start + MAX_ORIGIN_PATHS); + const answers = valueOf(await host.workspaceOps.gitOrigins(paths)).origins; + paths.forEach((path, i) => origins.set(path, answers[i])); + } + return projects.map((project) => ({ project, origin: origins.get(project.path)?.origin ?? null, mainCheckout: origins.get(project.path)?.mainCheckout ?? false })); +} + +async function localProjectsRoot(host: Host): Promise { + const { home } = valueOf(await host.workspaceOps.home()); + return `${home}${home.includes("\\") ? "\\" : "/"}${CLUSTER_PROJECTS_DIR}`; +} + +export async function PUT(request: Request, { params }: Context) { + if (shouldCheckApiRequestOrigin(request) && !isApiRequestOriginAllowed(request)) return fail("Cross-origin API requests are not allowed", "cross_origin_forbidden", 403); + if (request.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase() !== "application/json") return fail("Content-Type must be application/json", "unsupported_media_type", 415); + try { + const { id } = await params; + // This machine is the master: any join adds it while it is not a member; it never joins by request. + const host = id === LOCAL_HOST_ID ? null : getHost(id); + if (!host) return fail("Unknown host", "unknown_host", 404); + const body = await parseJsonWithinLimit(request, 8192); + const projectsRoot = isRecord(body) && Object.keys(body).length === 1 ? body.projectsRoot : undefined; + if (typeof projectsRoot !== "string" || !passes([{ hostId: id, projectsRoot, provisioned: true, draining: false }], [])) { + return fail("projectsRoot must be an absolute folder path", "invalid_projects_root", 400); + } + let pools: HostPool[]; + try { + pools = loadPools(); + } catch { + return storageFailure(); + } + const addLocal = !isClusterMember(pools, LOCAL_HOST_ID); + const joining = addLocal ? [getHost(LOCAL_HOST_ID), host] : [host]; + joining.forEach(requireReady); + // 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[] }[] = []; + for (const target of joining) { + const root = target === host ? projectsRoot : await localProjectsRoot(target); + gathered.push({ member: { hostId: target.id, projectsRoot: root }, facts: await hostFacts(target) }); + } + try { + pools = loadPools(); + } catch { + return storageFailure(); + } + // This machine's facts were not gathered: it was a member when the join began. + if (!addLocal && !isClusterMember(pools, LOCAL_HOST_ID)) return fail("The cluster changed during the join; try again", "cluster_changed", 409); + const now = new Date().toISOString(); + const valid = (project: PoolProject) => passes([], [project]); + for (const { member, facts } of gathered) { + // Added meanwhile by another join. + if (member.hostId === LOCAL_HOST_ID && isClusterMember(pools, LOCAL_HOST_ID)) continue; + // A checkout a pool already binds for this host stays with that pool. + const bound = poolProjectBindings(pools).get(member.hostId); + pools = joinCluster(pools, member, facts.filter(({ project }) => !bound?.has(comparableProjectPath(project.path))), now, randomUUID, valid); + } + savePools(pools); + notifyHostsChange(); + return Response.json({ pools }, { headers: noStore }); + } catch (error) { + return errorResponse(error); + } +} + +export async function DELETE(request: Request, { params }: Context) { + if (shouldCheckApiRequestOrigin(request) && !isApiRequestOriginAllowed(request)) return fail("Cross-origin API requests are not allowed", "cross_origin_forbidden", 403); + try { + const { id } = await params; + let pools: HostPool[]; + try { + pools = loadPools(); + } catch { + return storageFailure(); + } + pools = leaveCluster(pools, id); + savePools(pools); + if (loadHosts().find((record) => record.id === id)?.shareCredentials !== true) abortBrokerRequests(id); + notifyHostsChange(); + return Response.json({ pools }, { 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 3717104bd..fca246111 100644 --- a/app/api/hosts/broker/[...path]/route.ts +++ b/app/api/hosts/broker/[...path]/route.ts @@ -1,4 +1,6 @@ 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 { AuthBrokerUnavailableError, brokerFetch } from "@/lib/omp/auth-broker"; @@ -35,7 +37,7 @@ function only(source: Headers, names: readonly string[]): Headers { return picked; } -/** The sharing host the bearer token names, or the refusal to answer with (a 403 is logged; a 401 has no host to name). */ +/** 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() : ""; @@ -49,7 +51,14 @@ function admit(request: Request, path: string): HostRecord | Response { } if (!host) return fail("Unknown host token", 401); // `local` is refused by id: a hand-edited hosts.json can give its record the flag. - if (host.id === LOCAL_HOST_ID || !host.shareCredentials) { + let shares: boolean; + try { + shares = host.id !== LOCAL_HOST_ID && sharesCredentials(host, loadPools()); + } catch { + log(host.id, request.method, PLAIN_PATH.test(path) ? path : "-", 503, "pools_unreadable"); + return fail("The host pool configuration cannot be read", 503); + } + if (!shares) { log(host.id, request.method, PLAIN_PATH.test(path) ? path : "-", 403); return fail("Credential sharing is off for this host", 403); } diff --git a/app/api/hosts/route.ts b/app/api/hosts/route.ts index fba3b2e20..e0736420c 100644 --- a/app/api/hosts/route.ts +++ b/app/api/hosts/route.ts @@ -1,6 +1,7 @@ +import { isClusterMember, leaveCluster, sharesCredentials } from "@/lib/hosts/cluster"; import { closeHostLink, hostsSnapshot, listHosts, notifyHostsChange } from "@/lib/hosts/hub"; import { loadPools, savePools, type HostPool } from "@/lib/hosts/pools"; -import { createHost, HostRegistryUnreadableError, readHosts, revokeHost, UnknownHostError, updateHost } from "@/lib/hosts/registry"; +import { createHost, HostRegistryUnreadableError, readHosts, revokeHost, UnknownHostError, updateHost, type HostRecord } from "@/lib/hosts/registry"; import { abortBrokerRequests } from "@/lib/omp/auth-broker"; import { isRecord } from "@/lib/type-guards"; @@ -22,6 +23,15 @@ function failFor(error: unknown) { throw error; } +/** A member keeps sharing when its own flag goes off; pools that cannot be read leave that unknown, so its requests are cut. */ +function stillShares(record: HostRecord): boolean { + try { + return sharesCredentials(record, loadPools()); + } catch { + return false; + } +} + async function readBody(req: Request): Promise | null> { try { const body: unknown = await req.json(); @@ -66,12 +76,13 @@ export function GET() { export async function PUT(req: Request) { const body = await readBody(req); if (!hasOnlyKeys(body, ["pools"]) || !Array.isArray(body.pools)) return fail("pools must be an array", 400); - const knownHosts = new Set(["local"]); + let hosts: HostRecord[]; try { - for (const host of readHosts()) knownHosts.add(host.id); + hosts = readHosts(); } catch (error) { return failFor(error); } + const knownHosts = new Set(["local", ...hosts.map((host) => host.id)]); for (const pool of body.pools) { if (!hasOnlyKeys(pool, ["id", "label", "enabled", "members", "projects"]) || !Array.isArray(pool.members) || !Array.isArray(pool.projects)) return fail("Invalid pool configuration", 400); @@ -86,19 +97,26 @@ export async function PUT(req: Request) { } } } + let before: HostPool[]; try { - loadPools(); + before = loadPools(); } catch { return poolStorageFailure(); } + const after = body.pools as HostPool[]; try { - savePools(body.pools as HostPool[]); + savePools(after); } catch (error) { // Core validation precedes persistence; filesystem errors carry an errno code. if (isRecord(error) && typeof error.code === "string") return poolStorageFailure(); return fail("Invalid pool configuration", 400); } - return Response.json({ pools: body.pools }, { headers: noStore }); + notifyHostsChange(); + // Leaving the first pool, or no longer being in it, can end a host's sharing: cut off what it already has open. + for (const host of hosts) { + if (sharesCredentials(host, before) && !sharesCredentials(host, after)) abortBrokerRequests(host.id); + } + return Response.json({ pools: after }, { headers: noStore }); } export async function POST(req: Request) { @@ -135,8 +153,8 @@ export async function PATCH(req: Request) { if (shareCredentials !== undefined && typeof shareCredentials !== "boolean") return fail("shareCredentials must be a boolean", 400); if (label === undefined && allowAgentStart === undefined && shareCredentials === undefined) return fail("Nothing to update", 400); try { - updateHost(body.id, { label, allowAgentStart, shareCredentials }); - if (shareCredentials === false) abortBrokerRequests(body.id); + const updated = updateHost(body.id, { label, allowAgentStart, shareCredentials }); + if (shareCredentials === false && !stillShares(updated)) abortBrokerRequests(body.id); notifyHostsChange(); return Response.json({ host: hostsSnapshot().hosts.find((h) => h.id === body.id) }, { headers: noStore }); } catch (error) { @@ -148,6 +166,19 @@ export async function DELETE(req: Request) { const id = new URL(req.url).searchParams.get("id"); if (!id) return fail("id is required", 400); if (id === "local") return fail("This machine cannot be revoked", 400); + // An unreadable registry fails before the pools change: no member is removed while its record and link remain. + try { + readHosts(); + } catch (error) { + return failFor(error); + } + // A member leaves the cluster first: once its record is gone, no row is left to remove it there. + try { + const pools = loadPools(); + if (isClusterMember(pools, id)) savePools(leaveCluster(pools, id)); + } catch { + return poolStorageFailure(); + } try { // Registry first: with the record gone a daemon that redials gets 401 instead of reconnecting. if (!revokeHost(id)) return fail("Unknown host", 404); diff --git a/app/api/projects/route.ts b/app/api/projects/route.ts index 87b52230d..9fffbd7e7 100644 --- a/app/api/projects/route.ts +++ b/app/api/projects/route.ts @@ -7,7 +7,7 @@ import { isValidPoolOrigin, loadPools, pathApi, poolManagedProject, savePools } import { listProjectsAllHosts } from "@/lib/hosts/session-index"; import type { ProjectUpdate } from "@/lib/hosts/session-ops"; import { applyProjectPresentation, isReservedLaunchArg, ProjectPathError, type ProjectPresentationUpdate } from "@/lib/project-registry"; -import { cloneDirectoryName } from "@/lib/git-clone"; +import { cloneDirectoryName, repositoryKey } from "@/lib/git-clone"; import { isRecord } from "@/lib/type-guards"; import type { ProjectLaunchConfig } from "@/lib/types"; const MAX_EXTRA_ARGS = 32; @@ -110,7 +110,9 @@ export async function POST(req: Request) { if (!isValidPoolOrigin(body.origin)) throw new ProjectPathError("invalid_origin", "Invalid repository origin"); if (body.name !== undefined && (typeof body.name !== "string" || !body.name.trim())) throw new ProjectPathError("invalid_name", "Name must be a non-empty string"); if (body.defaultRef !== undefined && typeof body.defaultRef !== "string") throw new ProjectPathError("invalid_ref", "Default ref must be a string"); - const matches = pool.projects.filter((project) => project.origin === body.origin); + // One repository is one project whatever URL form names it (spec M4); an unsupported form matches only its own text. + const key = repositoryKey(body.origin); + const matches = pool.projects.filter((project) => project.origin === body.origin || (key !== null && repositoryKey(project.origin) === key)); if (matches.length > 1) throw new Error("Ambiguous pool project origin"); let project = matches[0]; if (!project) { diff --git a/components/AppShell.tsx b/components/AppShell.tsx index ba4f5bbf9..3768c12fb 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -39,7 +39,7 @@ import type { WorkspaceFileSource } from "@/lib/workspace-types"; import { buildAtMentionText, buildFileAtMentionsText, buildFileLineMentionText } from "@/lib/file-fuzzy"; import { getInitialNavigation } from "@/lib/initial-navigation"; import { comparableProjectPath } from "@/lib/comparable-path"; -import { hostProjectKey, LOCAL_HOST_ID, remoteHostId, projectIdentity, projectTargetId } from "@/lib/project-ordering"; +import { foldedHostProjectKey, hostProjectKey, LOCAL_HOST_ID, remoteHostId, projectIdentity, projectTargetId } from "@/lib/project-ordering"; import { useHostRows } from "@/hooks/useHostRows"; import { LocalDaemonBanner } from "./LocalDaemonBanner"; import { hostName } from "./host-status"; @@ -1775,7 +1775,12 @@ export function AppShell({ appName }: { appName: string }) { const newSessionHost = effectivePoolProject ? undefined : newSessionCwd !== null ? newSessionHostId : activeHostId; const newSessionHostKey = effectivePoolProject ? projectTargetId(effectivePoolProject) : newSessionHost ?? LOCAL_HOST_ID; const newSessionProject = effectivePoolProject ? projectIdentity(effectivePoolProject) : (workspaceOptions.cwd === effectiveNewSessionCwd && workspaceOptions.hostId === newSessionHostKey ? workspaceOptions.selectedProject : null) ?? effectiveNewSessionCwd ?? ""; - const hostProjects = workspaceOptions.projects.filter((project) => projectTargetId(project) === newSessionHostKey); + // The panel's target is the group the sidebar lists the project under: the cluster for a member's pinned project. The real host (above) is where the session runs. + const newSessionGroupKey = projectTargetId(effectivePoolProject ?? { hostId: newSessionHostKey }, pools); + // Pool projects first (stable), as in the sidebar's cluster group. + const hostProjects = workspaceOptions.projects.filter((project) => projectTargetId(project, pools) === newSessionGroupKey).sort((a, b) => Number(Boolean(b.poolId)) - Number(Boolean(a.poolId))); + // Two members' projects can share a path, so a non-pool option's value carries its host. + const newSessionWorkspaceValue = effectivePoolProject ? projectIdentity(effectivePoolProject) : effectiveNewSessionCwd ? hostProjectKey(newSessionHost, effectiveNewSessionCwd) : ""; const memberIds = new Set(pools.flatMap((pool) => pool.members.map((member) => member.hostId))); 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; @@ -2545,10 +2550,11 @@ export function AppShell({ appName }: { appName: string }) { { const key = event.target.value; - if (!key) { openAddProject(true, newSessionHostKey); return; } - const project = hostProjects.find((candidate) => projectIdentity(candidate) === key || (!candidate.poolId && candidate.path === key)); + if (!key) { openAddProject(true, newSessionGroupKey); return; } + const project = hostProjects.find((candidate) => projectIdentity(candidate) === key || (!candidate.poolId && hostProjectKey(candidate.hostId, candidate.path) === key)); if (!project) return; suppressCwdRef.current = project.path; setActivePoolProject(project.poolId ? project : null); setActiveCwd(project.poolId ? null : project.path); + setActiveHostId(project.poolId ? undefined : remoteHostId(project.hostId)); handleNewSession(crypto.randomUUID(), project.poolId ? null : project.path, project.hostId, project); }} > - {!effectivePoolProject && effectiveNewSessionCwd && !hostProjects.some((project) => comparableProjectPath(project.path) === comparableProjectPath(newSessionProject)) && ( - + {!effectivePoolProject && effectiveNewSessionCwd && !hostProjects.some((project) => foldedHostProjectKey(project.hostId, project.path) === foldedHostProjectKey(newSessionHost, newSessionProject)) && ( + )} - {hostProjects.map((project) => ( - - ))} + {hostProjects.map((project) => { + const name = project.alias ?? project.name ?? projectLabel(project.path); + // A member's pinned project: its option names the node. + const node = !project.poolId && projectTargetId(project, pools) !== (project.hostId ?? LOCAL_HOST_ID) ? hosts?.find((host) => host.id === (project.hostId ?? LOCAL_HOST_ID)) : undefined; + return ( + + ); + })}