Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -454,11 +454,13 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri
always before this machine, for `new_session` and `send_to_session` alike.
- **Not yet remote:** Explorer, Git, Worktrees, the Skills/Plugins/Agents/MCP
settings tabs and directory browsing show "Not available on remote hosts
yet". Sub-projects 2 and 3 of the spec add ops for them.
yet". Archive is refused for a remote session (501 `remote_unavailable`, the
menu item disabled): the Archived Sessions browser reads this machine's archive
only, so it could not be restored. Sub-projects 2 and 3 of the spec add ops for them.

#### Local daemon (`docs/specs/2026-10-29-local-daemon-design.md`)
- **Two services.** `ompweb` (web) and `ompweb-host` (`ompweb host`, the daemon) are installed together by `ompweb systemd install`, `ompweb launchd install` and the Windows tray install; uninstall removes both, `ompweb systemd restart` restarts the web unit only. The daemon owns this machine's omp children, so a web restart, update or redeploy leaves runs going; restarting the daemon ends them (auto-resume then resumes the sessions that were running). An upgrade restarts the daemon only when the running daemon's link version is outside the new release's `[MIN_LINK_PROTOCOL_VERSION, LINK_PROTOCOL_VERSION]` range (it would get 426 and exit); a daemon inside the range keeps running.
- **Local link bootstrap** (`lib/hosts/local-bootstrap.ts`, called from `instrumentation.node.ts`). `localLinkUrl()` builds the daemon's URL from `OMP_WEB_PORT`/`OMP_WEB_HOSTNAME` (set by the `ompweb` launcher; wildcard binds map to `127.0.0.1`, a non-loopback bind gets no link and a console warning). `ensureLocalHostLink()` makes sure the `local` record exists (`registry.ts`, `rotateLocalHostToken`) and writes `<agent dir>/omp-web/host.json` (`{url, token}`, 0600). A `host.json` whose token the registry still accepts and whose url matches is left alone, so a web restart does not make the daemon redial. It throws, and startup only logs, when `host.json` points to a non-loopback server (a remote-host login on this machine): it is never overwritten. The daemon re-reads `host.json` when its link gets 401 and exits only if the file still holds the rejected token.
- **Local link bootstrap** (`lib/hosts/local-bootstrap.ts`, called from `instrumentation.node.ts`). `localLinkUrl()` builds the daemon's URL from `OMP_WEB_PORT`/`OMP_WEB_HOSTNAME` (set by `startProduction` from its listen address, so the launcher, the binary and `npm start` all link; wildcard binds map to `127.0.0.1`, a non-loopback bind gets no link and a console warning). `ensureLocalHostLink()` makes sure the `local` record exists (`registry.ts`, `rotateLocalHostToken`) and writes `<agent dir>/omp-web/host.json` (`{url, token}`, 0600). A `host.json` whose token the registry still accepts and whose url matches is left alone, so a web restart does not make the daemon redial. It throws, and startup only logs, when `host.json` points to a non-loopback server (a remote-host login on this machine): it is never overwritten. The daemon re-reads `host.json` when its link gets 401 and exits only if the file still holds the rejected token.
- **Dev mode does not take the daemon.** With `NODE_ENV=development` `ensureLocalHostLink` is skipped, so the daemon stays linked to production and the dev server shows "This machine" offline. The local row of `GET /api/hosts` carries `daemonManaged: false` there, which hides the install banner.
- **`local` is a registry record like any host**, with three exceptions: it is listed first, `PATCH` takes `label` only (`allowAgentStart` is fixed), and it cannot be revoked. Renaming "This machine" is a `PATCH /api/hosts {id: "local", label}`; an empty label resets it (`registry.ts` stores `""`; `customLocalLabel()` / `DEFAULT_LOCAL_LABEL` map it). `getHost("local")` works without the record: it is the daemon link, offline while none is linked, and "needs upgrade" on a protocol mismatch (`hostVersion` in the row is the daemon's).
- **Adoption on hello** (`reattach`/`adopt` in `hub.ts`, `adoptRpcSession` in `rpc-manager.ts`). Each listed `{ch, sessionId, cwd, pending}` channel that has no transport on this server is a child of a previous server and is taken over by a new `AgentSessionWrapper` (`adopted: true`, `RpcProcess` option `adopted`). There is no session-list lookup: the spawn `cwd` comes from the hello, and the session identity from the child's own `get_state` (`applyIdentity`), so a new session whose file is not written yet is adoptable. The daemon names each child's current session in the hello (`PendingRequests.sessionId`: the file's header id at spawn, then the last successful `get_state`). Re-sync (`AgentSessionWrapper.adopt`): `negotiate_protocol`, `set_subagent_subscription`, `set_ask_dialog`, `get_state`, `get_subagents`, `get_btw_history`, then `replay` of the `pending` lines and `release` of the frames held meanwhile. Every command is bounded by `GET_STATE_TIMEOUT_MS`.
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -488,9 +488,9 @@ Notes:
whoever controls the ompweb server or the token. Keep the token private and
revoke it when a machine is retired.
- **Not available on remote hosts yet:** the file explorer, Git and worktree
panels, directory browsing, and the Skills, Plugins, Agents and MCP settings only
work on the machine ompweb runs on. Chat, session history, notifications and
starting sessions work on every host.
panels, directory browsing, archiving sessions, and the Skills, Plugins, Agents
and MCP settings only work on the machine ompweb runs on. Chat, session history,
notifications and starting sessions work on every host.
- **Agent-started sessions:** with agent tools enabled, an agent can pass a `host`
to `new_session` (it defaults to the agent's own host). A remote host asks for
confirmation each time unless **Agents can start sessions here without asking**
Expand Down
6 changes: 6 additions & 0 deletions app/api/sessions/[id]/archive/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { apiErrorResponse, hostOfflineResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils";
import { HostOpError } from "@/lib/hosts/link-protocol";
import { invalidateHostSessionList } from "@/lib/hosts/session-index";
import { LOCAL_HOST_ID } from "@/lib/hosts/registry";
import { clearExitedRpcSession, getRpcSession } from "@/lib/rpc-manager";

/** POST /api/sessions/[id]/archive — stop the live child, then archive the
Expand All @@ -13,6 +14,11 @@ export async function POST(
try {
const resolved = await resolveSessionHostOr404(id);
if ("response" in resolved) return resolved.response;
// The archive browser (/api/sessions/archive) reads this machine's archive only: a remote session archived on
// its host would vanish from the sidebar with no way to restore it.
if (resolved.host.id !== LOCAL_HOST_ID) {
return Response.json({ error: "Not available on remote hosts yet", code: "remote_unavailable" }, { status: 501 });
}
const { sessionOps } = resolved.host;
// Parent-session paths are native branch metadata. Moving only a parent
// would leave active children pointing at a path that no longer exists,
Expand Down
6 changes: 5 additions & 1 deletion components/SessionSidebar-rows.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { ConfirmDialog } from "./ui/field";
import { copyText } from "@/lib/clipboard";
import { transcriptToMarkdown } from "@/lib/transcript";
import { toast } from "./ui/toast";
import { remoteHostId } from "@/lib/project-ordering";
import {
MAX_PROJECT_SESSIONS,
formatRelativeTime,
Expand Down Expand Up @@ -719,6 +720,9 @@ const SessionItem = memo(function SessionItem({
toast.error(t("sessionSidebar.archiveFailed"));
}
}, [session.id, onDeleted, t]);
// The Archived Sessions browser lists this machine's archive only, so a remote archive could not be restored.
const archiveBlocked = hasChildren || remoteHostId(session.hostId) !== undefined;
const archiveTitle = hasChildren ? t("sessionSidebar.archiveLeafOnly") : archiveBlocked ? t("hosts.notAvailableRemote") : t("sessionSidebar.archive");

const handleDelete = useCallback(async () => {
if (deleting) return;
Expand Down Expand Up @@ -834,7 +838,7 @@ const SessionItem = memo(function SessionItem({
<MoreHorizontal size={14} strokeWidth={2} aria-hidden="true" />
</button>
<SidebarPortalMenu anchor={menuButtonRef} open={actionMenuOpen} onClose={() => setActionMenuOpen(false)} placement="below" minWidth={128}>
<button type="button" role="menuitem" className="sidebar-menu-item" onClick={(event) => { event.stopPropagation(); setActionMenuOpen(false); void handleArchive(); }} disabled={hasChildren} title={hasChildren ? t("sessionSidebar.archiveLeafOnly") : t("sessionSidebar.archive")} style={{ display: "block", width: "100%", padding: "6px 9px", border: "none", borderRadius: 6, background: "transparent", color: hasChildren ? "var(--text-dim)" : "var(--text-muted)", cursor: hasChildren ? "not-allowed" : "pointer", textAlign: "left", fontSize: 11, opacity: hasChildren ? 0.55 : 1 }}>{t("sessionSidebar.archive")}</button>
<button type="button" role="menuitem" className="sidebar-menu-item" onClick={(event) => { event.stopPropagation(); setActionMenuOpen(false); void handleArchive(); }} disabled={archiveBlocked} title={archiveTitle} style={{ display: "block", width: "100%", padding: "6px 9px", border: "none", borderRadius: 6, background: "transparent", color: archiveBlocked ? "var(--text-dim)" : "var(--text-muted)", cursor: archiveBlocked ? "not-allowed" : "pointer", textAlign: "left", fontSize: 11, opacity: archiveBlocked ? 0.55 : 1 }}>{t("sessionSidebar.archive")}</button>
<button type="button" role="menuitem" className="sidebar-menu-item" onClick={(event) => { startRename(event); setActionMenuOpen(false); }} style={{ display: "block", width: "100%", padding: "6px 9px", border: "none", borderRadius: 6, background: "transparent", color: "var(--text-muted)", cursor: "pointer", textAlign: "left", fontSize: 11 }}>{t("sessionSidebar.rename")}</button>
<button type="button" role="menuitem" className="sidebar-menu-item" onClick={(event) => { event.stopPropagation(); setActionMenuOpen(false); void handleCopyTranscript(); }} disabled={copyingTranscript} style={{ display: "block", width: "100%", padding: "6px 9px", border: "none", borderRadius: 6, background: "transparent", color: "var(--text-muted)", cursor: copyingTranscript ? "default" : "pointer", textAlign: "left", fontSize: 11, opacity: copyingTranscript ? 0.55 : 1 }}>{t("sessionSidebar.copyTranscript")}</button>
<button type="button" role="menuitem" className="sidebar-menu-item" disabled={deleting} onClick={(event) => { event.stopPropagation(); setActionMenuOpen(false); setConfirmDelete(true); }} style={{ display: "block", width: "100%", padding: "6px 9px", border: "none", borderRadius: 6, background: "transparent", color: "var(--status-error)", cursor: "pointer", textAlign: "left", fontSize: 11 }}>{t("sessionSidebar.delete")}</button>
Expand Down
2 changes: 1 addition & 1 deletion lib/hosts/local-bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { hostForToken, LOCAL_HOST_ID, rotateLocalHostToken } from "./registry";
/** Where the daemon dials this server, or why it cannot: the daemon uses plain http only on loopback, so a bind address elsewhere gets no link. */
export function localLinkUrl(env: NodeJS.ProcessEnv = process.env): { url: string } | { skip: string } {
const port = env.OMP_WEB_PORT;
if (!port) return { skip: "OMP_WEB_PORT is not set (start through the ompweb launcher)" };
if (!port) return { skip: "OMP_WEB_PORT is not set (the dev server does not link the daemon)" };
const bind = env.OMP_WEB_HOSTNAME || "127.0.0.1";
// A wildcard bind also answers on 127.0.0.1; "localhost" is dialed by name, so it matches whichever family the server bound.
const host = ["0.0.0.0", "::", "[::]"].includes(bind) ? "127.0.0.1" : bind === "::1" ? "[::1]" : bind;
Expand Down
25 changes: 24 additions & 1 deletion lib/omp/rpc-process-runtime.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ test("a response naming another command does not settle a command with its id",
const unsolicited = [];
proc.onFrame((frame) => unsolicited.push(frame.command));
transport.answer = (command) => {
// An adopted RpcProcess numbers from w1 again: the old server's late answer to its own w1 arrives first.
// A late answer naming another command, with this command's id, arrives first.
transport.send({ type: "response", id: command.id, command: "prompt", success: false, error: "stale" });
transport.send({ type: "response", id: command.id, command: command.type, success: true, data: { sessionId: "s" } });
};
Expand All @@ -385,6 +385,29 @@ test("a response naming another command does not settle a command with its id",
await proc.dispose(0);
});

test("a late answer to the previous server's command of the same type does not settle an adopted process's command", async () => {
// The previous server's process sent get_state and stopped before the child answered.
const before = makeAdoptedTransport([]);
const previous = new RpcProcess({ cwd: process.cwd(), transport: before, adopted: { protocolVersion: 2 } });
previous.release();
let staleId;
before.answer = (command) => { staleId = command.id; };
void previous.sendCommand({ type: "get_state" }).catch(() => {});
await previous.dispose(0);
assert.ok(staleId, "the previous process sent its get_state");

const transport = makeAdoptedTransport([]);
const proc = new RpcProcess({ cwd: process.cwd(), transport, adopted: { protocolVersion: 2 } });
proc.release();
transport.answer = (command) => {
assert.notEqual(command.id, staleId);
transport.send({ type: "response", id: staleId, command: "get_state", success: true, data: { sessionId: "stale" } });
transport.send({ type: "response", id: command.id, command: command.type, success: true, data: { sessionId: "s" } });
};
assert.deepEqual(await proc.sendCommand({ type: "get_state" }, 1_000), { sessionId: "s" });
await proc.dispose(0);
});

test("an adopted RpcProcess whose output outgrows the hold cap fails its commands and its replay", async () => {
const { LINK_LIMITS } = await import("../hosts/link-protocol.ts");
const saved = LINK_LIMITS.channelBufferBytes;
Expand Down
7 changes: 5 additions & 2 deletions lib/omp/rpc-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ export class RpcProcess {
/** Ids of the requests `replay` delivered (see `release`). */
private readonly replayedRequests = new Set<string>();
private nextId = 1;
// An adopted child may still answer the previous server's commands; a fresh prefix per process keeps those
// late answers from settling this process's commands with the same number.
private readonly idPrefix = `w${crypto.randomUUID().slice(0, 8)}-`;
private stderrTail = "";
private exited = false;
private exitInfo: { code: number | null; signal: NodeJS.Signals | null } | null = null;
Expand Down Expand Up @@ -337,7 +340,7 @@ export class RpcProcess {
}
if (this.heldOverflow) return Promise.reject(this.heldOverflow);
const dispatchedAt = Date.now();
const id = `w${this.nextId++}`;
const id = `${this.idPrefix}${this.nextId++}`;
return new Promise<T>((resolve, reject) => {
const entry: PendingCommand = {
command: command.type,
Expand Down Expand Up @@ -406,7 +409,7 @@ export class RpcProcess {
private handleResponse(response: RpcResponseFrame): void {
const id = response.id;
const entry = id ? this.pending.get(id) : undefined;
// An adopted child numbers from w1 again: a late answer to the old server's command of another type is not this one's.
// A late answer naming another command is not this one's either (defense beside the per-process id prefix).
if (!entry || !id || (response.command && response.command !== entry.command)) {
// Unsolicited response (or a command we already timed out) — surface to
// frame listeners so nothing is silently dropped.
Expand Down
3 changes: 3 additions & 0 deletions server/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,9 @@ export async function startProduction(listen: { port: number; hostname: string }
console.error(`Port ${listen.port} on ${listen.hostname} is already in use: is ompweb already running? Otherwise stop the process using it or start ompweb with --port ${listen.port + 1}.`);
process.exit(1);
}
// The local daemon link (local-bootstrap.ts, run by register) and the update worker dial this address; set it here
// so `npm start` (server/main.ts) links the daemon like the launcher and the binary do.
Object.assign(process.env, { OMP_WEB_PORT: String(server.port), OMP_WEB_HOSTNAME: listen.hostname });
await register();
console.log(`[omp-web] Ready on ${server.url.origin}`);
return server;
Expand Down
4 changes: 1 addition & 3 deletions server/binary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,7 @@ if (!existsSync(path.join(root, "dist", "index.html"))) {
process.exit(1);
}
const { hostname, port } = options;
// What the npm launcher hands its server: the local daemon link (instrumentation.node.ts) dials this address.
Object.assign(process.env, { OMP_WEB_PORT: port, OMP_WEB_HOSTNAME: hostname });
// Loaded after the environment above is set, for the modules that read it when they load.
// Loaded after OMP_WEB_PACKAGE_DIR is set above, for the modules that read it when they load.
const { startProduction } = await import("./app");
await startProduction({ port: Number(port), hostname });
const { entries, hint } = getAccessibleAddresses({ hostname, port });
Expand Down
Loading