diff --git a/CHANGELOG.md b/CHANGELOG.md index beb1f2821..da51b5384 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,8 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **The retry banner keeps its cancel button on-screen on mobile.** Retry details wrap within the composer, including long provider errors, instead of pushing the Abort retry button past the side of the screen. Long details scroll within a bounded area, and the controls reflow in narrow chat columns. - **Windows host updates allow more time for safety checks.** The process inventory gets up to 20 seconds to start and finish on a busy machine, instead of five. Shared installations and failed or unreadable inventories still block the update before the daemon is stopped. - **Copied uploads start retention at the send time on Windows too.** When a hard link cannot be used or its timestamp cannot be changed, the host writes a fresh exclusive copy instead of inheriting an old staging timestamp. Failed copies remain retryable without replacing unrelated files. +- **Windows servers can manage pools of Unix workers.** Pool configuration and clone paths use the worker's path rules, not the web server's OS. Creation journals retain their synced-file, atomic-rename commit on Windows without requiring unsupported directory fsync. +- **Session HTML export supports Windows OMP launchers.** Export uses the same `.cmd` and `.bat` handling as RPC sessions and version checks. - **Newly sent uploads survive an overlapping retention sweep.** The host refreshes the staged file's timestamp before making its hard link visible, for attachments and Files-panel uploads alike, so cleanup cannot mistake a just-sent file for an expired one. A Files-panel overwrite of an expired file can no longer be deleted by a sweep that inspected the file it replaced. - **Windows upload cleanup respects each daemon's retention policy.** Shared temporary roots now keep each daemon's attachments in its own subfolder, so a seven-day policy cannot delete another daemon's “Never” uploads, even with copied session UUIDs. Existing flat fallback files remain readable and are left untouched because their owner is unknown. - **Credential copies and config `.env` files stay private without blocking independent uploads.** The file viewer and upload preflight/overwrite deny editor swaps and backups such as `.agent.db.swp`, `agent.db~`, `.models.yml.swp` and `models.yml-backup` only directly in omp's actual agent directories (including profiles). `.env` and `.env.*` are also denied at genuine default/profile config roots and agent directories, including their symlinked real targets. Same-named session uploads, workspace files and package assets remain readable and replaceable. diff --git a/README.md b/README.md index 410765182..e0e399c7c 100644 --- a/README.md +++ b/README.md @@ -214,6 +214,47 @@ the daemon's link when it starts, so start the web server first. - **Development:** `npm run dev` does not take the daemon (see [Development](#development)). +### 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. + +Creation retries reuse the same intent and creation identity. Once a real session is known, +its owner remains authoritative for resume, files, terminal, uploads, artifacts, rename, and +delete, even if pool membership changes. An unavailable owner does not trigger replacement +on another worker or on the Mac. Dirty files and unpublished work remain on that owner; +there is no live migration or unpublished-work failover. After an uncertain response, +inspect the retained session before explicitly retrying a command that may have run. + + +### Local worker maintenance (Unix) + +`ompweb host status` prints daemon PID, native version/protocol, welcomed-link readiness, +executable/entrypoint identity and maintenance state without credentials. +`ompweb host drain` synchronously checks children (idle included), preparations, +uploads/controls, pending operations and reliable results, and closes new-work admission +only when idle. A busy refusal never kills work or changes admission. +`ompweb host resume` reopens the live daemon. Controls use a private Unix socket inside +the existing daemon, not TCP or a separate service. A disconnected deployer cannot release +a live drain. Ordinary standalone Windows hosts remain unchanged; local controls are Unix-only. +Disable central member admission before worker rollout; native drain is the final race-free guard. + +Worker service cutovers can additionally start drained through `OMP_WEB_HOST_DRAINED=1` +in their protected temporary unit environment. Live resume does not remove that startup +setting. After a deployer crash or lost final resume reply, verify the selected release, +PID and welcomed-link health, and remove the known worker maintenance flag before explicit +resume. Never infer from a missing acknowledgement that admission stayed closed, and never +stop or roll back a candidate after its deployment commit point. + ### Single binary Each [release](https://github.com/kahme247/ompweb/releases/latest) also ships @@ -533,9 +574,11 @@ Notes: @-mentions and live file watching use the owning machine's daemon, including This machine. Explorer uploads accept up to 2 GiB per file with no 100 MiB batch cap; preview limits remain 256 KiB for text and 10 MiB for images/DOCX. - File tabs retain their source host when you switch chats. An unavailable or - older daemon reports offline or asks for an update; main never substitutes its - own filesystem. + File tabs retain their source session, host and workspace when you switch chats; + paths from another conversation cannot be mentioned into the selected chat. + An unavailable or older daemon reports offline or asks for an update; main + never substitutes its own filesystem. Unprepared pool chats have no guessed + filesystem to browse. - **Git and worktrees on every host:** status, diffs, GitHub issue links, and worktree creation, selection and removal run on the owning daemon. Dirty worktrees still require explicit force confirmation. Switching a worktree diff --git a/app/api/agent/[id]/bash-output/route.ts b/app/api/agent/[id]/bash-output/route.ts index 009fe01fb..b5e5f4550 100644 --- a/app/api/agent/[id]/bash-output/route.ts +++ b/app/api/agent/[id]/bash-output/route.ts @@ -17,7 +17,7 @@ export async function GET( const opened = await host.workspaceOps.openBashOutput(id, path); if (!opened.ok) return opErrorResponse(opened); disableIdleTimeout(); - return new Response(workspaceReadStream(host, opened.value), { headers: { + return new Response(workspaceReadStream(host, opened.value, 0, opened.value.info.size - 1, request.signal), { headers: { "Content-Type": "text/plain; charset=utf-8", "Content-Disposition": "attachment; filename=\"bash-output.log\"", "Cache-Control": "no-store", diff --git a/app/api/agent/new/route.ts b/app/api/agent/new/route.ts index dc62d98f1..8c9578c43 100644 --- a/app/api/agent/new/route.ts +++ b/app/api/agent/new/route.ts @@ -1,10 +1,17 @@ import { apiErrorResponse, opErrorResponse, resolveHostOrError } from "@/lib/api-utils"; -import { WebRpcError, startNewRpcSession } from "@/lib/rpc-manager"; +import { WebRpcError, startNewRpcSession, type AgentSessionWrapper } from "@/lib/rpc-manager"; import { RpcCommandError } from "@/lib/omp/rpc-process"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { MAX_AGENT_COMMAND_REQUEST_BYTES } from "@/lib/image-attachments"; +import { validateAgentImages } from "@/lib/image-attachments"; +import { PoolStartError, startPooledSession } from "@/lib/hosts/pool-starts"; +import { HostOpError } from "@/lib/hosts/link-protocol"; +import { isRecord } from "@/lib/type-guards"; function newSessionErrorResponse(error: unknown) { + if (error instanceof PoolStartError) { + return Response.json({ error: error.message, code: error.code, sessionId: error.sessionId, hostId: error.hostId, cwd: error.cwd, delivery: error.delivery }, { status: error.status }); + } if (error instanceof RequestBodyTooLargeError) { return Response.json({ error: "New session request is too large", code: "request_too_large" }, { status: 413 }); } @@ -20,62 +27,72 @@ function newSessionErrorResponse(error: unknown) { } return apiErrorResponse(error); } -// POST /api/agent/new body: { cwd: string; type: string; hostId?: string; message?: string; ... } -// Spawns a brand-new omp session on `hostId` (this machine when absent). Most -// calls immediately send the first command; -// type:"ensure_session" only creates the runtime so clients can query commands. -// Returns { sessionId, data } where sessionId is omp's real session id. -// Model/thinking presets are applied post-ready via RPC set_model / -// set_thinking_level (not CLI flags) so failures surface as command errors and -// the live model catalog (incl. background discovery) is consulted. +// Pooled creation carries creationId/poolId/projectId, never physical host/cwd. +// Standalone creation keeps its existing checked host-local cwd and cleanup. export async function POST(req: Request) { try { const body = await parseJsonWithinLimit<{ cwd?: string; hostId?: unknown; [key: string]: unknown }>(req, MAX_AGENT_COMMAND_REQUEST_BYTES); - const { cwd: requestedCwd, hostId, ...command } = body; - // New-chat uploads have no session file to attach into; never forward bearer authority to native RPC. + if (!isRecord(body)) return Response.json({ error: "A session request object is required", code: "invalid_request" }, { status: 400 }); + const { cwd: requestedCwd, hostId, poolId, projectId, creationId, ref, ...command } = body; + delete command.intentHash; if (Object.hasOwn(command, "uploadProofs") || Object.hasOwn(command, "uploads")) { return Response.json({ error: "Files attach only to an existing session", code: "invalid_uploads" }, { status: 400 }); } - const target = resolveHostOrError(hostId); - if ("response" in target) return target.response; - const { host } = target; - - if (!requestedCwd || typeof requestedCwd !== "string") { - return Response.json({ error: "cwd is required", code: "cwd_required" }, { status: 400 }); + const pooled = poolId !== undefined || projectId !== undefined || creationId !== undefined || ref !== undefined; + if (pooled && (hostId !== undefined || requestedCwd !== undefined || typeof poolId !== "string" || typeof projectId !== "string" || typeof creationId !== "string" || (ref !== undefined && typeof ref !== "string"))) { + return Response.json({ error: "Pool creation requires creationId, poolId and projectId, without hostId or cwd", code: "invalid_pool_target" }, { status: 400 }); } - - const { provider, modelId, toolNames, thinkingLevel, advisor, ...promptCommand } = command as { provider?: string; modelId?: string; toolNames?: string[]; thinkingLevel?: string; advisor?: boolean; [key: string]: unknown }; + const { provider, modelId, toolNames, thinkingLevel, advisor, name, ...promptCommand } = command as { provider?: string; modelId?: string; toolNames?: string[]; thinkingLevel?: string; advisor?: boolean; name?: string; [key: string]: unknown }; // A session id has no meaning for a fresh spawn and must never reach the // child RPC: a stale or forged id would address the wrong session. delete promptCommand.sessionId; if (typeof promptCommand.type !== "string" || !promptCommand.type.trim()) { return Response.json({ error: "command type is required", code: "command_type_required" }, { status: 400 }); } + if ([provider, modelId, thinkingLevel, name].some((value) => value !== undefined && (typeof value !== "string" || !value.trim())) + || (toolNames !== undefined && (!Array.isArray(toolNames) || toolNames.some((value) => typeof value !== "string" || !value.trim()))) + || (advisor !== undefined && typeof advisor !== "boolean") + || (promptCommand.message !== undefined && typeof promptCommand.message !== "string")) { + return Response.json({ error: "Invalid session initialization fields", code: "invalid_creation_intent" }, { status: 400 }); + } + const imageError = validateAgentImages(promptCommand.images); + if (imageError) return Response.json({ error: imageError, code: "invalid_images" }, { status: 400 }); + + const initialize = async (session: AgentSessionWrapper, preserveUnknownDelivery: boolean) => { + if (provider && modelId) await session.send({ type: "set_model", provider, modelId }, { preserveUnknownDelivery }); + if (thinkingLevel) await session.send({ type: "set_thinking_level", level: thinkingLevel }, { preserveUnknownDelivery }); + if (name) await session.send({ type: "set_session_name", name }, { preserveUnknownDelivery }); + if (promptCommand.type === "ensure_session") return null; + return session.send(promptCommand, { preserveUnknownDelivery }); + }; + const preparing = promptCommand.type !== "ensure_session" || !!(provider && modelId) || !!thinkingLevel || !!name; - // The cwd is checked on its host; the host answers with the path it will use. - const preparing = promptCommand.type !== "ensure_session" || !!(provider && modelId) || !!thinkingLevel; - const started = await startNewRpcSession(host, requestedCwd, toolNames, advisor === true, preparing); + if (pooled) { + // The hash is derived here from every effectful field, including unknown command options. + const intent = { ...promptCommand, provider, modelId, toolNames, thinkingLevel, advisor, name }; + const result = await startPooledSession({ creationId: creationId as string, poolId: poolId as string, projectId: projectId as string, ...(ref === undefined ? {} : { ref: ref as string }), intent }, async (host, prepared, id, onStarted) => { + const started = await startNewRpcSession(host, prepared.cwd, toolNames, advisor === true, preparing, id); + if (!started.ok) throw new HostOpError(started.status, started.code, started.error); + const { session, realSessionId } = started.value; + await onStarted(realSessionId); + const run = () => initialize(session, true); + return { sessionId: realSessionId, data: await (preparing ? session.withPendingCommand(run, true) : run()) }; + }); + return Response.json({ success: true, ...result }); + } + + if (!requestedCwd || typeof requestedCwd !== "string") { + return Response.json({ error: "cwd is required", code: "cwd_required" }, { status: 400 }); + } + const target = resolveHostOrError(hostId); + if ("response" in target) return target.response; + const started = await startNewRpcSession(target.host, requestedCwd, toolNames, advisor === true, preparing); if (!started.ok) return opErrorResponse(started); const { session, realSessionId } = started.value; - try { - const run = async () => { - if (provider && modelId) await session.send({ type: "set_model", provider, modelId }); - if (thinkingLevel) await session.send({ type: "set_thinking_level", level: thinkingLevel }); - if (promptCommand.type === "ensure_session") { - return Response.json({ success: true, sessionId: realSessionId, data: null }); - } - const result = await session.send(promptCommand); - return Response.json({ success: true, sessionId: realSessionId, data: result }); - }; + const run = async () => Response.json({ success: true, sessionId: realSessionId, data: await initialize(session, false) }); return await (preparing ? session.withPendingCommand(run, true) : run()); } catch (error) { - // The child was spawned but the prompt never ran: without this cleanup a - // failed set_model/set_thinking_level/prompt leaves an orphaned omp - // process and a registry entry nobody will ever use. - // The link dropped: the first command may be running there, so the - // wrapper stays for the reconnect (and disposing it would wait for the link). - // Its id lets the client open it instead of starting a second session. if (error instanceof WebRpcError && error.code === "host_offline") { return Response.json({ error: error.message, code: error.code, hostOffline: true, delivery: error.delivery, sessionId: realSessionId }, { status: 503 }); } diff --git a/app/api/file-index/route.ts b/app/api/file-index/route.ts index dd53a66b7..36eed85d8 100644 --- a/app/api/file-index/route.ts +++ b/app/api/file-index/route.ts @@ -6,11 +6,11 @@ import { parseResultLimit } from "@/lib/file-fuzzy"; export async function GET(req: Request) { try { const params = new URL(req.url).searchParams; - const resolved = await resolveWorkspaceHost(params.get("hostId") ?? undefined, null); + const resolved = await resolveWorkspaceHost(params.get("hostId") ?? undefined, params.get("sessionId")); if ("response" in resolved) return resolved.response; const result = await resolved.host.workspaceOps.fileIndex( - params.get("cwd")?.trim() ?? "", params.get("q") ?? "", parseResultLimit(params.get("limit")), - params.get("kind") === "file" ? "file" : "all", params.get("refresh") === "1", + resolved.cwd ?? params.get("cwd")?.trim() ?? "", params.get("q") ?? "", parseResultLimit(params.get("limit")), + params.get("kind") === "file" ? "file" : "all", params.get("refresh") === "1", resolved.owner, ); return result.ok ? Response.json(result.value) : opErrorResponse(result); } catch (error) { diff --git a/app/api/files/[...path]/route.ts b/app/api/files/[...path]/route.ts index 4062022a2..7fe3d7e52 100644 --- a/app/api/files/[...path]/route.ts +++ b/app/api/files/[...path]/route.ts @@ -49,7 +49,7 @@ export async function POST(request: Request, { params }: { params: Promise<{ pat if (!Array.isArray(files) || files.length === 0 || files.length > 1000 || !files.every((file) => isRecord(file) && typeof file.id === "string" && typeof file.name === "string")) return Response.json({ error: "Invalid uploads", code: "invalid_uploads" }, { status: 400 }); names = files.map((file) => file.name as string); } - const inspection = await host.workspaceOps.inspectUploads(directory, names); + const inspection = await host.workspaceOps.inspectUploads(directory, names, resolved.owner); if (!inspection.ok) return opErrorResponse(inspection); if (type === "upload-check") return Response.json(inspection.value); const strategy = parseUploadConflictStrategy(searchParams.get("conflict")); @@ -59,7 +59,7 @@ export async function POST(request: Request, { params }: { params: Promise<{ pat let failureStatus = 200; for (const file of files as Array<{ id: string; name: string }>) { try { - const result = await publishWorkspaceUpload(file.id, requestOwner(request), host.id, directory, file.name, strategy); + const result = await publishWorkspaceUpload(file.id, requestOwner(request), host.id, directory, file.name, strategy, resolved.owner); (result.skipped ? skipped : uploaded).push(result.name); } catch (error) { const response = uploadErrorResponse(error); @@ -144,7 +144,7 @@ export async function GET( const resolved = await resolveWorkspaceHost(searchParams.get("hostId") ?? undefined, searchParams.get("sessionId")); if ("response" in resolved) return resolved.response; const { host } = resolved; - const input = { segments, sessionId: resolved.sessionId, sessionFile: resolved.sessionFile }; + const input = { segments, sessionId: resolved.sessionId, sessionFile: resolved.sessionFile, owner: resolved.owner }; if (type === "list") { const result = await host.workspaceOps.listFilesInRoot(input, searchParams.get("root")); return result.ok ? Response.json(result.value) : opErrorResponse(result); @@ -173,7 +173,7 @@ export async function GET( } disableIdleTimeout(); if (type === "preview") { - const buffer = await readWorkspaceBytes(host, opened.value, DOCX_PREVIEW_MAX_BYTES); + const buffer = await readWorkspaceBytes(host, opened.value, DOCX_PREVIEW_MAX_BYTES, request.signal); const result = await mammoth.convertToHtml({ buffer }, { externalFileAccess: false, convertImage: mammoth.images.dataUri }); return new Response(wrapDocxPreviewHtml(result.value, info.name), { headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-cache", @@ -181,7 +181,7 @@ export async function GET( "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff", } }); } - return streamWorkspaceFile(host, opened.value, image ?? audio ?? document ?? "application/octet-stream", request.headers.get("range"), type === "download"); + return streamWorkspaceFile(host, opened.value, image ?? audio ?? document ?? "application/octet-stream", request.headers.get("range"), type === "download", request.signal); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/git/diff/route.ts b/app/api/git/diff/route.ts index afcd9663a..72177cce2 100644 --- a/app/api/git/diff/route.ts +++ b/app/api/git/diff/route.ts @@ -3,9 +3,9 @@ import { apiErrorResponse, opErrorResponse, resolveWorkspaceHost } from "@/lib/a export async function GET(request: Request) { try { const params = new URL(request.url).searchParams; - const resolved = await resolveWorkspaceHost(params.get("hostId") ?? undefined, null); + const resolved = await resolveWorkspaceHost(params.get("hostId") ?? undefined, params.get("sessionId")); if ("response" in resolved) return resolved.response; - const result = await resolved.host.workspaceOps.gitDiff(params.get("cwd")?.trim() ?? "", params.get("path")?.trim() ?? ""); + const result = await resolved.host.workspaceOps.gitDiff(resolved.cwd ?? params.get("cwd")?.trim() ?? "", params.get("path")?.trim() ?? "", resolved.owner); return result.ok ? Response.json(result.value) : opErrorResponse(result); } catch (error) { return apiErrorResponse(error); } } diff --git a/app/api/git/status/route.ts b/app/api/git/status/route.ts index 999a04113..f807c66bd 100644 --- a/app/api/git/status/route.ts +++ b/app/api/git/status/route.ts @@ -3,9 +3,9 @@ import { apiErrorResponse, opErrorResponse, resolveWorkspaceHost } from "@/lib/a export async function GET(request: Request) { try { const params = new URL(request.url).searchParams; - const resolved = await resolveWorkspaceHost(params.get("hostId") ?? undefined, null); + const resolved = await resolveWorkspaceHost(params.get("hostId") ?? undefined, params.get("sessionId")); if ("response" in resolved) return resolved.response; - const result = await resolved.host.workspaceOps.gitStatus(params.get("cwd")?.trim() ?? ""); + const result = await resolved.host.workspaceOps.gitStatus(resolved.cwd ?? params.get("cwd")?.trim() ?? "", resolved.owner); return result.ok ? Response.json(result.value) : opErrorResponse(result); } catch (error) { return apiErrorResponse(error); } } diff --git a/app/api/hosts/route.ts b/app/api/hosts/route.ts index df5cf3087..66c89c096 100644 --- a/app/api/hosts/route.ts +++ b/app/api/hosts/route.ts @@ -1,11 +1,17 @@ import { closeHostLink, hostsSnapshot, listHosts, notifyHostsChange } from "@/lib/hosts/hub"; -import { createHost, HostRegistryUnreadableError, revokeHost, UnknownHostError, updateHost } from "@/lib/hosts/registry"; +import { loadPools, savePools, type HostPool } from "@/lib/hosts/pools"; +import { createHost, HostRegistryUnreadableError, readHosts, revokeHost, UnknownHostError, updateHost } from "@/lib/hosts/registry"; import { isRecord } from "@/lib/type-guards"; const MAX_LABEL_LENGTH = 100; const noStore = { "cache-control": "no-store" }; const fail = (error: string, status: number) => Response.json({ error }, { status, headers: noStore }); +const poolStorageFailure = () => fail("The pool registry (omp-web/pools.json) cannot be read or written; fix it before changing pools", 503); + +function hasOnlyKeys(value: unknown, keys: readonly string[]): value is Record { + return isRecord(value) && Object.keys(value).every((key) => keys.includes(key)); +} function failFor(error: unknown) { if (error instanceof HostRegistryUnreadableError) { @@ -47,7 +53,51 @@ function requestOrigin(req: Request): string { } export function GET() { - return Response.json(hostsSnapshot(), { headers: noStore }); + let pools: HostPool[]; + try { + pools = loadPools(); + } catch { + return poolStorageFailure(); + } + return Response.json({ ...hostsSnapshot(), pools }, { headers: noStore }); +} + +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"]); + try { + for (const host of readHosts()) knownHosts.add(host.id); + } catch (error) { + return failFor(error); + } + 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); + for (const member of pool.members) { + if (!hasOnlyKeys(member, ["hostId", "projectsRoot", "provisioned", "draining"]) + || typeof member.hostId !== "string" || !knownHosts.has(member.hostId)) return fail("Invalid or unknown pool member", 400); + } + for (const project of pool.projects) { + if (!hasOnlyKeys(project, ["id", "name", "origin", "defaultRef", "clonePaths", "addedAt", "hidden", "alias", "sortOrder", "pinOrder", "launchConfig"]) + || (project.launchConfig !== undefined && !hasOnlyKeys(project.launchConfig, ["profile", "advisor", "extraArgs"]))) { + return fail("Invalid pool project configuration", 400); + } + } + } + try { + loadPools(); + } catch { + return poolStorageFailure(); + } + try { + savePools(body.pools as HostPool[]); + } 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 }); } export async function POST(req: Request) { diff --git a/app/api/projects/route.ts b/app/api/projects/route.ts index 612fff9c3..87b52230d 100644 --- a/app/api/projects/route.ts +++ b/app/api/projects/route.ts @@ -1,10 +1,14 @@ +import { randomUUID } from "node:crypto"; import { apiErrorResponse, opErrorResponse, resolveHostOrError } from "@/lib/api-utils"; import { isValidOmpProfile } from "@/lib/omp-profile"; import { allowFileRoot } from "@/lib/file-access"; import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; +import { isValidPoolOrigin, loadPools, pathApi, poolManagedProject, savePools } from "@/lib/hosts/pools"; import { listProjectsAllHosts } from "@/lib/hosts/session-index"; import type { ProjectUpdate } from "@/lib/hosts/session-ops"; -import { isReservedLaunchArg, ProjectPathError } from "@/lib/project-registry"; +import { applyProjectPresentation, isReservedLaunchArg, ProjectPathError, type ProjectPresentationUpdate } from "@/lib/project-registry"; +import { cloneDirectoryName } from "@/lib/git-clone"; +import { isRecord } from "@/lib/type-guards"; import type { ProjectLaunchConfig } from "@/lib/types"; const MAX_EXTRA_ARGS = 32; const MAX_EXTRA_ARG_LENGTH = 256; @@ -28,6 +32,48 @@ function parseLaunchConfig(value: unknown): ProjectLaunchConfig | undefined { return { profile, advisor, extraArgs }; } +function parsePresentation(entry: Record): ProjectPresentationUpdate { + const alias = entry.alias === null ? null : typeof entry.alias === "string" ? entry.alias : undefined; + const sortOrder = entry.sortOrder === null ? null : typeof entry.sortOrder === "number" && Number.isFinite(entry.sortOrder) ? entry.sortOrder : undefined; + const pinOrder = entry.pinOrder === null ? null : typeof entry.pinOrder === "number" && Number.isFinite(entry.pinOrder) ? entry.pinOrder : undefined; + if (entry.alias !== undefined && alias === undefined) throw new ProjectPathError("invalid_alias", "Alias must be a string"); + if (entry.sortOrder !== undefined && sortOrder === undefined) throw new ProjectPathError("invalid_sort_order", "Sort order must be a number"); + if (entry.pinOrder !== undefined && pinOrder === undefined) throw new ProjectPathError("invalid_pin_order", "Pin order must be a number"); + return { alias, sortOrder, pinOrder, launchConfig: entry.launchConfig === null ? null : parseLaunchConfig(entry.launchConfig) }; +} + +function poolTarget(body: Record) { + if (body.hostId !== undefined || body.cwd !== undefined) throw new ProjectPathError("invalid_target", "Pool and host/path targets cannot be mixed"); + if (typeof body.poolId !== "string") throw new ProjectPathError("pool_required", "Pool ID is required"); + const pools = loadPools(); + const pool = pools.find((item) => item.id === body.poolId); + if (!pool) throw new ProjectPathError("pool_not_found", "Pool not found"); + return { pools, pool }; +} + +function pooledPatch(body: Record) { + const { pools, pool } = poolTarget(body); + const batch = body.updates !== undefined; + if (batch && (!Array.isArray(body.updates) || body.projectId !== undefined)) throw new ProjectPathError("invalid_target", "Invalid pool batch target"); + const rawUpdates = batch ? body.updates as unknown[] : [body]; + if (!rawUpdates.length || rawUpdates.length > MAX_PRESENTATION_UPDATES) throw new ProjectPathError("invalid_updates", "Invalid number of updates"); + const updates = new Map(); + for (const entry of rawUpdates) { + if (!isRecord(entry) || entry.cwd !== undefined || entry.hostId !== undefined || (batch && entry.poolId !== undefined)) { + throw new ProjectPathError("invalid_target", "Pool and host/path targets cannot be mixed"); + } + if (typeof entry.projectId !== "string" || !pool.projects.some((project) => project.id === entry.projectId)) throw new ProjectPathError("project_not_found", "Registered project not found"); + if (updates.has(entry.projectId)) throw new ProjectPathError("duplicate_project", "Duplicate project ID"); + updates.set(entry.projectId, parsePresentation(entry)); + } + pool.projects = pool.projects.map((project) => { + const update = updates.get(project.id); + return update ? applyProjectPresentation(project, update) : project; + }); + savePools(pools); + return Response.json({ projects: pool.projects.filter((project) => !project.hidden).map((project) => poolManagedProject(pool, project)) }); +} + // GET /api/projects → { projects: ManagedProject[] } // Registered (non-hidden) projects plus session-discovered projects, excluding // hidden entries, for this machine and then each linked host; each carries its @@ -41,7 +87,7 @@ export async function GET() { // have no sessions (the in-memory list does not survive restarts, and an // empty managed project derives no root from sessions). Only this // machine's: another host's paths do not exist here. - for (const project of projects) if (project.hostId === LOCAL_HOST_ID) allowFileRoot(project.path); + for (const project of projects) if (!project.poolId && project.hostId === LOCAL_HOST_ID) allowFileRoot(project.path); return Response.json({ projects }); } catch (error) { return apiErrorResponse(error); @@ -51,11 +97,38 @@ export async function GET() { // POST /api/projects body: { cwd } → { project: ManagedProject } // Validates the directory, resolves Git worktrees to their main projectRoot, // registers and authorizes it, and unhides it if it was previously hidden. +// Pool shape: { poolId, origin, name?, defaultRef?, launchConfig? }; registers an origin, never a checkout. export async function POST(req: Request) { try { - const body = await req.json() as { cwd?: unknown; launchConfig?: unknown; hostId?: unknown }; + const body: unknown = await req.json(); + if (!isRecord(body)) throw new ProjectPathError("invalid_target", "Project target must be an object"); const cwd = typeof body.cwd === "string" ? body.cwd : ""; const launchConfig = parseLaunchConfig(body.launchConfig); + if (body.poolId !== undefined || body.projectId !== undefined || body.origin !== undefined) { + const { pools, pool } = poolTarget(body); + if (body.projectId !== undefined) throw new ProjectPathError("invalid_target", "Registration generates the project ID"); + 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); + if (matches.length > 1) throw new Error("Ambiguous pool project origin"); + let project = matches[0]; + if (!project) { + project = { + id: randomUUID(), name: typeof body.name === "string" ? body.name.trim() : cloneDirectoryName(body.origin)!, + origin: body.origin, clonePaths: {}, addedAt: new Date().toISOString(), hidden: false, + }; + pool.projects.push(project); + } + project.hidden = false; + project.addedAt = new Date().toISOString(); + if (typeof body.name === "string") project.name = body.name.trim(); + if (typeof body.defaultRef === "string") project.defaultRef = body.defaultRef; + if (launchConfig !== undefined) project.launchConfig = launchConfig; + for (const member of pool.members) project.clonePaths[member.hostId] ??= pathApi(member.projectsRoot).join(member.projectsRoot, project.id); + savePools(pools); + return Response.json({ project: poolManagedProject(pool, project) }); + } const target = resolveHostOrError(body.hostId); if ("response" in target) return target.response; const { host } = target; @@ -81,17 +154,12 @@ export async function POST(req: Request) { // same cycle instead of silently no-oping. const MAX_PRESENTATION_UPDATES = 500; +// Pool mutations use { poolId, projectId, ...settings } or { poolId, updates: [{ projectId, ...settings }] }. export async function PATCH(req: Request) { try { - const body = await req.json() as { - cwd?: unknown; - alias?: unknown; - sortOrder?: unknown; - pinOrder?: unknown; - launchConfig?: unknown; - updates?: unknown; - hostId?: unknown; - }; + const body: unknown = await req.json(); + if (!isRecord(body)) throw new ProjectPathError("invalid_target", "Project target must be an object"); + if (body.poolId !== undefined || body.projectId !== undefined) return pooledPatch(body); const rawUpdates: unknown[] = Array.isArray(body.updates) ? body.updates : body.cwd !== undefined || body.alias !== undefined || body.sortOrder !== undefined || body.pinOrder !== undefined || body.launchConfig !== undefined @@ -106,17 +174,12 @@ export async function PATCH(req: Request) { const parsed: ProjectUpdate[] = []; for (const item of rawUpdates) { - const entry = item as { cwd?: unknown; alias?: unknown; sortOrder?: unknown; pinOrder?: unknown; launchConfig?: unknown }; + if (!isRecord(item)) throw new ProjectPathError("invalid_target", "Project update must be an object"); + const entry = item; + if (entry.poolId !== undefined || entry.projectId !== undefined) throw new ProjectPathError("invalid_target", "Pool and host/path targets cannot be mixed"); const cwd = typeof entry.cwd === "string" ? entry.cwd.trim() : ""; if (!cwd) return Response.json({ error: "Path is required", code: "path_required" }, { status: 400 }); - const alias = entry.alias === null ? null : typeof entry.alias === "string" ? entry.alias : undefined; - const sortOrder = entry.sortOrder === null ? null : typeof entry.sortOrder === "number" && Number.isFinite(entry.sortOrder) ? entry.sortOrder : undefined; - const pinOrder = entry.pinOrder === null ? null : typeof entry.pinOrder === "number" && Number.isFinite(entry.pinOrder) ? entry.pinOrder : undefined; - if (entry.alias !== undefined && alias === undefined) return Response.json({ error: "Alias must be a string", code: "invalid_alias" }, { status: 400 }); - if (entry.sortOrder !== undefined && sortOrder === undefined) return Response.json({ error: "Sort order must be a number", code: "invalid_sort_order" }, { status: 400 }); - if (entry.pinOrder !== undefined && pinOrder === undefined) return Response.json({ error: "Pin order must be a number", code: "invalid_pin_order" }, { status: 400 }); - const launchConfig = entry.launchConfig === null ? null : parseLaunchConfig(entry.launchConfig); - parsed.push({ cwd, alias, sortOrder, pinOrder, launchConfig }); + parsed.push({ cwd, ...parsePresentation(entry) }); } const target = resolveHostOrError(body.hostId); @@ -139,9 +202,19 @@ export async function PATCH(req: Request) { // DELETE /api/projects body: { cwd } → { success: true } // Hides the project from the sidebar without touching its directory or // sessions. Re-adding the directory (POST) restores it. +// Pool shape: { poolId, projectId }; hides presentation only, retaining all clone bindings and data. export async function DELETE(req: Request) { try { - const body = await req.json() as { cwd?: unknown; hostId?: unknown }; + const body: unknown = await req.json(); + if (!isRecord(body)) throw new ProjectPathError("invalid_target", "Project target must be an object"); + if (body.poolId !== undefined || body.projectId !== undefined) { + const { pools, pool } = poolTarget(body); + const project = pool.projects.find((item) => item.id === body.projectId); + if (!project) throw new ProjectPathError("project_not_found", "Registered project not found"); + project.hidden = true; + savePools(pools); + return Response.json({ success: true }); + } const cwd = typeof body.cwd === "string" ? body.cwd.trim() : ""; if (!cwd) { return Response.json({ error: "Path is required", code: "path_required" }, { status: 400 }); @@ -152,6 +225,7 @@ export async function DELETE(req: Request) { if (!result.ok) return opErrorResponse(result); return Response.json({ success: true }); } catch (error) { + if (error instanceof ProjectPathError) return Response.json({ error: error.message, code: error.code }, { status: 400 }); return apiErrorResponse(error); } } diff --git a/bin/bun-runtime.test.mjs b/bin/bun-runtime.test.mjs index 9e9d902c8..934d6aef7 100644 --- a/bin/bun-runtime.test.mjs +++ b/bin/bun-runtime.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -13,7 +13,7 @@ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".." const isWindows = process.platform === "win32"; function tempDir(t) { - const dir = mkdtempSync(path.join(tmpdir(), "bun-runtime-")); + const dir = realpathSync(mkdtempSync(path.join(tmpdir(), "bun-runtime-"))); t.after(() => rmSync(dir, { recursive: true, force: true })); return dir; } diff --git a/bin/omp-web-host.test.mjs b/bin/omp-web-host.test.mjs index cbde4bcf6..a4cea97be 100644 --- a/bin/omp-web-host.test.mjs +++ b/bin/omp-web-host.test.mjs @@ -76,6 +76,149 @@ test("`ompweb host login` refuses a token line over 4096 bytes without waiting f assert.equal(saved, null); }); +async function hostCommand(env, ...args) { + const child = spawn("node", [bin, "host", ...args], { env, stdio: ["ignore", "pipe", "pipe"] }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk) => { stdout += chunk; }); + child.stderr.on("data", (chunk) => { stderr += chunk; }); + const closed = new Promise((resolve) => child.once("close", (code) => resolve({ code, stdout, stderr }))); + const result = await Promise.race([closed, sleep(15_000, null, { ref: false })]); + if (!result) child.kill("SIGKILL"); + assert.ok(result, `host ${args.join(" ")} did not exit: ${stderr}`); + return result; +} + +function controlFixture(t, { url, longRoot = false } = {}) { + const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-control-cli-")); + const agentDir = join(scratch, ...(longRoot ? ["long-agent-directory-".repeat(10), "agent"] : ["agent"])); + const omp = join(scratch, "fixture-omp"); + writeFileSync(omp, `#!${process.execPath}\nconsole.log("18.0.0-cli-fixture");\n`, { mode: 0o700 }); + const env = { + ...process.env, HOME: scratch, USERPROFILE: scratch, PI_CODING_AGENT_DIR: agentDir, + XDG_CONFIG_HOME: join(scratch, "config"), XDG_DATA_HOME: join(scratch, "data"), + XDG_STATE_HOME: join(scratch, "state"), XDG_CACHE_HOME: join(scratch, "cache"), + OMP_WEB_OMP_BIN: omp, OMP_WEB_DISABLE_AUTOUPDATE: "1", + }; + mkdirSync(join(agentDir, "omp-web"), { recursive: true, mode: 0o700 }); + writeFileSync(join(agentDir, "omp-web", "host.json"), JSON.stringify({ url: url ?? "http://127.0.0.1:9", token: "private-cli-fixture-token" }), { mode: 0o600 }); + t.after(() => rmSync(scratch, { recursive: true, force: true })); + return { scratch, agentDir, env }; +} + +function launchHost(t, env) { + const child = spawn("node", [bin, "host"], { env, stdio: ["ignore", "pipe", "pipe"] }); + let stderr = ""; + child.stderr.on("data", (chunk) => { stderr += chunk; }); + const closed = new Promise((resolve) => child.once("close", (code) => resolve(code))); + t.after(async () => { + child.kill("SIGTERM"); + const result = await Promise.race([closed, sleep(5000, "timeout", { ref: false })]); + if (result === "timeout") child.kill("SIGKILL"); + child.stdout.destroy(); + child.stderr.destroy(); + }); + return { child, closed, log: () => stderr }; +} + +async function controlReady(env) { + const deadline = Date.now() + 15_000; + let answer; + do { + answer = await hostCommand(env, "status"); + if (answer.code === 0) return JSON.parse(answer.stdout); + await sleep(20); + } while (Date.now() < deadline); + assert.fail(`the real CLI endpoint did not become ready: ${answer.stderr}`); +} + +const unixControl = { skip: process.platform === "win32" && "Unix worker control; Windows ordinary host tests above remain unchanged" }; + +test("status/drain/resume consume the real CLI daemon endpoint and SIGTERM removes it", unixControl, async (t) => { + let hellos = 0; + const server = Bun.serve({ + hostname: "127.0.0.1", port: 0, + fetch(req, bun) { return bun.upgrade(req) ? undefined : new Response("Upgrade required", { status: 426 }); }, + websocket: { + message(ws, data) { + for (const line of String(data).split("\n").filter(Boolean)) { + const frame = JSON.parse(line); + if (frame.type === "hello") { + hellos += 1; + ws.send(JSON.stringify({ type: "welcome", v: 8, hostId: "cli-fixture" })); + } else if (typeof frame.seq === "number") ws.send(JSON.stringify({ type: "ack", ack: frame.seq })); + } + }, + }, + }); + t.after(() => server.stop(true)); + const f = controlFixture(t, { url: `http://127.0.0.1:${server.port}`, longRoot: true }); + const daemon = launchHost(t, f.env); + const { hostControlPath } = await import("../lib/hosts/host-control.ts"); + t.after(() => rmSync(join(hostControlPath(f.agentDir), ".."), { recursive: true, force: true })); + let status = await controlReady(f.env); + const deadline = Date.now() + 10_000; + while (!status.linked) { + assert.ok(Date.now() < deadline, `daemon never welcomed: ${daemon.log()}`); + await sleep(20); + 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, 8); + assert.equal(status.drained, false); + assert.equal(hellos, 1); + assert.equal(JSON.stringify(status).includes("private-cli-fixture-token"), false); + for (const [command, drained] of [["drain", true], ["status", true], ["resume", false]]) { + const answer = await hostCommand(f.env, command); + assert.equal(answer.code, 0, answer.stderr); + assert.equal(JSON.parse(answer.stdout).drained, drained); + assert.equal(JSON.parse(answer.stdout).pid, daemon.child.pid); + } + const duplicate = await hostCommand(f.env); + assert.equal(duplicate.code, 1, duplicate.stderr); + assert.match(duplicate.stderr, /already|running|occupied|in use/i); + assert.equal(hellos, 1, "endpoint acquisition precedes dialing, so a duplicate cannot replace the original link"); + assert.equal(JSON.parse((await hostCommand(f.env, "status")).stdout).pid, daemon.child.pid); + daemon.child.kill("SIGTERM"); + assert.equal(await daemon.closed, 0); + assert.equal(existsSync(hostControlPath(f.agentDir)), false); + assert.equal((await hostCommand(f.env, "status")).code, 1, "status must not start a replacement daemon"); +}); + +test("CLI startup failure cleans its endpoint without dialing or needing credentials", unixControl, async (t) => { + const f = controlFixture(t, { url: "http://not-loopback.invalid" }); + const { hostControlPath } = await import("../lib/hosts/host-control.ts"); + t.after(() => rmSync(join(hostControlPath(f.agentDir), ".."), { recursive: true, force: true })); + const result = await hostCommand(f.env); + assert.equal(result.code, 1); + assert.match(result.stderr, /https/i); + assert.equal(existsSync(hostControlPath(f.agentDir)), false); +}); + +test("CLI controls explicitly reject Windows while ordinary host startup stays available", { skip: process.platform !== "win32" && "Windows-only control-command contract" }, async (t) => { + const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-control-win-")); + t.after(() => rmSync(scratch, { recursive: true, force: true })); + const env = { ...process.env, HOME: scratch, USERPROFILE: scratch, PI_CODING_AGENT_DIR: join(scratch, "agent") }; + for (const command of ["status", "drain", "resume"]) { + const result = await hostCommand(env, command); + assert.equal(result.code, 1); + assert.match(result.stderr, /Windows.*unsupported|not supported.*Windows|Unix.only/i); + } +}); + +test("worker maintenance startup is drained before linking and can be explicitly resumed", unixControl, async (t) => { + const f = controlFixture(t); + const daemon = launchHost(t, { ...f.env, OMP_WEB_HOST_DRAINED: "1" }); + const { hostControlPath } = await import("../lib/hosts/host-control.ts"); + t.after(() => rmSync(join(hostControlPath(f.agentDir), ".."), { recursive: true, force: true })); + const status = await controlReady(f.env); + assert.equal(status.pid, daemon.child.pid); + assert.equal(status.drained, true); + const resumed = await hostCommand(f.env, "resume"); + assert.equal(resumed.code, 0, resumed.stderr); + assert.equal(JSON.parse(resumed.stdout).drained, false); +}); + test("`ompweb host login --add` and logout change only the selected URL without argv tokens", async (t) => { const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-multi-login-")); const agentDir = join(scratch, "agent"); diff --git a/components/AppShell.tsx b/components/AppShell.tsx index f82a8c9dc..ba4f5bbf9 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -39,11 +39,10 @@ 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 } from "@/lib/project-ordering"; -import { isLinkUp } from "@/lib/hosts/host"; +import { hostProjectKey, LOCAL_HOST_ID, remoteHostId, projectIdentity, projectTargetId } from "@/lib/project-ordering"; import { useHostRows } from "@/hooks/useHostRows"; import { LocalDaemonBanner } from "./LocalDaemonBanner"; -import { hostName, hostStatusText } from "./host-status"; +import { hostName } from "./host-status"; import { clearDraft } from "@/lib/draft-store"; import { useNotifications } from "@/hooks/useNotifications"; import { @@ -129,11 +128,17 @@ export function AppShell({ appName }: { appName: string }) { const isMobile = useIsMobile(); const isCompactOverlay = useIsCompactOverlay(); const [selectedSession, setSelectedSession] = useState(null); - // When user clicks +, we only store the cwd — no fake session id + // The transient identity belongs to one intentional new chat, not one request attempt. const [newSessionCwd, setNewSessionCwd] = useState(null); // Host of newSessionCwd; undefined is this machine. Every host-aware state // here uses that form (see remoteHostId). const [newSessionHostId, setNewSessionHostId] = useState(undefined); + const [newSessionCreation, setNewSessionCreation] = useState<{ id?: string; initialization?: string }>({}); + const newSessionCreationId = newSessionCreation.id; + const handleNewSessionInitialization = useCallback((initialization: string) => { + setNewSessionCreation((current) => current.id === newSessionCreationId && current.initialization === undefined ? { ...current, initialization } : current); + }, [newSessionCreationId]); + const [newSessionPoolProject, setNewSessionPoolProject] = useState(null); const [workspaceOptions, setWorkspaceOptions] = useState<{ projects: ManagedProject[]; selectedProject: string | null; cwd: string | null; hostId: string }>({ projects: [], selectedProject: null, cwd: null, hostId: LOCAL_HOST_ID }); const [addProjectOpen, setAddProjectOpen] = useState(false); const [addProjectHostId, setAddProjectHostId] = useState(LOCAL_HOST_ID); @@ -141,7 +146,7 @@ export function AppShell({ appName }: { appName: string }) { setAddProjectHostId(hostId); setAddProjectOpen(open); }, []); - const { hosts } = useHostRows(); + const { hosts, pools, poolsLoaded } = useHostRows(); const handleWorkspaceOptionsChange = useCallback((projects: ManagedProject[], selectedProject: string | null, cwd: string | null, hostId: string) => { setWorkspaceOptions({ projects, selectedProject, cwd, hostId }); }, []); @@ -1090,6 +1095,7 @@ export function AppShell({ appName }: { appName: string }) { const initialSessionId = initialNavigation.sessionId; const [activeCwd, setActiveCwd] = useState(null); const [activeHostId, setActiveHostId] = useState(undefined); + const [activePoolProject, setActivePoolProject] = useState(null); // Owned by the sidebar; rendered by the file panel's Worktrees tab. const [worktreeCtx, setWorktreeCtx] = useState(null); // True once the initial ?session= URL param has been resolved (or confirmed absent) @@ -1139,11 +1145,30 @@ export function AppShell({ appName }: { appName: string }) { return () => controller.abort(); }, [initialNavigation]); - const handleCwdChange = useCallback((cwd: string | null, projectRoot: string | null, hostId: string) => { - setActiveCwd(cwd); - setActiveHostId(remoteHostId(hostId)); - // Skip if cwd is null (initial mount) or during the initial URL restore. + const handleCwdChange = useCallback((cwd: string | null, projectRoot: string | null, hostId: string, project?: ManagedProject) => { + setActivePoolProject(project?.poolId ? project : null); + setActiveCwd(project?.poolId ? null : cwd); + setActiveHostId(project?.poolId ? undefined : remoteHostId(hostId)); + if (project?.poolId) { + if (selectedSession?.poolId === project.poolId && selectedSession.projectId === project.projectId) return; + if (newSessionPoolProject?.poolId === project.poolId && newSessionPoolProject.projectId === project.projectId) return; + setNewSessionPoolProject(project); + setNewSessionCreation({ id: crypto.randomUUID() }); + setNewSessionCwd(null); + setNewSessionHostId(undefined); + setSelectedSession(null); + setSessionKey((key) => key + 1); + setBranchTree([]); + setBranchActiveLeafId(null); + setSystemPrompt(null); + setSystemPromptLoading(false); + setActiveTopPanel(null); + router.replace("/"); + return; + } + // A standalone path is never a fallback for a pending pool placement. if (!cwd) return; + setNewSessionPoolProject(null); // Skip only when the notification matches the cwd we're suppressing for. if (suppressCwdRef.current !== null && suppressCwdRef.current === cwd) { suppressCwdRef.current = null; @@ -1168,6 +1193,7 @@ export function AppShell({ appName }: { appName: string }) { return prev; }); setNewSessionHostId(remoteHostId(hostId)); + setNewSessionCreation({ id: crypto.randomUUID() }); setSessionKey((k) => k + 1); setBranchTree([]); setBranchActiveLeafId(null); @@ -1175,7 +1201,7 @@ export function AppShell({ appName }: { appName: string }) { setSystemPromptLoading(false); setActiveTopPanel(null); router.replace("/"); - }, [router, selectedSession]); + }, [router, selectedSession, newSessionPoolProject]); const handleSelectSession = useCallback((session: SessionInfo, isRestore = false) => { // Re-picking the already-open session (sidebar double-click, palette @@ -1190,6 +1216,7 @@ export function AppShell({ appName }: { appName: string }) { } if (!isRestore && session.id === selectedSession?.id) return; setNewSessionCwd(null); + setNewSessionPoolProject(null); setSelectedSession(session); setSessionKey((k) => k + 1); setSystemPrompt(null); @@ -1209,11 +1236,14 @@ export function AppShell({ appName }: { appName: string }) { } }, [router, isMobile, selectedSession?.id]); - const handleNewSession = useCallback((_sessionId: string, cwd: string | null, hostId?: string) => { + const handleNewSession = useCallback((creationId: string, cwd: string | null, hostId?: string, project?: ManagedProject, initialization?: string) => { setSettingsTab(null); setSelectedSession(null); - setNewSessionCwd(cwd); - setNewSessionHostId(remoteHostId(hostId)); + const target = project ?? (cwd === activeCwd ? activePoolProject : null); + setNewSessionCreation({ id: creationId || crypto.randomUUID(), initialization }); + setNewSessionPoolProject(target?.poolId ? target : null); + setNewSessionCwd(target?.poolId ? null : cwd); + setNewSessionHostId(target?.poolId ? undefined : remoteHostId(hostId)); setSessionKey((k) => k + 1); setBranchTree([]); setBranchActiveLeafId(null); @@ -1225,7 +1255,7 @@ export function AppShell({ appName }: { appName: string }) { requestAnimationFrame(() => chatInputRef.current?.focus()); } router.replace("/"); - }, [router, isMobile]); + }, [router, isMobile, activeCwd, activePoolProject]); // ---- In-app Navigate back / forward over visited chat views ---- // Own stack, not the browser History API (that one belongs to the mobile @@ -1249,8 +1279,11 @@ export function AppShell({ appName }: { appName: string }) { sessionId: navSessionId, cwd: navSessionId ? navSessionCwd : newSessionCwd, ...(!navSessionId && newSessionHostId ? { hostId: newSessionHostId } : {}), + ...(!navSessionId && newSessionPoolProject ? { poolId: newSessionPoolProject.poolId, projectId: newSessionPoolProject.projectId } : {}), + ...(!navSessionId ? { creationId: newSessionCreationId } : {}), + ...(!navSessionId && newSessionPoolProject && newSessionCreation.initialization ? { initialization: newSessionCreation.initialization } : {}), }); - }, [navSessionId, navSessionCwd, newSessionCwd, newSessionHostId, recordNavigationView]); + }, [navSessionId, navSessionCwd, newSessionCwd, newSessionHostId, newSessionPoolProject, newSessionCreation, newSessionCreationId, recordNavigationView]); // Resolves a history entry's session id against the live list. `null` // means the id is gone (entry should be dropped); "unavailable" means the @@ -1278,7 +1311,9 @@ export function AppShell({ appName }: { appName: string }) { if (entry.sessionId === null) { if (direction === -1) navigationHistory.commitBack(); else navigationHistory.commitForward(); - handleNewSession("navigate-history", entry.cwd, entry.hostId); + const project = entry.poolId ? workspaceOptions.projects.find((candidate) => candidate.poolId === entry.poolId && candidate.projectId === entry.projectId) : undefined; + if (entry.poolId && !project) { toast.error(translate("errors.generic")); return; } + handleNewSession(entry.creationId ?? crypto.randomUUID(), entry.cwd, entry.hostId, project, entry.initialization); return; } const versionAtPress = navViewVersionRef.current; @@ -1294,7 +1329,7 @@ export function AppShell({ appName }: { appName: string }) { if (direction === -1) navigationHistory.dropPeekedBack(); else navigationHistory.dropPeekedForward(); } - }, [navigationHistory, peekNavigationBack, peekNavigationForward, fetchSessionForNavigation, handleNewSession, handleSelectSession]); + }, [navigationHistory, peekNavigationBack, peekNavigationForward, fetchSessionForNavigation, handleNewSession, handleSelectSession, workspaceOptions.projects]); // Shared by the sidebar buttons and the global shortcuts. The keyboard // layer always swallows the keystroke, so both directions stop dead at the @@ -1321,10 +1356,10 @@ export function AppShell({ appName }: { appName: string }) { // Global keyboard shortcuts (handles Esc, Ctrl+Alt+N etc.) useGlobalKeyboardShortcuts({ - onNewSession: (cwd: string) => handleNewSession(`kb-${Date.now()}`, cwd, activeHostId), + onNewSession: (cwd: string) => handleNewSession(crypto.randomUUID(), activePoolProject ? null : cwd, activeHostId, activePoolProject ?? undefined), onNavigateBack: handleNavigateBack, onNavigateForward: handleNavigateForward, - activeCwd, + activeCwd: activePoolProject ? projectIdentity(activePoolProject) : activeCwd, scopeNativeSelectAll, }); @@ -1346,6 +1381,7 @@ export function AppShell({ appName }: { appName: string }) { // Called by ChatWindow when a new session gets its real id from pi const handleSessionCreated = useCallback((session: SessionInfo) => { setNewSessionCwd(null); + setNewSessionPoolProject(null); setSelectedSession(session); setRefreshKey((k) => k + 1); hydrateSelectedSession(session.id); @@ -1444,6 +1480,7 @@ export function AppShell({ appName }: { appName: string }) { setRefreshKey((k) => k + 1); setSessionKey((k) => k + 1); setNewSessionCwd(null); + setNewSessionPoolProject(null); setSelectedSession((prev) => ({ ...(prev ?? { path: "", cwd: "", created: "", modified: "", messageCount: 0, firstMessage: "" }), id: newSessionId, @@ -1463,7 +1500,10 @@ export function AppShell({ appName }: { appName: string }) { if (selectedSession?.id === sessionId) { const cwd = selectedSession.cwd; setSelectedSession(null); - setNewSessionCwd(cwd ?? null); + setNewSessionCwd(selectedSession.poolId ? null : cwd ?? null); + setNewSessionCreation({ id: crypto.randomUUID() }); + setNewSessionPoolProject(selectedSession.poolId ? workspaceOptions.projects.find((project) => project.poolId === selectedSession.poolId && project.projectId === selectedSession.projectId) ?? null : null); + setNewSessionHostId(remoteHostId(selectedSession.hostId)); setSessionKey((k) => k + 1); setBranchTree([]); setBranchActiveLeafId(null); @@ -1471,7 +1511,7 @@ export function AppShell({ appName }: { appName: string }) { setActiveTopPanel(null); router.replace("/"); } - }, [selectedSession, router]); + }, [selectedSession, router, workspaceOptions.projects]); const handleInitialRestoreDone = useCallback(() => { setInitialSessionRestored(true); }, []); @@ -1533,14 +1573,10 @@ export function AppShell({ appName }: { appName: string }) { const absolute = filePath.startsWith("/") || filePath.startsWith("~/") || filePath.startsWith("\\\\") || /^[a-zA-Z]:[\\/]/.test(filePath); const rooted = !absolute && source.cwd ? joinFilePath(source.cwd, filePath) : filePath; const target = filePath.startsWith("~/") ? filePath : normalizeLocalPath(rooted); - const tabId = `file:${hostProjectKey(source.hostId, target)}`; - setFileTabs((prev) => { - const existing = prev.find((tab) => tab.id === tabId); - const sourceSessionId = source.sessionId ?? existing?.sourceSessionId; - if (!existing) return [...prev, { id: tabId, label: fileName, filePath: target, hostId: source.hostId, sourceCwd: source.cwd, sourceSessionId }]; - if (existing.sourceSessionId === sourceSessionId && existing.sourceCwd === source.cwd) return prev; - return prev.map((tab) => tab.id === tabId ? { ...tab, sourceSessionId, sourceCwd: source.cwd } : tab); - }); + const tabId = `file:${source.sessionId ?? hostProjectKey(source.hostId, source.cwd ?? "")}:${target}`; + setFileTabs((prev) => prev.some((tab) => tab.id === tabId) + ? prev + : [...prev, { id: tabId, label: fileName, filePath: target, hostId: source.hostId, sourceCwd: source.cwd, sourceSessionId: source.sessionId }]); setActiveFileTabId(tabId); setRightView("file"); setRightPanelOpen(true); @@ -1653,15 +1689,17 @@ export function AppShell({ appName }: { appName: string }) { const remoteHost = currentHostId !== undefined; const workspaceHostId = currentHostId ?? LOCAL_HOST_ID; const sidebarCwd = (activeHostId ?? LOCAL_HOST_ID) === workspaceHostId ? activeCwd : null; - const explorerCwd = selectedSession ? (sessionWorktreeRemoved ? sidebarCwd : sessionCwd) : newSessionCwd ?? sidebarCwd; + const explorerCwd = selectedSession + ? (sessionWorktreeRemoved ? sidebarCwd : sessionCwd) + : newSessionPoolProject || activePoolProject ? null : newSessionCwd ?? sidebarCwd; // File-panel integrations: every action works on the active tab so the right // panel behaves like an editor toolbar, not just a tab strip. const handleMentionActiveFile = useCallback(() => { - if (!activeFileTab) return; + if (!activeFileTab || activeFileTab.sourceSessionId !== (selectedSession?.id ?? null)) return; if (activeFileTab.hostId !== workspaceHostId) { toast.info(t("hosts.fileOtherHost")); return; } - handleAtMention(getRelativeFilePath(activeFileTab.filePath, explorerCwd ?? undefined), false); - }, [activeFileTab, explorerCwd, handleAtMention, workspaceHostId, t]); + handleAtMention(getRelativeFilePath(activeFileTab.filePath, activeFileTab.sourceCwd ?? undefined), false); + }, [activeFileTab, selectedSession?.id, handleAtMention, workspaceHostId, t]); const handleCopyActiveFilePath = useCallback(() => { if (!activeFileTab) return; @@ -1683,11 +1721,15 @@ export function AppShell({ appName }: { appName: string }) { }, [activeFileTab]); const handleRevealActiveFile = useCallback(() => { if (!activeFileTab) return; + if (activeFileTab.sourceSessionId !== (selectedSession?.id ?? null)) { + toast.info(t("appShell.revealSourceSession")); + return; + } if (activeFileTab.hostId !== workspaceHostId) { toast.info(t("hosts.fileOtherHost")); return; } setRevealTarget({ path: activeFileTab.filePath, hostId: activeFileTab.hostId }); setRightView("explorer"); setRightPanelOpen(true); - }, [activeFileTab, workspaceHostId, t]); + }, [activeFileTab, selectedSession?.id, workspaceHostId, t]); const handleSelectFileTab = useCallback((tabId: string) => { setActiveFileTabId(tabId); @@ -1728,14 +1770,17 @@ export function AppShell({ appName }: { appName: string }) { }, [selectedSession]); // Show chat area if a session is selected, or if we have a cwd to start a new session in - const effectiveNewSessionCwd = newSessionCwd ?? (selectedSession === null && activeCwd ? activeCwd : null); - const newSessionHost = newSessionCwd !== null ? newSessionHostId : activeHostId; - const newSessionHostKey = newSessionHost ?? LOCAL_HOST_ID; - const newSessionProject = (workspaceOptions.cwd === effectiveNewSessionCwd && workspaceOptions.hostId === newSessionHostKey ? workspaceOptions.selectedProject : null) ?? effectiveNewSessionCwd ?? ""; - const hostProjects = workspaceOptions.projects.filter((project) => (project.hostId ?? LOCAL_HOST_ID) === newSessionHostKey); + const effectivePoolProject = selectedSession ? null : newSessionPoolProject ?? activePoolProject; + const effectiveNewSessionCwd = effectivePoolProject ? null : newSessionCwd ?? (selectedSession === null && activeCwd ? activeCwd : null); + 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); + 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; const settingsHostId = activeCwd ? activeHostId : currentHostId; - const showChat = selectedSession !== null || effectiveNewSessionCwd !== null; + const showChat = selectedSession !== null || effectiveNewSessionCwd !== null || effectivePoolProject !== null; const currentRate = generationSpeed?.current; const rate = currentRate ?? generationSpeed?.average; const speed = showChat ? formatGenerationSpeed(rate) : null; @@ -1860,6 +1905,7 @@ export function AppShell({ appName }: { appName: string }) { onSessionDeleted={handleSessionDeleted} selectedCwd={selectedSession?.cwd ?? newSessionCwd ?? null} selectedHostId={selectedSession ? selectedSession.hostId ?? LOCAL_HOST_ID : newSessionHostId ?? LOCAL_HOST_ID} + selectedLogicalProjectKey={selectedSession?.poolId ? selectedSession.projectKey : effectivePoolProject ? projectIdentity(effectivePoolProject) : null} onCwdChange={handleCwdChange} onWorkspaceOptionsChange={handleWorkspaceOptionsChange} onWorktreeContextChange={setWorktreeCtx} @@ -1914,8 +1960,8 @@ export function AppShell({ appName }: { appName: string }) { // An empty cwd is truthy, so showChat would render the shell while // useAgentSession refuses to start — every send a silent no-op. // Fall back to the server's default cwd (~/omp-cwd-) instead. - if (activeCwd) { - handleNewSession(`palette-${Date.now()}`, activeCwd, activeHostId); + if (activeCwd || activePoolProject) { + handleNewSession(crypto.randomUUID(), activeCwd, activeHostId, activePoolProject ?? undefined); return; } const targetHost = currentHostId ?? LOCAL_HOST_ID; @@ -1929,7 +1975,7 @@ export function AppShell({ appName }: { appName: string }) { }) .then((data) => { if (!data.cwd) throw new Error("Empty cwd returned"); - if (navViewVersionRef.current === sourceVersion) handleNewSession(`palette-${Date.now()}`, data.cwd, targetHost); + if (navViewVersionRef.current === sourceVersion) handleNewSession(crypto.randomUUID(), data.cwd, targetHost); }) .catch(() => toast.error(translate("errors.generic"))); }} @@ -2479,11 +2525,16 @@ export function AppShell({ appName }: { appName: string }) { session={selectedSession} newSessionCwd={effectiveNewSessionCwd} newSessionHostId={newSessionHost} + newSessionCreationId={effectivePoolProject ? newSessionCreationId : undefined} + newSessionPoolId={effectivePoolProject?.poolId} + newSessionProjectId={effectivePoolProject?.projectId} + newSessionInitialization={effectivePoolProject ? newSessionCreation.initialization : undefined} + onNewSessionInitialization={handleNewSessionInitialization} hostStatus={chatHost?.status} hostLabel={chatHost ? hostName(t, chatHost) : undefined} - newSessionWorkspace={effectiveNewSessionCwd && ( + newSessionWorkspace={(effectiveNewSessionCwd || effectivePoolProject) && (
- {hosts && hosts.length > 1 && ( + {creationTargets.length > 1 && ( <>
@@ -2528,32 +2576,26 @@ export function AppShell({ appName }: { appName: string }) {