From 7826ff5416852d3f8695282a2c57f358061b4108 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:26:48 +0000 Subject: [PATCH 01/45] fix(windows): let in-app updates replace an npm-global install Port of ompweb-dev/ompweb#519. --- lib/hosts/update-worker.ts | 5 +- lib/hosts/update-worker.windows.test.mjs | 15 ++ lib/self-update.test.mjs | 8 +- lib/self-update.ts | 21 +- lib/server-update-worker.test.mjs | 136 +++++++++++- lib/server-update-worker.ts | 65 +++++- lib/upgrade-process.ts | 218 ++++++++++++++++++- lib/upgrade-process.windows-service.test.mjs | 170 +++++++++++++++ 8 files changed, 606 insertions(+), 32 deletions(-) diff --git a/lib/hosts/update-worker.ts b/lib/hosts/update-worker.ts index 7d17da17..6948313f 100644 --- a/lib/hosts/update-worker.ts +++ b/lib/hosts/update-worker.ts @@ -2,7 +2,7 @@ import { createHash, randomUUID } from "node:crypto"; import { execFile } from "node:child_process"; import { chmodSync, closeSync, createReadStream, createWriteStream, existsSync, fstatSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, writeFileSync, writeSync } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { createGunzip, inflateRawSync } from "node:zlib"; import { pipeline } from "node:stream/promises"; @@ -446,7 +446,8 @@ export async function stagePackage(d: HostPackageSource, staging: string): Promi const windows = process.platform === "win32" && /\.(cmd|bat)$/i.test(command); // `/s /c` strips one outer pair of quotes; verbatim so Node does not escape the inner ones (as Node's `shell: true`). const line = [command, ...args].map((arg) => `"${arg.replaceAll('"', '')}"`).join(" "); - await exec(windows ? process.env.ComSpec || "cmd.exe" : command, windows ? ["/d", "/s", "/c", `"${line}"`] : args, { timeout: DOWNLOAD_TIMEOUT_MS, maxBuffer: 1024 * 1024, env: workerEnvironment(), windowsHide: true, windowsVerbatimArguments: windows }); + // Windows refuses to rename a directory that is any live process's working directory, including this install child. + await exec(windows ? process.env.ComSpec || "cmd.exe" : command, windows ? ["/d", "/s", "/c", `"${line}"`] : args, { cwd: tmpdir(), timeout: DOWNLOAD_TIMEOUT_MS, maxBuffer: 1024 * 1024, env: workerEnvironment(), windowsHide: true, windowsVerbatimArguments: windows }); const modules = join(prefix, "node_modules"); const packageDir = join(modules, "@ompweb-dev", "tau"); const metadata = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8")); diff --git a/lib/hosts/update-worker.windows.test.mjs b/lib/hosts/update-worker.windows.test.mjs index 48d19274..2a4de460 100644 --- a/lib/hosts/update-worker.windows.test.mjs +++ b/lib/hosts/update-worker.windows.test.mjs @@ -44,3 +44,18 @@ test("a slow Windows process inventory allows private installs but still refuses assert.equal(reason !== null, fixture.refused, String(fixture.output)); } }); + +test("the package install child does not inherit the installation as its working directory", async (t) => { + let cwd; + const execFile = () => { throw new Error("not promisified"); }; + execFile[promisify.custom] = (_command, _args, options) => { + cwd = options?.cwd; + return Promise.reject(new Error("stop after cwd")); + }; + await mockBuiltin(t, "node:child_process", { execFile }); + const { stagePackage } = await import("./update-worker.ts?fresh=install-cwd"); + const staging = mkdtempSync(join(tmpdir(), "stage-cwd-")); + t.after(() => rmSync(staging, { recursive: true, force: true })); + await assert.rejects(() => stagePackage({ version: "9.9.9", installMethod: "npm", managerPath: process.execPath }, staging), /stop after cwd/); + assert.equal(cwd, tmpdir()); +}); diff --git a/lib/self-update.test.mjs b/lib/self-update.test.mjs index 2f93fa43..2498f1c9 100644 --- a/lib/self-update.test.mjs +++ b/lib/self-update.test.mjs @@ -286,13 +286,15 @@ test("a commit stages and preflights the release before updating hosts, then lau // The launcher is the supervised process: its pid is inspected, and the restart goes through it with the listen address. assert.equal(inspections[0].pid, process.ppid); assert.deepEqual(inspections[0].launch.args.slice(1), ["-p", "30187", "-H", "127.0.0.1", "--no-open"]); - assert.equal(inspections[0].launch.cwd, installDir); + assert.equal(inspections[0].launch.cwd, realProcess.cwdOutsideInstall(installDir)); + assert.notEqual(inspections[0].launch.cwd, installDir); const [launch] = launches; const root = resolveSelfUpdateTempRoot(); const attemptDir = join(root, "attempts", attemptId); assert.equal(launch.command, process.execPath); assert.deepEqual(launch.args, [join(attemptDir, "worker.mjs"), "--server-update-descriptor", join(attemptDir, "descriptor.json")]); + assert.equal(launch.cwd, realProcess.installSpawnCwd()); assert.ok(existsSync(launch.args[0]), "the Node bundle of the worker is built before the cutover"); // Neither the web password hash nor launcher plumbing reaches the helper: it runs npm, candidate preflights and a daemon. assert.equal(launch.env.TAU_PASSWORD_HASH, undefined); @@ -302,6 +304,8 @@ test("a commit stages and preflights the release before updating hosts, then lau assert.ok(!descriptorText.includes("secret-hash")); const restartEnvironment = JSON.parse(readFileSync(join(attemptDir, "launch-env.json"), "utf8")); assert.equal(restartEnvironment.TAU_PASSWORD_HASH, "secret-hash"); + assert.equal(restartEnvironment.TAU_PACKAGE_DIR, installDir); + assert.notEqual(inspections[0].launch.cwd, installDir); assert.equal("TAU_LAUNCHER_PID" in restartEnvironment, false); const descriptor = JSON.parse(descriptorText); assert.equal(descriptor.installMethod, "npm"); @@ -514,7 +518,7 @@ test("resuming staged bytes under a different artifact approval never dispatches function writeRecoveryJob(attemptDir, attemptId, installDir) { writeFileSync(join(attemptDir, "job.json"), JSON.stringify({ attemptId, install: selfUpdate.resolveServerInstall(), - launch: { command: process.execPath, args: [join(installDir, "bin", "tau.js"), "-p", "30187", "-H", "127.0.0.1", "--no-open"], cwd: installDir }, + launch: { command: process.execPath, args: [join(installDir, "bin", "tau.js"), "-p", "30187", "-H", "127.0.0.1", "--no-open"], cwd: realProcess.cwdOutsideInstall(installDir) }, server: { pid: DEAD_PID, identity: "old", supervisor: { kind: "foreground" } }, })); } diff --git a/lib/self-update.ts b/lib/self-update.ts index a4ddae0f..4aba0bf5 100644 --- a/lib/self-update.ts +++ b/lib/self-update.ts @@ -17,7 +17,7 @@ import { atomicWrite, attemptsDir, ensureSecureRoot, isActiveLease, LEASE_MS, leasePath, markerPath, patchStatus, readStateJson, removeSecureEmptyDirectory, removeSecureFile, renewLease, resolveSelfUpdateTempRoot, secureDirectory, secureRegularFile, SelfUpdateError, statusPath, type SelfUpdateStatus, type StoredStatus, } from "./self-update-state"; -import { type UpgradeLaunch, assertUpgradeProcessControl, inspectUpgradeProcess, launchDetachedUpgrade, secureUpgradeDirectory } from "./upgrade-process"; +import { type UpgradeLaunch, assertUpgradeProcessControl, cwdOutsideInstall, inspectUpgradeProcess, installSpawnCwd, launchDetachedUpgrade, secureUpgradeDirectory } from "./upgrade-process"; import { approveUpgradePlan, getApprovedReleasePin, getUpgradePlan, prepareUpgradePlan, removeUpgradePlan, upgradePlannedHosts } from "./upgrade-plan"; import type { UpgradeApproval, UpgradePlan } from "./upgrade-types"; import { DISABLE_AUTOUPDATE_ENV_VAR, isUpdateDisabled } from "./update-policy"; @@ -338,15 +338,18 @@ function serverRestart(install: ServerInstall): { launch: Omit { +function restartEnvironment(installDir: string): Record { const env: Record = {}; for (const [name, value] of Object.entries(process.env)) if (value !== undefined && !PLUMBING_ENV.includes(name.toUpperCase())) env[name] = value; + // Direct `server/main.ts` has no launcher to name the install, and its cwd is outside it. + env.TAU_PACKAGE_DIR = installDir; return env; } /** The helper's environment: no web secrets (it runs npm, candidate preflights and a daemon), no launcher plumbing. */ @@ -414,12 +417,12 @@ async function workerLaunch(job: CommitJob, attemptDir: string, descriptor: stri chmodSync(target, 0o700); return target; }; - if (install.method === "binary") return { command: copyRuntime(process.execPath), args: ["server-update-worker", descriptor], cwd: attemptDir, env }; + if (install.method === "binary") return { command: copyRuntime(process.execPath), args: ["server-update-worker", descriptor], cwd: installSpawnCwd(), env }; const bundle = await Bun.build({ entrypoints: [fileURLToPath(new URL("./server-update-worker.ts", import.meta.url))], target: "node", format: "esm", outdir: attemptDir, naming: "worker.mjs" }); if (!bundle.success) throw new Error(`Could not build the update worker: ${bundle.logs.map(String).join("; ")}`); // A runtime inside the package (Windows locks a running .exe) would be replaced under the worker. const runtime = insideInstall(install.installDir, install.runtime) ? copyRuntime(install.runtime) : install.runtime; - return { command: runtime, args: [join(attemptDir, "worker.mjs"), "--server-update-descriptor", descriptor], cwd: attemptDir, env }; + return { command: runtime, args: [join(attemptDir, "worker.mjs"), "--server-update-descriptor", descriptor], cwd: installSpawnCwd(), env }; } /** After the commit returned: stage and preflight the release, update the plan's other hosts, then hand over to the detached worker. */ @@ -470,7 +473,7 @@ async function coordinate(job: CommitJob): Promise { interruptSessions: job.interruptSessions, }; atomicWrite(join(attemptDir, "descriptor.json"), JSON.stringify(descriptor)); - atomicWrite(join(attemptDir, "launch-env.json"), JSON.stringify(restartEnvironment())); + atomicWrite(join(attemptDir, "launch-env.json"), JSON.stringify(restartEnvironment(install.installDir))); const pid = await launchDetachedUpgrade(await workerLaunch(job, attemptDir, join(attemptDir, "descriptor.json"))); patchStatus(attemptId, { ...(pid === undefined ? {} : { workerPid: pid }), coordinatorPid: undefined }); } catch (error) { @@ -528,7 +531,7 @@ async function startSelfUpdate(attemptId: string, approval: UpgradeApproval, res const serverUrl = links.length === 1 ? links[0].replace(/\/+$/, "") : null; if (localHost.kind !== "separate" && !serverUrl) throw unsupported("The local host's link to this server could not be identified"); await controllable("The detached update worker cannot be started safely", () => - launchDetachedUpgrade({ command: process.execPath, args: ["--version"], cwd: install.installDir, env: helperEnvironment() })); + launchDetachedUpgrade({ command: process.execPath, args: ["--version"], cwd: installSpawnCwd(), env: helperEnvironment() })); // Unknown activity is not consent: only explicit Force permits interruption. const interruptSessions = confirmed.force && localHost.kind === "shared" && local !== null && (local.sessionProcesses !== 0 || local.activeTurns !== 0); diff --git a/lib/server-update-worker.test.mjs b/lib/server-update-worker.test.mjs index 6721b71e..c5f1fab8 100644 --- a/lib/server-update-worker.test.mjs +++ b/lib/server-update-worker.test.mjs @@ -150,6 +150,10 @@ function scenario(t, { method = "npm", localHost = { kind: "absent" }, hostArgs const entrypoint = method === "binary" ? join(installDir, "tau") : join(installDir, "bin", "tau-host.js"); return { pid: host.pid, version: host.version, protocol: 1, linked: host.linked, linkedServers: host.linkedServers, drained: host.drained, executable: method === "binary" ? entrypoint : process.execPath, entrypoint }; }, + // No tray and no process table: the real lookups are PowerShell/CIM queries on Windows that cost seconds each. + findTray: async () => null, + trayPids: async () => [], + releaseLocks: async () => {}, sharedInstall: async (dir, ignored, owned) => { ctx.sharedInstallCalls.push({ dir, ignored, owned }); return ctx.sharing; @@ -173,6 +177,7 @@ test("a package update replaces the installation, restarts it on the new release assert.deepEqual(ctx.calls.filter((call) => call.startsWith("stop") || call.startsWith("restart")), ["stop server", "restart server"]); // The restarted process gets the server's own environment (the web password hash), which never sat in the descriptor. assert.equal(ctx.restarts[0].launch.env.TAU_PASSWORD_HASH, "secret-hash"); + assert.equal(ctx.restarts[0].launch.env.TAU_PACKAGE_DIR, ctx.installDir); assert.ok(!readFileSync(ctx.descriptorPath, "utf8").includes("secret-hash")); assert.equal(existsSync(ctx.attemptFile("launch-env.json")), false); assert.equal(existsSync(serverArtifact(ctx.installDir, "backup", ctx.id)), false); @@ -442,23 +447,20 @@ test("Windows: an exclusive directory handle refuses replacement until released" assert.equal(installedVersion(backup), OLD); }); -test("Windows: a stop that leaves the old binary alive refuses cutover without a duplicate restart", { skip: process.platform !== "win32", timeout: 60_000 }, async (t) => { +test("Windows: a stop that leaves the old binary alive is finished by stopping that executable before cutover", { skip: process.platform !== "win32", timeout: 60_000 }, async (t) => { const ctx = scenario(t); - const { child } = await startRunningExecutable(ctx, ctx.installDir); - // The production inventory, unlike the scripted lifecycle, must detect the old executable after the alleged stop. + const { child, exited } = await startRunningExecutable(ctx, ctx.installDir); ctx.deps.sharedInstall = defaultServerUpdateDeps.sharedInstall; - ctx.deps.restart = defaultServerUpdateDeps.restart; + ctx.deps.releaseLocks = defaultServerUpdateDeps.releaseLocks; const identity = await (await import("./process-identity.ts")).processStartIdentity(child.pid); Object.assign(ctx.descriptor.server.process, { pid: child.pid, identity, current: { pid: child.pid, identity } }); ctx.descriptor.server.pids = [child.pid]; writeFileSync(ctx.descriptorPath, JSON.stringify(ctx.descriptor), { mode: 0o600 }); - assert.equal(await run(ctx), 1); - assert.equal(installedVersion(ctx.installDir), OLD); - assert.equal(child.exitCode, null); - assert.equal(ctx.status().state, "failed"); - assert.deepEqual(ctx.restarts, []); - assert.match(ctx.status().error, /shared with another running process/); - assert.equal(ctx.plan().state, "recovery-required"); + assert.equal(await run(ctx), 0); + assert.equal(installedVersion(ctx.installDir), NEW); + await exited; + assert.notEqual(child.exitCode, null); + assert.equal(ctx.status().state, "succeeded"); }); async function livePid(t) { @@ -587,6 +589,20 @@ test("a delayed server stop is reconciled and the previous server restarts durin assert.equal(ctx.plan().state, "failed"); }); +test("a delayed server stop reconciles the server's surviving children before the previous server restarts", async (t) => { + const ctx = scenario(t); + const stop = ctx.deps.stop; + let attempts = 0; + ctx.deps.stop = async (proc) => { + if (proc.role === "server" && ++attempts === 1) throw Object.assign(new Error("Shutdown is still pending"), { code: "stop_pending" }); + return stop(proc); + }; + ctx.deps.releaseLocks = async (_dir, _spare, phase, trees) => { ctx.calls.push(`locks ${phase}${trees ? ` ${trees.join(",")}` : ""}`); }; + assert.equal(await run(ctx), 1); + const scoped = ctx.calls.indexOf("locks all 4242"); + assert.ok(scoped >= 0 && scoped < ctx.calls.indexOf("restart server"), ctx.calls.join(",")); +}); + test("a detached descriptor cannot replace the staged candidate's approved artifact identity", async (t) => { const ctx = scenario(t); const changed = structuredClone(ctx.descriptor); @@ -630,3 +646,101 @@ test("a new host without a specific-server link proof is rolled back, not finali assert.equal(ctx.host.version, OLD); assert.equal(ctx.plan().state, "failed"); }); + +test("tray locks are released before the server stop, and surviving runtimes before the swap", async (t) => { + const ctx = scenario(t); + ctx.deps.releaseLocks = async (_dir, spare, phase) => { + ctx.calls.push(`locks ${phase}`); + assert.ok(spare.includes(process.pid)); + if (phase === "tray") assert.ok(spare.includes(4242)); + else assert.deepEqual(spare, [process.pid]); + }; + assert.equal(await run(ctx), 0); + const tray = ctx.calls.indexOf("locks tray"); + const stop = ctx.calls.indexOf("stop server"); + const all = ctx.calls.indexOf("locks all"); + assert.ok(tray >= 0 && tray < stop && stop < all, ctx.calls.join(",")); +}); + +test("a tray that started the server is relaunched in the interactive session and the server is not started beside it", async (t) => { + const ctx = scenario(t, { localHost: { kind: "separate" } }); + const tasks = []; + ctx.deps.findTray = async () => ({ exe: join(ctx.installDir, "bin", "tau-tray.exe"), args: ["-Startup"] }); + ctx.deps.relaunchInteractiveTray = async (choice, operationId) => { + tasks.push({ command: choice.command, args: choice.args, operationId }); + const expectation = state.readStateJson(state.markerPath(ctx.id, "expect.json")); + state.atomicWrite(state.markerPath(ctx.id, "boot.json"), JSON.stringify({ attemptId: ctx.id, version: expectation.version, nonce: expectation.nonce, pid: process.pid })); + }; + assert.equal(await run(ctx), 0); + assert.equal(ctx.calls.includes("restart server"), false); + assert.equal(ctx.launches.length, 0); + assert.deepEqual(tasks, [{ command: join(ctx.installDir, "bin", "tau-tray.exe"), args: ["-Startup"], operationId: ctx.id }]); +}); + +test("a PowerShell tray is relaunched with its own command and the new install's script", async (t) => { + const ctx = scenario(t, { localHost: { kind: "separate" } }); + const tasks = []; + ctx.deps.findTray = async () => ({ exe: "powershell.exe", args: ["-File", join(ctx.installDir, "scripts", "windows", "tau-tray.ps1"), "-Startup"] }); + ctx.deps.relaunchInteractiveTray = async (choice) => { + tasks.push({ command: choice.command, args: choice.args }); + const expectation = state.readStateJson(state.markerPath(ctx.id, "expect.json")); + state.atomicWrite(state.markerPath(ctx.id, "boot.json"), JSON.stringify({ attemptId: ctx.id, version: expectation.version, nonce: expectation.nonce, pid: process.pid })); + }; + assert.equal(await run(ctx), 0); + assert.deepEqual(tasks, [{ command: "powershell.exe", args: ["-File", join(ctx.installDir, "scripts", "windows", "tau-tray.ps1"), "-Startup"] }]); +}); + +test("a shared install is refused before the tray is stopped, so tray and server keep running", async (t) => { + const ctx = scenario(t, { localHost: { kind: "separate" } }); + const trayPids = [555]; + ctx.deps.findTray = async () => ({ exe: join(ctx.installDir, "bin", "tau-tray.exe"), args: ["-Startup"] }); + ctx.deps.trayPids = async (_dir, _spare, serverPids) => { ctx.trayPidsServers = serverPids; return trayPids; }; + ctx.deps.releaseLocks = async (_dir, _spare, phase) => { ctx.calls.push(`locks ${phase}`); }; + ctx.deps.relaunchInteractiveTray = async () => { ctx.calls.push("relaunch tray"); }; + ctx.sharing = "another process uses the install"; + assert.equal(await run(ctx), 1); + assert.deepEqual(ctx.calls, []); + assert.ok(ctx.sharedInstallCalls[0].ignored.includes(555), "the tray itself is not a foreign sharer"); + assert.deepEqual(ctx.trayPidsServers, [4242], "the tray wrapper is verified against the server's launcher pids"); +}); + +test("a failure after the tray stopped, with the server still running, stops that server and relaunches the tray that starts it", async (t) => { + const ctx = scenario(t, { localHost: { kind: "separate" } }); + const tasks = []; + ctx.deps.findTray = async () => ({ exe: join(ctx.installDir, "bin", "tau-tray.exe"), args: ["-Startup"] }); + ctx.deps.releaseLocks = async (_dir, _spare, phase) => { + ctx.calls.push(`locks ${phase}`); + if (ctx.calls.filter((call) => call === "locks tray").length === 1) throw new Error("the tray stop failed midway"); + }; + ctx.deps.relaunchInteractiveTray = async (choice) => { + ctx.calls.push("relaunch tray"); + tasks.push(choice.command); + const expectation = state.readStateJson(state.markerPath(ctx.id, "expect.json")); + state.atomicWrite(state.markerPath(ctx.id, "boot.json"), JSON.stringify({ attemptId: ctx.id, version: expectation.version, nonce: expectation.nonce, pid: process.pid })); + }; + assert.equal(await run(ctx), 1); + assert.deepEqual(tasks, [join(ctx.installDir, "bin", "tau-tray.exe")]); + assert.ok(ctx.calls.indexOf("stop server") > ctx.calls.indexOf("locks tray"), ctx.calls.join(",")); + assert.ok(ctx.calls.indexOf("relaunch tray") > ctx.calls.indexOf("stop server"), ctx.calls.join(",")); + assert.equal(ctx.calls.includes("restart server"), false, "the tray starts the one server, not the worker"); + assert.equal(ctx.launches.length, 0); + assert.equal(installedVersion(ctx.installDir), OLD); +}); + +test("rolling back a tray-only stop reconciles the server's surviving children before the tray starts", async (t) => { + const ctx = scenario(t, { localHost: { kind: "separate" } }); + ctx.deps.findTray = async () => ({ exe: join(ctx.installDir, "bin", "tau-tray.exe"), args: ["-Startup"] }); + ctx.deps.releaseLocks = async (_dir, _spare, phase, trees) => { + ctx.calls.push(`locks ${phase}${trees ? ` ${trees.join(",")}` : ""}`); + if (ctx.calls.filter((call) => call === "locks tray").length === 1) throw new Error("the tray stop failed midway"); + }; + ctx.deps.relaunchInteractiveTray = async () => { + ctx.calls.push("relaunch tray"); + const expectation = state.readStateJson(state.markerPath(ctx.id, "expect.json")); + state.atomicWrite(state.markerPath(ctx.id, "boot.json"), JSON.stringify({ attemptId: ctx.id, version: expectation.version, nonce: expectation.nonce, pid: process.pid })); + }; + assert.equal(await run(ctx), 1); + const stop = ctx.calls.indexOf("stop server"); + const scoped = ctx.calls.indexOf("locks all 4242"); + assert.ok(stop >= 0 && scoped > stop && ctx.calls.indexOf("relaunch tray") > scoped, ctx.calls.join(",")); +}); diff --git a/lib/server-update-worker.ts b/lib/server-update-worker.ts index f7e1659b..01334414 100644 --- a/lib/server-update-worker.ts +++ b/lib/server-update-worker.ts @@ -15,7 +15,7 @@ import { assertOwnedPath, HOST_VERSION_PATTERN, hostLaunch, moveHostRelease, rep import { getAgentDir } from "./pi/paths"; import { isProcessAlive } from "./process-identity"; import { atomicWrite, attemptPath, isActiveLease, leasePath, markerPath, patchStatus, readStateJson, removeSecureFile, renewLease, secureRegularFile, statusPath, type SelfUpdateStage, type StoredStatus } from "./self-update-state"; -import { inspectUpgradeProcess, launchDetachedUpgrade, restartUpgradeProcess, stopUpgradeProcess, type UpgradeLaunch, type UpgradeProcess } from "./upgrade-process"; +import { cwdOutsideInstall, findInstallTrayPids, findTraySupervisor, inspectUpgradeProcess, installSpawnCwd, launchDetachedUpgrade, launchInteractiveTray, restartUpgradeProcess, serverRestartChoice, stopInstallLockingProcesses, stopUpgradeProcess, type TraySupervisor, type UpgradeLaunch, type UpgradeProcess } from "./upgrade-process"; import { isRecord } from "./type-guards"; import type { UpgradeParticipant, UpgradePlan } from "./upgrade-types"; import type { ApprovedReleasePin } from "./hosts/update-types"; @@ -63,6 +63,14 @@ export interface ServerUpdateDeps { launch: typeof launchDetachedUpgrade; hostControl: typeof requestHostControl; sharedInstall: typeof sharedHostInstallReason; + /** Stops processes that lock the install directory. `tray` first, so a tray cannot restart the server; `all` after the descriptor stop. */ + releaseLocks: typeof stopInstallLockingProcesses; + /** The tray that started the server, captured before it is stopped. Null when the server had no tray supervisor. */ + findTray: typeof findTraySupervisor; + /** The trays the tray stop would end, and the cmd.exe wrapper between a tray and the server launcher: not foreign sharers, so the shared-install check can run before it stops. */ + trayPids: typeof findInstallTrayPids; + /** Starts the tray in the logged-on session. Not the detached helper: that one is non-interactive. */ + relaunchInteractiveTray: typeof launchInteractiveTray; /** The new server has this long to report ready after it starts. */ bootTimeoutMs: number; /** The host has this long to answer its control endpoint linked, at the expected version. */ @@ -78,6 +86,10 @@ export const defaultServerUpdateDeps: ServerUpdateDeps = { launch: launchDetachedUpgrade, hostControl: requestHostControl, sharedInstall: sharedHostInstallReason, + releaseLocks: stopInstallLockingProcesses, + findTray: findTraySupervisor, + trayPids: findInstallTrayPids, + relaunchInteractiveTray: launchInteractiveTray, bootTimeoutMs: 120_000, hostTimeoutMs: 90_000, pollMs: 250, @@ -275,6 +287,8 @@ export function reportPlan(attemptId: string, participantId: string | null, stat /** Runs one update attempt; the exit code. The terminal result is always in status.json (and the plan), never only in the exit code. */ export async function runServerUpdateWorker(descriptorPath: string, deps: ServerUpdateDeps = defaultServerUpdateDeps): Promise { + // Windows refuses to rename a directory that is a live process's working directory. + if (process.argv[2] === "--server-update-descriptor" || process.argv[2] === "server-update-worker") process.chdir(installSpawnCwd()); // The terminal that started the update may close before it ends. process.on("SIGHUP", () => undefined); let d: ServerUpdateDescriptor; @@ -291,6 +305,9 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server catch (error) { if ((error as NodeJS.ErrnoException).code === "EEXIST") return 1; throw error; } const flags = { hostDrainPending: false, hostDrained: false, hostStopped: false, serverStopped: false, swapped: false, restarted: false }; + let tray: TraySupervisor | null = null; + let relaunchTray = false; + let trayStopped = false; const serverProcess = d.server.process; const hostProcess = d.localHost.kind === "shared" ? d.localHost.process : null; const backup = serverArtifact(d.installDir, "backup", id); @@ -307,7 +324,16 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server const nonce = randomUUID(); removeSecureFile(markerPath(id, "boot.json")); atomicWrite(markerPath(id, "expect.json"), JSON.stringify({ attemptId: id, version, nonce })); - const started = await deps.restart(serverProcess, { ...d.server.launch, env: readLaunchEnvironment(id) }); + const choice = serverRestartChoice(tray, d.installDir, cwdOutsideInstall(d.installDir)); + relaunchTray = choice.kind === "tray"; + // The tray must run in the logged-on session. The detached helper is only for a server that had no tray. + let started: number | undefined; + if (choice.kind === "tray") await deps.relaunchInteractiveTray(choice, id); + else { + const env = readLaunchEnvironment(id); + env.TAU_PACKAGE_DIR = d.installDir; + started = await deps.restart(serverProcess, { ...d.server.launch, env }); + } const deadline = Date.now() + deps.bootTimeoutMs; let exitedAt: number | undefined; for (;;) { @@ -377,12 +403,28 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server }; if (flags.restarted) { await step("The failed new host could not be stopped, so the previous installation was left in place", stopHostFromInstall, true); - if (!blocked) await step("The failed new server could not be stopped, so the previous installation was left in place", () => deps.stop(serverProcess), true); + if (!blocked) await step("The failed new server could not be stopped, so the previous installation was left in place", async () => { + if (relaunchTray) await deps.releaseLocks(d.installDir, [process.pid], "all"); + else await deps.stop(serverProcess); + }, true); } if (flags.swapped && !blocked) { await step("The previous installation could not be restored", () => restoreInstallDirectory(d.installDir, backup, failed).then(() => { flags.swapped = false; }), true); } - if (flags.serverStopped && !blocked) await step(`The previous server ${d.fromVersion} could not be restarted`, () => startServer(d.fromVersion)); + // Stopping the launcher on Windows can leave its bun child holding the port. Reconcile only the server's own tree: never the host daemon or other processes. + const restartPreviousServer = async (): Promise => { + await deps.releaseLocks(d.installDir, [process.pid], "all", d.server.pids); + await startServer(d.fromVersion); + }; + if (flags.serverStopped && !blocked) await step(`The previous server ${d.fromVersion} could not be restarted`, restartPreviousServer); + // The tray was stopped during preparation while the server kept running. A relaunched tray always starts its own server and would hit the occupied + // port, so stop our server (identity-checked) and let the tray start the one server; recovery is reported only after it is ready. + else if (trayStopped && !blocked) await step(`The previous tray and server ${d.fromVersion} could not be restarted`, async () => { + await deps.releaseLocks(d.installDir, [process.pid], "tray"); // a partial stop may have left it running: never two supervisors + await deps.stop(serverProcess); + flags.serverStopped = true; + await restartPreviousServer(); + }, true); if (flags.hostStopped && !blocked) await step("The previous local host could not be restarted", async () => { await deps.restart(hostProcess!, launchFor(d)); await awaitHost(d.fromVersion, hostProcess!.pid, true); @@ -393,7 +435,7 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server if (status.drained) await deps.hostControl("resume"); flags.hostDrainPending = false; }); - const touched = flags.serverStopped || flags.hostStopped || flags.swapped || flags.restarted || flags.hostDrained; + const touched = flags.serverStopped || flags.hostStopped || flags.swapped || flags.restarted || flags.hostDrained || trayStopped; const detail = notes.length ? `; ${notes.join("; ")}` : touched ? "; the previous release was restored" : ""; return { message: `${message(primary)}${detail}`.slice(0, 1500), recovered: notes.length === 0 }; }; @@ -405,8 +447,14 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server await verifyStagedRelease(d); // Nothing stops while an unknown process still runs from the installation: the server's tree and the shared host (and its sessions) are expected. const owned = [...d.server.pids, ...(hostProcess ? [hostProcess.pid] : [])]; - const sharing = await deps.sharedInstall(d.installDir, [process.pid, ...owned], owned); + tray = await deps.findTray(d.installDir, d.server.pids); + // Check before the tray stops: no refusal may leave a stopped tray beside a running server. The trays are ours to stop, not sharers. + const trays = await deps.trayPids(d.installDir, [process.pid, ...owned], d.server.pids); + const sharing = await deps.sharedInstall(d.installDir, [process.pid, ...owned, ...trays], owned); if (sharing) throw new Error(sharing); + trayStopped = tray !== null; // set before the stop: a release that fails midway may already have stopped it + // The tray exe lives in the package and is not a descriptor pid. Stop it before it can restart the server. + await deps.releaseLocks(d.installDir, [process.pid, ...owned], "tray"); stage("stopping"); if (hostProcess) { @@ -440,7 +488,10 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server } else if (!isProcessAlive(serverProcess.pid)) flags.serverStopped = true; throw error; } - const leftover = await deps.sharedInstall(d.installDir, [process.pid]); + // shortcut: a scheduled task can restart the host during the rename; hold that task across the swap if that race shows up. + // TerminateProcess stops only the descriptor pid, so a bun child whose command line references the install is still running. + await deps.releaseLocks(d.installDir, [process.pid], "all"); + const leftover = await deps.sharedInstall(d.installDir, [process.pid, ...trays]); // the tray's cmd.exe wrapper may still be exiting if (leftover) throw new Error(leftover); stage("installing"); diff --git a/lib/upgrade-process.ts b/lib/upgrade-process.ts index 5612bc7d..fd8d7fdc 100644 --- a/lib/upgrade-process.ts +++ b/lib/upgrade-process.ts @@ -2,7 +2,7 @@ import { execFile, spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync, type Stats } from "node:fs"; -import { tmpdir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { setTimeout as pause } from "node:timers/promises"; import { promisify } from "node:util"; @@ -1015,3 +1015,219 @@ export async function restartUpgradeProcess(plan: UpgradeProcess, launch: Upgrad plan.current = instance; return instance.pid ?? undefined; } + +export interface InstallLockRow { pid: number; ppid: number; exe: string; command: string; args?: string[] } +export interface InstallLockHit { pid: number; kind: "tray" | "runtime" } +export interface InstallLockSelection { stop: InstallLockHit[]; blocked: InstallLockHit[] } + +function slash(value: string): string { return value.replaceAll("\\", "/"); } +/** A path prefix safe to search for. A drive root or `/` would match every process. */ +function installKey(installDir: string): string | null { + const root = slash(installDir).replace(/\/+$/, "").toLowerCase(); + if (root.length < 3 || root === "/" || /^[a-z]:$/.test(root)) return null; + return root; +} +function mentionsInstall(text: string, root: string): boolean { + const value = slash(text).toLowerCase(); + let from = 0; + while (from < value.length) { + const at = value.indexOf(root, from); + if (at < 0) return false; + const before = at === 0 ? "" : value[at - 1]; + const after = value[at + root.length] ?? ""; + if ((before === "" || before === "\0" || /[\s"'=]/.test(before)) && (after === "" || after === "/" || after === "\0" || /[\s"']/.test(after))) return true; + from = at + root.length; + } + return false; +} +function ancestorsOf(rows: InstallLockRow[], pid: number): Set { + const byPid = new Map(rows.map((row) => [row.pid, row])); + const found = new Set(); + let current = byPid.get(pid); + for (let hops = 0; current && hops < 32; hops++) { + const parent = byPid.get(current.ppid); + if (!parent || parent.pid === current.pid || found.has(parent.pid)) break; + found.add(parent.pid); + current = parent; + } + return found; +} +/** Every ancestor pid of `pid`, including one that has no row any more. */ +function ancestorPids(rows: InstallLockRow[], pid: number): number[] { + const byPid = new Map(rows.map((row) => [row.pid, row])); + const found: number[] = []; + for (let current = byPid.get(pid), hops = 0; current && hops < 32 && !found.includes(current.ppid); hops++) { + found.push(current.ppid); + current = byPid.get(current.ppid); + } + return found; +} +function lockKind(row: InstallLockRow, root: string): InstallLockHit["kind"] | null { + const path = slash(row.exe || row.command.split("\0").find(Boolean) || ""); + const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase(); + const image = Boolean(row.exe) && mentionsInstall(row.exe, root); + const trayScript = (name === "powershell.exe" || name === "pwsh.exe") && /tau-tray\.(?:ps1|exe)/i.test(slash(row.command)) && mentionsInstall(row.command, root); + if ((name === "tau-tray.exe" && (image || mentionsInstall(row.command, root))) || trayScript) return "tray"; + if (image || (/^(node|bun)(\.exe)?$/.test(name) && mentionsInstall(row.command, root))) return "runtime"; + return null; +} + +/** + * Processes that keep an npm install from being renamed: the tray executable in the package (web-service.json has no + * pid for it), and node/bun whose image or command line references the install. `sparePids` are not selected. + * `protectPids` are the update worker: an ancestor of one is `blocked`, never stopped — stopping it would kill the worker. + */ +export function selectInstallLockingProcesses(rows: InstallLockRow[], installDir: string, sparePids: number[], protectPids: number[], onlyTreesOf?: number[]): InstallLockSelection { + const root = installKey(installDir); + const spare = new Set(sparePids); + const protectedAncestors = new Set(); + for (const pid of protectPids) for (const ancestor of ancestorsOf(rows, pid)) protectedAncestors.add(ancestor); + const trays: InstallLockHit[] = []; + const rest: InstallLockHit[] = []; + const blocked: InstallLockHit[] = []; + if (!root) return { stop: [], blocked }; + for (const row of rows) { + if (!Number.isSafeInteger(row.pid) || row.pid <= 1 || spare.has(row.pid)) continue; + const kind = lockKind(row, root); + if (!kind) continue; + // A stopped launcher is absent from the table but its survivors keep its pid as ppid (Windows does not reparent), so the chain may end at a pid that is gone. + if (onlyTreesOf && !onlyTreesOf.includes(row.pid) && !ancestorPids(rows, row.pid).some((pid) => onlyTreesOf.includes(pid))) continue; + const hit = { pid: row.pid, kind }; + if (protectedAncestors.has(row.pid)) blocked.push(hit); + else if (kind === "tray") trays.push(hit); + else rest.push(hit); + } + return { stop: [...trays, ...rest], blocked }; +} + +/** Where `npm install` / the update worker must run. A cwd inside the install makes Windows refuse the rename (EBUSY). */ +export function installSpawnCwd(temporary = tmpdir(), installDir?: string): string { + if (!temporary || !isAbsolute(temporary)) fail("The temporary directory is empty; refusing to run the update inside its installation"); + const root = installDir ? installKey(installDir) : null; + const value = slash(temporary).replace(/\/+$/, "").toLowerCase(); + if (root && (value === root || value.startsWith(`${root}/`))) fail("The temporary directory is inside the installation; refusing to use it as the update working directory"); + return temporary; +} + +/** A directory a restarted server may use. Never the installation: that cwd locks the next rename. */ +export function cwdOutsideInstall(installDir: string, home = homedir(), temporary = tmpdir()): string { + const root = installKey(installDir); + const outside = (candidate: string) => { + if (!candidate || !isAbsolute(candidate)) return false; + if (!root) return true; + const value = slash(candidate).replace(/\/+$/, "").toLowerCase(); + return value !== root && !value.startsWith(`${root}/`); + }; + if (outside(home)) return home; + if (outside(temporary)) return temporary; + return fail("No working directory outside the installation; refusing to start a process that would lock the next update"); +} + + +/** Stops install-locking processes one by one; `onlyTreesOf` limits that to those pids and their descendants. Never `taskkill /T`: a tree kill ends a worker that still descends from the target. */ +export async function stopInstallLockingProcesses(installDir: string, sparePids: number[], phase: "tray" | "all", onlyTreesOf?: number[]): Promise { + if (phase === "tray" && process.platform !== "win32") return; + const rows = (await listProcesses()).map((row) => ({ pid: row.pid, ppid: row.ppid, exe: row.exe, command: [row.exe, ...row.args].join("\0") })); + const selection = selectInstallLockingProcesses(rows, installDir, sparePids, [process.pid], onlyTreesOf); + const inPhase = (hit: InstallLockHit) => phase === "all" || hit.kind === "tray"; + const blocked = selection.blocked.filter(inPhase); + if (blocked.length) fail(`Refusing to stop process ${blocked.map((hit) => hit.pid).join(", ")}: the update worker descends from it, and stopping it would end the update`); + for (const hit of selection.stop.filter(inPhase)) { + await signalProcess(hit.pid, "SIGTERM"); + await waitStopped(hit.pid); + } +} + +export interface TraySupervisor { exe: string; args: string[] } +export type ServerRestartChoice = { kind: "tray"; command: string; args: string[]; cwd: string } | { kind: "direct" } + +/** The tray that started one of `serverPids`, if its image or script is this install. Any other tray is not the supervisor. */ +export function traySupervisor(rows: InstallLockRow[], serverPids: number[], installDir: string): TraySupervisor | null { + const root = installKey(installDir); + if (!root) return null; + const byPid = new Map(rows.map((row) => [row.pid, row])); + for (const pid of serverPids) { + for (const ancestor of ancestorsOf(rows, pid)) { + const row = byPid.get(ancestor); + if (!row || lockKind(row, root) !== "tray") continue; + // A parsed command line starts with the executable (argv[0]); it is the command, not an argument to forward. + const args = row.args ? row.args.slice(1) : row.command.split("\0").filter((arg) => arg && arg !== row.exe); + return { exe: row.exe, args }; + } + } + return null; +} + +/** Tray-supervised: start only the tray from the new install (it starts the server). Otherwise the worker starts the server. */ +export function serverRestartChoice(tray: TraySupervisor | null, installDir: string, cwd: string): ServerRestartChoice { + if (!tray) return { kind: "direct" }; + const name = slash(tray.exe).split("/").pop()?.toLowerCase() ?? ""; + const exeArg = (arg: string) => /tau-tray\.exe$/i.test(slash(arg)); + const scriptArg = (arg: string) => /tau-tray\.ps1$/i.test(slash(arg)); + if (name === "tau-tray.exe" || tray.args.some(exeArg)) { + return { kind: "tray", command: join(installDir, "bin", "tau-tray.exe"), args: tray.args.filter((arg) => !exeArg(arg)), cwd }; + } + return { kind: "tray", command: tray.exe, args: tray.args.map((arg) => scriptArg(arg) ? join(installDir, "scripts", "windows", "tau-tray.ps1") : arg), cwd }; +} + +/** + * Pids the update stops or expects: every tray from this installation that `stopInstallLockingProcesses(.., "tray")` would stop, and + * the `cmd.exe` the tray starts the server through (tray → cmd.exe → launcher → bun), which only the descriptor's `serverPids` verify. + * Any other `cmd.exe`, even one referencing the install, is not owned. + */ +export function selectOwnedTrayPids(rows: InstallLockRow[], installDir: string, sparePids: number[], serverPids: number[]): number[] { + const trays = selectInstallLockingProcesses(rows, installDir, sparePids, [process.pid]).stop.filter((hit) => hit.kind === "tray").map((hit) => hit.pid); + const wrappers = rows.filter((row) => + slash(row.exe).split("/").pop()?.toLowerCase() === "cmd.exe" && trays.includes(row.ppid) + && serverPids.some((pid) => ancestorPids(rows, pid).includes(row.pid))).map((row) => row.pid); + return [...trays, ...wrappers]; +} + +export async function findInstallTrayPids(installDir: string, sparePids: number[], serverPids: number[]): Promise { + if (process.platform !== "win32") return []; // the tray is a Windows program; elsewhere there is nothing to find + const rows = (await listProcesses()).map((row) => ({ pid: row.pid, ppid: row.ppid, exe: row.exe, command: [row.exe, ...row.args].join("\0") })); + return selectOwnedTrayPids(rows, installDir, sparePids, serverPids); +} + +export async function findTraySupervisor(installDir: string, serverPids: number[]): Promise { + if (process.platform !== "win32") return null; + const rows = (await listProcesses()).map((row) => ({ pid: row.pid, ppid: row.ppid, exe: row.exe, command: [row.exe, ...row.args].join("\0"), args: row.args })); + return traySupervisor(rows, serverPids, installDir); +} + +export interface InteractiveTrayTask { taskName: string; exe: string; args: string; cwd: string; encoded: string; script: string } + +const psLiteral = (value: string): string => `'${value.replaceAll("'", "''")}'`; + +/** CommandLineToArgvW's inverse for one argument: quote only when it holds whitespace or a quote. */ +const winArg = (arg: string): string => /[\s"]|^$/.test(arg) ? `"${arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"` : arg; + +/** A one-shot interactive task (`schtasks /IT`) that starts the selected tray command and exits, so deleting the task does not kill the tray. */ +export function interactiveTrayTask(choice: Pick, "command" | "args" | "cwd">, operationId: string): InteractiveTrayTask { + const { command: exe, cwd } = choice; + if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(operationId)) fail("Invalid tray relaunch operation id"); + if (!cwd || cwd.includes("\0")) fail("The tray working directory is empty"); + const taskName = `ompweb-tray-${operationId}`; + const args = choice.args.map(winArg).join(" "); + const encoded = encodePowershell(`Start-Process -FilePath ${psLiteral(exe)}${args ? ` -ArgumentList ${psLiteral(args)}` : ""} -WorkingDirectory ${psLiteral(cwd)}`); + const script = [ + `$name = ${psString(taskName)}`, + `$cwd = ${psString(cwd)}`, + `$arg = ${psString(`-NoProfile -WindowStyle Hidden -EncodedCommand ${encoded}`)}`, + // LogonType Interactive is schtasks /IT: the starter runs in the logged-on session, not the non-interactive WMI session. + `$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument $arg -WorkingDirectory $cwd`, + `$principal = New-ScheduledTaskPrincipal -UserId ([Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited`, + `$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 1)`, + `Register-ScheduledTask -TaskName $name -Action $action -Principal $principal -Settings $settings -Force | Out-Null`, + `try {`, + ` Start-ScheduledTask -TaskName $name`, + ` for ($i = 0; $i -lt 50; $i++) { if ((Get-ScheduledTask -TaskName $name).State -ne 'Running') { break }; Start-Sleep -Milliseconds 100 }`, + `} finally { Unregister-ScheduledTask -TaskName $name -Confirm:$false -ErrorAction SilentlyContinue }`, + ].join("\n"); + return { taskName, exe, args, cwd, encoded, script }; +} + +export async function launchInteractiveTray(choice: Parameters[0], operationId: string): Promise { + if (process.platform !== "win32") fail("An interactive tray can only be relaunched on Windows"); + await powershell(interactiveTrayTask(choice, operationId).script, 60000); +} diff --git a/lib/upgrade-process.windows-service.test.mjs b/lib/upgrade-process.windows-service.test.mjs index 3e98cee9..bec0761a 100644 --- a/lib/upgrade-process.windows-service.test.mjs +++ b/lib/upgrade-process.windows-service.test.mjs @@ -256,3 +256,173 @@ test("a helper launched under a service survives the service being stopped, with await sleep(1000); } }); + +const INSTALL = "C:/Users/x/AppData/Roaming/npm/node_modules/@kahme247/ompweb"; + +test("a tray exe inside the package is selected without a pid in web-service.json", async () => { + const { selectInstallLockingProcesses } = await import("./upgrade-process.ts"); + const rows = [ + { pid: 10, ppid: 1, exe: `${INSTALL}/bin/tau-tray.exe`, command: "-Startup" }, + { pid: 11, ppid: 1, exe: "C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", command: `powershell -File "${INSTALL}\\scripts\\windows\\tau-tray.ps1" -Startup` }, + { pid: 12, ppid: 1, exe: "C:/Program Files/Code/Code.exe", command: `code ${INSTALL}` }, + ]; + const selected = selectInstallLockingProcesses(rows, INSTALL, [], [99]); + assert.deepEqual(selected.blocked, []); + assert.deepEqual(selected.stop.map((hit) => hit.pid), [10, 11]); + assert.ok(selected.stop.every((hit) => hit.kind === "tray")); +}); + +test("a bun or node process whose command line references the install is selected even when it is not a descriptor pid", async () => { + const { selectInstallLockingProcesses } = await import("./upgrade-process.ts"); + const rows = [ + { pid: 20, ppid: 10, exe: "C:/Program Files/nodejs/node.exe", command: `"${INSTALL}\\bin\\tau.js" -p 30187` }, + { pid: 30, ppid: 20, exe: `${INSTALL}/node_modules/bun/bin/bun.exe`, command: `${INSTALL}\\server\\main.ts` }, + { pid: 31, ppid: 1, exe: "C:/Program Files/bun/bun.exe", command: `bun ${INSTALL}-other/server/main.ts` }, + { pid: 99, ppid: 4, exe: "C:/Temp/runtime.exe", command: "C:/Temp/worker.mjs" }, + ]; + const selected = selectInstallLockingProcesses(rows, INSTALL, [99], [99]); + assert.deepEqual(selected.stop.map((hit) => hit.pid), [20, 30]); + assert.ok(selected.stop.every((hit) => hit.kind === "runtime")); +}); + +test("scoped to the server launcher, a surviving bun child is selected after the launcher is gone; the host daemon and unrelated processes are not", async () => { + const { selectInstallLockingProcesses } = await import("./upgrade-process.ts"); + // Launcher 20 was stopped (absent from the table); Windows keeps its child's ppid, so the chain ends at a pid that no longer exists. + const rows = [ + { pid: 30, ppid: 20, exe: `${INSTALL}/node_modules/bun/bin/bun.exe`, command: `${INSTALL}\\server\\main.ts` }, + { pid: 31, ppid: 30, exe: `${INSTALL}/node_modules/bun/bin/bun.exe`, command: `${INSTALL}\\server\\worker.ts` }, + { pid: 40, ppid: 1, exe: "C:/Program Files/nodejs/node.exe", command: `"${INSTALL}\\bin\\tau-host.js"` }, + { pid: 41, ppid: 40, exe: `${INSTALL}/node_modules/bun/bin/bun.exe`, command: `${INSTALL}\\runner.ts` }, + { pid: 50, ppid: 1, exe: "C:/Program Files/bun/bun.exe", command: `bun ${INSTALL}\\other.ts` }, + ]; + const selected = selectInstallLockingProcesses(rows, INSTALL, [99], [99], [20]); + assert.deepEqual(selected.stop.map((hit) => hit.pid), [30, 31]); + assert.deepEqual(selectInstallLockingProcesses(rows, INSTALL, [99], [99]).stop.map((hit) => hit.pid), [30, 31, 40, 41, 50]); +}); + +test("the tray's cmd.exe wrapper between the tray and the launcher is owned; an unrelated cmd.exe referencing the install is not", async () => { + const { selectOwnedTrayPids } = await import("./upgrade-process.ts"); + const row = (pid, ppid, exe, args) => ({ pid, ppid, exe, command: [exe, ...args].join("\0"), args }); + const cmd = "C:/Windows/System32/cmd.exe"; + const bun = `${INSTALL}/node_modules/bun/bin/bun.exe`; + const rows = [ + row(10, 1, `${INSTALL}/bin/tau-tray.exe`, [`${INSTALL}/bin/tau-tray.exe`, "-Startup"]), + row(15, 10, cmd, [cmd, "/d", "/s", "/c", `"node.exe ${INSTALL}\\bin\\tau.js"`]), + row(20, 15, "C:/Program Files/nodejs/node.exe", ["node.exe", `${INSTALL}\\bin\\tau.js`]), + row(30, 20, bun, [bun, `${INSTALL}\\server\\main.ts`]), + // Not between the tray and the launcher: a user's shell, one under another parent, and a wrapper of an unrelated process. + row(60, 1, cmd, [cmd, "/k", `cd ${INSTALL}`]), + row(61, 10, cmd, [cmd, "/c", `echo ${INSTALL}`]), + row(62, 61, "C:/Program Files/nodejs/node.exe", ["node.exe", "other.js"]), + ]; + assert.deepEqual(selectOwnedTrayPids(rows, INSTALL, [99], [20, 30]).sort((a, b) => a - b), [10, 15]); + assert.deepEqual(selectOwnedTrayPids(rows, INSTALL, [99], [62]).sort((a, b) => a - b), [10, 61], "only the wrapper above the given server pids is owned"); + assert.deepEqual(selectOwnedTrayPids(rows.filter((r) => r.pid !== 10), INSTALL, [99], [20, 30]), [], "a cmd.exe with no tray above it is not owned"); +}); + +test("the update does not select a process the worker descends from", async () => { + const { selectInstallLockingProcesses } = await import("./upgrade-process.ts"); + const rows = [ + { pid: 10, ppid: 1, exe: `${INSTALL}/bin/tau-tray.exe`, command: `${INSTALL}\\bin\\tau-tray.exe -Startup` }, + { pid: 99, ppid: 10, exe: "C:/Temp/runtime.exe", command: "C:/Temp/worker.mjs" }, + ]; + const selected = selectInstallLockingProcesses(rows, INSTALL, [99], [99]); + assert.deepEqual(selected.stop, []); + assert.deepEqual(selected.blocked, [{ pid: 10, kind: "tray" }]); +}); + +test("update working directories stay outside the installation", async () => { + const { installSpawnCwd, cwdOutsideInstall } = await import("./upgrade-process.ts"); + const { homedir, tmpdir } = await import("node:os"); + assert.equal(installSpawnCwd(), tmpdir()); + assert.equal(cwdOutsideInstall(INSTALL), homedir()); + assert.notEqual(cwdOutsideInstall(INSTALL), INSTALL); + assert.throws(() => installSpawnCwd("/tmp/ompweb-install", "/tmp/ompweb-install"), /inside the installation/); + assert.equal(cwdOutsideInstall(homedir(), homedir(), tmpdir()), tmpdir()); +}); + +test("a tray that started the server is relaunched alone; otherwise the server restarts directly", async () => { + const { traySupervisor, serverRestartChoice } = await import("./upgrade-process.ts"); + const install = "C:/Users/x/AppData/Roaming/npm/node_modules/@kahme247/ompweb"; + const cwd = "C:/Users/x"; + const rows = [ + { pid: 10, ppid: 1, exe: `${install}/bin/tau-tray.exe`, command: "", args: [`${install}/bin/tau-tray.exe`, "-Startup"] }, + { pid: 20, ppid: 10, exe: "C:/Program Files/nodejs/node.exe", command: "", args: [`${install}/bin/tau.js`] }, + { pid: 30, ppid: 20, exe: `${install}/node_modules/bun/bin/bun.exe`, command: "", args: [`${install}/server/main.ts`] }, + { pid: 40, ppid: 1, exe: `${install}/bin/tau-tray.exe`, command: "", args: [`${install}/bin/tau-tray.exe`, "-OpenBrowser"] }, + ]; + const tray = traySupervisor(rows, [20, 30], install); + assert.deepEqual(tray, { exe: `${install}/bin/tau-tray.exe`, args: ["-Startup"] }); + const choice = serverRestartChoice(tray, install, cwd); + assert.equal(choice.kind, "tray"); + if (choice.kind !== "tray") return; + assert.equal(choice.command, join(install, "bin", "tau-tray.exe")); + assert.deepEqual(choice.args, ["-Startup"]); + assert.equal(choice.cwd, cwd); + assert.equal(traySupervisor(rows, [99], install), null, "a tray that did not start this server is not its supervisor"); + assert.deepEqual(serverRestartChoice(null, install, cwd), { kind: "direct" }); +}); + +test("a PowerShell tray supervisor keeps its flags and script but not its own executable (argv[0])", async () => { + const { traySupervisor, serverRestartChoice } = await import("./upgrade-process.ts"); + const install = "C:/Users/x/AppData/Roaming/npm/node_modules/@kahme247/ompweb"; + const script = `${install}/scripts/windows/tau-tray.ps1`; + // Production rows: args is the parsed command line (executable first) and command joins exe and args. + const row = (pid, ppid, exe, args) => ({ pid, ppid, exe, command: [exe, ...args].join("\0"), args }); + const pwshArgs = ["C:\\Program Files\\PowerShell\\7\\pwsh.exe", "-NoProfile", "-File", script, "-Startup"]; + const rows = [ + row(10, 1, "C:/Program Files/PowerShell/7/pwsh.exe", pwshArgs), + row(20, 10, "C:/Program Files/nodejs/node.exe", ["C:/Program Files/nodejs/node.exe", `${install}/bin/tau.js`]), + ]; + const tray = traySupervisor(rows, [20], install); + assert.deepEqual(tray, { exe: "C:/Program Files/PowerShell/7/pwsh.exe", args: ["-NoProfile", "-File", script, "-Startup"] }); + const choice = serverRestartChoice(tray, install, "C:/Users/x"); + assert.equal(choice.kind === "tray" && choice.command, "C:/Program Files/PowerShell/7/pwsh.exe"); + assert.deepEqual(choice.kind === "tray" && choice.args, ["-NoProfile", "-File", join(install, "scripts", "windows", "tau-tray.ps1"), "-Startup"]); +}); + +test("the interactive tray task is unique per operation, runs the selected command, and quotes hostile paths", async () => { + const { interactiveTrayTask } = await import("./upgrade-process.ts"); + const exe = "C:/Users/a b/o'mpweb/bin/tau-tray.exe"; + const cwd = "C:/Users/a b"; + const first = "11111111-1111-4111-8111-111111111111"; + const second = "22222222-2222-4222-8222-222222222222"; + const task = interactiveTrayTask({ command: exe, args: ["-Startup"], cwd }, first); + const other = interactiveTrayTask({ command: exe, args: ["-Startup"], cwd }, second); + assert.notEqual(task.taskName, other.taskName); + assert.match(task.taskName, new RegExp(first)); + assert.equal(task.exe, exe); + assert.equal(task.args, "-Startup"); + const inner = Buffer.from(task.encoded, "base64").toString("utf16le"); + // Windows PowerShell 5.1 Start-Process has -FilePath but no -LiteralPath. + assert.equal(inner, `Start-Process -FilePath '${exe.replaceAll("'", "''")}' -ArgumentList '-Startup' -WorkingDirectory '${cwd}'`); + assert.match(task.script, /LogonType Interactive/); + assert.match(task.script, /Unregister-ScheduledTask/); + assert.equal(task.script.includes("a b"), false, "a spaced path is not spliced into the registration script"); + assert.equal(task.script.includes("o'mpweb"), false, "a quoted path is not spliced into the registration script"); + assert.throws(() => interactiveTrayTask({ command: exe, args: [], cwd }, "not-an-id"), /operation id/); +}); + +test("the interactive tray task starts a PowerShell tray with its script and arguments, not the exe", async () => { + const { interactiveTrayTask } = await import("./upgrade-process.ts"); + const script = "C:/Users/a b/npm/ompweb/scripts/windows/tau-tray.ps1"; + const task = interactiveTrayTask({ command: "powershell.exe", args: ["-NoProfile", "-File", script, "-Startup"], cwd: "C:/Users/a b" }, "11111111-1111-4111-8111-111111111111"); + assert.equal(task.exe, "powershell.exe"); + assert.equal(task.args, `-NoProfile -File "${script}" -Startup`); + const inner = Buffer.from(task.encoded, "base64").toString("utf16le"); + assert.ok(inner.startsWith("Start-Process -FilePath 'powershell.exe' -ArgumentList '"), inner); + assert.equal(inner.includes("tau-tray.exe"), false); +}); + +test("a NUL-joined command line still matches an install path in its own argument", async () => { + const { selectInstallLockingProcesses } = await import("./upgrade-process.ts"); + const install = "C:/Users/x/AppData/Roaming/npm/node_modules/@kahme247/ompweb"; + const node = "C:/Program Files/nodejs/node.exe"; + const powershell = "C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe"; + const rows = [ + { pid: 20, ppid: 1, exe: node, command: [node, `${install}/bin/tau.js`, "-p", "30187"].join("\0") }, + { pid: 11, ppid: 1, exe: powershell, command: [powershell, "-File", `${install}/scripts/windows/tau-tray.ps1`, "-Startup"].join("\0") }, + ]; + const selected = selectInstallLockingProcesses(rows, install, [], [99]); + assert.deepEqual(selected.stop.map((hit) => hit.pid), [11, 20]); +}); From a8550d59cfd8e1348509057bd1100f7436c9f6c1 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:26:55 +0000 Subject: [PATCH 02/45] fix(windows): stop a failed host candidate that got the old daemon's pid Port of ompweb-dev/ompweb#526. --- lib/hosts/update-worker.test.mjs | 3 ++- lib/upgrade-process.test.mjs | 12 +++++++++++- lib/upgrade-process.ts | 2 +- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/lib/hosts/update-worker.test.mjs b/lib/hosts/update-worker.test.mjs index 75e4e26b..1b42554d 100644 --- a/lib/hosts/update-worker.test.mjs +++ b/lib/hosts/update-worker.test.mjs @@ -101,7 +101,8 @@ async function fixture(id, { candidate = "ack", installKind = "ack", method = "n writeFileSync(starterScript, `require("node:fs").writeFileSync(${JSON.stringify(ready)},String(process.pid));\n` + (shutdownDelay ? `process.on("SIGTERM",()=>setTimeout(()=>process.exit(0),${shutdownDelay}));\n` : "") + (sessions ? sessionDaemonScript(join(install, "bin", "idle-web.js"), sessionPids, sessions === "orphan") : `require(${JSON.stringify(host)});`)); starter = await spawnNodeOutsideService(starterScript, launch.env, [host, ...layout.hostArgs]); assert.ok(starter, "the fixture requires a scope outside the suite's service"); - for (let tries = 0; !existsSync(ready) || (sessions && !existsSync(sessionPids)); tries++) { + // The starter writes its pid with writeFileSync, which can be seen empty before the write lands. + for (let tries = 0; !existsSync(ready) || !readFileSync(ready, "utf8").trim() || (sessions && !existsSync(sessionPids)); tries++) { assert.ok(tries < 100, "the scoped daemon never became ready"); await wait(100); } diff --git a/lib/upgrade-process.test.mjs b/lib/upgrade-process.test.mjs index 78ee064a..46635f13 100644 --- a/lib/upgrade-process.test.mjs +++ b/lib/upgrade-process.test.mjs @@ -230,10 +230,20 @@ test("inspection refuses the wrong role, installation or process, and stop refus await assert.rejects(upgrade.stopUpgradeProcess({ ...plan, platform: "plan9" }), /Invalid upgrade process plan/); await assert.rejects(upgrade.stopUpgradeProcess({ ...plan, supervisor: { kind: "systemd", unit: "../evil", user: false, configHash: "x" } }), /Invalid upgrade process plan/); await assert.rejects(upgrade.stopUpgradeProcess({ ...plan, supervisor: { kind: "launchd", label: "dev.ompweb.test", domain: "pid/1", plist: join(fixture.dir, "test.plist"), configHash: "x" } }), /Invalid upgrade process plan/); - await assert.rejects(upgrade.stopUpgradeProcess({ ...plan, identity: `${plan.identity}-other` }), /Invalid upgrade process plan/); assert.ok(running(fixture.pid), "none of the refused plans touched the process"); }); +test("an instance that took the inspected pid over after a restart is stopped, and a recycled pid is still refused", { timeout: 120_000 }, async () => { + const fixture = await orphanHost("restarted onto the inspected pid"); + const inspected = await inspect(fixture); + // Windows can reuse a freed pid, so a restarted instance may hold the inspected pid with a later start time; simulated here by changing the recorded identities. + const reused = { ...inspected, identity: `${inspected.identity}-previous-instance` }; + await assert.rejects(upgrade.stopUpgradeProcess({ ...reused, current: { pid: fixture.pid, identity: `${inspected.identity}-recycled` } }), /no longer the process that was inspected/); + assert.ok(running(fixture.pid), "an instance that is not the recorded one is never signalled"); + await upgrade.stopUpgradeProcess(reused); + assert.ok(!running(fixture.pid), "the recorded instance was stopped"); +}); + test("a shell restart loop is frozen while its daemon is replaced, then resumed to start the daemon again", { skip: windows && "POSIX shell loops only; Windows supervisors are tasks and services", timeout: 120_000 }, async () => { const { dir, host, pidFile } = install("loop with spaces"); const script = join(dir, "loop.sh"); diff --git a/lib/upgrade-process.ts b/lib/upgrade-process.ts index fd8d7fdc..fcc09b10 100644 --- a/lib/upgrade-process.ts +++ b/lib/upgrade-process.ts @@ -647,7 +647,7 @@ function assertPlan(plan: UpgradeProcess): void { if (typeof plan.installDir !== "string" || !isAbsolute(plan.installDir)) bad("installDir"); const current = plan.current; if (!current || typeof current !== "object" || (current.pid === null) !== (current.identity === null) || (current.pid !== null && (!Number.isSafeInteger(current.pid) || current.pid <= 1 || typeof current.identity !== "string"))) bad("current instance"); - if (current.pid === plan.pid && current.identity !== plan.identity) bad("current instance does not match the inspected process"); + // `current` follows restarts and is checked against the live process when a stop acts on it; Windows may give the restarted instance the inspected pid, so the pid alone says nothing about identity. const s = plan.supervisor; const text = (value: unknown) => typeof value === "string" && value.length > 0 && value.length <= 4096 && !/[\0-\x1f]/.test(value); if (!s || typeof s !== "object") bad("supervisor"); From e52a194eb4ffa8d54db6aeee353b4b43165095c9 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:26:55 +0000 Subject: [PATCH 03/45] fix(outbox): prune delivered rows inside the add's write transaction Port of ompweb-dev/ompweb#535. --- lib/message-outbox.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/message-outbox.ts b/lib/message-outbox.ts index 53811a2b..16d873af 100644 --- a/lib/message-outbox.ts +++ b/lib/message-outbox.ts @@ -547,11 +547,13 @@ export async function runOutboxCommand(sessionId: string, command: Record { + // Inside the add's own write lock: a separate autocommit DELETE took the lock a second time per add, and failing + // to get it (busy past busy_timeout with several servers adding at once) failed the whole add with a 500. + pruneDelivered(database, now - KEEP_DELIVERED_MS); const concurrent = row(id); if (concurrent) { if (!entryBelongsToSession(concurrent, sessionId)) return { kind: "conflict" }; From 83a35896b772754c957983c34c077466b8f619f5 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:26:56 +0000 Subject: [PATCH 04/45] fix(windows): find the host's scheduled task without administrator rights Port of ompweb-dev/ompweb#539. --- lib/upgrade-process.ts | 17 ++++++++++++----- lib/upgrade-process.windows-service.test.mjs | 15 +++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/lib/upgrade-process.ts b/lib/upgrade-process.ts index fcc09b10..8b0b3830 100644 --- a/lib/upgrade-process.ts +++ b/lib/upgrade-process.ts @@ -93,7 +93,7 @@ function assertTrustedFile(path: string, what: string): void { // ---------------------------------------------------------------- processes -interface ProcessInfo { pid: number; ppid: number; state: string; exe: string; args: string[]; cwd: string | null; created: string | null } +interface ProcessInfo { pid: number; ppid: number; state: string; exe: string; args: string[]; cwd: string | null; created: string | null; name?: string } /** CommandLineToArgvW's rules: whitespace separates arguments, quotes group, backslashes escape only before a quote. */ function splitWindowsCommandLine(line: string): string[] { @@ -192,8 +192,8 @@ async function listProcesses(): Promise { return rows; } if (process.platform === "win32") { - const out = await powershell(`$rows = @(Get-CimInstance Win32_Process | ForEach-Object { [pscustomobject]@{ pid = [int]$_.ProcessId; ppid = [int]$_.ParentProcessId; exe = [string]$_.ExecutablePath; cmd = [string]$_.CommandLine; created = $(if ($_.CreationDate) { [string]$_.CreationDate.ToUniversalTime().Ticks } else { '' }) } })\nConvertTo-Json -Compress -InputObject $rows`, 120000); - return parseJson<{ pid: number; ppid: number; exe: string; cmd: string; created: string }[]>(out, "process list").map((row) => ({ pid: row.pid, ppid: row.ppid, state: "R", exe: row.exe, args: splitWindowsCommandLine(row.cmd), cwd: null, created: row.created || null })); + const out = await powershell(`$rows = @(Get-CimInstance Win32_Process | ForEach-Object { [pscustomobject]@{ pid = [int]$_.ProcessId; ppid = [int]$_.ParentProcessId; name = [string]$_.Name; exe = [string]$_.ExecutablePath; cmd = [string]$_.CommandLine; created = $(if ($_.CreationDate) { [string]$_.CreationDate.ToUniversalTime().Ticks } else { '' }) } })\nConvertTo-Json -Compress -InputObject $rows`, 120000); + return parseJson<{ pid: number; ppid: number; name: string; exe: string; cmd: string; created: string }[]>(out, "process list").map((row) => ({ pid: row.pid, ppid: row.ppid, state: "R", name: row.name, exe: row.exe, args: splitWindowsCommandLine(row.cmd), cwd: null, created: row.created || null })); } const env = { ...process.env, LC_ALL: "C" }; const [commands, names] = await Promise.all([ @@ -495,14 +495,21 @@ async function windowsService(name: string): Promise { const out = await powershell(`$s = @(Get-CimInstance Win32_Service | Where-Object { $_.Name -eq ${psString(name)} } | ForEach-Object { ${SERVICE_FIELDS} })\nif ($s.Count -ne 1) { throw 'Service not found' }\nConvertTo-Json -Compress -InputObject $s[0]`); return parseJson(out, "service"); } +/** + * The ancestors whose services may supervise this process. A scheduled task's tree hangs under the Schedule service's + * svchost (shared by many services), which is never one. Matched by name too: a non-administrator reads no + * ExecutablePath for a SYSTEM process. + */ +export function supervisorCandidatePids(chain: Pick[]): number[] { + return chain.filter((row) => !/^svchost\.exe$/i.test(row.name ?? "") && !/(^|[\\/])svchost\.exe$/i.test(row.exe)).map((row) => row.pid); +} async function inspectWindowsSupervisor(me: ProcessInfo, rows: ProcessInfo[], installDir: string): Promise { const byPid = new Map(rows.map((row) => [row.pid, row])); const chain = ancestry(byPid, me); const normal = (value: string) => value.toLowerCase().replaceAll("\\", "/"); const scripts = [...new Set(chain.slice(1).flatMap((row) => row.args.slice(1).filter((arg) => /\.(?:ps1|cmd|bat|vbs)$/i.test(arg))))]; const found = parseJson<{ services: WindowsService[]; tasks: WindowsTask[] }>(await powershell( - // A scheduled task's tree hangs under the Schedule service's svchost (shared by many services): never a candidate supervisor. - `$ids = @(${chain.filter((row) => !/(^|[\\/])svchost\.exe$/i.test(row.exe)).map((row) => row.pid).join(",")})\n$scripts = ${psStrings(scripts.map(normal))}\n` + + `$ids = @(${supervisorCandidatePids(chain).join(",")})\n$scripts = ${psStrings(scripts.map(normal))}\n` + `$services = @(Get-CimInstance Win32_Service | Where-Object { $_.ProcessId -and ($ids -contains [int]$_.ProcessId) } | ForEach-Object { ${SERVICE_FIELDS} })\n` + `$tasks = @()\nif ($scripts.Count -gt 0) { $tasks = @(Get-ScheduledTask | ForEach-Object { $t = $_; $text = ((@($t.Actions | ForEach-Object { $_.Execute + ' ' + $_.Arguments })) -join ' ').ToLowerInvariant().Replace('\\', '/'); $hit = $false; foreach ($s in $scripts) { if ($text.Contains($s)) { $hit = $true } }; if ($hit) { ${TASK_FIELDS} } }) }\n` + `ConvertTo-Json -Compress -Depth 6 -InputObject ([pscustomobject]@{ services = $services; tasks = $tasks })`), "supervisor query"); diff --git a/lib/upgrade-process.windows-service.test.mjs b/lib/upgrade-process.windows-service.test.mjs index bec0761a..34828fe1 100644 --- a/lib/upgrade-process.windows-service.test.mjs +++ b/lib/upgrade-process.windows-service.test.mjs @@ -259,6 +259,21 @@ test("a helper launched under a service survives the service being stopped, with const INSTALL = "C:/Users/x/AppData/Roaming/npm/node_modules/@kahme247/ompweb"; +test("the Schedule service's svchost is never a supervisor candidate, even with no readable executable path", async () => { + const { supervisorCandidatePids } = await import("./upgrade-process.ts"); + // A non-administrator's Win32_Process rows: SYSTEM processes have a name but an empty ExecutablePath (issue #537). + const chain = [ + { pid: 10, name: "node.exe", exe: "E:/Nodev/node.exe" }, + { pid: 11, name: "cmd.exe", exe: "C:\\Windows\\System32\\cmd.exe" }, + { pid: 12, name: "powershell.exe", exe: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" }, + { pid: 3336, name: "svchost.exe", exe: "" }, + { pid: 13, name: "SVCHOST.EXE", exe: "" }, + { pid: 14, exe: "C:\\Windows\\System32\\svchost.exe" }, + { pid: 700, name: "services.exe", exe: "" }, + ]; + assert.deepEqual(supervisorCandidatePids(chain), [10, 11, 12, 700]); +}); + test("a tray exe inside the package is selected without a pid in web-service.json", async () => { const { selectInstallLockingProcesses } = await import("./upgrade-process.ts"); const rows = [ From 45c6637360e2d3c76a4a5bcd399d078d576eac02 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:31:15 +0000 Subject: [PATCH 05/45] fix(updates): build the tray at release and resume host update downloads Port of ompweb-dev/ompweb#532. The committed bin/tau-tray.exe was still the omp-web build; releases now build it from native/tray. The omp runner download resume does not apply: tau has no runner download. --- .github/workflows/publish.yml | 6 +++ .github/workflows/verify-pr.yml | 9 ++++ lib/hosts/update-worker.test.mjs | 67 ++++++++++++++++++++++++ lib/hosts/update-worker.ts | 87 ++++++++++++++++++++++++++------ scripts/build-tray.sh | 12 +++++ 5 files changed, 166 insertions(+), 15 deletions(-) create mode 100644 scripts/build-tray.sh diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index cdca70f2..08891c3a 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,6 +35,12 @@ jobs: - run: npm install --global npm@^11.5.1 - run: npm ci + # The package's Windows tray, built from this tag's native/tray rather than the committed copy (ompweb-dev/ompweb#530). + - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5.4.0 + with: + dotnet-version: 8.0.x + - name: Build the Windows tray + run: sh scripts/build-tray.sh # The pi tau drives (`pi --mode rpc`), on PATH for the tests' live sessions, the smoke tests and preflight. - name: Install pi run: npm install --global "@earendil-works/pi-coding-agent@$PI_VERSION" diff --git a/.github/workflows/verify-pr.yml b/.github/workflows/verify-pr.yml index 52fc8642..8b9f054b 100644 --- a/.github/workflows/verify-pr.yml +++ b/.github/workflows/verify-pr.yml @@ -52,6 +52,15 @@ jobs: - name: Install dependencies run: npm ci + # What publish.yml runs before npm publish: the tray must build from these sources and carry this commit. + - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5.4.0 + if: runner.os == 'Linux' + with: + dotnet-version: 8.0.x + - name: Build the Windows tray (Linux only) + if: runner.os == 'Linux' + run: sh scripts/build-tray.sh + # The pi tau drives (`pi --mode rpc`), on PATH for the tests' live sessions, the smoke tests and preflight. - name: Install pi run: npm install --global "@earendil-works/pi-coding-agent@$PI_VERSION" diff --git a/lib/hosts/update-worker.test.mjs b/lib/hosts/update-worker.test.mjs index 1b42554d..c3a27f09 100644 --- a/lib/hosts/update-worker.test.mjs +++ b/lib/hosts/update-worker.test.mjs @@ -366,6 +366,73 @@ test("a release download streams to disk with its digest and stops at the size l } finally { globalThis.fetch = original; rmSync(dir, { recursive: true, force: true }); } }); +test("a dropped release download resumes with a Range request, and a server that ignores the range restarts it", async () => { + const original = globalThis.fetch; + const dir = mkdtempSync(join(base, "resume-")); + const body = Buffer.alloc(300_000); + for (let index = 0; index < body.length; index++) body[index] = index % 251; + const ranges = []; + let drops = 1; + let honorRange = true; + globalThis.fetch = async (_url, init) => { + const range = init.headers.Range ?? null; + ranges.push(range); + const from = range && honorRange ? Number(/^bytes=(\d+)-$/.exec(range)[1]) : 0; + const rest = body.subarray(from); + const headers = from ? { "content-range": `bytes ${from}-${body.length - 1}/${body.length}` } : {}; + // The first response drops after 100 000 bytes, as a broken connection does. + const drop = drops-- > 0; + let pulls = 0; + const stream = new ReadableStream({ pull(controller) { + if (pulls++ === 0) controller.enqueue(drop ? rest.subarray(0, 100_000) : rest); + else if (drop) controller.error(new TypeError("terminated")); + else controller.close(); + } }); + return new Response(stream, { status: from ? 206 : 200, headers }); + }; + const expected = `sha256:${createHash("sha256").update(body).digest("hex")}`; + try { + const file = join(dir, "runner"); + assert.equal(await worker.downloadHostUpdateFile("https://github.com/x", file, body.length), expected); + assert.deepEqual(ranges, [null, "bytes=100000-"]); + assert.deepEqual(readFileSync(file), body); + + // With `resume`, an earlier attempt's bytes are continued; a 200 answer to the range starts the file over. + const partial = join(dir, "partial"); + writeFileSync(partial, body.subarray(0, 50_000)); + ranges.length = 0; + assert.equal(await worker.downloadHostUpdateFile("https://github.com/x", partial, body.length, undefined, true), expected); + assert.deepEqual(ranges, ["bytes=50000-"]); + writeFileSync(partial, body.subarray(0, 50_000)); + honorRange = false; + ranges.length = 0; + assert.equal(await worker.downloadHostUpdateFile("https://github.com/x", partial, body.length, undefined, true), expected); + assert.deepEqual(readFileSync(partial), body); + + // A server that sends less of a range than asked for is asked for the rest. + ranges.length = 0; + globalThis.fetch = async (_url, init) => { + const range = init.headers.Range ?? null; + ranges.push(range); + const from = Number(/^bytes=(\d+)-$/.exec(range)[1]); + const end = Math.min(from + 100_000, body.length); + return new Response(body.subarray(from, end), { status: 206, headers: { "content-range": `bytes ${from}-${end - 1}/${body.length}` } }); + }; + writeFileSync(join(dir, "short"), body.subarray(0, 100_000)); + assert.equal(await worker.downloadHostUpdateFile("https://github.com/x", join(dir, "short"), body.length, undefined, true), expected); + assert.deepEqual(ranges, ["bytes=100000-", "bytes=200000-"]); + + // A server error is retried; any other HTTP refusal is not. + let failing = 1; + globalThis.fetch = async () => (failing-- > 0 ? new Response("busy", { status: 503 }) : new Response(body)); + assert.equal(await worker.downloadHostUpdateFile("https://github.com/x", join(dir, "busy"), body.length), expected); + ranges.length = 0; + globalThis.fetch = async (_url, init) => { ranges.push(init.headers.Range ?? null); return new Response("missing", { status: 404 }); }; + await assert.rejects(worker.downloadHostUpdateFile("https://github.com/x", join(dir, "missing"), body.length), /\(404\)/); + assert.equal(ranges.length, 1); + } finally { globalThis.fetch = original; rmSync(dir, { recursive: true, force: true }); } +}); + test("Windows ZIP entries are extracted from bounded central metadata and symlinks are rejected", () => { const name = Buffer.from("tau-windows-x64/tau.exe"); const data = Buffer.from("hello"); diff --git a/lib/hosts/update-worker.ts b/lib/hosts/update-worker.ts index 6948313f..698bf7f8 100644 --- a/lib/hosts/update-worker.ts +++ b/lib/hosts/update-worker.ts @@ -1,7 +1,7 @@ // Old daemons copy only this file. Keep its startup Node-only and load lifecycle code before any swap, from private copies or the descriptor's verified installation. import { createHash, randomUUID } from "node:crypto"; import { execFile } from "node:child_process"; -import { chmodSync, closeSync, createReadStream, createWriteStream, existsSync, fstatSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, writeFileSync, writeSync } from "node:fs"; +import { chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fstatSync, ftruncateSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, writeFileSync, writeSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { createGunzip, inflateRawSync } from "node:zlib"; @@ -198,39 +198,96 @@ export function requireHostUpdateRecovery(id: string, error: string): void { }); } -async function readHostUpdate(url: string, maxBytes: number, timeout: number, onChunk: (chunk: Uint8Array) => void): Promise { +/** A refusal that a new request would only repeat (an HTTP error, a size or destination check): never resumed. */ +class ReleaseRefusal extends Error {} +/** `from` > 0 asks for the bytes after `from`; `onStart(resumed, total)` reports whether the server sent only those (206, + * with the file's whole size when its Content-Range names it) or the whole file again, before the first chunk. `idle` + * aborts a response that sends nothing for that long. */ +async function readHostUpdate(url: string, maxBytes: number, timeout: number, onChunk: (chunk: Uint8Array) => void, from = 0, onStart?: (resumed: boolean, total?: number) => void, idle = timeout): Promise { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeout); + const stall = setTimeout(() => controller.abort(), idle); try { - const response = await fetch(url, { signal: controller.signal, cache: "no-store", headers: { "User-Agent": "tau-host-updater" } }); - if (!response.ok || !response.body) throw new Error(`Release request failed (${response.status})`); - if (response.url && (!response.url.startsWith("https://") || !["raw.githubusercontent.com", "api.github.com", "github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com", "registry.npmjs.org"].includes(new URL(response.url).hostname))) throw new Error("Unexpected release download destination"); - if (Number(response.headers.get("content-length")) > maxBytes) throw new Error("Release response is too large"); + const response = await fetch(url, { signal: controller.signal, cache: "no-store", headers: { "User-Agent": "tau-host-updater", ...(from > 0 ? { Range: `bytes=${from}-` } : {}) } }); + // 416: nothing lies after `from`; the caller's digest check decides whether what it holds is the file. + if (from > 0 && response.status === 416) { onStart?.(true); return; } + const range = /^bytes (\d+)-\d+\/(\d+|\*)$/.exec(response.headers.get("content-range") ?? ""); + const resumed = from > 0 && response.status === 206 && Number(range?.[1]) === from; + // A server error, 408 or 429 is worth another request; any other refusal is not. + if (!response.ok || !response.body) throw new (response.status >= 500 || [408, 429].includes(response.status) ? Error : ReleaseRefusal)(`Release request failed (${response.status})`); + if (response.status === 206 && !resumed) throw new ReleaseRefusal(`Release request failed (${response.status})`); + if (response.url && (!response.url.startsWith("https://") || !["raw.githubusercontent.com", "api.github.com", "github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com", "registry.npmjs.org"].includes(new URL(response.url).hostname))) throw new ReleaseRefusal("Unexpected release download destination"); + const limit = resumed ? maxBytes - from : maxBytes; + if (Number(response.headers.get("content-length")) > limit) throw new ReleaseRefusal("Release response is too large"); + onStart?.(resumed, resumed && range?.[2] !== "*" ? Number(range![2]) : undefined); const reader = response.body.getReader(); let size = 0; try { while (true) { + stall.refresh(); const item = await reader.read(); if (item.done) break; size += item.value.byteLength; - if (size > maxBytes) throw new Error("Release response is too large"); + if (size > limit) throw new ReleaseRefusal("Release response is too large"); onChunk(item.value); } } catch (error) { await reader.cancel().catch(() => {}); throw error; } - } finally { clearTimeout(timer); } + } finally { + clearTimeout(timer); + clearTimeout(stall); + controller.abort(); // a refused response's body is never read: release its connection + } } export async function fetchHostUpdateBytes(url: string, maxBytes: number, timeout = 5000): Promise { const chunks: Uint8Array[] = []; await readHostUpdate(url, maxBytes, timeout, (chunk) => { chunks.push(chunk); }); return Buffer.concat(chunks); } -/** Streams the response into a new `file` (never whole in memory); returns its `sha256:` digest. */ -export async function downloadHostUpdateFile(url: string, file: string, maxBytes: number, timeout = DOWNLOAD_TIMEOUT_MS): Promise { - const hash = createHash("sha256"); - const fd = openSync(file, "wx", 0o600); - try { await readHostUpdate(url, maxBytes, timeout, (chunk) => { writeSync(fd, chunk); hash.update(chunk); }); } - finally { closeSync(fd); } - return `sha256:${hash.digest("hex")}`; +/** A download request that receives nothing for this long is dropped and resumed. */ +const DOWNLOAD_STALL_MS = 60_000; +/** Consecutive resumed requests that may fail without receiving a byte before the download gives up. */ +const DOWNLOAD_RETRIES = 3; +/** + * Streams the response into `file` (never whole in memory); returns its `sha256:` digest. A request that drops or + * stalls is resumed with an HTTP `Range` request where it stopped, within `timeout` for the whole call. With `resume`, + * `file` may already hold the start of the download (an earlier call's bytes), which is continued the same way, and the + * digest is then that of the whole file as it is on disk once complete, whoever else wrote to it. + */ +export async function downloadHostUpdateFile(url: string, file: string, maxBytes: number, timeout = DOWNLOAD_TIMEOUT_MS, resume = false): Promise { + const deadline = Date.now() + timeout; + // Read-write without O_APPEND: Windows refuses to truncate a file opened for appending. Writes are positional. + const fd = openSync(file, constants.O_RDWR | constants.O_CREAT | (resume ? 0 : constants.O_EXCL), 0o600); + try { + let hash = createHash("sha256"); + let size = 0; + const buffer = Buffer.alloc(1024 * 1024); + for (let read; (read = readSync(fd, buffer, 0, buffer.length, size)) > 0; size += read) hash.update(buffer.subarray(0, read)); + if (size > maxBytes) { ftruncateSync(fd, 0); hash = createHash("sha256"); size = 0; } + for (let failures = 0; ;) { + const before = size; + let total: number | undefined; + try { + await readHostUpdate(url, maxBytes, Math.max(1, deadline - Date.now()), (chunk) => { writeSync(fd, chunk, 0, chunk.byteLength, size); hash.update(chunk); size += chunk.byteLength; }, size, (resumed, whole) => { + total = whole; + if (!resumed && size > 0) { ftruncateSync(fd, 0); hash = createHash("sha256"); size = 0; } + }, Math.min(DOWNLOAD_STALL_MS, timeout)); + // A server may send less of a range than asked for: ask for the rest. + if (total !== undefined && size < total) { + failures = size > before ? 0 : failures + 1; + if (failures > DOWNLOAD_RETRIES || Date.now() >= deadline) throw new ReleaseRefusal("Release download stopped short of its size"); + continue; + } + if (!resume) return `sha256:${hash.digest("hex")}`; + const disk = createHash("sha256"); + for (let read, at = 0; (read = readSync(fd, buffer, 0, buffer.length, at)) > 0; at += read) disk.update(buffer.subarray(0, read)); + return `sha256:${disk.digest("hex")}`; + } catch (error) { + failures = size > before ? 0 : failures + 1; + if (error instanceof ReleaseRefusal || failures > DOWNLOAD_RETRIES || Date.now() >= deadline) throw error; + await pause(Math.min(2000, Math.max(0, deadline - Date.now()))); + } + } + } finally { closeSync(fd); } } export function hostReleaseName(platform = process.platform, arch = process.arch): string { if (!["linux", "darwin", "win32"].includes(platform) || !["x64", "arm64"].includes(arch) || (platform === "win32" && arch !== "x64")) throw new Error(`Host updates are unsupported on ${platform}/${arch}`); diff --git a/scripts/build-tray.sh b/scripts/build-tray.sh new file mode 100644 index 00000000..829586de --- /dev/null +++ b/scripts/build-tray.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Builds bin/tau-tray.exe from native/tray at the checked-out commit and checks that the exe carries that commit, +# so a release never ships a tray older than its sources (ompweb-dev/ompweb#530). Runs on Linux too: tray.csproj sets +# EnableWindowsTargeting. publish.yml runs it before npm publish; verify-pr.yml runs it on every PR. +set -eu +sha=$(git rev-parse HEAD) +out=$(mktemp -d) +dotnet publish native/tray/tray.csproj -c Release -r win-x64 -p:SourceRevisionId="$sha" -o "$out" +grep -qa "+$sha" "$out/tau-tray.exe" || { echo "tau-tray.exe does not carry commit $sha" >&2; exit 1; } +cp "$out/tau-tray.exe" bin/tau-tray.exe +rm -rf "$out" +echo "bin/tau-tray.exe built from $sha" From 30ddc55aa928f4ef9938205a0d4c2fe019390fd6 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:36:20 +0000 Subject: [PATCH 06/45] fix(hosts): report pi to the server once it answers after the daemon started Port of ompweb-dev/ompweb#542. A daemon whose startup read found no pi reads the version again (30 s, doubling to 5 min) and sends a pi_version link message, so a host that gets pi after its daemon started comes online without a restart. The runner download retry does not apply: tau has no runner download. --- lib/hosts/daemon.test.mjs | 24 +++++++++++++++++++++++- lib/hosts/daemon.ts | 36 ++++++++++++++++++++++++++++++++++-- lib/hosts/hub.test.mjs | 13 +++++++++++++ lib/hosts/hub.ts | 3 +++ lib/hosts/link-protocol.ts | 7 ++++++- lib/pi/pi-cli.ts | 4 +++- 6 files changed, 82 insertions(+), 5 deletions(-) diff --git a/lib/hosts/daemon.test.mjs b/lib/hosts/daemon.test.mjs index f84962c5..8edb339c 100644 --- a/lib/hosts/daemon.test.mjs +++ b/lib/hosts/daemon.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { execFileSync, spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, utimesSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import test, { after } from "node:test"; @@ -551,6 +551,28 @@ test("an http:// loopback server links without --allow-http", async () => { } }); +test("a host whose pi was missing at start reads it again on its own, without a server asking", async () => { + const log = captureLog(); + renameSync(fakePi, `${fakePi}.missing`); + const server = scriptedServer(); + let daemon; + try { + daemon = runHostDaemon({ url: server.url, token: "t", allowHttp: false, piVersionRetryMs: 20 }); + await waitFor(() => server.hellos.length === 1, "the hello"); + assert.equal(server.hellos[0].piVersion, null); + // Past the first retries (20, 40, 80 ms): each miss arms the next. + await sleep(200); + assert.equal(server.up.some((m) => m.type === "pi_version"), false, "nothing while pi is missing"); + renameSync(`${fakePi}.missing`, fakePi); + await waitFor(() => server.up.some((m) => m.type === "pi_version"), "the retried pi_version"); + assert.equal(server.up.find((m) => m.type === "pi_version").piVersion, "14.0.0-fake"); + } finally { + if (existsSync(`${fakePi}.missing`)) renameSync(`${fakePi}.missing`, fakePi); + await daemon?.stop(); + log.restore(); + } +}); + test("a running host deletes expired staged uploads every hour, not only when it starts or takes an upload", async (t) => { const log = captureLog(); t.mock.timers.enable({ apis: ["setInterval"] }); diff --git a/lib/hosts/daemon.ts b/lib/hosts/daemon.ts index f5b143a1..b9e7de77 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -94,7 +94,11 @@ export interface HostDaemon { started: Promise; control(command: HostControlCommand): HostControlStatus; } -type DaemonOptions = { allowHttp: boolean; url?: string; token?: string; links?: HostLink[] }; +type DaemonOptions = { allowHttp: boolean; url?: string; token?: string; links?: HostLink[]; + /** Tests. */ piVersionRetryMs?: number }; +/** A daemon whose pi version read found nothing reads it again after this, doubling up to PI_VERSION_RETRY_MAX_MS. */ +const PI_VERSION_RETRY_MS = 30_000; +const PI_VERSION_RETRY_MAX_MS = 5 * 60_000; /** * `path` under `route` (`/api/hosts//`) on a linked server, with that link's token; null when dot segments * (also encoded) would climb out of `route`, which the route's own allow-list cannot see. @@ -126,6 +130,7 @@ export function runHostDaemon(options: DaemonOptions): HostDaemon { let stopping: Promise | undefined; let updateStateWarningLogged = false; let reloadTimer: NodeJS.Timeout | undefined; + let versionRetry: NodeJS.Timeout | undefined, versionRetryMs = options.piVersionRetryMs ?? PI_VERSION_RETRY_MS; let drained = process.env.TAU_HOST_DRAINED === "1"; let preparationsInFlight = 0, operationsInFlight = 0, nativeUpdatesInFlight = 0; const executable = realpathSync(process.execPath); @@ -507,7 +512,7 @@ export function runHostDaemon(options: DaemonOptions): HostDaemon { } function shutdown(code: number): Promise { if (stopping) return stopping; - stopped = true; watcher.close(); clearTimeout(reloadTimer); clearInterval(sweepTimer); clearInterval(capacityTimer); uploadRetention.stop(); + stopped = true; watcher.close(); clearTimeout(reloadTimer); clearInterval(sweepTimer); clearInterval(capacityTimer); clearTimeout(versionRetry); uploadRetention.stop(); clearTimeout(recoveryTimer); // Freeze before exit handlers observe children stopping. resume.freeze(); @@ -546,7 +551,34 @@ export function runHostDaemon(options: DaemonOptions): HostDaemon { .finally(() => { operationsInFlight--; if (!stopped) for (const link of links.values()) link.start(); + if (!stopped && piVersion === null) void refreshPiVersion(); }); + // A null version in the hello marks this host "pi not installed" and its sessions refused. pi installed after the + // daemon started, or a first start Windows' antivirus holds past the probe, misses the startup read: read again until pi answers, + // then tell every server (a link made later says it in its hello). One read at a time. + let refreshing: Promise | undefined; + function scheduleVersionRetry(): void { + clearTimeout(versionRetry); + versionRetry = setTimeout(() => void refreshPiVersion(), versionRetryMs); + versionRetry.unref?.(); + versionRetryMs = Math.min(versionRetryMs * 2, PI_VERSION_RETRY_MAX_MS); + } + async function readVersionAgain(): Promise { + await versionRead; + if (stopped || piVersion !== null) return; + clearTimeout(versionRetry); // this read is the retry; a miss arms the next one + const version = await getPiVersion(true).catch(error => { log("could not read pi version: " + reason(error)); return null; }); + if (stopped || piVersion !== null) return; + if (version === null) { + scheduleVersionRetry(); + return; + } + piVersion = version; + for (const link of links.values()) link.queue({ type: "pi_version", piVersion: version }, "pi_version"); + } + function refreshPiVersion(): Promise { + return refreshing ??= readVersionAgain().finally(() => { refreshing = undefined; }); + } const started = Promise.all([startupSweep, startupRecovery, versionRead]).then(() => {}); return { stop: () => shutdown(0), done, control, started }; } diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index 25bcbd49..5528fb2d 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -247,6 +247,19 @@ test("hello without omp marks the host pi-missing and spawnRpc rejects", async ( await down.cancel(); }); +test("a pi_version after a hello without pi brings the host online", async () => { + const link = await linkedHost("Late pi", { piVersion: null }); + assert.equal(link.remote.status(), "pi-missing"); + let changes = 0; + const stop = hub.onHostsChange(() => changes++); + assert.deepEqual(linkPost(link, [{ type: "pi_version", seq: 1, piVersion: "19.0.0" }]), [1]); + stop(); + assert.equal(link.remote.status(), "online"); + assert.ok(changes > 0, "Settings and the sidebar hear of it"); + assert.equal(hub.listHosts().find((h) => h.id === link.id).piVersion, "19.0.0"); + await link.down.cancel(); +}); + test("a second link with the same token closes the first socket with 4409, and frames still arriving on it are ignored", async () => { const a = await linkedHost("Two daemons"); assert.deepEqual(linkPost(a, [{ type: "stdout", seq: 500, ch: "none", line: "x" }]), [500]); diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 5d9c864b..1d2f3d4b 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -917,6 +917,9 @@ function applyUp(link: Link, message: UpMessage | UnknownMessage, whole?: UpMess return link.channels.get(message.ch)?.deliverLine(message.line); case "stderr": return link.channels.get(message.ch)?.deliverStderr(message.chunk); + case "pi_version": + link.piVersion = message.piVersion; + return setStatus(link, link.status === "pi-missing" ? "online" : link.status); case "resync": return link.channels.get(message.ch)?.deliverResync(); case "exit": { diff --git a/lib/hosts/link-protocol.ts b/lib/hosts/link-protocol.ts index 2ce370cb..e1bf7a46 100644 --- a/lib/hosts/link-protocol.ts +++ b/lib/hosts/link-protocol.ts @@ -163,6 +163,9 @@ export type UpMessage = | { type: "resync"; seq: number; ch: string } | { type: "notifier"; seq: number; on: boolean } | { type: "sessions_changed"; seq: number } + /** The pi version found after the hello said none (pi was installed or first answered later); a hub that predates + * it skips the type and keeps "pi not installed" until the next hello. */ + | { type: "pi_version"; seq: number; piVersion: string } | { type: "channels_changed"; seq: number; channels: HelloChannel[] } /** The daemon's link samples, at most LINK_LIMITS.statsSamples; a hub that predates it skips the type. Advisory: the * receiver keeps the valid ones and counts the rest in `invalid` (decodeUp only; a sender leaves it out). */ @@ -280,7 +283,7 @@ export function isHostOp(name: string): name is HostOpName { } const DOWN_TYPES: readonly string[] = ["welcome", "stdin", "kill", "interest", "host_tools", "req", "ping", "pong", "ack"]; -const UP_TYPES: readonly string[] = ["hello", "stdout", "stderr", "exit", "resync", "notifier", "sessions_changed", "channels_changed", "stats", "capacity", "config_state", "res", "upload_ack", "workspace_file", "ping", "pong", "ack"]; +const UP_TYPES: readonly string[] = ["hello", "stdout", "stderr", "exit", "resync", "notifier", "sessions_changed", "pi_version", "channels_changed", "stats", "capacity", "config_state", "res", "upload_ack", "workspace_file", "ping", "pong", "ack"]; /** `otherDirection`: the types only the other direction decodes; one of those arrived on the wrong way. */ function unknownMessage(o: Obj, otherDirection: readonly string[]): UnknownMessage { @@ -490,6 +493,8 @@ export function decodeUp(line: string): UpMessage | UnknownMessage { return { type: "notifier", seq: seqNum(o, "seq"), on: bool(o, "on") }; case "sessions_changed": return { type: "sessions_changed", seq: seqNum(o, "seq") }; + case "pi_version": + return { type: "pi_version", seq: seqNum(o, "seq"), piVersion: str(o, "piVersion") }; case "channels_changed": return { type: "channels_changed", seq: seqNum(o, "seq"), channels: channels(o) }; case "stats": diff --git a/lib/pi/pi-cli.ts b/lib/pi/pi-cli.ts index 3c8986e1..d1b798ed 100644 --- a/lib/pi/pi-cli.ts +++ b/lib/pi/pi-cli.ts @@ -95,7 +95,9 @@ export function resolvePiBin(fresh = false): string | null { /** Return the installed CLI version, using file metadata to invalidate cached * results without launching pi on every visit. An expiry covers opaque * launchers; concurrent callers share a probe. */ -export function getPiVersion(): Promise { +export function getPiVersion(fresh = false): Promise { + // fresh: a probe of its own, past the miss caches; one in flight may have looked before the binary arrived. + if (fresh) { binMissAt = 0; versionMiss = null; return probePiVersion(); } versionProbe ??= probePiVersion().finally(() => { versionProbe = null; }); From 484dcc576cc10981555c20fa07aa49ef3591de46 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:36:28 +0000 Subject: [PATCH 07/45] docs(agents): note the pi_version link message --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index a86a07e0..7c71df60 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -311,7 +311,7 @@ The table is static imports, not a runtime glob, so `bun build --compile` bundle ### Remote hosts (`lib/hosts/`, `app/api/hosts/`, `bin/tau-host.js`) - **Host seam** (`lib/hosts/host.ts`). Every host, this machine included, is reached over its daemon's link: `getHost(id)` returns a `RemoteHost`. `getHost("local")` is this machine's own `tau host`. `localHost` (`local-host.ts`) is the daemon's side. `RpcProcess`, the wrapper, the event hub, notifications, the queue and `/btw` never see where pi runs. Session and project file reads are `host.sessionOps` (`session-ops.ts`, run in the daemon), addressed by session id, never by path: routes use `resolveSessionHostOr404` (`lib/api-utils.ts`). New route code must not open a session file on main. Workspace operations (files, index, shell output, watch, Git/worktrees, browsing, default cwd `~/tau-cwd-YYYYMMDD`, clone) are `Host.workspaceOps` (`lib/workspace-types.ts`, `workspace-ops.ts`) for every host; they never fall back to main. `SessionInfo.hostId` and `ManagedProject.hostId` carry the host; sidebar/project state keys on `hostProjectKey` (bare path here, `:` elsewhere). -- **Shared hosts** (`docs/specs/2026-11-06-multi-server-host-design.md`): one daemon links every server in `host.json` (the top-level pair is its primary link, `links` the others). `open` joins one session process; events fan out, command replies return only to their sender. The daemon owns lifecycle, streaming snapshots (`stream-snapshot.ts`) and first-answer dialog settlement (`shared-requests.ts`). Web callbacks (host tools) go to the last-active eligible server and are not blindly retried. `channels_changed` announces background runs; `sessions_changed` invalidates lists; one link is the notification publisher (`notifier`). Cross-server fences live in the daemon: a history edit takes the `editLease` op before preflight, and a `peer_message_command` marker makes another server's identical echo ambiguous (`watchReplacement`). An open's preparation lease passes only to the command that asked for it (`withPendingCommand(run, true)`); a command timeout that recycles the child stops the shared process (`destroyAndWait(reason, true)`). Two daemons must never run competing `pi --resume` children on one agent dir. +- **Shared hosts** (`docs/specs/2026-11-06-multi-server-host-design.md`): one daemon links every server in `host.json` (the top-level pair is its primary link, `links` the others). `open` joins one session process; events fan out, command replies return only to their sender. The daemon owns lifecycle, streaming snapshots (`stream-snapshot.ts`) and first-answer dialog settlement (`shared-requests.ts`). Web callbacks (host tools) go to the last-active eligible server and are not blindly retried. `channels_changed` announces background runs; `sessions_changed` invalidates lists; `pi_version` reports pi found after a hello that said none (the daemon reads it again, 30 s doubling to 5 min); one link is the notification publisher (`notifier`). Cross-server fences live in the daemon: a history edit takes the `editLease` op before preflight, and a `peer_message_command` marker makes another server's identical echo ambiguous (`watchReplacement`). An open's preparation lease passes only to the command that asked for it (`withPendingCommand(run, true)`); a command timeout that recycles the child stops the shared process (`destroyAndWait(reason, true)`). Two daemons must never run competing `pi --resume` children on one agent dir. - **Application link** (`/api/hosts/link`, `link-protocol.ts`, `hub.ts`, `daemon-link.ts`, `daemon-channels.ts`): one WebSocket per host per web server, dialled by the daemon. Text frames carry messages (hub → daemon one per frame; daemon → hub newline-separated batches flushed every `flushMs` (16 ms) or at one piece); binary frames carry large op results (before the `res` naming them) and upload bytes (hub → daemon, `up:`). Every line except `hello`/`welcome`/`ack`/`ping`/`pong` has a per-direction `seq`; each side keeps unacked lines, resends after a reconnect and drops a `seq` it already applied. The daemon's first line of every frame is an `ack`; the hub answers every uplink frame with exactly one. Lines over `pieceBytes` (256 KiB) go as sequenced `part` messages (`PartJoiner`), results as binary frames of at most a piece; both sides queue per key (channel or request) in `LinkSender` and send round-robin. Each side sends queued units only while less than `unackedBytes` (512 KiB) is unacked (the daemon also waits for `bufferedAmount` under two pieces); control lines skip the window. The hub decodes a whole frame before applying any of it. `hello.ack === 0` means a fresh daemon. Each `hello.channels` entry carries `pending`: the raw stdout lines of that child's still-open `host_tool_call`s and blocking `ui_request`s (`pending-requests.ts`), or null past `pendingBytes`. Close codes (`LINK_CLOSE`): 1001 going away (shutdown), 1007 bad frame, 1008 bad first frame, 1009 too big, 4409 replaced, 4426 version; a revoked or unknown host's hello gets a plain close. - **Protocol versions.** The application link is v1 (`MIN_LINK_PROTOCOL_VERSION` = `LINK_PROTOCOL_VERSION` = 1, literal one-liners that deploy scripts parse with `sed`). A released version changes only compatibly: an added optional field or a message type receivers skip is fine; a changed type or meaning, or a newly required field, needs a new version. Receivers skip unknown message types (acking their `seq`) and answer unknown ops 501 `unknown_op`. A hello outside the range gets 4426 with `{"serverVersion":N}`. Once versions are released, main keeps at least N-1, and the first released version is a floor `MIN_LINK_PROTOCOL_VERSION` never goes above. Upgrade order: web app first, then hosts. - **Maintenance API v1** (`maintenance-protocol.ts`, `maintenance-hub.ts`, `daemon-maintenance.ts`, `/api/hosts/maintenance`): a separate request/reply WebSocket the daemon dials with the same bearer token, versioned apart (`MAINTENANCE_API_VERSION`) and kept stable so a host whose application protocol differs can still be inspected and updated. Ops: `status`, `listSessions`, `checkUpdates`, `updateSoftware`. Frames ≤ 1 MiB, 8 requests in flight, 30 s per request; a hello with another API version gets 4426 `{"apiVersion":N}`. Its hello reports `protocolVersion` (advisory), `tauVersion`, `piVersion`, platform and capabilities. Nothing it meets (no API on the server, another version, a refused token) stops the daemon or its pi children. Host updates use only this API (see "Updates"). From 00e47dfbf531ec864c0c00935d9db3f0154def67 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:36:46 +0000 Subject: [PATCH 08/45] fix(chat): count only completed subagents in the subagents header Port of ompweb-dev/ompweb#440. --- components/ComposerPanels.subagents.test.mjs | 56 ++++++++++++++++++++ components/ComposerPanels.tsx | 15 ++++-- lib/i18n/locales/en.json | 1 + lib/i18n/locales/ja.json | 1 + lib/i18n/locales/zh-CN.json | 1 + 5 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 components/ComposerPanels.subagents.test.mjs diff --git a/components/ComposerPanels.subagents.test.mjs b/components/ComposerPanels.subagents.test.mjs new file mode 100644 index 00000000..93551792 --- /dev/null +++ b/components/ComposerPanels.subagents.test.mjs @@ -0,0 +1,56 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test, { afterEach, beforeEach } from "node:test"; +import React from "react"; +const { cleanup, render, screen } = await import("@testing-library/react/pure.js"); + +const { ComposerPanels } = await import("./ComposerPanels.tsx"); + +beforeEach(() => { + window.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {} }); + // Collapsible headers scroll their active row into view. + window.HTMLElement.prototype.scrollIntoView = () => {}; +}); +afterEach(() => { + cleanup(); + localStorage.clear(); + delete window.matchMedia; + delete window.HTMLElement.prototype.scrollIntoView; +}); + +function makeSubagent(index, status) { + return { id: `s${index}`, agent: "explore", index, status, task: `task ${index}`, source: "live" }; +} + +function renderPanels(subagents) { + render(React.createElement(ComposerPanels, { + todoPhases: [], + subagents, + onSelectSubagent() {}, + defaultExpanded: true, + })); +} + +test("subagents header shows the completed count once nothing is running (#352)", () => { + renderPanels(Array.from({ length: 6 }, (_, i) => makeSubagent(i, "completed"))); + const counter = screen.getByLabelText("6/6 complete"); + assert.equal(counter.textContent, "6/6 complete"); +}); + +test("subagents header counts only truly completed runs, not failed ones (#352)", () => { + renderPanels([ + ...Array.from({ length: 4 }, (_, i) => makeSubagent(i, "completed")), + ...Array.from({ length: 2 }, (_, i) => makeSubagent(i + 4, "failed")), + ]); + const counter = screen.getByLabelText("4/6 complete"); + assert.equal(counter.textContent, "4/6 complete"); +}); + +test("subagents header still shows the running count while any subagent runs", () => { + renderPanels([ + ...Array.from({ length: 2 }, (_, i) => makeSubagent(i, "started")), + ...Array.from({ length: 4 }, (_, i) => makeSubagent(i + 2, "completed")), + ]); + const counter = screen.getByLabelText("2 running · 6 total"); + assert.equal(counter.textContent, "2/6"); +}); diff --git a/components/ComposerPanels.tsx b/components/ComposerPanels.tsx index 33eff924..02d0fea0 100644 --- a/components/ComposerPanels.tsx +++ b/components/ComposerPanels.tsx @@ -166,6 +166,15 @@ function SubagentsPanel({ subagents, onSelectSubagent, defaultExpanded = false, (subagent.source !== "history" && subagent.status === "started" ? running : completed).push(subagent); } const runningCount = running.length; + // Once nothing runs, the header counts finished subagents instead of + // showing 0/N (#352): "0/6" reads as if nothing finished. Only + // status === "completed" counts: the `completed` bucket above also holds + // failed/aborted runs, and "6/6 complete" must not claim those. + const completedCount = subagents.filter((subagent) => subagent.status === "completed").length; + const headerCount = runningCount === 0 ? completedCount : runningCount; + const headerSummary = runningCount === 0 + ? t("chatWindow.subagentCompletedSummary", { completed: completedCount, total: subagents.length }) + : t("chatWindow.subagentSummary", { running: runningCount, total: subagents.length }); function renderChip(subagent: SubagentInfo) { const stateLabel = t(SUBAGENT_STATE_KEYS[subagent.status]); @@ -255,10 +264,10 @@ function SubagentsPanel({ subagents, onSelectSubagent, defaultExpanded = false, ) : null} - {runningCount}/{subagents.length} + {runningCount === 0 ? headerSummary : `${headerCount}/${subagents.length}`} Date: Mon, 23 Nov 2026 09:36:47 +0000 Subject: [PATCH 09/45] feat(chat): render svg code fences inline Port of ompweb-dev/ompweb#455. --- components/MarkdownCode.tsx | 4 ++ components/SvgBlock.test.mjs | 114 +++++++++++++++++++++++++++++++++++ components/SvgBlock.tsx | 112 ++++++++++++++++++++++++++++++++++ 3 files changed, 230 insertions(+) create mode 100644 components/SvgBlock.test.mjs create mode 100644 components/SvgBlock.tsx diff --git a/components/MarkdownCode.tsx b/components/MarkdownCode.tsx index 51645cc1..9806c370 100644 --- a/components/MarkdownCode.tsx +++ b/components/MarkdownCode.tsx @@ -1,5 +1,6 @@ import type { HTMLAttributes } from "react"; import { MermaidBlock, CodeBlock } from "./MermaidBlock"; +import { SvgBlock } from "./SvgBlock"; /** Build the `code` renderer shared by MarkdownBody and FileViewer's * ReactMarkdown configs (the two previously inlined near-identical copies). @@ -23,6 +24,9 @@ export function markdownCodeRenderer(options: { if (lang === "mermaid") { return ; } + if (lang === "svg") { + return ; + } return ; } return ( diff --git a/components/SvgBlock.test.mjs b/components/SvgBlock.test.mjs new file mode 100644 index 00000000..b6cbe74b --- /dev/null +++ b/components/SvgBlock.test.mjs @@ -0,0 +1,114 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test from "node:test"; +import React from "react"; +import { renderToStaticMarkup } from "react-dom/server"; + +// SvgBlock parses at render time with the browser globals; jsdom provides +// them on window, so expose them before importing the component. +globalThis.DOMParser = window.DOMParser; +globalThis.XMLSerializer = window.XMLSerializer; + +const { SvgBlock, parseSvgMarkup } = await import("./SvgBlock.tsx"); +const { markdownCodeRenderer } = await import("./MarkdownCode.tsx"); + +const validSvg = ` + svg block renders inline + +`; + +test("parseSvgMarkup keeps a valid svg and normalizes its root", () => { + const markup = parseSvgMarkup(validSvg); + assert.match(markup, /]*viewBox="0 0 420 90"/); + assert.match(markup, /max-width:100%;height:auto/); + assert.match(markup, /fill="currentColor"/); + assert.match(markup, /xmlns="http:\/\/www\.w3\.org\/2000\/svg"/); + // Theme-variable fills survive sanitization. + assert.match(markup, /fill="var\(--muted\)"/); +}); + +test("parseSvgMarkup strips script, event handlers, foreignObject, style and javascript hrefs", () => { + const markup = parseSvgMarkup(` + + +
evil
+ x + y + +
`); + assert.doesNotMatch(markup, / and the browser +// parses and executes the nested SVG's scripts. vbscript: is dead in modern +// browsers but still honored by some embedded WebViews — block it too. +const UNSAFE_HREF = /^\s*(javascript|vbscript|data:)/i; +const UNSAFE_ATTRIBUTE = /^on/i; +// A style attribute can smuggle code through url(javascript:…) or the legacy +// IE expression(…); match inside url(…) rather than at the value start, +// since the URL sits after a property name (background: url(…)). +const UNSAFE_STYLE = /expression\s*\(|url\s*\(\s*['"]?\s*(javascript|vbscript|data):/i; + +function sanitizeSvg(root: Element): void { + for (const tag of UNSAFE_TAGS) { + for (const el of root.querySelectorAll(tag)) el.remove(); + } + // querySelectorAll("*") covers descendants only — the root itself can also + // carry an on* handler or a javascript: href, so sweep it too. + for (const el of [root, ...root.querySelectorAll("*")]) { + for (const attr of [...el.attributes]) { + if (UNSAFE_ATTRIBUTE.test(attr.name)) { + el.removeAttribute(attr.name); + continue; + } + if (/^(href|xlink:href)$/i.test(attr.name) && UNSAFE_HREF.test(attr.value)) { + el.removeAttribute(attr.name); + } + if (/^style$/i.test(attr.name) && UNSAFE_STYLE.test(attr.value)) { + el.removeAttribute(attr.name); + } + } + } +} + +/** + * Parse + sanitize an SVG fence into embeddable markup, or null when the + * source is not a well-formed `` document (malformed input, or a fence + * still streaming half-written markup). Pure except for DOMParser / + * XMLSerializer, so tests drive it directly. + */ +export function parseSvgMarkup(code: string): string | null { + let doc: Document; + try { + doc = new DOMParser().parseFromString(code, "image/svg+xml"); + } catch { + return null; + } + if (doc.querySelector("parsererror")) return null; + const root = doc.documentElement; + if (!root || root.nodeName.toLowerCase() !== "svg") return null; + sanitizeSvg(root); + const style = root.getAttribute("style"); + root.setAttribute("style", `${style ? `${style};` : ""}max-width:100%;height:auto`); + if (!root.hasAttribute("fill")) root.setAttribute("fill", "currentColor"); + if (!root.hasAttribute("xmlns")) root.setAttribute("xmlns", "http://www.w3.org/2000/svg"); + return new XMLSerializer().serializeToString(root); +} + +export function SvgBlock({ code, isStreaming }: SvgBlockProps) { + const markup = useMemo(() => parseSvgMarkup(code), [code]); + + // Streaming generates half-written markup; fall back to the code block until + // the fence closes. + if (!markup) { + return ; + } + return ( +
+ ); +} From b812d6f160b1ed3847ff6b32a6d866034e02c831 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:36:48 +0000 Subject: [PATCH 10/45] fix(sidebar): mark a completed session seen once it is opened Port of ompweb-dev/ompweb#336. --- components/SessionSidebar-chrome.tsx | 41 +---- components/SessionSidebar-rows.tsx | 26 +-- components/SessionSidebar.completed.test.mjs | 169 +++++++++++++++++++ components/SessionSidebar.tsx | 25 ++- lib/i18n/locales/en.json | 6 +- lib/i18n/locales/ja.json | 6 +- lib/i18n/locales/zh-CN.json | 6 +- lib/i18n/locales/zh-TW.json | 6 +- 8 files changed, 212 insertions(+), 73 deletions(-) create mode 100644 components/SessionSidebar.completed.test.mjs diff --git a/components/SessionSidebar-chrome.tsx b/components/SessionSidebar-chrome.tsx index 347bf5a8..78f4db43 100644 --- a/components/SessionSidebar-chrome.tsx +++ b/components/SessionSidebar-chrome.tsx @@ -450,12 +450,13 @@ function ExitedSessionIndicator({ title, size = 14 }: { title: string; size?: nu ); } -function RecentlyCompletedIndicator({ size = 12 }: { size?: number }) { +/** A session that finished in the background and has not been opened since. */ +function CompletedUnreadIndicator({ size = 12 }: { size?: number }) { const { t } = useI18n(); return ( ); } - - -function UnreadSessionIndicator({ size = 14 }: { size?: number }) { - const { t } = useI18n(); - const reducedMotion = usePrefersReducedMotion(); - return ( - - - - ); -} export { TauTitle, PathLabel, ExitedSessionIndicator, RunningSessionIndicator, - RecentlyCompletedIndicator, + CompletedUnreadIndicator, SIDEBAR_BUTTON_TRANSITION, SidebarIconButton, SidebarPortalMenu, - UnreadSessionIndicator, useScramble, }; diff --git a/components/SessionSidebar-rows.tsx b/components/SessionSidebar-rows.tsx index 5e90be6d..df6a9951 100644 --- a/components/SessionSidebar-rows.tsx +++ b/components/SessionSidebar-rows.tsx @@ -18,13 +18,12 @@ import { type SessionTreeNode, } from "./SessionSidebar-helpers"; import { + CompletedUnreadIndicator, ExitedSessionIndicator, - RecentlyCompletedIndicator, RunningSessionIndicator, SIDEBAR_BUTTON_TRANSITION, SidebarIconButton, SidebarPortalMenu, - UnreadSessionIndicator, } from "./SessionSidebar-chrome"; /** @@ -103,7 +102,6 @@ interface ProjectRowProps { runningSessionIds: Set; awaitingInputIds: Set; unreadSessionIds: Set; - recentlyCompletedIds?: Set; exitedSessions: Map; relativeTimeNow: number; onActivate: (project: ManagedProject) => void; @@ -143,7 +141,6 @@ function ProjectRow({ runningSessionIds, awaitingInputIds, unreadSessionIds, - recentlyCompletedIds, exitedSessions, relativeTimeNow, onActivate, @@ -485,7 +482,6 @@ function ProjectRow({ awaitingInputIds={awaitingInputIds} unreadSessionIds={unreadSessionIds} exitedSessions={exitedSessions} - recentlyCompletedIds={recentlyCompletedIds} relativeTimeNow={relativeTimeNow} onSelectSession={onSelectSession} onRenamed={onRenamed} @@ -539,7 +535,6 @@ const SessionTreeItem = memo(function SessionTreeItem({ awaitingInputIds, unreadSessionIds, exitedSessions, - recentlyCompletedIds, relativeTimeNow, onSelectSession, onRenamed, @@ -554,7 +549,6 @@ const SessionTreeItem = memo(function SessionTreeItem({ awaitingInputIds: Set; unreadSessionIds: Set; exitedSessions: Map; - recentlyCompletedIds?: Set; relativeTimeNow: number; onSelectSession: (s: SessionInfo) => void; onRenamed?: () => void; @@ -575,7 +569,6 @@ const SessionTreeItem = memo(function SessionTreeItem({ const isRunning = runningSessionIds.has(sessionId); const isAwaitingInput = awaitingInputIds.has(sessionId); const isUnread = unreadSessionIds.has(sessionId); - const isRecentlyCompleted = !isRunning && (recentlyCompletedIds?.has(sessionId) ?? false); const exited = exitedSessions.get(sessionId); // Stable callbacks: depend only on primitives / stable parent callbacks so @@ -617,7 +610,6 @@ const SessionTreeItem = memo(function SessionTreeItem({ isAwaitingInput={isAwaitingInput} isUnread={isUnread} exited={exited} - isRecentlyCompleted={isRecentlyCompleted} relativeTimeNow={relativeTimeNow} onClick={handleClick} onRenamed={onRenamed} @@ -644,7 +636,6 @@ const SessionTreeItem = memo(function SessionTreeItem({ awaitingInputIds={awaitingInputIds} unreadSessionIds={unreadSessionIds} exitedSessions={exitedSessions} - recentlyCompletedIds={recentlyCompletedIds} relativeTimeNow={relativeTimeNow} onSelectSession={onSelectSession} onRenamed={onRenamed} @@ -674,11 +665,10 @@ const SessionTreeItem = memo(function SessionTreeItem({ const id = prev.node.session.id; if (prev.awaitingInputIds.has(id) !== next.awaitingInputIds.has(id)) return false; } - if (prev.recentlyCompletedIds !== next.recentlyCompletedIds) { - const id = prev.node.session.id; - if ((prev.recentlyCompletedIds?.has(id) ?? false) !== (next.recentlyCompletedIds?.has(id) ?? false)) return false; - } if (prev.unreadSessionIds !== next.unreadSessionIds) { + // Nested rows render inside this memo boundary, so a parent must pass a + // changed set down even when only a descendant's unread state flipped. + if (prev.node.children.length > 0) return false; const id = prev.node.session.id; if (prev.unreadSessionIds.has(id) !== next.unreadSessionIds.has(id)) return false; } @@ -698,7 +688,6 @@ const SessionItem = memo(function SessionItem({ isAwaitingInput, isUnread, exited, - isRecentlyCompleted, onClick, onRenamed, onDeleted, @@ -716,7 +705,6 @@ const SessionItem = memo(function SessionItem({ isAwaitingInput?: boolean; isUnread?: boolean; exited?: ExitedRpcSession; - isRecentlyCompleted?: boolean; onClick: () => void; onRenamed?: () => void; onDeleted?: (id: string) => void; @@ -923,15 +911,13 @@ const SessionItem = memo(function SessionItem({ {session.worktreeBranch && } {hasChildren && }
- {(isRunning || exited || isRecentlyCompleted || isUnread) && ( + {(isRunning || exited || isUnread) && ( {isRunning ? : exited ? - : isRecentlyCompleted - ? - : } + : } )}
diff --git a/components/SessionSidebar.completed.test.mjs b/components/SessionSidebar.completed.test.mjs new file mode 100644 index 00000000..e65566cf --- /dev/null +++ b/components/SessionSidebar.completed.test.mjs @@ -0,0 +1,169 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test, { afterEach, before } from "node:test"; +import React from "react"; +const { act, cleanup, render, screen, waitFor, within } = await import("@testing-library/react/pure.js"); +const { default: userEvent } = await import("@testing-library/user-event"); + +// The sidebar's green check means "finished in the background, not opened +// since": it follows the persisted unread set, never recency ranking. + +const { SessionSidebar } = await import("./SessionSidebar.tsx"); + +const UNREAD_KEY = "tau:unread-session-ids"; +const CHECK = "Finished — not opened yet"; +const PROJECT = "/work/alpha"; + +function session(id, firstMessage, minutesAgo) { + const at = new Date(Date.now() - minutesAgo * 60_000).toISOString(); + return { path: `${PROJECT}/${id}.jsonl`, id, cwd: PROJECT, projectRoot: PROJECT, created: at, modified: at, messageCount: 2, firstMessage }; +} +const SESSIONS = [ + session("s-bg", "Background task", 1), + session("s-open", "Open task", 2), + session("s-seen", "Seen task", 3), +]; +/** What /api/sessions serves; a test may swap it before mounting. */ +let sessions = SESSIONS; + +/** The tab side of the shared event-stream worker (lib/event-stream.ts), so a + * test can push `running` frames on the channel the sidebar opened. */ +const eventStreams = new Map(); +const eventWorker = { + onmessage: null, + onerror: null, + postMessage(message) { + if (message.op === "open") eventStreams.set(message.id, message.channel); + else if (message.op === "close") eventStreams.delete(message.id); + }, +}; +function deliverRunning(runningSessionIds) { + const id = [...eventStreams].findLast(([, channel]) => channel.kind === "running")?.[0]; + assert.ok(id, "the sidebar must hold a running channel"); + act(() => { + eventWorker.onmessage({ data: { id, type: "message", data: JSON.stringify({ type: "running", runningSessionIds, exitedSessions: [] }) } }); + }); +} + +/** Responses still being consumed; drained before each test ends so no state + * update lands after the DOM globals are torn down. */ +const inflight = new Set(); +before(() => { + globalThis.Worker = function Worker() { return eventWorker; }; + window.HTMLElement.prototype.scrollIntoView = () => {}; + globalThis.fetch = (url) => { + const path = String(url).split("?")[0]; + const body = path === "/api/sessions" + ? { sessions, runningSessionIds: [] } + : path === "/api/projects" ? { projects: [{ path: PROJECT }] } : {}; + const response = Promise.resolve(new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } })); + inflight.add(response); + void response.then(() => setTimeout(() => inflight.delete(response), 0)); + return response; + }; +}); +afterEach(async () => { + await act(async () => { + while (inflight.size > 0) await new Promise((resolve) => setTimeout(resolve, 5)); + }); + cleanup(); + localStorage.clear(); + sessions = SESSIONS; +}); + +function Harness({ initialSelected }) { + const [selected, setSelected] = React.useState(initialSelected); + return React.createElement(SessionSidebar, { + selectedSessionId: selected, + onSelectSession: (s) => setSelected(s.id), + addProjectOpen: false, + setAddProjectOpen: () => {}, + onOpenArchive: () => {}, + skipInitialProjectSelection: true, + }); +} + +async function mount({ selected = null, unread } = {}) { + localStorage.setItem("tau:expanded-projects", JSON.stringify([PROJECT])); + if (unread) localStorage.setItem(UNREAD_KEY, JSON.stringify(unread)); + render(React.createElement(Harness, { initialSelected: selected })); + await screen.findByText("Seen task"); +} + +const row = (title) => screen.getByText(title).closest(".session-item-row"); +/** Any check mark in the row, whatever its label (main labelled it "Recently completed"). */ +const hasCheck = (title) => row(title).querySelector("svg.lucide-check") !== null; + +test("a session that finishes in the background shows the check until it is opened", async () => { + await mount(); + deliverRunning(["s-bg"]); + assert.equal(hasCheck("Background task"), false, "running sessions show the spinner, not the check"); + deliverRunning([]); + await waitFor(() => assert.equal(hasCheck("Background task"), true)); + assert.ok(within(row("Background task")).getByLabelText(CHECK)); + assert.deepEqual(JSON.parse(localStorage.getItem(UNREAD_KEY)), ["s-bg"]); + + await userEvent.click(screen.getByText("Background task")); + await waitFor(() => assert.equal(hasCheck("Background task"), false)); + assert.equal(localStorage.getItem(UNREAD_KEY), null, "opening it clears the persisted marker"); +}); + +test("a session that finishes while it is open never shows the check", async () => { + await mount({ selected: "s-open" }); + deliverRunning(["s-open"]); + deliverRunning([]); + await waitFor(() => assert.equal(localStorage.getItem(UNREAD_KEY), null)); + assert.equal(hasCheck("Open task"), false); +}); + +test("recent but already seen sessions show no check and stay in the running-only filter", async () => { + await mount(); + for (const title of ["Background task", "Open task", "Seen task"]) assert.equal(hasCheck(title), false, title); + + await userEvent.click(screen.getByRole("button", { name: "Show running sessions only" })); + // Nothing runs, yet the recent-runs retention keeps the finished sessions listed. + assert.ok(screen.getByText("Seen task")); + assert.equal(hasCheck("Seen task"), false); +}); + +test("opening the session in another tab clears the check here", async () => { + await mount({ unread: ["s-bg"] }); + assert.equal(hasCheck("Background task"), true); + + localStorage.removeItem(UNREAD_KEY); + act(() => { window.dispatchEvent(new window.StorageEvent("storage", { key: UNREAD_KEY, oldValue: '["s-bg"]', newValue: null })); }); + assert.equal(hasCheck("Background task"), false); +}); + +test("a check adopted from another tab skips the session open in this tab", async () => { + await mount({ selected: "s-open" }); + localStorage.setItem(UNREAD_KEY, JSON.stringify(["s-bg", "s-open"])); + act(() => { window.dispatchEvent(new window.StorageEvent("storage", { key: UNREAD_KEY, newValue: '["s-bg","s-open"]' })); }); + assert.equal(hasCheck("Background task"), true); + assert.equal(hasCheck("Open task"), false); + assert.deepEqual(JSON.parse(localStorage.getItem(UNREAD_KEY)), ["s-bg"], "the open session is written back as seen"); +}); + +test("a check another tab writes for the session open here alone is written back as seen", async () => { + await mount({ selected: "s-open" }); + // This tab's set is empty, so dropping the open session changes no state here. + localStorage.setItem(UNREAD_KEY, JSON.stringify(["s-open"])); + act(() => { window.dispatchEvent(new window.StorageEvent("storage", { key: UNREAD_KEY, newValue: '["s-open"]' })); }); + assert.equal(hasCheck("Open task"), false); + assert.equal(localStorage.getItem(UNREAD_KEY), null, "the other tab is told the open session is seen"); +}); + +test("a nested child's check updates when only the child becomes unread", async () => { + sessions = [...SESSIONS, { ...session("s-child", "Child task", 0), parentSessionId: "s-bg" }]; + await mount(); + assert.equal(hasCheck("Child task"), false); + // Let every startup fetch land so only the unread set changes below. + await act(async () => { + while (inflight.size > 0) await new Promise((resolve) => setTimeout(resolve, 5)); + }); + + localStorage.setItem(UNREAD_KEY, JSON.stringify(["s-child"])); + act(() => { window.dispatchEvent(new window.StorageEvent("storage", { key: UNREAD_KEY, newValue: '["s-child"]' })); }); + await waitFor(() => assert.equal(hasCheck("Child task"), true)); + assert.equal(hasCheck("Background task"), false, "the parent itself stays unmarked"); +}); diff --git a/components/SessionSidebar.tsx b/components/SessionSidebar.tsx index 301b4a71..1e089c01 100644 --- a/components/SessionSidebar.tsx +++ b/components/SessionSidebar.tsx @@ -34,6 +34,7 @@ import { INITIAL_RESTORE_MAX_ATTEMPTS, INITIAL_RESTORE_RETRY_MS, MAX_PROJECT_SESSIONS, + UNREAD_SESSIONS_STORAGE_KEY, buildSessionTree, livePlace, loadExpandedProjects, @@ -498,6 +499,14 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, }; }, [loadSessions]); + // The green check ("finished in the background, not opened yet") comes from + // this running-to-idle comparison, per browser. Two known boundaries: + // - A run that starts and finishes while every tab of this browser is closed + // is never seen leaving the running set, so it gets no check. + // - When omp moves a running conversation to a new session id, the running + // channel lists only the new id, so (by reading the code) the old id can + // read as finished here and its preserved file get a check. Telling a move + // from a finish needs the channel to carry the move, which it does not. useEffect(() => { const previous = previousRunningSessionIdsRef.current; const allCompleted = [...previous].filter((id) => !runningSessionIds.has(id)); @@ -546,6 +555,21 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, return next; }); }, [selectedSessionId]); + // Keep this browser's other tabs in step: opening a finished session in one + // tab clears its check everywhere. The session open in this tab counts as + // seen, so it never adopts a check (dropping it is written back). + useEffect(() => { + const onStorage = (event: StorageEvent) => { + if (event.key !== null && event.key !== UNREAD_SESSIONS_STORAGE_KEY) return; + const stored = loadUnreadSessionIds(); + // Write the drop back here: when this tab's set already equals the rest, + // no state change would reach the persistence effect. + if (selectedSessionId && stored.delete(selectedSessionId)) saveUnreadSessionIds(stored); + setUnreadSessionIds((prev) => (prev.size === stored.size && [...stored].every((id) => prev.has(id)) ? prev : stored)); + }; + window.addEventListener("storage", onStorage); + return () => window.removeEventListener("storage", onStorage); + }, [selectedSessionId]); const restoredRef = useRef(false); @@ -1827,7 +1851,6 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, awaitingInputIds={awaitingInputIds} unreadSessionIds={unreadSessionIds} exitedSessions={exitedSessions} - recentlyCompletedIds={effectiveRecentCompletedSet} relativeTimeNow={relativeTimeNow} onActivate={activateProject} onToggleExpand={toggleProjectExpanded} diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index e67b7014..e3d35d6a 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -1142,7 +1142,7 @@ "pluginsConfig.update": "Update", "pluginsConfig.updating": "Updating...", "pluginsConfig.version": "Version", - "projects.activity": "{running} running, {unread} unread, {exited} exited unexpectedly", + "projects.activity": "{running} running, {unread} finished and not opened yet, {exited} exited unexpectedly", "projects.add": "Add workspace", "projects.addTitle": "Add a workspace directory to the sidebar", "projects.collapseProject": "Collapse {name}", @@ -1215,8 +1215,6 @@ "sessionSidebar.loading": "Loading...", "sessionSidebar.mainBadge": "main", "sessionSidebar.new": "New Session", - "sessionSidebar.newActivity": "New activity", - "sessionSidebar.newSessionActivity": "New session activity", "sessionSidebar.newSessionIn": "New session in {cwd}", "sessionSidebar.newWorktree": "New worktree…", "sessionSidebar.newWorktreeTitle": "Create a worktree checkout for a branch", @@ -1254,7 +1252,7 @@ "sessionSidebar.searchPlaceholder": "Search sessions…", "sessionSidebar.filterRunning": "Show running sessions only", "sessionSidebar.filterRunningTitle": "Show active and recently completed sessions (up to {count})", - "sessionSidebar.recentlyCompleted": "Recently completed", + "sessionSidebar.completedUnread": "Finished — not opened yet", "sessionSidebar.noMatches": "No matching sessions", "sessionSidebar.searchingTranscripts": "Searching transcripts… results may move as better matches are found", "sessionSidebar.searchStopped": "Search stopped. Transcript results may be incomplete.", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 2466c6ee..f5e91e51 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -1105,7 +1105,7 @@ "pluginsConfig.update": "更新", "pluginsConfig.updating": "更新中...", "pluginsConfig.version": "バージョン", - "projects.activity": "{running} 実行中、{unread} 未読、{exited} 異常終了", + "projects.activity": "{running} 実行中、{unread} 完了・未表示、{exited} 異常終了", "projects.add": "ワークスペースを追加", "projects.addTitle": "サイドバーにワークスペースディレクトリを追加", "projects.collapseProject": "{name} を折りたたむ", @@ -1178,8 +1178,6 @@ "sessionSidebar.loading": "読み込み中...", "sessionSidebar.mainBadge": "main", "sessionSidebar.new": "新しいセッション", - "sessionSidebar.newActivity": "新しいアクティビティ", - "sessionSidebar.newSessionActivity": "新しいセッションアクティビティ", "sessionSidebar.newSessionIn": "{cwd} で新しいセッション", "sessionSidebar.newWorktree": "新しいワークツリー…", "sessionSidebar.newWorktreeTitle": "ブランチのワークツリーチェックアウトを作成します", @@ -1214,7 +1212,7 @@ "sessionSidebar.searchPlaceholder": "セッションを検索…", "sessionSidebar.filterRunning": "実行中のセッションのみ表示", "sessionSidebar.filterRunningTitle": "実行中および最近完了したセッションを表示(最大{count}件)", - "sessionSidebar.recentlyCompleted": "最近完了", + "sessionSidebar.completedUnread": "完了 — まだ開いていません", "sessionSidebar.noMatches": "一致するセッションがありません", "sessionSidebar.searchingTranscripts": "会話内容を検索中… より良い一致が見つかると順位が変わることがあります", "sessionSidebar.searchStopped": "検索を停止しました。会話内容の結果は不完全な可能性があります。", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 6cab073d..f33fe048 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -1105,7 +1105,7 @@ "pluginsConfig.update": "更新", "pluginsConfig.updating": "更新中...", "pluginsConfig.version": "版本", - "projects.activity": "{running} 个运行中,{unread} 个未读,{exited} 个异常退出", + "projects.activity": "{running} 个运行中,{unread} 个已完成未查看,{exited} 个异常退出", "projects.add": "添加工作区", "projects.addTitle": "将工作区目录添加到侧边栏", "projects.collapseProject": "折叠 {name}", @@ -1178,8 +1178,6 @@ "sessionSidebar.loading": "加载中...", "sessionSidebar.mainBadge": "main", "sessionSidebar.new": "新建会话", - "sessionSidebar.newActivity": "新活动", - "sessionSidebar.newSessionActivity": "新的会话活动", "sessionSidebar.newSessionIn": "在 {cwd} 新建会话", "sessionSidebar.newWorktree": "新建工作树…", "sessionSidebar.newWorktreeTitle": "为某个分支创建工作树检出", @@ -1214,7 +1212,7 @@ "sessionSidebar.searchPlaceholder": "搜索会话…", "sessionSidebar.filterRunning": "仅显示运行中的会话", "sessionSidebar.filterRunningTitle": "显示正在运行和最近完成的会话(最多{count}个)", - "sessionSidebar.recentlyCompleted": "最近完成", + "sessionSidebar.completedUnread": "已完成,尚未查看", "sessionSidebar.noMatches": "没有匹配的会话", "sessionSidebar.searchingTranscripts": "正在搜索会话内容… 找到更好的匹配时结果顺序可能变化", "sessionSidebar.searchStopped": "搜索已停止。会话内容结果可能不完整。", diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index 1e9fe047..9994f31b 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -1140,7 +1140,7 @@ "pluginsConfig.update": "更新", "pluginsConfig.updating": "更新中...", "pluginsConfig.version": "版本", - "projects.activity": "{running} 個執行中,{unread} 個未讀,{exited} 個意外結束", + "projects.activity": "{running} 個執行中,{unread} 個已完成尚未查看,{exited} 個意外結束", "projects.add": "新增工作區", "projects.addTitle": "將工作區目錄新增至側邊欄", "projects.collapseProject": "摺疊 {name}", @@ -1214,8 +1214,6 @@ "sessionSidebar.loading": "載入中...", "sessionSidebar.mainBadge": "主要", "sessionSidebar.new": "新對話", - "sessionSidebar.newActivity": "新動態", - "sessionSidebar.newSessionActivity": "新對話動態", "sessionSidebar.newSessionIn": "在 {cwd} 中建立新對話", "sessionSidebar.newWorktree": "新增工作樹…", "sessionSidebar.newWorktreeTitle": "為分支建立工作樹簽出(worktree checkout)", @@ -1253,7 +1251,7 @@ "sessionSidebar.searchPlaceholder": "搜尋對話…", "sessionSidebar.filterRunning": "僅顯示執行中的對話", "sessionSidebar.filterRunningTitle": "顯示進行中與最近完成的對話(最多 {count} 個)", - "sessionSidebar.recentlyCompleted": "最近完成", + "sessionSidebar.completedUnread": "已完成,尚未查看", "sessionSidebar.noMatches": "沒有相符的對話", "sessionSidebar.searchingTranscripts": "正在搜尋逐字稿… 隨著找到更佳相符結果,順序可能會變動", "sessionSidebar.searchStopped": "搜尋已停止。逐字稿搜尋結果可能不完整。", From f35ee764b0a49020edf3fed9b61b4795e55ed702 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:36:48 +0000 Subject: [PATCH 11/45] fix(i18n): add the zh-TW completed-subagents summary Port of ompweb-dev/ompweb#545. --- lib/i18n/locales/zh-TW.json | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index 9994f31b..548ae451 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -579,6 +579,7 @@ "chatWindow.subagentState.failed": "失敗", "chatWindow.subagentState.started": "執行中", "chatWindow.subagentSummary": "{running} 個執行中 · 共 {total} 個", + "chatWindow.subagentCompletedSummary": "已完成 {completed}/{total}", "chatWindow.completedSubagents": "已完成 ({count})", "chatWindow.subagentsPanel": "子代理", "chatWindow.subagentRetrying": "正在重試 {attempt}/{max}", From 36b8331ba670d8573c757cb08c580dff796c5384 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:36:49 +0000 Subject: [PATCH 12/45] perf(sessions): strip unused assistant fields from the session response Port of ompweb-dev/ompweb#454. --- lib/session-reader.test.mjs | 43 +++++++++++++++++++++++++++++ lib/session-reader.ts | 55 ++++++++++++++++++++++++++++++++++++- 2 files changed, 97 insertions(+), 1 deletion(-) diff --git a/lib/session-reader.test.mjs b/lib/session-reader.test.mjs index 0654cc64..e34294ec 100644 --- a/lib/session-reader.test.mjs +++ b/lib/session-reader.test.mjs @@ -270,6 +270,49 @@ test("defers historical thinking without changing live-session content", () => { assert.equal(full.messages[1].content[0].thinking, "large reasoning"); }); +test("strips unused per-message fields from assistant messages in the display context (#307)", () => { + const entries = [ + userEntry("u1", null, "start"), + { + ...assistantEntry("a1", "u1", "answer"), + message: { + role: "assistant", + provider: "test", + model: "test-model", + content: [ + // Real payloads nest the signatures inside content blocks too + // (thinkingSignature on thinking blocks, textSignature on text + // blocks — see tests/fixtures/omp-delta-stream.ndjson); the strip + // must drop those as well, not just the message-level fields. + { type: "thinking", thinking: "large reasoning", thinkingSignature: "c2lnbmF0dXJlLWJsb2Nr" }, + { type: "text", text: "answer", textSignature: "c2lnbmF0dXJlLXRleHQ" }, + ], + inputTransformations: [{ type: "thinking_dropped", path: "messages.0.content.0", reason: "prefix_binding_mismatch" }], + thinkingSignature: "c2lnbmF0dXJl", + requestControls: { maxTokens: 100 }, + contextSnapshot: { tokens: 123 }, + }, + }, + ]; + + // Stripped with and without deferThinking: the UI never reads these fields. + for (const options of [undefined, { deferThinking: true }]) { + const context = buildSessionContext(entries, undefined, options); + const assistant = context.messages[1]; + assert.equal("inputTransformations" in assistant, false); + assert.equal("thinkingSignature" in assistant, false); + assert.equal("requestControls" in assistant, false); + assert.equal("contextSnapshot" in assistant, false); + assert.equal("thinkingSignature" in assistant.content[0], false); + assert.equal("textSignature" in assistant.content[1], false); + assert.equal(assistant.content[1].text, "answer"); + assert.equal(assistant.model, "test-model"); + } + // Without deferThinking the thinking text survives the strip. + const full = buildSessionContext(entries); + assert.equal(full.messages[1].content[0].thinking, "large reasoning"); +}); + test("does not defer empty historical thinking blocks", () => { const entries = [ userEntry("u1", null, "start"), diff --git a/lib/session-reader.ts b/lib/session-reader.ts index f01ff27b..fd23bf44 100644 --- a/lib/session-reader.ts +++ b/lib/session-reader.ts @@ -1125,6 +1125,59 @@ function stripToolResultDetails(message: AgentMessage): AgentMessage { return rest; } +/** + * Per-message fields the history UI never reads dominate the session + * response (measured 2.1 MB of a 3.7 MB context on a 597-message session; + * inputTransformations alone is 53% — #307). They are provider-internal + * (opaque thinking signatures, request controls, context snapshots) and no + * reader in components/, hooks/, lib/ or app/ touches them, so the display + * context drops them. The on-disk session file keeps the full message. + * + * Real payloads also nest the signatures inside content blocks — a thinking + * block carries thinkingSignature and a text block textSignature (see + * tests/fixtures/omp-delta-stream.ndjson) — so the strip walks the blocks + * too. transcriptToMarkdown reads only block.thinking / block.text, never + * the signatures, so dropping them changes no rendered output. + */ +const UNUSED_ASSISTANT_MESSAGE_FIELDS = [ + "inputTransformations", + "thinkingSignature", + "requestControls", + "contextSnapshot", +] as const; + +// Signature fields nested inside assistant content blocks (thinking/text). +const UNUSED_ASSISTANT_BLOCK_FIELDS = ["thinkingSignature", "textSignature"] as const; + +function stripUnusedAssistantFields(message: AgentMessage): AgentMessage { + if (message.role !== "assistant") return message; + const record = message as unknown as Record; + const hasMessageFields = UNUSED_ASSISTANT_MESSAGE_FIELDS.some((field) => record[field] !== undefined); + const content = Array.isArray(message.content) ? message.content : null; + const hasBlockFields = content?.some((block) => { + const b = block as unknown as Record; + return ( + b !== null && + typeof b === "object" && + UNUSED_ASSISTANT_BLOCK_FIELDS.some((field) => b[field] !== undefined) + ); + }); + if (!hasMessageFields && !hasBlockFields) return message; + const stripped = { ...record }; + for (const field of UNUSED_ASSISTANT_MESSAGE_FIELDS) delete stripped[field]; + if (content && hasBlockFields) { + stripped.content = content.map((block) => { + const b = block as unknown as Record; + if (b === null || typeof b !== "object") return block; + if (UNUSED_ASSISTANT_BLOCK_FIELDS.every((field) => b[field] === undefined)) return block; + const copy = { ...b }; + for (const field of UNUSED_ASSISTANT_BLOCK_FIELDS) delete copy[field]; + return copy; + }); + } + return stripped as unknown as AgentMessage; +} + function toolResultImagesAsUrls(message: AgentMessage): AgentMessage { if (message.role !== "toolResult") return message; const content = toolResultContentAsUrls(message.content); @@ -1206,7 +1259,7 @@ export function entryToUiMessage( const normalized = options.deferToolResultImages ? toolResultImagesAsUrls(normalizeToolCalls(raw)) : normalizeToolCalls(raw); - const message = stripToolResultDetails(normalized); + const message = stripUnusedAssistantFields(stripToolResultDetails(normalized)); const displayMessage = options.origin && message.role === "user" ? { ...message, origin: options.origin } : message; if (!options.deferThinking || displayMessage.role !== "assistant") return withNormalizedTimestamp(displayMessage); // Guard like the loader does for bad lines: normalizeToolCalls passes From c3bcef3ced15239553dcdc6b608888c83deaf0d5 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:37:38 +0000 Subject: [PATCH 13/45] feat(api): app-info handshake and a per-connection heartbeat Port of ompweb-dev/ompweb#407. --- AGENTS.md | 1 + README.md | 6 +++ app/api/app-info/route.ts | 22 ++++++++++ app/api/events/route.ts | 7 ++- lib/app-info-route.test.mjs | 17 ++++++++ lib/event-stream-hub.test.mjs | 81 ++++++++++++++++++++++++++++++++++- lib/event-stream-hub.ts | 24 ++++++++--- lib/event-stream-protocol.ts | 11 +++++ server/routes.ts | 2 + 9 files changed, 163 insertions(+), 8 deletions(-) create mode 100644 app/api/app-info/route.ts create mode 100644 lib/app-info-route.test.mjs diff --git a/AGENTS.md b/AGENTS.md index 7c71df60..a8525d9d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -437,6 +437,7 @@ pi's wire `message_update` is delta-only (pi `docs/json.md`): `usage` and `assis - `lib/event-stream-worker.ts` (SharedWorker; dedicated Worker where SharedWorker is missing) holds the browser's one `/api/events` EventSource and multiplexes every tab's subscriptions: frames arrive as `event: `, control frames as `event: mux` (`hello`/`open`/`end`); subscriptions are attached with `POST /api/events`. Tabs POST their agent commands and uploads themselves. `buildEventStreamWorker` bundles it into `dist/event-stream-worker.js`, whose URL carries the content hash. - Tabs use `openEventStream(channel)` (`lib/event-stream.ts`) with EventSource semantics: `onerror` + CONNECTING = reconnecting, CLOSED = fatal (e.g. 409 for a wrapper-less session). Dead tabs are detected with a lifetime Web Lock. - Channels (`event-stream-hub.ts`): `running` (badges + list hints), `notifications` (one tab's, by `clientId`), `hosts` (the `GET /api/hosts` body), `host-tools` (cross-session `open_url`/`notify`/`open_file`), `session` (observer-only, never spawns pi; merges `message_update`s under backpressure), `file` (viewer watch, same allow-list as `/api/files`). A failing frame ends only its own subscription. Split channels by consumer, lifetime, key and access check; `notifications` and `host-tools` are subscribed from `AppShell`. +- **Native-client handshake and keep-alive.** `GET /api/app-info` (behind the `/api` gate, `no-store`) answers `{ name, version, api: 1, capabilities }`: package identity and which server-side features exist, never a credential or setting. A capability is added only with its implementation; today it carries `heartbeatParam`. `GET /api/events?heartbeat=` sets that connection's keep-alive comment frame: an integer in 15..110, anything else the 30 s default (not clamped). A value above the reverse proxy's read timeout (nginx: 60 s) drops an idle stream before its first keep-alive. - **Metrics.** Tabs and the worker record `action`, `event`, `reconnect`, `hang` and `dropped` samples; the worker POSTs them to `/api/transport-metrics` every 30 s or 200 samples. One worker-wide clock (lowest RTT of recent probes) times them. - **Connection tab** (right panel, while "Show connection diagnostics" is on, `tau:connection-diagnostics`): polls the worker (`diag`) once a second; status, last reconnect and per-transport stats (`lib/transport-stats.ts`) over the last 30 min. Command rows include confirmed replies only; app ↔ pi rows skip commands the web app answers itself (`NO_SPAWN_REPLIES` and friends). - **Worker rules.** No `AbortSignal.timeout`/`any` or `Promise.withResolvers` (a test checks the bundle). Every global it uses must be injectable into the `vm` context of `lib/event-stream-worker.test.mjs`. Ids use `Math.random().toString(36).slice(2, 12) + Date.now().toString(36)` (insecure LAN origins lack `crypto.randomUUID`). diff --git a/README.md b/README.md index 0602daa1..b095f287 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,12 @@ VPN, and keep tau itself bound to `127.0.0.1`. The proxy must pass WebSocket upg on the paths that hosts authenticate with their token: `/api/hosts/link`, `/api/hosts/maintenance` and `/api/hosts/cluster-config/…`. +A server-sent-events client keeps its stream alive with a comment frame every 30 s by default; `GET /api/events?heartbeat=` +(15 to 110) chooses another interval for that connection. A value outside that range falls back to the 30 s default. The proxy's +read timeout must stay above the interval the client asks for: nginx's default `proxy_read_timeout` is 60 s, so a client selecting +110 s needs a timeout above 110 s (for example `proxy_read_timeout 120s;`), or the proxy drops the idle stream before its first +keep-alive. `GET /api/app-info` tells a native client whether the server supports the query. + #### Skipping the password behind a trusted proxy tau cannot see client addresses itself, so a reverse proxy can vouch for requests instead. The proxy sends a secret in diff --git a/app/api/app-info/route.ts b/app/api/app-info/route.ts new file mode 100644 index 00000000..ab06e77a --- /dev/null +++ b/app/api/app-info/route.ts @@ -0,0 +1,22 @@ +import packageJson from "../../../package.json"; + +/** + * Capability handshake for native clients. Rides the normal /api auth gate; it + * carries the package version and which server-side features exist, never any + * credential or configuration value. + * + * Every flag names a route or shape this server actually serves: a client that + * reads one and finds the feature missing would break, so a capability is added + * only together with its implementation. + */ +export function GET(): Response { + return Response.json({ + name: "tau", + version: packageJson.version, + api: 1, + capabilities: { + /** `GET /api/events?heartbeat=<15..110>` chooses this connection's keep-alive. */ + heartbeatParam: true, + }, + }, { headers: { "Cache-Control": "no-store" } }); +} diff --git a/app/api/events/route.ts b/app/api/events/route.ts index 0c163b7d..38b0c3ba 100644 --- a/app/api/events/route.ts +++ b/app/api/events/route.ts @@ -1,5 +1,5 @@ import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; -import { EventStreamConnection, getEventStreamConnection } from "@/lib/event-stream-hub"; +import { EventStreamConnection, getEventStreamConnection, parseHeartbeatSeconds } from "@/lib/event-stream-hub"; import { parseEventStreamRequest, UNKNOWN_CONNECTION_CODE } from "@/lib/event-stream-protocol"; const MAX_REQUEST_BYTES = 16 * 1024; @@ -8,7 +8,10 @@ const MAX_REQUEST_BYTES = 16 * 1024; // Subscriptions are attached with POST (see lib/event-stream-protocol.ts). export function GET(req: Request, { disableIdleTimeout }: { disableIdleTimeout: () => void }) { disableIdleTimeout(); - const connection = new EventStreamConnection(req.signal); + // A native client may ask for a longer keep-alive (`?heartbeat=110`); values + // outside 15..110 fall back to the 30 s default rather than being clamped. + const heartbeat = parseHeartbeatSeconds(new URL(req.url).searchParams.get("heartbeat")); + const connection = new EventStreamConnection(req.signal, { heartbeatMs: heartbeat * 1000 }); return new Response(connection.stream, { headers: { "Content-Type": "text/event-stream", diff --git a/lib/app-info-route.test.mjs b/lib/app-info-route.test.mjs new file mode 100644 index 00000000..e54c16e4 --- /dev/null +++ b/lib/app-info-route.test.mjs @@ -0,0 +1,17 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const route = await import("../app/api/app-info/route.ts"); +const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); + +test("app-info identifies tau, its version and every capability it serves", async () => { + const response = await route.GET(); + assert.equal(response.status, 200); + assert.equal(response.headers.get("cache-control"), "no-store"); + const body = await response.json(); + assert.equal(body.name, "tau"); + assert.equal(body.version, pkg.version); + assert.equal(body.api, 1); + assert.deepEqual(body.capabilities, { heartbeatParam: true }); +}); diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index 319cd52a..6115d93a 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -17,7 +17,7 @@ after(() => { fs.rmSync(isolatedAgentDir, { recursive: true, force: true }); }); -const { EventStreamConnection, getEventStreamConnection } = await import("./event-stream-hub.ts"); +const { EventStreamConnection, getEventStreamConnection, parseHeartbeatSeconds } = await import("./event-stream-hub.ts"); const route = await import("../app/api/events/route.ts"); const { AgentSessionWrapper } = await import("./rpc-manager.ts"); const { closeOutboxStore } = await import("./message-outbox.ts"); @@ -1005,3 +1005,82 @@ test("a fresh outbox snapshot replaces the pending one when capacity returns bef done(); } }); + +test("the heartbeat query falls back to the 30 s default outside 15..110 seconds", () => { + for (const value of [null, undefined, "", "abc", "0", "14", "111", "1e3", "-30", "100000"]) { + assert.equal(parseHeartbeatSeconds(value), 30, String(value)); + } + assert.equal(parseHeartbeatSeconds("15"), 15); + assert.equal(parseHeartbeatSeconds("30"), 30); + assert.equal(parseHeartbeatSeconds("110"), 110); + assert.equal(parseHeartbeatSeconds(" 60 "), 60); +}); + +test("GET /api/events applies the heartbeat query to that connection only", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setInterval", "Date"], now: 1_000_000 }); + const open = async (query) => { + const ac = new AbortController(); + const response = route.GET(new Request(`http://localhost/api/events${query}`, { signal: ac.signal }), { disableIdleTimeout() {} }); + const reader = response.body.getReader(); + const hello = await readFrame(reader); + const connection = getEventStreamConnection(hello.data.connectionId); + assert.ok(connection); + return { connection, reader, ac }; + }; + const fast = await open("?heartbeat=17"); + const slow = await open("?heartbeat=500"); + const plain = await open(""); + // One pending read per connection: a heartbeat settles it, so the interval + // the route actually armed is observed, not a getter's echo of it. + const reads = { fast: fast.reader.read(), slow: slow.reader.read(), plain: plain.reader.read() }; + const outcome = (read) => Promise.race([ + read.then(() => "beat"), + new Promise((resolve) => setTimeout(() => resolve("none"), 100)), + ]); + try { + t.mock.timers.tick(16_999); + assert.equal(await outcome(reads.fast), "none", "no heartbeat before the requested 17 s"); + assert.equal(await outcome(reads.slow), "none"); + assert.equal(await outcome(reads.plain), "none"); + t.mock.timers.tick(1); + assert.equal(await outcome(reads.fast), "beat", "the requested 17 s interval"); + assert.equal(decoder.decode((await reads.fast).value), ":\n\n"); + assert.equal(await outcome(reads.slow), "none", "out-of-range values keep the default"); + assert.equal(await outcome(reads.plain), "none", "no query keeps the default"); + t.mock.timers.tick(13_000); + assert.equal(await outcome(reads.slow), "beat", "the 30 s default interval"); + assert.equal(await outcome(reads.plain), "beat", "the 30 s default interval"); + } finally { + for (const { connection, reader } of [fast, slow, plain]) { + await reader.cancel(); + assert.equal(connection.isClosed, true); + } + } +}); + +test("the connection's keep-alive timer fires at the requested interval, never earlier", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setInterval", "Date"], now: 1_000_000 }); + const connection = new EventStreamConnection(undefined, { heartbeatMs: 15_000 }); + const reader = connection.stream.getReader(); + try { + const hello = await readFrame(reader); + assert.equal(hello.event, "mux"); + // One read stays pending across the wait: an early heartbeat settles it and + // fails here, instead of being read back after the advertised deadline. + const beat = reader.read(); + t.mock.timers.tick(14_999); + assert.equal( + await Promise.race([ + beat.then(() => "beat"), + new Promise((resolve) => setTimeout(() => resolve("none"), 100)), + ]), + "none", + "no heartbeat before the requested interval", + ); + t.mock.timers.tick(1); + assert.equal(decoder.decode((await beat).value), ":\n\n", "one heartbeat at the requested interval"); + } finally { + connection.close(); + await reader.cancel(); + } +}); diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index f9fcab38..63ce4315 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -24,7 +24,19 @@ import { isRecord } from "./type-guards"; // the browser's shared worker. // Heartbeat keeps the socket alive through reverse proxies that drop silent connections. +// A native client may ask for a longer one per connection (`/api/events?heartbeat=`). const HEARTBEAT_MS = 30_000; +export const MIN_HEARTBEAT_SECONDS = 15; +export const MAX_HEARTBEAT_SECONDS = 110; + +/** `?heartbeat=` in [15, 110]; anything else keeps the 30 s default. */ +export function parseHeartbeatSeconds(value: string | null | undefined): number { + if (typeof value !== "string" || !/^\d{1,4}$/.test(value.trim())) return HEARTBEAT_MS / 1000; + const seconds = Number(value.trim()); + if (seconds < MIN_HEARTBEAT_SECONDS || seconds > MAX_HEARTBEAT_SECONDS) return HEARTBEAT_MS / 1000; + return seconds; +} + const encoder = new TextEncoder(); export type SubscribeResult = @@ -78,11 +90,12 @@ export interface FrameSink { } class SseSink implements FrameSink { - readonly heartbeatMs = HEARTBEAT_MS; + readonly heartbeatMs: number; readonly stream: ReadableStream; private controller!: ReadableStreamDefaultController; - constructor(onPull: () => void, onCancel: () => void) { + constructor(onPull: () => void, onCancel: () => void, heartbeatMs = HEARTBEAT_MS) { + this.heartbeatMs = heartbeatMs; this.stream = new ReadableStream({ start: (controller) => { this.controller = controller; }, // A slow consumer resumed reading: deliver coalesced updates now rather @@ -142,13 +155,14 @@ export class EventStreamConnection { private readonly subscriptions = new Map(); private readonly signal: AbortSignal | undefined; - constructor(signal?: AbortSignal, sink?: FrameSink) { + /** `options.heartbeatMs` overrides the keep-alive for this connection's SSE sink. */ + constructor(signal?: AbortSignal, sink?: FrameSink | { heartbeatMs?: number }) { this.signal = signal; - if (sink) { + if (sink && "write" in sink) { this.sink = sink; this.stream = null; } else { - const sse = new SseSink(() => this.resume(), () => this.close()); + const sse = new SseSink(() => this.resume(), () => this.close(), sink?.heartbeatMs ?? HEARTBEAT_MS); this.sink = sse; this.stream = sse.stream; } diff --git a/lib/event-stream-protocol.ts b/lib/event-stream-protocol.ts index bdf3b9b7..a0e58762 100644 --- a/lib/event-stream-protocol.ts +++ b/lib/event-stream-protocol.ts @@ -12,6 +12,17 @@ // Every frame also carries `id: `, read as `lastEventId`. // Subscriptions are added/removed with POST /api/events (EventStreamRequest). // +// Keep-alive: the server writes a comment frame (`:\n\n`) on an idle stream, +// 30 s by default. A native client may ask for another interval with +// `GET /api/events?heartbeat=`; the value belongs to that connection +// only, must be an integer in [15, 110], and anything else (absent, malformed, +// out of range) falls back to the 30 s default rather than being clamped. +// A longer interval needs a reverse-proxy read timeout above it: nginx's +// default `proxy_read_timeout` is 60 s, so `heartbeat=110` disconnects an idle +// stream there before its first keep-alive. Keep the proxy timeout above the +// requested interval (e.g. 120 s for 110 s) or request a shorter one. +// `GET /api/app-info` advertises `capabilities.heartbeatParam` for this query. +// // Agent commands go as POST /api/agent/[id] and uploads over /api/uploads, from the tab. // // lib/event-stream-worker.ts imports this module (bundled by server/client-env.ts). diff --git a/server/routes.ts b/server/routes.ts index 5fc4aef1..b3a35068 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -3,6 +3,7 @@ import * as agentIdBashOutput from "@/app/api/agent/[id]/bash-output/route"; import * as agentId from "@/app/api/agent/[id]/route"; import * as agentNew from "@/app/api/agent/new/route"; +import * as appInfo from "@/app/api/app-info/route"; import * as appUpdateNotes from "@/app/api/app-update/notes/route"; import * as appUpdate from "@/app/api/app-update/route"; import * as authAccountsProvider from "@/app/api/auth/accounts/[provider]/route"; @@ -97,6 +98,7 @@ export const ROUTE_MODULES: Record = { "agent/[id]/bash-output": agentIdBashOutput, "agent/[id]": agentId, "agent/new": agentNew, + "app-info": appInfo, "app-update/notes": appUpdateNotes, "app-update": appUpdate, "auth/accounts/[provider]": authAccountsProvider, From bd33536b57d025dc3c6a6885f2627daaeb785360 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:38:32 +0000 Subject: [PATCH 14/45] =?UTF-8?q?feat(directory-picker):=20add=20a=20Brows?= =?UTF-8?q?e=E2=80=A6=20button=20that=20opens=20the=20OS=20folder=20dialog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port of ompweb-dev/ompweb#544. --- app/api/cwd/pick/route.ts | 20 ++++++++ app/api/cwd/picker/route.ts | 9 ++++ components/DirectoryPicker.tsx | 48 ++++++++++++++++++- lib/cwd-picker.test.mjs | 44 +++++++++++++++++ lib/cwd-picker.ts | 88 ++++++++++++++++++++++++++++++++++ lib/hosts/host-login.test.mjs | 11 ++++- lib/hosts/host-login.ts | 3 +- lib/i18n/locales/en.json | 1 + lib/i18n/locales/ja.json | 1 + lib/i18n/locales/zh-CN.json | 1 + lib/i18n/locales/zh-TW.json | 1 + server/app.ts | 12 +++-- server/routes.ts | 10 +++- 13 files changed, 241 insertions(+), 8 deletions(-) create mode 100644 app/api/cwd/pick/route.ts create mode 100644 app/api/cwd/picker/route.ts create mode 100644 lib/cwd-picker.test.mjs create mode 100644 lib/cwd-picker.ts diff --git a/app/api/cwd/pick/route.ts b/app/api/cwd/pick/route.ts new file mode 100644 index 00000000..9a2db36d --- /dev/null +++ b/app/api/cwd/pick/route.ts @@ -0,0 +1,20 @@ +import { apiErrorResponse } from "@/lib/api-utils"; +import { pickDirectory, pickerAvailable } from "@/lib/cwd-picker"; +import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; + +// POST /api/cwd/pick body: { hostId?: string } → { path } | { cancelled: true } +// Opens the OS folder dialog on this machine. A page opened from another machine has no desktop +// here, and another host's paths do not exist here either, so both cases are refused. +export async function POST(req: Request, context: { localPeer: boolean }) { + try { + const body = await req.json().catch(() => ({})) as { hostId?: unknown }; + const hostId = typeof body.hostId === "string" && body.hostId ? body.hostId : LOCAL_HOST_ID; + const picked = hostId === LOCAL_HOST_ID && pickerAvailable(context.localPeer) ? await pickDirectory() : null; + if (!picked) { + return Response.json({ error: "The folder dialog is only available on this machine", code: "picker_unavailable" }, { status: 501 }); + } + return Response.json(picked); + } catch (error) { + return apiErrorResponse(error); + } +} diff --git a/app/api/cwd/picker/route.ts b/app/api/cwd/picker/route.ts new file mode 100644 index 00000000..cec55627 --- /dev/null +++ b/app/api/cwd/picker/route.ts @@ -0,0 +1,9 @@ +import { pickerAvailable } from "@/lib/cwd-picker"; + +// GET /api/cwd/picker → { available } — may this page open the server machine's folder dialog? +// Only a page opened on the machine itself: a remote browser has no desktop here. Locality is the +// connection's peer address from the server (context.localPeer), never request.url's host, which the +// client writes through its Host header. +export function GET(_request: Request, context: { localPeer: boolean }) { + return Response.json({ available: pickerAvailable(context.localPeer) }); +} diff --git a/components/DirectoryPicker.tsx b/components/DirectoryPicker.tsx index 97056f95..139f219e 100644 --- a/components/DirectoryPicker.tsx +++ b/components/DirectoryPicker.tsx @@ -7,6 +7,7 @@ import { useI18n } from "@/lib/i18n"; import { formatApiError } from "@/lib/i18n/api-error"; import { appendProgress, cloneDirectoryName } from "@/lib/git-clone"; import { randomUUID as newCloneId } from "@/lib/random-uuid"; +import { LOCAL_HOST_ID } from "@/lib/project-ordering"; interface DirectoryEntry { name: string; @@ -73,6 +74,8 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host, const [directories, setDirectories] = useState([]); const [drives, setDrives] = useState(null); const [loadError, setLoadError] = useState(null); + const [nativePickerAvailable, setNativePickerAvailable] = useState(false); + const [nativePickerBusy, setNativePickerBusy] = useState(false); const [extraArgs, setExtraArgs] = useState(""); const [loading, setLoading] = useState(!pool); const [cloneUrl, setCloneUrl] = useState(""); @@ -84,7 +87,7 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host, const cloneLogRef = useRef(null); const browseAbortRef = useRef(null); const cloning = cloneId !== null; - const locked = busy || cloning; + const locked = busy || cloning || nativePickerBusy; const dialogRef = useModalDialog({ onClose: () => { if (!locked) onCancel(); }, active: portalTarget !== null, @@ -119,6 +122,35 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host, return () => browseAbortRef.current?.abort(); }, [navigateTo]); + // The OS folder dialog runs on the server's desktop, so it is offered only for this machine. + useEffect(() => { + if (pool || host.id !== LOCAL_HOST_ID) return; + let active = true; + void fetch("/api/cwd/picker") + .then(async (response) => (await response.json()) as { available?: boolean }) + .then((data) => { if (active) setNativePickerAvailable(Boolean(data.available)); }) + .catch(() => {}); + return () => { active = false; }; + }, [host.id, pool]); + + const pickNativeDirectory = async () => { + if (locked) return; + setNativePickerBusy(true); + setLoadError(null); + try { + const response = await fetch("/api/cwd/pick", { + method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ hostId: host.id }), + }); + const data = await response.json() as { path?: string; error?: string; code?: string }; + if (!response.ok || data.error) throw new Error(formatApiError({ ...data, error: data.error ?? `HTTP ${response.status}` })); + if (data.path) await navigateTo(data.path); + } catch (cause) { + setLoadError(cause instanceof Error ? cause.message : String(cause)); + } finally { + setNativePickerBusy(false); + } + }; + useEffect(() => () => { cloneAbortRef.current?.abort(); cloneAbortRef.current = null; }, []); useEffect(() => { @@ -298,6 +330,20 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host, > {t("directoryPicker.go")} + {nativePickerAvailable && !pool && ( + + )}
diff --git a/lib/cwd-picker.test.mjs b/lib/cwd-picker.test.mjs new file mode 100644 index 00000000..67ed40e2 --- /dev/null +++ b/lib/cwd-picker.test.mjs @@ -0,0 +1,44 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +const { dialogOutcome, hasPicker, pickDirectory, pickerAvailable, pickerCommand } = await import("./cwd-picker.ts"); + +test("every desktop platform gets a folder dialog, anything else gets none", () => { + const win = pickerCommand("win32"); + assert.equal(win?.file, "powershell.exe"); + assert.ok(win?.args.includes("-STA")); + assert.ok(win?.args.some((arg) => arg.includes("System.Windows.Forms.FolderBrowserDialog"))); + assert.ok(win?.args.some((arg) => arg.includes("[Console]::Out.Write"))); + assert.equal(pickerCommand("darwin")?.file, "osascript"); + assert.deepEqual(pickerCommand("linux")?.args.slice(0, 2), ["--file-selection", "--directory"]); + assert.equal(pickerCommand("freebsd"), null); +}); + +test("no chooser means no dialog and no error, and no Browse button either", async () => { + assert.equal(await pickDirectory("freebsd"), null); + assert.equal(hasPicker("freebsd"), false); + // Windows and macOS ship their chooser; Linux is the only platform whose binary can be missing. + assert.equal(hasPicker("win32"), true); + assert.equal(hasPicker("darwin"), true); +}); + +test("a dismissed dialog is not a failure, and an AppleScript error is not a dismissal", () => { + // The chosen path keeps a meaningful trailing space; only the line terminator goes. + assert.deepEqual(dialogOutcome("win32", 0, "C:\\Users\\me\\a folder \r\n", ""), { path: "C:\\Users\\me\\a folder " }); + assert.deepEqual(dialogOutcome("win32", 0, "", ""), { cancelled: true }); + assert.deepEqual(dialogOutcome("linux", 1, "", ""), { cancelled: true }); + assert.deepEqual(dialogOutcome("darwin", 1, "", "execution error: User canceled. (-128)"), { cancelled: true }); + assert.deepEqual(dialogOutcome("darwin", 1, "", "execution error: Can't get application. (-1728)\n"), { + error: "execution error: Can't get application. (-1728)", + }); + assert.deepEqual(dialogOutcome("linux", 2, "", "zenity: cannot open display"), { error: "zenity: cannot open display" }); + assert.deepEqual(dialogOutcome("win32", 1, "", ""), { error: "The folder dialog exited with code 1" }); +}); + +test("a connection from another machine never gets the dialog, whatever its Host header said", () => { + // context.localPeer comes from the accepted socket, so a remote client cannot reach the dialog. + assert.equal(pickerAvailable(false, "win32"), false); + assert.equal(pickerAvailable(false, "darwin"), false); + assert.equal(pickerAvailable(true, "win32"), true); + assert.equal(pickerAvailable(true, "freebsd"), false); +}); diff --git a/lib/cwd-picker.ts b/lib/cwd-picker.ts new file mode 100644 index 00000000..a19d48f6 --- /dev/null +++ b/lib/cwd-picker.ts @@ -0,0 +1,88 @@ +// The OS folder dialog for the machine running the server. Only meaningful when the page is +// opened on that same desktop, so the /api/cwd routes gate on the connection's peer address. +import { spawn, spawnSync } from "node:child_process"; + +export type PickedDirectory = { path: string } | { cancelled: true }; + +const DIALOG_TIMEOUT_MS = 5 * 60 * 1000; + +/** The folder-dialog command for this platform, or null where we know no chooser. */ +export function pickerCommand(platform: NodeJS.Platform = process.platform): { file: string; args: string[] } | null { + if (platform === "win32") { + // ponytail: the classic WinForms dialog, not IFileOpenDialog — it works from a non-console + // parent without COM plumbing; swap in the Vista-style picker if the look ever matters. + return { + file: "powershell.exe", + args: [ + "-NoProfile", + "-STA", + "-Command", + [ + "Add-Type -AssemblyName System.Windows.Forms | Out-Null", + "$d = New-Object System.Windows.Forms.FolderBrowserDialog", + "$d.Description = 'Select a folder'", + "$d.SelectedPath = $env:USERPROFILE", + "if ($d.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write($d.SelectedPath) }", + ].join("; "), + ], + }; + } + if (platform === "darwin") return { file: "osascript", args: ["-e", 'POSIX path of (choose folder with prompt "Select a folder")'] }; + if (platform === "linux") return { file: "zenity", args: ["--file-selection", "--directory", "--title", "Select a folder"] }; + return null; +} + +/** Whether this platform's chooser is installed: Windows and macOS ship theirs, Linux needs zenity. */ +export function hasPicker(platform: NodeJS.Platform = process.platform): boolean { + const command = pickerCommand(platform); + if (!command) return false; + if (platform !== "linux") return true; + return spawnSync("which", [command.file], { stdio: "ignore" }).status === 0; +} + +/** Both the Browse button and the pick request need this: a chooser on the machine the browser is on. */ +export function pickerAvailable(localPeer: boolean, platform: NodeJS.Platform = process.platform): boolean { + return localPeer && hasPicker(platform); +} + +/** What a finished dialog means: a chosen path, a dismissal, or a failure worth reporting. */ +export type DialogOutcome = PickedDirectory | { error: string }; + +/** Reads a chooser's exit status: only a real dismissal counts as cancellation. */ +export function dialogOutcome( + platform: NodeJS.Platform | string, + code: number | null, + stdout: string, + stderr: string, +): DialogOutcome { + // Only the chooser's own line terminator: a directory name may end in a space. + const path = stdout.replace(/[\r\n]+$/, ""); + if (path) return { path }; + // Dismissed: zenity exits 1, the Windows dialog exits 0 with no output, and osascript exits 1 + // for a cancelled dialog — but every other AppleScript error exits 1 too, so it needs -128. + const dismissed = + code === 0 || (code === 1 && (platform === "linux" || (platform === "darwin" && stderr.includes("(-128)")))); + if (dismissed) return { cancelled: true }; + return { error: stderr.replace(/[\r\n]+$/, "") || `The folder dialog exited with code ${code}` }; +} + +/** Opens the dialog and waits for it; null when this platform has no chooser. */ +export function pickDirectory(platform: NodeJS.Platform = process.platform): Promise { + const command = pickerCommand(platform); + if (!command) return Promise.resolve(null); + return new Promise((resolve, reject) => { + const child = spawn(command.file, command.args, { windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }); + let stdout = ""; + let stderr = ""; + const timer = setTimeout(() => child.kill(), DIALOG_TIMEOUT_MS); + child.stdout.setEncoding("utf8").on("data", (chunk: string) => { stdout += chunk; }); + child.stderr.setEncoding("utf8").on("data", (chunk: string) => { stderr += chunk; }); + child.on("error", (cause) => { clearTimeout(timer); reject(cause); }); + child.on("close", (code) => { + clearTimeout(timer); + const outcome = dialogOutcome(platform, code, stdout, stderr); + if ("error" in outcome) reject(new Error(outcome.error)); + else resolve(outcome); + }); + }); +} diff --git a/lib/hosts/host-login.test.mjs b/lib/hosts/host-login.test.mjs index b06b409e..8c53c0af 100644 --- a/lib/hosts/host-login.test.mjs +++ b/lib/hosts/host-login.test.mjs @@ -16,7 +16,7 @@ const lock = `${file}.lock`; const primary = { url: "https://production.example", token: "production-token" }; const staging = { url: "http://127.0.0.1:40000", token: "staging-token" }; const other = { url: "https://other.example", token: "other-token" }; -const { addHostLink, loginHost, readHostLinks, readHostLogin, removeHostLink } = await import("./host-login.ts"); +const { addHostLink, isLoopbackHost, loginHost, readHostLinks, readHostLogin, removeHostLink } = await import("./host-login.ts"); const saved = () => JSON.parse(readFileSync(file, "utf8")); const seed = (value) => writeFileSync(file, JSON.stringify(value)); beforeEach(() => { @@ -209,3 +209,12 @@ test("legacy login and concurrent add retain the additional entry", { timeout: 2 assert.deepEqual(readHostLogin(), other); assert.deepEqual(new Map(readHostLinks().map((link) => [link.url, link.token])), new Map([staging, other].map((link) => [link.url, link.token]))); }); + +test("a socket address is loopback only for this machine, IPv4-mapped included", () => { + for (const address of ["127.0.0.1", "127.8.9.10", "::1", "[::1]", "::ffff:127.0.0.1", "localhost"]) { + assert.equal(isLoopbackHost(address), true, address); + } + for (const address of ["10.0.0.5", "::ffff:10.0.0.5", "192.168.1.20", "", "fe80::1"]) { + assert.equal(isLoopbackHost(address), false, address); + } +}); diff --git a/lib/hosts/host-login.ts b/lib/hosts/host-login.ts index 56c1c3cb..b7ac27cf 100644 --- a/lib/hosts/host-login.ts +++ b/lib/hosts/host-login.ts @@ -15,7 +15,8 @@ export type HostLink = { url: string; token: string }; type SavedLink = HostLink & Record; type HostConfig = Record & { url?: string; token?: string; links?: SavedLink[] }; -export const isLoopbackHost = (hostname: string) => hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname); +/** A loopback name or address, including the IPv4-mapped form a dual-stack socket reports. */ +export const isLoopbackHost = (hostname: string) => hostname === "localhost" || hostname === "::1" || hostname === "[::1]" || /^(::ffff:)?127(\.\d{1,3}){3}$/i.test(hostname); /** Existing configuration must never be confused with a first login. */ export class HostLoginUnreadableError extends Error { diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index e3d35d6a..8c2c3b38 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -624,6 +624,7 @@ "subagentTranscript.completionTruncated": "Output truncated", "codeBlock.copied": "copied", "codeBlock.copy": "copy", + "directoryPicker.browse": "Browse…", "directoryPicker.cancel": "Cancel", "directoryPicker.checking": "Checking…", "directoryPicker.close": "Close", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index f5e91e51..a6573354 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -610,6 +610,7 @@ "subagentTranscript.completionTruncated": "出力は切り捨てられました", "codeBlock.copied": "コピーしました", "codeBlock.copy": "コピー", + "directoryPicker.browse": "参照…", "directoryPicker.cancel": "キャンセル", "directoryPicker.checking": "確認中…", "directoryPicker.close": "閉じる", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index f33fe048..92d80a75 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -610,6 +610,7 @@ "subagentTranscript.completionTruncated": "输出已被截断", "codeBlock.copied": "已复制", "codeBlock.copy": "复制", + "directoryPicker.browse": "浏览…", "directoryPicker.cancel": "取消", "directoryPicker.checking": "检查中…", "directoryPicker.close": "关闭", diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index 548ae451..2e66e92e 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -624,6 +624,7 @@ "subagentTranscript.completionTruncated": "輸出已截斷", "codeBlock.copied": "已複製", "codeBlock.copy": "複製", + "directoryPicker.browse": "瀏覽…", "directoryPicker.cancel": "取消", "directoryPicker.checking": "檢查中…", "directoryPicker.close": "關閉", diff --git a/server/app.ts b/server/app.ts index 2fd9b6fd..796493d8 100644 --- a/server/app.ts +++ b/server/app.ts @@ -1,6 +1,7 @@ import { readFileSync } from "node:fs"; import path from "node:path"; import { parseArgs } from "node:util"; +import { isLoopbackHost } from "@/lib/hosts/host-login"; import { hostLinkSocket, type LinkSocketData } from "@/lib/hosts/hub"; import { maintenanceSocket, type MaintenanceSocketData } from "@/lib/hosts/maintenance-hub"; import { proxy } from "@/proxy"; @@ -51,7 +52,7 @@ function decodable(pathname: string): boolean { async function handle( request: Request, server: Bun.Server, - respond: (context: { gate: "public" | "authenticated"; disableIdleTimeout: () => void }) => Response | undefined | Promise, + respond: (context: { gate: "public" | "authenticated"; disableIdleTimeout: () => void; localPeer: boolean }) => Response | undefined | Promise, ): Promise { let pathname: string; try { @@ -62,6 +63,10 @@ async function handle( } const gate = proxy(request); if (gate instanceof Response) return finalizeResponse(request, gate); + // Locality for routes that act on this desktop: the accepted socket, never request.url's host, which the + // client writes through its Host header. + const address = server.requestIP(request)?.address; + const localPeer = address !== undefined && isLoopbackHost(address); if (!decodable(pathname)) return finalizeResponse(request, text("Bad Request", 400)); const lifted = gate === "authenticated" && pathname.startsWith("/api/"); if (lifted) server.timeout(request, 0); @@ -71,6 +76,7 @@ async function handle( try { response = await respond({ gate, + localPeer, disableIdleTimeout: () => { keepOpen = true; server.timeout(request, 0); @@ -128,7 +134,7 @@ export function startServer(options: { port: number; hostname: string; dev: bool for (const [key, mod] of Object.entries(ROUTE_MODULES)) { const { pattern, rest } = routePattern(key); const matcher = new URLPattern({ pathname: pattern }); - routes[pattern] = (request, server) => handle(request, server, ({ disableIdleTimeout }) => { + routes[pattern] = (request, server) => handle(request, server, ({ disableIdleTimeout, localPeer }) => { // Bun's router matched the raw path, but the gate and the handler read request.url, where `..` and `%2e%2e` // are resolved. Answer only when that path is still this route, so no gated route runs under an ungated path. const { pathname } = new URL(request.url); @@ -139,7 +145,7 @@ export function startServer(options: { port: number; hostname: string; dev: bool if (name !== "0" && value !== undefined) params[name] = decodeURIComponent(value); } if (rest) params[rest.name] = pathname.split("/").slice(rest.index).filter(Boolean).map(decodeURIComponent); - return dispatch(mod, request, params, disableIdleTimeout, (data) => server.upgrade(request, { data })); + return dispatch(mod, request, params, disableIdleTimeout, (data) => server.upgrade(request, { data }), localPeer); }); } if (html) routes[DEV_INDEX] = html; diff --git a/server/routes.ts b/server/routes.ts index b3a35068..e30711d9 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -12,6 +12,8 @@ import * as authApiKeyProvider from "@/app/api/auth/api-key/[provider]/route"; import * as authLoginProvider from "@/app/api/auth/login/[provider]/route"; import * as authProviders from "@/app/api/auth/providers/route"; import * as cwdBrowse from "@/app/api/cwd/browse/route"; +import * as cwdPick from "@/app/api/cwd/pick/route"; +import * as cwdPicker from "@/app/api/cwd/picker/route"; import * as cwdValidate from "@/app/api/cwd/validate/route"; import * as defaultCwd from "@/app/api/default-cwd/route"; import * as events from "@/app/api/events/route"; @@ -87,9 +89,10 @@ type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; // its socket; see handle() in server/app.ts. // upgrade: makes the request a WebSocket (server.upgrade), a host link; a handler that upgraded // returns undefined. +// localPeer: the connection came from this machine's loopback interface. Taken from the socket, never from Host. export type RouteHandler = ( request: Request, - context: { params: Promise; disableIdleTimeout: () => void; upgrade: (data: ServerSocketData) => boolean }, + context: { params: Promise; disableIdleTimeout: () => void; upgrade: (data: ServerSocketData) => boolean; localPeer: boolean }, ) => Response | undefined | Promise; export type RouteModule = Partial>; @@ -107,6 +110,8 @@ export const ROUTE_MODULES: Record = { "auth/login/[provider]": authLoginProvider, "auth/providers": authProviders, "cwd/browse": cwdBrowse, + "cwd/pick": cwdPick, + "cwd/picker": cwdPicker, "cwd/validate": cwdValidate, "default-cwd": defaultCwd, "events": events, @@ -190,6 +195,7 @@ export async function dispatch( params: Record, disableIdleTimeout: () => void = () => {}, upgrade: (data: ServerSocketData) => boolean = () => false, + localPeer = false, ): Promise { const handler = mod[request.method as Method] ?? (request.method === "HEAD" ? mod.GET : undefined); if (!handler) { @@ -199,7 +205,7 @@ export async function dispatch( return new Response(null, { status: 204, headers: { allow } }); } try { - return await handler(request, { params: Promise.resolve(params) as Promise, disableIdleTimeout, upgrade }); + return await handler(request, { params: Promise.resolve(params) as Promise, disableIdleTimeout, upgrade, localPeer }); } catch (error) { console.error(error); return Response.json({ error: "Internal Server Error" }, { status: 500 }); From 33be65ed145ffd8efc49a2511fe6f8bea5cabe2e Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:41:07 +0000 Subject: [PATCH 15/45] feat(sessions): navigation-only reads, context ETag and a prompt-less state Port of ompweb-dev/ompweb#415. A rename now falls back to pi's session_info entry only when pi refused it or the child is gone. --- AGENTS.md | 6 +- app/api/agent/[id]/route.ts | 13 +- app/api/sessions/[id]/context/route.ts | 31 +- app/api/sessions/[id]/route.ts | 104 ++++- lib/api-utils.ts | 18 + lib/hosts/hub.test.mjs | 12 + lib/hosts/hub.ts | 15 +- lib/hosts/session-ops.ts | 64 +++- lib/pi-types.ts | 3 +- lib/pi/session-files.ts | 2 +- lib/rpc-manager.ts | 7 +- lib/session-reader.ts | 41 ++ lib/session-routes.test.mjs | 500 +++++++++++++++++++++++++ 13 files changed, 778 insertions(+), 38 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a8525d9d..a3cc8f3a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -140,9 +140,9 @@ app/api/ sessions/search/route.ts GET ?q= NDJSON { scores } batches (titles + per-host transcripts) sessions/import/route.ts POST import a session .jsonl sessions/archive/route.ts GET archives of every host | POST restore (see "Session archive and restore") - sessions/[id]/route.ts GET/PATCH/DELETE a session + sessions/[id]/route.ts GET/PATCH/DELETE a session; GET ?meta=1 answers the navigation shape (tree + leaf, no transcript), ?includeState=alive the split liveness shape (`running` = a turn in flight, `alive` = the child exists) sessions/[id]/state/route.ts GET live state; always carries `outbox`, `outboxSettledIds`, `outboxScope` - sessions/[id]/context/route.ts GET ?leafId= context of one leaf (read-only branch view) + sessions/[id]/context/route.ts GET ?leafId= context of one leaf (read-only branch view); strong ETag, 304 on a matching If-None-Match sessions/[id]/entries/[entryId]/thinking/route.ts GET one deferred thinking block sessions/[id]/matches/route.ts GET ?q=&limit= best search hits in the active conversation sessions/[id]/export/route.ts GET exported HTML (`tau-session-.html`; a remote session's always as an attachment) @@ -150,7 +150,7 @@ app/api/ sessions/[id]/auto-name/route.ts POST stored title, else one derived from the first user message (`generated` always false) sessions/[id]/subagents/route.ts, subagents/[subagentId]/route.ts subagent roster history and transcripts agent/new/route.ts POST start a session (host, pool or cluster target) - agent/[id]/route.ts GET state | POST any agent command (`runAgentCommand`) + agent/[id]/route.ts GET state (?systemPrompt=0 drops the system prompt from the poll) | POST any agent command (`runAgentCommand`) agent/[id]/bash-output/route.ts GET streamed `!` command output events/route.ts GET the multiplexed SSE | POST subscribe/unsubscribe channels transport-metrics/route.ts GET { now } (clock probe) | POST { samples } → /tau/transport-metrics.jsonl diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index dde692b5..d30c9d4c 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -33,10 +33,13 @@ export async function POST( // GET /api/agent/[id] - Get current agent state export async function GET( - _req: Request, + req: Request, { params }: { params: Promise<{ id: string }> } ) { const { id } = await params; + // Default stays the full shape; `?systemPrompt=0` drops the ~13 KB prompt + // from the 15 s state poll. Any other value (including "1") keeps it. + const includeSystemPrompt = new URL(req.url).searchParams.get("systemPrompt") !== "0"; try { const session = getRpcSession(id); @@ -44,7 +47,13 @@ export async function GET( return Response.json({ running: false }); } try { - const state = await session.send({ type: "get_state" }); + // Through the wrapper's command path, not a dedicated method: that is + // the contract every wrapper fake implements, and `dispatchCommand` + // already honors `systemPrompt: false`. + const state = await session.send({ + type: "get_state", + ...(includeSystemPrompt ? {} : { systemPrompt: false }), + }); return Response.json({ running: true, state }); } catch (error) { if (error instanceof WebRpcError && error.code === "session_unresponsive") { diff --git a/app/api/sessions/[id]/context/route.ts b/app/api/sessions/[id]/context/route.ts index d0bc36a6..9431f15f 100644 --- a/app/api/sessions/[id]/context/route.ts +++ b/app/api/sessions/[id]/context/route.ts @@ -1,8 +1,27 @@ import { buildSessionContext } from "@/lib/session-reader"; -import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; +import { apiErrorResponse, ifNoneMatchSatisfied, opErrorResponse, resolveSessionHostOr404, strongEtag } from "@/lib/api-utils"; import { getRpcSession } from "@/lib/rpc-manager"; import { MAX_SYNC_MESSAGES, parseHistoryCursor, selectSessionHistory, type SessionHistoryCursor, type SessionHistoryPage, type SessionSyncResponse } from "@/lib/session-sync"; +/** + * Serialize once, key the validator on those exact bytes: the ETag cannot + * disagree with the body, and it covers everything that shapes it (branch, + * options, live stream snapshot) without this route needing the file's + * identity — which a remote host would not expose to this process. + */ +function jsonBodyResponse(req: Request, body: unknown, cacheControl: "no-store" | null = null): Response { + const text = JSON.stringify(body); + const etag = strongEtag(text); + const headers: Record = { ETag: etag }; + if (cacheControl) headers["Cache-Control"] = cacheControl; + if (ifNoneMatchSatisfied(req.headers.get("if-none-match"), etag)) { + return new Response(null, { status: 304, headers }); + } + return new Response(text, { + headers: { "Content-Type": "application/json", "Content-Length": String(Buffer.byteLength(text)), ...headers }, + }); +} + export async function GET( req: Request, { params }: { params: Promise<{ id: string }> } @@ -63,7 +82,7 @@ export async function GET( const session = notFound && (boundary === "1" || (sync === "1" && !cursor?.lastEntryId && leafId === undefined)) ? getRpcSession(id) : undefined; if (session?.isAlive() && !(await session.host.sessionFileExists(session.sessionFile))) { if (boundary === "1") { - return Response.json({ entryIds: [] }, { headers: { "Cache-Control": "no-store" } }); + return jsonBodyResponse(req, { entryIds: [] }, "no-store"); } const response: SessionSyncResponse = { ...selectSessionHistory(buildSessionContext([]), cursor, limit), @@ -71,12 +90,12 @@ export async function GET( leafId: null, live: session.getStreamSnapshot(), }; - return Response.json(response, { headers: { "Cache-Control": "no-store" } }); + return jsonBodyResponse(req, response, "no-store"); } return "response" in result ? result.response : opErrorResponse(result); } if (boundary === "1") { - return Response.json(result.value, { headers: { "Cache-Control": "no-store" } }); + return jsonBodyResponse(req, result.value, "no-store"); } if (sync === "1") { const page = result.value as { history: SessionHistoryPage; leafId: string | null; tipId: string | null }; @@ -87,9 +106,9 @@ export async function GET( ? session.getStreamSnapshot() : null; const response: SessionSyncResponse = { ...page.history, sessionId: id, leafId: page.leafId, live }; - return Response.json(response, { headers: { "Cache-Control": "no-store" } }); + return jsonBodyResponse(req, response, "no-store"); } - return Response.json(result.value); + return jsonBodyResponse(req, result.value); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/sessions/[id]/route.ts b/app/api/sessions/[id]/route.ts index c67b2a77..10f9635a 100644 --- a/app/api/sessions/[id]/route.ts +++ b/app/api/sessions/[id]/route.ts @@ -1,11 +1,26 @@ import { apiErrorResponse, hostOfflineResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; import { HostOpError } from "@/lib/hosts/link-protocol"; import { invalidateHostSessionList } from "@/lib/hosts/session-index"; +import type { SessionReadValue } from "@/lib/hosts/session-ops"; import { invalidateSessionCaches } from "@/lib/session-reader"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { clearExitedRpcSession, getLiveRpcSessionIds, getRpcSession, WebRpcError } from "@/lib/rpc-manager"; import { forgetSessionReplacementMappings } from "@/lib/message-outbox"; import { removeSessionWatches } from "@/lib/github/watch-store"; +import { RpcCommandError, RpcCommandTimeoutError } from "@/lib/pi/rpc-process"; + +/** Session-level failures a client retries instead of treating the request as + * applied: pi is busy, restarting or was reset, and the session keeps going. + * `session_slow` and `session_state_timeout` are the codes the wrapper and the + * `get_state` dispatch use for "the completion is unknown"; this route answers + * its own `RpcCommandTimeoutError` with `session_slow` below, and accepts the + * rest from any wrapper that raises them, so a client sees one stable name. */ +const RETRIABLE_SESSION_CODES: Record = { + session_slow: true, + session_state_timeout: true, + session_restarting: true, + session_unresponsive: true, +}; /** Stable, client-safe error body for catch-all handlers: details go to the * server log only, never to the browser. */ @@ -13,18 +28,51 @@ function sessionsErrorResponse(error: unknown): Response { if (error instanceof WebRpcError && error.code === "session_busy") { return Response.json({ error: error.message, code: error.code }, { status: 409 }); } + // pi is busy, restarting or was reset — not gone: the session keeps running, + // so a client retries instead of treating the rename as applied. + if (error instanceof WebRpcError && RETRIABLE_SESSION_CODES[error.code]) { + return Response.json({ error: error.message, code: error.code }, { status: 503 }); + } + // A command timeout leaves the completion unknown. Nothing was written here + // and the child still owns the file, so the client retries and re-reads the + // title instead of assuming the rename stuck. + if (error instanceof RpcCommandTimeoutError) { + return Response.json( + { error: "The session did not confirm the change in time. It keeps running — retry shortly.", code: "session_slow" }, + { status: 503 }, + ); + } if (error instanceof RequestBodyTooLargeError) { return Response.json({ error: "Request body is too large", code: "request_too_large" }, { status: 413 }); } if (error instanceof SyntaxError) { return Response.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); } - // A host link failure keeps its status: 503 offline, 504 timeout. - if (error instanceof HostOpError) return apiErrorResponse(error); + // A host link failure keeps its status: 503 offline, 504 timeout. A live + // wrapper whose link dropped answers 503 `{hostOffline: true}` plus its + // `delivery` ("refused": nothing left this server). + if (error instanceof HostOpError || (error instanceof WebRpcError && error.code === "host_offline")) return apiErrorResponse(error); console.error("[api/sessions]", error); return Response.json({ error: "Session request failed", code: "session_request_failed" }, { status: 500 }); } +/** `?meta=1` against a daemon that predates the option: it ignores `meta` and + * answers the full transcript. Derive the navigation shape from it — the same + * context supplies the branch metadata — so the client never receives the + * second copy. `lastMessageAt` stays absent: that daemon never scanned it. */ +function navigationShape(value: SessionReadValue): SessionReadValue { + if (!value.context) return value; + return { + ...value, + info: { + ...value.info, + model: value.context.model, + thinkingLevel: value.context.thinkingLevel, + }, + context: null, + }; +} + export async function GET( req: Request, { params }: { params: Promise<{ id: string }> } @@ -35,34 +83,62 @@ export async function GET( if ("response" in resolved) return resolved.response; const searchParams = new URL(req.url).searchParams; + const meta = searchParams.get("meta") === "1"; const includeState = searchParams.has("includeState"); + // `?includeState=alive` opts into the split liveness shape; every other + // value (including bare `?includeState`) keeps the historical meaning. + const stateAlive = searchParams.get("includeState") === "alive"; const read = await resolved.host.sessionOps.readSession(id, { deferThinking: searchParams.has("deferThinking"), deferMedia: searchParams.has("deferMedia"), + meta, }); if (!read.ok) return opErrorResponse(read); + // A daemon that predates `meta` ignores the option and answers the full + // transcript; derive the navigation shape here so the client never gets it. + const value = meta ? navigationShape(read.value) : read.value; // ?includeState=1 inlines the wrapper's live agent state (same shape as // GET /api/agent/[id]) so the client's post-turn refresh is one request // instead of two. On a get_state failure the field is omitted entirely — // callers treat a missing `agent` as "fetch it separately". - let agent: { running: boolean; state?: unknown } | undefined; + // + // The historical shape says `running: true` for any live wrapper, idle + // included (that is what /api/agent and /state answer). The idle/running + // split is opt-in (`?includeState=alive`), so an existing caller keeps its + // meaning: `running` there is the child's liveness, not a turn in flight. + let agent: { running: boolean; alive?: boolean; state?: unknown } | undefined; if (includeState) { const rpc = getRpcSession(id); if (rpc?.isAlive()) { try { - agent = { running: true, state: await rpc.send({ type: "get_state" }) }; + const state = await rpc.send({ type: "get_state" }); + // The child can exit between its reply and this line: its state is + // stale then, so answer the not-live shape instead of reporting it. + if (rpc.isAlive()) { + agent = stateAlive + ? { running: rpc.isRunning(), alive: true, state } + : { running: true, state }; + } else { + agent = stateAlive ? { running: false, alive: false } : { running: false }; + } } catch { // Leave agent unset; the session payload is still valid without it. } } else { - agent = { running: false }; + agent = stateAlive ? { running: false, alive: false } : { running: false }; } } + // ?meta=1 is the navigation shape: the tree and leaf the native client + // reads from this route, without a second transcript copy. `context` is + // omitted entirely (not null) so clients keyed on its presence keep their + // historical shape; the transcript comes from /api/sessions/[id]/context. + const { context, ...navigation } = value; return Response.json({ sessionId: id, - ...read.value, + ...navigation, + ...(context ? { context } : {}), ...(agent ? { agent } : {}), }); } catch (error) { @@ -92,8 +168,20 @@ export async function PATCH( await rpc.send({ type: "set_session_name", name: name.trim() }); renamed = true; } catch (error) { - if (error instanceof WebRpcError && error.code === "session_busy") throw error; - // Fall back to a session_info entry in the file below. + // The file fallback is only for "nothing was applied": pi answered + // with a rejection (`RpcCommandError`), or the child died before + // answering, so no live process can flush over our write. Everything + // else keeps its own answer: a timeout leaves the completion unknown + // while the child still owns the file, and a busy/restarting/offline + // session is retried by the client instead of being written behind + // pi's back (its next flush would clobber the slot). + if (error instanceof RpcCommandError) { + // pi rejected the command outright; fall through to the file. + } else if (error instanceof RpcCommandTimeoutError || error instanceof WebRpcError) { + throw error; + } else if (rpc.isAlive?.()) { + throw error; + } } } if (!renamed) { diff --git a/lib/api-utils.ts b/lib/api-utils.ts index d04b50f3..9ed697cb 100644 --- a/lib/api-utils.ts +++ b/lib/api-utils.ts @@ -1,3 +1,4 @@ +import { createHash } from "crypto"; import { pooledWorkspaceForSession } from "./hosts/pool-starts"; import { isValidSessionId } from "./session-file-references-core"; import { isLinkUp, type Host } from "./hosts/host"; @@ -84,6 +85,23 @@ export function opErrorResponse(result: Extract, { ok: false } return Response.json({ error: result.error, code: result.code }, { status: result.status }); } +/** Strong, quoted ETag from the inputs that identify one response body. */ +export function strongEtag(identity: string): string { + return `"${createHash("sha256").update(identity).digest("hex").slice(0, 32)}"`; +} + +/** Whether an `If-None-Match` header covers `etag` (`*` always does). Uses the + * weak comparison RFC 9110 §13.1.2 requires, so a proxy that weakens our + * strong tag (`W/"…"`) still gets its 304. */ +export function ifNoneMatchSatisfied(header: string | null, etag: string): boolean { + if (!header) return false; + const expected = etag.replace(/^W\//, ""); + return header.split(",").some((candidate) => { + const value = candidate.trim(); + return value === "*" || value.replace(/^W\//, "") === expected; + }); +} + /** Uniform JSON error body used by most API routes. A host link failure keeps * its status (503 offline, 504 timeout) and code; a session whose host is * offline answers 503 `{hostOffline: true}`, plus its `delivery` for an agent diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index 5528fb2d..ed562052 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -483,6 +483,12 @@ test("export, session and context results must have the fields the routes read", await assert.rejects(answer(() => ops.exportSession("s1"), null), badResult); await assert.rejects(answer(() => ops.readSession("s1", options), "not a session"), badResult); await assert.rejects(answer(() => ops.readSession("s1", options), { info: {}, context: null }), badResult); + // `?meta=1`: a null context must carry the navigation fields the route reads. + const metaOptions = { ...options, meta: true }; + await assert.rejects(answer(() => ops.readSession("s1", metaOptions), { info: {}, context: null }), badResult); + await assert.rejects(answer(() => ops.readSession("s1", metaOptions), { info: { model: null, thinkingLevel: "off" }, leafId: null, tree: "t", context: null }), badResult); + await assert.rejects(answer(() => ops.readSession("s1", metaOptions), { info: { model: null }, leafId: null, tree: [], context: null }), badResult); + await assert.rejects(answer(() => ops.readSession("s1", metaOptions), { info: { model: null, thinkingLevel: "off" }, leafId: 3, tree: [], context: null }), badResult); await assert.rejects(answer(() => ops.readContext("s1", undefined, contextOptions()), { context: 3 }), badResult); await assert.rejects(answer(() => ops.readContext("s1", undefined, contextOptions({ boundary: true })), { entryIds: "e1" }), badResult); await assert.rejects(answer(() => ops.readContext("s1", undefined, contextOptions({ sync: { cursor: null, limit: 10 } })), { leafId: null, tipId: null }), badResult); @@ -491,6 +497,12 @@ test("export, session and context results must have the fields the routes read", assert.deepEqual((await answer(() => ops.exportSession("s1"), exported)).value, exported); const session = { filePath: "/f", info: { id: "s1" }, leafId: null, tree: [], context: { messages: [] } }; assert.deepEqual((await answer(() => ops.readSession("s1", options), session)).value, session); + // A daemon that predates `?meta=1` ignores the option and answers the full + // transcript; the route normalizes it, so the validator must accept it. + assert.deepEqual((await answer(() => ops.readSession("s1", metaOptions), session)).value, session); + // The navigation shape itself: no transcript, branch metadata in `info`. + const navigation = { filePath: "/f", info: { id: "s1", model: null, thinkingLevel: "off" }, leafId: "e1", tree: [], context: null }; + assert.deepEqual((await answer(() => ops.readSession("s1", metaOptions), navigation)).value, navigation); const page = { history: { messages: [] }, leafId: "e1", tipId: "e1" }; assert.deepEqual((await answer(() => ops.readContext("s1", "e1", contextOptions({ sync: { cursor: null, limit: 10 } })), page)).value, page); assert.deepEqual((await answer(() => ops.readContext("s1", undefined, contextOptions({ boundary: true })), { entryIds: ["e1"] })).value, { entryIds: ["e1"] }); diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 1d2f3d4b..5f64880d 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -1026,8 +1026,19 @@ function validResult(op: keyof SessionOps, result: unknown, args: unknown[]): bo && typeof value.baseCommit === "string" && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(value.baseCommit); case "exportSession": return isRecord(value) && typeof value.html === "string" && typeof value.fileName === "string"; - case "readSession": - return isRecord(value) && isRecord(value.info) && isRecord(value.context); + case "readSession": { + const options = isRecord(args[1]) ? args[1] : {}; + if (!isRecord(value) || !isRecord(value.info)) return false; + // A daemon that predates `?meta=1` ignores the option and answers the + // full transcript; the route derives the navigation shape from it. + if (isRecord(value.context)) return true; + if (options.meta !== true || value.context !== null) return false; + // Nothing to derive the navigation fields from: a null-context result + // must carry the tree, leaf and branch metadata itself (model may be null). + return Array.isArray(value.tree) && nullableString(value.leafId) + && (value.info.model === null || isRecord(value.info.model)) + && typeof value.info.thinkingLevel === "string"; + } case "readContext": { // The context route reads a different shape per mode. const options = isRecord(args[2]) ? args[2] : {}; diff --git a/lib/hosts/session-ops.ts b/lib/hosts/session-ops.ts index 6414ef6a..d3cfb4b6 100644 --- a/lib/hosts/session-ops.ts +++ b/lib/hosts/session-ops.ts @@ -25,6 +25,7 @@ import { MAX_SESSION_LOAD_BYTES, readSessionHeaderSync, sessionNameFromEntries, + scanSessionInfoCached, setSessionTitle, writeSessionFileAtomicSync, } from "../pi/session-files"; @@ -44,6 +45,7 @@ import { } from "../project-registry"; import { buildSessionContext, + buildSessionContextSummary, getSessionContextBoundary, getSessionEntries, getSessionEntriesForDisplayAsync, @@ -70,6 +72,9 @@ export type OpResult = { ok: true; value: T } | { ok: false; status: number; export interface SessionReadOptions { deferThinking: boolean; deferMedia: boolean; + /** Navigation-only shape (`?meta=1`): `context` is null and `info` carries + * the branch's model/thinking level and the conversation's activity time. */ + meta?: boolean; } export interface ContextReadOptions extends SessionReadOptions { @@ -84,10 +89,15 @@ export interface ContextReadOptions extends SessionReadOptions { /** `GET /api/sessions/[id]` minus the route's `sessionId` and live `agent`. */ export interface SessionReadValue { filePath: string; - info: Omit; + info: Omit & { + /** `?meta=1` only: the branch's model choice and reasoning level. */ + model?: SessionContext["model"]; + thinkingLevel?: string; + }; leafId: string | null; tree: unknown[]; - context: SessionContext; + /** null in the `?meta=1` navigation shape. */ + context: SessionContext | null; } export interface ProjectUpdate { @@ -192,6 +202,27 @@ function branchPreviewForEntry(entry: { id?: string; type?: string; message?: un return { ...(role ? { role } : {}), text }; } +/** First `{type:"text"}` block's text in a message content array ("" when none). */ +function textBlockText(content: readonly unknown[]): string { + for (const block of content) { + if (block && typeof block === "object" && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") { + return block.text; + } + } + return ""; +} + +/** `info.firstMessage`: the first user message's text, with the "(no messages)" fallback. */ +function firstUserMessageText(messages: ReadonlyArray<{ role?: string; content?: unknown }>): string { + const message = messages.find((entry) => entry.role === "user"); + if (!message) return "(no messages)"; + const content = message.content; + const text = typeof content === "string" + ? content + : Array.isArray(content) ? textBlockText(content) : ""; + return text || "(no messages)"; +} + /** * Project the session tree into the shallow navigation tree sent to the client. * Keeps roots, branch points, and leaves while contracting single-child chains @@ -331,7 +362,7 @@ export const sessionOps: SessionOps = { }, listSessionIdsForRestore: async () => listSessionIdsForRestore(), - async readSession(id, { deferThinking, deferMedia: deferToolResultImages }) { + async readSession(id, { deferThinking, deferMedia: deferToolResultImages, meta }) { const filePath = await resolveSessionPath(id); if (!filePath) return sessionNotFound(); try { @@ -342,14 +373,21 @@ export const sessionOps: SessionOps = { const displayEntries = await getSessionEntriesForDisplayAsync(filePath); const leafId = getLeafEntryId(displayEntries); const tree = projectTreeForResponse(buildSessionTree(displayEntries)); - const context = buildSessionContext(displayEntries, leafId, { deferThinking, deferToolResultImages }); + // ?meta=1 is the navigation shape: the tree and leaf the native client + // reads from this route, without the second transcript copy. The context + // stays on /api/sessions/[id]/context, which defers media/thinking and + // answers 304. Without the parameter the historical shape is unchanged. + const context = meta ? null : buildSessionContext(displayEntries, leafId, { deferThinking, deferToolResultImages }); + const summary = meta ? buildSessionContextSummary(displayEntries, leafId, { deferThinking, deferToolResultImages }) : null; + // Same scan the session list uses (memoized on size+mtime), so the + // detail's activity time cannot diverge from the sidebar's. + const lastMessageAt = meta ? scanSessionInfoCached(filePath)?.lastMessageAt?.toISOString() : undefined; let modified = header.timestamp ?? new Date().toISOString(); try { modified = statSync(filePath).mtime.toISOString(); } catch { /* use header timestamp */ } const parentSessionId = header.parentSession ? await resolveParentSessionId(header.parentSession) : undefined; - const firstUser = context.messages.find((m) => m.role === "user"); const info = { path: filePath, id: header.id, @@ -357,14 +395,16 @@ export const sessionOps: SessionOps = { name: sessionNameFromEntries(displayEntries), created: header.timestamp, modified, - messageCount: context.messages.length, - firstMessage: firstUser - ? (() => { - const c = (firstUser as { content: unknown }).content; - return typeof c === "string" ? c : (Array.isArray(c) ? (c.find((b: { type: string }) => b.type === "text") as { text: string } | undefined)?.text ?? "" : "") || "(no messages)"; - })() - : "(no messages)", + messageCount: context ? context.messages.length : summary!.messageCount, + firstMessage: context ? firstUserMessageText(context.messages) : summary!.firstMessage, parentSessionId, + // The meta shape has no `context`, so the branch's model/thinking + // level and the conversation's activity time ride in `info` instead. + ...(summary ? { + model: summary.model, + thinkingLevel: summary.thinkingLevel, + ...(lastMessageAt ? { lastMessageAt } : {}), + } : {}), }; return ok({ filePath, info, leafId, tree, context }); } catch (error) { diff --git a/lib/pi-types.ts b/lib/pi-types.ts index 59f4a4fb..2c4c38ef 100644 --- a/lib/pi-types.ts +++ b/lib/pi-types.ts @@ -116,7 +116,8 @@ export interface WebSessionState { queuedMessages: QueuedMessages; supportsClientMessageIds?: boolean; contextUsage: ContextUsage | null; - systemPrompt: string; + /** Absent when the client asked for the prompt-less shape (`?systemPrompt=0`). */ + systemPrompt?: string; thinkingLevel: string; autoRetryEnabled?: boolean; todoPhases: TodoPhase[]; diff --git a/lib/pi/session-files.ts b/lib/pi/session-files.ts index 0149f1a6..429baa70 100644 --- a/lib/pi/session-files.ts +++ b/lib/pi/session-files.ts @@ -773,7 +773,7 @@ export function invalidateAllSessionScanCaches(): void { /** scanSessionInfo memoized on (path, size, mtimeMs). Callers must treat the * returned info as immutable — cache hits share one object. */ -function scanSessionInfoCached(filePath: string): PiSessionInfo | undefined { +export function scanSessionInfoCached(filePath: string): PiSessionInfo | undefined { let stat: { size: number; mtime: Date; mtimeMs: number }; try { stat = statSync(filePath); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 0ca70405..8e7c57b1 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -1640,7 +1640,7 @@ export class AgentSessionWrapper { } } - private buildWebState(state: RpcSessionState): WebSessionState { + private buildWebState(state: RpcSessionState, includeSystemPrompt = true): WebSessionState { const wasRunning = this.isRunning(); // Reconcile process-side flags with authoritative child state. @@ -1697,7 +1697,8 @@ export class AgentSessionWrapper { queuedMessages: state.queuedMessages ?? { steering: [], followUp: [] }, ...(state.supportsClientMessageIds === true ? { supportsClientMessageIds: true } : {}), contextUsage: state.contextUsage ?? null, - systemPrompt: state.systemPrompt?.join("\n\n") ?? "", + // `?systemPrompt=0` drops the ~13 KB prompt from the 15 s state poll. + ...(includeSystemPrompt ? { systemPrompt: state.systemPrompt?.join("\n\n") ?? "" } : {}), thinkingLevel: state.thinkingLevel ?? "off", todoPhases: state.todoPhases ?? [], extensionStatuses: Array.from(this.extensionStatuses, ([key, text]) => ({ key, text })), @@ -2263,7 +2264,7 @@ export class AgentSessionWrapper { case "get_state": { try { const state = await this.proc.sendCommand({ type: "get_state" }, GET_STATE_TIMEOUT_MS); - return this.buildWebState(state); + return this.buildWebState(state, command.systemPrompt !== false); } catch (error) { if (error instanceof RpcCommandTimeoutError) { // This is only an observer poll. A busy event loop or delayed RPC diff --git a/lib/session-reader.ts b/lib/session-reader.ts index fd23bf44..00a99b0a 100644 --- a/lib/session-reader.ts +++ b/lib/session-reader.ts @@ -815,6 +815,47 @@ export function buildSessionContext( }; } +/** First `{type:"text"}` block's text in a message content array ("" when none). */ +function textBlockText(content: readonly unknown[]): string { + for (const block of content) { + if (block && typeof block === "object" && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") { + return block.text; + } + } + return ""; +} + +/** + * The two `info` fields derived from the active context — `messageCount` and + * `firstMessage` — without converting a whole transcript into UI messages, + * plus the branch's `model`/`thinkingLevel` (the meta shape carries them in + * `info` because it has no `context`). `GET /api/sessions/[id]?meta=1` needs + * them for a navigation-only response, where building (and then dropping) a + * multi-megabyte context would defeat the point of the meta shape. + */ +export function buildSessionContextSummary( + entries: SessionEntry[], + leafId?: string | null, + options: { deferThinking?: boolean; deferToolResultImages?: boolean; includePreCompaction?: boolean } = {}, +): { messageCount: number; firstMessage: string; model: SessionContext["model"]; thinkingLevel: string } { + const { selected, model, thinkingLevel } = selectSessionContext(entries, leafId, options); + let firstMessage = "(no messages)"; + for (const entry of selected) { + const userMessage = entry.type === "branch_summary" + ? Boolean(entry.summary) + : entry.type === "message" && isRecord(entry.message) && entry.message.role === "user"; + if (!userMessage) continue; + const message = entryToUiMessage(entry, options); + const content = message && "content" in message ? message.content : undefined; + const text = typeof content === "string" + ? content + : Array.isArray(content) ? textBlockText(content) : ""; + firstMessage = text || "(no messages)"; + break; + } + return { messageCount: selected.length, firstMessage, model, thinkingLevel }; +} + /** Select ordering and branch metadata without converting message bodies. */ function selectSessionContext( entries: SessionEntry[], diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index dc84e0f5..f219232f 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -17,8 +17,10 @@ const stateRoute = await import("../app/api/sessions/[id]/state/route.ts"); const autoNameRoute = await import("../app/api/sessions/[id]/auto-name/route.ts"); const sessionsListRoute = await import("../app/api/sessions/route.ts"); const { cacheSessionPath, invalidateSessionListCache, listAllSessions, resolveSessionPath } = await import("./session-reader.ts"); +const { sessionOps } = await import("./hosts/session-ops.ts"); const { allowFileRoot, normalizeSlashes } = await import("./file-access.ts"); const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); +const { RpcCommandError, RpcCommandTimeoutError } = await import("./pi/rpc-process.ts"); const { closeHostLink, getHost, linkTimings } = await import("./hosts/hub.ts"); const { HostOpError } = await import("./hosts/link-protocol.ts"); const { revokeHost } = await import("./hosts/registry.ts"); @@ -201,6 +203,320 @@ test("session and context routes map a missing session to 404, not 413", async ( const ctxRes = await contextRoute.GET(ctxReq, { params: Promise.resolve({ id: "no-such-session" }) }); assert.equal(ctxRes.status, 404); }); + +test("?meta=1 answers the navigation shape and leaves the transcript to /context", async () => { + await withAgentDir(async (dir) => { + writeSessionFile(dir, "2026-01-01_meta.jsonl", { + id: "0a000000-0000-4000-8000-000000000030", + cwd: join(tmpdir(), "tau-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello meta" } }, + { type: "message", id: "a1", parentId: "u1", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: "world" } }, + { type: "model_change", id: "m1", parentId: "a1", timestamp: "2026-01-01T00:00:02.000Z", model: "test/model", role: "default" }, + { type: "thinking_level_change", id: "t1", parentId: "m1", timestamp: "2026-01-01T00:00:03.000Z", thinkingLevel: "high" }, + ]); + + const fullRes = await sessionRoute.GET( + new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000030"), + { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000030" }) }, + ); + const full = await fullRes.json(); + assert.equal(fullRes.status, 200); + assert.ok(Array.isArray(full.context.messages)); + + const metaRes = await sessionRoute.GET( + new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000030?meta=1"), + { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000030" }) }, + ); + const meta = await metaRes.json(); + assert.equal(metaRes.status, 200, JSON.stringify(meta)); + assert.deepEqual(Object.keys(meta).sort(), ["filePath", "info", "leafId", "sessionId", "tree"]); + assert.equal(Object.hasOwn(meta, "context"), false, "the transcript must not ride along"); + assert.deepEqual(meta.tree, full.tree, "the navigation tree is identical"); + assert.equal(meta.leafId, full.leafId); + const { model, thinkingLevel, lastMessageAt, ...metaBase } = meta.info; + assert.deepEqual(metaBase, full.info, "info derives the same count and first message"); + assert.equal(metaBase.messageCount, 2); + assert.equal(metaBase.firstMessage, "hello meta"); + // The meta shape has no context, so the fields its consumers need ride in info. + assert.deepEqual(model, { provider: "test", modelId: "model" }); + assert.deepEqual(model, full.context.model, "same value the full response exposes"); + assert.equal(thinkingLevel, "high"); + assert.equal(thinkingLevel, full.context.thinkingLevel); + assert.equal(lastMessageAt, "2026-01-01T00:00:01.000Z", "same scan the sidebar uses"); + + // Any other value (including meta=0) keeps the historical shape. + const untouched = await sessionRoute.GET( + new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000030?meta=0"), + { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000030" }) }, + ); + assert.ok(Array.isArray((await untouched.json()).context.messages)); + }); +}); + +test("?includeState=1 keeps the historical shape: a live idle wrapper answers running:true", async (t) => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000032"; + writeSessionFile(dir, "2026-01-01_state.jsonl", { + id, + cwd: join(tmpdir(), "tau-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + ]); + const previousSessions = globalThis.__tauSessions; + const wrapper = { + isAlive: () => true, + // Idle: no turn in flight. The historical contract still says running. + isRunning: () => false, + send: async (command) => { + assert.equal(command.type, "get_state"); + return { sessionId: id, isStreaming: false }; + }, + host: getHost("local"), + }; + globalThis.__tauSessions = new Map([[id, wrapper]]); + t.after(() => { globalThis.__tauSessions = previousSessions; }); + + const live = await sessionRoute.GET( + new Request(`http://localhost/api/sessions/${id}?includeState=1`), + { params: Promise.resolve({ id }) }, + ); + assert.equal(live.status, 200); + const agent = (await live.json()).agent; + assert.deepEqual(agent, { running: true, state: { sessionId: id, isStreaming: false } }, + "an existing caller keeps the live-wrapper meaning of running; the idle/running split is opt-in"); + }); +}); + +test("?includeState=alive opts into the idle/running split", async (t) => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000034"; + writeSessionFile(dir, "2026-01-01_alive.jsonl", { + id, + cwd: join(tmpdir(), "tau-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + ]); + const previousSessions = globalThis.__tauSessions; + let running = false; + const wrapper = { + isAlive: () => true, + isRunning: () => running, + send: async () => ({ sessionId: id, isStreaming: running }), + host: getHost("local"), + }; + globalThis.__tauSessions = new Map([[id, wrapper]]); + t.after(() => { globalThis.__tauSessions = previousSessions; }); + + const read = async () => (await sessionRoute.GET( + new Request(`http://localhost/api/sessions/${id}?includeState=alive`), + { params: Promise.resolve({ id }) }, + )).json(); + const idle = (await read()).agent; + assert.deepEqual(idle, { running: false, alive: true, state: { sessionId: id, isStreaming: false } }, + "alive but idle: the child exists, no turn is running"); + running = true; + const busy = (await read()).agent; + assert.deepEqual(busy, { running: true, alive: true, state: { sessionId: id, isStreaming: true } }); + }); +}); + +test("?includeState=1 without a live wrapper keeps the historical running:false", async (t) => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000033"; + writeSessionFile(dir, "2026-01-01_no-wrapper.jsonl", { + id, + cwd: join(tmpdir(), "tau-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + ]); + const previousSessions = globalThis.__tauSessions; + globalThis.__tauSessions = new Map(); + t.after(() => { globalThis.__tauSessions = previousSessions; }); + + const res = await sessionRoute.GET( + new Request(`http://localhost/api/sessions/${id}?includeState=1`), + { params: Promise.resolve({ id }) }, + ); + assert.equal(res.status, 200); + assert.deepEqual((await res.json()).agent, { running: false }, "no extra field for a caller that did not ask for the split"); + + const split = await sessionRoute.GET( + new Request(`http://localhost/api/sessions/${id}?includeState=alive`), + { params: Promise.resolve({ id }) }, + ); + const agent = (await split.json()).agent; + assert.equal(agent.running, false); + assert.equal(agent.alive, false); + assert.equal(Object.hasOwn(agent, "state"), false, "no child, no state"); + }); +}); + +test("?includeState never reports a child that exited after answering as live", async (t) => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000035"; + writeSessionFile(dir, "2026-01-01_exit-after-answer.jsonl", { + id, + cwd: join(tmpdir(), "tau-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + ]); + const previousSessions = globalThis.__tauSessions; + let alive = true; + const wrapper = { + isAlive: () => alive, + isRunning: () => true, + send: async () => { + // The child answered, then exited before the handler resumed. + alive = false; + return { sessionId: id, isStreaming: true }; + }, + host: getHost("local"), + }; + globalThis.__tauSessions = new Map([[id, wrapper]]); + t.after(() => { globalThis.__tauSessions = previousSessions; }); + + const read = async (query) => (await sessionRoute.GET( + new Request(`http://localhost/api/sessions/${id}?${query}`), + { params: Promise.resolve({ id }) }, + )).json(); + const historical = (await read("includeState=1")).agent; + assert.deepEqual(historical, { running: false }, "the stale state is dropped and the live flag is not claimed"); + const split = (await read("includeState=alive")).agent; + assert.deepEqual(split, { running: false, alive: false }, "the child is gone: not alive, not running"); + }); +}); + +test("?meta=1 normalizes a daemon that ignores the option instead of shipping the transcript", async () => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000036"; + writeSessionFile(dir, "2026-01-01_old-daemon.jsonl", { + id, + cwd: join(tmpdir(), "tau-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello legacy" } }, + { type: "message", id: "a1", parentId: "u1", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: "world" } }, + { type: "model_change", id: "m1", parentId: "a1", timestamp: "2026-01-01T00:00:02.000Z", model: "test/model", role: "default" }, + { type: "thinking_level_change", id: "t1", parentId: "m1", timestamp: "2026-01-01T00:00:03.000Z", thinkingLevel: "high" }, + ]); + + const res = await sessionRoute.GET( + new Request(`http://localhost/api/sessions/${id}?meta=1`), + { params: Promise.resolve({ id }) }, + ); + const meta = await res.json(); + assert.equal(res.status, 200, JSON.stringify(meta)); + assert.deepEqual(Object.keys(meta).sort(), ["filePath", "info", "leafId", "sessionId", "tree"], + "the older daemon's transcript is not forwarded under the navigation shape"); + assert.equal(Object.hasOwn(meta, "context"), false); + assert.deepEqual(meta.info.model, { provider: "test", modelId: "model" }, "derived from the full context it did send"); + assert.equal(meta.info.thinkingLevel, "high"); + assert.equal(meta.info.messageCount, 2); + assert.equal(meta.info.firstMessage, "hello legacy"); + assert.equal(meta.leafId, "t1"); + assert.ok(Array.isArray(meta.tree) && meta.tree.length > 0); + }, { + // A daemon built before `?meta=1`: it drops the option and answers the full transcript. + readSession: (args) => sessionOps.readSession(args.id, { ...args.options, meta: false }), + }); +}); + +test("context sends a strong ETag, answers 304, and re-keys it when the body changes", async () => { + await withAgentDir(async (dir) => { + const filePath = writeSessionFile(dir, "2026-01-01_etag.jsonl", { + id: "0a000000-0000-4000-8000-000000000031", + cwd: join(tmpdir(), "tau-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + { type: "message", id: "a1", parentId: "u1", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: "world" } }, + ]); + + const first = await getContext("0a000000-0000-4000-8000-000000000031"); + assert.equal(first.status, 200); + const etag = first.headers.get("etag"); + assert.match(etag, /^"[0-9a-f]{32}"$/, "a quoted strong ETag"); + const firstText = await first.text(); + assert.equal(first.headers.get("content-length"), String(Buffer.byteLength(firstText)), "content-length describes these exact bytes"); + + const cached = await getContext("0a000000-0000-4000-8000-000000000031"); + const cachedEtag = cached.headers.get("etag"); + assert.equal(cachedEtag, etag, "an unchanged body reuses the validator"); + await cached.json(); + + const notModified = await contextRoute.GET( + new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000031/context", { headers: { "If-None-Match": cachedEtag } }), + { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000031" }) }, + ); + assert.equal(notModified.status, 304); + assert.equal(await notModified.text(), ""); + assert.equal(notModified.headers.get("etag"), cachedEtag, "304 repeats the validator"); + + // If-None-Match uses the weak comparison function: a proxy that weakened + // our strong tag must still get its 304. + const weak = await contextRoute.GET( + new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000031/context", { headers: { "If-None-Match": `W/${cachedEtag}` } }), + { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000031" }) }, + ); + assert.equal(weak.status, 304); + assert.equal(await weak.text(), ""); + + // A different body input is a different validator, never a 304. + const branch = await getContext("0a000000-0000-4000-8000-000000000031", "leafId=u1"); + assert.equal(branch.status, 200); + assert.notEqual(branch.headers.get("etag"), cachedEtag); + await branch.json(); + + // Same options, file content changed: the body hash changes with the body. + writeSessionFile(dir, "2026-01-01_etag.jsonl", { + id: "0a000000-0000-4000-8000-000000000031", + cwd: join(tmpdir(), "tau-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + { type: "message", id: "a1", parentId: "u1", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: "world" } }, + { type: "message", id: "a2", parentId: "a1", timestamp: "2026-01-01T00:00:02.000Z", message: { role: "assistant", content: "again" } }, + ]); + assert.ok(existsSync(filePath)); + const changed = await getContext("0a000000-0000-4000-8000-000000000031"); + assert.equal(changed.status, 200); + assert.notEqual(changed.headers.get("etag"), cachedEtag); + assert.deepEqual((await changed.json()).context.entryIds, ["u1", "a1", "a2"]); + }); +}); + +test("paged history answers the same strong ETag and 304s on a repeated read", async () => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-00000000000d"; + writeSessionFile(dir, "2026-01-01_sync-etag.jsonl", { id, cwd: dir, timestamp: "2026-01-01T00:00:00.000Z" }, [ + { type: "message", id: "one", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "one" } }, + { type: "message", id: "two", parentId: "one", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: "two" } }, + ]); + const response = await getContext(id, "sync=1&limit=1&deferThinking"); + assert.equal(response.status, 200); + const etag = response.headers.get("etag"); + assert.match(etag, /^"[0-9a-f]{32}"$/); + await response.json(); + + const repeated = await getContext(id, "sync=1&limit=1&deferThinking"); + assert.equal(repeated.headers.get("etag"), etag, "an unchanged page reuses the validator"); + await repeated.json(); + + const notModified = await contextRoute.GET( + new Request(`http://localhost/api/sessions/${id}/context?sync=1&limit=1&deferThinking`, { headers: { "If-None-Match": etag } }), + { params: Promise.resolve({ id }) }, + ); + assert.equal(notModified.status, 304); + assert.equal(await notModified.text(), ""); + }); +}); + // ============================================================================ // Route-level integration: DELETE re-parenting + import invalidation // (TODO §3 leftover — fork itself is RPC-gated behind the omp binary and is @@ -1647,6 +1963,139 @@ test("sidebar rename cannot fall back to disk while Edit owns the session", asyn }); }); +test("a rename that times out on a live child answers 503 and writes nothing", async () => { + // A timeout leaves the completion unknown: pi may still apply the rename and + // write the file itself, so a slot write here would race its next flush and + // the client would show success for a rename that never stuck. + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000012"; + const filePath = writeSessionFile(dir, "0a000000-0000-4000-8000-000000000012.jsonl", { id, cwd: dir }, [ + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "question" } }, + { type: "message", id: "a1", parentId: "u1", message: { role: "assistant", content: [] } }, + ]); + cacheSessionPath(id, filePath); + const originalFile = readFileSync(filePath); + const commands = []; + const rpc = { + isAlive: () => true, + host: getHost("local"), + isEditingHistory: () => false, + async send(command) { + commands.push(command); + // What the wrapper raises when the child never answers the command. + throw new RpcCommandTimeoutError("set_session_name", 5_000); + }, + }; + const previousSessions = globalThis.__tauSessions; + globalThis.__tauSessions = new Map([[id, rpc]]); + try { + const response = await sessionRoute.PATCH(new Request(`http://localhost/api/sessions/${id}`, { + method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Renamed" }), + }), { params: Promise.resolve({ id }) }); + assert.equal(response.status, 503); + const body = await response.json(); + assert.equal(body.code, "session_slow", "the client's retriable contract, not a generic 500"); + assert.deepEqual(commands.map((command) => command.type), ["set_session_name"]); + assert.deepEqual(readFileSync(filePath), originalFile, "an unknown outcome must not touch the session title slot"); + } finally { + globalThis.__tauSessions = previousSessions; + } + }); +}); + +test("each real rename failure class keeps its intentional HTTP answer and writes nothing", async () => { + // The classes the wrapper actually raises on a live session, and the answer + // each one owes the client. None of them may fall back to the on-disk slot: + // the child still owns the file, so a write would be clobbered by its flush. + const cases = [ + // pi is busy with a turn: retriable, the session keeps running. + { error: () => new WebRpcError("pi is busy and did not answer in time; the session keeps running.", "session_slow"), status: 503, code: "session_slow" }, + // The status query timed out; the session was left running, so it retries. + { error: () => new WebRpcError("The pi status query timed out. The session was left running; retry shortly.", "session_state_timeout"), status: 503, code: "session_state_timeout" }, + // A reload is replacing the child: retriable once it is back. + { error: () => new WebRpcError("This session is restarting — retry in a moment.", "session_restarting"), status: 503, code: "session_restarting" }, + // The child stopped responding and was reset: retriable on a fresh child. + { error: () => new WebRpcError("The pi session stopped responding and was reset.", "session_unresponsive"), status: 503, code: "session_unresponsive" }, + // The host link is down, nothing was sent: the client retries after reconnect. + { error: () => new WebRpcError("Workstation is offline. The run continues there; it reconnects automatically.", "host_offline", "refused"), status: 503, code: "host_offline", hostOffline: true, delivery: "refused" }, + // A history edit owns the session: the client waits, then retries. + { error: () => new WebRpcError("Wait for the history edit to finish", "session_busy"), status: 409, code: "session_busy" }, + // A timeout whose child died meanwhile: the completion is still unknown, so + // the file must not be rewritten just because no live process remains. + { error: () => new RpcCommandTimeoutError("set_session_name", 5_000), status: 503, code: "session_slow", childDied: true }, + ]; + for (const [index, expected] of cases.entries()) { + await withAgentDir(async (dir) => { + const id = `0a000000-0000-4000-8000-00000000004${index}`; + const filePath = writeSessionFile(dir, `${id}.jsonl`, { id, cwd: dir }, [ + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "question" } }, + { type: "message", id: "a1", parentId: "u1", message: { role: "assistant", content: [] } }, + ]); + cacheSessionPath(id, filePath); + const originalFile = readFileSync(filePath); + let alive = true; + const rpc = { + isAlive: () => alive, + host: getHost("local"), + isEditingHistory: () => false, + async send() { + // A timeout can outlive the child it was waiting for. + if (expected.childDied) alive = false; + throw expected.error(); + }, + }; + const previousSessions = globalThis.__tauSessions; + globalThis.__tauSessions = new Map([[id, rpc]]); + try { + const response = await sessionRoute.PATCH(new Request(`http://localhost/api/sessions/${id}`, { + method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Renamed" }), + }), { params: Promise.resolve({ id }) }); + const body = await response.json(); + assert.equal(response.status, expected.status, `${expected.code}: ${JSON.stringify(body)}`); + assert.equal(body.code, expected.code); + if (expected.hostOffline) assert.equal(body.hostOffline, true, "a client identifies the offline host"); + if (expected.delivery) assert.equal(body.delivery, expected.delivery, "nothing left this server"); + assert.deepEqual(readFileSync(filePath), originalFile, `${expected.code} must not rewrite the session title slot`); + } finally { + globalThis.__tauSessions = previousSessions; + } + }); + } +}); + +test("a rename pi rejects outright still falls back to the file", async () => { + // The other half of the contract: `RpcCommandError` means nothing was + // applied, so the on-disk title slot is the correct place to write. + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000013"; + const filePath = writeSessionFile(dir, "0a000000-0000-4000-8000-000000000013.jsonl", { id, cwd: dir }, [ + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "question" } }, + { type: "message", id: "a1", parentId: "u1", message: { role: "assistant", content: [] } }, + ]); + cacheSessionPath(id, filePath); + const rpc = { + isAlive: () => true, + host: getHost("local"), + isEditingHistory: () => false, + async send() { + throw new RpcCommandError("set_session_name", "Unknown command", "unsupported"); + }, + }; + const previousSessions = globalThis.__tauSessions; + globalThis.__tauSessions = new Map([[id, rpc]]); + try { + const response = await sessionRoute.PATCH(new Request(`http://localhost/api/sessions/${id}`, { + method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Renamed" }), + }), { params: Promise.resolve({ id }) }); + assert.equal(response.status, 200); + assert.deepEqual(await response.json(), { ok: true }); + assert.match(readFileSync(filePath, "utf8"), /"type":"session_info".*"name":"Renamed"/); + } finally { + globalThis.__tauSessions = previousSessions; + } + }); +}); + test("automatic title fallback cannot write after Edit takes over", async () => { await withAgentDir(async (dir) => { const id = "0a000000-0000-4000-8000-000000000011"; @@ -1815,3 +2264,54 @@ test("GET /api/sessions?id= returns only the requested session for na assert.deepEqual(dataNone.sessions, []); }); }); + +test("the state poll omits the system prompt only when asked", async (t) => { + const { AgentSessionWrapper } = await import("./rpc-manager.ts"); + const sent = []; + const wrapper = Object.create(AgentSessionWrapper.prototype); + Object.assign(wrapper, { + _alive: true, _sessionId: "sp", _sessionFile: "/sp.jsonl", _sessionName: "sp", + // The real `dispatchCommand`/`buildWebState` path runs: only the child's RPC + // is faked, so the route's flag has to travel all the way into the built state. + proc: { + isAlive: true, + sendCommand: async (command) => { + sent.push(command); + return { + sessionId: "sp", sessionFile: "/sp.jsonl", sessionName: "sp", + isStreaming: false, isCompacting: false, steeringMode: "all", followUpMode: "all", + interruptMode: "immediate", autoCompactionEnabled: false, autoRetryEnabled: false, + messageCount: 0, queuedMessageCount: 0, thinkingLevel: "off", + systemPrompt: ["first line", "second line"], + }; + }, + }, + // `buildWebState` reconciles identity through the owning host, so the fake + // needs the fields that path reads. + host: { id: "local", label: "This machine", status: () => "online", onStatus: () => () => {} }, + promptRunning: false, streaming: false, compacting: false, + bashRunning: false, pendingUiRequests: new Map(), pendingHostTools: new Map(), pendingHostUris: new Map(), + extensionStatuses: new Map(), extensionWidgets: new Map(), + movedFromIds: [], nativeQueuedMessages: { steering: [], followUp: [] }, + promptDispatchPendingCount: 0, historyEditInFlight: false, mcpListWaiter: null, + awaitingAgentStart: false, awaitingAgentStartDeadline: 0, continuationGraceUntil: 0, + streamSequence: 0, responseObserved: false, fastModeEnabled: false, sessionMovePending: false, + invalidateSessionLists() {}, resetStream() {}, clearLiveSnapshots() {}, + // `sent` records the frames at the child boundary (proc.sendCommand), so + // the assertion below is about what pi would receive. + send: async (command) => AgentSessionWrapper.prototype.dispatchCommand.call(wrapper, command), + }); + const route = await import("../app/api/agent/[id]/route.ts"); + const before = globalThis.__tauSessions; + globalThis.__tauSessions = new Map([["sp", wrapper]]); + t.after(() => { globalThis.__tauSessions = before; }); + const full = await route.GET(new Request("http://localhost/api/agent/sp"), { params: Promise.resolve({ id: "sp" }) }); + assert.equal(full.status, 200); + assert.equal((await full.json()).state.systemPrompt, "first line\n\nsecond line", "the default poll carries the prompt"); + const lean = await route.GET(new Request("http://localhost/api/agent/sp?systemPrompt=0"), { params: Promise.resolve({ id: "sp" }) }); + assert.equal(lean.status, 200); + const leanState = (await lean.json()).state; + assert.equal("systemPrompt" in leanState, false, "?systemPrompt=0 drops the field from the built state"); + assert.equal(leanState.sessionId, "sp", "the rest of the state is untouched"); + assert.equal(sent.length, 2, "each poll asked the child once"); +}); From 7141e24f1d703e35ee86f112f22e5ed996b54487 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:45:23 +0000 Subject: [PATCH 16/45] feat(notifications): answer a pending dialog from the notification Port of ompweb-dev/ompweb#414, without omp's formDialog and session-move aliases. --- AGENTS.md | 5 +- app/api/notifications/answer/route.ts | 75 ++++ components/ui/toast.click.test.mjs | 59 +++ docs/plans/2026-10-29-local-daemon.md | 2 +- docs/specs/2026-10-06-notifications-design.md | 72 +++- docs/specs/2026-10-29-local-daemon-design.md | 5 +- hooks/useNotifications.ts | 46 ++- lib/event-stream-hub.test.mjs | 22 ++ lib/event-stream-hub.ts | 10 +- lib/notification-answer-route.test.mjs | 311 ++++++++++++++++ lib/notification-client.ts | 6 +- lib/notification-events.test.mjs | 135 +++++++ lib/notification-events.ts | 261 ++++++++++++- lib/notification-hub.test.mjs | 197 +++++++++- lib/notification-hub.ts | 145 +++++++- lib/notification-store.test.mjs | 18 + lib/notification-store.ts | 13 +- lib/notification-sw.test.mjs | 19 + lib/pi-types.ts | 10 + lib/rpc-manager.test.mjs | 342 +++++++++++++++++- lib/rpc-manager.ts | 211 ++++++++++- public/sw.js | 5 +- server/routes.ts | 2 + 23 files changed, 1925 insertions(+), 46 deletions(-) create mode 100644 app/api/notifications/answer/route.ts create mode 100644 lib/notification-answer-route.test.mjs diff --git a/AGENTS.md b/AGENTS.md index a3cc8f3a..65b68791 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -177,7 +177,7 @@ app/api/ worktrees/route.ts GET/POST/DELETE git worktrees on the owning daemon files/[...path], file-index, git/status, git/diff, cwd/browse, cwd/validate, default-cwd, home, github-repo workspace reads (daemon-owned) media/[hash]/route.ts GET tool-result image by sha256 (?thumb=1 → 480px WebP) - notifications/devices, presence, history push devices, presence reports, notification history + notifications/devices, presence, history, answer push devices, presence reports, notification history, answering a pending dialog stt/route.ts, stt/[jobId]/route.ts, stt/[jobId]/audio/route.ts transcription jobs uploads/route.ts, uploads/[id]/route.ts composer uploads (start/resume, chunks, abort) usage/route.ts, manifest/route.ts usage report; web app manifest @@ -562,7 +562,8 @@ The todo plan (`TodoList`) and subagent roster sit pinned above the input, each ### Notifications (`lib/notification-*.ts`, `public/sw.js`, Settings → Notifications) - Detection runs on the server in `AgentSessionWrapper.handleFrame` (and `handleProcessExit`), so unwatched sessions notify. `createNotificationDetector()` inspects top-level frames only (subagent frames never notify). "Completed" fires on `session_settled`; a failed or aborted last prompt suppresses it. A refused message command reaches only the server that sent it (pi answers it only in that command's `response`). Failures arrive as `prompt_error` and `process_exit`; one failure per run. A crash notifies "Run failed" while a run or its background work is unsettled. - **Presence vs streams.** Tabs report `{clientId, deviceId, visible, sessionId, seq}` to `/api/notifications/presence` (on change, input after idling, every 30 s; expires 60 s after receipt; `visible` = visible and input within 3 min; `sessionId` null while Settings hides the chat; an older `seq` is dropped). Streams are the tab's open `notifications` subscriptions. Prefs PUTs run one at a time. -- **Routing** (`routeNotification`): a visible tab on the session drops the event everywhere; else, with a visible connected tab, `whenActive: "toast"` devices get a toast on their active tabs; else push (subscribed devices) or in-page `showNotification`. The server decides before pushing (iOS revokes permission for silent pushes; `sw.js` always shows what it receives). +- **Routing** (`routeNotification`): a visible tab on the session drops the event everywhere; else, with a visible connected tab, `whenActive: "toast"` devices get a toast on their active tabs; else push (subscribed devices) or in-page `showNotification`. The server decides before pushing (iOS revokes permission for silent pushes; `sw.js` always shows what it receives), so a settled dialog is retracted on the tab streams only (`{type: "notification-dismiss", tag, sessionId, requestId}`), never by a push. +- **Answering from a notification.** An `input` notification carries its blocking dialog (`confirm`, `select`, `input`, `editor`, `ask`) as `dialog` when the whole dialog fits the push budget, never clipped. `POST /api/notifications/answer {sessionId, requestId, response}` answers it through the same `ui_response` path the web dialog uses, checked against the pending dialog first (400 leaves it answerable); it never spawns pi (`sessionGone`, `alreadySettled` are 200s). - Prefs and subscriptions are per device (`localStorage`, mirrored to the SQLite store in `/tau/`, 0600, WAL; it holds the VAPID key and the history). Push text is rendered server-side in the device's locale. - `/sw.js` and `/badge-96.png` are ungated. Clicks survive an expired sign-in: `proxy.ts` sends `/?session=…` to `/login?next=…`, and `LoginForm` accepts only `/?…` targets. - The history (`lib/notification-history.ts`, `/api/notifications/history`) keeps the newest 100 of every type some device enabled, already read when a visible tab shows that session; shown by `NotificationBell` (desktop popover) and the right panel's Notifications tab (mobile). Entries become read when the list closes, on Mark all as read or when opened (`OPEN_SESSION_EVENT`, `tau-open-session`); a reused id (`:`) is unread again. diff --git a/app/api/notifications/answer/route.ts b/app/api/notifications/answer/route.ts new file mode 100644 index 00000000..c31b2dff --- /dev/null +++ b/app/api/notifications/answer/route.ts @@ -0,0 +1,75 @@ +import { commandErrorResponse } from "@/lib/agent-command"; +import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; +import type { ExtensionUiResponse, RpcAskDialogAnswer } from "@/lib/pi-types"; +import { getRpcSession, isAskAnswers } from "@/lib/rpc-manager"; +import { isRecord } from "@/lib/type-guards"; + +/** Answers are text; 64 KB leaves room for a long ask customInput without becoming a payload channel. */ +const MAX_BODY_BYTES = 64 * 1024; +const MAX_ID_CHARS = 256; + +const invalid = (error: string) => Response.json({ error, code: "invalid_answer_request" }, { status: 400 }); + +function isId(value: unknown): value is string { + return typeof value === "string" && value.length > 0 && value.length <= MAX_ID_CHARS; +} + +/** + * Exactly one response variant, and nothing else. Shapes come from + * ExtensionDialog; the ask payload reuses the agent route's validation. + */ +function parseResponse(value: unknown): ExtensionUiResponse | null { + if (!isRecord(value)) return null; + const keys = Object.keys(value); + if (keys.length !== 1) return null; + switch (keys[0]) { + case "value": + return typeof value.value === "string" ? { value: value.value } : null; + case "confirmed": + return typeof value.confirmed === "boolean" ? { confirmed: value.confirmed } : null; + case "cancelled": + return value.cancelled === true ? { cancelled: true } : null; + case "answers": + return isAskAnswers(value.answers) ? { answers: value.answers as RpcAskDialogAnswer[] } : null; + default: + return null; + } +} + +/** + * POST /api/notifications/answer — answer a pending blocking extension dialog + * from a notification action. Looks up the live wrapper (also through moved- + * session aliases) and never spawns pi. Behind the normal auth gate. + * + * 200 {status:"answered"} routed through the shared extension_ui_response command + * 200 {status:"alreadySettled"} the request id is not pending + * 200 {status:"sessionGone"} no live wrapper for the session + * 400 on an invalid body, an answer the pending dialog does not take, or a + * request that is not a dialog at all (`open_url` takes no answer) + * 400 session_restarting / 503 {hostOffline: true} when it cannot be delivered + */ +export async function POST(req: Request) { + let body: unknown; + try { + body = await parseJsonWithinLimit(req, MAX_BODY_BYTES); + } catch (error) { + if (error instanceof RequestBodyTooLargeError) { + return Response.json({ error: "Answer is too large", code: "request_too_large" }, { status: 413 }); + } + return invalid("Invalid JSON request body"); + } + if (!isRecord(body) || !isId(body.sessionId) || !isId(body.requestId)) { + return invalid("sessionId, requestId and response are required"); + } + const response = parseResponse(body.response); + if (!response) return invalid("response must be exactly one of value, confirmed, cancelled or answers"); + + const session = getRpcSession(body.sessionId); + if (!session || !session.isAlive()) return Response.json({ status: "sessionGone" }); + + try { + return Response.json({ status: await session.answerExtensionUiRequest(body.requestId, response) }); + } catch (error) { + return commandErrorResponse(error); + } +} diff --git a/components/ui/toast.click.test.mjs b/components/ui/toast.click.test.mjs index c692dc6b..098f0a9d 100644 --- a/components/ui/toast.click.test.mjs +++ b/components/ui/toast.click.test.mjs @@ -26,6 +26,12 @@ function deliverNotification(message) { assert.ok(id, "useNotifications must hold a notifications channel"); eventWorker.onmessage({ data: { id, type: "message", data: JSON.stringify({ type: "notification", ...message }) } }); } +/** A frame the server's notification channel sends verbatim (lib/event-stream-hub.ts). */ +function deliverFrame(frame) { + const id = [...eventStreams].findLast(([, channel]) => channel.kind === "notifications")?.[0]; + assert.ok(id, "useNotifications must hold a notifications channel"); + eventWorker.onmessage({ data: { id, type: "message", data: JSON.stringify(frame) } }); +} before(() => { globalThis.AbortController = window.AbortController; @@ -124,6 +130,59 @@ test("a session notification toast opens its session from a card click; one with assert.deepEqual(sessions, ["s1"]); }); +test("a retraction frame closes the toast of its own request and leaves a newer dialog of the same tag", async () => { + render(React.createElement(ToastProvider, null)); + renderHook(() => useNotifications({ sessionId: null, locale: "en", onOpenSession: () => {} })); + const cards = () => Array.from(document.querySelectorAll(".toast-card")); + const titles = () => cards().map((card) => card.querySelector(".display-serif")?.textContent); + + // The first dialog of this session, then the retraction that settles it. + act(() => { + deliverNotification({ kind: "toast", event: { type: "input", sessionId: "s1", sessionName: "Deploy", detail: "Ship it?", requestId: "req-1" } }); + }); + assert.deepEqual(titles(), ["Deploy"]); + act(() => { + deliverFrame({ type: "notification-dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-1" }); + }); + assert.deepEqual(titles(), [], "the settled question's card is gone"); + + // A replacement dialog of the same tag: a late retraction of the old request + // must not close it, and the matching one does. + act(() => { + deliverNotification({ kind: "toast", event: { type: "input", sessionId: "s1", sessionName: "Deploy", detail: "Or now?", requestId: "req-2" } }); + }); + act(() => { + deliverFrame({ type: "notification-dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-1" }); + }); + assert.deepEqual(titles(), ["Deploy"], "a stale retraction leaves the next dialog alone"); + act(() => { + deliverFrame({ type: "notification-dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-2" }); + }); + assert.deepEqual(titles(), []); +}); + +test("a retraction refreshes the history mirror, so a settled entry stops showing as unread", async () => { + const requests = []; + const previousFetch = globalThis.fetch; + globalThis.fetch = async (url, init = {}) => { + requests.push([init.method ?? "GET", String(url)]); + return { ok: true, json: async () => ({ entries: [] }) }; + }; + try { + renderHook(() => useNotifications({ sessionId: null, locale: "en", onOpenSession: () => {} })); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + requests.length = 0; + await act(async () => { + deliverFrame({ type: "notification-dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-1" }); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + assert.deepEqual(requests, [["GET", "/api/notifications/history"]], "the tab re-reads what the server marked read"); + } finally { + globalThis.fetch = previousFetch; + act(() => notificationHistory.clear()); + } +}); + test("a notification the OS showed is listed in history", async () => { const created = []; // Bare `Notification` in the code under test resolves to the global, not window. diff --git a/docs/plans/2026-10-29-local-daemon.md b/docs/plans/2026-10-29-local-daemon.md index a6097b79..a89029f9 100644 --- a/docs/plans/2026-10-29-local-daemon.md +++ b/docs/plans/2026-10-29-local-daemon.md @@ -53,7 +53,7 @@ } // hello: channels: { ch: string; sessionId: string | null; pending: string[] | null }[] ``` - Opened by `host_tool_call` and `extension_ui_request` with a method in `BLOCKING_UI_METHODS` (import from `lib/notification-events.ts` if it has no next/@ imports, else move the constant to a shared module). Closed by `host_tool_result`/`extension_ui_response` with the same id on stdin, or `host_tool_cancel` (`targetId`) / an `extension_ui_request` cancel frame from omp. A chunked frame's raw `rpc_chunk` lines are kept together. + Opened by `host_tool_call` and `extension_ui_request` with a blocking dialog method (`select`, `confirm`, `input`, `editor`, `askDialog`, `formDialog` or `approve`). Closed by `host_tool_result`/`extension_ui_response` with the same id on stdin, or `host_tool_cancel` (`targetId`) / an `extension_ui_request` cancel frame from omp. A chunked frame's raw `rpc_chunk` lines are kept together. - [ ] **Step 1: Failing tests** — `pending-requests.test.mjs`: an `ask` request then its `extension_ui_response` → `lines()` is `[]`; an open `host_tool_call` → `lines()` holds its raw line; a request split into three `rpc_chunk` lines → `lines()` holds all three in order; `host_tool_cancel` with `targetId` closes the call; past `limitBytes` → `null`; a non-blocking `notify` UI request is not kept. `daemon.test.mjs`: after a link drop the next `hello` carries the open request's line for its channel. - [ ] **Step 2: Run** `node --experimental-strip-types --test lib/hosts/pending-requests.test.mjs lib/hosts/daemon.test.mjs` → FAIL. - [ ] **Step 3: Implement**; bump `LINK_PROTOCOL_VERSION` to 3 and update `decodeUp` for the new hello field. diff --git a/docs/specs/2026-10-06-notifications-design.md b/docs/specs/2026-10-06-notifications-design.md index 4ffee932..8d19cdb9 100644 --- a/docs/specs/2026-10-06-notifications-design.md +++ b/docs/specs/2026-10-06-notifications-design.md @@ -31,8 +31,14 @@ Rules: - Local slash commands (`prompt_result` with `agentInvoked: false`), aborted runs, `auto_retry_start` and `auto_retry_end {success: true}` never notify. - Every notification has tag `:`, so a repeat replaces the - previous one instead of stacking. Notifications are not retracted when they - stop applying. + previous one instead of stacking. An `input` notification is retracted when + the dialog behind it settles (answered, cancelled, expired, or its pi child + went away): every reachable tab gets a `notification-dismiss` frame naming + the tag and request id. No push carries the retraction — a push that + displays nothing is a silent push, which browsers punish — so a device that + is not reachable keeps the stale card until the next `input` push replaces + it by tag. The request id rides on every delivery, so a retraction closes + only its own dialog and never the next one of the same tag. ## Architecture @@ -148,14 +154,74 @@ push: iOS Safari revokes push permission for pushes that show nothing. | Route | Method | Purpose | |---|---|---| -| `/api/agent/running/events?clientId=` | GET | existing SSE stream, now also `{type: "notification", kind, event}` | +| `/api/agent/running/events?clientId=` | GET | existing SSE stream, now also `{type: "notification", kind, event}` and `{type: "notification-dismiss", tag, sessionId, requestId}` | | `/api/notifications/presence` | POST | presence report | | `/api/notifications/devices?deviceId=` | GET | VAPID public key, whether this device has a subscription | | `/api/notifications/devices` | PUT | `{deviceId, prefs, subscription?}`; an omitted subscription keeps the stored one | | `/api/notifications/test` | POST | `{deviceId}`: a test push; 502 with the push service's answer when it fails | +| `/api/notifications/answer` | POST | `{sessionId, requestId, response}`: answer a pending blocking dialog from a notification | All routes sit behind the existing password gate and origin check. +### Answering from a notification + +A blocking dialog (`confirm`, `select`, `input`, `editor`, `ask`) is carried in +the `input` notification's `dialog` field, in the SSE frame, the history entry +and the push body, so a client can offer its answer without an open chat tab. +`POST /api/notifications/answer` takes `{sessionId, requestId, response}` with +exactly one response variant: `{confirmed}`, `{value}`, `{cancelled: true}`, or +`{answers}` for an `ask`. The body is capped at 64 KiB and read with +`parseJsonWithinLimit`. + +- The route looks the session up in the live registry and never spawns pi: an unknown or exited session + answers `200 {status: "sessionGone"}`, and a request id that is not pending + answers `200 {status: "alreadySettled"}`. Neither is an error. +- The answer is checked against the pending dialog first, so a payload the + dialog cannot take is a 400 and leaves the question answerable: a `select` + takes one of its own labels, a `confirm` a confirmation, an `input`/`editor` + a value, and an `ask` its answers. A request whose method is not a dialog + takes no answer at all: `open_url` is fire-and-forget (nothing waits for + an answer), so any response to it is a 400 `invalid_dialog_answer` + before anything is sent. An `ask` payload is validated against the pending + questions: one answer per + question in request order, each answer naming its own question id, only + labels that question offers, no label twice, and a single-select question + takes either one label or free text — never both. `customInput` is trimmed + before it counts. A cancel is always accepted. +- A dialog is never clipped to fit the notification. If any part would have to + be shortened (a title over 160 characters, a confirm message over 480, an ask + question over 240, an option label over 160, a placeholder over 80, or a + dialog over its 1,800-byte budget), the notification carries no `dialog` at + all and only opens the session. The same request is then refused with 400 + `invalid_dialog_answer` by the answer route: nothing is answerable that the + notification did not advertise in full. The complete push body stays under + the 4 KB Web Push limit; its `input` body is the dialog's own text verbatim + (a confirm's title and message, an ask's questions, or the dialog title), so a + push never shows a clipped prefix next to live buttons. A dialog whose + decision text the contract cannot represent is omitted too: a server-owned + confirm (`serverPayload` renders from/to/delivery/host/cwd), an option with a + `description`/`preview`, an ask question with a `header`, or a `secret` + `input`. A frame without an id never becomes the request id `"undefined"`. +- An accepted answer goes through the same `extension_ui_response` command the + desktop dialog sends, so it resolves a server-owned confirmation and applies + the offline/restarting gate: a host that is offline answers 503 + `{hostOffline: true}` and a restarting session 400 `session_restarting`, + never `answered`. The dialog is settled only after the answer was admitted. +- Settling a dialog retracts its notification on every reachable tab: + `{type: "notification-dismiss", tag, sessionId, requestId}`, and the history + entry of exactly that request becomes read. A newer dialog of the same tag + keeps its own unread entry. A push retry that wakes after the settlement + delivers nothing. No push carries the retraction: a push that displays + nothing is a silent push (iOS revokes the permission, Chromium and Firefox + substitute a generic card and mute the origin), so a device that is not + reachable keeps the stale card until the next `input` push replaces it by + tag or the app syncs. +- A resync that dropped a dialog (a linked host discarding buffered output) + retracts it too, but as a *forgotten* settlement: the retraction is + temporary, so if the host replays the same request id the question is + announced and pushed again instead of being suppressed. A permanent + settlement of the same request is never lifted by that. + ## Settings: Notifications tab A `SettingsTabs` category `notifications` (icon `Bell`). Contents: diff --git a/docs/specs/2026-10-29-local-daemon-design.md b/docs/specs/2026-10-29-local-daemon-design.md index 99b0ff1a..25d0dbbf 100644 --- a/docs/specs/2026-10-29-local-daemon-design.md +++ b/docs/specs/2026-10-29-local-daemon-design.md @@ -93,8 +93,9 @@ on the web server: missed would block the run forever. The daemon already sees every line, so it keeps, per channel, the raw lines of each blocking request still open: -- opened by a `host_tool_call` or an `extension_ui_request` whose method is in - `BLOCKING_UI_METHODS` (decoded with `RpcFrameDecoder`, so chunked frames are +- opened by a `host_tool_call` or an `extension_ui_request` whose method is a + blocking dialog (`select`, `confirm`, `input`, `editor`, `askDialog`, + `formDialog` or `approve`; decoded with `RpcFrameDecoder`, so chunked frames are kept whole); - closed by the matching `host_tool_result` / `extension_ui_response` written to stdin, or a `host_tool_cancel` / UI cancel from omp. diff --git a/hooks/useNotifications.ts b/hooks/useNotifications.ts index 29c9382f..9ce197f1 100644 --- a/hooks/useNotifications.ts +++ b/hooks/useNotifications.ts @@ -115,9 +115,13 @@ export function useNotifications({ sessionId, locale, onOpenSession }: { session // OPEN_SESSION_EVENT, so listeners such as the bell popover see each one. useEffect(() => { const openSession = (sessionId: string) => window.dispatchEvent(new CustomEvent(OPEN_SESSION_EVENT, { detail: sessionId })); - const showToast = (rendered: RenderedNotification, type: NotificationEvent["type"]) => { + // Request id of the toast each tag currently shows. A retraction names the + // request it closes, so a toast replaced by the next dialog of that tag stays. + const toastRequests = new Map(); + const showToast = (rendered: RenderedNotification, type: NotificationEvent["type"], requestId?: string) => { const show = type === "error" ? toast.error : toast.info; const target = rendered.sessionId; + toastRequests.set(rendered.tag, requestId); // The whole card opens the session (click, tap, or Enter on the focused card); following it is reading it. show(rendered.title, rendered.body, { id: rendered.tag, @@ -132,14 +136,36 @@ export function useNotifications({ sessionId, locale, onOpenSession }: { session notificationHistory.add(event); const rendered = renderNotification(event, translate); if (kind === "toast") { - showToast(rendered, event.type); + showToast(rendered, event.type, event.requestId); return; } // Permission withdrawn or never granted: the toast is the only way left to tell the user. - void showSystemNotification(rendered).then((shown) => { - if (!shown) showToast(rendered, event.type); + void showSystemNotification(rendered, event.requestId).then((shown) => { + if (!shown) showToast(rendered, event.type, event.requestId); }); }; + // The dialog was answered, cancelled or expired elsewhere. Close only the + // notification of that request id: a buffered push can arrive after the + // next dialog for the same tag is already shown, and that one stays. + const dismiss = async (tag: string, requestId: string) => { + if (toastRequests.get(tag) === requestId) { + toastRequests.delete(tag); + toast.close(tag); + } + try { + const registration = "serviceWorker" in navigator ? await navigator.serviceWorker.getRegistration() : undefined; + const shown = await registration?.getNotifications({ tag }) ?? []; + for (const notification of shown) { + const data: unknown = notification.data; + if (isRecord(data) && data.requestId === requestId) notification.close(); + } + } catch { + // A closing registration must not break the toast path. + } + // The server marked the entry read when the dialog settled; an open tab + // would otherwise keep showing it unread until a later refresh. + void notificationHistory.load(); + }; const onOpen = (raw: Event) => { if (!(raw instanceof CustomEvent)) return; if (typeof raw.detail === "string" && raw.detail) openRef.current(raw.detail); @@ -158,12 +184,20 @@ export function useNotifications({ sessionId, locale, onOpenSession }: { session if (data.type === "tau-notification-shown") void notificationHistory.load(); }; // This tab's own channel: the server delivers here while it is open, on any - // view (the chat, Settings, ...), and counts the tab as reachable. + // view (the chat, Settings, ...), and counts the tab as reachable. A settled + // input dialog arrives as a dismiss frame and retracts only its own request. const stream = openEventStream({ kind: "notifications", clientId: notificationClientId }); stream.onmessage = ({ data }) => { try { const frame: unknown = JSON.parse(data); - if (!isRecord(frame) || frame.type !== "notification" || (frame.kind !== "toast" && frame.kind !== "os") || !isRecord(frame.event)) return; + if (!isRecord(frame)) return; + if (frame.type === "notification-dismiss") { + if (typeof frame.tag === "string" && frame.tag && typeof frame.requestId === "string" && frame.requestId) { + void dismiss(frame.tag, frame.requestId); + } + return; + } + if (frame.type !== "notification" || (frame.kind !== "toast" && frame.kind !== "os") || !isRecord(frame.event)) return; // Built by our own server's notification hub from a NotificationEvent. const event = frame.event as unknown as NotificationEvent; deliver(frame.kind, event); diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index 6115d93a..e2da48ac 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -12,15 +12,20 @@ const previousAgentDir = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = isolatedAgentDir; after(() => { closeOutboxStore(); + // publishNotificationDismiss opens the notification store; Windows cannot + // delete its directory while the database is open. + closeNotificationStore(); if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; else process.env.PI_CODING_AGENT_DIR = previousAgentDir; fs.rmSync(isolatedAgentDir, { recursive: true, force: true }); }); const { EventStreamConnection, getEventStreamConnection, parseHeartbeatSeconds } = await import("./event-stream-hub.ts"); +const hub = await import("./notification-hub.ts"); const route = await import("../app/api/events/route.ts"); const { AgentSessionWrapper } = await import("./rpc-manager.ts"); const { closeOutboxStore } = await import("./message-outbox.ts"); +const { closeNotificationStore } = await import("./notification-store.ts"); const idleSnapshot = () => ({ cursor: { streamId: "test-stream", sequence: 0 } }); const decoder = new TextDecoder(); @@ -195,6 +200,23 @@ test("a notifications subscription keeps its tab reachable until it ends; malfor assert.equal(streams().has("tab-notify-02"), false, "a dropped socket must detach its tabs"); }); +test("a published retraction reaches the tab as a notification-dismiss frame naming its request", async () => { + const { connection, reader } = await connect(); + try { + assert.deepEqual(await connection.subscribe("s1", { kind: "notifications", clientId: "tab-notify-03" }), { ok: true }); + assert.deepEqual(await readFrame(reader), { event: "mux", data: { type: "open", sub: "s1" } }); + // The hub's own publish path, not a hand-built sender: this is the frame a + // real settlement produces. + hub.publishNotificationDismiss("s-done", "req-42"); + assert.deepEqual(await readFrame(reader), { + event: "s1", + data: { type: "notification-dismiss", tag: "s-done:input", sessionId: "s-done", requestId: "req-42" }, + }); + } finally { + await reader.cancel(); + } +}); + test("host-tools subscription delivers cross-session calls and releases its listener", async () => { globalThis.__tauHostToolListeners ??= new Set(); const listeners = globalThis.__tauHostToolListeners; diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 63ce4315..ffacb7d7 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -404,7 +404,15 @@ function openRunningChannel(handle: SubscriptionHandle): SubscribeResult { // as reachable for toasts and in-page system notifications while this is open. function openNotificationsChannel(clientId: string, handle: SubscriptionHandle): SubscribeResult { handle.open(); - handle.setDetach(attachNotificationClient(clientId, (message) => handle.send({ type: "notification", ...message }))); + handle.setDetach(attachNotificationClient(clientId, (message) => { + // A retraction is its own frame type: the client's notification branch + // accepts only the toast/os kinds, so a wrapped dismiss would be dropped. + if (message.kind === "dismiss") { + handle.send({ type: "notification-dismiss", tag: message.tag, sessionId: message.sessionId, requestId: message.requestId }); + return; + } + handle.send({ type: "notification", ...message }); + })); return SUBSCRIBED; } diff --git a/lib/notification-answer-route.test.mjs b/lib/notification-answer-route.test.mjs new file mode 100644 index 00000000..ba0330cf --- /dev/null +++ b/lib/notification-answer-route.test.mjs @@ -0,0 +1,311 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test, { after } from "node:test"; + +// Real POST /api/notifications/answer with fake live wrappers: no pi spawn, +// no notification store writes beyond the throwaway agent dir. +const agentDir = mkdtempSync(join(tmpdir(), "tau-answer-route-")); +const previousAgentDir = process.env.PI_CODING_AGENT_DIR; +process.env.PI_CODING_AGENT_DIR = agentDir; +const { closeNotificationStore } = await import("./notification-store.ts"); +after(() => { + globalThis.__tauSessions = undefined; + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + // The live wrapper publishes notifications, which opens the store in this dir; + // Windows cannot delete a directory while that database is open. + closeNotificationStore(); + rmSync(agentDir, { recursive: true, force: true }); +}); + +const route = await import("../app/api/notifications/answer/route.ts"); +const { WebRpcError } = await import("./rpc-manager.ts"); +const hub = await import("./notification-hub.ts"); +const notificationStore = await import("./notification-store.ts"); +const { DEFAULT_NOTIFICATION_PREFS } = await import("./notification-events.ts"); + +const URL_ = "http://localhost/api/notifications/answer"; +const post = (body, headers = {}) => route.POST(new Request(URL_, { + method: "POST", + headers: { "content-type": "application/json", ...headers }, + body: typeof body === "string" ? body : JSON.stringify(body), +})); + +function fakeSession({ alive = true, result = "answered", error = null } = {}) { + const calls = []; + return { + calls, + session: { + isAlive: () => alive, + answerExtensionUiRequest(id, response) { + calls.push([id, response]); + if (error) throw error; + return result; + }, + }, + }; +} + +test("a valid answer reaches the live wrapper exactly once", async () => { + const { calls, session } = fakeSession(); + globalThis.__tauSessions = new Map([["s1", session]]); + const response = await post({ sessionId: "s1", requestId: "req-1", response: { confirmed: true } }); + assert.equal(response.status, 200); + assert.deepEqual(await response.json(), { status: "answered" }); + assert.deepEqual(calls, [["req-1", { confirmed: true }]]); +}); + +test("all four response variants are accepted", async () => { + const { calls, session } = fakeSession(); + globalThis.__tauSessions = new Map([["s1", session]]); + for (const answer of [{ value: "main" }, { confirmed: false }, { cancelled: true }, { answers: [{ id: "q", selectedOptions: ["A"], customInput: "other" }] }]) { + assert.equal((await post({ sessionId: "s1", requestId: "req", response: answer })).status, 200); + } + assert.deepEqual(calls.map(([, answer]) => answer), [ + { value: "main" }, { confirmed: false }, { cancelled: true }, { answers: [{ id: "q", selectedOptions: ["A"], customInput: "other" }] }, + ]); +}); + +test("alreadySettled and sessionGone are reported, not treated as errors", async () => { + globalThis.__tauSessions = new Map([["s1", fakeSession({ result: "alreadySettled" }).session]]); + const settled = await post({ sessionId: "s1", requestId: "req", response: { value: "x" } }); + assert.deepEqual(await settled.json(), { status: "alreadySettled" }); + + const dead = await post({ sessionId: "s2", requestId: "req", response: { value: "x" } }); + assert.deepEqual(await dead.json(), { status: "sessionGone" }); + + globalThis.__tauSessions = new Map([["s3", fakeSession({ alive: false }).session]]); + const exited = await post({ sessionId: "s3", requestId: "req", response: { value: "x" } }); + assert.deepEqual(await exited.json(), { status: "sessionGone" }); +}); + +test("a moved conversation answers through its old id", async () => { + // registerSession keeps the old ids routable after pi moves the file, so + // one registry entry under both keys is what the route sees. + const { calls, session } = fakeSession(); + globalThis.__tauSessions = new Map([["s1", session], ["s0", session]]); + const response = await post({ sessionId: "s0", requestId: "req-1", response: { value: "yes" } }); + assert.deepEqual(await response.json(), { status: "answered" }); + assert.deepEqual(calls, [["req-1", { value: "yes" }]]); +}); + +test("malformed requests are rejected before touching any session", async () => { + const { calls, session } = fakeSession(); + globalThis.__tauSessions = new Map([["s1", session]]); + const cases = [ + null, + [], + "text", + { sessionId: "s1", requestId: "req" }, + { sessionId: "", requestId: "req", response: { value: "x" } }, + { sessionId: "s1", requestId: "r".repeat(257), response: { value: "x" } }, + { sessionId: "s1", requestId: "req", response: {} }, + { sessionId: "s1", requestId: "req", response: { value: 1 } }, + { sessionId: "s1", requestId: "req", response: { cancelled: false } }, + { sessionId: "s1", requestId: "req", response: { value: "x", confirmed: true } }, + { sessionId: "s1", requestId: "req", response: { answers: "yes" } }, + { sessionId: "s1", requestId: "req", response: { answers: [{ id: 1, selectedOptions: [] }] } }, + ]; + for (const body of cases) { + const response = await post(body); + assert.equal(response.status, 400, JSON.stringify(body)); + assert.equal((await response.json()).code, "invalid_answer_request"); + } + assert.deepEqual(calls, []); +}); + +test("invalid JSON and an oversized body get distinct statuses", async () => { + assert.equal((await post("{not json")).status, 400); + const huge = JSON.stringify({ sessionId: "s1", requestId: "req", response: { value: "x".repeat(70_000) } }); + const response = await post(huge, { "content-length": String(Buffer.byteLength(huge)) }); + assert.equal(response.status, 413); + assert.equal((await response.json()).code, "request_too_large"); +}); + +test("a wrapper validation error becomes a 400 with its own code", async () => { + const { session } = fakeSession({ error: new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers") }); + globalThis.__tauSessions = new Map([["s1", session]]); + const response = await post({ sessionId: "s1", requestId: "req", response: { value: "x" } }); + assert.equal(response.status, 400); + assert.deepEqual(await response.json(), { error: "Invalid ask dialog answers", code: "invalid_ask_answers" }); +}); + +test("an answer that cannot be delivered is not reported as answered", async () => { + // The wrapper's send() applies the offline/restarting gate; the route must + // surface it instead of claiming the question was answered. + for (const [error, status, body] of [ + [new WebRpcError("Laptop is offline. The run continues there; it reconnects automatically.", "host_offline", "refused"), 503, { hostOffline: true, delivery: "refused" }], + [new WebRpcError("This session is restarting — retry in a moment.", "session_restarting"), 400, { code: "session_restarting" }], + ]) { + const { session } = fakeSession({ error }); + globalThis.__tauSessions = new Map([["s1", session]]); + const response = await post({ sessionId: "s1", requestId: "req", response: { confirmed: true } }); + assert.equal(response.status, status, error.code); + const payload = await response.json(); + assert.equal(payload.status, undefined, "a failed delivery is never answered"); + for (const [key, value] of Object.entries(body)) assert.equal(payload[key], value, `${error.code} ${key}`); + } +}); + +// The real wrapper and the real route: this is the boundary the ask +// validation has to hold at, not a fake session that only echoes. +const { AgentSessionWrapper } = await import("./rpc-manager.ts"); +const { localHost } = await import("./hosts/local-host.ts"); + +/** A live wrapper whose pi frames the test drives; `sent` collects what reached the child. */ +function liveAskSession(t) { + // Earlier tests left fake sessions in the registry; a running-change broadcast + // walks it, and those fakes are not wrappers. + globalThis.__tauSessions = new Map(); + let feed; + const sent = []; + const wrapper = new AgentSessionWrapper({ + isAlive: true, + waitReady: async () => ({ type: "ready", protocolVersion: 2 }), + negotiateProtocol: async () => {}, + onFrame(handler) { feed = handler; return () => {}; }, + sendCommand: async (command) => command.type === "get_state" + ? { sessionId: "ask-live", sessionFile: "/tmp/ask-live.jsonl", isStreaming: false, isCompacting: false } + : {}, + sendFrame(frame) { sent.push(frame); }, + dispose: async () => {}, + }, process.cwd(), null, "", undefined, localHost); + wrapper.start(); + t.after(() => wrapper.destroyAndWait()); + return { wrapper, sent, emit: (frame) => feed(frame) }; +} + +test("the real wrapper refuses ask answers pi would reject, and keeps the question answerable", async (t) => { + const { wrapper, sent, emit } = liveAskSession(t); + await wrapper.waitUntilReady(); + globalThis.__tauSessions = new Map([["ask-live", wrapper]]); + const ask = () => emit({ + type: "ui_request", id: 51, method: "askDialog", + args: [[ + { id: "q1", question: "Pick one", options: [{ label: "A" }, { label: "B" }] }, + { id: "q2", question: "Pick many", multi: true, options: [{ label: "X" }, { label: "Y" }] }, + ]], + }); + ask(); + const rejected = [ + [[], "answers:[] for a nonempty ask"], + [[{ id: "q1", selectedOptions: ["A"] }], "one answer short"], + [[{ id: "q1", selectedOptions: ["A"] }, { id: "q2", selectedOptions: [] }, { id: "q2", selectedOptions: [] }], "one answer too many"], + [[{ id: "unknown", selectedOptions: ["A"] }, { id: "q2", selectedOptions: [] }], "unknown question id"], + [[{ id: "q1", selectedOptions: ["nope"] }, { id: "q2", selectedOptions: [] }], "unknown option label"], + [[{ id: "q1", selectedOptions: ["A", "B"] }, { id: "q2", selectedOptions: [] }], "two labels on a single-select question"], + ]; + for (const [answers, why] of rejected) { + const response = await post({ sessionId: "ask-live", requestId: "51", response: { answers } }); + assert.equal(response.status, 400, why); + assert.equal((await response.json()).code, "invalid_ask_answers", why); + assert.deepEqual(sent, [], `${why}: nothing reaches pi`); + // Still answerable: the next request for it is not alreadySettled. + const replay = []; + wrapper.onEvent((event) => replay.push(event)); + assert.equal(replay[0]?.id, 51, `${why}: the dialog stays pending for reconnects`); + } + + // The legitimate answers the same dialog accepts. + for (const answers of [ + [{ id: "q1", selectedOptions: ["A"] }, { id: "q2", selectedOptions: ["X", "Y"] }], + [{ id: "q1", selectedOptions: [], customInput: "typed" }, { id: "q2", selectedOptions: [] }], + ]) { + ask(); + const response = await post({ sessionId: "ask-live", requestId: "51", response: { answers } }); + assert.deepEqual(await response.json(), { status: "answered" }, JSON.stringify(answers)); + const forwarded = sent.at(-1); + assert.equal(forwarded.type, "ui_response"); + assert.equal(forwarded.id, 51); + assert.equal(forwarded.value.kind, "submit"); + assert.deepEqual(forwarded.value.results.map(({ id, selectedOptions, customInput }) => ({ id, selectedOptions, ...(customInput === undefined ? {} : { customInput }) })), answers); + } + + // A cancel is always accepted, and a second answer is already settled. + ask(); + assert.deepEqual(await (await post({ sessionId: "ask-live", requestId: "51", response: { cancelled: true } })).json(), { status: "answered" }); + assert.deepEqual(await (await post({ sessionId: "ask-live", requestId: "51", response: { cancelled: true } })).json(), { status: "alreadySettled" }); +}); + +test("a dialog the notification omitted is not answerable from a notification", async (t) => { + const { wrapper, sent, emit } = liveAskSession(t); + await wrapper.waitUntilReady(); + globalThis.__tauSessions = new Map([["ask-live", wrapper]]); + // The whole message must fit: clipping it would display only the harmless + // prefix of an approval and leave it answerable. + emit({ + type: "ui_request", id: 77, method: "confirm", + args: ["Allow tool: bash", `${"A".repeat(480)} --delete-everything`], + }); + + const response = await post({ sessionId: "ask-live", requestId: "77", response: { confirmed: true } }); + assert.equal(response.status, 400); + assert.deepEqual(await response.json(), { error: "This dialog cannot be answered from a notification", code: "invalid_dialog_answer" }); + assert.deepEqual(sent, [], "no ui_response reaches pi for a dialog the notification never advertised"); + + // The dialog is only unanswerable from the notification: the open session + // still gets it replayed and can answer there. + const replay = []; + wrapper.onEvent((event) => replay.push(event)); + assert.equal(replay[0]?.id, 77, "the dialog stays pending for the chat UI"); +}); + +test("a server-owned confirm carries no partial approval into the notification", async (t) => { + const { wrapper, sent } = liveAskSession(t); + await wrapper.waitUntilReady(); + globalThis.__tauSessions = new Map([["ask-live", wrapper]]); + notificationStore.saveDevice("srv-confirm-device", { ...DEFAULT_NOTIFICATION_PREFS, enabled: true }); + const events = []; + const detach = hub.attachNotificationClient("srv-confirm-tab", (message) => { + if (message.kind === "toast" || message.kind === "os") events.push(message.event); + }); + t.after(detach); + hub.reportPresence({ clientId: "srv-confirm-tab", deviceId: "srv-confirm-device", visible: false, sessionId: null, seq: 1 }); + + const controller = new AbortController(); + // From/to/delivery are rendered by the web dialog only; a notification that + // carried just the message would still approve a decision the user cannot see + // in full. confirmFromServer is the real path that raises this dialog. + const pending = wrapper.confirmFromServer("Send a message to session prod?", { + kind: "send_to_session", + from: { id: "ask-live", name: "Source", hostId: "local", hostLabel: "This machine" }, + to: null, + delivery: "steer", + message: "rm -rf /srv/app", + }, controller.signal); + assert.equal(events.length, 1, "the confirm is published"); + const published = events[0]; + assert.ok(published.requestId?.startsWith("tau:"), published.requestId); + assert.equal(published.dialog, undefined, "a partial approval is never advertised"); + + const response = await post({ sessionId: "ask-live", requestId: published.requestId, response: { confirmed: true } }); + assert.equal(response.status, 400); + assert.deepEqual(await response.json(), { error: "This dialog cannot be answered from a notification", code: "invalid_dialog_answer" }); + assert.deepEqual(sent, [], "nothing reaches pi"); + const replay = []; + wrapper.onEvent((event) => replay.push(event)); + assert.equal(replay[0]?.id, published.requestId, "the web dialog stays pending for the full context"); + + controller.abort(); + assert.equal(await pending, false); +}); + +test("an ask question without options answers with an empty options list", async (t) => { + const { wrapper, sent, emit } = liveAskSession(t); + await wrapper.waitUntilReady(); + globalThis.__tauSessions = new Map([["ask-live", wrapper]]); + // A free-text question has no `options` key: the published dialog must still + // answer instead of throwing on the missing array. + emit({ type: "ui_request", id: 52, method: "askDialog", args: [[{ id: "q", question: "Free text?" }]] }); + + const response = await post({ + sessionId: "ask-live", requestId: "52", + response: { answers: [{ id: "q", selectedOptions: [], customInput: "typed" }] }, + }); + assert.deepEqual(await response.json(), { status: "answered" }); + const forwarded = sent.at(-1); + assert.equal(forwarded.type, "ui_response"); + assert.deepEqual(forwarded.value.results[0].options, []); +}); diff --git a/lib/notification-client.ts b/lib/notification-client.ts index e93e7ca6..ceceade0 100644 --- a/lib/notification-client.ts +++ b/lib/notification-client.ts @@ -199,14 +199,16 @@ export const OPEN_SESSION_EVENT = "tau-open-session"; * Show a system notification the same way the service worker shows pushes. * Returns false when the browser does not allow it, so the caller can fall back. */ -export async function showSystemNotification(notification: RenderedNotification): Promise { +export async function showSystemNotification(notification: RenderedNotification, requestId?: string): Promise { if (!("Notification" in window) || Notification.permission !== "granted") return false; const options: NotificationOptions = { body: notification.body, icon: "/icon-192.png", badge: "/badge-96.png", tag: notification.tag, - data: { url: notification.url, sessionId: notification.sessionId }, + // A dismiss closes only the notification of the same request id, so a + // shown dialog must carry it too. + data: { url: notification.url, sessionId: notification.sessionId, ...(requestId ? { requestId } : {}) }, }; try { const registration = "serviceWorker" in navigator ? await navigator.serviceWorker.getRegistration() : undefined; diff --git a/lib/notification-events.test.mjs b/lib/notification-events.test.mjs index 7d573b60..edbe9ed1 100644 --- a/lib/notification-events.test.mjs +++ b/lib/notification-events.test.mjs @@ -80,6 +80,114 @@ test("untrusted prefs fall back to defaults field by field", () => { }); }); +test("a blocking dialog carries its request id and answerable payload", () => { + const [event] = run([{ + type: "ui_request", + id: "req-1", + method: "confirm", + args: ["Allow tool: bash", "Run rm -rf build?"], + }]); + assert.equal(event.requestId, "req-1"); + assert.deepEqual(event.dialog, { requestId: "req-1", method: "confirm", title: "Allow tool: bash", message: "Run rm -rf build?" }); +}); + +test("a dialog that cannot be carried exactly is omitted instead of clipped", () => { + // A clipped confirm would show only the harmless prefix of an approval and + // still offer Yes/No: omit the whole dialog, keep the request id for the + // retraction, and let the app open the session instead. + const destructive = `${"A".repeat(480)} --delete-everything`; + const [confirm] = run([{ type: "ui_request", id: "req-long", method: "confirm", args: ["Allow tool: bash", destructive] }]); + assert.equal(confirm.dialog, undefined); + assert.equal(confirm.requestId, "req-long"); + + // The title and an ask question are held to the same rule. + const [title] = run([{ type: "ui_request", id: "req-title", method: "select", args: ["T".repeat(161), ["Yes", "No"]] }]); + assert.equal(title.dialog, undefined); + const [question] = run([{ type: "ui_request", id: "req-ask", method: "askDialog", args: [[{ id: "q", question: "Q".repeat(241), options: [] }]] }]); + assert.equal(question.dialog, undefined); + // open_url is fire-and-forget: no resolver in pi, so never a dialog. + const [openUrl] = run([{ type: "ui_request", id: "req-url", method: "open_url", args: ["https://example.com"] }]); + assert.equal(openUrl.dialog, undefined); + + // At the cap the whole text still fits, so the dialog is carried verbatim. + const message = "B".repeat(480); + const [atCap] = run([{ type: "ui_request", id: "req-cap", method: "confirm", args: ["Allow tool: bash", message] }]); + assert.equal(atCap.dialog.message, message); + assert.equal(atCap.dialog.message.length, 480); +}); + +test("decision text the notification cannot render omits the dialog", () => { + // The web shows an option's description/preview, an ask's question header and + // a secret input as decision-relevant UI; the notification has no field for + // them, so publishing only the label would answer a partially seen dialog. + const [described] = run([{ + type: "ui_request", id: "s-desc", method: "select", + args: ["Pick", [{ label: "Delete", description: "Removes the production database" }, { label: "Keep" }]], + }]); + assert.equal(described.dialog, undefined); + assert.equal(described.requestId, "s-desc"); + + const [preview] = run([{ + type: "ui_request", id: "q-prev", method: "askDialog", + args: [[{ id: "q", question: "Pick", options: [{ label: "A", preview: "rm -rf /srv" }] }]], + }]); + assert.equal(preview.dialog, undefined); + + const [header] = run([{ + type: "ui_request", id: "q-head", method: "askDialog", + args: [[{ id: "q", header: "Production", question: "Deploy?" }]], + }]); + assert.equal(header.dialog, undefined); + + const [secret] = run([{ type: "ui_request", id: "i-secret", method: "input", args: ["API token", "paste", { secret: true }] }]); + assert.equal(secret.dialog, undefined); + + // Empty hints hide nothing, so those dialogs stay answerable. + const [plainInput] = run([{ type: "ui_request", id: "i-plain", method: "input", args: ["Name", "type", { secret: false }] }]); + assert.ok(plainInput.dialog); + const [plainSelect] = run([{ type: "ui_request", id: "s-plain", method: "select", args: ["Pick", [{ label: "A", description: "" }]] }]); + assert.ok(plainSelect.dialog); + + // A missing id must not become the request id "undefined". + const [noId] = run([{ type: "ui_request", method: "confirm", args: ["Approve", "Do it"] }]); + assert.equal(noId.dialog, undefined); + assert.equal(noId.requestId, undefined); + + // Server-owned confirms render from/to/delivery/cwd; the contract cannot, so + // the notification only opens the session instead of offering a partial yes. + const [serverConfirm] = run([{ + type: "ui_request", id: "srv-1", method: "confirm", args: ["Send a message?", ""], + serverPayload: { + kind: "send_to_session", + from: { id: "s1", name: "Source", hostId: "local", hostLabel: "This machine" }, + to: null, + delivery: "steer", + message: "rm -rf /srv", + }, + }]); + assert.equal(serverConfirm.dialog, undefined); + assert.equal(serverConfirm.requestId, "srv-1"); +}); + +test("an ask dialog keeps option labels verbatim and drops payloads that cannot be answered", () => { + const questions = [{ id: "q1", question: "Ship it?", options: [{ label: "Yes" }, { label: "No" }], multi: true }]; + const [event] = run([{ type: "ui_request", id: "req-2", method: "askDialog", args: [questions] }]); + assert.deepEqual(event.dialog.questions, [{ id: "q1", question: "Ship it?", options: ["Yes", "No"], multi: true, allowCustom: true }]); + + // A label that would have to be clipped cannot be answered: no dialog, but + // the request id still reaches the notification so a retraction can close it. + const long = [{ id: "q1", question: "Ship it?", options: [{ label: "x".repeat(200) }] }]; + const [clipped] = run([{ type: "ui_request", id: "req-3", method: "askDialog", args: [long] }]); + assert.equal(clipped.dialog, undefined); + assert.equal(clipped.requestId, "req-3"); +}); + +test("a form dialog has no answerable dialog but keeps its request id", () => { + const [event] = run([{ type: "ui_request", id: "req-4", method: "formDialog", args: ["
"] }]); + assert.equal(event.requestId, "req-4"); + assert.equal(event.dialog, undefined); +}); + test("rendered notifications open their session and clip long details", () => { const t = (key, vars) => `${key}${vars ? JSON.stringify(vars) : ""}`; const rendered = renderNotification({ type: "error", sessionId: "a b", sessionName: null, detail: "x".repeat(500) }, t); @@ -89,6 +197,33 @@ test("rendered notifications open their session and clip long details", () => { assert.ok(rendered.body.length < 260, rendered.body); }); +test("an input body shows its dialog's decision text verbatim, never a clipped prefix", () => { + const t = (key, vars) => `${key}${vars ? JSON.stringify(vars) : ""}`; + const title = "Allow tool: bash"; + const message = `${"A".repeat(460)} --delete-everything`; + assert.equal(message.length, 480); + const confirm = renderNotification({ + type: "input", sessionId: "s1", sessionName: "Refactor", requestId: "req-1", detail: title, + dialog: { requestId: "req-1", method: "confirm", title, message }, + }, t); + assert.ok(confirm.body.includes(message), "the whole approval message reaches the body"); + assert.ok(!confirm.body.includes("…"), "the body is not clipped while the buttons are live"); + + const questions = [ + { id: "q1", question: "Deploy the first service?" }, + { id: "q2", question: "Deploy the second service?" }, + ]; + const ask = renderNotification({ + type: "input", sessionId: "s1", sessionName: "Refactor", requestId: "req-2", detail: "Deploy", + dialog: { requestId: "req-2", method: "ask", questions }, + }, t); + for (const question of questions) assert.ok(ask.body.includes(question.question), question.id); + + // Without a dialog there are no live buttons, so the generic detail cap stays. + const plain = renderNotification({ type: "input", sessionId: "s1", sessionName: "Refactor", detail: "x".repeat(500) }, t); + assert.ok(plain.body.includes("…")); +}); + test("a pasted overlong session name is clipped so push payloads stay small", () => { const rendered = renderNotification({ type: "completed", sessionId: "s1", sessionName: "y".repeat(60_000) }, (key) => key); assert.equal(rendered.title.length, 100); diff --git a/lib/notification-events.ts b/lib/notification-events.ts index febc18a9..5cf7115e 100644 --- a/lib/notification-events.ts +++ b/lib/notification-events.ts @@ -8,6 +8,34 @@ import { isRecord } from "./type-guards"; export const NOTIFICATION_TYPES = ["completed", "input", "error"] as const; export type NotificationType = (typeof NOTIFICATION_TYPES)[number]; +/** One question of an `ask` dialog, reduced to what a notification can answer. */ +export interface NotificationDialogQuestion { + id: string; + question: string; + /** Option labels (the web dialog sends labels back as `selectedOptions`). */ + options?: string[]; + multi?: boolean; + /** The web dialog always offers an "Other" free-text field unless pi forbids it. */ + allowCustom?: boolean; +} + +/** + * The blocking extension dialog behind an `input` notification. Carried in the + * SSE frame, the history entry and the push body so the native app can render + * Yes/No/option buttons or a reply field without an open chat tab. + */ +export interface NotificationDialog { + requestId: string; + method: "select" | "confirm" | "input" | "editor" | "ask"; + title?: string; + message?: string; + options?: string[]; + questions?: NotificationDialogQuestion[]; + placeholder?: string; + /** Wall-clock expiry (ms), present when pi set a timeout. */ + expiresAt?: number; +} + export interface NotificationEvent { /** `test` is only sent by the settings "Send test notification" button. */ type: NotificationType | "test"; @@ -15,6 +43,10 @@ export interface NotificationEvent { sessionName: string | null; /** Question or error text. */ detail?: string; + /** `input` only: the id a retraction (`publishNotificationDismiss`) matches. */ + requestId?: string; + /** `input` only: the dialog waiting for an answer, when it fits a push payload. */ + dialog?: NotificationDialog; } /** One entry of the persisted notification history; `id` is the replace-tag `:`. */ @@ -76,9 +108,29 @@ function clip(text: string, max = MAX_DETAIL): string { return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat; } +/** + * The decision text a dialog carries, verbatim: a confirm's title and message, + * an ask's questions, or the title of a select/input/editor. The body of an + * `input` event uses this instead of the clipped `detail`, so a push can never + * show only the harmless prefix of an approval whose buttons are live. + */ +function dialogBody(dialog: NotificationDialog | undefined): string | undefined { + if (!dialog) return undefined; + if (dialog.method === "confirm") { + const parts = [dialog.title, dialog.message].filter((text): text is string => Boolean(text)); + return parts.length > 0 ? parts.join(" — ") : undefined; + } + if (dialog.method === "ask") { + const questions = (dialog.questions ?? []).map((question) => question.question); + return questions.length > 0 ? questions.join("\n") : dialog.title; + } + return dialog.title; +} + /** Title, body, click target, and replace-tag for one event in the caller's language. */ export function renderNotification(event: NotificationEvent, t: Translate): RenderedNotification { - const detail = event.detail ? clip(event.detail) : ""; + const dialogDetail = event.type === "input" ? dialogBody(event.dialog) : undefined; + const detail = dialogDetail || (event.detail ? clip(event.detail) : ""); let body: string; switch (event.type) { case "completed": @@ -103,6 +155,11 @@ export function renderNotification(event: NotificationEvent, t: Translate): Rend }; } +/** + * Extension UI dialogs a notification can answer. Only these five arm an answer. + */ +export const DIALOG_UI_METHODS: ReadonlySet = new Set(["select", "confirm", "input", "editor", "askDialog"]); + const NOTIFICATION_ID_PATTERN = /^[A-Za-z0-9_-]{8,64}$/; /** Client and device ids: generated by the browser, checked by the server. */ @@ -112,6 +169,199 @@ export function isValidNotificationId(value: unknown): value is string { const str = (value: unknown): string | undefined => (typeof value === "string" && value.trim() ? value : undefined); +/** True when a field carries text (or a non-text value) a notification cannot render. */ +function carriesVisibleText(value: unknown): boolean { + if (value === undefined || value === null) return false; + return typeof value !== "string" || value.trim() !== ""; +} + +// Push payloads must stay well under the 4 KB Web Push limit. A dialog that +// cannot be represented within these caps is omitted entirely so the app falls +// back to "Open" instead of showing a partial question. +const DIALOG_TEXT = { title: 160, message: 480, placeholder: 80, option: 160, question: 240, questionOption: 120 }; +const DIALOG_COUNTS = { options: 12, questions: 5, questionOptions: 9 }; +const DIALOG_ID_CHARS = 128; +const MAX_DIALOG_BYTES = 1800; +const DIALOG_METHODS: Record = { select: true, confirm: true, input: true, editor: true, ask: true }; +const encoder = new TextEncoder(); + +/** + * One line of dialog text, or `null` when the whole text does not fit the + * notification's budget. Truncating is never an option: a `confirm` that showed + * only the harmless prefix of an approval would stay answerable. Absent or + * empty text is `undefined` (the dialog's other fields still identify it). + */ +function exactDialogText(value: unknown, max: number): string | undefined | null { + if (value === undefined || value === null) return undefined; + if (typeof value !== "string") return null; + const flat = value.replace(/\s+/g, " ").trim(); + if (!flat) return undefined; + return flat.length > max ? null : flat; +} + +/** + * Option labels travel back to pi as the answer and are compared verbatim + * (`extension_ui_response.selectedOptions`), so they are never trimmed, + * flattened or clipped. A set that has to be altered to fit the notification + * makes the whole dialog unrepresentable: the notification then only opens + * the session instead of sending an answer pi would not match. + */ +function exactDialogOptions(value: unknown, maxCount: number, maxChars: number): string[] | undefined { + if (!Array.isArray(value) || value.length > maxCount) return undefined; + const labels: string[] = []; + for (const entry of value) { + const label = typeof entry === "string" ? entry : isRecord(entry) ? entry.label : undefined; + if (typeof label !== "string" || label.length === 0 || label.length > maxChars) return undefined; + // The web renders an option's description and preview as decision text; the + // notification has no field for them, so such a dialog must not be offered. + if (isRecord(entry) && (carriesVisibleText(entry.description) || carriesVisibleText(entry.preview))) return undefined; + labels.push(label); + } + return labels.length > 0 ? labels : undefined; +} + +/** `ask` questions: ids must be unique and complete, or the whole dialog is unusable. */ +function dialogQuestions(value: unknown): NotificationDialogQuestion[] | undefined { + if (!Array.isArray(value) || value.length === 0 || value.length > DIALOG_COUNTS.questions) return undefined; + const questions: NotificationDialogQuestion[] = []; + const ids = new Set(); + for (const raw of value) { + if (!isRecord(raw)) return undefined; + // The id is the key pi matches the answer against; trimming it could + // answer a different question, so a padded id makes the dialog unusable. + const id = typeof raw.id === "string" ? raw.id : ""; + // A question header is rendered by the web as decision context. + if (carriesVisibleText(raw.header)) return undefined; + const question = exactDialogText(raw.question, DIALOG_TEXT.question); + if (!id || id.trim() !== id || id.length > DIALOG_ID_CHARS || ids.has(id) || !question) return undefined; + ids.add(id); + const entry: NotificationDialogQuestion = { id, question }; + // A non-empty list must survive exactly or the question would lose + // choices; an empty list is just a free-text question. + if (raw.options !== undefined && raw.options !== null) { + if (!Array.isArray(raw.options)) return undefined; + if (raw.options.length > 0) { + const options = exactDialogOptions(raw.options, DIALOG_COUNTS.questionOptions, DIALOG_TEXT.questionOption); + if (!options) return undefined; + entry.options = options; + } + } + if (raw.multi === true) entry.multi = true; + // Same rule as ExtensionDialog: every question may be answered with "Other". + if (raw.allowCustom !== false) entry.allowCustom = true; + questions.push(entry); + } + return questions; +} + +/** + * Reduce a blocking `extension_ui_request` frame to the answerable dialog a + * notification carries. Returns undefined for `open_url` (no answer) and for + * any frame the push payload cannot represent *exactly*: a field that would + * have to be truncated, an option set that would change, or a dialog over the + * byte budget. The notification then only opens the session — it never offers + * an answer based on a partial question. + */ +export function buildNotificationDialog(frame: Record): NotificationDialog | undefined { + const method = typeof frame.method === "string" ? frame.method : ""; + if (!DIALOG_METHODS[method]) return undefined; + // The id is echoed in the answer; never trim it into a different request. + const requestId = typeof frame.id === "string" ? frame.id : ""; + if (!requestId || requestId.trim() !== requestId || requestId.length > DIALOG_ID_CHARS) return undefined; + + const dialog: NotificationDialog = { requestId, method: method as NotificationDialog["method"] }; + const title = exactDialogText(frame.title, DIALOG_TEXT.title); + if (title === null) return undefined; + if (title) dialog.title = title; + + switch (dialog.method) { + case "select": { + const options = exactDialogOptions(frame.options, DIALOG_COUNTS.options, DIALOG_TEXT.option); + if (!options) return undefined; + dialog.options = options; + break; + } + case "confirm": { + const message = exactDialogText(frame.message, DIALOG_TEXT.message); + if (message === null) return undefined; + if (message) dialog.message = message; + break; + } + case "input": { + const placeholder = exactDialogText(frame.placeholder, DIALOG_TEXT.placeholder); + if (placeholder === null) return undefined; + if (placeholder) dialog.placeholder = placeholder; + break; + } + case "editor": + // The editor body (prefill) is not part of the notification contract: the + // app opens the session to edit it. The title is enough to name it. + break; + case "ask": { + const questions = dialogQuestions(frame.questions); + if (!questions) return undefined; + dialog.questions = questions; + break; + } + } + + // Nothing user-visible to show: the notification body already carries detail. + if (!dialog.title && !dialog.message && !dialog.placeholder && !dialog.questions && !dialog.options) return undefined; + if (typeof frame.expiresAt === "number" && Number.isFinite(frame.expiresAt) && frame.expiresAt > 0) dialog.expiresAt = frame.expiresAt; + if (encoder.encode(JSON.stringify(dialog)).byteLength > MAX_DIALOG_BYTES) return undefined; + return dialog; +} + +/** + * tau's `ui_request` carries the dialog's fields positionally in `args`; + * the notification contract names them. Methods that cannot be answered from a + * notification (a whole-form ask, an approval) map to undefined. + */ +function notificationDialogFrame(frame: Record): Record | undefined { + const method = typeof frame.method === "string" ? frame.method : ""; + const args = Array.isArray(frame.args) ? frame.args : []; + // A server-owned confirm renders from/to/delivery/host/cwd in `serverPayload` + // (ExtensionDialog's ServerConfirmBody). The notification contract has no + // field for them, so carrying only the message would still approve a decision + // the user cannot see in full: omit the dialog and open the session. + if (frame.serverPayload !== undefined && frame.serverPayload !== null) return undefined; + // Never turn a missing id into the request id "undefined". + const rawId = frame.id; + if (typeof rawId !== "string" && typeof rawId !== "number") return undefined; + if (typeof rawId === "number" && !Number.isSafeInteger(rawId)) return undefined; + const base: Record = { id: String(rawId), expiresAt: frame.expiresAt }; + switch (method) { + case "select": + return { ...base, method, title: args[0], options: args[1] }; + case "confirm": + return { ...base, method, title: args[0], message: args[1] }; + case "input": { + const options = isRecord(args[2]) ? args[2] : undefined; + // The web masks a secret input; a notification answer would type it into + // plain sight, so such a dialog is not answerable from a notification. + if (options && Boolean(options.secret)) return undefined; + return { ...base, method, title: args[0], placeholder: args[1] }; + } + case "editor": + return { ...base, method, title: args[0], prefill: args[1] }; + case "askDialog": + return { ...base, method: "ask", questions: args[0] }; + default: + return undefined; + } +} + +/** + * Whether a pending wire dialog is one the notification could actually carry. + * The answer route refuses anything else, so a request the notification had to + * omit (unrepresentable text, an oversized payload, a whole-form dialog, an + * approval or `open_url`) is not answerable from a notification either. + */ +export function isNotificationAnswerable(frame: Record): boolean { + const mapped = notificationDialogFrame(frame); + return mapped !== undefined && buildNotificationDialog(mapped) !== undefined; +} + type Detect = (frame: Record, session: { sessionId: string; sessionName: string | null }) => NotificationEvent[]; /** @@ -165,7 +415,14 @@ export function createNotificationDetector(): Detect { const detail = str(first) ?? (Array.isArray(first) && isRecord(first[0]) ? str(first[0].question) : undefined) ?? str(args[1]); - return [{ ...base, type: "input", detail }]; + const event: NotificationEvent = { ...base, type: "input", detail }; + // Carried even without a dialog (form/approve/oversized payload) so the + // matching retraction can still close this notification. + if (frame.id !== undefined) event.requestId = String(frame.id); + const mapped = notificationDialogFrame(frame); + const dialog = mapped ? buildNotificationDialog(mapped) : undefined; + if (dialog) event.dialog = dialog; + return [event]; } default: return []; diff --git a/lib/notification-hub.test.mjs b/lib/notification-hub.test.mjs index f6db7ded..3668347a 100644 --- a/lib/notification-hub.test.mjs +++ b/lib/notification-hub.test.mjs @@ -6,7 +6,7 @@ import { Database } from "bun:sqlite"; import test from "node:test"; const hub = await import("./notification-hub.ts"); -const { DEFAULT_NOTIFICATION_PREFS } = await import("./notification-events.ts"); +const { DEFAULT_NOTIFICATION_PREFS, buildNotificationDialog } = await import("./notification-events.ts"); const store = await import("./notification-store.ts"); const webpush = (await import("web-push")).default; @@ -203,6 +203,54 @@ test("pushes are written in the device's language with urgency by type", async ( ]); }); +test("an answerable dialog never pushes a payload over the 4 KB cap", async (t) => { + isolatedStore(t); + const sent = []; + webpush.sendNotification = async (_subscription, payload) => { + sent.push({ size: Buffer.byteLength(payload), payload: JSON.parse(payload) }); + }; + store.saveDevice("phone-0001", prefs(), subscription); + + // The largest confirm the dialog budget admits (title 160 + message 480). + const dialog = buildNotificationDialog({ + id: "req-push", + method: "confirm", + title: "t".repeat(160), + message: "m".repeat(480), + }); + assert.ok(dialog, "a dialog at every text cap is still representable"); + hub.publishNotification({ + type: "input", + sessionId: "s2", + sessionName: "Deploy", + // The rendered body clips this; the raw detail must not widen the payload. + detail: "d".repeat(5_000), + requestId: "req-push", + dialog, + }); + + // An ask with five full-length questions, on a session with a long CJK name: + // the body repeats the questions verbatim beside the dialog. + const questions = Array.from({ length: 5 }, (_, index) => ({ id: `q${index}`, question: `${index}:${"q".repeat(238)}` })); + const ask = buildNotificationDialog({ id: "req-ask", method: "ask", questions }); + assert.ok(ask, "five capped questions still fit the dialog budget"); + hub.publishNotification({ + type: "input", + sessionId: "s3", + sessionName: "会話".repeat(30), + detail: "d".repeat(5_000), + requestId: "req-ask", + dialog: ask, + }); + await new Promise((resolve) => setImmediate(resolve)); + + assert.equal(sent.length, 2); + for (const push of sent) assert.ok(push.size < 4096, `push payload is ${push.size} bytes`); + assert.deepEqual(sent[0].payload.dialog, dialog); + for (const question of questions) assert.ok(sent[1].payload.body.includes(question.question), question.id); + assert.ok(!sent[1].payload.body.includes("…")); +}); + for (const status of [404, 410]) { test(`a push service ${status} removes the subscription but keeps the device prefs`, async (t) => { isolatedStore(t); @@ -305,6 +353,153 @@ test("a retry is dropped once the device turned notifications off", async (t) => assert.equal(attempts, 1); }); +test("a settled dialog is retracted on every reachable stream and its history entry becomes read", (t) => { + isolatedStore(t); + store.saveDevice("phone-0001", prefs()); + const received = []; + hub.attachNotificationClient("phone-tab", (message) => received.push(message)); + hub.reportPresence({ clientId: "phone-tab", deviceId: "phone-0001", visible: false, sessionId: null, seq: 1 }); + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-1", detail: "Ship it?" }); + assert.deepEqual(received.map((message) => message.kind), ["os"]); + assert.deepEqual(store.listHistory().map((entry) => [entry.id, entry.read]), [["s2:input", false]]); + + hub.publishNotificationDismiss("s2", "req-1"); + assert.deepEqual(received.at(-1), { kind: "dismiss", tag: "s2:input", sessionId: "s2", requestId: "req-1" }); + assert.deepEqual(store.listHistory().map((entry) => [entry.id, entry.read]), [["s2:input", true]]); +}); + +test("a retraction pushes nothing at all: a push that displays nothing is a silent push", async (t) => { + isolatedStore(t); + const sent = []; + webpush.sendNotification = async (_subscription, payload) => { + sent.push(JSON.parse(payload)); + }; + // Both a subscribed phone and an iPhone: neither may get a dismiss push. + // Chromium and Firefox answer a push that shows nothing with a generic card + // and mute the origin; iOS revokes the permission outright. + store.saveDevice("phone-0001", prefs(), subscription); + store.saveDevice("iphone-0001", prefs(), { ...subscription, endpoint: "https://web.push.apple.com/xyz" }); + hub.publishNotificationDismiss("s2", "req-1"); + await flush(); + assert.deepEqual(sent, [], "no device is pushed a retraction"); +}); + +test("the retraction reads only the entry of its own request, not a newer dialog of the same tag", (t) => { + isolatedStore(t); + store.saveDevice("phone-0001", prefs()); + // Request A's entry is replaced by request B's, which is still pending. + store.recordHistory({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-B", detail: "Or now?" }); + hub.publishNotificationDismiss("s2", "req-A"); + assert.deepEqual(store.listHistory().map((entry) => [entry.event.requestId, entry.read]), [["req-B", false]], "a stale retraction leaves the pending entry unread"); + hub.publishNotificationDismiss("s2", "req-B"); + assert.deepEqual(store.listHistory().map((entry) => [entry.event.requestId, entry.read]), [["req-B", true]]); +}); + +test("a forgotten dialog is retracted now, and a replay of the same request is announced and pushed again", async (t) => { + isolatedStore(t); + t.mock.timers.enable({ apis: ["setTimeout"] }); + t.mock.method(console, "warn", () => {}); + const pushes = []; + webpush.sendNotification = async (_subscription, payload) => { + pushes.push(JSON.parse(payload).requestId); + throw offline(); + }; + // One device takes pushes, another has only a reachable tab. + store.saveDevice("phone-0001", prefs(), subscription); + store.saveDevice("desk-0001", prefs()); + const frames = []; + hub.attachNotificationClient("tab-0001", (message) => frames.push(message)); + hub.reportPresence({ clientId: "tab-0001", deviceId: "desk-0001", visible: false, sessionId: null, seq: 1 }); + + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-1" }); + await flush(); + assert.deepEqual(pushes, ["req-1"]); + assert.equal(frames.at(-1).kind, "os", "the tab shows the question"); + + // A resync dropped the dialog: it is retracted now, so no tab keeps offering it. + hub.publishNotificationForgotten("s2", "req-1"); + assert.deepEqual(frames.at(-1), { kind: "dismiss", tag: "s2:input", sessionId: "s2", requestId: "req-1" }); + + // The host replays the same request id: the question is pending again, so its + // notification goes out and its push is attempted, not suppressed by the + // retraction the resync just recorded. + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-1" }); + await flush(); + assert.equal(frames.at(-1).kind, "os", "the replayed question is delivered again"); + assert.deepEqual(pushes, ["req-1", "req-1"], "the push of the replayed question is not suppressed"); +}); + +test("a forgotten dialog stays retracted while no replay restores it", async (t) => { + isolatedStore(t); + t.mock.timers.enable({ apis: ["setTimeout"] }); + t.mock.method(console, "warn", () => {}); + let attempts = 0; + webpush.sendNotification = async () => { + attempts += 1; + throw offline(); + }; + store.saveDevice("phone-0001", prefs(), subscription); + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-1" }); + await flush(); + assert.equal(attempts, 1); + hub.publishNotificationForgotten("s2", "req-1"); + t.mock.timers.tick(hub.PUSH_RETRY_DELAYS_MS[0]); + await flush(); + assert.equal(attempts, 1, "the sleeping retry woke up after the resync and sent nothing"); +}); + +test("a forgotten retraction never lifts a permanent settlement of the same request", async (t) => { + isolatedStore(t); + t.mock.timers.enable({ apis: ["setTimeout"] }); + t.mock.method(console, "warn", () => {}); + let attempts = 0; + webpush.sendNotification = async () => { + attempts += 1; + throw offline(); + }; + store.saveDevice("phone-0001", prefs(), subscription); + // Answered, then a resync forgets a dialog of the same session. + hub.publishNotificationDismiss("s2", "req-1"); + hub.publishNotificationForgotten("s2", "req-1"); + // A replay of the answered request must not reopen its notification. + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-1" }); + await flush(); + assert.equal(attempts, 0, "an answered dialog is never pushed again"); +}); + +test("a retraction never pushes, whatever the device's preferences are", async (t) => { + isolatedStore(t); + const sent = []; + webpush.sendNotification = async (_subscription, payload) => { + sent.push(JSON.parse(payload)); + }; + // Each device needs its own endpoint: saving one moves it off any other device. + store.saveDevice("phone-0001", prefs({ enabled: false }), subscription); + store.saveDevice("phone-0002", prefs({ types: { ...DEFAULT_NOTIFICATION_PREFS.types, input: false } }), { ...subscription, endpoint: "https://push.example/def" }); + hub.publishNotificationDismiss("s2", "req-1"); + await flush(); + assert.deepEqual(sent, [], "a retraction is not an alert and is never pushed, gated or not"); +}); + +test("a push retry after the dialog settled delivers nothing", async (t) => { + isolatedStore(t); + t.mock.timers.enable({ apis: ["setTimeout"] }); + t.mock.method(console, "warn", () => {}); + let attempts = 0; + webpush.sendNotification = async () => { + attempts += 1; + throw offline(); + }; + store.saveDevice("phone-0001", prefs(), subscription); + hub.publishNotification({ type: "input", sessionId: "s2", sessionName: "Deploy", requestId: "req-1" }); + await flush(); + assert.equal(attempts, 1); + hub.publishNotificationDismiss("s2", "req-1"); + t.mock.timers.tick(hub.PUSH_RETRY_DELAYS_MS[0]); + await flush(); + assert.equal(attempts, 1, "the sleeping retry woke up after the answer and sent nothing"); +}); + test("the test button gets one attempt and the network failure's cause", async (t) => { isolatedStore(t); t.mock.method(console, "warn", () => {}); diff --git a/lib/notification-hub.ts b/lib/notification-hub.ts index da6b433e..68556caa 100644 --- a/lib/notification-hub.ts +++ b/lib/notification-hub.ts @@ -9,7 +9,7 @@ import { type NotificationEvent, type RenderedNotification, } from "./notification-events"; -import { dropDeviceSubscription, getDevice, getVapidKeys, listDevices, recordHistory, type NotificationDevice } from "./notification-store"; +import { dropDeviceSubscription, getDevice, getVapidKeys, listDevices, markHistoryRead, recordHistory, type NotificationDevice } from "./notification-store"; /** * Server side of notifications: presence of open tabs, per-device preferences @@ -23,6 +23,14 @@ const PUSH_TTL_SECONDS = 3600; const PUSH_TIMEOUT_MS = 10_000; /** Waits before each retry of a push the push service never answered or answered 429/5xx. Well inside the TTL. */ export const PUSH_RETRY_DELAYS_MS = [2_000, 10_000, 30_000]; +/** + * How long a retraction keeps suppressing further delivery attempts of the + * same `input` push: one retry cycle is its backoff waits plus the time a + * single attempt may hang, and no retry can outlive that. + */ +export const PUSH_RETRACTION_TTL_MS = PUSH_RETRY_DELAYS_MS.reduce((total, delay) => total + delay, 0) + + (PUSH_RETRY_DELAYS_MS.length + 1) * PUSH_TIMEOUT_MS; + // Apple's push service rejects VAPID subjects it cannot resolve (e.g. localhost mail). const VAPID_SUBJECT = `https://github.com/${releaseRepo()}`; @@ -37,7 +45,16 @@ export interface NotificationPresence { lastSeen: number; } -export type NotificationMessage = { kind: "toast" | "os"; event: NotificationEvent }; +/** + * A toast/system notification, or the retraction of a session's `input` + * notification once its dialog was answered, cancelled, expired or its pi + * child went away. The retraction reaches a tab as `type: "notification-dismiss"` + * (lib/event-stream-hub.ts wraps it); it is never pushed (see + * `publishNotificationDismiss`). + */ +export type NotificationMessage = + | { kind: "toast" | "os"; event: NotificationEvent } + | { kind: "dismiss"; tag: string; sessionId: string; requestId: string }; type Send = (message: NotificationMessage) => void; @@ -49,6 +66,15 @@ interface HubState { presence: Map; /** Open SSE streams per tab. Independent of presence: streams reconnect, overlap, and close while the tab stays put. */ streams: Map>; + /** `:` → when it was retracted. A push retry of a settled dialog must deliver nothing (see `publishNotificationDismiss`). */ + retractions: Map; + /** + * The same, for a settlement a replay may undo: a resync forgets a dialog + * whose replayed frame can restore the very same request id. The retraction + * still closes what is on screen and stops a sleeping retry, and publishing + * that request id again lifts it (see `publishNotification`). + */ + temporaryRetractions: Map; } declare global { @@ -56,7 +82,12 @@ declare global { } function hub(): HubState { - return (globalThis.__tauNotificationHub ??= { presence: new Map(), streams: new Map() }); + const state = (globalThis.__tauNotificationHub ??= { presence: new Map(), streams: new Map(), retractions: new Map(), temporaryRetractions: new Map() }); + // `bun --hot` keeps this object across a re-evaluation: a state created by + // the previous module instance may predate a field added here. + state.retractions ??= new Map(); + state.temporaryRetractions ??= new Map(); + return state; } export function getVapidPublicKey(): string { @@ -152,15 +183,40 @@ function stillSubscribed(deviceId: string, endpoint: string): boolean { } } -/** Never throws: a failed push must not break delivery to anyone else. */ +/** + * True while this dialog's retraction still covers a push retry. Every path + * that settles a dialog (answer, cancel, expiry, process exit) records one, + * and `sendPush` asks before every attempt: a retry that wakes up after + * another client answered must never re-deliver a question nobody can answer. + * A temporary retraction (a resync that forgot the dialog) counts the same way + * until the request is published again. + */ +function isRetracted(sessionId: string, requestId: string, now: number): boolean { + const state = hub(); + const key = `${sessionId}:${requestId}`; + const at = state.retractions.get(key) ?? state.temporaryRetractions.get(key); + return at !== undefined && now - at <= PUSH_RETRACTION_TTL_MS; +} + async function sendPush(device: NotificationDevice, event: NotificationEvent, retryDelaysMs: readonly number[] = []): Promise<{ ok: true } | { ok: false; error: string }> { const subscription = device.subscription; if (!subscription) return { ok: false, error: "no push subscription" }; for (let attempt = 0; ; attempt++) { + // A retry can wake long after the dialog was answered, cancelled, expired + // or its pi child died: delivering now would show a dead question. + if (event.type === "input" && event.requestId && isRetracted(event.sessionId, event.requestId, Date.now())) { + return { ok: false, error: "dialog settled" }; + } try { const { publicKey, privateKey } = getVapidKeys(webpush.generateVAPIDKeys); - // `type` lets the service worker tell open tabs which kind of entry to list. - await webpush.sendNotification(subscription, JSON.stringify({ ...renderFor(event, device.prefs.locale), type: event.type }), { + // `type` lets the service worker tell open tabs which kind of entry to list; + // `requestId`/`dialog` let the app answer without opening the session. + await webpush.sendNotification(subscription, JSON.stringify({ + ...renderFor(event, device.prefs.locale), + type: event.type, + ...(event.requestId ? { requestId: event.requestId } : {}), + ...(event.dialog ? { dialog: event.dialog } : {}), + }), { TTL: PUSH_TTL_SECONDS, urgency: event.type === "input" || event.type === "error" ? "high" : "normal", timeout: PUSH_TIMEOUT_MS, @@ -192,6 +248,10 @@ async function sendPush(device: NotificationDevice, event: NotificationEvent, re /** Never throws: callers publish from the RPC frame path, and a store failure must not cost them the frame. */ export function publishNotification(event: NotificationEvent): void { const state = hub(); + // A replayed dialog (resync after a lost link) restores a request a resync + // had temporarily retracted: it is pending again, so its notification and + // its pushes must go out as for any other question. + if (event.type === "input" && event.requestId) state.temporaryRetractions.delete(`${event.sessionId}:${event.requestId}`); let devices: NotificationDevice[] = []; try { devices = listDevices(); @@ -225,6 +285,79 @@ export function publishNotification(event: NotificationEvent): void { } } +/** + * Retract a session's `input` notification: its dialog was answered by any + * client, cancelled, expired, or its pi child went away. Every reachable tab + * gets the retraction on its stream, and the history entry becomes read + * because the question is settled. + * + * No push goes out: a push that displays nothing counts as a silent push, and + * Chromium and Firefox answer one with a browser-substituted card ("This site + * has been updated in the background") and eventually mute the origin, exactly + * as iOS revokes the permission. A device that is not reachable keeps the stale + * card until the next `input` push replaces it by tag or the app syncs. + * + * Never throws: callers run on the RPC frame path. + */ +export function publishNotificationDismiss(sessionId: string, requestId: string): void { + retract(sessionId, requestId, "permanent"); +} + +/** + * Retract a dialog this server only *forgot*: a resync dropped the pending + * request, and the replayed frames may restore the very same request id. + * Everything a retraction does happens (open tabs close it, a sleeping push + * retry stops, the history entry becomes read), but the record is temporary: + * publishing that request id again lifts it, so a replayed question is + * announced and pushed like a new one instead of being suppressed for the + * retraction TTL. A dialog that is really gone is never replayed, and its + * notification stays closed. + */ +export function publishNotificationForgotten(sessionId: string, requestId: string): void { + retract(sessionId, requestId, "temporary"); +} + +function retract(sessionId: string, requestId: string, kind: "permanent" | "temporary"): void { + const tag = `${sessionId}:input`; + const state = hub(); + const now = Date.now(); + // Recorded first: a retry of that `input` push may be sleeping right now. + for (const [key, at] of state.retractions) { + if (now - at > PUSH_RETRACTION_TTL_MS) state.retractions.delete(key); + } + for (const [key, at] of state.temporaryRetractions) { + if (now - at > PUSH_RETRACTION_TTL_MS) state.temporaryRetractions.delete(key); + } + const key = `${sessionId}:${requestId}`; + if (kind === "permanent") { + state.temporaryRetractions.delete(key); + state.retractions.set(key, now); + } else if (!state.retractions.has(key)) { + // A permanent settlement of the same request wins: a replay of an answered + // dialog must not reopen its notification. + state.temporaryRetractions.set(key, now); + } + // Only the entry of this request is read: a newer dialog of the same tag + // replaced it in the history, and that one is still waiting for an answer. + try { + markHistoryRead([tag], requestId); + } catch (error) { + console.warn("[notifications] history read mark failed:", error); + } + // Every reachable tab hears it: one that never showed this notification + // closes nothing, and the frame names the request so a later dialog of the + // same tag stays. A tab whose stream died keeps nothing to clear. + for (const sends of state.streams.values()) { + for (const send of sends) { + try { + send({ kind: "dismiss", tag, sessionId, requestId }); + } catch { + // A closing stream must not break delivery to the others. + } + } + } +} + /** Settings "Send test notification" for a device with push: reports whether the push service accepted it. * One attempt, so the button answers at once. */ export async function sendTestPush(deviceId: string): Promise<{ ok: true } | { ok: false; error: string }> { diff --git a/lib/notification-store.test.mjs b/lib/notification-store.test.mjs index 88ec4ae4..ad771ac8 100644 --- a/lib/notification-store.test.mjs +++ b/lib/notification-store.test.mjs @@ -202,6 +202,24 @@ test("mark read by ids, remove one, clear", (t) => { assert.deepEqual(store.listHistory(), []); }); +test("a request-scoped read marks only that request's entry, never a newer dialog or a legacy one", (t) => { + isolated(t); + // Request B replaced A's entry under the same tag. + store.recordHistory({ ...event("s2"), type: "input", requestId: "req-B" }); + store.markHistoryRead(["s2:input"], "req-A"); + assert.deepEqual(store.listHistory().map((e) => [e.event.requestId, e.read]), [["req-B", false]], "a stale retraction leaves the pending entry unread"); + store.markHistoryRead(["s2:input"], "req-B"); + assert.deepEqual(store.listHistory().map((e) => [e.event.requestId, e.read]), [["req-B", true]]); + // An entry recorded before request ids existed has no requestId at all: + // SQLite's `IS` compares NULL to a string as false, so it stays unread. + store.recordHistory({ ...event("s3"), type: "input" }); + store.markHistoryRead(["s3:input"], "req-anything"); + assert.deepEqual(store.listHistory().filter((e) => e.event.sessionId === "s3").map((e) => [e.event.requestId, e.read]), [[undefined, false]]); + // Without a request id the tag alone still marks it, as the client's own PATCH does. + store.markHistoryRead(["s3:input"]); + assert.deepEqual(store.listHistory().filter((e) => e.event.sessionId === "s3").map((e) => e.read), [true]); +}); + function writeLegacy(dir, content) { mkdirSync(join(dir, "tau"), { recursive: true }); const file = join(dir, "tau", "notifications.json"); diff --git a/lib/notification-store.ts b/lib/notification-store.ts index 942f4d57..b480a83a 100644 --- a/lib/notification-store.ts +++ b/lib/notification-store.ts @@ -260,11 +260,20 @@ export function recordHistory(event: NotificationEvent, { at = Date.now(), read return { id, event, at, read }; } -export function markHistoryRead(ids: string[]): void { +/** + * Mark entries read. With `requestId`, only an entry whose stored event still + * names that request is marked: a newer dialog of the same tag replaced the + * entry, and that one is still waiting for an answer. + */ +export function markHistoryRead(ids: string[], requestId?: string): void { const database = db(); const mark = database.prepare("UPDATE history SET read = 1 WHERE id = ?"); + const markMatching = database.prepare("UPDATE history SET read = 1 WHERE id = ? AND json_extract(event, '$.requestId') IS ?"); transaction(database, () => { - for (const id of ids) mark.run(id); + for (const id of ids) { + if (requestId === undefined) mark.run(id); + else markMatching.run(id, requestId); + } }); } diff --git a/lib/notification-sw.test.mjs b/lib/notification-sw.test.mjs index 2dcb4344..fcdd6a67 100644 --- a/lib/notification-sw.test.mjs +++ b/lib/notification-sw.test.mjs @@ -20,6 +20,7 @@ function loadWorker(windows = [], globals = {}) { }); return { shown, + registration: self.registration, message: (event) => listeners.message(event), push: async (payload) => { let done; @@ -44,6 +45,24 @@ test("a shown push is reported to every open tab with its kind, text and session assert.deepEqual(messages, [["a", { type: "tau-notification-shown", notification }], ["b", { type: "tau-notification-shown", notification }]]); }); +test("every push the worker receives is displayed, including one that names a settled request", async () => { + const closed = []; + const worker = loadWorker(); + // The server never pushes a retraction (a push that shows nothing is a + // silent push), so the worker has no dismiss branch: it always displays. + const notifications = [{ data: { requestId: "req-1" }, close: () => closed.push("req-1") }]; + worker.registration.getNotifications = async () => notifications; + await worker.push({ type: "dismiss", tag: "s1:input", sessionId: "s1", requestId: "req-1" }); + assert.deepEqual(closed, [], "a payload is never acted on without being shown"); + assert.equal(worker.shown.length, 1, "even an unexpected payload becomes a visible notification"); +}); + +test("a dialog push carries its request id so a retraction can match it", async () => { + const worker = loadWorker(); + await worker.push({ type: "input", title: "Deploy", body: "Ship it?", tag: "s1:input", sessionId: "s1", requestId: "req-9" }); + assert.equal(worker.shown[0].options.data.requestId, "req-9"); +}); + test("an unreadable push still shows a notification and reports it as info", async () => { const messages = []; const worker = loadWorker([{ postMessage: (message) => messages.push(structuredClone(message)) }]); diff --git a/lib/pi-types.ts b/lib/pi-types.ts index 2c4c38ef..c85f7311 100644 --- a/lib/pi-types.ts +++ b/lib/pi-types.ts @@ -204,6 +204,16 @@ export interface RpcAskDialogAnswer { customInput?: string; } +/** + * One answer to a blocking dialog, from the web dialog or the notification + * answer endpoint. Exactly one variant is sent. + */ +export type ExtensionUiResponse = + | { value: string } + | { confirmed: boolean } + | { cancelled: true } + | { answers: RpcAskDialogAnswer[] }; + /** * tau's host-tool bridge: tau registers host tools (set_host_tools, which the * daemon hands to the extension's `/tau_host_tools`) that the agent can call; diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index a994d34a..efc08dc2 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -833,9 +833,14 @@ async function reachableTab() { saveDevice("desk-0001", { enabled: true, types: { completed: true, input: true, error: true }, whenActive: "toast", locale: "en" }); globalThis.__tauExitedSessions = new Map(); const delivered = []; + const messages = []; globalThis.__tauNotificationHub = { presence: new Map([["tab-0001", { clientId: "tab-0001", deviceId: "desk-0001", visible: false, sessionId: null, lastSeen: Date.now() }]]), - streams: new Map([["tab-0001", new Set([(message) => delivered.push([message.event.type, message.event.detail])])]]), + streams: new Map([["tab-0001", new Set([(message) => { + messages.push(message); + // Retractions carry no event; the notification assertions read the kind. + if (message.kind !== "dismiss") delivered.push([message.event.type, message.event.detail]); + }])]]), }; const restore = () => { globalThis.__tauNotificationHub = previousHub; @@ -846,12 +851,12 @@ async function reachableTab() { closeNotificationStore(); rmSync(dir, { recursive: true, force: true }); }; - return { delivered, restore }; + return { delivered, messages, restore }; } /** A wrapper whose omp frames the test drives, with one reachable tab collecting notifications. */ async function notifyingSession(t) { - const { delivered, restore } = await reachableTab(); + const { delivered, messages, restore } = await reachableTab(); let feed; /** What omp's get_state answers; tests change it to simulate session moves and switches. */ const piState = { sessionId: "notify-session", sessionFile: "/tmp/notify-session.jsonl", isStreaming: false, isCompacting: false }; @@ -870,7 +875,7 @@ async function notifyingSession(t) { await wrapper.destroyAndWait(); restore(); }); - return { wrapper, feed, delivered, piState }; + return { wrapper, feed, delivered, messages, piState }; } test("after a session switches to another conversation, a tab left on the old id no longer silences it", async (t) => { @@ -898,6 +903,93 @@ test("omp frames reach the user as notifications: settled run, pending question" assert.deepEqual(delivered, [["completed", undefined], ["input", "Delete the branch?"]]); }); +test("every settlement path retracts the pending question's notification, and only once", async (t) => { + const { wrapper, feed, messages } = await notifyingSession(t); + const dismisses = () => messages.filter((message) => message.kind === "dismiss"); + const ask = (id) => feed({ type: "ui_request", id, method: "confirm", args: ["Delete the branch?", ""] }); + + // Answered from the desktop. + ask(1); + assert.deepEqual(dismisses(), []); + await wrapper.send({ type: "ui_response", id: 1, value: true }); + assert.deepEqual(dismisses(), [{ kind: "dismiss", tag: "notify-session:input", sessionId: "notify-session", requestId: "1" }]); + + // Cancelled by pi. + ask(2); + feed({ type: "ui_end", id: 2 }); + assert.deepEqual(dismisses().at(-1), { kind: "dismiss", tag: "notify-session:input", sessionId: "notify-session", requestId: "2" }); + + // Expired by its own timeout. + feed({ type: "ui_request", id: 3, method: "input", args: ["Value", null, { timeout: 1 }] }); + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.deepEqual(dismisses().at(-1), { kind: "dismiss", tag: "notify-session:input", sessionId: "notify-session", requestId: "3" }); + + // Answered from a notification: the same path, so the same retraction. + ask(4); + assert.equal(await wrapper.answerExtensionUiRequest("4", { confirmed: true }), "answered"); + assert.deepEqual(dismisses().at(-1), { kind: "dismiss", tag: "notify-session:input", sessionId: "notify-session", requestId: "4" }); + // A second answer is not a settlement of anything. + assert.equal(await wrapper.answerExtensionUiRequest("4", { confirmed: true }), "alreadySettled"); + assert.equal(dismisses().length, 4); +}); + +test("clearing every pending dialog (restart, destroy) retracts each one", async (t) => { + const { wrapper, feed, messages } = await notifyingSession(t); + feed({ type: "ui_request", id: 1, method: "input", args: ["First"] }); + feed({ type: "ui_request", id: 2, method: "select", args: ["Second", ["A"]] }); + await wrapper.destroyAndWait(); + assert.deepEqual(messages.filter((message) => message.kind === "dismiss").map((message) => message.requestId).sort(), ["1", "2"]); +}); + +test("a retraction keeps the session id the notification was published under after pi moves the conversation", async (t) => { + const { wrapper, feed, messages, piState } = await notifyingSession(t); + feed({ type: "ui_request", id: 7, method: "confirm", args: ["Continue?", ""] }); + // pi moves the conversation to a new file, then the dialog is answered. + Object.assign(piState, { sessionId: "moved-session", sessionFile: "/tmp/moved-session.jsonl" }); + feed({ type: "notice", level: "warning", source: "session-persistence", message: "moved" }); + await new Promise((resolve) => setImmediate(resolve)); + await wrapper.send({ type: "ui_response", id: 7, value: true }); + assert.deepEqual(messages.filter((message) => message.kind === "dismiss"), [ + { kind: "dismiss", tag: "notify-session:input", sessionId: "notify-session", requestId: "7" }, + ]); +}); + +test("a server-owned confirm is settled by the notification answer path, not just forgotten", async (t) => { + const { wrapper, messages } = await notifyingSession(t); + const events = []; + wrapper.onEvent((event) => events.push(event)); + const answer = wrapper.confirmFromServer("Start a session on build-box?"); + const request = events.find((event) => event.type === "ui_request" && event.method === "confirm"); + assert.equal(await wrapper.answerExtensionUiRequest(request.id, { confirmed: true }), "answered"); + assert.equal(await answer, true, "the registered server resolver runs"); + assert.equal(messages.at(-1).requestId, request.id); +}); + +test("destroying a session retracts a server-owned confirm under its own tau request id", async (t) => { + const { wrapper, messages } = await notifyingSession(t); + const events = []; + wrapper.onEvent((event) => events.push(event)); + const answer = wrapper.confirmFromServer("Start a session on build-box?"); + const request = events.find((event) => event.type === "ui_request" && event.method === "confirm"); + assert.match(request.id, /^tau:/, "the server owns this dialog's id"); + assert.deepEqual(messages.filter((message) => message.kind === "dismiss"), [], "nothing is retracted while it waits"); + + await wrapper.destroyAndWait(); + assert.equal(await answer, false, "the dialog is declined"); + assert.deepEqual(messages.filter((message) => message.kind === "dismiss"), [ + { kind: "dismiss", tag: "notify-session:input", sessionId: "notify-session", requestId: request.id }, + ], "dropServerUiRequests settles the dialog instead of only forgetting it"); +}); + +test("an answer the pending dialog does not take is refused before anything settles", async (t) => { + const { wrapper, feed, messages } = await notifyingSession(t); + feed({ type: "ui_request", id: 8, method: "select", args: ["Which?", ["A", "B"]] }); + await assert.rejects(wrapper.answerExtensionUiRequest("8", { value: "C" }), { code: "invalid_dialog_answer" }); + await assert.rejects(wrapper.answerExtensionUiRequest("8", { confirmed: true }), { code: "invalid_dialog_answer" }); + assert.deepEqual(messages.filter((message) => message.kind === "dismiss"), [], "a refused answer leaves the dialog pending"); + assert.equal(await wrapper.answerExtensionUiRequest("8", { value: "B" }), "answered"); +}); + test("a crash during a run notifies the user once", async (t) => { const { wrapper, feed, delivered } = await notifyingSession(t); feed({ type: "agent_start" }); @@ -1411,6 +1503,126 @@ test("expired dialogs are not replayed by a later stream subscription", async (t assert.deepEqual(received, []); }); +test("a dialog whose deadline passed while no timer could run is retracted when a tab attaches, not replayed", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); + const { messages, restore } = await reachableTab(); + let feed; + const piState = { sessionId: "replay-expiry", sessionFile: "/tmp/replay-expiry.jsonl", isStreaming: false, isCompacting: false }; + const fakeProc = { + isAlive: true, + waitReady: async () => ({ type: "ready", protocolVersion: 2 }), + negotiateProtocol: async () => {}, + onFrame: (handler) => { feed = handler; return () => {}; }, + sendCommand: async (command) => command.type === "get_state" ? { ...piState } : {}, + sendFrame: () => {}, + dispose: async () => {}, + }; + const wrapper = new SnapshotWrapper(fakeProc, process.cwd(), null, "", undefined, localHost); + wrapper.start(); + await wrapper.waitUntilReady(); + t.after(async () => { + await wrapper.destroyAndWait(); + restore(); + }); + + feed({ type: "ui_request", id: "q-exp", method: "confirm", args: ["Deploy?", "", { timeout: 1_000 }] }); + // The deadline passes without its timer running (a wrapper that outlived the + // timer, e.g. across a hot reload): only the replay path can notice. + t.mock.timers.setTime(Date.now() + 5_000); + const replayed = []; + wrapper.onEvent((event) => replayed.push(event)); + assert.deepEqual(replayed.filter((event) => event.type === "ui_request"), [], "an expired dialog is not offered again"); + assert.deepEqual(messages.filter((message) => message.kind === "dismiss"), [ + { kind: "dismiss", tag: "replay-expiry:input", sessionId: "replay-expiry", requestId: "q-exp" }, + ], "the replay-time expiry retracts the notification it published"); + assert.equal(await wrapper.answerExtensionUiRequest("q-exp", { confirmed: true }), "alreadySettled"); +}); + +test("an expired dialog is retracted once, is not answerable, and a later one of the same tag still is", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); + const { messages, restore } = await reachableTab(); + let feed; + const piState = { sessionId: "expiry-session", sessionFile: "/tmp/expiry-session.jsonl", isStreaming: false, isCompacting: false }; + const fakeProc = { + isAlive: true, + waitReady: async () => ({ type: "ready", protocolVersion: 2 }), + negotiateProtocol: async () => {}, + onFrame: (handler) => { feed = handler; return () => {}; }, + sendCommand: async (command) => command.type === "get_state" ? { ...piState } : {}, + sendFrame: () => {}, + dispose: async () => {}, + }; + const wrapper = new SnapshotWrapper(fakeProc, process.cwd(), null, "", undefined, localHost); + wrapper.start(); + await wrapper.waitUntilReady(); + t.after(async () => { + await wrapper.destroyAndWait(); + restore(); + }); + const dismisses = () => messages.filter((message) => message.kind === "dismiss"); + + feed({ type: "ui_request", id: 21, method: "confirm", args: ["Deploy?", "", { timeout: 1_000 }] }); + t.mock.timers.tick(1_001); + assert.deepEqual(dismisses(), [{ kind: "dismiss", tag: "expiry-session:input", sessionId: "expiry-session", requestId: "21" }]); + // An expired request id is gone: answering it is not a settlement of anything. + assert.equal(await wrapper.answerExtensionUiRequest("21", { confirmed: true }), "alreadySettled"); + assert.equal(dismisses().length, 1, "an answer after expiry retracts nothing twice"); + + // The next dialog of the same tag is a new question with its own lifecycle. + feed({ type: "ui_request", id: 22, method: "confirm", args: ["Deploy?", ""] }); + assert.equal(await wrapper.answerExtensionUiRequest("22", { confirmed: true }), "answered"); + assert.deepEqual(dismisses().at(-1), { kind: "dismiss", tag: "expiry-session:input", sessionId: "expiry-session", requestId: "22" }); +}); + +for (const [method, args, accepted, refused] of [ + ["confirm", ["Continue?", ""], { confirmed: false }, { value: "yes" }], + ["select", ["Which?", ["A", "B"]], { value: "A" }, { confirmed: true }], + ["input", ["Value"], { value: "text" }, { confirmed: true }], + ["editor", ["Edit"], { value: "text" }, { confirmed: true }], + ["askDialog", [[{ id: "q", question: "Pick", options: [{ label: "A" }] }]], { answers: [{ id: "q", selectedOptions: ["A"] }] }, { value: "A" }], +]) { + test(`a ${method} dialog refuses the answer variants it does not take, and keeps the dialog pending`, async (t) => { + const { wrapper, emit, sentFrames } = snapshotSession(t); + emit({ type: "ui_request", id: 41, method, args }); + for (const response of [refused, { answers: [{ id: "q", selectedOptions: ["A"] }] }, { confirmed: true }]) { + // Only the variants that really do not belong to this method. + if (method === "confirm" && "confirmed" in response) continue; + if (method === "select" && "value" in response) continue; + if ((method === "input" || method === "editor") && "value" in response) continue; + if (method === "askDialog" && "answers" in response) continue; + await assert.rejects( + wrapper.answerExtensionUiRequest("41", response), + { name: "WebRpcError" }, + `${method} must refuse ${JSON.stringify(response)}`, + ); + } + assert.deepEqual(sentFrames, [], `${method}: a refused answer never reaches pi`); + const replay = []; + wrapper.onEvent((event) => replay.push(event)); + assert.equal(replay[0]?.id, 41, `${method}: a refused answer leaves the dialog pending`); + assert.equal(await wrapper.answerExtensionUiRequest("41", accepted), "answered"); + assert.equal(sentFrames.length, 1, `${method}: the accepted answer is forwarded once`); + }); +} + +test("a form dialog is never answerable from a notification: it takes no response and stays pending", async (t) => { + const { wrapper, emit, sentFrames } = snapshotSession(t); + emit({ type: "ui_request", id: "u1", method: "formDialog", args: ["
"] }); + for (const response of [{ value: "opened" }, { confirmed: true }, { cancelled: true }]) { + await assert.rejects( + wrapper.answerExtensionUiRequest("u1", response), + { code: "invalid_dialog_answer" }, + `open_url must refuse ${JSON.stringify(response)}`, + ); + } + assert.deepEqual(sentFrames, [], "pi registers no resolver for open_url: nothing may be sent"); + const replay = []; + wrapper.onEvent((event) => replay.push(event)); + assert.equal(replay[0]?.id, "u1", "a refused answer leaves the request replayable"); + await assert.rejects(wrapper.answerExtensionUiRequest("u1", { value: "opened" }), { code: "invalid_dialog_answer" }, "and it never becomes answered"); + assert.deepEqual(sentFrames, [], "no answer of any kind reaches pi"); +}); + test("native web metadata cannot forge either wire or cached tool snapshot sequencing", async (t) => { const { wrapper, emit } = snapshotSession(t); const events = []; @@ -1505,6 +1717,76 @@ test("a runner dialog answer carries a numeric id; a non-numeric one is refused assert.deepEqual(sentFrames, [{ type: "ui_response", id: 4, value: true }]); }); +test("ask answers are validated against the pending questions before the dialog is consumed", async (t) => { + const { wrapper, emit, sentFrames } = snapshotSession(t); + emit({ + type: "ui_request", id: 42, method: "askDialog", + args: [[ + { id: "q1", question: "Pick one", options: [{ label: "A" }, { label: "B" }] }, + { id: "q2", question: "Pick many", multi: true, options: [{ label: "X" }, { label: "Y" }] }, + ]], + }); + // Each of these is a payload the ask dialog's parser throws on: the + // dialog must stay pending and nothing may reach the child. + const rejected = [ + [[], "no answers for two questions"], + [[{ id: "q1", selectedOptions: ["A"] }], "one answer short"], + [[{ id: "q1", selectedOptions: ["A"] }, { id: "q2", selectedOptions: [] }, { id: "q2", selectedOptions: [] }], "one answer too many"], + [[{ id: "nope", selectedOptions: ["A"] }, { id: "q2", selectedOptions: [] }], "unknown question id"], + [[{ id: "q2", selectedOptions: ["A"] }, { id: "q1", selectedOptions: [] }], "answers out of question order"], + [[{ id: "q1", selectedOptions: ["C"] }, { id: "q2", selectedOptions: [] }], "unknown option label"], + [[{ id: "q1", selectedOptions: ["A", "B"] }, { id: "q2", selectedOptions: [] }], "two labels on a single-select question"], + [[{ id: "q1", selectedOptions: ["A"] }, { id: "q2", selectedOptions: ["X", "X"] }], "the same label twice"], + [[{ id: "q1", selectedOptions: ["A"], customInput: "free" }, { id: "q2", selectedOptions: [] }], "a single-select answer with both a label and free text"], + ]; + for (const [answers, why] of rejected) { + await assert.rejects( + wrapper.send({ type: "ui_response", id: 42, value: { kind: "submit", results: answers } }), + { name: "WebRpcError", code: "invalid_ask_answers" }, + why, + ); + await assert.rejects( + wrapper.answerExtensionUiRequest("42", { answers }), + { name: "WebRpcError", code: "invalid_ask_answers" }, + `notification path: ${why}`, + ); + } + assert.deepEqual(sentFrames, [], "no rejected answer reaches pi"); + const replay = []; + wrapper.onEvent((event) => replay.push(event)); + assert.equal(replay[0]?.method, "askDialog", "every rejection leaves the dialog pending for reconnects"); + + // Valid shapes pi accepts: a label, free text instead of a label, a blank + // customInput (pi trims it away), several labels on a multi-select, and a + // multi-select with no labels at all. + for (const answers of [ + [{ id: "q1", selectedOptions: ["B"] }, { id: "q2", selectedOptions: ["X", "Y"] }], + [{ id: "q1", selectedOptions: [], customInput: "typed instead" }, { id: "q2", selectedOptions: [] }], + [{ id: "q1", selectedOptions: ["A"], customInput: " " }, { id: "q2", selectedOptions: ["Y"], customInput: "and this" }], + ]) { + await wrapper.answerExtensionUiRequest("42", { answers }); + const forwarded = sentFrames.at(-1); + assert.equal(forwarded.type, "ui_response"); + assert.equal(forwarded.id, 42); + assert.equal(forwarded.value.kind, "submit"); + assert.deepEqual(forwarded.value.results.map(({ id, selectedOptions, customInput }) => ({ id, selectedOptions, ...(customInput === undefined ? {} : { customInput }) })), answers); + const afterAnswer = []; + wrapper.onEvent((event) => afterAnswer.push(event)); + assert.deepEqual(afterAnswer, [], "an accepted answer settles the dialog"); + emit({ + type: "ui_request", id: 42, method: "askDialog", + args: [[ + { id: "q1", question: "Pick one", options: [{ label: "A" }, { label: "B" }] }, + { id: "q2", question: "Pick many", multi: true, options: [{ label: "X" }, { label: "Y" }] }, + ]], + }); + } + + // A cancel is still accepted whatever the questions are. + await wrapper.answerExtensionUiRequest("42", { cancelled: true }); + assert.deepEqual(sentFrames.at(-1), { type: "ui_response", id: 42, value: undefined }); +}); + test("answering a dialog in one tab dismisses it in every other attached tab", async (t) => { const { wrapper, emit } = snapshotSession(t); const other = []; @@ -3147,6 +3429,58 @@ test("a resync from the host reconciles the session", async (t) => { assert.equal(session.isRunning(), false); }); +test("a resync forgets a pending dialog without a tombstone that would suppress its replay", async (t) => { + const { messages, restore } = await reachableTab(); + let feed; + let resync; + const piState = { sessionId: "resync-session", sessionFile: "/tmp/resync-session.jsonl", isStreaming: false, isCompacting: false }; + const fakeProc = { + isAlive: true, + // A host-owned child: the daemon owns the lifecycle and replays its open + // requests after a resync, which is the only path that forgets dialogs. + transport: { hostOwnedLifecycle: true, onResync: (listener) => { resync = listener; } }, + waitReady: async () => ({ type: "ready", protocolVersion: 2 }), + negotiateProtocol: async () => {}, + onFrame: (handler) => { feed = handler; return () => {}; }, + sendCommand: async (command) => command.type === "get_state" ? { ...piState } : {}, + sendFrame: () => {}, + dispose: async () => {}, + }; + const wrapper = new SnapshotWrapper(fakeProc, process.cwd(), null, "", undefined, localHost); + wrapper.start(); + await wrapper.waitUntilReady(); + t.after(async () => { + await wrapper.destroyAndWait(); + restore(); + }); + const dismisses = () => messages.filter((message) => message.kind === "dismiss"); + const shown = () => messages.filter((message) => message.kind !== "dismiss"); + const dialog = { type: "ui_request", id: 31, method: "confirm", args: ["Deploy?", ""] }; + + feed(dialog); + assert.equal(shown().length, 1, "the question is announced"); + assert.deepEqual(dismisses(), []); + + // The link dropped buffered output: the dialog is forgotten, and its + // notification is retracted so no tab keeps offering an answer. + const cancelled = []; + wrapper.onEvent((event) => cancelled.push(event)); + // Attaching replays the pending dialog; only what the resync emits matters here. + cancelled.length = 0; + resync(); + assert.deepEqual(dismisses(), [{ kind: "dismiss", tag: "resync-session:input", sessionId: "resync-session", requestId: "31" }]); + assert.deepEqual(cancelled.map(({ type, id }) => ({ type, id })), [ + { type: "ui_end", id: 31 }, + ]); + + // The host replays the same request id: it is pending again, so the question + // is announced again. A permanent tombstone would have suppressed this. + feed(dialog); + assert.equal(shown().length, 2, "a replayed question is announced again"); + assert.equal(await wrapper.answerExtensionUiRequest("31", { confirmed: true }), "answered"); + assert.equal(dismisses().length, 2, "the replayed dialog is answerable and settles normally"); +}); + test("disposing a session whose host goes offline mid-wait returns instead of waiting for the link", async (t) => { const { startRpcSession } = await import("./rpc-manager.ts"); const transport = scriptedTransport("s-bounded"); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 8e7c57b1..6f557e98 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -28,12 +28,14 @@ import { samePath } from "./paths"; import { isRecord } from "./type-guards"; import type { MessageOrigin } from "./message-origin"; import { isClientMessageId, readQueueSnapshot } from "./client-message-ids"; -import { createNotificationDetector } from "./notification-events"; -import { publishNotification } from "./notification-hub"; +import { createNotificationDetector, DIALOG_UI_METHODS, isNotificationAnswerable } from "./notification-events"; +import { publishNotification, publishNotificationDismiss, publishNotificationForgotten } from "./notification-hub"; import { eventWithToolResultImageUrls } from "./media-cache"; import type { BashResultInfo, PiModel, + ExtensionUiResponse, + RpcAskDialogQuestion, RpcAvailableSlashCommand, RpcSessionState, SessionStatsInfo, @@ -138,6 +140,113 @@ export class WebRpcError extends Error { } } +/** Shape check for an ask-dialog `answers` payload. */ +export function isAskAnswers(value: unknown): boolean { + return Array.isArray(value) && value.every((answer: unknown) => + isRecord(answer) + && typeof answer.id === "string" + && Array.isArray(answer.selectedOptions) + && answer.selectedOptions.every((option: unknown) => typeof option === "string") + && (answer.customInput === undefined || typeof answer.customInput === "string")); +} + +/** + * Convert a notification answer to the `ui_response` command the desktop + * dialog sends, checking it against the pending dialog's own arguments. A + * cancel carries no `value` (a missing value is a cancel). + */ +function uiResponseCommand( + pending: { type: string; [key: string]: unknown }, + response: ExtensionUiResponse, +): { type: "ui_response"; id: number | string; value?: unknown } { + const id = pending.id as number | string; + const method = typeof pending.method === "string" ? pending.method : ""; + const args = Array.isArray(pending.args) ? pending.args : []; + if ("cancelled" in response) return { type: "ui_response", id }; + if (method === "askDialog") { + if (!("answers" in response) || !isAskAnswers(response.answers)) { + throw new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers"); + } + const questions = Array.isArray(args[0]) ? args[0] as RpcAskDialogQuestion[] : []; + const problem = askAnswersProblem(response.answers, questions); + if (problem) throw new WebRpcError(`Invalid ask dialog answers: ${problem}`, "invalid_ask_answers"); + return { + type: "ui_response", + id, + value: { + kind: "submit", + results: response.answers.map((answer, index) => { + const question = questions[index]; + return { + id: answer.id, + question: question.question, + options: Array.isArray(question.options) ? question.options.map((option) => option.label) : [], + multi: question.multi === true, + selectedOptions: answer.selectedOptions, + ...(answer.customInput !== undefined ? { customInput: answer.customInput } : {}), + }; + }), + }, + }; + } + if ("answers" in response) throw new WebRpcError("This dialog does not take answers", "invalid_ask_answers"); + if (method === "confirm") { + if (!("confirmed" in response)) throw new WebRpcError("This dialog takes a confirmation", "invalid_dialog_answer"); + return { type: "ui_response", id, value: response.confirmed }; + } + if (method === "select") { + const items = Array.isArray(args[1]) ? args[1] : []; + const labels = items + .map((item) => (typeof item === "string" ? item : isRecord(item) && typeof item.label === "string" ? item.label : undefined)) + .filter((label): label is string => label !== undefined); + if (!("value" in response) || !labels.includes(response.value)) { + throw new WebRpcError("The selected option is not offered by this dialog", "invalid_dialog_answer"); + } + return { type: "ui_response", id, value: response.value }; + } + if (!("value" in response)) throw new WebRpcError("This dialog takes a text answer", "invalid_dialog_answer"); + return { type: "ui_response", id, value: response.value }; +} + +/** + * Why `answers` cannot answer `questions`, or null when they can. Mirrors the ask + * dialog's own parsing, which rejects any mismatch: one + * answer per question in request order, each naming its own question, only + * labels that question offers, no label twice, and a single-select question + * takes either one option or free text, never both. `customInput` is trimmed, so + * blank free text counts as absent. Checking here keeps a rejected payload from + * consuming the pending dialog, which would leave the ask tool failed. + */ +export function askAnswersProblem(answers: unknown, questions: unknown): string | null { + if (!Array.isArray(questions)) return "the pending ask carries no questions"; + if (!Array.isArray(answers)) return "answers must be an array"; + if (answers.length !== questions.length) return `answers must carry ${questions.length} entries in question order`; + for (const [index, raw] of questions.entries()) { + const question = isRecord(raw) ? raw : {}; + const id = typeof question.id === "string" ? question.id : ""; + const answer = answers[index]; + if (!isRecord(answer)) return `answer ${index} must be an object`; + if (answer.id !== id) return `answer ${index} must have id ${JSON.stringify(id)}`; + const options = Array.isArray(question.options) ? question.options : []; + const labels = options.flatMap((option) => (isRecord(option) && typeof option.label === "string" ? [option.label] : [])); + const selected = answer.selectedOptions; + if (!Array.isArray(selected)) return `answer ${JSON.stringify(id)} must carry a selectedOptions array`; + const chosen: string[] = []; + for (const label of selected) { + if (typeof label !== "string" || !labels.includes(label)) return `answer ${JSON.stringify(id)} selected unknown option ${JSON.stringify(label)}`; + if (chosen.includes(label)) return `answer ${JSON.stringify(id)} selected ${JSON.stringify(label)} twice`; + chosen.push(label); + } + const custom = answer.customInput; + if (custom !== undefined && typeof custom !== "string") return `answer ${JSON.stringify(id)} customInput must be a string`; + const text = typeof custom === "string" ? custom.trim() : ""; + if (question.multi !== true && (chosen.length > 1 || (chosen.length > 0 && text !== ""))) { + return `answer ${JSON.stringify(id)} is single-select but carries more than one answer`; + } + } + return null; +} + // Commands forwarded to pi verbatim (request shape already matches rpc-types). const PASSTHROUGH_COMMANDS = new Set([ "abort", @@ -373,6 +482,8 @@ export class AgentSessionWrapper { private listeners: EventListener[] = []; private pendingUiRequests = new Map(); private uiExpiryTimers = new Map>(); + /** Session id each `input` notification was published under, keyed by request id: the wrapper's session id can change before the dialog settles, and the retraction tag must still match. */ + private inputNotificationSessions = new Map(); /** Dialogs tau itself raised (confirmFromServer): answered here, never forwarded to pi. */ private serverUiRequests = new Map void>(); private extensionStatuses = new Map(); @@ -686,7 +797,11 @@ export class AgentSessionWrapper { this.recoveringUpdates = false; for (const [id, event] of [...this.pendingUiRequests]) { if (this.serverUiRequests.has(id)) continue; - this.forgetPendingUiRequest(id); + // The frames that were lost may have answered a dialog, and the replay + // that follows may restore it: forget it now (its notification must not + // keep offering an answer this server no longer holds), but as a + // *forgotten* settlement, so the replayed request is published again. + this.settlePendingUiRequest(id, "forgotten"); this.emit({ type: "ui_end", id: event.id }); } } @@ -900,6 +1015,11 @@ export class AgentSessionWrapper { const notifications = this.detectNotification(frame, session); if (this.hostOwnedLifecycle && !isNotifier(this.host.id)) return; for (const notification of notifications) { + // Remember the id it is published under: a later identity change moves + // `_sessionId`, and the retraction must still name the same tag. + if (notification.type === "input" && notification.requestId) { + this.inputNotificationSessions.set(notification.requestId, notification.sessionId); + } publishNotification(notification); } } @@ -1012,7 +1132,7 @@ export class AgentSessionWrapper { this.trackUiRequest(event); break; case "ui_end": - this.forgetPendingUiRequest(String(event.id)); + this.settlePendingUiRequest(String(event.id)); break; case "ui": this.trackPresentation(event); @@ -1102,8 +1222,9 @@ export class AgentSessionWrapper { notifyRunningChange({ refreshSessionList }); } - /** Forget a pending dialog and its expiry timer. */ + /** Forget a pending dialog, its expiry timer and the id its notification was published under. */ private forgetPendingUiRequest(id: string): void { + this.inputNotificationSessions.delete(id); // An answered or expired dialog no longer waits on the user: the sidebar follows. if (this.pendingUiRequests.delete(id)) notifyRunningChange(); const timer = this.uiExpiryTimers.get(id); @@ -1113,18 +1234,74 @@ export class AgentSessionWrapper { } } + /** + * A pending dialog is settled (answered, cancelled, expired or its child is + * gone): forget it and retract the `input` notification it produced, so no + * other tab or device keeps offering an answer to a question that is gone. + * + * `forgotten` is the same for a dialog this server only *dropped*: a resync + * lost it, and the frames the host replays can restore the very same request + * id. The notification is retracted now (nothing on screen may keep offering + * an answer to a question this server no longer holds), but the retraction is + * temporary, so a replay of that request announces and pushes it again + * instead of being suppressed for the retraction TTL. + */ + private settlePendingUiRequest(id: string, reason: "settled" | "forgotten" = "settled"): boolean { + if (!this.pendingUiRequests.has(id)) return false; + // Read before forgetting: the tag is the one the notification went out with. + const publishedSession = this.inputNotificationSessions.get(id); + this.forgetPendingUiRequest(id); + // One server publishes a notification and its retraction: a former + // notifier must not close what the elected one still owns. + if (publishedSession && (!this.hostOwnedLifecycle || isNotifier(this.host.id))) { + if (reason === "forgotten") publishNotificationForgotten(publishedSession, id); + else publishNotificationDismiss(publishedSession, id); + } + return true; + } + + /** + * Answer a blocking dialog from a notification action. The answer is checked + * against the pending dialog first (a select takes one of its own options, a + * confirm takes a confirmation, an ask takes answers), then it goes through + * the same `ui_response` command the desktop dialog sends: that path resolves + * a server-owned confirm and applies the offline/restarting gate, so an + * answer is never reported when it could not be delivered. + */ + async answerExtensionUiRequest(id: string, response: ExtensionUiResponse): Promise<"answered" | "alreadySettled"> { + const pending = this.pendingUiRequests.get(id); + if (!pending) return "alreadySettled"; + const method = typeof pending.method === "string" ? pending.method : ""; + // Some requests are stored as pending only so they are replayed; pi + // registers no resolver for them, so an "answer" would be dropped there + // while this server reported success and retracted the notification. + if (!DIALOG_UI_METHODS.has(method)) { + throw new WebRpcError("This request does not take an answer", "invalid_dialog_answer"); + } + // Keep the route in step with what the notification promised: a dialog the + // push had to omit (over-long confirm message, ask question or title, an + // oversized payload) is not answerable through the notification route. + if (!isNotificationAnswerable(pending)) { + throw new WebRpcError("This dialog cannot be answered from a notification", "invalid_dialog_answer"); + } + await this.send(uiResponseCommand(pending, response)); + return "answered"; + } + private clearPendingUiRequests(): void { this.dropServerUiRequests(); for (const timer of this.uiExpiryTimers.values()) clearTimeout(timer); this.uiExpiryTimers.clear(); - this.pendingUiRequests.clear(); + // The child is going away (restart, destroy, process exit): every dialog it + // waited on is settled, and its notification must not outlive it. + for (const id of [...this.pendingUiRequests.keys()]) this.settlePendingUiRequest(id); } /** Settle every server dialog as declined and close it in attached tabs. */ private dropServerUiRequests(): void { for (const [id, resolve] of this.serverUiRequests) { this.serverUiRequests.delete(id); - this.forgetPendingUiRequest(id); + this.settlePendingUiRequest(id); this.emit({ type: "ui_end", id }); resolve(false); } @@ -1145,7 +1322,7 @@ export class AgentSessionWrapper { }; const abort = () => { if (!this.serverUiRequests.delete(id)) return; - this.forgetPendingUiRequest(id); + this.settlePendingUiRequest(id); this.emit({ type: "ui_end", id }); finish(false); }; @@ -1168,7 +1345,7 @@ export class AgentSessionWrapper { const timeout = isRecord(options) && typeof options.timeout === "number" ? options.timeout : undefined; if (timeout && timeout > 0) { event.expiresAt = Date.now() + timeout; - const timer = setTimeout(() => this.forgetPendingUiRequest(id), timeout); + const timer = setTimeout(() => this.settlePendingUiRequest(id), timeout); timer.unref?.(); this.uiExpiryTimers.set(id, timer); } @@ -1491,7 +1668,7 @@ export class AgentSessionWrapper { for (const [id, event] of this.pendingUiRequests) { const expiresAt = event.expiresAt as number | undefined; if (expiresAt !== undefined && expiresAt <= now) { - this.forgetPendingUiRequest(id); + this.settlePendingUiRequest(id); continue; } listener({ ...event, web: { streamId: this.streamId, sequence: ++this.streamSequence } }); @@ -2379,13 +2556,21 @@ export class AgentSessionWrapper { // The runner numbers its dialogs and ignores any other id; only tau's own confirms keep string ids. const runnerId = serverRequest ? undefined : /^\d+$/.test(key) ? Number(key) : NaN; if (runnerId !== undefined && !Number.isSafeInteger(runnerId)) throw new WebRpcError("Invalid dialog id", "invalid_ui_response"); - const method = this.pendingUiRequests.get(key)?.method; + const pending = this.pendingUiRequests.get(key); + const method = pending?.method; // A malformed answer would drop the dialog from reconnect replay while pi rejects it. if (value !== undefined && method === "askDialog" && !isRecord(value)) { throw new WebRpcError("Invalid dialog answer", "invalid_ui_response"); } - const wasPending = this.pendingUiRequests.has(key); - this.forgetPendingUiRequest(key); + // The ask dialog parses the submitted results exactly: one answer per + // question, only offered labels, no duplicate on a single-select. Refuse + // a payload it would reject before the dialog is consumed. + if (value !== undefined && method === "askDialog" && isRecord(value) && value.kind === "submit") { + const questions = pending && Array.isArray(pending.args) ? (pending.args as unknown[])[0] : undefined; + const problem = askAnswersProblem(value.results, questions); + if (problem) throw new WebRpcError(`Invalid ask dialog answers: ${problem}`, "invalid_ask_answers"); + } + const wasPending = this.settlePendingUiRequest(key); if (serverRequest) { this.serverUiRequests.delete(key); serverRequest(value === true); diff --git a/public/sw.js b/public/sw.js index 0163db15..990f9994 100644 --- a/public/sw.js +++ b/public/sw.js @@ -15,6 +15,9 @@ self.addEventListener("push", (event) => { } catch { // Unreadable payload: still show something (iOS revokes silent pushes). } + const requestId = typeof data.requestId === "string" + ? data.requestId + : typeof data.dialog?.requestId === "string" ? data.dialog.requestId : ""; const shown = { type: data.type === "error" ? "error" : "info", title: data.title || "tau", @@ -30,7 +33,7 @@ self.addEventListener("push", (event) => { badge: "/badge-96.png", tag: shown.tag || undefined, renotify: Boolean(shown.tag), - data: { url: data.url || "/", sessionId: shown.sessionId }, + data: { url: data.url || "/", sessionId: shown.sessionId, ...(requestId ? { requestId } : {}) }, }); // Open tabs list it in their Notifications tab, like a notification the page showed itself. const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true }); diff --git a/server/routes.ts b/server/routes.ts index e30711d9..eaab5986 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -38,6 +38,7 @@ import * as modelsConfigCatalog from "@/app/api/models-config/catalog/route"; import * as modelsConfig from "@/app/api/models-config/route"; import * as modelsConfigTest from "@/app/api/models-config/test/route"; import * as models from "@/app/api/models/route"; +import * as notificationsAnswer from "@/app/api/notifications/answer/route"; import * as notificationsDevices from "@/app/api/notifications/devices/route"; import * as notificationsHistory from "@/app/api/notifications/history/route"; import * as notificationsPresence from "@/app/api/notifications/presence/route"; @@ -136,6 +137,7 @@ export const ROUTE_MODULES: Record = { "models-config": modelsConfig, "models-config/test": modelsConfigTest, "models": models, + "notifications/answer": notificationsAnswer, "notifications/devices": notificationsDevices, "notifications/history": notificationsHistory, "notifications/presence": notificationsPresence, From ee5dad881c3a32b8f5f830d809251905eaa29a2c Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:47:41 +0000 Subject: [PATCH 17/45] perf(events): hold tool snapshots to one frame per second Port of ompweb-dev/ompweb#418. --- AGENTS.md | 1 + hooks/useAgentSession-sync.test.mjs | 31 +++ lib/event-stream-hub.test.mjs | 374 ++++++++++++++++++++++++++++ lib/event-stream-hub.ts | 264 +++++++++++++++++--- 4 files changed, 632 insertions(+), 38 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 65b68791..c4f0f455 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -437,6 +437,7 @@ pi's wire `message_update` is delta-only (pi `docs/json.md`): `usage` and `assis - `lib/event-stream-worker.ts` (SharedWorker; dedicated Worker where SharedWorker is missing) holds the browser's one `/api/events` EventSource and multiplexes every tab's subscriptions: frames arrive as `event: `, control frames as `event: mux` (`hello`/`open`/`end`); subscriptions are attached with `POST /api/events`. Tabs POST their agent commands and uploads themselves. `buildEventStreamWorker` bundles it into `dist/event-stream-worker.js`, whose URL carries the content hash. - Tabs use `openEventStream(channel)` (`lib/event-stream.ts`) with EventSource semantics: `onerror` + CONNECTING = reconnecting, CLOSED = fatal (e.g. 409 for a wrapper-less session). Dead tabs are detected with a lifetime Web Lock. - Channels (`event-stream-hub.ts`): `running` (badges + list hints), `notifications` (one tab's, by `clientId`), `hosts` (the `GET /api/hosts` body), `host-tools` (cross-session `open_url`/`notify`/`open_file`), `session` (observer-only, never spawns pi; merges `message_update`s under backpressure), `file` (viewer watch, same allow-list as `/api/files`). A failing frame ends only its own subscription. Split channels by consumer, lifetime, key and access check; `notifications` and `host-tools` are subscribed from `AppShell`. +- **Tool snapshots** (`event-stream-hub.ts`, session channel): pi sends the whole accumulated output on every `tool_execution_update`, so the newest snapshot per `toolCallId` is held outside the ordered message queue and written at most once per `TOOL_UPDATE_FRAME_MIN_INTERVAL_MS` of that tool. Any other session frame is a boundary that releases every held snapshot ahead of itself in emission order, so nothing is dropped or reordered within a domain; across domains an older sequence may arrive later, which the browser's separate floors (`hooks/useAgentSession-sync.ts`) allow. A written snapshot is stamped with its write time. - **Native-client handshake and keep-alive.** `GET /api/app-info` (behind the `/api` gate, `no-store`) answers `{ name, version, api: 1, capabilities }`: package identity and which server-side features exist, never a credential or setting. A capability is added only with its implementation; today it carries `heartbeatParam`. `GET /api/events?heartbeat=` sets that connection's keep-alive comment frame: an integer in 15..110, anything else the 30 s default (not clamped). A value above the reverse proxy's read timeout (nginx: 60 s) drops an idle stream before its first keep-alive. - **Metrics.** Tabs and the worker record `action`, `event`, `reconnect`, `hang` and `dropped` samples; the worker POSTs them to `/api/transport-metrics` every 30 s or 200 samples. One worker-wide clock (lowest RTT of recent probes) times them. - **Connection tab** (right panel, while "Show connection diagnostics" is on, `tau:connection-diagnostics`): polls the worker (`diag`) once a second; status, last reconnect and per-transport stats (`lib/transport-stats.ts`) over the last 30 min. Command rows include confirmed replies only; app ↔ pi rows skip commands the web app answers itself (`NO_SPAWN_REPLIES` and friends). diff --git a/hooks/useAgentSession-sync.test.mjs b/hooks/useAgentSession-sync.test.mjs index f967b1ca..2ba06e6e 100644 --- a/hooks/useAgentSession-sync.test.mjs +++ b/hooks/useAgentSession-sync.test.mjs @@ -149,6 +149,37 @@ test("a snapshot no field takes still completes deltas that arrived without thei assert.equal(pipe.shown.at(-1), "abcd"); }); +test("a tool snapshot older than a newer message delta is accepted, not stale", () => { + // Tool frames are fenced per tool and by the lifecycle/tool-snapshot floors, + // never by messageSequence: the catch-up sequence domains are separate. A + // mutation that adds messageSequence to the tool floor rejects tool@2 here. + const catchUp = createSessionCatchUp({ sessionId: () => "s1", scope: () => "run", history() {}, subscribe: () => false, live() {} }); + catchUp.observe({ type: "connected", web: { streamId: "s", sequence: 0 } }); + assert.equal( + catchUp.observe({ + type: "message_update", messageId: "m1", message: { role: "assistant" }, + assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "x" }, web: { streamId: "s", sequence: 3 }, + }), + null, + "the message delta at 3 is applied", + ); + assert.equal( + catchUp.observe({ type: "tool_execution_update", toolCallId: "t1", web: { streamId: "s", sequence: 2 } }), + null, + "tool@2 is accepted after message-delta@3: tool and message floors are separate", + ); + assert.equal( + catchUp.observe({ type: "tool_execution_update", toolCallId: "t1", web: { streamId: "s", sequence: 1 } }), + "stale", + "per-tool monotonicity still rejects an older snapshot of the same tool", + ); + assert.equal( + catchUp.observe({ type: "tool_execution_update", toolCallId: "t2", web: { streamId: "s", sequence: 1 } }), + null, + "another tool has its own floor", + ); +}); + // Base-less deltas through the coalescer into catch-up, reads failing at once, on a clock the test moves (performance.now and timers). function missingBasePipeline(t) { t.mock.timers.enable({ apis: ["setTimeout"] }); diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index e2da48ac..a6d06360 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -861,6 +861,94 @@ test("a sink connection writes name/at/data, coalesces while backpressured and f } }); +test("a boundary frame written to a peer that pulls synchronously is not written twice", async () => { + // An SSE consumer that is ready when the frame is handed over pulls inside + // `write`, which re-enters the drain while the frame is still in flight. A + // boundary frame (`tool_execution_end`, `message_end`) must reach the peer once. + const writes = []; + let connection; + let resuming = false; + const sink = { + heartbeatMs: 60_000, + write(name, at, data) { + writes.push({ name, data: JSON.parse(data) }); + // One pull per write, like a reader that is ready for each enqueue: do not + // recurse through the writes this pull itself causes. + if (!resuming) { + resuming = true; + try { connection?.resume(); } finally { resuming = false; } + } + return true; + }, + backpressured: () => false, + heartbeat: () => true, + close() {}, + }; + const session = emitterSession(); + const release = withSession("sync-pull-sess", session); + connection = new EventStreamConnection(undefined, sink); + try { + assert.deepEqual(await connection.subscribe("s1", { kind: "session", sessionId: "sync-pull-sess" }), { ok: true }); + writes.length = 0; + session.emit({ type: "tool_execution_start", toolCallId: "t1", toolName: "bash", args: { command: "make" } }); + session.emit({ type: "tool_execution_end", toolCallId: "t1", toolName: "bash", result: { content: [] }, isError: false }); + assert.deepEqual(writes.map(({ name, data }) => [name, data.type, data.toolCallId ?? null]), [ + ["s1", "tool_execution_start", "t1"], + ["s1", "tool_execution_end", "t1"], + ]); + } finally { + connection.close(); + release(); + } +}); + +test("two held snapshots released in one drain are written once and in emit order when the peer pulls", async (t) => { + // The timer drain releases both open windows in one pass. A sink write that + // re-enters resume() drains the second one first; iterating the stale entry + // list would then write that frame again. The release loop must stop at the + // live map's current value. + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const writes = []; + let connection; + let resuming = false; + const sink = { + heartbeatMs: 60_000, + write(name, at, data) { + writes.push({ name, data: JSON.parse(data) }); + if (!resuming) { + resuming = true; + try { connection?.resume(); } finally { resuming = false; } + } + return true; + }, + backpressured: () => false, + heartbeat: () => true, + close() {}, + }; + const session = emitterSession(); + const release = withSession("sync-pull-release", session); + connection = new EventStreamConnection(undefined, sink); + try { + assert.deepEqual(await connection.subscribe("s1", { kind: "session", sessionId: "sync-pull-release" }), { ok: true }); + writes.length = 0; + // Prime both windows, then let both next snapshots wait for the same timer. + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v1" }); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "t2-v1" }); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v2" }); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "t2-v2" }); + assert.deepEqual(writes.map(({ data }) => data.output), ["t1-v1", "t2-v1"], "both later snapshots are held"); + t.mock.timers.tick(1000); + assert.deepEqual( + writes.map(({ data }) => data.output), + ["t1-v1", "t2-v1", "t1-v2", "t2-v2"], + "one drain releases both held snapshots exactly once, in emit order", + ); + } finally { + connection.close(); + release(); + } +}); + test("a sink that refuses a write closes the connection", async () => { let closed = 0; const sink = { heartbeatMs: 1000, write: () => false, backpressured: () => false, heartbeat: () => true, close() { closed += 1; } }; @@ -943,6 +1031,243 @@ test("while the peer is behind, a whole message replaces the queued updates of t } }); +test("tool snapshots are throttled to one per second and boundary frames flush the latest first", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-throttle"); + try { + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "a" }); + assert.deepEqual(writes.map(({ data }) => data.output), ["a"], "the first snapshot is written at once"); + + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "ab" }); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "abc" }); + assert.equal(writes.length, 1, "snapshots inside the window are held, newest wins"); + + t.mock.timers.tick(999); + assert.equal(writes.length, 1); + t.mock.timers.tick(1); + assert.deepEqual(writes.map(({ data }) => data.output), ["a", "abc"], "the window releases only the newest snapshot"); + + // A boundary frame right after a held snapshot flushes that snapshot first. + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "abcd" }); + session.emit({ type: "tool_execution_end", toolCallId: "t1", output: "abcd" }); + assert.deepEqual( + writes.slice(2).map(({ data }) => data.type), + ["tool_execution_update", "tool_execution_end"], + "the held snapshot precedes the end frame", + ); + assert.equal(writes[2].data.output, "abcd"); + } finally { + done(); + } +}); + +test("a tool snapshot is stamped with its write time, not the time it was held", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-stamp"); + try { + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "first" }); + assert.equal(writes[0].at, 1_000_000); + t.mock.timers.tick(400); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "held" }); + t.mock.timers.tick(600); + assert.equal(writes.length, 2, "the window released the held snapshot"); + assert.equal(writes[1].at, 1_001_000, "the stamp is the write time, so the deliberate hold is not reported as latency"); + } finally { + done(); + } +}); + +test("concurrent tools hold their newest snapshot independently and never supersede each other", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-concurrent"); + try { + // The maintainer's probe: t1-v1, t1-v2 and t2-v1 inside one window. + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v1" }); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v2" }); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "t2-v1" }); + assert.deepEqual( + writes.map(({ data }) => data.output), + ["t1-v1", "t2-v1"], + "t2's first snapshot is not delayed by t1's window: it has no window of its own yet", + ); + + t.mock.timers.tick(1_000); + assert.deepEqual( + writes.map(({ data }) => data.output), + ["t1-v1", "t2-v1", "t1-v2"], + "the held newest snapshot of t1 releases when its window opens", + ); + + // A later window: t1 is slow, t2 is fast. t2 must keep flowing. + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v3" }); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "t2-v2" }); + t.mock.timers.tick(1_000); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "t2-v3" }); + t.mock.timers.tick(1_000); + assert.deepEqual( + writes.map(({ data }) => data.output), + ["t1-v1", "t2-v1", "t1-v2", "t2-v2", "t1-v3", "t2-v3"], + "a slow tool's window never holds back another tool's snapshots", + ); + } finally { + done(); + } +}); + +/** A tool snapshot carrying the stream metadata the browser uses as a cursor. */ +const toolFrame = (toolCallId, sequence, output) => ({ + type: "tool_execution_update", toolCallId, output, web: { streamId: "s", sequence }, +}); + +test("a superseding tool snapshot is held outside the message queue, so the cursor never goes backwards", async () => { + const { sink, session, connection, writes, done } = await sinkSubscription("tool-supersede-cross"); + try { + // The maintainer's probe: t1@1, t2@2, newer t1@3, all while the peer is behind. + sink.behind = true; + session.emit(toolFrame("t1", 1, "t1-v1")); + session.emit(toolFrame("t2", 2, "t2-v1")); + session.emit(toolFrame("t1", 3, "t1-v3")); + assert.deepEqual(writes, [], "nothing is written while the peer is behind"); + sink.behind = false; + connection.resume(); + assert.deepEqual( + writes.map(({ data }) => data.web.sequence), + [2, 3], + "t2's first snapshot and t1's newest are written in sequence order", + ); + assert.deepEqual(writes.map(({ data }) => data.output), ["t2-v1", "t1-v3"]); + } finally { + done(); + } +}); + +test("a superseding tool snapshot never overtakes a message delta emitted before it", async () => { + const { sink, session, connection, writes, done } = await sinkSubscription("tool-supersede-delta"); + try { + sink.behind = true; + session.emit(toolFrame("t1", 1, "t1-v1")); + session.emit(deltaFrame(2, "text_delta", 0, { delta: "D2" })); + session.emit(toolFrame("t1", 3, "t1-v3")); + assert.deepEqual(writes, []); + sink.behind = false; + connection.resume(); + assert.deepEqual( + writes.map(({ data }) => data.web.sequence), + [2, 3], + "the delta emitted before the replacement keeps its place ahead of it", + ); + assert.deepEqual( + writes.map(({ data }) => [data.type, data.assistantMessageEvent?.delta ?? data.output]), + [["message_update", "D2"], ["tool_execution_update", "t1-v3"]], + ); + } finally { + done(); + } +}); + +test("a held tool snapshot is not lost when a boundary frame ends its tool", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-end-order"); + try { + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "a" }); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "ab" }); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "b" }); + session.emit({ type: "tool_execution_end", toolCallId: "t1", output: "ab" }); + assert.deepEqual( + writes.map(({ data }) => [data.type, data.output]), + [["tool_execution_update", "a"], ["tool_execution_update", "b"], ["tool_execution_update", "ab"], ["tool_execution_end", "ab"]], + "the held snapshot of t1 precedes the end frame that ends it", + ); + } finally { + done(); + } +}); + +test("message deltas are never throttled while a tool snapshot is held", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-delta-order"); + try { + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "first" }); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "held" }); + assert.equal(writes.length, 1); + + session.emit(deltaFrame(1, "text_delta", 0, { delta: "hi" })); + assert.deepEqual( + writes.slice(1).map(({ data }) => data.type), + ["message_update"], + "a delta is written at once and never releases the held snapshot", + ); + assert.equal(writes[1].data.assistantMessageEvent.delta, "hi"); + assert.equal(writes.length, 2, "the held snapshot is still waiting for its window"); + } finally { + done(); + } +}); + +test("a queued message delta is written before a held tool snapshot (emission order)", { timeout: 5000 }, async () => { + const { sink, session, connection, writes, done } = await sinkSubscription("tool-delta-behind"); + try { + sink.behind = true; + session.emit(deltaFrame(1, "text_delta", 0, { delta: "first" })); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "second" }); + assert.deepEqual(writes, []); + sink.behind = false; + connection.resume(); + assert.deepEqual( + writes.map(({ data }) => [data.type, data.assistantMessageEvent?.delta ?? data.output]), + [["message_update", "first"], ["tool_execution_update", "second"]], + "the older queued delta must precede the held tool snapshot", + ); + } finally { + done(); + } +}); + +test("a backpressured delta, tool snapshot and end frame reach the wire in emission order", { timeout: 5000 }, async () => { + const { sink, session, connection, writes, done } = await sinkSubscription("tool-delta-backpressure"); + try { + // The maintainer's probe: D1, T, END emitted while the sink is behind. + sink.behind = true; + session.emit(deltaFrame(1, "text_delta", 0, { delta: "D1" })); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "T" }); + session.emit({ type: "tool_execution_end", toolCallId: "t1", output: "T" }); + assert.deepEqual( + writes.map(({ data }) => [data.type, data.assistantMessageEvent?.delta ?? data.output]), + [["message_update", "D1"], ["tool_execution_update", "T"], ["tool_execution_end", "T"]], + "the drain preserves emission order; the tool update never jumps ahead of the older delta", + ); + sink.behind = false; + connection.resume(); + assert.equal(writes.length, 3, "nothing is written twice"); + } finally { + done(); + } +}); + +test("a heartbeat never writes a held tool snapshot around queued message deltas", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setInterval", "Date"], now: 1_000_000 }); + const { sink, session, connection, writes, done } = await sinkSubscription("tool-heartbeat-order"); + try { + sink.behind = true; + session.emit(deltaFrame(1, "text_delta", 0, { delta: "D1" })); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "T" }); + assert.deepEqual(writes, [], "both wait while the peer is behind"); + // The heartbeat force-flushes; it must not write the held snapshot ahead of + // the older delta that the sink cannot take yet. + t.mock.timers.tick(60_000); + assert.deepEqual(writes, [], "the heartbeat writes nothing while the peer is behind"); + sink.behind = false; + connection.resume(); + assert.deepEqual( + writes.map(({ data }) => [data.type, data.assistantMessageEvent?.delta ?? data.output]), + [["message_update", "D1"], ["tool_execution_update", "T"]], + "the delta precedes the tool snapshot emitted after it", + ); + } finally { + done(); + } +}); + test("outbox snapshots wait through backpressured heartbeats and resumes, keeping the latest settled ids", async (t) => { t.mock.timers.enable({ apis: ["setInterval", "Date"], now: 1_000_000 }); const { sink, session, connection, writes, done } = await sinkSubscription("outbox-heartbeat"); @@ -1106,3 +1431,52 @@ test("the connection's keep-alive timer fires at the requested interval, never e await reader.cancel(); } }); + +test("the per-tool cap holds while message deltas stream: a delta neither waits for nor releases a held snapshot", { timeout: 5000 }, async (t) => { + // The regression the earlier design could not see: `release` mode ignored the + // throttle window, so every delta flushed the held snapshot. A bash tool that + // prints while the model streams text (the normal case) got one snapshot per + // delta, i.e. no cap at all. + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-cap-under-deltas"); + try { + for (let i = 0; i < 10; i += 1) { + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: `v${i}` }); + session.emit(deltaFrame(i + 1, "text_delta", 0, { delta: `d${i}` })); + t.mock.timers.tick(100); + } + const snapshots = writes.filter(({ data }) => data.type === "tool_execution_update"); + const deltas = writes.filter(({ data }) => data.type === "message_update"); + assert.equal(deltas.length, 10, "every delta is written at once: they are not throttled"); + assert.ok( + snapshots.length <= 2, + `at most one snapshot per second despite 10 deltas (got ${snapshots.length})`, + ); + assert.deepEqual(snapshots.map(({ data }) => data.output), ["v0", "v9"], "the newest snapshot is the one that survives"); + } finally { + done(); + } +}); + +test("one tool's closed window never delays another tool's first snapshot", { timeout: 5000 }, async (t) => { + // The other half of the same contract: the hold lives outside the ordered + // message queue, so a tool that has never been written has no window to wait + // for and must not sit behind an older tool's held snapshot. + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-no-cross-delay"); + try { + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v1" }); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v2" }); + t.mock.timers.tick(400); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "t2-v1" }); + assert.deepEqual( + writes.map(({ data }) => data.output), + ["t1-v1", "t2-v1"], + "t2's first snapshot is written at once, 400 ms after t1's held one", + ); + t.mock.timers.tick(600); + assert.deepEqual(writes.map(({ data }) => data.output), ["t1-v1", "t2-v1", "t1-v2"]); + } finally { + done(); + } +}); diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index ffacb7d7..b117869e 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -45,14 +45,57 @@ export type SubscribeResult = const SUBSCRIBED: SubscribeResult = { ok: true }; +/** + * The floor between two `tool_execution_update` snapshots of one tool in one + * session subscription. pi sends the accumulated tool output on every update, + * so a bash run printing megabytes would otherwise forward the whole buffer + * many times per second. Each frame is a self-contained snapshot of one + * `toolCallId`, so holding the newest one per tool is lossless and concurrent + * tools never supersede each other; a boundary frame (`tool_execution_end`, + * `message_end`, …) always flushes them first, in emission order, so the final + * output is never delayed. Message deltas are not throttled: they are + * incremental since the delta protocol, and — because a held snapshot is not in + * the message queue — they neither wait for one nor release one. + */ +export const TOOL_UPDATE_FRAME_MIN_INTERVAL_MS = 1_000; + class Subscription { active = true; detach: (() => void) | null = null; - // Session backpressure queue: message updates merge and consecutive outbox - // snapshots replace each other. Other frames flush it first to preserve order. - pendingUpdates: QueuedUpdate[] = []; - - constructor(readonly id: string, readonly coalescesMessageUpdates: boolean) {} + // Message and outbox updates plus boundary frames, in emission order: message + // updates merge and consecutive outbox snapshots replace each other. Tool + // snapshots are held OUTSIDE this queue (see `heldToolUpdates`), so a held + // snapshot can neither delay a queued frame nor be released by one. + pendingUpdates: QueuedFrame[] = []; + /** + * The newest snapshot of each tool, keyed by `toolCallId`, held until its + * window opens. It needs no position among the message frames: the browser + * fences a tool frame by the tool and lifecycle sequences, never by the + * message sequence (`hooks/useAgentSession-sync.ts`). `seq` is the emission + * counter of the frame it holds, so a boundary flush can merge it back into + * the queue in the order it was emitted. + */ + heldToolUpdates = new Map(); + /** When the last snapshot of each tool was written (absent = never written). */ + lastToolUpdateAt = new Map(); + /** Monotonic emission counter: orders held snapshots against queued frames. */ + emitCount = 0; + /** The one timer that releases held frames once their window elapsed. */ + drainTimer: NodeJS.Timeout | undefined = undefined; + /** Deadline of `drainTimer`; a newer frame may pull it forward. */ + drainAt = 0; + + constructor(readonly id: string, readonly throttlesAgentUpdates: boolean) {} + + /** Drop held frames and their timer (unsubscribe, end, close). */ + clearUpdates(): void { + this.pendingUpdates = []; + this.heldToolUpdates.clear(); + this.lastToolUpdateAt.clear(); + clearTimeout(this.drainTimer); + this.drainTimer = undefined; + this.drainAt = 0; + } } /** What a channel opener may do with its subscription. */ @@ -234,7 +277,7 @@ export class EventStreamConnection { private release(subscription: Subscription): void { subscription.active = false; - subscription.pendingUpdates = []; + subscription.clearUpdates(); const detach = subscription.detach; subscription.detach = null; runDetach(detach); @@ -271,47 +314,190 @@ export class EventStreamConnection { return this.write(subscription.id, text, at); } - private flush(subscription: Subscription, force = false): boolean { - if (!force && this.sink.backpressured()) return true; - const queued = subscription.pendingUpdates; + /** The peer drained: deliver queued frames now rather than waiting for the next event or heartbeat. */ + resume(): void { + this.flushAll(); + } + + private flushAll(): boolean { + for (const subscription of this.subscriptions.values()) { + if (!this.drainAndReschedule(subscription)) return false; + } + return !this.closed; + } + + /** + * Write the message/outbox queue in emission order, then release every held + * tool snapshot whose window has opened. A held snapshot never blocks a + * queued frame and a queued frame never releases a held snapshot: the two are + * independent, which is what makes the throttle hold under a streaming turn + * (deltas arrive constantly) and keeps one tool's window from delaying + * another tool's snapshot. + * + * `force` (a boundary frame is waiting) writes the queued frames without + * regard to backpressure, because the frame that follows must not be delayed; + * a boundary flush merges the held snapshots into the queue first, in + * emission order, so the end frame never overtakes the output it ends. The + * heartbeat retries through the non-force path, so it never overrides + * backpressure; a snapshot released by its own window is written only while + * the sink has capacity. + * + * A tool snapshot is stamped with the time it is actually written, not the + * time it was emitted: the deliberate hold must not read as network latency. + */ + private drain(subscription: Subscription, force = false): boolean { + // A stamp whose window elapsed is useless: a later snapshot is writable at once. + for (const [toolCallId, at] of subscription.lastToolUpdateAt) { + if (Date.now() - at >= TOOL_UPDATE_FRAME_MIN_INTERVAL_MS) subscription.lastToolUpdateAt.delete(toolCallId); + } + // Detach the queue before writing: `writeFrame` can release the peer + // synchronously (a stream pull calls `resume()`, which drains every + // subscription), and that re-entrant drain must see an empty queue rather + // than write the frames this loop still holds a second time. + const queue = subscription.pendingUpdates; subscription.pendingUpdates = []; - for (let i = 0; i < queued.length; i++) { - if (!force && this.sink.backpressured()) { - subscription.pendingUpdates = queued.slice(i); - return true; - } - const { data, at } = queued[i]; - if (!this.writeFrame(subscription, data, at)) return false; + let written = 0; + while (written < queue.length) { + if (!force && this.sink.backpressured()) break; + const frame = queue[written]; + written += 1; + if (!this.writeFrame(subscription, frame.data, frame.tool ? Date.now() : frame.at)) return !this.closed; + } + // Frames appended while writing stay behind the ones still to write. + if (written < queue.length) subscription.pendingUpdates = queue.slice(written).concat(subscription.pendingUpdates); + if (this.sink.backpressured()) return !this.closed; + // Release what the windows allow. Ordering is required per tool, not across + // tools: two independent tools may be written in either order, so the emit + // order here is deterministic, not a consumer dependency. + const releasable = [...subscription.heldToolUpdates.entries()] + .filter(([toolCallId]) => Date.now() >= (subscription.lastToolUpdateAt.get(toolCallId) ?? 0) + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS) + .sort(([, a], [, b]) => a.seq - b.seq); + for (const [toolCallId, held] of releasable) { + // A sink whose write re-enters `drain()` may already have released and + // written this entry from the live map: stop at the current value, never + // write a stale iteration snapshot a second time. + if (subscription.heldToolUpdates.get(toolCallId) !== held) continue; + subscription.heldToolUpdates.delete(toolCallId); + const stamp = Date.now(); + subscription.lastToolUpdateAt.set(toolCallId, stamp); + if (!this.writeFrame(subscription, held.data, stamp)) return !this.closed; + } + return !this.closed; + } + + /** Drain what is ready, then arm the one timer for the next held snapshot. */ + private drainAndReschedule(subscription: Subscription, force = false): boolean { + if (!this.drain(subscription, force)) return false; + if (!subscription.active || this.closed) return !this.closed; + if (subscription.heldToolUpdates.size === 0) { + clearTimeout(subscription.drainTimer); + subscription.drainTimer = undefined; + subscription.drainAt = 0; + return true; } + // The sink's owner calls `resume()` once it has capacity again, and the + // heartbeat retries: a timer here would only spin while the peer is behind. + if (this.sink.backpressured()) return true; + let earliest = Infinity; + for (const toolCallId of subscription.heldToolUpdates.keys()) { + const at = subscription.lastToolUpdateAt.get(toolCallId) ?? 0; + earliest = Math.min(earliest, at + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS); + } + this.scheduleDrain(subscription, Math.max(earliest - Date.now(), 1)); return true; } - /** The peer drained: deliver coalesced updates now rather than waiting for the next event or heartbeat. */ - resume(): void { - this.flushAll(); + /** + * Arm the timer that releases held frames. A newer frame only pulls the + * deadline forward, never pushes it back. + */ + private scheduleDrain(subscription: Subscription, delayMs: number): void { + if (!subscription.active || this.closed) return; + const deadline = Date.now() + delayMs; + if (subscription.drainTimer !== undefined && subscription.drainAt <= deadline) return; + clearTimeout(subscription.drainTimer); + subscription.drainAt = deadline; + subscription.drainTimer = setTimeout(() => { + subscription.drainTimer = undefined; + subscription.drainAt = 0; + if (!subscription.active || this.closed) return; + this.drainAndReschedule(subscription); + }, delayMs); + // A throttle window must not keep the process alive. + subscription.drainTimer.unref?.(); } - private flushAll(): boolean { - for (const subscription of this.subscriptions.values()) this.flush(subscription); - return !this.closed; + /** + * Move every held snapshot into the message queue, in the order it was + * emitted. Used when a boundary frame arrives: it must not overtake output + * that was emitted before it, and the queue is the one place a drain writes + * in order. + */ + private releaseHeldToolUpdates(subscription: Subscription): void { + if (subscription.heldToolUpdates.size === 0) return; + const held = [...subscription.heldToolUpdates.entries()].sort(([, a], [, b]) => a.seq - b.seq); + subscription.heldToolUpdates.clear(); + for (const [toolCallId, update] of held) { + // `tool: true` makes the drain stamp the write time, not this release time. + subscription.pendingUpdates.push({ data: update.data, at: Date.now(), tool: true }); + subscription.lastToolUpdateAt.set(toolCallId, Date.now()); + } } private deliver(subscription: Subscription, data: unknown): void { if (!subscription.active || this.closed) return; - if ( - subscription.coalescesMessageUpdates - && isRecord(data) - && (data.type === "outbox_update" || (data.type === "message_update" && this.sink.backpressured())) - ) { - queueUpdate(subscription.pendingUpdates, data, Date.now()); - if (data.type === "outbox_update") this.flush(subscription); + // Other channels never queue: their frames are neither throttled nor merged. + if (!subscription.throttlesAgentUpdates) { + this.writeFrame(subscription, data); return; } - if (this.flush(subscription, true)) this.writeFrame(subscription, data); + if (isRecord(data)) { + if (data.type === "tool_execution_update" && typeof data.toolCallId === "string" && data.toolCallId) { + // Held outside the message queue: the browser fences a tool frame by + // its tool/lifecycle sequences, never by `messageSequence`, so it needs + // no position among the deltas. The newest snapshot per tool wins. + subscription.heldToolUpdates.set(data.toolCallId, { data, seq: ++subscription.emitCount }); + this.drainAndReschedule(subscription); + return; + } + if (data.type === "outbox_update" || data.type === "message_update") { + // Nothing waits: the frame goes out at once, and it never releases a + // held tool snapshot (that would defeat the throttle). + if (subscription.pendingUpdates.length === 0 && subscription.heldToolUpdates.size === 0 && !this.sink.backpressured()) { + this.writeFrame(subscription, data); + return; + } + queueUpdate(subscription.pendingUpdates, data, Date.now()); + this.drainAndReschedule(subscription); + return; + } + } + // Every other frame is a boundary (`tool_execution_end`, `message_end`, …): + // everything emitted before it must reach the client first, in order. The + // held snapshots were emitted before it too, so they join the queue ahead + // of it — in their own emission order — and the forced drain writes all of + // it without regard to backpressure. + this.releaseHeldToolUpdates(subscription); + subscription.pendingUpdates.push({ data, at: Date.now() }); + this.drainAndReschedule(subscription, true); } } -type QueuedUpdate = { data: Record; at: number }; +/** + * One queued frame. `at` is the emit time, so the stamp keeps measuring + * server-to-peer delay — except for a tool snapshot released by a boundary + * frame, which is stamped when it is written (`tool`): the deliberate hold must + * not read as network latency in Connection diagnostics. + */ +type QueuedFrame = { data: unknown; at: number; tool?: boolean }; + +/** + * The newest snapshot of one tool, held until its window opens. Each frame + * carries the tool's whole accumulated output, so a newer snapshot supersedes + * the held one losslessly. `seq` orders it against the other held snapshots + * when a boundary frame flushes them all. + */ +type HeldToolUpdate = { data: Record; seq: number }; /** * Merge a `message_update` into a backpressure queue without losing anything: @@ -323,10 +509,11 @@ type QueuedUpdate = { data: Record; at: number }; * joining a delta to an earlier entry would put it before frames it follows * and break the sequence fence the browser relies on. */ -function queueUpdate(queue: QueuedUpdate[], data: Record, at: number): void { +function queueUpdate(queue: QueuedFrame[], data: Record, at: number): void { + const last = queue.at(-1); + const lastData = last && isRecord(last.data) ? last.data : null; if (data.type === "outbox_update") { - const last = queue.at(-1); - if (last?.data.type === "outbox_update") { + if (last && lastData?.type === "outbox_update") { last.data = data; last.at = at; } else { @@ -336,14 +523,15 @@ function queueUpdate(queue: QueuedUpdate[], data: Record, at: n } if (!isDeltaUpdate(data)) { for (let i = queue.length - 1; i >= 0; i--) { - if (queue[i].data.type === "outbox_update") break; - if (queue[i].data.messageId === data.messageId) queue.splice(i, 1); + const frame = queue[i]; + if (!isRecord(frame.data)) continue; + if (frame.data.type === "outbox_update") break; + if (frame.data.messageId === data.messageId) queue.splice(i, 1); } queue.push({ data, at }); return; } - const last = queue.at(-1); - const merged = last && isDeltaUpdate(last.data) ? mergeDeltaUpdates(last.data, data) : null; + const merged = lastData && isDeltaUpdate(lastData) ? mergeDeltaUpdates(lastData, data) : null; if (last && merged) { last.data = merged; last.at = at; From 754b24c236cc47e38cd1629038376a79a556febc Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:47:46 +0000 Subject: [PATCH 18/45] fix(ui): prevent file-panel tabs from clipping on overflow Port of ompweb-dev/ompweb#547. --- app/globals.css | 7 ++----- components/TabBar.tsx | 3 +-- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/app/globals.css b/app/globals.css index 905a46ae..84e2f73e 100644 --- a/app/globals.css +++ b/app/globals.css @@ -3747,6 +3747,7 @@ html[data-touch-targets="accessible"] .right-panel-toolbar { } .right-panel-toolbar { --right-panel-close-width: 44px; + --tab-height: 44px; } html:root .shell-toolbar-btn.right-panel-close-button { padding-top: env(safe-area-inset-top, 0px) !important; @@ -3758,7 +3759,7 @@ html[data-touch-targets="accessible"] .right-panel-toolbar { .right-panel-toolbar > div:first-child { display: flex; align-items: center; - min-height: 44px; + min-height: var(--tab-height); } .right-panel-toolbar > [role="toolbar"] > button { min-width: 40px; @@ -3767,10 +3768,6 @@ html[data-touch-targets="accessible"] .right-panel-toolbar { .right-panel-toolbar .tabbar-scroll { width: 100%; } - .right-panel-toolbar .tabbar-scroll, - .right-panel-toolbar .tabbar-tab { - height: 44px !important; - } } :root { diff --git a/components/TabBar.tsx b/components/TabBar.tsx index b0040478..3a93b3b9 100644 --- a/components/TabBar.tsx +++ b/components/TabBar.tsx @@ -212,11 +212,10 @@ export function TabBar({ tabs, activeTabId, onSelectTab, onCloseTab, explorerSel className="tabbar-scroll" style={{ display: "flex", - alignItems: "flex-end", background: "var(--bg-panel)", + // Let a classic horizontal scrollbar take space below the tabs. overflowX: "auto", flexShrink: 0, - height: "var(--tab-height)", }} > {onSelectNotifications && ( From 3115fb09689c2a927ecb0333d4d3cb93ea2e9ff0 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:48:17 +0000 Subject: [PATCH 19/45] fix(projects): keep a re-added workspace's display data and avoid worktree path collisions Port of ompweb-dev/ompweb#554 (rework of ompweb-dev/ompweb#297). --- components/SessionSidebar.tsx | 11 +----- lib/hosts/session-ops.ts | 2 +- lib/project-ordering.test.mjs | 17 ++++++++ lib/project-ordering.ts | 9 ++++- lib/project-registry.test.mjs | 32 +++++++++++++++ lib/project-registry.ts | 30 ++++++++++++-- lib/workspace-memory.test.mjs | 37 ++++++------------ lib/workspace-memory.ts | 73 +++++++---------------------------- lib/worktree.test.mjs | 40 +++++++++++++++++++ lib/worktree.ts | 45 ++++++++++++++++++++- 10 files changed, 194 insertions(+), 102 deletions(-) diff --git a/components/SessionSidebar.tsx b/components/SessionSidebar.tsx index 1e089c01..4edef3d2 100644 --- a/components/SessionSidebar.tsx +++ b/components/SessionSidebar.tsx @@ -8,7 +8,7 @@ import { DirectoryPicker } from "./DirectoryPicker"; import { ProjectLaunchConfigDialog } from "./ProjectLaunchConfigDialog"; import { Tooltip } from "./ui/primitives"; import { toast } from "./ui/toast"; -import { clearLastOpenSession, setLastOpenSession, workspaceKeyOf } from "@/lib/workspace-memory"; +import { workspaceKeyOf } from "@/lib/workspace-memory"; import { LOCAL_HOST_ID, foldedHostProjectKey, groupProjectsByHost, groupSessionsByProject, hostProjectKey, projectIdentity, projectTargetId, nextPinOrder, orderProjects, projectActivityCounts, remoteHostId, type ProjectSortMode } from "@/lib/project-ordering"; import { isLinkUp } from "@/lib/hosts/host"; import { useHostRows } from "@/hooks/useHostRows"; @@ -1472,16 +1472,9 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, // Stable callbacks for the session list so memoized children don't re-render // on every parent state change. const handleSessionDeleted = useCallback((id: string) => { - const deleted = allSessions.find((session) => session.id === id); - if (deleted) clearLastOpenSession(hostProjectKey(deleted.hostId, workspaceKeyOf(deleted))); onSessionDeleted?.(id); loadSessions(); - }, [allSessions, onSessionDeleted, loadSessions]); - - useEffect(() => { - const selected = allSessions.find((session) => session.id === selectedSessionId); - if (selected) setLastOpenSession(hostProjectKey(selected.hostId, workspaceKeyOf(selected)), selected.id); - }, [allSessions, selectedSessionId]); + }, [onSessionDeleted, loadSessions]); return (
diff --git a/lib/hosts/session-ops.ts b/lib/hosts/session-ops.ts index d3cfb4b6..f280f837 100644 --- a/lib/hosts/session-ops.ts +++ b/lib/hosts/session-ops.ts @@ -704,7 +704,7 @@ export const sessionOps: SessionOps = { const next = upsertProject(loadProjectRegistry(), projectRoot, new Date().toISOString(), launchConfig); saveProjectRegistry(next); const entry = next.projects.find((p) => comparableProjectPath(p.path) === comparableProjectPath(projectRoot))!; - return ok({ path: entry.path, addedAt: entry.addedAt, launchConfig: entry.launchConfig }); + return ok({ path: entry.path, addedAt: entry.addedAt, alias: entry.alias, sortOrder: entry.sortOrder, pinOrder: entry.pinOrder, launchConfig: entry.launchConfig }); } catch (error) { if (error instanceof ProjectPathError) return fail(400, error.code, error.message); throw error; diff --git a/lib/project-ordering.test.mjs b/lib/project-ordering.test.mjs index 14c3b5fb..8cf66770 100644 --- a/lib/project-ordering.test.mjs +++ b/lib/project-ordering.test.mjs @@ -94,6 +94,23 @@ test("groups sessions under their project, including worktree sessions", () => { assert.deepEqual(grouped.get("/other").map((s) => s.id).sort(), ["fork", "parent"]); }); +test("session with no workspace key at all is skipped, not bucketed", () => { + // Deliberately no "unknown workspace" bucket: the sidebar renders one row + // per project (it iterates projects, never this map's keys), so a bucket + // keyed "" would be unreachable dead data. A session that carries a key in + // any field still groups via workspaceKeyOf's empty-string fallthrough; + // only a header with no location at all has nowhere to go. + const projects = [{ path: "/proj/a" }]; + const sessions = [ + session("s1", { cwd: "", projectRoot: "", projectKey: "" }), + session("s2", { cwd: "/proj/a", projectRoot: "/proj/a", projectKey: "/proj/a" }), + ]; + const grouped = groupSessionsByProject(projects, sessions); + assert.deepEqual(grouped.get("/proj/a").map((s) => s.id), ["s2"]); + assert.equal([...grouped.values()].flat().some((s) => s.id === "s1"), false); + assert.equal(grouped.has(""), false); +}); + test("projectActivityCounts tallies running, unread, and exited sessions per project", () => { const sessions = [ session("running-main", { projectRoot: "/repo" }), diff --git a/lib/project-ordering.ts b/lib/project-ordering.ts index c092ce35..32a1c54d 100644 --- a/lib/project-ordering.ts +++ b/lib/project-ordering.ts @@ -169,7 +169,14 @@ export function projectActivityCounts( /** Group sessions by logical project identity, or by host-bound physical path. * Every managed project gets a bucket, including empty projects. Physical paths - * compare case-insensitively on Windows; logical IDs stay case-sensitive. */ + * compare case-insensitively on Windows; logical IDs stay case-sensitive. + * Sessions with no workspace key at all are skipped, deliberately: the + * sidebar renders one row per project (it iterates projects, never this + * map's keys), so there is no row a key-less session could appear under — + * an "unknown workspace" bucket here would be unreachable dead data. The + * empty-string fallthrough in workspaceKeyOf already rescues any session + * that carries a key in any field; only a header with no location at all + * is left, and grouping cannot place it under any project. */ export function groupSessionsByProject( projects: ManagedProject[], sessions: SessionInfo[], diff --git a/lib/project-registry.test.mjs b/lib/project-registry.test.mjs index 649df8dd..d06589b6 100644 --- a/lib/project-registry.test.mjs +++ b/lib/project-registry.test.mjs @@ -92,6 +92,38 @@ test("re-adding a workspace without config preserves its launch config", () => { assert.deepEqual(replaced.projects[0].launchConfig, { extraArgs: ["--verbose"] }); }); +test("re-adding a workspace preserves its alias, sort order, and pin order", () => { + const seeded = parseProjectRegistry(JSON.stringify({ version: 1, projects: [{ + path: P("/one"), addedAt: "2026-01-01T00:00:00.000Z", hidden: false, + alias: "My Workspace", sortOrder: 3, pinOrder: 0, + }] })); + const hidden = hideProject(seeded, P("/one")); + assert.equal(hidden.projects[0].hidden, true); + assert.equal(hidden.projects[0].alias, "My Workspace"); + const revived = upsertProject(hidden, P("/one"), "2026-02-01T00:00:00.000Z"); + const entry = revived.projects[0]; + assert.equal(entry.hidden, false); + assert.equal(entry.alias, "My Workspace"); + assert.equal(entry.sortOrder, 3); + assert.equal(entry.pinOrder, 0); +}); + +test("re-adding a workspace whose pin order was taken moves it last among pins", () => { + // Pinned at 0, hidden; meanwhile another project takes pinOrder 0 (fresh + // pins take max+1 over the visible list, which never counted the hidden + // entry). Re-adding must keep the project pinned — at the end of the + // pinned list — not silently share pinOrder 0 or drop the pin. + const seeded = parseProjectRegistry(JSON.stringify({ version: 1, projects: [ + { path: P("/one"), addedAt: "2026-01-01T00:00:00.000Z", hidden: true, pinOrder: 0 }, + { path: P("/two"), addedAt: "2026-01-02T00:00:00.000Z", hidden: false, pinOrder: 0 }, + ] })); + const revived = upsertProject(seeded, P("/one"), "2026-02-01T00:00:00.000Z"); + const one = revived.projects.find((p) => comparableProjectPath(p.path) === comparableProjectPath(P("/one"))); + const two = revived.projects.find((p) => comparableProjectPath(p.path) === comparableProjectPath(P("/two"))); + assert.equal(two.pinOrder, 0); + assert.equal(one.pinOrder, 1); +}); + test("applies batch presentation updates in one pass", () => { const registry = parseProjectRegistry(JSON.stringify({ version: 1, diff --git a/lib/project-registry.ts b/lib/project-registry.ts index 4439b639..08a6b94c 100644 --- a/lib/project-registry.ts +++ b/lib/project-registry.ts @@ -184,10 +184,32 @@ export function upsertProject( const key = comparableProjectPath(canonical); const existing = registry.projects.find((p) => comparableProjectPath(p.path) === key); const projects = registry.projects.filter((p) => comparableProjectPath(p.path) !== key); - // An omitted launchConfig preserves the stored one: re-adding a workspace - // (e.g. un-hiding) without config must not wipe it. Explicit clear goes - // through PATCH with null. - projects.push({ path: canonical, addedAt: now, hidden: false, launchConfig: launchConfig ?? existing?.launchConfig, ...(discovered ? { discovered: true as const } : {}) }); + // Re-adding a workspace (e.g. un-hiding) must not wipe its stored display + // data: alias, sort order, pin order, and launch config all carry over + // from the existing entry. An omitted launchConfig preserves the stored + // one; explicit clear goes through PATCH with null. Display fields have no + // POST parameter, so carrying them over is unconditional — PATCH applies + // its own updates on top afterwards. + // Pin-order collision: while this project was hidden, another project may + // have taken its pinOrder (fresh pins take max+1 over the visible list, + // which never counted the hidden entry). Keeping the duplicate would make + // the pinned order ambiguous — orderProjects only stable-sorts ties — so + // a colliding pin moves to the end of the pinned list instead of + // unpinning: the project stays pinned, just last. + let pinOrder = existing?.pinOrder; + if (pinOrder !== undefined && projects.some((p) => !p.hidden && p.pinOrder === pinOrder)) { + pinOrder = Math.max(-1, ...projects.filter((p) => !p.hidden).map((p) => p.pinOrder ?? -1)) + 1; + } + projects.push({ + path: canonical, + addedAt: now, + hidden: false, + alias: existing?.alias, + sortOrder: existing?.sortOrder, + pinOrder, + launchConfig: launchConfig ?? existing?.launchConfig, + ...(discovered ? { discovered: true as const } : {}), + }); return { version: 1, projects }; } diff --git a/lib/workspace-memory.test.mjs b/lib/workspace-memory.test.mjs index 7a0be516..69e01c94 100644 --- a/lib/workspace-memory.test.mjs +++ b/lib/workspace-memory.test.mjs @@ -2,35 +2,20 @@ import assert from "node:assert/strict"; import test from "node:test"; const { - clearLastOpenSession, - getLastOpenSession, - setLastOpenSession, workspaceKeyOf, } = await import("./workspace-memory.ts"); -function createStorage(values = {}) { - const entries = new Map(Object.entries(values)); - return { - getItem(key) { return entries.get(key) ?? null; }, - setItem(key, value) { entries.set(key, value); }, - removeItem(key) { entries.delete(key); }, - entries, - }; -} - -test("remembers the last session for each project independently", () => { - const storage = createStorage(); - setLastOpenSession("project-a", "session-a", storage); - setLastOpenSession("project-b", "session-b", storage); - - assert.equal(getLastOpenSession("project-a", storage), "session-a"); - assert.equal(getLastOpenSession("project-b", storage), "session-b"); - clearLastOpenSession("project-a", storage); - assert.equal(getLastOpenSession("project-a", storage), null); - assert.equal(getLastOpenSession("project-b", storage), "session-b"); -}); - test("uses the shared project root so worktrees restore the same workspace", () => { assert.equal(workspaceKeyOf({ cwd: "D:/repo-worktrees/feature", projectRoot: "D:/repo" }), "D:/repo"); - assert.equal(workspaceKeyOf({ cwd: "D:/scratch" }), "D:/scratch"); + assert.equal(workspaceKeyOf({ cwd: "/scratch" }), "/scratch"); +}); + +test("empty-string fields fall through to the next workspace key", () => { + // Headers from hand-edited or partially written session files can carry + // "" instead of a missing field; ?? would keep the empty string and the + // session would group under no project. + assert.equal(workspaceKeyOf({ cwd: "/scratch", projectRoot: "", projectKey: "" }), "/scratch"); + assert.equal(workspaceKeyOf({ cwd: "", projectRoot: "/repo", projectKey: "" }), "/repo"); + assert.equal(workspaceKeyOf({ cwd: "", projectRoot: "", projectKey: "" }), ""); + assert.equal(workspaceKeyOf({ cwd: "", projectRoot: "", projectKey: "", poolId: "pool-1", projectId: "proj-1" }), "pool:pool-1:proj-1"); }); diff --git a/lib/workspace-memory.ts b/lib/workspace-memory.ts index 843e1b9f..c99bfc90 100644 --- a/lib/workspace-memory.ts +++ b/lib/workspace-memory.ts @@ -1,63 +1,18 @@ - -const STORAGE_KEY = "tau:last-open-by-project"; - -interface StorageLike { - getItem(key: string): string | null; - setItem(key: string, value: string): void; - removeItem(key: string): void; -} - -function browserStorage(): StorageLike | null { - if (typeof window === "undefined") return null; - try { - return window.localStorage; - } catch { - return null; - } -} - -function readEntries(storage: StorageLike): Record { - try { - const raw = storage.getItem(STORAGE_KEY); - if (!raw) return {}; - const value: unknown = JSON.parse(raw); - if (!value || typeof value !== "object" || Array.isArray(value)) return {}; - return Object.fromEntries(Object.entries(value).filter(([, id]) => typeof id === "string" && id.length > 0)) as Record; - } catch { - return {}; - } -} +// NOTE: this module used to also record the last-open session per project +// (get/set/clearLastOpenSession, localStorage key "tau:last-open-by-project"). +// No caller ever read the recorded value back — project activation is +// deliberately selection-only (see activateProject in SessionSidebar: it sets +// the selected workspace, it never opens a session) — so the helpers were +// dead writes on every selection and were removed rather than wired into a +// behavior change. Any value already stored under that key is orphaned and +// never read. export function workspaceKeyOf(workspace: { cwd?: string; path?: string; projectRoot?: string; projectKey?: string; poolId?: string; projectId?: string }): string { - if (workspace.poolId && workspace.projectId) return workspace.projectKey ?? `pool:${workspace.poolId}:${workspace.projectId}`; - return workspace.projectKey ?? workspace.projectRoot ?? workspace.cwd ?? workspace.path ?? ""; -} - -export function getLastOpenSession(workspace: string, storage: StorageLike | null = browserStorage()): string | null { - if (!storage) return null; - return readEntries(storage)[workspace] ?? null; -} - -export function setLastOpenSession(workspace: string, sessionId: string, storage: StorageLike | null = browserStorage()): void { - if (!storage) return; - try { - const entries = readEntries(storage); - entries[workspace] = sessionId; - storage.setItem(STORAGE_KEY, JSON.stringify(entries)); - } catch { - // Workspace restoration is a best-effort convenience. - } -} - -export function clearLastOpenSession(workspace: string, storage: StorageLike | null = browserStorage()): void { - if (!storage) return; - try { - const entries = readEntries(storage); - if (!(workspace in entries)) return; - delete entries[workspace]; - if (Object.keys(entries).length === 0) storage.removeItem(STORAGE_KEY); - else storage.setItem(STORAGE_KEY, JSON.stringify(entries)); - } catch { - // Workspace restoration is a best-effort convenience. + if (workspace.poolId && workspace.projectId) { + // Empty strings count as missing, not as a key: hand-edited or partially + // written session headers can carry "" where a field is absent, and ?? + // would keep the empty string, grouping the session under no project. + return workspace.projectKey || `pool:${workspace.poolId}:${workspace.projectId}`; } + return workspace.projectKey || workspace.projectRoot || workspace.cwd || workspace.path || ""; } diff --git a/lib/worktree.test.mjs b/lib/worktree.test.mjs index 8ebabe8e..cca3178d 100644 --- a/lib/worktree.test.mjs +++ b/lib/worktree.test.mjs @@ -72,3 +72,43 @@ test("discovers the main checkout and linked worktrees without retaining prunabl rmSync(root, { recursive: true, force: true }); } }); + +test("slash and dash branches with the same sanitized name get distinct worktree dirs", async (t) => { + try { + execFileSync("git", ["--version"], { stdio: "ignore" }); + } catch { + t.skip("git is not installed"); + return; + } + + const root = mkdtempSync(join(tmpdir(), "tau-worktree-test-")); + const repo = join(root, "repo"); + const worktreeBase = `${repo}-worktrees`; + try { + git(root, ["init", repo]); + git(repo, ["config", "user.email", "tau@example.invalid"]); + git(repo, ["config", "user.name", "tau test"]); + writeFileSync(join(repo, "README.md"), "fixture\n"); + git(repo, ["add", "README.md"]); + git(repo, ["commit", "-m", "fixture"]); + + // The pre-existing dir for a-b must keep its name (backwards compat). + const dashed = await addWorktree(repo, "a-b"); + assert.equal(dashed.branch, "a-b"); + assert.ok(dashed.path.endsWith("a-b")); + // a/b sanitizes to the same base name; it must not be refused, and it + // must not reuse the a-b worktree's directory. + const slashed = await addWorktree(repo, "a/b"); + assert.equal(slashed.branch, "a/b"); + assert.notEqual(slashed.path, dashed.path); + assert.equal(existsSync(slashed.path), true); + const worktrees = await listWorktrees(repo); + assert.ok(worktrees.some((entry) => samePath(entry.path, dashed.path) && entry.branch === "a-b")); + assert.ok(worktrees.some((entry) => samePath(entry.path, slashed.path) && entry.branch === "a/b")); + // Re-adding the same branch is still refused with the plain error. + await assert.rejects(() => addWorktree(repo, "a-b"), /Directory already exists/); + } finally { + rmSync(worktreeBase, { recursive: true, force: true }); + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/lib/worktree.ts b/lib/worktree.ts index 429b05fc..de668cd1 100644 --- a/lib/worktree.ts +++ b/lib/worktree.ts @@ -1,4 +1,5 @@ import { execFile } from "child_process"; +import { createHash } from "crypto"; import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "fs"; import { basename, dirname, join, resolve } from "path"; import { promisify } from "util"; @@ -297,6 +298,24 @@ function sanitizeBranchForDir(branch: string): string { return branch.replace(/[\/\\:*?"<>|\s]+/g, "-").replace(/^-+|-+$/g, ""); } +/** Short stable suffix distinguishing branches whose sanitized directory + * names collide (e.g. "a/b" and "a-b" both sanitize to "a-b"). Only used on + * collision, so already-created worktree directories keep their names. */ +function worktreeDirSuffix(branch: string): string { + return createHash("sha256").update(branch).digest("hex").slice(0, 8); +} + +/** Branch checked out at a worktree path, or null when the path is not a + * registered worktree (stray directory, prunable entry, or missing git). */ +async function findWorktreeBranch(cwd: string, worktreePath: string): Promise { + try { + const worktrees = await listWorktrees(cwd); + return findWorktreeByPath(worktrees, worktreePath)?.branch ?? null; + } catch { + return null; + } +} + export async function addWorktree(cwd: string, branch: string): Promise<{ path: string; branch: string }> { const trimmed = branch.trim(); if (!trimmed) throw new Error("Branch name is required"); @@ -314,9 +333,31 @@ export async function addWorktree(cwd: string, branch: string): Promise<{ path: const repoRoot = await getRepoRoot(cwd); const baseDir = `${resolve(repoRoot)}-worktrees`; - const worktreePath = join(baseDir, dirName); + // sanitizeBranchForDir is not injective ("a/b" and "a-b" both map to + // "a-b"), so a plain exists check refuses the second branch. The base name + // is kept as-is so already-created worktrees keep working; only on a real + // collision does the directory gain a short hash of the branch name. + let worktreePath = join(baseDir, dirName); if (existsSync(worktreePath)) { - throw new Error(`Directory already exists: ${worktreePath}`); + const owner = await findWorktreeBranch(cwd, worktreePath); + if (owner === trimmed) { + throw new Error(`Directory already exists: ${worktreePath}`); + } + const disambiguated = join(baseDir, `${dirName}-${worktreeDirSuffix(trimmed)}`); + if (existsSync(disambiguated)) { + const disambiguatedOwner = await findWorktreeBranch(cwd, disambiguated); + if (disambiguatedOwner === trimmed) { + throw new Error(`Directory already exists: ${disambiguated}`); + } + // Distinct error: the directory is taken by something other than this + // branch and even the hash-suffixed fallback is occupied, so no safe + // directory can be picked automatically. + throw new Error( + `Worktree directory already exists for a different branch: ${disambiguated}` + + (disambiguatedOwner ? ` (checked out branch: ${disambiguatedOwner})` : " (not a registered worktree)"), + ); + } + worktreePath = disambiguated; } mkdirSync(baseDir, { recursive: true }); if (lstatSync(baseDir).isSymbolicLink() || !samePath(realPathOrSelf(baseDir), baseDir)) throw new Error("Worktree directory must not be a symbolic link"); From 6b5a9bf65d4f92cc00ce69a97d5722540f8b56ca Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Mon, 23 Nov 2026 09:49:44 +0000 Subject: [PATCH 20/45] feat(composer): fullscreen edit mode and one-line collapse for long sent messages Port of ompweb-dev/ompweb#556. --- components/ChatInput.fullscreen.test.mjs | 74 ++++++++++++++++ components/ChatInput.tsx | 106 ++++++++++++++++++++++- components/MessageView.test.mjs | 18 ++++ components/MessageView.tsx | 6 +- lib/i18n/locales/en.json | 4 + lib/i18n/locales/ja.json | 4 + lib/i18n/locales/zh-CN.json | 4 + lib/i18n/locales/zh-TW.json | 4 + 8 files changed, 218 insertions(+), 2 deletions(-) create mode 100644 components/ChatInput.fullscreen.test.mjs diff --git a/components/ChatInput.fullscreen.test.mjs b/components/ChatInput.fullscreen.test.mjs new file mode 100644 index 00000000..d065c0c3 --- /dev/null +++ b/components/ChatInput.fullscreen.test.mjs @@ -0,0 +1,74 @@ +import assert from "node:assert/strict"; +import "../tests/setup-dom.mjs"; +import test from "node:test"; +import React from "react"; + +const { act, cleanup, fireEvent, render } = await import("@testing-library/react/pure.js"); +const { ChatInput } = await import("./ChatInput.tsx"); + +// jsdom 29 ships no matchMedia, and the composer reads one at mount for the +// word-completion default (`(pointer: fine)`). Never match: desktop composer. +window.matchMedia = (media) => ({ + media, + matches: false, + onchange: null, + addEventListener() {}, + removeEventListener() {}, + addListener() {}, + removeListener() {}, + dispatchEvent() { return false; }, +}); + +async function renderComposer(t, props = {}) { + const sent = []; + const view = render(React.createElement(ChatInput, { + async onSend(message) { sent.push(message); return { status: "accepted" }; }, + onThinkingLevelChange() {}, + thinkingLevel: "auto", + isStreaming: false, + ...props, + })); + t.after(() => cleanup()); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); + return { view, sent }; +} + +const expandButton = (view) => view.getByRole("button", { name: /Expand editor|chatInput\.expandEditor/ }); + +test("the composer opens a full-screen editor that shares its draft", async (t) => { + const { view } = await renderComposer(t); + assert.equal(view.queryByRole("dialog"), null, "the editor must start closed"); + fireEvent.click(expandButton(view)); + const dialog = view.getByRole("dialog"); + const editor = dialog.querySelector("textarea"); + assert.ok(editor, "the full-screen editor needs a textarea"); + fireEvent.change(editor, { target: { value: "a very long prompt\nwith many lines" } }); + assert.equal(editor.value, "a very long prompt\nwith many lines"); + // Done closes the editor and the compact composer keeps the same text. + // (The header ✕ shares the Done label; the footer button is the text one.) + fireEvent.click(view.getByText("Done")); + assert.equal(view.queryByRole("dialog"), null); + const [compact] = view.container.querySelectorAll("textarea"); + assert.equal(compact.value, "a very long prompt\nwith many lines"); +}); + +test("Ctrl+Enter in the full-screen editor sends the draft", async (t) => { + const { view, sent } = await renderComposer(t); + fireEvent.click(expandButton(view)); + const editor = view.getByRole("dialog").querySelector("textarea"); + fireEvent.change(editor, { target: { value: "send me" } }); + fireEvent.keyDown(editor, { key: "Enter", ctrlKey: true }); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); }); + assert.deepEqual(sent, ["send me"]); + assert.equal(view.queryByRole("dialog"), null, "sending closes the editor"); +}); + +test("Escape closes the full-screen editor without sending", async (t) => { + const { view, sent } = await renderComposer(t); + fireEvent.click(expandButton(view)); + const editor = view.getByRole("dialog").querySelector("textarea"); + fireEvent.change(editor, { target: { value: "keep me" } }); + fireEvent.keyDown(editor, { key: "Escape" }); + assert.equal(view.queryByRole("dialog"), null); + assert.deepEqual(sent, []); +}); diff --git a/components/ChatInput.tsx b/components/ChatInput.tsx index 1beff50f..5dc7fa9b 100644 --- a/components/ChatInput.tsx +++ b/components/ChatInput.tsx @@ -2,7 +2,7 @@ import React, { useRef, useState, useCallback, useEffect, useLayoutEffect, useImperativeHandle, forwardRef, memo, KeyboardEvent } from "react"; import { createPortal } from "react-dom"; -import { ChevronDown, ClipboardPaste, CornerDownRight, ListChecks, Loader2, Mic, Paperclip, Plus, RotateCw, Shrink, Terminal, Wrench, X } from "lucide-react"; +import { ChevronDown, ClipboardPaste, CornerDownRight, ListChecks, Loader2, Maximize2, Mic, Paperclip, Plus, RotateCw, Shrink, Terminal, Wrench, X } from "lucide-react"; import { getSubmitDuringRunBehavior } from "@/lib/composer-prefs"; import type { BuiltinSlashCommandResult, CompactResultInfo, PromptSendOptions, PromptSubmissionResult, QueuedMessages, SlashCommandInfo } from "@/hooks/useAgentSession"; import type { ActiveGoal, ActivePlan } from "@/lib/web-mode-state"; @@ -356,6 +356,9 @@ export const ChatInput = memo(forwardRef(function ChatIn const contextContainer = isMobile ? sessionInfoContainer : composerContextContainer; const [plusMenuOpen, setPlusMenuOpen] = useState(false); const [plusExpanded, setPlusExpanded] = useState<"tools" | null>(null); + // Full-screen editing surface for long prompts; shares the composer's draft + // value, so closing it (or sending from it) keeps the same text. + const [editorFullscreen, setEditorFullscreen] = useState(false); const [modelSearchQuery, setModelSearchQuery] = useState(""); const [attachedImages, setAttachedImages] = useState(() => ( draftKey ? draftImagesToAttachedImages(getDraft(draftKey)?.images) : [] @@ -3569,6 +3572,27 @@ export const ChatInput = memo(forwardRef(function ChatIn
+ {editorFullscreen && createPortal( +
+
+ {t("chatInput.fullscreenEditor")} + {t("chatInput.fullscreenEditorHint")} + +
+