diff --git a/apps/desktop/scripts/main-process-bundle.test.mjs b/apps/desktop/scripts/main-process-bundle.test.mjs index 6e1f767d7d39..4ff4f930b398 100644 --- a/apps/desktop/scripts/main-process-bundle.test.mjs +++ b/apps/desktop/scripts/main-process-bundle.test.mjs @@ -13,12 +13,14 @@ it("keeps lazy Linux imports and worker bundles from executing desktop startup t const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-desktop-bundle-")); try { const workerEntries = [ + "src/backend/DesktopBackendRecoveryWorker.ts", "src/electron/WindowsForegroundFocusWorker.ts", "src/snapShot/GlobalShiftShortcutWorker.ts", "src/snapShot/RegionSnapShotWorker.ts", "src/snapShot/SnapShotAccessibilityWorker.ts", ]; await Promise.all([ + NodeFSP.mkdir(NodePath.join(directory, "src/backend"), { recursive: true }), NodeFSP.mkdir(NodePath.join(directory, "src/electron"), { recursive: true }), NodeFSP.mkdir(NodePath.join(directory, "src/snapShot"), { recursive: true }), ]); @@ -104,7 +106,10 @@ void import("./linux.ts").then(({ result }) => process.emit("ready", result));`, for (const entry of workerEntries) { load(NodePath.join(outputDirectory, entry.replace(/^src\//, "").replace(/\.ts$/, ".cjs"))); } - assert.deepEqual(workers, [42, 42, 42, 42]); + assert.deepEqual( + workers, + workerEntries.map(() => 42), + ); assert.deepEqual(startups, [42]); } finally { await NodeFSP.rm(directory, { recursive: true, force: true }); diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index a14fae5eefc6..415b1bf135dc 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -241,6 +241,7 @@ const startLocalBackend = Effect.gen(function* () { return yield* new DesktopDevelopmentBackendPortRequiredError(); } + yield* DesktopBackendPool.recoverLocalBackend; // A backend started while another server holds this home's lock can only exit with code 78. if ( !(settings.wslOnly && settings.wslBackendEnabled) && diff --git a/apps/desktop/src/app/DesktopWebLinks.test.ts b/apps/desktop/src/app/DesktopWebLinks.test.ts index e4259f66fb5e..13182d924bd4 100644 --- a/apps/desktop/src/app/DesktopWebLinks.test.ts +++ b/apps/desktop/src/app/DesktopWebLinks.test.ts @@ -3,6 +3,7 @@ import { assert, describe, it } from "@effect/vitest"; import * as NodeEvents from "node:events"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as DesktopWindow from "../window/DesktopWindow.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; @@ -12,15 +13,32 @@ import * as DesktopWebLinks from "./DesktopWebLinks.ts"; const makeWindow = () => { const sent: Array = []; const revealed: Array = []; - const webContents = Object.assign(new NodeEvents.EventEmitter(), { - isDestroyed: () => false, - send: (channel: string, url: string) => { - if (channel === WEB_LINK_OPEN_CHANNEL) sent.push(url); - }, - }); - const window = { webContents } as unknown as Electron.BrowserWindow; - const reload = () => - webContents.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false }); + const open = () => { + const webContents = Object.assign(new NodeEvents.EventEmitter(), { + isDestroyed: () => false, + send: (channel: string, url: string) => { + if (channel === WEB_LINK_OPEN_CHANNEL) sent.push(url); + }, + }); + return { webContents } as unknown as Electron.BrowserWindow; + }; + let window = Option.some(open()); + const reload = () => { + if (Option.isSome(window)) { + window.value.webContents.emit("did-start-navigation", { + isMainFrame: true, + isSameDocument: false, + }); + } + }; + const close = () => { + const closed = window; + window = Option.none(); + if (Option.isSome(closed)) closed.value.webContents.emit("destroyed"); + }; + const reopen = () => { + window = Option.some(open()); + }; const layer = DesktopWebLinks.layer.pipe( Layer.provide( Layer.succeed(DesktopWindow.DesktopWindow, { @@ -31,13 +49,14 @@ const makeWindow = () => { Layer.succeed( ElectronWindow.ElectronWindow, ElectronWindow.ElectronWindow.of({ - currentMainOrFirst: Effect.succeedSome(window), + main: Effect.sync(() => window), + currentMainOrFirst: Effect.sync(() => window), reveal: (target: Electron.BrowserWindow) => Effect.sync(() => void revealed.push(target)), } as unknown as ElectronWindow.ElectronWindow["Service"]), ), ), ); - return { sent, revealed, layer, reload }; + return { sent, revealed, layer, reload, close, reopen }; }; describe("DesktopWebLinks", () => { @@ -59,6 +78,7 @@ describe("DesktopWebLinks", () => { yield* webLinks.setRendererReady(false); yield* webLinks.receive("https://example.com/fourth"); assert.strictEqual(sent.length, 3); + assert.strictEqual(revealed.length, 2); }).pipe(Effect.provide(layer)); }); @@ -75,4 +95,31 @@ describe("DesktopWebLinks", () => { assert.deepStrictEqual(sent, ["https://example.com/during-reload"]); }).pipe(Effect.provide(layer)); }); + + it.effect("asks for a window when a link arrives after the main window closed", () => { + const { sent, revealed, layer, close, reopen } = makeWindow(); + return Effect.gen(function* () { + const webLinks = yield* DesktopWebLinks.DesktopWebLinks; + close(); + yield* webLinks.receive("https://example.com/at-launch"); + assert.strictEqual(revealed.length, 0); + + reopen(); + yield* webLinks.setRendererReady(true); + assert.deepStrictEqual(sent, ["https://example.com/at-launch"]); + assert.strictEqual(revealed.length, 1); + + close(); + yield* webLinks.receive("https://example.com/after-close"); + assert.deepStrictEqual(sent, ["https://example.com/at-launch"]); + assert.strictEqual(revealed.length, 2); + + reopen(); + yield* webLinks.setRendererReady(true); + assert.deepStrictEqual(sent, [ + "https://example.com/at-launch", + "https://example.com/after-close", + ]); + }).pipe(Effect.provide(layer)); + }); }); diff --git a/apps/desktop/src/app/DesktopWebLinks.ts b/apps/desktop/src/app/DesktopWebLinks.ts index c1932c5ce905..b63f187aefb6 100644 --- a/apps/desktop/src/app/DesktopWebLinks.ts +++ b/apps/desktop/src/app/DesktopWebLinks.ts @@ -29,6 +29,7 @@ const make = Effect.gen(function* () { const pending: Array = []; let listening: Electron.WebContents | null = null; let detachListening: (() => void) | null = null; + let rendererHasListened = false; const stopListening = () => { detachListening?.(); @@ -55,6 +56,7 @@ const make = Effect.gen(function* () { if (listening === webContents) return; stopListening(); listening = webContents; + rendererHasListened = true; const onNavigation = ( event: Electron.Event, ) => { @@ -71,11 +73,12 @@ const make = Effect.gen(function* () { }); return DesktopWebLinks.of({ - receive: Effect.fn("DesktopWebLinks.receive")(function (url) { - return Effect.suspend(() => { - pending.push(url); - return flush; - }); + receive: Effect.fn("DesktopWebLinks.receive")(function* (url) { + pending.push(url); + yield* flush; + if (!rendererHasListened || Option.isSome(yield* electronWindow.main)) return; + // macOS fires `activate` only on reopen, not when a link opens the app. + yield* desktopWindow.activate.pipe(Effect.ignore); }), setRendererReady: Effect.fn("DesktopWebLinks.setRendererReady")(function (ready) { return ready ? startListening : Effect.sync(stopListening); diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index ff5b7b8c08e4..c69e84515533 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -358,6 +358,61 @@ describe("DesktopBackendManager", () => { }), ); + it.effect("delivers fd3 bootstrap while ownership recording is pending", () => + Effect.gen(function* () { + const recording = yield* Deferred.make(); + const finishRecording = yield* Deferred.make(); + const receivedBootstrap = yield* Deferred.make>(); + const exitObserved = yield* Deferred.make(); + const childExit = yield* Deferred.make(); + const forgotten = yield* Ref.make(false); + const layerSpawner = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make( + Effect.fnUntraced(function* (command) { + if (!ChildProcess.isStandardCommand(command)) { + return yield* Effect.die("Expected a standard local backend command"); + } + const fd = command.options.additionalFds?.fd3; + if (fd?.type !== "input" || fd.stream === undefined) { + return yield* Effect.die("Expected a bootstrap stream on fd 3"); + } + yield* fd.stream.pipe( + Stream.decodeText(), + Stream.mkString, + Effect.timeoutOption(Duration.seconds(1)), + Effect.flatMap((payload) => Deferred.succeed(receivedBootstrap, payload)), + Effect.forkScoped, + ); + return makeProcess({ exitCode: Deferred.await(childExit) }); + }), + ), + ); + const run = yield* DesktopBackendManager.runBackendProcess({ + ...baseConfig, + desktopTelemetryStream: Stream.empty, + onExitObserved: () => Deferred.succeed(exitObserved, undefined).pipe(Effect.asVoid), + trackProcess: () => + Deferred.succeed(recording, undefined).pipe( + Effect.andThen(Deferred.await(finishRecording)), + Effect.as(Ref.set(forgotten, true)), + ), + }).pipe(Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)), Effect.forkChild); + + yield* Deferred.await(recording); + yield* TestClock.adjust(Duration.seconds(2)); + const payload = yield* Deferred.await(receivedBootstrap); + assert.isTrue(Option.isSome(payload), "desktop bootstrap missed the reader deadline"); + assert.deepEqual(yield* decodeBootstrap(Option.getOrThrow(payload)), baseConfig.bootstrap); + yield* Deferred.succeed(childExit, ChildProcessSpawner.ExitCode(0)); + yield* Deferred.await(exitObserved); + assert.isFalse(yield* Ref.get(forgotten)); + yield* Deferred.succeed(finishRecording, undefined); + yield* Fiber.join(run); + assert.isTrue(yield* Ref.get(forgotten)); + }), + ); + it.effect("reports a SIGKILL exit without an exit code", () => Effect.gen(function* () { const exitCause = PlatformError.systemError({ diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index 4f7e115a5456..3f65c70305be 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -196,6 +196,8 @@ export const BackendProcessError = Schema.Union([ ]); export type BackendProcessError = typeof BackendProcessError.Type; +type TrackBackendProcess = (pid: number) => Effect.Effect>; + interface RunBackendProcessOptions extends DesktopBackendStartConfig { readonly desktopTelemetryStream: Stream.Stream; readonly desktopBrowserStream?: Stream.Stream; @@ -205,6 +207,7 @@ interface RunBackendProcessOptions extends DesktopBackendStartConfig { ) => Effect.Effect; readonly readinessTimeout?: Duration.Duration; readonly outputDrainTimeout?: Duration.Duration; + readonly trackProcess?: TrackBackendProcess; readonly onStarted?: (pid: number) => Effect.Effect; readonly onExitObserved?: () => Effect.Effect; readonly onReady?: (pid: number) => Effect.Effect; @@ -254,6 +257,7 @@ export interface BackendInstanceSpec { readonly id: BackendInstanceId; readonly label: Effect.Effect; readonly configResolve: Effect.Effect; + readonly trackProcess?: TrackBackendProcess; /** Receives the ready run's URL and pid; reading current config could race a subsequent restart. */ readonly onReady?: (httpBaseUrl: URL, pid: number) => Effect.Effect; readonly onShutdown?: () => Effect.Effect; @@ -503,6 +507,10 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( }), ), ); + // The child has a deadline for reading fd 3. Keep recovery bookkeeping off its startup path. + const tracking = options.trackProcess + ? yield* options.trackProcess(handle.pid).pipe(Effect.forkScoped) + : undefined; const outputFibers: Array> = []; const serverReady = yield* Deferred.make(); @@ -646,6 +654,11 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( Effect.exit, ); yield* options.onExitObserved?.() ?? Effect.void; + // A cancelled run may leave a survivor. Only forget after observing a real exit. + if (tracking && Exit.isSuccess(exit)) { + const forgetProcess = yield* Fiber.join(tracking); + yield* forgetProcess; + } yield* Effect.forEach(outputFibers, Fiber.await, { concurrency: "unbounded", discard: true, @@ -944,6 +957,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( const program = runBackendProcess({ ...config.value, + ...(spec.trackProcess === undefined ? {} : { trackProcess: spec.trackProcess }), desktopTelemetryStream: desktopTelemetryPublisher.encoded, desktopBrowserStream: desktopBrowserHost.events, onDesktopBrowserCommand: desktopBrowserHost.handleCommandLine, diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts index 1221b38d9020..f32bc489a219 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.ts @@ -24,6 +24,7 @@ import { ChildProcessSpawner } from "effect/process"; import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts"; import * as DesktopBackendManager from "./DesktopBackendManager.ts"; +import * as DesktopBackendRecoveryProcess from "./DesktopBackendRecoveryProcess.ts"; import * as DesktopHomeOwner from "./DesktopHomeOwner.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopObservability from "../app/DesktopObservability.ts"; @@ -37,9 +38,29 @@ import * as ElectronDialog from "../electron/ElectronDialog.ts"; import * as ElectronApp from "../electron/ElectronApp.ts"; import { m } from "../i18n/messages.ts"; -const { logWarning: logBackendPoolWarning } = +const { logInfo: logBackendPoolInfo, logWarning: logBackendPoolWarning } = DesktopObservability.makeComponentLogger("desktop-backend-pool"); +const makeRecovery = Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + if (environment.platform !== "darwin" || !environment.isPackaged) return undefined; + const runFork = Effect.runForkWith(yield* Effect.context()); + return DesktopBackendRecoveryProcess.make({ + appDataDirectory: environment.appDataDirectory, + stateDir: environment.stateDir, + onRecovery: (pid) => + runFork(logBackendPoolInfo("recovering a backend left by a previous desktop", { pid })), + onError: (operation) => + runFork(logBackendPoolWarning("desktop backend recovery failed", { operation })), + }); +}); + +export const recoverLocalBackend = makeRecovery.pipe( + Effect.flatMap((recovery) => + recovery === undefined ? Effect.void : Effect.promise((signal) => recovery.recover(signal)), + ), +); + const decodeServerRuntime = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Struct({ pid: Schema.Number, port: Schema.Number })), ); @@ -127,6 +148,7 @@ export const layer = Layer.effect( const electronApp = yield* ElectronApp.ElectronApp; const appSettings = yield* DesktopAppSettings.DesktopAppSettings; const { primaryBackendStartup } = yield* DesktopState.DesktopState; + const recovery = yield* makeRecovery; // Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends. const layerScope = yield* Scope.Scope; const factoryContext = yield* Effect.context(); @@ -226,6 +248,16 @@ export const layer = Layer.effect( // Resolve lazily: startup loads persisted settings after pool initialization. label: configuration.resolvePrimaryLabel, configResolve: configuration.resolvePrimary, + ...(recovery === undefined + ? {} + : { + trackProcess: (pid) => + Effect.promise(() => recovery.track(pid)).pipe( + Effect.map((forget) => + forget === undefined ? Effect.void : Effect.promise(forget), + ), + ), + }), // Absorb window errors so readiness can reset restartAttempt. onReady: (httpBaseUrl, pid) => FiberHandle.run(updateMarkerWait, releaseUpdateMarker(httpBaseUrl, pid)).pipe( diff --git a/apps/desktop/src/backend/DesktopBackendRecovery.test.ts b/apps/desktop/src/backend/DesktopBackendRecovery.test.ts new file mode 100644 index 000000000000..41bccac67002 --- /dev/null +++ b/apps/desktop/src/backend/DesktopBackendRecovery.test.ts @@ -0,0 +1,201 @@ +// @effect-diagnostics nodeBuiltinImport:off - Drive actual macOS subprocesses and their file permissions. +import * as NodeChildProcess from "node:child_process"; +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as NodeEvents from "node:events"; +import * as NodeFSP from "node:fs/promises"; +import * as NodeNet from "node:net"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeProcess from "node:process"; + +import { assert, describe, expect, it } from "@effect/vitest"; + +import { make } from "./DesktopBackendRecovery.ts"; +import { loadMacProcessAuditToken } from "./MacProcessAuditToken.ts"; + +const childCode = ` + import { createServer } from "node:net"; + process.once("message", () => { + const listener = createServer(); + listener.listen(0, "127.0.0.1", () => process.send(listener.address().port)); + setTimeout(() => listener.close(), 30_000).unref(); + }); +`; + +const launcherCode = ` + import { spawn } from "node:child_process"; + import { once } from "node:events"; + import { unlink } from "node:fs/promises"; + const [moduleUrl, appDataDirectory, stateDir, childCode] = process.argv.slice(1); + const { make } = await import(moduleUrl); + const recovery = make({ + appDataDirectory, + stateDir, + launcherPid: process.pid, + onRecovery: () => {}, + onError: (operation, error) => { throw new Error(operation, { cause: error }); }, + }); + const backend = spawn(process.execPath, ["--input-type=module", "-e", childCode], { + stdio: ["ignore", "ignore", "inherit", "ipc"], + detached: true, + }); + await once(backend, "spawn"); + const record = await recovery.track(backend.pid); + if (!record) throw new Error("Backend fixture was not recorded"); + const listening = once(backend, "message"); + backend.send("start"); + const [port] = await listening; + process.send({ pid: backend.pid, port }); + await once(backend, "exit"); + await unlink(record); +`; + +async function spawnTrackedBackend( + appDataDirectory: string, + stateDir: string, + cleanup: AsyncDisposableStack, +) { + const moduleUrl = new URL("./DesktopBackendRecovery.ts", import.meta.url).href; + const launcher = NodeChildProcess.spawn( + NodeProcess.execPath, + ["--input-type=module", "-e", launcherCode, moduleUrl, appDataDirectory, stateDir, childCode], + { stdio: ["ignore", "ignore", "inherit", "ipc"] }, + ); + const exited = NodeEvents.EventEmitter.once(launcher, "exit"); + const stopLauncher = async () => { + launcher.kill("SIGKILL"); + await exited; + }; + cleanup.defer(stopLauncher); + const backend = await Promise.race([ + NodeEvents.EventEmitter.once(launcher, "message").then( + ([message]) => message as { pid: number; port: number }, + ), + exited.then(() => { + throw new Error("Fixture launcher exited before its backend was ready"); + }), + ]); + const native = await loadMacProcessAuditToken(); + const token = native.read(backend.pid); + assert.isDefined(token); + cleanup.defer(() => native.signal(token, "SIGKILL")); + return { ...backend, token, stopLauncher }; +} + +async function checkPortIsFree(port: number) { + const listener = NodeNet.createServer(); + listener.listen(port, "127.0.0.1"); + try { + await NodeEvents.EventEmitter.once(listener, "listening"); + } finally { + await new Promise((resolve) => listener.close(() => resolve())); + } +} + +describe.runIf(NodeProcess.platform === "darwin")("macOS desktop backend recovery", () => { + it("cleans up a truncated record only after the writer releases it", async () => { + await using cleanup = new AsyncDisposableStack(); + const stateDir = await NodeFSP.realpath( + await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-record-")), + ); + cleanup.defer(() => NodeFSP.rm(stateDir, { recursive: true, force: true })); + const directory = NodePath.join(stateDir, "t3code-backend-recovery"); + await NodeFSP.mkdir(directory, { mode: 0o700 }); + const scope = NodeCrypto.createHash("sha256") + .update(JSON.stringify([stateDir, await NodeFSP.realpath(NodeProcess.execPath)])) + .digest("hex"); + const path = () => NodePath.join(directory, `${scope}.${NodeCrypto.randomUUID()}.json`); + const partial = path(); + const future = path(); + const unsafe = path(); + await NodeFSP.writeFile(future, '{"version":2}', { mode: 0o600 }); + await NodeFSP.writeFile(unsafe, "{", { mode: 0o600 }); + await NodeFSP.chmod(unsafe, 0o644); + const errors: unknown[] = []; + const recovered: number[] = []; + const recovery = make({ + appDataDirectory: stateDir, + stateDir, + launcherPid: NodeProcess.pid, + onRecovery: (pid) => recovered.push(pid), + onError: (_, error) => errors.push(error), + }); + { + // Darwin O_EXLOCK keeps the record private to the writer until close or exit. + await using writer = await NodeFSP.open( + partial, + NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL | 0x20, + 0o600, + ); + await writer.writeFile('{"version":'); + await recovery.recover(); + assert.equal(await NodeFSP.readFile(partial, "utf8"), '{"version":'); + } + await recovery.recover(); + await recovery.recover(); + await expect(NodeFSP.stat(partial)).rejects.toMatchObject({ code: "ENOENT" }); + assert.equal(await NodeFSP.readFile(future, "utf8"), '{"version":2}'); + assert.equal(await NodeFSP.readFile(unsafe, "utf8"), "{"); + assert.deepEqual(recovered, []); + assert.deepEqual(errors, []); + }); + + it("releases a frozen orphan's port and leaves a backend with a live launcher running", async () => { + await using cleanup = new AsyncDisposableStack(); + const appDataDirectory = await NodeFSP.mkdtemp( + NodePath.join(NodeOS.tmpdir(), "t3-backend-recovery-"), + ); + cleanup.defer(() => NodeFSP.rm(appDataDirectory, { recursive: true, force: true })); + // The first launcher records ownership before the home exists. + const stateDir = NodePath.join(appDataDirectory, "home", "userdata"); + const orphan = await spawnTrackedBackend(appDataDirectory, stateDir, cleanup); + await NodeFSP.mkdir(stateDir, { recursive: true }); + const live = await spawnTrackedBackend(appDataDirectory, stateDir, cleanup); + const native = await loadMacProcessAuditToken(); + const recovered: number[] = []; + const errors: unknown[] = []; + const recovery = make({ + appDataDirectory, + stateDir, + launcherPid: NodeProcess.pid, + onRecovery: (pid) => recovered.push(pid), + onError: (_, error) => errors.push(error), + }); + + NodeProcess.kill(orphan.pid, "SIGSTOP"); + await orphan.stopLauncher(); + await expect(checkPortIsFree(orphan.port)).rejects.toMatchObject({ code: "EADDRINUSE" }); + + const wrongVersion = Buffer.from(live.token, "hex"); + wrongVersion[28] = wrongVersion[28]! ^ 1; + native.signal(wrongVersion.toString("hex"), "SIGKILL"); + assert.equal(native.read(live.pid), live.token); + + const otherHome = make({ + appDataDirectory, + stateDir: NodePath.join(stateDir, "other"), + launcherPid: NodeProcess.pid, + onRecovery: (pid) => recovered.push(pid), + onError: (_, error) => errors.push(error), + }); + await otherHome.recover(); + assert.deepEqual(recovered, []); + + const records = NodePath.join(appDataDirectory, "t3code-backend-recovery"); + for (const name of await NodeFSP.readdir(records)) + await NodeFSP.chmod(NodePath.join(records, name), 0o644); + await recovery.recover(); + assert.deepEqual(recovered, []); + assert.equal(native.read(orphan.pid), orphan.token); + for (const name of await NodeFSP.readdir(records)) + await NodeFSP.chmod(NodePath.join(records, name), 0o600); + + await recovery.recover(); + assert.deepEqual(errors, []); + assert.deepEqual(recovered, [orphan.pid]); + assert.isUndefined(native.read(orphan.pid)); + await checkPortIsFree(orphan.port); + assert.equal(native.read(live.pid), live.token); + }); +}); diff --git a/apps/desktop/src/backend/DesktopBackendRecovery.ts b/apps/desktop/src/backend/DesktopBackendRecovery.ts new file mode 100644 index 000000000000..3077b6922400 --- /dev/null +++ b/apps/desktop/src/backend/DesktopBackendRecovery.ts @@ -0,0 +1,300 @@ +// @effect-diagnostics nodeBuiltinImport:off - Secure record opens require O_NOFOLLOW and fstat. +import * as NodeChildProcess from "node:child_process"; +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; +import * as NodeProcess from "node:process"; +import * as NodeTimersPromises from "node:timers/promises"; +import * as NodeUtil from "node:util"; + +import { + auditTokenPid, + isProcessAuditToken, + loadMacProcessAuditToken, + type MacProcessAuditToken, +} from "./MacProcessAuditToken.ts"; + +const exec = NodeUtil.promisify(NodeChildProcess.execFile); +const directoryName = "t3code-backend-recovery"; +const maxRecordBytes = 512; +// Darwin sys/fcntl.h. Node accepts these open flags but does not export them. +const O_SHLOCK = 0x10; +const O_EXLOCK = 0x20; +const observedFileName = /^[0-9a-f]{64}\.[0-9a-f-]{36}\.json$/; +const scopePattern = /^[0-9a-f]{64}$/; +const bootIdPattern = /^[0-9a-f-]{36}$/i; +const terminateGraceMs = 5_000; +const killGraceMs = 1_000; +const pollIntervalMs = 250; + +interface RecoveryRecord { + readonly version: 1; + readonly bootId: string; + readonly scope: string; + readonly launcher: string; + readonly backend: string; +} + +type RecordReadResult = RecoveryRecord | "incomplete" | undefined; + +function decodeRecord(raw: string): RecordReadResult { + try { + const value = JSON.parse(raw) as Partial | null; + if ( + value?.version !== 1 || + typeof value.bootId !== "string" || + !bootIdPattern.test(value.bootId) || + typeof value.scope !== "string" || + !scopePattern.test(value.scope) || + !isProcessAuditToken(value.launcher) || + !isProcessAuditToken(value.backend) + ) { + return undefined; + } + const owner = auditTokenPid(value.launcher); + const child = auditTokenPid(value.backend); + if (owner <= 1 || child <= 1 || owner > 0x7fff_ffff || child > 0x7fff_ffff || owner === child) { + return undefined; + } + return { + version: 1, + bootId: value.bootId, + scope: value.scope, + launcher: value.launcher, + backend: value.backend, + }; + } catch { + return "incomplete"; + } +} + +const isErrorCode = (error: unknown, code: string) => + (error as NodeJS.ErrnoException)?.code === code; + +function ownsPrivateFile(info: { uid: number; mode: number }): boolean { + return info.uid === NodeProcess.getuid?.() && (info.mode & 0o077) === 0; +} + +async function readRecord(path: string): Promise { + const file = await NodeFSP.open( + path, + NodeFS.constants.O_RDONLY | + NodeFS.constants.O_NOFOLLOW | + NodeFS.constants.O_NONBLOCK | + O_SHLOCK, + ); + try { + const info = await file.stat(); + if ( + !info.isFile() || + info.nlink !== 1 || + !ownsPrivateFile(info) || + info.size > maxRecordBytes + ) { + return undefined; + } + const bytes = Buffer.alloc(maxRecordBytes + 1); + const { bytesRead } = await file.read(bytes); + return bytesRead > maxRecordBytes + ? undefined + : decodeRecord(bytes.toString("utf8", 0, bytesRead)); + } finally { + await file.close(); + } +} + +type ProcessStatus = "same" | "gone" | "unknown"; + +function status(native: MacProcessAuditToken, token: string): ProcessStatus { + const target = auditTokenPid(token); + const observed = native.read(target); + if (observed !== undefined) return observed === token ? "same" : "gone"; + try { + NodeProcess.kill(target, 0); + return "unknown"; + } catch (error) { + return isErrorCode(error, "ESRCH") ? "gone" : "unknown"; + } +} + +async function waitForExit( + native: MacProcessAuditToken, + token: string, + graceMs: number, + signal: AbortSignal, +): Promise { + const deadline = performance.now() + graceMs; + while (performance.now() < deadline) { + if (status(native, token) === "gone") return true; + await NodeTimersPromises.setTimeout(pollIntervalMs, undefined, { signal }); + } + return status(native, token) === "gone"; +} + +async function recoverRecord( + native: MacProcessAuditToken, + record: RecoveryRecord, + options: { launcherPid: number; signal: AbortSignal; onRecovery: (pid: number) => void }, +): Promise { + const backendPid = auditTokenPid(record.backend); + if (backendPid === options.launcherPid) return false; + // The launch record already binds the executable. Its vnode may be gone after + // a volume disconnect, but the kernel still knows the recorded audit token. + const ownsOrphan = () => + status(native, record.launcher) === "gone" && + status(native, record.backend) === "same" && + native.parent(backendPid) === 1; + + if (status(native, record.backend) === "gone") return true; + if (!ownsOrphan()) return false; + + options.signal.throwIfAborted(); + options.onRecovery(backendPid); + native.signal(record.backend, "SIGTERM"); + if (await waitForExit(native, record.backend, terminateGraceMs, options.signal)) return true; + if (!ownsOrphan()) return false; + options.signal.throwIfAborted(); + native.signal(record.backend, "SIGKILL"); + return waitForExit(native, record.backend, killGraceMs, options.signal); +} + +async function readBootId(): Promise { + const { stdout } = await exec("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"], { + timeout: 1_000, + }); + const bootId = stdout.trim(); + if (!bootIdPattern.test(bootId)) throw new Error("Could not identify the current macOS boot"); + return bootId; +} + +// A first launch can precede creation of the state directory. Resolve existing +// ancestors so a symlinked home keeps the same key after that directory appears. +async function canonicalHome(path: string): Promise { + try { + return await NodeFSP.realpath(path); + } catch (error) { + if (!isErrorCode(error, "ENOENT") || NodePath.dirname(path) === path) throw error; + return NodePath.join(await canonicalHome(NodePath.dirname(path)), NodePath.basename(path)); + } +} + +export function make(input: { + readonly appDataDirectory: string; + readonly stateDir: string; + /** The desktop main process; this module runs in a helper so native calls stay off main. */ + readonly launcherPid: number; + readonly onRecovery: (pid: number) => void; + readonly onError: (operation: string, error: unknown) => void; +}) { + // Use Application Support even when the T3 home or the app lives on removable storage. + const directory = NodePath.join(input.appDataDirectory, directoryName); + const scope = async () => { + const [home, executable] = await Promise.all([ + canonicalHome(input.stateDir), + NodeFSP.realpath(NodeProcess.execPath), + ]); + const prefix = NodeCrypto.createHash("sha256") + .update(JSON.stringify([home, executable])) + .digest("hex"); + return { prefix, executable }; + }; + const privateDirectory = async () => { + const info = await NodeFSP.lstat(directory); + if (!info.isDirectory() || !ownsPrivateFile(info)) { + throw new Error("Backend recovery records must be in an owner-only directory"); + } + }; + + return { + /** Returns the record path, which the launcher removes after observing the backend exit. */ + async track(backendPid: number): Promise { + try { + const [native, bootId, { prefix, executable }] = await Promise.all([ + loadMacProcessAuditToken(), + readBootId(), + scope(), + ]); + const launcher = native.read(input.launcherPid); + const backend = native.read(backendPid); + // A token and executable alone do not prove this desktop actually spawned this process. + if ( + launcher === undefined || + backend === undefined || + native.parent(backendPid) !== input.launcherPid || + native.executable(backendPid) !== executable || + native.read(backendPid) !== backend + ) { + throw new Error("Could not verify desktop ownership of the backend"); + } + await NodeFSP.mkdir(directory, { mode: 0o700 }).catch((error) => { + if (!isErrorCode(error, "EEXIST")) throw error; + }); + await privateDirectory(); + const path = NodePath.join(directory, `${prefix}.${NodeCrypto.randomUUID()}.json`); + // Take the lock at creation so recovery can distinguish a partial write from a crash. + { + await using file = await NodeFSP.open( + path, + NodeFS.constants.O_WRONLY | + NodeFS.constants.O_CREAT | + NodeFS.constants.O_EXCL | + O_EXLOCK, + 0o600, + ); + await file.writeFile( + JSON.stringify({ version: 1, bootId, scope: prefix, launcher, backend }), + ); + } + return path; + } catch (error) { + input.onError("record backend", error); + return undefined; + } + }, + async recover(signal: AbortSignal = new AbortController().signal): Promise { + try { + await privateDirectory(); + const { prefix } = await scope(); + const records = (await NodeFSP.readdir(directory)).filter( + (name) => name.startsWith(`${prefix}.`) && observedFileName.test(name), + ); + if (records.length === 0) return; + + const [bootId, native] = await Promise.all([readBootId(), loadMacProcessAuditToken()]); + await Promise.all( + records.map(async (name) => { + const path = NodePath.join(directory, name); + try { + const record = await readRecord(path); + if ( + record === "incomplete" || + (record !== undefined && + record.scope === prefix && + (record.bootId !== bootId || + (await recoverRecord(native, record, { + launcherPid: input.launcherPid, + signal, + onRecovery: input.onRecovery, + })))) + ) { + await NodeFSP.unlink(path); + } + } catch (error) { + // EAGAIN means the launcher is still writing this record. + if ( + !signal.aborted && + !isErrorCode(error, "ENOENT") && + !isErrorCode(error, "EAGAIN") + ) { + input.onError("recover backend", error); + } + } + }), + ); + } catch (error) { + if (!isErrorCode(error, "ENOENT")) input.onError("read backend records", error); + } + }, + }; +} diff --git a/apps/desktop/src/backend/DesktopBackendRecoveryProcess.ts b/apps/desktop/src/backend/DesktopBackendRecoveryProcess.ts new file mode 100644 index 000000000000..8ff505235aff --- /dev/null +++ b/apps/desktop/src/backend/DesktopBackendRecoveryProcess.ts @@ -0,0 +1,99 @@ +// @effect-diagnostics globalTimers:off -- Worker deadlines run at child-process callback boundaries outside Effect fibers. +// @effect-diagnostics nodeBuiltinImport:off -- This desktop-only helper owns a Node child process. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; + +export type RecoveryWorkerMessage = + | { readonly type: "recovering"; readonly pid: number } + | { readonly type: "error"; readonly operation: string } + | { readonly type: "tracked"; readonly record: string }; + +const trackDeadlineMs = 5_000; +// Covers the worker's SIGTERM and SIGKILL grace periods with room to start. +const recoverDeadlineMs = 10_000; + +/** Runs recovery's native process inspection in a helper so a stall cannot block desktop main. */ +export function make(input: { + readonly appDataDirectory: string; + readonly stateDir: string; + readonly onRecovery: (pid: number) => void; + readonly onError: (operation: string) => void; +}) { + const run = ( + operation: "track" | "recover", + deadlineMs: number, + options: { readonly backendPid?: number; readonly signal?: AbortSignal } = {}, + ) => + new Promise((resolve) => { + let record: string | undefined; + let worker: NodeChildProcess.ChildProcess; + try { + worker = NodeChildProcess.fork( + // Main is bundled to dist-electron/main.cjs; the worker is a separate entry under it. + NodePath.join(__dirname, "backend", "DesktopBackendRecoveryWorker.cjs"), + [ + operation, + input.appDataDirectory, + input.stateDir, + String(process.pid), + ...(options.backendPid === undefined ? [] : [String(options.backendPid)]), + ], + { + // The default macOS Helper executable would not match the backend's recorded executable. + execPath: process.execPath, + env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" }, + execArgv: [], + stdio: ["ignore", "ignore", "inherit", "ipc"], + }, + ); + } catch { + input.onError("start recovery worker"); + resolve(undefined); + return; + } + let settled = false; + const finish = () => { + if (settled) return; + settled = true; + clearTimeout(deadline); + options.signal?.removeEventListener("abort", stop); + resolve(record); + }; + const stop = () => { + worker.kill("SIGKILL"); + finish(); + }; + const deadline = setTimeout(() => { + input.onError(`${operation} deadline`); + stop(); + }, deadlineMs); + deadline.unref(); + if (options.signal?.aborted) stop(); + else options.signal?.addEventListener("abort", stop, { once: true }); + worker.on("message", (raw) => { + const message = raw as RecoveryWorkerMessage; + if (message.type === "recovering") input.onRecovery(message.pid); + else if (message.type === "error") input.onError(message.operation); + else record = message.record; + }); + worker.once("error", () => { + input.onError("recovery worker"); + stop(); + }); + worker.once("exit", finish); + }); + + return { + track: async (backendPid: number) => { + const record = await run("track", trackDeadlineMs, { backendPid }); + if (record === undefined) return undefined; + return () => + NodeFSP.unlink(record).catch((error: NodeJS.ErrnoException) => { + if (error.code !== "ENOENT") input.onError("forget backend"); + }); + }, + recover: (signal: AbortSignal) => + run("recover", recoverDeadlineMs, { signal }).then(() => undefined), + }; +} diff --git a/apps/desktop/src/backend/DesktopBackendRecoveryWorker.ts b/apps/desktop/src/backend/DesktopBackendRecoveryWorker.ts new file mode 100644 index 000000000000..3751c39f51f1 --- /dev/null +++ b/apps/desktop/src/backend/DesktopBackendRecoveryWorker.ts @@ -0,0 +1,36 @@ +import { make } from "./DesktopBackendRecovery.ts"; +import type { RecoveryWorkerMessage } from "./DesktopBackendRecoveryProcess.ts"; + +process.once("disconnect", () => process.exit(0)); + +const pending: Array> = []; +const send = (message: RecoveryWorkerMessage) => { + const sent = new Promise((resolve) => { + if (process.send === undefined) resolve(); + else process.send(message, () => resolve()); + }); + pending.push(sent); + return sent; +}; + +async function run() { + const [operation, appDataDirectory, stateDir, launcherPid, backendPid] = process.argv.slice(2); + if (appDataDirectory === undefined || stateDir === undefined) return; + const recovery = make({ + appDataDirectory, + stateDir, + launcherPid: Number(launcherPid), + onRecovery: (pid) => void send({ type: "recovering", pid }), + onError: (failed) => void send({ type: "error", operation: failed }), + }); + if (operation === "track") { + const record = await recovery.track(Number(backendPid)); + if (record !== undefined) await send({ type: "tracked", record }); + } else if (operation === "recover") { + await recovery.recover(); + } +} + +void run() + .then(() => Promise.all(pending)) + .finally(() => process.disconnect?.()); diff --git a/apps/desktop/src/backend/MacProcessAuditToken.ts b/apps/desktop/src/backend/MacProcessAuditToken.ts new file mode 100644 index 000000000000..53ce7ab57ca2 --- /dev/null +++ b/apps/desktop/src/backend/MacProcessAuditToken.ts @@ -0,0 +1,121 @@ +import * as NodeOS from "node:os"; + +// mach/task_info.h: TASK_AUDIT_TOKEN returns eight native uint32_t values. +const TASK_AUDIT_TOKEN = 15; +const AUDIT_TOKEN_WORDS = 8; +const AUDIT_TOKEN_BYTES = AUDIT_TOKEN_WORDS * Uint32Array.BYTES_PER_ELEMENT; +const AUDIT_TOKEN_PID_OFFSET = 5 * Uint32Array.BYTES_PER_ELEMENT; +const PROC_PIDPATH_MAXSIZE = 4096; +// sys/proc_info.h: proc_bsdshortinfo begins with the PID and parent PID. +const PROC_PIDT_SHORTBSDINFO = 13; +const PROC_PIDT_SHORTBSDINFO_SIZE = 64; + +export const isProcessAuditToken = (value: unknown): value is string => + typeof value === "string" && /^[0-9a-f]{64}$/.test(value); + +export const auditTokenPid = (token: string): number => + Buffer.from(token, "hex").readUInt32LE(AUDIT_TOKEN_PID_OFFSET); + +export interface MacProcessAuditToken { + readonly read: (pid: number) => string | undefined; + readonly executable: (pid: number) => string | undefined; + readonly parent: (pid: number) => number | undefined; + readonly signal: (token: string, signal: "SIGTERM" | "SIGKILL") => void; +} + +let macProcessAuditToken: Promise | undefined; + +/** Signals a kernel process identity so a PID reused after verification cannot receive the signal. */ +export const loadMacProcessAuditToken = (): Promise => + (macProcessAuditToken ??= import("ffi-rs").then(({ DataType, load, open }) => { + const library = "t3-macos-process-identity"; + open({ library, path: "/usr/lib/libSystem.B.dylib" }); + const self = load({ + library, + funcName: "mach_task_self", + retType: DataType.U32, + paramsType: [], + paramsValue: [], + }); + + return { + read(pid) { + const task = Buffer.alloc(4); + const nameResult = load({ + library, + funcName: "task_name_for_pid", + retType: DataType.I32, + paramsType: [DataType.U32, DataType.I32, DataType.U8Array], + paramsValue: [self, pid, task], + }); + if (nameResult !== 0) return undefined; + + const port = task.readUInt32LE(); + try { + const token = Buffer.alloc(AUDIT_TOKEN_BYTES); + const count = Buffer.alloc(4); + count.writeUInt32LE(AUDIT_TOKEN_WORDS); + const infoResult = load({ + library, + funcName: "task_info", + retType: DataType.I32, + paramsType: [DataType.U32, DataType.I32, DataType.U8Array, DataType.U8Array], + paramsValue: [port, TASK_AUDIT_TOKEN, token, count], + }); + return infoResult === 0 && + count.readUInt32LE() === AUDIT_TOKEN_WORDS && + token.readUInt32LE(AUDIT_TOKEN_PID_OFFSET) === pid + ? token.toString("hex") + : undefined; + } finally { + load({ + library, + funcName: "mach_port_deallocate", + retType: DataType.I32, + paramsType: [DataType.U32, DataType.U32], + paramsValue: [self, port], + }); + } + }, + executable(pid) { + const path = Buffer.alloc(PROC_PIDPATH_MAXSIZE); + const length = load({ + library, + funcName: "proc_pidpath", + retType: DataType.I32, + paramsType: [DataType.I32, DataType.U8Array, DataType.U32], + paramsValue: [pid, path, path.byteLength], + }); + return length > 0 && length <= path.byteLength + ? path.toString("utf8", 0, length).replace(/\0$/, "") + : undefined; + }, + parent(pid) { + const info = Buffer.alloc(PROC_PIDT_SHORTBSDINFO_SIZE); + const length = load({ + library, + funcName: "proc_pidinfo", + retType: DataType.I32, + paramsType: [DataType.I32, DataType.I32, DataType.BigInt, DataType.U8Array, DataType.I32], + paramsValue: [pid, PROC_PIDT_SHORTBSDINFO, 0n, info, info.byteLength], + }); + return length === info.byteLength && info.readUInt32LE() === pid + ? info.readUInt32LE(4) + : undefined; + }, + signal(token, name) { + if (!isProcessAuditToken(token)) throw new Error("Invalid macOS audit token"); + const result = load({ + library, + funcName: "proc_signal_with_audittoken", + retType: DataType.I32, + paramsType: [DataType.U8Array, DataType.I32], + paramsValue: [Buffer.from(token, "hex"), NodeOS.constants.signals[name]], + }); + // ESRCH includes a process that exited or was replaced after the last observation. + if (result !== 0 && result !== NodeOS.constants.errno.ESRCH) { + throw new Error(`macOS could not deliver ${name} (errno ${result})`); + } + }, + }; + })); diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index 33f3ac5e8aaf..611ddac05046 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -54,8 +54,7 @@ export class ElectronMenu extends Context.Service< readonly setApplicationMenu: ( template: readonly Electron.MenuItemConstructorOptions[], ) => Effect.Effect; - /** macOS native editing actions, without a renderer round trip. */ - readonly sendActionToFirstResponder: (action: string) => Effect.Effect; + readonly pasteAndMatchStyle: Effect.Effect; readonly showContextMenu: ( input: ElectronMenuContextInput, ) => Effect.Effect>; @@ -194,9 +193,14 @@ export const make = Effect.gen(function* () { }; return ElectronMenu.of({ - sendActionToFirstResponder: Effect.fn("ElectronMenu.sendActionToFirstResponder")((action) => - Effect.sync(() => Electron.Menu.sendActionToFirstResponder(action)), - ), + pasteAndMatchStyle: Effect.sync(() => { + const focused = Electron.webContents.getFocusedWebContents(); + // A mounted guest can report focus while the host owns the focused frame. + const target = focused?.hostWebContents ?? focused; + if (target && !target.isDestroyed()) { + target.pasteAndMatchStyle(); + } + }), setApplicationMenu: Effect.fn("ElectronMenu.setApplicationMenu")(function (template) { return Effect.try({ try: () => { diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 8e96129293fc..b086f6782918 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -50,6 +50,10 @@ const makeDebuggee = ( readonly deferFocus?: boolean; /** The guest is still loading its first page. */ readonly loading?: boolean; + /** Like a guest of a hidden window: it answers a capture only once Electron captures it. */ + readonly drawsOnlyWhenCaptured?: () => boolean; + /** Electron's capture of this guest never settles. */ + readonly capturesStall?: () => boolean; readonly refuse?: (method: string, sessionId: string | undefined) => boolean; } = {}, ) => { @@ -90,7 +94,14 @@ const makeDebuggee = ( }), }); let destroyed = false; + let nativeCaptures = 0; const webContents = Object.assign(new NodeEvents.EventEmitter(), { + capturePage: () => { + nativeCaptures += 1; + if (options.capturesStall?.()) return new Promise(() => {}); + if (options.drawsOnlyWhenCaptured?.()) pending.splice(0).forEach((resolve) => resolve()); + return Promise.resolve({}); + }, getURL: () => "http://localhost/", getTitle: () => "Page", getUserAgent: () => "Electron", @@ -117,6 +128,7 @@ const makeDebuggee = ( /** Refuses the pending command the debugger received with this id. */ refuse: (id: number) => rejects[sent.indexOf(id)]?.(), focusEmulation, + nativeCaptures: () => nativeCaptures, nextSend: () => new Promise((resolve) => sendWaiters.push(resolve)), release: () => pending.splice(0).forEach((resolve) => resolve()), releaseFirst: () => pending.shift()?.(), @@ -364,6 +376,91 @@ describe("DesktopBrowserHost", () => { }).pipe(Effect.scoped), ); + it.effect("prods a guest its window stopped drawing until what waits on it settles", () => + Effect.gen(function* () { + let drawsWhenCaptured = true; + let capturesStall = false; + const host = yield* makeDrawnHost; + const debuggee = makeDebuggee({ + drawsOnlyWhenCaptured: () => drawsWhenCaptured, + capturesStall: () => capturesStall, + }); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + const painting = yield* watchPainting(host); + + yield* command(host, 1, "Page.captureScreenshot"); + yield* settle; + expect(debuggee.sent).toEqual([1]); + yield* TestClock.adjust("250 millis"); + expect(yield* Queue.take(replies)).toBe(1); + expect(debuggee.nativeCaptures()).toBe(1); + + // A wait that settles within a frame is never prodded. + yield* command(host, 3, "Page.captureScreenshot"); + yield* settle; + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(3); + yield* TestClock.adjust("1 second"); + expect(debuggee.nativeCaptures()).toBe(1); + + // A long wait is prodded less often as it goes on, once per tick though it holds focus too. + drawsWhenCaptured = false; + yield* command(host, 4, "Page.captureScreenshot"); + yield* settle; + for (const [wait, prods] of [ + ["250 millis", 2], + ["500 millis", 3], + ["1 second", 4], + ["2 seconds", 5], + ["2 seconds", 6], + ] as const) { + yield* TestClock.adjust(wait); + expect(debuggee.nativeCaptures()).toBe(prods); + } + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(4); + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(6); + + // A command that outlasts its first prod is painted like a capture, which also unthrottles it. + // A wait the agent's turn gave up on is no longer prodded. + yield* command(host, 5, "Runtime.evaluate"); + yield* settle; + painting.length = 0; + yield* TestClock.adjust("250 millis"); + expect(debuggee.nativeCaptures()).toBe(7); + expect(painting).toEqual([true]); + yield* host.handleCommandLine( + encodeJson({ type: "turn", threadId: key.threadId, active: false }), + ); + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(7); + expect(painting).toEqual([true, false]); + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(5); + + // Captures Electron never settles pile up no further than two. + capturesStall = true; + yield* command(host, 6, "Runtime.evaluate"); + yield* settle; + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(9); + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(6); + // Even across a reattach of the same guest, as when DevTools closes. + host.detach(key); + host.attach(key, debuggee.tab); + const reattached = yield* watchReplies(host); + yield* command(host, 7, "Runtime.evaluate"); + yield* settle; + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(9); + debuggee.releaseFirst(); + expect(yield* Queue.take(reattached)).toBe(7); + }).pipe(Effect.scoped), + ); + it.effect("stops waiting on a screenshot the page navigated away from", () => Effect.gen(function* () { const host = yield* makeDrawnHost; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index ce5d7074a786..b3812e90d54b 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -32,6 +32,12 @@ const POINTER_TRAVEL = new Set(["mouseMoved", "mouseWheel"]); const FOCUS_IDLE = "5 seconds"; /** How long a screenshot waits for the client to draw its guest at full detail. */ const CAPTURE_DRAW_WAIT = "1 second"; +/** Most waits settle within a frame or two of this, so a quick one is never prodded. */ +const PAINT_NUDGE_FIRST_MS = 250; +/** A long wait, such as a page awaiting a timer, is prodded less often as it goes on. */ +const PAINT_NUDGE_LONGEST_MS = 2_000; +/** Electron's capture has no deadline and a cold guest can stall one, so a second may follow. */ +const PAINT_NUDGE_IN_FLIGHT = 2; /** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */ const FIRST_PAGE_TIMEOUT = "5 seconds"; const ERR_ABORTED = -3; @@ -73,6 +79,11 @@ interface AttachedTab { readonly focusPending: Map; /** Screenshots Chromium was sent and has not answered; each keeps its wake lock until then. */ readonly capturing: Set; + /** Each wait on the guest's next frame, as whether it still waits; the guest is prodded until none do. */ + readonly frameWaits: Set<() => boolean>; + nudging: Fiber.Fiber | null; + /** A wait outlasted its first nudge, so the guest is painted and unthrottled like a capture. */ + frameStalled: boolean; /** Whether the client keeps the guest painting, as published on `painting`. */ painting: boolean; /** @@ -243,7 +254,7 @@ export const make = Effect.gen(function* () { }; /** - * Electron composites no offscreen guest, so its screenshot or screencast waits for a frame + * Electron composites no offscreen guest, so a screenshot, screencast or stalled command waits for a frame * that never comes. The client paints the guest behind the app while one is pending; the * capture then finishes on its own, and the guest goes back offscreen once none is. */ @@ -252,12 +263,78 @@ export const make = Effect.gen(function* () { tabs.get(keyOf(tab.key)) === tab && (tab.screencasts.size > 0 || tab.capturing.size > 0 || + tab.frameStalled || tab.waitingScreenshots.some((waiting) => waiting.live())); if (tab.painting === active) return; tab.painting = active; runFork(PubSub.publish(painting, { key: tab.key, active })); }; + /** By guest rather than attachment, since reopening DevTools reattaches the same guest. */ + const nativeCaptures = new WeakMap(); + const startNudging = (tab: AttachedTab) => { + tab.nudging ??= runFork(nudgePaint(tab, PAINT_NUDGE_FIRST_MS)); + }; + + const endNudging = (tab: AttachedTab) => { + tab.nudging = null; + if (!tab.frameStalled) return; + tab.frameStalled = false; + syncPainting(tab); + }; + + /** + * A hidden, minimized or covered window (which Electron reports as visible) stops drawing its + * guest, so a wait on its next frame never ends. Electron's own capture still draws one. + */ + const nudgePaint = (tab: AttachedTab, delayMs: number): Effect.Effect => + Effect.sleep(delayMs).pipe( + Effect.andThen( + Effect.suspend(() => { + const { webContents } = tab.debuggee; + for (const waits of tab.frameWaits) if (!waits()) tab.frameWaits.delete(waits); + if ( + tab.frameWaits.size === 0 || + tabs.get(keyOf(tab.key)) !== tab || + webContents.isDestroyed() + ) { + endNudging(tab); + return Effect.void; + } + // On Windows a hidden window's throttled guest draws nothing, and capturePage cannot wake it. + if (!tab.frameStalled) { + tab.frameStalled = true; + syncPainting(tab); + } + const inFlight = nativeCaptures.get(webContents) ?? 0; + if (inFlight < PAINT_NUDGE_IN_FLIGHT) { + nativeCaptures.set(webContents, inFlight + 1); + const settled = () => { + nativeCaptures.set(webContents, (nativeCaptures.get(webContents) ?? 1) - 1); + }; + webContents.capturePage().then(settled, settled); + } + return nudgePaint(tab, Math.min(delayMs * 2, PAINT_NUDGE_LONGEST_MS)); + }), + ), + ); + + /** Prods the guest while `work` is pending and `waits` holds; one loop serves all of a tab's waits. */ + const nudgedUntilSettled = ( + tab: AttachedTab, + waits: () => boolean, + work: () => Promise, + ) => { + tab.frameWaits.add(waits); + startNudging(tab); + return work().finally(() => { + tab.frameWaits.delete(waits); + if (tab.frameWaits.size > 0 || tab.nudging === null) return; + runFork(Fiber.interrupt(tab.nudging)); + endNudging(tab); + }); + }; + /** A command may wait on the page's next frame, so the guest stays focused until it settles. */ const holdFocus = (tab: AttachedTab, owner: string | undefined, work: () => Promise) => { const pending = {}; @@ -265,7 +342,8 @@ export const make = Effect.gen(function* () { tab.focusUses += 1; setFocusEmulation(tab, true); releaseFocusWhenIdle(tab); - return work().finally(() => { + // Dropping the hold, at a turn's end or a new document, stops the prods too. + return nudgedUntilSettled(tab, () => tab.focusPending.has(pending), work).finally(() => { if (!tab.focusPending.delete(pending)) return; tab.focusUses += 1; releaseFocusWhenIdle(tab); @@ -296,11 +374,14 @@ export const make = Effect.gen(function* () { const sent = {}; tab.capturing.add(sent); syncPainting(tab); + const sendNudged = () => nudgedUntilSettled(tab, () => tab.capturing.has(sent), send); // Sent at once when already drawn, so it keeps its place among the commands after it. - return (drawnTabs.has(keyOf(tab.key)) ? send() : whenDrawn(tab).then(send)).finally(() => { - tab.capturing.delete(sent); - syncPainting(tab); - }); + return (drawnTabs.has(keyOf(tab.key)) ? sendNudged() : whenDrawn(tab).then(sendNudged)).finally( + () => { + tab.capturing.delete(sent); + syncPainting(tab); + }, + ); }; /** @@ -537,6 +618,9 @@ export const make = Effect.gen(function* () { focusUses: 0, focusPending: new Map(), capturing: new Set(), + frameWaits: new Set(), + nudging: null, + frameStalled: false, painting: false, agentUsed: false, focusReleasing: false, diff --git a/apps/desktop/src/quickMessage/DesktopQuickMessage.test.ts b/apps/desktop/src/quickMessage/DesktopQuickMessage.test.ts index e14652688cea..16b15cb0d20e 100644 --- a/apps/desktop/src/quickMessage/DesktopQuickMessage.test.ts +++ b/apps/desktop/src/quickMessage/DesktopQuickMessage.test.ts @@ -381,7 +381,7 @@ const layerTest = (main: { webContents: FakeWebContents } | null, revealed: Arra menuOwners.push(input.window as unknown as FakePanel); }), setApplicationMenu: () => Effect.void, - sendActionToFirstResponder: () => Effect.void, + pasteAndMatchStyle: Effect.void, showContextMenu: () => Effect.succeedNone, }), Layer.mock(ElectronShell.ElectronShell)({ diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index 867a9521e09c..16d01813677d 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -1,4 +1,5 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { assert, describe, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -10,7 +11,7 @@ import * as Electron from "electron"; import { vi } from "vite-plus/test"; vi.mock("electron", () => ({ - webContents: { getAllWebContents: vi.fn(() => []) }, + webContents: { getAllWebContents: vi.fn(() => []), getFocusedWebContents: vi.fn() }, })); import * as ElectronApp from "../electron/ElectronApp.ts"; @@ -124,24 +125,23 @@ const layerDesktopWindow = ( const layerElectronMenu = ( applicationMenuTemplate: Deferred.Deferred, - nativeAction?: Deferred.Deferred, + platform: NodeJS.Platform, ) => - Layer.succeed(ElectronMenu.ElectronMenu, { - sendActionToFirstResponder: (action) => - nativeAction - ? Deferred.succeed(nativeAction, action).pipe(Effect.asVoid) - : Effect.die("unexpected native menu action"), - setApplicationMenu: (template) => - Deferred.succeed(applicationMenuTemplate, template).pipe(Effect.asVoid), - popupTemplate: () => Effect.void, - showContextMenu: () => Effect.succeedNone, - } satisfies ElectronMenu.ElectronMenu["Service"]); + Layer.effect( + ElectronMenu.ElectronMenu, + ElectronMenu.make.pipe( + Effect.map((menu) => ({ + ...menu, + setApplicationMenu: (template: readonly Electron.MenuItemConstructorOptions[]) => + Deferred.succeed(applicationMenuTemplate, template).pipe(Effect.asVoid), + })), + ), + ).pipe(Layer.provide(Layer.succeed(HostProcess.Platform, platform))); const configureMenu = ( selectedAction: Deferred.Deferred, applicationMenuTemplate: Deferred.Deferred, environment: Partial = {}, - nativeAction?: Deferred.Deferred, dispatches?: Array<{ readonly action: string; readonly options: DesktopWindow.DesktopMenuDispatchOptions | undefined; @@ -154,7 +154,12 @@ const configureMenu = ( }).pipe( Effect.provide( DesktopApplicationMenu.layer.pipe( - Layer.provideMerge(layerElectronMenu(applicationMenuTemplate, nativeAction)), + Layer.provideMerge( + layerElectronMenu( + applicationMenuTemplate, + environment.platform ?? environmentInput.platform, + ), + ), Layer.provideMerge(layerDesktopWindow(selectedAction, dispatches)), Layer.provideMerge(layerDesktopUpdates(services)), Layer.provideMerge(layerElectronDialog(services)), @@ -178,7 +183,6 @@ const checkForUpdatesFromMacMenu = (state: Partial) => applicationMenuTemplate, { platform: "darwin" }, undefined, - undefined, { checkResult: { checked: true, @@ -218,6 +222,29 @@ const checkForUpdatesFromMacMenu = (state: Partial) => return yield* dialog.value; }); +const pressPasteAsText = ( + template: readonly Electron.MenuItemConstructorOptions[], +): ((focused: object) => void) => { + const editMenu = template.find((item) => item.label === "Edit"); + if (!Array.isArray(editMenu?.submenu)) { + throw new Error("Expected Edit menu submenu to be an array."); + } + const pasteAsTextItem = editMenu.submenu.find((item) => item.label === "Paste as Text"); + assert.equal(pasteAsTextItem?.accelerator, "CmdOrCtrl+Shift+V"); + const click = pasteAsTextItem?.click; + if (typeof click !== "function") { + throw new Error("Expected Paste as Text menu item to have a click handler."); + } + return (focused) => { + using _focused = vi + .spyOn(Electron.webContents, "getFocusedWebContents") + .mockReturnValue(focused as Electron.WebContents); + click({} as Electron.MenuItem, undefined, { + triggeredByAccelerator: true, + } as unknown as KeyboardEvent); + }; +}; + describe("DesktopApplicationMenu", () => { it.effect("keeps display branding in the macOS application menu", () => Effect.gen(function* () { @@ -262,7 +289,7 @@ describe("DesktopApplicationMenu", () => { readonly options: DesktopWindow.DesktopMenuDispatchOptions | undefined; }> = []; - yield* configureMenu(selectedAction, applicationMenuTemplate, {}, undefined, dispatches); + yield* configureMenu(selectedAction, applicationMenuTemplate, {}, dispatches); const template = yield* Deferred.await(applicationMenuTemplate); const fileMenu = template.find((item) => item.label === "File"); @@ -297,7 +324,6 @@ describe("DesktopApplicationMenu", () => { selectedAction, applicationMenuTemplate, { platform: "darwin" }, - undefined, dispatches, ); @@ -330,70 +356,46 @@ describe("DesktopApplicationMenu", () => { }), ); - it.effect("uses the native macOS paste action without injecting a renderer paste", () => - Effect.gen(function* () { - const selectedAction = yield* Deferred.make(); - const nativeAction = yield* Deferred.make(); - const applicationMenuTemplate = - yield* Deferred.make(); - yield* configureMenu( - selectedAction, - applicationMenuTemplate, - { platform: "darwin" }, - nativeAction, - ); - const template = yield* Deferred.await(applicationMenuTemplate); - const editMenu = template.find((item) => item.label === "Edit"); - if (!Array.isArray(editMenu?.submenu)) { - throw new Error("Expected Edit menu submenu to be an array."); - } - const pasteAsTextItem = editMenu.submenu.find((item) => item.label === "Paste as Text"); - if (typeof pasteAsTextItem?.click !== "function") { - throw new Error("Expected Paste as Text menu item to have a click handler."); - } - pasteAsTextItem.click( - {} as Electron.MenuItem, - {} as Electron.BrowserWindow, - { triggeredByAccelerator: true } as unknown as KeyboardEvent, - ); - assert.equal(yield* Deferred.await(nativeAction), "pasteAndMatchStyle:"); - assert.isFalse(yield* Deferred.isDone(selectedAction)); - }), + it.effect.each(["linux", "win32"] as const)( + "leaves the %s accelerator to Chromium instead of injecting a paste", + (platform) => + Effect.gen(function* () { + const selectedAction = yield* Deferred.make(); + const applicationMenuTemplate = + yield* Deferred.make(); + + yield* configureMenu(selectedAction, applicationMenuTemplate, { platform }); + + const focused = { isDestroyed: () => false, pasteAndMatchStyle: vi.fn() }; + pressPasteAsText(yield* Deferred.await(applicationMenuTemplate))(focused); + assert.equal(focused.pasteAndMatchStyle.mock.calls.length, 0); + assert.isFalse(yield* Deferred.isDone(selectedAction)); + }), ); - // On Windows/Linux Chromium pastes for the accelerator on its own. Dispatching - // the renderer action would also call pasteAsText and duplicate that paste. - it.effect("leaves the accelerator to Chromium instead of injecting a paste", () => + it.effect("pastes natively and synchronously for the macOS accelerator", () => Effect.gen(function* () { const selectedAction = yield* Deferred.make(); const applicationMenuTemplate = yield* Deferred.make(); - const dispatches: Array<{ - readonly action: string; - readonly options: DesktopWindow.DesktopMenuDispatchOptions | undefined; - }> = []; - yield* configureMenu(selectedAction, applicationMenuTemplate, {}, undefined, dispatches); - - const template = yield* Deferred.await(applicationMenuTemplate); - const editMenu = template.find((item) => item.label === "Edit"); - if (!Array.isArray(editMenu?.submenu)) { - throw new Error("Expected Edit menu submenu to be an array."); - } - const pasteAsTextItem = editMenu.submenu.find((item) => item.label === "Paste as Text"); - if (typeof pasteAsTextItem?.click !== "function") { - throw new Error("Expected Paste as Text menu item to have a click handler."); - } - - pasteAsTextItem.click( - {} as Electron.MenuItem, - {} as Electron.BrowserWindow, - { - triggeredByAccelerator: true, - } as unknown as KeyboardEvent, - ); + yield* configureMenu(selectedAction, applicationMenuTemplate, { platform: "darwin" }); + const press = pressPasteAsText(yield* Deferred.await(applicationMenuTemplate)); + + const host = { isDestroyed: () => false, pasteAndMatchStyle: vi.fn() }; + press(host); + assert.equal(host.pasteAndMatchStyle.mock.calls.length, 1); + + // Electron reports a mounted preview guest as focused while the host's composer has focus. + const guest = { + isDestroyed: () => false, + pasteAndMatchStyle: vi.fn(), + hostWebContents: host, + }; + press(guest); + assert.equal(host.pasteAndMatchStyle.mock.calls.length, 2); + assert.equal(guest.pasteAndMatchStyle.mock.calls.length, 0); assert.isFalse(yield* Deferred.isDone(selectedAction)); - assert.deepEqual(dispatches, []); }), ); diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index 8423f0577e94..1db231f60031 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -193,6 +193,7 @@ export const make = Effect.gen(function* () { const context = yield* Effect.context(); const runPromise = Effect.runPromiseWith(context); const runFork = Effect.runForkWith(context); + const runSync = Effect.runSyncWith(context); const runMenuEffect = ( action: string, @@ -217,22 +218,20 @@ export const make = Effect.gen(function* () { const settingsClick = () => { runMenuEffect("open-settings", dispatchMenuAction("open-settings")); }; - // macOS shortcuts use native editing; a renderer round trip can duplicate the terminal fallback. - // Mouse clicks use the renderer so the composer arms its inline paste bypass. const pasteAsTextClick = ( _item: Electron.MenuItem, _window: Electron.BaseWindow | undefined, event: Electron.KeyboardEvent, ) => { if (event.triggeredByAccelerator === true) { + // Chromium pastes this chord itself except on macOS. Paste synchronously there: + // a renderer round trip can land after the terminal's own clipboard read. if (environment.platform === "darwin") { - runMenuEffect( - "paste-as-text", - electronMenu.sendActionToFirstResponder("pasteAndMatchStyle:"), - ); + runSync(electronMenu.pasteAndMatchStyle); } return; } + // The composer needs the renderer event to keep the menu paste inline. runMenuEffect("paste-as-text", dispatchMenuAction("paste-as-text")); }; const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => { diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 982c5c76536c..b4cbe54fd718 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -203,7 +203,7 @@ const layerDesktopServerExposure = Layer.succeed(DesktopServerExposure.DesktopSe } satisfies DesktopServerExposure.DesktopServerExposure["Service"]); const layerElectronMenu = Layer.succeed(ElectronMenu.ElectronMenu, { - sendActionToFirstResponder: () => Effect.die("unexpected native menu action"), + pasteAndMatchStyle: Effect.void, setApplicationMenu: () => Effect.void, popupTemplate: () => Effect.void, showContextMenu: () => Effect.succeedNone, @@ -349,7 +349,7 @@ function layerTest(input: { DesktopState.layer, layerElectronApp, Layer.succeed(ElectronMenu.ElectronMenu, { - sendActionToFirstResponder: () => Effect.die("unexpected native menu action"), + pasteAndMatchStyle: Effect.void, setApplicationMenu: () => Effect.void, showContextMenu: () => Effect.succeedNone, popupTemplate: input.onPopupTemplate ?? (() => Effect.void), diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index 6ded8e851ddb..42063f99b63a 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -90,6 +90,7 @@ export default defineConfig({ outExtensions: () => ({ js: ".cjs" }), define: publicConfigDefine, entry: [ + "src/backend/DesktopBackendRecoveryWorker.ts", "src/electron/WindowsForegroundFocusWorker.ts", "src/snapShot/GlobalShiftShortcutWorker.ts", "src/snapShot/RegionSnapShotWorker.ts", diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt index 3b45931f87eb..617915efa668 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt @@ -69,6 +69,15 @@ class T3WorkspaceNavigationModule : Module() { Name("T3WorkspaceNavigation") View(T3WorkspaceNavigationView::class) { Prop("tabs") { view: T3WorkspaceNavigationView, value: List -> view.tabs = value } + Prop("tabTitles") { view: T3WorkspaceNavigationView, value: Map -> + view.tabTitles = value + } + Prop("expandedTabTitles") { view: T3WorkspaceNavigationView, value: Map -> + view.expandedTabTitles = value + } + Prop("newThreadTitle") { view: T3WorkspaceNavigationView, value: String -> + view.newThreadTitle = value + } Prop("selectedTab") { view: T3WorkspaceNavigationView, value: String -> view.selectedTab = value } @@ -127,6 +136,9 @@ class T3WorkspaceNavigationView( private val onNewThread by EventDispatcher() private val onOverlayChange by EventDispatcher() var tabs by mutableStateOf(listOf("threads", "pullRequests", "issues", "usage", "settings")) + var tabTitles by mutableStateOf(emptyMap()) + var expandedTabTitles by mutableStateOf(emptyMap()) + var newThreadTitle by mutableStateOf("New thread") var selectedTab by mutableStateOf("threads") var rail by mutableStateOf(false) var floating by mutableStateOf(false) @@ -356,7 +368,7 @@ class T3WorkspaceNavigationView( .height(FAB_SIZE) .width(lerp(FAB_SIZE, EXPANDED_RAIL_WIDTH - RAIL_INSET * 2, fraction)) .alpha(if (newEnabled) 1f else DISABLED_ALPHA) - .semantics { contentDescription = "New thread" }, + .semantics { contentDescription = newThreadTitle }, ) { Row( Modifier.padding(start = (FAB_SIZE - ICON_SIZE) / 2).clipToBounds(), @@ -364,7 +376,7 @@ class T3WorkspaceNavigationView( ) { Icon(painterResource(R.drawable.t3_new_thread), contentDescription = null) Text( - "New thread", + newThreadTitle, Modifier.padding(start = 12.dp).alpha(labelAlpha(fraction)).clearAndSetSemantics {}, style = MaterialTheme.typography.labelLarge, fontSize = (14 * textScale).sp, @@ -412,7 +424,7 @@ class T3WorkspaceNavigationView( } } - private fun tabTitle(tab: String) = when (tab) { + private fun tabTitle(tab: String) = tabTitles[tab] ?: when (tab) { "threads" -> "Chats" "pullRequests" -> "Pulls" "issues" -> "Issues" @@ -422,7 +434,7 @@ class T3WorkspaceNavigationView( } private fun expandedTabTitle(tab: String) = - if (tab == "pullRequests") "Pull requests" else tabTitle(tab) + expandedTabTitles[tab] ?: if (tab == "pullRequests") "Pull requests" else tabTitle(tab) @Composable private fun tabIconPainter(tab: String) = painterResource( diff --git a/apps/mobile/src/features/layout/workspace/AndroidWorkspaceNavigation.android.tsx b/apps/mobile/src/features/layout/workspace/AndroidWorkspaceNavigation.android.tsx index 382336367e2f..6276fcc2ef8c 100644 --- a/apps/mobile/src/features/layout/workspace/AndroidWorkspaceNavigation.android.tsx +++ b/apps/mobile/src/features/layout/workspace/AndroidWorkspaceNavigation.android.tsx @@ -1,5 +1,10 @@ -import { selectedNavigationTab, visibleNavigationTabs } from "./navigation-tab-order"; +import { + NAVIGATION_TAB_LABELS, + selectedNavigationTab, + visibleNavigationTabs, +} from "./navigation-tab-order"; import { requireNativeView } from "expo"; +import { msg, useGT, useMessages } from "gt-react-native"; import { CommonActions, useNavigation } from "@react-navigation/native"; import { Keyboard, @@ -35,6 +40,9 @@ interface NativeNavigationProps extends ViewProps { readonly rail: boolean; readonly floating: boolean; readonly tabs: readonly string[]; + readonly tabTitles: Readonly>; + readonly expandedTabTitles: Readonly>; + readonly newThreadTitle: string; readonly selectedTab: AndroidWorkspaceNavigationTab; readonly dark: boolean; readonly textScale: number; @@ -55,6 +63,12 @@ interface NativeNavigationProps extends ViewProps { readonly onOverlayChange: (event: NativeSyntheticEvent<{ readonly overlay: boolean }>) => void; } +const TAB_TITLES = { + ...NAVIGATION_TAB_LABELS, + threads: msg("Chats", { $context: "navigation tab, list of chat threads" }), + settings: msg("Settings"), +}; + const NativeNavigation = requireNativeView("T3WorkspaceNavigation"); function nativeColor(value: string) { @@ -73,6 +87,8 @@ export function AndroidWorkspaceNavigation(props: { readonly onOverlayChange?: (overlay: boolean) => void; }) { const workspace = useWorkspaceTabs()!; + const gt = useGT(); + const m = useMessages(); const order = useNavigationTabOrder(); const hidden = useHiddenNavigationTabs(); const root = useAndroidWorkspaceRoot(); @@ -87,7 +103,7 @@ export function AndroidWorkspaceNavigation(props: { const window = useWindowDimensions(); const rail = Boolean(props.rail); const floating = !rail && Boolean(props.floating); - const tabs = [...visibleNavigationTabs(order, hidden, rail ? 5 : 4), "settings"]; + const tabs = [...visibleNavigationTabs(order, hidden, rail ? 5 : 4), "settings" as const]; const { containerColor, indicatorColor, selectedColor, unselectedColor } = androidWorkspaceNavigationColors(colors, rail, floating); const selectedTab = selectedNavigationTab( @@ -120,6 +136,9 @@ export function AndroidWorkspaceNavigation(props: { rail={rail} floating={floating} tabs={tabs} + tabTitles={Object.fromEntries(tabs.map((tab) => [tab, m(TAB_TITLES[tab])]))} + expandedTabTitles={{ pullRequests: gt("Pull requests") }} + newThreadTitle={gt("New thread")} selectedTab={selectedTab} dark={themeAppearance === "dark"} textScale={scale} diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index ff495d8145ea..95017cc243bf 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -1206,7 +1206,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { title: gt("Rename", { $context: "verb, thread action" }), image: "square.and.pencil", }, - { id: "mark-unread", title: gt("Mark unread"), image: "envelope.badge" }, + ...(thread.latestRun?.completedAt != null && threadCanArchive(thread.runtime) + ? [{ id: "mark-unread", title: gt("Mark unread"), image: "envelope.badge" }] + : []), ...buildThreadTitleRegenerationMenuItems( { supported: props.titleRegenerationSupported, diff --git a/apps/mobile/src/i18n/native-locale.test.ts b/apps/mobile/src/i18n/native-locale.test.ts new file mode 100644 index 000000000000..781eae9e898f --- /dev/null +++ b/apps/mobile/src/i18n/native-locale.test.ts @@ -0,0 +1,55 @@ +import * as NodeChildProcess from "node:child_process"; +import * as NodeURL from "node:url"; +import { expect, it } from "vite-plus/test"; + +it("uses the new Android locale before native storage finishes writing it", () => { + // Load the real GT store in a subprocess because mobile's Vite config replaces GT. + const output = NodeChildProcess.execFileSync( + process.execPath, + [ + "--input-type=module", + "-e", + ` + import { createRequire, registerHooks } from "node:module"; + import { pathToFileURL } from "node:url"; + + const require = createRequire(process.cwd() + "/package.json"); + const gtEntry = pathToFileURL(require.resolve("gt-react-native")); + const androidBridge = "data:text/javascript," + encodeURIComponent(\` + const preferences = new Map(); + export const pending = []; + export const Platform = { OS: "android" }; + export const TurboModuleRegistry = { + getEnforcing: () => ({ + getNativeLocales: () => ["en-US"], + nativeStoreGet: (key) => preferences.get(key) ?? null, + nativeStoreSet: (key, value) => { + pending.push(() => preferences.set(key, value)); + }, + }), + }; + \`); + const hooks = registerHooks({ + resolve(specifier, context, nextResolve) { + return specifier === "react-native" + ? { url: androidBridge, shortCircuit: true } + : nextResolve(specifier, context); + }, + }); + const { initializeGT } = await import(new URL("./setup/initializeGT.js", gtEntry)); + const { NativeConditionStore } = await import( + new URL("./condition-store/NativeConditionStore.js", gtEntry) + ); + const { pending } = await import(androidBridge); + hooks.deregister(); + + initializeGT({ defaultLocale: "en", locales: ["en", "zh"] }); + new NativeConditionStore({ locale: "en" }); + for (const apply of pending.splice(0)) apply(); + console.log(new NativeConditionStore({ locale: "zh" }).getLocale()); + `, + ], + { cwd: NodeURL.fileURLToPath(new URL("../../", import.meta.url)), encoding: "utf8" }, + ); + expect(output.trim()).toBe("zh"); +}); diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 64831512a9ef..0f3f8519bddc 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -1306,8 +1306,16 @@ describe("AssetAccess", () => { const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-asset-revision-" }); const pages = path.join(root, "pages"); yield* fileSystem.makeDirectory(pages); + // Coarse kernel clocks can stamp two quick same-size writes alike, so each edit gets its own mtime. + let editedAt = 1_000; const write = (name: string, text: string) => - fileSystem.writeFileString(path.join(pages, name), text); + fileSystem + .writeFileString(path.join(pages, name), text) + .pipe( + Effect.andThen( + Effect.promise(() => NodeFSP.utimes(path.join(pages, name), ++editedAt, editedAt)), + ), + ); yield* write("a.html", ''); yield* write("a.css", "body { color: red; }"); yield* write("b.html", "

b

"); diff --git a/apps/server/src/cli/environment.test.ts b/apps/server/src/cli/environment.test.ts index 9ad17441add6..2fcdc88589e6 100644 --- a/apps/server/src/cli/environment.test.ts +++ b/apps/server/src/cli/environment.test.ts @@ -5,6 +5,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { NodeHttpServer } from "@effect/platform-node"; import * as NodeServices from "@effect/platform-node/NodeServices"; import type { ExecutionEnvironmentDescriptor } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NetService from "@t3tools/shared/Net"; import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -101,7 +102,7 @@ it.effect("links a file of environments, reports each line, and fails when one d retry, `${one.url} ${firstCode}\n${two.url} ${yield* codeFor(two)}\n${three.url} never-valid\n`, ); - yield* link(retry); + yield* link("~/retry.txt").pipe(Effect.provideService(HostProcess.HomeDirectory, baseDir)); const retried = (yield* reports).at(-1) ?? ""; expect(retried).toContain( `${one.url}: already linked as VM 1 (environment-vm-1), left as it is`, diff --git a/apps/server/src/cli/environment.ts b/apps/server/src/cli/environment.ts index ab55715e721c..a4b47ebbe8c5 100644 --- a/apps/server/src/cli/environment.ts +++ b/apps/server/src/cli/environment.ts @@ -29,6 +29,7 @@ import * as PeerLinks from "../peer/PeerLinks.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { expandHomePath } from "../os-jank.ts"; import { authLocationFlags, type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts"; /** @@ -201,7 +202,7 @@ const readLinkBatch = Effect.fn("environment.readLinkBatch")(function* (from: st ); } const fs = yield* FileSystem.FileSystem; - return yield* fs.readFileString(from); + return yield* fs.readFileString(yield* expandHomePath(from)); }); const environmentLinkCommand = Command.make("link", { diff --git a/apps/server/src/cli/install.test.ts b/apps/server/src/cli/install.test.ts index f7aaeca3120c..f7d8b1df86d7 100644 --- a/apps/server/src/cli/install.test.ts +++ b/apps/server/src/cli/install.test.ts @@ -212,17 +212,32 @@ it.layer(NodeServices.layer)("t3 install", (it) => { const globalBin = path.join(root, "global-bin"); yield* fs.makeDirectory(globalBin); yield* fs.writeFileString(path.join(globalBin, "t3"), ""); + yield* fs.chmod(path.join(globalBin, "t3"), 0o755); yield* offer(false, { env: { PATH: globalBin } }); assert.equal(asked, 0); assert.isFalse(yield* fs.exists(link)); - // A runner's own .bin on PATH is not an installed t3. + // A directory or non-executable file named `t3` on PATH is not an installed t3. + const dirBin = path.join(root, "dir-bin"); + yield* fs.makeDirectory(path.join(dirBin, "t3"), { recursive: true }); + const nonExecBin = path.join(root, "non-exec-bin"); + yield* fs.makeDirectory(nonExecBin); + yield* fs.writeFileString(path.join(nonExecBin, "t3"), ""); + assert.isFalse(yield* offer(undefined, { env: { PATH: dirBin } })); + assert.equal(asked, 1); + assert.isFalse(yield* offer(undefined, { env: { PATH: nonExecBin } })); + assert.equal(asked, 2); + asked = 0; + + // A runner's own .bin on PATH, even found through a bare launcher record, is not an installed t3. const npxBin = path.join(npmPackage, "../.bin"); const pnpmBin = path.join(root, ".cache/pnpm/dlx/abc/node_modules/.bin"); for (const bin of [npxBin, pnpmBin]) { yield* fs.makeDirectory(bin, { recursive: true }); yield* fs.writeFileString(path.join(bin, "t3"), ""); + yield* fs.chmod(path.join(bin, "t3"), 0o755); } + yield* fs.writeFileString(path.join(runtimeDir, "launchers"), "t3\n"); assert.isFalse(yield* offer(undefined, { env: { PATH: `${npxBin}:${pnpmBin}` } })); assert.equal(asked, 1); assert.isFalse(yield* fs.exists(path.join(runtimeDir, "install-prompt-declined"))); diff --git a/apps/server/src/cli/install.ts b/apps/server/src/cli/install.ts index 4e6420842dc9..b789930b2cfb 100644 --- a/apps/server/src/cli/install.ts +++ b/apps/server/src/cli/install.ts @@ -322,7 +322,7 @@ export const offerCliInstall = Effect.fn("cli.install.offer")(function* "")); const candidates = [ - ...launchers.split(/\r?\n/).filter(Boolean), + ...launchers.split(/\r?\n/).filter((launcher) => path.isAbsolute(launcher)), path.join(path.dirname(runtimeDir), "bin", windows ? "t3.cmd" : "t3"), ...(environment.PATH ?? environment.Path ?? "") .split(windows ? ";" : ":") @@ -332,7 +332,7 @@ export const offerCliInstall = Effect.fn("cli.install.offer")(function* names.map((name) => path.join(directory, name))), ]; for (const candidate of candidates) { - if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) return true; + if (yield* resolveCommandPath(candidate, { env: environment })) return true; } const declinedFile = path.join(runtimeDir, "install-prompt-declined"); diff --git a/apps/server/src/cli/invocation.test.ts b/apps/server/src/cli/invocation.test.ts index 668b86c9b025..844971bb206c 100644 --- a/apps/server/src/cli/invocation.test.ts +++ b/apps/server/src/cli/invocation.test.ts @@ -8,6 +8,7 @@ import * as Path from "effect/Path"; import packageJson from "../../package.json" with { type: "json" }; import { posixLauncherScript } from "../cloud/pinnedRuntime.ts"; import { + hostShellWord, resolveHostCliCommand, resolveRootCliCommand, resolveServerInstallation, @@ -187,6 +188,40 @@ it.layer(NodeServices.layer)("host CLI commands", (it) => { ); }), ); + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "names the absolute path of a t3 found through a relative PATH entry", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const bin = yield* fs.makeTempDirectoryScoped(); + yield* fs.writeFileString(path.join(bin, "t3"), "#!/bin/sh\n", { mode: 0o755 }); + const hostCommand = (searchPath: string) => + resolveHostCliCommand("doctor").pipe( + Effect.provideService(HostProcess.ExecutablePath, "/usr/bin/node"), + Effect.provideService(HostProcess.Arguments, [ + "/usr/bin/node", + "/opt/t3/lib/node_modules/t3/dist/bin.mjs", + ]), + Effect.provideService(HostProcess.IsExecutable, false), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Environment, { PATH: searchPath }), + ); + + // A relative entry was searched from this process's directory, unlike the user's shell. + expect(yield* hostCommand(path.relative(process.cwd(), bin))).toEqual({ + command: `${hostShellWord("linux", path.join(bin, "t3"))} doctor`, + launcher: false, + }); + // An empty entry makes the shell search its own directory first, wherever that is. + expect(yield* hostCommand(`:${bin}`)).toEqual({ + command: `${hostShellWord("linux", path.join(bin, "t3"))} doctor`, + launcher: false, + }); + expect(yield* hostCommand(bin)).toEqual({ command: "t3 doctor", launcher: false }); + }), + ); }); it.layer(NodeServices.layer)("manual server installation ownership", (it) => { diff --git a/apps/server/src/cli/invocation.ts b/apps/server/src/cli/invocation.ts index 4804d44f0e32..69a3a5815bbd 100644 --- a/apps/server/src/cli/invocation.ts +++ b/apps/server/src/cli/invocation.ts @@ -205,7 +205,16 @@ export const resolveHostCliCommand = Effect.fn("invocation.resolveHostCliCommand ) : null; if (own === null || own === (yield* real(onPath))) { - return { command: withArgs(command), launcher: false }; + const path = yield* Path.Path; + const searchPath = (yield* HostProcess.Environment).PATH ?? ""; + // With an empty or relative PATH entry, plain `t3` depends on the directory it runs from. + const cwdDependent = + platform !== "win32" && + searchPath.length > 0 && + searchPath.split(":").some((entry) => !path.isAbsolute(entry)); + if (!cwdDependent) return { command: withArgs(command), launcher: false }; + const quoted = hostShellWord(platform, path.resolve(onPath)); + return { command: withArgs(`${quoted} ${subcommand}`), launcher: false }; } } const launcher = yield* resolveInstallLauncher; diff --git a/apps/server/src/cli/policy.test.ts b/apps/server/src/cli/policy.test.ts index 7066cceebcd0..d06998ff4288 100644 --- a/apps/server/src/cli/policy.test.ts +++ b/apps/server/src/cli/policy.test.ts @@ -1,12 +1,16 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import { Command } from "effect/cli"; +import { cli } from "../binCli.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import { makePersistedServerRuntimeState, @@ -16,7 +20,7 @@ import { describeRunningServer } from "./policy.ts"; const encodeState = Schema.encodeEffect(Schema.fromJsonString(PersistedServerRuntimeState)); -it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => +it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => { it.effect("tells whether the running server loaded the installed policy", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -53,5 +57,32 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => assert.include(yield* running(null, null), "runs without a policy, as installed"); assert.include(yield* running(undefined), "does not report which policy it loaded"); }), - ), -); + ); + + it.effect("templates reads a ~/ --policy file from the home directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-policy-templates-" }); + yield* fs.writeFileString( + path.join(home, "policy.json"), + JSON.stringify({ schemaVersion: 1, organization: "Tilde Corp" }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })([ + "policy", + "templates", + home, + "--policy=~/policy.json", + ]).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + Effect.provide(NetService.layer), + ); + + assert.include( + yield* fs.readFileString(path.join(home, "macos", "t3code.mobileconfig")), + "Tilde Corp", + ); + }), + ); +}); diff --git a/apps/server/src/cli/policy.ts b/apps/server/src/cli/policy.ts index dafc5352166f..c48e2bc535a6 100644 --- a/apps/server/src/cli/policy.ts +++ b/apps/server/src/cli/policy.ts @@ -13,6 +13,7 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import { listManageableSettings } from "../policy/managedSettings.ts"; import { macosProfile, windowsAdml, windowsAdmx } from "../policy/policyTemplates.ts"; +import { expandHomePath } from "../os-jank.ts"; import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; @@ -132,13 +133,14 @@ const templatesCommand = Command.make("templates", { const path = yield* Path.Path; let document = SAMPLE_POLICY; if (Option.isSome(policy)) { - if (!(yield* fs.exists(policy.value))) { + const file = yield* expandHomePath(policy.value); + if (!(yield* fs.exists(file))) { return yield* new CliError.UserError({ cause: policy.value, userMessage: `No policy file at ${policy.value}.`, }); } - const loaded = (yield* ManagedPolicy.load(policy.value)).document; + const loaded = (yield* ManagedPolicy.load(file)).document; if (loaded !== undefined) document = loaded; } const random = yield* SecureRandom.SecureRandom; diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.ts index ada548ba2bf3..70907ab446a0 100644 --- a/apps/server/src/cli/service.test.ts +++ b/apps/server/src/cli/service.test.ts @@ -288,6 +288,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands const { service, uninstalls } = makeTestService({ ...status, installedBaseDir: input.otherHome ? "/home/me/.t3" : baseDir, + ...(input.otherHome ? { otherBaseDir: "/home/me/.t3" } : {}), }); vi.spyOn(BootService, "layer").mockReturnValue( Layer.succeed( diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts index fc2aa8d0889a..4c55d1fa329d 100644 --- a/apps/server/src/cli/service.ts +++ b/apps/server/src/cli/service.ts @@ -325,19 +325,14 @@ const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags). flags, Effect.gen(function* () { const service = yield* BootService.BootService; - const path = yield* Path.Path; - const { baseDir } = yield* ServerConfig.ServerConfig; // An unreadable unit stays removable; only a unit known to serve another home is kept. - const installedBaseDir = yield* service.status.pipe( - Effect.map((status) => status.installedBaseDir), + const otherBaseDir = yield* service.status.pipe( + Effect.map((status) => status.otherBaseDir), Effect.orElseSucceed(() => undefined), ); - if ( - installedBaseDir !== undefined && - path.resolve(installedBaseDir) !== path.resolve(baseDir) - ) { + if (otherBaseDir !== undefined) { yield* Console.log( - `The T3 Code service serves ${installedBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(installedBaseDir)}\` to remove it.`, + `The T3 Code service serves ${otherBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(otherBaseDir)}\` to remove it.`, ); return; } diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index 52e38b394069..dfec29529fb3 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -541,17 +541,29 @@ it.effect("--output-schema reads a ~/ path from the home directory", () => }).pipe(Effect.provide(NodeServices.layer)), ); -/** Serves t3_thread_read pages the way the server does: positions count every item. */ +/** Serves t3_thread_read pages the way the server does: positions count every item, and a cursorless read is the newest page. */ const timelineTools = (types: ReadonlyArray) => { const items = types.map((type, position) => ({ position, itemId: `item-${position}`, type })); const served: Array = []; const call = ((_tool: string, input: unknown) => { const args = input as { readonly afterPosition?: number; readonly limit: number }; + const isMessage = (item: (typeof items)[number]) => + ["user_message", "assistant_message", "proposed_plan"].includes(item.type); + if (args.afterPosition === undefined) { + const page = items.filter(isMessage).slice(-args.limit); + served.push(page.length); + return Effect.succeed({ + thread: { itemCount: items.length }, + items: page, + nextPosition: null, + hasMore: false, + }); + } // Scanning one match past the page keeps reads of huge fixtures linear. const matching: typeof items = []; - for (let position = (args.afterPosition ?? -1) + 1; position < items.length; position++) { + for (let position = args.afterPosition + 1; position < items.length; position++) { const item = items[position]!; - if (["user_message", "assistant_message", "proposed_plan"].includes(item.type)) { + if (isMessage(item)) { matching.push(item); if (matching.length > args.limit) break; } diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 2b25c0fd38b8..0137f3441bb1 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -436,7 +436,7 @@ const readTimeline = Effect.fn("cli.thread.readTimeline")(function* ( view: "messages" | "activity", ) { const items: Array = []; - let afterPosition: number | undefined; + let afterPosition: number | null = -1; let page: OrchestratorMcpThreadReadResult; do { page = yield* tools.call( @@ -447,13 +447,13 @@ const readTimeline = Effect.fn("cli.thread.readTimeline")(function* ( limit: READ_PAGE_LIMIT, maxCharsPerItem: READ_ITEM_MAX_CHARS, runLimit: 1, - ...(afterPosition === undefined ? {} : { afterPosition }), + afterPosition, }, OrchestratorMcpThreadReadResult, ); items.push(...page.items); - afterPosition = page.nextPosition ?? undefined; - } while (page.hasMore && afterPosition !== undefined); + afterPosition = page.nextPosition; + } while (page.hasMore && afterPosition !== null); return { thread: page.thread, items }; }); @@ -493,7 +493,7 @@ export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(fun limit: READ_PAGE_LIMIT, maxCharsPerItem: READ_ITEM_MAX_CHARS, runLimit: 1, - ...(afterPosition < 0 ? {} : { afterPosition }), + afterPosition, }, OrchestratorMcpThreadReadResult, ); @@ -945,7 +945,7 @@ const threadStartCommand = Command.make("start", { ), option: Flag.String("option").pipe( Flag.withDescription( - "Model option as id=value, such as effort=high. Repeat for more. Needs --provider and --model.", + "Model option as id=value (Codex: reasoningEffort=high; Claude: effort=high). Ids depend on the model. Repeat for more. Needs --provider and --model.", ), Flag.atLeast(0), ), diff --git a/apps/server/src/cli/triage.test.ts b/apps/server/src/cli/triage.test.ts index a6c50af4168c..6782826c299a 100644 --- a/apps/server/src/cli/triage.test.ts +++ b/apps/server/src/cli/triage.test.ts @@ -193,3 +193,51 @@ it.live("a failed agent launch points at the prompt it could not run", () => ), ), ); + +it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "starts an agent found through a relative PATH entry from the session directory", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const binDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-bin-" }); + // Relative to this process, as an entry like "." is to the server that checked it. + const relativeBinDir = NodePath.relative(process.cwd(), binDir); + // Nested deeper than the entry climbs, so from the session directory it leads nowhere. + const climbs = relativeBinDir.split(NodePath.sep).filter((part) => part === "..").length; + const baseDir = NodePath.join( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-cli-" }), + ...Array.from({ length: climbs }, () => "nested"), + ); + NodeFS.mkdirSync(baseDir, { recursive: true }); + NodeFS.writeFileSync(NodePath.join(binDir, "codex"), FAILING_AGENT_POSIX, { mode: 0o755 }); + yield* Effect.acquireRelease( + Effect.sync(() => { + vi.stubEnv("PATH", relativeBinDir); + vi.stubEnv("CODEX_HOME", NodePath.join(baseDir, "codex-home")); + }), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + const previousExitCode = process.exitCode; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + process.exitCode = previousExitCode; + }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })([ + "triage", + "--agent", + "codex", + "--base-dir", + baseDir, + ]); + + // The fake agent ran and exited 1, rather than failing to start. + assert.equal(process.exitCode, 1); + assert.include((yield* TestConsole.logLines).join("\n"), "Codex exited with code 1."); + }).pipe( + Effect.provide( + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer), + ), + ), +); diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.ts index cb0f94b25458..df73347cd9fe 100644 --- a/apps/server/src/cli/triage.ts +++ b/apps/server/src/cli/triage.ts @@ -4,7 +4,8 @@ import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeReadlinePromises from "node:readline/promises"; -import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { isCommandAvailable, resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell"; import * as Config from "effect/Config"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; @@ -220,7 +221,14 @@ export const triageCommand = Command.make("triage", { const model = Option.getOrUndefined(flags.model); const launchPrompt = buildTriageLaunchPrompt(promptFilePath); - const spawnSpec = yield* resolveSpawnCommand(selected.command, [ + // The agent starts in the session directory, so a PATH match relative to this one would + // be searched from there. Windows keeps the bare name for its .cmd shim handling. + const onPath = + (yield* HostProcess.Platform) === "win32" + ? null + : yield* resolveCommandPath(selected.command); + const command = onPath === null ? selected.command : NodePath.resolve(onPath); + const spawnSpec = yield* resolveSpawnCommand(command, [ ...(model === undefined ? [] : ["--model", model]), ...(selected.promptArgs ?? []), launchPrompt, diff --git a/apps/server/src/cli/uninstall.test.ts b/apps/server/src/cli/uninstall.test.ts index c22760da5345..19093032fc3d 100644 --- a/apps/server/src/cli/uninstall.test.ts +++ b/apps/server/src/cli/uninstall.test.ts @@ -89,23 +89,38 @@ it.live("reports failure when the Windows cleanup shell cannot start", () => ); it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall command", (it) => { - it.effect("names another home's service it leaves installed", () => + it.effect.each([ + { + label: "names another home's service it leaves installed", + otherFromRead: 1, + removed: [], + output: "--base-dir '/home/me/.t3'", + }, + { + label: "leaves a service that serves another home by the time it is removed", + otherFromRead: 2, + removed: [], + output: "Left the background service: it now serves another T3 home.", + }, + ])("$label", (input) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-cli-test-" }); const uninstalls: Array = []; + let reads = 0; vi.spyOn(BootService, "layer").mockReturnValue( Layer.succeed( BootService.BootService, BootService.BootService.of({ - status: Effect.succeed({ + status: Effect.sync(() => ({ supported: true, installed: true, current: true, installedBaseDir: "/home/me/.t3", + ...(++reads >= input.otherFromRead ? { otherBaseDir: "/home/me/.t3" } : {}), unitPath: "/home/me/.config/systemd/user/t3code.service", logPath: "/home/me/.t3/userdata/logs/boot-service.log", - }), + })), withStopped: (operation) => operation, restart: Effect.die("unexpected restart"), install: () => Effect.die("unexpected install"), @@ -133,8 +148,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall com ), ), ); - assert.deepStrictEqual(uninstalls, []); - assert.include(output, "--base-dir '/home/me/.t3'"); + assert.deepStrictEqual(uninstalls, input.removed); + assert.include(output, input.output); }), ); }); @@ -200,9 +215,21 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { // recorded launchers: through a symlinked home, and dangling after a prune. const throughAlias = path.join(root, "bin/t3-alias"); const pruned = path.join(root, "bin/t3-pruned"); + const scriptThroughAlias = path.join(scriptDir, "t3-alias"); + const prunedScript = path.join(scriptDir, "t3-pruned"); yield* fs.symlink(root, path.join(root, "alias")); yield* fs.symlink(path.join(root, "alias/runtime/versions/1.0.0/t3"), throughAlias); yield* fs.symlink(path.join(versionsDir, "0.9.0/t3"), pruned); + yield* fs.writeFileString( + scriptThroughAlias, + posixLauncherScript(path.join(root, "alias/runtime/versions/1.0.0/t3")), + { mode: 0o755 }, + ); + yield* fs.writeFileString( + prunedScript, + posixLauncherScript(path.join(versionsDir, "0.9.0/t3")), + { mode: 0o755 }, + ); // Another program inside a version is not a launcher. const sibling = path.join(root, "bin/t3-sibling"); yield* fs.symlink(path.join(versionsDir, "1.0.0/node"), sibling); @@ -216,6 +243,8 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { pruned, sibling, script, + scriptThroughAlias, + prunedScript, editedScript, path.join(root, "missing"), ].join("\n") + "\n", @@ -226,6 +255,8 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { throughAlias, pruned, script, + scriptThroughAlias, + prunedScript, ]); } diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts index a0d47c738491..ae884caa63fe 100644 --- a/apps/server/src/cli/uninstall.ts +++ b/apps/server/src/cli/uninstall.ts @@ -75,7 +75,8 @@ const ownsLauncher = Effect.fn("cli.uninstall.owns_launcher")(function* ( const realVersionsDir = yield* fs .realPath(versionsDir) .pipe(Effect.orElseSucceed(() => versionsDir)); - // The link's own text keeps a pruned (dangling) target; the real path sees through a + const scriptTarget = platform === "win32" ? undefined : yield* readPosixLauncherTarget(launcher); + // The link or script text keeps a pruned (dangling) target; the real path sees through a // symlinked T3 home. const targets = platform === "win32" @@ -91,7 +92,10 @@ const ownsLauncher = Effect.fn("cli.uninstall.owns_launcher")(function* ( Effect.orElseSucceed(() => undefined), ), yield* fs.realPath(launcher).pipe(Effect.orElseSucceed(() => undefined)), - yield* readPosixLauncherTarget(launcher), + scriptTarget, + scriptTarget !== undefined + ? yield* fs.realPath(scriptTarget).pipe(Effect.orElseSucceed(() => undefined)) + : undefined, ]; return targets.some( (target) => @@ -151,9 +155,7 @@ const planUninstall = Effect.fn("cli.uninstall.plan")(function* (input: { const status = yield* service.status; const installedBaseDir = status.supported && status.installed ? status.installedBaseDir : undefined; - const servesThisHome = - installedBaseDir !== undefined && - path.resolve(installedBaseDir) === path.resolve(input.baseDir); + const servesThisHome = installedBaseDir !== undefined && status.otherBaseDir === undefined; const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir); const runtimeDir = path.dirname(versionsDir); const launchedAs = (yield* HostProcess.IsExecutable) ? yield* resolveLauncherPath : undefined; @@ -254,12 +256,14 @@ const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: { } } - if (plan.service) { + // The prompt can wait a long time; keep a service or launcher that changed hands meanwhile. + if (plan.service && (yield* service.status).otherBaseDir !== undefined) { + yield* Console.log("Left the background service: it now serves another T3 home."); + } else if (plan.service) { yield* service.uninstall; yield* Console.log("Removed the background service."); } for (const launcher of plan.launchers) { - // The prompt can wait a long time; never delete a file that replaced the launcher meanwhile. if (!(yield* ownsLauncher(launcher, plan.versionsDir))) { yield* Console.log(`Left ${launcher}: it no longer runs this t3.`); continue; diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index 07f3458fb3b6..dc798afdaa4d 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -423,9 +423,7 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: { const status = yield* service.status; // Service names are per user, so another home's unit belongs to a different install. - const servesThisHome = - status.installedBaseDir !== undefined && - path.resolve(status.installedBaseDir) === path.resolve(input.baseDir); + const servesThisHome = status.installedBaseDir !== undefined && status.otherBaseDir === undefined; const serviceInstalled = status.supported && status.installed && servesThisHome; const foreground = yield* findForegroundServer({ serverRuntimeStatePath: input.serverRuntimeStatePath, diff --git a/apps/server/src/cli/workflow.test.ts b/apps/server/src/cli/workflow.test.ts index 0c99ca8ee8d2..82b4705e45fa 100644 --- a/apps/server/src/cli/workflow.test.ts +++ b/apps/server/src/cli/workflow.test.ts @@ -166,21 +166,25 @@ it.effect("reports what the server refused instead of calling it unreachable", ( }), ); -it.effect("signal refuses both addresses at once before reaching the server", () => +it.effect("signal sends only one complete address to the server", () => Effect.gen(function* () { - const { error, calls } = yield* runCli([ - "signal", - "{}", - "--run", - "run-1", - "--wait", - "approve", - "--workflow", - "review", - "--channel", - "pr-1", - ]); - assert.strictEqual(error?._tag, "ThreadUsageError"); - assert.lengthOf(calls, 0); + const byRun = ["--run", "run-1", "--wait", "approve"]; + const byChannel = ["--workflow", "review", "--channel", "pr-1"]; + for (const [address, sent] of [ + [byRun, true], + [byChannel, true], + [[...byRun, ...byChannel], false], + [[], false], + [["--run", "run-1"], false], + [["--wait", "approve"], false], + [["--workflow", "review"], false], + [["--channel", "pr-1"], false], + ] as const) { + const { error, calls } = yield* runCli(["signal", "{}", ...address], () => + Effect.succeed({ structuredContent: { delivery: "delivered" } }), + ); + assert.strictEqual(error?._tag, sent ? undefined : "ThreadUsageError"); + assert.lengthOf(calls, sent ? 1 : 0); + } }), ); diff --git a/apps/server/src/cli/workflow.ts b/apps/server/src/cli/workflow.ts index 95a499043c6c..c02ee63551f8 100644 --- a/apps/server/src/cli/workflow.ts +++ b/apps/server/src/cli/workflow.ts @@ -244,6 +244,13 @@ const signalCommand = Command.make("signal", { "Address a signal with --run and --wait, or with --workflow and --channel, not both.", }); } + const completeRun = Option.isSome(flags.run) && Option.isSome(flags.wait); + const completeChannel = Option.isSome(flags.workflow) && Option.isSome(flags.channel); + if (!completeRun && !completeChannel) { + return yield* new ThreadUsageError({ + detail: "Address a signal with --run and --wait, or with --workflow and --channel.", + }); + } yield* withThreadTools( { ...flags, json: false }, Effect.fn("cli.workflow.signal")(function* (tools) { diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index ad926f2b5154..c327464ddfa2 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -22,6 +22,7 @@ import * as ProcessRunner from "../processRunner.ts"; import { serviceLauncherLockPath } from "../serviceLauncher.ts"; import * as BootService from "./bootService.ts"; import { pinnedRuntimePaths } from "./pinnedRuntime.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; import { decodeServiceUnit, disabledServiceTask, @@ -1307,6 +1308,28 @@ process.disconnect(); }), ); + it.effect("treats a symlinked T3 home path as the same home", () => + Effect.gen(function* () { + const { service, fs, baseDir, commands, makeService } = yield* makeHarness(); + yield* service.install(); + const path = yield* Path.Path; + const linkDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-symlink-home-" }); + const aliasDir = path.join(linkDir, "a$$b"); + yield* fs.symlink(baseDir, aliasDir); + + const alias = yield* makeService(undefined, "1.2.3", aliasDir); + expect(yield* alias.status).toMatchObject({ current: true }); + expect((yield* alias.status).otherBaseDir).toBeUndefined(); + expect(yield* alias.restart).toBe("restarted"); + commands.length = 0; + yield* alias.withStopped(Effect.void); + expect(commands).toContain("systemctl --user stop t3code.service"); + expect((yield* alias.install()).baseDir).toBe(aliasDir); + expect(yield* service.status).toMatchObject({ current: true }); + expect((yield* service.status).otherBaseDir).toBeUndefined(); + }), + ); + it.effect("hands the whole install to systemd without changing the running service", () => Effect.gen(function* () { const { fs, commands, invocations, control, makeService } = yield* makeHarness(); @@ -1406,6 +1429,7 @@ process.disconnect(); const outcome = yield* inside.restart; expect(commands).toEqual([ "systemctl --user daemon-reload", + `/bin/sh -c ${RESTORE_OOMD_WATCH_SCRIPT}`, "systemctl --user enable t3code.service", "systemctl --user reset-failed t3code.service", "systemctl --user restart --no-block t3code.service", diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 4f81ec864193..90d01b10526f 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -19,6 +19,7 @@ import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; import * as ProcessRunner from "../processRunner.ts"; import { acquireServiceSelectionLock } from "./serviceSelectionLock.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; import { serviceLauncherIsRunning, serviceLauncherLockPath, @@ -329,12 +330,21 @@ function systemdManager(input: { command: "systemctl", args: ["--user", "reset-failed", BOOT_SERVICE_UNIT_FILE], }; - const prepareActivation = [ + const reload = [ { step: "reloading systemd user units", command: "systemctl", args: ["--user", "daemon-reload"], }, + { + step: "restoring systemd-oomd's watch on the user manager", + optional: true, + command: "/bin/sh", + args: ["-c", RESTORE_OOMD_WATCH_SCRIPT], + }, + ]; + const prepareActivation = [ + ...reload, { step: "enabling the service", command: "systemctl", @@ -388,13 +398,7 @@ function systemdManager(input: { timeout: STOP_STEP_TIMEOUT, }, ], - finalize: [ - { - step: "reloading systemd user units", - command: "systemctl", - args: ["--user", "daemon-reload"], - }, - ], + finalize: reload, }; } @@ -1020,12 +1024,15 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { let { manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir); const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE); const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE); + const canonicalPath = (dir: string) => + fs.realPath(dir).pipe(Effect.orElseSucceed(() => path.resolve(dir))); + const isThisHome = (dir: string) => + Effect.zipWith(canonicalPath(dir), canonicalPath(input.baseDir), (a, b) => a === b); const otherBaseDirOf = (unit: string) => { const installedBaseDir = bootServiceBaseDirOf(unit); - return installedBaseDir !== undefined && - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ? installedBaseDir - : undefined; + return installedBaseDir === undefined + ? Effect.undefined + : Effect.map(isThisHome(installedBaseDir), (same) => (same ? undefined : installedBaseDir)); }; const writeDurably = (filePath: string, contents: string | Uint8Array) => Effect.scoped( @@ -1257,7 +1264,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const refuseOtherBaseDir = Effect.gen(function* () { const existingUnit = yield* readUnit().pipe(Effect.option); const installedBaseDir = Option.isSome(existingUnit) - ? otherBaseDirOf(existingUnit.value) + ? yield* otherBaseDirOf(existingUnit.value) : undefined; if (installedBaseDir !== undefined) { return yield* new BootServiceOtherBaseDirError({ @@ -1487,10 +1494,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const unit = yield* readUnit().pipe(Effect.option); if (Option.isNone(unit)) return "skipped" as const; const installedBaseDir = bootServiceBaseDirOf(unit.value); - if ( - installedBaseDir === undefined || - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ) { + if (installedBaseDir === undefined || !(yield* isThisHome(installedBaseDir))) { return "skipped" as const; } // Writes no state, and the launcher lets an update transition in flight @@ -1520,10 +1524,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const unit = yield* readUnit().pipe(Effect.option); if (Option.isNone(unit)) return yield* operation; const installedBaseDir = bootServiceBaseDirOf(unit.value); - if ( - installedBaseDir === undefined || - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ) { + if (installedBaseDir === undefined || !(yield* isThisHome(installedBaseDir))) { return yield* operation; } // `is-active` misses crash-looping systemd units; launchd can be loaded without a pid. @@ -1603,7 +1604,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ? serviceStateActiveVersion(stateText.value) : undefined; const installedBaseDir = bootServiceBaseDirOf(unit); - const otherBaseDir = otherBaseDirOf(unit); + const otherBaseDir = yield* otherBaseDirOf(unit); + // Another spelling of this home is current; repairing it would flip the unit between spellings. + const thisHomeUnit = + installedBaseDir !== undefined && otherBaseDir === undefined + ? unit.replaceAll(installedBaseDir, () => input.baseDir) + : unit; const normalizeUnit = (contents: string) => manager.kind === "launchd" ? contents.replace(/(PATH<\/key>\n\s*)[^<]*(<\/string>)/, "$1$2") @@ -1625,7 +1631,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { current: problems.length === 0 && !(manager.kind === "systemd" && systemdUnsafeValue(planForUnit(unit))) && - normalizeUnit(unit) === normalizeUnit(manager.render(planForUnit(unit))) && + normalizeUnit(thisHomeUnit) === normalizeUnit(manager.render(planForUnit(unit))) && runtimeEntryExists && Option.isSome(runtimeSentinel) && runtimeSentinel.value.trim() === input.cliVersion && diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index 28a7d720c525..d5f15cd1b459 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -18,6 +18,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ProcessRunner from "../processRunner.ts"; import { + findPosixLauncher, isVersionExecutable, ensurePinnedRuntimeInstalled, isUnpublishedRelease, @@ -25,7 +26,9 @@ import { pinnedRuntimePaths, PinnedRuntimeInstallError, type PinnedRuntimeProgress, + posixLauncherScript, prunePinnedRuntimes, + resolveLauncherPath, } from "./pinnedRuntime.ts"; import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts"; @@ -987,3 +990,67 @@ it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => { }), ); }); + +// NTFS reports no exec bits, and these lookups pass over files without them. +const posixHost = HostProcess.Platform.defaultValue() !== "win32"; + +it.layer(NodeServices.layer)("launcher lookup on PATH", (it) => { + it.effect.skipIf(!posixHost)( + "resolves an empty entry of a nonempty PATH against the working directory", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launcher-path-" }); + const launcher = path.join(root, "t3"); + yield* fs.writeFileString(launcher, "", { mode: 0o755 }); + const missing = path.join(root, "missing"); + const lookup = (platform: NodeJS.Platform, searchPath: string) => + resolveLauncherPath.pipe( + Effect.provideService(HostProcess.InvokedAs, "t3"), + Effect.provideService(HostProcess.Platform, platform), + Effect.provideService(HostProcess.Environment, { PATH: searchPath }), + Effect.provideService(HostProcess.WorkingDirectory, root), + ); + + assert.equal(yield* lookup("linux", `:${missing}`), launcher); + assert.equal(yield* lookup("linux", `${missing}:`), launcher); + assert.equal(yield* lookup("linux", `${missing}::${missing}`), launcher); + // An empty PATH searches nothing, and Windows has no such rule. + assert.isUndefined(yield* lookup("linux", "")); + assert.isUndefined(yield* lookup("win32", `;${missing}`)); + }), + ); + + it.effect.skipIf(!posixHost)("finds a launcher script through an empty PATH entry", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launcher-path-" }); + const versionsDir = path.join(root, ".t3", "runtime", "versions"); + const executable = path.join(versionsDir, "1.0.0", "t3"); + yield* fs.makeDirectory(path.dirname(executable), { recursive: true }); + yield* fs.writeFileString(executable, "", { mode: 0o755 }); + const bin = path.join(root, "bin"); + yield* fs.makeDirectory(bin); + yield* fs.writeFileString(path.join(bin, "t3"), posixLauncherScript(executable), { + mode: 0o755, + }); + const script = yield* fs.realPath(path.join(bin, "t3")); + const missing = path.join(root, "missing"); + const lookup = (searchPath: string) => + findPosixLauncher({ launchedAs: executable, versionsDir }).pipe( + Effect.provideService(HostProcess.Environment, { + PATH: searchPath, + T3CODE_INSTALL_BIN_DIR: missing, + }), + Effect.provideService(HostProcess.WorkingDirectory, bin), + ); + + assert.equal(yield* lookup(`:${missing}`), script); + assert.equal(yield* lookup(`${missing}:`), script); + // An empty PATH searches nothing, not even the working directory. + assert.isUndefined(yield* lookup("")); + }), + ); +}); diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index a972e76b70c2..7c0d9240c5e0 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -537,9 +537,11 @@ export const resolveLauncherPath = Effect.gen(function* () { return path.resolve(cwd, invokedAs); } const delimiter = platform === "win32" ? ";" : ":"; - for (const directory of (environment["PATH"] ?? "").split(delimiter)) { - if (directory.length === 0) continue; - const candidate = path.resolve(cwd, directory, invokedAs); + const searchPath = environment["PATH"] ?? ""; + for (const directory of searchPath.split(delimiter)) { + // POSIX shells search the working directory for an empty entry of a nonempty PATH. + if (directory.length === 0 && (platform === "win32" || searchPath.length === 0)) continue; + const candidate = path.resolve(cwd, directory || ".", invokedAs); const info = yield* fs.stat(candidate).pipe(Effect.option); // Like the shell, pass over directories and non-executable files named the same. if ( @@ -645,12 +647,13 @@ export const findPosixLauncher = Effect.fn("cloud.pinned_runtime.find_posix_laun .readFileString(path.join(path.dirname(input.versionsDir), "launchers")) .pipe(Effect.orElseSucceed(() => "")); const cwd = yield* HostProcess.WorkingDirectory; + const searchPath = environment["PATH"] ?? ""; const candidates = [ - // PATH first, resolved like the shell does: it decides which t3 the user runs. - ...(environment["PATH"] ?? "") - .split(":") - .filter((directory) => directory.length > 0) - .map((directory) => path.resolve(cwd, directory, "t3")), + // PATH first, resolved like the shell does: it decides which t3 the user runs. An empty + // entry of a nonempty PATH is the working directory; an empty PATH searches nothing. + ...(searchPath.length === 0 ? [] : searchPath.split(":")).map((directory) => + path.resolve(cwd, directory || ".", "t3"), + ), path.join( environment["T3CODE_INSTALL_BIN_DIR"] || path.join(yield* HostProcess.HomeDirectory, ".local", "bin"), diff --git a/apps/server/src/cloud/serviceLauncherClient.test.ts b/apps/server/src/cloud/serviceLauncherClient.test.ts index 338ff32a3c16..8c52725dd8a3 100644 --- a/apps/server/src/cloud/serviceLauncherClient.test.ts +++ b/apps/server/src/cloud/serviceLauncherClient.test.ts @@ -6,6 +6,7 @@ import * as PlatformError from "effect/PlatformError"; import { assert, expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; +import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; import { @@ -83,11 +84,42 @@ it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])( }; const host = new FakeLauncherProcess({ protocol, childVersion: "1.1.0", update: pending }); host.env["HOME"] = root; - const client = yield* makeClient(host, "1.1.0"); + // The launcher reloads the user manager after commit, so oomd's watch must already be mirrored. + const bin = path.join(root, "bin"); + const calls = path.join(root, "systemctl-calls"); + yield* fs.makeDirectory(bin); + yield* fs.writeFileString( + path.join(bin, "systemctl"), + [ + "#!/bin/sh", + `echo "$*" >>'${calls}'`, + 'case "$*" in', + " *ControlGroup*) echo /user.slice/user-1000.slice/user@1000.service ;;", + " *ManagedOOMMemoryPressureLimit*) echo 0 ;;", + " *ManagedOOMMemoryPressure\\ *) echo kill ;;", + "esac", + "", + ].join("\n"), + ); + yield* fs.chmod(path.join(bin, "systemctl"), 0o755); + host.env["PATH"] = `${bin}:/usr/bin:/bin`; + const sentPrepared = yield* Deferred.make(); + const send = host.send; + host.send = (message, callback) => { + Deferred.doneUnsafe(sentPrepared, Effect.void); + return send(message, callback); + }; + const client = yield* makeClient(host, "1.1.0").pipe( + Effect.provideService(HostProcess.Platform, "linux"), + ); const prepared = yield* Effect.forkChild(client.prepareTrial({ baseDir }), { startImmediately: true, }); - yield* Effect.yieldNow; + yield* Deferred.await(sentPrepared); + // Nothing runs systemctl after "prepared", so the log is what ran before it. + expect(yield* fs.readFileString(calls)).toContain( + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill", + ); expect(host.sent).toEqual([{ type: "prepared", updateId: "update-1" }]); assert.equal(yield* fs.readLink(installed), exe("1.0.0")); @@ -325,4 +357,71 @@ it.layer(NodeServices.layer)("self-update launchers", (it) => { assert.equal(yield* fs.readLink(onPath), foreign); }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); + + it.effect.each([ + { name: "leading", searchPath: (missing: string) => `:${missing}`, moved: true }, + { name: "trailing", searchPath: (missing: string) => `${missing}:`, moved: true }, + { name: "whole", searchPath: () => "", moved: false }, + ])("treats a $name empty PATH entry like the shell does", ({ searchPath, moved }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const cwd = path.join(root, "work"); + const inCwd = path.join(cwd, "t3"); + for (const file of [exe("1.0.0"), exe("2.0.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, "", { mode: 0o755 }); + } + yield* fs.makeDirectory(cwd); + yield* fs.symlink(exe("1.0.0"), inCwd); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + PATH: searchPath(path.join(root, "missing")), + }), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + + // A nonempty PATH searches the working directory there; an empty PATH searches nothing. + if (moved) { + assert.equal(yield* fs.readFileString(inCwd), posixLauncherScript(exe("2.0.0"))); + } else { + assert.equal(yield* fs.readLink(inCwd), exe("1.0.0")); + } + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), + ); + + it.effect("passes over a working-directory t3 the shell cannot run", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const cwd = path.join(root, "work"); + const onPath = path.join(root, "bin/t3"); + for (const file of [exe("1.0.0"), exe("2.0.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, "", { mode: 0o755 }); + } + // A directory named t3 in the working directory, which the shell skips. + yield* fs.makeDirectory(path.join(cwd, "t3"), { recursive: true }); + yield* fs.makeDirectory(path.dirname(onPath), { recursive: true }); + yield* fs.symlink(exe("1.0.0"), onPath); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + PATH: `:${path.dirname(onPath)}`, + }), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + + assert.equal(yield* fs.readFileString(onPath), posixLauncherScript(exe("2.0.0"))); + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), + ); }); diff --git a/apps/server/src/cloud/serviceLauncherClient.ts b/apps/server/src/cloud/serviceLauncherClient.ts index e8f8941f3f9e..50b596b0e30d 100644 --- a/apps/server/src/cloud/serviceLauncherClient.ts +++ b/apps/server/src/cloud/serviceLauncherClient.ts @@ -8,6 +8,8 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import packageJson from "../../package.json" with { type: "json" }; import { @@ -24,6 +26,7 @@ import { type ServiceLauncherParentMessage, type SupportedLauncherProtocol, } from "./serviceProtocol.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; export class ServiceLauncherClientError extends Schema.TaggedError()( "ServiceLauncherClientError", @@ -163,9 +166,21 @@ export const repointLaunchers = Effect.fn("cloud.service_launcher_client.repoint (environment["HOME"] ? path.join(environment["HOME"], ".local", "bin") : undefined); const candidates = new Set(); if (installBinDir !== undefined) candidates.add(path.join(installBinDir, "t3")); - for (const directory of (environment["PATH"] ?? "").split(":")) { - if (directory.length === 0) continue; - const candidate = path.join(directory, "t3"); + const searchPath = environment["PATH"] ?? ""; + const cwd = yield* HostProcess.WorkingDirectory; + for (const directory of searchPath.split(":")) { + // Like the shell, an empty entry of a nonempty PATH is the working directory. + if (directory.length === 0 && searchPath.length === 0) continue; + const candidate = path.join(directory || cwd, "t3"); + if (directory.length === 0) { + // The shell passes over a working-directory entry it cannot run and keeps searching. + const info = yield* fs.stat(candidate).pipe(Effect.option); + if (Option.isNone(info) || info.value.type !== "File" || (info.value.mode & 0o111) === 0) { + continue; + } + candidates.add(candidate); + break; + } if ( yield* fs.exists(candidate).pipe( Effect.catch((cause) => @@ -252,6 +267,22 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o const path = yield* Path.Path; const environment = yield* HostProcess.Environment; const platform = yield* HostProcess.Platform; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + // The launcher that commits a remote update is the old one; its reload after commit + // keeps oomd's watch only if the policy is mirrored before it. + const keepOomdWatch = + platform === "linux" + ? spawner + .exitCode( + ChildProcess.make("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + env: environment, + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + }), + ) + .pipe(Effect.timeout("30 seconds"), Effect.ignore) + : Effect.void; const exchange = ( message: ServiceLauncherChildMessage, @@ -331,28 +362,31 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o : context.update; const prepareTrial = (input: { readonly baseDir: string }) => pending !== undefined - ? exchange( - { type: "prepared", updateId: pending.id }, - (reply) => reply.type === "committed" && reply.updateId === pending.id, - ).pipe( - Effect.flatMap((reply) => - reply.type !== "committed" - ? Effect.die("service launcher returned an impossible prepared response") - : repointLaunchers({ - baseDir: input.baseDir, - targetVersion: pending.targetVersion, - }).pipe( - Effect.provideService(FileSystem.FileSystem, fs), - Effect.provideService(Path.Path, path), - Effect.provideService(HostProcess.Environment, environment), - Effect.provideService(HostProcess.Platform, platform), - Effect.as({ - id: pending.id, - fromVersion: pending.fromVersion, + ? Effect.andThen( + keepOomdWatch, + exchange( + { type: "prepared", updateId: pending.id }, + (reply) => reply.type === "committed" && reply.updateId === pending.id, + ).pipe( + Effect.flatMap((reply) => + reply.type !== "committed" + ? Effect.die("service launcher returned an impossible prepared response") + : repointLaunchers({ + baseDir: input.baseDir, targetVersion: pending.targetVersion, - status: "committed" as const, - }), - ), + }).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + Effect.provideService(HostProcess.Environment, environment), + Effect.provideService(HostProcess.Platform, platform), + Effect.as({ + id: pending.id, + fromVersion: pending.fromVersion, + targetVersion: pending.targetVersion, + status: "committed" as const, + }), + ), + ), ), ) : Effect.succeed(outcome); diff --git a/apps/server/src/cloud/serviceProtection.ts b/apps/server/src/cloud/serviceProtection.ts index 48790bcf6cc0..a8952ce299fd 100644 --- a/apps/server/src/cloud/serviceProtection.ts +++ b/apps/server/src/cloud/serviceProtection.ts @@ -8,6 +8,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as ProcessRunner from "../processRunner.ts"; import { BOOT_SERVICE_UNIT_FILE } from "./bootService.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; const PROTECT_DROP_IN = "90-t3code-protect.conf"; const SYSTEM_UNIT_DIR = "/etc/systemd/system"; @@ -210,10 +211,12 @@ export const detectRemoteAccessUnits = run("list remote-access services", "syste Effect.withSpan("ServiceProtection.detectRemoteAccessUnits"), ); -const reloadUserManager = run("reload systemd user units", "systemctl", [ - "--user", - "daemon-reload", -]); +const reloadUserManager = Effect.andThen( + run("reload systemd user units", "systemctl", ["--user", "daemon-reload"]), + run("restore systemd-oomd's watch", "/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT]).pipe( + Effect.ignore, + ), +); const writeDropIns = Effect.fn("ServiceProtection.writeDropIns")(function* ( dropIns: ReadonlyArray, diff --git a/apps/server/src/cloud/userManagerOom.test.ts b/apps/server/src/cloud/userManagerOom.test.ts new file mode 100644 index 000000000000..67c0e51e1163 --- /dev/null +++ b/apps/server/src/cloud/userManagerOom.test.ts @@ -0,0 +1,72 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { expect, it } from "vite-plus/test"; + +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; + +const userService = "/user.slice/user-1001.slice/user@1001.service"; + +it.each([ + [ + "mirrors the system manager's kill policy onto the user manager's root slice", + { cgroup: userService, mode: "kill", limit: "4252017622", duration: "" }, + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=99.00%", + ], + [ + "keeps a custom duration and an unset limit", + { cgroup: userService, mode: "kill", limit: "0", duration: "20s" }, + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=0.00% ManagedOOMMemoryPressureDurationSec=20s", + ], + [ + "leaves the slice alone when oomd is not told to kill", + { cgroup: userService, mode: "auto", limit: "0", duration: "infinity" }, + undefined, + ], + [ + "leaves the slice alone outside a user@ service", + { cgroup: "/system.slice/foo.service", mode: "kill", limit: "0", duration: "infinity" }, + undefined, + ], +])("%s", (_name, system, expected) => { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-oomd-")); + try { + const calls = NodePath.join(root, "calls"); + NodeFS.writeFileSync( + NodePath.join(root, "systemctl"), + [ + "#!/bin/sh", + 'echo "$*" >>"$CALLS"', + 'case "$*" in', + ' *ControlGroup*) echo "$CGROUP" ;;', + ' *ManagedOOMMemoryPressureLimit*) echo "$LIMIT" ;;', + ' *ManagedOOMMemoryPressureDurationUSec*) echo "$DURATION" ;;', + ' *ManagedOOMMemoryPressure\\ *) echo "$MODE" ;;', + "esac", + "", + ].join("\n"), + { mode: 0o755 }, + ); + const result = NodeChildProcess.spawnSync("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + encoding: "utf8", + env: { + PATH: `${root}:/usr/bin:/bin`, + CALLS: calls, + CGROUP: system.cgroup, + MODE: system.mode, + LIMIT: system.limit, + DURATION: system.duration, + }, + }); + expect(result.stderr).toBe(""); + expect(result.status).toBe(0); + const setProperty = NodeFS.readFileSync(calls, "utf8") + .split("\n") + .find((call) => call.includes("set-property")); + expect(setProperty).toBe(expected); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/apps/server/src/cloud/userManagerOom.ts b/apps/server/src/cloud/userManagerOom.ts new file mode 100644 index 000000000000..6f23427b8399 --- /dev/null +++ b/apps/server/src/cloud/userManagerOom.ts @@ -0,0 +1,22 @@ +/** + * Run after `systemctl --user daemon-reload`. The user manager's -.slice shares the cgroup of + * user@.service and reports it to systemd-oomd as `auto` on reload, which drops the system + * manager's `kill` watch (systemd/systemd#43174). Mirroring that policy onto -.slice restores the + * watch and keeps it through later reloads. Best effort: exits 0 when there is nothing to mirror. + */ +export const RESTORE_OOMD_WATCH_SCRIPT = [ + "unit=$(systemctl --user show --property=ControlGroup --value -- -.slice) || exit 0", + "unit=${unit##*/}", + "case $unit in user@*.service) ;; *) exit 0 ;; esac", + 'show() { systemctl show --property="$1" --value "$unit"; }', + '[ "$(show ManagedOOMMemoryPressure)" = kill ] || exit 0', + "limit=$(show ManagedOOMMemoryPressureLimit)", + "case $limit in '' | *[!0-9]*) exit 0 ;; esac", + // The limit is a fraction of 2^32; set-property takes a percentage. + "p=$(( (limit * 10000 + 2147483648) / 4294967296 ))", + 'set -- ManagedOOMMemoryPressure=kill "ManagedOOMMemoryPressureLimit=$((p / 100)).$(printf %02d $((p % 100)))%"', + "duration=$(show ManagedOOMMemoryPressureDurationUSec)", + 'case $duration in "" | infinity) ;; *) set -- "$@" "ManagedOOMMemoryPressureDurationSec=$duration" ;; esac', + 'exec systemctl --user set-property --runtime -- -.slice "$@"', + "", +].join("\n"); diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index 14e526cd13c9..4c10b8a93cff 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -647,8 +647,15 @@ it("readThread returns the newest items that fit the response budget", async () maxCharsPerItem: 1_500, }; const result = yield* service.readThread(makeScope(), read); - // The CLI reads as a client without a cursor and follows only hasMore. - const first = yield* service.readThread({ ...makeScope(), thread: undefined }, read); + // An outside MCP client, such as claude.ai, reads without a thread or a link. + const outside = yield* service.readThread( + { + ...makeScope(), + thread: undefined, + client: { sessionId: "session-1", label: "claude.ai", access: "read-only" }, + }, + read, + ); const fromStart = yield* service.readThread(makeScope(), { ...read, afterPosition: -1 }); const linked = yield* service.readThread( { @@ -666,7 +673,7 @@ it("readThread returns the newest items that fit the response budget", async () expect(pageOptions).toEqual([ { beforePosition: Number.POSITIVE_INFINITY, limit: 100, view: "activity" }, - { limit: 100, view: "activity" }, + { beforePosition: Number.POSITIVE_INFINITY, limit: 100, view: "activity" }, { afterPosition: -1, limit: 100, view: "activity" }, { beforePosition: Number.POSITIVE_INFINITY, limit: 100, view: "activity" }, ]); @@ -676,10 +683,13 @@ it("readThread returns the newest items that fit the response budget", async () expect(result.items.at(-1)?.position).toBe(99); expect(result.earlierPosition).toBe(result.items[0]?.position); expect(result.hasMore).toBe(false); - expect(first.items[0]?.position).toBe(0); - expect(first.hasMore).toBe(true); - expect(first.nextPosition).toBe(first.items.at(-1)?.position); + expect(outside.items.at(-1)?.position).toBe(99); + expect(outside.earlierPosition).toBe(outside.items[0]?.position); + expect(outside.hasMore).toBe(false); + // The t3 thread CLI pages forward from here, following only hasMore. expect(fromStart.items[0]?.position).toBe(0); + expect(fromStart.hasMore).toBe(true); + expect(fromStart.nextPosition).toBe(fromStart.items.at(-1)?.position); expect(linked.items.at(-1)?.position).toBe(99); expect(linked.earlierPosition).toBe(linked.items[0]?.position); expect(linked.hasMore).toBe(false); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index d3d42162f81d..9438b58d7bbc 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -3760,11 +3760,7 @@ const make = Effect.gen(function* () { const view = input.view ?? "messages"; const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT; const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS; - // Client callers (the CLI) page forward from a cursorless read. - const newestFirst = - input.beforePosition !== undefined || - (input.afterPosition === undefined && - (scope.thread !== undefined || scope.client?.linked === true)); + const newestFirst = input.beforePosition !== undefined || input.afterPosition === undefined; const timeline = yield* threadManagement .getTimelinePage(input.threadId, { ...(input.afterPosition === undefined ? {} : { afterPosition: input.afterPosition }), diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index 7caa425d32f2..95f816f151b9 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -207,7 +207,10 @@ const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* ( Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null), dispatch, }), - Layer.mock(PullRequestService.PullRequestService)(options.pullRequests ?? {}), + Layer.mock(PullRequestService.PullRequestService)({ + addressedProject: () => Effect.succeed(project ?? undefined), + ...options.pullRequests, + }), Layer.mock(GitManager.GitManager)(options.git ?? {}), Layer.succeed(SecureRandom.SecureRandom, testCrypto), McpToolAccessTestkit.liveThreadsLayer, @@ -416,6 +419,18 @@ describe("pull request toolkit handlers", () => { }), ); + it.effect("says when repository is not owner/repo on a known host", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ project: makeProject() }); + const error = yield* harness + .call("link_pull_request", { repository: "github.com/org/repo", number: 1 }) + .pipe(Effect.flip); + expect(error).toMatchObject({ _tag: "PullRequestRepositoryInvalidError" }); + expect(error.message).toContain("owner/repo"); + expect(yield* Ref.get(harness.commands)).toEqual([]); + }), + ); + it.effect("treats a duplicate link as alreadyLinked rather than an error", () => Effect.gen(function* () { const harness = yield* makeHarness({ @@ -929,6 +944,40 @@ describe("source control tools", () => { }), ); + it.effect("reads an Azure DevOps PR by number at its organization and project", () => + Effect.gen(function* () { + const asked: Array = []; + const harness = yield* makeHarness({ + project: makeProject({ + canonicalKey: "dev.azure.com/contoso/project/_git/repo", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "https://contoso@dev.azure.com/contoso/project/_git/repo", + }, + provider: SourceControlProviderKind.make("azure-devops"), + displayName: "contoso/project/_git/repo", + owner: "contoso", + name: "repo", + }), + pullRequests: { + detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)), + activity: () => Effect.succeed(activity), + }, + }); + const result = yield* harness.call("pull_request_read", { number: 123 }); + expect(result).toMatchObject({ + host: "dev.azure.com", + repository: "contoso/project/_git/repo", + number: 123, + url: "https://dev.azure.com/contoso/project/_git/repo/pullrequest/123", + }); + expect(asked).toMatchObject([ + { host: "dev.azure.com", repository: "contoso/project/_git/repo", number: 123 }, + ]); + }), + ); + it.effect("pages a long conversation and the PR list through the cursors they return", () => Effect.gen(function* () { const comment = (body: string) => diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 41efd9ee8baa..0875f069afea 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -309,10 +309,9 @@ const make = Effect.gen(function* () { | typeof PullRequestUnlinkFailedError | typeof PullRequestForgeError, ) => - projects.getShell(thread.projectId).pipe( - Effect.map(Option.getOrUndefined), - Effect.mapError((cause) => new Failure({ cause })), - ); + pullRequests + .addressedProject(thread.projectId) + .pipe(Effect.mapError((cause) => new Failure({ cause }))); const dispatchFailure = (Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError) => @@ -362,7 +361,12 @@ const make = Effect.gen(function* () { const known = yield* projects .listShells() .pipe(Effect.mapError((cause) => new PullRequestListFailedError({ cause }))); - const callerProject = known.find((project) => project.id === callerThread?.projectId); + const callerProject = + callerThread === undefined + ? undefined + : yield* pullRequests + .addressedProject(callerThread.projectId) + .pipe(Effect.mapError((cause) => new PullRequestListFailedError({ cause }))); // A pull request named by host and repository builds its URL through the project that holds // it, which need not be the caller's. const urlProject = (input: PullRequestTargetInput) => diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index e845449006be..d47baf1db8b7 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -38,6 +38,7 @@ import { PullRequestTargetIncompleteError, PullRequestHostRequiredError, PullRequestUrlUnavailableError, + PullRequestRepositoryInvalidError, } from "../../../pullRequest/pullRequestTarget.ts"; import * as PullRequestService from "../../../pullRequest/PullRequestService.ts"; import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts"; @@ -181,6 +182,7 @@ export const PullRequestToolError = Schema.Union([ PullRequestTargetIncompleteError, PullRequestHostRequiredError, PullRequestUrlUnavailableError, + PullRequestRepositoryInvalidError, PullRequestThreadRequiredError, PullRequestLinkFailedError, PullRequestUnlinkFailedError, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index cd9694690181..4c817ce8ba8e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -12120,6 +12120,213 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + describe("warm process after the session changed outside T3", () => { + const firstReply = "00000000-0000-4000-8000-000000000c01"; + const secondReply = "00000000-0000-4000-8000-000000000c02"; + const terminalPrompt = "00000000-0000-4000-8000-000000000c03"; + const terminalReply = "00000000-0000-4000-8000-000000000c04"; + const line = (entry: object) => + `${JSON.stringify({ isSidechain: false, sessionId: WAKE_NATIVE_SESSION, ...entry })}\n`; + const entry = ( + type: "user" | "assistant", + uuid: string, + parentUuid: string | null, + content: unknown, + extra?: object, + ) => line({ type, uuid, parentUuid, message: { role: type, content }, ...extra }); + const t3Turn = (promptUuid: string) => + entry("user", promptUuid, null, "Request 1") + + entry("assistant", firstReply, promptUuid, [{ type: "text", text: "Working." }]) + + entry("assistant", secondReply, firstReply, [{ type: "text", text: "Done." }]); + const terminalExchange = + entry("user", terminalPrompt, secondReply, "Typed in the terminal") + + entry("assistant", terminalReply, terminalPrompt, [{ type: "text", text: "Answered." }]); + + // Streams one T3 turn of two reply blocks, writes the transcript, then starts the next turn. + const nextTurnAfter = Effect.fnUntraced(function* (input: { + readonly transcript: ((promptUuid: string) => string) | null; + readonly backgroundShell?: boolean; + readonly scheduledWakeup?: boolean; + readonly wakeFiresDuringRead?: boolean; + readonly pinnedHead?: string; + }) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const configDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-stale-" }); + const projectDir = path.join(configDir, "projects", "-workspace"); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + const transcriptOpened = yield* Deferred.make(); + const releaseTranscript = yield* Deferred.make(); + const heldFileSystem: FileSystem.FileSystem = { + ...fileSystem, + open: (filePath, options) => + filePath.endsWith(".jsonl") + ? Deferred.succeed(transcriptOpened, undefined).pipe( + Effect.andThen(Deferred.await(releaseTranscript)), + Effect.andThen(fileSystem.open(filePath, options)), + ) + : fileSystem.open(filePath, options), + }; + const harness = yield* makeWakeHarnessWithOptions({ + environment: { CLAUDE_CONFIG_DIR: configDir }, + freshQueueOnReopen: true, + }).pipe( + input.wakeFiresDuringRead === true + ? Effect.provideService(FileSystem.FileSystem, heldFileSystem) + : (effect) => effect, + ); + const providerThread = + input.pinnedHead === undefined + ? harness.providerThread + : { + ...harness.providerThread, + nativeConversationHeadRef: { + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeId: input.pinnedHead, + strength: "weak" as const, + }, + }; + const now = yield* DateTime.now; + const turn = (ordinal: number) => + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread, + now, + attemptId: RunAttemptId.make(`attempt-stale-process:${ordinal}`), + text: `Request ${ordinal}`, + attachments: [], + providerTurnOrdinal: ordinal, + }); + yield* harness.runtime.startTurn(turn(1)); + if (input.backgroundShell === true) yield* harness.offerAndWait(wakeTaskStarted); + if (input.scheduledWakeup === true || input.wakeFiresDuringRead === true) { + for (const frame of scheduleWakeupFrames({ + toolUseId: "toolu_stale_process_wakeup", + uuids: ["00000000-0000-4000-8000-000000000c05", "00000000-0000-4000-8000-000000000c06"], + toolInput: { delaySeconds: 3600, prompt: "check", reason: "wake", noop: false }, + scheduledFor: DateTime.toEpochMillis(now) + 3_600_000, + })) { + yield* harness.offerAndWait(frame); + } + } + yield* harness.offerAndWait(makeAssistantTextFrame({ uuid: firstReply, text: "Working." })); + yield* harness.offerAndWait(makeAssistantTextFrame({ uuid: secondReply, text: "Done." })); + yield* harness.offerAndWait(turnOneResult); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + if (input.transcript !== null) { + yield* fileSystem.writeFileString( + path.join(projectDir, `${WAKE_NATIVE_SESSION}.jsonl`), + input.transcript(harness.promptUuid(0)), + ); + } + if (input.wakeFiresDuringRead !== true) { + yield* harness.runtime.startTurn(turn(2)); + return harness; + } + yield* TestClock.adjust("1 hour"); + const nextTurn = yield* Effect.forkChild(harness.runtime.startTurn(turn(2))); + yield* Deferred.await(transcriptOpened); + yield* harness.offerAndWait(wakeTurnInit); + yield* Deferred.succeed(releaseTranscript, undefined); + yield* Fiber.join(nextTurn); + return harness; + }); + const layer = Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ); + + it.effect.each([ + { + name: "the session transcript gained messages outside T3", + transcript: (promptUuid: string) => t3Turn(promptUuid) + terminalExchange, + }, + { + // The terminal's rows alone are longer than the tail T3 reads first. + name: "a long terminal exchange followed its last message", + transcript: (promptUuid: string) => + t3Turn(promptUuid) + + entry("user", terminalPrompt, secondReply, "x".repeat(1_200_000)) + + entry("assistant", terminalReply, terminalPrompt, [ + { type: "text", text: "y".repeat(1_200_000) }, + ]), + }, + ])("replaces a warm process when $name", (row) => + Effect.gen(function* () { + const harness = yield* nextTurnAfter(row); + assert.lengthOf(harness.processQueues, 2, "the next turn must open a fresh process"); + assert.equal(harness.getOpenedOptions()?.resume, WAKE_NATIVE_SESSION); + assert.isUndefined(harness.getOpenedOptions()?.resumeSessionAt); + }).pipe(Effect.provide(layer)), + ); + + it.effect.each([ + { + name: "the file lags the stream", + transcript: (promptUuid: string) => + entry("user", promptUuid, null, "Request 1") + + entry("assistant", firstReply, promptUuid, [{ type: "text", text: "Working." }]), + }, + { + name: "only bookkeeping follows T3's reply", + transcript: (promptUuid: string) => + t3Turn(promptUuid) + + line({ + type: "system", + subtype: "turn_duration", + uuid: "sys-1", + parentUuid: secondReply, + }) + + line({ type: "last-prompt", leafUuid: secondReply }) + + entry("assistant", "side-1", secondReply, [{ type: "text", text: "x" }], { + isSidechain: true, + }) + + entry("user", "meta-1", secondReply, "Caveat", { isMeta: true }) + + entry("user", "stop-1", secondReply, "[Request interrupted by user]") + + JSON.stringify({ type: "user", uuid: "half-written", parentUuid: secondReply }).slice( + 0, + 30, + ), + }, + { name: "there is no transcript", transcript: null }, + { + name: "a pinned head decides where to resume", + transcript: (promptUuid: string) => t3Turn(promptUuid) + terminalExchange, + pinnedHead: firstReply, + }, + { + name: "replacing it would end background work", + transcript: (promptUuid: string) => t3Turn(promptUuid) + terminalExchange, + backgroundShell: true, + }, + { + name: "replacing it would cancel a scheduled wakeup", + transcript: (promptUuid: string) => t3Turn(promptUuid) + terminalExchange, + scheduledWakeup: true, + }, + { + name: "its scheduled wakeup fires while the transcript is read", + transcript: (promptUuid: string) => t3Turn(promptUuid) + terminalExchange, + wakeFiresDuringRead: true, + }, + { + // Longer than the tail T3 reads, and the process's own messages are not written yet. + name: "a long transcript's tail holds none of its messages", + transcript: () => + entry("user", "old-1", null, "x".repeat(1_200_000)) + + entry("assistant", "old-2", "old-1", [{ type: "text", text: "y".repeat(1_200_000) }]), + }, + ])("keeps the warm process when $name", (row) => + Effect.gen(function* () { + const harness = yield* nextTurnAfter(row); + assert.lengthOf(harness.processQueues, 1); + assert.lengthOf(harness.offeredMessages, 2); + }).pipe(Effect.provide(layer)), + ); + }); + // The passive row is the frame Claude 2.1.303 emits for a Stop hook returning a systemMessage. it.effect.each([ { name: "hides a passive summary", level: "notice", visible: false }, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index efbad7b0a869..38c4e26cd8b1 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -1439,25 +1439,22 @@ const decodeClaudeHistoryMessages = Schema.decodeUnknownEffect( ), ); +interface ClaudeHistoryMessage { + readonly type: string; + readonly uuid: string; + readonly message: { readonly content: unknown; readonly model?: unknown }; +} + // The placeholder reply the CLI records for a failed request. export function claudeHistoryEndsOnFailedRequest( - messages: ReadonlyArray<{ - readonly type: string; - readonly message: { readonly content: unknown; readonly model?: unknown }; - }>, + messages: ReadonlyArray, ): boolean { const last = messages.at(-1); return last?.type === "assistant" && last.message.model === ""; } // Claude's interactive reply-on-resume removes native abort rows before querying the saved history. -export function claudeResumeSessionAt( - messages: ReadonlyArray<{ - readonly type: string; - readonly uuid: string; - readonly message: { readonly content: unknown }; - }>, -): string | undefined { +function claudeMessagesBeforeTrailingAborts(messages: ReadonlyArray): number { let end = messages.length; let toolInterrupted = false; while (end > 0) { @@ -1496,9 +1493,57 @@ export function claudeResumeSessionAt( } break; } + return end; +} + +export function claudeResumeSessionAt( + messages: ReadonlyArray, +): string | undefined { + const end = claudeMessagesBeforeTrailingAborts(messages); return end === messages.length ? undefined : messages[end - 1]?.uuid; } +// Transcript lines can exceed 100 KB; the tail only has to reach this process's last message. +const CLAUDE_TRANSCRIPT_TAIL_BYTES = 2 * 1024 * 1024; +// A long terminal exchange pushes that message out of the tail; one wider read looks for it. +const CLAUDE_TRANSCRIPT_WIDE_TAIL_BYTES = 32 * 1024 * 1024; + +/** Whether a live process missed messages a terminal `claude --resume` appended to its session. + * Anchors on the last message the process emitted; Claude flushes the file after streaming, so + * an emitted message can be missing from it. Lines with no anchor before them prove nothing: + * they can all predate the process, so the answer is undefined. */ +function claudeTranscriptHasUnseenMessages( + lines: ReadonlyArray, + emittedUuids: ReadonlySet, +): boolean | undefined { + let anchored = false; + let unseen: Array = []; + for (const line of lines) { + let entry: unknown; + try { + entry = JSON.parse(line); + } catch { + continue; + } + const uuid = field(entry, "uuid"); + if (typeof uuid !== "string" || !isClaudeTranscriptConversationLine(entry)) continue; + if (emittedUuids.has(uuid)) { + anchored = true; + unseen = []; + continue; + } + if ( + field(entry, "isSidechain") === true || + field(entry, "isMeta") === true || + field(entry, "isCompactSummary") === true + ) { + continue; + } + unseen.push({ type: entry.type, uuid, message: { content: entry.message.content } }); + } + return anchored ? claudeMessagesBeforeTrailingAborts(unseen) > 0 : undefined; +} + const claudeConfigDirOf = ( path: Path.Path, environment: NodeJS.ProcessEnv, @@ -5880,6 +5925,9 @@ interface ClaudeLiveQueryContext { // Per process, not per session: a relative temp dir follows the cwd this CLI // was launched in, and a later turn's cwd can differ. readonly taskOutputRoot: string | undefined; + // Root messages this process streamed; what it holds beyond the history it resumed. + readonly emittedMessageUuids: Set; + transcriptPath: string | undefined; } interface ActiveClaudeToolCall { @@ -14133,6 +14181,73 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return false; }); + const claudeProjectsDir = Effect.gen(function* () { + const configuredDir = adapterOptions.environment.CLAUDE_CONFIG_DIR?.trim() ?? ""; + return path.join( + configuredDir.length > 0 + ? path.resolve(session.cwd, configuredDir) + : path.join(yield* HostProcess.HomeDirectory, ".claude"), + "projects", + ); + }); + + const locateClaudeTranscript = Effect.fnUntraced(function* (nativeThreadId: string) { + const projectsDir = yield* claudeProjectsDir; + let newest: { readonly path: string; readonly mtime: number } | undefined; + for (const project of yield* fileSystem.readDirectory(projectsDir)) { + const candidate = path.join(projectsDir, project, `${nativeThreadId}.jsonl`); + const info = yield* fileSystem.stat(candidate).pipe(Effect.option); + if (Option.isNone(info) || info.value.type !== "File") continue; + const mtime = Option.getOrUndefined(info.value.mtime)?.getTime() ?? 0; + if (newest === undefined || mtime > newest.mtime) newest = { path: candidate, mtime }; + } + return newest?.path; + }); + + // A failed read keeps the process: replacing it is only right when the file proves a miss. + const liveProcessMissedTranscriptMessages = Effect.fn( + "ClaudeAdapterV2.liveProcessMissedTranscriptMessages", + )( + function* (live: ClaudeLiveQueryContext) { + if (live.emittedMessageUuids.size === 0) return false; + live.transcriptPath ??= yield* locateClaudeTranscript(live.nativeThreadId); + const transcriptPath = live.transcriptPath; + if (transcriptPath === undefined) return false; + const readTail = (maxBytes: number) => + Effect.scoped( + Effect.gen(function* () { + const handle = yield* fileSystem.open(transcriptPath, { flag: "r" }); + const size = Number((yield* handle.stat).size); + const start = Math.max(0, size - maxBytes); + yield* handle.seek(BigInt(start), "start"); + const bytes = yield* handle.readAlloc(size - start); + const lines = ( + Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : "" + ).split("\n"); + // The last piece is empty or a line Claude is still writing; a cut tail starts + // mid-line. + lines.pop(); + if (start > 0) lines.shift(); + return { lines, wholeFile: start === 0 }; + }), + ); + for (const maxBytes of [ + CLAUDE_TRANSCRIPT_TAIL_BYTES, + CLAUDE_TRANSCRIPT_WIDE_TAIL_BYTES, + ]) { + const tail = yield* readTail(maxBytes); + const missed = claudeTranscriptHasUnseenMessages( + tail.lines, + live.emittedMessageUuids, + ); + if (missed !== undefined) return missed; + if (tail.wholeFile) break; + } + return false; + }, + Effect.orElseSucceed(() => false), + ); + const routedCatalogFor = (live: ClaudeLiveQueryContext) => routeModelCatalog(modelCatalog, live.settingsCwd, live.launchArgSettings); @@ -14199,6 +14314,35 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { return existing; } + let replaceStaleProcess = false; + if ( + !turnInput.resume && + existing !== null && + existing.nativeThreadId === nativeThreadId && + existing.queryPolicyKey === queryPolicyKey && + !existing.stopping && + // A pinned head already decides where a fresh process resumes. + resumeSessionAt === undefined + ) { + // Decided before the transcript read: with no pending wakeup then, none can fire during it. + const keepsWork = + (yield* liveProcessRunsBackgroundWork(existing)) || + scheduledWakeupsByNativeThread.has(nativeThreadId) || + (yield* holdsBufferedWake( + nativeThreadId, + (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [], + )); + if (yield* liveProcessMissedTranscriptMessages(existing)) { + if (keepsWork) { + yield* Effect.logWarning( + "orchestration-v2.claude-stale-process-kept-for-background-work", + { threadId: turnInput.threadId, nativeThreadId }, + ); + } else { + replaceStaleProcess = true; + } + } + } const reuseLaunchSettings = existing !== null && existing.nativeThreadId === nativeThreadId && @@ -14237,6 +14381,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( existing.nativeThreadId === nativeThreadId && existing.queryPolicyKey === queryPolicyKey && !existing.stopping && + !replaceStaleProcess && existing.selection.queryIdentity !== compiledSelection.queryIdentity && canApplyClaudeSelectionLive(existing.selection, compiledSelection) && (existing.selection.apiModelId === compiledSelection.apiModelId || @@ -14251,6 +14396,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( existing.nativeThreadId === nativeThreadId && existing.queryPolicyKey === queryPolicyKey && !existing.stopping && + !replaceStaleProcess && existing.selection.queryIdentity === compiledSelection.queryIdentity ) { // A denied ExitPlanMode leaves Claude in plan mode. Restore only from plan: @@ -14486,6 +14632,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( resolvedTurnCwd, hostPlatform, ), + emittedMessageUuids: new Set(), + transcriptPath: undefined, }; // One step, so the replaced process cannot exit between the install and the handoff. yield* Ref.update(queryContext, (replaced) => { @@ -14503,6 +14651,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( sdkMessageLock.withPermits(1)( Effect.suspend(() => { let firstInit = false; + if ( + (message.type === "assistant" || message.type === "user") && + message.parent_tool_use_id === null && + message.uuid !== undefined + ) { + context.emittedMessageUuids.add(message.uuid); + } if ( message.type === "system" && message.subtype === "init" && @@ -15559,13 +15714,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const claudeTranscriptState = Effect.fn("ClaudeAdapterV2.claudeTranscriptState")(function* ( nativeThreadId: string, ) { - const configuredDir = adapterOptions.environment.CLAUDE_CONFIG_DIR?.trim() ?? ""; - const projectsDir = path.join( - configuredDir.length > 0 - ? path.resolve(session.cwd, configuredDir) - : path.join(yield* HostProcess.HomeDirectory, ".claude"), - "projects", - ); + const projectsDir = yield* claudeProjectsDir; // Any message in any transcript copy means Claude may still resume it. let found = false; let unreadable = false; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index abb02c5fb3ec..77034e1e1cc0 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -3519,6 +3519,99 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("keeps an asynchronous Codex alert distinguishable from the final answer", () => + Effect.gen(function* () { + const nativeThreadId = "async-alert-thread"; + const nativeTurnId = "async-alert-turn"; + const agentMessage = (id: string, text: string, delivery: "async" | null) => ({ + type: "emit_inbound" as const, + label: id, + frame: { + method: "item/completed", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + item: { + type: "agentMessage", + id, + text, + phase: "final_answer", + delivery, + questions: null, + }, + }, + }, + }); + const transcript = makeCodexReplayTranscript({ + scenario: "async-alert-and-final-answer", + entries: [ + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId, + prompt: "Alert me, then finish.", + }), + agentMessage("call_alert_1", "I found an important detail.", "async"), + agentMessage("msg_final", "Here is the ordinary final answer.", null), + { + type: "emit_inbound", + label: "complete", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("async-alert-attempt"), + text: "Alert me, then finish.", + }), + ); + yield* harness.firstTerminal; + const classification = (nativeId: string) => { + const item = harness.events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.nativeItemRef?.nativeId === nativeId, + ); + assert.equal(item?.type, "turn_item.updated"); + if (item?.type !== "turn_item.updated") return {}; + const { + id: _id, + nodeId: _nodeId, + messageId: _messageId, + nativeItemRef: _nativeItemRef, + ordinal: _ordinal, + text: _text, + startedAt: _startedAt, + completedAt: _completedAt, + updatedAt: _updatedAt, + ...rest + } = item.turnItem as typeof item.turnItem & { messageId?: unknown; text?: unknown }; + return rest; + }; + assert.notDeepEqual(classification("call_alert_1"), classification("msg_final")); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("returns a Codex question's answer under its native question id", () => Effect.gen(function* () { const nativeThreadId = "question-id-thread"; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index c147a7e4e086..ba8a0a9a6703 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1531,6 +1531,7 @@ interface ActiveCodexTurnContext { // Modern approval requests omit paths; keep the kinds without retaining patch bodies. readonly fileChangeKindsByItem: Map; readonly messagePhases: Map; + readonly asyncMessageIds: Set; readonly itemPositions: Map< string, { readonly ordinal: number; readonly startedAt: DateTime.Utc } @@ -2989,6 +2990,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( itemPositions: new Map(), fileChangeKindsByItem: new Map(), messagePhases: new Map(), + asyncMessageIds: new Set(), runningCompactionItemIds: new Set(), modelCalls: makeCodexModelCallState(), runningWebSearchItems: new Map(), @@ -3626,6 +3628,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( itemPositions: new Map(), fileChangeKindsByItem: new Map(), messagePhases: new Map(), + asyncMessageIds: new Set(), runningCompactionItemIds: new Set(), modelCalls: makeCodexModelCallState(), runningWebSearchItems: new Map(), @@ -4326,6 +4329,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(context.messagePhases.has(item.id) ? { phase: context.messagePhases.get(item.id) } : {}), + ...(context.asyncMessageIds.has(item.id) ? { delivery: "async" as const } : {}), messageId, text: item.text, streaming: !completed, @@ -6003,6 +6007,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (payload.item.type === "agentMessage") { if (payload.item.phase != null) context.messagePhases.set(payload.item.id, payload.item.phase); + if (payload.item.delivery === "async") context.asyncMessageIds.add(payload.item.id); if (payload.item.phase == null || payload.item.phase === "final_answer") { yield* Ref.update(finalAnswerItemIdsByTurn, (current) => { const updated = new Map(current); @@ -6407,6 +6412,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (payload.item.phase != null) context.messagePhases.set(payload.item.id, payload.item.phase); + if (payload.item.delivery === "async") context.asyncMessageIds.add(payload.item.id); const finalAnswer = payload.item.phase == null || payload.item.phase === "final_answer"; if (finalAnswer) { yield* Ref.update(finalAnswerItemIdsByTurn, (current) => { @@ -8002,6 +8008,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( itemPositions: new Map(), fileChangeKindsByItem: new Map(), messagePhases: new Map(), + asyncMessageIds: new Set(), runningCompactionItemIds: new Set(), modelCalls: makeCodexModelCallState(), runningWebSearchItems: new Map(), diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index b14153601f69..ddd00a3b2a8d 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -8030,7 +8030,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { dispatchMode = { type: "queue_after_active" }; } - // An agent's automatic send must not overtake an earlier agent message still queued + // An agent's automatic send must not overtake its own earlier message still queued // (e.g. behind /compact), or the agent receives them out of send order. if ( command.deliveryIntent === "auto" && @@ -8047,7 +8047,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio queuedRuns.map((run) => run.userMessageId), ) .pipe(mapDispatchError(command)); - if ([...queuedMessages.values()].some((message) => message.createdBy === "agent")) { + if ( + [...queuedMessages.values()].some( + (message) => + message.createdBy === "agent" && message.senderThreadId === command.senderThreadId, + ) + ) { dispatchMode = { type: "queue_after_active" }; } } @@ -8164,6 +8169,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio delivery.generation !== requestedCompletion.generation || delivery.messageId !== command.messageId || (projection.messages.some((candidate) => candidate.id === command.messageId) && + command.steerFollowUpOfRunId === undefined && !isUndeliveredMailboxSteer(projection, command.messageId)) ) { return yield* new OrchestratorDispatchError({ @@ -8240,6 +8246,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const commandNotice = noticeKind === "command" && command.creationSource === "server"; if ( !freshContext && + // A steer follow-up was declined by the active turn; steering it again loses it. + command.steerFollowUpOfRunId === undefined && // Steering refuses a command, so a notice that reads like one stays queued. !isSlashCommand(command) && (delegatedCompletion !== undefined diff --git a/apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts b/apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts index 86323b0bcafb..80d875b76f94 100644 --- a/apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts +++ b/apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts @@ -417,7 +417,7 @@ it.effect.each([false, true])( ); it.effect.each(["none", "writer", "snapshots"] as const)( - "runs another stream's control during a busy commit; splits slow backlogs for a write waiting on %s", + "runs another stream's control during a busy commit; splits slow backlogs only for a write waiting on the writer (%s)", (waitingOn) => Effect.gen(function* () { const started = yield* Deferred.make(); @@ -468,13 +468,63 @@ it.effect.each(["none", "writer", "snapshots"] as const)( yield* Fiber.join(write); assert.deepEqual( yield* Queue.takeAll(recorder.output), - waitingOn === "none" + // A write still waiting on its own thread's snapshots gains nothing from a shorter batch. + waitingOn !== "writer" ? [[event(-1)], backlog] : [[event(-1)], ...backlog.map((raw) => [raw])], ); }), ); +it.effect("splits a slow batch once a waiting write's own snapshot has run", () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + let first = true; + const recorder = yield* recordBatches( + Effect.gen(function* () { + if (!first) return; + first = false; + yield* Deferred.succeed(started, undefined); + yield* Deferred.await(release); + }), + ); + const leading = yield* recorder + .consume(Stream.make(event(-1)), recorder.process, Effect.succeed(false)) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(started); + const own = snapshot("a", "a", "thread-a"); + const others = [0, 1, 2, 3].map((index) => snapshot(`b${index}`, "b", "thread-b")); + const pulled = yield* Deferred.make(); + const slow = yield* recorder + .consume( + Stream.fromArray([own, ...others]).pipe( + Stream.tap((raw) => + raw === others.at(-1) ? Deferred.succeed(pulled, undefined) : Effect.void, + ), + ), + (raw) => recorder.process(raw).pipe(Effect.andThen(TestClock.adjust("100 millis"))), + Effect.succeed(false), + ) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.await(pulled); + yield* TestClock.adjust(0); + const write = yield* recorder + .barrier(Queue.offer(recorder.output, [control]), ["thread-a"]) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(leading); + yield* Fiber.join(write); + yield* Fiber.join(slow); + assert.deepEqual(yield* Queue.takeAll(recorder.output), [ + [event(-1)], + [own], + [control], + others, + ]); + }), +); + const blockFirstCommit = Effect.gen(function* () { const started = yield* Deferred.make(); const release = yield* Deferred.make(); diff --git a/apps/server/src/orchestration-v2/ProviderCommitBatch.ts b/apps/server/src/orchestration-v2/ProviderCommitBatch.ts index 1fa7eac5ecd3..7fb354f10472 100644 --- a/apps/server/src/orchestration-v2/ProviderCommitBatch.ts +++ b/apps/server/src/orchestration-v2/ProviderCommitBatch.ts @@ -164,8 +164,8 @@ export const make = Effect.fn("ProviderCommitBatch.make")(function* ( const pending = new Set(); let closed = false; let servings = 0; - // Writes in `barrier` that have not finished; they wait on the batch or the writer it holds. - let waitingWriters = 0; + // The snapshots each unfinished `barrier` write waits on. + const waitingWrites = new Set>(); const shutdown = Effect.gen(function* () { closed = true; yield* Queue.shutdown(wake); @@ -319,10 +319,18 @@ export const make = Effect.fn("ProviderCommitBatch.make")(function* ( taken = 0; const startedAt = yield* Clock.monotonicTimeNanos; for (const { job, superseded } of units) { + // Cutting only helps a write that needs none of the units still to run. if ( taken > 0 && - waitingWriters > 0 && - (yield* Clock.monotonicTimeNanos) - startedAt >= MAX_HOLD_NANOS + waitingWrites.size > 0 && + (yield* Clock.monotonicTimeNanos) - startedAt >= MAX_HOLD_NANOS && + Array.from(waitingWrites).some((jobs) => + units + .slice(taken) + .every( + (unit) => !jobs.has(unit.job) && !unit.superseded.some((j) => jobs.has(j)), + ), + ) ) return; taken++; @@ -393,20 +401,23 @@ export const make = Effect.fn("ProviderCommitBatch.make")(function* ( ) { if (closed) return yield* Effect.interrupt; if (!enabled || (yield* CurrentWorker) === (yield* Effect.fiberId)) return yield* effect; + const jobs: ReadonlySet = new Set( + Array.from(pending).filter( + (job) => threadIds === undefined || threadIds.includes(job.threadId), + ), + ); return yield* Effect.uninterruptibleMask((restore) => { - waitingWriters++; + waitingWrites.add(jobs); return restore( Effect.gen(function* () { - for (const job of Array.from(pending)) { - if (threadIds === undefined || threadIds.includes(job.threadId)) yield* job.settled; - } + for (const job of jobs) yield* job.settled; if (closed) return yield* Effect.interrupt; return yield* effect; }), ).pipe( Effect.ensuring( Effect.sync(() => { - waitingWriters--; + waitingWrites.delete(jobs); }), ), ); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index f2f992d8f4ee..e6652c596390 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -611,6 +611,8 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( resumeCount: current.resumeCount + 1, })).pipe(Effect.as(threadInput.providerThread)), startTurn: () => options.startTurn ?? Effect.void, + resumeTurn: () => options.startTurn ?? Effect.void, + compactThread: () => options.startTurn ?? Effect.void, steerTurn: () => Effect.void, interruptTurn: () => Ref.update(state, (current) => ({ @@ -2137,6 +2139,103 @@ it.effect.each([ }), ); +const idleReleaseAroundRun = (start: "compactThread" | "resumeTurn") => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make(`thread-${start}-outlasts-idle-timeout`); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const subscriber = yield* runtime.subscribeEvents!; + const terminal = yield* subscriber.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + Effect.forkScoped, + ); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + nativeThreadId: `native-${threadId}`, + }); + const runId = idAllocator.derive.run({ threadId, ordinal: 1 }); + const run = { + appThread: (yield* projectionStore.getThreadProjection(threadId)).thread, + threadId, + runId, + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId }), + providerThread, + modelSelection, + runtimePolicy, + }; + const messageId = yield* idAllocator.allocate.message({ threadId, ordinal: 1 }); + yield* start === "compactThread" + ? runtime.compactThread!({ + ...run, + message: { + createdBy: "user", + creationSource: "web", + messageId, + text: "/compact", + attachments: [], + }, + }) + : runtime.resumeTurn!({ ...run, messageId }); + + // A running compaction or continuation can go minutes without a provider event. + yield* TestClock.adjust("2 seconds"); + assert.isTrue(yield* manager.isLive(providerSessionId)); + + const queue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId)); + assert.isDefined(queue); + yield* Queue.offer(queue!, { + type: "turn.terminal", + driver: CODEX_DRIVER, + providerThreadId: providerThread.id, + providerTurnId: idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: `native-turn-${start}`, + }), + runOrdinal: 1, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + // The event pump marks the run idle before it publishes the event. + yield* Fiber.join(terminal); + yield* TestClock.adjust("2 seconds"); + assert.isFalse(yield* manager.isLive(providerSessionId)); + }).pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1_000 }))); + }); + +it.effect.each([ + { run: "compaction", start: "compactThread" }, + { run: "manual continuation", start: "resumeTurn" }, +] as const)( + "ProviderSessionManagerV2 keeps a session through a $run that outlasts the idle timeout", + ({ start }) => idleReleaseAroundRun(start), +); + it.effect.each(["session metadata", "session status changes", "provider work"] as const)( "ProviderSessionManagerV2 expires idle sessions according to %s", (activity) => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index dc1ae318a4c2..291ac02272a2 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2532,6 +2532,80 @@ export const layerWithOptions = ( modelFamily: normalizeModelMetricLabel(model), }, }); + // A start, continuation or compaction keeps the session busy until its turn.terminal. + const busyTurn = ( + input: Pick< + ProviderAdapter.ProviderAdapterV2TurnInput, + "threadId" | "providerThread" | "runOrdinal" | "runId" + >, + run: () => Effect.Effect, + ) => + observeActivity( + providerSessionId, + ensureThreadAttached({ + providerSessionId, + threadId: input.threadId, + providerInstanceId: runtime.instanceId, + }), + ).pipe( + // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. + Effect.andThen( + holdThreadLoaded({ + providerSessionId, + threadId: input.threadId, + providerThread: input.providerThread, + }), + ), + Effect.andThen( + Effect.acquireUseRelease( + markBusy( + providerSessionId, + busyTurnKey(input.providerThread.id, input.runOrdinal), + runtime, + ).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.driver-session.activity-failed", { + providerSessionId, + cause, + }).pipe(Effect.as(true)), + ), + // A release between attach and markBusy leaves nothing to mark: fail the + // start instead of running it on a runtime being torn down. + Effect.flatMap((marked) => + marked + ? Effect.void + : Effect.fail( + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: runtime.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause: "The provider session was released while the turn started.", + }), + ), + ), + ), + run, + (_, exit) => + Exit.isFailure(exit) + ? observeActivity( + providerSessionId, + markIdle(providerSessionId, input.providerThread.id, input.runOrdinal), + ).pipe( + // A failed start can leave its native thread gone (Claude rejecting a + // resume), so the next start must ask the adapter to resume it again. + Effect.andThen( + forgetProviderThreadLoaded({ + providerSessionId, + threadId: input.threadId, + runtime, + }), + ), + ) + : Effect.void, + ), + ), + ); return { ...runtime, // Pi replaces its session snapshot as metadata changes. @@ -2663,78 +2737,32 @@ export const layerWithOptions = ( Effect.map(({ loaded }) => loaded), ), startTurn: (input) => - observeActivity( - providerSessionId, - ensureThreadAttached({ - providerSessionId, - threadId: input.threadId, - providerInstanceId: runtime.instanceId, - }), - ).pipe( - // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. - Effect.andThen( - holdThreadLoaded({ - providerSessionId, - threadId: input.threadId, - providerThread: input.providerThread, - }), + busyTurn(input, () => + agentFeedbackMode.pipe( + Effect.flatMap((agentFeedback) => runtime.startTurn({ ...input, agentFeedback })), + turnMetrics("send", input.modelSelection.model), ), - Effect.andThen( - Effect.acquireUseRelease( - markBusy( - providerSessionId, - busyTurnKey(input.providerThread.id, input.runOrdinal), - runtime, - ).pipe( - Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.driver-session.activity-failed", { - providerSessionId, - cause, - }).pipe(Effect.as(true)), - ), - // A release between attach and markBusy leaves nothing to mark: fail the - // start instead of running it on a runtime being torn down. - Effect.flatMap((marked) => - marked - ? Effect.void - : Effect.fail( - new ProviderAdapter.ProviderAdapterTurnStartError({ - driver: runtime.driver, - threadId: input.threadId, - providerThreadId: input.providerThread.id, - runId: input.runId, - cause: "The provider session was released while the turn started.", - }), - ), + ), + ...(runtime.resumeTurn === undefined + ? {} + : { + resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => + busyTurn(input, () => + runtime.resumeTurn!(input).pipe( + turnMetrics("resume", input.modelSelection.model), ), ), - () => - agentFeedbackMode.pipe( - Effect.flatMap((agentFeedback) => - runtime.startTurn({ ...input, agentFeedback }), - ), - turnMetrics("send", input.modelSelection.model), + }), + ...(runtime.compactThread === undefined + ? {} + : { + compactThread: (input: ProviderAdapter.ProviderAdapterV2TurnInput) => + busyTurn(input, () => + runtime.compactThread!(input).pipe( + turnMetrics("compact", input.modelSelection.model), ), - (_, exit) => - Exit.isFailure(exit) - ? observeActivity( - providerSessionId, - markIdle(providerSessionId, input.providerThread.id, input.runOrdinal), - ).pipe( - // A failed start can leave its native thread gone (Claude rejecting a - // resume), so the next start must ask the adapter to resume it again. - Effect.andThen( - forgetProviderThreadLoaded({ - providerSessionId, - threadId: input.threadId, - runtime, - }), - ), - ) - : Effect.void, - ), - ), - ), + ), + }), steerTurn: (input) => observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe( Effect.andThen(runtime.steerTurn(input).pipe(turnMetrics("steer"))), diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index d199eea71440..0fc200d0c571 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1723,6 +1723,149 @@ it.effect.each(declinedSteerTimings)( }), ); +// regression: #41509 a declined steer of a delegated completion wake must still queue the wake +it.effect("queues a delegated completion wake whose steer the provider declined", () => + Effect.gen(function* () { + const { events, started, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "steering-declined-delegated-completion", + false, + true, + Effect.void, + true, + undefined, + (turn) => + Effect.fail( + new ProviderAdapter.ProviderAdapterSteerDeclinedError({ + driver, + providerThreadId: turn.providerThread.id, + providerTurnId: turn.providerTurnId, + }), + ), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const first = started[0]!; + const messageId = MessageId.make("message:declined-wake"); + const taskId = NodeId.make("task:declined-wake"); + const parentRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id === first.runId, + )!; + const now = yield* DateTime.now; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("event:declined-wake:cohort"), + type: "run.updated", + threadId, + runId: first.runId, + occurredAt: now, + payload: { + ...parentRun, + delegatedCompletion: { + disposition: "open", + nextGeneration: 2, + delivery: { generation: 1, messageId, taskIds: [taskId] }, + }, + }, + }, + { + id: EventId.make("event:declined-wake:task"), + type: "subagent.updated", + threadId, + runId: first.runId, + nodeId: taskId, + occurredAt: now, + payload: { + id: taskId, + threadId, + runId: first.runId, + parentNodeId: first.rootNodeId, + origin: "app_owned", + createdBy: "agent", + driver, + providerInstanceId: instanceId, + providerThreadId: null, + childThreadId: null, + nativeTaskRef: null, + prompt: "Do background work", + title: "Background test", + model: null, + completionWake: "always", + completionDelivery: { state: "claimed", observedByRunId: null }, + status: "completed", + result: "done", + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("wake"), + threadId, + messageId, + text: "Delegated task completed", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + delegatedCompletion: { parentRunId: first.runId, generation: 1, taskIds: [taskId] }, + createdBy: "agent", + creationSource: "server", + }); + yield* worker.drain(); + const effects = yield* (yield* EffectOutbox.EffectOutboxV2).listByCommandId( + CommandId.make("wake"), + ); + assert.deepEqual( + effects.map((effect) => [effect.request.type, effect.status]), + [["provider-turn.steer", "succeeded"]], + "the declined steer's queue fallback was rejected", + ); + const pending = yield* orchestrator.getThreadProjection(threadId); + const queued = pending.runs.find( + (run) => run.userMessageId === messageId && run.id !== first.runId, + ); + assert.equal(queued?.status, "queued"); + + const turn = pending.providerTurns[0]!; + const settled = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status === "waiting", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: turn.providerThreadId, + providerTurnId: turn.id, + runOrdinal: first.runOrdinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* Fiber.join(settled); + yield* worker.drain(); + yield* orchestrator.resumeQueuedRuns; + yield* worker.drain(); + assert.equal(started[1]?.message.messageId, messageId, "the parent was never woken"); + }).pipe(Effect.provide(layer)); + }), +); + // regression: #26695 cancelling a Copilot prompt to steer it kills its background agents it.effect("queues a steer until the turn ends when the provider cannot steer it", () => Effect.gen(function* () { @@ -1920,6 +2063,56 @@ it.effect("delivers agent messages queued behind /compact before a later one ste }), ); +// regression: #41455 one sender's queued message holds back another sender's automatic steer +it.effect("an agent's automatic send steers past another sender's queued message", () => + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "agent-steer-past-other-sender", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const active = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "running", + )!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("send-first"), + threadId, + messageId: MessageId.make("message:queued-first"), + text: "queued first", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + senderThreadId: ThreadId.make("thread:sender-a"), + }); + yield* worker.drain(); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("send-urgent"), + threadId, + messageId: MessageId.make("message:urgent"), + text: "urgent", + attachments: [], + dispatchMode: { type: "steer_active", targetRunId: active.id }, + deliveryIntent: "auto", + createdBy: "agent", + creationSource: "mcp", + senderThreadId: ThreadId.make("thread:sender-c"), + }); + yield* worker.drain(); + + assert.lengthOf(started, 1); + assert.deepEqual( + steered.map((text) => text.split("\n").at(-1)), + ["urgent"], + ); + }).pipe(Effect.provide(layer)); + }), +); + // regression: #33454 a steer that restarts a completion wake run left its cohort claimed forever const restartCompletionWake = Effect.fn("restartCompletionWake")(function* ( harness: Pick< diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts index 5ac36c81da6b..daa90d011eed 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts @@ -82,6 +82,25 @@ const remark = ( const noRemarks: ReadonlyArray = []; +const codeRabbitReply = (status: string, action = "Action performed") => + ` + + + +
+${action} +
+
+
+ +${status} + +> Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. + +
+
+
`; + describe("evaluatePullRequestWatch", () => { it.each(["pending", "success"] as const)( "reports a required rebase once with %s CI", @@ -915,6 +934,76 @@ describe("evaluatePullRequestWatch", () => { assert.deepEqual(evaluatePullRequestWatch(report.next, detail(), comments).changes, []); }); + it("skips CodeRabbit review acknowledgements and wakes once for their outcome edits", () => { + const current = ` +
+✅ Actions performed + +Review triggered. + +
`; + // GitHub's GraphQL API names bots without the "[bot]" suffix that its REST API adds. + for (const [login, acknowledgement] of [ + ["coderabbitai[bot]", codeRabbitReply("Review triggered.")], + ["coderabbitai[bot]", codeRabbitReply("Full review triggered.")], + ["coderabbitai[bot]", current], + ["coderabbitai", current], + ] as const) { + const queued = { + ...remark(login, "2026-10-02T12:06:00Z", acknowledgement), + kind: "issue-comment" as const, + path: null, + }; + const watching = watch({ headSha: "aaaaaaaaaa", wakes: 2 }); + const progress = evaluatePullRequestWatch(watching, detail(), [queued]); + assert.deepEqual(progress.changes, []); + assert.equal(progress.next.remarksThrough, queued.createdAt); + assert.deepEqual(progress.next.remarkIds, [queued.id]); + assert.equal(progress.next.wakes, 2); + assert.isFalse(progress.exhausted); + assert.deepEqual(evaluatePullRequestWatch(progress.next, detail(), [queued]).changes, []); + + const outcome = { + ...queued, + body: codeRabbitReply("Review finished."), + editedAt: "2026-10-02T12:07:00Z", + }; + const finished = evaluatePullRequestWatch(progress.next, detail(), [outcome]); + assert.deepEqual(finished.changes, [{ kind: "remarks", remarks: [outcome] }]); + assert.equal(finished.next.wakes, 3); + assert.deepEqual(evaluatePullRequestWatch(finished.next, detail(), [outcome]).changes, []); + + const late = remark("reviewer", queued.createdAt); + const mixed = evaluatePullRequestWatch(watching, detail(), [queued, late]); + assert.deepEqual(mixed.changes, [{ kind: "remarks", remarks: [late] }]); + assert.deepEqual(mixed.next.remarkIds, [queued.id, late.id]); + } + }); + + it("keeps other replies and outcomes actionable beside CodeRabbit review progress", () => { + const bodies = [ + codeRabbitReply("Full review triggered.", "Actions performed"), + codeRabbitReply("Unable to review.", "Action not completed"), + codeRabbitReply("Here is the answer to your question."), + "Review triggered.", + codeRabbitReply("Review triggered.").replace( + "", + "", + ), + ]; + const comments = [ + ...bodies.map((body, index) => ({ + ...remark("coderabbitai[bot]", "2026-10-02T12:06:00Z", body), + id: `coderabbit-${index}`, + })), + remark("other-bot[bot]", "2026-10-02T12:06:00Z", bodies[0]), + remark("reviewer", "2026-10-02T12:06:00Z", bodies[0]), + ]; + const report = evaluatePullRequestWatch(watch(), detail(), comments); + assert.deepEqual(report.changes, [{ kind: "remarks", remarks: comments.slice(1) }]); + assert.deepEqual(evaluatePullRequestWatch(report.next, detail(), comments).changes, []); + }); + it("cuts a long remark in the wake message without splitting an emoji", () => { const body = `${"x".repeat(196)}🚀 and more`; const report = evaluatePullRequestWatch(watch(), detail(), [ diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index 8e378c1682c0..ab0daf1ef3d0 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -59,6 +59,15 @@ const isFailedCheck = (check: PullRequestCheck) => const workflowRunOf = (url: string | null) => url?.match(/^.*\/actions\/runs\/\d+/)?.[0] ?? null; const approvalKey = (check: PullRequestCheck) => workflowRunOf(check.url) ?? check.name; +function isReviewAcknowledgement(remark: PullRequestComment): boolean { + return ( + remark.author?.login.toLowerCase().replace(/\[bot\]$/, "") === "coderabbitai" && + /[\s\S]*?
[^\p{L}<]*Actions? performed<\/summary>\s*(?:
\s*
\s*
\s*)?(?:Full review|Review) triggered\./u.test( + remark.body.slice(0, 1_000), + ) + ); +} + export function evaluatePullRequestWatch( watch: ThreadPullRequestWatch, detail: Pick< @@ -236,7 +245,8 @@ export function evaluatePullRequestWatch( remark.author?.login.toLowerCase() !== own ); }); - if (fresh.length > 0) changes.push({ kind: "remarks", remarks: fresh }); + const actionable = fresh.filter((remark) => !isReviewAcknowledgement(remark)); + if (actionable.length > 0) changes.push({ kind: "remarks", remarks: actionable }); const latest = Math.max(through, ...fresh.map((remark) => Date.parse(activeAt(remark)))); const atLatest = fresh.filter((remark) => Date.parse(activeAt(remark)) === latest); const remarksThrough = latest === through ? watch.remarksThrough : activeAt(atLatest[0]!); diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts index f8ec027f5363..116481f9ee10 100644 --- a/apps/server/src/peer/PeerForwarding.test.ts +++ b/apps/server/src/peer/PeerForwarding.test.ts @@ -423,7 +423,17 @@ const makeLaptop = Effect.gen(function* () { ), Effect.provideService(McpSchema.McpServerClient, mcpClient), ); - return { links: Context.get(linking, PeerLinks.PeerLinks), call }; + const callAsClient = (name: string, args: Record) => + server.callTool({ name, arguments: args }).pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, { + ...scopeOf("outside-client"), + requestNamespace: "client:session-1", + thread: undefined, + client: { sessionId: "session-1", label: "claude.ai", access: "read-only" }, + }), + Effect.provideService(McpSchema.McpServerClient, mcpClient), + ); + return { links: Context.get(linking, PeerLinks.PeerLinks), call, callAsClient }; }); const failureOf = (result: McpSchema.CallToolResult) => { @@ -682,14 +692,20 @@ it.effect("runs any tool that takes a linked environment there", () => }); expect(archived.isError).toBe(false); expect((yield* Ref.get(seen)).stops).toEqual([`thread.archive ${boxThread}`]); - // A cursorless read from an agent here gets the newest page there, as it does locally. + // A cursorless read from here gets the newest page there, as it does locally. const read = yield* a.call("thread:laptop-full", "t3_thread_read", { environmentId: box.environmentId, threadId: boxThread, }); expect(read.isError).toBe(false); + const clientRead = yield* a.callAsClient("t3_thread_read", { + environmentId: box.environmentId, + threadId: boxThread, + }); + expect(clientRead.isError).toBe(false); expect((yield* Ref.get(seen)).reads).toEqual([ { beforePosition: Number.MAX_SAFE_INTEGER, limit: 10, view: "messages" }, + { beforePosition: Number.MAX_SAFE_INTEGER, limit: 10, view: "messages" }, ]); // This environment's own id keeps the call here. diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.ts index d60ebcd8f42d..17ef4f233f82 100644 --- a/apps/server/src/peer/PeerForwarding.ts +++ b/apps/server/src/peer/PeerForwarding.ts @@ -254,9 +254,9 @@ const make = Effect.gen(function* () { Effect.flatMap((enabled) => (enabled ? Effect.void : Effect.fail(linkedEnvironmentsOff))), ); - // A peer pages a client's cursorless read forward; an agent's gets the newest page, as it does here. - const newestPageForAgent = (scope: Scope, toolName: string, params: unknown) => { - if (toolName !== "t3_thread_read" || scope.thread === undefined) return undefined; + // Older peers page some cursorless reads forward; ask for the newest page, as a read here gets. + const newestPage = (toolName: string, params: unknown) => { + if (toolName !== "t3_thread_read") return undefined; const input = params as OrchestratorMcpThreadReadInput; return input.afterPosition === undefined && input.beforePosition === undefined ? { ...input, beforePosition: Number.MAX_SAFE_INTEGER } @@ -268,7 +268,7 @@ const make = Effect.gen(function* () { args: unknown, ): Effect.Effect, OrchestratorMcpFailure> => forward(scope, tool.name, tool.parametersSchema, tool.successSchema, environmentId, args); - const newest = newestPageForAgent(scope, tool.name, params); + const newest = newestPage(tool.name, params); const forwarded: Effect.Effect< Tool.Success, OrchestratorMcpFailure diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts index 8f1d6cc381d6..3861fbb97b07 100644 --- a/apps/server/src/peer/PeerLinks.test.ts +++ b/apps/server/src/peer/PeerLinks.test.ts @@ -859,9 +859,8 @@ it.effect("linking a picked machine that answers nowhere names it and links noth it.live("linking an address with nothing listening says so, unlike one that is not T3 Code", () => Effect.scoped( Effect.gen(function* () { - const closed = yield* Effect.scoped( - serveRaw(() => Effect.succeed(HttpServerResponse.empty({ status: 404 }))), - ); + // Any test worker can reuse a closed ephemeral port; port 2 is privileged and outside that range. + const closed = "http://127.0.0.1:2"; const notT3 = yield* serveRaw(() => Effect.succeed( HttpServerResponse.text("

Not Found

", { status: 404, contentType: "text/html" }), diff --git a/apps/server/src/persistence/OrchestrationEventStore.ts b/apps/server/src/persistence/OrchestrationEventStore.ts index e55d82713871..69b1b7be0632 100644 --- a/apps/server/src/persistence/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/OrchestrationEventStore.ts @@ -19,6 +19,7 @@ import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as SqlClient from "effect/sql/SqlClient"; import * as SqlSchema from "effect/sql/SqlSchema"; import * as Effect from "effect/Effect"; +import { identity } from "effect/Function"; import * as Layer from "effect/Layer"; import * as PubSub from "effect/PubSub"; import * as Option from "effect/Option"; @@ -181,8 +182,21 @@ interface ApplicationEventRow { const decodeV2EventJson = Schema.decodeUnknownEffect(OrchestrationV2DomainEventJson); const encodeV2EventJson = Schema.encodeEffect(OrchestrationV2DomainEventJson); const decodeV2StoredEvent = Schema.decodeUnknownEffect(OrchestrationV2StoredEvent); +// decodeV2EventJson already validated the event; decoding it again here is the hot cost in replay. +const decodeV2StoredEventHeader = Schema.decodeUnknownEffect( + OrchestrationV2StoredEvent.mapFields(({ event: _event, ...fields }) => fields), +); const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); +// Same result as decodeJson; only malformed input pays for the schema's error. +const parseJson = (json: string) => { + if (typeof json !== "string") return decodeJson(json); + try { + return Effect.succeed(JSON.parse(json)); + } catch { + return decodeJson(json); + } +}; function metadataForV2Event(event: OrchestrationV2DomainEvent): Record { return { @@ -196,11 +210,10 @@ function metadataForV2Event(event: OrchestrationV2DomainEvent): Record) : {}; const event = yield* decodeV2EventJson({ @@ -217,16 +230,14 @@ const rowToV2StoredEvent = Effect.fn("OrchestrationEventStore.rowToV2StoredEvent : { providerInstanceId: values.providerInstanceId }), ...(values.rawEventId === undefined ? {} : { rawEventId: values.rawEventId }), }); - return yield* decodeV2StoredEvent({ + const { sequence, commandId } = yield* decodeV2StoredEventHeader({ sequence: row.sequence, commandId: row.command_id, - event, }); + return { sequence, commandId, event }; }); -const rowToProjectEvent = Effect.fn("OrchestrationEventStore.rowToProjectEvent")(function* ( - row: ApplicationEventRow, -) { +const rowToProjectEvent = Effect.fnUntraced(function* (row: ApplicationEventRow) { return yield* decodeProjectEvent({ sequence: row.sequence, eventId: row.event_id, @@ -237,8 +248,8 @@ const rowToProjectEvent = Effect.fn("OrchestrationEventStore.rowToProjectEvent") commandId: row.command_id, causationEventId: row.causation_event_id, correlationId: row.correlation_id, - payload: yield* decodeJson(row.payload_json), - metadata: yield* decodeJson(row.metadata_json), + payload: yield* parseJson(row.payload_json), + metadata: yield* parseJson(row.metadata_json), }); }); @@ -250,11 +261,12 @@ function rowToApplicationStoredEvent( const isKnownProjectEventType = Schema.is(ProjectEventType); -const keepReplayRow = (row: ApplicationEventRow, skipUnknownEventTypes?: boolean) => - skipUnknownEventTypes !== true || - (row.aggregate_kind === "project" - ? isKnownProjectEventType(row.event_type) - : isKnownOrchestrationV2EventType(row.event_type)) +const keepKnownEventTypeRow = (row: ApplicationEventRow) => + ( + row.aggregate_kind === "project" + ? isKnownProjectEventType(row.event_type) + : isKnownOrchestrationV2EventType(row.event_type) + ) ? Effect.succeed(true) : Effect.logWarning("Skipping an application event row with an unknown event type", { aggregateKind: row.aggregate_kind, @@ -581,7 +593,9 @@ const makeEventStore = Effect.gen(function* () { ); }, ).pipe( - Stream.filterEffect((row) => keepReplayRow(row, input?.skipUnknownEventTypes)), + // Query the next page on the reader while this one decodes. + Stream.bufferArray({ capacity: 1 }), + input?.skipUnknownEventTypes === true ? Stream.filterEffect(keepKnownEventTypeRow) : identity, Stream.mapEffect((row) => rowToV2StoredEvent(row).pipe( Effect.mapError( @@ -589,6 +603,7 @@ const makeEventStore = Effect.gen(function* () { ), ), ), + Stream.withSpan("OrchestrationEventStore.readAgentEvents"), ); }; @@ -716,7 +731,9 @@ const makeEventStore = Effect.gen(function* () { }), ), ).pipe( - Stream.filterEffect((row) => keepReplayRow(row, input.skipUnknownEventTypes)), + // Query the next page on the reader while this one decodes. + Stream.bufferArray({ capacity: 1 }), + input.skipUnknownEventTypes === true ? Stream.filterEffect(keepKnownEventTypeRow) : identity, Stream.mapEffect((row) => rowToApplicationStoredEvent(row).pipe( Effect.mapError( @@ -724,6 +741,7 @@ const makeEventStore = Effect.gen(function* () { ), ), ), + Stream.withSpan("OrchestrationEventStore.readApplicationEvents"), ); const streamProjectedApplicationEvents: OrchestrationEventStore["Service"]["streamProjectedApplicationEvents"] = diff --git a/apps/server/src/preview/PortScanner.test.ts b/apps/server/src/preview/PortScanner.test.ts index e2fdbe4efea2..b9e3cee2a7b0 100644 --- a/apps/server/src/preview/PortScanner.test.ts +++ b/apps/server/src/preview/PortScanner.test.ts @@ -837,6 +837,56 @@ effectIt.effect.each(["linux", "darwin", "win32"] as const)( }, ); +effectIt.effect.each(["linux", "darwin"] as const)( + "skips the DevTools port of a browser an agent's tool launched on %s", + (platform) => { + const appPort = 43_126; + const devToolsPort = 43_127; + const agentEnvironment = `PATH=/usr/bin\0${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`; + const procFiles: Record = { + "/proc/4242/environ": agentEnvironment, + "/proc/4242/cmdline": "node\0server.js\0", + "/proc/6000/environ": agentEnvironment, + "/proc/6000/cmdline": "/opt/google/chrome/chrome\0--remote-debugging-port=0\0about:blank\0", + }; + const missing = FileSystem.makeNoop({}); + const layer = layerScanner.pipe( + Layer.provide( + Layer.mergeAll( + FileSystem.layerNoop({ + readFileString: (path) => { + const content = procFiles[path]; + return content === undefined ? missing.readFileString(path) : Effect.succeed(content); + }, + }), + Layer.succeed(ProcessRunner.ProcessRunner, { + run: (input) => + Effect.succeed( + processOutput( + input.command === "lsof" + ? `p4242\ncnode\nn127.0.0.1:${appPort}\np6000\ncchrome\nn127.0.0.1:${devToolsPort}\n` + : ` 4242 1 node server.js PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-agent\n` + + ` 6000 1 /opt/google/chrome/chrome --remote-debugging-port=0 about:blank PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-agent\n`, + ), + ), + }), + Layer.succeed(HostProcess.Platform, platform), + FetchHttpClient.layer.pipe( + Layer.provide(Layer.succeed(FetchHttpClient.Fetch, () => Promise.reject(new Error()))), + ), + ), + ), + ); + + return Effect.gen(function* () { + const scanner = yield* PortScanner.PortDiscovery; + expect(yield* scanner.scan()).toMatchObject([ + { port: appPort, pid: 4242, agent: { threadId: "thread-agent" } }, + ]); + }).pipe(Effect.provide(layer)); + }, +); + effectIt.effect.each(["linux", "darwin"] as const)( "attributes listeners to the agent thread in their environment on %s, after the agent exits", (platform) => { diff --git a/apps/server/src/preview/PortScanner.ts b/apps/server/src/preview/PortScanner.ts index abe3603f44fb..db5dd3fa9e65 100644 --- a/apps/server/src/preview/PortScanner.ts +++ b/apps/server/src/preview/PortScanner.ts @@ -372,6 +372,9 @@ const lsofProcessIds = (raw: string): ReadonlyArray => { const AGENT_THREAD_ASSIGNMENT = new RegExp(`(?:^|\\s)${AGENT_THREAD_ENV}=(\\S+)`); +/** A browser an agent's tool drives listens only for DevTools, which is not a page to preview. */ +const DEVTOOLS_PORT_ARGUMENT = /(?:^|[\s\0])--remote-debugging-port=/; + /** Reads `/proc//environ`, whose entries are NUL-separated. */ const parseProcEnvironThread = (raw: string): ThreadId | null => { const prefix = `${AGENT_THREAD_ENV}=`; @@ -418,7 +421,9 @@ const parsePsEnvironmentThreads = ( const value = AGENT_THREAD_ASSIGNMENT.exec(match[3]!)?.[1]; threads.set( Number(match[1]), - value ? { threadId: ThreadId.make(value), isAgentCli: Number(match[2]) === serverPid } : null, + value && !DEVTOOLS_PORT_ARGUMENT.test(match[3]!) + ? { threadId: ThreadId.make(value), isAgentCli: Number(match[2]) === serverPid } + : null, ); } return threads; @@ -572,6 +577,11 @@ export const make = Effect.gen(function* PortDiscoveryMake() { Effect.orElseSucceed(() => null), ); if (threadId === null) return [pid, null] as const; + const isDevTools = yield* fileSystem.readFileString(`/proc/${pid}/cmdline`).pipe( + Effect.map((cmdline) => DEVTOOLS_PORT_ARGUMENT.test(cmdline)), + Effect.orElseSucceed(() => false), + ); + if (isDevTools) return [pid, null] as const; const parent = yield* fileSystem.readFileString(`/proc/${pid}/stat`).pipe( Effect.map(parseProcStatParent), Effect.orElseSucceed(() => null), diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index 491cb90a9d15..70fbb4ee396e 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -1810,6 +1810,34 @@ it.effect( ).pipe(Effect.provide(layer)), ); +it.effect("stops typing long text at the request's deadline and says how far it got", () => + Effect.scoped( + Effect.gen(function* () { + const { broker, tabId } = yield* ready; + const page = contexts[0]!.page; + page.evaluate.mockImplementation(async () => true as never); + let now = 1_700_000_000_000; + const clock = vi.spyOn(Date, "now").mockImplementation(() => now); + yield* Effect.addFinalizer(() => Effect.sync(() => clock.mockRestore())); + // Each piece of keys takes 10 seconds here: over the request's 5, under the 15-second default. + const type = vi.fn(async (_text: string) => void (now += 10_000)); + Object.assign(page, { keyboard: { type } }); + const failure = yield* broker + .invoke({ + scope, + tabId, + operation: "type", + input: { text: "a".repeat(200) }, + timeoutMs: 5_000, + }) + .pipe(Effect.flip); + expect(failure._tag).toBe("PreviewAutomationTimeoutError"); + expect(failure.message).toMatch(/after 64 of 200 characters/); + expect(type.mock.calls).toEqual([["a".repeat(64)]]); + }), + ).pipe(Effect.provide(layer)), +); + it.effect("reports a pending dialog without evaluating the page and resolves it explicitly", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index eb896686e483..47688e7c0bf7 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -2961,10 +2961,14 @@ const make = Effect.gen(function* () { return recordAction(tab, "upload", () => uploadFiles(tab, input as PreviewAutomationUploadInput), ); - case "type": - return recordAction(tab, "type", () => - ServerBrowserPage.type(tab.page, input as PreviewAutomationTypeInput), - ); + case "type": { + // As for click: typing stops at the broker's deadline instead of running on after the reply. + const typeInput = { + ...(input as PreviewAutomationTypeInput), + timeoutMs: Math.max(1, Math.floor(deadlineMs - performance.now())), + }; + return recordAction(tab, "type", () => ServerBrowserPage.type(tab.page, typeInput)); + } case "press": return recordAction(tab, "press", () => ServerBrowserPage.press(tab.page, input as PreviewAutomationPressInput), diff --git a/apps/server/src/preview/ServerBrowserPage.test.ts b/apps/server/src/preview/ServerBrowserPage.test.ts index 33bac55dd679..74cefba067ac 100644 --- a/apps/server/src/preview/ServerBrowserPage.test.ts +++ b/apps/server/src/preview/ServerBrowserPage.test.ts @@ -468,6 +468,36 @@ describe("server browser element refs", () => { expect(await inner.inputValue()).toBe(""); }); + it("types into a field that builds its value from keydown, with and without clear", async () => { + await page.setContent( + ``, + ); + const keys = (selector: string) => + page.locator(selector).evaluate((field) => (field as unknown as { keys: string }).keys); + await ServerBrowserPage.type(page, { locator: "#a", text: "girona42" }); + expect(await keys("#a")).toBe("girona42"); + await ServerBrowserPage.type(page, { locator: "#b", text: "girona42", clear: true }); + expect(await keys("#b")).toBe("girona42"); + await ServerBrowserPage.type(page, { locator: "#b", text: "a".repeat(501), clear: true }); + expect(await keys("#b")).toBe(`girona42${"a".repeat(501)}`); + + await page.setContent( + `
`, + ); + await ServerBrowserPage.type(page, { locator: "text=Email", text: "a@b.c", clear: true }); + expect(await page.locator("#e").inputValue()).toBe("a@b.c"); + await ServerBrowserPage.type(page, { locator: "#d", text: "2026-01-31", clear: true }); + expect(await page.locator("#d").inputValue()).toBe("2026-01-31"); + await ServerBrowserPage.type(page, { locator: "text=Tint", text: "#ff0000", clear: true }); + expect(await page.locator("#c").inputValue()).toBe("#ff0000"); + await ServerBrowserPage.type(page, { locator: "#r", text: "70", clear: true }); + expect(await page.locator("#r").inputValue()).toBe("70"); + await ServerBrowserPage.type(page, { locator: "#e", text: "x\ny" }); + await ServerBrowserPage.type(page, { locator: "#t", text: "one\r\ntwo" }); + expect(await page.locator("#t").inputValue()).toBe("one\ntwo"); + expect(await page.locator("#sent").inputValue()).toBe(""); + }); + it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => { await page.setContent(`
password:
@@ -1092,7 +1122,7 @@ describe("server browser type", () => { ({ locator: () => ({ last: () => ({ count: () => new Promise(() => {}) }) }), evaluate: focusAnswer, - keyboard: { insertText: async (text: string) => void typed.push(text) }, + keyboard: { type: async (text: string) => void typed.push(text) }, }) as unknown as Page; it("types into the focused field when Playwright's utility world never answers", async () => { @@ -1129,6 +1159,30 @@ describe("server browser type", () => { detail: { timeoutMs: 300 }, }); expect(typed).toEqual([]); + + // A target whose element is found but whose page then stops answering. + const fill = vi.fn(async () => {}); + const hung = { + locator: () => ({ evaluate: () => new Promise(() => {}), fill }), + keyboard: { type: async (text: string) => void typed.push(text) }, + } as unknown as Page; + void ServerBrowserPage.type(hung, { + locator: "#field", + text: "hello", + clear: true, + timeoutMs: 300, + }).then( + () => (outcome = "typed"), + (error: unknown) => (outcome = error), + ); + outcome = "pending"; + await vi.advanceTimersByTimeAsync(300); + expect(outcome).toMatchObject({ + tag: "PreviewAutomationTimeoutError", + detail: { timeoutMs: 300 }, + }); + expect(fill).not.toHaveBeenCalled(); + expect(typed).toEqual([]); } finally { vi.useRealTimers(); } diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index eda2f28ac76c..7f9fe26e20ad 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -1093,8 +1093,8 @@ const focusTextTarget = (target: FocusCandidate | null) => { return active != null && (active === element || element.contains(active)); }; -// A `*:focus` locator needs Playwright's utility world, which some desktop tabs never get. -const focusedTextField = async (page: Page, timeout: number) => { +// Playwright's own timeout covers finding the element, not a page that stops answering the evaluation. +const pageAnswer = async
(answer: Promise, timeout: number) => { let timer: ReturnType | undefined; const expired = new Promise((_, reject) => { timer = setTimeout( @@ -1102,29 +1102,77 @@ const focusedTextField = async (page: Page, timeout: number) => { reject( new ServerBrowserOperationError({ tag: "PreviewAutomationTimeoutError", - message: `The page did not report its focused element within ${timeout}ms, so no text was typed.`, + message: `The page did not answer within ${timeout}ms, so no text was typed.`, detail: { timeoutMs: timeout }, }), ), timeout, ); }); - return await Promise.race([page.evaluate(focusTextTarget, null), expired]).finally(() => - clearTimeout(timer), + return await Promise.race([answer, expired]).finally(() => clearTimeout(timer)); +}; + +// Serialized into the page's main world, so it must not reference module scope. +const valueOnlyInput = ( + target: FocusCandidate & { + closest(selector: string): { readonly control: FocusCandidate | null } | null; + }, +) => { + // As fill does, a target that is not a control stands for its label's control. + const element = target.tagName === "INPUT" ? target : target.closest("label")?.control; + return ( + element?.tagName === "INPUT" && + ["color", "date", "datetime-local", "month", "range", "time", "week"].includes( + element.type ?? "", + ) ); }; +// Keys reach pages that build their value from keydown. Line breaks stay text: Enter would submit the form. +const typeKeys = async (page: Page, text: string, timeoutMs: number, deadline: number) => { + let typed = 0; + for (const [index, part] of text.split(/([\r\n]+)/u).entries()) { + // Keys cost about a millisecond each, so long text is sent in pieces that stop at the deadline. + const pieces = index % 2 === 1 ? [part] : (part.match(/[^]{1,64}/gu) ?? []); + for (const piece of pieces) { + if (Date.now() >= deadline) { + const reason = `Typing stopped after ${typed} of ${text.length} characters, which the field now holds. Type the rest in another call or raise timeoutMs.`; + throw new ServerBrowserOperationError({ + tag: "PreviewAutomationTimeoutError", + message: reason, + detail: { timeoutMs, reason }, + }); + } + if (index % 2 === 1) await page.keyboard.insertText(piece); + else await page.keyboard.type(piece); + typed += piece.length; + } + } +}; + export const type = async (page: Page, input: PreviewAutomationTypeInput) => { - const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + // One deadline across steps keeps the reply inside the broker's grace; Playwright reads 0 as none. + const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const deadline = Date.now() + timeoutMs; + const remaining = () => Math.max(1, deadline - Date.now()); const locator = targetLocator(page, input); if (locator !== null && input.clear) { - await locator.fill(input.text, { timeout }); + // Pickers and sliders take a value such as 2026-01-31 only from fill, and some reject an empty one. + const timeout = remaining(); + if (await pageAnswer(locator.evaluate(valueOnlyInput, undefined, { timeout }), timeout)) { + await locator.fill(input.text, { timeout: remaining() }); + return; + } + // fill follows a label to its control and leaves that control focused for the keys. + await locator.fill("", { timeout: remaining() }); + await typeKeys(page, input.text, timeoutMs, deadline); return; } const focused = locator === null - ? await focusedTextField(page, timeout) - : await locator.evaluate(focusTextTarget, undefined, { timeout }); + ? // A `*:focus` locator needs Playwright's utility world, which some desktop tabs never get. + await pageAnswer(page.evaluate(focusTextTarget, null), remaining()) + : await locator.evaluate(focusTextTarget, undefined, { timeout: remaining() }); if (focused !== true) { throw new ServerBrowserOperationError({ tag: "PreviewAutomationTargetNotEditableError", @@ -1135,7 +1183,7 @@ export const type = async (page: Page, input: PreviewAutomationTypeInput) => { await page.keyboard.press("ControlOrMeta+A"); await page.keyboard.press("Delete"); } - await page.keyboard.insertText(input.text); + await typeKeys(page, input.text, timeoutMs, deadline); }; export const hover = async ( diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 486e3baeb4a7..32f733b09d17 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -180,6 +180,42 @@ it.effect.skipIf(windowsHost)("opens home-relative targets using the server home }).pipe(Effect.provide(NodeServices.layer)), ); +it.effect.skipIf(windowsHost)("reports a Finder reveal that open -R rejects", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + const open = path.join(binDir, "open"); + yield* fileSystem.writeFileString(open, "#!/bin/sh\n"); + yield* fileSystem.chmod(open, 0o755); + const target = path.join(binDir, "linked-file.txt"); + yield* fileSystem.writeFileString(target, ""); + + const exit = yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + return yield* launcher + .launchEditor({ editor: "file-manager", cwd: target, reveal: true }) + .pipe(Effect.exit); + }).pipe( + Effect.provide( + layerTest({ + platform: "darwin", + env: { PATH: binDir }, + spawnResult: (command) => { + assert.deepEqual(command.args, ["-R", target]); + return { exitCode: 1 }; + }, + }), + ), + ); + + assert.ok(Exit.isFailure(exit)); + const error = Cause.squash(exit.cause); + assert.instanceOf(error, ExternalLauncher.ExternalLauncherEditorSpawnError); + assert.include(String(error), target); + }).pipe(Effect.provide(NodeServices.layer)), +); + it.effect.skipIf(windowsHost)( "launched browsers and editors do not inherit ELECTRON_RUN_AS_NODE", () => @@ -883,6 +919,67 @@ for (const cwd of ["/workspace with spaces/", "/workspace with spaces/file.ts:12 ); } +// Stand-ins for a `--version` check. The Cursor Agent CLI installs a cursor script that fails +// when no IDE is behind it, and a slow first start stays silent for longer than the check waits. +const scripts = { works: "", fails: "exit 1", stalls: "exec sleep 30" }; +// Each row: title, editor, script first on PATH, extra install, result on darwin, result on linux. +for (const [title, id, first, extra, onDarwin, onLinux = onDarwin] of [ + ["keeps a working cursor on PATH ahead of the bundle", "cursor", "works", "bundle", "cursor"], + ["keeps a cursor that never answers --version", "cursor", "stalls", "none", "cursor"], + ["skips a failing cursor for a later cursor on PATH", "cursor", "fails", "later", "later"], + ["skips a failing cursor for the Cursor bundle", "cursor", "fails", "bundle", "bundle", "none"], + ["rejects a zed that never answers --version", "zed", "stalls", "none", "none"], +] as const) { + for (const platform of ["darwin", "linux"] as const) { + it.effect.skipIf(windowsHost)(`${title} on ${platform}`, () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-check-" }); + const commands = { + cursor: "cursor", + none: undefined, + first: path.join(home, "bin", id), + later: path.join(home, "later-bin", id), + bundle: path.join(home, "Applications/Cursor.app/Contents/Resources/app/bin/cursor"), + }; + for (const key of ["first", extra] as const) { + if (key === "none") continue; + yield* fs.makeDirectory(path.dirname(commands[key]), { recursive: true }); + const script = key === "first" ? scripts[first] : scripts.works; + yield* fs.writeFileString(commands[key], `#!/bin/sh\n${script}\n`); + yield* fs.chmod(commands[key], 0o755); + } + const editor = EDITORS.find((editor) => editor.id === id)!; + const env = { HOME: home, PATH: `${home}/bin:${home}/later-bin` }; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const started = yield* Deferred.make(); + // Signal that the `--version` check has a running process. + const signal = Deferred.succeed(started, undefined); + const [resolved] = yield* Effect.all( + [ + resolveEditorCommand(editor, env).pipe( + Effect.provideService(HostProcess.Platform, platform), + Effect.provideService(Path.Path, withSystemBin(path, path.join(home, "system-bin"))), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((cmd) => spawner.spawn(cmd).pipe(Effect.tap(signal))), + ), + ), + // The check runs on the test clock, so its timeout passes only when the clock moves. + first === "stalls" + ? Deferred.await(started).pipe(Effect.andThen(TestClock.adjust("2 seconds"))) + : Effect.void, + ], + { concurrency: "unbounded" }, + ); + const expected = commands[platform === "darwin" ? onDarwin : onLinux]; + assert.equal(Option.getOrUndefined(resolved)?.command, expected); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + } +} + for (const { layout, pathNames, fallbackNames, expected } of [ { layout: "PATH", pathNames: ["zed", "zeditor"], fallbackNames: [], expected: "zeditor" }, { @@ -942,14 +1039,16 @@ for (const { layout, pathNames, fallbackNames, expected } of [ ); } -// Linux editor discovery also probes fixed system directories; tests point them at a temp -// directory so an editor installed on the host cannot satisfy the lookup. +// Editor discovery also probes fixed system directories (Linux bin folders, macOS /Applications); +// tests point them at a temp directory so an editor installed on the host cannot satisfy the lookup. const withSystemBin = (path: Path.Path, systemBin: string): Path.Path => ({ ...path, join: (...parts) => path.join( ...parts.map((part) => - ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part, + ["/Applications", "/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) + ? systemBin + : part, ), ), }); diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index acf1d49d94ed..64e49c8ccce0 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -50,12 +50,14 @@ interface EditorLaunch { readonly command: string; readonly args: ReadonlyArray; readonly detached?: boolean; + readonly waitForExit?: boolean; } interface ProcessLaunch { readonly command: string; readonly args: ReadonlyArray; readonly options: ChildProcess.CommandOptions; + readonly waitForExit?: boolean; } interface TargetPathAndPosition { @@ -726,7 +728,14 @@ const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner > { if (platform === "darwin") { - return { editor: "file-manager", target, command: "open", args: ["-R", target] }; + // `open -R` reports targets Finder cannot reveal only through its exit status. + return { + editor: "file-manager", + target, + command: "open", + args: ["-R", target], + waitForExit: true, + }; } if (platform === "win32") { @@ -945,7 +954,7 @@ const readGraphicalSessionEnv = Effect.fn("externalLauncher.readGraphicalSession Effect.orElseSucceed((): NodeJS.ProcessEnv => ({})), ); -const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* ( +const launchProcess = Effect.fn("externalLauncher.launchProcess")(function* ( launch: ProcessLaunch, onError: (cause: unknown) => ExternalLauncherError, ): Effect.fn.Return { @@ -958,6 +967,14 @@ const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* ( extendEnv: false, }); + if (launch.waitForExit) { + const exitCode = yield* spawner.exitCode(command).pipe(Effect.mapError(onError)); + if (exitCode !== 0) { + return yield* onError(new Error(`${launch.command} exited with status ${exitCode}`)); + } + return; + } + yield* spawner.spawn(command).pipe( Effect.flatMap((handle) => handle.unref), Effect.asVoid, @@ -970,7 +987,7 @@ const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* ( target: string, ): Effect.fn.Return { const launch = yield* resolveBrowserLaunch(target); - return yield* launchAndUnref( + return yield* launchProcess( launch, (cause) => new ExternalLauncherBrowserSpawnError({ @@ -1001,10 +1018,11 @@ const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(fu if (spawnCommand.shell && launch.args.some((arg) => WINDOWS_SHIM_UNSAFE_ARG_PATTERN.test(arg))) { return yield* new ExternalLauncherUnsupportedTargetError({ editor: launch.editor }); } - yield* launchAndUnref( + yield* launchProcess( { command: spawnCommand.command, args: spawnCommand.args, + waitForExit: launch.waitForExit ?? false, options: { detached: launch.detached ?? true, shell: spawnCommand.shell, diff --git a/apps/server/src/project/AgentSessionJson.ts b/apps/server/src/project/AgentSessionJson.ts index c9dc6baa5f5e..35b2ac9fad1b 100644 --- a/apps/server/src/project/AgentSessionJson.ts +++ b/apps/server/src/project/AgentSessionJson.ts @@ -49,7 +49,11 @@ export class TranscriptJsonLimitError extends Schema.TaggedError void, selectPath: (path: JsonPath) => boolean, - options?: { readonly maxDepth?: number }, + options?: { + readonly maxDepth?: number; + // Reports each selected top-level string field as soon as it ends, before the record does. + readonly onTopLevelString?: (key: string, value: string) => void; + }, ) { // 3.6.0 omits the synchronous tokenizer from types; parser() adds an unnecessary async generator. const { jsonParser } = StreamJson as typeof StreamJson & { @@ -133,7 +137,13 @@ export function createTranscriptJsonReader( return; case "endString": case "endNumber": - if (selectedValue) assemble(token); + if (selectedValue) { + const parent = stack[0]; + if (token.name === "endString" && stack.length === 1 && typeof parent?.key === "string") { + options?.onTopLevelString?.(parent.key, value); + } + assemble(token); + } endValue(); return; case "nullValue": diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index ae61c81e63b0..a244fd56ff66 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -2464,6 +2464,63 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("imports a Claude session whose first prompt carries an image over 1 MiB", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-large-image-claude-"); + const codexHomePath = yield* makeTempDir("t3code-large-image-codex-"); + const workspace = yield* makeTempDir("t3code-large-image-workspace-"); + const sessionId = "large-image-session"; + const contents = [ + { type: "queue-operation", operation: "enqueue", sessionId }, + { type: "queue-operation", operation: "dequeue", sessionId }, + { + type: "user", + cwd: workspace, + sessionId, + timestamp: "2026-08-24T10:00:00.000Z", + message: { + role: "user", + content: [ + { type: "text", text: "Look at this screenshot" }, + { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: "A".repeat(1_100 * 1024), + }, + }, + ], + }, + }, + { + type: "assistant", + sessionId, + timestamp: "2026-08-24T10:01:00.000Z", + message: { role: "assistant", content: [{ type: "text", text: "Done" }] }, + }, + ] + .map((record) => encodeTranscriptRecord(record)) + .join("\n"); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-large-image", `${sessionId}.jsonl`), + contents, + mtimeMs: nowMs - 60 * 60 * 1000, + }); + + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + + expect(threads.map((thread) => thread.providerSessionId)).toEqual([sessionId]); + }), + ); + it.effect("imports every transcript that fits the per-file record limit", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 24c887a43592..b5713f351ed3 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -170,6 +170,17 @@ const decodePiEntryLinks = Schema.decodeUnknownOption( }), ); const selectTranscriptPath = createTranscriptJsonSelector(TranscriptRecord); +// Only the fields extractCwd reads, so a cwd record carrying a large image stays small in memory. +const selectCwdPath = createTranscriptJsonSelector( + Schema.Struct({ + cwd: Schema.String, + type: Schema.String, + payload: Schema.Struct({ + cwd: Schema.String, + source: Schema.Struct({ subagent: Schema.Null, subAgent: Schema.Null }), + }), + }), +); const decodeCodexTurnMetadata = Schema.decodeUnknownOption(CodexTurnMetadata); export const decodeImportedTranscriptPayload = Schema.decodeUnknownOption( Schema.Struct({ @@ -845,13 +856,7 @@ function isT3ManagedWorktree( } // false stops metadata scanning for an excluded rollout, even if later records contain a cwd. -function extractCwd(line: string, source: AgentSessionSource): string | null | false { - let parsed: unknown; - try { - parsed = JSON.parse(line); - } catch { - return null; - } +function extractCwd(parsed: unknown, source: AgentSessionSource): string | null | false { if (typeof parsed !== "object" || parsed === null) return null; const record = parsed as Record; @@ -1245,11 +1250,28 @@ export const make = Effect.gen(function* () { const size = isCompressedTranscript(transcript.filePath) ? Number.POSITIVE_INFINITY : transcript.identity.size; - const decoder = new TextDecoder(); - let remaining = ""; let bytesRead = 0; let recordsRead = 0; - const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, size); + let selectedBytes = 0; + const reserveSelected = (bytes: number) => { + selectedBytes += bytes; + if (selectedBytes > MAX_TRANSCRIPT_SCAN_BYTES) { + throw new TranscriptJsonLimitError({ + message: "Transcript cwd fields exceed the scan limit", + }); + } + }; + // Claude writes cwd before message, so a record with a large image need not be read to its end. + let topLevelCwd: string | null = null; + const createReader = () => + createTranscriptJsonReader(reserveSelected, selectCwdPath, { + onTopLevelString: (key, value) => { + if (key === "cwd" && value.trim().length > 0) topLevelCwd ??= value; + }, + }); + let reader = createReader(); + let decoder = new TextDecoder(); + let recordStarted = false; const reserveRecord = () => { if ( recordsRead === MAX_METADATA_RECORDS_PER_TRANSCRIPT || @@ -1262,13 +1284,43 @@ export const make = Effect.gen(function* () { budget.recordsRemaining -= 1; return true; }; - const readLastRecord = () => { - const record = remaining + decoder.decode(); - return record.length === 0 || !reserveRecord() - ? null - : extractCwd(record.trim(), source); + const finishRecord = () => { + reader.write(decoder.decode()); + const value = reader.finish(); + reader = createReader(); + decoder = new TextDecoder(); + recordStarted = false; + selectedBytes = 0; + return extractCwd(value, source); }; + const scanChunk = (chunk: Uint8Array): string | false | null | undefined => { + let start = 0; + while (start < chunk.byteLength) { + const newline = chunk.indexOf(10, start); + const end = newline === -1 ? chunk.byteLength : newline; + if (end > start) { + recordStarted = true; + reader.write(decoder.decode(chunk.subarray(start, end), { stream: true })); + if (topLevelCwd !== null) return reserveRecord() ? topLevelCwd : null; + } + if (newline === -1) return undefined; + if (!reserveRecord()) return null; + const cwd = finishRecord(); + if (cwd !== null) return cwd; + start = newline + 1; + } + return undefined; + }; + const parse = (f: () => A) => + Effect.try({ + try: f, + catch: (cause) => + new TranscriptParseError({ filePath: transcript.filePath, cause }), + }); + const readLastRecord = () => + !recordStarted || !reserveRecord() ? null : finishRecord(); + const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, size); while (bytesRead < maxBytes) { if (budget.bytesRemaining === 0 || budget.operationsRemaining === 0) { budget.truncated = true; @@ -1283,26 +1335,19 @@ export const make = Effect.gen(function* () { budget.bytesRemaining -= readSize; const next = yield* readChunk(readSize); if (Option.isNone(next)) { - return readLastRecord(); + return yield* parse(readLastRecord); } bytesRead += next.value.byteLength; - remaining += decoder.decode(next.value, { stream: true }); - const lines = remaining.split("\n"); - remaining = lines.pop() ?? ""; - - for (const line of lines) { - if (!reserveRecord()) return null; - const cwd = extractCwd(line.trim(), source); - if (cwd !== null) return cwd; - } + const result = yield* parse(() => scanChunk(next.value)); + if (result !== undefined) return result; } if (bytesRead < size) { budget.truncated = true; return null; } - return readLastRecord(); + return yield* parse(readLastRecord); }), ), ), diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index f2bc091bb607..2ed799ef5d09 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -1020,7 +1020,9 @@ describe("ProjectSetupScriptRunner", () => { const { writes } = yield* setup({ shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", }); - expect(yield* Queue.take(writes)).toContain("$global:LASTEXITCODE"); + const submitted = yield* Queue.take(writes); + expect(submitted).toContain("$global:LASTEXITCODE"); + expect(submitted).not.toContain("\x1b[200~"); }), ); @@ -1091,9 +1093,11 @@ describe("ProjectSetupScriptRunner", () => { it.effect("types into a quiet shell that has no line editor", () => Effect.gen(function* () { - const { writes } = yield* setup(); + const { writes } = yield* setup({ command: "printf '%s\\n' 'setup-ready'\n".repeat(120) }); yield* TestClock.adjust("3 seconds"); - expect(yield* Queue.take(writes)).toContain("vp i"); + const submitted = yield* Queue.take(writes); + expect(submitted).toContain("setup-ready"); + expect(submitted).not.toContain("\x1b[200~"); }), ); @@ -1153,6 +1157,7 @@ const runObservedSetup = Effect.fnUntraced(function* (command: string) { const { writes, outputLines, emit, completion } = yield* setup({ command }); yield* emit({ ...event, type: "output", data: "\x1b[?2004h" }); const submitted = yield* Queue.take(writes); + const shellInput = submitted.replace("\x1b[200~", "").replace("\x1b[201~", ""); const cwd = yield* HostProcess.WorkingDirectory; const env = yield* HostProcess.Environment; @@ -1163,7 +1168,7 @@ const runObservedSetup = Effect.fnUntraced(function* (command: string) { const handle = yield* spawner.spawn( ChildProcess.make( "/bin/bash", - ["--noprofile", "--norc", "-c", submitted.replaceAll("\r", "\n")], + ["--noprofile", "--norc", "-c", shellInput.replaceAll("\r", "\n")], { cwd, env: { PATH: env.PATH }, @@ -1184,6 +1189,7 @@ const runObservedSetup = Effect.fnUntraced(function* (command: string) { yield* emit({ ...event, type: "closed" }); return { submitted, + shellInput, lines: yield* Queue.clear(outputLines), exitCode: (yield* completion).exitCode, }; @@ -1229,9 +1235,10 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX setup co assert.deepEqual(result.lines, expected); assert.equal(result.exitCode, 0); assert.equal(result.submitted.at(-1), "\r"); - assert.notInclude(result.submitted, "\n"); - // The runner can write before the shell switches the terminal out of canonical mode. - for (const line of result.submitted.slice(0, -1).split("\r")) { + assert.isTrue(result.submitted.startsWith(" \x1b[200~")); + assert.isTrue(result.submitted.endsWith("\x1b[201~\r")); + assert.notInclude(result.submitted.slice(0, -1), "\r"); + for (const line of result.shellInput.slice(0, -1).split("\n")) { assert.isBelow(utf8.encode(line).byteLength, 1_024); } }), diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index 8b84d5db10d9..1ac01dd94286 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -415,7 +415,7 @@ export const make = Effect.gen(function* () { const seen = activity; yield* Effect.sleep(SHELL_QUIET_FALLBACK); if (activity !== seen) continue; - if (!busy) return "ready" as const; + if (!busy) return "quiet" as const; yield* input.onStartupPrompt; } }); @@ -627,7 +627,12 @@ export const make = Effect.gen(function* () { : terminalManager.write({ threadId: input.threadId, terminalId, - data: projectScriptTerminalInput(commandLine), + // macOS zsh garbles long typed-ahead multiline input; a live line editor takes it as one paste. + data: projectScriptTerminalInput( + shell === "ready" && completionShell === "posix" && commandLine.includes("\r") + ? `\x1b[200~${commandLine.replaceAll("\r", "\n")}\x1b[201~` + : commandLine, + ), }), ), Effect.catchCause((cause) => diff --git a/apps/server/src/project/RepositoryIdentityResolver.test.ts b/apps/server/src/project/RepositoryIdentityResolver.test.ts index 1c00bd075779..808e553846ac 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.test.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.test.ts @@ -128,6 +128,47 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { }).pipe(Effect.provide(ProcessRunner.layer)), ); + it.effect("keys a remote by its configured URL when insteadOf rewrites it", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-instead-of-test-", + }); + + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "origin", "https://github.com/T3Tools/t3code.git"]); + yield* git(cwd, ["config", "url.https://proxy.example/.insteadOf", "https://github.com/"]); + yield* git(cwd, ["config", "remote.origin.gh-resolved", "base"]); + const remotes = yield* git(cwd, ["remote", "-v"]); + expect(remotes.stdout).toContain("https://proxy.example/T3Tools/t3code.git (fetch)"); + + const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const identity = yield* resolver.resolve(cwd); + + expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code"); + expect(identity?.provider).toBe("github"); + expect(identity?.displayName).toBe("T3Tools/t3code"); + expect(identity?.locator).toEqual({ + source: "git-remote", + remoteName: "origin", + remoteUrl: "https://github.com/T3Tools/t3code.git", + }); + + const shorthandCwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-instead-of-shorthand-test-", + }); + yield* git(shorthandCwd, ["init"]); + yield* git(shorthandCwd, ["remote", "add", "origin", "gh:T3Tools/t3code.git"]); + yield* git(shorthandCwd, ["config", "url.https://github.com/.insteadOf", "gh:"]); + + const shorthandIdentity = yield* resolver.resolve(shorthandCwd); + + expect(shorthandIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); + expect(shorthandIdentity?.provider).toBe("github"); + expect(shorthandIdentity?.locator.remoteUrl).toBe("https://github.com/T3Tools/t3code.git"); + }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), + ); + it.effect("keeps a literal .git in an Azure DevOps repository name", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.ts index 22144cb6b964..d40355750e80 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.ts @@ -51,14 +51,35 @@ function isLocalRemoteUrl(url: string): boolean { return colonIndex === -1 || (slashIndex !== -1 && slashIndex < colonIndex); } -function parseRemoteFetchUrls(stdout: string): Map { +// `git remote -v` applies url.*.insteadOf, which can point a GitHub remote at a proxy or mirror. +// A configured URL that names a forge wins; a shorthand like `gh:` is known only once rewritten. +function parseConfiguredRemoteUrls(config: string): Map { + const urls = new Map(); + for (const line of config.split("\n")) { + const match = /^remote\.(\S+)\.url (.+)$/u.exec(line); + // Git fetches from the first of several configured URLs. + if (match?.[1] && match[2] && !urls.has(match[1])) urls.set(match[1], match[2]); + } + return urls; +} + +function parseRemoteFetchUrls( + stdout: string, + configuredUrls: ReadonlyMap, +): Map { const remotes = new Map(); for (const line of stdout.split(/\r?\n/)) { // Git uses a tab before the URL and one space before the direction; both can occur in URLs. // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`. const match = /^(\S+)\t(.+) \((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(line); if (!match) continue; - const [, remoteName = "", remoteUrl = "", direction = ""] = match; + const [, remoteName = "", fetchUrl = "", direction = ""] = match; + const configuredUrl = configuredUrls.get(remoteName); + const remoteUrl = + configuredUrl !== undefined && + (sourceControlDefinitions.recognizeRemote(configuredUrl)?.kind ?? "unknown") !== "unknown" + ? configuredUrl + : fetchUrl; if ( direction !== "fetch" || remoteName.length === 0 || @@ -332,20 +353,24 @@ const resolveRepositoryIdentityFromCacheKey = Effect.fn( timeoutBehavior: "timedOutResult", }) .pipe(Effect.option); - const [remoteResult, resolvedResult] = yield* Effect.all( - [runGit(["remote", "-v"]), runGit(["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"])], + const [remoteResult, configResult] = yield* Effect.all( + [ + runGit(["remote", "-v"]), + runGit(["config", "--get-regexp", "^remote\\..*\\.(url|gh-resolved)$"]), + ], { concurrency: "unbounded" }, ); if (remoteResult._tag === "None" || remoteResult.value.code !== 0) { return null; } - const remotes = parseRemoteFetchUrls(remoteResult.value.stdout); - // Exits 1 when no remote has a mark. + // Exits 1 when no key matches. const resolved = - resolvedResult._tag === "Some" && resolvedResult.value.code === 0 - ? resolvedResult.value.stdout - : ""; + configResult._tag === "Some" && configResult.value.code === 0 ? configResult.value.stdout : ""; + const remotes = parseRemoteFetchUrls( + remoteResult.value.stdout, + parseConfiguredRemoteUrls(resolved), + ); const remote = pickPrimaryRemote(remotes, resolved); if (!remote) return null; const originUrl = remotes.get("origin"); diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 5cca0d2a961e..cf25d9c2f40d 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -115,6 +115,13 @@ function xml(source: string, extension: string): XmlNode { if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node); if ( (extension === ".docx" && node.name === "del") || + (extension === ".docx" && + node.name === "r" && + children(node) + .flatMap((child) => (child.name === "rPr" ? children(child) : [])) + .some( + (prop) => prop.name === "vanish" && ["true", "1", "on"].includes(prop.attrs.val ?? "1"), + )) || (odf && node.name === "annotation" && parent.name !== "semantics") || (extension === ".odp" && node.name === "page-thumbnail" && @@ -142,6 +149,20 @@ function xml(source: string, extension: string): XmlNode { const children = (node: XmlNode | undefined) => node?.children.filter((child): child is XmlNode => typeof child !== "string") ?? []; +function slideRelationshipId(slide: XmlNode, inheritedAttributes: XmlNode["attrs"]) { + for (const [name, value] of Object.entries(slide.attrs)) { + if (!name.endsWith(":id")) continue; + const binding = `xmlns:${name.slice(0, -3)}`; + const namespace = slide.attrs[binding] ?? inheritedAttributes[binding]; + if ( + namespace === "http://schemas.openxmlformats.org/officeDocument/2006/relationships" || + namespace === "http://purl.oclc.org/ooxml/officeDocument/relationships" + ) + return value; + } + return slide.attrs["r:id"] ?? slide.attrs.id; +} + function retainCompatibilityFallback(parent: XmlNode, fallback: XmlNode): boolean { // Markup-compatibility fallbacks repeat their mc:Choice content, e.g. Word text boxes. // Keep one when no Choice carries text, such as a chart with a VML caption. @@ -442,6 +463,7 @@ function* notebook(source: string): Generator { // Per-byte decoding only supports the single-byte \fcharset values. const FONT_CODE_PAGES = new Map([ + [0, "windows-1252"], [77, "macintosh"], [161, "windows-1253"], [162, "windows-1254"], @@ -454,6 +476,18 @@ const FONT_CODE_PAGES = new Map([ [238, "windows-1250"], ]); +// Per-byte decoding only supports single-byte code pages. +const singleByteCodePage = (value: number) => + value === 0 + ? "windows-1252" + : value === 866 + ? "ibm866" + : value === 10000 + ? "macintosh" + : value === 874 || (value >= 1250 && value <= 1258) + ? `windows-${value}` + : undefined; + function* rtf(source: string): Generator { if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document"); let state = { @@ -463,10 +497,12 @@ function* rtf(source: string): Generator { uc: 1, font: 0, fontTable: false, + fontFile: false, decoder: new TextDecoder("windows-1252"), }; const stack: Array = []; - // A font's \fcharset, not the document code page, encodes the bytes written in that font. + // A font's \cpg, else its \fcharset, not the document code page, encodes the bytes written in + // that font. A \cpg inside \fontfile encodes the font's file name instead. const fonts = new Map(); let defaultFont = 0; const decoder = () => fonts.get(state.font) ?? state.decoder; @@ -540,6 +576,7 @@ function* rtf(source: string): Generator { ) state.skip = true; if (control === "fonttbl") state.fontTable = true; + else if (control === "fontfile") state.fontFile = true; else if (control === "deff") state.font = defaultFont = value; else if (control === "f") { state.font = value; @@ -547,6 +584,9 @@ function* rtf(source: string): Generator { } else if (control === "fcharset" && state.fontTable) { const codePage = FONT_CODE_PAGES.get(value); if (codePage) fonts.set(state.font, new TextDecoder(codePage)); + } else if (control === "cpg" && state.fontTable && !state.fontFile) { + const codePage = singleByteCodePage(value); + if (codePage) fonts.set(state.font, new TextDecoder(codePage)); } if (control === "deleted") state.deleted = value !== 0; else if (control === "v") state.hiddenText = value !== 0; @@ -558,15 +598,7 @@ function* rtf(source: string): Generator { if (control === "mac" || (control === "ansicpg" && value === 10000)) state.decoder = new TextDecoder("macintosh"); else if (control === "ansicpg") { - // Per-byte decoding only supports single-byte code pages. - const label = - value === 0 - ? "windows-1252" - : value === 866 - ? "ibm866" - : value === 874 || (value >= 1250 && value <= 1258) - ? `windows-${value}` - : undefined; + const label = singleByteCodePage(value); if (!label) throw new Error("Unsupported RTF code page"); state.decoder = new TextDecoder(label, { fatal: true }); } else if (control === "uc") { @@ -606,12 +638,19 @@ async function* document(path: string, extension: string): AsyncGenerator name.replaceAll(/[A-Z]/gu, (char) => char.toLowerCase()); + const folded = new Map(); + for (const name of files.keys()) + if (!folded.has(foldAscii(name))) folded.set(foldAscii(name), name); + const part = (name: string) => (files.has(name) ? name : (folded.get(foldAscii(name)) ?? name)); + const has = (name: string) => files.has(part(name)); const notes: string[] = []; const skip = (name: string) => notes.push(`\n[Skipped document part: ${name} (missing or invalid XML).]\n`); const read = (name: string): XmlNode => { try { - const data = files.get(name); + const data = files.get(part(name)); if (!data) throw new Error("Missing document part"); return xml(data, extension); } catch (error) { @@ -624,18 +663,18 @@ async function* document(path: string, extension: string): AsyncGenerator rel.attrs.TargetMode !== "External") - .map((rel) => [rel.attrs.Id, rel.attrs.Target]), + .map((rel) => [rel.attrs.Id, rel.attrs]), ); if (extension === ".docx") { // The package relationship names the main part; Word for the web saves word/document2.xml. - const target = files.has("_rels/.rels") + const target = has("_rels/.rels") ? [...all(read("_rels/.rels"), "Relationship")].find( (rel) => rel.attrs.Type?.endsWith("/officeDocument") && rel.attrs.TargetMode !== "External", )?.attrs.Target : undefined; const main = target && NodePath.posix.normalize(target).replace(/^\//, ""); - yield* paragraphs(read(main && files.has(main) ? main : "word/document.xml")); + yield* paragraphs(read(main && has(main) ? main : "word/document.xml")); } else if ([".odt", ".ods", ".odp"].includes(extension)) { const content = read("content.xml"); if (extension === ".odt") yield* paragraphs(content); @@ -662,12 +701,19 @@ async function* document(path: string, extension: string): AsyncGenerator { + const target = workbookRelations.find((rel) => rel.Type?.endsWith(`/${part}`))?.Target; + return target ? NodePath.posix.resolve("/xl", target).slice(1) : `xl/${part}.xml`; + }; const dateSystem = ["1", "true"].includes( all(workbook, "workbookPr").next().value?.attrs.date1904 ?? "", ) ? "1904" : "1900"; - const styles = files.has("xl/styles.xml") ? read("xl/styles.xml") : undefined; + const stylesPath = workbookPartPath("styles"); + const styles = has(stylesPath) ? read(stylesPath) : undefined; const customFormats = new Map( styles ? [...all(styles, "numFmt")].map((node) => [node.attrs.numFmtId, node.attrs.formatCode]) @@ -675,14 +721,12 @@ async function* document(path: string, extension: string): AsyncGenerator node.name === "sldIdLst"); + const inheritedAttributes = { ...presentation?.attrs, ...slideList?.attrs }; let index = 0; for (const slide of children(slideList).filter((node) => node.name === "sldId")) { yield `\n\n## Slide ${++index}\n`; - const target = rels.get(slide.attrs["r:id"] ?? slide.attrs.id); + const target = rels.get(slideRelationshipId(slide, inheritedAttributes))?.Target; if (!target) { skip(`slide relationship ${index}`); continue; @@ -771,7 +816,7 @@ async function* document(path: string, extension: string): AsyncGenerator { \f0 \'e3\'e1\'c7\'cd\'d9\'c9\f1 : caf\'e9, \f0\plain\'c7a}`, "ملاحظة: café, Ça", ], + [ + "ANSI font under another code page", + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl\f0\froman\fcharset0 Times-Roman;}\f0 \'805 caf\'e9}`, + "€5 café", + ], + [ + "font code page", + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl{\f0\fnil\fcharset0\cpg1251 Arial;}{\f1\fnil\fcharset204 Arial{\*\fontfile\cpg1252 arial.ttf};}}\f0 \'cf\'f0\'e8\f1\'e2\'e5\'f2}`, + "Привет", + ], + [ + "ANSI font in a Macintosh document", + String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0 LucidaGrande;}\f0 pridr\'9eana}`, + "pridržana", + ], + [ + "Macintosh font code page", + String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0\cpg10000 Geneva;}\f0 Caf\'8e}`, + "Café", + ], [ "font character set outside the font table", String.raw`{\rtf1\ansi{\fonttbl{\f0\fcharset178 A;}{\f0\fcharset0 B;}{\f1\fcharset0 C;}{\f2\fcharset178 D;}{\f2 E;}}{\stylesheet{\s0\f1\fcharset178 N;}}\f0 \'e3\f1\'e3\f2\'e3}`, @@ -860,6 +880,16 @@ describe("question answer paths", () => { expected: ["Intro 3\nFee $700\tdue"], absent: ["PAGEREF", "$500", "Moved", "\u2011"], }, + { + ext: "docx", + bounded: true, + parts: { + "word/document.xml": + 'Opening FormulaOmittedZero False Off DraftNoteAsideShown', + }, + expected: ["Opening Zero False Off Shown"], + absent: ["Omitted", "Draft", "Note", "Aside", "Formula"], + }, { ext: "odt", bounded: true, @@ -923,9 +953,9 @@ describe("question answer paths", () => { "xl/workbook.xml": '', "xl/_rels/workbook.xml.rels": - '', - "xl/sharedStrings.xml": "Lantern", - "xl/styles.xml": + '', + "catalog/items.xml": "Lantern", + "formatting/cells.xml": '', "xl/worksheets/second.xml": '037', @@ -1011,7 +1041,9 @@ describe("question answer paths", () => { "ppt/presentation.xml": ` - + + + diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts index fb13edeafbda..a6207db60332 100644 --- a/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts +++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts @@ -421,48 +421,53 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic }), ); - it.effect("measures only the PR change using the renamed verified remote's fetch URL", () => - Effect.gen(function* () { - const repositories = yield* makeRepositories; - const fork = `${repositories.root}/fork`; - yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]); - yield* git(fork, ["branch", "stack-base", "main~1"]); - // The cached identity still names origin, which now belongs to the stale fork. - yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]); - yield* git(repositories.workspace, ["remote", "add", "origin", fork]); - yield* git(repositories.workspace, [ - "config", - `url.${repositories.remote}.insteadOf`, - "review-upstream:", - ]); - yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]); - const changed = yield* Deferred.make(); - const driver = yield* GitVcsDriver.GitVcsDriver; - const stored = yield* Deferred.make(); - const context = yield* Layer.build( - makeLayer({ - ...repositories, - stored, - generate: (input) => - git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe( - Effect.provideService(GitVcsDriver.GitVcsDriver, driver), - Effect.orDie, - Effect.flatMap((names) => Deferred.succeed(changed, names)), - Effect.as({ stops: [] }), - ), - }), - ); - const service = Context.get( - context, - PullRequestReviewGuideService.PullRequestReviewGuideService, - ); - yield* service.generate(reference); - assert.strictEqual(yield* Deferred.await(changed), "feature.txt"); - yield* Deferred.await(stored); - const result = yield* service.get(reference); - assert.strictEqual(result.guide?.headSha, repositories.headSha); - assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]); - }), + it.effect.each(["rewritten", "configured"] as const)( + "measures only the PR change through the renamed remote matched by its %s URL", + (locatorUrl) => + Effect.gen(function* () { + const repositories = yield* makeRepositories; + const fork = `${repositories.root}/fork`; + yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]); + yield* git(fork, ["branch", "stack-base", "main~1"]); + // The cached identity still names origin, which now belongs to the stale fork. + yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]); + yield* git(repositories.workspace, ["remote", "add", "origin", fork]); + yield* git(repositories.workspace, [ + "config", + `url.${repositories.remote}.insteadOf`, + "review-upstream:", + ]); + yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]); + const changed = yield* Deferred.make(); + const driver = yield* GitVcsDriver.GitVcsDriver; + const stored = yield* Deferred.make(); + const context = yield* Layer.build( + makeLayer({ + ...repositories, + ...(locatorUrl === "configured" + ? { locator: { ...ACME_APP.locator, remoteUrl: "review-upstream:" } } + : {}), + stored, + generate: (input) => + git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + Effect.orDie, + Effect.flatMap((names) => Deferred.succeed(changed, names)), + Effect.as({ stops: [] }), + ), + }), + ); + const service = Context.get( + context, + PullRequestReviewGuideService.PullRequestReviewGuideService, + ); + yield* service.generate(reference); + assert.strictEqual(yield* Deferred.await(changed), "feature.txt"); + yield* Deferred.await(stored); + const result = yield* service.get(reference); + assert.strictEqual(result.guide?.headSha, repositories.headSha); + assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]); + }), ); it.effect("keeps excerpts despite the checkout's diff driver and a failing hook", () => diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts index 0963b0aeaa52..916227c77214 100644 --- a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts +++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts @@ -146,7 +146,7 @@ const make = Effect.gen(function* () { stack: PullRequestStack | null, runId: string, ) { - // Identity names can be stale; match effective fetch URLs, including insteadOf rewrites. + // Identity names can be stale; the identity keeps a remote's URL before or after insteadOf. const names = yield* git .execute({ operation: "PullRequestReviewGuideService.listRemotes", @@ -157,16 +157,24 @@ const make = Effect.gen(function* () { const remote = yield* Effect.findFirst( [locator.remoteName, ...names.filter((name) => name !== locator.remoteName)], (name) => - git - .execute({ - operation: "PullRequestReviewGuideService.remoteUrl", - cwd: workspaceRoot, - args: ["remote", "get-url", "--", name], - }) - .pipe( - Effect.map((result) => result.stdout.trim() === locator.remoteUrl), - Effect.orElseSucceed(() => false), - ), + Effect.forEach( + [ + ["remote", "get-url", "--", name], + ["config", "--get-all", `remote.${name}.url`], + ], + (args) => + git + .execute({ + operation: "PullRequestReviewGuideService.remoteUrl", + cwd: workspaceRoot, + args, + }) + .pipe( + Effect.map((result) => result.stdout.split("\n")[0]?.trim() === locator.remoteUrl), + Effect.orElseSucceed(() => false), + ), + { concurrency: "unbounded" }, + ).pipe(Effect.map((matches) => matches.includes(true))), ).pipe(Effect.map(Option.getOrUndefined)); if (remote === undefined) { return yield* new PullRequestOperationError({ diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 6e6490cb58d6..5845c1b85ba6 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -40,6 +40,7 @@ import { import * as PullRequestProviderRegistry from "./PullRequestProviderRegistry.ts"; import * as PullRequestService from "./PullRequestService.ts"; import * as PullRequestReadCache from "./PullRequestReadCache.ts"; +import { resolveTarget } from "./pullRequestTarget.ts"; function project(input: { readonly id: string; @@ -425,6 +426,12 @@ it.effect("lists GitHub Enterprise PRs for a stored unknown repository after hos // Agents get the forge tools only where the host is one T3 reads. assert.isTrue(yield* service.servesProject("p1" as ProjectId)); assert.isFalse(yield* service.servesProject("p2" as ProjectId)); + // ...and those tools build PR URLs through the same refined forge. + const target = yield* resolveTarget( + { repository: "team/project", number: 42 }, + yield* service.addressedProject("p1" as ProjectId), + ); + assert.strictEqual(target.url, "https://code.example.test/team/project/pull/42"); }), ); @@ -3115,6 +3122,47 @@ it.effect("close and reopen notify subscribed readers after invalidating their c }), ); +it.effect("a refused merge notifies readers so they re-read the conflicting state", () => + Effect.gen(function* () { + let mergeable = true; + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequestSummary: () => + Effect.succeed({ + ...changeRequest(1, "2026-09-16T00:00:00.000Z"), + mergeability: mergeable ? "mergeable" : "conflicting", + }), + runAction: () => + Effect.suspend(() => { + mergeable = false; + return Effect.fail( + new PullRequestProviderError({ + provider: SourceControlProviderKind.make("github"), + operation: "runAction", + reason: "failed", + detail: "Pull Request has merge conflicts", + }), + ); + }), + }), + ], + }); + + assert.strictEqual((yield* service.summary(reference)).mergeability, "mergeable"); + const refreshed = yield* service.subscribeRefreshes.pipe( + Stream.take(1), + Stream.mapEffect(() => service.summary(reference)), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + yield* Effect.flip(service.runAction({ ...reference, action: "merge" })); + assert.strictEqual(Option.getOrThrow(yield* Fiber.join(refreshed)).mergeability, "conflicting"); + }), +); + it.effect("reads a host's repositories in one search, and files the rows back under each", () => Effect.gen(function* () { const asked: Array> = []; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 128178868c13..904d55654f04 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -258,6 +258,10 @@ export class PullRequestService extends Context.Service< readonly changes: (input: PullRequestRef) => Stream.Stream; /** Whether the project's checkout is on a forge T3 reads change requests from. */ readonly servesProject: (projectId: ProjectId) => Effect.Effect; + /** The project as `servesProject` sees it: identity resolved, its forge refined. */ + readonly addressedProject: ( + projectId: ProjectId, + ) => Effect.Effect; readonly threadComments: ( input: PullRequestThreadCommentsInput, ) => Effect.Effect; @@ -358,6 +362,7 @@ export interface SupportedProject { readonly cursorKey: string; readonly project: OrchestrationProjectShell; readonly api: PullRequestProviderApi; + readonly kind: SourceControlProviderKind; readonly repository: string; readonly host: string; /** Unlike Azure repository names, remotes are unique across an organization. */ @@ -366,6 +371,8 @@ export interface SupportedProject { } interface WorkspaceProjects { + /** Every project read, with its repository identity resolved. */ + readonly projects: ReadonlyArray; readonly supported: ReadonlyArray; readonly unimplemented: ReadonlyMap< string, @@ -1026,6 +1033,7 @@ export const make = Effect.gen(function* () { cursorKey: key, project, api: withRateLimitBackoff(api, host, rateLimits), + kind, repository, host, remote: @@ -1037,7 +1045,7 @@ export const make = Effect.gen(function* () { : sourceControlDefinitions.canonicalRepositoryKey(repositoryKey.toLowerCase()), }); } - return { supported, unimplemented, viewerRoots, refinedProjectIdsByHost }; + return { projects, supported, unimplemented, viewerRoots, refinedProjectIdsByHost }; }), ); @@ -1087,7 +1095,7 @@ export const make = Effect.gen(function* () { return Effect.gen(function* () { const publicHost = sourceControlDefinitions.findByPublicHost(host); const api = publicHost === undefined ? null : registry.get(publicHost.kind); - if (api?.readsPublicHostWithoutCheckout) { + if (publicHost !== undefined && api?.readsPublicHostWithoutCheckout) { const selected = yield* projects.getShell(ref.projectId).pipe( Effect.mapError( (cause) => @@ -1103,6 +1111,7 @@ export const make = Effect.gen(function* () { cursorKey: listCursorKey(host, repository), project: selected.value, api: withRateLimitBackoff(api, host, rateLimits), + kind: publicHost.kind, repository, host, remote: sourceControlDefinitions.repositoryKeyFromRemote( @@ -1166,6 +1175,18 @@ export const make = Effect.gen(function* () { Effect.orElseSucceed(() => true), ); + const addressedProject: PullRequestService["Service"]["addressedProject"] = (projectId) => + listWorkspaceProjects({ projectId }).pipe( + Effect.map(({ projects, supported }) => { + const own = supported[0]; + if (own === undefined) return projects.find((project) => project.id === projectId); + const identity = own.project.repositoryIdentity; + return identity == null || identity.provider === own.kind + ? own.project + : { ...own.project, repositoryIdentity: { ...identity, provider: own.kind } }; + }), + ); + const changes: PullRequestService["Service"]["changes"] = (input) => Stream.unwrap( requireProject(input).pipe( @@ -3972,8 +3993,16 @@ export const make = Effect.gen(function* () { )(function* (input) { const ref = yield* canonicalRef(input); yield* readCache.invalidate(refScope(ref)); + // A refusal (e.g. a merge conflict) means readers hold stale state, so refresh them too. const { repository, summary } = yield* runAction(input).pipe( Effect.ensuring(readCache.invalidate(refScope(ref))), + Effect.tapError(() => + Effect.suspend(() => { + bumpRefEpoch(ref); + listingsEpoch = ++epochCounter; + return SubscriptionRef.set(pullRequestRefreshes, listingsEpoch); + }), + ), ); bumpRefEpoch({ ...ref, repository }); listingsEpoch = ++epochCounter; @@ -4160,6 +4189,7 @@ export const make = Effect.gen(function* () { activity: credentialCached(activity), changes, servesProject, + addressedProject, preview: credentialCached(preview), threadComments, diff: credentialCached(diff), diff --git a/apps/server/src/pullRequest/PullRequestWatchService.test.ts b/apps/server/src/pullRequest/PullRequestWatchService.test.ts index 8982e795e261..2a02bd796795 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.test.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.test.ts @@ -14,7 +14,6 @@ import { describe, expect, it } from "@effect/vitest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; @@ -22,7 +21,6 @@ import { type PullRequestTestThread, v2PullRequestThread, } from "../orchestration-v2/testkit/pullRequestFixtures.ts"; -import * as ProjectService from "../project/ProjectService.ts"; import * as PullRequestService from "./PullRequestService.ts"; import * as PullRequestWatchService from "./PullRequestWatchService.ts"; import type { PullRequestTarget } from "./pullRequestTarget.ts"; @@ -124,9 +122,6 @@ const makeHarness = Effect.fn("makePullRequestWatchHarness")(function* ( const thread = options.thread === undefined ? makeThread([]) : options.thread; const project = options.project === undefined ? makeProject() : options.project; const dependencies = Layer.mergeAll( - Layer.mock(ProjectService.ProjectService)({ - getShell: () => Effect.succeed(Option.fromNullishOr(project)), - }), Layer.mock(Orchestrator.OrchestratorV2)({ getThreadShell: (id) => Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null), @@ -136,6 +131,7 @@ const makeHarness = Effect.fn("makePullRequestWatchHarness")(function* ( ), }), Layer.mock(PullRequestService.PullRequestService)({ + addressedProject: () => Effect.succeed(project ?? undefined), summary: (input) => options.readFailure !== undefined ? Effect.fail(options.readFailure) diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts index 32f51f540bf9..878892d343d5 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -11,11 +11,9 @@ import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; -import * as ProjectService from "../project/ProjectService.ts"; import * as PullRequestService from "./PullRequestService.ts"; import { resolveTarget, @@ -83,7 +81,6 @@ export class PullRequestWatchService extends Context.Service< const make = Effect.gen(function* () { const engine = yield* Orchestrator.OrchestratorV2; - const projects = yield* ProjectService.ProjectService; const pullRequests = yield* PullRequestService.PullRequestService; const random = yield* SecureRandom.SecureRandom; @@ -108,10 +105,9 @@ const make = Effect.gen(function* () { }) { const { watching } = input; const thread = yield* requireThread(input.threadId); - const project = yield* projects.getShell(thread.projectId).pipe( - Effect.map(Option.getOrUndefined), - Effect.mapError((cause) => new PullRequestWatchFailedError({ cause })), - ); + const project = yield* pullRequests + .addressedProject(thread.projectId) + .pipe(Effect.mapError((cause) => new PullRequestWatchFailedError({ cause }))); const target = yield* resolveTarget(input.target, project); const watchedLink = (shell: OrchestrationV2ThreadShell) => threadPullRequestsOf(shell).find( diff --git a/apps/server/src/pullRequest/pullRequestTarget.ts b/apps/server/src/pullRequest/pullRequestTarget.ts index 4520b0523a36..45312f830463 100644 --- a/apps/server/src/pullRequest/pullRequestTarget.ts +++ b/apps/server/src/pullRequest/pullRequestTarget.ts @@ -5,6 +5,7 @@ import * as Schema from "effect/Schema"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import { normalizeThreadPullRequestKey } from "../sourceControl/threadPullRequests.ts"; +import { pullRequestSyncKey } from "./pullRequestSyncKey.ts"; export interface PullRequestTarget { readonly url?: string | undefined; @@ -49,11 +50,21 @@ export class PullRequestUrlUnavailableError extends Schema.TaggedError()( + "PullRequestRepositoryInvalidError", + {}, +) { + override get message(): string { + return "Pass repository as owner/repo, without the host."; + } +} + export type PullRequestTargetError = | PullRequestUrlInvalidError | PullRequestTargetIncompleteError | PullRequestHostRequiredError - | PullRequestUrlUnavailableError; + | PullRequestUrlUnavailableError + | PullRequestRepositoryInvalidError; export interface ResolvedTarget { readonly host: string; @@ -92,29 +103,45 @@ export const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(func if (input.repository === undefined || input.number === undefined) { return yield* new PullRequestTargetIncompleteError({}); } + // Azure DevOps tools name the project's repository by its bare name, which no URL can be built + // from, so it is read as the project's full repository path. + const own = + project?.repositoryIdentity == null || input.repository.includes("/") + ? null + : pullRequestSyncKey( + { + projectId: project.id, + host: input.host, + repository: input.repository, + number: input.number, + }, + project.repositoryIdentity, + ); const projectHost = projectHostAndProvider(project); - const host = (input.host ?? projectHost.host)?.toLowerCase(); + const host = (own?.host ?? input.host ?? projectHost.host)?.toLowerCase(); if (host === undefined) { return yield* new PullRequestHostRequiredError({}); } - const repository = input.repository.toLowerCase(); + const repository = (own?.repository ?? input.repository).toLowerCase(); // Without a URL, a public forge host says what shape its change request URLs take; // any other host is taken to run the project's own forge. const recognizedKind = sourceControlDefinitions.recognizeRemote(`https://${host}`)?.kind; const kind = sourceControlDefinitions.findByPublicHost(host)?.kind ?? (recognizedKind === "gitcafe" ? recognizedKind : projectHost.kind); + const definition = kind === null ? null : sourceControlDefinitions.get(kind); const url = - kind === null - ? null - : sourceControlDefinitions.get(kind).changeRequestUrl({ - host, - repository, - number: input.number, - remoteUrl: project?.repositoryIdentity?.locator.remoteUrl, - }); + definition?.changeRequestUrl({ + host, + repository, + number: input.number, + remoteUrl: project?.repositoryIdentity?.locator.remoteUrl, + }) ?? null; if (url === null) { - return yield* new PullRequestUrlUnavailableError({}); + // A known forge returns no URL when the repository is not in its shape. + return yield* definition === null || definition.kind === "unknown" + ? new PullRequestUrlUnavailableError({}) + : new PullRequestRepositoryInvalidError({}); } return { ...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }), diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index c7259b4bd84f..86df5b092ac8 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -553,7 +553,7 @@ setInterval(() => {}, 1_000); ); yield* fs.writeFileString( path.join(bin, "systemctl"), - `#!/bin/sh\necho reload >> '${path.join(root, "reloads")}'\n`, + `#!/bin/sh\n[ "$*" = "--user daemon-reload" ] && echo reload >> '${path.join(root, "reloads")}'\n`, ); yield* fs.chmod(path.join(bin, "busctl"), 0o755); yield* fs.chmod(path.join(bin, "systemctl"), 0o755); @@ -896,6 +896,51 @@ process.exit(0); }), ); + it.effect("repoints a unit that names this T3 home through a symlink", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-alias-" }); + const alias = path.join(root, "alias"); + yield* fs.symlink(root, alias); + const statePath = path.join(root, "runtime", "service-state.json"); + yield* writeFakeRuntime( + fs, + path, + path.join(root, "runtime", "versions", "1.1.0"), + "setInterval(() => {}, 1_000);\n", + ); + yield* Effect.promise(() => + writeServiceState(statePath, { + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.1.0", + update: { + id: "update-1", + fromVersion: "1.0.0", + targetVersion: "1.1.0", + status: "committed", + }, + }), + ); + const unit = yield* fakeServiceUnit(fs, path, alias, "1.0.0"); + const launcher = new Launcher( + root, + yield* Effect.promise(() => readServiceState(statePath)), + { + serviceUnit: unit, + }, + ); + const running = launcher.run(); + yield* Effect.promise(() => launcher.stop("SIGTERM")); + yield* Effect.promise(() => running); + + assert.equal( + yield* fs.readFileString(unit.path), + renderBootServiceUnit(unitPlan(alias, "1.1.0")), + ); + }), + ); + it.effect("waits without exiting and restarts once the other owner releases the T3 home", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 8dcd7886fce5..44220f2c4b14 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -8,6 +8,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import * as NodeUtil from "node:util"; import { acquireServiceSelectionLock } from "./cloud/serviceSelectionLock.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./cloud/userManagerOom.ts"; import { isNoCopyOnWrite, markNoCopyOnWrite } from "./noCopyOnWrite.ts"; import type { @@ -224,8 +225,8 @@ async function serviceUnitFromEnvironment( ); return { path: NodePath.join(unitDir, unitName), - reload: () => - new Promise((resolve, reject) => { + reload: async () => { + await new Promise((resolve, reject) => { NodeChildProcess.spawn("systemctl", ["--user", "daemon-reload"], { stdio: "ignore", timeout: 30_000, @@ -236,7 +237,16 @@ async function serviceUnitFromEnvironment( ? resolve() : reject(new Error(`systemctl --user daemon-reload exited with ${code ?? signal}`)), ); - }), + }); + await new Promise((resolve) => { + NodeChildProcess.spawn("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + stdio: "ignore", + timeout: 30_000, + }) + .once("error", () => resolve()) + .once("exit", () => resolve()); + }); + }, }; } @@ -1406,9 +1416,10 @@ export class Launcher { } const contents = decodeServiceUnit(await NodeFSP.readFile(unit.path)); const installedBaseDir = serviceUnitBaseDirOf(contents); + const real = (dir: string) => NodeFSP.realpath(dir).catch(() => NodePath.resolve(dir)); if ( installedBaseDir === undefined || - NodePath.resolve(installedBaseDir) !== NodePath.resolve(this.#baseDir) + (await real(installedBaseDir)) !== (await real(this.#baseDir)) ) { return; } diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 43f4b89d5f04..e214450714f9 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -1147,14 +1147,39 @@ it.live("removes a task folder's clean worktrees and keeps the one with uncommit expect((yield* taskFolders.find(root))?.repositories).toHaveLength(2); yield* command(`${root}/dist/api`, ["checkout", "--", "tracked.txt"]); + // Git deletes the checkout, then fails on metadata it cannot delete. + const adminDir = (yield* command(`${root}/dist/api`, [ + "rev-parse", + "--absolute-git-dir", + ])).stdout.trim(); + const stuck = `${adminDir}/scratch`; + yield* fs.makeDirectory(stuck); + yield* fs.writeFileString(`${stuck}/f`, "x\n"); + yield* fs.chmod(stuck, 0o555); + yield* Effect.addFinalizer(() => fs.chmod(stuck, 0o755).pipe(Effect.ignore)); const second = yield* service.runNow; expect(second.entries.filter((entry) => entry.path?.startsWith(root))).toEqual( [`${root}/dist/api`, root].map((path) => - expect.objectContaining({ path, outcome: "removed" }), + expect.objectContaining({ path, outcome: "kept" }), ), ); + expect(yield* fs.exists(`${root}/dist/api`)).toBe(false); + // The checkout is gone, so the folder goes and only the record keeps the metadata in view. + expect( + (yield* service.runNow).entries.filter((entry) => entry.path?.startsWith(root)), + ).toEqual( + [ + { path: `${root}/dist/api`, outcome: "failed" }, + { path: root, outcome: "removed" }, + ].map((entry) => expect.objectContaining(entry)), + ); expect(yield* fs.exists(root)).toBe(false); + yield* fs.chmod(stuck, 0o755); + expect((yield* service.runNow).entries).toEqual([ + expect.objectContaining({ path: `${root}/dist/api`, outcome: "removed" }), + ]); + expect(yield* fs.exists(adminDir)).toBe(false); expect(yield* fs.readFileString(`${api.path}/tracked.txt`)).toBe("original\n"); }), ), @@ -3040,6 +3065,79 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live("keeps reporting a worktree whose git metadata cannot be deleted", () => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* cleanupFixture(); + const adminDir = (yield* fixture.command(fixture.worktree, [ + "rev-parse", + "--absolute-git-dir", + ])).stdout.trim(); + // Stands in for root-owned files a container wrote into the worktree's git dir. + const stuck = `${adminDir}/scratch/fanal`; + yield* fixture.fs.makeDirectory(stuck, { recursive: true }); + yield* fixture.fs.writeFileString(`${stuck}/f`, "x\n"); + yield* fixture.fs.chmod(stuck, 0o555); + yield* Effect.addFinalizer(() => fixture.fs.chmod(stuck, 0o755).pipe(Effect.ignore)); + yield* fixture.service.runNow; + // Git may delete these before it reaches the folder it cannot, and then stops listing + // the worktree. + yield* fixture.fs.remove(`${adminDir}/gitdir`, { force: true }); + yield* fixture.fs.remove(`${adminDir}/HEAD`, { force: true }); + const later = yield* fixture.service.runNow; + expect(later.entries).toEqual([ + expect.objectContaining({ + path: fixture.worktree, + outcome: expect.stringMatching(/^(kept|failed)$/), + }), + ]); + expect((yield* fixture.service.runNow).entries).toEqual(later.entries); + expect(yield* fixture.fs.exists(stuck)).toBe(true); + yield* fixture.fs.chmod(stuck, 0o755); + expect((yield* fixture.service.runNow).entries).toEqual([ + expect.objectContaining({ path: fixture.worktree, outcome: "removed" }), + ]); + expect(yield* fixture.fs.exists(adminDir)).toBe(false); + expect((yield* fixture.service.runNow).entries).toEqual([]); + // An unreadable record may still name leftovers, so it is reported and kept as it is. + const record = `${fixture.config.stateDir}/storage-cleanup-leftovers.json`; + yield* fixture.fs.writeFileString(record, "{"); + expect((yield* fixture.service.runNow).entries).toEqual([ + expect.objectContaining({ path: record, outcome: "failed" }), + ]); + expect(yield* fixture.fs.readFileString(record)).toBe("{"); + }), + ), + ); + it.live("leaves git metadata that a recreated worktree took over from a failed removal", () => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* cleanupFixture(); + const adminDir = (yield* fixture.command(fixture.worktree, [ + "rev-parse", + "--absolute-git-dir", + ])).stdout.trim(); + const stuck = `${adminDir}/scratch`; + yield* fixture.fs.makeDirectory(stuck); + yield* fixture.fs.writeFileString(`${stuck}/f`, "x\n"); + yield* fixture.fs.chmod(stuck, 0o555); + yield* Effect.addFinalizer(() => fixture.fs.chmod(stuck, 0o755).pipe(Effect.ignore)); + yield* fixture.service.runNow; + // The user repairs and prunes the leftover, then the thread resumes under the same name. + yield* fixture.fs.chmod(stuck, 0o755); + yield* fixture.command(fixture.repo, ["worktree", "prune"]); + yield* fixture.command(fixture.repo, ["worktree", "add", fixture.worktree, "feature"]); + // Only the cleanup rules remove it now: its metadata is no longer a leftover. + expect((yield* fixture.service.runNow).entries).toEqual([ + expect.objectContaining({ + path: fixture.worktree, + outcome: "removed", + reason: expect.stringMatching(/^Inactive for/), + }), + ]); + }), + ), + ); it.live("skips a stored worktree path whose parent is a regular file", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index 0908e2e546eb..fbee1de40906 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -5,6 +5,7 @@ import { GitCommandError, OrchestrationV2AppThreadJson, OrchestrationV2ProviderSessionJson, + StorageCleanupReportEntry, parseWorktreeCleanupIgnoredNames, TextGenerationError, WORKTREE_CLEANUP_IGNORED_NAME_MAX_COUNT, @@ -21,9 +22,9 @@ import type { TerminalSummary, WorktreeCleanupRules, StorageCleanupReport, - StorageCleanupReportEntry, ThreadId, } from "@t3tools/contracts"; +import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings"; import { resolveWorktreeT3Home } from "@t3tools/shared/devHome"; import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; @@ -81,6 +82,11 @@ const decodeCleanupThread = Schema.decodeUnknownEffect( const decodeCleanupSession = Schema.decodeUnknownEffect( Schema.fromJsonString(OrchestrationV2ProviderSessionJson), ); +const decodeWorktreeLeftovers = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Array(Schema.Struct({ adminDir: Schema.String, entry: StorageCleanupReportEntry })), + ), +); // pnpm 11 writes this file as JSON, older versions as YAML. const decodePnpmModulesManifest = Schema.decodeUnknownEffect( Schema.Struct({ @@ -1381,6 +1387,103 @@ const make = Effect.gen(function* () { }); }); + // Git deletes a checkout before its metadata under `/.git/worktrees`. When the + // metadata then cannot be deleted, no checkout is left for a sweep to find and Git may no longer + // list the worktree, so the leftover is written down here and retried until it is gone. + const leftoversPath = path.join(config.stateDir, "storage-cleanup-leftovers.json"); + // Only a missing file is empty: an unreadable one may hold records a write would replace. + const readLeftovers = fs.readFileString(leftoversPath).pipe( + Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed("[]")), + Effect.flatMap(decodeWorktreeLeftovers), + ); + const writeLeftovers = ( + leftovers: ReadonlyArray<{ + readonly adminDir: string; + readonly entry: StorageCleanupReportEntry; + }>, + ) => + leftovers.length === 0 + ? fs.remove(leftoversPath, { force: true }) + : writeFileStringAtomically({ + filePath: leftoversPath, + contents: `${JSON.stringify(leftovers, null, 2)}\n`, + }); + const worktreeAdminDir = Effect.fn("StorageCleanup.worktreeAdminDir")(function* ( + worktreePath: string, + ) { + const gitDir = yield* git.execute({ + operation: "StorageCleanup.worktreeAdminDir", + cwd: worktreePath, + args: ["rev-parse", "--absolute-git-dir"], + }); + return gitDir.stdout.trim(); + }); + const noteLeftover = Effect.fn("StorageCleanup.noteLeftover")( + function* (adminDir: string, entry: StorageCleanupReportEntry) { + if (entry.path === null || path.basename(path.dirname(adminDir)) !== "worktrees") return; + // A removal Git refused keeps its checkout, and the next sweep looks at it again. + if (yield* fs.exists(entry.path).pipe(Effect.orElseSucceed(() => true))) return; + if (!(yield* fs.exists(adminDir).pipe(Effect.orElseSucceed(() => true)))) return; + const others = (yield* readLeftovers).filter((leftover) => leftover.adminDir !== adminDir); + yield* writeLeftovers([...others, { adminDir, entry }]); + }, + Effect.catch((error) => + Effect.logWarning("storage cleanup could not record leftover git metadata", { error }), + ), + ); + const removeLeftover = Effect.fn("StorageCleanup.removeLeftover")(function* (adminDir: string) { + // Pruning by hand frees the name, and a worktree recreated since may have taken it. + const gitFile = yield* fs.readFileString(path.join(adminDir, "gitdir")).pipe( + Effect.map((gitdir) => path.resolve(adminDir, gitdir.trim())), + Effect.option, + ); + if (Option.isSome(gitFile) && (yield* fs.exists(gitFile.value))) { + const current = yield* worktreeAdminDir(path.dirname(gitFile.value)); + if ((yield* fs.realPath(current)) === (yield* fs.realPath(adminDir))) return false; + } + yield* fs.remove(adminDir, { recursive: true }); + return true; + }); + const retryLeftovers = Effect.fn("StorageCleanup.retryLeftovers")(function* ( + entries: StorageCleanupReportEntry[], + ) { + const leftovers = yield* readLeftovers; + const remaining: Array<(typeof leftovers)[number]> = []; + for (const leftover of leftovers) { + const { adminDir, entry } = leftover; + if (!(yield* fs.exists(adminDir).pipe(Effect.orElseSucceed(() => true)))) continue; + const failure = yield* removeLeftover(adminDir).pipe( + Effect.map((removed) => { + if (removed) + entries.push({ + ...entry, + outcome: "removed", + reason: "Deleted git metadata an earlier cleanup left behind", + }); + return null; + }), + Effect.catch((error) => Effect.succeed(error)), + ); + if (failure === null) continue; + remaining.push(leftover); + entries.push({ + ...entry, + outcome: "failed", + reason: `Git metadata at ${adminDir} could not be deleted: ${cleanupFailureReason(failure)}`, + }); + yield* Effect.logWarning("storage cleanup failed for leftover git metadata", { + threadId: entry.threadId, + error: failure, + }); + } + if (remaining.length !== leftovers.length) + yield* writeLeftovers(remaining).pipe( + Effect.catch((error) => + Effect.logWarning("storage cleanup could not update leftover git metadata", { error }), + ), + ); + }); + const cleanWorktrees = Effect.fn("StorageCleanup.cleanWorktrees")(function* ( serverSettings: ServerSettings, now: number, @@ -1843,18 +1946,24 @@ const make = Effect.gen(function* () { if (blockedSinceLease !== null) return keep(blockedSinceLease); if (yield* settingsChangedSinceCheck) return keep("settings changed since check"); const checkoutBytes = new Map(); + const adminDirs = new Map(); // Each checkout passes the checks a single worktree does, or it stays. const result = yield* taskFolders.remove({ root: taskFolder.root, force: false, forget: deleted, inspect: (checkout) => - inspectCheckout( - checkout.worktreePath, - thread.branch, - settings, - settingsChangedSinceCheck, - ).pipe( + worktreeAdminDir(checkout.worktreePath).pipe( + Effect.map((adminDir) => adminDirs.set(checkout.worktreePath, adminDir)), + Effect.ignore, + Effect.andThen( + inspectCheckout( + checkout.worktreePath, + thread.branch, + settings, + settingsChangedSinceCheck, + ), + ), Effect.tap(({ bytes }) => Effect.sync(() => checkoutBytes.set(checkout.worktreePath, bytes)), ), @@ -1870,12 +1979,16 @@ const make = Effect.gen(function* () { reason: sentence(removalReason), bytes: checkoutBytes.get(removedPath) ?? null, }); - for (const keptCheckout of result.kept) + for (const keptCheckout of result.kept) { entries.push({ ...entry, path: keptCheckout.path, reason: sentence(keptCheckout.reason), }); + const adminDir = adminDirs.get(keptCheckout.path); + if (adminDir !== undefined) + yield* noteLeftover(adminDir, { ...entry, path: keptCheckout.path }); + } if (result.kept.length > 0 && deleted && settings.worktreeOnDelete) kept.push(worktreePath); yield* gitManager.invalidateStatus(project.workspaceRoot); @@ -2057,6 +2170,7 @@ const make = Effect.gen(function* () { // Forced removal already discards local files; do not widen its final-check window. if (settings.worktreeKeepWhen === "tracked-changes" && !submodules.force) yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean"); + const adminDir = yield* worktreeAdminDir(worktreePath); yield* removeLinkedWorktree({ operation: "StorageCleanup.cleanupGit", cwd: repository, @@ -2065,7 +2179,7 @@ const make = Effect.gen(function* () { force: submodules.force, execute: git.execute, run: (args) => cleanupGit(repository, [...args], "git worktree remove"), - }); + }).pipe(Effect.tapError(() => noteLeftover(adminDir, entry))); entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes }); yield* gitManager.invalidateStatus(project.workspaceRoot); // Preserve branch/path so ProviderTurnStartService can recreate the checkout on resume. @@ -2266,6 +2380,26 @@ const make = Effect.gen(function* () { yield* cleanCheckpointRefs().pipe( Effect.catch((cause) => Effect.logWarning("checkpoint ref cleanup failed", { cause })), ); + yield* retryLeftovers(entries).pipe( + Effect.catch((error) => + Effect.gen(function* () { + entries.push({ + kind: "worktree", + outcome: "failed", + reason: `Could not read the record of leftover git metadata: ${cleanupFailureReason(error)}`, + path: leftoversPath, + projectPath: null, + threadId: null, + threadTitle: null, + bytes: null, + files: null, + }); + yield* Effect.logWarning("storage cleanup could not read leftover git metadata", { + error, + }); + }), + ), + ); const deletedWorktrees = yield* cleanWorktrees(serverSettings, now, entries, trigger).pipe( Effect.catch((error) => Effect.gen(function* () { diff --git a/apps/server/src/telemetry/ProviderDimensions.test.ts b/apps/server/src/telemetry/ProviderDimensions.test.ts index 3959d7dc78e4..e24bb480d1e2 100644 --- a/apps/server/src/telemetry/ProviderDimensions.test.ts +++ b/apps/server/src/telemetry/ProviderDimensions.test.ts @@ -7,20 +7,15 @@ const provider = ( instanceId: string, driver: string, models: ReadonlyArray<{ slug: string; isCustom: boolean }>, - auth: Record = {}, ) => ({ instanceId: ProviderInstanceId.make(instanceId), driver, - auth: { status: "authenticated", ...auth }, models, }) as unknown as ServerProvider; const providers = [ provider("work-codex", "codex", [{ slug: "gpt-5.5", isCustom: false }]), - provider("azure-codex", "codex", [{ slug: "gpt-acme-finetune", isCustom: false }], { - endpoint: "https://acme.example.com", - }), provider("claudeAgent", "claudeAgent", [ { slug: "claude-opus-5-5", isCustom: false }, { slug: "my-private-finetune", isCustom: true }, @@ -42,17 +37,13 @@ const thread = ( ...overrides, }); -it("omits custom, user-configured, endpoint-served, and unknown models and instance names", () => { +it("reports every model name but never instance names", () => { expect( agentToolProperties({ tool: "t3_thread_send", providers, caller: thread("claudeAgent", "my-private-finetune"), - targets: [ - thread("opencode", "ollama/acme-internal"), - thread("removed-instance", "gpt-5.5"), - thread("azure-codex", "gpt-acme-finetune"), - ], + targets: [thread("opencode", "ollama/acme-internal"), thread("removed-instance", "gpt-5.5")], outcome: { outcome: "ok" }, }).map(({ callerProvider, callerModel, targetProvider, targetModel }) => ({ callerProvider, @@ -63,22 +54,16 @@ it("omits custom, user-configured, endpoint-served, and unknown models and insta ).toEqual([ { callerProvider: "claudeAgent", - callerModel: undefined, + callerModel: "my-private-finetune", targetProvider: "opencode", - targetModel: undefined, + targetModel: "ollama/acme-internal", }, { callerProvider: "claudeAgent", - callerModel: undefined, + callerModel: "my-private-finetune", targetProvider: "unknown", targetModel: undefined, }, - { - callerProvider: "claudeAgent", - callerModel: undefined, - targetProvider: "codex", - targetModel: undefined, - }, ]); }); diff --git a/apps/server/src/telemetry/ProviderDimensions.ts b/apps/server/src/telemetry/ProviderDimensions.ts index 497f1e660131..7aa44cd46727 100644 --- a/apps/server/src/telemetry/ProviderDimensions.ts +++ b/apps/server/src/telemetry/ProviderDimensions.ts @@ -13,8 +13,7 @@ export interface ProviderDimensions { /** * Anonymous provider and model for a model selection. Instance ids are - * user-defined, so only the driver kind is reported. The model is reported - * only when the selected instance's vendor catalog lists it. + * user-defined, so only the driver kind is reported. */ export function providerDimensions( providers: ReadonlyArray, @@ -22,15 +21,16 @@ export function providerDimensions( ): ProviderDimensions { const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId); if (provider === undefined) return { provider: "unknown" }; - const model = vendorCatalogEntry(provider, [selection.model]); - return model === undefined - ? { provider: provider.driver } - : { provider: provider.driver, model: model.slug }; + return { provider: provider.driver, model: modelLabel(providers, selection.model) }; } const DATED_SNAPSHOT = /-\d{8}$/u; +// Absolute, home, relative, or Windows paths, such as a local GGUF file. Directories can name the user. +const FILE_PATH = /^(?:[/~]|\.{1,2}[/\\]|[A-Za-z]:[\\/])|\\/u; + +const fileName = (model: string) => + FILE_PATH.test(model) ? model.slice(model.search(/[^/\\]*$/u)) : model; -// The bundled manifest is reviewed in this repo. Vendor catalogs ship models before it does. const MANIFEST_LABELS: ReadonlyMap = new Map( Object.values(BUNDLED_MODEL_MANIFEST.providers ?? {}).flatMap((catalog) => catalog.models.flatMap((model) => @@ -39,43 +39,17 @@ const MANIFEST_LABELS: ReadonlyMap = new Map( ), ); -// Drivers whose model lists come from the vendor. OpenCode, Pi, and ACP agents list the -// user's own configuration, such as local Ollama tags. Codex and Claude also list -// early-access code names, so only slugs in the vendor's public family vouch for them. -const VENDOR_CATALOGS: ReadonlyMap = new Map([ - ["cursor", undefined], - ["grok", undefined], - ["antigravity", undefined], - ["codex", /^gpt-/u], - ["claudeAgent", /^claude-/u], -]); - -// A custom endpoint or gateway serves whatever names its owner chose. -const isVendorRouted = (auth: ServerProvider["auth"]) => - auth.endpoint === undefined && auth.type !== "customEndpoint" && auth.type !== "bedrock"; - -function vendorCatalogEntry(provider: ServerProvider, candidates: ReadonlyArray) { - if (!VENDOR_CATALOGS.has(provider.driver) || !isVendorRouted(provider.auth)) return undefined; - const family = VENDOR_CATALOGS.get(provider.driver); - return provider.models.find( - (entry) => - !entry.isCustom && - (family === undefined || family.test(entry.slug)) && - (candidates.includes(entry.slug) || - entry.aliases?.some((alias) => candidates.includes(alias)) === true), - ); -} - /** - * The vendor catalog slug that a native or routed model id names, such as - * `anthropic/claude-opus-5-5` or a dated snapshot. Models outside the bundled - * manifest and vendor-routed provider catalogs, including user-added ones and - * names a custom endpoint serves, return undefined. + * The model name analytics reports. A routed id, alias, or dated snapshot that the + * bundled manifest or a provider's model list knows, such as `anthropic/claude-opus-5-5` + * or `antigravity-default`, maps to its catalog slug. A file path reports only its file + * name. Any other id is reported as is. */ -export function catalogModelLabel( - providers: ReadonlyArray, - model: string, -): string | undefined { +export function modelLabel(providers: ReadonlyArray, model: string): string { + return fileName(catalogSlug(providers, model) ?? model); +} + +function catalogSlug(providers: ReadonlyArray, model: string) { const leaf = model.slice(model.lastIndexOf("/") + 1); const candidates = [model, leaf, leaf.replace(DATED_SNAPSHOT, "")]; for (const candidate of candidates) { @@ -83,7 +57,11 @@ export function catalogModelLabel( if (label !== undefined) return label; } for (const provider of providers) { - const match = vendorCatalogEntry(provider, candidates); + const match = provider.models.find( + (entry) => + candidates.includes(entry.slug) || + entry.aliases?.some((alias) => candidates.includes(alias)) === true, + ); if (match !== undefined) return match.slug; } return undefined; diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts index 0ce417e9a2c8..14e4a8b68633 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts @@ -15,7 +15,7 @@ import * as Layer from "effect/Layer"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as AnalyticsService from "./AnalyticsService.ts"; -import { catalogModelLabel } from "./ProviderDimensions.ts"; +import { modelLabel } from "./ProviderDimensions.ts"; import { ProviderTurnAnalytics, RequestUsageLedger, @@ -26,29 +26,9 @@ import { } from "./ProviderUsageAnalytics.ts"; const providers = [ - // Vendor-routed Codex lists OpenAI's catalog, including early-access code names. - { - driver: "codex", - models: [{ slug: "gpt-6-sol" }, { slug: "gpt-6.2-sol" }, { slug: "nova-alpha" }], - }, - // A custom endpoint serves whatever its owner chose, including private deployments. - { - instanceId: "azure-codex", - driver: "codex", - auth: { endpoint: "https://acme.example.com" }, - models: [{ slug: "acme-azure-deployment" }, { slug: "gpt-acme-finetune" }], - }, - { - driver: "claudeAgent", - models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }, { slug: "claude-opus-6" }], - }, - { - instanceId: "claude-gateway", - driver: "claudeAgent", - auth: { type: "customEndpoint" }, - models: [{ slug: "claude-ops-internal" }], - }, - { driver: "opencode", models: [{ slug: "ollama/acme-internal" }] }, + { driver: "codex", models: [{ slug: "gpt-6-sol" }] }, + { driver: "pi", models: [{ slug: "/Users/jane/models/llama.gguf", aliases: ["pi-local"] }] }, + { driver: "claudeAgent", models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }] }, // Antigravity ships models before the bundled manifest lists them. { driver: "antigravity", @@ -58,25 +38,14 @@ const providers = [ ], }, ].map( - ({ - instanceId, - driver, - auth, - models, - }: { - instanceId?: string; - driver: string; - auth?: Record; - models: ReadonlyArray<{ slug: string; aliases?: ReadonlyArray }>; - }) => + ({ driver, models }) => ({ - instanceId: ProviderInstanceId.make(instanceId ?? driver), + instanceId: ProviderInstanceId.make(driver), driver, - auth: { status: "authenticated", ...auth }, models: models.map((model) => ({ ...model, isCustom: false })), }) as unknown as ServerProvider, ); -const label = (model: string) => catalogModelLabel(providers, model); +const label = (model: string) => modelLabel(providers, model); const at = (ms: number) => DateTime.makeUnsafe(ms); const complete = (input: number, output: number, extra: Partial = {}) => @@ -335,7 +304,7 @@ describe("provider usage reporting", () => { }); }); - it("reports routed catalog models and closed efforts only", () => { + it("reports every model name and closed efforts only", () => { const routed = (model: string, variant: string) => providerTurnProperties( { @@ -356,30 +325,22 @@ describe("provider usage reporting", () => { observedModel: "claude-opus-5-5", effort: "high", }); - for (const local of [ - routed("ollama/acme-internal", "secret-variant"), - routed("acme-azure-deployment", "high"), - ]) { - expect(local).not.toHaveProperty("model"); - expect(local).not.toHaveProperty("observedModel"); - } - expect(routed("ollama/acme-internal", "secret-variant")).not.toHaveProperty("effort"); + const local = routed("ollama/acme-internal", "secret-variant"); + expect(local).toMatchObject({ + model: "ollama/acme-internal", + observedModel: "ollama/acme-internal", + }); + expect(local).not.toHaveProperty("effort"); }); - it("reports vendor catalog models the bundled manifest does not list", () => { + it("maps provider catalog aliases to their slug and file paths to their file name", () => { expect(label("gemini-4-hydrogen")).toBe("gemini-4-hydrogen"); expect(label("antigravity-default")).toBe("gemini-4-neon"); - expect(label("gemini-4-unlisted")).toBeUndefined(); - expect(label("gpt-6.2-sol")).toBe("gpt-6.2-sol"); - expect(label("claude-opus-6")).toBe("claude-opus-6"); - for (const hidden of [ - "nova-alpha", - "acme-azure-deployment", - "gpt-acme-finetune", - "claude-ops-internal", - ]) { - expect(label(hidden)).toBeUndefined(); - } + expect(label("/Users/jane/models/qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("~/models/qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("C:\\Users\\jane\\qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("../jane/qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("pi-local")).toBe("llama.gguf"); }); it("reports closed service tiers from a tier option or a fast mode toggle", () => { diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.ts index ce7f29ba1f8d..a281f40479b5 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.ts @@ -26,7 +26,7 @@ import { } from "@t3tools/shared/model"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as AnalyticsService from "./AnalyticsService.ts"; -import { catalogModelLabel } from "./ProviderDimensions.ts"; +import { modelLabel } from "./ProviderDimensions.ts"; // Bump when a field changes meaning, so reports can split old and new rows. const REPORT_VERSION = 2; @@ -74,8 +74,8 @@ export interface RunSettledReport { } type Properties = Readonly>; -/** Maps a native model id to a vendor catalog label, or undefined to keep it out. */ -export type ModelLabeler = (model: string) => string | undefined; +/** Maps a native model id to the name analytics reports. */ +export type ModelLabeler = (model: string) => string; const TERMINAL_STATUSES: ReadonlySet = new Set([ "completed", @@ -403,7 +403,7 @@ export const layer = Layer.effect( registry.getProviders, (providers): ModelLabeler => (model) => - catalogModelLabel(providers, model), + modelLabel(providers, model), ); return { runStarted: Effect.fn("ProviderTurnAnalytics.runStarted")((input) => diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index def3820c8a01..9c53c87986bd 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -3,6 +3,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { + DEFAULT_MAX_TERMINAL_BUFFER_BYTES, DEFAULT_SERVER_SETTINGS, DEFAULT_TERMINAL_ID, ProjectId, @@ -495,6 +496,98 @@ it("restores bounded history across append compaction, clears and split Unicode" expect(persisted).toBe("z".repeat(maxBytes)); }); +it("stops holding a control sequence that outgrows its limit", () => { + const limit = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; + // No final byte for a CSI and no terminator for a string. + const filler = "0123456789 123\r\n".repeat(64); + const fed = filler.repeat(Math.ceil(limit / filler.length) + 2); + // The terminal runs the line breaks inside a CSI while it waits for the final byte. + const lineBreaks = fed.replaceAll(/[^\r\n]/g, ""); + for (const { name, open, end, history } of [ + { name: "OSC, BEL", open: ["\u001b]0;"], end: ["\u0007"], history: "\u001b\\" }, + { + name: "OSC, split ST", + open: ["\u001b]0;"], + end: ["\u001b", "\\\u001b[31m"], + history: "\u001b\\\u001b[31m", + }, + // The last UTF-8 byte of U+20805 is 0x85, NEL, which ends the DCS and replays as ESC E. + { + name: "DCS, split code point", + open: ["\u001bPstuck"], + end: ["\ud842", "\udc05"], + history: "\u001b\\\u001bE", + }, + // The dropped CSI's ESC ended the title, so history ends it too. Its final byte would have + // made it a query that the replay answers. + { + name: "CSI after a title its ESC cuts short", + open: ["\u001b]0;title", "\u001b["], + end: ["\n6n"], + history: `\u001b]0;title\u001b\\${lineBreaks}\n`, + }, + { + name: "CSI, ESC", + open: ["\u001b["], + end: ["\n\u001b[31m"], + history: `\u001b\\${lineBreaks}\n\u001b[31m`, + }, + ]) { + let held = ""; + let visible = ""; + const feed = (data: string) => { + const sanitized = TerminalManager.sanitizeTerminalHistoryChunk(held, data); + held = sanitized.pendingControlSequence; + visible += sanitized.visibleText; + }; + + feed("before\n"); + for (const data of open) feed(data); + for (let offset = 0; offset < fed.length; offset += filler.length) { + feed(fed.slice(offset, offset + filler.length)); + } + expect(held.length, name).toBeLessThanOrEqual(3); + + for (const data of end) feed(data); + feed("after\n"); + expect(held, name).toBe(""); + expect(visible, name).toBe(`before\n${history}after\n`); + } + + // Held text of exactly the limit stays held, and a sequence that ends in the chunk where it + // passes the limit is kept whole. + for (const atLimit of ["\u001b]".padEnd(limit, "0"), "\u001b[".padEnd(limit, "0")]) { + expect(TerminalManager.sanitizeTerminalHistoryChunk("", atLimit)).toEqual({ + visibleText: "", + pendingControlSequence: atLimit, + }); + const ended = `${atLimit}0${atLimit[1] === "]" ? "\u0007" : "m"}`; + expect(TerminalManager.sanitizeTerminalHistoryChunk("", ended)).toEqual({ + visibleText: ended, + pendingControlSequence: "", + }); + } + + // An escape sequence keeps its first four intermediates, the only ones libghostty reads. + const escape = '\u001b!"#$'; + expect(TerminalManager.sanitizeTerminalHistoryChunk(escape, "%&")).toEqual({ + visibleText: "", + pendingControlSequence: escape, + }); + expect(TerminalManager.sanitizeTerminalHistoryChunk(escape, "%&B")).toEqual({ + visibleText: `${escape}%&B`, + pendingControlSequence: "", + }); + + // A completed escape sequence stays when another ESC follows it at once. + for (const kept of ["OLD\u001bc\u001b[31mNEW", "abc\u001b7\u001b[2;5HB\u001b8Z"]) { + expect(TerminalManager.sanitizeTerminalHistoryChunk("", kept)).toEqual({ + visibleText: kept, + pendingControlSequence: "", + }); + } +}); + it.layer( Layer.mergeAll( NodeServices.layer, @@ -1763,6 +1856,39 @@ it.layer( }), ); + it.effect("starts a snapshot inside the sequence the terminal has not finished", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + const outputs = yield* Queue.unbounded(); + const unsubscribe = yield* manager.subscribe((event) => + event.type === "output" ? Queue.offer(outputs, undefined).pipe(Effect.asVoid) : Effect.void, + ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + const historyAfter = Effect.fnUntraced(function* (data: string) { + process.emitData(data); + yield* Queue.take(outputs); + return (yield* manager.open(openInput())).history; + }); + + expect(yield* historyAfter("A\u001b]0;ti")).toBe("A\u001b]0;ti"); + // A long string would push history out of the client's budget, so its payload is left out. + expect(yield* historyAfter("x".repeat(4_096))).toBe("A\u001b]"); + // Past the limit only the introducer is left to replay. + expect(yield* historyAfter("x".repeat(DEFAULT_MAX_TERMINAL_BUFFER_BYTES))).toBe( + "A\u001b\\\u001b]", + ); + expect(yield* historyAfter("\u0007B")).toBe("A\u001b\\B"); + + // Saved history has no live output to finish the sequence. + process.emitData("\u001b]0;open"); + yield* Queue.take(outputs); + yield* manager.close({ threadId: "thread-1" }); + expect(yield* readFileString(yield* historyLogPath(logsDir))).toBe("A\u001b\\B"); + }), + ); + it.effect("preserves large chunked OSC 52 and DCS strings across reopen", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index ff19e4b76860..82c92d0f7c42 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -427,7 +427,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { worktreePath: session.worktreePath, status: session.status, pid: session.pid, - history: session.history.value(), + history: session.history.value() + unfinishedSequenceReplay(session), exitCode: session.exitCode, exitSignal: session.exitSignal, label: terminalWireLabel(session), @@ -1406,7 +1406,32 @@ function findEscapeSequenceEndIndex(input: string, start: number): number | null const HISTORY_SEQUENCE_START = /\u001b/; const NEXT_HISTORY_SEQUENCE_START = new RegExp(HISTORY_SEQUENCE_START.source, "g"); -function sanitizeTerminalHistoryChunk( +// Clients keep this much output and drop a sequence their trim cuts through, so none of them +// could replay a longer string or CSI whole. +const MAX_HELD_SEQUENCE_LENGTH = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; +// ESC and four intermediates: libghostty ignores every intermediate past the fourth. +const MAX_HELD_ESCAPE_LENGTH = 5; +// Leads the held text of a string or CSI that outgrew its limit and stays out of history. Only its +// introducer is still held, with a final ESC or high surrogate that may begin its end. Other held +// text starts with ESC. +const OVERSIZED_SEQUENCE = "\u0018"; +// Stands in for the ESC of an oversized sequence, which ended any string history left open. +const STRING_TERMINATOR = "\u001b\\"; + +// Longer held text is cut to its introducer in a snapshot, so it cannot push history out of the +// client's budget or add its size to every resync. +const MAX_SNAPSHOT_SEQUENCE_LENGTH = 4_096; + +// History leaves out the sequence the terminal is still inside. A client that starts from a +// snapshot needs it, or it prints the rest of the sequence as text. +function unfinishedSequenceReplay(session: TerminalSessionState): string { + const held = session.pendingHistoryControlSequence; + if (held.startsWith(OVERSIZED_SEQUENCE)) return held.slice(1); + if (held.length <= MAX_SNAPSHOT_SEQUENCE_LENGTH) return held; + return held.slice(0, 2) + (/[\u001b\ud800-\udbff]$/.exec(held)?.[0] ?? ""); +} + +export function sanitizeTerminalHistoryChunk( pendingControlSequence: string, data: string, ): { visibleText: string; pendingControlSequence: string } { @@ -1414,9 +1439,12 @@ function sanitizeTerminalHistoryChunk( return { visibleText: data, pendingControlSequence: "" }; } - const input = `${pendingControlSequence}${data}`; - // Only the pending prefix's final ESC can begin a terminator split across chunks. - const pendingScanStart = Math.max(0, pendingControlSequence.length - 1); + const resumesOversized = pendingControlSequence.startsWith(OVERSIZED_SEQUENCE); + const held = resumesOversized ? pendingControlSequence.slice(1) : pendingControlSequence; + const input = `${held}${data}`; + // Only the held text's final code unit, an ESC or a high surrogate, can begin an end split + // across chunks. + const pendingScanStart = Math.max(0, held.length - 1); let visibleText = ""; let index = 0; // Set when a C1 code point began the sequence at `index`: the ESC form that stands in for it. @@ -1433,6 +1461,7 @@ function sanitizeTerminalHistoryChunk( // Empty for a sequence the input introduces itself, which starts with ESC at `index`. const prefix = c1Introducer; c1Introducer = ""; + const oversized = resumesOversized && index === 0; const contentStart = prefix.length > 0 ? index : index + 2; const nextCodePoint = (prefix || input).charCodeAt(prefix.length > 0 ? 1 : index + 1); if (Number.isNaN(nextCodePoint)) { @@ -1440,19 +1469,21 @@ function sanitizeTerminalHistoryChunk( } if (nextCodePoint === 0x5b) { - let cursor = contentStart; + // A held CSI has not ended, so only its last code unit is scanned again. + let cursor = index === 0 ? Math.max(contentStart, pendingScanStart) : contentStart; // Inside a CSI Ghostty executes 0x00-0x0F and ignores DEL and 0x10-0x1F, which it would // print in ground state. None join the parameters; only executed ones survive a strip. - let body = ""; - let executedControls = ""; + const executedControls = () => + input.slice(contentStart, cursor).replace(/[^\x00-\x0f]+/g, ""); while (cursor < input.length) { const cursorCodePoint = input.charCodeAt(cursor); const cancelled = isControlSequenceCancel(cursorCodePoint); if (cancelled || isCsiFinalByte(cursorCodePoint)) { - if (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? "")) { + const body = input.slice(contentStart, cursor).replace(/[^\x20-\x7e]+/g, ""); + if (!oversized && (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? ""))) { append(prefix + input.slice(index, cursor + 1)); } else { - append(executedControls); + append(executedControls()); } index = cursor + 1; break; @@ -1464,10 +1495,10 @@ function sanitizeTerminalHistoryChunk( if (c1) { // The CSI ends here undispatched, so it is kept only when the terminal is back in // ground with nothing to answer. - if (c1.next.length === 0 && !c1.query) { + if (!oversized && c1.next.length === 0 && !c1.query) { append(prefix + input.slice(index, end)); } else { - append(executedControls + c1.safe); + append(executedControls() + c1.safe); } c1Introducer = c1.next; index = end; @@ -1478,19 +1509,24 @@ function sanitizeTerminalHistoryChunk( } // An ESC abandons the CSI and starts the next sequence, which may be stripped. if (cursorCodePoint === 0x1b) { - append(executedControls); + append(executedControls()); index = cursor; break; } - if (cursorCodePoint < 0x10) { - executedControls += input[cursor]; - } else if (cursorCodePoint >= 0x20 && cursorCodePoint !== 0x7f) { - body += input[cursor]; - } cursor += 1; } if (cursor >= input.length) { - return { visibleText, pendingControlSequence: prefix + input.slice(index) }; + const unfinished = prefix + input.slice(index); + if (oversized || unfinished.length > MAX_HELD_SEQUENCE_LENGTH) { + // The terminal has run these controls already, so history takes them as they come. + append((oversized ? "" : STRING_TERMINATOR) + executedControls()); + const endStart = /[\ud800-\udbff]$/.exec(unfinished)?.[0] ?? ""; + return { + visibleText, + pendingControlSequence: `${OVERSIZED_SEQUENCE}\u001b[${endStart}`, + }; + } + return { visibleText, pendingControlSequence: unfinished }; } continue; } @@ -1507,7 +1543,16 @@ function sanitizeTerminalHistoryChunk( nextCodePoint === 0x5d, ); if (stringEnd === null) { - return { visibleText, pendingControlSequence: prefix + input.slice(index) }; + const unfinished = prefix + input.slice(index); + if (oversized || unfinished.length > MAX_HELD_SEQUENCE_LENGTH) { + append(oversized ? "" : STRING_TERMINATOR); + const endStart = /[\u001b\ud800-\udbff]$/.exec(unfinished)?.[0] ?? ""; + return { + visibleText, + pendingControlSequence: OVERSIZED_SEQUENCE + unfinished.slice(0, 2) + endStart, + }; + } + return { visibleText, pendingControlSequence: unfinished }; } const { end, c1 } = stringEnd; const content = stripStringTerminator( @@ -1517,6 +1562,7 @@ function sanitizeTerminalHistoryChunk( // has its own terminator. Without one, the query ends at the next ESC, which history may // strip, so ST would not replay the same and the query stays. if ( + !oversized && nextCodePoint === 0x5d && isOscPaletteQuery(content) && /[\x07\x18\x1a]$|\x1b\\$/.test(input.slice(index, end)) @@ -1526,6 +1572,7 @@ function sanitizeTerminalHistoryChunk( continue; } const strip = + oversized || (nextCodePoint === 0x5d && shouldStripOscSequence(content)) || (nextCodePoint === 0x50 && shouldStripDcsSequence(content)); if (c1 === undefined || (!strip && c1.effect.next.length === 0 && !c1.effect.query)) { @@ -1544,7 +1591,10 @@ function sanitizeTerminalHistoryChunk( const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1); if (escapeSequenceEndIndex === null) { - return { visibleText, pendingControlSequence: input.slice(index) }; + return { + visibleText, + pendingControlSequence: input.slice(index, index + MAX_HELD_ESCAPE_LENGTH), + }; } // ESC Z (DECID) is the legacy primary device attributes query. if (nextCodePoint !== 0x5a) { diff --git a/apps/server/src/workflows/WorkflowAgentLinks.test.ts b/apps/server/src/workflows/WorkflowAgentLinks.test.ts index 92b7a4f7b2ff..8fcba6dc9f3f 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.test.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.test.ts @@ -113,26 +113,55 @@ it.effect("starts a thread there by the project's folder, with the step's key as ); it.effect("registers a folder that is not a project there yet", () => + Effect.gen(function* () { + for (const [project, title] of [ + [input.project, "app"], + ["/work/team\\api", "team\\api"], + ["C:\\work\\app", "app"], + ]) { + const there = peer({ + t3_project_list: [{ projects: [], nextCursor: null }], + t3_project_create: [{ id: "p-new", workspaceRoot: project }], + t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], + }); + yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.start({ ...input, project }, "env-b", "workflow:k", EnvironmentId.make("env-a")), + ), + there.layer, + ); + assert.deepStrictEqual( + there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]), + [ + ["t3_project_list", undefined], + ["t3_project_create", title], + ["t3_thread_launch", "p-new"], + ], + ); + } + }), +); + +it.effect("finds a Windows folder there however its separators are written", () => Effect.gen(function* () { const there = peer({ - t3_project_list: [{ projects: [], nextCursor: null }], - t3_project_create: [{ id: "p-new", workspaceRoot: "/work/app" }], + t3_project_list: [ + { projects: [{ id: "p-app", workspaceRoot: "C:\\work\\app" }], nextCursor: null }, + ], t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], }); yield* Effect.provide( Effect.flatMap(WorkflowAgentLinks.make, (links) => - links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")), + links.start( + { ...input, project: "C:/work/app" }, + "env-b", + "workflow:k", + EnvironmentId.make("env-a"), + ), ), there.layer, ); - assert.deepStrictEqual( - there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]), - [ - ["t3_project_list", undefined], - ["t3_project_create", "app"], - ["t3_thread_launch", "p-new"], - ], - ); + assert.equal(there.calls.at(-1)?.arguments.projectId, "p-app"); }), ); diff --git a/apps/server/src/workflows/WorkflowAgentLinks.ts b/apps/server/src/workflows/WorkflowAgentLinks.ts index 6a0836fc0162..8d0bdc1d0c67 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.ts @@ -7,6 +7,11 @@ import { OrchestratorMcpThreadSendResult, OrchestratorMcpThreadWaitResult, } from "@t3tools/contracts"; +import { + fileBasename, + isWindowsDrivePath, + normalizeProjectPathForComparison, +} from "@t3tools/shared/path"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -77,6 +82,7 @@ export const make = Effect.gen(function* () { environment: string, path: string, ) { + const target = normalizeProjectPathForComparison(path); let cursor: number | null = 0; while (cursor !== null) { const page: Schema.Schema.Type = @@ -86,7 +92,9 @@ export const make = Effect.gen(function* () { ProjectToolkit.tools.t3_project_list.successSchema, { cursor, limit: 100 }, ); - const found = page.projects.find((project) => project.workspaceRoot === path); + const found = page.projects.find( + (project) => normalizeProjectPathForComparison(project.workspaceRoot) === target, + ); if (found !== undefined) return found.id; cursor = page.nextCursor; } @@ -104,7 +112,9 @@ export const make = Effect.gen(function* () { ) { const known = yield* listed(environment, path); if (known !== undefined) return known; - const title = path.split("/").findLast((part) => part.length > 0) ?? path; + const title = isWindowsDrivePath(path) + ? fileBasename(path) + : (path.split("/").findLast((part) => part.length > 0) ?? path); const created = yield* call( environment, "t3_project_create", diff --git a/apps/server/src/workflows/WorkflowAgents.ts b/apps/server/src/workflows/WorkflowAgents.ts index 674b72c69aa3..834a78134026 100644 --- a/apps/server/src/workflows/WorkflowAgents.ts +++ b/apps/server/src/workflows/WorkflowAgents.ts @@ -4,6 +4,7 @@ import type { ProviderInteractionMode, RuntimeMode, } from "@t3tools/contracts"; +import { isWindowsDrivePath } from "@t3tools/shared/path"; import * as Context from "effect/Context"; import type * as Duration from "effect/Duration"; import type * as Effect from "effect/Effect"; @@ -67,7 +68,8 @@ export const launchOnContinue = new WorkflowAgentError({ }); /** A project named by its folder instead of its id. */ -export const isProjectPath = (project: string) => project.startsWith("/"); +export const isProjectPath = (project: string) => + project.startsWith("/") || isWindowsDrivePath(project); /** Where agent steps run. The server implements it with threads; tests stand in for it. */ export class WorkflowAgents extends Context.Service< diff --git a/apps/server/src/workflows/WorkflowForge.test.ts b/apps/server/src/workflows/WorkflowForge.test.ts index 58f962642351..1d402227c57b 100644 --- a/apps/server/src/workflows/WorkflowForge.test.ts +++ b/apps/server/src/workflows/WorkflowForge.test.ts @@ -85,6 +85,27 @@ it.effect("what a step does through the forge is kept against it, one key per th }).pipe(Effect.provide(forge)), ); +it.effect("a step can name its project by a Windows folder", () => + Effect.gen(function* () { + const { pullRequests } = yield* WorkflowForge.WorkflowForge; + const noted: Array = []; + const inStep = Context.make(StepReferences, { + note: (reference) => Effect.sync(() => void noted.push(reference)), + }); + for (const project of ["C:\\Users\\me\\app", "C:/Users/me/app"]) { + yield* Effect.provideContext( + pullRequests.act({ project, url: "https://github.com/Me/App/pull/7" }, "merge"), + inStep, + ); + } + const address = { projectId, host: "github.com", repository: "me/app", number: 7 }; + assert.deepStrictEqual( + noted.map((reference) => reference.address), + [address, address], + ); + }).pipe(Effect.provide(forge)), +); + it("a step's pull requests are the ones its thread was linked to while it ran", () => { const link = (number: number, linkedAt: string, source = "agent") => ({ host: "github.com", diff --git a/apps/web/src/browserHistoryStore.browser.test.ts b/apps/web/src/browserHistoryStore.browser.test.ts index c0c22fc2558a..92e16d76243e 100644 --- a/apps/web/src/browserHistoryStore.browser.test.ts +++ b/apps/web/src/browserHistoryStore.browser.test.ts @@ -2,6 +2,7 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { resetBrowserHistoryForTests, useBrowserHistoryStore } from "./browserHistoryStore"; +import { randomUUID } from "./lib/utils"; const storageKey = "t3code:browser-history:v1"; const oldEntry = { url: "http://example.test/removed", lastVisitedAt: 1 }; @@ -117,8 +118,7 @@ it("refreshes the open history when another document adds a visit", async () => JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); - using documents = new DisposableStack(); - const otherStore = await openHistoryDocument(documents); + const otherStore = await openHistoryDocument(); await vi.waitFor(() => expect(otherStore.getState().byProjectKey).toEqual({ a: [page] })); otherStore.getState().recordVisit("a", page.url, page.lastVisitedAt); @@ -164,29 +164,15 @@ it("bounds saved thread mappings while keeping live registrations", async () => } }); -async function openHistoryDocument( - disposables: DisposableStack, - { withoutIndexedDB = false } = {}, -) { - const source = new URL(import.meta.url); - source.pathname = source.pathname.replace(/\.browser\.test\.ts$/, ".ts"); - source.search = ""; - const frame = document.createElement("iframe"); - disposables.defer(() => frame.remove()); - frame.srcdoc = `${withoutIndexedDB ? '' : ""} - `; - await new Promise((resolve) => { - frame.onload = () => resolve(); - document.body.append(frame); - }); - const store = ( - frame.contentWindow as (Window & { historyStore?: typeof useBrowserHistoryStore }) | null - )?.historyStore; - if (!store) throw new Error("The history document did not load."); - return store; +// A fresh module instance stands in for another tab: it gets its own store, IndexedDB connection +// and BroadcastChannel without an iframe reloading the app's whole module graph. +async function openHistoryDocument() { + const source = new URL("./browserHistoryStore.ts", import.meta.url); + source.searchParams.set("document", randomUUID()); + const module: typeof import("./browserHistoryStore") = await import( + /* @vite-ignore */ source.href + ); + return module.useBrowserHistoryStore; } function deleteHistoryDatabase() { @@ -210,14 +196,13 @@ it("moves the legacy snapshot into the shared database", async () => { JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); try { - using documents = new DisposableStack(); - const first = await openHistoryDocument(documents); + const first = await openHistoryDocument(); await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); expect(localStorage.getItem(storageKey)).toBeNull(); first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); - const reopened = await openHistoryDocument(documents); + const reopened = await openHistoryDocument(); await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), ); @@ -233,8 +218,7 @@ it("persists new visits from an open document after its history database is dele JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); try { - using documents = new DisposableStack(); - const first = await openHistoryDocument(documents); + const first = await openHistoryDocument(); await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); first.getState().removeUrl("a", page.url); await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({})); @@ -243,7 +227,7 @@ it("persists new visits from an open document after its history database is dele first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); - const reopened = await openHistoryDocument(documents); + const reopened = await openHistoryDocument(); await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual({ b: [otherEntry] })); } finally { await resetHistoryFixture(); @@ -257,11 +241,7 @@ it("keeps overlapping visits from independent documents", async () => { JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); try { - using documents = new DisposableStack(); - const [first, second] = await Promise.all([ - openHistoryDocument(documents), - openHistoryDocument(documents), - ]); + const [first, second] = await Promise.all([openHistoryDocument(), openHistoryDocument()]); first.getState().recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); second.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); const expected = { a: [page, oldEntry], b: [otherEntry] }; @@ -272,7 +252,7 @@ it("keeps overlapping visits from independent documents", async () => { // A fresh document should read the committed visits even after the legacy seed is gone. localStorage.removeItem(storageKey); - const reopened = await openHistoryDocument(documents); + const reopened = await openHistoryDocument(); await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual(expected)); } finally { await resetHistoryFixture(); @@ -282,16 +262,25 @@ it("keeps overlapping visits from independent documents", async () => { it("keeps visits saved while IndexedDB could not open", async () => { await resetHistoryFixture(); try { - using documents = new DisposableStack(); - const db = await openHistoryFixture(documents); + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); await writeHistoryFixture(db, { byProjectKey: { a: [page] }, projectKeyByThreadKey: {} }); - const offline = await openHistoryDocument(documents, { withoutIndexedDB: true }); - offline.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); - await vi.waitFor(() => - expect(storedHistory()).toHaveProperty("byProjectKey", { b: [otherEntry] }), - ); + vi.stubGlobal("indexedDB", { + open() { + throw new Error("blocked"); + }, + }); + try { + const offline = await openHistoryDocument(); + offline.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => + expect(storedHistory()).toHaveProperty("byProjectKey", { b: [otherEntry] }), + ); + } finally { + vi.unstubAllGlobals(); + } - const online = await openHistoryDocument(documents); + const online = await openHistoryDocument(); await vi.waitFor(() => expect(online.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), ); diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 77a613d58979..385cbefced8c 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -123,7 +123,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { Button } from "./ui/button"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { recordVisitForThread } from "../browserHistoryStore"; -import { contextMenuSourceOf } from "../contextMenuSource"; +import { contextMenuSourceOf, openContextMenuFromKeyboard } from "../contextMenuSource"; import { PreferredEditorEnvironmentRequiredError, useOpenInPreferredEditor, @@ -1751,6 +1751,9 @@ const CHAT_MARKDOWN_COMPONENTS = { void readLocalApi()?.shell.openExternal(href); }); }} + onKeyDown={(event) => { + if (href && faviconHost) openContextMenuFromKeyboard(event); + }} onContextMenu={(event) => { if (!href || !faviconHost) return; event.preventDefault(); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index dbf66a8fc55e..4e95f9fe3e33 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -2837,6 +2837,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }), isRegeneratingTitle, isRunning: !threadRuntimeCanArchive(thread.runtime), + hasCompletedRun: thread.latestRun?.completedAt != null, supports: { settlement: configLoaded, autoSettleOptOut: supportsAutoSettleOptOut, diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts index 8cecf25c2c32..4f6d93d0f8c3 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts @@ -16,6 +16,7 @@ const state = vi.hoisted(() => ({ shells: null as unknown as { set: (id: string, value: unknown) => void }, navigate: vi.fn(), sound: vi.fn(), + unlock: vi.fn(), badge: vi.fn(), settingsListeners: new Set<() => void>(), })); @@ -82,7 +83,7 @@ vi.mock(import("../hooks/useSettings"), async (original) => ({ vi.mock(import("../threadNotifications"), async (original) => ({ ...(await original()), playNotificationSound: state.sound, - unlockNotificationAudio: vi.fn(), + unlockNotificationAudio: state.unlock, setNotificationBadge: state.badge, })); @@ -295,6 +296,19 @@ it("presents completion notifications and sound as soon as the shell completes", expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function)); }); +it.each([ + { client: "desktop app", when: "at startup", bridge: {}, beforeGesture: 1 }, + { client: "browser", when: "on the first gesture", bridge: undefined, beforeGesture: 0 }, +])("readies notification sound in the $client $when", async ({ bridge, beforeGesture }) => { + await using app = setup(); + using _bridge = stubGlobal("desktopBridge", bridge); + state.mode = "sound"; + app.start(); + expect(state.unlock).toHaveBeenCalledTimes(beforeGesture); + document.dispatchEvent(new Event("pointerdown")); + expect(state.unlock).toHaveBeenCalledTimes(beforeGesture + 1); +}); + it.each([false, true])( "presents one completion when a monitor ends with a final wake (disconnected: %s)", async (disconnect) => { diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index bd34c74d4727..b45442568c0a 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -485,6 +485,8 @@ export function startThreadNotifications( }); } if (hasNotificationSound(nextMode)) { + // Electron's default autoplay policy needs no gesture, unlike browsers. + if (window.desktopBridge) unlockNotificationAudio(); document.addEventListener("pointerdown", unlockNotificationAudio); document.addEventListener("keydown", unlockNotificationAudio); stops.push(() => { diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx index a0309a82ed0c..f123185e72da 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.tsx +++ b/apps/web/src/components/chat/MarkdownFileLink.tsx @@ -16,7 +16,7 @@ import { memo, useState, type MouseEvent as ReactMouseEvent } from "react"; import { useGT } from "gt-react"; import { FolderIcon } from "lucide-react"; -import { contextMenuSourceOf } from "../../contextMenuSource"; +import { contextMenuSourceOf, openContextMenuFromKeyboard } from "../../contextMenuSource"; import { readLocalApi } from "../../localApi"; import { cn } from "../../lib/utils"; import { shouldOpenMarkdownFileLinkInEditor } from "../../markdown-links"; @@ -419,6 +419,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ handleOpenInFilePreview(); }} onContextMenu={handleContextMenu} + onKeyDown={openContextMenuFromKeyboard} > = 0 - ? resolvePathLinkTarget(props.relativePath.slice(0, lastSeparator), props.cwd) + ? resolvePathLinkTarget(props.relativePath.slice(0, lastSeparator + 1), props.cwd) : props.cwd; return ( diff --git a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx index 07e05010baab..4a6e5da91b87 100644 --- a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx @@ -18,6 +18,7 @@ const state = vi.hoisted(() => ({ optimistic: null as ProjectReadFileResult | null, writeFile: vi.fn(), assetUrl: { _tag: "Loading" } as import("~/assets/assetUrls").AssetUrlState, + assetResources: [] as Array, mintUrl: vi.fn<() => Promise>(), browserAssetMints: 0, openedBrowserUrls: [] as string[], @@ -65,7 +66,13 @@ vi.mock(import("~/hooks/useWorkspaceMutationRefresh"), () => ({ vi.mock(import("~/assets/assetUrls"), async (original) => ({ ...(await original()), useAssetUrlRefresh: () => state.mintUrl, - useAssetUrlState: () => state.assetUrl, + useAssetUrlState: ( + _environmentId: unknown, + resource: import("@t3tools/contracts").AssetResource | null, + ) => { + if (resource) state.assetResources.push(resource); + return state.assetUrl; + }, })); vi.mock(import("~/browser/previewRuntime"), async (original) => ({ ...(await original()), @@ -173,6 +180,7 @@ function setup() { state.file = null; state.optimistic = null; state.assetUrl = { _tag: "Loading" }; + state.assetResources = []; state.openedBrowserUrls = []; let mints = 0; state.mintUrl.mockReset().mockImplementation(async () => `/assets/report.docx?mint=${++mints}`); @@ -188,14 +196,18 @@ function setup() { }; } -function markdownPreview(truncated: boolean, contents = "- [ ] Keep the rest of this file\n") { +function markdownPreview( + truncated: boolean, + contents = "- [ ] Keep the rest of this file\n", + relativePath = "tasks.md", +) { state.file = { - relativePath: "tasks.md", + relativePath, contents, byteLength: truncated ? 1_200_000 : contents.length, truncated, }; - return filePreview("tasks.md"); + return filePreview(relativePath); } function filePreview(relativePath: string, workspaceMutationId: string | null = null) { @@ -717,3 +729,19 @@ describe("rendered Markdown select all", () => { await expectFileOnlySelection(); }); }); + +describe("rendered Markdown relative images", () => { + it.each([ + ["2026-11-23T14:05/README.md", "/workspace/2026-11-23T14:05/diagram.png"], + ["/README.md", "/diagram.png"], + ])("resolves relative images in %s against its folder", async (relativePath, expectedPath) => { + using _settings = setup(); + await using _screen = await render( + markdownPreview(false, "![diagram](diagram.png)\n", relativePath), + ); + await vi.waitFor(() => expect(state.assetResources).not.toHaveLength(0)); + expect(state.assetResources).toContainEqual( + expect.objectContaining({ _tag: "media-file", path: expectedPath }), + ); + }); +}); diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 53783c7ded6a..b32a64fd1837 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -299,6 +299,18 @@ Third}`; for (const [rtf, expected] of [ [String.raw`{\rtf1\ansi\ansicpg0 Caf\'e9}`, "

Café

"], [String.raw`{\rtf1\ansi\ansicpg866 \'8f\'e0\'a8\'a2\'a5\'e2}`, "

Привет

"], + [ + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl\f0\froman\fcharset0 Times-Roman;}\f0 \'805 caf\'e9}`, + "

€5 café

", + ], + [ + String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0 LucidaGrande;}\f0 pridr\'9eana}`, + "

pridržana

", + ], + [ + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl{\f0\fnil\fcharset0\cpg1251 Arial;}{\f1\fnil\fcharset204 Arial{\*\fontfile\cpg1252 arial.ttf};}}\f0 \'cf\'f0\'e8\f1\'e2\'e5\'f2}`, + "

Привет

", + ], ] as const) { const decoded = openRtf(bytes(rtf)); if (decoded.type !== "document") throw new Error("Expected document"); @@ -426,6 +438,23 @@ Third}`; "final entry", ], }, + { + output_type: "error", + ename: "ZeroDivisionError", + evalue: "division by zero", + traceback: [], + }, + { + output_type: "error", + evalue: "\u001b[31mbad input\u001b[0m", + traceback: [], + }, + { + output_type: "error", + ename: "RuntimeError", + evalue: "kernel reset", + traceback: ["\u001b[31m\u001b[0m", " \n"], + }, ], }, ], @@ -446,6 +475,9 @@ Third}`; kind: "text", text: "Traceback (most recent call last):\nCell In[3], line 1\n----> 1 fail()\nValueError: preview proof\nfinal entry", }, + { kind: "text", text: "ZeroDivisionError: division by zero" }, + { kind: "text", text: "bad input" }, + { kind: "text", text: "RuntimeError: kernel reset" }, ]); expect(() => openNotebook(bytes('{"nbformat":3,"cells":[]}'))).toThrow( expect.objectContaining({ code: "notebook-unsupported" }), @@ -577,6 +609,26 @@ Third}`; } }); + it("keeps OpenDocument image descriptions in image alt text", async () => { + const archive = new JSZip() + .file( + "content.xml", + '' + + 'LogoResearch & "Design"Visible caption', + ) + .file( + "picture.png", + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==", + { base64: true }, + ); + + const result = await openDocument(archive, "odt"); + if (result.type !== "document") throw new Error("Expected document"); + expect(result.pages[0]!.html).toMatch( + /^

Logo Research & "Design"Visible caption<\/p>$/, + ); + }); + it("reads EPUB chapters in spine order and removes active and remote content", async () => { const archive = new JSZip() .file( diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index d0c6bea968de..d04f1c9882ee 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -29,6 +29,7 @@ const namespacePrefixes: Record = { "urn:oasis:names:tc:opendocument:xmlns:table:1.0": "table", "urn:oasis:names:tc:opendocument:xmlns:text:1.0": "text", "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0": "draw", + "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0": "svg", "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0": "presentation", "http://www.w3.org/1999/xlink": "xlink", "http://www.w3.org/1999/xhtml": "", @@ -266,7 +267,7 @@ async function epubHtml(node: XmlNode, archive: JSZip, base: string): Promise${children}`; } -async function odfHtml(node: XmlNode, archive: JSZip): Promise { +async function odfHtml(node: XmlNode, archive: JSZip, imageAlt = ""): Promise { if (node.name === "#text") return pipe(text(node), escape, boundedMarkup); if (node.name === "text:s" || node.name === "text:tab") return boundedMarkup( @@ -278,12 +279,14 @@ async function odfHtml(node: XmlNode, archive: JSZip): Promise { archive, archivePath("content.xml", node.attrs["xlink:href"] ?? ""), ); - return src ? `` : ""; + return src ? `${boundedMarkup(escape(imageAlt))}` : ""; } if ( [ "office:annotation", "presentation:notes", + "svg:title", + "svg:desc", "text:tracked-changes", "office:scripts", "draw:object", @@ -298,8 +301,16 @@ async function odfHtml(node: XmlNode, archive: JSZip): Promise { ].includes(node.name) ) return ""; + const childImageAlt = + node.name === "draw:frame" + ? ["svg:title", "svg:desc"] + .map((name) => node.children.find((child) => child.name === name)) + .map((child) => (child ? text(child).trim() : "")) + .filter(Boolean) + .join(" ") + : ""; let children = ""; - for (const child of node.children) children += await odfHtml(child, archive); + for (const child of node.children) children += await odfHtml(child, archive, childImageAlt); const tags: Record = { "text:p": "p", "text:h": "h2", @@ -490,12 +501,16 @@ export function openNotebook(bytes: ArrayBuffer): OfficeWorkerResult { } const html = notebookText(data["text/html"]); if (html.trim() && htmlImagesFit(html)) return { kind: "html" as const, text: html }; - return { - kind: "text" as const, - text: terminalOutputPlainText( - notebookText(output.text ?? data["text/plain"] ?? tracebackLines(output.traceback)), - ), - }; + const text = terminalOutputPlainText( + notebookText(output.text ?? data["text/plain"] ?? tracebackLines(output.traceback)), + ); + if (text.trim() || output.output_type !== "error") return { kind: "text" as const, text }; + const summary = [output.ename, output.evalue] + .filter((part) => typeof part === "string") + .map((part) => terminalOutputPlainText(notebookText(part))) + .filter((part) => part.trim().length > 0) + .join(": "); + return { kind: "text" as const, text: summary }; }) .filter((output) => output.text.trim().length > 0), }; @@ -527,6 +542,21 @@ const RTF_CHARACTERS = new Map([ ["rtlmark", "\u200f"], ]); +const rtfCodePageLabel = (codePage: number) => + ( + { + 0: "windows-1252", + 866: "ibm866", + 65001: "utf-8", + 932: "shift_jis", + 936: "gbk", + 949: "euc-kr", + 950: "big5", + 874: "windows-874", + 10000: "macintosh", + } as Record + )[codePage] ?? `windows-${codePage}`; + export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { if (bytes.byteLength > 8 * 1024 * 1024) throw new PreviewError({ code: "rtf-too-large" }); // Keep byte offsets intact for binary destinations and multibyte code pages. @@ -545,8 +575,11 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { uc: 1, font: 0, fontTable: false, + fontFile: false, decoder: new TextDecoder("windows-1252"), }; + // A font's \cpg, else its \fcharset, encodes the bytes written in that font. A \cpg inside + // \fontfile encodes the font's file name instead. const fonts = new Map(); let defaultFont = 0; const stack: (typeof state)[] = []; @@ -657,7 +690,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { else if (word === "fcharset" && state.fontTable) { const label = ( { - 0: state.decoder.encoding, + 0: "windows-1252", 1: state.decoder.encoding, 77: "macintosh", 128: "shift_jis", @@ -677,6 +710,13 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { } as Record )[arg]; if (label) fonts.set(state.font, new TextDecoder(label)); + } else if (word === "fontfile") state.fontFile = true; + else if (word === "cpg" && state.fontTable && !state.fontFile) { + try { + fonts.set(state.font, new TextDecoder(rtfCodePageLabel(arg))); + } catch { + // An unknown font code page leaves the font on its \fcharset. + } } else if ( [ "colortbl", @@ -701,22 +741,8 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { state.skip = true; else if (word === "mac") state.decoder = new TextDecoder("macintosh"); else if (word === "ansicpg") { - const label = - ( - { - 0: "windows-1252", - 866: "ibm866", - 65001: "utf-8", - 932: "shift_jis", - 936: "gbk", - 949: "euc-kr", - 950: "big5", - 874: "windows-874", - 10000: "macintosh", - } as Record - )[arg] ?? `windows-${arg}`; try { - state.decoder = new TextDecoder(label); + state.decoder = new TextDecoder(rtfCodePageLabel(arg)); } catch { throw new PreviewError({ code: "rtf-code-page" }); } diff --git a/apps/web/src/components/threadActionMenu.logic.test.ts b/apps/web/src/components/threadActionMenu.logic.test.ts index caf43b9789fe..68c7dc3daf6b 100644 --- a/apps/web/src/components/threadActionMenu.logic.test.ts +++ b/apps/web/src/components/threadActionMenu.logic.test.ts @@ -24,6 +24,7 @@ const baseState: ThreadActionMenuState = { canSnoozeNow: true, isRegeneratingTitle: false, isRunning: false, + hasCompletedRun: true, supports: { settlement: true, autoSettleOptOut: true, @@ -374,6 +375,14 @@ describe("buildThreadActionMenuItems", () => { expect(items.find((item) => item.id === "turn-into-project")?.disabled).toBe(true); }); + it.each([ + ["while the thread is running", { isRunning: true }], + ["before any run has completed", { hasCompletedRun: false }], + ])("omits mark unread %s", (_, overrides) => { + const items = buildThreadActionMenuItems({ ...baseState, ...overrides }); + expect(items.map((item) => item.id)).not.toContain("mark-unread"); + }); + it("disables only rename where no inline title editor exists", () => { const items = buildThreadActionMenuItems({ ...baseState, canRename: false }); expect(items.filter((item) => item.disabled).map((item) => item.id)).toEqual(["rename"]); diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index 393c19c388db..317373978082 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -166,6 +166,8 @@ export interface ThreadActionMenuState { readonly isRegeneratingTitle: boolean; /** Archive rejects attached providers, so disable it while running. */ readonly isRunning: boolean; + /** The server marks unread against the latest run's completion, so in-flight runs cannot be. */ + readonly hasCompletedRun: boolean; readonly supports: { readonly settlement: boolean; readonly autoSettleOptOut: boolean; @@ -360,7 +362,9 @@ export function buildThreadActionMenuItems( }, ] : []), - { id: "mark-unread", label: resolve(msg("Mark unread")), icon: "mail-open" }, + ...(state.hasCompletedRun && !state.isRunning + ? [{ id: "mark-unread" as const, label: resolve(msg("Mark unread")), icon: "mail-open" }] + : []), ...(state.canRestartSession ? [ { diff --git a/apps/web/src/contextMenuSource.ts b/apps/web/src/contextMenuSource.ts index 11ecfbdf336f..8e959003d141 100644 --- a/apps/web/src/contextMenuSource.ts +++ b/apps/web/src/contextMenuSource.ts @@ -1,8 +1,38 @@ import type { ContextMenuSource } from "@t3tools/contracts"; +// Menus opened by openContextMenuFromKeyboard; a script-made event cannot keep button -1. +const keyboardContextMenus = new WeakSet(); + // Chromium uses no button for keyboard context menus and zero clicks for keyboard activation. export function contextMenuSourceOf( - event: Pick, + event: Pick & { readonly nativeEvent?: Event }, ): ContextMenuSource { + if (event.nativeEvent !== undefined && keyboardContextMenus.has(event.nativeEvent)) { + return "keyboard"; + } return (event.type === "click" ? event.detail === 0 : event.button === -1) ? "keyboard" : "mouse"; } + +/** + * Opens an element's context menu from the keyboard. Chromium on macOS turns neither + * Shift+F10 nor the ContextMenu key into a `contextmenu` event, so the key is handled + * here and the element's own handler receives a menu event that reads as keyboard-opened. + * Preventing the key keeps other platforms from opening the menu a second time. + */ +export function openContextMenuFromKeyboard( + event: Pick & { + readonly currentTarget: Element; + }, +): void { + if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return; + event.preventDefault(); + const bounds = event.currentTarget.getBoundingClientRect(); + const menu = new MouseEvent("contextmenu", { + bubbles: true, + cancelable: true, + clientX: bounds.left, + clientY: bounds.bottom, + }); + keyboardContextMenus.add(menu); + event.currentTarget.dispatchEvent(menu); +} diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index aef0b98f5e94..bf101e5ca08f 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -206,6 +206,7 @@ export function useThreadActionMenu(input: { canSnoozeNow: canSnooze(thread, { now: now.toISOString() }), isRegeneratingTitle, isRunning: !threadRuntimeCanArchive(thread.runtime), + hasCompletedRun: thread.latestRun?.completedAt != null, supports, snoozePresets, integrations: readEnvironmentLinkIntegrations(threadRef.environmentId), diff --git a/docs/fork-differences.md b/docs/fork-differences.md index 5136c6109f74..2653a6624464 100644 --- a/docs/fork-differences.md +++ b/docs/fork-differences.md @@ -27,11 +27,10 @@ Code: [checkouts.ts](../packages/contracts/src/checkouts.ts), [CheckoutAttachPicker.tsx](../apps/web/src/components/chat/CheckoutAttachPicker.tsx), and [CheckoutInspect.ts](../apps/server/src/checkouts/CheckoutInspect.ts). -## macOS Paste as Text shortcut +## Desktop Paste as Text menu -In the macOS desktop app, **⌘⇧V** pastes text into the composer instead of doing nothing. -Both the shortcut and **Edit → Paste as Text** keep large text inline. The shortcut uses -the native macOS editing action so it does not inject a second paste into the terminal. +**Edit → Paste as Text** also works in Quick Message. The menu sends the paste to the focused +trusted app window without opening or raising the main window. Code: [DesktopApplicationMenu.ts](../apps/desktop/src/window/DesktopApplicationMenu.ts). diff --git a/docs/internals/08_product-analytics.md b/docs/internals/08_product-analytics.md index 24cb8b04e39f..375f6be84b85 100644 --- a/docs/internals/08_product-analytics.md +++ b/docs/internals/08_product-analytics.md @@ -28,7 +28,9 @@ an authenticated connection does not count as product use. - Payloads stay strictly to product metadata, closed contract enums, and normalized measurements: never attach prompts, file paths, credentials, raw provider payloads, device names, conversation - IDs, user-named provider instance IDs, or non-vendor/custom model names. + IDs, or user-named provider instance IDs. Model IDs are reported as the provider used them, + including custom models; known aliases and routed IDs map to one catalog slug, and a model + that is a file path reports only its file name. - The sole exception is opt-in `agent.feedback`, which [`FeedbackService`](../../apps/server/src/feedback/FeedbackService.ts) scrubs of paths, private values, and secret-shaped strings, and only attaches bounded conversation traces when the user diff --git a/docs/internals/16_performance-regressions.md b/docs/internals/16_performance-regressions.md index 0e42c0fa09f3..863ccc0c7b69 100644 --- a/docs/internals/16_performance-regressions.md +++ b/docs/internals/16_performance-regressions.md @@ -37,6 +37,13 @@ heap, and first-request latency against a fake Anthropic API and the real `claud isolated runs. - Use `scaling` to separate per-thread cost from fixed server overhead, and `--soak ` to spot rising heap slopes (leaks). +- Steer server work by `working`: many worktree threads editing files at once with one client + subscribed to all of them. Turns per minute that stay flat as threads are added mean the + server, not the agents, is the bottleneck. +- Upper bounds no user hits daily, such as 20 clients reconnecting at once, run only with + `--stress`; the default reconnect is a user's 3 devices holding 10 threads each. +- `--quick` shortens every window for a per-PR or nightly check; `compare` refuses to mix quick + and full runs. `server-metrics --help` says which scenario to trust for what. - Test macOS, Windows, and Linux with `--no-agent-scope`: Linux systemd agent scopes mask per-process polling paths that other platforms run. diff --git a/docs/user/install.md b/docs/user/install.md index fa14dd3dcaca..a585b4707bad 100644 --- a/docs/user/install.md +++ b/docs/user/install.md @@ -195,19 +195,20 @@ and enable the provider you want. Installation, login, and configuration belong to that environment's machine, even when you connect from a phone or another computer. -| Provider | Install and authenticate | -| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Codex | [Connect with ChatGPT](./providers-codex.md#connect-with-chatgpt), or install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`. | -| Claude | Install [Claude Code](https://claude.com/product/claude-code), then run `claude auth login`. | -| Cursor | Install [Cursor CLI](https://cursor.com/cli), then run `agent login`. | -| Grok Build | Install [Grok Build CLI](https://x.ai/cli), then run `grok login`. | -| Kiro | Install [Kiro CLI](https://kiro.dev/docs/cli/), then run `kiro-cli login`. | -| OpenCode | Install [OpenCode](https://opencode.ai), then run `opencode auth login`. | -| Antigravity | Install and sign in with Google from T3 Code's provider settings. | -| Pi | Install [Pi](./providers-pi.md#set-up-pi) with Node.js 22.19 or newer, then run `pi` and `/login`. | -| Custom ACP | Install any ACP agent and sign in with its own CLI, then add it as a [Custom ACP](./providers-custom-acp.md) provider. | -| Muse Code | Install [Muse Code](https://dev.meta.ai/docs/muse-code) on the server, run `muse login`, then enable it in Settings → Providers. | -| fx | Install [fx](https://fx.sh) with `curl -fsSL https://fx.sh/setup.sh \| bash`, then run `fx login`. | +| Provider | Install and authenticate | +| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Codex | [Connect with ChatGPT](./providers-codex.md#connect-with-chatgpt), or install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`. | +| Claude | Install [Claude Code](https://claude.com/product/claude-code), then run `claude auth login`. | +| Cursor | Install [Cursor CLI](https://cursor.com/cli), then run `agent login`. | +| Grok Build | Install [Grok Build CLI](https://x.ai/cli), then run `grok login`. | +| Kiro | Install [Kiro CLI](https://kiro.dev/docs/cli/), then run `kiro-cli login`. | +| OpenCode | Install [OpenCode](https://opencode.ai), then run `opencode auth login`. | +| Antigravity | Install and sign in with Google from T3 Code's provider settings. | +| Pi | Install [Pi](./providers-pi.md#set-up-pi) with Node.js 22.19 or newer, then run `pi` and `/login`. | +| Muse Code | Install [Muse Code](https://dev.meta.ai/docs/muse-code) on the server, run `muse login`, then enable it in Settings → Providers. | +| fx | Install [fx](https://fx.sh) with `curl -fsSL https://fx.sh/setup.sh \| bash`, then run `fx login`. | +| ACP Registry agents | Add GitHub Copilot and other [ACP agents](./providers-acp.md#add-an-agent) from **Settings → Providers → Add provider → Show more**. | +| Custom ACP | Install any ACP agent and sign in with its own CLI, then add it as a [Custom ACP](./providers-custom-acp.md) provider. | Provider CLIs must be on the server's `PATH`. If T3 Code cannot find one, set its **Binary path** in provider settings, especially when using a version manager. @@ -246,8 +247,9 @@ their original values. For provider-specific setup and accounts, see [Codex](./providers-codex.md), [Claude](./providers-claude.md), [Devin](./providers-devin.md), [OpenCode](./providers-opencode.md), -[Antigravity](./providers-antigravity.md), [Kiro](./providers-kiro.md), [Pi](./providers-pi.md), and -[Muse Code](./providers-muse.md), [fx](./providers-fx.md), and [Custom ACP agents](./providers-custom-acp.md). +[Antigravity](./providers-antigravity.md), [Kiro](./providers-kiro.md), +[Pi](./providers-pi.md), [Muse Code](./providers-muse.md), [fx](./providers-fx.md), +[ACP Registry agents](./providers-acp.md), and [Custom ACP agents](./providers-custom-acp.md). ### Provider check timeouts diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index a7974e17911b..73ef506e5f44 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -173,9 +173,10 @@ started in the app are. `send` never interrupts: a busy thread gets the message as its next turn. Pass `-` as the message to read it from stdin. To choose the model, pass `--provider --model `. Add -`--option id=value` for each model option, such as `--option effort=high`. -Option ids and values depend on the model; `true` and `false` set on/off -options. +`--option id=value` for each model option. For reasoning effort, Codex uses +`--option reasoningEffort=high`, while Claude uses `--option effort=high`. +Option ids and allowed values depend on the provider and model; use those +reported by `orchestrator_capabilities`. `true` and `false` set on/off options. `--wait` prints the agent's reply. It exits 1 when the run fails or stops, and 2 when the agent waits for an answer you give in the app. Add `--json` for a diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md index 4c6b3f20eaad..be7fdd938ff0 100644 --- a/docs/user/telemetry.md +++ b/docs/user/telemetry.md @@ -6,8 +6,8 @@ uses, the server also sends hashed account identifiers: your T3 Connect account, Claude accounts when you are signed in, and a random identifier for each device that connects. The endpoint keeps a copy of each event and forwards events to PostHog. Events include the provider, model, reasoning effort, permission mode, turn and request results, duration, release channel, and token counts when -available. Child-agent token counts are reported separately from the main agent's. Model names -are sent only when they appear in a provider's public model list. +available. Child-agent token counts are reported separately from the main agent's. Events include +the model ID the provider used, including custom models and models served by a custom endpoint. Product events do not include prompts, responses, file contents, authentication tokens, conversation IDs, raw provider events, or child-agent output. The one exception is [agent feedback](#agent-feedback), @@ -52,8 +52,8 @@ Before anything is saved, T3 Code removes file paths (when text mentions one, th goes with it), your user name, machine name, project title, branch, and git remote, and anything that looks like a key, token, email address, or URL with a password. It cannot recognise your code or a name written in a sentence, so only include the conversation when it holds nothing you would -not send. Reports from agents also name the provider, and the model when it is from the provider's -public model list. No thread IDs or project IDs are sent. +not send. Reports from agents also name the provider and the model. No thread IDs or project IDs +are sent. Reports are saved on your machine first, and a declined one is not saved at all; its card keeps only what you would have sent without the conversation. When product usage diff --git a/knip.jsonc b/knip.jsonc index 55a53f69d1e3..19c783509e5a 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -85,6 +85,7 @@ // Electron loads these bundles by filename rather than importing them. "entry": [ "gnome-extension/extension.js!", + "src/backend/DesktopBackendRecoveryWorker.ts!", "src/electron/WindowsForegroundFocusWorker.ts!", "src/snapShot/GlobalShiftShortcutWorker.ts!", "src/snapShot/RegionSnapShotWorker.ts!", diff --git a/packages/client-runtime/src/workflows.test.ts b/packages/client-runtime/src/workflows.test.ts index 9fce777fd564..14991a1c6543 100644 --- a/packages/client-runtime/src/workflows.test.ts +++ b/packages/client-runtime/src/workflows.test.ts @@ -298,6 +298,9 @@ describe("workflowSaidStart", () => { expect(workflowSaidStart(said, 200)).toBeNull(); expect(workflowSaidStart(said, 40)).toBe("It is a real bug.\n\n**Where:** line 5."); expect(workflowSaidStart(said, 10)).toBe("It is a real bug."); + const unspaced = "这个问题出现在解析器中。".repeat(60); + expect(workflowSaidStart(unspaced, 10)).toBe("这个问题出现在解析器…"); + expect(workflowSaidStart("😀".repeat(30), 9)).toBe(`${"😀".repeat(4)}…`); }); }); diff --git a/packages/client-runtime/src/workflows.ts b/packages/client-runtime/src/workflows.ts index 3808f9470323..2a4eac6c00b4 100644 --- a/packages/client-runtime/src/workflows.ts +++ b/packages/client-runtime/src/workflows.ts @@ -700,7 +700,15 @@ export function workflowSaidStart(said: string, limit: number): string | null { kept = `${kept}\n\n${paragraph}`; } // One paragraph that runs on is cut at a word, which can still split markup but not a word. - if (kept.length > limit * 2) kept = `${kept.slice(0, kept.lastIndexOf(" ", limit))}…`; + // Text with no space before the limit, such as Chinese, is cut at the limit, never inside a + // surrogate pair. + if (kept.length > limit * 2) { + const space = kept.lastIndexOf(" ", limit); + const before = kept.charCodeAt(limit - 1); + const highSurrogateLast = before >= 0xd800 && before <= 0xdbff; + const end = space > 0 ? space : highSurrogateLast ? limit - 1 : limit; + kept = `${kept.slice(0, end)}…`; + } return kept === said ? null : kept; } diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 997f66490a7b..74560cfc4340 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -2067,6 +2067,8 @@ export const OrchestrationV2TurnItem = Schema.Union([ ...OrchestrationV2TurnItemBaseFields, type: Schema.Literal("assistant_message"), phase: Schema.optional(AssistantMessagePhase), + /** The provider sent this mid-turn, apart from the turn's answer. */ + delivery: Schema.optional(Schema.Literal("async")), messageId: MessageId, text: Schema.String, textOmitted: DedupedBodyMarker, @@ -2984,6 +2986,8 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ ...OrchestrationV2TurnItemJsonBaseFields, type: Schema.Literal("assistant_message"), phase: Schema.optional(AssistantMessagePhase), + /** The provider sent this mid-turn, apart from the turn's answer. */ + delivery: Schema.optional(Schema.Literal("async")), messageId: MessageId, text: Schema.String, attachments: Schema.optional(Schema.Array(ChatAttachment)), diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts index 701ad57fe488..c08627eccdc0 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts @@ -495,8 +495,7 @@ describe("OpenCode2Client usage limits", () => { const result = yield* api.usageLimits("/remote"); if (reason === undefined) assert.strictEqual(result, undefined); else assert.strictEqual(result?.unavailable?.reason, reason); - if ("data" in body && body.data === null) - assert.include(result?.unavailable?.message ?? "", "signed in"); + if (reason === "unsupported") assert.strictEqual(result?.unavailable?.message, undefined); if ("message" in body) assert.include(result?.unavailable?.message ?? "", "OpenCode Console budgets"); } diff --git a/packages/provider-opencode/src/server/v2/usageLimits.ts b/packages/provider-opencode/src/server/v2/usageLimits.ts index bdf678e42469..ea3f141b2100 100644 --- a/packages/provider-opencode/src/server/v2/usageLimits.ts +++ b/packages/provider-opencode/src/server/v2/usageLimits.ts @@ -95,12 +95,8 @@ export const readServerUsageLimits = Effect.fn("OpenCode2Client.usageLimits")(fu ), }); const body = yield* HttpClientResponse.schemaBodyJson(ResponseBody)(response); - if (body.data === null) - return makeUnavailableUsageLimits({ - checkedAt, - reason: "unsupported", - message: "No OpenCode Console workspace is signed in.", - }); + // OpenCode needs no Console workspace, so its absence is not worth a notice. + if (body.data === null) return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); const { go, budgets, workspace } = body.data; const usageURL = URL.parse(workspace.usageURL); const externalUsage = diff --git a/packages/shared/src/editor.ts b/packages/shared/src/editor.ts index 902e06bd7f98..544da3d67e98 100644 --- a/packages/shared/src/editor.ts +++ b/packages/shared/src/editor.ts @@ -37,9 +37,10 @@ const isVersionedBundle = (entry: string, name: string) => { return /^\d[\d.]*$/.test(entry.slice(name.length + 1, -".app".length)); }; -// OpenZFS's event daemon is also named zed; it rejects `--version` instead of starting. -const isZedEditor = Effect.fn("editor.isZedEditor")( - function* (command: string) { +// OpenZFS's event daemon is also named zed, and the Cursor Agent CLI installs a cursor script +// that fails without an IDE behind it; both reject `--version` instead of starting. +const isEditorCommand = Effect.fn("editor.isEditorCommand")( + function* (command: string, isZed: boolean) { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const handle = yield* spawner.spawn( ChildProcess.make(command, ["--version"], { @@ -52,10 +53,12 @@ const isZedEditor = Effect.fn("editor.isZedEditor")( [handle.stdout.pipe(Stream.decodeText(), Stream.runHead), handle.exitCode], { concurrency: "unbounded" }, ); - return exitCode === 0 && Option.getOrElse(stdout, () => "").startsWith("Zed"); + return exitCode === 0 && (!isZed || Option.getOrElse(stdout, () => "").startsWith("Zed")); }, Effect.scoped, - Effect.timeout("2 seconds"), + // A slow first start after an update must not hide a working Cursor. + (probe, _command, isZed) => + Effect.timeoutOrElse(probe, { duration: "2 seconds", orElse: () => Effect.succeed(!isZed) }), Effect.catchCause(() => Effect.succeed(false)), ); @@ -69,6 +72,7 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun // Prefer Zed's macOS bundle because OpenZFS also installs a zed executable. const preferBundle = platform === "darwin" && editor.id === "zed"; const preferZeditor = platform === "linux" && editor.id === "zed"; + const probeCursor = editor.id === "cursor" && platform !== "win32"; if (platform === "win32" && editor.id === "zed") { const isStable = (resolved: string) => !isPrereleaseZedPath(resolved); let firstCommand: string | undefined; @@ -83,7 +87,7 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun if (firstCommand === undefined && matches.length > 0) firstCommand = command; } if (firstCommand !== undefined) return Option.some({ command: firstCommand, baseArgs }); - } else if (!preferBundle && !preferZeditor) { + } else if (!preferBundle && !preferZeditor && !probeCursor) { for (const command of editor.commands) { if (yield* isCommandAvailable(command, { env })) return Option.some({ command, baseArgs }); } @@ -95,7 +99,7 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun const names = installNames[editor.id] ?? [editor.label]; const command = editor.commands[0]; const jetbrains = editor.launchStyle === "line-column"; - const candidates: string[] = []; + const candidates: string[] = probeCursor ? [...editor.commands] : []; let toolbox: { dir: string; suffix: string } | undefined; if (platform === "darwin") { @@ -216,14 +220,15 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun const probeZed = editor.id === "zed" && platform !== "win32"; const rejected = new Set(); for (const candidate of candidates) { - // OpenZFS zed can shadow the editor's zed in an earlier PATH entry. + // An earlier PATH entry can hold OpenZFS zed or the Cursor Agent CLI's cursor script. const matches = - probeZed && candidate === "zed" + (probeZed || probeCursor) && candidate === command ? yield* resolveCommandPaths(candidate, { env, until: () => false }) : [yield* resolveCommandPath(candidate, { env })]; for (const resolved of matches) { if (resolved === null || rejected.has(resolved)) continue; - if (probeZed && path.basename(candidate) === "zed" && !(yield* isZedEditor(resolved))) { + const probed = probeCursor || (probeZed && path.basename(candidate) === "zed"); + if (probed && !(yield* isEditorCommand(resolved, probeZed))) { rejected.add(resolved); continue; } diff --git a/packages/shared/src/relayClient.test.ts b/packages/shared/src/relayClient.test.ts index 594d5ad215b1..f317cc22b356 100644 --- a/packages/shared/src/relayClient.test.ts +++ b/packages/shared/src/relayClient.test.ts @@ -717,6 +717,45 @@ describe("RelayClient", () => { ); }); + it.effect.skipIf(windowsHost)( + "finds a PATH binary through an empty entry by its absolute path", + () => + run((baseDir) => + Effect.gen(function* () { + const cwd = `${baseDir}/work`; + const inCwd = `${cwd}/cloudflared`; + yield* writeExecutable(inCwd); + const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }); + const resolveWith = (searchPath: string) => { + const env = { PATH: searchPath }; + return manager.resolve.pipe( + Effect.provideService( + ConfigProvider.ConfigProvider, + ConfigProvider.fromEnv({ env }), + ), + Effect.provideService(HostProcess.Environment, env), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + }; + const found = { + status: "available", + executablePath: inCwd, + source: "path", + version: RelayClient.CLOUDFLARED_VERSION, + }; + + expect(yield* resolveWith(`:${baseDir}/missing`)).toEqual(found); + expect(yield* resolveWith(`${baseDir}/missing:`)).toEqual(found); + const missing = { status: "missing", version: RelayClient.CLOUDFLARED_VERSION }; + // An empty PATH searches nothing, not even the working directory. + expect(yield* resolveWith("")).toEqual(missing); + // A whitespace entry is not an empty one. + expect(yield* resolveWith(` :${baseDir}/missing`)).toEqual(missing); + expect(yield* resolveWith(`${baseDir}/missing: `)).toEqual(missing); + }), + ), + ); + it.effect.skipIf(windowsHost)("reports an outdated override as missing", () => { const versions: Record = {}; return run( diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.ts index 19e42955ea55..81838ea4f65a 100644 --- a/packages/shared/src/relayClient.ts +++ b/packages/shared/src/relayClient.ts @@ -374,13 +374,21 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function const resolvePathExecutable = Effect.gen(function* () { // Read hydrated PATH directly; ConfigProvider may have cached it before fixPath. - const pathValue = (yield* HostProcess.Environment).PATH?.trim(); + const rawPathValue = (yield* HostProcess.Environment).PATH; + // POSIX keeps the raw value, so trimming never turns " :/bin" into an empty entry. + const pathValue = platform === "win32" ? rawPathValue?.trim() : rawPathValue; if (!pathValue) return null; const delimiter = platform === "win32" ? ";" : ":"; + const cwd = yield* HostProcess.WorkingDirectory; for (const directory of pathValue.split(delimiter)) { + // POSIX shells search the working directory for an empty entry. Resolve it now: the + // connector may be launched from elsewhere. + const workingDirectoryEntry = directory === "" && platform !== "win32"; const trimmed = directory.trim().replace(/^"|"$/gu, ""); - if (trimmed.length === 0) continue; - const candidate = path.join(trimmed, executableFileName(platform)); + if (trimmed.length === 0 && !workingDirectoryEntry) continue; + const candidate = workingDirectoryEntry + ? path.resolve(cwd, executableFileName(platform)) + : path.join(trimmed, executableFileName(platform)); if (!(yield* isExecutableFile(candidate))) continue; const available = yield* compatibleCandidate(candidate, "path"); if (available) return available; diff --git a/patches/gt-react-native@11.4.18.patch b/patches/gt-react-native@11.4.18.patch new file mode 100644 index 000000000000..03480dff1935 --- /dev/null +++ b/patches/gt-react-native@11.4.18.patch @@ -0,0 +1,129 @@ +diff --git a/dist/commonjs/condition-store/NativeConditionStore.js b/dist/commonjs/condition-store/NativeConditionStore.js +index 83349e43d9cad0c02a5d076a56c66d7d26943206..ac31f5e92bdd3b9f1e3346e6800887bc85d934d3 100644 +--- a/dist/commonjs/condition-store/NativeConditionStore.js ++++ b/dist/commonjs/condition-store/NativeConditionStore.js +@@ -11,20 +11,21 @@ let _generaltranslation_react_core_pure = require("@generaltranslation/react-cor + */ + var NativeConditionStore = class { + customReload; ++ locale; + constructor(config) { + this.customReload = config._reload ?? (() => void 0); +- this.updateLocale(config.locale ?? require_utils_getLocale.getLocale()); ++ this.locale = require_utils_resolveLocale.resolveLocale(config.locale ?? require_utils_getLocale.getLocale()); ++ require_utils_nativeStore.nativeStoreSet(getLocaleStoreKey(), this.locale); + const region = require_utils_getInitialNativeConditions.getInitialRegion({ region: config.region }); + if (region !== void 0) this.updateRegion(region); + this.updateEnableI18n(require_utils_getInitialNativeConditions.getInitialEnableI18n({ enableI18n: config.enableI18n })); + } + getLocale = () => { +- return require_utils_getLocale.getLocale(); ++ return this.locale; + }; + setLocale = (locale) => { +- const nextLocale = require_utils_resolveLocale.resolveLocale(locale); +- require_utils_nativeStore.nativeStoreSet(getLocaleStoreKey(), nextLocale); +- this.reload({ locale: nextLocale }); ++ this.updateLocale(locale); ++ this.reload({ locale: this.locale }); + }; + getRegion = () => { + return require_utils_nativeStore.nativeStoreGet(getRegionStoreKey()) || void 0; +@@ -41,7 +42,8 @@ var NativeConditionStore = class { + this.reload({ enableI18n }); + }; + updateLocale = (locale) => { +- require_utils_nativeStore.nativeStoreSet(getLocaleStoreKey(), require_utils_resolveLocale.resolveLocale(locale)); ++ this.locale = require_utils_resolveLocale.resolveLocale(locale); ++ require_utils_nativeStore.nativeStoreSet(getLocaleStoreKey(), this.locale); + }; + updateRegion = (region) => { + require_utils_nativeStore.nativeStoreSet(getRegionStoreKey(), region ?? ""); +diff --git a/dist/module/condition-store/NativeConditionStore.js b/dist/module/condition-store/NativeConditionStore.js +index aeadfee50fb03ee827b9326486eb39ef46b0921c..3d08229ee6acd065c868a14a8647343e37286121 100644 +--- a/dist/module/condition-store/NativeConditionStore.js ++++ b/dist/module/condition-store/NativeConditionStore.js +@@ -9,20 +9,21 @@ import { getI18nConfig } from "@generaltranslation/react-core/pure"; + */ + var NativeConditionStore = class { + customReload; ++ locale; + constructor(config) { + this.customReload = config._reload ?? (() => void 0); +- this.updateLocale(config.locale ?? getLocale()); ++ this.locale = resolveLocale(config.locale ?? getLocale()); ++ nativeStoreSet(getLocaleStoreKey(), this.locale); + const region = getInitialRegion({ region: config.region }); + if (region !== void 0) this.updateRegion(region); + this.updateEnableI18n(getInitialEnableI18n({ enableI18n: config.enableI18n })); + } + getLocale = () => { +- return getLocale(); ++ return this.locale; + }; + setLocale = (locale) => { +- const nextLocale = resolveLocale(locale); +- nativeStoreSet(getLocaleStoreKey(), nextLocale); +- this.reload({ locale: nextLocale }); ++ this.updateLocale(locale); ++ this.reload({ locale: this.locale }); + }; + getRegion = () => { + return nativeStoreGet(getRegionStoreKey()) || void 0; +@@ -39,7 +40,8 @@ var NativeConditionStore = class { + this.reload({ enableI18n }); + }; + updateLocale = (locale) => { +- nativeStoreSet(getLocaleStoreKey(), resolveLocale(locale)); ++ this.locale = resolveLocale(locale); ++ nativeStoreSet(getLocaleStoreKey(), this.locale); + }; + updateRegion = (region) => { + nativeStoreSet(getRegionStoreKey(), region ?? ""); +diff --git a/src/condition-store/NativeConditionStore.ts b/src/condition-store/NativeConditionStore.ts +index 3f300ed703db4d35e2118bbfe01430f370201f9e..18c3af21acaf3e6b4c7de2b8341c6847f8de1b73 100644 +--- a/src/condition-store/NativeConditionStore.ts ++++ b/src/condition-store/NativeConditionStore.ts +@@ -29,11 +29,14 @@ export type ReloadType = (state: NativeConditionStoreState) => void; + */ + export class NativeConditionStore implements WritableConditionStoreInterface { + private customReload: ReloadType; ++ private locale: string; + + constructor(config: NativeConditionStoreParams) { + this.customReload = config._reload ?? (() => undefined); + +- this.updateLocale(config.locale ?? getLocale()); ++ // Android's void TurboModule setter writes asynchronously. ++ this.locale = resolveLocale(config.locale ?? getLocale()); ++ nativeStoreSet(getLocaleStoreKey(), this.locale); + const region = getInitialRegion({ + region: config.region, + }); +@@ -48,13 +51,12 @@ export class NativeConditionStore implements WritableConditionStoreInterface { + } + + getLocale = (): string => { +- return getLocale(); ++ return this.locale; + }; + + setLocale = (locale: LocaleCandidates): void => { +- const nextLocale = resolveLocale(locale); +- nativeStoreSet(getLocaleStoreKey(), nextLocale); +- this.reload({ locale: nextLocale }); ++ this.updateLocale(locale); ++ this.reload({ locale: this.locale }); + }; + + getRegion = (): string | undefined => { +@@ -76,7 +78,8 @@ export class NativeConditionStore implements WritableConditionStoreInterface { + }; + + updateLocale = (locale: LocaleCandidates): void => { +- nativeStoreSet(getLocaleStoreKey(), resolveLocale(locale)); ++ this.locale = resolveLocale(locale); ++ nativeStoreSet(getLocaleStoreKey(), this.locale); + }; + + updateRegion = (region: string | undefined): void => { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0827f79757d7..32cb31a1adbb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -296,6 +296,7 @@ overrides: react-native-pdf-jsi: 6.1.0 react-native-webview: 14.0.1 react-native-svg: 15.16.1 + gt-react-native: 11.4.18 app-builder-lib: 26.16.1 electron-updater: 6.8.9 expo-modules-core: 58.0.30 @@ -385,6 +386,7 @@ patchedDependencies: expo-sharing@58.0.22: 321a86e1471e34c53f1f2937fbb4304ea3f7b7a78ad9e4d35febc2b9e73e9688 expo-video@58.0.13: e80ec3ef8c4af50a607beea1c0917e71ba679844efdb702b45d17a5f03cf466c expo-widgets@58.0.27: 0e26817ca487a5156bcc9499f7db2e99a7d102f4a53b6b738f00552958774c86 + gt-react-native@11.4.18: 9e9babb38642464db18e12d1a9f3531acda06056cfee82ee0261ba8bdc1aefaa mdast-util-math@3.0.0: afe6b2c89e1eaddfd3c90cf2723f12c9a17d513e65beff51653781486013251c mdast-util-to-hast@13.2.1: 57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1 micromark-extension-gfm-table@2.1.1: 9ad23a530e45d9f83cba1da8654fe16d5af8b59d5c73d5c7a7c91fd25b9be1d8 @@ -749,7 +751,7 @@ importers: version: 58.0.27(patch_hash=0e26817ca487a5156bcc9499f7db2e99a7d102f4a53b6b738f00552958774c86)(@babel/core@7.29.7(supports-color@8.1.1))(expo@58.0.23)(react-dom@19.3.0(react@19.3.0))(react-native-worklets@0.13.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)(supports-color@8.1.1))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) gt-react-native: specifier: 11.4.18 - version: 11.4.18(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + version: 11.4.18(patch_hash=9e9babb38642464db18e12d1a9f3531acda06056cfee82ee0261ba8bdc1aefaa)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) pele: specifier: 'catalog:' version: 1.8.0 @@ -13148,10 +13150,12 @@ packages: yuku-core@0.19.0: resolution: {integrity: sha512-kYK9e1XdfirNhkipzW0wmMcSWcVF/CWnuugodfVYRCUwvoBefweL9HzB96OiKEhsx78V5WbUxbJqlizMX869Qg==} engines: {node: '>=14.18.0'} + deprecated: 'Yuku is now one package with one core. Use "yuku" instead: https://yuku.fyi/javascript/. Existing installs keep working but get no more fixes.' yuku-parser@0.19.0: resolution: {integrity: sha512-XrBh9ZiQK5mJVRxZBAvD6LwRyAYrK3MFtH3+onyuxFL5hFD44EC3QOmIC1FjTj6H2MMwq46/NAI+NZxLZPZgxg==} engines: {node: '>=14.18.0'} + deprecated: 'Yuku is now one package with one core. Use "yuku" instead: https://yuku.fyi/javascript/. Existing installs keep working but get no more fixes.' zod-to-json-schema@3.25.2: resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==} @@ -20127,7 +20131,7 @@ snapshots: '@generaltranslation/format': 0.1.9 generaltranslation: 9.5.9 - gt-react-native@11.4.18(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0): + gt-react-native@11.4.18(patch_hash=9e9babb38642464db18e12d1a9f3531acda06056cfee82ee0261ba8bdc1aefaa)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0): dependencies: '@formatjs/intl-datetimeformat': 6.18.2 '@formatjs/intl-displaynames': 6.8.13 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index fdaafa748a67..d90784356120 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -128,6 +128,7 @@ overrides: react-native-pdf-jsi: 6.1.0 react-native-webview: 14.0.1 react-native-svg: 15.16.1 + gt-react-native: 11.4.18 app-builder-lib: 26.16.1 electron-updater: 6.8.9 expo-modules-core: 58.0.30 @@ -285,6 +286,9 @@ patchedDependencies: react-native-svg@15.16.1: patches/react-native-svg@15.16.1.patch # Android: double-tap zoom no longer cancels itself, and taps near a link open it. react-native-pdf-jsi@6.1.0: patches/react-native-pdf-jsi@6.1.0.patch + # Android: a language change applies at once instead of reading back the old locale + # before the async native write lands. + gt-react-native@11.4.18: patches/gt-react-native@11.4.18.patch # The MCP Events extension (SEP-3415) on effect/ai, until Effect ships it. effect@4.1.5: patches/effect@4.1.5.patch diff --git a/scripts/scenarios/agent-browser-devtools-port-not-a-server.e2e.ts b/scripts/scenarios/agent-browser-devtools-port-not-a-server.e2e.ts new file mode 100644 index 000000000000..a06708901bd7 --- /dev/null +++ b/scripts/scenarios/agent-browser-devtools-port-not-a-server.e2e.ts @@ -0,0 +1,74 @@ +import * as NodeNet from "node:net"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Option from "effect/Option"; +import * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +import { ScenarioError } from "./shell.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +// Serves on the port its last argument ends in, and prints once it listens. +const LISTENER = `require("node:http").createServer((_, res) => res.end("ok")).listen(Number(process.argv.at(-1).split("=").at(-1)), "127.0.0.1", () => console.log("listening"))`; + +const freePort = () => + new Promise((resolve, reject) => { + const server = NodeNet.createServer().listen(0, "127.0.0.1", () => { + const address = server.address(); + server.close(() => + typeof address === "object" && address !== null + ? resolve(address.port) + : reject(new Error("no port")), + ); + }); + }); + +/** A listener started as an agent's shell starts one: with the thread in its environment. */ +const listen = Effect.fn("scenario.listen")(function* (threadId: string, arg: string) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const hostEnvironment = yield* HostProcess.Environment; + const child = yield* spawner.spawn( + ChildProcess.make(yield* HostProcess.ExecutablePath, ["-e", LISTENER, "--", arg], { + env: { PATH: hostEnvironment.PATH, T3CODE_THREAD_ID: threadId }, + extendEnv: false, + stdin: "ignore", + stdout: "pipe", + stderr: "ignore", + }), + ); + const output = yield* child.stdout.pipe(Stream.decodeText(), Stream.runHead); + if (!Option.getOrElse(output, () => "").includes("listening")) { + return yield* new ScenarioError({ message: `The listener for ${arg} exited before listening` }); + } +}); + +test( + "An agent browser's DevTools port is not listed with the thread's servers", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Dev server", messages: ["Start"] }); + const [serverPort, devToolsPort] = [await freePort(), await freePort()]; + const scope = await runPromise(Scope.make()); + try { + await runPromise( + Effect.all([ + listen(thread.threadId, `${serverPort}`), + listen(thread.threadId, `--remote-debugging-port=${devToolsPort}`), + ]).pipe(Scope.provide(scope)), + ); + await browser.setViewport({ width: 1920, height: 1000 }); + await t3.open(thread); + + const servers = screen.getByRole("region", "Servers"); + await servers.getByText(`localhost:${serverPort}`).waitFor({ timeout: 60_000 }); + await app.screenshot("thread-servers"); + await expect(servers.getByText(`localhost:${devToolsPort}`)).toHaveCount(0); + } finally { + await runPromise(Scope.close(scope, Exit.void)); + } + }, +); diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index c11cfca1589a..296320bbc1e2 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -39,8 +39,41 @@ const Soak = Schema.Struct({ rssMBPerHour: Schema.Number, }); +const MachineState = Schema.Struct({ + /** The highest 1-minute load average read through the run; none on Windows. */ + load1: Schema.NullOr(Schema.Number), + /** Cores other node, T3 and agent processes kept busy over the run; Linux only. */ + otherCpuCores: Schema.NullOr(Schema.Number), + minutes: Schema.Number, +}); +export type MachineState = typeof MachineState.Type; + +const WorkingPoint = Schema.Struct({ + ...Window.fields, + /** Turns finished inside the window, per minute; higher is better. */ + turnsPerMin: Schema.Number, + /** Send to the agent's first API request. */ + toRequestMs: Spread, + /** The turn's last reply byte to the client seeing the run end. */ + turnEndMs: Spread, + /** Send to the client seeing the run end. */ + turnMs: Spread, +}); +export type WorkingPoint = typeof WorkingPoint.Type; + +const Reconnect = Schema.Struct({ + clients: Schema.Number, + threadsPerClient: Schema.optional(Schema.Number), + /** Drop to every subscription delivering its snapshot again. */ + resubscribedMs: Schema.Number, + loopDelayP99Ms: Schema.Number, + loopDelayMaxMs: Schema.Number, +}); + /** One pass over the scenarios. */ export const Measured = Schema.Struct({ + /** What else the machine was doing during the pass; never compared, only warned about. */ + machine: Schema.optional(MachineState), startup: Schema.optional(Schema.Struct({ readyMs: Schema.Number })), rest: Schema.optional(Window), firstWord: Schema.optional(Schema.Struct({ inPlace: FirstWord, worktree: FirstWord })), @@ -53,13 +86,25 @@ export const Measured = Schema.Struct({ Schema.Struct({ /** The quiet window by subscribed thread count. */ attached: Schema.Record(Schema.String, Window), - /** Every client drops and reconnects at once. */ - storm: Schema.Struct({ - clients: Schema.Number, - resubscribedMs: Schema.Number, - loopDelayP99Ms: Schema.Number, - loopDelayMaxMs: Schema.Number, - }), + /** A user's few devices, each holding the shell, VCS status and threads, drop and reconnect. */ + reconnect: Schema.optional(Reconnect), + /** With --stress: 20 clients holding one thread each drop and reconnect at once. */ + storm: Schema.optional(Reconnect), + }), + ), + /** + * N threads in worktrees of their own run editing turns back to back, all at once, with one + * web-like client subscribed to all of them. The scenario to steer server performance by. + */ + working: Schema.optional( + Schema.Struct({ + /** Each window by the number of threads working in it. */ + active: Schema.Record(Schema.String, WorkingPoint), + /** Fits over the windows: what each additional working thread costs. */ + heapMBPerThread: Schema.Number, + rssMBPerThread: Schema.Number, + cpuPctPerThread: Schema.Number, + loopDelayP99MsPerThread: Schema.Number, }), ), /** 50 short turns back to back on one thread. */ @@ -202,20 +247,155 @@ export function flatten(measured: Measured): Map { return values; } -function noiseFloor(metric: string) { - if (metric.startsWith("scaling.")) return metric.endsWith("cpuPctPerThread") ? 0.2 : 2; - if (metric.startsWith("soak.")) return 20; - if (metric.endsWith("cpuPct")) return 1; - if (metric.endsWith("wakeupsPerSec")) return 20; - if (metric.endsWith("MB")) return 15; - if (metric.endsWith("KB")) return 20; - if (metric.includes(".shellMs.") || metric.includes(".openMs.")) return 50; - if (metric.endsWith("loopDelayP50Ms")) return 2; - if (metric.endsWith("loopDelayP99Ms")) return 5; - if (metric.endsWith("loopDelayMaxMs")) return 20; - if (metric.endsWith("gcPauseMs")) return 10; - if (metric.endsWith("gcCount")) return 20; - return 300; +/** + * How far a metric moves between runs of the same commit, and whether it moves little enough to + * gate on. First match wins. Re-derive from A/A files with `server-metrics noise`; see + * docs/internals/performance-regressions.md for the runs these came from. + */ +export interface NoiseRule { + readonly pattern: RegExp; + /** Absolute change a metric must clear on top of the relative threshold. */ + readonly floor: number; + /** False for metrics an A/A run moves too far to gate on: shown, never counted. */ + readonly gate: boolean; +} + +/** Shown, never counted: these A/A intervals were wider than half the metric (see `noise`). */ +const informational = (pattern: RegExp): NoiseRule => ({ pattern, floor: 0, gate: false }); + +// Estimated from A/A runs on cups (16 cores, load 1 to 20) on 2026-11-23, with and without the +// agent scope, rounded up and taking the larger of the two. +// busy and soak had no A/A run and keep the earlier floors. +export const NOISE_RULES: ReadonlyArray = [ + informational(/loopDelayP50Ms$/), + informational(/^(rest|quiet|streaming|clients\.attached\.\d+)\.loopDelay(P99|Max)Ms$/), + informational(/^(rest|quiet|clients\.attached\.\d+)\.gc(Count|PauseMs)$/), + informational(/^(streaming|pipeline)\.gcPauseMs$/), + informational( + /^(pipeline\.loopDelayMaxMs|clients\.(storm|reconnect)\.loopDelayP99Ms|quiet\.cpuPct)$/, + ), + informational(/^scaling\.(cpuPct|wakeups)PerThread$/), + informational(/^clients\.attached\.\d+\.(cpuPct|wakeupsPerSec)$/), + informational(/^(firstWord\..*|pipeline\.turnEndMs)\.p90$/), + { pattern: /^scaling\.heapMBPerThread$/, floor: 0.06, gate: true }, + { pattern: /^scaling\.rssMBPerThread$/, floor: 0.2, gate: true }, + { pattern: /^soak\./, floor: 20, gate: true }, + informational(/^working\.(cpuPct|loopDelayP99Ms)PerThread$/), + informational(/^working\.active\.\d+\.(wakeupsPerSec|loopDelayMaxMs|gcPauseMs)$/), + { pattern: /^working\.heapMBPerThread$/, floor: 0.06, gate: true }, + { pattern: /^working\.rssMBPerThread$/, floor: 0.2, gate: true }, + { pattern: /^working\.active\.\d+\.turnsPerMin$/, floor: 4, gate: true }, + { pattern: /^working\.active\.\d+\.toRequestMs\.median$/, floor: 1_100, gate: true }, + { pattern: /^working\.active\.\d+\.turnEndMs\.median$/, floor: 1_700, gate: true }, + { + pattern: /^working\.active\.\d+\.(toRequestMs\.p90|turnMs\.median)$/, + floor: 1_900, + gate: true, + }, + { pattern: /^working\.active\.\d+\.turnEndMs\.p90$/, floor: 2_200, gate: true }, + { pattern: /^working\.active\.\d+\.turnMs\.p90$/, floor: 2_800, gate: true }, + // Peak RSS while 20 agents run swings by a checkpoint's git children; the settled RSS does not. + { pattern: /^working\.active\.\d+\.rssPeakMB$/, floor: 170, gate: true }, + { pattern: /^working\.active\.\d+\.(cpuPct|loopDelayP99Ms)$/, floor: 5, gate: true }, + { pattern: /^working\.active\.\d+\.gcCount$/, floor: 8, gate: true }, + { pattern: /^startup\.readyMs$/, floor: 600, gate: true }, + { pattern: /^firstWord\./, floor: 600, gate: true }, + { pattern: /^pipeline\.(toRequestMs|turnEndMs)\.median$/, floor: 300, gate: true }, + { pattern: /^pipeline\.(toRequestMs\.p90|msPerTurn)$/, floor: 600, gate: true }, + // The reconnect had no A/A run yet and takes the storm's floors. + { pattern: /^clients\.(storm|reconnect)\.resubscribedMs$/, floor: 200, gate: true }, + { pattern: /^rest\.cpuPct$/, floor: 1, gate: true }, + { pattern: /cpuPct$/, floor: 3.5, gate: true }, + { pattern: /^(rest|quiet)\.wakeupsPerSec$/, floor: 12, gate: true }, + { pattern: /wakeupsPerSec$/, floor: 110, gate: true }, + { pattern: /rssPeakMB$/, floor: 16, gate: true }, + { pattern: /rssMB$/, floor: 4, gate: true }, + { pattern: /heapAfterGcMB$/, floor: 1, gate: true }, + { pattern: /MB$/, floor: 15, gate: true }, + { pattern: /KB$/, floor: 20, gate: true }, + { pattern: /\.(shellMs|openMs)\./, floor: 50, gate: true }, + { pattern: /loopDelayP99Ms$/, floor: 3, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 22, gate: true }, + { pattern: /gcPauseMs$/, floor: 55, gate: true }, + { pattern: /gcCount$/, floor: 6, gate: true }, + { pattern: /./, floor: 300, gate: true }, +]; + +export function noiseRule(metric: string, rules: ReadonlyArray = NOISE_RULES) { + return rules.find((rule) => rule.pattern.test(metric)) ?? { floor: 0, gate: true }; +} + +/** An error and the errors it wraps as one line, outermost first, repeats left out. */ +export function describeFailure(error: unknown): string { + const parts: string[] = []; + const seen = new Set(); + for (let at = error; at !== undefined && at !== null && !seen.has(at);) { + seen.add(at); + if (typeof at !== "object") { + parts.push(String(at)); + break; + } + const tag = "_tag" in at && typeof at._tag === "string" ? at._tag : undefined; + const message = "message" in at && typeof at.message === "string" ? at.message.trim() : ""; + const text = message || tag || String(at); + if (!parts.some((part) => part.includes(text))) parts.push(text); + at = "cause" in at ? at.cause : undefined; + } + return parts.join(": "); +} + +/** Why two files cannot be compared at all: a quick run measures shorter windows than a full one. */ +export function profileMismatch(before: ServerMetrics, after: ServerMetrics) { + const profile = (metrics: ServerMetrics) => metrics.meta.profile ?? "full"; + return profile(before) === profile(after) + ? undefined + : `before is a ${profile(before)} run and after a ${profile(after)} one; compare quick runs only with quick runs`; +} + +/** Throughput, where a drop is the regression. */ +export const higherIsBetter = (metric: string) => metric.endsWith("PerMin"); + +/** Fields that describe a run rather than measure it. */ +const isMetric = (metric: string) => + !( + metric === "soak.minutes" || + metric.startsWith("machine.") || + metric.endsWith("loopSamples") || + metric === "busy.projects" || + metric === "busy.ballastMB" || + metric.endsWith(".clients") || + metric.endsWith(".threadsPerClient") || + metric.endsWith(".threads") || + metric === "busy.largeThread.messages" || + metric.startsWith("scaling.points") + ); + +/** + * A run is loaded when other node, T3 and agent processes kept this share of the cores busy, or, + * where that is unknown, when the 1-minute load passed this much per CPU. The load counts the + * run's own agents too, so it is only the fallback. + */ +export const HEAVY_LOAD_PER_CPU = 0.75; +export const HEAVY_OTHER_CPU_SHARE = 0.25; + +/** One line per side whose runs shared the machine with heavy load, so its numbers are suspect. */ +export function loadWarnings(side: string, metrics: ServerMetrics) { + const cpus = typeof metrics.meta.cpus === "number" ? metrics.meta.cpus : null; + if (cpus === null) return []; + const loaded = metrics.runs.flatMap(({ machine }) => + machine && + (machine.otherCpuCores === null + ? (machine.load1 ?? 0) >= cpus * HEAVY_LOAD_PER_CPU + : machine.otherCpuCores >= cpus * HEAVY_OTHER_CPU_SHARE) + ? [machine] + : [], + ); + if (loaded.length === 0) return []; + const worstLoad = Math.max(...loaded.map(({ load1 }) => load1 ?? 0)); + const worstOther = Math.max(...loaded.map(({ otherCpuCores }) => otherCpuCores ?? 0)); + return [ + `${side} ran under heavy load in ${loaded.length} of ${metrics.runs.length} runs (load up to ${worstLoad} on ${cpus} CPUs, other node/T3/agent processes up to ${worstOther} cores); rerun on a quieter machine before trusting a change`, + ]; } const median = (values: ReadonlyArray) => { @@ -241,20 +421,137 @@ export function bootstrapMedianDifference(a: ReadonlyArray, b: ReadonlyA return [differences[49]!, differences[1_949]!] as const; } -export function compareMetrics(before: ServerMetrics, after: ServerMetrics, threshold = 10) { - const collect = (metrics: ServerMetrics) => { - const values = new Map(); - for (const run of metrics.runs) { - for (const [metric, value] of flatten(run)) { - values.set(metric, [...(values.get(metric) ?? []), value]); - } +/** + * False for a wakeup count where only one side had the delay sampler: wakeups include the + * sampler's only when `loopSamples` sits beside them, so the two measured different things. The + * per-thread fit comes from the quiet windows, so it follows their method. + */ +function sameWakeupMethod( + metric: string, + a: ReadonlyMap, + b: ReadonlyMap, +) { + const window = + metric === "scaling.wakeupsPerThread" + ? "quiet." + : metric.endsWith("wakeupsPerSec") + ? metric.slice(0, -"wakeupsPerSec".length) + : ""; + return !window || a.has(`${window}loopSamples`) === b.has(`${window}loopSamples`); +} + +/** CPU seconds spent between two reads keyed by pid and start time; a process that exited is lost. */ +export function competingBetween( + before: ReadonlyMap, + after: ReadonlyMap, +) { + return [...after].reduce((total, [key, seconds]) => total + seconds - (before.get(key) ?? 0), 0); +} + +/** Why a directory is not an A/A pair: its files must record one and the same commit. */ +export function noisePairProblem(dir: string, a: ServerMetrics, b: ServerMetrics) { + const commits = [a.meta.commit, b.meta.commit]; + if (commits.some((commit) => typeof commit !== "string" || commit === "")) { + return `${dir}: a.json or b.json records no commit, so it cannot be shown to be an A/A run`; + } + return commits[0] === commits[1] + ? undefined + : `${dir}: a.json is ${commits[0]} and b.json ${commits[1]}; noise floors need one commit against itself`; +} + +/** Every metric's values across a file's runs. */ +const collect = (metrics: ServerMetrics) => { + const values = new Map(); + for (const run of metrics.runs) { + for (const [metric, value] of flatten(run)) { + values.set(metric, [...(values.get(metric) ?? []), value]); } - return values; - }; + } + return values; +}; + +/** Two significant digits, rounded up, so a derived floor never sits under what was seen. */ +const ceilSignificant = (value: number) => { + if (value <= 0) return 0; + const step = 10 ** (Math.floor(Math.log10(value)) - 1); + return round(Math.ceil(value / step) * step, 6); +}; + +/** An A/A interval wider than this share of a metric's median makes it informational. */ +export const NOISY_SHARE = 0.5; + +export interface NoiseRow { + readonly metric: string; + readonly median: number; + /** The widest half-width of an A/A pair's 95% interval of the median difference. */ + readonly halfWidth: number; + /** The largest |median(A) - median(B)| over the A/A pairs. */ + readonly aaDifference: number; + readonly floor: number; + readonly suggestedFloor: number; + readonly gate: boolean; + readonly suggestedGate: boolean; +} + +/** + * Each metric's A/A spread as `compare` sees it: the 95% interval of the median difference. The + * estimated floor (half the widest half-width, or the A/A median difference if larger) is how far + * an A/A interval must miss zero to flag. It is an estimate, not a bound. + */ +export function noiseReport( + pairs: ReadonlyArray, + rules: ReadonlyArray = NOISE_RULES, +) { + const found = new Map(); + for (const [before, after] of pairs) { + const a = collect(before); + const b = collect(after); + for (const [metric, x] of a) { + const y = b.get(metric); + if (!y || !isMetric(metric) || !sameWakeupMethod(metric, a, b)) continue; + const [low, high] = bootstrapMedianDifference(x, y); + const entry = found.get(metric) ?? { medians: [], halfWidth: 0, aaDifference: 0 }; + entry.medians.push(median([...x, ...y])); + entry.halfWidth = Math.max(entry.halfWidth, (high - low) / 2); + entry.aaDifference = Math.max(entry.aaDifference, Math.abs(median(y) - median(x))); + found.set(metric, entry); + } + } + const rows: NoiseRow[] = [...found].map(([metric, entry]) => { + const middle = median(entry.medians); + const rule = noiseRule(metric, rules); + return { + metric, + median: round(middle, 2), + halfWidth: round(entry.halfWidth, 2), + aaDifference: round(entry.aaDifference, 2), + floor: rule.floor, + suggestedFloor: ceilSignificant(Math.max(entry.halfWidth / 2, entry.aaDifference)), + gate: rule.gate, + suggestedGate: entry.halfWidth <= Math.abs(middle) * NOISY_SHARE, + }; + }); + const lines = [ + "| metric | median | ± A/A interval | A/A diff | floor | estimated floor | gated | suggest gating |", + "| :-- | --: | --: | --: | --: | --: | :-: | :-: |", + ...rows.map( + (row) => + `| ${row.metric} | ${row.median} | ${row.halfWidth} | ${row.aaDifference} | ${row.floor} | ${row.suggestedFloor}${row.suggestedFloor > row.floor ? " ⚠" : ""} | ${row.gate ? "yes" : "no"} | ${row.suggestedGate ? "yes" : "no"} |`, + ), + ]; + return { rows, table: lines.join("\n") }; +} + +export function compareMetrics( + before: ServerMetrics, + after: ServerMetrics, + threshold = 10, + rules: ReadonlyArray = NOISE_RULES, +) { const a = collect(before); const b = collect(after); const lines = [ - "### Server metrics (lower is better)", + "### Server metrics (lower is better, except throughput per minute)", "", `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs), ${after.meta.platform}${after.meta.noAgentScope ? ", no agent scope" : ""}`, "", @@ -264,18 +561,9 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre const regressed: string[] = []; const improved: string[] = []; let compared = 0; + const informational: string[] = []; for (const metric of new Set([...a.keys(), ...b.keys()])) { - if ( - metric === "soak.minutes" || - metric.endsWith("loopSamples") || - metric === "busy.projects" || - metric === "busy.ballastMB" || - metric === "clients.storm.clients" || - metric === "busy.largeThread.messages" || - metric.startsWith("scaling.points") - ) { - continue; - } + if (!isMetric(metric)) continue; const x = a.get(metric); const y = b.get(metric); if (!x || !y) { @@ -285,13 +573,7 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre // Wakeups include the delay sampler's only when `loopSamples` sits beside them, so a file // from before the sampler and one from after measured different things. The per-thread fit // comes from the quiet windows. - const window = - metric === "scaling.wakeupsPerThread" - ? "quiet." - : metric.endsWith("wakeupsPerSec") - ? metric.slice(0, -"wakeupsPerSec".length) - : ""; - if (window && a.has(`${window}loopSamples`) !== b.has(`${window}loopSamples`)) { + if (!sameWakeupMethod(metric, a, b)) { lines.push(`| ${metric} | ${median(x)} | ${median(y)} | not comparable | | |`); continue; } @@ -299,12 +581,16 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre const mx = median(x); const my = median(y); // A change counts only past both the relative threshold and the absolute noise floor. - const limit = Math.max(noiseFloor(metric), (Math.abs(mx) * threshold) / 100); + const rule = noiseRule(metric, rules); + const limit = Math.max(rule.floor, (Math.abs(mx) * threshold) / 100); const repeated = x.length > 1 && y.length > 1; const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx]; - const verdict = low > limit ? "worse" : high < -limit ? "better" : ""; - if (verdict === "worse") regressed.push(metric); - if (verdict === "better") improved.push(metric); + const up = low > limit ? "worse" : high < -limit ? "better" : ""; + const moved = higherIsBetter(metric) ? { worse: "better", better: "worse", "": "" }[up] : up; + if (moved && !rule.gate) informational.push(metric); + else if (moved === "worse") regressed.push(metric); + else if (moved === "better") improved.push(metric); + const verdict = rule.gate ? moved : moved ? `${moved} (noisy, not gated)` : "noisy"; const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100; const shown = Number.isFinite(percent) ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%` @@ -314,7 +600,8 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`, ); } - return { table: lines.join("\n"), regressed, improved, compared }; + const warnings = [...loadWarnings("before", before), ...loadWarnings("after", after)]; + return { table: lines.join("\n"), regressed, improved, informational, compared, warnings }; } const CallFrame = Schema.Struct({ diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 760c850dbbbe..d45e4d5c613a 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -3,10 +3,16 @@ import { describe, expect, it } from "vite-plus/test"; import { compareMetrics, + competingBetween, activityRenewalMissed, + describeFailure, heapGrowth, + loadWarnings, nextActivityReport, + noiseReport, + noisePairProblem, parsePsCpuTime, + profileMismatch, parseRunSelection, pathRewrites, pathSpellings, @@ -43,6 +49,17 @@ const base: Quiet = { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 }; const cpuRuns = (...values: number[]) => quietRuns(...values.map((cpuPct) => ({ ...base, cpuPct }))); +// Fixed floors, so these cases test how compare gates rather than the calibrated table. +const gatedRules = [ + { pattern: /cpuPct$/, floor: 1, gate: true }, + { pattern: /wakeupsPerSec$/, floor: 20, gate: true }, + { pattern: /MB$/, floor: 15, gate: true }, + { pattern: /loopDelayP99Ms$/, floor: 5, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 20, gate: true }, + { pattern: /gcPauseMs$/, floor: 10, gate: true }, + { pattern: /./, floor: 300, gate: true }, +]; + describe("compareMetrics", () => { it.each([ ["a CPU jump past both the percentage and the floor", { cpuPct: 18.6 }, ["quiet.cpuPct"], []], @@ -60,7 +77,12 @@ describe("compareMetrics", () => { ["quiet.rssPeakMB"], ], ])("one run each: %s", (_name, change, regressed, improved) => { - const result = compareMetrics(quietRuns(base), quietRuns({ ...base, ...change })); + const result = compareMetrics( + quietRuns(base), + quietRuns({ ...base, ...change }), + 10, + gatedRules, + ); expect(result.regressed).toEqual(regressed); expect(result.improved).toEqual(improved); }); @@ -75,10 +97,10 @@ describe("compareMetrics", () => { it("flags repeated runs only when the whole interval clears the limit", () => { const steady = cpuRuns(26.1, 27.4, 25.8); const fixed = cpuRuns(2.2, 2.5, 2.1); - expect(compareMetrics(steady, fixed).improved).toContain("quiet.cpuPct"); - expect(compareMetrics(fixed, steady).regressed).toContain("quiet.cpuPct"); + expect(compareMetrics(steady, fixed, 10, gatedRules).improved).toContain("quiet.cpuPct"); + expect(compareMetrics(fixed, steady, 10, gatedRules).regressed).toContain("quiet.cpuPct"); // The medians differ by 2.8 points, past the floor, but a resampled median can match. - expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9)).regressed).toEqual([]); + expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9), 10, gatedRules).regressed).toEqual([]); }); it("reads a file written before loop delay and GC were recorded", () => { @@ -129,6 +151,175 @@ describe("compareMetrics", () => { }); }); +describe("compareMetrics with noise rules", () => { + const rules = [ + { pattern: /cpuPct$/, floor: 1, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 20, gate: false }, + { pattern: /./, floor: 1_000, gate: true }, + ]; + it.each([ + ["a gated metric past its floor", { cpuPct: 5 }, ["quiet.cpuPct"], []], + ["an ungated metric far past its floor", { loopDelayMaxMs: 300 }, [], ["quiet.loopDelayMaxMs"]], + ["an ungated metric under its floor", { loopDelayMaxMs: 20 }, [], []], + ])("%s", (_name, change, regressed, informational) => { + const result = compareMetrics(quietRuns(base), quietRuns({ ...base, ...change }), 10, rules); + expect(result.regressed).toEqual(regressed); + expect(result.informational).toEqual(informational); + }); + + it("marks an ungated metric in the table either way", () => { + const result = compareMetrics(quietRuns(base), quietRuns(base), 10, rules); + expect(result.table).toContain("| quiet.loopDelayMaxMs | 8 | 8 | 0% | | noisy |"); + }); +}); + +describe("noisePairProblem", () => { + const at = (commit: string | null): ServerMetrics => ({ meta: { ...meta, commit }, runs: [] }); + it.each([ + ["one commit against itself", at("abc"), at("abc"), undefined], + [ + "an A/B directory", + at("abc"), + at("def"), + "ab-out: a.json is abc and b.json def; noise floors need one commit against itself", + ], + [ + "a file with no commit", + at(null), + at(null), + "ab-out: a.json or b.json records no commit, so it cannot be shown to be an A/A run", + ], + ])("%s", (_name, a, b, problem) => { + expect(noisePairProblem("ab-out", a, b)).toBe(problem); + }); +}); + +describe("competingBetween", () => { + it.each([ + ["a process that kept running", [["10:500", 900]], [["10:500", 960]], 60], + ["a new process, counted whole", [], [["11:700", 30]], 30], + ["a reused pid is a new process", [["10:500", 900]], [["10:800", 300]], 300], + ["a process that exited is lost", [["10:500", 900]], [], 0], + ] as const)("%s", (_name, before, after, seconds) => { + expect(competingBetween(new Map(before), new Map(after))).toBe(seconds); + }); +}); + +describe("loadWarnings", () => { + const loaded = (cpus: number | null, ...machines: Array<[number | null, number | null]>) => + ({ + meta: { ...meta, cpus }, + runs: machines.map(([load1, otherCpuCores]) => ({ + machine: { load1, otherCpuCores, minutes: 10 }, + })), + }) satisfies ServerMetrics; + it.each([ + ["a quiet machine", loaded(16, [4, 1], [5, 2]), 0], + ["load past 0.75 per CPU with other processes unknown", loaded(16, [4, null], [12.5, null]), 1], + ["high load from the run's own agents", loaded(16, [21, 1]), 0], + ["other processes on a quarter of the cores", loaded(16, [4, 4.1]), 1], + ["no CPU count", loaded(null, [40, 40]), 0], + ["no machine state, as in older files", { meta: { ...meta, cpus: 16 }, runs: [{}] }, 0], + ])("%s", (_name, metrics, count) => { + expect(loadWarnings("before", metrics)).toHaveLength(count); + }); + + it("names the worst run", () => { + expect(loadWarnings("after", loaded(16, [13, 4.5], [14.2, 5]))[0]).toContain( + "after ran under heavy load in 2 of 2 runs (load up to 14.2 on 16 CPUs, other node/T3/agent processes up to 5 cores)", + ); + }); + + it("is reported by compareMetrics", () => { + expect(compareMetrics(quietRuns(base), loaded(16, [20, null])).warnings).toHaveLength(1); + }); +}); + +describe("noiseReport", () => { + it.each([ + // Resampled medians differ by -0.3 to 1.1: half-width 0.7, so the floor is 0.35. + ["the A/A interval", cpuRuns(2, 2.2, 2.4), cpuRuns(2.1, 3.1, 2.3), 0.7, 0.1, 0.35], + // Constant sides: no interval, and medians 2 and 3.25 differ by 1.25. + ["the A/A median difference", cpuRuns(2, 2), cpuRuns(3.25, 3.25), 0, 1.25, 1.3], + ])("estimates a floor from %s, rounded up", (_name, a, b, halfWidth, aaDifference, floor) => { + const [row] = noiseReport([[a, b]]).rows.filter(({ metric }) => metric === "quiet.cpuPct"); + expect(row).toMatchObject({ halfWidth, aaDifference, suggestedFloor: floor }); + }); + + it("leaves out wakeups counted with the delay sampler on one side only", () => { + const sampled: ServerMetrics = { + meta, + runs: quietRuns({ ...base, wakeupsPerSec: 160 }).runs.map((run) => ({ + quiet: { ...run.quiet, loopSamples: 2_900 }, + })), + }; + const metrics = noiseReport([[quietRuns(base), sampled]]).rows.map(({ metric }) => metric); + expect(metrics).not.toContain("quiet.wakeupsPerSec"); + expect(metrics).toContain("quiet.cpuPct"); + }); + + it("takes the widest pair, and calls a metric noisy when its interval passes half its median", () => { + const quiet = [cpuRuns(2, 2.1), cpuRuns(2, 2.1)] as const; + const wild = [cpuRuns(1, 4), cpuRuns(2, 2)] as const; + const [row] = noiseReport([quiet, wild]).rows.filter(({ metric }) => metric === "quiet.cpuPct"); + expect(row?.halfWidth).toBe(1.5); + expect(row?.suggestedGate).toBe(false); + }); + + it("leaves out fields that describe a run", () => { + const withMachine = (metrics: ServerMetrics): ServerMetrics => ({ + ...metrics, + runs: metrics.runs.map((run) => ({ + ...run, + machine: { load1: 3, otherCpuCores: 1, minutes: 9 }, + })), + }); + const rows = noiseReport([[withMachine(cpuRuns(1)), withMachine(cpuRuns(1))]]).rows; + expect(rows.some(({ metric }) => metric.startsWith("machine."))).toBe(false); + }); +}); + +describe("compareMetrics on working throughput", () => { + const working = (turnsPerMin: number) => + ({ + meta, + runs: [ + { + working: { + active: { + "20": { + ...loopAtRest, + cpuPct: 90, + wakeupsPerSec: 1_600, + rssPeakMB: 700, + rssMB: 560, + heapAfterGcMB: 218, + turnsPerMin, + toRequestMs: { median: 4_000, p90: 9_000 }, + turnEndMs: { median: 16_000, p90: 25_000 }, + turnMs: { median: 24_000, p90: 36_000 }, + }, + }, + heapMBPerThread: 0.2, + rssMBPerThread: 0.8, + cpuPctPerThread: 0, + loopDelayP99MsPerThread: 0, + }, + }, + ], + }) satisfies ServerMetrics; + const rules = [{ pattern: /turnsPerMin$/, floor: 2, gate: true }]; + it.each([ + ["fewer turns a minute", 20, ["working.active.20.turnsPerMin"], []], + ["more turns a minute", 45, [], ["working.active.20.turnsPerMin"]], + ["a move under the floor", 34, [], []], + ])("%s", (_name, turnsPerMin, regressed, improved) => { + const result = compareMetrics(working(33), working(turnsPerMin), 5, rules); + expect(result.regressed).toEqual(regressed); + expect(result.improved).toEqual(improved); + }); +}); + describe("compareMetrics on the busy shell snapshot", () => { const window = { cpuPct: 1, wakeupsPerSec: 10, rssPeakMB: 500, rssMB: 500, heapAfterGcMB: 200 }; const busyRun = (shellMs: number, shellKB: number) => @@ -158,6 +349,41 @@ describe("compareMetrics on the busy shell snapshot", () => { }); }); +describe("describeFailure", () => { + it.each([ + ["a plain error", new Error("boom"), "boom"], + [ + "an RPC error wrapping the server's", + new Error("RpcClientError", { cause: new Error("Command x was already handled") }), + "RpcClientError: Command x was already handled", + ], + ["a tagged error with no message", { _tag: "TimeoutError" }, "TimeoutError"], + [ + "a cause that repeats its wrapper", + new Error("lost: gone", { cause: new Error("gone") }), + "lost: gone", + ], + ["a string", "exit 1", "exit 1"], + ])("%s", (_name, error, expected) => { + expect(describeFailure(error)).toBe(expected); + }); +}); + +describe("profileMismatch", () => { + const withProfile = (profile?: string): ServerMetrics => ({ + meta: profile === undefined ? meta : { ...meta, profile }, + runs: [], + }); + it.each([ + ["two full runs", withProfile("full"), withProfile("full"), false], + ["a file from before profiles, against a full run", withProfile(), withProfile("full"), false], + ["two quick runs", withProfile("quick"), withProfile("quick"), false], + ["a full run against a quick one", withProfile(), withProfile("quick"), true], + ])("%s", (_name, before, after, refused) => { + expect(profileMismatch(before, after) !== undefined).toBe(refused); + }); +}); + describe("heapGrowth", () => { it("lists only constructors that grew, small growth included", () => { const before = new Map([ diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 8ab475f38a5a..ef2b091607ce 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -13,12 +13,14 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; import * as Clock from "effect/Clock"; +import * as Cause from "effect/Cause"; import * as Console from "effect/Console"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -28,10 +30,14 @@ import * as Random from "effect/Random"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; import { Argument, Command, Flag } from "effect/cli"; import { + CommandId, + MessageId, + type OrchestrationV2ThreadStreamItem, ORCHESTRATION_PROTOCOL_HEADER, ORCHESTRATION_PROTOCOL_VERSION, ORCHESTRATION_PROTOCOL_VERSION_TEXT, @@ -54,10 +60,16 @@ import { run } from "./scenarios/shell.ts"; import { compareMetrics, CpuProfile, + describeFailure, HeapProfile, HeapSnapshot, heapByConstructor, heapGrowth, + competingBetween, + loadWarnings, + noiseReport, + noisePairProblem, + profileMismatch, round, ServerMetrics, slope, @@ -70,7 +82,9 @@ import { parseRunSelection, summarizeProfiles, type FirstWord, + type MachineState, type Measured, + type WorkingPoint, type ProfileSummary, type Window, } from "./server-metrics-report.ts"; @@ -78,9 +92,47 @@ import { const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)); const MODEL = "claude-haiku-4-5"; const SLOW_MARKER = "[[stream-slowly]]"; -/** Sequential turns in the pipeline scenario. */ -const PIPELINE_TURNS = 50; -/** Clients that drop and reconnect at once in the clients scenario. */ +/** A prompt holding this streams a reply that ends in a Write tool call, then a short answer. */ +const EDIT_MARKER = "[[edit-files]]"; +/** + * How long each scenario measures. `quick` keeps every scenario but shortens its windows, for a + * per-PR or nightly check; its numbers compare only with other quick runs. + */ +const PROFILES = { + full: { + /** Idle time before a quiet window, so startup and thread setup work has drained. */ + settleSeconds: 15, + windowSeconds: 30, + streamingSeconds: 60, + profileSeconds: 20, + /** Sequential turns in the pipeline scenario. */ + pipelineTurns: 50, + /** Threads working at once in each window of the working scenario. */ + workingThreads: [5, 10, 20], + workingWarmupSeconds: 10, + /** Long enough that most threads finish a turn inside it even at 20 working. */ + workingSeconds: 30, + threads: "0,5,10,20", + runs: 5, + }, + quick: { + settleSeconds: 5, + windowSeconds: 10, + streamingSeconds: 20, + profileSeconds: 5, + pipelineTurns: 15, + workingThreads: [5, 20], + workingWarmupSeconds: 5, + workingSeconds: 20, + threads: "0,10", + runs: 3, + }, +} as const; +type Profile = (typeof PROFILES)[keyof typeof PROFILES]; +/** A user's devices: clients that drop and reconnect at once, each holding this many threads. */ +const RECONNECT_CLIENTS = 3; +const RECONNECT_THREADS = 10; +/** Clients that drop and reconnect at once in the opt-in storm, each holding one thread. */ const STORM_CLIENTS = 20; /** Event-loop delay sampling interval; each sample wakes the loop once. */ const LOOP_RESOLUTION_MS = 10; @@ -122,6 +174,8 @@ interface ApiRequest { readonly agent: boolean; readonly stream: boolean; readonly marker: string | undefined; + /** The request carries a tool result, so it is a turn's follow-up rather than its start. */ + readonly toolResult: boolean; /** When the reply's last event was produced; streamed replies only. */ endedAt?: number; } @@ -130,8 +184,26 @@ const MessagesRequest = Schema.Struct({ stream: Schema.optional(Schema.Boolean), model: Schema.optional(Schema.String), tools: Schema.optional(Schema.Array(Schema.Unknown)), + messages: Schema.optional( + Schema.Array(Schema.Struct({ role: Schema.String, content: Schema.Unknown })), + ), }); +/** Whether the newest message hands back a tool's result. */ +const endsInToolResult = (messages: typeof MessagesRequest.Type.messages) => { + const content = messages?.at(-1)?.content; + return ( + Array.isArray(content) && + content.some( + (block: unknown) => + typeof block === "object" && + block !== null && + "type" in block && + block.type === "tool_result", + ) + ); +}; + /** Streams a canned reply to every Messages request; a prompt holding SLOW_MARKER streams slowly. */ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(function* () { const requests: ApiRequest[] = []; @@ -151,7 +223,9 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio Effect.orElseSucceed((): typeof MessagesRequest.Type => ({})), ); const streamed = body.stream === true; + const toolResult = endsInToolResult(body.messages); const entry: ApiRequest = { + toolResult, at: yield* nowMs, stream: streamed, // Title and branch-name jobs carry only their structured-output tool; the agent carries many. @@ -177,10 +251,13 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio const event = (name: string, data: object) => `event: ${name}\ndata: ${encodeJson({ type: name, ...data })}\n\n`; const slow = raw.includes(SLOW_MARKER); - const words = slow ? 2_000 : 40; + // An editing turn streams a longer first reply, then writes a file in the agent's directory. + const cwd = /Primary working directory: ([^\\"\n]+)/.exec(raw)?.[1]?.trim(); + const edit = entry.agent && raw.includes(EDIT_MARKER) && !toolResult && cwd !== undefined; + const words = slow ? 2_000 : edit ? 150 : 40; const deltas = Stream.range(0, words - 1).pipe( Stream.mapEffect((word) => - Effect.sleep(Duration.millis(slow ? 50 : 5)).pipe( + Effect.sleep(Duration.millis(slow ? 50 : edit ? 10 : 5)).pipe( Effect.as( event("content_block_delta", { index: 0, @@ -190,6 +267,43 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio ), ), ); + const toolCall = edit + ? Stream.make( + event("content_block_stop", { index: 0 }), + event("content_block_start", { + index: 1, + content_block: { + type: "tool_use", + id: `toolu_bench_${requests.length}`, + name: "Write", + input: {}, + }, + }), + event("content_block_delta", { + index: 1, + delta: { + type: "input_json_delta", + partial_json: encodeJson({ + file_path: `${cwd}/bench/${entry.marker ?? `turn-${requests.length}`}.md`, + content: Array.from({ length: 40 }, (_, line) => `line ${line} of ${id}`).join( + "\n", + ), + }), + }, + }), + event("content_block_stop", { index: 1 }), + event("message_delta", { + delta: { stop_reason: "tool_use", stop_sequence: null }, + usage: { output_tokens: words }, + }), + ) + : Stream.make( + event("content_block_stop", { index: 0 }), + event("message_delta", { + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { output_tokens: words }, + }), + ); const events = Stream.make( event("message_start", { message: { @@ -206,15 +320,7 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio event("content_block_start", { index: 0, content_block: { type: "text", text: "" } }), ).pipe( Stream.concat(deltas), - Stream.concat( - Stream.make( - event("content_block_stop", { index: 0 }), - event("message_delta", { - delta: { stop_reason: "end_turn", stop_sequence: null }, - usage: { output_tokens: words }, - }), - ), - ), + Stream.concat(toolCall), // Stamped as the last event is produced, so it is set before any client can see the end. Stream.concat( Stream.fromEffect( @@ -1122,6 +1228,11 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( server: Server, token: string, threadIds: ReadonlyArray, + /** Sees every item a thread subscription delivers, the snapshot included. */ + onThreadItem: ( + threadId: string, + item: OrchestrationV2ThreadStreamItem, + ) => Effect.Effect = () => Effect.void, ) { const http = yield* HttpClient.HttpClient; // Headers alone do not finish a request; the deadline covers the body too. @@ -1156,6 +1267,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( const ready = Effect.fn("serverMetrics.subscription")(function* ( stream: Stream.Stream, isReady: (item: A) => boolean, + onItem: (item: A) => Effect.Effect = () => Effect.void, ) { const synchronized = yield* Deferred.make(); const lose = (message: string) => @@ -1164,7 +1276,9 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( ); yield* stream.pipe( Stream.runForEach((item) => - isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void, + onItem(item).pipe( + Effect.andThen(isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void), + ), ), Effect.andThen(lose("a subscription ended")), Effect.catchCause(() => lose("a subscription failed")), @@ -1238,6 +1352,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( acceptDedupedBodies: true, }), synchronized, + (item) => onThreadItem(threadId, item), ), )), ]; @@ -1248,6 +1363,19 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }), ); return { + /** Sends a message the way the composer does, starting a turn at once. */ + send: (threadId: string, messageId: string, text: string) => + client["orchestration.dispatchCommand"]({ + type: "message.dispatch", + commandId: CommandId.make(messageId), + threadId: ThreadId.make(threadId), + messageId: MessageId.make(messageId), + text, + attachments: [], + createdBy: "user", + creationSource: "web", + dispatchMode: { type: "start_immediately" }, + }), /** Fails if any of this client's subscriptions or reports was lost since it attached. */ healthy: Effect.flatMap(Ref.get(lost), (message) => message === undefined ? Effect.void : Effect.fail(new MetricsError({ message })), @@ -1255,6 +1383,48 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }; }); +/** + * Attaches one client per entry, each holding the shell, VCS status and its threads, lets them + * settle, then drops all of them at once and reconnects them: the time until every subscription + * delivered its snapshot again, and the loop delay across it. + */ +const reconnectAll = Effect.fn("serverMetrics.reconnectAll")(function* ( + server: Server, + token: string, + clientThreads: ReadonlyArray>, +) { + // Each client gets its own scope so they can be dropped on cue; the server's scope still closes + // any left open when a step fails or is interrupted. + const clientScope = Effect.acquireRelease(Scope.make(), (scope, exit) => + Scope.close(scope, exit), + ); + const attachAll = (scopes: ReadonlyArray) => + Effect.forEach( + scopes, + (scope, index) => + attachClient(server, token, clientThreads[index] ?? []).pipe(Scope.provide(scope)), + { concurrency: "unbounded" }, + ); + const clients = yield* Effect.forEach(clientThreads, () => clientScope); + const first = yield* attachAll(clients); + yield* Effect.sleep(Duration.seconds(10)); + yield* Effect.forEach(first, (client) => client.healthy, { discard: true }); + yield* server.loopStart; + const dropped = yield* nowMs; + yield* Effect.forEach(clients, (scope) => Scope.close(scope, Exit.void), { + concurrency: "unbounded", + discard: true, + }); + const reopened = yield* Effect.forEach(clientThreads, () => clientScope); + const second = yield* attachAll(reopened); + const resubscribedMs = Math.round((yield* nowMs) - dropped); + const loop = yield* server.loopRead; + // The first cohort again: a loss between its check and the drop happened in the reconnect. + yield* Effect.forEach([...first, ...second], (client) => client.healthy, { discard: true }); + yield* Effect.forEach(reopened, (scope) => Scope.close(scope, Exit.void), { discard: true }); + return { resubscribedMs, loopDelayP99Ms: round(loop.p99), loopDelayMaxMs: round(loop.max) }; +}); + /** * Short turns back to back on one thread: how long a send takes to reach the API, how long the * end of the reply takes to become a finished run the CLI sees (turn end and checkpoint), the time @@ -1302,6 +1472,126 @@ const pipelineTurns = Effect.fn("serverMetrics.pipelineTurns")(function* ( }; }); +const TERMINAL_RUN = new Set(["completed", "failed", "interrupted", "cancelled", "rolled_back"]); + +/** Threads that each answered once in a worktree of their own, by id. */ +const openWorktreeThreads = Effect.fn("serverMetrics.openWorktreeThreads")(function* ( + server: Server, + count: number, +) { + const answers = yield* Effect.forEach( + Array.from({ length: count }, (_, index) => index), + (index) => server.threadStart(`Say hello ${index}.`, ["--wait", "--worktree", "main"]), + { concurrency: 5 }, + ); + const ids = answers.map((answer) => /^Thread (\S+)$/m.exec(answer.stderr)?.[1]); + const failed = answers.find((answer, index) => answer.exitCode !== 0 || !ids[index]); + if (failed) { + return yield* new MetricsError({ + message: `a worktree thread failed to start: ${failed.stderr.trim() || failed.stdout.trim()}`, + }); + } + return ids.filter((id) => id !== undefined); +}); + +/** + * Every given thread runs editing turns back to back, all at once, sent and watched by one client + * subscribed to all of them, as the web client is. Each turn streams a reply, writes a file in the + * thread's worktree through the agent's Write tool, and ends in a checkpoint of that change. The + * window is measured while every thread is working; turns finished inside it are timed. + */ +const workingWindow = Effect.fn("serverMetrics.workingWindow")(function* ( + environment: Environment, + server: Server, + token: string, + threadIds: ReadonlyArray, + timing: { readonly warmupSeconds: number; readonly windowSeconds: number }, + /** The first turn's marker number; each window needs its own range, as ids never repeat. */ + firstMarker: number, +) { + // One pending turn per thread: its message id and when the run's end reached the client. + const pending = new Map }>(); + const client = yield* attachClient(server, token, threadIds, (threadId, item) => { + if (item.kind !== "event" || item.event.type !== "run.updated") return Effect.void; + const run = item.event.payload; + const turn = pending.get(threadId); + if (!turn || run.userMessageId !== turn.messageId || !TERMINAL_RUN.has(run.status)) { + return Effect.void; + } + return Deferred.succeed(turn.done, run.status).pipe(Effect.asVoid); + }); + const turns: Array<{ endedAt: number; toRequest: number; turnEnd: number; turnMs: number }> = []; + let stopping = false; + let sequence = 0; + const work = Effect.fn("serverMetrics.workingThread")(function* (threadId: string) { + while (!stopping) { + const marker = `bench-run-${firstMarker + sequence++}`; + const messageId = `bench-message-${marker}`; + const done = yield* Deferred.make(); + pending.set(threadId, { messageId, done }); + const sentAt = yield* nowMs; + yield* client.send(threadId, messageId, `Edit a file. ${EDIT_MARKER} ${marker}`); + const status = yield* Deferred.await(done).pipe( + Effect.timeoutOrElse({ + duration: Duration.seconds(120), + orElse: () => new MetricsError({ message: `turn ${marker} never ended` }), + }), + ); + const endedAt = yield* nowMs; + if (status !== "completed") { + return yield* new MetricsError({ message: `turn ${marker} ended ${status}` }); + } + const forTurn = environment.requests.filter( + (request) => request.agent && request.marker === marker && request.at >= sentAt, + ); + const first = forTurn.find((request) => !request.toolResult); + const last = forTurn.findLast((request) => request.toolResult); + if (first === undefined || last?.endedAt === undefined) { + return yield* new MetricsError({ + message: `turn ${marker} never called its Write tool; is the Claude CLI's tool set unchanged?`, + }); + } + turns.push({ + endedAt, + toRequest: first.at - sentAt, + turnEnd: endedAt - last.endedAt, + turnMs: endedAt - sentAt, + }); + } + }); + const workers = yield* Effect.forEach(threadIds, (threadId) => Effect.forkScoped(work(threadId))); + // A failed turn ends the window at once instead of thinning it. + const failed = Effect.forEach(workers, Fiber.join, { + concurrency: "unbounded", + discard: true, + }).pipe(Effect.andThen(Effect.never)); + return yield* Effect.raceFirst( + Effect.gen(function* () { + yield* Effect.sleep(Duration.seconds(timing.warmupSeconds)); + const from = yield* nowMs; + const window = yield* server.measure(timing.windowSeconds); + const to = yield* nowMs; + // Every thread finishes the turn it is on, so the next window starts from idle threads. + stopping = true; + yield* Effect.forEach(workers, Fiber.join, { discard: true }); + yield* client.healthy; + const inside = turns.filter((turn) => turn.endedAt >= from && turn.endedAt <= to); + if (inside.length === 0) { + return yield* new MetricsError({ message: "no turn finished inside the window" }); + } + const point: WorkingPoint = { + ...window, + turnsPerMin: round((inside.length / (to - from)) * 60_000), + toRequestMs: spread(inside.map((turn) => turn.toRequest)), + turnEndMs: spread(inside.map((turn) => turn.turnEnd)), + turnMs: spread(inside.map((turn) => turn.turnMs)), + }; + return point; + }), + failed, + ); +}, Effect.scoped); + const SCENARIOS = [ "startup", "rest", @@ -1310,6 +1600,7 @@ const SCENARIOS = [ "streaming", "clients", "pipeline", + "working", "busy", ] as const; /** Scenarios that read the developer's real database, so they run only when named. */ @@ -1325,6 +1616,9 @@ interface RunOptions { /** A seeded base dir for the busy scenario. */ readonly seed: string | undefined; readonly ballastMB: number; + /** Also runs the upper-bound stress cases, such as the 20-client reconnect storm. */ + readonly stress: boolean; + readonly profile: Profile; /** Where full CPU and allocation profiles go; none are written without it. */ readonly profileDir: string | undefined; } @@ -1333,6 +1627,7 @@ interface RunOptions { const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOptions) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const machine = yield* watchMachine; const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-" }); const api = yield* serveFakeAnthropic(); const environment: Environment = { @@ -1353,9 +1648,21 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption name: string, body: (server: Server) => Effect.Effect, serverOptions: ServerOptions = {}, - ) => Effect.scoped(Effect.flatMap(startServer(environment, name, serverOptions), body)); + ) => + Effect.scoped(Effect.flatMap(startServer(environment, name, serverOptions), body)).pipe( + // Names the scenario and its cause in one line, instead of a stack from deep in the RPC client. + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.fail( + new MetricsError({ + message: `the ${name} scenario failed: ${describeFailure(Cause.squash(cause))}`, + }), + ), + ), + ); const profile = Effect.fn("serverMetrics.saveProfile")(function* (server: Server, name: string) { - const { summary, raw } = yield* server.profile(20); + const { summary, raw } = yield* server.profile(options.profile.profileSeconds); profiles[name] = summary; if (options.profileDir === undefined) return; yield* fs.makeDirectory(options.profileDir, { recursive: true }); @@ -1374,8 +1681,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption Effect.gen(function* () { measured.startup = { readyMs: server.readyMs }; if (wanted("rest")) { - yield* Effect.sleep(Duration.seconds(15)); - measured.rest = yield* server.measure(30); + yield* Effect.sleep(Duration.seconds(options.profile.settleSeconds)); + measured.rest = yield* server.measure(options.profile.windowSeconds); } if (wanted("firstWord")) { measured.firstWord = { @@ -1394,8 +1701,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption for (const threads of options.threads) { if (threads > open) yield* openThreads(server, open, threads - open); open = Math.max(open, threads); - yield* Effect.sleep(Duration.seconds(15)); - points.push({ threads, window: yield* server.measure(30) }); + yield* Effect.sleep(Duration.seconds(options.profile.settleSeconds)); + points.push({ threads, window: yield* server.measure(options.profile.windowSeconds) }); } const last = points.at(-1); if (last) measured.quiet = last.window; @@ -1427,62 +1734,76 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption yield* withServer("clients", (server) => Effect.gen(function* () { const token = yield* server.issueToken; - const most = Math.max(STORM_CLIENTS, ...options.threads); + const most = Math.max( + RECONNECT_THREADS, + options.stress ? STORM_CLIENTS : 0, + ...options.threads, + ); const threads = yield* openThreads(server, 0, most); const attached: Record = {}; for (const count of options.threads) { yield* Effect.scoped( Effect.gen(function* () { const client = yield* attachClient(server, token, threads.slice(0, count)); - yield* Effect.sleep(Duration.seconds(10)); - attached[`${count}`] = yield* server.measure(30); + yield* Effect.sleep(Duration.seconds(options.profile.settleSeconds)); + attached[`${count}`] = yield* server.measure(options.profile.windowSeconds); yield* client.healthy; }), ); } - // Each client gets its own scope so the storm can drop them on cue; the server's scope - // still closes any left open when a step fails or is interrupted. - const clientScope = Effect.acquireRelease(Scope.make(), (scope, exit) => - Scope.close(scope, exit), + const reconnect = yield* reconnectAll( + server, + token, + Array.from({ length: RECONNECT_CLIENTS }, () => threads.slice(0, RECONNECT_THREADS)), ); // Every client holds the shell, VCS status and one thread, then all drop and come back. - const clients = yield* Effect.forEach(threads.slice(0, STORM_CLIENTS), () => clientScope); - const first = yield* Effect.forEach( - clients, - (scope, index) => - attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)), - { concurrency: "unbounded" }, - ); - yield* Effect.sleep(Duration.seconds(10)); - yield* Effect.forEach(first, (client) => client.healthy, { discard: true }); - yield* server.loopStart; - const dropped = yield* nowMs; - yield* Effect.forEach(clients, (scope) => Scope.close(scope, Exit.void), { - concurrency: "unbounded", - discard: true, - }); - const reopened = yield* Effect.forEach(clients, () => clientScope); - const second = yield* Effect.forEach( - reopened, - (scope, index) => - attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)), - { concurrency: "unbounded" }, - ); - const resubscribedMs = Math.round((yield* nowMs) - dropped); - const loop = yield* server.loopRead; - // The first cohort again: a loss between its check and the drop happened in the storm. - yield* Effect.forEach([...first, ...second], (client) => client.healthy, { discard: true }); - yield* Effect.forEach(reopened, (scope) => Scope.close(scope, Exit.void), { - discard: true, - }); + const storm = options.stress + ? yield* reconnectAll( + server, + token, + threads.slice(0, STORM_CLIENTS).map((thread) => [thread]), + ) + : undefined; measured.clients = { attached, - storm: { - clients: STORM_CLIENTS, - resubscribedMs, - loopDelayP99Ms: round(loop.p99), - loopDelayMaxMs: round(loop.max), + reconnect: { + clients: RECONNECT_CLIENTS, + threadsPerClient: RECONNECT_THREADS, + ...reconnect, }, + ...(storm ? { storm: { clients: STORM_CLIENTS, ...storm } } : {}), + }; + }), + ); + } + if (wanted("working")) { + yield* withServer("working", (server) => + Effect.gen(function* () { + const token = yield* server.issueToken; + const counts = options.profile.workingThreads; + const threads = yield* openWorktreeThreads(server, Math.max(...counts)); + const active: Record = {}; + for (const [index, count] of counts.entries()) { + active[`${count}`] = yield* workingWindow( + environment, + server, + token, + threads.slice(0, count), + { + warmupSeconds: options.profile.workingWarmupSeconds, + windowSeconds: options.profile.workingSeconds, + }, + 30_000 + index * 10_000, + ); + } + const fit = (pick: (point: WorkingPoint) => number) => + round(slope(counts.map((count) => [count, pick(active[`${count}`]!)] as const)), 3); + measured.working = { + active, + heapMBPerThread: fit((point) => point.heapAfterGcMB), + rssMBPerThread: fit((point) => point.rssMB), + cpuPctPerThread: fit((point) => point.cpuPct), + loopDelayP99MsPerThread: fit((point) => point.loopDelayP99Ms ?? 0), }; }), ); @@ -1490,7 +1811,11 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption if (wanted("pipeline")) { yield* withServer("pipeline", (server) => Effect.gen(function* () { - measured.pipeline = yield* pipelineTurns(environment, server, PIPELINE_TURNS); + measured.pipeline = yield* pipelineTurns( + environment, + server, + options.profile.pipelineTurns, + ); }), ); } @@ -1522,7 +1847,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption return yield* new MetricsError({ message: "fewer than 5 replies started streaming" }); } yield* Effect.sleep(Duration.seconds(5)); - measured.streaming = yield* server.measure(60); + measured.streaming = yield* server.measure(options.profile.streamingSeconds); yield* profile(server, "streaming"); }), ); @@ -1536,8 +1861,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption (server) => Effect.gen(function* () { yield* server.ballast(options.ballastMB); - yield* Effect.sleep(Duration.seconds(30)); - const rest = yield* server.measure(30); + yield* Effect.sleep(Duration.seconds(options.profile.settleSeconds * 2)); + const rest = yield* server.measure(options.profile.windowSeconds); yield* server.assertIdle(server.startedAt); const shell = yield* loadShell(server, 5); const largest = server.largest; @@ -1547,7 +1872,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption const git = yield* Effect.raceFirst( Effect.gen(function* () { yield* Effect.sleep(Duration.seconds(5)); - const window = yield* server.measure(30); + const window = yield* server.measure(options.profile.windowSeconds); yield* profile(server, "busyGit"); return window; }), @@ -1595,8 +1920,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption yield* takeSample; nextSample += 120_000; } - const threadId = - threads[yield* Random.nextIntBetween(0, threads.length, { halfOpen: true })]; + // Round robin, so two soaks send the same turns to the same threads. + const threadId = threads[turn % threads.length]; if (threadId === undefined) return yield* new MetricsError({ message: "no soak threads" }); const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`); @@ -1619,6 +1944,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption }), ); } + measured.machine = yield* machine; return { measured: measured as Measured, profiles, soakHeapGrowth }; }, Effect.scoped); @@ -1641,6 +1967,110 @@ const machineLoad = Effect.gen(function* () { ), ); +/** Comm names of the processes that compete with a measured server on a developer's machine. */ +const COMPETING = /^(node|node-MainThread|t3|claude|codex|vite|pnpm)/; + +/** + * CPU seconds of every node, T3, claude or codex process outside this script's own tree, keyed by + * pid and start time so a reused pid is a new process. Linux only; elsewhere none, and the run + * records only the load average. + */ +const competingCpuSeconds = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform !== "linux") return Option.none>(); + const fs = yield* FileSystem.FileSystem; + const self = Number(yield* fs.readLink("/proc/self")); + const parents = new Map(); + const cpu = new Map(); + for (const entry of yield* fs.readDirectory("/proc")) { + if (!/^\d+$/.test(entry)) continue; + const stat = yield* fs + .readFileString(`/proc/${entry}/stat`) + .pipe(Effect.orElseSucceed(() => "")); + const open = stat.indexOf(" ("); + const close = stat.lastIndexOf(") "); + if (open < 0 || close < 0) continue; + const fields = stat.slice(close + 2).split(" "); + const pid = Number(entry); + parents.set(pid, Number(fields[1])); + if (COMPETING.test(stat.slice(open + 2, close))) { + // Fields after the name start at the state, field 3: utime 14, stime 15, starttime 22. + cpu.set(pid, { + key: `${pid}:${fields[19]}`, + seconds: (Number(fields[11]) + Number(fields[12])) / 100, + }); + } + } + const ours = (pid: number) => { + for (let at: number | undefined = pid; at !== undefined && at > 1; at = parents.get(at)) { + if (at === self) return true; + } + return false; + }; + return Option.some( + new Map([...cpu].filter(([pid]) => !ours(pid)).map(([, { key, seconds }]) => [key, seconds])), + ); +}).pipe(Effect.orElseSucceed(() => Option.none>())); + +/** How often the machine watcher reads competing CPU; a process that exits loses at most this. */ +const MACHINE_SAMPLE_SECONDS = 10; + +const load1 = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform === "win32") return Option.none(); + if (platform === "linux") { + const fs = yield* FileSystem.FileSystem; + const text = yield* fs.readFileString("/proc/loadavg").pipe(Effect.option); + return Option.map(text, (value) => Number(value.split(" ")[0])); + } + const text = yield* output("sysctl", ["-n", "vm.loadavg"]); + return Option.map(text, (value) => Number(value.replace(/[{}]/g, "").trim().split(/\s+/)[0])); +}).pipe(Effect.map(Option.filter(Number.isFinite))); + +/** + * Starts watching the machine for one run; the returned effect reads what competed with it: the + * highest 1-minute load seen and the cores other T3, node and agent processes kept busy. + */ +const watchMachine = Effect.gen(function* () { + const startedAt = yield* nowMs; + const loads: number[] = []; + // Unknown (none) once any read fails, so a partial sum never passes for the whole run. + let competing: Option.Option = Option.some(0); + let previous = yield* competingCpuSeconds; + if (Option.isNone(previous)) competing = Option.none(); + // The periodic and final reads would otherwise interleave across the await below. + const reading = yield* Semaphore.make(1); + const read = Effect.gen(function* () { + loads.push(...Option.toArray(yield* load1)); + if (Option.isNone(previous) || Option.isNone(competing)) return; + const next = yield* competingCpuSeconds; + if (Option.isNone(next)) { + competing = Option.none(); + return; + } + competing = Option.some(competing.value + competingBetween(previous.value, next.value)); + previous = next; + }).pipe(reading.withPermits(1)); + yield* read; + // Reading through the run, not only at its ends, keeps a busy process that exits mid-run. + yield* read.pipe( + Effect.delay(Duration.seconds(MACHINE_SAMPLE_SECONDS)), + Effect.forever, + Effect.forkScoped, + ); + return Effect.gen(function* () { + yield* read; + const elapsed = ((yield* nowMs) - startedAt) / 1_000; + const machine: MachineState = { + load1: loads.length ? round(Math.max(...loads), 2) : null, + otherCpuCores: + Option.isSome(competing) && elapsed > 0 ? round(competing.value / elapsed, 2) : null, + minutes: round(elapsed / 60, 1), + }; + return machine; + }); +}); + const metaFor = Effect.fn("serverMetrics.metaFor")(function* (options: RunOptions) { const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; @@ -1668,6 +2098,7 @@ const metaFor = Effect.fn("serverMetrics.metaFor")(function* (options: RunOption yield* output("git", ["rev-parse", "--short=12", "HEAD"], options.checkout), ), noAgentScope: options.noAgentScope, + profile: options.profile === PROFILES.quick ? "quick" : "full", agentScope: platform === "linux" && !options.noAgentScope && @@ -1694,13 +2125,23 @@ const report = Effect.fn("serverMetrics.report")(function* ( after: ServerMetrics, threshold: number, ) { - const { table, regressed, improved, compared } = compareMetrics(before, after, threshold); + const mismatch = profileMismatch(before, after); + if (mismatch !== undefined) return yield* new MetricsError({ message: mismatch }); + const { table, regressed, improved, informational, compared, warnings } = compareMetrics( + before, + after, + threshold, + ); yield* Console.log(table); + for (const warning of warnings) yield* Console.error(`Warning: ${warning}`); if (compared === 0) { return yield* new MetricsError({ message: "the two files share no metric, so nothing was compared", }); } + if (informational.length) { + yield* Console.error(`Moved, but too noisy to gate on: ${informational.join(", ")}`); + } if (improved.length) yield* Console.error(`Better: ${improved.join(", ")}`); if (regressed.length === 0) return; yield* Console.error(`Worse: ${regressed.join(", ")}`); @@ -1723,12 +2164,20 @@ const runFlags = { ), runs: Flag.Int("runs").pipe( Flag.withSchema(PositiveInt), - Flag.withDescription("firstWord runs in each variant."), - Flag.withDefault(5), + Flag.withDescription("firstWord runs in each variant. Default 5, 3 with --quick."), + Flag.optional, ), threads: Flag.String("threads").pipe( - Flag.withDescription("Open thread counts the quiet scenario measures."), - Flag.withDefault("0,5,10,20"), + Flag.withDescription( + "Open thread counts the quiet and clients scenarios measure. Default 0,5,10,20; 0,10 with --quick.", + ), + Flag.optional, + ), + quick: Flag.Boolean("quick").pipe( + Flag.withDefault(false), + Flag.withDescription( + "Shorter windows, fewer turns and fewer points (about a third of the time), for a per-PR or nightly check. Compare quick runs only with quick runs.", + ), ), only: Flag.String("only").pipe( Flag.withDescription(`Scenarios to run, comma separated: ${SCENARIOS.join(", ")}.`), @@ -1757,6 +2206,12 @@ const runFlags = { ), Flag.withDefault(768), ), + stress: Flag.Boolean("stress").pipe( + Flag.withDefault(false), + Flag.withDescription( + "Also run upper bounds no user hits daily: clients drops 20 clients at once and reconnects them. Compare stress numbers only with stress numbers.", + ), + ), soak: Flag.Int("soak").pipe( Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), Flag.withDescription( @@ -1767,14 +2222,16 @@ const runFlags = { }; interface RunFlags { readonly noAgentScope: boolean; - readonly runs: number; - readonly threads: string; + readonly runs: Option.Option; + readonly threads: Option.Option; + readonly quick: boolean; readonly only: Option.Option; readonly soak: number; readonly seedDir: Option.Option; readonly busyProjects: number; readonly busyThreads: number; readonly busyBallast: number; + readonly stress: boolean; } const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( @@ -1783,9 +2240,10 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( profileDir: string | undefined, ) { const path = yield* Path.Path; + const profile = flags.quick ? PROFILES.quick : PROFILES.full; const selection = parseRunSelection({ only: Option.getOrElse(flags.only, () => ""), - threads: flags.threads, + threads: Option.getOrElse(flags.threads, () => profile.threads), soak: flags.soak, scenarios: SCENARIOS, }); @@ -1794,13 +2252,15 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( const options: RunOptions = { checkout: path.resolve(checkout), noAgentScope: flags.noAgentScope, - runs: flags.runs, + runs: Option.getOrElse(flags.runs, () => profile.runs), threads, only, soakMinutes: flags.soak, profileDir, seed: undefined, ballastMB: flags.busyBallast, + stress: flags.stress, + profile, }; return options; }); @@ -1863,7 +2323,7 @@ const runCommand = Command.make( }, Effect.scoped), ).pipe( Command.withDescription( - "Measure a checkout's server: startup, rest and first word on one server, then quiet threads (with their cost per thread), streaming and an optional soak on servers of their own. Needs the real claude CLI on PATH; on Windows the native claude.exe from claude.ai/install.ps1, since an npm claude.cmd shim cannot be started without a shell.", + "Measure a checkout's server: startup, rest and first word on one server, then quiet threads (with their cost per thread), clients, many threads working, the turn pipeline, streaming and an optional soak on servers of their own. Needs the real claude CLI on PATH; on Windows the native claude.exe from claude.ai/install.ps1, since an npm claude.cmd shim cannot be started without a shell.", ), ); @@ -1937,15 +2397,70 @@ const compareCommand = Command.make( }), ).pipe( Command.withDescription( - "Markdown table of two result files, lower is better. With 2+ runs a side, a metric counts only when the 95% bootstrap interval of the median difference clears the threshold and its noise floor (1 CPU point, 20 wakeups/s, 15 MB, 300 ms; per thread 2 MB or 0.2 CPU points). Exits 1 on a regression.", + "Markdown table of two result files, lower is better. With 2+ runs a side, a metric counts only when the 95% bootstrap interval of the median difference clears the threshold and its noise floor, measured from A/A runs (see `noise`). Metrics too noisy to gate on are shown but never counted. Warns when either side ran under heavy machine load. Exits 1 on a regression.", + ), +); + +const noiseCommand = Command.make( + "noise", + { + dirs: Argument.String("dir").pipe( + Argument.withDescription("An `ab` out dir (a.json and b.json) of one commit against itself."), + Argument.atLeast(1), + ), + }, + Effect.fn("serverMetrics.noise")(function* (input) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const read = (file: string) => + fs.readFileString(file).pipe(Effect.flatMap(decodeJson(ServerMetrics))); + const pairs = yield* Effect.forEach(input.dirs, (dir) => + Effect.gen(function* () { + const a = yield* read(path.join(dir, "a.json")); + const b = yield* read(path.join(dir, "b.json")); + const problem = noisePairProblem(dir, a, b); + if (problem !== undefined) return yield* new MetricsError({ message: problem }); + for (const [file, metrics] of [ + ["a.json", a], + ["b.json", b], + ] as const) { + for (const warning of loadWarnings(path.join(dir, file), metrics)) { + yield* Console.error(`Warning: ${warning}`); + } + } + return [a, b] as const; + }), + ); + const { rows, table } = noiseReport(pairs); + if (rows.length === 0) { + return yield* new MetricsError({ + message: "no metric was measured on both sides of any pair, so nothing was calibrated", + }); + } + yield* Console.log(table); + }), +).pipe( + Command.withDescription( + "Spread of every metric over A/A runs (`ab `), an estimated floor covering the half ranges and median differences these runs showed, and which metrics are too noisy to gate on. ⚠ marks a current floor under the estimate. Refuses directories whose two files record different commits.", ), ); const serverMetricsCommand = Command.make("server-metrics").pipe( Command.withDescription( - "Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows.", + `Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows. + +Which scenario answers what: + working Many threads editing files at once, one client watching all: steer performance work by its loop delay, turn end and turns per minute. + pipeline One thread's overhead per turn: send to API request, reply end to run end. + clients What an attached client costs, and a user's 3 devices reconnecting. --stress adds the 20-client storm, an upper bound. + quiet Idle cost per open thread (the scaling fit); rest is an idle server. + streaming CPU and loop delay while 5 replies stream. + firstWord A new thread's time to the API; startup is time to the first answer. Latency on a shared machine is noisy. + busy Opt-in: a copy of your real database, read-only, for costs an empty one hides. + +Trust a change only from \`ab\` on one machine. compare gates on floors measured from A/A runs (\`noise\`), shows metrics too noisy to gate on without counting them, and warns when other processes loaded the machine; rerun then. --quick suits a per-PR or nightly check; decide on full runs.`, ), - Command.withSubcommands([runCommand, abCommand, compareCommand]), + Command.withSubcommands([runCommand, abCommand, compareCommand, noiseCommand]), ); if (import.meta.main) { @@ -1957,6 +2472,16 @@ if (import.meta.main) { NodeSocket.layerWebSocketConstructor, ), ), + Effect.catchTags({ + MetricsError: (error) => + Console.error(`server-metrics: ${error.message}`).pipe( + Effect.andThen( + Effect.sync(() => { + process.exitCode = 1; + }), + ), + ), + }), NodeRuntime.runMain, ); }