diff --git a/.pnpmfile.cjs b/.pnpmfile.cjs index 87a153f7b030d..8e79fceda4142 100644 --- a/.pnpmfile.cjs +++ b/.pnpmfile.cjs @@ -1,16 +1,22 @@ const fs = require("node:fs"); const path = require("node:path"); -// Our forks ship as tarballs in apps/mobile/deps. A pnpm patch on one is a second source of -// truth that the next tarball silently drops, so changes go to the fork (apps/mobile/deps/README.md). +// Our forks ship as tarballs in apps/mobile/deps and apps/web/deps. A pnpm patch on one is a +// second source of truth that the next tarball silently drops, so changes go to the fork (see +// the README beside each tarball). +const FORK_APPS = ["apps/mobile", "apps/web"]; + function forkTarballPatches(patchedDependencies) { - const manifestPath = path.join(__dirname, "apps/mobile/package.json"); - // Release staging installs a partial workspace without the mobile app. - if (!patchedDependencies || !fs.existsSync(manifestPath)) return []; - const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); - const forks = Object.keys(dependencies).filter((name) => - String(dependencies[name]).startsWith("file:deps/"), - ); + if (!patchedDependencies) return []; + const forks = FORK_APPS.flatMap((app) => { + const manifestPath = path.join(__dirname, app, "package.json"); + // Release staging installs a partial workspace without every app. + if (!fs.existsSync(manifestPath)) return []; + const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); + return Object.keys(dependencies).filter((name) => + String(dependencies[name]).startsWith("file:deps/"), + ); + }); return Object.keys(patchedDependencies).filter((key) => forks.some((name) => key === name || key.startsWith(`${name}@`)), ); @@ -23,7 +29,7 @@ module.exports = { if (forkPatches.length > 0) { throw new Error( `pnpm-workspace.yaml patches ${forkPatches.join(", ")}, which ships as a fork tarball in ` + - "apps/mobile/deps. Change the fork and replace the tarball instead (apps/mobile/deps/README.md).", + "an app's deps directory. Change the fork and replace the tarball instead (deps/README.md).", ); } // Windows installs need Linux x64 glibc binaries because WSL shares node_modules. diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 0ccce648bba61..ba09871ee1c5a 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -4,6 +4,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import * as NetService from "@t3tools/shared/Net"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -173,6 +174,31 @@ const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")( ); // Spawns the local backend as soon as the protocol, IPC, and legacy storage that every window needs exist. +/** + * The server reads T3CODE_FEATURE_FLAGS once at start, from the value cached at the last + * discovery. When the login shell now sets different flags, restart it so they apply. + */ +const restartOnFeatureFlagChange = Effect.fn("desktop.restartOnFeatureFlagChange")(function* ( + backend: DesktopBackendManager.DesktopBackendInstance, +) { + const state = yield* DesktopState.DesktopState; + const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; + let startedWith = (yield* HostProcess.Environment).T3CODE_FEATURE_FLAGS; + yield* shellEnvironment.updates.pipe( + Stream.filter((snapshot) => snapshot.discovered), + Stream.runForEach( + Effect.fnUntraced(function* (snapshot) { + const flags = snapshot.environment.T3CODE_FEATURE_FLAGS ?? undefined; + if (flags === startedWith || (yield* Ref.get(state.quitting))) return; + startedWith = flags; + yield* logBootstrapInfo("restarting backend for changed T3CODE_FEATURE_FLAGS"); + yield* backend.stop(); + yield* backend.start; + }), + ), + ); +}); + const startLocalBackend = Effect.gen(function* () { const state = yield* DesktopState.DesktopState; const environment = yield* DesktopEnvironment.DesktopEnvironment; @@ -268,6 +294,7 @@ const startLocalBackend = Effect.gen(function* () { } yield* primaryBackend.start; yield* logBootstrapInfo("bootstrap backend start requested"); + yield* Effect.forkScoped(restartOnFeatureFlagChange(primaryBackend)); // The renderer asks for this token first; minting it at readiness saves a round trip. yield* Effect.forkScoped( (yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth).getBearerToken.pipe( diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index 3e8b4967dfde5..929148fdbb32f 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -69,7 +69,7 @@ const fakeAppImage = (canMount = true, app = REPORTER) => { // Stays up after a signal until the test lets it finish, like a server shutting down. const SLOW_SERVER = [ "#!/bin/sh", - "trap 'echo stopping >&3; read go; echo stopped >&3; exit 0' TERM HUP", + "trap 'echo stopping >&3; read go; echo \"stopped $go\" >&3; exit 7' TERM HUP", "echo ready", "while :; do sleep 0.05; done", "", @@ -101,9 +101,16 @@ const lines = (stream: NodeJS.ReadableStream) => { }; describe("renderCliShim", () => { - it.skipIf(!hasSetsid).each(["SIGTERM", "SIGHUP"] as const)( - "keeps the AppImage mounted until the server exits after %s to the process group", - async (signal) => { + // Ctrl-C, an SSH hangup, or a supervisor signals the process group. systemd's default KillMode + // also signals the mounter, and KillMode=mixed signals only the launcher. + it.skipIf(!hasSetsid).each([ + ["SIGTERM", "the process group"], + ["SIGHUP", "the process group"], + ["SIGTERM", "every process"], + ["SIGTERM", "the launcher"], + ] as const)( + "keeps the AppImage mounted until the server exits after %s to %s", + async (signal, target) => { const { root, shim } = fakeAppImage(true, SLOW_SERVER); const child = NodeChildProcess.spawn(shim, [], { detached: true, @@ -114,12 +121,12 @@ describe("renderCliShim", () => { try { const stdout = lines(child.stdout!); const events = lines(child.stdio[3] as NodeJS.ReadableStream); - const exited = new Promise((resolve) => child.on("close", resolve)); + const exited = new Promise((resolve) => child.on("close", resolve)); await stdout.until((line) => line === "ready"); mounter = Number(NodeFS.readFileSync(NodePath.join(root, "mounter.pid"), "utf8")); - // Ctrl-C in a terminal, a closed SSH session, or a service manager signals the whole group. - process.kill(-child.pid!, signal); + process.kill(target === "the launcher" ? child.pid! : -child.pid!, signal); + if (target === "every process") process.kill(mounter, signal); // The shell runs pending traps in ascending signal number, and WINCH outnumbers TERM and // HUP, so a mounter that also got the group signal unmounts before it answers this probe. process.kill(mounter, "SIGWINCH"); @@ -128,8 +135,8 @@ describe("renderCliShim", () => { await events.until((line) => line === "stopping"); child.stdin!.end("go\n"); - await exited; - expect(events.seen.slice(-2)).toEqual(["stopped", "unmounted"]); + expect(await exited).toBe(7); + expect(events.seen.slice(-2)).toEqual(["stopped go", "unmounted"]); } finally { for (const pid of [-child.pid!, mounter]) { if (pid === undefined) continue; @@ -156,6 +163,8 @@ describe("renderCliShim", () => { const result = run(shim, ["--version"]); expect(result.status).toBe(3); expect(result.stdout).toContain(`appimage=${appImage}`); + const closedStdin = NodeChildProcess.spawnSync("sh", ["-c", '"$0" --version <&-', shim]); + expect(closedStdin.status).toBe(3); }); it("keeps the install's T3 home under sudo, unless one is set", () => { diff --git a/apps/desktop/src/app/DesktopCliShim.ts b/apps/desktop/src/app/DesktopCliShim.ts index 217f3b327dc9e..0f7e605da6b36 100644 --- a/apps/desktop/src/app/DesktopCliShim.ts +++ b/apps/desktop/src/app/DesktopCliShim.ts @@ -91,11 +91,15 @@ export const renderCliShim = (input: { // Extract-and-run would make the runtime start the app instead of mounting it. "unset APPIMAGE_EXTRACT_AND_RUN", // Its own session keeps a group signal (Ctrl-C, SSH hangup) from unmounting it under the - // running server; the traps unmount it after. Without setsid the extract fallback runs. + // running server, and ignoring TERM survives a stop sent to every process (systemd's default). + // Without setsid the extract fallback runs. "work=$(mktemp -d) || exit 1", + "trap '' TERM", 'setsid "$app" --appimage-mount >"$work/mount" 2>/dev/null &', "mounter=$!", - `trap 'kill "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`, + // It unmounts itself on TERM, which it now ignores, so the trap unmounts it. Lazily, like the + // runtime: the server's own children may still be exiting. + `trap '[ -z "$mount" ] || fusermount3 -uz "$mount" 2>/dev/null || fusermount -uz "$mount" 2>/dev/null; kill -HUP "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`, "trap 'exit 130' INT TERM HUP", "mount=", 'while kill -0 "$mounter" 2>/dev/null; do', @@ -111,7 +115,24 @@ export const renderCliShim = (input: { "fi", // The runtime sets this when it launches the app; the CLI skips its path-keyed compile cache on it. 'export APPIMAGE="$app"', - run("$mount"), + // The shell must outlive the CLI to unmount, so it forwards TERM and HUP; the terminal sends + // Ctrl-C to the CLI directly. A background child would read /dev/null, so pass stdin on fd 9. + // With stdin closed, `exec 9<&0` would end the shell; `command` makes it a normal error. + "{ command exec 9<&0; } 2>/dev/null || exec 9/dev/null' TERM`, + `trap 'kill -HUP "$cli" 2>/dev/null' HUP`, + "trap '' INT", + "status=0", + 'wait "$cli" || status=$?', + // A trapped signal interrupts wait; wait again for the CLI's own exit status. + 'while kill -0 "$cli" 2>/dev/null; do', + " status=0", + ' wait "$cli" || status=$?', + "done", + 'exit "$status"', "", ].join("\n"); }; diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 0704907e36ca0..2288fbb9cae4e 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -89,8 +89,7 @@ const WSL_FORWARDED_ENV_NAMES = [ "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "T3CODE_TELEMETRY_ENABLED", - "T3CODE_GITHUB_APP_CLIENT_ID", - "T3CODE_TANSTACK_SOURCE", + "T3CODE_FEATURE_FLAGS", // Otherwise the WSL server keeps exporting to endpoints from the bootstrap. "T3CODE_OTEL_SDK_DISABLED", "OTEL_SDK_DISABLED", diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index b256025eff844..9c50501a1bdfd 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -4,6 +4,7 @@ import type { ManagedPolicyLimits } from "@t3tools/contracts"; import { EDITORS, REMOTE_CAPABLE_EDITOR_IDS } from "@t3tools/contracts"; import { resolveEditorCommand } from "@t3tools/shared/editor"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { makePathDirectoryListings, PathDirectoryListings } from "@t3tools/shared/shell"; import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -11,6 +12,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; import type * as Electron from "electron"; @@ -550,6 +552,7 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( ); describe("probeRemoteEditors PATH scan", () => { + const FIXTURE_MTIME = 1_767_225_600; const platform = HostProcess.Platform.defaultValue(); const launcherName = (command: string) => (platform === "win32" ? `${command}.cmd` : command); @@ -570,6 +573,9 @@ describe("probeRemoteEditors PATH scan", () => { yield* fs.writeFileString(file, "#!/bin/sh\n"); if (platform !== "win32") yield* fs.chmod(file, 0o755); } + // A listing of a directory changed moments ago is not kept, so age them past that window. + for (const dir of dirs) yield* fs.utimes(dir, FIXTURE_MTIME, FIXTURE_MTIME); + yield* TestClock.setTime((FIXTURE_MTIME + 60) * 1000); return { root, env: { @@ -581,19 +587,15 @@ describe("probeRemoteEditors PATH scan", () => { }; }); - const countingFileSystem = (counter: { stat: number; reads: Map }) => + const countingFileSystem = (reads: Map) => Layer.effect( FileSystem.FileSystem, Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; return FileSystem.FileSystem.of({ ...fs, - stat: (target) => { - counter.stat += 1; - return fs.stat(target); - }, readDirectory: (target, options) => { - counter.reads.set(target, (counter.reads.get(target) ?? 0) + 1); + reads.set(target, (reads.get(target) ?? 0) + 1); return fs.readDirectory(target, options); }, }); @@ -612,44 +614,38 @@ describe("probeRemoteEditors PATH scan", () => { return available; }); - it.effect("reads each PATH directory once instead of stat-ing every candidate per editor", () => + it.effect("finds the editors a serial scan finds, listing each PATH directory at most once", () => Effect.gen(function* () { const { env: baseEnv } = yield* makeFakePath(); const delimiter = platform === "win32" ? ";" : ":"; - const uncachedCounter = { stat: 0, reads: new Map() }; - const cachedCounter = { stat: 0, reads: new Map() }; - const uncachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` }; - const cachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` }; - const uncached = yield* serialReference(uncachedEnv).pipe( - Effect.provide(countingFileSystem(uncachedCounter)), + const reads = new Map(); + // Distinct PATH values keep one scan from answering the other out of the resolution cache. + const serialEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` }; + const probeEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` }; + const serial = yield* serialReference(serialEnv).pipe( + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), ); - const cached = yield* probeRemoteEditors + const probed = yield* probeRemoteEditors .handler(undefined) .pipe( - Effect.provideService(HostProcess.Environment, cachedEnv), + Effect.provideService(HostProcess.Environment, probeEnv), Effect.provideService(HostProcess.Platform, platform), - Effect.provide(countingFileSystem(cachedCounter)), + Effect.provide(countingFileSystem(reads)), + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), ); // The host can add editors from app folders the fixture can't redirect (e.g. /Applications). const fixtureEditors = ["cursor", "vscode", "zed", "webstorm"]; assert.deepStrictEqual( - uncached.filter((id) => fixtureEditors.includes(id)), + serial.filter((id) => fixtureEditors.includes(id)), fixtureEditors, ); - assert.deepStrictEqual(cached, uncached); - assert.isAbove(uncachedCounter.stat, 0); - // On every platform the probe lists each PATH directory at most once. Only PATH entries count: - // resolveEditorCommand also reads app folders such as /Applications on macOS. - const pathReads = cachedEnv.PATH.split(delimiter) + assert.deepStrictEqual(probed, serial); + // Only PATH entries count: resolveEditorCommand also reads app folders such as /Applications + // on macOS. PATH directories are listed on Windows only, once even for concurrent probes. + const pathReads = probeEnv.PATH.split(delimiter) .filter((entry) => entry.length > 0) - .map((entry) => cachedCounter.reads.get(entry) ?? 0); - assert.isAbove(Math.max(...pathReads), 0); - assert.isAtMost(Math.max(...pathReads), 1); - // Without the listings, Windows stats every PATH entry x PATHEXT candidate for each editor; - // elsewhere there is no PATHEXT, so the stat count is about the same either way. - if (platform === "win32") { - assert.isBelow(cachedCounter.stat, uncachedCounter.stat / 2); - } + .map((entry) => reads.get(entry) ?? 0); + assert.strictEqual(Math.max(...pathReads), platform === "win32" ? 1 : 0); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index abf4ec929a7b7..c6ad0bef18c81 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -17,7 +17,6 @@ import { } from "@t3tools/contracts"; import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon"; import { resolveEditorCommand } from "@t3tools/shared/editor"; -import { withPathDirectoryListings } from "@t3tools/shared/shell"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment"; import * as FileSystem from "effect/FileSystem"; @@ -446,7 +445,6 @@ export const probeRemoteEditors = DesktopIpc.makeIpcMethod({ result: Schema.Array(EditorId), handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () { const env = yield* HostProcess.Environment; - // Shared listings stop each editor re-stating every PATH entry x PATHEXT candidate on Windows. const resolved = yield* Effect.forEach( REMOTE_CAPABLE_EDITOR_IDS, (editorId) => { @@ -456,7 +454,7 @@ export const probeRemoteEditors = DesktopIpc.makeIpcMethod({ : Effect.succeed(false); }, { concurrency: REMOTE_EDITOR_PROBE_CONCURRENCY }, - ).pipe(withPathDirectoryListings); + ); return REMOTE_CAPABLE_EDITOR_IDS.filter((_, index) => resolved[index]); }), }); diff --git a/apps/desktop/src/preview/LoopbackTunnel.test.ts b/apps/desktop/src/preview/LoopbackTunnel.test.ts index fe83817c0d5e8..5b3cf08c9f728 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.test.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.test.ts @@ -2,6 +2,7 @@ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"; import * as NodeWS from "@effect/platform-node/NodeWS"; import { EnvironmentId } 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 NodeNet from "node:net"; import * as Context from "effect/Context"; @@ -30,20 +31,23 @@ const closeServer = (server: NodeNet.Server | NodeWS.WebSocketServer) => ); /** A local listener that must never see a connection: the reviewer's own localhost server. */ -const listenDecoy = Effect.acquireRelease( - Effect.promise( - () => - new Promise<{ server: NodeNet.Server; connections: () => number }>((resolve) => { - let connections = 0; - const server = NodeNet.createServer((socket) => { - connections++; - socket.destroy(); - }); - server.listen(0, "127.0.0.1", () => resolve({ server, connections: () => connections })); - }), - ), - ({ server }) => closeServer(server), -); +const listenDecoyOn = (host: string) => + Effect.acquireRelease( + Effect.promise( + () => + new Promise<{ server: NodeNet.Server; connections: () => number }>((resolve, reject) => { + let connections = 0; + const server = NodeNet.createServer((socket) => { + connections++; + socket.destroy(); + }); + server.once("error", reject); + server.listen(0, host, () => resolve({ server, connections: () => connections })); + }), + ), + ({ server }) => closeServer(server), + ); +const listenDecoy = listenDecoyOn("127.0.0.1"); /** Stands in for the environment's /api/preview/tunnel: echoes each frame behind a 0xee byte. */ const listenEndpoint = Effect.acquireRelease( @@ -101,6 +105,7 @@ const makeTunnel = ( }), NodeFileSystem.layer, SecureRandom.layerWebCrypto, + NetService.layer, host ?? Layer.empty, ), ), @@ -357,24 +362,33 @@ it.effect("forwards a port over the tunnel on the same local port until stopped" }), ); -it.effect("moves a forward to a free port when its own is taken here", () => - Effect.gen(function* () { - const decoy = yield* listenDecoy; - const endpoint = yield* listenEndpoint; - const remotePort = addressPort(decoy.server); - const tunnel = yield* makeTunnel( - `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, - ); - const forward = yield* tunnel.forward({ - environmentId: EnvironmentId.make("remote"), - remotePort, - }); - expect(forward.localPort).not.toBe(remotePort); +const hasIpv6Loopback = await new Promise((resolve) => { + const probe = NodeNet.createServer(); + probe.once("error", () => resolve(false)); + probe.listen(0, "::1", () => probe.close(() => resolve(true))); +}); - expect(yield* exchange(forward.localPort, Uint8Array.of(6))).toEqual([0xee, 6]); - expect(endpoint.requests.at(-1)).toBe(`/api/preview/tunnel?port=${remotePort}`); - expect(decoy.connections()).toBe(0); - }), +// Vite listens on ::1 by default on macOS, and Node's default listen is ::. +it.effect.each(hasIpv6Loopback ? ["127.0.0.1", "::1", "::"] : ["127.0.0.1"])( + "moves a forward to a free port when its own is taken here on %s", + (host) => + Effect.gen(function* () { + const decoy = yield* listenDecoyOn(host); + const endpoint = yield* listenEndpoint; + const remotePort = addressPort(decoy.server); + const tunnel = yield* makeTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, + ); + const forward = yield* tunnel.forward({ + environmentId: EnvironmentId.make("remote"), + remotePort, + }); + expect(forward.localPort).not.toBe(remotePort); + + expect(yield* exchange(forward.localPort, Uint8Array.of(6))).toEqual([0xee, 6]); + expect(endpoint.requests.at(-1)).toBe(`/api/preview/tunnel?port=${remotePort}`); + expect(decoy.connections()).toBe(0); + }), ); /** An environment on this machine: each tunnel connection dials the requested local port. */ diff --git a/apps/desktop/src/preview/LoopbackTunnel.ts b/apps/desktop/src/preview/LoopbackTunnel.ts index 1e06993fa54f0..f84dc3e5c38a2 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.ts @@ -11,6 +11,7 @@ import type { EnvironmentId, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; import type { NonEmptyReadonlyArray } from "effect/Array"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; @@ -314,6 +315,7 @@ const make = Effect.gen(function* () { const platform = yield* HostProcess.Platform; const userId = yield* HostProcess.UserId; const random = yield* SecureRandom.SecureRandom; + const net = yield* NetService.NetService; const listenerScope = yield* Effect.scope; const routing = yield* Semaphore.make(1); const forwarding = yield* Semaphore.make(1); @@ -503,6 +505,13 @@ const make = Effect.gen(function* () { }); }); + // `localhost` also names ::1, and a server here on ::1 or :: does not collide with the + // forward's 127.0.0.1 bind, so it would keep answering `localhost` in place of the forward. + const servedOverIpv6 = (port: number) => + Effect.forEach(["::1", "::"], (host) => net.canListenOnHost(port, host)).pipe( + Effect.map((free) => free.includes(false)), + ); + const forward: LoopbackTunnel["Service"]["forward"] = Effect.fn("LoopbackTunnel.forward")( function* ({ environmentId, remotePort }) { const existing = forwarded.get(forwardKey(environmentId, remotePort)); @@ -513,7 +522,8 @@ const make = Effect.gen(function* () { const scope = yield* Scope.fork(listenerScope); const bind = (port: number) => NodeSocketServer.make({ port, host: "127.0.0.1" }).pipe(Scope.provide(scope)); - const server = yield* bind(remotePort).pipe( + const preferredPort = (yield* servedOverIpv6(remotePort)) ? 0 : remotePort; + const server = yield* bind(preferredPort).pipe( // Taken here, or privileged: any free port still reaches the environment's. Effect.catch(() => bind(0)), Effect.onError(() => Scope.close(scope, Exit.void)), diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 621c5c64178d2..dedd202acb1ee 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -983,11 +983,13 @@ describe("DesktopShellEnvironment", () => { USERPROFILE: "C:\\Users\\testuser", }; + const scripts: Array = []; const prepared = yield* runShellEnvironment({ env, platform: "win32", handler: (command) => { if (command._tag !== "StandardCommand") return ""; + scripts.push(String(command.args.at(-1))); const loadProfile = !command.args.includes("-NoProfile"); return loadProfile ? envOutput({ @@ -1021,6 +1023,13 @@ describe("DesktopShellEnvironment", () => { env.FNM_MULTISHELL_PATH, "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123", ); + assert.isNotEmpty(scripts); + for (const script of scripts) { + assert.include( + script, + "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)", + ); + } }), ); diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 3c90d7bfcaff1..620fd8f561fa8 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -123,8 +123,7 @@ const LOGIN_SHELL_ENV_NAMES = [ "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", - "T3CODE_GITHUB_APP_CLIENT_ID", - "T3CODE_TANSTACK_SOURCE", + "T3CODE_FEATURE_FLAGS", "T3CODE_RELEASE_BASE_URL", "__MISE_DIFF", "JAVA_HOME", @@ -235,6 +234,8 @@ const logShellEnvironmentCommandError = ( const captureWindowsEnvironmentCommand = (names: ReadonlyArray) => [ "$ErrorActionPreference = 'Stop'", + // Redirected PowerShell output uses the console code page, which mangles non-ASCII paths. + "try { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch {}", ...names.flatMap((name) => { return [ `Write-Output '${startMarker(name)}'`, @@ -553,8 +554,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "JAVA_HOME", "PNPM_HOME", "T3CODE_TELEMETRY_ENABLED", - "T3CODE_GITHUB_APP_CLIENT_ID", - "T3CODE_TANSTACK_SOURCE", + "T3CODE_FEATURE_FLAGS", "T3CODE_RELEASE_BASE_URL", ] as const) { if (!config.env[name] && shellEnvironment[name]) { @@ -661,6 +661,8 @@ const CACHED_ENV_NAMES = [ "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", + // The server reads its flags once at start, before discovery can finish. + "T3CODE_FEATURE_FLAGS", ] as const; /** @public */ diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 464f7ab9929b0..a868851d5c9da 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -471,9 +471,6 @@ const config: ExpoConfig = { ], extra: { appVariant: APP_VARIANT, - secretsFeatureEnabled: ["1", "true"].includes( - process.env.T3CODE_FEATURE_SECRETS?.trim().toLowerCase() ?? "", - ), iosPersonalTeamBuild: isIosPersonalTeamBuild, relay: { url: repoEnv.T3CODE_RELAY_URL ?? null, 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 1208f3176935d..b4183cb3c8fcf 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 @@ -421,7 +421,7 @@ class T3WorkspaceNavigationView( } private fun expandedTabTitle(tab: String) = - if (tab == "pullRequests") "Pull Requests" else tabTitle(tab) + if (tab == "pullRequests") "Pull requests" else tabTitle(tab) @Composable private fun tabIconPainter(tab: String) = painterResource( diff --git a/apps/mobile/src/components/ProviderIcon.tsx b/apps/mobile/src/components/ProviderIcon.tsx index 62a64102265de..f4bdf2f388ba6 100644 --- a/apps/mobile/src/components/ProviderIcon.tsx +++ b/apps/mobile/src/components/ProviderIcon.tsx @@ -197,7 +197,8 @@ export function ProviderInstanceIcon(props: { borderRadius: 999, borderWidth: 1, ...(props.surfaceColor ? { borderColor: props.surfaceColor } : {}), - backgroundColor: accentColor, + // An undefined inline key still overrides the className color when styles merge. + ...(accentColor ? { backgroundColor: accentColor } : {}), alignItems: "center", justifyContent: "center", }} @@ -208,7 +209,7 @@ export function ProviderInstanceIcon(props: { fontSize: 7, fontWeight: "600", lineHeight: 9, - color: accentColor ? providerAccentForegroundColor(accentColor) : undefined, + ...(accentColor ? { color: providerAccentForegroundColor(accentColor) } : {}), }} > {providerInstanceInitials(props.displayName)} diff --git a/apps/mobile/src/features/issues/IssueCommentComposer.tsx b/apps/mobile/src/features/issues/IssueCommentComposer.tsx index 75ff1199595a3..901dee46152a4 100644 --- a/apps/mobile/src/features/issues/IssueCommentComposer.tsx +++ b/apps/mobile/src/features/issues/IssueCommentComposer.tsx @@ -170,7 +170,11 @@ export function IssueCommentComposer(props: { /> {/* TalkBack orders siblings by position; outside this row the editor reads after Send. */} { + const host = params.host ? { host: params.host } : {}; + if (target.kind === "issue") { + navigation.dispatch( + StackActions.push("Issue", { + environmentId: params.environmentId, + projectId: params.projectId, + tracker: params.tracker, + ...host, + scope: target.repository, + issueKey: String(target.number), + }), + ); + } else if (sameHost) { + navigation.dispatch( + StackActions.push("PullRequest", { + environmentId: params.environmentId, + projectId: params.projectId, + repository: target.repository, + number: target.number, + ...host, + }), + ); + } else { + void tryOpenExternalUrl(target.url); + } + }; return ( @@ -414,7 +454,21 @@ function IssueEventRow({ event }: { readonly event: IssueEvent }) { {event.actor?.login ?? gt("Someone", { $context: "an unknown person" })} {" "} - {issueEventSentence(event, messages)} + {source === undefined || event.detail === null || at < 0 ? ( + sentence + ) : ( + <> + {sentence.slice(0, at)} + openSource(source)} + > + {event.detail} + + {sentence.slice(at + event.detail.length)} + + )} {relativeTime(event.createdAt, undefined, messages)} @@ -505,7 +559,7 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { ...detail.events.map((event) => ({ key: `e:${event.id}`, at: event.createdAt, - content: , + content: , })), ].sort((left, right) => Date.parse(left.at) - Date.parse(right.at)) : []; diff --git a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx index 3251cb8773f03..f0604d6b4ceb6 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx @@ -10,7 +10,7 @@ import { useContext, useMemo, useState, type ComponentProps, type ReactNode } fr import { Platform, Pressable, ScrollView, StyleSheet, View } from "react-native"; import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"; import { pullRequestImageSource } from "./pullRequestMediaSource"; -import { parseMarkdownDocument } from "../../lib/markdownDocument"; +import { markdownReferenceDefinitions, parseMarkdownDocument } from "../../lib/markdownDocument"; import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; @@ -44,7 +44,7 @@ export function PullRequestDescription(props: { const document = parseMarkdownDocument(props.markdown); const content = pullRequestDescriptionContent( document, - splitPullRequestBody(props.markdown), + splitPullRequestBody(props.markdown, markdownReferenceDefinitions), messages, ); return { diff --git a/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx b/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx index 5daf5ef20565b..7b904c8e33105 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx @@ -122,6 +122,7 @@ export const PullRequestListRow = memo( ), item.title, status.label, + item.visibility === "private" ? gt("Private") : null, conflict ? conflict.label.toLowerCase() : null, gt("by {author}", { author: item.author?.login ?? gt("unknown author") }), review ? review.accessibleLabel : null, @@ -178,6 +179,17 @@ export const PullRequestListRow = memo( {item.repository} #{item.number} + {item.visibility === "private" ? ( + + + + ) : null} {item.stack ? ( splitPullRequestBody(props.markdown), [props.markdown]); + const segments = useMemo( + () => splitPullRequestBody(props.markdown, markdownReferenceDefinitions), + [props.markdown], + ); const [undoneTicks, setUndoneTicks] = useState(0); const gallery: FilePreviewItem[] = markdownImageSources( props.imageGroupMarkdown ?? props.markdown, diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx index b6771b0954c16..cb897dc39c6cc 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx @@ -86,6 +86,7 @@ import { useAndroidWorkspaceBack } from "../layout/workspace/useAndroidWorkspace import { EmptyState } from "../../components/ui/EmptyState"; import { SegmentedControl } from "../../components/ui/SegmentedControl"; import { SymbolView } from "../../components/ui/AppSymbol"; +import { PullRequestGlyph } from "./pullRequestGlyphs"; import { ScreenContent } from "../../components/ui/ScreenContent"; import { RelativeTime } from "../../components/RelativeTime"; import { usePullRequestConnected } from "./usePullRequestConnected"; @@ -228,6 +229,16 @@ function PullRequestIdentity(props: { {status.label} )} + {"visibility" in pr && pr.visibility === "private" ? ( + + + {gt("Private")} + + ) : null} {"changedFiles" in pr && pr.changedFiles !== undefined ? ( diff --git a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts index 6500a79885a8d..7acb1640694f7 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts @@ -1,4 +1,4 @@ -import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown"; +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-references"; import { describe, expect, it } from "vite-plus/test"; import { nativePullRequestMarkdown } from "./pullRequestAutolinks"; diff --git a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts index 6d6a1bfe4b624..74e21d39018ee 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vite-plus/test"; -import type { MarkdownNode } from "../../lib/markdownDocument"; +import { markdownReferenceDefinitions, type MarkdownNode } from "../../lib/markdownDocument"; import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown"; import { pullRequestDescriptionContent } from "./pullRequestDescriptionContent"; @@ -15,6 +15,7 @@ describe("PR attachments", () => { } as MarkdownNode; const media = splitPullRequestBody( `${uri}\n\nhttps://drop.example.com/demo.mp4\n\nhttps://github.com/user-attachments/assets/123-abc`, + markdownReferenceDefinitions, ); expect(pullRequestDescriptionContent(document, media).attachments).toEqual([ { uri, caption: "Screenshot", kind: "image" }, @@ -30,6 +31,7 @@ describe("PR attachments", () => { it("collects videos from a before/after table", () => { const media = splitPullRequestBody( "\n\n\n
BeforeAfter
\n\nhttps://drop.example.com/before.mp4\n\n\n\nhttps://drop.example.com/after.mp4\n\n
", + markdownReferenceDefinitions, ); expect( pullRequestDescriptionContent({ type: "root" } as MarkdownNode, media).attachments, diff --git a/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts b/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts index fa79d882cc23d..16b84c596d627 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts @@ -7,4 +7,5 @@ export const PullRequestGlyph = { merged: "arrow.triangle.merge", stack: "square.3.layers.3d", conflicting: "exclamationmark.triangle", + private: { ios: "lock.fill", android: "lock" }, } as const satisfies Record; diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.ts b/apps/mobile/src/features/pull-requests/pullRequestList.ts index e7c2f5de769c4..3b30c11d65e64 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestList.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestList.ts @@ -190,6 +190,7 @@ export function pullRequestListRowsAreEqual( previous.title === next.title && previous.url === next.url && previous.state === next.state && + previous.visibility === next.visibility && previous.isDraft === next.isDraft && previous.mergeability === next.mergeability && previous.baseBranch === next.baseBranch && diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts b/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts index 105f4a1095009..5758e6b2ee84a 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts @@ -8,7 +8,7 @@ import { } from "@t3tools/client-runtime/pull-request-editing"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { PullRequestDetail } from "@t3tools/contracts"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { AsyncResult } from "effect/reactivity"; import { useGT } from "gt-react-native"; import { useRef, useState } from "react"; diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx index db2e7169d4930..881f67e86648f 100644 --- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx @@ -2,7 +2,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native" import { TextInputWrapper } from "expo-paste-input"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { T, useGT } from "gt-react-native"; -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { ScrollView, View, useWindowDimensions } from "react-native"; import * as Dialog from "../../components/ui/Dialog"; import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal"; @@ -16,6 +16,7 @@ import { cn } from "../../lib/cn"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages"; import { useNativePaste } from "../../lib/useNativePaste"; +import { scheduleUnusedComposerAttachmentCleanup } from "../../state/use-composer-drafts"; import { setPendingConnectionError } from "../../state/use-remote-environment-registry"; import { appendReviewCommentToDraft } from "../../state/use-thread-composer-state"; import { @@ -49,6 +50,31 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp const { environmentId, threadId } = props.route.params; const [commentText, setCommentText] = useState(""); const [attachments, setAttachments] = useState>([]); + const attachmentsRef = useRef(attachments); + const isMountedRef = useRef(true); + // Store file references before React commits, so closing the sheet can release them. + const replaceAttachments = (next: ReadonlyArray) => { + attachmentsRef.current = next; + setAttachments(next); + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases owned image files when the sheet unmounts + useEffect(() => { + isMountedRef.current = true; + return () => { + isMountedRef.current = false; + scheduleUnusedComposerAttachmentCleanup(attachmentsRef.current); + }; + }, []); + + function appendImages(images: ReadonlyArray): void { + if (!isMountedRef.current) { + scheduleUnusedComposerAttachmentCleanup(images); + return; + } + if (images.length > 0) { + replaceAttachments([...attachmentsRef.current, ...images]); + } + } const [previewFile, setPreviewFile] = useState(null); const { selectedLines, highlightedLinesById } = useMemo(() => { @@ -90,27 +116,25 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp }; const handleNativePaste = useNativePaste((uris) => { void (async () => { - try { - const result = await convertPastedImagesToAttachments({ - uris, - existingCount: attachments.length, - }); - if (result.attachments.length > 0) { - setAttachments((current) => [...current, ...result.attachments]); - } - if (result.error) Dialog.alert(gt("Could not paste image"), result.error); - } catch (error) { + const result = await convertPastedImagesToAttachments({ + uris, + existingCount: attachmentsRef.current.length, + }).catch((error: unknown) => { console.error("[review comment] error converting pasted images", error); + return null; + }); + if (result === null) return; + appendImages(result.attachments); + if (result.error && isMountedRef.current) { + Dialog.alert(gt("Could not paste image"), result.error); } })(); }); async function handlePickImages(): Promise { - const result = await pickComposerImages({ existingCount: attachments.length }); - if (result.images.length > 0) { - setAttachments((current) => [...current, ...result.images]); - } - if (result.error) { + const result = await pickComposerImages({ existingCount: attachmentsRef.current.length }); + appendImages(result.images); + if (result.error && isMountedRef.current) { setPendingConnectionError(result.error); } } @@ -124,9 +148,10 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp environmentId, threadId, text: formatReviewCommentContext(target, commentText), - attachments, + attachments: attachmentsRef.current, }); - setAttachments([]); + scheduleUnusedComposerAttachmentCleanup(attachmentsRef.current); + replaceAttachments([]); dismissComposer(); }; @@ -255,9 +280,12 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp onPressPreview={setPreviewFile} removeButtonPlacement="gutter" onRemove={(imageId) => { - setAttachments((current) => - current.filter((image) => image.id !== imageId), - ); + const current = attachmentsRef.current; + const removed = current.find((image) => image.id === imageId); + replaceAttachments(current.filter((image) => image.id !== imageId)); + if (removed) { + scheduleUnusedComposerAttachmentCleanup([removed]); + } }} />
diff --git a/apps/mobile/src/features/settings/CloudVoiceSection.tsx b/apps/mobile/src/features/settings/CloudVoiceSection.tsx index dceb42d86e457..3e782d2457fa3 100644 --- a/apps/mobile/src/features/settings/CloudVoiceSection.tsx +++ b/apps/mobile/src/features/settings/CloudVoiceSection.tsx @@ -2,6 +2,7 @@ import { T, useGT, useMessages } from "gt-react-native"; import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; import { cloudSpeechDisclosure } from "@t3tools/shared/speechCopy"; import { setCloudSpeechKey } from "@t3tools/client-runtime/voice-input"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { configuredSecretSources, secretRequestReference, @@ -20,7 +21,6 @@ import { type VoiceTranscriptionDestination, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; -import Constants from "expo-constants"; import { AsyncResult } from "effect/reactivity"; import { type ReactNode, useState } from "react"; import { ScrollView, TextInput, View } from "react-native"; @@ -199,7 +199,7 @@ function CloudChoices({ environment, active, onClose }: Props & { onClose: () => const [model, setModel] = useState(""); const [sourceId, setSourceId] = useState(null); const sources = - Constants.expoConfig?.extra?.secretsFeatureEnabled === true && + hasFeatureFlag(environment.serverConfig, "secretProviders") && environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings.secretProviders, messages) : []; diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx index 8e15dad08ac23..e878f86581b4a 100644 --- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx @@ -1228,6 +1228,7 @@ function TaskForm({ display={Platform.OS === "ios" ? "spinner" : "default"} onDismiss={() => setTimePickerOpen(false)} onValueChange={(_, selected) => { + if (Platform.OS === "android") setTimePickerOpen(false); const timeOfDay = `${String(selected.getHours()).padStart(2, "0")}:${String(selected.getMinutes()).padStart(2, "0")}`; setDraft((current) => ({ ...current, diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts index 1dea547de53b4..7ca92b23c3208 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from "@effect/vitest"; +import { describe, expect, it, vi } from "vite-plus/test"; import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, @@ -13,6 +13,32 @@ import { selectIncomingShareAttachmentsForServer, } from "./incoming-share-model"; +const nativeImage = vi.hoisted(() => ({ + resize: vi.fn(), +})); + +vi.mock("expo-image-manipulator", () => ({ + SaveFormat: { PNG: "png", JPEG: "jpeg" }, + ImageManipulator: { + manipulate: (source: string | { width: number; height: number }) => { + let size = typeof source === "string" ? { width: 3000, height: 1500 } : source; + const context = { + resize: (next: { width: number; height: number }) => { + nativeImage.resize(next); + size = next; + return context; + }, + renderAsync: async () => ({ + ...size, + release: () => {}, + saveAsync: async () => ({ uri: "file:///cache/resized.png", base64: "YWJj" }), + }), + }; + return context; + }, + }, +})); + describe("incoming native shares", () => { it("converts shared text, URLs, and images into a durable composer draft", async () => { const image: SharePayload = { @@ -35,6 +61,9 @@ describe("incoming native shares", () => { originalName: "Screenshot.png", }; const removeOwnedFile = vi.fn(() => Promise.resolve()); + const readBase64 = vi.fn(async () => "YWJj"); + const persistedUri = "file:///documents/t3-composer-attachments/Screenshot.png"; + const persistFile = vi.fn(async () => persistedUri); const result = await buildIncomingShareDraft({ id: "share-1", @@ -42,7 +71,9 @@ describe("incoming native shares", () => { payloads, resolvedPayloads: [resolvedImage], fileReader: { - readBase64: async () => "YWJj", + readBase64, + persistFile, + readSize: async (uri) => (uri === persistedUri ? 3 : null), removeOwnedFile, }, }); @@ -59,16 +90,95 @@ describe("incoming native shares", () => { name: "Screenshot.png", mimeType: "image/png", sizeBytes: 3, - dataUrl: "data:image/png;base64,YWJj", - previewUri: "data:image/png;base64,YWJj", + fileUri: persistedUri, + previewUri: persistedUri, }, ], warnings: [], }); expect(removeOwnedFile).toHaveBeenCalledWith(image.value); + expect(removeOwnedFile).not.toHaveBeenCalledWith(persistedUri); expect(hasIncomingShareContent(result)).toBe(true); }); + it("persists the resized PNG for a shared image over 2000px", async () => { + const header = Buffer.alloc(24); + header.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + header.set([0x49, 0x48, 0x44, 0x52], 12); + header.writeUInt32BE(3000, 16); + header.writeUInt32BE(1500, 20); + const persistedUri = "file:///documents/t3-composer-attachments/screenshot.png"; + const persistFile = vi.fn(async () => persistedUri); + const removeOwnedFile = vi.fn(async (_uri: string) => undefined); + + const draft = await buildIncomingShareDraft({ + id: "share-resize", + createdAt: "2026-07-15T10:00:00.000Z", + payloads: [ + { shareType: "image", value: "content://shared/screenshot", mimeType: "image/png" }, + ], + resolvedPayloads: [], + fileReader: { + readBase64: async () => header.toString("base64"), + persistFile, + readSize: async () => 3, + removeOwnedFile, + }, + }); + + expect(nativeImage.resize).toHaveBeenCalledWith({ width: 2000, height: 1000 }); + expect(persistFile).toHaveBeenCalledWith("file:///cache/resized.png", "screenshot"); + expect(draft.attachments).toEqual([ + { + id: "share-resize-image-0", + type: "image", + name: "screenshot", + mimeType: "image/png", + sizeBytes: 3, + fileUri: persistedUri, + previewUri: persistedUri, + }, + ]); + expect(draft.warnings).toEqual([]); + expect(removeOwnedFile).not.toHaveBeenCalledWith(persistedUri); + }); + + it("releases a shared image when its stored size cannot be measured", async () => { + const image: SharePayload = { + shareType: "image", + value: "file:///shared/photo.png", + mimeType: "image/png", + }; + const persistedUri = "file:///documents/t3-composer-attachments/photo.png"; + const removeOwnedFile = vi.fn(async (_uri: string) => undefined); + const result = await buildIncomingShareDraft({ + id: "share-unmeasured", + createdAt: "2026-07-15T10:00:00.000Z", + payloads: [image], + resolvedPayloads: [ + { + ...image, + contentUri: image.value, + contentType: "image", + contentMimeType: "image/png", + contentSize: 3, + originalName: "photo.png", + }, + ], + fileReader: { + readBase64: async () => "unused", + persistFile: async () => persistedUri, + readSize: async () => null, + removeOwnedFile, + }, + }); + + expect(result.attachments).toEqual([]); + expect(result.warnings).toEqual(["'photo.png' is empty or could not be read."]); + expect(removeOwnedFile).toHaveBeenCalledWith(persistedUri); + expect(removeOwnedFile).toHaveBeenCalledWith(image.value); + }); + it("skips oversized images and releases the temporary native file", async () => { const image: SharePayload = { shareType: "image", diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts index 9bfc2dcca1b29..86c17c6059e0e 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.ts @@ -412,6 +412,9 @@ export async function buildIncomingShareDraft(input: { continue; } + const name = resolved?.originalName ?? fallbackName(uri, index, mimeType); + let persistedImageUri: string | undefined; + let retainedImageUri: string | undefined; try { const sharedBase64 = await input.fileReader.readBase64(uri); // Use already-read bytes because native image loaders may not read the provider's file. @@ -421,36 +424,54 @@ export async function buildIncomingShareDraft(input: { base64: sharedBase64, }); const base64 = fitted?.base64 ?? sharedBase64; - const sizeBytes = fitted - ? estimateBase64ByteSize(base64) - : (resolved?.contentSize ?? estimateBase64ByteSize(base64)); - if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - warnings.push( - m( - msg("''{name}'' exceeds the 10 MB attachment limit.", { - name: resolved?.originalName ?? fallbackName(uri, index, mimeType), - }), - ), - ); + const decodedSize = estimateBase64ByteSize(base64); + if (decodedSize <= 0 || decodedSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + warnings.push(m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name }))); + continue; + } + if (input.fileReader.persistFile) { + persistedImageUri = await input.fileReader.persistFile(fitted?.uri ?? uri, name); + const sizeBytes = (await input.fileReader.readSize?.(persistedImageUri)) ?? null; + if (sizeBytes === null || sizeBytes <= 0) { + warnings.push(m(msg("''{name}'' is empty or could not be read.", { name }))); + continue; + } + if (sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, m)); + continue; + } + attachments.push({ + id: `${input.id}-image-${index}`, + type: "image", + name, + mimeType, + sizeBytes, + fileUri: persistedImageUri, + previewUri: persistedImageUri, + }); + retainedImageUri = persistedImageUri; continue; } const dataUrl = `data:${mimeType};base64,${base64}`; attachments.push({ id: `${input.id}-image-${index}`, type: "image", - name: resolved?.originalName ?? fallbackName(uri, index, mimeType), + name, mimeType, - sizeBytes, + sizeBytes: decodedSize, dataUrl, // Data-backed previews outlive temporary share files and App Group entries. previewUri: dataUrl, }); } catch { - warnings.push( - m(msg("Could not read ''{name}''.", { name: fallbackName(uri, index, mimeType) })), - ); + warnings.push(m(msg("Could not read ''{name}''.", { name }))); } finally { - await releaseOwnedFiles(input.fileReader, [uri, payload.value]); + await releaseOwnedFiles( + input.fileReader, + [uri, payload.value, persistedImageUri].filter( + (candidate) => candidate !== retainedImageUri, + ), + ); } } diff --git a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx index 97a3ce45fab3a..a8cc689b7a5cf 100644 --- a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx +++ b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx @@ -36,6 +36,7 @@ import { cn } from "../../lib/cn"; import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { vcsEnvironment } from "../../state/vcs"; +import { useRefreshBranchesOnFocus } from "./use-refresh-branches-on-focus"; import { useSearchToolbarInset } from "../../components/ui/useBarInset"; import type { AppBarSearch } from "../../components/ui/AppBar"; import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider"; @@ -466,6 +467,7 @@ export function BranchPickerScreen(props: { const m = useMessages(); const navigation = useNavigation(); const insets = useSafeAreaInsets(); + useRefreshBranchesOnFocus(props.project?.environmentId, props.project?.workspaceRoot); const search: AppBarSearch = { value: props.query, onChangeText: props.onQueryChange, diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index a28c03843b163..025b91326762b 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -860,7 +860,10 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ); } - if (imageSource._tag === "Blocked") { + if ( + media?.kind !== "image" || + !("resource" in media.source) || + media.source.resource._tag !== "media-file" + ) { return ; } return ( ); @@ -4400,6 +4396,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { {...(usesNativeAutomaticInsets ? { contentInset: { top: anchorTopInset } } : {})} freeze={props.freeze} maintainScrollAtEnd={jumpReady ? false : THREAD_FEED_MAINTAIN_SCROLL_AT_END} + maintainScrollAtEndThreshold={THREAD_FEED_MAINTAIN_SCROLL_AT_END_THRESHOLD} maintainVisibleContentPosition data={groupedFeed} extraData={listAppearanceData} diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx index 82f5cc62a7b68..2f2bffa336402 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx @@ -82,9 +82,6 @@ vi.mock("expo/fetch", () => ({ fetch: vi.fn() })); vi.mock("react-native-svg", () => ({ parse: vi.fn(), SvgAst: () => null })); vi.mock("@t3tools/client-runtime/state/assets", () => ({ MISSING_FILE_ACCESS_MESSAGE: "" })); vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null })); -vi.mock("../../components/ui/FilePreviewGallery", () => ({ - useFilePreviewGallery: () => (source: unknown) => source, -})); vi.mock("../../components/ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => {children}, })); @@ -96,11 +93,64 @@ vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: vi.mock("../../state/assets", () => ({ useAssetUrlState: vi.fn() })); import { RegistryContext } from "@effect/atom-react"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { AtomRegistry } from "effect/reactivity"; import { fetch } from "expo/fetch"; import { parse } from "react-native-svg"; -import { MarkdownImageAvailableWidthContext, ThreadMarkdownImageView } from "./ThreadMarkdownImage"; +import { FilePreviewGallery } from "../../components/ui/FilePreviewGallery"; +import type { FilePreviewSource } from "../../components/ui/FilePreviewModal.types"; +import { useAssetUrlState } from "../../state/assets"; +import { + MarkdownImageAvailableWidthContext, + ThreadMarkdownImage, + ThreadMarkdownImageView, +} from "./ThreadMarkdownImage"; + +it("keeps the tapped workspace image fragment on its gallery page", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const root = createRoot(document.createElement("div")); + const environmentId = EnvironmentId.make("environment-1"); + const threadId = ThreadId.make("thread-1"); + const resource = { _tag: "media-file", threadId, path: "/repo/./red.png" } as const; + const red = { kind: "image", environmentId, resource, srcFragment: "#detail" } as const; + const blue = { + kind: "image", + environmentId, + resource: { ...resource, path: "/repo/./blue.png" }, + } as const; + const openPreview = vi.fn<(source: FilePreviewSource) => void>(); + vi.mocked(useAssetUrlState).mockReturnValueOnce({ + _tag: "Success", + url: "https://example.test/red.png", + expiresAt: 0, + }); + try { + await act(async () => + root.render( + + + , + ), + ); + await act(async () => harness.pressable.onPress?.({ nativeEvent: {} })); + expect(openPreview).toHaveBeenCalledWith( + expect.objectContaining({ + resource, + srcFragment: "#detail", + gallery: [expect.objectContaining(red), blue], + }), + ); + } finally { + await act(async () => root.unmount()); + } +}); it("keeps the frame size when the same image reports a different decoded width", async () => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx index 8a7540625cc08..8e18d8445c85a 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx @@ -342,6 +342,7 @@ export function ThreadMarkdownImage(props: { gallery: undefined, environmentId: props.environmentId, resource: props.resource, + ...(props.srcFragment === undefined ? {} : { srcFragment: props.srcFragment }), }), ); }} diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx index 56be7cd27d7a9..f90416a70b8b4 100644 --- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx @@ -118,11 +118,10 @@ import { } from "./thread-settings-options"; import { canCommitPendingModel, - favoritesFirst, modelFavoriteKey, - modelMatchesCatalogQuery, pendingModelAfterPress, providerSectionIsCollapsed, + visibleCatalogModels, } from "./thread-settings-sheet-state"; import { formatProviderUpdateRequiredNotice } from "@t3tools/client-runtime/providerUpdateRequiredModels"; import type { MessageResolver } from "../../i18n/messages"; @@ -896,28 +895,15 @@ function buildThreadSettingsCatalogItems( return []; } const driver = group.models[0]?.providerDriver ?? group.providerKey; - const catalogModels = - session.manageHidden || - session.showLegacy || - session.providerFilter === FAVORITES_PROVIDER_FILTER - ? group.models - : group.models.filter( - (model) => - !model.isLegacy || session.isDisplayed(model) || session.favoriteKeys.has(model.key), - ); - const visibleModels = favoritesFirst( - catalogModels.filter( - (model) => - (session.providerFilter !== FAVORITES_PROVIDER_FILTER || - session.favoriteKeys.has(model.key)) && - modelMatchesCatalogQuery({ - model, - providerLabel: group.providerLabel, - query: session.searchQuery, - }), - ), - session.favoriteKeys, - ); + const visibleModels = visibleCatalogModels({ + models: group.models, + providerLabel: group.providerLabel, + query: session.searchQuery, + favoriteKeys: session.favoriteKeys, + favoritesOnly: session.providerFilter === FAVORITES_PROVIDER_FILTER, + showLegacy: session.manageHidden || session.showLegacy, + isDisplayed: session.isDisplayed, + }); const updateRequiredNotice = group.updateRequired && session.providerFilter !== FAVORITES_PROVIDER_FILTER ? formatProviderUpdateRequiredNotice( diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx index 436fb4dd0b403..8653d859442f4 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx @@ -8,7 +8,10 @@ const checkout = vi.hoisted(() => ({ branches: [] as Array<{ name: string; worktreePath: string | null }>, })); -vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) })); +vi.mock("@react-navigation/native", () => ({ + useFocusEffect: () => {}, + useNavigation: () => ({}), +})); vi.mock("../../../components/ui/SheetHeader", () => ({ SheetHeader: () => null })); vi.mock("../../../components/ui/FitSheet", () => ({ FitSheet: ({ children }: { children: ReactNode }) =>
{children}
, diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx index 084dd7880fba1..f0ddc71fea15d 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx @@ -20,6 +20,7 @@ const state = vi.hoisted(() => ({ })); vi.mock("@react-navigation/native", () => ({ + useFocusEffect: () => {}, useNavigation: () => ({ goBack: () => state.goBackCalls++, isFocused: () => state.focused, diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx index df1ad6649c8f7..618996c61500c 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx @@ -14,6 +14,7 @@ import { useSelectedThreadGitActions } from "../../../state/use-selected-thread- import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state"; import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree"; import { vcsEnvironment } from "../../../state/vcs"; +import { useRefreshBranchesOnFocus } from "../use-refresh-branches-on-focus"; import { SheetActionButton } from "./gitSheetComponents"; type GitBranchesSheetProps = StaticScreenProps<{ @@ -26,6 +27,7 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) { const navigation = useNavigation(); const { selectedThread } = useThreadSelection(); const { selectedThreadCwd } = useSelectedThreadWorktree(); + useRefreshBranchesOnFocus(selectedThread?.environmentId, selectedThreadCwd); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); const { canChangeThreadBranch } = gitActions; diff --git a/apps/mobile/src/features/threads/legendListAtEnd.test.ts b/apps/mobile/src/features/threads/legendListAtEnd.test.ts new file mode 100644 index 0000000000000..fc0dbcfbe0b56 --- /dev/null +++ b/apps/mobile/src/features/threads/legendListAtEnd.test.ts @@ -0,0 +1,107 @@ +import * as NodeFS from "node:fs"; +import * as NodeModule from "node:module"; +import * as NodePath from "node:path"; +import * as NodeVM from "node:vm"; + +import { describe, expect, it } from "vite-plus/test"; + +import { + THREAD_FEED_MAINTAIN_SCROLL_AT_END, + THREAD_FEED_MAINTAIN_SCROLL_AT_END_THRESHOLD, +} from "./threadFeedEndFollow"; + +const require = NodeModule.createRequire(import.meta.url); + +interface ListInternals { + readonly checkAtBottom: (ctx: unknown) => void; + readonly settleUserScroll: (ctx: unknown) => void; +} + +// The end checks are internal to the patched bundle; expose them from the native build as seen on iOS. +function loadPatchedListInternals(): ListInternals { + const webBundlePath = require.resolve("@legendapp/list/react-native"); + const bundlePath = NodePath.join(NodePath.dirname(webBundlePath), "react-native.js"); + const source = `${NodeFS.readFileSync(bundlePath, "utf8")}\nmodule.exports.internals = { checkAtBottom, settleUserScroll };`; + const inert: object = new Proxy(function () {}, { + get: (_target, key) => (key === Symbol.toPrimitive ? () => "" : inert), + apply: () => inert, + construct: () => inert, + }); + const withInertFallback = (target: object) => + new Proxy(target, { + get: (object, key) => (key in object ? Reflect.get(object, key) : inert), + }); + const reactNative = withInertFallback({ Platform: withInertFallback({ OS: "ios" }) }); + const module = { exports: {} as { internals?: ListInternals } }; + NodeVM.compileFunction(source, ["exports", "require", "module"], { filename: bundlePath })( + module.exports, + (id: string) => (id === "react-native" ? reactNative : inert), + module, + ); + const internals = module.exports.internals; + if (!internals) throw new Error(`list internals not found in ${bundlePath}`); + return internals; +} + +const { checkAtBottom, settleUserScroll } = loadPatchedListInternals(); + +// iPhone 17 Pro thread feed: header inset 116, composer inset 142.5, rows 693.29, +// so the end rests at -38.21 and the start at -116. +const scrollLength = 874; +const insetTop = 116; +const insetBottom = 142.5; +const contentSize = 835.79; + +function createFeedList(scroll: number, rowsLength = contentSize - insetBottom) { + const values = new Map([["totalSize", rowsLength]]); + const ctx = { + values, + listeners: new Map(), + scrollAxisGap: 0, + state: { + queuedInitialLayout: true, + didFinishInitialScroll: true, + scroll, + scrollLength, + scheduledWork: { cancel: () => {}, has: () => false }, + props: { + data: [{}], + contentInset: { top: insetTop, bottom: insetBottom }, + maintainScrollAtEnd: THREAD_FEED_MAINTAIN_SCROLL_AT_END, + maintainScrollAtEndThreshold: THREAD_FEED_MAINTAIN_SCROLL_AT_END_THRESHOLD, + onEndReachedThreshold: 0.5, + }, + }, + }; + return { ctx, values }; +} + +function isAtEnd(scroll: number, rowsLength?: number) { + const { ctx, values } = createFeedList(scroll, rowsLength); + checkAtBottom(ctx); + return values.get("isAtEnd"); +} + +describe("patched LegendList end detection in the thread feed", () => { + it("does not report the start edge as the end when content overflows below the header inset", () => { + expect(isAtEnd(contentSize - scrollLength)).toBe(true); + expect(isAtEnd(-insetTop, 758 - insetBottom), "content that exactly fits").toBe(true); + + expect( + isAtEnd(-insetTop), + "a feed pulled to its start edge (scroll -116) is 77.8pt from its end", + ).toBe(false); + expect(isAtEnd(-114), "a feed just below its start edge is 75.8pt from its end").toBe(false); + }); + + it("does not re-arm end following when a pull to the start edge is released", () => { + const { ctx, values } = createFeedList(-insetTop); + checkAtBottom(ctx); + Object.assign(ctx.state, { userScrollContentSize: contentSize }); + settleUserScroll(ctx); + checkAtBottom(ctx); + + expect(values.get("isFollowingEnd")).toBe(false); + expect(values.get("isWithinMaintainScrollAtEndThreshold")).toBe(false); + }); +}); diff --git a/apps/mobile/src/features/threads/thread-command-output.tsx b/apps/mobile/src/features/threads/thread-command-output.tsx index ee74a86e3db5b..2a929d96e5f7c 100644 --- a/apps/mobile/src/features/threads/thread-command-output.tsx +++ b/apps/mobile/src/features/threads/thread-command-output.tsx @@ -73,7 +73,7 @@ export function ThreadCommandOutput(props: { }} > {data?.output.truncated ? ( - + Earlier output not shown ) : null} diff --git a/apps/mobile/src/features/threads/thread-settings-sheet-state.test.ts b/apps/mobile/src/features/threads/thread-settings-sheet-state.test.ts index 53b5874c7e3a7..49910ca1871f4 100644 --- a/apps/mobile/src/features/threads/thread-settings-sheet-state.test.ts +++ b/apps/mobile/src/features/threads/thread-settings-sheet-state.test.ts @@ -11,7 +11,11 @@ import { rememberModelOptions, withRememberedModelOptions, } from "../../state/use-model-option-memory"; -import { canCommitPendingModel, pendingModelAfterPress } from "./thread-settings-sheet-state"; +import { + canCommitPendingModel, + pendingModelAfterPress, + visibleCatalogModels, +} from "./thread-settings-sheet-state"; function modelOption( model: string, @@ -158,4 +162,23 @@ describe("thread settings sheet state", () => { ]), ).toBe(false); }); + + it("finds legacy models by search without enabling Show legacy models", () => { + const current = modelOption("gpt-next"); + const legacy = { ...modelOption("claude-opus-4-8"), label: "Claude Opus 4.8", isLegacy: true }; + const visible = (query: string) => + visibleCatalogModels({ + models: [current, legacy], + providerLabel: "Codex", + query, + favoriteKeys: new Set(), + favoritesOnly: false, + showLegacy: false, + isDisplayed: () => false, + }).map((model) => model.label); + + expect(visible("")).toEqual(["gpt-next"]); + expect(visible(" ")).toEqual(["gpt-next"]); + expect(visible("Claude Opus 4.8")).toEqual(["Claude Opus 4.8"]); + }); }); diff --git a/apps/mobile/src/features/threads/thread-settings-sheet-state.ts b/apps/mobile/src/features/threads/thread-settings-sheet-state.ts index 4fff09253ab4b..120e7f7e68236 100644 --- a/apps/mobile/src/features/threads/thread-settings-sheet-state.ts +++ b/apps/mobile/src/features/threads/thread-settings-sheet-state.ts @@ -35,6 +35,36 @@ export function modelMatchesCatalogQuery(input: { ].some((value) => value.toLocaleLowerCase().includes(query)); } +export function visibleCatalogModels(input: { + readonly models: ReadonlyArray; + readonly providerLabel: string; + readonly query: string; + readonly favoriteKeys: ReadonlySet; + readonly favoritesOnly: boolean; + readonly showLegacy: boolean; + readonly isDisplayed: (model: ModelOption) => boolean; +}): ReadonlyArray { + const catalogModels = + input.showLegacy || input.favoritesOnly || input.query.trim().length > 0 + ? input.models + : input.models.filter( + (model) => + !model.isLegacy || input.isDisplayed(model) || input.favoriteKeys.has(model.key), + ); + return favoritesFirst( + catalogModels.filter( + (model) => + (!input.favoritesOnly || input.favoriteKeys.has(model.key)) && + modelMatchesCatalogQuery({ + model, + providerLabel: input.providerLabel, + query: input.query, + }), + ), + input.favoriteKeys, + ); +} + export function pendingModelAfterPress(input: { readonly current: ModelOption | null; readonly pressed: ModelOption; diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index 8f22d0b511651..f0bc00e11385e 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -971,7 +971,7 @@ const ThreadWorkLogRow = function ThreadWorkLogRow( ) : null} {timestamp.toLocaleString(undefined, { month: "short", @@ -1185,7 +1185,7 @@ const ThreadWorkLogRow = function ThreadWorkLogRow( row.workEntry.questionAnswer && hasQuestionAnswer(row.workEntry.questionAnswer) ? "text-foreground" - : "text-foreground-subtle" + : "text-foreground-muted" } >{` ${answerPreview}`} ) : null} diff --git a/apps/mobile/src/features/threads/threadFeedEndFollow.ts b/apps/mobile/src/features/threads/threadFeedEndFollow.ts new file mode 100644 index 0000000000000..d4f42c2b2e6e6 --- /dev/null +++ b/apps/mobile/src/features/threads/threadFeedEndFollow.ts @@ -0,0 +1,8 @@ +export const THREAD_FEED_MAINTAIN_SCROLL_AT_END = { + animated: false, + on: { dataChange: true, itemLayout: true, layout: true }, +} as const; + +// Re-arm end following only at the end itself: a release short of it, such as pulling to +// load earlier activity, must not snap back to the end. +export const THREAD_FEED_MAINTAIN_SCROLL_AT_END_THRESHOLD = 0; diff --git a/apps/mobile/src/features/threads/use-refresh-branches-on-focus.ts b/apps/mobile/src/features/threads/use-refresh-branches-on-focus.ts new file mode 100644 index 0000000000000..6366994b9641e --- /dev/null +++ b/apps/mobile/src/features/threads/use-refresh-branches-on-focus.ts @@ -0,0 +1,25 @@ +import { RegistryContext } from "@effect/atom-react"; +import { useFocusEffect } from "@react-navigation/native"; +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { useCallback, useContext } from "react"; + +import { vcsEnvironment } from "../../state/vcs"; + +export function useRefreshBranchesOnFocus( + environmentId: EnvironmentId | undefined, + cwd: string | null | undefined, +) { + const registry = useContext(RegistryContext); + useFocusEffect( + useCallback(() => { + if (environmentId === undefined || !cwd) return; + void runAtomCommand( + registry, + vcsEnvironment.refreshLocalStatusForPicker, + { environmentId, input: { cwd } }, + { reportFailure: false }, + ); + }, [cwd, environmentId, registry]), + ); +} diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 96d8f922340f7..50a987787b4e4 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -20,6 +20,7 @@ import { import { msg, T, useGT, useMessages, Var } from "gt-react-native"; import { Fragment, type ReactNode, useId, useState } from "react"; import { Pressable, View } from "react-native"; +import { useNowMinuteMs } from "../../lib/clock"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; import { Defs, Path, Pattern, Rect, Svg } from "react-native-svg"; @@ -201,7 +202,6 @@ function PoolWindowCard({ windowId: pool.id, windowKind: pool.kind, environmentIds, - now, }); const summary = ( <> @@ -211,7 +211,7 @@ function PoolWindowCard({ {label ?? pool.label} ) : null} - + {pool.remainingPercent}% @@ -590,13 +590,13 @@ type AccountScreenProps = StaticScreenProps<{ windowId: string; windowKind: LimitPoolWindow["kind"]; environmentIds: readonly string[] | null; - now: number; }>; export function UsageLimitAccountScreen({ route }: AccountScreenProps) { const insets = useSafeAreaInsets(); const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); - const { accountKey, windowId, windowKind, environmentIds, now } = route.params; + const { accountKey, windowId, windowKind, environmentIds } = route.params; + const now = useNowMinuteMs(); const selectedIds = environmentIds === null ? null : new Set(environmentIds.map((id) => EnvironmentId.make(id))); const selected = diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index f538b87920412..f4d80a116eece 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} konnte keine WebSocket-Verbindung herstellen.", "d9ce6c142a485959": "{host} hat {seconds} s lang nicht geantwortet.", "d6bdce8f4e6101a4": "{host} wurde getrennt.", + "8450a95e5214d199": "{host} hat ein Update der Serverkonfiguration gesendet, das dieser Client nicht lesen konnte.", + "56b4ff3993c93eca": "{host} hat eine inkompatible Serverkonfiguration gesendet.", + "368c4d4f99c66bfb": "Aktualisiere Client und Server auf kompatible Versionen.", "e5fd422e445391fc": "Upload fehlgeschlagen. Zum Wiederholen tippen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2851,6 +2854,7 @@ "f9d3c8aa453829ce": "Tippe auf eine Person, um ein Review anzufordern. Tippe auf einen angefragten Reviewer, um die Anfrage zu entfernen. Änderungen werden beim Schließen dieses Fensters gesendet.", "8d3770f150f0bcb4": "Angefragt", "fff1c3d17603f394": "Dieser Anbieter akzeptiert eine Reviewer-ID, kann aber keine Kandidaten auflisten.", + "bbb7d40a7ad7ab71": "Privat", "85ae9979ad3b0c1e": "Basis-Branch {branch} kopieren", "06a684782801e8f7": "Head-Branch {branch} kopieren", "8e4f3c862193b8a5": "Bearbeiten", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 745201ad99094..62b182b1a30c9 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} could not establish a WebSocket connection.", "d9ce6c142a485959": "{host} stopped responding for {seconds}s.", "d6bdce8f4e6101a4": "{host} disconnected.", + "8450a95e5214d199": "{host} sent a server configuration update this client could not read.", + "56b4ff3993c93eca": "{host} sent an incompatible server configuration.", + "368c4d4f99c66bfb": "Update the client and server to compatible versions.", "e5fd422e445391fc": "Upload failed. Tap to retry.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2851,6 +2854,7 @@ "f9d3c8aa453829ce": "Tap someone to request a review. Tap a requested reviewer to remove the request. Changes are sent when you close this sheet.", "8d3770f150f0bcb4": "Requested", "fff1c3d17603f394": "This provider accepts a reviewer ID but cannot list candidates.", + "bbb7d40a7ad7ab71": "Private", "85ae9979ad3b0c1e": "Copy base branch {branch}", "06a684782801e8f7": "Copy head branch {branch}", "8e4f3c862193b8a5": "Edit", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index fb134339cd3c4..55d4e81456cc5 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} no pudo establecer una conexión WebSocket.", "d9ce6c142a485959": "{host} dejó de responder durante {seconds} s.", "d6bdce8f4e6101a4": "{host} se desconectó.", + "8450a95e5214d199": "{host} envió una actualización de la configuración del servidor que este cliente no pudo leer.", + "56b4ff3993c93eca": "{host} envió una configuración del servidor incompatible.", + "368c4d4f99c66bfb": "Actualiza el cliente y el servidor a versiones compatibles.", "e5fd422e445391fc": "Error al subir. Toca para reintentar.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2847,6 +2850,7 @@ "f9d3c8aa453829ce": "Toca a alguien para solicitarle una revisión. Toca a un revisor solicitado para quitar la solicitud. Los cambios se envían al cerrar esta hoja.", "8d3770f150f0bcb4": "Solicitado", "fff1c3d17603f394": "Este proveedor acepta un ID de revisor, pero no puede listar candidatos.", + "bbb7d40a7ad7ab71": "Privado", "85ae9979ad3b0c1e": "Copiar la rama base {branch}", "06a684782801e8f7": "Copiar la rama head {branch}", "8e4f3c862193b8a5": "Editar", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index d6aef220df3a2..245547981f3dc 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} n’a pas pu établir de connexion WebSocket.", "d9ce6c142a485959": "{host} ne répond plus depuis {seconds} s.", "d6bdce8f4e6101a4": "{host} est déconnecté.", + "8450a95e5214d199": "{host} a envoyé une mise à jour de la configuration du serveur que ce client n’a pas pu lire.", + "56b4ff3993c93eca": "{host} a envoyé une configuration de serveur incompatible.", + "368c4d4f99c66bfb": "Mettez à jour le client et le serveur vers des versions compatibles.", "e5fd422e445391fc": "Échec de l’envoi. Touchez pour réessayer.", "b2bc6bd92ea24e5c": "{size} Mo", "88f84178edbb7f57": "{size} Ko", @@ -2847,6 +2850,7 @@ "f9d3c8aa453829ce": "Touchez une personne pour lui demander une revue. Touchez un relecteur sollicité pour retirer la demande. Les modifications sont envoyées à la fermeture de ce panneau.", "8d3770f150f0bcb4": "Sollicité", "fff1c3d17603f394": "Ce fournisseur accepte un ID de relecteur mais ne peut pas lister les candidats.", + "bbb7d40a7ad7ab71": "Privé", "85ae9979ad3b0c1e": "Copier la branche de base {branch}", "06a684782801e8f7": "Copier la branche de tête {branch}", "8e4f3c862193b8a5": "Modifier", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 8cd9fba5c8332..a62452cddc89d 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} は WebSocket 接続を確立できませんでした。", "d9ce6c142a485959": "{host} は {seconds} 秒間応答していません。", "d6bdce8f4e6101a4": "{host} の接続が切断されました。", + "8450a95e5214d199": "{host} から、このクライアントで読み取れないサーバー設定の更新が送信されました。", + "56b4ff3993c93eca": "{host} から互換性のないサーバー設定が送信されました。", + "368c4d4f99c66bfb": "クライアントとサーバーを互換性のあるバージョンに更新してください。", "e5fd422e445391fc": "アップロードに失敗しました。タップして再試行してください。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2844,6 +2847,7 @@ "f9d3c8aa453829ce": "ユーザーをタップするとレビューをリクエストします。リクエスト済みのレビュアーをタップするとリクエストを削除します。変更はこのシートを閉じたときに送信されます。", "8d3770f150f0bcb4": "リクエスト済み", "fff1c3d17603f394": "このプロバイダーはレビュアー ID を受け付けますが、候補を一覧表示できません。", + "bbb7d40a7ad7ab71": "プライベート", "85ae9979ad3b0c1e": "ベースブランチ {branch} をコピー", "06a684782801e8f7": "ヘッドブランチ {branch} をコピー", "8e4f3c862193b8a5": "編集", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 731eaeecaec22..87195d1e59336 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host}에서 WebSocket 연결을 설정할 수 없습니다.", "d9ce6c142a485959": "{host}이(가) {seconds}초 동안 응답하지 않습니다.", "d6bdce8f4e6101a4": "{host} 연결이 끊어졌습니다.", + "8450a95e5214d199": "{host}에서 이 클라이언트가 읽을 수 없는 서버 구성 업데이트를 보냈습니다.", + "56b4ff3993c93eca": "{host}에서 호환되지 않는 서버 구성을 보냈습니다.", + "368c4d4f99c66bfb": "클라이언트와 서버를 호환되는 버전으로 업데이트하세요.", "e5fd422e445391fc": "업로드에 실패했습니다. 탭하여 다시 시도하세요.", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", @@ -2848,6 +2851,7 @@ "f9d3c8aa453829ce": "검토를 요청하려면 사람을 탭하세요. 요청을 제거하려면 요청된 검토자를 탭하세요. 변경 사항은 이 시트를 닫을 때 전송됩니다.", "8d3770f150f0bcb4": "요청됨", "fff1c3d17603f394": "이 제공자는 검토자 ID를 받지만 후보를 나열할 수 없습니다.", + "bbb7d40a7ad7ab71": "비공개", "85ae9979ad3b0c1e": "기준 브랜치 {branch} 복사", "06a684782801e8f7": "헤드 브랜치 {branch} 복사", "8e4f3c862193b8a5": "편집", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 2c4ee1bc64fc4..fb5d60acdbd89 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} não conseguiu estabelecer uma conexão WebSocket.", "d9ce6c142a485959": "{host} parou de responder por {seconds} s.", "d6bdce8f4e6101a4": "{host} desconectou.", + "8450a95e5214d199": "{host} enviou uma atualização da configuração do servidor que este cliente não conseguiu ler.", + "56b4ff3993c93eca": "{host} enviou uma configuração de servidor incompatível.", + "368c4d4f99c66bfb": "Atualize o cliente e o servidor para versões compatíveis.", "e5fd422e445391fc": "Falha no envio. Toque para tentar novamente.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2847,6 +2850,7 @@ "f9d3c8aa453829ce": "Toque em alguém para solicitar uma revisão. Toque em um revisor solicitado para remover a solicitação. As alterações são enviadas quando você fecha esta folha.", "8d3770f150f0bcb4": "Solicitado", "fff1c3d17603f394": "Este provedor aceita um ID de revisor, mas não consegue listar candidatos.", + "bbb7d40a7ad7ab71": "Privado", "85ae9979ad3b0c1e": "Copiar branch base {branch}", "06a684782801e8f7": "Copiar branch head {branch}", "8e4f3c862193b8a5": "Editar", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index c4f78e560083b..b5beca32c6869 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} не удалось установить WebSocket-соединение.", "d9ce6c142a485959": "{host} не отвечает уже {seconds} с.", "d6bdce8f4e6101a4": "{host} отключён.", + "8450a95e5214d199": "{host} отправил обновление конфигурации сервера, которое этот клиент не смог прочитать.", + "56b4ff3993c93eca": "{host} отправил несовместимую конфигурацию сервера.", + "368c4d4f99c66bfb": "Обновите клиент и сервер до совместимых версий.", "e5fd422e445391fc": "Ошибка загрузки. Нажмите, чтобы повторить.", "b2bc6bd92ea24e5c": "{size} МБ", "88f84178edbb7f57": "{size} КБ", @@ -2899,6 +2902,7 @@ "f9d3c8aa453829ce": "Нажмите на человека, чтобы запросить ревью. Нажмите на запрошенного ревьюера, чтобы отменить запрос. Изменения отправляются при закрытии этой панели.", "8d3770f150f0bcb4": "Запрошен", "fff1c3d17603f394": "Этот провайдер принимает ID ревьюера, но не может показать список кандидатов.", + "bbb7d40a7ad7ab71": "Приватный", "85ae9979ad3b0c1e": "Копировать базовую ветку {branch}", "06a684782801e8f7": "Копировать head-ветку {branch}", "8e4f3c862193b8a5": "Изменить", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index fa3a3dd6d039f..28ed7e557146a 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} kunde inte upprätta en WebSocket-anslutning.", "d9ce6c142a485959": "{host} slutade svara i {seconds} s.", "d6bdce8f4e6101a4": "{host} kopplades från.", + "8450a95e5214d199": "{host} skickade en uppdatering av serverkonfigurationen som den här klienten inte kunde läsa.", + "56b4ff3993c93eca": "{host} skickade en inkompatibel serverkonfiguration.", + "368c4d4f99c66bfb": "Uppdatera klienten och servern till kompatibla versioner.", "e5fd422e445391fc": "Uppladdningen misslyckades. Tryck för att försöka igen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} kB", @@ -2851,6 +2854,7 @@ "f9d3c8aa453829ce": "Tryck på någon för att begära en granskning. Tryck på en begärd granskare för att ta bort begäran. Ändringarna skickas när du stänger det här bladet.", "8d3770f150f0bcb4": "Begärd", "fff1c3d17603f394": "Leverantören accepterar ett granskar-id men kan inte lista kandidater.", + "bbb7d40a7ad7ab71": "Privat", "85ae9979ad3b0c1e": "Kopiera basgrenen {branch}", "06a684782801e8f7": "Kopiera huvudgrenen {branch}", "8e4f3c862193b8a5": "Redigera", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f36e76805c298..52857eda6cc8a 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} 无法建立 WebSocket 连接。", "d9ce6c142a485959": "{host} 已 {seconds} 秒无响应。", "d6bdce8f4e6101a4": "{host} 已断开连接。", + "8450a95e5214d199": "{host} 发送了此客户端无法读取的服务器配置更新。", + "56b4ff3993c93eca": "{host} 发送了不兼容的服务器配置。", + "368c4d4f99c66bfb": "请将客户端和服务器更新到兼容的版本。", "e5fd422e445391fc": "上传失败。点按以重试。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2848,6 +2851,7 @@ "f9d3c8aa453829ce": "轻点某人以请求审查。轻点已请求的审查者以移除请求。关闭此面板时会发送更改。", "8d3770f150f0bcb4": "已请求", "fff1c3d17603f394": "此提供方接受审查者 ID,但无法列出候选人。", + "bbb7d40a7ad7ab71": "私有", "85ae9979ad3b0c1e": "复制基础分支 {branch}", "06a684782801e8f7": "复制头部分支 {branch}", "8e4f3c862193b8a5": "编辑", diff --git a/apps/mobile/src/lib/composerContext.test.ts b/apps/mobile/src/lib/composerContext.test.ts index e2a5a015c61af..255666ebcf0b2 100644 --- a/apps/mobile/src/lib/composerContext.test.ts +++ b/apps/mobile/src/lib/composerContext.test.ts @@ -8,6 +8,7 @@ import { type ServerProviderSkill, } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, @@ -167,7 +168,7 @@ describe("mobile composer context", () => { const modelTokens = (text: string) => composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), new Set(), collectComposerModelTokens(text, known), ) @@ -256,7 +257,7 @@ describe("mobile composer context", () => { const skills = [babysit, disabled, agentOnly]; const tokens = composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(skills), ); expect(tokens.map((token) => token.source)).toEqual([ @@ -271,14 +272,14 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels([]), ).map((token) => token.type), ).toEqual(["mention", "context", "context", "citation", "citation"]); expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels([{ ...babysit, name: "HOME" }]), ) .filter((token) => token.type === "skill") @@ -292,7 +293,7 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(promoted), ) .filter((token) => token.type === "skill") @@ -301,7 +302,7 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(skills), ) .filter((token) => token.type === "skill") diff --git a/apps/mobile/src/lib/composerContext.ts b/apps/mobile/src/lib/composerContext.ts index 754774c4f1306..219a61108fd51 100644 --- a/apps/mobile/src/lib/composerContext.ts +++ b/apps/mobile/src/lib/composerContext.ts @@ -40,6 +40,7 @@ import { composerMathRanges, type ComposerInlineToken, } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; const isMessageContext = Schema.is(OrchestrationMessageContext); const decodeMessageContext = Schema.decodeUnknownOption(OrchestrationMessageContext); @@ -73,7 +74,7 @@ export function composerMentionPath(source: string, context?: OrchestrationMessa const record = context?.records.find((entry) => entry.contextId === reference.contextId); return record?.kind === "mention" && "path" in record ? record.path : null; } - const token = collectComposerInlineTokens(`${source} `)[0]; + const token = collectComposerInlineTokens(`${source} `, { findMath: markdownMathRanges })[0]; return token?.type === "mention" && token.source === source ? token.value : null; } @@ -222,7 +223,12 @@ export function composerContextEditorTokens( !references.some((ref) => token.start < ref.end && token.end > ref.start) && !citations.some((ref) => token.start < ref.end && token.end > ref.start), ); - const taken = [...inlineTokens, ...references, ...citations, ...composerMathRanges(text)]; + const taken = [ + ...inlineTokens, + ...references, + ...citations, + ...composerMathRanges(text, markdownMathRanges), + ]; const models = modelTokens.filter( (mention) => !taken.some((range) => mention.start < range.end && mention.end > range.start), ); diff --git a/apps/mobile/src/lib/composerFiles.test.ts b/apps/mobile/src/lib/composerFiles.test.ts index bdcd35c36ff75..73f0af20fcc00 100644 --- a/apps/mobile/src/lib/composerFiles.test.ts +++ b/apps/mobile/src/lib/composerFiles.test.ts @@ -2,6 +2,9 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts"; import type { ImagePickerAsset } from "expo-image-picker"; +// Bytes of image files the tests create, so stored attachments can be read back and measured. +const imageFiles = new Map(); + const mocks = vi.hoisted(() => ({ documentUri: "file:///documents", pickFile: vi.fn(), @@ -57,6 +60,8 @@ vi.mock("expo-file-system", () => { async copy(destination: File): Promise { mocks.copy(this.uri, destination.uri); + const bytes = imageFiles.get(this.uri); + if (bytes !== undefined) imageFiles.set(destination.uri, bytes); } async base64(): Promise { @@ -99,6 +104,16 @@ import { import { isForegroundHandoffActive } from "./foreground-handoff"; import { retainComposerAttachmentFile } from "./composerAttachmentFiles"; +const STORED = "file:///documents/t3-composer-attachments/attachment-id"; + +function sizeOtherFilesAs(bytes: number): void { + mocks.size.mockImplementation((uri: string) => { + if (uri.startsWith("content:")) return null; + const stored = imageFiles.get(uri); + return stored === undefined ? bytes : Buffer.from(stored, "base64").byteLength; + }); +} + describe("composer file attachments", () => { beforeEach(() => { mocks.documentUri = "file:///documents"; @@ -110,7 +125,8 @@ describe("composer file attachments", () => { mocks.size.mockReset(); mocks.readBase64.mockReset(); mocks.manipulate.mockReset(); - mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? null : 42)); + imageFiles.clear(); + sizeOtherFilesAs(42); }); describe("photo library image conversion", () => { @@ -151,8 +167,11 @@ describe("composer file attachments", () => { width: size.width, height: size.height, release: mocks.release, - saveAsync: async (options: { format: string }) => - native.encode?.(size, options.format) ?? native.saved, + saveAsync: async (options: { format: string }) => { + const saved = native.encode?.(size, options.format) ?? native.saved; + if (saved.base64 !== undefined) imageFiles.set(saved.uri, saved.base64); + return saved; + }, }), }; return context; @@ -160,7 +179,7 @@ describe("composer file attachments", () => { }); it.each(["image/heic", "image/heif", undefined])( - "renders a %s photo to JPEG natively and previews the rendered file", + "renders a %s photo to JPEG natively and stores it in an owned file", async (mimeType) => { mocks.pickMedia.mockResolvedValue({ canceled: false, @@ -180,8 +199,8 @@ describe("composer file attachments", () => { name: "photo.jpg", mimeType: "image/jpeg", sizeBytes: 4, - dataUrl: `data:image/jpeg;base64,${rendered.base64}`, - previewUri: rendered.uri, + fileUri: `${STORED}-photo.jpg`, + previewUri: `${STORED}-photo.jpg`, }, ], error: null, @@ -200,6 +219,7 @@ describe("composer file attachments", () => { assets: [{ ...photo, fileName: name, mimeType: original.mimeType }], }); mocks.readBase64.mockResolvedValue(original.base64); + imageFiles.set(photo.uri, original.base64); const result = await pickComposerImages({ existingCount: 0 }); @@ -210,11 +230,12 @@ describe("composer file attachments", () => { expect.objectContaining({ name, mimeType: original.mimeType, - dataUrl: `data:${original.mimeType};base64,${original.base64}`, + fileUri: `${STORED}-${name}`, sizeBytes: Buffer.from(original.base64, "base64").byteLength, - previewUri: photo.uri, }), ]); + expect(result.images[0]).not.toHaveProperty("dataUrl"); + expect(imageFiles.get(`${STORED}-${name}`)).toBe(original.base64); }); it("shrinks a fitted PNG further when re-encoding it exceeds the image limit", async () => { @@ -229,7 +250,7 @@ describe("composer file attachments", () => { uri: `file:///cache/fitted-${size.width}x${size.height}.${format}`, base64: Buffer.alloc(size.width * size.height * 4).toString("base64"), }); - mocks.size.mockReturnValue(7 * 1024 * 1024); + sizeOtherFilesAs(7 * 1024 * 1024); mocks.readBase64.mockResolvedValue(header.toString("base64")); mocks.pickMedia.mockResolvedValue({ canceled: false, @@ -248,12 +269,14 @@ describe("composer file attachments", () => { name: "IMG_9280.png", mimeType: "image/png", sizeBytes: last.width * last.height * 4, - previewUri: `file:///cache/fitted-${last.width}x${last.height}.png`, + fileUri: `${STORED}-IMG_9280.png`, }), ); expect(image!.sizeBytes).toBeLessThanOrEqual(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES); expect(mocks.delete).toHaveBeenCalledWith("file:///cache/fitted-1397x2000.png"); - expect(mocks.delete).not.toHaveBeenCalledWith(image!.previewUri); + expect(imageFiles.get(image!.previewUri)).toBe( + Buffer.alloc(last.width * last.height * 4).toString("base64"), + ); }); it("measures the picker file instead of trusting the reported size", async () => { @@ -261,7 +284,7 @@ describe("composer file attachments", () => { canceled: false, assets: [{ ...photo, fileName: "photo.png", mimeType: "image/png", fileSize: 42 }], }); - mocks.size.mockReturnValue(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); + sizeOtherFilesAs(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); const result = await pickComposerImages({ existingCount: 0 }); @@ -372,7 +395,7 @@ describe("composer file attachments", () => { ); expect(result).toEqual({ attachments: [ - expect.objectContaining({ type: "image", dataUrl: "data:image/png;base64,YWJj" }), + expect.objectContaining({ type: "image", fileUri: `${STORED}-photo.png` }), { id: "attachment-id", type: "file", @@ -398,7 +421,7 @@ describe("composer file attachments", () => { expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]); expect(result.error).toBe("Video attachments are unavailable here."); - expect(mocks.copy).not.toHaveBeenCalled(); + expect(mocks.copy).not.toHaveBeenCalledWith(video.uri, expect.anything()); }); it("uses local video metadata when the picker omits its name, MIME type, or size", async () => { @@ -476,7 +499,7 @@ describe("composer file attachments", () => { expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]); expect(result.error).toBe("You can attach up to 100 attachments per message."); expect(mocks.pickMedia).toHaveBeenCalledWith(expect.objectContaining({ selectionLimit: 1 })); - expect(mocks.copy).not.toHaveBeenCalled(); + expect(mocks.copy).not.toHaveBeenCalledWith(video.uri, expect.anything()); }); it("reports a native video retrieval error and ends the foreground handoff", async () => { @@ -506,7 +529,7 @@ describe("composer file attachments", () => { canceled: false, assets: [{ uri: `file:///picker/${name}`, name, mimeType, size: 3 }], }); - mocks.size.mockReturnValue(3); + sizeOtherFilesAs(3); mocks.readBase64.mockResolvedValue("YWJj"); const result = await pickComposerFiles({ existingCount: 0 }); @@ -519,16 +542,14 @@ describe("composer file attachments", () => { name, mimeType: expected, sizeBytes: 3, - dataUrl: `data:${expected};base64,YWJj`, - previewUri: `data:${expected};base64,YWJj`, + fileUri: `${STORED}-${name}`, + previewUri: `${STORED}-${name}`, }, ], error: null, }); expect(mocks.manipulate).not.toHaveBeenCalled(); - expect(mocks.delete).toHaveBeenCalledWith( - `file:///documents/t3-composer-attachments/attachment-id-${name}`, - ); + expect(mocks.delete).not.toHaveBeenCalled(); }); it.each([ @@ -590,17 +611,19 @@ describe("composer file attachments", () => { header.writeUInt32BE(3000, 20); const original = header.toString("base64"); mocks.readBase64.mockResolvedValue(original); + imageFiles.set("file:///picker/photo.png", original); const resize = vi.fn(); const renderAsync = vi.fn(async () => ({ width: 4000, height: 3000, release: vi.fn(), - saveAsync: vi.fn(async () => ({ - uri: "file:///cache/fitted.png", - base64: oversized + saveAsync: vi.fn(async () => { + const base64 = oversized ? Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1).toString("base64") - : "YWJj", - })), + : "YWJj"; + imageFiles.set("file:///cache/fitted.png", base64); + return { uri: "file:///cache/fitted.png", base64 }; + }), })); mocks.manipulate.mockImplementation(() => { const context = { @@ -626,14 +649,12 @@ describe("composer file attachments", () => { type: "image", mimeType: "image/png", sizeBytes: oversized ? header.length : 3, - dataUrl: `data:image/png;base64,${oversized ? original : "YWJj"}`, - previewUri: oversized - ? `data:image/png;base64,${original}` - : "file:///cache/fitted.png", + fileUri: `${STORED}-photo.png`, }), ], error: null, }); + expect(imageFiles.get(`${STORED}-photo.png`)).toBe(oversized ? original : "YWJj"); }); it("releases the owned copy when reading an image fails", async () => { diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts index d7830b8ed3466..de05411a8f327 100644 --- a/apps/mobile/src/lib/composerImages.test.ts +++ b/apps/mobile/src/lib/composerImages.test.ts @@ -122,6 +122,8 @@ vi.mock("./uuid", () => ({ import { convertPastedImagesToAttachments, persistComposerAttachmentFile } from "./composerImages"; +const STORED = "file:///documents/t3-composer-attachments/attachment-id"; + function oversizedPng(): string { const png = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(png); @@ -150,10 +152,12 @@ describe("native pasted image cleanup", () => { expect.objectContaining({ name: "pasted-image.jpeg", mimeType: "image/jpeg", - dataUrl: "data:image/jpeg;base64,aGVsbG8=", - previewUri: "data:image/jpeg;base64,aGVsbG8=", + fileUri: `${STORED}-pasted-image.jpeg`, + previewUri: `${STORED}-pasted-image.jpeg`, }), ]); + expect(attachments[0]).not.toHaveProperty("dataUrl"); + expect(files.get(`${STORED}-pasted-image.jpeg`)?.base64).toBe("aGVsbG8="); expect(files.get(uri)?.deleted).toBe(false); }); @@ -171,10 +175,10 @@ describe("native pasted image cleanup", () => { expect.objectContaining({ name: "pasted-image.jpeg", mimeType: "image/jpeg", - dataUrl: "data:image/jpeg;base64,cmVuZGVyZWQ=", - previewUri: "data:image/jpeg;base64,cmVuZGVyZWQ=", + fileUri: `${STORED}-pasted-image.jpeg`, }), ]); + expect(files.get(`${STORED}-pasted-image.jpeg`)?.base64).toBe("cmVuZGVyZWQ="); expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true); expect(files.get(uri)?.deleted).toBe(false); }); @@ -197,7 +201,7 @@ describe("native pasted image cleanup", () => { expect(files.get(uri)?.deleted).toBe(false); }); - it("converts owned files to data-backed previews and deletes the source", async () => { + it("stores owned pastes in an attachment file and deletes the source", async () => { const uri = "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png"; const gif = @@ -212,11 +216,13 @@ describe("native pasted image cleanup", () => { expect(attachments).toEqual([ expect.objectContaining({ - dataUrl: "data:image/png;base64,aGVsbG8=", - previewUri: "data:image/png;base64,aGVsbG8=", + fileUri: `${STORED}-pasted-image.png`, + previewUri: `${STORED}-pasted-image.png`, }), - expect.objectContaining({ mimeType: "image/gif", dataUrl: "data:image/gif;base64,R0lGODlh" }), + expect.objectContaining({ mimeType: "image/gif", fileUri: `${STORED}-pasted-image.gif` }), ]); + expect(files.get(`${STORED}-pasted-image.png`)?.base64).toBe("aGVsbG8="); + expect(files.get(`${STORED}-pasted-image.gif`)?.base64).toBe("R0lGODlh"); expect(files.get(uri)?.deleted).toBe(true); expect(files.get(gif)?.deleted).toBe(true); }); @@ -267,7 +273,7 @@ describe("native pasted image cleanup", () => { const result = await convertPastedImagesToAttachments({ uris: [gone, kept], existingCount: 0 }); expect(result.attachments).toEqual([ - expect.objectContaining({ dataUrl: "data:image/png;base64,aGVsbG8=" }), + expect.objectContaining({ fileUri: `${STORED}-pasted-image.png` }), ]); expect(result.error).toBe("Could not read a pasted image."); }); diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index 69f26103134b9..4c81024c1d403 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -124,7 +124,7 @@ export function isFileBackedComposerAttachment( return attachment.fileUri !== undefined; } -/** Inline library/clipboard images own no file; local ids cannot resolve server assets. */ +/** Legacy inline images have only a local draft id, so a remote asset lookup cannot load them. */ export function composerAttachmentInlineUri( attachment: DraftComposerAttachment | undefined, ): string | undefined { @@ -135,6 +135,11 @@ export function composerAttachmentInlineUri( const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste"; const ATTACHMENT_COPY_CHUNK_BYTES = 64 * 1024; +// Android's java.net.URI rejects characters expo-file-system leaves unencoded, such as `[` and `]`. +function safeComposerAttachmentName(name: string): string { + return name.replace(/[^\w. -]/g, "-") || "file"; +} + export async function persistComposerAttachmentFile( uri: string, name: string, @@ -143,9 +148,7 @@ export async function persistComposerAttachmentFile( const { Directory, File, FileMode, Paths } = await import("expo-file-system"); const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY); directory.create({ idempotent: true, intermediates: true }); - // Android's java.net.URI rejects characters expo-file-system leaves unencoded, such as `[` and `]`. - const safeName = name.replace(/[^\w. -]/g, "-") || "file"; - const destination = new File(directory, `${uuidv4()}-${safeName}`); + const destination = new File(directory, `${uuidv4()}-${safeComposerAttachmentName(name)}`); const source = new File(uri); const sourceSize = source.size; if ( @@ -218,6 +221,35 @@ export async function persistComposerAttachmentFile( return destination.uri; } +async function ownedComposerImageAttachment(input: { + readonly fileUri: string; + readonly name: string; + readonly mimeType: string; +}): Promise { + try { + const { File } = await import("expo-file-system"); + const sizeBytes = new File(input.fileUri).size; + if (sizeBytes === null || sizeBytes <= 0) { + throw new Error(m(msg("''{name}'' is empty or could not be read.", { name: input.name }))); + } + if (sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + throw new Error( + fileAttachmentTooLargeMessage(input.name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, m), + ); + } + return { + ...input, + id: uuidv4(), + type: "image", + sizeBytes, + previewUri: input.fileUri, + }; + } catch (error) { + await removePersistedComposerAttachmentFile(input.fileUri); + throw error; + } +} + export async function removePersistedComposerAttachmentFile(uri: string): Promise { try { const { File, Paths } = await import("expo-file-system"); @@ -333,37 +365,29 @@ export async function pickComposerFiles(input: { attachments.push(attachment); continue; } + const { File } = await import("expo-file-system"); + let fileUri = attachment.fileUri; try { - const { File } = await import("expo-file-system"); - const original = await new File(attachment.fileUri).base64(); - const candidate = await fitComposerImage({ - uri: attachment.fileUri, - mimeType, - base64: original, - }); + const original = await new File(fileUri).base64(); + const candidate = await fitComposerImage({ uri: fileUri, mimeType, base64: original }); const fitted = candidate !== null && estimateBase64ByteSize(candidate.base64) <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES ? candidate : null; - const base64 = fitted?.base64 ?? original; - const sizeBytes = estimateBase64ByteSize(base64); - if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - throw new Error(m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name }))); + if (fitted !== null) { + fileUri = await persistComposerAttachmentFile( + fitted.uri, + name, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + await removePersistedComposerAttachmentFile(attachment.fileUri); } - const dataUrl = `data:${mimeType};base64,${base64}`; - attachments.push({ - id: attachment.id, - type: "image", - name, - mimeType, - sizeBytes, - dataUrl, - previewUri: fitted?.uri ?? dataUrl, - }); - } finally { + } catch (cause) { await removePersistedComposerAttachmentFile(attachment.fileUri); + throw cause; } + attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType })); } catch (cause) { error = errorDisplayMessage(cause, m) ?? m(msg("Could not read ''{name}''.", { name })); } @@ -517,7 +541,7 @@ export async function pickComposerMedia(input: { ? mimeType : null; - let image: { base64: string; mimeType: string; name: string; previewUri: string }; + let image: { base64: string; mimeType: string; name: string; uri: string }; try { if (originalMimeType !== null) { const { File } = await import("expo-file-system"); @@ -531,7 +555,7 @@ export async function pickComposerMedia(input: { base64: fitted?.base64 ?? base64, mimeType: originalMimeType, name, - previewUri: fitted?.uri ?? asset.uri, + uri: fitted?.uri ?? asset.uri, }; } else { const rendered = await renderPhoto(asset.uri); @@ -539,7 +563,7 @@ export async function pickComposerMedia(input: { base64: rendered.base64, mimeType: "image/jpeg", name: /\.jpe?g$/i.test(name) ? name : `${name.replace(/\.[^.]+$/, "")}.jpg`, - previewUri: rendered.uri, + uri: rendered.uri, }; } } catch { @@ -553,15 +577,18 @@ export async function pickComposerMedia(input: { continue; } - attachments.push({ - id: uuidv4(), - type: "image", - name: image.name, - mimeType: image.mimeType, - sizeBytes, - dataUrl: `data:${image.mimeType};base64,${image.base64}`, - previewUri: image.previewUri, - }); + try { + const fileUri = await persistComposerAttachmentFile( + image.uri, + image.name, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + attachments.push( + await ownedComposerImageAttachment({ fileUri, name: image.name, mimeType: image.mimeType }), + ); + } catch (cause) { + error = errorDisplayMessage(cause, m) ?? m(msg("Failed to read ''{name}''.", { name })); + } } return { @@ -639,6 +666,7 @@ export async function convertPastedImagesToAttachments(input: { temporaryUris.push(fitted.uri); } let base64 = fitted?.base64 ?? pastedBase64; + let sourceUri = fitted?.uri ?? uri; if ( rendered === null && estimateBase64ByteSize(base64) > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES @@ -647,6 +675,7 @@ export async function convertPastedImagesToAttachments(input: { temporaryUris.push(jpeg.uri); mimeType = "image/jpeg"; base64 = jpeg.base64; + sourceUri = jpeg.uri; } const sizeBytes = estimateBase64ByteSize(base64); if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { @@ -656,16 +685,13 @@ export async function convertPastedImagesToAttachments(input: { : m(msg("Could not read a pasted image.")); continue; } - const dataUrl = `data:${mimeType};base64,${base64}`; - attachments.push({ - id: uuidv4(), - type: "image", - name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`, - mimeType, - sizeBytes, - dataUrl, - previewUri: dataUrl, - }); + const name = `pasted-image.${mimeType.split("/")[1] ?? "png"}`; + const fileUri = await persistComposerAttachmentFile( + sourceUri, + name, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType })); } catch (cause) { console.warn("Failed to read pasted image", uri, cause); error = m(msg("Could not read a pasted image.")); diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index cd0bd8ae9890c..7c463ac0c3438 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -23,6 +23,7 @@ import { acquireAudioSession, activateAudioSession, releaseAudioSession } from " import { ThreadFeed } from "../features/threads/ThreadFeed"; import type { ThreadFeedEntry } from "./threadActivity"; import type { MarkdownImageRenderer } from "../native/SelectableMarkdownText"; +import type { FilePreviewItem, FilePreviewSource } from "../components/ui/FilePreviewModal.types"; const audio = vi.hoisted(() => ({ status: { @@ -203,12 +204,18 @@ vi.mock("../native/SelectableMarkdownText", () => ({ onLinkPress(href: string): void; renderImage?: MarkdownImageRenderer; }) => { - const embed = props.markdown.match(/!\[([^\]]*)\]\(([^)]+)\)/); + const embeds = [...props.markdown.matchAll(/!\[([^\]]*)\]\(([^)]+)\)/g)]; return createElement( "div", null, createElement("button", { onClick: () => props.onLinkPress("target.ts") }, props.markdown), - embed && props.renderImage?.({ href: embed[2]!, alt: embed[1]!, title: null }), + embeds.map(([, alt, href], index) => + createElement( + Fragment, + { key: index }, + props.renderImage?.({ href: href!, alt: alt!, title: null }), + ), + ), ); }, })); @@ -238,7 +245,9 @@ vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0, bottom: 0 }), })); vi.mock("expo-haptics", () => ({ selectionAsync: async () => {} })); -vi.mock("expo-image", () => ({})); +vi.mock("expo-image", () => ({ Image: () => null })); +vi.mock("expo/fetch", () => ({})); +vi.mock("react-native-svg", () => ({})); vi.mock("uniwind", () => ({})); vi.mock("../components/ui/Dialog", () => ({})); vi.mock("../components/ui/Sheet", () => ({ @@ -254,13 +263,19 @@ vi.mock("../components/ui/NativePresentation", () => ({ vi.mock("../components/ui/Menu", () => ({ Menu: ({ children }: { children?: ReactNode }) => children, })); -vi.mock("../components/ui/FilePreviewGallery", () => ({ - FilePreviewGallery: ({ children }: { children?: ReactNode }) => children, - useFilePreviewGallery: () => (source: unknown) => source, -})); +function previewPath(item: FilePreviewItem) { + return "resource" in item && "path" in item.resource ? item.resource.path : null; +} + vi.mock("../components/ui/FilePreviewModal", () => ({ - FilePreviewModal: (props: { source: { name: string } | null }) => - props.source ? createElement("div", { "data-file-preview": props.source.name }) : null, + FilePreviewModal: ({ source }: { source: FilePreviewSource | null }) => + source + ? createElement("div", { + "data-file-preview": source.name, + "data-selected-path": previewPath(source), + "data-gallery": JSON.stringify(source.gallery?.map(previewPath)), + }) + : null, })); vi.mock("../components/ui/VideoPreviewModal", () => ({ VideoPreviewModal: () => null })); vi.mock("../components/ComposerContextSheet", () => ({})); @@ -313,10 +328,6 @@ vi.mock("../features/layout/AdaptiveWorkspaceLayout", () => ({ })); vi.mock("../features/threads/thread-workflow-opening", () => ({ useWorkflowOpening: () => null })); vi.mock("../features/threads/useFileChipShare", () => ({ useFileChipShare: () => vi.fn() })); -vi.mock("../features/threads/ThreadMarkdownImage", async () => { - const { createContext } = await import("react"); - return { MarkdownImageAvailableWidthContext: createContext(390) }; -}); vi.mock("../features/threads/ZoomableImagePressable", async () => { const { Pressable } = await import("react-native"); return { ZoomableImagePressable: Pressable }; @@ -1408,6 +1419,70 @@ describe("inline file previews", () => { }); describe("ThreadFeed previews", () => { + it("opens a tapped workspace image on its own gallery page, in message order", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const threadId = ThreadId.make("thread-1"); + const messageId = MessageId.make("message-1"); + const timestamp = "2026-10-20T00:00:00.000Z"; + const container = document.createElement("div"); + const root = createRoot(container); + try { + await act(async () => + root.render( + createElement(ThreadFeed, { + environmentId: EnvironmentId.make("environment-1"), + threadId, + detailRef: null, + threadTitle: "preview", + workspaceRoot: "/repo", + feed: [ + { + type: "message", + id: messageId, + createdAt: timestamp, + message: { + id: messageId, + role: "assistant", + text: "![Red](./red.png)\n\n![Blue](./blue.png)", + attachments: [], + createdAt: timestamp, + updatedAt: timestamp, + runId: null, + streaming: false, + visibility: "local", + sourceThreadId: threadId, + }, + }, + ], + queuedMessages: [], + dispatchingMessageId: null, + onEditPendingMessage: null, + contentPresentation: { kind: "ready" }, + latestRun: null, + activeWorkStartedAt: null, + listRef: { current: null }, + freeze: { value: false } as Parameters[0]["freeze"], + contentInsetEndAdjustment: { value: 0 } as Parameters< + typeof ThreadFeed + >[0]["contentInsetEndAdjustment"], + anchorMessageId: null, + keyboardOffset: 0, + }), + ), + ); + await act(async () => + container.querySelector(`[aria-label="Red"]`)!.click(), + ); + const preview = container.querySelector("[data-file-preview]"); + expect(preview?.getAttribute("data-selected-path")).toBe("/repo/./red.png"); + expect(preview?.getAttribute("data-gallery")).toBe( + JSON.stringify(["/repo/./red.png", "/repo/./blue.png"]), + ); + } finally { + await act(async () => root.unmount()); + } + }); + it("does not commit an open preview over a different thread", async () => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const environmentId = EnvironmentId.make("environment-1"); diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx index ef57536abe95f..7e8eba1d01b28 100644 --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx @@ -1,6 +1,7 @@ import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste"; import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext"; import { useComposerModelTokens } from "./useComposerModelTokens"; import { requireNativeView } from "expo"; @@ -169,11 +170,12 @@ export function ComposerEditor({ // an abandoned render from leaking a trailing token into the next one. const [confirmedTokens, setConfirmedTokens] = useState(() => ({ value: props.value, - tokens: collectComposerInlineTokens(props.value), + tokens: collectComposerInlineTokens(props.value, { findMath: markdownMathRanges }), })); let tokens = confirmedTokens.tokens; if (confirmedTokens.value !== props.value) { tokens = collectComposerInlineTokens(props.value, { + findMath: markdownMathRanges, preserveTrailingFrom: confirmedTokens.tokens, }); setConfirmedTokens({ value: props.value, tokens }); diff --git a/apps/mobile/src/native/T3ComposerEditor.native.tsx b/apps/mobile/src/native/T3ComposerEditor.native.tsx index 28f47c3b758ab..4a0f57e411020 100644 --- a/apps/mobile/src/native/T3ComposerEditor.native.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.native.tsx @@ -1,6 +1,7 @@ import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste"; import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext"; import { DEFAULT_COMPOSER_ENTER_BEHAVIOR } from "../lib/composerEnterBehavior"; import { useComposerModelTokens } from "./useComposerModelTokens"; @@ -156,11 +157,12 @@ export function ComposerEditor({ // an abandoned render from leaking a trailing token into the next one. const [confirmedTokens, setConfirmedTokens] = useState(() => ({ value: props.value, - tokens: collectComposerInlineTokens(props.value), + tokens: collectComposerInlineTokens(props.value, { findMath: markdownMathRanges }), })); let tokens = confirmedTokens.tokens; if (confirmedTokens.value !== props.value) { tokens = collectComposerInlineTokens(props.value, { + findMath: markdownMathRanges, preserveTrailingFrom: confirmedTokens.tokens, }); setConfirmedTokens({ value: props.value, tokens }); diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.ts index d85340a8556d2..e7e9fe9a302a0 100644 --- a/apps/mobile/src/state/thread-outbox-model.ts +++ b/apps/mobile/src/state/thread-outbox-model.ts @@ -34,8 +34,8 @@ import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/compose import type { DraftComposerAttachment } from "../lib/composerImages"; import { scopedThreadKey } from "../lib/scopedEntities"; -// Keep current writes until a compatible native baseline includes the v4 reader. -const THREAD_OUTBOX_SCHEMA_VERSION = 3; +// v4 file-backed writes require native baselines with embedded readers and storage guards. +const THREAD_OUTBOX_SCHEMA_VERSION = 4; const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000; const QueuedThreadCreationSchema = Schema.Struct({ @@ -52,7 +52,7 @@ const QueuedThreadCreationSchema = Schema.Struct({ }); export const QueuedThreadMessageSchema = Schema.Struct({ - schemaVersion: Schema.Literals([1, 2, THREAD_OUTBOX_SCHEMA_VERSION, 4]), + schemaVersion: Schema.Literals([1, 2, 3, THREAD_OUTBOX_SCHEMA_VERSION]), environmentId: EnvironmentId, threadId: ThreadId, messageId: MessageId, diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts index fd1c248f5de9b..8c1870f76836b 100644 --- a/apps/mobile/src/state/use-composer-drafts.test.ts +++ b/apps/mobile/src/state/use-composer-drafts.test.ts @@ -91,9 +91,12 @@ const composerDraftFileMocks = vi.hoisted(() => { exists = true; size = 3; parentDirectory = null; + uri = "file:///documents/attachment.png"; create() {} + async copy() {} + moveSync() {} async text() { @@ -144,6 +147,7 @@ const incomingShareStorageMocks = vi.hoisted(() => ({ vi.mock("expo-file-system", () => ({ Directory: composerDraftFileMocks.Directory, File: composerDraftFileMocks.File, + FileMode: {}, Paths: { document: { uri: "file:///documents" } }, })); @@ -297,7 +301,7 @@ it.each(["picker open", "reading image"] as const)( expect.objectContaining({ type: "image", name: "screenshot.png", - dataUrl: "data:image/png;base64,YWJj", + fileUri: "file:///documents/attachment.png", }), ], ); @@ -1217,6 +1221,22 @@ describe("mobile composer drafts", () => { expect( appAtomRegistry.get(composerDraftsAtom)[pasteKey]?.attachments.map(({ id }) => id), ).toEqual(["red", "blue"]); + + const makeStoredPaste = (id: string) => ({ + id, + type: "image" as const, + name: "pasted-image.png", + mimeType: "image/png", + sizeBytes: 3, + fileUri: `file:///documents/t3-composer-attachments/${id}-pasted-image.png`, + previewUri: `file:///documents/t3-composer-attachments/${id}-pasted-image.png`, + }); + const storedKey = "new-task:environment-1:project-stored-pastes"; + appendComposerDraftAttachments(storedKey, [makeStoredPaste("red")]); + appendComposerDraftAttachments(storedKey, [makeStoredPaste("green")]); + expect( + appAtomRegistry.get(composerDraftsAtom)[storedKey]?.attachments.map(({ id }) => id), + ).toEqual(["red", "green"]); }); it("keeps shared attachment files until every draft releases them", async () => { diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index 0020defdc5915..10d8fd7a4f271 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -1431,7 +1431,9 @@ function isSameAttachment(a: DraftComposerAttachment, b: DraftComposerAttachment a.mimeType === b.mimeType && a.sizeBytes === b.sizeBytes && a.name === b.name && - (a.type !== "image" || b.type !== "image" || a.dataUrl === b.dataUrl) + (a.type !== "image" || + b.type !== "image" || + (a.dataUrl === b.dataUrl && a.fileUri === b.fileUri)) ); } diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 48e7fc02b5b32..a26af21009c05 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -870,7 +870,6 @@ export function useThreadComposerState(input: { } // Resolve at send time because outbox delivery may be delayed. - // Steering uses "auto" so an ended turn queues a run instead of restoring the draft. // An approval redirect must steer the waiting turn instead of queueing behind it. const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior; const followUpAction = resolveComposerDispatchMode({ @@ -885,9 +884,7 @@ export function useThreadComposerState(input: { ? "queue" : followUpAction === "auto" ? null - : followUpAction === "queue" - ? "queue" - : "auto"; + : followUpAction; // A redirect belongs to the approval it answers; the armed session waits for the next message. const freshContext = beforeDispatch === undefined && isFreshSessionPending(threadKey); diff --git a/apps/server/package.json b/apps/server/package.json index 9b9b3c022cacb..780cc64f0b2e5 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -20,7 +20,6 @@ "build:bundle": "vp pack", "build:exe": "node scripts/cli.ts build-exe", "start": "node dist/bin.mjs", - "typecheck": "effect-tsgo tsrs --noEmit", "speech:catalog:sync": "node scripts/sync-speech-catalog.ts", "speech:catalog:check": "node scripts/sync-speech-catalog.ts --check", "test": "vp test run", diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index 86d7330887376..39952a385ba87 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -191,7 +191,11 @@ export const authenticateMediaRequest = export const failEnvironmentInternal = /* Request instrumentation already owns the span; keep this helper in that context. */ - Effect.fnUntraced(function* (reason: EnvironmentInternalErrorReason, error?: unknown) { + Effect.fnUntraced(function* ( + reason: EnvironmentInternalErrorReason, + error?: unknown, + detail?: string, + ) { const traceId = yield* currentEnvironmentTraceId; if (error !== undefined) { yield* Effect.logError("environment api operation failed", { @@ -200,7 +204,12 @@ export const failEnvironmentInternal = cause: error, }); } - return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId }); + return yield* new EnvironmentInternalError({ + code: "internal_error", + reason, + traceId, + ...(detail === undefined ? {} : { detail }), + }); }); // Plaintext LAN servers still need the cookie; TLS arrives through a proxy that sets X-Forwarded-Proto. diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index ddbc49e1ced74..9d1ffb5c1298a 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -3,6 +3,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeEvents from "node:events"; import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; import { assert, expect, it } from "@effect/vitest"; import * as ConfigProvider from "effect/ConfigProvider"; @@ -22,6 +23,7 @@ import { import * as NetService from "@t3tools/shared/Net"; import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability"; import * as OtelEnvironment from "@t3tools/shared/otelEnvironment"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as HostProcess from "@t3tools/shared/HostProcess"; import packageJson from "../../package.json" with { type: "json" }; @@ -31,6 +33,8 @@ import { SERVICE_LAUNCHER_PROTOCOL, } from "../cloud/serviceProtocol.ts"; import { deriveServerPaths } from "../config.ts"; +import * as ProcessRunner from "../processRunner.ts"; +import { acquireServerOwnership } from "../serverOwnership.ts"; import { resolveServerConfig } from "./config.ts"; const deriveExplicitServerPaths = (baseDir: string, devUrl: URL | undefined) => @@ -173,44 +177,100 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { }), ); + const acquireOwnership = (baseDir: string) => + acquireServerOwnership(NodePath.join(baseDir, "userdata", "server-runtime.json")).pipe( + Effect.provide(Layer.merge(ProcessRunner.layer, NodeCrypto.layer)), + Effect.provideService(HostProcess.HomeDirectory, baseDir), + Effect.provideService(HostProcess.Environment, {}), + ); + + const resolveManualWebLaunch = (baseDir: string, cwd: string) => + resolveServerConfig({ ...minimalWebFlags(baseDir), cwd: Option.some(cwd) }, Option.none(), { + rejectRunningServer: true, + }).pipe( + Effect.provide( + Layer.merge(NetService.layer, ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }))), + ), + Effect.mapError(String), + Effect.result, + ); + + it.effect("refuses a manual web launch while a lock-aware server owns the T3 home", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-live-" }); + const child = yield* liveProcess; + assert(child.pid !== undefined); + const owner = yield* acquireOwnership(baseDir); + yield* owner.publish({ + version: 1, + pid: child.pid, + port: 3773, + origin: "http://127.0.0.1:3773", + startedAt: "2026-10-01T00:00:00.000Z", + }); + const cwd = path.join(baseDir, "project"); + const result = yield* resolveManualWebLaunch(baseDir, cwd); + assert(Result.isFailure(result)); + expect(result.failure).toContain("A T3 Code server is already running"); + expect(result.failure).toContain(`pid ${child.pid}`); + expect(yield* fs.exists(cwd)).toBe(false); + }), + ); + + it.effect("refuses a manual web launch when a pre-lock record belongs to a live process", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-legacy-" }); + const child = yield* liveProcess; + assert(child.pid !== undefined); + const stateDir = path.join(baseDir, "userdata"); + yield* fs.makeDirectory(stateDir, { recursive: true }); + yield* fs.writeFileString( + path.join(stateDir, "server-runtime.json"), + yield* encodeUnknownJson({ + version: 1, + pid: child.pid, + port: 3773, + origin: "http://127.0.0.1:3773", + startedAt: "2026-10-01T00:00:00.000Z", + }), + ); + const cwd = path.join(baseDir, "project"); + const result = yield* resolveManualWebLaunch(baseDir, cwd); + assert(Result.isFailure(result)); + expect(result.failure).toContain(`pid ${child.pid}`); + expect(yield* fs.exists(cwd)).toBe(false); + }), + ); + it.effect( - "refuses a manual web launch when a runtime record belongs to another live process", + "allows a manual web launch when a lock-aware record's PID was reused by an unrelated process", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-live-" }); + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-reused-" }); const child = yield* liveProcess; assert(child.pid !== undefined); - const stateDir = path.join(baseDir, "userdata"); - yield* fs.makeDirectory(stateDir, { recursive: true }); + // The killed server's lock file stays behind, released. + yield* Effect.scoped(acquireOwnership(baseDir)); yield* fs.writeFileString( - path.join(stateDir, "server-runtime.json"), + path.join(baseDir, "userdata", "server-runtime.json"), yield* encodeUnknownJson({ version: 1, pid: child.pid, + ownerId: "4ec9f94a-0000-4000-8000-000000000000", port: 3773, origin: "http://127.0.0.1:3773", startedAt: "2026-10-01T00:00:00.000Z", }), ); const cwd = path.join(baseDir, "project"); - const error = yield* resolveServerConfig( - { ...minimalWebFlags(baseDir), cwd: Option.some(cwd) }, - Option.none(), - { rejectRunningServer: true }, - ).pipe( - Effect.provide( - Layer.merge( - NetService.layer, - ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), - ), - ), - Effect.flip, - ); - expect(String(error)).toContain("A T3 Code server is already running"); - expect(String(error)).toContain(`pid ${child.pid}`); - expect(yield* fs.exists(cwd)).toBe(false); + const result = yield* resolveManualWebLaunch(baseDir, cwd); + expect(result).toEqual(Result.succeed(expect.objectContaining({ cwd }))); }), ); diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index 25d6c6eb62dd6..a62682772bcce 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -27,6 +27,7 @@ import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts"; import * as ServerConfig from "../config.ts"; import { expandHomePath, resolveBaseDir } from "../os-jank.ts"; import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { isServerOwnershipHeld } from "../serverOwnership.ts"; import { resolveHostCliCommand } from "./invocation.ts"; const modeFlag = Flag.Literals("mode", ServerConfig.RuntimeMode.literals).pipe( @@ -349,12 +350,15 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct // and supervisor handoff are separate; this preflight cannot arbitrate two starts. if (options?.rejectRunningServer && mode === "web") { const runtime = yield* readPersistedServerRuntimeState(derivedPaths.serverRuntimeStatePath); - // A killed container can leave a record with the new server's own PID. + // A killed container can leave a record whose PID is now ours or an unrelated process's. + // Lock-aware records are live only while their owner still holds the lock. if ( Option.isSome(runtime) && runtime.value.pid > 0 && runtime.value.pid !== process.pid && - isProcessAlive(runtime.value.pid) + isProcessAlive(runtime.value.pid) && + (runtime.value.ownerId === undefined || + isServerOwnershipHeld(derivedPaths.serverRuntimeStatePath)) ) { // Bare `t3 pair` prefers a linked worktree's `.t3`, so always name this home. const { command: pairCommand } = yield* resolveHostCliCommand("pair", [ diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index 7231ea7f2b3e0..bb0906a9c6919 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -53,6 +53,103 @@ vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => { const threadId = ThreadId.make("thread-1"); const runId = RunId.make("run-1"); +it.effect("list includes delegated threads across pages and still leaves out subagents", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-list-" }); + yield* persistServerRuntimeState({ + path: path.join(baseDir, "userdata", "server-runtime.json"), + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3_773, + }), + }); + const projectId = ProjectId.make("project-1"); + const item = (id: string) => ({ + threadId: id, + projectId, + title: id, + createdBy: "user", + creationSource: "web", + status: "idle", + latestRunId: null, + providerInstanceId: "codex", + model: "test", + runtimeMode: "full-access", + interactionMode: "default", + linkedPullRequest: null, + settled: false, + settledAt: null, + snoozed: false, + snoozedUntil: null, + parentThreadId: null, + relationshipToParent: null, + itemCount: 0, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + const root = item("root"); + const delegated = { + ...item("delegated"), + delegatedFrom: { environmentId: "env-1", threadId: "remote", title: "Remote" }, + }; + const subagent = { ...item("child"), parentThreadId: "root", relationshipToParent: "subagent" }; + using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue( + Effect.succeed({ + call: (tool, args) => { + if (tool === "t3_project_list") + return Effect.succeed({ + structuredContent: { + projects: [{ id: projectId, title: "Project", workspaceRoot: baseDir }], + nextCursor: null, + }, + }); + if (tool === "t3_thread_list") { + const all = args.includeSubagents ? [root, subagent, delegated] : [root]; + const cursor = Number(args.cursor); + return Effect.succeed({ + structuredContent: { + projectId, + currentThreadId: null, + threads: all.slice(cursor, cursor + 2), + nextCursor: cursor + 2 < all.length ? cursor + 2 : null, + total: all.length, + }, + }); + } + return Effect.die(`unexpected ${tool} call`); + }, + }), + ); + yield* Command.runWith(threadCommand, { version: "0.0.0" })([ + "list", + "--project", + projectId, + "--json", + "--base-dir", + baseDir, + ]); + const listed = JSON.parse(String((yield* TestConsole.logLines).at(-1))) as Array<{ + threadId: string; + }>; + assert.deepStrictEqual( + listed.map((entry) => entry.threadId), + ["root", "delegated"], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + NetService.layer, + ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })), + ), + ), + ), +); + it.effect( "start resolves home-relative project paths while preserving ids and relative paths", () => @@ -461,6 +558,40 @@ const timelineTools = (types: ReadonlyArray) => { const tail = (tools: number) => [...Array(tools).fill("tool_call"), "assistant_message"]; +it.effect("show retains pull request metadata when reading a later message window", () => + Effect.gen(function* () { + const link = { + host: "github.com", + repository: "owner/repo", + number: 1, + url: "https://github.com/owner/repo/pull/1", + source: "manual", + state: "open", + watching: false, + watchStartedAt: null, + } as const; + const call = ((_tool: string, input: unknown) => { + const args = input as { afterPosition?: number; limit: number }; + const first = args.afterPosition === undefined && args.limit === 1; + return Effect.succeed({ + thread: { + itemCount: 200, + status: first ? "running" : "completed", + pullRequestCount: 1, + ...(first ? { pullRequests: [link], openPullRequestCount: 1 } : {}), + }, + items: first ? [] : [{ position: 199, itemId: "message", type: "assistant_message" }], + nextPosition: 199, + hasMore: false, + }); + }) as ThreadTools["call"]; + const { thread } = yield* readLatestMessages({ call }, threadId, 1); + assert.strictEqual(thread.status, "completed"); + assert.deepStrictEqual(thread.pullRequests, [link]); + assert.strictEqual(thread.openPullRequestCount, 1); + }), +); + it.effect("show reads the end of a long thread, not its whole history", () => Effect.gen(function* () { const { tools, served, latest } = timelineTools([ diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 8849f10c6a5ec..09ee65c32172b 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -459,7 +459,8 @@ export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(fun ); afterPosition = page.nextPosition ?? Number.POSITIVE_INFINITY; } while (page.hasMore && afterPosition < (end ?? Number.POSITIVE_INFINITY) - 1); - thread = page.thread; + // Only the first read carries pull request previews; later pages omit them. + thread = Object.assign({}, thread, page.thread); // A window can hold the whole --messages count, too many to spread as arguments. messages = window.concat(messages); before = start; @@ -850,10 +851,12 @@ const threadListCommand = Command.make("list", { while (cursor !== null) { const page: OrchestratorMcpThreadListResult = yield* tools.call( "t3_thread_list", - { projectId: project.id, includeSubagents: false, limit: 100, cursor }, + { projectId: project.id, includeSubagents: true, limit: 100, cursor }, OrchestratorMcpThreadListResult, ); - threads.push(...page.threads); + threads.push( + ...page.threads.filter((thread) => thread.relationshipToParent !== "subagent"), + ); cursor = page.nextCursor; } if (flags.json) { diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index 7e4d69482eebf..28a7d720c525f 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -152,6 +152,8 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { }, }).pipe(Effect.forkScoped); yield* Deferred.await(firstChunk); + // Nothing is staged mid-download, so an age-based prune elsewhere cannot remove it. + assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []); yield* Fiber.interrupt(install); assert.deepEqual(progress.at(-1), { stage: "download", received: 4, total: undefined }); assert.isTrue(progress.every((event) => event.stage === "download")); @@ -729,6 +731,46 @@ it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => { }), ); + it.effect("removes the runtime a committed update replaced", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { baseDir } = yield* setup(["1.0.0", "1.1.0"]); + yield* fs.writeFileString( + path.join(baseDir, "runtime", "service-state.json"), + JSON.stringify({ + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.1.0", + update: { id: "u", fromVersion: "1.0.0", targetVersion: "1.1.0", status: "committed" }, + }), + ); + + const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["1.1.0"] }).pipe( + Effect.provideService(ProcessRunner.ProcessRunner, lsofRunner("p1\nftxt\nn/bin/sh\n")), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Environment, {}), + ); + assert.deepEqual(removed, ["1.0.0"]); + }), + ); + + it.effect("removes a staging directory an interrupted install abandoned long ago", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { baseDir, versionsDir, install } = yield* setup(["1.0.0"]); + yield* install(".staging-abc", "never"); + yield* fs.utimes(path.join(versionsDir, ".staging-abc"), 0, 0); + + yield* prunePinnedRuntimes({ baseDir, keep: ["1.0.0"] }).pipe( + Effect.provideService(ProcessRunner.ProcessRunner, lsofRunner("p1\nftxt\nn/bin/sh\n")), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Environment, {}), + ); + assert.deepEqual(yield* fs.readDirectory(versionsDir), ["1.0.0"]); + }), + ); + it.effect.each([ { name: "its directory is on PATH", onPath: true, recorded: false, linkedHome: false }, { diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index 08180f80a67ab..13c8f251c93b6 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -260,11 +260,9 @@ const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")( ); }); -const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(function* ( +const downloadArchive = Effect.fn("cloud.pinned_runtime.download_archive")(function* ( input: PinnedRuntimeInstallInput, - stagingDir: string, ) { - const { fs, path } = input; const platformKey = cliArchivePlatformKey(input.platform, input.arch); if (platformKey === undefined) { return yield* new PinnedRuntimeInstallError({ @@ -292,7 +290,15 @@ const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(fun step: "verifying the t3 release archive checksum", }); } + return archive; +}); +const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(function* ( + input: PinnedRuntimeInstallInput, + stagingDir: string, + archive: Uint8Array, +) { + const { fs, path } = input; const archivePath = path.join(stagingDir, PINNED_RUNTIME_ARCHIVE_FILE); yield* fs .writeFile(archivePath, archive) @@ -413,10 +419,13 @@ const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")( }), ), ); + // Downloads are buffered in memory and can take hours; staging only once they finish keeps a + // staging directory's age a sign of abandonment for prunes in other processes. + const archive = yield* downloadArchive(input); const stagingDir = yield* fs .makeTempDirectory({ directory: versionsDir, - prefix: ".staging-", + prefix: PINNED_RUNTIME_STAGING_PREFIX, }) .pipe( Effect.mapError( @@ -434,7 +443,7 @@ const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")( }; return yield* Effect.gen(function* () { - yield* installFromArchive(input, stagingDir); + yield* installFromArchive(input, stagingDir, archive); input.onProgress?.({ stage: "validate" }); yield* input.validate(stagingPaths); @@ -485,6 +494,7 @@ const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")( export const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) => pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input)); +const PINNED_RUNTIME_STAGING_PREFIX = ".staging-"; const PINNED_RUNTIME_PRUNED_PREFIX = ".pruned-"; /** * Another process may have just published a runtime it has not yet pointed anything at: an @@ -817,6 +827,16 @@ const selectUnusedRuntimes = Effect.fn("cloud.pinned_runtime.select_unused")(fun (yield* Clock.currentTimeMillis) - Duration.toMillis(PINNED_RUNTIME_PRUNE_GRACE); const completed: Array = []; for (const version of entries) { + if (version.startsWith(PINNED_RUNTIME_STAGING_PREFIX)) { + // A crashed or interrupted install leaves its staging directory behind. + const stagingDir = path.join(versionsDir, version); + const modifiedAt = yield* fs.stat(stagingDir).pipe( + Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime()), + Effect.orElseSucceed(() => undefined), + ); + if (modifiedAt !== undefined && modifiedAt < settledBefore) pruned.add(stagingDir); + continue; + } if (!isExactServiceVersion(version)) continue; const versionDir = path.join(versionsDir, version); const sentinelPath = path.join(versionDir, ".install-complete"); @@ -854,7 +874,8 @@ const selectUnusedRuntimes = Effect.fn("cloud.pinned_runtime.select_unused")(fun if (state === undefined) return pruned; keep.add(state.activeVersion); if (state.update !== undefined) { - keep.add(state.update.fromVersion); + // A committed update never returns to the runtime it replaced. + if (state.update.status !== "committed") keep.add(state.update.fromVersion); keep.add(state.update.targetVersion); } } @@ -901,8 +922,8 @@ const selectUnusedRuntimes = Effect.fn("cloud.pinned_runtime.select_unused")(fun /** * Keep runtimes named by callers, service state, running processes, launchers, or references, - * and anything published within an hour. Only prune completed runtimes; leave staging - * directories, symlinks, and unexpected entries untouched. + * and anything published within an hour. Only prune completed runtimes and staging directories + * untouched for an hour; leave symlinks and unexpected entries untouched. */ export const prunePinnedRuntimes = Effect.fn("cloud.pinned_runtime.prune")(function* (input: { readonly baseDir: string; @@ -917,11 +938,14 @@ export const prunePinnedRuntimes = Effect.fn("cloud.pinned_runtime.prune")(funct ); const removed: Array = []; for (const target of pruned) { + const name = path.basename(target); yield* fs.remove(target, { recursive: true, force: true }).pipe( Effect.andThen( - Effect.sync(() => - removed.push(path.basename(target).slice(PINNED_RUNTIME_PRUNED_PREFIX.length)), - ), + Effect.sync(() => { + if (name.startsWith(PINNED_RUNTIME_PRUNED_PREFIX)) { + removed.push(name.slice(PINNED_RUNTIME_PRUNED_PREFIX.length)); + } + }), ), Effect.catch((cause) => Effect.logWarning("Could not remove an unused t3 runtime.", { target, cause }), diff --git a/apps/server/src/environment/DirectEndpoints.ts b/apps/server/src/environment/DirectEndpoints.ts index 4508d208e75e6..c39ca1d85484e 100644 --- a/apps/server/src/environment/DirectEndpoints.ts +++ b/apps/server/src/environment/DirectEndpoints.ts @@ -24,7 +24,12 @@ import { import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "./ServerEnvironment.ts"; -import { isLoopbackHost, isPrivateNetworkAddress, isVirtualInterface } from "../startupAccess.ts"; +import { + isLoopbackHost, + isPrivateNetworkAddress, + isVirtualInterface, + WINDOWS_HOST_ADAPTER_MAC, +} from "../startupAccess.ts"; type NetworkInterfacesMap = ReturnType; @@ -52,9 +57,6 @@ const isTailscaleInterface = ( /^tailscale/i.test(name) || entries.some((entry) => entry.family === "IPv6" && isTailnetHost(entry.address)); -// Windows adapter names are mutable; Linux bridges can inherit these MACs. -const WINDOWS_HOST_ADAPTER_MAC = /^(0a:00:27|00:50:56:c0:00):/i; - export function resolveBoundEndpoints(input: { readonly platform: NodeJS.Platform; readonly host: string | undefined; diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 064427a3727f5..1bce13cb0f020 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -86,6 +86,8 @@ interface FakeProviderScenario { kind?: string; /** False for a host that opens every change request ready for review. */ createsDraftChangeRequests?: boolean; + /** The companion repository of a host with private change requests. */ + privateRemote?: { readonly url: string; readonly repository: string }; /** Answers to successive change request listings, whatever their head selector. */ prListSequence?: ReadonlyArray>; prListByHeadSelector?: Record>; @@ -124,6 +126,7 @@ type FakeProviderCall = readonly headSelector: string; readonly title: string; readonly draft: unknown; + readonly private?: boolean; } | { readonly operation: "getChangeRequest"; readonly reference: string } | { @@ -483,6 +486,9 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { service: { kind, createsDraftChangeRequests: scenario.createsDraftChangeRequests ?? true, + ...(scenario.privateRemote === undefined + ? {} + : { privateChangeRequestRemote: () => Effect.succeed(scenario.privateRemote!) }), ...headBranchProbe, listChangeRequests: (input) => record(input.cwd, { @@ -517,6 +523,7 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { headSelector: input.headSelector, title: input.title, draft: "draft" in input ? input.draft : undefined, + ...(input.private === undefined ? {} : { private: input.private }), }), getDefaultBranch: (input) => record(input.cwd, { operation: "getDefaultBranch" }).pipe( @@ -1100,6 +1107,60 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("a turn-end status refresh reads the branch remote and remote URL once", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["checkout", "-b", "feature/turn-end"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/turn-end"]); + const gitCommands: string[] = []; + const { manager } = yield* makeManager({ gitCommands }); + const count = (cmd: string) => gitCommands.filter((args) => args === cmd).length; + + // Turn end: local status, then the PR lookup for a branch that has no PR yet. + yield* manager.invalidateLocalStatus(repoDir); + yield* manager.localStatus({ cwd: repoDir }); + yield* manager.invalidateRemoteStatus(repoDir); + const remote = yield* manager.remoteStatus( + { cwd: repoDir }, + { refreshUpstream: false, refreshMissingPullRequest: true }, + ); + + expect(remote?.pr ?? null).toBeNull(); + expect(count("config --get branch.feature/turn-end.remote")).toBe(1); + expect(count("config --get-all remote.origin.url")).toBe(1); + + // The thread's PR backfill can reach the lookup before the status refresh does. + const backfillCommands: string[] = []; + const backfill = yield* makeManager({ gitCommands: backfillCommands }); + yield* backfill.manager.localStatus({ cwd: repoDir }); + yield* backfill.manager.branchPullRequest( + { cwd: repoDir, branch: "feature/turn-end" }, + { confirmTerminal: false }, + ); + yield* backfill.manager.remoteStatus( + { cwd: repoDir }, + { refreshUpstream: false, refreshMissingPullRequest: true }, + ); + expect( + backfillCommands.filter((args) => args === "config --get branch.feature/turn-end.remote") + .length, + ).toBe(1); + + // A fresh identity check reads git itself, not what local status just read. + yield* manager.invalidateLocalStatus(repoDir); + yield* manager.localStatus({ cwd: repoDir }); + gitCommands.length = 0; + yield* manager.branchPullRequest( + { cwd: repoDir, branch: "feature/turn-end" }, + { freshGitState: true }, + ); + expect(count("config --get-all remote.origin.url")).toBe(1); + }), + ); + it.effect("a git read in flight during a T3 git action does not outlive it", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -5052,6 +5113,132 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect( + "createPullRequest opens a private PR from the companion and never pushes to origin", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const companionDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "sec/fix"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "fix.txt"), "fix\n"); + yield* runGit(repoDir, ["add", "fix.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Fix"]); + const heads = (remote: string) => + runGit(repoDir, ["ls-remote", "--heads", remote]).pipe( + Effect.map((result) => + result.stdout + .split("\n") + .flatMap((line) => (line ? [line.split("\t")[1]] : [])) + .toSorted(), + ), + ); + const createPrivate = (manager: GitManager.GitManager["Service"]) => + manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Fix", + body: "Body", + private: true, + }); + + // A host without private pull requests refuses before anything is pushed. + const unsupported = yield* makeManager({ providerScenario: { prListSequence: [[]] } }); + const refused = yield* Effect.flip(createPrivate(unsupported.manager)); + expect(refused.message).toContain("has no private pull requests"); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + expect(created(unsupported.providerCalls)).toEqual([]); + + const privateRemote = { url: companionDir, repository: "pingdotgg/codething-mvp.private" }; + const open = { + number: 9, + title: "Fix", + url: "https://source.tanstack.com/@pingdotgg/codething-mvp/pull/9", + baseRefName: "main", + headRefName: "sec/fix", + headRepositoryNameWithOwner: privateRemote.repository, + }; + const supported = yield* makeManager({ + providerScenario: { privateRemote, prListSequence: [[], [open]] }, + }); + expect(yield* createPrivate(supported.manager)).toMatchObject({ + status: "created", + number: 9, + }); + expect(yield* heads(companionDir)).toEqual(["refs/heads/sec/fix"]); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + // The branch tracks the companion, which is how status finds its pull request. + expect( + (yield* runGit(repoDir, [ + "rev-parse", + "--abbrev-ref", + "sec/fix@{upstream}", + ])).stdout.trim(), + ).toBe("pingdotgg/sec/fix"); + expect( + (yield* runGit(repoDir, ["config", "--get", "branch.sec/fix.pushRemote"])).stdout.trim(), + ).toBe("pingdotgg"); + expect( + supported.providerCalls.flatMap((call) => + call.operation === "createChangeRequest" ? [call] : [], + ), + ).toMatchObject([{ baseRefName: "main", headSelector: "sec/fix", private: true }]); + + // Later commits follow the recorded push remote. + NodeFS.writeFileSync(NodePath.join(repoDir, "late.txt"), "late\n"); + yield* runGit(repoDir, ["add", "late.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Late"]); + const again = yield* makeManager({ + providerScenario: { privateRemote, prListSequence: [[open]] }, + }); + expect(yield* createPrivate(again.manager)).toMatchObject({ + status: "opened_existing", + number: 9, + }); + const localHead = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout.trim(); + expect( + (yield* runGit(repoDir, ["ls-remote", companionDir, "refs/heads/sec/fix"])).stdout, + ).toContain(localHead); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + expect(created(again.providerCalls)).toEqual([]); + + // A lookup answered before the create must not hide the pull request the create returns. + yield* runGit(repoDir, ["checkout", "-b", "sec/two", "main"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "two.txt"), "two\n"); + yield* runGit(repoDir, ["add", "two.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Two"]); + const two = { ...open, number: 10, headRefName: "sec/two" }; + const warmed = yield* makeManager({ + providerScenario: { privateRemote, prListByHeadSelector: { "sec/two": [two] } }, + }); + const lookup = warmed.manager.branchPullRequest({ cwd: repoDir, branch: "sec/two" }); + expect(yield* lookup).toBeNull(); + expect(yield* createPrivate(warmed.manager)).toMatchObject({ status: "opened_existing" }); + expect(yield* lookup).toMatchObject({ number: 10 }); + yield* runGit(repoDir, ["checkout", "sec/fix"]); + + // So does a create that forgets to ask for private: it never publishes the branch. + NodeFS.writeFileSync(NodePath.join(repoDir, "later.txt"), "later\n"); + yield* runGit(repoDir, ["add", "later.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Later"]); + const forgetful = yield* makeManager({ + providerScenario: { privateRemote, prListOtherwise: [open] }, + }); + yield* Effect.exit( + forgetful.manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Fix", + body: "Body", + }), + ); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + }), + ); + it.effect("createPullRequest pushes to the push remote and never to the base branch", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index dab6d4d20924e..dedf2d19f54ed 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -111,6 +111,8 @@ export interface GitLocalStatusOptions { export interface GitRemoteStatusOptions extends GitVcsDriver.GitRemoteStatusOptions { readonly refreshMissingPullRequest?: boolean; + /** Details the caller just read without fetching; used instead of reading them again. */ + readonly statusDetails?: GitVcsDriver.GitRemoteStatusDetails; } export type GitBranchPullRequest = NonNullable & { @@ -197,6 +199,12 @@ export class GitManager extends Context.Service< readonly body: string; readonly baseBranch?: string | undefined; readonly draft?: boolean | undefined; + /** + * Opens it where only people with write access see it. The branch goes to the host's + * private companion repository and never to the repository itself. Fails on a host + * without private pull requests. + */ + readonly private?: boolean | undefined; }) => Effect.Effect; readonly subscribePullRequestStateChanges: Effect.Effect< Stream.Stream, @@ -218,6 +226,8 @@ const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20); const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15); const PR_LOOKUP_CACHE_CAPACITY = 2_048; const PR_LOOKUP_GIT_STATE_TTL = Duration.minutes(5); +// Turn end looks up the PR ~0.5 s after local status; older reads are read again. +const LOCAL_STATUS_GIT_READS_HANDOFF_TTL = Duration.seconds(5); const SETTLED_PR_LOOKUP_RECHECK_INTERVAL = Duration.minutes(15); // Shared by every background caller (backfill, settlement, cleanup), so startup discovery // cannot fill the git and forge process slots that foreground work also needs. @@ -1287,7 +1297,7 @@ export const make = Effect.gen(function* () { Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)), ); const hostingProvider = details.hasOriginRemote - ? yield* resolveHostingProvider(cwd, details.branch) + ? yield* resolveHostingProviderForLocalStatus(cwd, details.branch) : null; return { @@ -1331,7 +1341,30 @@ export const make = Effect.gen(function* () { cwd: string, ): shared is SharedPrLookupGitReads => shared !== null && shared.open && shared.cwd === cwd && prLookupEpoch(cwd) === shared.epoch; - const withPrLookupGitReads = (effect: Effect.Effect, cwd: string) => + // Branch remote and remote URLs that local status just read, reused by the PR lookups that + // follow it (turn end runs the status lookup and the thread's PR backfill) instead of reading again. + const localStatusGitReads = new Map< + string, + Pick + >(); + const recentLocalStatusGitReads = (cwd: string) => + Clock.currentTimeMillis.pipe( + Effect.map((now) => { + const handoff = localStatusGitReads.get(cwd); + if (handoff === undefined || handoff.epoch !== prLookupEpoch(cwd)) return undefined; + const isFresh = (entry: RememberedPrLookupValue) => + now - entry.readAtMs < Duration.toMillis(LOCAL_STATUS_GIT_READS_HANDOFF_TTL); + return { + configValues: new Map([...handoff.configValues].filter(([, entry]) => isFresh(entry))), + remoteUrls: new Map([...handoff.remoteUrls].filter(([, entry]) => isFresh(entry))), + }; + }), + ); + const openPrLookupGitReads = ( + effect: Effect.Effect, + cwd: string, + handoff: Pick | undefined, + ) => Effect.suspend(() => { const shared: SharedPrLookupGitReads = { open: true, @@ -1339,8 +1372,8 @@ export const make = Effect.gen(function* () { cwd, epoch: prLookupEpoch(cwd), remotes: undefined, - configValues: new Map(), - remoteUrls: new Map(), + configValues: handoff?.configValues ?? new Map(), + remoteUrls: handoff?.remoteUrls ?? new Map(), }; return effect.pipe( Effect.provideService(prLookupGitReads, shared), @@ -1355,9 +1388,15 @@ export const make = Effect.gen(function* () { ), ); }); + const withPrLookupGitReads = (effect: Effect.Effect, cwd: string) => + openPrLookupGitReads(effect, cwd, undefined); + const withRecentLocalStatusGitReads = (effect: Effect.Effect, cwd: string) => + Effect.flatMap(recentLocalStatusGitReads(cwd), (handoff) => + openPrLookupGitReads(effect, cwd, handoff), + ); const withActivePrLookupGitReads = (cwd: string, effect: Effect.Effect) => Effect.flatMap(prLookupGitReads, (shared) => - isActivePrLookupGitReads(shared, cwd) ? effect : withPrLookupGitReads(effect, cwd), + isActivePrLookupGitReads(shared, cwd) ? effect : withRecentLocalStatusGitReads(effect, cwd), ); const prLookupCacheKey = ( cwd: string, @@ -1603,9 +1642,11 @@ export const make = Effect.gen(function* () { cwd: string, options?: GitRemoteStatusOptions, ) { - const details = yield* gitCore - .statusDetailsRemote(cwd, options) - .pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null))); + const details = + options?.statusDetails ?? + (yield* gitCore + .statusDetailsRemote(cwd, options) + .pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)))); if (details === null || !details.isRepo) { return null; } @@ -1777,6 +1818,32 @@ export const make = Effect.gen(function* () { .pipe(Effect.orElseSucceed(() => null)); return handle?.context?.provider ?? provider; }); + const resolveHostingProviderForLocalStatus = (cwd: string, branch: string | null) => + Effect.suspend(() => { + const reads: SharedPrLookupGitReads = { + open: true, + queriedProvider: false, + cwd, + epoch: prLookupEpoch(cwd), + remotes: undefined, + configValues: new Map(), + remoteUrls: new Map(), + }; + return resolveHostingProvider(cwd, branch).pipe( + Effect.provideService(prLookupGitReads, reads), + Effect.ensuring( + Effect.sync(() => { + reads.open = false; + localStatusGitReads.delete(cwd); + if (localStatusGitReads.size >= STATUS_RESULT_CACHE_CAPACITY) { + const oldestCwd = localStatusGitReads.keys().next().value; + if (oldestCwd !== undefined) localStatusGitReads.delete(oldestCwd); + } + localStatusGitReads.set(cwd, reads); + }), + ), + ); + }); const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* ( cwd: string, @@ -2820,9 +2887,131 @@ export const make = Effect.gen(function* () { }), ); - const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn( - "GitManager.createPullRequest", - )(function* (input) { + const openPrivatePullRequest = Effect.fn("GitManager.openPrivatePullRequest")(function* ( + input: Parameters[0], + ) { + const { cwd } = input; + const provider = yield* sourceControlProvider(cwd); + const definition = sourceControlDefinitions.get(provider.kind); + const terms = definition.changeRequest; + const fail = (detail: string, cause?: unknown) => + new GitManagerError({ + operation: "createPullRequest", + cwd, + detail, + ...(cause === undefined ? {} : { cause }), + }); + if (provider.privateChangeRequestRemote === undefined) { + return yield* fail( + `${definition.label} has no private ${terms.plural}. Nothing was pushed. Leave out private to open a public one.`, + ); + } + const status = yield* gitCore.statusDetails(cwd); + const branch = status.branch; + if (!branch) return yield* fail("Cannot create a pull request from detached HEAD."); + const resolved = yield* resolvePrBase(cwd, branch, status.upstreamRef, { + isCrossRepository: false, + remoteName: publishedRemoteName( + yield* readConfigValueNullable(cwd, `branch.${branch}.remote`), + ), + }); + const baseBranch = input.baseBranch ?? resolved.baseBranch; + if (baseBranch === branch) { + return yield* fail( + `${branch} is the base branch. Check out a feature branch to create ${terms.shortLabelWithArticle}.`, + ); + } + const companion = yield* provider.privateChangeRequestRemote({ cwd }); + const remoteName = yield* gitCore.ensureRemote({ + cwd, + preferredName: companion.repository.split("/")[0] || "private", + url: companion.url, + }); + // Recorded before the push, so a later push of this branch, by T3 or by plain `git push`, + // goes to the companion too and never publishes the branch. + yield* gitCore.writeConfigValue({ + cwd, + key: `branch.${branch}.pushRemote`, + value: remoteName, + }); + yield* gitCore + .execute({ + operation: "GitManager.openPrivatePullRequest.push", + cwd, + args: ["push", "--", remoteName, `refs/heads/${branch}:refs/heads/${branch}`], + timeoutMs: null, + }) + .pipe( + Effect.mapError((cause) => + fail(`Could not push ${branch} to ${companion.repository}: ${cause.detail}`, cause), + ), + Effect.tapError(() => invalidateStatus(cwd)), + ); + // The companion branch is the pull request's head, so status finds it through the upstream. + yield* gitCore + .setBranchUpstream({ cwd, branch, remoteName, remoteBranch: branch }) + .pipe(Effect.ensuring(invalidateStatus(cwd))); + const findOpen = provider + .listChangeRequests({ cwd, headSelector: branch, state: "open" }) + .pipe( + Effect.map( + (listed) => + listed.find( + (pr) => + pr.headRefName === branch && + pr.headRepositoryNameWithOwner?.toLowerCase() === + companion.repository.toLowerCase(), + ) ?? null, + ), + ); + const existing = yield* findOpen; + if (existing) { + return { + status: "opened_existing" as const, + url: existing.url, + number: existing.number, + baseBranch: existing.baseRefName, + headBranch: existing.headRefName, + title: existing.title, + }; + } + const bodyFile = path.join( + tempDir, + `t3code-pr-body-${process.pid}-${yield* randomUUIDv4(cwd)}.md`, + ); + yield* fileSystem + .writeFileString(bodyFile, input.body) + .pipe( + Effect.mapError((cause) => fail("Failed to write pull request body temp file.", cause)), + ); + yield* provider + .createChangeRequest({ + cwd, + baseRefName: baseBranch, + headSelector: branch, + title: input.title, + bodyFile, + private: true, + ...(input.draft === true ? { draft: true } : {}), + }) + .pipe( + Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.ignore)), + Effect.ensuring(invalidateStatus(cwd)), + ); + // The PR already exists at this point, so a failed lookup only loses its metadata. + const created = yield* findOpen.pipe(Effect.orElseSucceed(() => null)); + return { + status: "created" as const, + ...(created ? { url: created.url, number: created.number } : {}), + baseBranch: created?.baseRefName ?? baseBranch, + headBranch: created?.headRefName ?? branch, + title: created?.title ?? input.title, + }; + }); + + const pushAndOpenPullRequest = Effect.fn("GitManager.pushAndOpenPullRequest")(function* ( + input: Parameters[0], + ) { const status = yield* gitCore.statusDetails(input.cwd); const needsPush = yield* createPrNeedsPush(input.cwd, status); if (needsPush && status.branch) { @@ -2874,6 +3063,16 @@ export const make = Effect.gen(function* () { : Effect.void, ), ); + return result; + }); + + const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn( + "GitManager.createPullRequest", + )(function* (input) { + const result = + input.private === true + ? yield* openPrivatePullRequest(input) + : yield* pushAndOpenPullRequest(input); const openedAsDraft = result.status === "created" && (yield* sourceControlProvider(input.cwd)).createsDraftChangeRequests === true; @@ -3089,6 +3288,16 @@ export const make = Effect.gen(function* () { ], { concurrency: "unbounded" }, ).pipe(Effect.map((parts) => parts.join("\u0000"))); + // A fresh identity check, which confirms terminal results, must read git itself. + const withBranchPullRequestGitReads = ( + effect: Effect.Effect, + cacheCwd: string, + _branch: string, + options: { readonly freshGitState: boolean }, + ) => + options.freshGitState + ? withPrLookupGitReads(effect, cacheCwd) + : withRecentLocalStatusGitReads(effect, cacheCwd); const lookupBranchPullRequest = Effect.fn("lookupBranchPullRequest")(function* ( cacheCwd: string, branch: string, @@ -3257,7 +3466,7 @@ export const make = Effect.gen(function* () { // Hosting CLIs may target upstream; the PR URL identifies its actual repository. repositoryKey: pullRequestRepositoryKey(latest.url), }; - }, withPrLookupGitReads); + }, withBranchPullRequestGitReads); const checkedOutPullRequestKey = (branch: string) => `branch.${branch}.t3-pull-request`; diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index f012a65bb0692..4cf3e62d9a93f 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -59,6 +59,7 @@ export class GitWorkflowService extends Context.Service< readonly refName: string; readonly aheadCount: number; readonly behindCount: number; + readonly details: GitVcsDriver.GitRemoteStatusDetails; } | null, GitManagerServiceError >; @@ -68,7 +69,8 @@ export class GitWorkflowService extends Context.Service< ) => Effect.Effect; readonly invalidateLocalStatus: (cwd: string) => Effect.Effect; readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect; - readonly readRefSnapshot: (cwd: string) => Effect.Effect; + readonly readLocalStatusRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readLocalStatusRefSnapshot"]; + readonly readRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readRefSnapshot"]; readonly invalidateStatus: (cwd: string) => Effect.Effect; /** The checkout's own HEAD file, inside a linked worktree's admin directory when there is one. */ readonly headPath: (cwd: string) => Effect.Effect; @@ -384,6 +386,7 @@ export const make = Effect.gen(function* () { refName: details.branch, aheadCount: details.aheadCount, behindCount: details.behindCount, + details, } : null; }), @@ -396,6 +399,7 @@ export const make = Effect.gen(function* () { }), invalidateLocalStatus: gitManager.invalidateLocalStatus, invalidateRemoteStatus: gitManager.invalidateRemoteStatus, + readLocalStatusRefSnapshot: git.readLocalStatusRefSnapshot, readRefSnapshot: git.readRefSnapshot, invalidateStatus: gitManager.invalidateStatus, headPath: Effect.fn("GitWorkflowService.headPath")(function* (cwd) { diff --git a/apps/server/src/git/sharedCheckoutGuard.test.ts b/apps/server/src/git/sharedCheckoutGuard.test.ts new file mode 100644 index 0000000000000..1723b29c10bb8 --- /dev/null +++ b/apps/server/src/git/sharedCheckoutGuard.test.ts @@ -0,0 +1,167 @@ +import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as GitWorkflowService from "./GitWorkflowService.ts"; +import { assertCheckoutIdle, busyThreadsInCheckout } from "./sharedCheckoutGuard.ts"; + +const projectId = ProjectId.make("project-a"); +const otherProjectId = ProjectId.make("project-b"); +const nestedProjectId = ProjectId.make("project-nested"); +const childRepositoryProjectId = ProjectId.make("project-child-repository"); + +const thread = ( + title: string, + overrides: { + readonly projectId?: ProjectId; + readonly worktreePath?: string | null; + readonly activityRunStatus?: "preparing" | "starting" | "running" | "waiting" | null; + readonly archived?: boolean; + } = {}, +) => ({ + archived: overrides.archived ?? false, + id: ThreadId.make(title), + title, + projectId: overrides.projectId ?? projectId, + worktreePath: overrides.worktreePath ?? null, + activityRunStatus: + overrides.activityRunStatus === undefined ? "running" : overrides.activityRunStatus, +}); + +describe("busyThreadsInCheckout", () => { + it("finds running local threads in the project root checkout", () => { + const busy = busyThreadsInCheckout({ + checkoutPaths: ["/repo"], + projectIds: new Set([projectId]), + threads: [ + thread("local running"), + thread("local idle", { activityRunStatus: null }), + thread("worktree running", { worktreePath: "/worktrees/a" }), + thread("other project", { projectId: otherProjectId }), + ], + }); + + expect(busy.map(({ title }) => title)).toEqual(["local running"]); + }); + + it("finds running threads that share a worktree", () => { + const busy = busyThreadsInCheckout({ + checkoutPaths: ["/worktrees/a"], + projectIds: new Set(), + threads: [ + thread("same worktree", { worktreePath: "/worktrees/a", activityRunStatus: "waiting" }), + thread("other worktree", { worktreePath: "/worktrees/b" }), + thread("local running"), + ], + }); + + expect(busy.map(({ title }) => title)).toEqual(["same worktree"]); + }); +}); + +describe("assertCheckoutIdle", () => { + const guardLayer = (input: { + readonly repositoryRoot: string; + readonly threads: ReadonlyArray>; + readonly failWorktreeLookup?: boolean; + }) => + Layer.mergeAll( + Layer.mock(GitWorkflowService.GitWorkflowService)({ + repositoryRoot: (cwd) => + Effect.succeed(cwd.startsWith("/repo/child") ? "/repo/child" : input.repositoryRoot), + }), + Layer.mock(ProjectService.ProjectService)({ + snapshot: Effect.succeed({ + projects: [ + { id: projectId, workspaceRoot: "/repo" }, + { id: nestedProjectId, workspaceRoot: "/repo/packages/app" }, + { id: childRepositoryProjectId, workspaceRoot: "/repo/child" }, + { id: otherProjectId, workspaceRoot: "/other" }, + ], + } as never), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getShellSnapshot: (options) => + options?.worktreePath !== undefined && input.failWorktreeLookup + ? Effect.fail("worktree lookup failed" as never) + : Effect.succeed( + (() => { + const matching = input.threads.filter( + (candidate) => + (options?.projectId === undefined || + candidate.projectId === options.projectId) && + (options?.worktreePath === undefined || + candidate.worktreePath === options.worktreePath), + ); + return { + threads: matching.filter((candidate) => !candidate.archived), + archivedThreads: matching.filter((candidate) => candidate.archived), + } as never; + })(), + ), + }), + ); + + it.effect("refuses a switch from a subdirectory of a busy checkout", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo/src").pipe( + Effect.flip, + Effect.provide(guardLayer({ repositoryRoot: "/repo", threads: [thread("local running")] })), + ); + expect(error.detail).toContain("'local running'"); + }), + ); + + it.effect("keeps a busy thread when another lookup fails", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo").pipe( + Effect.flip, + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + threads: [thread("local running")], + failWorktreeLookup: true, + }), + ), + ); + expect(error.detail).toContain("'local running'"); + }), + ); + + it.effect("refuses a switch while a nested project or archived thread is working", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo").pipe( + Effect.flip, + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + threads: [ + thread("nested running", { projectId: nestedProjectId }), + thread("archived running", { archived: true }), + thread("other running", { projectId: otherProjectId }), + thread("child repository running", { projectId: childRepositoryProjectId }), + ], + }), + ), + ); + // Exactly these two: a third busy thread would read "and 1 more". + expect(error.detail).toMatch( + /^'(nested|archived) running' and '(nested|archived) running' are still working/, + ); + }), + ); + + it.effect("allows a switch when no thread is working", () => + assertCheckoutIdle("test", "/repo").pipe( + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + threads: [thread("local idle", { activityRunStatus: null })], + }), + ), + ), + ); +}); diff --git a/apps/server/src/git/sharedCheckoutGuard.ts b/apps/server/src/git/sharedCheckoutGuard.ts new file mode 100644 index 0000000000000..442ef14dc71e9 --- /dev/null +++ b/apps/server/src/git/sharedCheckoutGuard.ts @@ -0,0 +1,101 @@ +import { + GitCommandError, + type OrchestrationV2ThreadShell, + type ProjectId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; + +import * as GitWorkflowService from "./GitWorkflowService.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; + +type CheckoutThread = Pick< + OrchestrationV2ThreadShell, + "id" | "title" | "projectId" | "worktreePath" | "activityRunStatus" +>; + +/** Threads with an active run whose working directory is one of `checkoutPaths`. */ +export function busyThreadsInCheckout(input: { + readonly checkoutPaths: ReadonlyArray; + readonly projectIds: ReadonlySet; + readonly threads: ReadonlyArray; +}): ReadonlyArray { + return input.threads.filter( + (thread) => + (thread.activityRunStatus ?? null) !== null && + (thread.worktreePath === null + ? input.projectIds.has(thread.projectId) + : input.checkoutPaths.includes(thread.worktreePath)), + ); +} + +function describeBusyCheckout(titles: ReadonlyArray): string { + const quoted = titles.map((title) => `'${title}'`); + const names = + quoted.length <= 2 + ? quoted.join(" and ") + : `${quoted.slice(0, 2).join(", ")} and ${quoted.length - 2} more`; + return `${names} ${quoted.length === 1 ? "is" : "are"} still working in this checkout. Wait for ${quoted.length === 1 ? "it" : "them"} to finish, or use a worktree for a separate branch.`; +} + +/** Switching a shared checkout's ref moves every thread working in it, mid-turn included. */ +export const assertCheckoutIdle = Effect.fn("sharedCheckoutGuard.assertCheckoutIdle")(function* ( + operation: string, + cwd: string, +) { + const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; + const projectService = yield* ProjectService.ProjectService; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + // `git checkout` from a subdirectory moves the whole checkout; records may hold either spelling. + const root = yield* gitWorkflow.repositoryRoot(cwd).pipe(Effect.orElseSucceed(() => null)); + const checkoutPaths = [...new Set([cwd, ...(root === null ? [] : [root])])]; + const projects = yield* projectService.snapshot.pipe( + Effect.map((snapshot) => snapshot.projects), + Effect.orElseSucceed(() => []), + ); + // A project rooted inside the checkout shares it, as in a monorepo package, unless it is its + // own repository nested there. + const nested = yield* Effect.forEach( + projects.filter( + ({ workspaceRoot }) => + root !== null && + !checkoutPaths.includes(workspaceRoot) && + workspaceRoot.startsWith(`${root}/`), + ), + (project) => + gitWorkflow.repositoryRoot(project.workspaceRoot).pipe( + Effect.map((projectRoot) => (projectRoot === root ? [project] : [])), + Effect.orElseSucceed(() => []), + ), + { concurrency: "unbounded" }, + ); + const projectIds = new Set( + [ + ...projects.filter(({ workspaceRoot }) => checkoutPaths.includes(workspaceRoot)), + ...nested.flat(), + ].map(({ id }) => id), + ); + // Archiving does not stop a run, so archived threads can still be working. Each lookup fails + // open on its own, so one failure keeps what the others found. + const snapshots = yield* Effect.forEach( + [ + ...checkoutPaths.map((worktreePath) => threadManagement.getShellSnapshot({ worktreePath })), + ...[...projectIds].map((projectId) => threadManagement.getShellSnapshot({ projectId })), + ], + (snapshot) => snapshot.pipe(Effect.orElseSucceed(() => ({ threads: [], archivedThreads: [] }))), + { concurrency: "unbounded" }, + ); + const busy = busyThreadsInCheckout({ + checkoutPaths, + projectIds, + threads: snapshots.flatMap((snapshot) => [...snapshot.threads, ...snapshot.archivedThreads]), + }); + const titles = [...new Map(busy.map((thread) => [thread.id, thread.title])).values()]; + if (titles.length === 0) return; + return yield* new GitCommandError({ + operation, + command: "git checkout", + cwd, + detail: describeBusyCheckout(titles), + }); +}); diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index e8308b8480d02..6291f304e6efc 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -156,7 +156,9 @@ function makeService(input: { readonly projects: ReadonlyArray; readonly trackers: ReadonlyArray; readonly bindings?: Record; - readonly readBindings?: IssueTrackerBindings.IssueTrackerBindingsRepository["Service"]["list"]; + readonly readBindings?: ReturnType< + IssueTrackerBindings.IssueTrackerBindingsRepository["Service"]["list"] + >; }) { return IssueService.IssueService.pipe( Effect.provide( @@ -164,7 +166,7 @@ function makeService(input: { Layer.provide( Layer.mergeAll( Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ - list: + list: () => input.readBindings ?? Effect.succeed( new Map( diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 27499b240d655..9b9b050ab6ad0 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -42,6 +42,7 @@ import { type IssueTrackerApi, type StandaloneIssueTrackerApi, type TrackerIssueDetail, + type TrackerIssueLink, } from "@t3tools/source-control-core/server/IssueTracker"; import { parseUrl } from "@t3tools/shared/url"; @@ -148,6 +149,7 @@ export class IssueService extends Context.Service< { readonly list: (input: IssueListInput) => Effect.Effect; readonly detail: (input: IssueRef) => Effect.Effect; + readonly linkMetadata: (input: IssueRef) => Effect.Effect; readonly comments: ( input: IssueCommentsPageInput, ) => Effect.Effect; @@ -249,7 +251,7 @@ const make = Effect.gen(function* () { ); if (shells.length === 0) return []; // One read per listing, not per project, and never cached so Settings changes apply. - const bound = yield* bindings.list.pipe( + const bound = yield* bindings.list(filter.projectId).pipe( // A failed read is not an unbound project: that would list the git host's issues alone. Effect.mapError( (cause) => @@ -524,6 +526,22 @@ const make = Effect.gen(function* () { ), ); + const linkMetadata: IssueService["Service"]["linkMetadata"] = (input) => + requireProject(input).pipe( + Effect.flatMap((project) => { + const read = project.api.getIssueLink ?? project.api.getIssue; + return read({ + cwd: project.project.workspaceRoot, + host: project.host, + scope: project.scope, + key: input.key, + }).pipe( + Effect.map(({ title, url, displayKey }) => ({ title, url, displayKey })), + Effect.mapError(toIssueError("detail")), + ); + }), + ); + const comments: IssueService["Service"]["comments"] = (input) => requireProject(input).pipe( Effect.flatMap((project) => @@ -796,6 +814,7 @@ const make = Effect.gen(function* () { return IssueService.of({ list, detail: traced("detail", detail), + linkMetadata: traced("linkMetadata", linkMetadata), comments: traced("comments", comments), templates: traced("templates", templates), candidates: interactive(traced("candidates", candidates)), diff --git a/apps/server/src/issue/IssueTrackerConnections.ts b/apps/server/src/issue/IssueTrackerConnections.ts index 390cc9701e858..704116fc65326 100644 --- a/apps/server/src/issue/IssueTrackerConnections.ts +++ b/apps/server/src/issue/IssueTrackerConnections.ts @@ -113,7 +113,7 @@ const make = Effect.gen(function* () { const list: IssueTrackerConnections["Service"]["list"] = Effect.all({ trackers: Effect.forEach(registry.standalone, current, { concurrency: 4 }), - bindings: bindings.list.pipe( + bindings: bindings.list().pipe( Effect.map((bound) => Object.fromEntries(bound)), // No single tracker is at fault; the first registered one carries the report. Effect.mapError(secretFailure(anyTracker, "The project bindings could not be read.")), diff --git a/apps/server/src/issue/linkedThreads.ts b/apps/server/src/issue/linkedThreads.ts index c38b75c6b0944..03c337996f08a 100644 --- a/apps/server/src/issue/linkedThreads.ts +++ b/apps/server/src/issue/linkedThreads.ts @@ -15,6 +15,8 @@ const decodeLinkedThreads = Schema.decodeUnknownEffect(IssueLinkedThreadsResult) export const listLinkedIssueThreads = Effect.fn("listLinkedIssueThreads")( function* (key: ThreadIssueKey) { const sql = yield* SqlClient.SqlClient; + // The CASE stops SQLite hoisting the side-chat check out of the link loop, + // where it would re-parse every thread's payload, not just matching ones. const rows = yield* sql<{ id: string; projectId: string; @@ -37,9 +39,11 @@ export const listLinkedIssueThreads = Effect.fn("listLinkedIssueThreads")( t.updated_at AS "updatedAt" FROM orchestration_v2_projection_threads AS t JOIN json_each(t.payload_json, '$.issues') AS link - WHERE json_extract(link.value, '$.key') = ${key.key.trim()} - AND t.deleted_at IS NULL - AND json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1 + WHERE t.deleted_at IS NULL + AND CASE WHEN json_extract(link.value, '$.key') = ${key.key.trim()} + THEN json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1 + ELSE 0 + END ORDER BY "updatedAt" DESC, id ASC `.pipe(NodeSqliteClient.readOnly); const threads = rows diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index c404fef75ad52..7e846811e1440 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -446,16 +446,154 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }).pipe(Effect.provide(layerKeybindings())), ); - it.effect("unassigns a shortcut without restoring it on startup and can reassign it", () => + it.effect("preserves sibling shortcuts when editing an inherited shortcut", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + const target = { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" } as const; + const sibling = { ...target, key: "mod+n" }; + const unrelated = { ...sibling, command: "threadPanel.toggle" } as const; + yield* writeKeybindingsConfig(keybindingsConfigPath, [unrelated]); + + const replacement = { ...target, key: "f8" }; + const saved = yield* keybindings.upsertKeybindingRule({ + ...replacement, + replace: { ...target, key: "Shift+Mod+O", when: "!(terminalFocus)" }, + }); + const relevant = (rule: (typeof saved.keybindings)[number]) => + rule.command === target.command || rule.command === unrelated.command; + const expected = SharedKeybindings.compileResolvedKeybindingsConfig([ + sibling, + unrelated, + replacement, + ]); + assert.deepEqual(saved.keybindings.filter(relevant), expected); + + yield* keybindings.syncDefaultKeybindingsOnStartup; + const snapshot = yield* keybindings.getSnapshot; + assert.deepEqual(snapshot.keybindings.filter(relevant), expected); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect("preserves sibling shortcuts when adding to an inherited command", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + yield* writeKeybindingsConfig(keybindingsConfigPath, []); + + const added = { key: "f9", command: "chat.new" } as const; + const saved = yield* keybindings.upsertKeybindingRule(added); + assert.deepEqual( + saved.keybindings.filter((rule) => rule.command === added.command), + SharedKeybindings.compileResolvedKeybindingsConfig([ + { key: "mod+n", command: added.command, when: "!terminalFocus" }, + { key: "mod+shift+o", command: added.command, when: "!terminalFocus" }, + added, + ]), + ); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect("preserves sibling shortcuts by rejecting an edit that would evict saved rules", () => Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + const original = JSON.stringify([ + { key: "f7", command: "terminal.new" }, + ...Array.from({ length: MAX_KEYBINDINGS_COUNT - 2 }, (_, index) => ({ + key: "f1", + command: `future.command-${index}`, + })), + ]); + yield* fs.writeFileString(keybindingsConfigPath, original); + + const target = { key: "mod+n", command: "chat.new", when: "!terminalFocus" } as const; + const result = yield* toDetailResult( + keybindings.upsertKeybindingRule({ ...target, key: "f8", replace: target }), + ); + assertFailure(result, "Not enough room to save this shortcut and its inherited shortcuts."); + assert.equal(yield* fs.readFileString(keybindingsConfigPath), original); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect("preserves sibling shortcuts only if visible within the binding limit", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; yield* writeKeybindingsConfig( keybindingsConfigPath, - Array.from({ length: MAX_KEYBINDINGS_COUNT }, (_, index) => ({ + Array.from({ length: 210 }, (_, index) => ({ key: "mod+alt+f1", command: `script.filler-${index}.run` as const, })), ); + + const target = { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" } as const; + const local = { ...target, key: "mod+shift+n", command: "chat.newLocal" } as const; + const relevant = (rule: { readonly command: KeybindingCommand }) => + rule.command === target.command || rule.command === local.command; + const before = yield* keybindings.getSnapshot; + assert.deepEqual( + before.keybindings.filter(relevant), + SharedKeybindings.compileResolvedKeybindingsConfig([target, local]), + ); + + const replacement = { ...target, key: "f8" }; + const saved = yield* keybindings.upsertKeybindingRule({ ...replacement, replace: target }); + assert.deepEqual( + saved.keybindings.filter(relevant), + SharedKeybindings.compileResolvedKeybindingsConfig([local, replacement]), + ); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect( + "preserves sibling shortcuts when an inherited edit target has since become hidden", + () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + yield* writeKeybindingsConfig( + keybindingsConfigPath, + Array.from({ length: 209 }, (_, index) => ({ + key: "mod+alt+f1", + command: `script.filler-${index}.run` as const, + })), + ); + + const target = { key: "mod+n", command: "chat.new", when: "!terminalFocus" } as const; + const sibling = { ...target, key: "mod+shift+o" }; + const isChatNew = (binding: { readonly command: KeybindingCommand }) => + binding.command === target.command; + const before = yield* keybindings.getSnapshot; + assert.deepEqual( + before.keybindings.filter(isChatNew), + SharedKeybindings.compileResolvedKeybindingsConfig([target, sibling]), + ); + + const afterUnrelatedSave = yield* keybindings.upsertKeybindingRule({ + key: "mod+alt+f1", + command: "script.extra.run", + }); + assert.deepEqual( + afterUnrelatedSave.keybindings.filter(isChatNew), + SharedKeybindings.compileResolvedKeybindingsConfig([sibling]), + ); + + const replacement = { ...target, key: "f8" }; + const saved = yield* keybindings.upsertKeybindingRule({ ...replacement, replace: target }); + assert.deepEqual( + saved.keybindings.filter(isChatNew), + SharedKeybindings.compileResolvedKeybindingsConfig([sibling, replacement]), + ); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect("unassigns a shortcut without restoring it on startup and can reassign it", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + yield* writeKeybindingsConfig(keybindingsConfigPath, []); const keybindings = yield* Keybindings.Keybindings; const target = SharedKeybindings.DEFAULT_KEYBINDINGS.find( (rule) => rule.command === "composer.sendBackground", diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index d3d0fa5cbebd6..d9a6a8dbf01d3 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -174,6 +174,7 @@ const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule); const decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig); const decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries); const encodeRawKeybindingsEntriesPrettyJson = Schema.encodeEffect(RawKeybindingsEntriesPrettyJson); +const isSameResolvedKeybindingRule = Schema.toEquivalence(ResolvedKeybindingRule); export interface KeybindingsConfigState { readonly keybindings: ResolvedKeybindingsConfig; @@ -669,15 +670,34 @@ const make = Effect.gen(function* () { const customConfig = yield* loadWritableCustomKeybindingsConfig(); const rule = keybindingRuleFromInput(input); const replaceTarget = replaceTargetFromUpsertInput(input); - const siblingDefaults = - rule.when === "false" && - replaceTarget && - !customConfig.some(({ rule: entry }) => entry?.command === rule.command) - ? DEFAULT_KEYBINDINGS.filter( - (entry) => - entry.command === rule.command && !isSameKeybindingRule(entry, replaceTarget), - ).map((entry) => ({ value: entry, rule: entry })) - : []; + // A saved rule overrides every inherited default for its command. + let siblingDefaults: ReadonlyArray = []; + if ( + (!replaceTarget || + (replaceTarget.command === rule.command && + DEFAULT_KEYBINDINGS.some((entry) => isSameKeybindingRule(entry, replaceTarget)))) && + !customConfig.some(({ rule: entry }) => entry?.command === rule.command) && + decodeResolvedKeybindingFromConfigExit(rule)._tag === "Success" + ) { + const customRules = customConfig.flatMap(({ rule: entry }) => (entry ? [entry] : [])); + const visibleBindings = mergeWithDefaultKeybindings( + compileResolvedKeybindingsConfig(customRules), + ).filter((entry) => entry.command === rule.command); + siblingDefaults = DEFAULT_KEYBINDINGS.filter((entry) => { + if ( + entry.command !== rule.command || + (replaceTarget && isSameKeybindingRule(entry, replaceTarget)) || + isSameKeybindingRule(entry, rule) + ) { + return false; + } + const resolved = compileResolvedKeybindingRule(entry); + return ( + resolved && + visibleBindings.some((binding) => isSameResolvedKeybindingRule(binding, resolved)) + ); + }); + } const retainedConfig = customConfig.filter(({ rule: entry }) => { if (!entry) return true; return ( @@ -685,11 +705,20 @@ const make = Effect.gen(function* () { !isSameKeybindingRule(entry, rule) ); }); - const availableSlots = MAX_KEYBINDINGS_COUNT - siblingDefaults.length - 1; + const availableSlots = MAX_KEYBINDINGS_COUNT - 1; + if ( + siblingDefaults.length > 0 && + retainedConfig.length + siblingDefaults.length > availableSlots + ) { + return yield* new KeybindingsConfigError({ + configPath: keybindingsConfigPath, + detail: "Not enough room to save this shortcut and its inherited shortcuts.", + }); + } const nextConfig = [ ...siblingDefaults, - ...retainedConfig.slice(-availableSlots), - { value: rule, rule }, + ...retainedConfig.slice(-availableSlots).map(({ value }) => value), + rule, ]; if (retainedConfig.length > availableSlots) { yield* Effect.logWarning("truncating keybindings config to max entries", { @@ -697,7 +726,7 @@ const make = Effect.gen(function* () { maxEntries: MAX_KEYBINDINGS_COUNT, }); } - yield* writeConfigAtomically(nextConfig.map(({ value }) => value)); + yield* writeConfigAtomically(nextConfig); return yield* reloadAndEmit; }), ), diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index e5d47410817f2..3842d1a4b3bf2 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -124,7 +124,6 @@ const snapshotResult = { title: "Example", loading: false, visibleText: "Example", - interactiveElements: [], accessibilityTree: {}, consoleEntries: [], networkEntries: [], @@ -421,18 +420,6 @@ it.effect.each([ url: "http://example.test/", loading: false, visibleText: "Save your changes", - interactiveElements: [ - { - tag: "button", - role: "button", - name: "Save", - selector: "#save", - x: 0, - y: 0, - width: 20, - height: 10, - }, - ], accessibilityTree: { role: "document", name: "Example" }, consoleEntries: [], networkEntries: [], @@ -482,7 +469,7 @@ it.effect.each([ expect(snapshot.isError).toBe(false); expect(snapshot.structuredContent).toEqual({ ...boundedMetadata, - omitted: ["accessibilityTree (use interactiveElements locators or preview_evaluate)"], + omitted: ["accessibilityTree (use preview_evaluate)"], }); const [identity, text, ...rest] = snapshot.content; expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({ @@ -492,7 +479,7 @@ it.effect.each([ expect(rest).toEqual([ { type: "text", - text: "Snapshot text was bounded. Omitted: accessibilityTree (use interactiveElements locators or preview_evaluate).", + text: "Snapshot text was bounded. Omitted: accessibilityTree (use preview_evaluate).", }, ...(images ? [ @@ -890,25 +877,9 @@ it.effect("keeps the snapshot text under the agent's output ceiling", () => Effect.scoped( Effect.gen(function* () { const pageText = "/Users/theo/Code/project\nClaude, Codex · 79 threads\n".repeat(600); - const element = (name: string, index: number) => ({ - tag: "div", - role: "presentation", - name, - selector: `div:nth-of-type(${index})`, - x: 0, - y: 0, - width: 10, - height: 10, - }); const oversized = { ...snapshotResult, visibleText: pageText, - interactiveElements: [ - element(pageText, 1), - element(pageText, 2), - element(pageText, 3), - element("Continue", 4), - ], accessibilityTree: { nodes: Array.from({ length: 2_000 }, (_, i) => ({ nodeId: `${i}` })) }, consoleEntries: Array.from({ length: 100 }, (_, i) => ({ level: "log", @@ -933,14 +904,10 @@ it.effect("keeps the snapshot text under the agent's output ceiling", () => const parsed = decodeJsonText(body) as { readonly accessibilityTree?: unknown; readonly visibleText: string; - readonly interactiveElements: ReadonlyArray<{ readonly name: string }>; readonly consoleEntries: ReadonlyArray<{ readonly text: string }>; }; expect(parsed.accessibilityTree).toBeUndefined(); expect(parsed.visibleText.length).toBeLessThanOrEqual(8_001); - expect(parsed.interactiveElements).toHaveLength(4); - expect(parsed.interactiveElements[0]?.name.length).toBeLessThanOrEqual(201); - expect(parsed.interactiveElements[3]?.name).toBe("Continue"); expect(parsed.consoleEntries).toHaveLength(40); expect(parsed.consoleEntries[0]?.text).toBe("entry 60"); expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree"); @@ -960,7 +927,6 @@ it.effect("bounds the snapshot text even when nothing but logs and the title are const oversized = { ...snapshotResult, title: `t${"😀".repeat(35_000)}`, - interactiveElements: [], consoleEntries: [{ level: "log", text: `x${"😀".repeat(35_000)}`, timestamp: "t" }], }; yield* serveSnapshots("mcp-bounded-logs-client", oversized); @@ -992,19 +958,14 @@ it.effect("bounds the snapshot text even when nothing but logs and the title are it.effect("bounds page text made of wide characters before dropping locators", () => Effect.scoped( Effect.gen(function* () { + const accessibilityTree = Array.from( + { length: 20 }, + (_, i) => `- button "Button ${i}" [ref=t3-1-e${i}]`, + ).join("\n"); yield* serveSnapshots("mcp-wide-text-client", { ...snapshotResult, visibleText: "界".repeat(9_000), - interactiveElements: Array.from({ length: 20 }, (_, i) => ({ - tag: "button", - role: "button", - name: `Button ${i}`, - selector: `#button-${i}`, - x: 0, - y: 0, - width: 10, - height: 10, - })), + accessibilityTree, }); const snapshot = yield* callSnapshot({ includeImage: false }); @@ -1016,10 +977,10 @@ it.effect("bounds page text made of wide characters before dropping locators", ( ); const parsed = decodeJsonText(body) as { readonly visibleText: string; - readonly interactiveElements: ReadonlyArray; + readonly accessibilityTree: string; }; expect(parsed.visibleText).toMatch(/^界+…$/); - expect(parsed.interactiveElements).toHaveLength(20); + expect(parsed.accessibilityTree).toBe(accessibilityTree); expect(notice?.type === "text" ? notice.text : "").toContain( "visibleText after 4000 characters", ); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index d7bea75493b73..4c9d9dca1081a 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -373,7 +373,6 @@ export const MAX_SNAPSHOT_TEXT_BYTES = 20_000; const MAX_SNAPSHOT_VISIBLE_TEXT_CHARS = 8_000; // Page text and the ARIA tree both shrink to this before either drops below it. const SNAPSHOT_TEXT_FLOOR_CHARS = 2_000; -const MAX_SNAPSHOT_ELEMENT_NAME_CHARS = 200; const MAX_SNAPSHOT_LOG_ENTRIES = 40; const MAX_SNAPSHOT_LOG_TEXT_CHARS = 500; const MAX_SNAPSHOT_IDENTIFIER_CHARS = 2_048; @@ -406,10 +405,6 @@ type SnapshotMetadata = { readonly url: string; readonly title: string; readonly visibleText: string; - readonly interactiveElements: ReadonlyArray<{ - readonly name: string; - readonly [key: string]: unknown; - }>; readonly consoleEntries: ReadonlyArray; readonly networkEntries: ReadonlyArray; readonly actionTimeline: ReadonlyArray; @@ -426,7 +421,7 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { const { accessibilityTree, ...withoutTree } = metadata; const ariaTree = typeof accessibilityTree === "string" ? accessibilityTree : undefined; if (accessibilityTree !== undefined && ariaTree === undefined) { - omitted.push("accessibilityTree (use interactiveElements locators or preview_evaluate)"); + omitted.push("accessibilityTree (use preview_evaluate)"); } const tail = (entries: ReadonlyArray, label: string) => { if (entries.length > MAX_SNAPSHOT_LOG_ENTRIES) { @@ -444,41 +439,23 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { ) { omitted.push(`url or title after ${MAX_SNAPSHOT_IDENTIFIER_CHARS} characters`); } - if ( - metadata.interactiveElements.some( - (element) => element.name.length > MAX_SNAPSHOT_ELEMENT_NAME_CHARS, - ) - ) { - omitted.push(`element names longer than ${MAX_SNAPSHOT_ELEMENT_NAME_CHARS} characters`); - } const bounded = { ...withoutTree, url: cutText(metadata.url, MAX_SNAPSHOT_IDENTIFIER_CHARS), title: cutText(metadata.title, MAX_SNAPSHOT_IDENTIFIER_CHARS), - interactiveElements: metadata.interactiveElements.map((element) => ({ - ...element, - name: cutText(element.name, MAX_SNAPSHOT_ELEMENT_NAME_CHARS), - })), consoleEntries: tail(metadata.consoleEntries, "console entries"), networkEntries: tail(metadata.networkEntries, "network entries"), actionTimeline: tail(metadata.actionTimeline, "action timeline entries"), }; // Per-field character caps can still exceed the total byte ceiling. - const shedOrder = [ - "actionTimeline", - "networkEntries", - "consoleEntries", - "interactiveElements", - ] as const; + const shedOrder = ["actionTimeline", "networkEntries", "consoleEntries"] as const; const lists: Record<(typeof shedOrder)[number], ReadonlyArray> = { - interactiveElements: bounded.interactiveElements, consoleEntries: bounded.consoleEntries, networkEntries: bounded.networkEntries, actionTimeline: bounded.actionTimeline, }; const dropped: Record<(typeof shedOrder)[number], number> = { - interactiveElements: 0, consoleEntries: 0, networkEntries: 0, actionTimeline: 0, @@ -493,22 +470,18 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { }); let text = encodeJsonText(value()); while (utf8Length(text) > MAX_SNAPSHOT_TEXT_BYTES) { - // Logs shed first, oldest first. Below the floors, locator-bearing elements and tree go last. + // Logs shed first, oldest first. Below the floors, the locator-bearing tree goes last. const key = - shedOrder.find( - (candidate) => candidate !== "interactiveElements" && lists[candidate].length > 0, - ) ?? + shedOrder.find((candidate) => lists[candidate].length > 0) ?? (visibleTextChars > SNAPSHOT_TEXT_FLOOR_CHARS ? "visibleText" : ariaTreeChars > SNAPSHOT_TEXT_FLOOR_CHARS ? "accessibilityTree" : visibleTextChars > 0 ? "visibleText" - : lists.interactiveElements.length > 0 - ? "interactiveElements" - : ariaTreeChars > 0 - ? "accessibilityTree" - : undefined); + : ariaTreeChars > 0 + ? "accessibilityTree" + : undefined); if (key === undefined) break; if (key === "visibleText") { visibleTextChars = halveToFloor(visibleTextChars); @@ -517,12 +490,7 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { } else { const keep = Math.floor(lists[key].length / 2); dropped[key] += lists[key].length - keep; - lists[key] = - keep === 0 - ? [] - : key === "interactiveElements" - ? lists[key].slice(0, keep) - : lists[key].slice(-keep); + lists[key] = keep === 0 ? [] : lists[key].slice(-keep); } text = encodeJsonText(value()); } diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 2dad1fe68ee6d..551a84109cfa2 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -106,6 +106,7 @@ describe("OrchestratorMcpService", () => { threadId: parentThreadId, origin: "app_owned", childThreadId, + title: "Merge", driver: "codex", model: "gpt-5.6-terra", result: "terminal result", @@ -252,6 +253,13 @@ describe("OrchestratorMcpService", () => { const commandIds = yield* Ref.get(acknowledgementCommandIds); assert.equal(commandIds.length, 2); assert.notEqual(commandIds[0], commandIds[1]); + + const missing = yield* service + .taskStatus(scope, NodeId.make("node:mcp-ack-missing")) + .pipe(Effect.flip); + assert.equal(missing.code, "task_not_found"); + assert.include(missing.message, "No delegated task with id node:mcp-ack-missing"); + assert.include(missing.message, `${taskId} (Merge)`); }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); }), ); @@ -617,7 +625,8 @@ describe("OrchestratorMcpService", () => { const childThreadId = ThreadId.make("thread:mcp-next-child"); const taskId = NodeId.make("node:mcp-next-task"); let finished = false; - let pendingRequest = false; + let firstRun = false; + let pendingRequest: "live" | "message" | null = null; const parentProjection = () => ({ thread: { id: parentThreadId }, @@ -640,19 +649,33 @@ describe("OrchestratorMcpService", () => { const childRun = () => ({ id: RunId.make("run:mcp-next-child"), ordinal: 1, - status: finished ? ("completed" as const) : ("running" as const), - delegatedTaskId: taskId, + status: finished && !firstRun ? ("completed" as const) : ("running" as const), + // A task's first run is untagged; the child's fork node names the task. + ...(firstRun ? {} : { delegatedTaskId: taskId }), }); const childProjection = () => ({ - thread: { id: childThreadId, title: "Child task" }, + thread: { + id: childThreadId, + title: "Child task", + forkedFrom: { type: "node", nodeId: taskId }, + }, runs: [childRun()], contextTransfers: [], messages: [], subagents: [], providerThreads: [], providerTurns: [], - runtimeRequests: pendingRequest ? [{ status: "pending" }] : [], + runtimeRequests: + pendingRequest === null + ? [] + : [ + { + kind: "user_input", + status: "pending", + responseCapability: { type: pendingRequest }, + }, + ], nodes: [], turnItems: [], }) as unknown as OrchestrationV2ThreadProjection; @@ -668,7 +691,7 @@ describe("OrchestratorMcpService", () => { Effect.succeed({ threadId: childThreadId, run: childRun() as unknown as OrchestrationV2ThreadProjection["runs"][number], - timedOut: !finished, + timedOut: !finished || firstRun, }), dispatch: () => Effect.succeed({} as never), }), @@ -705,13 +728,28 @@ describe("OrchestratorMcpService", () => { assert.equal(waiting.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); // A child waiting on a question or approval needs an answer, not a wake. - pendingRequest = true; + pendingRequest = "live"; const asking = yield* service.waitForThread(scope, { threadId: childThreadId }); assert.isTrue(asking.timedOut); assert.notProperty(asking, "next"); - pendingRequest = false; + // A question answered by message does not stop the child. + pendingRequest = "message"; + const working = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.equal(working.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); + pendingRequest = null; + + firstRun = true; + const first = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.equal(first.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); + + // An untagged run after the task has its result is no longer that task. finished = true; + const followUp = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.isTrue(followUp.timedOut); + assert.notProperty(followUp, "next"); + firstRun = false; + const completed = yield* service.taskStatus(scope, taskId); assert.equal(completed.status, "completed"); assert.notProperty(completed, "next"); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 07b137c61e354..f9ad32a6e1d3e 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -154,6 +154,7 @@ const TASK_WAKE_EVENTS = [ { thread: "child", eventType: "runtime-request.updated" }, ] as const; const SECRET_REQUEST_POLL_INTERVAL_MS = 500; +const MAX_LISTED_TASKS = 10; const DEFAULT_THREAD_LIST_LIMIT = 10; const DEFAULT_THREAD_READ_LIMIT = 10; const DEFAULT_THREAD_RUN_LIMIT = 10; @@ -1805,6 +1806,33 @@ const make = Effect.gen(function* () { const requestKey = (clientRequestId: string | undefined): Effect.Effect => clientRequestId === undefined ? random.uuidV4() : Effect.succeed(clientRequestId); + const taskNotFound = Effect.fn("OrchestratorMcpService.taskNotFound")(function* ( + scope: McpThreadInvocationScope, + taskId: NodeId, + ): Effect.fn.Return { + const { subagents } = yield* loadThreadRecords(scope.thread.threadId, ["subagents"], { + omitSettledSubagents: true, + }); + const open = subagents.filter( + (task) => + task.origin === "app_owned" && + (task.childThreadId !== null || task.remoteChild !== undefined), + ); + const listed = open + .slice(0, MAX_LISTED_TASKS) + .map((task) => (task.title ? `${task.id} (${task.title})` : task.id)) + .join(", "); + const more = + open.length > MAX_LISTED_TASKS ? `, and ${open.length - MAX_LISTED_TASKS} more` : ""; + return yield* failure( + "task_not_found", + `No delegated task with id ${taskId} exists on thread ${scope.thread.threadId}. ` + + (open.length === 0 + ? "This thread has no open delegated tasks." + : `Open delegated tasks on this thread: ${listed}${more}.`), + ); + }); + const readTask = Effect.fn("OrchestratorMcpService.readTask")(function* ( scope: McpThreadInvocationScope, taskId: NodeId, @@ -1820,10 +1848,7 @@ const make = Effect.gen(function* () { candidate.threadId === scope.thread.threadId, ); if (task === undefined || (task.childThreadId === null && task.remoteChild === undefined)) { - return yield* failure( - "task_not_found", - `Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`, - ); + return yield* taskNotFound(scope, taskId); } if (task.childThreadId === null) { return yield* readRemoteTask(scope, task, waitTimedOut, acknowledgeTerminal); @@ -3006,10 +3031,7 @@ const make = Effect.gen(function* () { task.remoteChild !== undefined, ); if (remoteTask === undefined) { - return yield* failure( - "task_not_found", - `Delegated task ${input.taskId} does not belong to thread ${scope.thread.threadId}.`, - ); + return yield* taskNotFound(scope, input.taskId); } return yield* remoteDelegation.cancel(scope, remoteTask, input); } @@ -3298,6 +3320,7 @@ const make = Effect.gen(function* () { threadId, projectId: parent.thread.projectId, title, + ...(request.title?.trim() ? { titleRenamed: true } : {}), modelSelection: target.modelSelection, runtimeMode, interactionMode, @@ -3712,7 +3735,11 @@ const make = Effect.gen(function* () { }) .pipe(Effect.mapError(threadManagementFailure)); const status = result.run === null ? "idle" : runOutcome(result.run); - const taskId = result.run?.delegatedTaskId; + // A task's first run carries no task id; the child's untagged runs continue that task + // until it has a result. + const taskId = + result.run?.delegatedTaskId ?? + (target.thread.forkedFrom?.type === "node" ? target.thread.forkedFrom.nodeId : undefined); const ownedTask = result.timedOut && status !== "waiting" && @@ -3724,7 +3751,8 @@ const make = Effect.gen(function* () { task.origin === "app_owned" && task.threadId === parent.thread.id && task.childThreadId === input.threadId && - task.completionDelivery?.state !== "disposed", + task.completionDelivery?.state !== "disposed" && + (result.run?.delegatedTaskId !== undefined || task.result === null), ); // A child waiting on a question or approval needs an answer, not a wake. const childRequests = ownedTask @@ -3733,7 +3761,10 @@ const make = Effect.gen(function* () { .pipe(Effect.mapError(threadManagementFailure))).runtimeRequests : []; const wakesCaller = - ownedTask && !childRequests.some((request) => request.status === "pending"); + ownedTask && + !childRequests.some( + (request) => request.status === "pending" && request.responseCapability.type === "live", + ); return { threadId: input.threadId, runId: result.run?.id ?? null, diff --git a/apps/server/src/mcp/toolkits/issues/handlers.test.ts b/apps/server/src/mcp/toolkits/issues/handlers.test.ts index 143ba4a0c98a3..9867324f7fc23 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.test.ts @@ -158,6 +158,7 @@ const makeHarness = Effect.fn("makeIssuesToolkitHarness")(function* ( issueLayer ?? Layer.mock(IssueService.IssueService)({ detail: () => Effect.succeed(detail), + linkMetadata: () => Effect.succeed(detail), projectScope: (projectId) => Effect.succeed({ projectId, @@ -260,7 +261,7 @@ describe("issue toolkit handlers", () => { projectLayer, Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ - list: Effect.succeed(new Map([[PROJECT_ID, { tracker, scope: "ENG" }]])), + list: () => Effect.succeed(new Map([[PROJECT_ID, { tracker, scope: "ENG" }]])), }), Layer.succeed( IssueTrackerRegistry.IssueTrackerRegistry, @@ -314,9 +315,10 @@ describe("issue toolkit handlers", () => { projectLayer, Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ - list: Effect.succeed( - new Map([[PROJECT_ID, { tracker, scope: "ENG", additionalScopes: ["OPS"] }]]), - ), + list: () => + Effect.succeed( + new Map([[PROJECT_ID, { tracker, scope: "ENG", additionalScopes: ["OPS"] }]]), + ), }), Layer.succeed( IssueTrackerRegistry.IssueTrackerRegistry, diff --git a/apps/server/src/mcp/toolkits/issues/handlers.ts b/apps/server/src/mcp/toolkits/issues/handlers.ts index b45b3d3dbd875..c09dbc356d61f 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.ts @@ -269,20 +269,20 @@ const make = Effect.gen(function* () { link_issue: writesThread((input) => Effect.gen(function* () { const thread = yield* requireThread(input.threadId); - const target = yield* resolveTarget({ + const target: ResolvedTarget = yield* resolveTarget({ ...input, projectId: input.projectId ?? thread.projectId, }); // Reading the issue proves it exists and names it for the thread's row. - const detail = yield* readIssue(target); - const url = target.url ?? detail.url; + const issue = target.issue ?? (yield* issues.linkMetadata(refOf(target))); + const url = target.url ?? issue.url; const { alreadyLinked } = yield* threadIssues .link({ threadId: thread.id, ref: refOf(target), url, - displayKey: detail.displayKey, - title: detail.title, + displayKey: issue.displayKey, + title: issue.title, source: "agent", }) .pipe(Effect.catchCause(linkFailure)); diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index c13a8ab9353cc..d03b038ee0780 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -254,6 +254,7 @@ it.effect( expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required"); expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined(); expect(belowCeiling.launched[0]?.generateTitle).toBeUndefined(); + expect(belowCeiling.launched[0]?.titleRenamed).toBe(true); const titled = yield* launchWith("full-access", "full-access", { title: "Fix", @@ -261,6 +262,7 @@ it.effect( message: "Fix the bug", }); expect(titled.launched[0]).toMatchObject({ title: "Fix", generateTitle: true }); + expect(titled.launched[0]?.titleRenamed).toBeUndefined(); for (const message of [undefined, "", " \n "]) { const idleTitled = yield* launchWith("full-access", "full-access", { diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 3966d48ccd090..76f53b43bdfdc 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -438,6 +438,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { projectId, title: input.title, ...(input.generateTitle === undefined ? {} : { generateTitle: input.generateTitle }), + ...(input.generateTitle === true ? {} : { titleRenamed: true }), modelSelection, runtimeMode: startedRuntimeMode, interactionMode, diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index b7edff187579d..7caa425d32f2e 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -837,6 +837,7 @@ describe("source control tools", () => { body: "Adds tools.", state: "open", isDraft: false, + visibility: "private", author: null, headBranch: "tools", baseBranch: "main", @@ -892,6 +893,7 @@ describe("source control tools", () => { }); const compact = yield* harness.call("pull_request_read", {}); expect(compact).toMatchObject({ + visibility: "private", headSha: "abc123", checks: { passed: 2, pending: 1, failed: ["Lint", "E2E"], incomplete: true }, unresolvedThreads: 1, @@ -1178,7 +1180,11 @@ describe("source control tools", () => { it.effect("opens a PR from the thread's worktree and links it even if dismissed", () => Effect.gen(function* () { - const opened: Array<{ readonly cwd: string; readonly draft: boolean | undefined }> = []; + const opened: Array<{ + readonly cwd: string; + readonly draft: boolean | undefined; + readonly private: boolean | undefined; + }> = []; const harness = yield* makeHarness({ thread: { ...makeThread([makeLink(43, { source: "stack-dismissed" })]), @@ -1186,7 +1192,9 @@ describe("source control tools", () => { }, git: { createPullRequest: (input) => - Effect.sync(() => opened.push({ cwd: input.cwd, draft: input.draft })).pipe( + Effect.sync(() => + opened.push({ cwd: input.cwd, draft: input.draft, private: input.private }), + ).pipe( Effect.as({ status: "created" as const, url: "https://github.com/t3tools/t3code/pull/43", @@ -1202,9 +1210,10 @@ describe("source control tools", () => { title: "Add tools", body: "Adds tools.", draft: true, + private: true, }); expect(result).toMatchObject({ number: 43, created: true }); - expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true }]); + expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true, private: true }]); expect(yield* Ref.get(harness.commands)).toMatchObject([ { type: "thread.pull-request.link", number: 43, source: "created" }, ]); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index f85d8f0abac4a..ddb3f2a025d43 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -66,6 +66,7 @@ import { PullRequestsToolkit, type ThreadPullRequestEntry, alreadyEndedWatchNext, + CHECKS_ALREADY_PASSED_WATCH_NEXT, CHILD_PULL_REQUEST_REPORT_NEXT, } from "./tools.ts"; @@ -333,9 +334,11 @@ const make = Effect.gen(function* () { .setWatching({ threadId, target: input, watching, until: input.until }) .pipe( Effect.map((result) => - result.state === undefined - ? result - : { ...result, next: alreadyEndedWatchNext(result.state) }, + result.state !== undefined + ? { ...result, next: alreadyEndedWatchNext(result.state) } + : result.checksState === "passing" + ? { ...result, next: CHECKS_ALREADY_PASSED_WATCH_NEXT } + : result, ), Effect.catchTags({ PullRequestWatchThreadNotFoundError: (error) => @@ -617,6 +620,7 @@ const make = Effect.gen(function* () { title: detail.title, state: detail.state, isDraft: detail.isDraft, + ...(detail.visibility === undefined ? {} : { visibility: detail.visibility }), author: detail.author?.login ?? null, headBranch: detail.headBranch, baseBranch: detail.baseBranch, @@ -1052,6 +1056,7 @@ const make = Effect.gen(function* () { body: input.body, baseBranch: input.base, draft: input.draft, + private: input.private, }) .pipe(Effect.mapError(forgeFailure)); if (created.url === undefined) { diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 71d0a28d4e392..1e75c5bbaa19f 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -16,6 +16,7 @@ import { PullRequestReviewGuideRun, PullRequestState, PullRequestUnavailableError, + PullRequestVisibility, PullRequestWatchUntil, ThreadPullRequestLinkSource, TrimmedNonEmptyString, @@ -262,6 +263,7 @@ export const WatchPullRequestResult = Schema.Struct({ description: "The PR already ended, so nothing was watched.", }), ), + checksState: Schema.optional(PullRequestChecksState), next: Schema.optional(Schema.String), }); export type WatchPullRequestResult = typeof WatchPullRequestResult.Type; @@ -269,6 +271,9 @@ export type WatchPullRequestResult = typeof WatchPullRequestResult.Type; export const alreadyEndedWatchNext = (state: "merged" | "closed") => `This PR is already ${state}, so there is nothing to watch. Report that and end your turn.`; +export const CHECKS_ALREADY_PASSED_WATCH_NEXT = + "Checks already pass on this head, so no wake will come for them. Act on that now; the watch still wakes you on later changes."; + export const ThreadPullRequestEntry = Schema.Struct({ ...PullRequestIdentity, source: ThreadPullRequestLinkSource, @@ -517,6 +522,9 @@ export const ReadPullRequestResult = Schema.Struct({ title: Schema.String, state: PullRequestState, isDraft: Schema.Boolean, + visibility: Schema.optional(PullRequestVisibility).annotate({ + description: "Only on a host with private PRs.", + }), author: Schema.NullOr(Schema.String), headBranch: Schema.String, baseBranch: Schema.String, @@ -675,6 +683,10 @@ const CreatePullRequestTool = Tool.make("pull_request_create", { body: Schema.String, base: Schema.optional(TrimmedNonEmptyString), draft: Schema.optional(Schema.Boolean), + private: Schema.optional(Schema.Boolean).annotate({ + description: + "Visible to writers only; the branch never reaches origin. Fails on a host without private PRs.", + }), }), success: CreatePullRequestResult, failure: PullRequestToolError, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index d79257944c8e9..7815f8d959a2f 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -8,7 +8,11 @@ import { } from "@t3tools/provider-acp-registry/testing"; import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings"; import { AcpRegistryCatalog } from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; -import { decodeAcpReplayTranscript, makeAcpReplayRuntime } from "./AcpAdapterV2.testkit.ts"; +import { + decodeAcpReplayTranscript, + makeAcpReplayCompletenessAssertion, + makeAcpReplayRuntime, +} from "./AcpAdapterV2.testkit.ts"; // @effect-diagnostics nodeBuiltinImport:off import * as NodeFS from "node:fs"; import * as NodeHttp from "node:http"; @@ -3038,6 +3042,180 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + // regression: #27646 an agent that leaves its mode itself must not be forced back, but picking + // the old mode again must reach it, even when a v1 agent reports only the mode update. + it.live("reports a mode the agent left itself so picking it again is sent", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-mode-only-" }); + const statusPath = path.join(directory, "status.json"); + const sessionId = "mode-only-session"; + const modeOption = (currentValue: string) => ({ + id: "mode", + name: "Mode", + category: "mode", + type: "select", + currentValue, + options: [ + { value: "ask", name: "Ask" }, + { value: "architect", name: "Architect" }, + ], + }); + const setArchitect = [ + { + type: "expect_outbound" as const, + frame: { + kind: "request", + method: "session/set_config_option", + params: { sessionId, configId: "mode", value: "architect" }, + }, + }, + { + type: "emit_inbound" as const, + frame: { + kind: "response", + method: "session/set_config_option", + result: { configOptions: [modeOption("architect")] }, + }, + }, + ]; + const prompt = (updates: ReadonlyArray) => [ + { + type: "expect_outbound" as const, + frame: { kind: "request", method: "session/prompt", params: "" }, + }, + ...updates.map((update) => ({ + type: "emit_inbound" as const, + frame: { kind: "notification", method: "session/update", params: { sessionId, update } }, + })), + { + type: "emit_inbound" as const, + frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } }, + }, + ]; + const transcript = yield* decodeAcpReplayTranscript( + { + provider: ACP_TEST_DRIVER, + protocol: "acp.ndjson-jsonrpc", + version: "1", + scenario: "mode-only-update", + entries: [ + { + type: "expect_outbound", + frame: { kind: "request", method: "initialize", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "initialize", + result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] }, + }, + }, + { + type: "expect_outbound", + frame: { kind: "request", method: "session/new", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/new", + result: { sessionId, configOptions: [modeOption("ask")] }, + }, + }, + ...setArchitect, + ...prompt([{ sessionUpdate: "current_mode_update", currentModeId: "ask" }]), + ...prompt([]), + ...setArchitect, + ...prompt([]), + ], + }, + ACP_TEST_DRIVER, + ); + const instanceId = ProviderInstanceId.make("acp-test-mode-only"); + const threadId = ThreadId.make("thread-acp-mode-only"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeAcpReplayRuntime({ + transcript, + statusPath, + fileSystem, + scriptPath: yield* path.fromFileUrl( + new URL("../../../scripts/acp-replay-agent.ts", import.meta.url), + ), + childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, + }), + }, + selfInvocation: yield* resolveSelfInvocation(), + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: directory, + }); + const architect = { + instanceId, + model: "default", + options: [{ id: "mode", value: "architect" }], + } as const; + const ask = { ...architect, options: [{ id: "mode", value: "ask" }] }; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-mode-only"), + modelSelection: architect, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: architect, + runtimePolicy, + }); + const now = yield* DateTime.now; + const reported: Array = []; + // The thread follows the agent to ask; only the user's renewed pick sets architect again. + for (const [ordinal, modelSelection] of [ + [1, architect], + [2, ask], + [3, architect], + ] as const) { + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal, + modelSelection, + }), + ); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runForEach((event) => + Effect.sync(() => { + if (event.type === "thread_model_selection.updated") { + reported.push({ + threadId: event.threadId, + instanceId: event.instanceId, + changes: event.changes, + }); + } + }), + ), + ); + } + assert.deepStrictEqual(reported, [ + { threadId, instanceId, changes: [{ id: "mode", from: "architect", to: "ask" }] }, + ]); + yield* makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + // regression: #21499 turns blocked only on T3 thread waits must show as waiting it.effect.each(["agent_message_chunk"] as const)( "keeps named ACP %s open while deriving thread wait execution state", @@ -11857,6 +12035,8 @@ describe("AcpAdapterV2", () => { assert.deepInclude(late.providerThread.contextUsage, { usedTokens: 13101 }); // With no run left to receive it, only a session-scoped update reaches the projection. assert.isTrue(late.sessionScoped); + // It is written straight to the projection, so it must not revive the settled turn. + assert.equal(late.providerThread.status, "idle"); }).pipe(Effect.provide(layerTest), Effect.scoped), ); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index e1665b1bafb3e..c0733af964b30 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -42,6 +42,7 @@ import { type OrchestrationV2AppThread, type OrchestrationV2PendingBackgroundTask, OrchestrationV2ProviderThread, + OrchestrationV2ProviderTurnTokenUsage, ProjectId, ProviderInstanceId, type ResolvedProviderInstanceEnvironment, @@ -978,6 +979,8 @@ describe("ClaudeAdapterV2 device instructions", () => { }); }); +const decodeProviderTurnTokenUsage = Schema.decodeSync(OrchestrationV2ProviderTurnTokenUsage); + describe("ClaudeAdapterV2 context usage", () => { it("dates cache expiry from the request start, not the response end", () => { const usage = ClaudeAdapterV2.claudeProviderTurnTokenUsage( @@ -993,6 +996,28 @@ describe("ClaudeAdapterV2 context usage", () => { ); assert.strictEqual(usage.promptCacheExpiresAt, "2026-08-29T00:05:00.000Z"); }); + + it("counts missing, negative, or non-finite usage fields as zero", () => { + const partialUsage = ClaudeAdapterV2.claudeProviderTurnTokenUsage( + { + input_tokens: 1_200, + cache_creation_input_tokens: Number.NaN, + cache_read_input_tokens: -5, + output_tokens: undefined, + }, + 200_000, + "2026-08-29T00:03:00.000Z", + ); + assert.deepEqual(decodeProviderTurnTokenUsage(partialUsage), { + usedTokens: 1_200, + maxTokens: 200_000, + inputTokens: 1_200, + cachedInputTokens: 0, + outputTokens: 0, + reasoningOutputTokens: 0, + updatedAt: "2026-08-29T00:03:00.000Z", + }); + }); }); describe("ClaudeAdapterV2 approval presentation", () => { @@ -10359,6 +10384,90 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("ignores empty stream usage frames and accepts partial usage deltas from proxies", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-empty-start-usage"), + text: "Continue.", + attachments: [], + }), + ); + // Some Anthropic-compatible proxies send an empty `usage: {}` object on + // message_start or omit fields from message_delta / assistant snapshots. + const frames = [ + usageStreamFrame({ + type: "message_start", + message: { id: "msg_empty_first", usage: {} }, + }), + usageSnapshotFrame("msg_empty_first", "00000000-0000-4000-8000-000000000674", {}), + usageStreamFrame({ + type: "message_delta", + delta: { stop_reason: "tool_use", stop_sequence: null }, + usage: { input_tokens: 12_345 }, + }), + usageStreamFrame({ + type: "message_start", + message: { id: "msg_empty_second", usage: {} }, + }), + usageSnapshotFrame("msg_empty_second", "00000000-0000-4000-8000-000000000675", { + input_tokens: 12_500, + }), + usageStreamFrame({ + type: "message_delta", + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { output_tokens: 80 }, + }), + usageStreamFrame({ + type: "message_start", + message: { id: "msg_null_usage", usage: null }, + }), + usageStreamFrame({ + type: "message_delta", + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { input_tokens: 12_600, output_tokens: 40 }, + }), + usageSnapshotFrame("msg_null_usage", "00000000-0000-4000-8000-000000000676", {}), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000677", result: "Done." }), + ]; + for (const frame of frames) yield* Queue.offer(harness.sdkMessages, frame); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "completed"); + const tokenUsages = harness.events.flatMap((event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage + ? [decodeProviderTurnTokenUsage(event.providerTurn.tokenUsage)] + : [], + ); + assert.deepEqual( + tokenUsages.map((usage) => ({ + usedTokens: usage.usedTokens, + inputTokens: usage.inputTokens, + outputTokens: usage.outputTokens, + cachedInputTokens: usage.cachedInputTokens, + })), + [ + { usedTokens: 12_345, inputTokens: 12_345, outputTokens: 0, cachedInputTokens: 0 }, + { usedTokens: 12_500, inputTokens: 12_500, outputTokens: 0, cachedInputTokens: 0 }, + { usedTokens: 12_580, inputTokens: 12_500, outputTokens: 80, cachedInputTokens: 0 }, + { usedTokens: 12_640, inputTokens: 12_600, outputTokens: 40, cachedInputTokens: 0 }, + ], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("measures a model outside the catalog against the window Claude reports", () => Effect.gen(function* () { const harness = yield* makeWakeHarness; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts index bed26e69ae008..5d08adab93042 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts @@ -1496,7 +1496,9 @@ const resolveClaudeRecordingExecutablePath = Effect.fn("resolveClaudeRecordingEx function* (environment: NodeJS.ProcessEnv) { const resolveExecutable = yield* SpawnExecutableResolution; const platform = yield* HostProcess.Platform; - const resolved = resolveExecutable("claude", platform, environment); + const resolved = yield* Effect.promise(async () => + resolveExecutable("claude", platform, environment), + ); if (resolved === undefined) { return undefined; } diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index b120f9feb5e5a..5b8c5fabd54b7 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -290,25 +290,31 @@ function claudeAutoCompactThreshold(autoCompactWindow: string, maxTokens: number : {}; } +function optionalClaudeUsageTokenCount(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) && value >= 0 + ? Math.round(value) + : undefined; +} + function claudeMessageInputTokens(usage: { - readonly input_tokens: number; - readonly cache_creation_input_tokens?: number | null; - readonly cache_read_input_tokens?: number | null; + readonly input_tokens?: number | null | undefined; + readonly cache_creation_input_tokens?: number | null | undefined; + readonly cache_read_input_tokens?: number | null | undefined; }): number { return ( - usage.input_tokens + - (usage.cache_creation_input_tokens ?? 0) + - (usage.cache_read_input_tokens ?? 0) + (optionalClaudeUsageTokenCount(usage.input_tokens) ?? 0) + + (optionalClaudeUsageTokenCount(usage.cache_creation_input_tokens) ?? 0) + + (optionalClaudeUsageTokenCount(usage.cache_read_input_tokens) ?? 0) ); } export function claudeProviderTurnTokenUsage( usage: { - readonly input_tokens: number; - readonly cache_creation_input_tokens?: number | null; - readonly cache_read_input_tokens?: number | null; - readonly cache_creation?: ClaudeCacheCreation | null; - readonly output_tokens: number; + readonly input_tokens?: number | null | undefined; + readonly cache_creation_input_tokens?: number | null | undefined; + readonly cache_read_input_tokens?: number | null | undefined; + readonly cache_creation?: ClaudeCacheCreation | null | undefined; + readonly output_tokens?: number | null | undefined; }, maxTokens: number | null, updatedAt: string, @@ -316,7 +322,8 @@ export function claudeProviderTurnTokenUsage( requestedAt?: DateTime.Utc, ) { const inputTokens = claudeMessageInputTokens(usage); - const outputTokens = usage.output_tokens; + const outputTokens = optionalClaudeUsageTokenCount(usage.output_tokens) ?? 0; + const cachedInputTokens = optionalClaudeUsageTokenCount(usage.cache_read_input_tokens) ?? 0; const promptCacheTtlMs = claudePromptCacheTtlMs(usage.cache_creation); // The cache lifetime starts with the request, not when its response ends. const promptCacheExpiresAt = @@ -327,7 +334,7 @@ export function claudeProviderTurnTokenUsage( usedTokens: inputTokens + outputTokens, maxTokens, inputTokens, - cachedInputTokens: usage.cache_read_input_tokens ?? 0, + cachedInputTokens, outputTokens, reasoningOutputTokens: 0, ...(promptCacheTtlMs === undefined ? {} : { promptCacheTtlMs }), @@ -343,20 +350,30 @@ type ClaudeMessageUsage = Parameters[0]; function mergeClaudeStreamUsage( current: ClaudeMessageUsage, delta: { - readonly input_tokens?: number | null; - readonly cache_creation_input_tokens?: number | null; - readonly cache_read_input_tokens?: number | null; - readonly output_tokens: number; + readonly input_tokens?: number | null | undefined; + readonly cache_creation_input_tokens?: number | null | undefined; + readonly cache_read_input_tokens?: number | null | undefined; + readonly output_tokens?: number | null | undefined; }, ): ClaudeMessageUsage { return { ...current, - input_tokens: delta.input_tokens ?? current.input_tokens, + input_tokens: + optionalClaudeUsageTokenCount(delta.input_tokens) ?? + optionalClaudeUsageTokenCount(current.input_tokens) ?? + 0, cache_creation_input_tokens: - delta.cache_creation_input_tokens ?? current.cache_creation_input_tokens ?? null, + optionalClaudeUsageTokenCount(delta.cache_creation_input_tokens) ?? + optionalClaudeUsageTokenCount(current.cache_creation_input_tokens) ?? + null, cache_read_input_tokens: - delta.cache_read_input_tokens ?? current.cache_read_input_tokens ?? null, - output_tokens: delta.output_tokens, + optionalClaudeUsageTokenCount(delta.cache_read_input_tokens) ?? + optionalClaudeUsageTokenCount(current.cache_read_input_tokens) ?? + null, + output_tokens: + optionalClaudeUsageTokenCount(delta.output_tokens) ?? + optionalClaudeUsageTokenCount(current.output_tokens) ?? + 0, }; } export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_PROVIDER); @@ -7117,13 +7134,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId: string, options?: { readonly status?: OrchestrationV2ProviderThread["status"]; + /** The process exited on its own, taking work whose outcome had not reached the agent. */ + readonly exitedUnexpectedly?: boolean; }, ) { - const hadRoster = - rosterForNativeThread( - yield* Ref.get(pendingBackgroundTasksByNativeThread), - nativeThreadId, - ).size > 0; + const roster = rosterForNativeThread( + yield* Ref.get(pendingBackgroundTasksByNativeThread), + nativeThreadId, + ); + const hadRoster = roster.size > 0; const remembered = (yield* Ref.get(lastProviderThreadByNativeThread)).get(nativeThreadId); const hadPersistedRoster = (remembered?.pendingBackgroundTasks?.length ?? 0) > 0; const priorOpaqueTombstones = taskIdSetForNativeThread( @@ -7142,6 +7161,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const preservedOpaqueTombstones = [...priorOpaqueTombstones].filter((taskId) => bufferedTaskNotificationIds.has(taskId), ); + // Idle outcomes reach Claude only through a wake; a requested one still delivers its buffer. + const wakeRequested = (yield* Ref.get(requestedContinuations)).has(nativeThreadId); + const lostBackgroundTasks = + options?.exitedUnexpectedly === true + ? [ + ...claudePendingBackgroundTasksFromRoster( + roster, + taskIdSetForNativeThread( + yield* Ref.get(awaitedBackgroundTasksByNativeThread), + nativeThreadId, + ), + ), + ...(yield* owedWakeTasksForNativeThread(nativeThreadId)), + ].filter((task) => !(wakeRequested && bufferedTaskNotificationIds.has(task.taskId))) + : []; scheduledWakeupsByNativeThread.delete(nativeThreadId); possibleEarlyWakeNativeThreads.delete(nativeThreadId); yield* clearPendingBackgroundTasksForNativeThread(nativeThreadId); @@ -7160,10 +7194,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( preservedOpaqueTombstones, ); } - if (!hadRoster && !hadPersistedRoster) { + if (remembered === undefined) { return; } - if (remembered === undefined) { + if (lostBackgroundTasks.length > 0 && remembered.appThreadId !== null) { + yield* emitProviderEvent({ + type: "background_work.lost", + driver: CLAUDE_PROVIDER, + threadId: remembered.appThreadId, + providerThreadId: remembered.id, + tasks: lostBackgroundTasks, + }); + } + if (!hadRoster && !hadPersistedRoster) { return; } const activeContext = yield* Ref.get(activeTurn); @@ -10051,7 +10094,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), }); } else { - yield* resetBackgroundTaskStateForNativeThreadProcess(closedQuery.nativeThreadId); + yield* resetBackgroundTaskStateForNativeThreadProcess(closedQuery.nativeThreadId, { + exitedUnexpectedly: !interrupted, + }); } // Preserve buffered outcomes before Stop clears the wake buffer. yield* endSubagentsOfClosedQuery({ @@ -11025,14 +11070,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( reasoning.messageId = event.message.id; reasoning.streamBlocks.clear(); context.assistant.streamBlocks.clear(); - const usage: ClaudeMessageUsage | undefined = event.message.usage; - context.streamUsage = - usage === undefined ? null : { messageId: event.message.id, usage }; - if (usage !== undefined) yield* emitContextUsage(context, usage, true); + const usage: ClaudeMessageUsage = event.message.usage ?? {}; + context.streamUsage = { messageId: event.message.id, usage }; + yield* emitContextUsage(context, usage, true); } else if (event.type === "message_delta") { - const usage: typeof event.usage | undefined = event.usage; + const usage: typeof event.usage | null | undefined = event.usage; const stream = context.streamUsage; - if (stream?.usage && usage !== undefined) { + if (stream?.usage && usage != null) { stream.usage = mergeClaudeStreamUsage(stream.usage, usage); yield* emitContextUsage(context, stream.usage); } @@ -11499,7 +11543,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // CLI-generated frames report zero usage, not context usage. if ( message.parent_tool_use_id === null && - message.message.usage !== undefined && + message.message.usage != null && message.message.model !== "" ) { const snapshotUsage = message.message.usage; @@ -11514,7 +11558,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { stream.usage = { ...snapshotUsage, - output_tokens: Math.max(snapshotUsage.output_tokens, stream.usage.output_tokens), + output_tokens: Math.max( + optionalClaudeUsageTokenCount(snapshotUsage.output_tokens) ?? 0, + optionalClaudeUsageTokenCount(stream.usage.output_tokens) ?? 0, + ), }; yield* emitContextUsage(context, stream.usage); } @@ -13232,6 +13279,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const closedExistingNativeThreadId = existing !== null ? existing.nativeThreadId : null; clearedNativeSessions.delete(nativeThreadId); if (existing !== null) { + existing.stopping = true; yield* existing.query.close.pipe(Effect.ignore); if (existing.nativeThreadId !== nativeThreadId) { yield* clearWakeStateForNativeThread(existing.nativeThreadId); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index cd5e51a32f616..d30748a0df77c 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1235,6 +1235,7 @@ describe("CodexAdapterV2 session initialize", () => { runtimePolicy: CODEX_TEST_RUNTIME_POLICY, }), initializeRequests: () => initializeRequests, + runtime, events: runtime.events, }; }); @@ -1531,6 +1532,179 @@ describe("CodexAdapterV2 session initialize", () => { ), ), ); + + // The no-op notification lands right after the request is written, so the + // test advances the clock only once the app-server is known to be silent. + const requestWritten: CodexReplay.CodexAppServerReplayEntry = { + type: "emit_inbound", + label: "request-written", + frame: { method: "t3/test/requestWritten", params: {} }, + }; + const awaitRequestWritten = + (written: Deferred.Deferred) => + ( + entry: Parameters< + NonNullable + >[0], + ) => + entry.label === "request-written" ? Deferred.succeed(written, undefined) : Effect.void; + const UNANSWERED_REQUEST_BUDGET = "5 minutes"; + // ProviderTurnStartService skips retries and fresh-thread fallback on this tag. + const failedOnDeadline = (exit: Exit.Exit): boolean => { + if (!Exit.isFailure(exit)) return false; + let error: unknown = Cause.squash(exit.cause); + while (Predicate.hasProperty(error, "cause")) { + if (Predicate.isTagged(error, "CodexAppServerUnresponsiveError")) return true; + error = error.cause; + } + return Predicate.isTagged(error, "CodexAppServerUnresponsiveError"); + }; + + // regression: #24300 a wedged shared app-server left thread/start pending and stayed ready + it.effect("fails and retires a shared app-server that never answers thread/start", () => + Effect.gen(function* () { + const written = yield* Deferred.make(); + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: "thread-start-unanswered", + entries: [...replayPreamble("thread-start-unanswered").slice(0, 4), requestWritten], + }), + awaitRequestWritten(written), + ); + const events = yield* session.runtime.events.pipe( + Stream.runDrain, + Effect.exit, + Effect.timeoutOption(UNANSWERED_REQUEST_BUDGET), + Effect.forkChild({ startImmediately: true }), + ); + const ensured = yield* session + .ensureThread("thread-start-unanswered") + .pipe( + Effect.exit, + Effect.timeoutOption(UNANSWERED_REQUEST_BUDGET), + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.await(written); + yield* TestClock.adjust(UNANSWERED_REQUEST_BUDGET); + + const settled = yield* Fiber.join(ensured); + assert.isTrue( + Option.isSome(settled) && failedOnDeadline(settled.value), + `ensureThread did not fail on the deadline within ${UNANSWERED_REQUEST_BUDGET} of an unanswered thread/start`, + ); + const retired = yield* Fiber.join(events); + assert.isTrue( + Option.isSome(retired) && Exit.isFailure(retired.value), + "session events did not fail after thread/start passed its deadline", + ); + const refused = yield* Effect.exit(session.ensureThread("thread-start-after-retire")); + const refusal = Exit.isFailure(refused) ? Cause.squash(refused.cause) : undefined; + assert.isTrue( + Predicate.hasProperty(refusal, "cause") && + Predicate.isTagged(refusal.cause, "CodexAppServerRetiredError"), + "a retired app-server accepted a new thread", + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + const turnPreamble = codexReplayPreamble({ + nativeThreadId: "turn-start-unanswered", + nativeTurnId: "turn-unanswered", + prompt: "Hello", + }); + // regression: #24300 a stopped shared app-server left a loaded thread's next turn pending forever + it.effect.each([ + { + method: "config/read", + entries: [ + ...turnPreamble.slice(0, 5), + { + type: "expect_outbound", + label: "thread/name/set", + frame: { + id: 3, + method: "thread/name/set", + params: { threadId: "turn-start-unanswered", name: CODEX_TEST_THREAD_TITLE }, + }, + } satisfies CodexReplay.CodexAppServerReplayEntry, + { + type: "emit_inbound", + label: "thread/name/set", + frame: { id: 3, result: {} }, + } satisfies CodexReplay.CodexAppServerReplayEntry, + { + type: "expect_outbound", + label: "config/read", + frame: { + id: 4, + method: "config/read", + params: { cwd: "/workspace", includeLayers: false }, + }, + } satisfies CodexReplay.CodexAppServerReplayEntry, + ], + }, + { method: "turn/start", entries: turnPreamble.slice(0, 6) }, + ])("fails a turn whose $method the shared app-server never answers", ({ entries }) => + Effect.gen(function* () { + const written = yield* Deferred.make(); + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: "turn-start-unanswered", + entries: [...entries, requestWritten], + }), + awaitRequestWritten(written), + ); + const threadId = ThreadId.make("thread-turn-start-unanswered"); + const providerThread = yield* session.ensureThread(threadId); + + const outcome = yield* session.runtime + .startTurn( + makeCodexTestTurnInput({ + threadId, + providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("turn-start-unanswered-attempt"), + text: "Hello", + }), + ) + .pipe( + Effect.exit, + Effect.timeoutOption(UNANSWERED_REQUEST_BUDGET), + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.await(written); + yield* TestClock.adjust(UNANSWERED_REQUEST_BUDGET); + const settled = yield* Fiber.join(outcome); + + assert.isTrue( + Option.isSome(settled), + `startTurn was still waiting after ${UNANSWERED_REQUEST_BUDGET}`, + ); + if (Option.isSome(settled)) { + assert.isTrue(failedOnDeadline(settled.value), "startTurn did not fail on the deadline"); + } + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); }); describe("CodexAdapterV2 post-settle continuation", () => { @@ -12635,6 +12809,28 @@ describe("CodexAdapterV2 post-settle continuation", () => { { operation: "delete", path: "/w/e.ts" }, { operation: "add", path: "/w/a.ts" }, ]); + assert.equal( + fileChanges[0]?.diffStr, + [ + 'diff --git "a//w/c.ts" "b//w/d.ts"', + '--- "a//w/c.ts"', + '+++ "b//w/d.ts"', + "@@", + 'diff --git "a//w/e.ts" "b//w/e.ts"', + '--- "a//w/e.ts"', + "+++ /dev/null", + "@@ -1,1 +0,0 @@", + "-gone", + "\\ No newline at end of file", + 'diff --git "a//w/a.ts" "b//w/a.ts"', + "--- /dev/null", + '+++ "b//w/a.ts"', + "@@ -0,0 +1,1 @@", + "+export {};", + "\\ No newline at end of file", + "", + ].join("\n"), + ); }).pipe( Effect.scoped, Effect.provide( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 09036b09e3f77..181ed17fd5c16 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -178,6 +178,35 @@ type CodexFileChangeKinds = Readonly< Record >; +// Diff parsers split at Git headers once one exists, so each file of a multi-file patch needs its own. +function codexMultiFilePatch( + changes: ReadonlyArray, +): string { + return changes + .map(({ path, kind, diff }) => { + const oldPath = path; + const newPath = (kind.type === "update" && kind.move_path) || path; + const git = `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${newPath}`)}\n`; + if (kind.type === "update" && diff.startsWith("diff --git ")) return diff; + if (kind.type === "update" && diff.startsWith("--- ")) return `${git}${diff}`; + let hunks = diff; + // Codex records added and deleted files as their raw contents. + if (kind.type !== "update") { + const lines = diff.split("\n"); + const hasFinalNewline = diff.endsWith("\n"); + if (hasFinalNewline) lines.pop(); + const added = kind.type === "add"; + const range = `1,${lines.length}`; + hunks = `@@ -${added ? "0,0" : range} +${added ? range : "0,0"} @@\n${lines.map((line) => `${added ? "+" : "-"}${line}`).join("\n")}\n${hasFinalNewline ? "" : "\\ No newline at end of file\n"}`; + } + const before = kind.type === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`); + const after = kind.type === "delete" ? "/dev/null" : JSON.stringify(`b/${newPath}`); + return `${git}--- ${before}\n+++ ${after}\n${hunks}`; + }) + .map((section) => (section.endsWith("\n") ? section : `${section}\n`)) + .join(""); +} + function codexFileChangeApprovalPrompt(input: { readonly reason?: string | null; readonly grantRoot?: string | null; @@ -541,6 +570,26 @@ function codexMcpToolOutput( // A hung MCP resource read must not hold run ingestion open. const MCP_APP_CAPTURE_TIMEOUT = "20 seconds"; +// Session setup and turn start requests answer promptly; silence this long means a wedged app-server. +const CODEX_APP_SERVER_REQUEST_DEADLINE = "2 minutes"; + +class CodexAppServerUnresponsiveError extends Schema.TaggedError()( + "CodexAppServerUnresponsiveError", + { method: Schema.String }, +) { + override get message() { + return `Codex app-server did not answer ${this.method} within ${CODEX_APP_SERVER_REQUEST_DEADLINE}.`; + } +} + +class CodexAppServerRetiredError extends Schema.TaggedError()( + "CodexAppServerRetiredError", + {}, +) { + override get message() { + return "Codex app-server was retired and accepts no new work."; + } +} function codexMcpAppResourceUri(item: CodexDynamicToolItem): string | undefined { if (item.type !== "mcpToolCall") return undefined; @@ -2140,6 +2189,39 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); // A failed open is discarded, so the next turn spawns the updated binary. if (adapterOptions.compatibility !== undefined) yield* ensureInitialized; + // Failing the event stream makes the session manager release this app-server. + // Queue.fail lets readers take items already buffered before they see the failure. + // Buffered events drain before the session manager drops this runtime; refuse work meanwhile. + let retired = false; + const retireAppServer = (cause: unknown) => + Effect.suspend(() => { + retired = true; + return Queue.fail( + events, + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: CODEX_PROVIDER, + providerSessionId: input.providerSessionId, + cause, + }), + ); + }); + const rejectIfRetired = Effect.suspend(() => + retired ? Effect.fail(new CodexAppServerRetiredError()) : Effect.void, + ); + yield* client.awaitTermination.pipe(Effect.catch(retireAppServer), Effect.forkScoped); + // The outcome of an unanswered request is unknown, so it fails rather than retries. + const withAppServerDeadline = + (method: string) => + (effect: Effect.Effect) => + effect.pipe( + Effect.timeoutOrElse({ + duration: CODEX_APP_SERVER_REQUEST_DEADLINE, + orElse: () => { + const error = new CodexAppServerUnresponsiveError({ method }); + return retireAppServer(error).pipe(Effect.andThen(Effect.fail(error))); + }, + }), + ); // Read per thread: a workspace's project config can add its own servers. const readStdioMcpServers = (cwd: string | null | undefined) => ensureInitialized.pipe( @@ -2155,6 +2237,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.as>([]), ), ), + withAppServerDeadline("config/read"), ); const now = yield* DateTime.now; const session = providerSession({ @@ -2164,21 +2247,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( model: input.modelSelection.model, now, }); - // Drain final notifications before the session manager retires the dead process. - // Queue.fail lets readers take items already buffered before they see the failure. - yield* client.awaitTermination.pipe( - Effect.catch((cause) => - Queue.fail( - events, - new ProviderAdapter.ProviderAdapterEventStreamError({ - driver: CODEX_PROVIDER, - providerSessionId: input.providerSessionId, - cause, - }), - ), - ), - Effect.forkScoped, - ); const rateLimitSnapshot = yield* Ref.make(undefined); const limitedTurnItems = yield* Ref.make( new Map>(), @@ -4246,7 +4314,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updatedAt, type: "file_change", fileName: firstChange.path, - diffStr: firstChange.diff, + diffStr: + item.changes.length > 1 ? codexMultiFilePatch(item.changes) : firstChange.diff, changes: item.changes.map((change) => { const movePath = change.kind.type === "update" ? change.kind.move_path : undefined; return movePath @@ -7677,6 +7746,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.catch(() => Effect.logDebug("Codex config read failed.").pipe(Effect.as(undefined)), ), + withAppServerDeadline("config/read"), ); const turnStartParams = yield* buildCodexTurnStartParams({ cyberAccess: codexCyberAccess(models, turnInput.modelSelection.model), @@ -7708,7 +7778,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(yield* Ref.get(settledTurns)), ...(yield* Ref.get(activeTurns)), ]); - const started = yield* client.request("turn/start", turnStartParams); + const started = yield* client + .request("turn/start", turnStartParams) + .pipe(withAppServerDeadline("turn/start")); const previousTurn = previousTurns.get(started.turn.id) ?? (yield* Ref.get(activeTurns)).get(started.turn.id); @@ -7798,6 +7870,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, command: OrchestrationV2GoalCommand, ) { + yield* rejectIfRetired; if (command.type === "set") yield* validateCodexGoalObjective(command.objective); const threadId = yield* getNativeThreadId(turnInput.providerThread); rootProviderThreads.set(threadId, turnInput.providerThread); @@ -8075,7 +8148,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( return false; }), ensureThread: (threadInput) => - ensureInitialized.pipe( + rejectIfRetired.pipe( + Effect.andThen(ensureInitialized), Effect.andThen( Effect.all([ mcpSessions.read(threadInput.threadId), @@ -8107,6 +8181,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( thread: response.thread, }), ), + withAppServerDeadline("thread/start"), Effect.mapError( (cause) => new ProviderAdapter.ProviderAdapterEnsureThreadError({ @@ -8118,6 +8193,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), resumeThread: Effect.fn("CodexAdapterV2.resumeThread")( function* (threadInput) { + yield* rejectIfRetired; const nativeThreadId = yield* getNativeThreadId(threadInput.providerThread); const appThreadId = threadInput.threadId ?? threadInput.providerThread.appThreadId; const resume = resumeNativeThread(nativeThreadId, { @@ -8140,6 +8216,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( goalUpdatesHeld.add(nativeThreadId); const response = yield* ensureInitialized.pipe( Effect.andThen(resume), + withAppServerDeadline("thread/resume"), Effect.flatMap(decodeCodexResumeMetadata), // Stay registered: a lost or undecodable response may still have resumed the thread. Effect.onError(() => @@ -8252,6 +8329,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (goalCommand !== null) return runGoalCommand(turnInput, goalCommand); const nativeThreadId = turnInput.providerThread.nativeThreadRef?.nativeId; return Effect.gen(function* () { + yield* rejectIfRetired; if ( !continuation && nativeThreadId != null && diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 88563aeb43492..0e4bc5d088048 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -3653,6 +3653,8 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), out("session.command", { sessionID: SESSION, name: "git/hello", text: "WORLD" }), reply("session.command", null), + out("session.active"), + replyData("session.active", { [SESSION]: { type: "running" } }), { type: "runtime_exit", status: "success" } as const, out("event.subscribe"), out("session.active"), @@ -3701,6 +3703,83 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect("finishes a workspace command that never starts an execution", () => + Effect.gen(function* () { + // A plugin command whose handler skips the model returns 204 and emits no execution events. + const { runtime, thread } = yield* resumed([ + out("command.list", ""), + reply("command.list", { location: { directory: WORK }, data: [{ name: "noop" }] }), + out("message.list", { sessionID: SESSION, order: "desc", limit: "1" }), + reply("message.list", { + data: [ + { id: "msg_idle_before", time: { created: 1 }, type: "idle", outcome: "succeeded" }, + ], + cursor: {}, + }), + out("session.command", { sessionID: SESSION, name: "noop", text: "" }), + reply("session.command", null), + out("session.active"), + replyData("session.active", {}), + out("message.list", { sessionID: SESSION, order: "desc", limit: "1" }), + reply("message.list", { + data: [ + { id: "msg_idle_before", time: { created: 1 }, type: "idle", outcome: "succeeded" }, + ], + cursor: {}, + }), + ]); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + yield* runtime.startTurn({ + ...turnInput(thread), + message: { ...turnInput(thread).message, text: "/noop" }, + }); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); + }).pipe(Effect.scoped), + ); + + it.effect("ends a command from execution events that arrive after its reply", () => + Effect.gen(function* () { + const offers: Array = []; + const { runtime, thread } = yield* resumed([ + out("command.list", ""), + reply("command.list", { location: { directory: WORK }, data: [{ name: "quick" }] }), + out("message.list", { sessionID: SESSION, order: "desc", limit: "1" }), + reply("message.list", { data: [], cursor: {} }), + out("session.command", { sessionID: SESSION, name: "quick", text: "" }), + reply("session.command", null), + // The execution already ended, but its events trail the HTTP replies. + out("session.active"), + replyData("session.active", {}), + out("message.list", { sessionID: SESSION, order: "desc", limit: "1" }), + reply("message.list", { + data: [ + { id: "msg_idle_quick", time: { created: 2 }, type: "idle", outcome: "failed" }, + { id: "msg_user_quick", time: { created: 1 }, text: "Answer quickly", type: "user" }, + ], + cursor: {}, + }), + event("session.execution.started", { sessionID: SESSION }), + event("session.execution.failed", { + sessionID: SESSION, + error: { type: "provider", message: "The model failed." }, + }), + ]).pipe( + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, { + offer: (request) => Effect.sync(() => void offers.push(request)), + take: Effect.never, + }), + ); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + yield* runtime.startTurn({ + ...turnInput(thread), + message: { ...turnInput(thread).message, text: "/quick" }, + }); + assert.equal((yield* Fiber.join(terminal))?.status, "failed"); + assert.lengthOf(offers, 0); + assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread)); + }).pipe(Effect.scoped), + ); + it.effect("sends a $skill that appears once OpenCode finishes scanning the directory", () => Effect.gen(function* () { const prompts: Array = []; @@ -8235,6 +8314,8 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { reply("message.list", { data: [], cursor: {} }), out("session.command", { sessionID: SESSION, name: "goal", text: control }), reply("session.command", null), + out("session.active"), + replyData("session.active", { [SESSION]: { type: "running" } }), event("session.text.ended", { sessionID: SESSION, assistantMessageID: "msg_legacy_goal", @@ -8346,6 +8427,8 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { reply("message.list", { data: [], cursor: {} }), out("session.command", { sessionID: SESSION, name: "goal", text: "Write proof.txt" }), reply("session.command", null), + out("session.active"), + replyData("session.active", { [SESSION]: { type: "running" } }), event("rpc.opencode.goal.changed", { sessionID: SESSION, goal: nativeGoal("active") }), event("session.execution.succeeded", { sessionID: SESSION }), out("rpc.call", ""), diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index af276de7ff276..cc570a9ef113d 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -37,10 +37,12 @@ import * as CheckpointCaptureService from "./CheckpointCaptureService.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; import * as WorkspaceFolders from "../workspace/WorkspaceFolders.ts"; const layerProjectionStoreTest = Layer.mergeAll( + ThreadCommandExecutor.layer, ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)), SqlitePersistence.layerMemory, ); @@ -311,6 +313,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { ), ) : Layer.mock(CheckpointService.CheckpointServiceV2)({ + capturesSoFar: () => Effect.succeed(0), repositoryScopes: () => Effect.succeed([]), materializeBaselineCheckpoint: () => Effect.die( @@ -696,265 +699,290 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { }), ); - it.effect("records the checkpoint of a cancelled run and keeps it cancelled", () => - Effect.gen(function* () { - const projectionStore = yield* ProjectionStore.ProjectionStoreV2; - const now = yield* DateTime.now; - const cancelledAt = DateTime.add(now, { seconds: 1 }); - const cancelledThreadId = ThreadId.make("thread:checkpoint-capture-cancelled"); - const cancelledRunId = RunId.make("run:checkpoint-capture-cancelled"); - const cancelledScopeId = CheckpointScopeId.make("scope:checkpoint-capture-cancelled"); - const cancelledRootNodeId = NodeId.make("node:checkpoint-capture-cancelled-root"); - const cancelledProviderThreadId = ProviderThreadId.make( - "provider-thread:checkpoint-capture-cancelled", - ); - yield* projectionStore.apply({ - id: EventId.make("event:checkpoint-capture-cancelled:thread"), - type: "thread.created", - threadId: cancelledThreadId, - occurredAt: now, - payload: { - createdBy: "user", - creationSource: "web", - id: cancelledThreadId, - projectId, - title: "Checkpoint capture after cancel", - providerInstanceId, - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - activeProviderThreadId: null, - lineage: { - parentThreadId: null, - relationshipToParent: null, - rootThreadId: cancelledThreadId, + it.effect.each([false, true])( + "records the checkpoint and keeps a run cancelled, cancelled during capture=%s", + (cancelDuringCapture) => + Effect.gen(function* () { + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor; + const now = yield* DateTime.now; + const cancelledAt = DateTime.add(now, { seconds: 1 }); + const cancelledThreadId = ThreadId.make("thread:checkpoint-capture-cancelled"); + const cancelledRunId = RunId.make("run:checkpoint-capture-cancelled"); + const cancelledScopeId = CheckpointScopeId.make("scope:checkpoint-capture-cancelled"); + const cancelledRootNodeId = NodeId.make("node:checkpoint-capture-cancelled-root"); + const cancelledProviderThreadId = ProviderThreadId.make( + "provider-thread:checkpoint-capture-cancelled", + ); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-cancelled:thread"), + type: "thread.created", + threadId: cancelledThreadId, + occurredAt: now, + payload: { + createdBy: "user", + creationSource: "web", + id: cancelledThreadId, + projectId, + title: "Checkpoint capture after cancel", + providerInstanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: cancelledThreadId, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, }, - forkedFrom: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - lastVisitedAt: null, - deletedAt: null, - }, - }); - const runningRun: OrchestrationV2Run = { - id: cancelledRunId, - threadId: cancelledThreadId, - ordinal: 1, - providerInstanceId, - modelSelection, - providerThreadId: cancelledProviderThreadId, - userMessageId: MessageId.make("message:checkpoint-capture-cancelled"), - rootNodeId: cancelledRootNodeId, - activeAttemptId: null, - status: "running", - requestedAt: now, - startedAt: now, - completedAt: null, - checkpointId: null, - contextHandoffId: null, - }; - const runningRootNode = { - id: cancelledRootNodeId, - threadId: cancelledThreadId, - runId: cancelledRunId, - parentNodeId: null, - rootNodeId: cancelledRootNodeId, - kind: "root_turn" as const, - status: "running" as const, - countsForRun: true, - providerThreadId: cancelledProviderThreadId, - providerTurnId: null, - nativeItemRef: null, - runtimeRequestId: null, - checkpointScopeId: cancelledScopeId, - startedAt: now, - completedAt: null, - }; - const scope = { - id: cancelledScopeId, - threadId: cancelledThreadId, - runId: cancelledRunId, - nodeId: cancelledRootNodeId, - parentScopeId: null, - providerThreadId: cancelledProviderThreadId, - kind: "root_run" as const, - ordinalWithinParent: 0, - advancesAppRunCount: true, - cwd: "/repo", - createdAt: now, - }; - yield* projectionStore.apply({ - id: EventId.make("event:checkpoint-capture-cancelled:provider-thread"), - type: "provider-thread.updated", - threadId: cancelledThreadId, - nodeId: cancelledRootNodeId, - driver, - providerInstanceId, - occurredAt: now, - payload: { - id: cancelledProviderThreadId, - driver, + }); + const runningRun: OrchestrationV2Run = { + id: cancelledRunId, + threadId: cancelledThreadId, + ordinal: 1, providerInstanceId, - providerSessionId: null, - appThreadId: cancelledThreadId, - ownerNodeId: cancelledRootNodeId, - nativeThreadRef: null, - nativeConversationHeadRef: null, - status: "idle", - firstRunOrdinal: 1, - lastRunOrdinal: 1, - handoffIds: [], - forkedFrom: null, - createdAt: now, - updatedAt: now, - }, - }); - yield* projectionStore.apply({ - id: EventId.make("event:checkpoint-capture-cancelled:scope"), - type: "checkpoint-scope.created", - threadId: cancelledThreadId, - runId: cancelledRunId, - nodeId: cancelledRootNodeId, - occurredAt: now, - payload: scope, - }); - yield* projectionStore.apply({ - id: EventId.make("event:checkpoint-capture-cancelled:baseline"), - type: "checkpoint.captured", - threadId: cancelledThreadId, - nodeId: cancelledRootNodeId, - driver, - providerInstanceId, - occurredAt: now, - payload: { - id: CheckpointId.make("checkpoint:cancelled-baseline-0"), + modelSelection, + providerThreadId: cancelledProviderThreadId, + userMessageId: MessageId.make("message:checkpoint-capture-cancelled"), + rootNodeId: cancelledRootNodeId, + activeAttemptId: null, + status: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }; + const runningRootNode = { + id: cancelledRootNodeId, threadId: cancelledThreadId, - scopeId: cancelledScopeId, - runId: null, + runId: cancelledRunId, + parentNodeId: null, + rootNodeId: cancelledRootNodeId, + kind: "root_turn" as const, + status: "running" as const, + countsForRun: true, + providerThreadId: cancelledProviderThreadId, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: cancelledScopeId, + startedAt: now, + completedAt: null, + }; + const scope = { + id: cancelledScopeId, + threadId: cancelledThreadId, + runId: cancelledRunId, nodeId: cancelledRootNodeId, - parentCheckpointId: null, - ordinalWithinScope: 0, - appRunOrdinal: null, - ref: CheckpointRef.make("checkpoint-ref:cancelled-baseline-0"), - status: "ready", - files: [], - capturedAt: now, - }, - }); - for (const [status, completedAt] of [ - ["running", null], - ["cancelled", cancelledAt], - ] as const) { + parentScopeId: null, + providerThreadId: cancelledProviderThreadId, + kind: "root_run" as const, + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: "/repo", + createdAt: now, + }; yield* projectionStore.apply({ - id: EventId.make(`event:checkpoint-capture-cancelled:run-${status}`), - type: "run.updated", + id: EventId.make("event:checkpoint-capture-cancelled:provider-thread"), + type: "provider-thread.updated", threadId: cancelledThreadId, - runId: cancelledRunId, nodeId: cancelledRootNodeId, + driver, providerInstanceId, - occurredAt: completedAt ?? now, - payload: { ...runningRun, status, completedAt }, + occurredAt: now, + payload: { + id: cancelledProviderThreadId, + driver, + providerInstanceId, + providerSessionId: null, + appThreadId: cancelledThreadId, + ownerNodeId: cancelledRootNodeId, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }, }); yield* projectionStore.apply({ - id: EventId.make(`event:checkpoint-capture-cancelled:node-${status}`), - type: "node.updated", + id: EventId.make("event:checkpoint-capture-cancelled:scope"), + type: "checkpoint-scope.created", threadId: cancelledThreadId, runId: cancelledRunId, nodeId: cancelledRootNodeId, + occurredAt: now, + payload: scope, + }); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-cancelled:baseline"), + type: "checkpoint.captured", + threadId: cancelledThreadId, + nodeId: cancelledRootNodeId, + driver, providerInstanceId, - occurredAt: completedAt ?? now, - payload: { ...runningRootNode, status, completedAt }, + occurredAt: now, + payload: { + id: CheckpointId.make("checkpoint:cancelled-baseline-0"), + threadId: cancelledThreadId, + scopeId: cancelledScopeId, + runId: null, + nodeId: cancelledRootNodeId, + parentCheckpointId: null, + ordinalWithinScope: 0, + appRunOrdinal: null, + ref: CheckpointRef.make("checkpoint-ref:cancelled-baseline-0"), + status: "ready", + files: [], + capturedAt: now, + }, }); - } + const applyStatus = (status: "waiting" | "cancelled", completedAt: DateTime.Utc | null) => + Effect.gen(function* () { + yield* projectionStore.apply({ + id: EventId.make(`event:checkpoint-capture-cancelled:run-${status}`), + type: "run.updated", + threadId: cancelledThreadId, + runId: cancelledRunId, + nodeId: cancelledRootNodeId, + providerInstanceId, + occurredAt: completedAt ?? now, + payload: { ...runningRun, status, completedAt }, + }); + yield* projectionStore.apply({ + id: EventId.make(`event:checkpoint-capture-cancelled:node-${status}`), + type: "node.updated", + threadId: cancelledThreadId, + runId: cancelledRunId, + nodeId: cancelledRootNodeId, + providerInstanceId, + occurredAt: completedAt ?? now, + payload: { ...runningRootNode, status, completedAt }, + }); + }).pipe((effect) => threadCommands.withLock(cancelledThreadId, effect)); + yield* applyStatus("waiting", null); + if (!cancelDuringCapture) yield* applyStatus("cancelled", cancelledAt); - const captured = { - id: CheckpointId.make("checkpoint:cancelled-captured-1"), - threadId: cancelledThreadId, - scopeId: cancelledScopeId, - runId: cancelledRunId, - nodeId: cancelledRootNodeId, - parentCheckpointId: CheckpointId.make("checkpoint:cancelled-baseline-0"), - ordinalWithinScope: 1, - appRunOrdinal: 1, - ref: CheckpointRef.make("checkpoint-ref:cancelled-captured-1"), - status: "ready" as const, - files: [], - capturedAt: cancelledAt, - }; - const commits = yield* Ref.make(0); - const layerCapture = CheckpointCaptureService.layer.pipe( - Layer.provide( - Layer.mergeAll( - IdAllocator.layer, - Layer.mock(CheckpointService.CheckpointServiceV2)({ - repositoryScopes: () => Effect.succeed([]), - materializeBaselineCheckpoint: () => - Effect.die("baseline materialization must be skipped when ordinal 0 is ready"), - capture: () => Effect.succeed(captured), - }), - Layer.mock(EventSink.EventSinkV2)({ - commitCommand: (input) => - Effect.forEach(input.events, (event) => projectionStore.apply(event)).pipe( - Effect.andThen(Ref.update(commits, (count) => count + 1)), - Effect.as({ committed: true } as never), - Effect.orDie, - ), - }), + const captured = { + id: CheckpointId.make("checkpoint:cancelled-captured-1"), + threadId: cancelledThreadId, + scopeId: cancelledScopeId, + runId: cancelledRunId, + nodeId: cancelledRootNodeId, + parentCheckpointId: CheckpointId.make("checkpoint:cancelled-baseline-0"), + ordinalWithinScope: 1, + appRunOrdinal: 1, + ref: CheckpointRef.make("checkpoint-ref:cancelled-captured-1"), + status: "ready" as const, + files: [], + capturedAt: cancelledAt, + }; + const commits = yield* Ref.make(0); + const layerCapture = CheckpointCaptureService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + Layer.mock(CheckpointService.CheckpointServiceV2)({ + capturesSoFar: () => Effect.succeed(0), + repositoryScopes: () => Effect.succeed([]), + materializeBaselineCheckpoint: () => + Effect.die("baseline materialization must be skipped when ordinal 0 is ready"), + capture: () => + (cancelDuringCapture ? applyStatus("cancelled", cancelledAt) : Effect.void).pipe( + Effect.as(captured), + Effect.orDie, + ), + }), + Layer.mock(EventSink.EventSinkV2)({ + commitCommand: (input) => + Effect.forEach(input.events, (event) => projectionStore.apply(event)).pipe( + Effect.andThen(Ref.update(commits, (count) => count + 1)), + Effect.as({ committed: true } as never), + Effect.orDie, + ), + }), + ), ), - ), - ); + ); - yield* Effect.gen(function* () { - const service = yield* CheckpointCaptureService.CheckpointCaptureServiceV2; - yield* service.execute({ - threadId: cancelledThreadId, + yield* Effect.gen(function* () { + const service = yield* CheckpointCaptureService.CheckpointCaptureServiceV2; + yield* service.execute({ + threadId: cancelledThreadId, + runId: cancelledRunId, + scopeId: cancelledScopeId, + }); + yield* service.execute({ + threadId: cancelledThreadId, + runId: cancelledRunId, + scopeId: cancelledScopeId, + }); + }).pipe(Effect.provide(layerCapture)); + + assert.equal(yield* Ref.get(commits), 1); + const projected = yield* projectionStore.getCheckpointCaptureContext(cancelledThreadId, { runId: cancelledRunId, scopeId: cancelledScopeId, }); - yield* service.execute({ + assert.equal(projected.run?.status, "cancelled"); + assert.equal(projected.run?.checkpointId, captured.id); + const completedAt = projected.run?.completedAt; + assert.equal( + completedAt ? DateTime.formatIso(completedAt) : completedAt, + DateTime.formatIso(cancelledAt), + ); + assert.equal(projected.rootNode?.status, "cancelled"); + assert.deepEqual([...projected.preservedCheckpointOrdinals].toSorted(), [0, 1]); + + // A rewind leaves the run's checkpoint stale; the next capture must rebaseline it. + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-cancelled:captured-stale"), + type: "checkpoint.captured", threadId: cancelledThreadId, + runId: cancelledRunId, + nodeId: cancelledRootNodeId, + providerInstanceId, + occurredAt: cancelledAt, + payload: { ...captured, status: "stale" }, + }); + const afterRewind = yield* projectionStore.getCheckpointCaptureContext(cancelledThreadId, { runId: cancelledRunId, scopeId: cancelledScopeId, }); - }).pipe(Effect.provide(layerCapture)); + assert.deepEqual(afterRewind.preservedCheckpointOrdinals, [0]); - assert.equal(yield* Ref.get(commits), 1); - const projected = yield* projectionStore.getCheckpointCaptureContext(cancelledThreadId, { - runId: cancelledRunId, - scopeId: cancelledScopeId, - }); - assert.equal(projected.run?.status, "cancelled"); - assert.equal(projected.run?.checkpointId, captured.id); - const completedAt = projected.run?.completedAt; - assert.equal( - completedAt ? DateTime.formatIso(completedAt) : completedAt, - DateTime.formatIso(cancelledAt), - ); - assert.equal(projected.rootNode?.status, "cancelled"); - assert.deepEqual([...projected.preservedCheckpointOrdinals].toSorted(), [0, 1]); - - // A rewind leaves the run's checkpoint stale; the next capture must rebaseline it. - yield* projectionStore.apply({ - id: EventId.make("event:checkpoint-capture-cancelled:captured-stale"), - type: "checkpoint.captured", - threadId: cancelledThreadId, - runId: cancelledRunId, - nodeId: cancelledRootNodeId, - providerInstanceId, - occurredAt: cancelledAt, - payload: { ...captured, status: "stale" }, - }); - const afterRewind = yield* projectionStore.getCheckpointCaptureContext(cancelledThreadId, { - runId: cancelledRunId, - scopeId: cancelledScopeId, - }); - assert.deepEqual(afterRewind.preservedCheckpointOrdinals, [0]); - }), + // A failed capture still records which run ended there; the next capture must keep that link. + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-cancelled:captured-error"), + type: "checkpoint.captured", + threadId: cancelledThreadId, + runId: cancelledRunId, + nodeId: cancelledRootNodeId, + providerInstanceId, + occurredAt: cancelledAt, + payload: { ...captured, status: "error" }, + }); + const afterFailedCapture = yield* projectionStore.getCheckpointCaptureContext( + cancelledThreadId, + { runId: cancelledRunId, scopeId: cancelledScopeId }, + ); + assert.deepEqual([...afterFailedCapture.preservedCheckpointOrdinals].toSorted(), [0, 1]); + }), ); it.effect("completes a side chat run with a missing checkpoint and never touches git", () => diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index 119b5420be343..dd7f27079a4e5 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -21,6 +21,7 @@ import * as CheckpointService from "./CheckpointService.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; // Git processes are already capped server-wide; this keeps one thread from taking every slot. const REPOSITORY_CAPTURE_CONCURRENCY = 6; @@ -57,6 +58,7 @@ export const layer: Layer.Layer< | EventSink.EventSinkV2 | IdAllocator.IdAllocatorV2 | ProjectionStore.ProjectionStoreV2 + | ThreadCommandExecutor.ThreadCommandExecutor > = Layer.effect( CheckpointCaptureServiceV2, Effect.gen(function* () { @@ -64,6 +66,7 @@ export const layer: Layer.Layer< const eventSink = yield* EventSink.EventSinkV2; const ids = yield* IdAllocator.IdAllocatorV2; const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor; const execute = Effect.fn("orchestrationV2.checkpointCapture.execute")(function* (input: { readonly threadId: ThreadId; @@ -135,6 +138,8 @@ export const layer: Layer.Layer< }; // Each scope is checked on its own, so a retried capture fills only what is missing. const captureRoot = Effect.gen(function* () { + // Materializing a baseline waits on the folder's lock before the capture does. + const capturesBeforeLock = yield* checkpoints.capturesSoFar(scope.cwd); const threadStartCheckpoint = baselineOrdinalWithinScope === 0 || isPreserved(0) ? null : yield* materializeBaseline(0); const baselineCheckpoint = isPreserved(baselineOrdinalWithinScope) @@ -148,6 +153,7 @@ export const layer: Layer.Layer< appRunOrdinal: run.ordinal, capturedAt, forceMissing: sideChat, + capturesBeforeLock, ...excluded(scope), }); return { threadStartCheckpoint, baselineCheckpoint, checkpoint }; @@ -202,8 +208,6 @@ export const layer: Layer.Layer< ], { concurrency: 2 }, ); - // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run. - const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run; const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`); const checkpointEvent = (payload: OrchestrationV2Checkpoint) => Effect.map(ids.allocate.event({ threadId: input.threadId, commandId }), (id) => ({ @@ -239,110 +243,131 @@ export const layer: Layer.Layer< ]; }), ); - yield* eventSink.commitCommand({ - commandId, - threadId: input.threadId, - commandType: "checkpoint.capture", - acceptedAt: capturedAt, - effects: [], - events: [ - // Root records come last: a client that takes the latest ordinal-0 baseline gets the thread's. - ...repositoryEvents.flat(), - ...(threadStartCheckpoint === null - ? [] - : [ - { - id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), - type: "checkpoint.captured" as const, - threadId: input.threadId, - nodeId: threadStartCheckpoint.nodeId, - driver: providerThread.driver, - providerInstanceId: run.providerInstanceId, - occurredAt: capturedAt, - payload: threadStartCheckpoint, - }, - ]), - ...(baselineCheckpoint === null - ? [] - : [ - { - id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), - type: "checkpoint.captured" as const, - threadId: input.threadId, - nodeId: baselineCheckpoint.nodeId, - driver: providerThread.driver, - providerInstanceId: run.providerInstanceId, - occurredAt: capturedAt, - payload: baselineCheckpoint, - }, - ]), - { - id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), - type: "checkpoint.captured", - threadId: input.threadId, - runId: run.id, - nodeId: rootNode.id, - driver: providerThread.driver, - providerInstanceId: run.providerInstanceId, - occurredAt: capturedAt, - payload: checkpoint, - }, - { - id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), - type: "turn-item.updated", - threadId: input.threadId, - runId: run.id, - nodeId: rootNode.id, - driver: providerThread.driver, - providerInstanceId: run.providerInstanceId, - occurredAt: capturedAt, - payload: makeCheckpointTurnItem({ - idAllocator: ids, - run, - rootNode, - providerThread, - checkpoint, - completedAt: capturedAt, - }), - }, - { - id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), - type: "run.updated", + // Stop and deletion may commit while Git captures; reread under their lock before finalizing. + yield* threadCommands.withLock( + input.threadId, + Effect.gen(function* () { + const { runs } = yield* projections.getThreadRecords(input.threadId, ["runs"], { + runIds: [run.id], + }); + const currentRun = runs[0]; + if (currentRun === undefined || currentRun.activeAttemptId !== run.activeAttemptId) { + return; + } + const stoppedNow = + currentRun.status === "interrupted" || currentRun.status === "cancelled"; + if (currentRun.status !== "waiting" && !stoppedNow) { + return; + } + // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run. + const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = + currentRun; + yield* eventSink.commitCommand({ + commandId, threadId: input.threadId, - runId: run.id, - nodeId: rootNode.id, - providerInstanceId: run.providerInstanceId, - occurredAt: capturedAt, - payload: stopped - ? { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id } - : { - ...runWithoutDelegatedCompletion, - status: "completed", + commandType: "checkpoint.capture", + acceptedAt: capturedAt, + effects: [], + events: [ + // Root records come last: a client that takes the latest ordinal-0 baseline gets the thread's. + ...repositoryEvents.flat(), + ...(threadStartCheckpoint === null + ? [] + : [ + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "checkpoint.captured" as const, + threadId: input.threadId, + nodeId: threadStartCheckpoint.nodeId, + driver: providerThread.driver, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: threadStartCheckpoint, + }, + ]), + ...(baselineCheckpoint === null + ? [] + : [ + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "checkpoint.captured" as const, + threadId: input.threadId, + nodeId: baselineCheckpoint.nodeId, + driver: providerThread.driver, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: baselineCheckpoint, + }, + ]), + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "checkpoint.captured", + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + driver: providerThread.driver, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: checkpoint, + }, + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "turn-item.updated", + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + driver: providerThread.driver, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: makeCheckpointTurnItem({ + idAllocator: ids, + run, + rootNode, + providerThread, + checkpoint, completedAt: capturedAt, - checkpointId: checkpoint.id, - }, - }, - ...(stopped - ? [] - : [ - { - id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), - type: "node.updated" as const, - threadId: input.threadId, - runId: run.id, - nodeId: rootNode.id, - providerInstanceId: run.providerInstanceId, - occurredAt: capturedAt, - payload: { - ...rootNode, - status: "completed" as const, - completedAt: capturedAt, - checkpointScopeId: scope.id, - }, - }, - ]), - ], - }); + }), + }, + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "run.updated", + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: stoppedNow + ? { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id } + : { + ...runWithoutDelegatedCompletion, + status: "completed", + completedAt: capturedAt, + checkpointId: checkpoint.id, + }, + }, + ...(stoppedNow + ? [] + : [ + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "node.updated" as const, + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: { + ...rootNode, + status: "completed" as const, + completedAt: capturedAt, + checkpointScopeId: scope.id, + }, + }, + ]), + ], + }); + }), + ); }); return CheckpointCaptureServiceV2.of({ diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.taskFolder.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.taskFolder.test.ts index 851e7fb592450..529dea74dec91 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.taskFolder.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.taskFolder.test.ts @@ -152,7 +152,13 @@ const layerFor = (state: State, options: Options) => { IdAllocator.layer, CheckpointCaptureService.layer.pipe( Layer.provide( - Layer.mergeAll(layerCheckpoints, layerEventSink, IdAllocator.layer, layerProjections), + Layer.mergeAll( + layerCheckpoints, + layerEventSink, + IdAllocator.layer, + layerProjections, + ThreadCommandExecutor.layer, + ), ), ), CheckpointRollbackService.layer.pipe( diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index 2f41a9a379306..ff368dccb64d9 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -401,9 +401,14 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.effect.each([{ restoreFiles: true }, { restoreFiles: false }])( - "holds turn starts inside the worktree during rollback with restoreFiles $restoreFiles", - ({ restoreFiles }) => +it.effect.each([ + { restoreFiles: true, status: "ready" }, + { restoreFiles: false, status: "ready" }, + // A failed capture still pins the conversation. + { restoreFiles: false, status: "error" }, +])( + "holds turn starts inside the worktree during rollback with restoreFiles $restoreFiles to a $status checkpoint", + ({ restoreFiles, status }) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -438,7 +443,7 @@ it.effect.each([{ restoreFiles: true }, { restoreFiles: false }])( providerInstanceId, }, providerSession: undefined, - checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 }, + checkpoint: { id: checkpointId, scopeId, status, appRunOrdinal: 0 }, scope: { id: scopeId, cwd: worktreePath }, runsToRollback: [], targetAttempt: undefined, @@ -840,7 +845,7 @@ const seedRollbackHistory = Effect.gen(function* () { ), ), ); - const rollback = (ordinal: number) => + const rollback = (ordinal: number, restoreFiles?: boolean) => Effect.gen(function* () { const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2; yield* service.execute({ @@ -848,6 +853,7 @@ const seedRollbackHistory = Effect.gen(function* () { providerThreadId, scopeId, checkpointId: checkpointId(ordinal), + ...(restoreFiles === undefined ? {} : { restoreFiles }), }); }).pipe(Effect.provide(serviceLayer)); @@ -943,6 +949,21 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe }), ); + it.effect("rewinds the conversation to a run whose snapshot capture failed", () => + Effect.gen(function* () { + const history = yield* seedRollbackHistory; + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE orchestration_v2_projection_checkpoints + SET status = 'error', payload_json = json_set(payload_json, '$.status', 'error') + WHERE checkpoint_id = ${history.checkpointId(2)}`; + + yield* history.rollback(2, false); + + assert.deepEqual(history.rollbackCounts, [4]); + assert.deepEqual(history.restored, []); + }), + ); + it.effect( "rewinds stopped runs repeatedly without counting discarded provider turns again", () => diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index 6f9fe79cfde3b..8d6fd1c09441d 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -178,8 +178,10 @@ export const layer: Layer.Layer< // A repository's checkpoints follow the thread's; they are not a place to rewind to. typeof scope.repositoryPath === "string" || checkpoint.scopeId !== scope.id || - // Missing snapshots support conversation rewind, and restoring a task folder's repositories. + // Missing or failed snapshots support conversation rewind; missing ones also restoring a + // task folder's repositories. (checkpoint.status !== "ready" && + !(checkpoint.status === "error" && !restoreFiles) && !(checkpoint.status === "missing" && (!restoreFiles || linkedProjectFolder))) ) { return yield* invalidTarget(); diff --git a/apps/server/src/orchestration-v2/CheckpointService.test.ts b/apps/server/src/orchestration-v2/CheckpointService.test.ts index 8887d391da176..0433208167a73 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.test.ts @@ -21,6 +21,7 @@ import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as TestClock from "effect/testing/TestClock"; @@ -550,6 +551,156 @@ it.effect("backs off only baseline retries after repeated workspace capture time }), ); +it.effect("skips post-turn captures that waited out another capture's timeout in the folder", () => + Effect.gen(function* () { + const scopeFor = (name: string): OrchestrationV2CheckpointScope => ({ + id: CheckpointScopeId.make(`checkpoint-scope:shared-folder:${name}`), + threadId: ThreadId.make(`thread:shared-folder:${name}`), + runId: RunId.make(`run:shared-folder:${name}:1`), + nodeId: NodeId.make(`node:shared-folder:${name}:1`), + parentScopeId: null, + providerThreadId: ProviderThreadId.make(`provider-thread:shared-folder:${name}`), + kind: "root_run", + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: "/repo/shared", + createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"), + }); + const attempts = yield* Ref.make(0); + // Outcomes for upcoming attempts; an attempt with none scripted times out. + const script = yield* Ref.make>([]); + const started = yield* Queue.unbounded(); + const layerTest = CheckpointService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + layerNoTrackedFolders, + Layer.mock(CheckpointStore.CheckpointStore)({ + isGitRepository: () => Effect.succeed(true), + hasCheckpointRef: () => Effect.succeed(false), + resolveCleanHead: () => Effect.succeed(null), + captureCheckpoint: ({ cwd }) => + Effect.gen(function* () { + yield* Ref.update(attempts, (count) => count + 1); + yield* Queue.offer(started, undefined); + yield* Effect.sleep("30 seconds"); + const [next = "timeout", ...rest] = yield* Ref.get(script); + yield* Ref.set(script, rest); + if (next === "ready") return; + return yield* new VcsProcessTimeoutError({ + operation: "GitVcsDriver.checkpoints.captureCheckpoint", + command: "git", + cwd, + timeoutMs: 30_000, + }); + }), + }), + ), + ), + Layer.provideMerge(NodeCrypto.layer), + ); + yield* Effect.gen(function* () { + const checkpoints = yield* CheckpointService.CheckpointServiceV2; + const captureTurn = (scope: OrchestrationV2CheckpointScope) => + checkpoints + .capture({ + scope, + ordinalWithinScope: 1, + runId: scope.runId!, + nodeId: scope.nodeId!, + appRunOrdinal: 1, + capturedAt: scope.createdAt, + }) + .pipe(Effect.forkChild); + // A baseline's short budget running out says nothing about a post-turn capture. + const baseline = yield* checkpoints + .captureBaseline({ scope: scopeFor("baseline"), ordinalWithinScope: 0 }) + .pipe(Effect.result, Effect.forkChild); + yield* Queue.take(started); + const afterBaseline = yield* captureTurn(scopeFor("after-baseline")); + yield* TestClock.adjust("5 seconds"); + yield* Fiber.join(baseline); + yield* Queue.take(started); + yield* TestClock.adjust("30 seconds"); + assert.strictEqual((yield* Fiber.join(afterBaseline)).status, "error"); + assert.strictEqual(yield* Ref.get(attempts), 2); + + const first = yield* captureTurn(scopeFor("first")); + yield* Queue.take(started); + // Other threads in the same folder finish their turns while the first capture hangs. + const waiting = [ + yield* captureTurn(scopeFor("second")), + yield* captureTurn(scopeFor("third")), + ]; + const repository = scopeFor("repository"); + const repositoryWaiting = yield* checkpoints + .captureRepository({ + scope: repository, + runId: repository.runId!, + nodeId: repository.nodeId!, + ordinalWithinScope: 1, + capturedAt: repository.createdAt, + baselineCapturedAt: repository.createdAt, + baselineRecorded: true, + }) + .pipe(Effect.forkChild); + // A thread's root capture first materializes its baseline, which waits on the lock too. + const root = scopeFor("root"); + const rootWaiting = yield* Effect.gen(function* () { + const capturesBeforeLock = yield* checkpoints.capturesSoFar(root.cwd); + yield* checkpoints.materializeBaselineCheckpoint({ + scope: root, + ordinalWithinScope: 0, + nodeId: root.nodeId!, + capturedAt: root.createdAt, + }); + return yield* checkpoints.capture({ + scope: root, + ordinalWithinScope: 1, + runId: root.runId!, + nodeId: root.nodeId!, + appRunOrdinal: 1, + capturedAt: root.createdAt, + capturesBeforeLock, + }); + }).pipe(Effect.forkChild); + yield* TestClock.adjust("30 seconds"); + assert.strictEqual((yield* Fiber.join(first)).status, "error"); + // Room for every waiter to probe, so the count below is what fails without the fix. + yield* TestClock.adjust("120 seconds"); + for (const fiber of waiting) { + assert.strictEqual((yield* Fiber.join(fiber)).status, "error"); + } + const repositoryCaptured = yield* Fiber.join(repositoryWaiting); + assert.strictEqual(Option.getOrThrow(repositoryCaptured).checkpoint.status, "error"); + assert.strictEqual((yield* Fiber.join(rootWaiting)).status, "error"); + assert.strictEqual(yield* Ref.get(attempts), 3, "each waiter spent its own full timeout"); + + // A capture that starts after the timeout still probes for recovery. + const later = yield* captureTurn(scopeFor("later")); + yield* TestClock.adjust("30 seconds"); + assert.strictEqual((yield* Fiber.join(later)).status, "error"); + assert.strictEqual(yield* Ref.get(attempts), 4); + + // A success ahead in the queue does not hide a timeout that follows it. + yield* Ref.set(script, ["ready", "timeout"]); + const recovered = yield* captureTurn(scopeFor("recovered")); + const relapsed = yield* captureTurn(scopeFor("relapsed")); + const queuedBehind = yield* captureTurn(scopeFor("queued-behind")); + yield* TestClock.adjust("90 seconds"); + assert.deepEqual( + [ + (yield* Fiber.join(recovered)).status, + (yield* Fiber.join(relapsed)).status, + (yield* Fiber.join(queuedBehind)).status, + ], + ["ready", "error", "error"], + ); + assert.strictEqual(yield* Ref.get(attempts), 6, "the waiter probed after a later timeout"); + }).pipe(Effect.provide(layerTest)); + }), +); + it.effect("keeps the pre-rewind snapshot of a folder a failed rewind could not put back", () => { const targets = ["first", "second"].map((name) => ({ scope: { id: CheckpointScopeId.make(`checkpoint-scope:rewind:${name}`), cwd: `/repo/${name}` }, diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index d8a3da1f0c8ca..ec3e872d61c2b 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -220,7 +220,11 @@ export interface CheckpointServiceV2Shape { readonly capturedAt: DateTime.Utc; readonly forceMissing?: boolean; readonly excludePaths?: ReadonlyArray; + /** `capturesSoFar` from before an earlier wait on the folder's lock, when there was one. */ + readonly capturesBeforeLock?: number; }) => Effect.Effect; + /** How many captures have finished in a folder, for a caller that waits on it before `capture`. */ + readonly capturesSoFar: (cwd: string) => Effect.Effect; /** * A tracked repository's checkpoint for a run, with the baseline before it unless that is * already recorded. None when the run left the repository as it found it, which costs one @@ -388,19 +392,43 @@ export const layer: Layer.Layer< capacity: 128, lookup: () => Effect.succeed(0), }); + // Unlike the streak, a success never rewinds the count, so a waiter can order outcomes. A + // baseline running out of its short budget is not a post-turn capture timing out. + const lastCaptures = new Map(); + const noteCapture = (cwd: string, timedOut: boolean) => + Effect.sync(() => { + lastCaptures.set(cwd, { count: (lastCaptures.get(cwd)?.count ?? 0) + 1, timedOut }); + }); + const capturesSoFar = (cwd: string) => lastCaptures.get(cwd)?.count ?? 0; + const withCaptureLock = Effect.fn("CheckpointService.withCaptureLock")(function* ( + cwd: string, + capturesBeforeLock: number | undefined, + effect: (capturesBeforeLock: number) => Effect.Effect, + ) { + return yield* withWorkspaceLock(cwd, effect(capturesBeforeLock ?? capturesSoFar(cwd))); + }); // Both callers hold the workspace lock; post-turn captures always probe for recovery. const captureWorkspaceCheckpoint = Effect.fn("CheckpointService.captureWorkspaceCheckpoint")( function* (input: CheckpointStore.CaptureCheckpointInput, baseline = false) { const capture = checkpointStore.captureCheckpoint(input); yield* (baseline ? capture.pipe(Effect.timeout(BASELINE_CAPTURE_BUDGET)) : capture).pipe( - Effect.tap(() => Cache.invalidate(captureTimeouts, input.cwd)), + Effect.tap(() => + Effect.andThen( + Cache.invalidate(captureTimeouts, input.cwd), + noteCapture(input.cwd, false), + ), + ), Effect.tapError((error) => error._tag === "VcsProcessTimeoutError" || error._tag === "TimeoutError" ? Effect.gen(function* () { const previous = yield* Cache.get(captureTimeouts, input.cwd); yield* Cache.set(captureTimeouts, input.cwd, previous + 1); + yield* noteCapture(input.cwd, !baseline); }) - : Cache.invalidate(captureTimeouts, input.cwd), + : Effect.andThen( + Cache.invalidate(captureTimeouts, input.cwd), + noteCapture(input.cwd, false), + ), ), ); }, @@ -590,8 +618,7 @@ export const layer: Layer.Layer< readonly cleanHead?: string; }, ) => - withWorkspaceLock( - input.scope.cwd, + withCaptureLock(input.scope.cwd, input.capturesBeforeLock, (capturesBeforeLock) => Effect.gen(function* () { const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, { scopeId: input.scope.id, @@ -634,32 +661,47 @@ export const layer: Layer.Layer< }; } - const captureStatus = yield* ( - input.cleanHead === undefined - ? captureWorkspaceCheckpoint({ - cwd: input.scope.cwd, - checkpointRef, - ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), - ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), - }) - : checkpointStore.captureHeadCheckpoint({ - cwd: input.scope.cwd, - checkpointRef, - head: input.cleanHead, - }) - ).pipe( - Effect.as("ready" as const), - Effect.catchTags({ - VcsUnsupportedOperationError: () => Effect.succeed("missing" as const), - }), - Effect.catch((cause) => - Effect.logWarning("orchestration V2 checkpoint capture failed", { - scopeId: input.scope.id, - checkpointRef, - cause: String(cause), - }).pipe(Effect.as("error" as const)), - ), - ); + // Threads sharing a folder queue on its lock. One that waited out another's timeout + // would only time out again while its own queued messages wait behind it. + const lastCapture = lastCaptures.get(input.scope.cwd); + const timedOutWhileWaiting = + input.cleanHead === undefined && + lastCapture !== undefined && + lastCapture.timedOut && + lastCapture.count > capturesBeforeLock; + const captureStatus = timedOutWhileWaiting + ? yield* Effect.logWarning( + "orchestration V2 checkpoint capture skipped after a capture timed out in its folder", + { scopeId: input.scope.id, checkpointRef }, + ).pipe(Effect.as("error" as const)) + : yield* ( + input.cleanHead === undefined + ? captureWorkspaceCheckpoint({ + cwd: input.scope.cwd, + checkpointRef, + ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), + ...(input.excludePaths === undefined + ? {} + : { excludePaths: input.excludePaths }), + }) + : checkpointStore.captureHeadCheckpoint({ + cwd: input.scope.cwd, + checkpointRef, + head: input.cleanHead, + }) + ).pipe( + Effect.as("ready" as const), + Effect.catchTags({ + VcsUnsupportedOperationError: () => Effect.succeed("missing" as const), + }), + Effect.catch((cause) => + Effect.logWarning("orchestration V2 checkpoint capture failed", { + scopeId: input.scope.id, + checkpointRef, + cause: String(cause), + }).pipe(Effect.as("error" as const)), + ), + ); if (captureStatus !== "ready") { return { @@ -882,10 +924,11 @@ export const layer: Layer.Layer< const repositoryScopesIfReadable: CheckpointServiceV2Shape["repositoryScopesIfReadable"] = Effect.fn("CheckpointService.repositoryScopes")( function* (input) { - const [workspace, submodules] = yield* Effect.all([ - workspaceFolders.forThread(input), - workspaceFolders.submodules(input), - ]); + const workspace = yield* workspaceFolders.forThread(input); + const submodules = yield* workspaceFolders.submodules({ + ...input, + folders: workspace.folders, + }); return yield* Effect.forEach( [...workspace.folders.filter((folder) => folder.isGitRepository), ...submodules], (folder) => @@ -966,6 +1009,7 @@ export const layer: Layer.Layer< )(function* (input) { const { cwd, id } = input.scope; const baselineOrdinal = input.ordinalWithinScope - 1; + const capturesBeforeLock = capturesSoFar(cwd); const start = yield* withWorkspaceLock( cwd, Effect.gen(function* () { @@ -1023,6 +1067,7 @@ export const layer: Layer.Layer< ordinalWithinScope: input.ordinalWithinScope, appRunOrdinal: null, capturedAt: input.capturedAt, + capturesBeforeLock, ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), ...(start.cleanHead === null ? {} : { cleanHead: start.cleanHead }), }); @@ -1135,6 +1180,7 @@ export const layer: Layer.Layer< captureBaseline, materializeBaselineCheckpoint, capture, + capturesSoFar: (cwd: string) => Effect.sync(() => capturesSoFar(cwd)), captureRepository, restore, deleteStaleRefs, diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index 9a3a71acd3bc0..de951ab234775 100644 --- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts @@ -15,6 +15,7 @@ import { ThreadId, type OrchestrationV2DomainEvent, } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -22,6 +23,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; @@ -42,6 +44,7 @@ import * as ProviderContinuationRequests from "@t3tools/provider-core/server/Pro import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import * as ThreadLaunchService from "./ThreadLaunchService.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -1211,10 +1214,19 @@ it.effect.each([ event.payload.status === "running" && event.payload.runAttemptId !== parent.activeAttemptId, ); + // The next run starts from an async reaction to the parent's capture, which drain does not await. + const nextStarting = yield* watch( + (event) => + event.type === "run.updated" && + event.payload.id !== parent.id && + event.payload.status === "starting", + ); yield* answer(offers[0]!); yield* cancel(offers[1]!); yield* Fiber.join(ended); yield* worker.drain(); + yield* Fiber.join(nextStarting); + yield* worker.drain(); yield* Fiber.join(nextRunning); // The older message runs first; the steer waits right behind it on its own model. const behind = yield* queued; @@ -1238,10 +1250,18 @@ it.effect.each([ yield* worker.drain(); assert.equal(offers[3]?.priority, "next"); const beforeEnded = yield* settled(before.id, "waiting"); + const steerStarting = yield* watch( + (event) => + event.type === "run.updated" && + event.payload.userMessageId === steerId && + event.payload.status === "starting", + ); yield* answer(offers[2]!); yield* cancel(offers[3]!); yield* Fiber.join(beforeEnded); yield* worker.drain(); + yield* Fiber.join(steerStarting); + yield* worker.drain(); assert.deepEqual(yield* queuedOrder, [[MessageId.make("after"), false]]); assert.equal(offers.length, 5); assert.equal(offers[4]?.priority, undefined); @@ -1350,3 +1370,274 @@ it.effect.each([ ), ), ); + +// SIGKILL ends the stream without a frame. SIGTERM makes the CLI stop its tasks first; the +// empty roster level can come before or after the stop notification. +const exitWhileIdle = (options: { + readonly awaited: boolean; + readonly signal: "SIGKILL" | "SIGTERM" | "SIGTERM-roster-first"; +}) => + Effect.scoped( + Effect.gen(function* () { + const { awaited, signal } = options; + const cwd = yield* checkpointWorkspace("claude-idle-exit-awaited-task"); + const processes: Array> = []; + const offers: SDKUserMessage[] = []; + const taskId = "b8sleep180"; + const registry = Layer.unwrap( + Effect.gen(function* () { + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: modelSelection.instanceId, + settings, + environment: {}, + attachmentsDir: cwd, + fileSystem: yield* FileSystem.FileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator: yield* IdAllocator.IdAllocatorV2, + continuationRequests: yield* ProviderContinuationRequests.ProviderContinuationRequests, + queryRunner: { + allocateSessionId: Effect.succeed(sessionId), + open: () => + Effect.gen(function* () { + const sdkMessages = yield* Queue.unbounded(); + processes.push(sdkMessages); + return { + messages: Stream.fromQueue(sdkMessages), + offer: (message: SDKUserMessage) => + Effect.sync(() => void offers.push(message)), + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + renameSession: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"), + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"), + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Queue.shutdown(sdkMessages), + }; + }), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + return ProviderAdapterRegistry.layerSingle(adapter); + }), + ).pipe( + Layer.provide(Layer.mergeAll(IdAllocator.layer, NodeServices.layer, NodeCrypto.layer)), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + const threadId = ThreadId.make("thread:idle-exit-awaited-task"); + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamDomainEvents.pipe( + Stream.filter(predicate), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make("project:idle-exit-awaited-task"), + title: "Idle exit", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const running = yield* watch( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("first"), + threadId, + messageId: MessageId.make("first"), + text: "Sleep 180 seconds in the background and wait for it.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(running); + const firstProcess = processes[0]!; + const rostered = yield* watch( + (event) => + event.type === "provider-thread.updated" && + event.payload.pendingBackgroundTasks?.some((task) => task.taskId === taskId) === true, + ); + yield* Queue.offer( + firstProcess, + frame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [{ task_id: taskId, task_type: "local_bash", description: "sleep 180" }], + uuid: "roster", + session_id: sessionId, + }), + ); + yield* Fiber.join(rostered); + if (awaited) { + const records = yield* orchestrator.getThreadRecords(threadId, ["providerThreads"]); + const providerThread = records.providerThreads[0]!; + const runtime = yield* sessions.get(providerThread.providerSessionId!); + if (Option.isNone(runtime) || runtime.value.awaitBackgroundTasks === undefined) { + return yield* Effect.die("Claude runtime must accept background waits"); + } + const awaitedRoster = yield* watch( + (event) => + event.type === "provider-thread.updated" && + event.payload.pendingBackgroundTasks?.some((task) => task.awaited === true) === true, + ); + yield* runtime.value.awaitBackgroundTasks({ + providerThread, + taskIds: [taskId], + awaited: true, + }); + yield* Fiber.join(awaitedRoster); + } + const settled = yield* watch( + (event) => + event.type === "run.updated" && + (event.payload.status === "waiting" || event.payload.status === "completed"), + ); + yield* Queue.offer(firstProcess, result("waiting-on-sleep", false)); + yield* Fiber.join(settled); + yield* worker.drain(); + const beforeExit = yield* orchestrator.getThreadProjection(threadId); + const firstRun = beforeExit.runs[0]!; + assert.deepEqual( + beforeExit.providerThreads[0]?.pendingBackgroundTasks?.map((task) => [ + task.taskId, + task.awaited, + ]), + [[taskId, awaited ? true : undefined]], + ); + + const recorded = yield* watch((event) => event.type === "run.background-work-cancelled"); + const woken = yield* watch( + (event) => event.type === "run.updated" && event.payload.id !== firstRun.id, + ); + if (signal !== "SIGKILL") { + const notification = frame({ + type: "system", + subtype: "task_notification", + task_id: taskId, + status: "stopped", + output_file: "", + summary: "sleep 180", + uuid: "stopped", + session_id: sessionId, + }); + const emptyRoster = frame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [], + uuid: "roster-empty", + session_id: sessionId, + }); + const killed = frame({ + type: "system", + subtype: "task_updated", + task_id: taskId, + patch: { status: "killed", end_time: 1 }, + uuid: "killed", + session_id: sessionId, + }); + yield* Queue.offerAll( + firstProcess, + signal === "SIGTERM" + ? [notification, killed, emptyRoster] + : [emptyRoster, notification, killed], + ); + } + // The CLI exits while the thread is idle, after its last frames; the T3 server keeps running. + yield* Queue.end(firstProcess); + yield* Fiber.join(recorded); + yield* worker.drain(); + + const afterExit = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + afterExit.runs + .find((run) => run.id === firstRun.id) + ?.restartCancelledBackgroundWork?.map((work) => work.id), + [taskId], + "the run must record the awaited task the exited process took with it", + ); + // Drained effects already dispatched any wake, so a missing one fails here instead of hanging. + assert.equal( + afterExit.runs.some((run) => run.id !== firstRun.id), + awaited, + "only awaited work wakes the agent without a user message", + ); + if (!awaited) return; + yield* Fiber.join(woken); + yield* worker.drain(); + const afterWake = yield* orchestrator.getThreadProjection(threadId); + assert.lengthOf( + afterWake.runs.filter((run) => run.id !== firstRun.id), + 1, + "the agent must be woken exactly once", + ); + assert.lengthOf(offers.slice(1), 1); + assert.include( + JSON.stringify(offers[1]?.message), + taskId, + "the wake must carry a note naming the lost task", + ); + assert.equal( + afterWake.messages.filter((message) => message.createdBy === "user").length, + 1, + ); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { name: "claude-idle-exit-awaited-task" }, + registry, + { runEffectWorker: false, runContinuationWorker: true }, + ), + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + +it.effect("wakes the agent when Claude's process exits while it awaits background work", () => + exitWhileIdle({ awaited: true, signal: "SIGKILL" }), +); + +it.effect("wakes the agent when Claude stops awaited background work before exiting", () => + exitWhileIdle({ awaited: true, signal: "SIGTERM" }), +); + +it.effect("wakes the agent when Claude empties its roster before stopping awaited work", () => + exitWhileIdle({ awaited: true, signal: "SIGTERM-roster-first" }), +); + +it.effect("records but does not wake for an unawaited shell lost when Claude's process exits", () => + exitWhileIdle({ awaited: false, signal: "SIGKILL" }), +); diff --git a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts index 5211da2faf169..c13e31cb0c161 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts @@ -12,6 +12,15 @@ import { selectHistory, } from "@t3tools/provider-core/server/handoffBudget"; +// A first word with a second slash is a path, not a command. +const SLASH_COMMAND = /^\s*\/[^\s/]+(?:\s|$)/u; + +/** Providers only run a native command that opens the prompt, so its turn defers inline context to the next one. */ +export const isSlashCommandMessage = (message: { + readonly role: string; + readonly text: string; +}): boolean => message.role === "user" && SLASH_COMMAND.test(message.text); + /** The provider prompt for a turn that carries inline context ahead of the user's text. */ export const withInlineContext = (context: string, userText: string): string => context === "" ? userText : `${context}\n\nUser message:\n${userText}`; @@ -37,7 +46,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH handoff.delivery.status === "pending", ); if (pending.length === 0 || (input.deferInline && input.inject === undefined)) - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; const budget = typeof input.budget === "number" ? input.budget : yield* input.budget; let coverage = pending .map( @@ -76,7 +85,8 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH budget, }); if (historyCost(selected.messages, selected.context) > budget) { - if (input.deferInline) return { context: "", delivered: Effect.void, unsent: Effect.void }; + if (input.deferInline) + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; return yield* new ContextHandoffBudgetError(); } const omittedItemIds = new Set(selected.omittedItemIds); @@ -127,7 +137,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH }); if (injected) { yield* persist("injected"); - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; } } else { yield* persist("pending"); @@ -135,12 +145,13 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH if (input.deferInline) { // Compaction cannot carry inline transcripts; retain for the next turn if native injection is unsupported. yield* Effect.forEach(pending, input.persist, { discard: true }); - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; } return { context: renderHistory(selected.messages, selected.context), delivered: persist("inline"), unsent: Effect.forEach(pending, input.persist, { discard: true }), + inlineHandoffs: pending, }; }, ); diff --git a/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts new file mode 100644 index 0000000000000..b9c20c02b5afe --- /dev/null +++ b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts @@ -0,0 +1,328 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + ProviderTurnId, + ThreadId, + type OrchestrationV2DomainEvent, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import { ClaudeProviderCapabilitiesV2 } from "./Adapters/ClaudeAdapterV2.ts"; +import * as EffectWorker from "./EffectWorker.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; + +const driver = ProviderDriverKind.make("claudeAgent"); +const instanceId = ProviderInstanceId.make("claudeAgent"); +const modelSelection = { instanceId, model: "claude-test" }; +const parentThreadId = ThreadId.make("thread:delegated-terminal-retry-parent"); +const childError = "Failed to initialize session: No space left on device"; + +type ParentRead = { + readonly store: ProjectionStore.ProjectionStoreV2["Service"]; + readonly threadId: ThreadId; + readonly fields: ReadonlyArray; + readonly filter: Parameters[2]; +}; + +// The parent hears of a child only from the reaction to the child's terminal run. +// The injected failure stands in for a storage error, such as a full disk, and fails once. +const runDelegation = (input: { + readonly name: string; + readonly parentEndsFirst: boolean; + readonly failRead?: (read: ParentRead) => Effect.Effect; + readonly failChildRunMessage?: boolean; +}) => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace(input.name); + let armed = false; + const turns: Array<{ + readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput; + readonly events: Queue.Queue; + }> = []; + const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { + instanceId, + driver, + getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), + openSession: (session) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const events = yield* Queue.unbounded(); + return { + instanceId, + driver, + providerSessionId: session.providerSessionId, + providerSession: { + id: session.providerSessionId, + driver, + providerInstanceId: instanceId, + status: "ready", + cwd, + model: modelSelection.model, + capabilities: ClaudeProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + events: Stream.fromQueue(events), + ensureThread: ({ threadId }) => + IdAllocator.isDelegatedTaskThread(threadId) + ? Effect.fail( + new ProviderAdapter.ProviderAdapterEnsureThreadError({ + driver, + threadId, + cause: new Error(childError), + }), + ) + : Effect.succeed({ + id: ProviderThreadId.make(`provider-thread:${threadId}`), + driver, + providerInstanceId: instanceId, + providerSessionId: session.providerSessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn: (turn) => + Effect.gen(function* () { + turns.push({ turn, events }); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`), + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: null, + ordinal: turn.providerTurnOrdinal, + status: "running", + startedAt: now, + completedAt: null, + }, + }); + }), + steerTurn: () => Effect.die("unused"), + interruptTurn: () => Effect.void, + respondToRuntimeRequest: () => Effect.die("unused"), + readThreadSnapshot: () => Effect.die("unused"), + rollbackThread: () => Effect.die("unused"), + forkThread: () => Effect.die("unused"), + }; + }), + }; + const layerTest = ProviderReplayHarness.layerWithRegistry( + { name: input.name }, + ProviderAdapterRegistry.layerSingle(adapter), + { + runEffectWorker: false, + runContinuationWorker: true, + wrapProjectionStore: (store) => ({ + ...store, + getThreadRecords: (threadId, fields, filter) => + Effect.gen(function* () { + if ( + armed && + input.failRead !== undefined && + (yield* input.failRead({ store, threadId, fields, filter })) + ) { + armed = false; + return yield* new ProjectionStore.ProjectionStoreReadError({ threadId }); + } + return yield* store.getThreadRecords(threadId, fields, filter); + }), + getRunMessage: (threadId, runId) => { + if ( + !armed || + !input.failChildRunMessage || + !IdAllocator.isDelegatedTaskThread(threadId) + ) { + return store.getRunMessage(threadId, runId); + } + armed = false; + return Effect.fail(new ProjectionStore.ProjectionStoreReadError({ threadId })); + }, + }), + }, + ); + + return yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamDomainEvents.pipe( + Stream.filter(predicate), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-parent"), + threadId: parentThreadId, + projectId: ProjectId.make("project:delegated-terminal-retry"), + title: "Parent", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const parentRunning = yield* watch( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-parent"), + threadId: parentThreadId, + messageId: MessageId.make("message:start-parent"), + text: "Delegate a review", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(parentRunning); + const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!; + + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("delegate"), + parentThreadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Review the change", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + completionWake: "always", + createdBy: "agent", + creationSource: "mcp", + }); + const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!; + const childThreadId = task.childThreadId!; + + const endParentTurn = Effect.gen(function* () { + const parentTurn = (yield* orchestrator.getThreadProjection(parentThreadId)) + .providerTurns[0]!; + const parentEvents = turns.find((entry) => entry.turn.threadId === parentThreadId)!.events; + const now = yield* DateTime.now; + yield* Queue.offer(parentEvents, { + type: "provider_turn.updated", + driver, + providerTurn: { ...parentTurn, status: "completed", completedAt: now }, + }); + yield* Queue.offer(parentEvents, { + type: "turn.terminal", + driver, + providerThreadId: parentTurn.providerThreadId, + providerTurnId: parentTurn.id, + runOrdinal: parentRun.ordinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + }); + + if (input.parentEndsFirst) { + const parentEnded = yield* watch( + (event) => + event.type === "run.updated" && + event.payload.id === parentRun.id && + event.payload.status !== "running", + ); + yield* endParentTurn; + yield* Fiber.join(parentEnded); + } + + armed = true; + const childFailed = yield* watch( + (event) => + event.type === "run.updated" && + event.payload.threadId === childThreadId && + event.payload.status === "failed", + ); + for (let attempt = 0; attempt < 5; attempt++) { + yield* worker.drain(); + yield* TestClock.adjust("1 second"); + } + yield* Fiber.join(childFailed); + + if (!input.parentEndsFirst) yield* endParentTurn; + for (let attempt = 0; attempt < 5; attempt++) { + yield* worker.drain(); + yield* TestClock.adjust("30 seconds"); + } + + assert.isFalse(armed, "the injected read failed once"); + const parent = yield* orchestrator.getThreadProjection(parentThreadId); + const settled = parent.subagents.find((row) => row.id === task.id); + assert.equal(settled?.status, "failed"); + assert.equal(settled?.result, childError); + assert.isTrue( + parent.messages.some( + (message) => message.delegatedCompletion?.taskIds.includes(task.id) === true, + ), + "the parent is woken with the child's failure", + ); + }).pipe(Effect.provide(layerTest)); + }); + +it.effect("a delegated child that fails to start reaches its parent after a failed read", () => + runDelegation({ + name: "delegated-child-terminal-retry", + parentEndsFirst: false, + // Only finalizing the parent's task reads its rows by child thread. + failRead: ({ filter }) => Effect.succeed(filter?.subagentChildThreadIds !== undefined), + }), +); + +it.effect("an idle parent is woken when its wake fails after the task settles", () => + runDelegation({ + name: "delegated-child-terminal-wake-retry", + parentEndsFirst: true, + failRead: ({ store, threadId, fields, filter }) => + threadId !== parentThreadId || fields.join() !== "runs" || filter?.runIds === undefined + ? Effect.succeed(false) + : store.getThreadRecords(parentThreadId, ["subagents"]).pipe( + Effect.map((records) => records.subagents.some((task) => task.result !== null)), + Effect.orDie, + ), + }), +); + +it.effect("a delegated child reaches its parent after its own delivery read fails", () => + runDelegation({ + name: "delegated-child-terminal-delivery-read", + parentEndsFirst: false, + failChildRunMessage: true, + }), +); diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 441c9992e73cc..3d6575bd6a405 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -19,6 +19,7 @@ import { ProviderInstanceId, ProviderSessionId, ProviderThreadId, + ProviderTurnId, RunId, RuntimeRequestId, ThreadId, @@ -5063,6 +5064,138 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { }), ); + // regression: #34401 a parent's Stop killed a child's background build but its task read completed + it.effect("reports a child its parent's Stop reached as interrupted", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const stoppedAt = DateTime.add(now, { seconds: 10 }); + const threadId = ThreadId.make("thread:stop-background-parent"); + const projectId = ProjectId.make("project:stop-background-parent"); + const runId = RunId.make("run:stop-background-parent"); + const rootNodeId = NodeId.make("node:stop-background-parent-root"); + yield* seedParentWithTerminalTask({ + threadId, + projectId, + runId, + rootNodeId, + taskId: NodeId.make("node:stop-background-parent-settled"), + deliveryState: "delivered", + now, + }); + // Background launches report their command finished at once; only the roster tracks the work. + const seedStoppedChild = (name: string, parentStopped: boolean, reachedTurn: boolean) => + Effect.gen(function* () { + const child = yield* seedRestartCancelledChild({ + parentThreadId: threadId, + projectId, + parentRunId: runId, + rootNodeId, + name, + completionWake: "always", + continuationPending: false, + runStatus: "completed", + now, + }); + const item = { + threadId: child.childThreadId, + runId: child.childRunId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + }; + const scope = { + type: "turn-item.updated" as const, + threadId: child.childThreadId, + runId: child.childRunId, + providerInstanceId: modelSelection.instanceId, + }; + yield* eventSink.write({ + commandId: CommandId.make(`command:${name}:stop`), + events: [ + { + ...scope, + id: EventId.make(`event:${name}:command`), + occurredAt: now, + payload: { + ...item, + id: TurnItemId.make(`turn-item:${name}:command`), + type: "command_execution", + ordinal: 1, + status: "completed", + title: "Run build", + input: "./build.sh", + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }, + { + ...scope, + id: EventId.make(`event:${name}:interrupt-request`), + occurredAt: stoppedAt, + payload: { + ...item, + id: TurnItemId.make(`turn-item:${name}:interrupt-request`), + // Stop interrupting background work names its provider turn; an idle run's marker does not. + providerTurnId: reachedTurn ? ProviderTurnId.make(`provider-turn:${name}`) : null, + type: "run_interrupt_request", + ordinal: 2, + status: "completed", + title: "Interrupt requested", + startedAt: stoppedAt, + completedAt: stoppedAt, + updatedAt: stoppedAt, + message: "Stopped by user", + }, + }, + ], + }); + if (parentStopped) { + const task = (yield* orchestrator.getThreadProjection(threadId)).subagents.find( + (row) => row.id === child.taskId, + )!; + yield* eventSink.write({ + commandId: CommandId.make(`command:${name}:parent-stop`), + events: [ + { + id: EventId.make(`event:${name}:disposed`), + type: "subagent.updated", + threadId, + runId, + nodeId: task.id, + driver, + providerInstanceId: modelSelection.instanceId, + occurredAt: stoppedAt, + payload: { + ...task, + completionDelivery: { state: "disposed", observedByRunId: null }, + updatedAt: stoppedAt, + }, + }, + ], + }); + } + return child; + }); + const cut = yield* seedStoppedChild("stop-background-cut", true, true); + const idle = yield* seedStoppedChild("stop-background-idle", true, false); + const finished = yield* seedStoppedChild("stop-background-finished", false, true); + + yield* orchestrator.recoverDelegatedTasks; + + const settled = yield* orchestrator.getThreadProjection(threadId); + const statusOf = (taskId: NodeId) => + settled.subagents.find((row) => row.id === taskId)?.status; + assert.equal(statusOf(cut.taskId), "interrupted"); + assert.equal(statusOf(idle.taskId), "completed"); + assert.equal(statusOf(finished.taskId), "completed"); + }), + ); + it.effect("cancelling a task whose child already finished keeps its completed result", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index c637446d78827..6c805cfc4592f 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -390,8 +390,7 @@ export const layerExecutor: Layer.Layer< threadId: effect.threadId, messageId: message.id, ...(error.steerDeclined ? { steerFollowUpOfRunId: run.id } : {}), - ...(error.steerDeclined && - effect.request.steerFollowUpAfterRunOrdinal !== undefined + ...(effect.request.steerFollowUpAfterRunOrdinal !== undefined ? { steerFollowUpAfterRunOrdinal: effect.request.steerFollowUpAfterRunOrdinal, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index e27fe09d07d1b..5936f57ad5014 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -28,6 +28,7 @@ import { CommandId, type GuestMessageId, isCompactionCommandMessage, + isDeliveredProviderTurn, isOrchestrationV2WorkActive, isProviderNativeSubagentThread, MessageId, @@ -101,14 +102,17 @@ import { } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as FiberSet from "effect/FiberSet"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; @@ -979,6 +983,14 @@ function delegatedCompletionWakeDetail( .join("\n\n"); } +// Startup recovery settles whatever is still missed after this window. +const parentTaskSyncRetry = Schedule.exponential("1 second").pipe( + Schedule.modifyDelay(({ duration }) => + Effect.succeed(Duration.min(duration, Duration.seconds(30))), + ), + Schedule.upTo({ duration: Duration.hours(1) }), +); + function isTerminalDelegatedTaskStatus(status: OrchestrationV2Subagent["status"]): boolean { return ( status === "completed" || @@ -1028,7 +1040,7 @@ function nextQueuedRun( return queuedRunsInDeliveryOrder(projection).find((run) => run.queueHeld !== true); } -// Delegated completions, monitor notifications and unpinned scheduled deliveries never choose a +// Delegated completions, monitor notifications and queued messages that name no model never choose a // model, so a queued one runs on the thread's current pick rather than the one frozen at queue time. function followsCurrentConversation( message: @@ -1588,7 +1600,9 @@ function lastDeliveredRunForProviderThread( isHandoffSourceRun(run) && run.providerThreadId === providerThreadId && (run.status === "completed" || - projection.providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId)), + projection.providerTurns.some( + (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn), + )), ); } @@ -2142,6 +2156,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } }); + const offerChildTaskDeliveries = + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */ + Effect.fnUntraced(function* (parentThreadId: ThreadId, childThreadId: ThreadId) { + // A task's wake lives on the run that requested it; the parent's other wakes are not this child's. + const { subagents } = yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"], { + subagentChildThreadIds: [childThreadId], + }); + const parentRunIds = new Set( + subagents.flatMap((task) => + task.childThreadId === childThreadId && task.runId !== null ? [task.runId] : [], + ), + ); + for (const parentRunId of parentRunIds) { + yield* offerDelegatedCompletionDelivery(parentThreadId, parentRunId); + } + }); + /** Marks a wake the provider received delivered and reserves the next one for pending siblings. */ const acceptDelegatedCompletionDelivery = Effect.fn( "Orchestrator.acceptDelegatedCompletionDelivery", @@ -3564,7 +3595,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageId: message.id, steerFollowUpOfRunId: run.id, steerFollowUpAfterRunOrdinal: afterRunOrdinal, - modelSelection: steer?.modelSelection ?? run.modelSelection, + ...(message.followsThreadSelection === true + ? {} + : { modelSelection: steer?.modelSelection ?? run.modelSelection }), text: message.text, ...(message.context ? { context: message.context } : {}), attachments: message.attachments, @@ -4010,6 +4043,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio id: command.threadId, projectId: command.projectId, title: command.title, + ...(command.titleRenamed === true ? { titleRenamed: true } : {}), providerInstanceId: command.modelSelection.instanceId, modelSelection: command.modelSelection, runtimeMode: command.runtimeMode, @@ -7398,7 +7432,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio !hasTitleSetBeforeFirstMessage(projection.thread, command.titleSeed); if ( !isNativeMaintenanceCommand(command) && - (seedsUntitledThread || (command.createdBy === "user" && (yield* onlyMaintenanceHistory))) + (seedsUntitledThread || + (command.createdBy === "user" && + // A draft opened by `/compact` is titled after it, so only a chosen title stays here. + projection.thread.titleRenamed !== true && + (yield* onlyMaintenanceHistory))) ) { const now = yield* DateTime.now; const thread: OrchestrationV2AppThread = { @@ -7881,6 +7919,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // restart command that stops the active run goes first, so nothing queued applies before it. // Buffered provider wakes drain output their own provider already produced. const incomingMessage = { ...command, delegatedCompletion }; + // A message that names no model runs on the thread's pick when it starts, not a copy from now. + const followsThreadSelection = + command.modelSelection === undefined && + (command.scheduledTaskId !== undefined || + (shouldQueue && + !followsCurrentConversation(incomingMessage) && + !isBufferedProviderNotification(incomingMessage))); if ( shouldQueue && // A steer whose run ended keeps the thread's selection, as it did before it queued. @@ -8031,10 +8076,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.creationSource === "provider" && !(yield* stopReachedRun(command, command.threadId, activeRun.id)); let steerFollowUpQueuePosition: number | undefined; - if ( - command.steerFollowUpOfRunId !== undefined && - command.steerFollowUpAfterRunOrdinal !== undefined - ) { + if (command.steerFollowUpAfterRunOrdinal !== undefined) { const afterRunOrdinal = command.steerFollowUpAfterRunOrdinal; const steerOrdinal = projection.turnItems.find( @@ -8148,9 +8190,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), - ...(command.scheduledTaskId !== undefined && command.modelSelection === undefined - ? { followsThreadSelection: true as const } - : {}), + ...(followsThreadSelection ? { followsThreadSelection: true as const } : {}), id: command.messageId, threadId: command.threadId, runId, @@ -8197,7 +8237,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runId: queued.id, providerInstanceId: queued.providerInstanceId, occurredAt: now, - payload: { ...queued, queuePosition: (queued.queuePosition ?? queued.ordinal) + 1 }, + payload: { + ...queued, + ...(heldRunsToRelease.includes(queued) ? { queueHeld: false } : {}), + queuePosition: (queued.queuePosition ?? queued.ordinal) + 1, + }, }); } } @@ -8573,9 +8617,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), - ...(command.scheduledTaskId !== undefined && command.modelSelection === undefined - ? { followsThreadSelection: true as const } - : {}), + ...(followsThreadSelection ? { followsThreadSelection: true as const } : {}), id: command.messageId, threadId: command.threadId, runId, @@ -14492,9 +14534,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio targetCheckpoint.appRunOrdinal ?? 0, ) !== null, ); - // Missing snapshots otherwise support conversation rewind only. + // Missing or failed snapshots otherwise support conversation rewind only. if ( targetCheckpoint.status !== "ready" && + !(targetCheckpoint.status === "error" && command.restoreFiles === false) && !( targetCheckpoint.status === "missing" && (command.restoreFiles === false || restoresRepositories) @@ -15089,7 +15132,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageRoles: ["assistant"], messageRunIds: resultRunIds, turnItemRunIds: resultRunIds, - turnItemTypes: SUBAGENT_RESULT_TURN_ITEM_TYPES, + turnItemTypes: [...SUBAGENT_RESULT_TURN_ITEM_TYPES, "run_interrupt_request"], providerTurnAttemptIds: [childRun, ...reportRuns].flatMap( (run) => run.activeAttemptId ?? [], ), @@ -15134,9 +15177,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (task === undefined) { return; } - // A cancelled task's completed run ends it interrupted. + // A cancelled task's completed run ends it interrupted, as does one whose provider turn its + // parent's Stop interrupted to kill background work. Stop's marker on an idle run names no + // provider turn and interrupted nothing. const cancelled = task.cancelledRunId === childRun.id; - if (cancelled && terminalStatus === "completed") outcome = terminalStatus = "interrupted"; + const stopped = + task.completionDelivery?.state === "disposed" && + childResult.turnItems.some( + (item) => + item.runId === childRun.id && + item.type === "run_interrupt_request" && + item.providerTurnId !== null, + ); + if ((cancelled || stopped) && terminalStatus === "completed") + outcome = terminalStatus = "interrupted"; // Every result the child sent is among its own transfers, far fewer than the parent's. const childTransfers = yield* projectionStore.getThreadRecords(childThreadId, [ "contextTransfers", @@ -16457,6 +16511,57 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : dispatch; }); + const parentTaskSyncRetries = yield* FiberSet.make(); + const syncDelegatedParentTask = Effect.fn("Orchestrator.syncDelegatedParentTask")(function* ( + childThreadId: ThreadId, + options: { readonly syncRunId: RunId | undefined; readonly retry: boolean }, + ) { + const parentThreadId = yield* appOwnedSubagentParentThreadId(childThreadId); + if (parentThreadId === undefined) return; + const finalize = finalizeAppOwnedSubagent( + childThreadId, + options.syncRunId === undefined ? undefined : { syncRunId: options.syncRunId }, + ); + yield* threadDispatch.withLock( + parentThreadId, + // A failed attempt may have committed the result before offering its wake. + options.retry + ? offerChildTaskDeliveries(parentThreadId, childThreadId).pipe(Effect.andThen(finalize)) + : finalize, + ); + }); + // Only these reactions tell a parent about its child before a restart; a dropped one leaves its task running. + const updateDelegatedParentTask = Effect.fn("Orchestrator.updateDelegatedParentTask")(function* ( + childThreadId: ThreadId, + syncRunId?: RunId, + ) { + const context = { + threadId: childThreadId, + ...(syncRunId === undefined ? {} : { runId: syncRunId }), + }; + yield* syncDelegatedParentTask(childThreadId, { syncRunId, retry: false }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Retrying a delegated task update for its parent", { + ...context, + cause, + }).pipe( + Effect.andThen( + syncDelegatedParentTask(childThreadId, { syncRunId, retry: true }).pipe( + Effect.retry({ schedule: parentTaskSyncRetry }), + Effect.delay("1 second"), + Effect.catchCause((cause) => + Effect.logWarning("Failed to update a delegated task for its parent", { + ...context, + cause, + }), + ), + FiberSet.run(parentTaskSyncRetries), + ), + ), + ), + ), + ); + }); const handleRunUpdate = Effect.fn("Orchestrator.handleRunUpdate")( function* (stored: OrchestrationV2StoredEvent) { if (stored.event.type !== "run.updated") return; @@ -16478,10 +16583,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); } - yield* threadDispatch.withLock( - threadId, - finalizeDelegatedCompletionDelivery(threadId, run.id), - ); + yield* threadDispatch + .withLock(threadId, finalizeDelegatedCompletionDelivery(threadId, run.id)) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to settle a delegated completion delivery", { + threadId, + runId: run.id, + cause, + }), + ), + ); yield* threadDispatch .withLock( threadId, @@ -16510,13 +16622,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); } - const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId); - if (parentThreadId !== undefined) { - yield* threadDispatch.withLock( - parentThreadId, - finalizeAppOwnedSubagent(threadId, { syncRunId: run.id }), - ); - } + yield* updateDelegatedParentTask(threadId, run.id); }, (effect, stored) => effect.pipe( @@ -16651,23 +16757,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ).pipe( Stream.filter(settlesChildWork), Stream.runForEach((stored) => - threadReactions.run( - stored.event.threadId, - Effect.gen(function* () { - const childThreadId = stored.event.threadId; - const parentThreadId = yield* appOwnedSubagentParentThreadId(childThreadId); - if (parentThreadId === undefined) return; - yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(childThreadId)); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("Failed to finalize a delegated child after its work settled", { - threadId: stored.event.threadId, - sequence: stored.sequence, - cause, - }), - ), - ), - ), + threadReactions.run(stored.event.threadId, updateDelegatedParentTask(stored.event.threadId)), ), Effect.forkScoped, ); @@ -16850,22 +16940,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return; yield* threadDispatch.withLock( parentThreadId, - Effect.gen(function* () { - // A task's wake lives on the run that requested it; the parent's other wakes are not this child's. - const { subagents } = yield* projectionStore.getThreadRecords( - parentThreadId, - ["subagents"], - { subagentChildThreadIds: [threadId] }, - ); - const parentRunIds = new Set( - subagents.flatMap((task) => - task.childThreadId === threadId && task.runId !== null ? [task.runId] : [], - ), - ); - for (const parentRunId of parentRunIds) { - yield* offerDelegatedCompletionDelivery(parentThreadId, parentRunId); - } - }).pipe( + offerChildTaskDeliveries(parentThreadId, threadId).pipe( Effect.andThen( finalizeAppOwnedSubagent( threadId, diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index 86a4c6c77375d..cb2fb0e87ada4 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -433,7 +433,7 @@ it.effect("sql: lists only active threads with pull request links, oldest first" const store = yield* ProjectionStore.ProjectionStoreV2; yield* createThread("no-links"); yield* createThread("empty-links", { pullRequests: [] }); - yield* createThread("archived-link", { + const archived = yield* createThread("archived-link", { archivedAt: old, pullRequests: [pullRequestLink(1)], }); @@ -459,6 +459,12 @@ it.effect("sql: lists only active threads with pull request links, oldest first" (yield* store.getThreadsWithPullRequests(open)).map((thread) => thread.id), [open], ); + assert.deepEqual( + (yield* store.getThreadsWithPullRequests(undefined, { includeArchived: true })).map( + (thread) => thread.id, + ), + [settled, archived, open], + ); }).pipe(Effect.provide(layerSql)), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index b6539e46344f1..8df11001e241a 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -3197,6 +3197,14 @@ it.effect("SQL shells read a subagent family and a worktree's threads", () => yield* createThread({ name: "archived-child", parent: "root", root: "root", archived: true }); yield* createThread({ name: "other", worktreePath: "/repo" }); yield* createThread({ name: "other-child", parent: "other", root: "other", worktreePath }); + yield* createThread({ + name: "aliased-child", + parent: "other", + root: "other", + worktreePath: `${worktreePath}/`, + }); + yield* createThread({ name: "cased", worktreePath: worktreePath.toUpperCase() }); + yield* createThread({ name: "windows", worktreePath: "C:\\Répo\\WT" }); const family = (threadId: ThreadId) => store @@ -3208,26 +3216,39 @@ it.effect("SQL shells read a subagent family and a worktree's threads", () => assert.sameMembers([...(yield* family(id("grandchild")))], tree); assert.deepEqual([...(yield* family(id("missing")))], []); - // Includes another root's idle child on the same path, which a shell may leave out. + // Includes another root's idle child on the same path, which a shell may leave out, under any + // spelling of that path. POSIX paths keep their case. const { statements, tracer } = traceSqlStatements(); const onWorktree = yield* store .getShellSnapshot({ location: "active", worktreePath }) .pipe(Effect.withTracer(tracer)); assert.sameMembers( onWorktree.threads.map((thread) => thread.id), - [id("root"), id("child"), id("other-child")], + [id("root"), id("child"), id("other-child"), id("aliased-child")], + ); + const onWindowsWorktree = yield* store + .getShellSnapshot({ location: "active", worktreePath: "c:/Répo/wt/" }) + .pipe(Effect.withTracer(tracer)); + assert.deepEqual( + onWindowsWorktree.threads.map((thread) => thread.id), + [id("windows")], ); - // A path names a few threads; scanning every thread parses every payload. + // A path, ASCII or not, names a few threads; scanning every thread parses every payload. const sql = yield* SqlClient.SqlClient; - const threadQuery = statements.find((statement) => + const threadQueries = statements.filter((statement) => statement.includes("AS latest_run_stop_requested"), ); - assert.isDefined(threadQuery); - const threadPlan = (yield* sql.unsafe<{ readonly detail: string }>( - `EXPLAIN QUERY PLAN ${threadQuery}`, - [], - )).map((row) => row.detail); - assert.notInclude(threadPlan, "SCAN t", threadPlan.join("\n")); + assert.lengthOf(threadQueries, 2); + for (const threadQuery of threadQueries) { + const threadPlan = (yield* sql.unsafe<{ readonly detail: string }>( + `EXPLAIN QUERY PLAN ${threadQuery}`, + [], + )).map((row) => row.detail); + assert.isFalse( + threadPlan.some((detail) => detail.startsWith("SCAN t ")), + threadPlan.join("\n"), + ); + } // A fork keeps its deleted source's root, so the deleted root still names the live tree. yield* store.apply({ id: EventId.make("event:family:root-deleted"), @@ -7614,6 +7635,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { [ "message:turn-start-commands:compact", "message:turn-start-commands:goal", + "message:turn-start-commands:later", "message:turn-start-commands:rolled-back", ], ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index ba91ba94d2520..e930fa67e3836 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -102,6 +102,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import type * as Statement from "effect/sql/Statement"; import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; +import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts"; import { DELEGATED_TASK_MESSAGE_CONDITION } from "./delegatedTaskMessage.ts"; import { @@ -684,6 +685,7 @@ export interface ProjectionStoreV2Shape { ) => Effect.Effect, ProjectionStoreV2Error>; readonly getThreadsWithPullRequests: ( threadId?: ThreadId, + options?: { readonly includeArchived?: boolean }, ) => Effect.Effect, ProjectionStoreV2Error>; /** Titles of the given threads that exist, archived ones included. */ readonly getThreadLinkMetadata: ( @@ -1257,6 +1259,7 @@ type ShellThreadRow = { readonly thread_id: string; readonly payload_json: string; readonly forked_from_run_source_thread_id: string | null; + readonly worktree_path: string | null; readonly latest_run_id: string | null; readonly latest_run_status: string | null; readonly latest_run_requested_at: string | null; @@ -5550,7 +5553,7 @@ export const layer: Layer.Layer = const messageIds = [run, unsentSource].flatMap((source) => source === undefined ? [] : [source.userMessageId], ); - // Earlier /compact and /goal turns defer context too; parseGoalCommand narrows the /goal prefix match. + // Earlier slash command turns defer context too; isSlashCommandMessage narrows the match. const messages = yield* sql` SELECT payload_json FROM ( SELECT payload_json, created_at, message_id FROM orchestration_v2_projection_messages @@ -6378,7 +6381,7 @@ export const layer: Layer.Layer = runRows[0] === undefined ? undefined : yield* decodeRunPayload(runRows[0].payload_json); - const preservedCheckpoint = sql`(status = 'ready' OR (status = 'missing' AND run_id IS NOT NULL))`; + const preservedCheckpoint = sql`(status = 'ready' OR (status IN ('missing', 'error') AND run_id IS NOT NULL))`; const [ nodeRows, scopeRows, @@ -6490,7 +6493,7 @@ export const layer: Layer.Layer = checkpoint === undefined || scope === undefined || checkpoint.scopeId !== scope.id || - (checkpoint.status !== "ready" && checkpoint.status !== "missing") || + checkpoint.status === "stale" || providerThread.id !== thread.activeProviderThreadId || providerThread.providerInstanceId !== thread.modelSelection.instanceId ) @@ -8396,6 +8399,7 @@ export const layer: Layer.Layer = THEN json_extract(t.payload_json, '$.forkedFrom.threadId') ELSE NULL END AS forked_from_run_source_thread_id, + json_extract(t.payload_json, '$.worktreePath') AS worktree_path, presented.run_id AS latest_run_id, presented.status AS latest_run_status, presented.requested_at AS latest_run_requested_at, @@ -8592,8 +8596,12 @@ export const layer: Layer.Layer = }${ worktreePath === undefined ? sql`` - : sql` AND CASE WHEN json_valid(t.payload_json) - THEN json_extract(t.payload_json, '$.worktreePath') END = ${worktreePath}` + : // Matches orchestration_v2_projection_threads_worktree_path_key_idx, so this never + // scans. SQLite lower() folds only ASCII: Windows paths differing only in the case + // of another letter are not found. readShellSnapshotRows keeps the exact comparison. + sql` AND CASE WHEN json_valid(t.payload_json) + THEN lower(rtrim(replace(trim(json_extract(t.payload_json, '$.worktreePath')), '\\', '/'), '/')) + END = lower(rtrim(replace(trim(${worktreePath}), '\\', '/'), '/'))` }${threadIds === undefined ? sql`` : sql` AND t.thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)}))`} ORDER BY t.updated_at ASC, t.thread_id ASC `; @@ -8972,12 +8980,12 @@ export const layer: Layer.Layer = const getThreadsWithPullRequests: ProjectionStoreV2Shape["getThreadsWithPullRequests"] = Effect.fn("ProjectionStore.getThreadsWithPullRequests")( - function* (threadId) { + function* (threadId, options) { const rows = yield* sql` SELECT payload_json FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL${threadId === undefined ? sql`` : sql` AND thread_id = ${threadId}`} - AND json_extract(payload_json, '$.archivedAt') IS NULL + ${options?.includeArchived === true ? sql`` : sql`AND json_extract(payload_json, '$.archivedAt') IS NULL`} AND json_array_length(payload_json, '$.pullRequests') > 0 ORDER BY updated_at ASC, thread_id ASC `; @@ -9212,7 +9220,16 @@ export const layer: Layer.Layer = const readShellSnapshotRows = Effect.fn("ProjectionStore.readShellSnapshotRows")(function* ( options: ShellSnapshotOptions | undefined, ) { - const targetThreadRows = yield* selectShellThreadRows(undefined, options); + const worktreeKey = + options?.worktreePath === undefined + ? undefined + : normalizeProjectPathForComparison(options.worktreePath); + const targetThreadRows = (yield* selectShellThreadRows(undefined, options)).filter( + (row) => + worktreeKey === undefined || + (row.worktree_path !== null && + normalizeProjectPathForComparison(row.worktree_path) === worktreeKey), + ); const targetThreadIds = new Set(targetThreadRows.map((row) => ThreadId.make(row.thread_id))); const rowsByThreadId = new Map( targetThreadRows.map((row) => [ThreadId.make(row.thread_id), row] as const), diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts index 938ad7e81eec5..67f7bf51554ff 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts @@ -2263,6 +2263,60 @@ layer("ProviderEventIngestorV2", (it) => { }), ); + it.effect("applies an agent's mode change without undoing newer thread settings", () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const eventSink = yield* EventSink.EventSinkV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const rootEvent = yield* threadCreatedEvent(now); + if (rootEvent.type !== "thread.created") throw new Error("Expected thread fixture"); + // Saved mid-turn: a newer model and effort the reporting turn never saw. + const saved = { + ...modelSelection, + model: "gpt-6.1-sol", + options: [ + { id: "effort", value: "high" }, + { id: "mode", value: "plan" }, + ], + }; + yield* eventSink.write({ + events: [{ ...rootEvent, payload: { ...rootEvent.payload, modelSelection: saved } }], + }); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId: rootEvent.threadId, + }); + const ingest = (instanceId: ProviderInstanceId, from: string) => + ingestor.ingestNormalized({ + providerSessionId, + providerInstanceId: modelSelection.instanceId, + threadId: rootEvent.threadId, + event: { + type: "thread_model_selection.updated", + driver: CODEX_DRIVER, + threadId: rootEvent.threadId, + instanceId, + changes: [{ id: "mode", from, to: "default" }], + }, + }); + assert.deepEqual( + (yield* ingest(modelSelection.instanceId, "plan")).map((stored) => stored.event.type), + ["thread.model-selection-updated"], + ); + assert.deepEqual((yield* projectionStore.getThread(rootEvent.threadId)).modelSelection, { + ...saved, + options: [ + { id: "effort", value: "high" }, + { id: "mode", value: "default" }, + ], + }); + assert.deepEqual(yield* ingest(modelSelection.instanceId, "plan"), []); + assert.deepEqual(yield* ingest(ProviderInstanceId.make("other-instance"), "default"), []); + }), + ); + it.effect( "recovers a missing Claude child once and preserves saved metadata on later recovery", () => diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index e036bbe8994c1..118a13a334266 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -497,6 +497,37 @@ export const layer: Layer.Layer< }), ]; } + case "thread_model_selection.updated": { + const { instanceId, changes } = input.event; + const thread = yield* projections.getThread(input.event.threadId).pipe( + Effect.catchTags({ + ProjectionStoreThreadNotFoundError: () => Effect.succeed(null), + }), + ); + const current = thread?.modelSelection; + if (thread === null || current?.instanceId !== instanceId || !current.options) { + return []; + } + let changed = false; + const options = current.options.map((option) => { + const change = changes.find( + (candidate) => candidate.id === option.id && candidate.from === option.value, + ); + if (change === undefined) return option; + changed = true; + return { ...option, value: change.to }; + }); + if (!changed) return []; + const now = yield* DateTime.now; + return [ + yield* makeDomainEvent(input, { + type: "thread.model-selection-updated", + threadId: thread.id, + payload: { ...thread, modelSelection: { ...current, options }, updatedAt: now }, + occurredAt: now, + }), + ]; + } case "provider_session.updated": return [ yield* makeDomainEvent(input, { @@ -652,9 +683,10 @@ export const layer: Layer.Layer< } case "background_work.updated": return []; + case "background_work.lost": case "command_output.delta": case "prompt_suggestion.updated": - // The session manager serves these to clients before ingestion. + // The session manager handles these before ingestion. return []; case "turn.terminal": const dismissed = yield* dismissNativeUserInputs( @@ -884,7 +916,9 @@ export const layer: Layer.Layer< (effect) => input.event.type === "app_thread.created" ? threadCommands.withLock(input.event.appThread.id, effect) - : effect, + : input.event.type === "thread_model_selection.updated" + ? threadCommands.withLock(input.event.threadId, effect) + : effect, ), ), }); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 297677bd5f520..dd573acb1fe17 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -1224,7 +1224,12 @@ export const layerWithOptions = ( // Like restart recovery: an unexpected exit records the work it cancelled on the run that // started it and wakes that run, so the agent restarts awaited work instead of waiting on it. const writeReleasedWorkNote = Effect.fn("ProviderSessionManager.writeReleasedWorkNote")( - function* (released: ReleasedProviderThread) { + function* ( + released: Pick< + ReleasedProviderThread, + "threadId" | "providerSessionId" | "providerThreadId" | "lostTasks" | "lostItems" + >, + ) { const { threadId, providerSessionId, lostTasks, lostItems } = released; if (lostTasks.length === 0 && lostItems.length === 0) return; const { runs, turnItems } = yield* projectionStore.getThreadRecords( @@ -2933,6 +2938,26 @@ export const layerWithOptions = ( if (nativeEvent.type === "command_output.delta") { return commandOutput.append(nativeEvent); } + // A query process can exit under a live session, after the run's last event. + if (nativeEvent.type === "background_work.lost") { + return writeReleasedWorkNote({ + threadId: nativeEvent.threadId, + providerSessionId: entry.runtime.providerSessionId, + providerThreadId: nativeEvent.providerThreadId, + lostTasks: nativeEvent.tasks, + lostItems: [], + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: entry.runtime.driver, + providerSessionId: entry.runtime.providerSessionId, + raisedByT3: true, + cause, + }), + ), + ); + } if (nativeEvent.type === "prompt_suggestion.updated") { return SubscriptionRef.update(promptSuggestionStore, (current) => { const next = new Map(current); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 4bf6e71397fe5..ef9bd2bb32712 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -2289,6 +2289,27 @@ effectIt.effect("refuses unsupported resume instead of manufacturing a user prom }), ); +effectIt.effect.each([ + { contextRun: "current" }, + { contextRun: "failed", switchedProvider: true }, +] as const)( + "a resume that carries pending context asks a provider without native resume to continue: %j", + (sideChat) => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "", + manualContinuation: true, + nativeResumeUnsupported: true, + sideChat, + }); + yield* harness.start; + expect(harness.settledRuns).toEqual([]); + expect(harness.startTurn.mock.calls.map(([turn]) => turn.message.text)).toEqual([ + withInlineContext("SIDE_CHAT_CONTEXT", "Continue where you left off."), + ]); + }), +); + effectIt.effect.each([ { contextRun: "current", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, { contextRun: "failed", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, @@ -2526,7 +2547,7 @@ effectIt.effect.each( { ...choice, resuming: true }, ]), )( - "$goalDriver goal prompts defer switched-provider history only with native support: $nativeGoals, resuming: $resuming", + "$goalDriver goal prompts go verbatim whether or not goals are native: $nativeGoals, resuming: $resuming", ({ goalDriver, nativeGoals, resuming }) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ @@ -2549,11 +2570,7 @@ effectIt.effect.each( } harness.tryHandlePromptCommand.mockReturnValue(Effect.succeed(false)); yield* harness.start; - expect(harness.startTurn.mock.calls[0]?.[0].message.text.includes("SIDE_CHAT_CONTEXT")).toBe( - !nativeGoals, - ); - if (nativeGoals) - expect(harness.startTurn.mock.calls[0]?.[0].message.text).toBe("/goal all tests pass"); + expect(harness.startTurn.mock.calls[0]?.[0].message.text).toBe("/goal all tests pass"); }), ); @@ -3146,6 +3163,40 @@ effectIt.effect("leaves the run starting when a session-open failure will be ret }), ); +effectIt.effect("fails rather than retries a provider thread request with an unknown outcome", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + ensureThreadFailure: { _tag: "CodexAppServerUnresponsiveError", method: "thread/start" }, + }); + + yield* harness.startWithRetry; + + expect(harness.startRootRun).not.toHaveBeenCalled(); + expect(harness.projection().runs.at(-1)?.status).toBe("failed"); + }), +); + +effectIt.effect("fails rather than starts a fresh thread when a resume outcome is unknown", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + resumeFailure: new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: ProviderDriverKind.make("codex"), + providerSessionId: ProviderSessionId.make("resume-provider-session"), + cause: { _tag: "CodexAppServerUnresponsiveError", method: "thread/resume" }, + }), + }); + + const exit = yield* Effect.exit(harness.startWithRetry); + + expect(exit._tag).toBe("Success"); + expect(harness.fallbackEnsureThread).not.toHaveBeenCalled(); + expect(harness.startRootRun).not.toHaveBeenCalled(); + expect(harness.projection().runs.at(-1)?.status).toBe("failed"); + }), +); + effectIt.effect("fails the run without a retry when the provider needs sign-in", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index e47e88eda09a0..1cb77e387f950 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -15,7 +15,7 @@ import { type OrchestrationV2RunAttempt, type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, - isCompactionCommandMessage, + isDeliveredProviderTurn, parseGoalCommand, RunId, RunAttemptId, @@ -32,6 +32,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; import { @@ -60,7 +61,11 @@ import { historicalMessage, latestNativeContextUsage, } from "@t3tools/provider-core/server/handoffBudget"; -import { deliverContextHandoffs, withInlineContext } from "./ContextHandoffDelivery.ts"; +import { + deliverContextHandoffs, + isSlashCommandMessage, + withInlineContext, +} from "./ContextHandoffDelivery.ts"; import { isProviderCommand, outputInstructions } from "./runOutput.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -78,7 +83,9 @@ import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; import { isRestartNoteContinuation, pendingRestartCancelledBackgroundWork, + pendingStoppedDelegatedTasks, restartCancelledBackgroundWorkNote, + stoppedDelegatedTasksNote, } from "./RestartBackgroundNote.ts"; export class ProviderTurnStartError extends Schema.TaggedError()( @@ -158,6 +165,13 @@ const refusedBeforePrompt = (error: unknown): boolean => error.detail === CLAUDE_QUERY_ENDED_BEFORE_TURN_DETAIL) || (Predicate.hasProperty(error, "cause") && refusedBeforePrompt(error.cause)); +// The provider may have acted on a request it never answered, so a retry could duplicate it. +const OUTCOME_UNKNOWN_TAGS = ["CodexAppServerUnresponsiveError"] as const; + +const outcomeUnknown = (error: unknown): boolean => + OUTCOME_UNKNOWN_TAGS.some((tag) => Predicate.isTagged(error, tag)) || + (Predicate.hasProperty(error, "cause") && outcomeUnknown(error.cause)); + /** * Whether a non-truncating provider's native session lost the conversation kept before `run`. * Rollback resets it: the newest accepted turn was rolled back (works without legacy-missing @@ -173,7 +187,9 @@ const nativeSessionMissesKeptTurns = ( ): boolean => { const nativeId = providerThread.nativeThreadRef?.nativeId; if (nativeId === undefined) return false; - const acceptedAttemptIds = new Set(projection.providerTurns.map((turn) => turn.runAttemptId)); + const acceptedAttemptIds = new Set( + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); const accepted = projection.attempts.filter((attempt) => acceptedAttemptIds.has(attempt.id)); const runsById = new Map(projection.runs.map((source) => [source.id, source])); const ordinalOf = (attempt: OrchestrationV2RunAttempt) => @@ -404,12 +420,22 @@ export const layer: Layer.Layer< return { ...session, startTurn: (input: Parameters[0]) => start(input), - ...(session.resumeTurn === undefined - ? {} - : { - resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => - start(ProviderAdapter.resumeTurnInput(input)), - }), + // Pending context can prompt a resume, so even a session without native resume takes one. + resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => + session.resumeTurn === undefined && deliver === undefined + ? Effect.fail( + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: session.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause: new ProviderAdapter.ProviderResumeUnsupportedError({ + driver: session.driver, + providerThreadId: input.providerThread.id, + }), + }), + ) + : start(ProviderAdapter.resumeTurnInput(input)), ...(session.compactThread === undefined ? {} : { @@ -570,11 +596,10 @@ export const layer: Layer.Layer< )) || (source.status === "completed" && handoff.delivery === undefined && - // Compaction and /goal turns defer history to the next turn. + // Slash command turns defer history to the next turn. projection.messages.some( (message) => - message.id === source.userMessageId && - (isCompactionCommandMessage(message) || parseGoalCommand(message) !== null), + message.id === source.userMessageId && isSlashCommandMessage(message), ))), ))); const isSideChatHandoff = (handoff: OrchestrationV2ContextHandoff) => @@ -980,7 +1005,9 @@ export const layer: Layer.Layer< ) { const loaded = yield* Effect.result(load); if (loaded._tag === "Success") return loaded.success; - if (input.willRetry === true) return yield* loaded.failure; + if (input.willRetry === true && !outcomeUnknown(loaded.failure)) { + return yield* loaded.failure; + } yield* settleStartFailure({ signal: "provider-thread-load-failure", title: "Provider turn failed to start", @@ -997,7 +1024,7 @@ export const layer: Layer.Layer< records: providerMessage.context?.records ?? [], }), ); - // Native goal commands go verbatim; handoff history waits a turn. + const slashCommand = isSlashCommandMessage(providerMessage); const goalDriver = session.driver === "codex" || session.driver === "claudeAgent" || @@ -1015,26 +1042,50 @@ export const layer: Layer.Layer< projection.providerTurns, projection.attempts, ); + let compactionMessageIdSet: ReadonlySet | undefined; + const compactionMessageIds = () => + (compactionMessageIdSet ??= new Set( + projection.messages.filter(isSlashCommandMessage).map((candidate) => candidate.id), + )); const restartCancelledWork = pendingRestartCancelledBackgroundWork({ runs: projection.runs, providerTurns: projection.providerTurns, - compactionMessageIds: () => - new Set( - projection.messages - .filter( - (candidate) => - isCompactionCommandMessage(candidate) || - (goalDriver && parseGoalCommand(candidate) !== null), - ) - .map((candidate) => candidate.id), - ), + compactionMessageIds, run, attempts: projection.attempts, }); - const restartNote = + // The turn start context omits settled tasks, so read them only after a Stop disposed some. + // A failed read fails the start: a turn that ran without the note would count as telling it. + const stoppedRunIds = projection.runs + .filter( + (source) => + source.providerThreadId === run.providerThreadId && + source.delegatedCompletion?.disposition === "stopped", + ) + .map((source) => source.id); + const stoppedTasks = + stoppedRunIds.length === 0 || compactionMessageIds().has(run.userMessageId) + ? [] + : pendingStoppedDelegatedTasks({ + providerThreadId: run.providerThreadId, + runs: projection.runs, + providerTurns: projection.providerTurns, + attempts: projection.attempts, + compactionMessageIds: compactionMessageIds(), + subagents: (yield* projectionStore.getThreadRecords( + projection.thread.id, + ["subagents"], + { subagentRunIds: stoppedRunIds }, + )).subagents, + }); + const restartNote = [ restartCancelledWork.length === 0 ? "" - : restartCancelledBackgroundWorkNote(restartCancelledWork); + : restartCancelledBackgroundWorkNote(restartCancelledWork), + stoppedTasks.length === 0 ? "" : stoppedDelegatedTasksNote(stoppedTasks), + ] + .filter((part) => part !== "") + .join("\n\n"); const tokenCap = yield* handoffTokenCapConfig.pipe( Effect.orElseSucceed(() => DEFAULT_HANDOFF_TOKEN_CAP), ); @@ -1087,7 +1138,12 @@ export const layer: Layer.Layer< ...settledHandoffs.flatMap((handoff) => handoff.delivery?.omittedItemIds ?? []), ]); const deliveredAttemptIds = new Set( - projection.providerTurns.map((turn) => turn.runAttemptId), + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); + const droppedAttemptIds = new Set( + projection.providerTurns + .filter((turn) => !isDeliveredProviderTurn(turn)) + .map((turn) => turn.runAttemptId), ); const acceptedAttempts = projection.attempts.filter( (source) => @@ -1159,7 +1215,9 @@ export const layer: Layer.Layer< (source) => source.ordinal < run.ordinal && source.providerThreadId === providerThread.id && - (source.status === "failed" || source.status === "interrupted") && + (source.status === "failed" || + source.status === "interrupted" || + (source.status === "cancelled" && droppedAttemptIds.has(source.activeAttemptId))) && !deliveredAttemptIds.has(source.activeAttemptId), ); const missedRunIds = new Set(missedRuns.map((source) => source.id)); @@ -1225,7 +1283,7 @@ export const layer: Layer.Layer< }), ]; // History delivery (inline or injected) is text only, so missed images ride on prompts - // until a later run's is accepted. Compaction and /goal starts carry none. A missed run's + // until a later run's is accepted. Slash command starts carry none. A missed run's // own accepted attempt predates its unsent steering input, so it does not count. const runsById = new Map(projection.runs.map((source) => [source.id, source])); const messagesById = new Map(projection.messages.map((message) => [message.id, message])); @@ -1235,12 +1293,7 @@ export const layer: Layer.Layer< const source = runsById.get(attempt.runId); if (source === undefined) continue; const message = messagesById.get(source.userMessageId); - if ( - message !== undefined && - (isCompactionCommandMessage(message) || - (goalDriver && parseGoalCommand(message) !== null)) - ) - continue; + if (message !== undefined && isSlashCommandMessage(message)) continue; lastPromptOrdinal = Math.max(lastPromptOrdinal, source.ordinal); } const attachments = missedHistory.flatMap((item) => @@ -1536,7 +1589,9 @@ export const layer: Layer.Layer< const rejectedHistory = yield* Effect.gen(function* () { if (session.driver !== "codex") return false; const acceptedAttemptIds = new Set( - projection.providerTurns.map((turn) => turn.runAttemptId), + projection.providerTurns + .filter(isDeliveredProviderTurn) + .map((turn) => turn.runAttemptId), ); const previous = projection.runs.findLast( (source) => @@ -1605,7 +1660,9 @@ export const layer: Layer.Layer< // Dispatch prepares no import handoff for a session import: its history is in the native session. const importedNativeSession = projection.thread.historyOrigin === "v1_import" && - !projection.providerTurns.some((turn) => turn.providerThreadId === providerThread.id) && + !projection.providerTurns.some( + (turn) => turn.providerThreadId === providerThread.id && isDeliveredProviderTurn(turn), + ) && !projection.contextHandoffs.some( (handoff) => handoff.toProviderThreadId === providerThread.id && @@ -1643,7 +1700,7 @@ export const layer: Layer.Layer< handoffs: [...handoffs, ...resumedRetryHandoff.handoffs], providerThread: { ...resumed.success, id: providerThread.id }, budget: context.budget, - deferInline: isCompactionCommandMessage(providerMessage) || goalCommand, + deferInline: slashCommand, alreadyDeliveredItemIds: context.deliveredItemIds, persist: () => Effect.void, }).pipe( @@ -1670,11 +1727,12 @@ export const layer: Layer.Layer< resumedHandoffContext = undefined; resumedRetryHandoff = undefined; if (!(yield* isCurrentAttemptInStatus("starting"))) return undefined; - // Another client is still writing to the native thread. A fresh - // session here would silently split the conversation from it. + // Another client is still writing to the native thread, or the provider may have + // resumed it without answering. A fresh session would split the conversation. if ( resumed._tag === "Failure" && - resumed.failure._tag === "ProviderAdapterThreadInUseError" + (resumed.failure._tag === "ProviderAdapterThreadInUseError" || + outcomeUnknown(resumed.failure)) ) { return yield* loadFromProvider(Effect.fail(resumed.failure)); } @@ -1844,7 +1902,21 @@ export const layer: Layer.Layer< legacyInputRunIds, budget, } = handoffContext; - if (manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined) { + const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); + const carriesPendingContext = + effectiveHandoffs.length > 0 || + retryHandoff.handoffs.length > 0 || + retryHandoff.attachments.length > 0 || + sideChatHandoff !== undefined || + restartNote !== "" || + noteContinuation; + // Pending context turns the resume into a prompted turn, which needs no native resume. + if ( + manualResume && + unsentResumeMessage === undefined && + session.resumeTurn === undefined && + !carriesPendingContext + ) { yield* settleStartFailure({ signal: "resume-unsupported", title: "Native resume is unavailable", @@ -1855,7 +1927,6 @@ export const layer: Layer.Layer< }); return; } - const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, contextUsage: handoffUsage, @@ -2025,11 +2096,15 @@ export const layer: Layer.Layer< ], }); }); + let inlineDeliveredHandoffs: ReadonlyArray = []; + let promptDroppedOnTerminal = false; + const inlineDeliveryLock = yield* Semaphore.make(1); + const retryHandoffIds = new Set(retryHandoff.handoffs.map((handoff) => handoff.id)); const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")( function* (turnInput: Parameters[0], compact = false) { const delivery = yield* deliverContextHandoffs({ handoffs: [...effectiveHandoffs, ...retryHandoff.handoffs], - deferInline: compact || goalCommand, + deferInline: compact || slashCommand, providerThread: runningProviderThread, budget, alreadyDeliveredItemIds: deliveredItemIds, @@ -2048,9 +2123,18 @@ export const layer: Layer.Layer< const start = compact ? session.compactThread! : session.startTurn; // Like history, the side chat context waits for a turn that sends a prompt. const sideChatContext = - sideChatHandoff === undefined || compact || goalCommand + sideChatHandoff === undefined || compact || slashCommand ? "" : sideChatHandoff.summaryText; + // Record inline handoffs before startTurn so an immediate dropped terminal can restore them. + inlineDeliveredHandoffs = [ + ...delivery.inlineHandoffs.map((handoff) => + retryHandoffIds.has(handoff.id) + ? { ...handoff, status: "superseded" as const } + : handoff, + ), + ...(sideChatContext === "" || sideChatHandoff === undefined ? [] : [sideChatHandoff]), + ]; const context = [delivery.context, sideChatContext, restartNote] .filter((part) => part !== "") .join("\n\n"); @@ -2059,7 +2143,7 @@ export const layer: Layer.Layer< const { resume: _resume, ...contextInput } = startInput; const { message: resumeMessage, resume: _resumeIntent, ...resumeInput } = startInput; const missedAttachments = - compact || goalCommand + compact || slashCommand ? [] : retryHandoff.attachments.filter( (missed) => @@ -2070,10 +2154,16 @@ export const layer: Layer.Layer< // A resume that must be prompted still needs a request, or the agent has nothing to do. const requestText = turnInput.resume && prompted && userText === "" ? RESUME_PROMPT : userText; - const text = goalCommand ? userText : withInlineContext(context, requestText); + const text = slashCommand ? userText : withInlineContext(context, requestText); const operation = - turnInput.resume && !prompted && session.resumeTurn !== undefined - ? session.resumeTurn({ ...resumeInput, messageId: resumeMessage.messageId }) + turnInput.resume && !prompted + ? (session.resumeTurn?.({ ...resumeInput, messageId: resumeMessage.messageId }) ?? + Effect.fail( + new ProviderAdapter.ProviderResumeUnsupportedError({ + driver: session.driver, + providerThreadId: providerThread.id, + }), + )) : start({ ...(prompted ? contextInput : startInput), message: { @@ -2101,31 +2191,39 @@ export const layer: Layer.Layer< : Effect.void, ), ); - // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. - const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId; - yield* Effect.forEach( - [ - delivery.delivered, - ...(sideChatContext === "" || sideChatHandoff === undefined || nativeThreadId == null - ? [] - : [ - persistHandoff({ - ...sideChatHandoff, - toProviderThreadId: runningProviderThread.id, - delivery: { nativeThreadId, status: "inline" as const, itemIds: [] }, - }), - ]), - ], - (record) => - record.pipe( - Effect.catchCause(() => - Effect.logWarning("Failed to record accepted context handoff delivery", { - runId: run.id, - deliveryStatus: "pending", - }), - ), - ), - { discard: true }, + // Serialize acceptance writes against dropped-terminal restoration so neither overwrites the other. + yield* inlineDeliveryLock.withPermits(1)( + Effect.gen(function* () { + if (promptDroppedOnTerminal) return; + // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. + const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId; + yield* Effect.forEach( + [ + delivery.delivered, + ...(sideChatContext === "" || + sideChatHandoff === undefined || + nativeThreadId == null + ? [] + : [ + persistHandoff({ + ...sideChatHandoff, + toProviderThreadId: runningProviderThread.id, + delivery: { nativeThreadId, status: "inline" as const, itemIds: [] }, + }), + ]), + ], + (record) => + record.pipe( + Effect.catchCause(() => + Effect.logWarning("Failed to record accepted context handoff delivery", { + runId: run.id, + deliveryStatus: "pending", + }), + ), + ), + { discard: true }, + ); + }), ); }, Effect.mapError((cause) => @@ -2140,15 +2238,9 @@ export const layer: Layer.Layer< }), ), ); - const deliverySession = - effectiveHandoffs.length === 0 && - retryHandoff.handoffs.length === 0 && - retryHandoff.attachments.length === 0 && - sideChatHandoff === undefined && - restartNote === "" && - !noteContinuation - ? session - : makeDeliverySession(session, startWithHandoffs); + const deliverySession = carriesPendingContext + ? makeDeliverySession(session, startWithHandoffs) + : session; return runExecution.startRootRun({ commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`), appThread: projection.thread, @@ -2186,6 +2278,13 @@ export const layer: Layer.Layer< hasUnpairedRunInterruptRequest: runControls.hasUnpairedRunInterruptRequest, loadRunInterruptReason: runControls.loadRunInterruptReason, hasWorkspaceMoved: runControls.hasWorkspaceMoved, + loadDroppedInlineHandoffs: () => + inlineDeliveryLock.withPermits(1)( + Effect.sync(() => { + promptDroppedOnTerminal = true; + return inlineDeliveredHandoffs; + }), + ), loadUnsettledWork: runControls.loadUnsettledWork, message: { messageId: message.id, diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts index b5b3a033789dd..bd5b016fdc673 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts @@ -1,10 +1,12 @@ import { assert, it } from "@effect/vitest"; import { MessageId, + NodeId, ProviderThreadId, RunAttemptId, RunId, type OrchestrationV2Run, + type OrchestrationV2Subagent, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -14,7 +16,9 @@ import { isAwaitedWork, isRestartNoteContinuation, pendingRestartCancelledBackgroundWork, + pendingStoppedDelegatedTasks, restartContinuationNote, + stoppedDelegatedTasksNote, mergeRestartCancelledBackgroundWork, } from "./RestartBackgroundNote.ts"; @@ -277,3 +281,51 @@ it("counts a prompted mid-turn or chained continuation as delivering the note", [], ); }); + +// regression: #34401 Stop interrupted a parent's delegated tasks without telling its agent +it("tells the next completed turn about delegated tasks its Stop interrupted, once", () => { + const at = (minute: number) => DateTime.makeUnsafe(`2026-10-03T10:0${minute}:00.000Z`); + const spawning = run(1, claudeThread, { + requestedAt: at(0), + delegatedCompletion: { disposition: "stopped", nextGeneration: 1, delivery: null }, + }); + const task = (id: string, extra: Partial = {}) => + ({ + id: NodeId.make(id), + runId: spawning.id, + origin: "app_owned", + prompt: `Run ${id}.`, + title: null, + status: "interrupted", + completionDelivery: { state: "disposed", observedByRunId: null }, + completedAt: at(1), + ...extra, + }) as OrchestrationV2Subagent; + const stopped = task("stopped", { title: "Build A" }); + const subagents = [ + stopped, + task("cancelled", { cancelledRunId: RunId.make("run:child") }), + task("finished", { status: "completed" }), + task("delivered", { completionDelivery: { state: "delivered", observedByRunId: null } }), + ]; + const pending = (runs: ReadonlyArray, providerThreadId = claudeThread) => + pendingStoppedDelegatedTasks({ + providerThreadId, + runs, + providerTurns: runs.map(turnFor), + attempts: runs.map((source) => ({ id: source.activeAttemptId!, runId: source.id })), + subagents, + compactionMessageIds: new Set(), + }); + + assert.deepEqual(pending([spawning]), [stopped]); + // A /clear turn starts a fresh provider thread that never saw the stopped tasks. + assert.deepEqual(pending([spawning], codexThread), []); + assert.equal(stoppedDelegatedTasksNote([stopped]).split("\n")[1], "- Build A (task stopped)"); + // Requested while the task was still settling, so its turn start could not see it. + const racing = run(2, claudeThread, { requestedAt: at(0), startedAt: at(2) }); + assert.deepEqual(pending([spawning, racing]), [stopped]); + assert.deepEqual(pending([spawning, racing, run(3, claudeThread, { requestedAt: at(2) })]), []); + // A fresh-context turn on another provider thread never carried the note. + assert.deepEqual(pending([spawning, run(3, codexThread, { requestedAt: at(2) })]), [stopped]); +}); diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index ceaf2fd5de54b..878392b8377c6 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -1,17 +1,19 @@ -import type { - NodeId, - OrchestrationV2ConversationMessage, - OrchestrationV2PendingBackgroundTask, - OrchestrationV2ProviderThread, - OrchestrationV2ProviderTurn, - OrchestrationV2RestartCancelledBackgroundWork, - OrchestrationV2Run, - OrchestrationV2RunAttempt, - OrchestrationV2Subagent, - OrchestrationV2TurnItem, +import { + isDeliveredProviderTurn, + type NodeId, + type OrchestrationV2ConversationMessage, + type OrchestrationV2PendingBackgroundTask, + type OrchestrationV2ProviderThread, + type OrchestrationV2ProviderTurn, + type OrchestrationV2RestartCancelledBackgroundWork, + type OrchestrationV2Run, + type OrchestrationV2RunAttempt, + type OrchestrationV2Subagent, + type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import { subagentHoldsCompletion } from "@t3tools/provider-core/server/subagentProjection"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; +import * as DateTime from "effect/DateTime"; import { latestRootProviderFailure, runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; type Work = OrchestrationV2RestartCancelledBackgroundWork; @@ -149,9 +151,80 @@ export function restartCancelledBackgroundWorkNote( ].join("\n"); } +/** + * Delegated tasks a Stop on this provider thread interrupted, until a turn requested after they + * ended completes. A run's turn start reads tasks after its request, but can record startedAt + * later. A fresh context starts a new provider thread, so it never inherits the note. + */ +export function pendingStoppedDelegatedTasks(input: { + readonly providerThreadId: OrchestrationV2Run["providerThreadId"]; + readonly runs: ReadonlyArray; + readonly providerTurns: ReadonlyArray>; + readonly attempts: ReadonlyArray; + readonly subagents: ReadonlyArray; + readonly compactionMessageIds: ReadonlySet; +}): ReadonlyArray { + const stoppedRunIds = new Set( + input.runs + .filter( + (run) => + run.providerThreadId === input.providerThreadId && + run.delegatedCompletion?.disposition === "stopped", + ) + .map((run) => run.id), + ); + if (stoppedRunIds.size === 0) return []; + const completedAttemptIds = new Set( + input.providerTurns + .filter((turn) => turn.status === "completed") + .map((turn) => turn.runAttemptId), + ); + const toldRunRequests = input.runs + .filter( + (run) => + run.providerThreadId === input.providerThreadId && + !input.compactionMessageIds.has(run.userMessageId) && + input.attempts.some( + (attempt) => attempt.runId === run.id && completedAttemptIds.has(attempt.id), + ), + ) + .map((run) => DateTime.toEpochMillis(run.requestedAt)); + return input.subagents.filter( + (task) => + task.origin === "app_owned" && + task.runId !== null && + stoppedRunIds.has(task.runId) && + task.status === "interrupted" && + task.cancelledRunId === undefined && + task.completionDelivery?.state === "disposed" && + task.completedAt !== null && + !toldRunRequests.some( + (requestedAt) => requestedAt > DateTime.toEpochMillis(task.completedAt!), + ), + ); +} + +export function stoppedDelegatedTasksNote(tasks: ReadonlyArray): string { + const omitted = tasks.length - MAX_NOTE_ENTRIES; + return [ + "Note: Stop on this thread also stopped these delegated tasks before they finished. They will not report back on their own, so check them with task_status and start again what you still need:", + ...tasks + .slice(0, MAX_NOTE_ENTRIES) + .map( + (task) => + `- ${labelWithId( + compactLabel(task.title) === undefined ? task.prompt : task.title, + "delegated task", + ` (task ${task.id})`, + )}`, + ), + ...(omitted > 0 ? [`- and ${omitted} more`] : []), + ].join("\n"); +} + type ProviderTurnState = Pick< OrchestrationV2ProviderTurn, - "runAttemptId" | "providerThreadId" | "status" + "runAttemptId" | "providerThreadId" | "status" | "promptDropped" >; export function isRestartNoteSource( @@ -307,12 +380,14 @@ export function delegatedTaskResultRun( /** The provider never accepted this continuation's prompt, so starting it again repeats nothing. */ export function continuationFailedBeforePrompt( run: Pick, - providerTurns: ReadonlyArray>, + providerTurns: ReadonlyArray>, ): boolean { return ( run.status === "failed" && run.restartContinuationOfRunId !== undefined && - !providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId) + !providerTurns.some( + (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn), + ) ); } @@ -323,7 +398,9 @@ export function continuationStartRetryDelayMs( run: OrchestrationV2Run, projection: { readonly runs: ReadonlyArray; - readonly providerTurns: ReadonlyArray>; + readonly providerTurns: ReadonlyArray< + Pick + >; readonly turnItems: Parameters[1]; }, ): number | undefined { diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index a23a3fdf87bff..3667867904ec9 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -8,6 +8,7 @@ import { NodeId, type OrchestrationV2AppThread, type OrchestrationV2CheckpointScope, + type OrchestrationV2ContextHandoff, type OrchestrationV2DomainEvent, type OrchestrationV2ExecutionNode, type OrchestrationV2PendingBackgroundTask, @@ -3595,6 +3596,48 @@ it.effect("ends a running root command when the provider stream fails mid-turn", }), ); +it.effect("fails the run when a released session's interrupt exits interrupted", () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const key = "released-session-interrupted-interrupt"; + const { observed, finalEvents } = yield* captureRootRunTermination({ + key, + shouldFinalizeRun: () => Effect.succeed(true), + events: (ids) => + Stream.make({ + type: "provider_turn.updated" as const, + driver, + providerTurn: { + id: ids.rootProviderTurnId, + providerThreadId: ids.providerThreadId, + nodeId: ids.rootNodeId, + runAttemptId: ids.attemptId, + nativeTurnRef: null, + ordinal: 1, + status: "running" as const, + startedAt: now, + completedAt: null, + }, + }).pipe( + Stream.concat( + Stream.fail( + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver, + providerSessionId: ProviderSessionId.make(`session:${key}`), + raisedByT3: true, + cause: "Provider sign-in changed.", + }), + ), + ), + ), + // An ACP session whose scope is already closing interrupts the join. + interruptTurn: () => Effect.interrupt, + }); + assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]); + assert.isTrue(finalEvents.some((event) => event.type === "run.updated")); + }), +); + it.effect("keeps a running root command open when a write fails under a live provider", () => Effect.gen(function* () { const key = "write-error-running-command"; @@ -3702,6 +3745,49 @@ it.effect.each([ }), ); +it.effect("restores dropped inline handoffs when ingestion fails before the terminal", () => + Effect.gen(function* () { + const key = "dropped-turn-ingest-error"; + const ids = backgroundScenarioIds(key); + const handoff = { id: `handoff:${key}` } as unknown as OrchestrationV2ContextHandoff; + const { finalEvents } = yield* captureRootRunTermination({ + key, + shouldFinalizeRun: () => Effect.succeed(true), + loadDroppedInlineHandoffs: () => Effect.succeed([handoff]), + events: () => + Stream.make({ + type: "provider_turn.updated" as const, + driver, + threadId: ids.threadId, + providerTurn: { + id: ids.rootProviderTurnId, + providerThreadId: ids.providerThreadId, + runAttemptId: ids.attemptId, + ordinal: 1, + status: "failed", + promptDropped: true, + } as OrchestrationV2ProviderTurn, + }), + ingestNormalized: ({ event }) => + event.type === "provider_turn.updated" + ? Effect.fail( + new ProviderEventIngestor.ProviderEventPublishError({ + providerSessionId: ProviderSessionId.make(`session:${key}`), + eventCount: 1, + cause: new Error("SQLITE_FULL: database or disk is full"), + }), + ) + : Effect.succeed([]), + }); + assert.deepEqual( + finalEvents.flatMap((event) => + event.type === "context-handoff.updated" ? [event.payload.id] : [], + ), + [handoff.id], + ); + }), +); + it.effect("does not interrupt a provider when ingestion fails before the root turn is known", () => Effect.gen(function* () { const interrupts = yield* Ref.make(0); @@ -3989,6 +4075,7 @@ function captureRootRunTermination(input: { readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly hasWorkspaceMoved?: () => Effect.Effect; readonly loadRunInterruptReason?: () => Effect.Effect; + readonly loadDroppedInlineHandoffs?: RunExecutionService.RunExecutionServiceV2StartRootRunInput["loadDroppedInlineHandoffs"]; readonly hasPendingBackgroundWorkForThread?: ProviderAdapter.ProviderAdapterV2SessionRuntime["hasPendingBackgroundWorkForThread"]; readonly seedOpenSubagent?: boolean; readonly events?: ( @@ -4235,6 +4322,9 @@ function captureRootRunTermination(input: { ...(input.hasWorkspaceMoved === undefined ? {} : { hasWorkspaceMoved: input.hasWorkspaceMoved }), + ...(input.loadDroppedInlineHandoffs === undefined + ? {} + : { loadDroppedInlineHandoffs: input.loadDroppedInlineHandoffs }), message: { messageId: MessageId.make(`message:${input.key}`), text: input.messageText ?? "interrupt projection", diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 1bc83f639d5ae..a5eeaa9cb8b95 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -9,6 +9,7 @@ import { type NodeId, type OrchestrationV2AppThread, type OrchestrationV2CheckpointScope, + type OrchestrationV2ContextHandoff, type OrchestrationV2DomainEvent, type OrchestrationV2ExecutionNode, type OrchestrationV2ProviderFailure, @@ -459,6 +460,8 @@ export function routeProviderEvent( }, ]; } + case "thread_model_selection.updated": + return [event.threadId === input.threadId, state]; case "provider_thread.updated": { const belongs = state.ownedProviderThreadIds.has(event.providerThread.id) || @@ -586,9 +589,10 @@ export function routeProviderEvent( ]; case "background_work.updated": return [state.ownedProviderTurns.has(event.providerTurnId), state]; + case "background_work.lost": case "command_output.delta": case "prompt_suggestion.updated": - // The session manager serves these to clients directly; runs never see them. + // The session manager handles these itself; runs never see them. return [false, state]; case "turn.terminal": return event.providerTurnId === state.rootProviderTurnId @@ -658,6 +662,11 @@ export interface RunExecutionServiceV2StartRootRunInput { readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly loadRunInterruptReason?: () => Effect.Effect; readonly hasWorkspaceMoved?: () => Effect.Effect; + /** Restores inline context handoffs if the provider drops this turn's prompt before persisting it. */ + readonly loadDroppedInlineHandoffs?: () => Effect.Effect< + ReadonlyArray, + never + >; /** * Stored rows of a thread's unsettled work. Work a dead runtime left is ended from these, since * Stop may have settled it after the snapshots this run holds. @@ -736,6 +745,7 @@ export const layer: Layer.Layer< readonly abandonedProviderTurn?: OrchestrationV2ProviderTurn; // Stored root tool calls still open when the provider runtime was lost; nothing else ends them. readonly lostToolCalls?: ReadonlyArray; + readonly restoredHandoffs?: ReadonlyArray; readonly terminal: ProviderTerminalEvent; readonly completedAt?: DateTime.Utc; readonly failureItemPersisted: boolean; @@ -752,24 +762,35 @@ export const layer: Layer.Layer< status: input.terminal.status, completedAt, }; + const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId }); + const buildRestoredHandoffEvents = () => + input.terminal.promptDropped === true && + input.restoredHandoffs !== undefined && + input.restoredHandoffs.length > 0 + ? Effect.forEach(input.restoredHandoffs, (handoff) => + Effect.map(allocateEventId(), (id) => ({ + id, + type: "context-handoff.updated" as const, + threadId: input.run.threadId, + runId: input.run.id, + providerInstanceId: input.run.providerInstanceId, + occurredAt: completedAt, + payload: { ...handoff, updatedAt: completedAt }, + })), + ) + : Effect.succeed([]); const shouldFinalizeRun = input.shouldFinalizeRun === undefined ? true : yield* input.shouldFinalizeRun(); if (!shouldFinalizeRun) { - if (input.terminal.status === "interrupted") { - const hasUnpairedRequest = - input.hasUnpairedRunInterruptRequest === undefined - ? false - : yield* input.hasUnpairedRunInterruptRequest(); - if (hasUnpairedRequest) { - const reason = - input.loadRunInterruptReason === undefined - ? undefined - : yield* input.loadRunInterruptReason(); - yield* eventSink.writeWithEffects({ - effects: [], - events: [ + const restoredHandoffEvents = yield* buildRestoredHandoffEvents(); + const unpairedInterruptEvents = + input.terminal.status === "interrupted" && + (input.hasUnpairedRunInterruptRequest === undefined + ? false + : yield* input.hasUnpairedRunInterruptRequest()) + ? [ { - id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }), + id: yield* allocateEventId(), type: "turn-item.updated" as const, threadId: input.run.threadId, runId: input.run.id, @@ -781,18 +802,25 @@ export const layer: Layer.Layer< run: input.run, rootNode: input.rootNode, providerThread: input.providerThread, - reason, + reason: + input.loadRunInterruptReason === undefined + ? undefined + : yield* input.loadRunInterruptReason(), completedAt, }), }, - ], - }); - yield* input.refreshAfterTurn; - } + ] + : []; + const earlyEvents = [...unpairedInterruptEvents, ...restoredHandoffEvents]; + if (earlyEvents.length > 0) { + yield* eventSink.writeWithEffects({ + effects: [], + events: earlyEvents, + }); + yield* input.refreshAfterTurn; } return false; } - const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId }); const reason = input.terminal.status === "interrupted" ? ((input.loadRunInterruptReason === undefined @@ -839,6 +867,7 @@ export const layer: Layer.Layer< status: finalProviderThreadStatus(input.terminal.threadDisposition), updatedAt: completedAt, }; + const restoredHandoffEvents = yield* buildRestoredHandoffEvents(); const runEventId = yield* allocateEventId(); const nodeEventId = yield* allocateEventId(); const providerThreadEventId = yield* allocateEventId(); @@ -1005,6 +1034,7 @@ export const layer: Layer.Layer< occurredAt: completedAt, payload: finalizedProviderThread, }, + ...restoredHandoffEvents, ], } satisfies Parameters[0]; if (input.writeIfRunCurrent !== undefined) { @@ -1031,6 +1061,13 @@ export const layer: Layer.Layer< effects: finalization.effects, }); if (!result.committed) { + if (restoredHandoffEvents.length > 0) { + yield* eventSink.writeWithEffects({ + effects: [], + events: restoredHandoffEvents, + }); + yield* input.refreshAfterTurn; + } return false; } } else { @@ -1275,44 +1312,55 @@ export const layer: Layer.Layer< } const providerThread = yield* Ref.get(latestProviderThread); const openSubagents = yield* Ref.get(openRunOwnedSubagents); - const writeTerminal = (settledTerminal: ProviderTerminalEvent) => - writeFinalRunEvents({ - run: input.run, - rootNode: input.rootNode, - checkpointScope: input.checkpointScope, - providerThread, - attempt: input.attempt, - ...(input.shouldFinalizeRun === undefined - ? {} - : { - shouldFinalizeRun: input.shouldFinalizeRun, - // Stop may commit between the ownership read and this - // terminal write. Gate the events and checkpoint together. - writeIfRunCurrent: { - activeAttemptId: input.attempt.id, - expectedStatus: "running" as const, - unlessInterruptRequested: settledTerminal !== terminal, - }, - }), - ...(input.hasUnpairedRunInterruptRequest === undefined - ? {} - : { - hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest, - }), - ...(input.loadRunInterruptReason === undefined - ? {} - : { loadRunInterruptReason: input.loadRunInterruptReason }), - openRunOwnedSubagents: openSubagents, - openRunOwnedSubagentsTerminal: terminal, - ...(abandonedProviderTurn === undefined ? {} : { abandonedProviderTurn }), - terminal: settledTerminal, - failureItemPersisted: settledTerminal.status === "failed", - refreshAfterTurn, - }).pipe( - Effect.mapError( - (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), + const writeTerminal = Effect.fnUntraced( + function* (settledTerminal: ProviderTerminalEvent) { + const restoredHandoffs = + settledTerminal.promptDropped === true && + input.loadDroppedInlineHandoffs !== undefined + ? yield* input.loadDroppedInlineHandoffs() + : undefined; + return yield* writeFinalRunEvents({ + run: input.run, + rootNode: input.rootNode, + checkpointScope: input.checkpointScope, + providerThread, + attempt: input.attempt, + ...(input.shouldFinalizeRun === undefined + ? {} + : { + shouldFinalizeRun: input.shouldFinalizeRun, + // Stop may commit between the ownership read and this + // terminal write. Gate the events and checkpoint together. + writeIfRunCurrent: { + activeAttemptId: input.attempt.id, + expectedStatus: "running" as const, + unlessInterruptRequested: settledTerminal !== terminal, + }, + }), + ...(input.hasUnpairedRunInterruptRequest === undefined + ? {} + : { + hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest, + }), + ...(input.loadRunInterruptReason === undefined + ? {} + : { loadRunInterruptReason: input.loadRunInterruptReason }), + openRunOwnedSubagents: openSubagents, + openRunOwnedSubagentsTerminal: terminal, + ...(abandonedProviderTurn === undefined ? {} : { abandonedProviderTurn }), + ...(restoredHandoffs === undefined ? {} : { restoredHandoffs }), + terminal: settledTerminal, + failureItemPersisted: settledTerminal.status === "failed", + refreshAfterTurn, + }); + }, + (effect) => + effect.pipe( + Effect.mapError( + (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), + ), ), - ); + ); // A workspace handoff detaches the session and stops the turn that asked // for it: the run completes, while its native subagents still settle // as interrupted. The completed write refuses in the same transaction @@ -2090,13 +2138,13 @@ export const layer: Layer.Layer< }) .pipe( Effect.as(true), - Effect.catchCauseIf( - (interruptCause) => !Cause.hasInterruptsOnly(interruptCause), - (interruptCause) => - Effect.logWarning( - "orchestration V2 failed to interrupt turn after ingestion failure", - { runId: input.run.id, cause: interruptCause }, - ).pipe(Effect.as(false)), + // An adapter whose session scope is closing exits interrupted. That is + // its fiber, not this one: Effect never hands a fiber its own interrupt. + Effect.catchCause((interruptCause) => + Effect.logWarning( + "orchestration V2 failed to interrupt turn after ingestion failure", + { runId: input.run.id, cause: interruptCause }, + ).pipe(Effect.as(false)), ), // A failed interrupt leaves the stored turn running so the next start // retries it. The snapshot is cached before it is published, so it may @@ -2116,6 +2164,13 @@ export const layer: Layer.Layer< : null; const latestItemOrdinal = yield* Ref.get(latestTurnItemOrdinal); const openSubagents = yield* Ref.get(openRunOwnedSubagents); + const droppedPrompt = + (yield* Ref.get(terminalEvent))?.promptDropped === true || + rootProviderTurn?.promptDropped === true; + const recoveredHandoffs = + droppedPrompt && input.loadDroppedInlineHandoffs !== undefined + ? yield* input.loadDroppedInlineHandoffs() + : undefined; const lostToolCalls = runtimeLost ? yield* loadLostRootToolCalls.pipe( Effect.catchCauseIf( @@ -2141,18 +2196,24 @@ export const layer: Layer.Layer< }, openRunOwnedSubagents: openSubagents, ...(abandonedProviderTurn === null ? {} : { abandonedProviderTurn }), + ...(recoveredHandoffs === undefined + ? {} + : { restoredHandoffs: recoveredHandoffs }), lostToolCalls, completedAt, - terminal: makeFailedTerminalEvent( - makeProviderFailure({ - cause: squashed, - message: - knownProviderFailureMessage(squashed) ?? - userFacingDatabaseErrorMessage(squashed), - class: "unknown", - }), - latestItemOrdinal + 1, - ), + terminal: { + ...makeFailedTerminalEvent( + makeProviderFailure({ + cause: squashed, + message: + knownProviderFailureMessage(squashed) ?? + userFacingDatabaseErrorMessage(squashed), + class: "unknown", + }), + latestItemOrdinal + 1, + ), + ...(droppedPrompt ? { promptDropped: true as const } : {}), + }, failureItemPersisted: false, refreshAfterTurn, }).pipe( diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts index 890aa9d97467e..d5bff642383d3 100644 --- a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts +++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts @@ -581,6 +581,22 @@ it.live.each(["pooled", "exclusive"] as const)( Stream.runDrain, Effect.forkScoped, ); + // The continuation starts from an async run.updated reaction, which drain alone does not await. + const continuationRunning = yield* eventSink + .stream({ + threadId, + afterSequence: yield* eventSink.latestSequence({ threadId }), + }) + .pipe( + Stream.map((stored) => stored.event), + Stream.filter( + (event) => + event.type === "provider-turn.updated" && event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); // What t3_worktree_handoff dispatches while the calling turn is still running. const bound = yield* orchestrator.dispatch({ type: "thread.metadata.update", @@ -601,6 +617,7 @@ it.live.each(["pooled", "exclusive"] as const)( ["queued"], ); yield* Fiber.join(settled); + yield* Fiber.join(continuationRunning); yield* worker.drain(); return yield* orchestrator.getThreadProjection(threadId); }).pipe( diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 3ef67192ceb77..04257d91bc9a7 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1363,81 +1363,116 @@ it.effect("restarts the turn for an image when native steering takes text only", }), ); -it.effect("starts a steer that missed the turn on the saved next-turn selection", () => - Effect.gen(function* () { - const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - "steering-selection-follow-up", - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const threadId = yield* startFirstTurn; - const first = started[0]!; - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("steer"), - threadId, - messageId: MessageId.make("message:steer"), - text: "late steer", - attachments: [], - modelSelection: composerSelection, - dispatchMode: { type: "steer_active", targetRunId: first.runId }, - createdBy: "user", - creationSource: "web", - }); - 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, +it.effect.each(["complete", "stop-before-end"] as const)( + "starts a steer that missed the turn in its place on the saved next-turn selection: %s", + (timing) => + Effect.gen(function* () { + const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + `steering-selection-follow-up-${timing}`, ); - const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; - 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(); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const first = started[0]!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("steer"), + threadId, + messageId: MessageId.make("message:steer"), + text: "late steer", + attachments: [], + modelSelection: composerSelection, + dispatchMode: { type: "steer_active", targetRunId: first.runId }, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("queued-later"), + threadId, + messageId: MessageId.make("message:queued-later"), + text: "queued later", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + if (timing === "stop-before-end") { + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop"), + threadId, + runId: first.runId, + holdQueue: true, + }); + } + 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, + ); + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + 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(); + if (timing === "stop-before-end") { + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs + .filter((run) => run.status === "queued") + .toSorted((left, right) => (left.queuePosition ?? 0) - (right.queuePosition ?? 0)); + assert.deepEqual( + queued.map((run) => [run.userMessageId, run.queueHeld === true]), + [ + [MessageId.make("message:steer"), false], + [MessageId.make("message:queued-later"), false], + ], + ); + return; + } + yield* orchestrator.resumeQueuedRuns; + yield* worker.drain(); - const projection = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(steered, []); - assert.equal(started.length, 2); - assert.equal(started[1]?.message.messageId, MessageId.make("message:steer")); - assert.deepEqual(started[1]?.modelSelection, composerSelection); - assert.deepEqual(projection.thread.modelSelection, composerSelection); - const message = projection.turnItems.find( - (item) => - item.type === "user_message" && item.messageId === MessageId.make("message:steer"), - ); - assert.equal(message?.runId, started[1]!.runId); - assert.isAbove( - message!.ordinal, - Math.max( - ...projection.turnItems - .filter((item) => item.runId === first.runId) - .map((item) => item.ordinal), - ), - ); - }).pipe(Effect.provide(layer)); - }), + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(steered, []); + assert.equal(started.length, 2); + assert.equal(started[1]?.message.messageId, MessageId.make("message:steer")); + assert.deepEqual(started[1]?.modelSelection, composerSelection); + assert.deepEqual(projection.thread.modelSelection, composerSelection); + const message = projection.turnItems.find( + (item) => + item.type === "user_message" && item.messageId === MessageId.make("message:steer"), + ); + assert.equal(message?.runId, started[1]!.runId); + assert.isAbove( + message!.ordinal, + Math.max( + ...projection.turnItems + .filter((item) => item.runId === first.runId) + .map((item) => item.ordinal), + ), + ); + }).pipe(Effect.provide(layer)); + }), ); const declinedSteerTimings = [ @@ -2568,6 +2603,74 @@ it.effect("steers a promoted scheduled delivery with the thread's current select ), ); +it.effect("steers a deferred agent message on a pick made while it waited", () => + Effect.scoped( + Effect.gen(function* () { + const { started, steered, steeredSelections, layer, startFirstTurn, events } = + yield* nextTurnSelectionHarness("deferred-agent-steer-selection"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("turn-not-ready"), + type: "provider-turn.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...turn, status: "pending" }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("agent-steer"), + threadId, + messageId: MessageId.make("message:agent-steer"), + text: "agent steer", + attachments: [], + dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId }, + createdBy: "agent", + creationSource: "mcp", + }); + const deferred = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "queued", + )!; + assert.equal(deferred.steerWhenReadyRunId, started[0]!.runId); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make("select-composer"), + threadId, + modelSelection: composerSelection, + }); + const promoted = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === deferred.id && + event.payload.status === "cancelled", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Queue.offer(events, { type: "provider_turn.updated", driver, providerTurn: turn }); + yield* Fiber.join(promoted); + yield* worker.drain(); + + assert.lengthOf(steered, 1); + assert.deepEqual(steeredSelections, [composerSelection]); + assert.deepEqual( + (yield* orchestrator.getThreadProjection(threadId)).thread.modelSelection, + composerSelection, + ); + }).pipe(Effect.provide(layer)); + }), + ), +); + const claudeSelection = { instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-test", diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index e0ae516a190b5..0382415179bfc 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -103,6 +103,8 @@ export interface ThreadLaunchInput { readonly projectId: ProjectId; readonly title: string; readonly generateTitle?: boolean; + /** The caller chose `title`, so a first message keeps it. */ + readonly titleRenamed?: boolean; readonly modelSelection: ModelSelection; readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode; @@ -1458,6 +1460,7 @@ const make = Effect.gen(function* () { threadId: candidateThreadId, projectId: input.projectId, title: input.title, + ...(input.titleRenamed === true ? { titleRenamed: true } : {}), modelSelection: input.modelSelection, runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index b20feef64eadd..07bb2d64d80a5 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -28,6 +28,8 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Logger from "effect/Logger"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as PubSub from "effect/PubSub"; @@ -687,8 +689,24 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: const layerDependencies = Layer.mergeAll( Layer.mock(ProjectStore.ProjectStoreV2)({ listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)), + getShell: (projectId) => + Ref.get(snapshots).pipe( + Effect.map((snapshot) => + Option.fromNullishOr(snapshot.projects.find((project) => project.id === projectId)), + ), + ), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadsWithPullRequests: (_threadId, readOptions) => + Ref.get(snapshots).pipe( + Effect.map((snapshot) => + snapshot.threads + .filter( + (thread) => readOptions?.includeArchived === true || thread.archivedAt === null, + ) + .map((thread) => ({ ...thread, pullRequests: thread.pullRequests ?? [] })), + ), + ), ...options.projections, getSettlementCandidates: (threadId) => Ref.update(candidateReads, (reads) => [...reads, threadId]).pipe( @@ -2109,6 +2127,103 @@ describe("ThreadSettlementServiceV2 worker", () => { }).pipe(Effect.provide(fixture.layer)); }), ); + + it.effect("a merge does not settle a local thread on the branch of another thread's PR", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const mergedLink = { + ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")), + snapshot: { + ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")).snapshot!, + state: "merged" as const, + mergedAt: NOW, + }, + }; + const owner = makeThread("pr-owner", { branch: "feature", pullRequests: [mergedLink] }); + const sibling = makeThread("local-sibling", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + }); + const cachedSibling = makeThread("cached-sibling", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + branchPullRequest: { + projectId: PROJECT_ID, + repository: "owner/repository", + number: 42, + url: "https://example.test/owner/repository/pull/42", + }, + }); + const legacyOwner = makeThread("legacy-owner", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + linkedPullRequest: cachedSibling.branchPullRequest, + }); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([owner, sibling, legacyOwner, cachedSibling]), + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleOnMerge: true, + sidebarAutoSettleAfterDays: null, + }, + branchPullRequest: () => Effect.succeed(makeBranchPullRequest("merged")), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + yield* fixture.publishMerge; + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + + expect( + [ + ...new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)), + ].toSorted(), + ).toEqual([legacyOwner.id, owner.id].toSorted()); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + it.effect("an archived thread's pull request does not settle a local thread on its branch", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const link = persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")); + const owner = makeThread("archived-owner", { + branch: "feature", + archivedAt: DateTime.makeUnsafe("2026-08-29T00:00:00.000Z"), + pullRequests: [ + { ...link, snapshot: { ...link.snapshot!, state: "merged", mergedAt: NOW } }, + ], + }); + const sibling = makeThread("local-sibling", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + }); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([owner, sibling]), + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleOnMerge: true, + sidebarAutoSettleAfterDays: null, + }, + branchPullRequest: () => Effect.succeed(makeBranchPullRequest("merged")), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + yield* fixture.publishMerge; + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + + expect(yield* Ref.get(fixture.commands)).toEqual([]); + }).pipe(Effect.provide(fixture.layer)); + }), + ); }); describe("ThreadSettlementServiceV2 terminals", () => { @@ -2141,12 +2256,29 @@ describe("ThreadSettlementServiceV2 terminals", () => { it.effect("runs the settle script in the thread's own worktree", () => Effect.gen(function* () { + const warnings: string[] = []; + const logger = Logger.make(({ logLevel, message }) => { + if (logLevel === "Warn") warnings.push(JSON.stringify(message)); + }); const shared = appThread("shared-checkout-thread", "settled"); const missing = appThread("removed-worktree-thread", "settled", "/worktrees/removed"); const worktree = appThread("worktree-thread", "settled", "/worktrees/thread"); + const scriptless = makeProject(ProjectId.make("scriptless-project")); + const missingScriptless = { + ...appThread("removed-worktree-scriptless-thread", "settled", "/worktrees/scriptless"), + projectId: scriptless.id, + }; + const teardown = { + id: "teardown", + name: "Teardown", + command: "docker compose down", + icon: "configure", + runOnWorktreeCreate: false, + runOnSettle: true, + } as const; const fixture = yield* makeHarness({ - snapshot: makeSnapshot([]), - currentThreads: [shared, missing, worktree], + snapshot: makeSnapshot([], [{ ...makeProject(), scripts: [teardown] }, scriptless]), + currentThreads: [shared, missing, missingScriptless, worktree], existingWorktreePaths: ["/worktrees/thread"], }); @@ -2155,12 +2287,23 @@ describe("ThreadSettlementServiceV2 terminals", () => { yield* startHarness(service, fixture.activation, fixture.snapshotReads); yield* fixture.publishEvent(settledEvent(shared)); yield* fixture.publishEvent(settledEvent(missing)); + yield* fixture.publishEvent(settledEvent(missingScriptless)); yield* fixture.publishEvent(settledEvent(worktree)); const run = yield* Queue.take(fixture.scriptRuns); assert.strictEqual(run.threadId, worktree.id); assert.strictEqual(run.worktreePath, "/worktrees/thread"); assert.strictEqual(run.trigger, "settle"); - }).pipe(Effect.provide(fixture.layer)); + // A removed worktree skips a configured settle script; the log is its only trace. + assert.strictEqual(warnings.length, 1); + assert.include(warnings[0], missing.id); + assert.include(warnings[0], "/worktrees/removed"); + }).pipe( + Effect.provide( + fixture.layer.pipe( + Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })), + ), + ), + ); }), ); diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 6f05e0fd3c40c..ef0894f3ecbeb 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -3,6 +3,7 @@ import { isPullRequestWatchTask, turnItemUpdateCanEndBackgroundWork, } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; +import { resolveProjectScripts, settleProjectScript } from "@t3tools/shared/projectScripts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { @@ -20,6 +21,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FiberSet from "effect/FiberSet"; import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; @@ -35,6 +37,10 @@ import * as TerminalManager from "../terminal/Manager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ProjectStore from "./ProjectStore.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; +import { + legacyThreadPullRequestKey, + threadPullRequestKeyOf, +} from "../sourceControl/threadPullRequests.ts"; import { makeNoPullRequestRechecks } from "./noPullRequestRechecks.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -87,6 +93,20 @@ function pullRequestMatchesProject( ); } +function branchPullRequestKey(pullRequest: GitManager.GitBranchPullRequest): string | null { + const parsed = sourceControlDefinitions.parseChangeRequestUrl(pullRequest.url)?.link; + if (parsed !== undefined && parsed.number === pullRequest.number) { + return threadPullRequestKeyOf(parsed); + } + const separator = pullRequest.repositoryKey?.indexOf("/") ?? -1; + if (pullRequest.repositoryKey == null || separator <= 0) return null; + return threadPullRequestKeyOf({ + host: pullRequest.repositoryKey.slice(0, separator), + repository: pullRequest.repositoryKey.slice(separator + 1), + number: pullRequest.number, + }); +} + type SettlementPullRequestLink = NonNullable< ProjectionStore.ProjectionSettlementCandidate["pullRequests"] >[number]; @@ -481,7 +501,7 @@ export const make = Effect.gen(function* () { const reference = thread.linkedPullRequest ?? thread.branchPullRequest; if (reference != null) { return JSON.stringify([ - "linked", + thread.linkedPullRequest != null ? "linked" : "branch-reference", reference.projectId, reference.repository, reference.number, @@ -496,6 +516,22 @@ export const make = Effect.gen(function* () { ); }; const groups = Map.groupBy(lookupCandidates, lookupKey); + // A thread with no link of its own does not settle from a pull request another thread links, + // archived threads included. + const explicitlyLinked = new Set( + groups.size === 0 + ? [] + : (yield* projections.getThreadsWithPullRequests(undefined, { + includeArchived: true, + })).flatMap((thread) => + visibleThreadPullRequests(thread.pullRequests ?? []).map(threadPullRequestKeyOf), + ), + ); + const ownedByAnotherThread = (pullRequest: GitManager.GitBranchPullRequest | null) => { + if (pullRequest === null || pullRequest.state === "open") return false; + const key = branchPullRequestKey(pullRequest); + return key !== null && explicitlyLinked.has(key); + }; // wouldSettle and pullRequestFor run per lookup group; the git and pull request reads they make carry the spans. const wouldSettle = Effect.fnUntraced(function* ( @@ -524,6 +560,13 @@ export const make = Effect.gen(function* () { ) { const thread = group[0]!; const reference = thread.linkedPullRequest ?? thread.branchPullRequest; + if ( + thread.linkedPullRequest == null && + reference != null && + explicitlyLinked.has(threadPullRequestKeyOf(legacyThreadPullRequestKey(reference))) + ) { + return undefined; + } if (reference != null) { // Only matching PR links settle from this merge event; unrelated links require fresh lookup. const matchesMerge = @@ -601,9 +644,14 @@ export const make = Effect.gen(function* () { { refresh, confirmTerminal: false }, ); noPullRequestRechecks.record(key, nowMs, remembered !== null); + if (ownedByAnotherThread(remembered)) return undefined; if (refresh || remembered === null || remembered.state === "open") return remembered; if (!(yield* wouldSettle(group, remembered))) return undefined; - return yield* git.branchPullRequest({ cwd, branch: thread.branch }, { freshGitState: true }); + const fresh = yield* git.branchPullRequest( + { cwd, branch: thread.branch }, + { freshGitState: true }, + ); + return ownedByAnotherThread(fresh) ? undefined : fresh; }); // A merge, a shell close and a thread's own events read at once; only scheduled sweeps wait. @@ -712,7 +760,21 @@ export const make = Effect.gen(function* () { if (settled.deletedAt !== null || settled.settledOverride !== "settled") return; yield* terminals.closeOnSettle({ threadId }); const worktreePath = settled.worktreePath; - if (worktreePath === null || !(yield* fileSystem.exists(worktreePath))) return; + if (worktreePath === null) return; + if (!(yield* fileSystem.exists(worktreePath))) { + // A settle script that tears something down would otherwise be skipped with no trace. + const project = Option.getOrUndefined(yield* projectStore.getShell(settled.projectId)); + if ( + project !== undefined && + settleProjectScript(resolveProjectScripts(yield* settingsService.getSettings, project)) + ) { + yield* Effect.logWarning( + "settle script skipped: the thread's worktree no longer exists", + { threadId, worktreePath }, + ); + } + return; + } // Recheck after closing and worktree I/O; only live, settled threads may run scripts. const thread = yield* projections.getThread(threadId); if (thread.deletedAt !== null || thread.settledOverride !== "settled") return; diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts index 20cd5aaa76236..1d39000ed3a9f 100644 --- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts @@ -343,9 +343,19 @@ describe("ThreadTitleRegenerationService", () => { const threads = yield* ThreadManagement.ThreadManagementService; const outbox = yield* EffectOutbox.EffectOutboxV2; // An MCP launch names the thread, or leaves a placeholder, and sends no message. - for (const [key, title, expectedTitle, generates] of [ - ["preset", "[API] #4821 — retry webhook deliveries after a timeout", undefined, false], - ["placeholder", placeholderThreadTitle("Parent", 0), seed, true], + for (const [key, title, titleRenamed, compactFirst, expectedTitle, generates] of [ + [ + "preset", + "[API] #4821 - retry webhook deliveries after a timeout", + false, + false, + undefined, + false, + ], + ["placeholder", placeholderThreadTitle("Parent", 0), false, false, seed, true], + ["named like a placeholder", "Release thread 2", true, false, undefined, false], + ["named, then compacted", "Release notes", true, true, undefined, false], + ["draft titled by its /compact", "/compact", false, true, seed, true], ] as const) { const threadId = ThreadId.make(`thread:title:${key}`); yield* threads.dispatch({ @@ -354,6 +364,7 @@ describe("ThreadTitleRegenerationService", () => { threadId, projectId, title, + ...(titleRenamed ? { titleRenamed } : {}), modelSelection, runtimeMode: "full-access", interactionMode: "default", @@ -362,6 +373,21 @@ describe("ThreadTitleRegenerationService", () => { createdBy: "agent", creationSource: "mcp", }); + if (compactFirst) { + yield* threads.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`command:title:${key}:compact`), + threadId, + messageId: MessageId.make(`command:title:${key}:compact:message`), + text: "/compact", + titleSeed: "/compact", + attachments: [], + modelSelection, + dispatchMode: { type: "defer_start" }, + createdBy: "user", + creationSource: "web", + }); + } const requestId = CommandId.make(`command:title:${key}:message`); yield* threads.dispatch({ type: "message.dispatch", diff --git a/apps/server/src/orchestration-v2/deferredCommandMessage.ts b/apps/server/src/orchestration-v2/deferredCommandMessage.ts index 6c058337b2cd7..393fe981add55 100644 --- a/apps/server/src/orchestration-v2/deferredCommandMessage.ts +++ b/apps/server/src/orchestration-v2/deferredCommandMessage.ts @@ -6,10 +6,7 @@ const text = `json_extract(payload_json, '$.text')`; const whitespace = `'${JAVASCRIPT_TRIM_WHITESPACE}'`; /** - * A user message that is a `/compact` or `/goal` command, whose turns defer context to the next - * one. The partial index on it is only used when the read spells this text the same way. + * A user message that may be a slash command, whose turns defer context to the next one. The + * partial index on it is only used when the read spells this text the same way. */ -export const DEFERRED_COMMAND_MESSAGE_CONDITION = `role = 'user' AND ( - lower(trim(${text}, ${whitespace})) = '/compact' - OR trim(${text}, ${whitespace}) GLOB '/goal*' -)`; +export const DEFERRED_COMMAND_MESSAGE_CONDITION = `role = 'user' AND trim(${text}, ${whitespace}) GLOB '/*'`; diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index c899eb774bfc3..843e51da40423 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1878,6 +1878,28 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { [], ); assert.deepEqual(yield* outbox.listByCommandId(commandId), []); + if (status === "error") { + // A failed capture still pins the conversation. + const conversationCommandId = CommandId.make("runtime-rollback-error-conversation"); + const conversationOnly = yield* orchestrator.dispatch({ + type: "checkpoint.rollback", + commandId: conversationCommandId, + threadId, + checkpointId, + scopeId: scope.id, + restoreFiles: false, + }); + assert.deepEqual( + conversationOnly.storedEvents.map((stored) => stored.event.type), + ["thread.metadata-updated", "checkpoint.rollback-requested"], + ); + assert.deepEqual( + (yield* outbox.listByCommandId(conversationCommandId)).map( + (effect) => effect.request.type, + ), + ["provider-thread.rollback"], + ); + } } } }).pipe(Effect.provide(Layer.fresh(layerTest))), @@ -10051,6 +10073,87 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect( + "starts a queued agent message that names no model on a pick made while it waited", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make("runtime-layer-queued-agent-message-later-pick"); + const pickedSelection = { ...modelSelection, model: "gpt-5.5" }; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + createdBy: "user", + creationSource: "web", + title: "Pick while an agent message waits", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:active`), + threadId, + messageId: MessageId.make(`${threadId}:active`), + text: "active", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:agent`), + threadId, + messageId: MessageId.make(`${threadId}:agent`), + text: "Message from another thread", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + }); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make(`${threadId}:pick`), + threadId, + modelSelection: pickedSelection, + }); + const [active, agent] = (yield* orchestrator.getThreadProjection(threadId)).runs; + assert.isDefined(active); + assert.isDefined(agent); + const now = yield* DateTime.now; + const current = yield* orchestrator.getThreadProjection(threadId); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${active.id}:completed`), + type: "run.updated", + threadId, + runId: active.id, + occurredAt: now, + payload: { + ...current.runs.find((run) => run.id === active.id)!, + status: "completed", + completedAt: now, + }, + }, + ], + }); + yield* orchestrator.resumeQueuedRuns; + const after = yield* orchestrator.getThreadProjection(threadId); + const delivered = after.runs.find((run) => run.id === agent.id)!; + assert.equal(delivered.status, "starting"); + assert.deepEqual(after.thread.modelSelection, pickedSelection); + assert.deepEqual(delivered.modelSelection, pickedSelection); + }), + ); + it.effect("keeps a buffered provider wake on its own provider behind a queued pick", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index f05577c06c57e..18ee960fc9e4d 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -228,6 +228,7 @@ const layerCheckpointCaptureServiceProvided = CheckpointCaptureService.layer.pip layerEventSink, IdAllocator.layer, ProjectionStore.layer, + ThreadCommandExecutor.layer, ), ), ); diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts index 4b980e877b164..11d0f4f3e5bbe 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts @@ -295,4 +295,26 @@ describe("restart-cancelled background work", () => { ), ), ); + + it.effect("sends a slash command verbatim and tells the next user turn instead", () => + Effect.scoped( + Effect.gen(function* () { + const slashCommand = "/review the diff"; + const projection = yield* runRestart({ + resumedPrompts: [slashCommand, `${NOTE}\n\nUser message:\n${SECOND_AFTER_RESTART}`], + userMessagesAfterRestart: [slashCommand, SECOND_AFTER_RESTART], + continueThreadsAfterServerUpdate: false, + }); + assert.deepEqual( + projection.runs.map((run) => run.status), + ["completed", "completed", "completed"], + ); + }).pipe( + provideDeterministicTestRuntime, + Effect.provide( + Layer.merge(IdAllocator.layer, Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), + ); }); diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 333d87f3a6d51..bf47bc86109bb 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -509,6 +509,7 @@ export function layerWithRegistry( layerEventSinkProvided, IdAllocator.layer, layerStores, + ThreadCommandExecutor.layer, ), ), ); diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index ee048c2100592..811279357d917 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -118,6 +118,7 @@ function makeTestAdapter(input: { readonly failure?: ReturnType; readonly rejectedNativeThreads?: Ref.Ref>; readonly failedRunOrdinals?: ReadonlySet; + readonly promptDroppedRunOrdinals?: ReadonlySet; readonly brokenRunOrdinals?: ReadonlySet; readonly interruptedRunOrdinals?: ReadonlySet; readonly cancelledRunOrdinals?: ReadonlySet; @@ -410,6 +411,9 @@ function makeTestAdapter(input: { status: terminalStatus, startedAt: eventTime, completedAt: eventTime, + ...(input.promptDroppedRunOrdinals?.has(turnInput.runOrdinal) + ? { promptDropped: true as const } + : {}), }, }, { @@ -462,6 +466,9 @@ function makeTestAdapter(input: { threadDisposition: input.brokenRunOrdinals?.has(turnInput.runOrdinal) ? "broken" : "reusable", + ...(input.promptDroppedRunOrdinals?.has(turnInput.runOrdinal) + ? { promptDropped: true as const } + : {}), }, ]; const reportedUsage = input.tokenUsageByRunOrdinal?.[turnInput.runOrdinal]; @@ -3225,6 +3232,124 @@ describe("orchestration v2 provider switching", () => { }), ); + it.live.each([ + { name: "a slash command", text: "/implement do X", verbatim: true }, + { name: "a message opening with a path", text: "/usr/lib/foo is broken", verbatim: false }, + ] as const)( + "a switched ACP provider gets $name with the handoff where the command allows it", + ({ text: firstMessage, verbatim }) => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace(`slash-command-handoff-${verbatim}`); + const capturedTurns = yield* Ref.make>([]); + const originalPrompt = "Keep the release marker violet and preserve the existing API."; + const codexResponse = "I checked the API and found the release configuration."; + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CODEX_MODEL_SELECTION.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: CODEX_MODEL_SELECTION, + responseByRunOrdinal: { 1: codexResponse }, + capturedTurns, + }), + makeTestAdapter({ + instanceId: GROK_MODEL_SELECTION.instanceId, + driver: GROK_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + modelSelection: GROK_MODEL_SELECTION, + responseByRunOrdinal: { 2: "Implemented.", 3: "Continued." }, + capturedTurns, + }), + ]); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const waitForRun = (ordinal: number) => + orchestrator.streamStoredEvents.pipe( + Stream.filter( + ({ event }) => + event.type === "run.updated" && + event.threadId === threadId && + event.payload.ordinal === ordinal && + event.payload.status === "completed", + ), + Stream.runHead, + Effect.andThen(worker.drain()), + ); + const dispatch = (key: string, text: string, modelSelection: ModelSelection) => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`command:slash-handoff:${key}`), + threadId, + messageId: MessageId.make(`message:slash-handoff:${key}`), + createdBy: "user", + creationSource: "web", + text, + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("command:slash-handoff:create"), + threadId, + projectId, + createdBy: "user", + creationSource: "web", + title: "Slash command provider handoff", + modelSelection: CODEX_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + yield* dispatch("source", originalPrompt, CODEX_MODEL_SELECTION); + yield* waitForRun(1); + yield* dispatch("slash", firstMessage, GROK_MODEL_SELECTION); + yield* waitForRun(2); + const slashTurn = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.equal(slashTurn.driver, GROK_DRIVER); + if (!verbatim) { + assert.include(slashTurn.text, originalPrompt); + assert.include(slashTurn.text, `User message:\n${firstMessage}`); + return; + } + assert.equal( + slashTurn.text, + firstMessage, + "ACP only expands a native slash command when the prompt starts with it", + ); + + yield* dispatch("next", "Continue", GROK_MODEL_SELECTION); + yield* waitForRun(3); + const next = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.include(next.text, originalPrompt); + assert.include(next.text, codexResponse); + assert.include(next.text, "User message:\nContinue"); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { + name: "slash-command-handoff", + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + layerRegistry, + ), + ), + ); + }), + ), + ); + it.live("checks the queued provider's capability while the current provider stays running", () => Effect.gen(function* () { for (const scenario of [ @@ -6400,4 +6525,166 @@ describe("orchestration v2 provider switching", () => { ); }), ); + + it.effect.each([ + "same-provider-retry", + "cancelled-dropped", + "switch-away-and-return", + "persisted-failure", + ] as const)("handles an inline context handoff after a failed returning turn (%s)", (variant) => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace(`dropped-handoff-${variant}`); + const capturedTurns = yield* Ref.make>([]); + const dropped = variant !== "persisted-failure"; + const cancelled = variant === "cancelled-dropped"; + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CODEX_MODEL_SELECTION.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: CODEX_MODEL_SELECTION, + responseByRunOrdinal: { + 1: "Morning Codex summary.", + 3: "", + 4: "Recovered Codex answer.", + 5: "Recovered Codex after round-trip.", + }, + capturedTurns, + ...(cancelled + ? { cancelledRunOrdinals: new Set([3]) } + : { failedRunOrdinals: new Set([3]) }), + ...(dropped ? { promptDroppedRunOrdinals: new Set([3]) } : {}), + }), + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: { + 2: "Afternoon Claude shipped b63 live draft.", + 4: "Extra Claude turn after dropped handoff.", + }, + capturedTurns, + }), + ]); + + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const testThreadId = ThreadId.make(`thread:dropped-handoff:${variant}`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:dropped-handoff:${variant}:create`), + threadId: testThreadId, + projectId, + title: `Dropped handoff ${variant}`, + modelSelection: CODEX_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + let step = 0; + const send = (text: string, modelSelection: ModelSelection) => + Effect.gen(function* () { + step += 1; + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:dropped-handoff:${variant}:msg-${step}`), + threadId: testThreadId, + messageId: MessageId.make(`message:dropped-handoff:${variant}:${step}`), + text, + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* worker.drain(); + yield* waitForIdle(testThreadId); + yield* worker.drain(); + return yield* orchestrator.getThreadProjection(testThreadId); + }); + + // Run 1: establish native session on Codex. + yield* send("Morning task", CODEX_MODEL_SELECTION); + // Run 2: switch to Claude and do real work. + yield* send("Build live draft b63", CLAUDE_MODEL_SELECTION); + // Run 3: switch back to Codex (delta handoff covering run 2); fails. + const afterRun3 = yield* send("Resume after failure", CODEX_MODEL_SELECTION); + const run3 = afterRun3.runs.find((run) => run.ordinal === 3)!; + assert.equal(run3.status, cancelled ? "cancelled" : "failed"); + const run3Handoff = afterRun3.contextHandoffs.find( + (handoff) => handoff.targetRunId === run3.id, + ); + assert.isDefined(run3Handoff); + assert.deepEqual(run3Handoff?.coveredRunOrdinals, { from: 2, to: 2 }); + + if (dropped) { + assert.isUndefined( + run3Handoff?.delivery, + "dropping the failed prompt must clear inline handoff delivery", + ); + const run3Turn = afterRun3.providerTurns.find( + (turn) => turn.runAttemptId === run3.activeAttemptId, + ); + assert.equal(run3Turn?.promptDropped, true); + } else { + assert.equal(run3Handoff?.delivery?.status, "inline"); + } + + if (variant === "same-provider-retry" || variant === "cancelled-dropped") { + // Run 4: stay on Codex; must re-deliver run 2's handoff. + const afterRun4 = yield* send("Resume", CODEX_MODEL_SELECTION); + const turns = yield* Ref.get(capturedTurns); + const run4Turn = turns.at(-1)!; + assert.include(run4Turn.text, "Afternoon Claude shipped b63 live draft."); + assert.include(run4Turn.text, "Resume after failure"); + assert.include(run4Turn.text, "User message:\nResume"); + const updatedHandoff = afterRun4.contextHandoffs.find( + (handoff) => handoff.id === run3Handoff!.id, + ); + assert.equal(updatedHandoff?.delivery?.status, "inline"); + } else if (variant === "switch-away-and-return") { + // Run 4: bounce back to Claude, then Run 5: return to Codex. + yield* send("Continue on Claude", CLAUDE_MODEL_SELECTION); + const afterRun5 = yield* send("Back to Codex", CODEX_MODEL_SELECTION); + const run5 = afterRun5.runs.find((run) => run.ordinal === 5)!; + const run5Handoff = afterRun5.contextHandoffs.find( + (handoff) => handoff.targetRunId === run5.id, + ); + assert.isDefined(run5Handoff); + assert.deepEqual(run5Handoff?.coveredRunOrdinals, { from: 2, to: 4 }); + const run5Turn = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.include(run5Turn.text, "Afternoon Claude shipped b63 live draft."); + assert.include(run5Turn.text, "Extra Claude turn after dropped handoff."); + } else { + // Control: run 3 persisted its prompt before failing, so run 4 must not re-send run 2. + yield* send("Resume", CODEX_MODEL_SELECTION); + const run4Turn = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.notInclude(run4Turn.text, "Afternoon Claude shipped b63 live draft."); + } + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { + name: `dropped-handoff-${variant}`, + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + layerRegistry, + ), + ), + ); + }), + ); }); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_command/opencode_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_command/opencode_transcript.ndjson index 36c35d5799ad0..8d54c33ef3a2f 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_command/opencode_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_command/opencode_transcript.ndjson @@ -1,4 +1,4 @@ -{"type": "transcript_start", "provider": "opencode", "protocol": "opencode2-http.sse", "version": "2.0.18", "scenario": "opencode2_command", "metadata": {"source": "oc2-8 live recording command_t3.ndjson (2.0.18, openrouter/deepseek/deepseek-v4-flash)", "capturedAt": "2026-09-29", "description": "A real OpenCode 2.0.18 session recorded at the HTTP and SSE boundary: `/hello WORLD` names a workspace command (.opencode/command/hello.md), so T3 reads the directory's commands and runs it with session.command; OpenCode expands the template into the user message. T3's per-turn instructions entry (answered 204, as 2.0.18 does) is written before the thread's first turn. Before the command, T3 reads the session's newest history item (none on a new session, as 2.0.18 answers) so a reconnect can backfill a command, whose answer carries no item id."}} +{"type": "transcript_start", "provider": "opencode", "protocol": "opencode2-http.sse", "version": "2.0.18", "scenario": "opencode2_command", "metadata": {"source": "oc2-8 live recording command_t3.ndjson (2.0.18, openrouter/deepseek/deepseek-v4-flash)", "capturedAt": "2026-09-29", "description": "A real OpenCode 2.0.18 session recorded at the HTTP and SSE boundary: `/hello WORLD` names a workspace command (.opencode/command/hello.md), so T3 reads the directory's commands and runs it with session.command; OpenCode expands the template into the user message. T3's per-turn instructions entry (answered 204, as 2.0.18 does) is written before the thread's first turn. Before the command, T3 reads the session's newest history item (none on a new session, as 2.0.18 answers) so a reconnect can backfill a command, whose answer carries no item id. The session.active read after session.command was added by hand; OpenCode 2.2.2 lists a model-calling command's session there."}} {"type": "expect_outbound", "label": "event.subscribe", "frame": {"type": "event.subscribe"}} {"type": "expect_outbound", "label": "model.list", "frame": {"type": "model.list", "input": {"location[directory]": ""}}} {"type": "emit_inbound", "label": "model.list.response", "frame": {"type": "sdk.response", "operation": "model.list", "data": {"location": {"directory": ""}, "data": [{"id": "deepseek/deepseek-v4-flash", "modelID": "deepseek/deepseek-v4-flash", "providerID": "openrouter", "family": "deepseek-flash", "name": "DeepSeek V4 Flash", "compatibility": {"reasoningField": "reasoning_content"}, "package": "@opencode/ai/providers/openrouter", "settings": {"baseURL": "https://openrouter.ai/api/v1"}, "headers": {"HTTP-Referer": "https://opencode.ai/", "X-Title": "opencode"}, "capabilities": {"tools": true, "input": ["text"], "output": ["text"]}, "variants": [{"id": "none", "settings": {"reasoning": {"enabled": false}}}, {"id": "high", "settings": {"reasoning": {"effort": "high"}}}, {"id": "xhigh", "settings": {"reasoning": {"effort": "xhigh"}}}], "time": {"released": 1776988800000}, "cost": [{"input": 0.14, "output": 0.28, "cache": {"read": 0.028, "write": 0}}], "status": "active", "enabled": true, "limit": {"context": 1048576, "output": 131072}}]}}} @@ -15,6 +15,8 @@ {"type": "emit_inbound", "label": "message.list.response", "frame": {"type": "sdk.response", "operation": "message.list", "data": {"data": [], "cursor": {"previous": null, "next": null}}}} {"type": "expect_outbound", "label": "session.command", "frame": {"type": "session.command", "input": {"sessionID": "ses_f0f27cc49ffe6wl0jdiu4kO4FC", "name": "hello", "text": "WORLD"}}} {"type": "emit_inbound", "label": "session.command.response", "frame": {"type": "sdk.response", "operation": "session.command", "data": null}} +{"type": "expect_outbound", "label": "session.active", "frame": {"type": "session.active"}} +{"type": "emit_inbound", "label": "session.active.response", "frame": {"type": "sdk.response", "operation": "session.active", "data": {"data": {"ses_f0f27cc49ffe6wl0jdiu4kO4FC": {"type": "running"}}}}} {"type": "emit_inbound", "label": "session.inbox.enqueued", "frame": {"type": "sdk.event", "event": {"id": "evt_0f0d833f7001CR8gqnGibZ5mIH", "created": 1790747096055, "type": "session.inbox.enqueued", "location": {"directory": ""}, "data": {"inboxID": "msg_0f0d833f4001DhEyXmiqfz0kcF", "sessionID": "ses_f0f27cc49ffe6wl0jdiu4kO4FC", "item": {"type": "user", "payload": {"text": "Reply with exactly: HELLO WORLD"}, "delivery": "steer"}}, "durable": {"aggregateID": "ses_f0f27cc49ffe6wl0jdiu4kO4FC", "seq": 1, "version": 1}}}} {"type": "emit_inbound", "label": "session.execution.started", "frame": {"type": "sdk.event", "event": {"id": "evt_0f0d834000013DTH87ptN5evlM", "created": 1790747096064, "type": "session.execution.started", "data": {"sessionID": "ses_f0f27cc49ffe6wl0jdiu4kO4FC"}, "durable": {"aggregateID": "ses_f0f27cc49ffe6wl0jdiu4kO4FC", "seq": 2, "version": 1}}}} {"type": "emit_inbound", "label": "session.instructions.updated", "frame": {"type": "sdk.event", "event": {"id": "evt_0f0d8341c001S6iTOkDN2My4re", "created": 1790747096092, "metadata": {"instructions": {"initial": true}}, "type": "session.instructions.updated", "location": {"directory": ""}, "data": {"sessionID": "ses_f0f27cc49ffe6wl0jdiu4kO4FC", "delta": {"core/environment": "01f209da7564499aba1aa03a38a42dc4ed37f8e23457c5e19a54eba288092d1f", "core/date": "13b802fdef38a72e2e5d4cf7c6f9d270d07fb1787c3e4ff3ee1a8048fdbc46fa", "core/codemode": "616a7ad8b8e40e8a71eab238dfbbe9eaf0f4a9e6fdad853226d075bfe602e1e6", "core/skill-guidance": "b2aff856e4c0afa54b6d56ecdc438d66a6333b36a3b62677bb1a96da62079118"}}, "durable": {"aggregateID": "ses_f0f27cc49ffe6wl0jdiu4kO4FC", "seq": 3, "version": 2}}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts index c7579914964ee..bed80f2be65ef 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts @@ -24,32 +24,45 @@ function lastPiResponseData(transcript: ProviderReplayTranscript, command: strin return field(frame, "data"); } -/** Settled Pi usage uses each recorded get_session_stats response in order, not the last streaming total. */ +/** + * Settled Pi usage takes the context size from each turn's get_session_stats response and the + * input breakdown from the turn's last streamed message usage, since stats tokens are session totals. + */ export function assertPiSettledTokenUsage( result: OrchestratorV2ScenarioResult, transcript: ProviderReplayTranscript, ) { - const stats = transcript.entries.flatMap((entry) => - entry.type === "emit_inbound" && - field(entry.frame, "type") === "response" && - field(entry.frame, "command") === "get_session_stats" - ? [field(entry.frame, "data")] - : [], - ); - const turns = projectionFor(result, transcript.scenario).providerTurns; - assert.lengthOf(turns, stats.length); - for (const [index, turn] of turns.entries()) { - const contextUsage = field(stats[index], "contextUsage"); - const tokens = field(stats[index], "tokens"); - const { updatedAt: _updatedAt, ...tokenUsage } = turn.tokenUsage ?? { updatedAt: "" }; - assert.deepEqual(tokenUsage, { - usedTokens: field(contextUsage, "tokens"), - maxTokens: field(contextUsage, "contextWindow"), - inputTokens: field(tokens, "input"), - cachedInputTokens: field(tokens, "cacheRead"), - outputTokens: field(tokens, "output"), - }); + const expected: Array> = []; + let messageUsage: unknown; + for (const entry of transcript.entries) { + if (entry.type !== "emit_inbound") continue; + const usage = field(entry.frame, "usage"); + if (field(entry.frame, "type") === "message_update" && field(usage, "totalTokens") !== 0) { + messageUsage = usage; + } + if ( + field(entry.frame, "type") === "response" && + field(entry.frame, "command") === "get_session_stats" + ) { + const contextUsage = field(field(entry.frame, "data"), "contextUsage"); + const count = (key: string) => Number(field(messageUsage, key)); + expected.push({ + usedTokens: field(contextUsage, "tokens"), + maxTokens: field(contextUsage, "contextWindow"), + inputTokens: count("input") + count("cacheRead") + count("cacheWrite"), + cachedInputTokens: count("cacheRead"), + outputTokens: count("output"), + }); + } } + const turns = projectionFor(result, transcript.scenario).providerTurns; + assert.deepEqual( + turns.map((turn) => { + const { updatedAt: _updatedAt, ...tokenUsage } = turn.tokenUsage ?? { updatedAt: "" }; + return tokenUsage; + }), + expected, + ); } export function assertPiSimpleOutput( diff --git a/apps/server/src/os-jank.test.ts b/apps/server/src/os-jank.test.ts index 857adb2c8e5c3..46b3b6b1e9936 100644 --- a/apps/server/src/os-jank.test.ts +++ b/apps/server/src/os-jank.test.ts @@ -149,44 +149,52 @@ effectIt.effect("keeps mise's PATH record with the login shell PATH", () => ), ); -effectIt.effect("hydrates a missing JAVA_HOME from the login shell and keeps an explicit one", () => - Effect.acquireUseRelease( - Effect.sync(() => - vi - .spyOn(NodeChildProcess, "execFileSync") - .mockReturnValue( - [ - "__T3CODE_ENV_PATH_START__", - "/opt/homebrew/bin", - "__T3CODE_ENV_PATH_END__", - "__T3CODE_ENV_JAVA_HOME_START__", - "/opt/homebrew/opt/openjdk@17", - "__T3CODE_ENV_JAVA_HOME_END__", - ].join("\n"), - ), +effectIt.effect( + "hydrates missing JAVA_HOME and feature flags from the login shell and keeps explicit ones", + () => + Effect.acquireUseRelease( + Effect.sync(() => + vi + .spyOn(NodeChildProcess, "execFileSync") + .mockReturnValue( + [ + "__T3CODE_ENV_PATH_START__", + "/opt/homebrew/bin", + "__T3CODE_ENV_PATH_END__", + "__T3CODE_ENV_JAVA_HOME_START__", + "/opt/homebrew/opt/openjdk@17", + "__T3CODE_ENV_JAVA_HOME_END__", + "__T3CODE_ENV_T3CODE_FEATURE_FLAGS_START__", + "tanstack_source", + "__T3CODE_ENV_T3CODE_FEATURE_FLAGS_END__", + ].join("\n"), + ), + ), + () => + Effect.gen(function* () { + const missing: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; + const explicit: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + JAVA_HOME: "/custom/jdk", + T3CODE_FEATURE_FLAGS: "", + }; + + for (const env of [missing, explicit]) { + yield* fixPath().pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Environment, env), + Effect.provide(NodeServices.layer), + ); + } + + assert.equal(missing.JAVA_HOME, "/opt/homebrew/opt/openjdk@17"); + assert.equal(explicit.JAVA_HOME, "/custom/jdk"); + assert.equal(missing.T3CODE_FEATURE_FLAGS, "tanstack_source"); + assert.equal(explicit.T3CODE_FEATURE_FLAGS, ""); + }), + (probe) => Effect.sync(() => probe.mockRestore()), ), - () => - Effect.gen(function* () { - const missing: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; - const explicit: NodeJS.ProcessEnv = { - SHELL: "/bin/zsh", - PATH: "/usr/bin", - JAVA_HOME: "/custom/jdk", - }; - - for (const env of [missing, explicit]) { - yield* fixPath().pipe( - Effect.provideService(HostProcess.Platform, "darwin"), - Effect.provideService(HostProcess.Environment, env), - Effect.provide(NodeServices.layer), - ); - } - - assert.equal(missing.JAVA_HOME, "/opt/homebrew/opt/openjdk@17"); - assert.equal(explicit.JAVA_HOME, "/custom/jdk"); - }), - (probe) => Effect.sync(() => probe.mockRestore()), - ), ); effectIt.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () => diff --git a/apps/server/src/os-jank.ts b/apps/server/src/os-jank.ts index bc6528f91a5be..dc0c90a787123 100644 --- a/apps/server/src/os-jank.ts +++ b/apps/server/src/os-jank.ts @@ -32,7 +32,7 @@ function logPathHydrationWarning(message: string, error?: unknown): void { // __MISE_DIFF is mise's record of the PATH entries it added. It must travel // with the shell's PATH, or `mise x` can rebuild PATH behind a same-named // wrapper (`exec mise x claude -- claude`) that then re-runs itself forever. -const LOGIN_SHELL_ENV_NAMES = ["PATH", "__MISE_DIFF", "JAVA_HOME"] as const; +const LOGIN_SHELL_ENV_NAMES = ["PATH", "__MISE_DIFF", "JAVA_HOME", "T3CODE_FEATURE_FLAGS"] as const; const LOGIN_SHELL_TIMEOUT = Duration.seconds(5); const SLOW_LOGIN_SHELL_TIMEOUT_MS = 20_000; @@ -64,6 +64,10 @@ function applyLoginShellEnvironment( if (!env.JAVA_HOME && shellEnvironment.JAVA_HOME) { env.JAVA_HOME = shellEnvironment.JAVA_HOME; } + // A headless server (systemd, launchd) reads no profile, yet flags belong where users export them. + if (env.T3CODE_FEATURE_FLAGS === undefined && shellEnvironment.T3CODE_FEATURE_FLAGS) { + env.T3CODE_FEATURE_FLAGS = shellEnvironment.T3CODE_FEATURE_FLAGS; + } } function hydratePosixPath(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): void { diff --git a/apps/server/src/persistence/IssueTrackerBindings.ts b/apps/server/src/persistence/IssueTrackerBindings.ts index fbb0a398900d2..2f665b487e03f 100644 --- a/apps/server/src/persistence/IssueTrackerBindings.ts +++ b/apps/server/src/persistence/IssueTrackerBindings.ts @@ -26,7 +26,9 @@ const BindingRow = Schema.Struct({ export class IssueTrackerBindingsRepository extends Context.Service< IssueTrackerBindingsRepository, { - readonly list: Effect.Effect< + readonly list: ( + projectId?: ProjectId, + ) => Effect.Effect< ReadonlyMap, IssueTrackerBindingsRepositoryError >; @@ -56,32 +58,35 @@ function toSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + const select = sql` + SELECT project_id AS "projectId", tracker AS "tracker", scope AS "scope", + additional_scopes AS "additionalScopes" + FROM issue_tracker_bindings + `; const listRows = SqlSchema.findAll({ - Request: Schema.Void, + Request: Schema.UndefinedOr(ProjectId), Result: BindingRow, - execute: () => - sql` - SELECT project_id AS "projectId", tracker AS "tracker", scope AS "scope", - additional_scopes AS "additionalScopes" - FROM issue_tracker_bindings - `, + execute: (projectId) => + projectId === undefined ? select : sql`${select} WHERE project_id = ${projectId}`, }); return IssueTrackerBindingsRepository.of({ - list: listRows(undefined).pipe( - Effect.map( - (rows) => - new Map( - rows.map( - ({ projectId, additionalScopes, ...binding }) => - [ - projectId, - additionalScopes.length === 0 ? binding : { ...binding, additionalScopes }, - ] as const, + list: Effect.fn("IssueTrackerBindingsRepository.list")((projectId?: ProjectId) => + listRows(projectId).pipe( + Effect.map( + (rows) => + new Map( + rows.map( + ({ projectId, additionalScopes, ...binding }) => + [ + projectId, + additionalScopes.length === 0 ? binding : { ...binding, additionalScopes }, + ] as const, + ), ), - ), + ), + Effect.mapError(toSqlOrDecodeError("listIssueTrackerBindings", "IssueTrackerBinding")), ), - Effect.mapError(toSqlOrDecodeError("listIssueTrackerBindings", "IssueTrackerBinding")), ), set: Effect.fn("IssueTrackerBindingsRepository.set")( function* (input) { diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 91b521fdb6036..2b767af21f52f 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -113,6 +113,8 @@ import Migration0102 from "./Migrations/102_ThreadItemCounts.ts"; import Migration0103 from "./Migrations/103_IssueTrackerAdditionalScopes.ts"; import Migration0104 from "./Migrations/104_ProjectionProjectsTrackedFolders.ts"; import Migration0105 from "./Migrations/105_TaskFolders.ts"; +import Migration0106 from "./Migrations/106_WorktreePathKeyIndex.ts"; +import Migration0107 from "./Migrations/107_DeferredSlashCommandIndex.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -221,6 +223,8 @@ const migrationEntries = [ [103, "IssueTrackerAdditionalScopes", Migration0103], [104, "ProjectionProjectsTrackedFolders", Migration0104], [105, "TaskFolders", Migration0105], + [106, "WorktreePathKeyIndex", Migration0106], + [107, "DeferredSlashCommandIndex", Migration0107], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts new file mode 100644 index 0000000000000..c652d1f9bc851 --- /dev/null +++ b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts @@ -0,0 +1,48 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; + +const layer = it.layer(NodeSqliteClient.layer({ filename: ":memory:" })); +const updatedAt = "2026-09-01T00:00:00.000Z"; +const deliveredPayload = JSON.stringify({ completionDelivery: { state: "delivered" } }); + +layer("075_SubagentDeliveryState", (it) => { + it.effect("backfills delivery state without failing on an unreadable payload", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 74 }); + const payloads = [ + ["delivered", deliveredPayload], + ["unreadable", ""], + ]; + for (const [id, payload] of payloads) { + yield* sql` + INSERT INTO orchestration_v2_projection_subagents ( + subagent_id, thread_id, parent_node_id, provider, origin, status, updated_at, + payload_json + ) VALUES ( + ${id}, 'thread-1', 'node-1', 'codex', 'delegated', 'cancelled', ${updatedAt}, + ${payload} + ) + `; + } + + yield* runMigrations({ toMigrationInclusive: 75 }); + const rows = yield* sql` + SELECT subagent_id, completion_delivery_state, payload_json + FROM orchestration_v2_projection_subagents ORDER BY subagent_id + `; + assert.deepStrictEqual(rows, [ + { + subagent_id: "delivered", + completion_delivery_state: "delivered", + payload_json: deliveredPayload, + }, + { subagent_id: "unreadable", completion_delivery_state: null, payload_json: "" }, + ]); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts index 4406911cc8a8c..0288c89ceed05 100644 --- a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts +++ b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts @@ -11,7 +11,9 @@ export default Effect.gen(function* () { yield* sql` UPDATE orchestration_v2_projection_subagents SET completion_delivery_state = json_extract(payload_json, '$.completionDelivery.state') - WHERE json_type(payload_json, '$.completionDelivery') IS NOT NULL + WHERE CASE WHEN json_valid(payload_json) + THEN json_type(payload_json, '$.completionDelivery') IS NOT NULL + ELSE 0 END `; yield* sql` CREATE INDEX orchestration_v2_projection_subagents_settled_idx diff --git a/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts b/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts index 3ea190f41d2ed..9e61347812e74 100644 --- a/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts +++ b/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts @@ -21,13 +21,19 @@ it.layer(NodeSqliteClient.layer({ filename: ":memory:" }))( ); const projectId = ProjectId.make("web"); const binding = { tracker: IssueTrackerKind.make("linear"), scope: "ENG" }; - const read = () => bindings.list.pipe(Effect.map((all) => all.get(projectId))); + const read = () => bindings.list(projectId).pipe(Effect.map((rows) => rows.get(projectId))); assert.deepStrictEqual(yield* read(), binding); const multi = { ...binding, additionalScopes: ["OPS", "DOCS"] }; yield* bindings.set({ projectId, binding: multi, updatedAt: "2026-11-21" }); assert.deepStrictEqual(yield* read(), multi); yield* bindings.set({ projectId, binding, updatedAt: "2026-11-21" }); assert.deepStrictEqual(yield* read(), binding); + yield* sql` + INSERT INTO issue_tracker_bindings (project_id, tracker, scope, updated_at, additional_scopes) + VALUES ('other', 'linear', 'OPS', '2026-11-21', 'invalid') + `; + assert.deepStrictEqual(yield* read(), binding); + assert.strictEqual((yield* Effect.result(bindings.list()))._tag, "Failure"); }), ); }, diff --git a/apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts b/apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts new file mode 100644 index 0000000000000..9b1b42647d60a --- /dev/null +++ b/apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Keep this expression identical to ProjectionStore's loose worktree filter. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_threads_worktree_path_key_idx + ON orchestration_v2_projection_threads( + CASE WHEN json_valid(payload_json) + THEN lower(rtrim(replace(trim(json_extract(payload_json, '$.worktreePath')), '\\', '/'), '/')) + END + ) + `; +}); diff --git a/apps/server/src/persistence/Migrations/107_DeferredSlashCommandIndex.ts b/apps/server/src/persistence/Migrations/107_DeferredSlashCommandIndex.ts new file mode 100644 index 0000000000000..5c997fbc20a63 --- /dev/null +++ b/apps/server/src/persistence/Migrations/107_DeferredSlashCommandIndex.ts @@ -0,0 +1,17 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { DEFERRED_COMMAND_MESSAGE_CONDITION } from "../../orchestration-v2/deferredCommandMessage.ts"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // The turn-start read now matches every slash command; a partial index is only used when its + // predicate spells the read's condition, so rebuild the one migration 100 made. + yield* sql`DROP INDEX IF EXISTS orchestration_v2_projection_messages_deferred_command_idx`; + yield* sql.unsafe(` + CREATE INDEX orchestration_v2_projection_messages_deferred_command_idx + ON orchestration_v2_projection_messages(thread_id, created_at, message_id) + WHERE ${DEFERRED_COMMAND_MESSAGE_CONDITION} + `); +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index d2b0dafab8731..e7ec467f3ec0a 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -85,6 +85,8 @@ describe("V2 preview upgrade", () => { [103, "IssueTrackerAdditionalScopes"], [104, "ProjectionProjectsTrackedFolders"], [105, "TaskFolders"], + [106, "WorktreePathKeyIndex"], + [107, "DeferredSlashCommandIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -213,6 +215,8 @@ describe("V2 preview upgrade", () => { [103, "IssueTrackerAdditionalScopes"], [104, "ProjectionProjectsTrackedFolders"], [105, "TaskFolders"], + [106, "WorktreePathKeyIndex"], + [107, "DeferredSlashCommandIndex"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index 9d1460c9befd5..a15378ec3039c 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -235,7 +235,6 @@ function makeContext(onClose?: (context: BrowserContext) => void, initialUrl = " title: "test page", loading: false, visibleText: "delete", - interactiveElements: [], })), ariaSnapshot: vi.fn(async () => '- button "delete" [ref=e1]'), locator: vi.fn((): unknown => { diff --git a/apps/server/src/preview/ServerBrowserPage.test.ts b/apps/server/src/preview/ServerBrowserPage.test.ts index 79ccc4089aeee..9afe924dabc4c 100644 --- a/apps/server/src/preview/ServerBrowserPage.test.ts +++ b/apps/server/src/preview/ServerBrowserPage.test.ts @@ -61,7 +61,6 @@ describe("snapshot deadline diagnostics", () => { title: "", loading: false, visibleText: "", - interactiveElements: [], }), ariaSnapshot: async () => "", ...options.page, @@ -275,6 +274,23 @@ describe("server browser element refs", () => { }; const repeatedRows = `
    ${Array.from({ length: 5 }, (_, i) => `
  • row ${i + 1}
  • `).join("")}
`; + it("does not report an empty interactiveElements list beside a tree full of controls", async () => { + await page.setContent( + `
Sign in`, + ); + const result = await takeSnapshot(); + expect(buttonLocator(result.accessibilityTree, "Open menu")).toBeDefined(); + expect(String(result.accessibilityTree)).toContain('link "Sign in"'); + const elements = ( + result as { readonly interactiveElements?: ReadonlyArray<{ readonly name: string }> } + ).interactiveElements; + if (elements !== undefined) { + expect(elements.map((element) => element.name)).toEqual( + expect.arrayContaining(["Sign in", "Open menu", "Dismiss local database notice"]), + ); + } + }); + it("clicks the fifth repeated delete control without touching row one", async () => { await page.setContent(repeatedRows); const result = await takeSnapshot(); diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index ac37b9914ef76..f5eed496da5fe 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -198,7 +198,6 @@ const SNAPSHOT_SCRIPT = `(() => { title: document.title, loading: document.readyState !== "complete", visibleText: document.body?.innerText || "", - interactiveElements: [], }; })()`; @@ -699,10 +698,7 @@ const capture = async ( "page state", () => input.page.evaluate(SNAPSHOT_SCRIPT) as Promise< - Pick< - PreviewAutomationSnapshot, - "url" | "title" | "loading" | "visibleText" | "interactiveElements" - > + Pick >, ), // A cheap real frame still sizes the screenshot; computing it from metrics drifted from the PNG. diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 8ce873733d443..827d52bbda230 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -65,6 +65,7 @@ const layerTest = (input: { readonly onSpawn?: (command: ChildProcess.StandardCommand) => void; readonly onUnref?: () => void; readonly spawnResult?: (command: ChildProcess.StandardCommand) => MockSpawnResult | undefined; + readonly existingPaths?: ReadonlyArray; }) => { const layerSpawner = Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, @@ -92,6 +93,17 @@ const layerTest = (input: { NodeServices.layer, layerSpawner, input.path ? Layer.succeed(Path.Path, input.path) : Layer.empty, + // Reveal fixtures name paths that do not exist on the test host. + Layer.effect( + FileSystem.FileSystem, + Effect.map(FileSystem.FileSystem, (fileSystem) => ({ + ...fileSystem, + exists: (path: string) => + input.existingPaths?.includes(path) + ? Effect.succeed(true) + : fileSystem.exists(path), + })), + ).pipe(Layer.provide(NodeServices.layer)), ), ), ), @@ -571,6 +583,7 @@ for (const [replacement, verb, handler, target, expected] of [ layerTest({ platform: "win32", env: { PATH: "C:\\Windows", PATHEXT: ".EXE" }, + existingPaths: [target], onSpawn: (command) => { spawned = command; }, @@ -605,16 +618,13 @@ it.effect.skipIf(windowsHost)( yield* fileSystem.chmod(filePath, 0o755); } + const target = "/home/t3/workspace [draft]/author's ‘$media/clip|draft.mp4"; let spawned: ChildProcess.StandardCommand | undefined; const result = yield* Effect.gen(function* () { const launcher = yield* ExternalLauncher.ExternalLauncher; const kind = yield* launcher.resolveFileManagerRevealKind(); const editors = yield* launcher.resolveAvailableEditors(); - yield* launcher.launchEditor({ - editor: "file-manager", - cwd: "/home/t3/workspace [draft]/author's ‘$media/clip|draft.mp4", - reveal: true, - }); + yield* launcher.launchEditor({ editor: "file-manager", cwd: target, reveal: true }); return { kind, editors }; }).pipe( Effect.provide( @@ -625,6 +635,7 @@ it.effect.skipIf(windowsHost)( WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop", }, + existingPaths: [target], onSpawn: (command) => { spawned = command; }, @@ -687,6 +698,7 @@ it.effect.each([ layerTest({ platform: "win32", env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: "C:\\Windows" }, + existingPaths: ["C:/Users/t3/my project/a,b.ts"], onSpawn: (command) => spawned.push(command), spawnResult: (command) => (command.command.endsWith("reg.exe") ? registry : undefined), }), @@ -718,6 +730,38 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +// Explorer answers /select of a missing path by opening its default folder, not the parent. +it.effect("does not ask Explorer to select a file that does not exist", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + yield* fileSystem.writeFileString(path.join(binDir, "explorer.EXE"), ""); + const missing = path.join(binDir, "CLAUDE.md"); + const verbatim: Array]> = []; + yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + yield* launcher + .launchEditor({ editor: "file-manager", cwd: missing, reveal: true }) + .pipe(Effect.exit); + }).pipe( + Effect.provideService(WindowsVerbatimSpawn, (command, args) => + Effect.sync(() => verbatim.push([command, args])), + ), + Effect.provide( + layerTest({ + platform: "win32", + env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: "C:\\Windows" }, + spawnResult: (command) => + command.command.endsWith("reg.exe") ? { stdout: STOCK_FOLDER_VERB } : undefined, + }), + ), + ); + + assert.deepEqual(verbatim, []); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + for (const wsl of [false, true]) { it.effect.skipIf(windowsHost)( "selects a file over D-Bus on " + (wsl ? "WSLg without interop PowerShell" : "Linux"), @@ -747,6 +791,7 @@ for (const wsl of [false, true]) { ? { WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop" } : {}), }, + existingPaths: [target], onSpawn: (command) => spawnedCommands.push(command), spawnResult: (command) => command.command === "xdg-mime" diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index caa6664a1ba80..b5ffaf82fcc10 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -6,6 +6,7 @@ import { ExternalLauncherBrowserSpawnError, ExternalLauncherCommandNotFoundError, ExternalLauncherEditorSpawnError, + ExternalLauncherRevealTargetMissingError, ExternalLauncherUnknownEditorError, ExternalLauncherUnsupportedEditorError, ExternalLauncherUnsupportedTargetError, @@ -15,11 +16,7 @@ import { } from "@t3tools/contracts"; import { resolveEditorCommand } from "@t3tools/shared/editor"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import { - isCommandAvailable, - resolveSpawnCommand, - withPathDirectoryListings, -} from "@t3tools/shared/shell"; +import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell"; import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -40,6 +37,7 @@ export { ExternalLauncherBrowserSpawnError, ExternalLauncherCommandNotFoundError, ExternalLauncherEditorSpawnError, + ExternalLauncherRevealTargetMissingError, ExternalLauncherUnknownEditorError, ExternalLauncherUnsupportedEditorError, ExternalLauncherUnsupportedTargetError, @@ -503,7 +501,7 @@ const readEditorEnv = Effect.fn("externalLauncher.readEditorEnv")(function* () { const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () { const platform = yield* HostProcess.Platform; const env = yield* readEditorEnv(); - return yield* buildAvailableEditors(platform, env).pipe(withPathDirectoryListings); + return yield* buildAvailableEditors(platform, env); }); const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")( @@ -594,6 +592,13 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( } if (input.reveal === true) { + // Explorer answers /select of a missing path by opening its default folder, not the parent. + const exists = yield* (yield* FileSystem.FileSystem) + .exists(target) + .pipe(Effect.orElseSucceed(() => true)); + if (!exists) { + return yield* new ExternalLauncherRevealTargetMissingError({ editor: editorDef.id, target }); + } return yield* resolveFileManagerRevealLaunch(target, platform, env, command); } diff --git a/apps/server/src/project/ProjectCloneTracker.test.ts b/apps/server/src/project/ProjectCloneTracker.test.ts index bdbb47b767c03..3b2e6f1179b86 100644 --- a/apps/server/src/project/ProjectCloneTracker.test.ts +++ b/apps/server/src/project/ProjectCloneTracker.test.ts @@ -312,6 +312,68 @@ describe("ProjectCloneTracker", () => { }).pipe(Effect.provide(harness.layer)); }); + it.effect("a fresh clone into a failed clone's destination supersedes it", () => { + let attempts = 0; + const harness = makeHarness({ + clone: (input) => + Effect.suspend(() => + ++attempts === 1 + ? Effect.fail( + new SourceControlRepositoryError({ + operation: "cloneRepository", + provider: SourceControlProviderKind.make("unknown"), + detail: "fatal: repository not found", + }), + ) + : Effect.succeed({ + cwd: input.destinationPath, + remoteUrl: input.remoteUrl ?? "", + repository: null, + }), + ), + }); + // The failed clone's project still owns the destination. + const conflictingHooks: ProjectCloneTracker.ProjectCloneHooks = { + ...harness.hooks, + createProject: (input) => + Effect.fail( + new ProjectConflictError({ + projectId: input.projectId, + workspaceRoot: input.workspaceRoot, + conflictingProjectId: projectId, + }), + ), + }; + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + yield* tracker.start(startInput, harness.hooks); + yield* Effect.yieldNow; + expect((yield* tracker.get(projectId))?.phase).toBe("failed"); + + const second = ProjectId.make("project-2"); + const result = yield* tracker.start({ ...startInput, projectId: second }, conflictingHooks); + expect(result.projectId).toBe(projectId); + yield* Effect.yieldNow; + expect((yield* tracker.get(projectId))?.phase).toBe("done"); + expect(yield* tracker.get(second)).toBeNull(); + expect(harness.cloned).toEqual([projectId]); + }).pipe(Effect.provide(harness.layer)); + }); + + it.effect("refuses a second clone into a destination that is still cloning", () => { + const harness = makeHarness({ clone: () => Effect.never }); + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + yield* tracker.start(startInput, harness.hooks); + yield* Effect.yieldNow; + const error = yield* Effect.flip( + tracker.start({ ...startInput, projectId: ProjectId.make("project-2") }, harness.hooks), + ); + expect(error.message).toContain("already in progress"); + expect((yield* tracker.get(projectId))?.phase).toBe("running"); + }).pipe(Effect.provide(harness.layer)); + }); + it.effect("does not create a project when the clone cannot be prepared", () => { const harness = makeHarness(); const layer = ProjectCloneTracker.layer.pipe( diff --git a/apps/server/src/project/ProjectCloneTracker.ts b/apps/server/src/project/ProjectCloneTracker.ts index 0a24f11ffd89d..367b839cf2a6b 100644 --- a/apps/server/src/project/ProjectCloneTracker.ts +++ b/apps/server/src/project/ProjectCloneTracker.ts @@ -297,14 +297,19 @@ export const make = Effect.gen(function* () { endedAt: null, sequence: ++sequence, }; - const claimed = yield* Ref.modify(clones, (current) => { - const conflict = Array.from(current.values()).some( + const claim = yield* Ref.modify(clones, (current) => { + const overlapping = Array.from(current.values()).filter( (tracked) => tracked.snapshot.projectId === input.projectId || tracked.input.destinationPath === prepared.destinationPath, ); - if (conflict) return [false, current] as const; + // Only a running clone owns its destination; a failed or cancelled one + // left nothing behind, so a fresh start supersedes it. + if (overlapping.some((tracked) => tracked.snapshot.phase === "running")) { + return [null, current] as const; + } const next = new Map(current); + for (const stale of overlapping) next.delete(stale.snapshot.projectId); next.set(input.projectId, { snapshot, fiber: null, @@ -316,14 +321,16 @@ export const make = Effect.gen(function* () { protocol: input.protocol ?? "auto", }, }); - return [true, next] as const; + return [overlapping.map((stale) => stale.snapshot.projectId), next] as const; }); const alreadyInProgress = new SourceControlRepositoryError({ operation: "cloneRepository", provider: input.provider ?? SourceControlProviderKind.make("unknown"), detail: "A clone into this destination is already in progress.", }); - if (!claimed) return yield* alreadyInProgress; + if (claim === null) return yield* alreadyInProgress; + // A superseded done entry's pending removal would otherwise delete the new claim. + yield* Effect.forEach(claim, clearRetention, { discard: true }); // Finish or release the claim despite disconnects; a claim without a fiber cannot be cancelled or retried. const projectId = yield* Effect.uninterruptible( Effect.gen(function* () { diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index 0628030b8f91c..c495feb4cef66 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -197,6 +197,16 @@ describe("ProjectSetupScriptRunner", () => { }), ); + it.effect("keeps emoji whole when capping a long output line or partial-line buffer", () => + Effect.gen(function* () { + const { outputLines, emit } = yield* setup(); + yield* emit({ ...event, type: "output", data: `x${"🙂".repeat(250)}\r\n` }); + yield* emit({ ...event, type: "output", data: `${"🙂".repeat(2_100)}x` }); + yield* emit({ ...event, type: "output", data: "\r\n" }); + expect(yield* Queue.takeAll(outputLines)).toEqual([`x${"🙂".repeat(199)}`, "🙂".repeat(200)]); + }), + ); + it.effect("types into a quiet shell that has no line editor", () => Effect.gen(function* () { const { writes } = yield* setup(); diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index 0f2e58d121402..1c94a3f118757 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -1,4 +1,5 @@ import { linkOriginIsFenced, ProjectId, type ProjectScript, ThreadId } from "@t3tools/contracts"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import { projectScriptRuntimeEnv, projectScriptTerminalInput, @@ -310,7 +311,14 @@ export const make = Effect.gen(function* () { ) { return Effect.void; } - return input.onOutputLine(cleaned.slice(0, OUTPUT_LINE_MAX_LENGTH)); + return input.onOutputLine( + cleaned.slice( + 0, + splitsSurrogatePair(cleaned, OUTPUT_LINE_MAX_LENGTH) + ? OUTPUT_LINE_MAX_LENGTH - 1 + : OUTPUT_LINE_MAX_LENGTH, + ), + ); }); const unsubscribe = yield* terminalManager.subscribe((event) => { @@ -324,7 +332,10 @@ export const make = Effect.gen(function* () { lineBuffer = lines.pop() ?? ""; // Bound newline-free output; the sentinel has its own line, so retaining the tail is safe. if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) { - lineBuffer = lineBuffer.slice(-PARTIAL_LINE_MAX_LENGTH); + const start = lineBuffer.length - PARTIAL_LINE_MAX_LENGTH; + lineBuffer = lineBuffer.slice( + splitsSurrogatePair(lineBuffer, start) ? start + 1 : start, + ); } return Effect.forEach(lines, handleLine, { discard: true }).pipe( Effect.andThen( diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index 522be29a8b187..88589d1c9a773 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -7,6 +7,7 @@ import { ProviderDriverKind, ProviderInstanceId, ProviderSetupError, + type RuntimeMode, type ServerProviderUsageLimits, } from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; @@ -138,8 +139,10 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( readonly enabled?: boolean; readonly safe?: boolean; readonly probeUsage?: Effect.Effect; + readonly rememberedRuntimeModes?: ReadonlyArray; } = {}, ) { + const savedRuntimeModes = yield* Ref.make>>([]); const initialProbe = yield* Deferred.make(); const probeCalls = yield* Ref.make(0); const safetyCalls = yield* Ref.make(0); @@ -153,6 +156,10 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( stampIdentity: (snapshot) => Effect.succeed({ ...snapshot, instanceId, driver }), ...(options.auth ? { auth: options.auth } : {}), ...(options.probeUsage ? { probeUsage: options.probeUsage } : {}), + ...(options.rememberedRuntimeModes + ? { rememberedRuntimeModes: options.rememberedRuntimeModes } + : {}), + rememberRuntimeModes: (modes) => Ref.update(savedRuntimeModes, (saved) => [...saved, modes]), probe: Ref.update(probeCalls, (count) => count + 1).pipe( Effect.andThen(Ref.get(probe)), Effect.flatten, @@ -187,6 +194,7 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( initialUpdate, initialize, nextPublish, + savedRuntimeModes, }; }); @@ -381,6 +389,25 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { yield* harness.provider.onSessionStarted(startedWithAuto); yield* harness.provider.onSignedOut; expect(yield* supportedModes).toEqual(withoutAuto); + const withAuto: ReadonlyArray = [ + "approval-required", + "auto-accept-edits", + "auto", + "full-access", + ]; + expect(yield* Ref.get(harness.savedRuntimeModes)).toEqual([ + withAuto, + withoutAuto, + withAuto, + withoutAuto, + ]); + + // A restart offers what the last session advertised before any session starts. + const restarted = yield* makeHarness({ rememberedRuntimeModes: withAuto }); + yield* restarted.initialize; + expect(yield* restarted.provider.snapshot.getSnapshot).toMatchObject({ + supportedRuntimeModes: withAuto, + }); }), ); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index b3b68d46e8ba8..f5e18f6bece9d 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -172,6 +172,9 @@ interface AntigravityProviderOptions { readonly clearUsage?: Effect.Effect; readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities; readonly auth?: { readonly type: string; readonly label: string }; + /** Modes the last session advertised, saved because initialize alone does not report them. */ + readonly rememberedRuntimeModes?: ReadonlyArray; + readonly rememberRuntimeModes?: (modes: ReadonlyArray) => Effect.Effect; } const RUNTIME_MODES_WITHOUT_AUTO = [ @@ -209,7 +212,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func presentation: { displayName: "Antigravity", showInteractionModeToggle: false, - supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO, + supportedRuntimeModes: options.rememberedRuntimeModes ?? RUNTIME_MODES_WITHOUT_AUTO, }, enabled: settings.enabled, checkedAt, @@ -246,6 +249,14 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func thinkingLevels.set(model.currentValue, antigravityThinkingConfig(configOptions) ?? null); } }; + const rememberRuntimeModes = Effect.fn("AntigravityProvider.rememberRuntimeModes")(function* ( + previous: ReadonlyArray | undefined, + next: ReadonlyArray, + ) { + if (options.rememberRuntimeModes && previous?.join() !== next.join()) { + yield* options.rememberRuntimeModes(next); + } + }); const getSnapshot = SubscriptionRef.get(metadata).pipe( Effect.flatMap((state) => options.stampIdentity(state.draft)), ); @@ -400,17 +411,18 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func const before = yield* SubscriptionRef.get(metadata); const supportsTextGeneration = yield* options.supportsTextGeneration; const updatedAt = DateTime.formatIso(yield* DateTime.now); - yield* SubscriptionRef.update(metadata, (state) => { + const supportedRuntimeModes = antigravityRuntimeModes(started.sessionSetupResult); + const previousModes = yield* SubscriptionRef.modify(metadata, (state) => { if ( state.authRevision !== before.authRevision && state.draft.auth.status === "unauthenticated" ) { - return state; + return [supportedRuntimeModes, state] as const; } const { message: _previousMessage, ...draft } = state.draft; const workspaces = draft.workspaceSnapshots ?? []; const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined; - return { + const next = { authRevision: state.authRevision + 1, draft: { ...draft, @@ -424,7 +436,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func }, checkedAt: updatedAt, models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels), - supportedRuntimeModes: antigravityRuntimeModes(started.sessionSetupResult), + supportedRuntimeModes, supportsTextGeneration, ...(cwd ? { @@ -441,7 +453,9 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func : {}), }, } satisfies AntigravityProviderState; + return [draft.supportedRuntimeModes, next] as const; }); + yield* rememberRuntimeModes(previousModes, supportedRuntimeModes); if (!before.draft.usageLimits || before.draft.usageLimits.unavailable) yield* refreshUsage(); }); @@ -495,30 +509,30 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func yield* resetUsage; if (!settings.enabled) return; const updatedAt = DateTime.formatIso(yield* DateTime.now); - yield* SubscriptionRef.update( - metadata, - (state) => - ({ - authRevision: state.authRevision + 1, - draft: { - ...state.draft, - auth: { - status: "unauthenticated", - ...(usesCredentials ? options.auth : {}), - }, - status: "warning", - message: signInMessage, - checkedAt: updatedAt, - models: [], - slashCommands: [], - skills: [], - workspaceSnapshots: [], - supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO, - supportsTextGeneration: false, - usageLimits: undefined, + const previousModes = yield* SubscriptionRef.modify(metadata, (state) => [ + state.draft.supportedRuntimeModes, + { + authRevision: state.authRevision + 1, + draft: { + ...state.draft, + auth: { + status: "unauthenticated", + ...(usesCredentials ? options.auth : {}), }, - }) satisfies AntigravityProviderState, - ); + status: "warning", + message: signInMessage, + checkedAt: updatedAt, + models: [], + slashCommands: [], + skills: [], + workspaceSnapshots: [], + supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO, + supportsTextGeneration: false, + usageLimits: undefined, + }, + } satisfies AntigravityProviderState, + ]); + yield* rememberRuntimeModes(previousModes, RUNTIME_MODES_WITHOUT_AUTO); discoveredSkills.clear(); thinkingLevels.clear(); }); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 3d426785813c3..b0d11b453dc61 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -3,8 +3,10 @@ import { AntigravitySettings, ProviderDriverKind, ProviderSetupError, + RuntimeMode, settingsSecretLiteral, } from "@t3tools/contracts"; +import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; import { @@ -17,6 +19,7 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; +import * as Option from "effect/Option"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; @@ -86,6 +89,11 @@ const isNodeRuntimeUnavailableError = Schema.is(NodeRuntimeUnavailableError); const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError); const isProviderSetupError = Schema.is(ProviderSetupError); const isAcpErrorDetails = Schema.is(Schema.Struct({ details: Schema.String })); +const RememberedRuntimeModes = Schema.fromJsonString( + Schema.Struct({ authMethod: Schema.String, modes: Schema.Array(RuntimeMode) }), +); +const decodeRememberedRuntimeModes = Schema.decodeUnknownOption(RememberedRuntimeModes); +const encodeRememberedRuntimeModes = Schema.encodeSync(RememberedRuntimeModes); const REFRESH_FAILED = "Could not refresh Antigravity models. The previous model list is unchanged."; const PYTHON_SOCKS_REQUIRED = "python-socks is required to use a SOCKS proxy"; @@ -178,6 +186,18 @@ export const AntigravityDriver: ProviderDriver< ), ); const profileDirectory = directories.profile; + // Only a session reports whether agy offers Auto, so keep the last answer across restarts. + const runtimeModesPath = path.join(profileDirectory, "t3-runtime-modes.json"); + const rememberedRuntimeModes = yield* fileSystem.readFileString(runtimeModesPath).pipe( + Effect.map((contents) => + decodeRememberedRuntimeModes(contents).pipe( + Option.filter((saved) => saved.authMethod === auth.authMethod), + Option.map((saved) => saved.modes), + Option.getOrUndefined, + ), + ), + Effect.orElseSucceed(() => undefined), + ); for (const directory of [ directories.runtimeTemp, path.join(profileDirectory, "antigravity-acp", "tmp"), @@ -572,6 +592,16 @@ export const AntigravityDriver: ProviderDriver< probeUsage: usage.probe, clearUsage: usage.clear, auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) }, + ...(rememberedRuntimeModes ? { rememberedRuntimeModes } : {}), + rememberRuntimeModes: (modes) => + writeFileStringAtomically({ + filePath: runtimeModesPath, + contents: encodeRememberedRuntimeModes({ authMethod: auth.authMethod, modes }), + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.catch(() => Effect.logWarning("Could not save Antigravity permission modes.")), + ), supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 0033755bfe706..40d78ab16b05f 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -381,7 +381,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { path.join(sharedSkills, "yagni"), "---\nname: yagni\ndescription: Keep it simple.\n---\n", ); - yield* writeSkill( + const experimentalPath = yield* writeSkill( path.join(sharedSkills, "experimental-draft"), "---\nname: experimental-draft\n---\n", ); @@ -392,11 +392,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { "---\nname: linter\n---\n", ); yield* writeSkill(path.join(inheritedSkills, "skipped"), "---\nname: skipped\n---\n"); - // Backtracks exponentially under RegExp against the pattern below. - yield* writeSkill( - path.join(inheritedSkills, "a".repeat(40)), - "---\nname: backtrack\n---\n", - ); + yield* writeSkill(path.join(inheritedSkills, "lint-draft"), "---\nname: lint-draft\n---\n"); const projectSkills = path.join(input.cwd, "tools", "skills"); const projectPath = yield* writeSkill( @@ -425,7 +421,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { yield* fileSystem.writeFileString( path.join(globalConfigDir, "skills.json"), JSON.stringify({ - inherits: [{ path: inheritedConfigPath, include_only: ["linter", "(a*)*b"] }], + inherits: [{ path: inheritedConfigPath, include_only: ["linter", "lint-.*"] }], entries: [ { path: sharedSkills, exclude: ["experimental-.*"] }, { path: "~/tilde-skills" }, @@ -452,6 +448,12 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { assert.deepEqual(yield* discoverAntigravitySkills(input), [ { name: "deploy", path: projectPath, scope: "project", enabled: true }, + { + name: "experimental-draft", + path: experimentalPath, + scope: "user", + enabled: true, + }, { name: "linter", path: inheritedPath, scope: "user", enabled: true }, { name: "yagni", diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index f69b3d1c455be..edbe5e34a7343 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -185,106 +185,21 @@ const readSkillFrontmatter = Effect.fn("readAntigravitySkill")(function* ( return bytes.toString("utf8", 0, frontmatterEnd); }); -type SkillPatternMatcher = (entry: string) => boolean; - interface SkillEntryFilter { - readonly includeGroups: ReadonlyArray>; - readonly excludePatterns: ReadonlyArray; + readonly includeGroups: ReadonlyArray>; + readonly excludeNames: ReadonlyArray; } const EMPTY_SKILL_FILTER: SkillEntryFilter = { includeGroups: [], - excludePatterns: [], + excludeNames: [], }; -interface SkillPatternToken { - readonly test: (character: string) => boolean; - readonly optional: boolean; - readonly repeats: boolean; -} - -/** Undefined for syntax outside literals, escapes, `.`, `[...]` and `* + ?`; such patterns match literally. */ -function parseSkillPattern(pattern: string): ReadonlyArray | undefined { - const characters = Array.from(pattern); - const tokens: Array = []; - let index = 0; - while (index < characters.length) { - const character = characters[index]!; - let test: (candidate: string) => boolean; - if (character === "\\") { - const escaped = characters[index + 1]; - if (escaped === undefined) return undefined; - if (/[dDwWsS]/.test(escaped)) { - const characterClass = new RegExp(`^\\${escaped}$`, "u"); - test = (candidate) => characterClass.test(candidate); - } else { - test = (candidate) => candidate === escaped; - } - index += 2; - } else if (character === "[") { - const close = characters.indexOf("]", index + 2); - if (close === -1) return undefined; - let characterClass: RegExp; - try { - characterClass = new RegExp(`^[${characters.slice(index + 1, close).join("")}]$`, "u"); - } catch { - return undefined; - } - test = (candidate) => characterClass.test(candidate); - index = close + 1; - } else if (character === ".") { - test = () => true; - index += 1; - } else if ("()|{}^$*+?".includes(character)) { - return undefined; - } else { - test = (candidate) => candidate === character; - index += 1; - } - const quantifier = characters[index]; - const optional = quantifier === "*" || quantifier === "?"; - const repeats = quantifier === "*" || quantifier === "+"; - if (optional || repeats) { - index += 1; - if (characters[index] === "?") index += 1; - } - tokens.push({ test, optional, repeats }); - } - return tokens; -} - -/** Manifests can come from an opened workspace, so matching runs as an NFA in linear time instead of RegExp. */ -function compileSkillPattern(pattern: string): SkillPatternMatcher { - const tokens = parseSkillPattern(pattern); - if (tokens === undefined) return (entry) => entry === pattern; - const close = (states: Set) => { - for (const state of states) { - if (state < tokens.length && tokens[state]!.optional) states.add(state + 1); - } - return states; - }; - return (entry) => { - let states = close(new Set([0])); - for (const character of entry) { - const next = new Set(); - for (const state of states) { - const token = tokens[state]; - if (!token?.test(character)) continue; - next.add(state + 1); - if (token.repeats) next.add(state); - } - if (next.size === 0) return false; - states = close(next); - } - return states.has(tokens.length); - }; -} - function matchesSkillFilter(entry: string, filter: SkillEntryFilter): boolean { for (const group of filter.includeGroups) { - if (!group.some((matches) => matches(entry))) return false; + if (!group.includes(entry)) return false; } - return !filter.excludePatterns.some((matches) => matches(entry)); + return !filter.excludeNames.includes(entry); } function narrowSkillFilter( @@ -293,13 +208,13 @@ function narrowSkillFilter( ): SkillEntryFilter { const includeGroups = entry.include_only && entry.include_only.length > 0 - ? [...parent.includeGroups, entry.include_only.map(compileSkillPattern)] + ? [...parent.includeGroups, entry.include_only] : parent.includeGroups; - const excludePatterns = + const excludeNames = entry.exclude && entry.exclude.length > 0 - ? [...parent.excludePatterns, ...entry.exclude.map(compileSkillPattern)] - : parent.excludePatterns; - return { includeGroups, excludePatterns }; + ? [...parent.excludeNames, ...entry.exclude] + : parent.excludeNames; + return { includeGroups, excludeNames }; } // agy does not expand ~, so a ~/ path stays relative to the config file. diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts index b6dc61470e497..36d7e3f3313fc 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts @@ -21,7 +21,7 @@ function withWindowsResolution(input: { return (effect: Effect.Effect) => effect.pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => input.resolvedCommand), + Effect.provideService(SpawnExecutableResolution, async () => input.resolvedCommand), Effect.provideService(ClaudeExecutableFileCheck, (filePath) => existing.has(filePath)), ); } diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.ts index 5797066446b99..6f4e85812f0cc 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.ts @@ -50,7 +50,9 @@ export const resolveClaudeSdkExecutablePath = Effect.fn("resolveClaudeSdkExecuta const resolveExecutable = yield* SpawnExecutableResolution; const isFile = yield* ClaudeExecutableFileCheck; - const resolved = resolveExecutable(binaryPath, platform, environment) ?? binaryPath; + const resolved = + (yield* Effect.promise(async () => resolveExecutable(binaryPath, platform, environment))) ?? + binaryPath; const extension = NodePath.win32.extname(resolved).toLowerCase(); if (!WINDOWS_SHIM_EXTENSIONS.has(extension)) { return resolved; diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index e4ec16b77dde0..69b7bd9eb2c1d 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -565,6 +565,11 @@ const layerTestNodeServices = Layer.mergeAll( Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { getEnvironmentId: Effect.succeed(EnvironmentId.make("00000000-0000-4000-8000-000000000001")), }), + // A login shell that prints nothing, so refreshes never take PATH from the developer's profile. + Layer.effect( + HostProcess.Environment, + Effect.sync(() => ({ ...process.env, SHELL: "/usr/bin/true" })), + ), // An empty home, so the developer's own Claude settings never reach provider probes. Layer.effect( HostProcess.HomeDirectory, @@ -2562,10 +2567,37 @@ it.layer( }), ); - it.effect( - "rebuilds only instances missing their CLI when a refresh finds a new Windows PATH", - () => { - const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows" }; + // A login shell stand-in that prints the capture with one more PATH entry, as a profile edited + // after launch would. + const withLateLoginShell = (effect: (shell: string) => Effect.Effect) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-login-shell-" }); + const shell = `${dir}/sh`; + yield* fs.writeFileString( + shell, + '#!/bin/sh\nPATH=/opt/late:/usr/bin exec /bin/sh -c "$2"\n', + ); + yield* fs.chmod(shell, 0o755); + return yield* effect(shell); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)); + + it.effect.each([ + { + name: "Windows PATH", + platform: "win32" as const, + path: "C:\\Windows", + expectedPath: "C:\\Windows;C:\\Tools", + }, + { + name: "login-shell PATH", + platform: "linux" as const, + path: "/usr/bin", + expectedPath: "/opt/late:/usr/bin", + }, + ])("rebuilds only instances missing their CLI when a refresh finds a new $name", (host) => + withLateLoginShell((shell) => { + const env: NodeJS.ProcessEnv = { PATH: host.path, SHELL: shell }; return Effect.gen(function* () { const driver = ProviderDriverKind.make("codex"); const makeInstance = (id: string, installed: boolean): ProviderInstance => { @@ -2627,7 +2659,9 @@ it.layer( }), ), Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-path-" }), + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-path-", + }), ), Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ), @@ -2636,16 +2670,16 @@ it.layer( yield* registry.refresh(); - assert.strictEqual(env.PATH, "C:\\Windows;C:\\Tools"); + assert.strictEqual(env.PATH, host.expectedPath); assert.deepStrictEqual(rebuilt, [[ProviderInstanceId.make("missing")]]); }).pipe( - Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.Platform, host.platform), Effect.provideService(HostProcess.Environment, env), Effect.provideService(WindowsShellEnvironment, () => Effect.succeed({ PATH: "C:\\Windows;C:\\Tools" }), ), ); - }, + }), ); it.effect("rescans a requested cwd whose snapshot is still current", () => diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index 43f57bb99a777..43d66cd1ca049 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -26,12 +26,14 @@ import * as Ref from "effect/Ref"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as Semaphore from "effect/Semaphore"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; import * as ModelManifest from "./ModelManifest.ts"; import { applyProviderCompatibility } from "./providerCompatibility.ts"; import * as ServerConfig from "../config.ts"; -import { refreshWindowsPath } from "../os-jank.ts"; +import { refreshPathFromLoginShell, refreshWindowsPath } from "../os-jank.ts"; import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts"; import { @@ -747,7 +749,20 @@ export const layer = Layer.effect( // A refresh is how a user asks T3 to see a CLI installed since launch; a burst shares one probe. // Drivers copy the environment when built, so instances still missing their CLI are rebuilt // on the new PATH. They cannot have live sessions, and installed ones keep theirs. + // Compared with the last PATH seen here, since other features re-read the login shell too. + const hostEnvironment = yield* HostProcess.Environment; + const readHostPath = () => hostEnvironment.PATH ?? hostEnvironment.Path ?? hostEnvironment.path; + const lastHostPathRef = yield* Ref.make(readHostPath()); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const refreshHostPath = yield* refreshWindowsPath().pipe( + Effect.andThen(refreshPathFromLoginShell()), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.andThen( + Effect.suspend(() => { + const path = readHostPath(); + return Ref.getAndSet(lastHostPathRef, path).pipe(Effect.map((last) => last !== path)); + }), + ), Effect.flatMap((changed) => changed ? Ref.get(providersRef).pipe( diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index 796bc854d28d6..a000e05471bc6 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -1621,6 +1621,26 @@ describe("AcpSessionRuntime", () => { }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.effect("fails startup when the agent never answers initialize", () => + Effect.gen(function* () { + const initializeSent = yield* Deferred.make(); + const runtime = yield* AcpSessionRuntime.make({ + ...mockRuntimeOptions, + // A live child that reads stdin and never replies, like one stuck in disk sleep. + spawn: { command: "node", args: ["-e", "process.stdin.resume()"] }, + requestLogger: (event) => + event.method === "initialize" && event.status === "started" + ? Deferred.succeed(initializeSent, undefined) + : Effect.void, + }); + const startup = yield* runtime.start().pipe(Effect.forkChild); + yield* Deferred.await(initializeSent); + yield* TestClock.adjust("30 minutes"); + const exit = yield* Fiber.await(startup); + expect(Exit.isFailure(exit)).toBe(true); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it.effect("sends a cancel after the cancel timeout when its prompt never goes out", () => Effect.gen(function* () { const runtime = yield* AcpSessionRuntime.make({ diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index 05f12ec278fd9..7201d1edc0ba0 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -133,6 +133,47 @@ describe("Antigravity Auto", () => { ).toBe("deny"); }, ); + + it.each(["auto", "auto-accept-edits"] as const)( + "runs only server-qualified T3 MCP calls unasked in %s", + (runtimeMode) => { + const policy = { runtimeMode, cwd: "/workspace" }; + const request = ( + title: string, + rawInput?: Record, + ): EffectAcpSchema.RequestPermissionRequest => ({ + sessionId: "session-1", + toolCall: { toolCallId: "call-1", title, kind: "execute", rawInput }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], + }); + for (const t3Call of [ + request("Run mcp_t3-code_t3_thread_list?"), + request("MCP Tool delegate_task", { ServerName: "t3-code", ToolName: "delegate_task" }), + ]) { + expect(antigravityPermissionDisposition(policy, t3Call)).toBe("allow"); + expect( + antigravityPermissionDisposition({ ...policy, approvalPolicy: "on-request" }, t3Call), + ).toBe("ask"); + expect( + antigravityPermissionDisposition( + { ...policy, sandboxPolicy: { type: "readOnly" } }, + t3Call, + ), + ).toBe("deny"); + } + for (const otherCall of [ + // Names no server, so another MCP server's tool of the same name looks identical. + request("Running preview_status"), + request("Run mcp_github_create_issue"), + request("MCP Tool preview_status", { ServerName: "other", ToolName: "preview_status" }), + request("Run mcp_t3-code_preview_status", { + CommandLine: "Run mcp_t3-code_preview_status", + }), + ]) { + expect(antigravityPermissionDisposition(policy, otherCall)).toBe("ask"); + } + }, + ); }); describe("applyAntigravityAcpModelSelection", () => { diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 7434e23b5eda9..4d57305f7e0ec 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -25,9 +25,11 @@ import { import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { acpPermissionDisposition, + unknownRecord, type AcpRuntimePolicy, } from "@t3tools/provider-acp/server/clientPolicy"; import type { AcpSessionModeState } from "@t3tools/provider-acp/server/runtimeModel"; +import { T3_MCP_TOOL_NAMES } from "@t3tools/shared/t3McpToolPresentation"; import packageJson from "../../../package.json" with { type: "json" }; import { normalizeAntigravitySessionUpdate } from "./AntigravityProtocol.ts"; @@ -181,13 +183,40 @@ export function antigravitySessionMode( return modeId === "yolo" || modeId === "auto_edit" ? "default" : modeId; } +// Only calls that name T3's server: before agy 1.5.8 "Running " names no server, so another +// MCP server's tool of the same name would pass. +const ANTIGRAVITY_T3_MCP_TITLE = /^Run mcp_t3-code_(?[A-Za-z0-9_]+)\??$/; + +function isAntigravityT3McpRequest(request: EffectAcpSchema.RequestPermissionRequest): boolean { + const rawInput = unknownRecord(request.toolCall.rawInput); + if (rawInput?.ServerName !== undefined) { + return ( + rawInput.ServerName === "t3-code" && + typeof rawInput.ToolName === "string" && + T3_MCP_TOOL_NAMES.has(rawInput.ToolName) + ); + } + if (typeof rawInput?.CommandLine === "string") return false; + const tool = ANTIGRAVITY_T3_MCP_TITLE.exec(request.toolCall.title?.trim() ?? "")?.groups?.tool; + return tool !== undefined && T3_MCP_TOOL_NAMES.has(tool); +} + export function antigravityPermissionDisposition( policy: AcpRuntimePolicy, request: EffectAcpSchema.RequestPermissionRequest, ) { const disposition = acpPermissionDisposition(policy, request); + if (disposition === "deny") return "deny"; + // T3 authorizes its own MCP server, so Auto and Auto-accept edits run it unasked, as Claude does. + if ( + (policy.runtimeMode === "auto" || policy.runtimeMode === "auto-accept-edits") && + (policy.approvalPolicy === undefined || policy.approvalPolicy === "never") && + isAntigravityT3McpRequest(request) + ) { + return "allow"; + } // agy's Auto has already reviewed what it sends; the user decides unless the sandbox forbids it. - return policy.runtimeMode === "auto" && disposition !== "deny" ? "ask" : disposition; + return policy.runtimeMode === "auto" ? "ask" : disposition; } /** The runtime mode an Antigravity session mode grants; the inverse of `antigravityPermissionMode`. */ diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.ts index cfe47280fc4f1..93f7d1fc377c8 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts @@ -535,24 +535,42 @@ describe("Antigravity tool results", () => { ); }); + it("keeps the start of a long command line, where the program and target are", () => { + const head = "cat > notes.md <<'EOF'"; + const commandLine = `${head}\n${"note line\n".repeat(1_000)}EOF`; + const toolCall = normalizeAntigravityToolCall( + parseToolUpdate({ + ...commandStarted, + update: { ...commandStarted.update, rawInput: { CommandLine: commandLine } }, + }).toolCall, + ); + expect(toolCall.command?.startsWith(head)).toBe(true); + expect(toolCall.command).not.toContain("[Earlier output truncated]"); + expect((toolCall.data.rawInput as { CommandLine: string }).CommandLine.startsWith(head)).toBe( + true, + ); + }); + it("keeps 1.5 command input and output valid Unicode when cut", () => { const tail = `${"x".repeat(7_982)}build completed\r\n`; const output = `Command output:\nprefix\r\n🚀${tail}`; const expected = `[Earlier output truncated]\n\n${tail}`; + const head = "x".repeat(7_999); + const expectedCommand = `${head}\n\n[Command truncated]`; const toolCall = normalizeAntigravityToolCall( parseToolUpdate({ ...commandCompleted, update: { ...commandCompleted.update, - rawInput: { CommandLine: output }, + rawInput: { CommandLine: `${head}🚀 --flag` }, rawOutput: { output, exit_code: 0 }, content: [{ type: "content", content: { type: "text", text: output } }], }, }).toolCall, ); - expect(toolCall.command).toBe(expected.trimEnd()); + expect(toolCall.command).toBe(expectedCommand); expect(toolCall.data).toMatchObject({ - rawInput: { CommandLine: expected }, + rawInput: { CommandLine: expectedCommand }, rawOutput: { output: expected }, content: [{ content: { text: expected.trimEnd() } }], }); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 2ba17c8a86db5..c718667dcf42e 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -21,6 +21,7 @@ import { const TOOL_TEXT_LIMIT = 8_000; const TOOL_TEXT_TRUNCATED = "[Earlier output truncated]\n\n"; +const COMMAND_LINE_TRUNCATED = "\n\n[Command truncated]"; const QUESTION_LABEL_LIMIT = 512; const NativeToolFields = Schema.Struct({ @@ -194,11 +195,21 @@ function boundCommandText(text: string, limit = TOOL_TEXT_LIMIT): string { return copyBoundedText(`${TOOL_TEXT_TRUNCATED}${tail}`); } +// A command line's program and target are at its start, so it keeps its head. +function boundCommandLine(text: string, limit = TOOL_TEXT_LIMIT): string { + if ( + text.length <= limit || + (text.length <= limit + COMMAND_LINE_TRUNCATED.length && text.endsWith(COMMAND_LINE_TRUNCATED)) + ) { + return text; + } + const head = text.slice(0, limit).replace(/[\uD800-\uDBFF]$/u, ""); + return copyBoundedText(`${head}${COMMAND_LINE_TRUNCATED}`); +} + +const COMMAND_LINE_FIELDS = new Set(["CommandLine", "command_line", "commandLine", "command"]); + const COMMAND_TEXT_FIELDS = new Set([ - "CommandLine", - "command_line", - "commandLine", - "command", "aggregatedOutput", "combinedOutput", "combined_output", @@ -231,7 +242,13 @@ function sanitizeToolValue( return undefined; } const bound = - field !== undefined && COMMAND_TEXT_FIELDS.has(field) ? boundCommandText : boundText; + field === undefined + ? boundText + : COMMAND_LINE_FIELDS.has(field) + ? boundCommandLine + : COMMAND_TEXT_FIELDS.has(field) + ? boundCommandText + : boundText; const text = bound(value, Math.min(TOOL_TEXT_LIMIT, budget.text)); budget.text -= text.length; return text; @@ -468,7 +485,7 @@ export function normalizeAntigravityToolCall( output?.commandLine ?? output?.command_line ?? toolCall.command; - const command = nativeCommand?.trim() ? boundCommandText(nativeCommand.trim()) : undefined; + const command = nativeCommand?.trim() ? boundCommandLine(nativeCommand.trim()) : undefined; const nativeCwd = input?.Cwd ?? input?.WorkingDirectory ?? diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 139eba175bc8a..222f23b6b02d9 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59052 + "mcpToolListJsonBytes": 59170 } diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 9cec14dadd67e..ec1f1f694c2f4 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -34,6 +34,14 @@ const HIDDEN = new Set([ "sizeRelH", "sizeRelV", "fldData", + // An OpenDocument index keeps its templates beside the generated index; only the latter is content. + "table-of-content-source", + "illustration-index-source", + "table-index-source", + "object-index-source", + "user-index-source", + "alphabetical-index-source", + "bibliography-source", ]); // @effect-diagnostics-next-line extendsNativeError:off - this worker loads no Effect runtime; Truncation is a local throw sentinel. @@ -107,7 +115,10 @@ function xml(source: string, extension: string): XmlNode { if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node); if ( (extension === ".docx" && node.name === "del") || - (odf && node.name === "annotation" && parent.name !== "semantics") + (odf && node.name === "annotation" && parent.name !== "semantics") || + (extension === ".odp" && + node.name === "page-thumbnail" && + stack.some((ancestor) => ancestor.name === "notes")) ) { parent.children.pop(); return; @@ -159,9 +170,11 @@ function* all(node: XmlNode, name: string | readonly string[]): Generator { +function* text(node: XmlNode): Generator { if (HIDDEN.has(node.name)) return; - if (["tab", "ptab", "cell"].includes(node.name)) yield "\t"; + // Word text boxes hold their own paragraphs inside the anchoring paragraph. + if (node.name === "txbxContent") yield* paragraphs(node); + else if (["tab", "ptab", "cell"].includes(node.name)) yield "\t"; else if (["br", "line-break", "cr"].includes(node.name)) yield "\n"; else if (node.name === "noBreakHyphen") yield "\u2011"; else if (node.spaceCount !== undefined) { @@ -213,6 +226,18 @@ function* paragraphs(node: XmlNode): Generator { } } } +// A notes page also holds the slide image, slide number, date, header and footer placeholders. +const NOTES_PAGE_PLACEHOLDERS = new Set(["sldImg", "sldNum", "dt", "hdr", "ftr"]); +const isNotesPagePlaceholder = (node: XmlNode) => + node.name === "sp" && NOTES_PAGE_PLACEHOLDERS.has(all(node, "ph").next().value?.attrs.type ?? ""); +function withoutNotesPagePlaceholders(node: XmlNode): XmlNode { + return { + ...node, + children: node.children + .filter((child) => typeof child === "string" || !isNotesPagePlaceholder(child)) + .map((child) => (typeof child === "string" ? child : withoutNotesPagePlaceholders(child))), + }; +} function* inCell(parts: Iterable): Generator { yield CELL_START; yield* parts; @@ -256,9 +281,8 @@ function hasCellText(cell: XmlNode): boolean { function* table(node: XmlNode): Generator { let rowCount = 0; for (const row of all(node, ["tr", "table-row"])) { - const cells = children(row).filter((cell) => - ["tc", "table-cell", "covered-table-cell", "td", "th"].includes(cell.name), - ); + // Word nests a cell inside w:sdt when a content control wraps the whole cell. + const cells = [...all(row, ["tc", "table-cell", "covered-table-cell", "td", "th"])]; // ODS writers pad sheets with repeated empty rows and trailing cells. while (cells.length && !hasCellText(cells.at(-1)!)) cells.pop(); if (!cells.length) continue; @@ -416,10 +440,35 @@ function* notebook(source: string): Generator { } } +// Per-byte decoding only supports the single-byte \fcharset values. +const FONT_CODE_PAGES = new Map([ + [77, "macintosh"], + [161, "windows-1253"], + [162, "windows-1254"], + [163, "windows-1258"], + [177, "windows-1255"], + [178, "windows-1256"], + [186, "windows-1257"], + [204, "windows-1251"], + [222, "windows-874"], + [238, "windows-1250"], +]); + function* rtf(source: string): Generator { if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document"); - let state = { skip: false, deleted: false, uc: 1, decoder: new TextDecoder("windows-1252") }; + let state = { + skip: false, + deleted: false, + uc: 1, + font: 0, + fontTable: 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. + const fonts = new Map(); + let defaultFont = 0; + const decoder = () => fonts.get(state.font) ?? state.decoder; const hidden = () => state.skip || state.deleted; const symbols = new Map([ ["endash", "–"], @@ -454,7 +503,7 @@ function* rtf(source: string): Generator { const word = /^([a-z]+)(-?\d+)? ?/i.exec(rest); if (hex) { if (fallback) fallback--; - else if (!hidden()) yield state.decoder.decode(Uint8Array.of(Number.parseInt(hex[1]!, 16))); + else if (!hidden()) yield decoder().decode(Uint8Array.of(Number.parseInt(hex[1]!, 16))); i += 3; } else if (word) { i += word[0].length; @@ -489,8 +538,20 @@ function* rtf(source: string): Generator { ].includes(control) ) state.skip = true; + if (control === "fonttbl") state.fontTable = true; + else if (control === "deff") state.font = defaultFont = value; + else if (control === "f") { + state.font = value; + if (state.fontTable) fonts.delete(value); + } else if (control === "fcharset" && state.fontTable) { + const codePage = FONT_CODE_PAGES.get(value); + if (codePage) fonts.set(state.font, new TextDecoder(codePage)); + } if (control === "deleted") state.deleted = value !== 0; - else if (control === "plain") state.deleted = false; + else if (control === "plain") { + state.deleted = false; + state.font = defaultFont; + } if (control === "mac" || (control === "ansicpg" && value === 10000)) state.decoder = new TextDecoder("macintosh"); else if (control === "ansicpg") { @@ -524,9 +585,7 @@ function* rtf(source: string): Generator { } else if (char !== "\n" && char !== "\r") { if (fallback) fallback--; else if (!hidden()) - yield char.charCodeAt(0) < 128 - ? char - : state.decoder.decode(Uint8Array.of(char.charCodeAt(0))); + yield char.charCodeAt(0) < 128 ? char : decoder().decode(Uint8Array.of(char.charCodeAt(0))); } } } @@ -557,8 +616,17 @@ async function* document(path: string, extension: string): AsyncGenerator rel.attrs.TargetMode !== "External") .map((rel) => [rel.attrs.Id, rel.attrs.Target]), ); - if (extension === ".docx") yield* paragraphs(read("word/document.xml")); - else if ([".odt", ".ods", ".odp"].includes(extension)) { + if (extension === ".docx") { + // The package relationship names the main part; Word for the web saves word/document2.xml. + const target = files.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")); + } else if ([".odt", ".ods", ".odp"].includes(extension)) { const content = read("content.xml"); if (extension === ".odt") yield* paragraphs(content); else { @@ -567,8 +635,19 @@ async function* document(path: string, extension: string): AsyncGenerator child.name === "notes"); + yield* paragraphs({ + ...part, + children: part.children.filter((child) => child !== notes), + }); + if (notes && hasCellText(notes)) { + yield "\nNotes:\n"; + yield* paragraphs(notes); + } } } } else if (extension === ".xlsx") { @@ -691,14 +770,16 @@ async function* document(path: string, extension: string): AsyncGenerator { String.raw`{\rtf1\mac\ansicpg10000 Caf\'8e Cr\'8fme}`, "Café Crème", ], + [ + "font character set", + String.raw`{\rtf1\ansi\ansicpg1252\deff1{\fonttbl\f0\fnil\fcharset178 GeezaPro;\f1\fnil\fcharset0 LucidaGrande;} +\f0 \'e3\'e1\'c7\'cd\'d9\'c9\f1 : caf\'e9, \f0\plain\'c7a}`, + "ملاحظة: café, Ça", + ], + [ + "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}`, + "ããã", + ], ["destination symbol", String.raw`{\rtf1\ansi\u945\*Z}`, "αZ"], ["multiple units", String.raw`{\rtf1\ansi\uc4\u945?\tab\'3f\~Z}`, "αZ"], ["binary unit", String.raw`{\rtf1\ansi\u945\bin3 abcZ}`, "αZ"], @@ -574,6 +585,28 @@ describe("question answer paths", () => { expected: ["Readable despite embedded media"], absent: ["[Extracted text truncated"], }, + ...["/word/../word/document2.xml", "word/document2.xml"].map((target) => ({ + ext: "docx", + bounded: true, + parts: { + "_rels/.rels": ``, + "word/document.xml": "

Stale draft

", + "word/document2.xml": "

Launch moves to 3 March.

", + }, + expected: ["Launch moves to 3 March."], + absent: ["Stale draft", "[Skipped document part"], + })), + { + ext: "docx", + bounded: true, + parts: { + "_rels/.rels": + '', + "word/document.xml": "

Launch moves to 3 March.

", + }, + expected: ["Launch moves to 3 March."], + absent: ["[Skipped document part"], + }, ...[false, true].map((deep) => ({ ext: "docx", bounded: true, @@ -756,9 +789,9 @@ describe("question answer paths", () => { bounded: true, parts: { "word/document.xml": - 'BodyCallout boxCallout box', + 'BodyCallout boxSecond lineCallout boxSecond line', }, - expected: ["Body\nCallout box"], + expected: ["Body\nCallout box\nSecond line"], occurrences: { text: "Callout box", count: 1 }, }, { @@ -775,11 +808,12 @@ describe("question answer paths", () => { bounded: true, parts: { "word/document.xml": - 'Report & totalsNorth1234BeforeInnerAfterNeighbor', + 'Report & totalsNorth1234Annual reportDraftBeforeInnerAfterNeighbor', }, expected: [ "## Report & totals", "North\t12 34", + "Annual report\tDraft", "Before Inner After\tNeighbor\t\u2011\n\u2011", ], }, @@ -977,7 +1011,7 @@ describe("question answer paths", () => { "ppt/slides/_rels/slide1.xml.rels": '', "ppt/notesSlides/notes7.xml": - "evacuation code ORCHID-81", + 'evacuation code ORCHID-81Harbor briefing11/21/2026Crew only57', "ppt/notesSlides/notes3.xml": "Board at gate 4", "ppt/notesSlides/ignored.xml": "Unrelated notes", @@ -989,7 +1023,32 @@ describe("question answer paths", () => { "Departure\nNotes:\nBoard at gate 4", ], occurrences: { text: "## Slide ", count: 2 }, - absent: ["Unrelated notes", "[Skipped document part", "[Extracted text truncated"], + absent: [ + "Unrelated notes", + "Harbor briefing", + "11/21/2026", + "Crew only", + "57", + "[Skipped document part", + "[Extracted text truncated", + ], + }, + { + ext: "pptx", + bounded: true, + parts: { + "ppt/presentation.xml": + '', + "ppt/_rels/presentation.xml.rels": + '', + "ppt/slides/a.xml": "

Slide text

", + "ppt/slides/_rels/a.xml.rels": + '', + "ppt/notesSlides/empty.xml": + '57', + }, + expected: ["Slide text"], + absent: ["Notes:", "57"], }, ...[false, true].map((missing) => ({ ext: "pptx", @@ -1036,10 +1095,25 @@ describe("question answer paths", () => { ext: "odt", parts: { "content.xml": - '\n Orchard\n19violetcrates \n\t shipped todayDockGate\u00a0B SecondAconsole.log(1);\n B', + '\n Orchard\n19violetcrates \n\t shipped todayDockGate\u00a0B SecondAconsole.log(1);\n B' + + [ + "table-of-content", + "illustration-index", + "table-index", + "object-index", + "user-index", + "alphabetical-index", + "bibliography", + ] + .map( + (name) => + `Contents: ContentsOrchard 1`, + ) + .join("") + + "", }, expected: [ - "## Orchard\n19 violet crates shipped today\tDock\nGate\u00a0B\nSecond\nA B", + `## Orchard\n19 violet crates shipped today\tDock\nGate\u00a0B\nSecond\nA B${"\nContents\nOrchard 1".repeat(7)}`, ], }, { @@ -1087,9 +1161,20 @@ describe("question answer paths", () => { ext: "odp", parts: { "content.xml": - "\n First\n\t slide Second", + "" + + "\n First\n\t slide " + + "Overview" + + "Speaker only" + + "Second" + + "Slide previewThumbnail metadata" + + "" + + "Third" + + '' + + "", }, - expected: ["## Slide 1\nFirst slide\n\n## Slide 2\nSecond"], + expected: [ + "## Slide 1\nFirst slide\nOverview\nNotes:\nSpeaker only\n\n## Slide 2\nSecond\n\n## Slide 3\nThird\n\nNotes:\n42", + ], }, { ext: "ods", diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index e30938735c765..59ece029219df 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -1370,6 +1370,7 @@ export const make = Effect.gen(function* () { ...(input.item.checksState === undefined || input.item.checksState === null ? {} : { checksState: input.item.checksState }), + ...(input.item.visibility === undefined ? {} : { visibility: input.item.visibility }), viewerReviewRequested: input.item.author?.login.toLowerCase() !== viewer && input.item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer), @@ -1993,6 +1994,9 @@ export const make = Effect.gen(function* () { ...(changeRequest.mergeQueueRemoval === undefined ? {} : { mergeQueueRemoval: changeRequest.mergeQueueRemoval }), + ...(changeRequest.visibility === undefined + ? {} + : { visibility: changeRequest.visibility }), })), ), ), diff --git a/apps/server/src/pullRequest/PullRequestWatchService.test.ts b/apps/server/src/pullRequest/PullRequestWatchService.test.ts index edf4fee9c5c56..8982e795e2615 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.test.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.test.ts @@ -205,6 +205,16 @@ describe("PullRequestWatchService", () => { }), ); + it.effect("tells the caller when the checks already passed, since no wake will report it", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ readChecksState: "passing" }); + const result = yield* harness.setWatching(true, { + url: "https://github.com/t3tools/t3code/pull/9", + }); + expect(result).toMatchObject({ wasWatching: false, checksState: "passing" }); + }), + ); + it.effect("reports a missing hosting CLI before saving a watch and still allows unwatch", () => Effect.gen(function* () { const missing = new PullRequestUnavailableError({ diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts index 5e64ac4206896..32f51f540bf9f 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -2,6 +2,7 @@ import { CommandId, ThreadId, type OrchestrationV2ThreadShell, + type PullRequestChecksState, type PullRequestUnavailableError, type PullRequestWatchUntil, } from "@t3tools/contracts"; @@ -68,6 +69,8 @@ export class PullRequestWatchService extends Context.Service< readonly wasWatching: boolean; /** Set when the PR already ended, so no watch was registered. */ readonly state?: "merged" | "closed"; + /** CI as the start read saw it. Checks that already passed never wake the watch. */ + readonly checksState?: PullRequestChecksState; }, | PullRequestWatchFailedError | PullRequestWatchFromSubagentError @@ -130,6 +133,7 @@ const make = Effect.gen(function* () { if (watching && before?.snapshot?.state === "merged") return alreadyEnded("merged"); // A pending rollup has no failure yet, so any failure the first read finds is news. let checksPendingAtStart: boolean | undefined; + let checksStateAtStart: PullRequestChecksState | undefined; if (watching && !wasWatching) { const read = yield* pullRequests .summary( @@ -151,6 +155,7 @@ const make = Effect.gen(function* () { ); if (read?.state === "merged" || read?.state === "closed") return alreadyEnded(read.state); checksPendingAtStart = read === undefined ? undefined : read.checksState === "pending"; + checksStateAtStart = read?.checksState ?? undefined; } const uuid = yield* random.uuidV4().pipe(Effect.orDie); yield* engine @@ -180,6 +185,7 @@ const make = Effect.gen(function* () { ...target, watching: watchedLink(after)?.watch !== undefined, wasWatching, + ...(checksStateAtStart !== undefined && { checksState: checksStateAtStart }), }; }); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 68c95748d0ce8..3db6f783f649a 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -35,6 +35,7 @@ import * as Mac from "effect/crypto/Mac"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Exit from "effect/Exit"; import * as Duration from "effect/Duration"; @@ -90,6 +91,13 @@ const WEBHOOK_DEDUPE_LOG_PER_MINUTE = 10; const WEBHOOK_FILTERED_LOG_PER_MINUTE = 10; const WEBHOOK_DELIVERY_LOG_BODY_LIMIT = 64 * 1024; const WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT = 64 * 1024; +const loggedWebhookPrompt = (prompt: string) => + prompt.slice( + 0, + splitsSurrogatePair(prompt, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT) + ? WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT - 1 + : WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT, + ); const WEBHOOK_MAX_QUEUED_PER_TASK = 20; // Enforce the relay's per-task/minute limit here too; tunnel hostnames are public. const WEBHOOK_RATE_LIMIT_PER_MINUTE = 60; @@ -1947,7 +1955,7 @@ export const layer = Layer.effect( ${loggedBody}, ${input.request.body.byteLength}, ${truncated ? 1 : 0}, ${input.outcome}, ${input.signatureVerified ? 1 : 0}, ${encodeMissingFieldsJson(input.missing)}, - ${input.renderedPrompt?.slice(0, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT) ?? null}, + ${input.renderedPrompt === null ? null : loggedWebhookPrompt(input.renderedPrompt)}, ${input.error ?? null} WHERE EXISTS (SELECT 1 FROM scheduled_tasks WHERE task_id = ${input.taskId}) -- A held request retried after a rate limit reuses its relay @@ -2636,7 +2644,7 @@ export const layer = Layer.effect( } else { if (taskJson !== null) yield* sql`UPDATE scheduled_task_webhook_pending SET task_json = ${taskJson} WHERE delivery_id = ${entry.delivery_id}`; - yield* sql`UPDATE scheduled_task_webhook_deliveries SET outcome = 'accepted', error = NULL, rendered_prompt = ${rendered.prompt.slice(0, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT)}, missing_fields_json = ${encodeMissingFieldsJson(rendered.missing)} WHERE delivery_id = ${entry.delivery_id}`; + yield* sql`UPDATE scheduled_task_webhook_deliveries SET outcome = 'accepted', error = NULL, rendered_prompt = ${loggedWebhookPrompt(rendered.prompt)}, missing_fields_json = ${encodeMissingFieldsJson(rendered.missing)} WHERE delivery_id = ${entry.delivery_id}`; if (!(yield* runWebhookDelivery(task, entry.delivery_id, rendered.prompt))) return; } yield* remove; diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts index e06ed817ac4f4..82db6f5e16407 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts @@ -571,6 +571,28 @@ it.effect("drops a character split by the delivery log's body limit", () => ), ); +it.effect("drops an emoji split by the delivery log's prompt limit", () => + withService(({ service }) => + Effect.gen(function* () { + const { task } = yield* service.upsert(yield* webhookTaskInput({ prompt: "{{body.text}}" })); + const limit = 64 * 1024; + const frameOpen = "".length; + // The emoji's high surrogate is the last code unit the log keeps. + const bodyText = JSON.stringify({ text: `${"a".repeat(limit - 1 - frameOpen)}😀 tail` }); + yield* service.triggerWebhook( + requestFor(task, { bodyText, body: new TextEncoder().encode(bodyText) }), + ); + const [summary] = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries; + const { delivery } = yield* service.getWebhookDelivery({ + id: task.id, + deliveryId: summary!.id, + }); + assert.equal(delivery.renderedPrompt!.slice(-3), "aaa"); + assert.equal(delivery.renderedPrompt!.length, limit - 1); + }), + ), +); + const queuedDeliveryCases = [ { change: "paused", diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 720834730e99b..d06186beb1988 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -17,6 +17,7 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { EnvironmentHttpApi, type RepositoryIdentity } from "@t3tools/contracts"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cause from "effect/Cause"; import * as Duration from "effect/Duration"; @@ -1408,6 +1409,7 @@ const layerMakeServer = Layer.unwrap( Layer.provide(VcsProcess.layer), Layer.provideMerge(AgentScopeLive.layer), Layer.provideMerge(layerPlatformServices), + Layer.provideMerge(FeatureFlags.layer), Layer.provide(Layer.succeed(HostProcess.InvokedAs, invokedAs)), ); }), diff --git a/apps/server/src/serverOwnership.ts b/apps/server/src/serverOwnership.ts index 193233fa8abeb..20bb46a45e66e 100644 --- a/apps/server/src/serverOwnership.ts +++ b/apps/server/src/serverOwnership.ts @@ -207,6 +207,23 @@ const openOwnershipLock = (stateDir: string) => : new ServerOwnershipError({ stateDir, cause }), }); +/** Whether a running server holds the ownership lock. Read-only, so it never creates the lock file. */ +export const isServerOwnershipHeld = (statePath: string): boolean => { + let db: NodeSqlite.DatabaseSync | undefined; + try { + db = new NodeSqlite.DatabaseSync(ownershipLockPath(NodePath.dirname(statePath)), { + readOnly: true, + timeout: 0, + }); + db.prepare("SELECT 1 FROM sqlite_schema").get(); + return false; + } catch (cause) { + return isSqliteBusy(cause); + } finally { + db?.close(); + } +}; + /** Hold only the ownership lock until the scope closes, without claiming the runtime state. */ export const holdServerOwnershipLock = Effect.fn("holdServerOwnershipLock")(function* ( statePath: string, diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index c6f823d61f3c6..98c560cbf4973 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -75,16 +75,11 @@ function unsupportedProvider( // Binding context does not create a second provider-operation span. return SourceControlProvider.SourceControlProvider.of({ kind, - // Unknown hosts have no readable change requests; return none to avoid poll warnings on every refresh. - listChangeRequests: (input) => - kind === "unknown" - ? Effect.succeed([]) - : new SourceControlProviderError({ - provider: kind, - operation: "listChangeRequests", - cwd: input.cwd, - detail: `No ${kind} source control provider is registered.`, - }), + // Unknown hosts, and hosts whose forge a feature flag leaves out, have no readable change + // requests; return none to avoid poll warnings on every refresh. + listChangeRequests: Effect.fn("SourceControlProviderRegistry.unsupported.listChangeRequests")( + () => Effect.succeed([]), + ), getChangeRequest: (input) => new SourceControlProviderError({ provider: kind, @@ -227,6 +222,15 @@ function bindProviderContext( context: input.context ?? context, }); }), + ...(provider.privateChangeRequestRemote === undefined + ? {} + : { + privateChangeRequestRemote: (input) => + provider.privateChangeRequestRemote!({ + ...input, + context: input.context ?? context, + }), + }), getRepositoryCloneUrls: Effect.fnUntraced(function* (input) { return yield* provider.getRepositoryCloneUrls({ ...input, diff --git a/apps/server/src/sourceControl/builtInDrivers.ts b/apps/server/src/sourceControl/builtInDrivers.ts index 0e994dcac4a7f..33aa77ffefd8f 100644 --- a/apps/server/src/sourceControl/builtInDrivers.ts +++ b/apps/server/src/sourceControl/builtInDrivers.ts @@ -3,6 +3,7 @@ import type { SourceControlDriverInstance, } from "@t3tools/source-control-core/server/driver"; import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -21,9 +22,21 @@ export class SourceControlDrivers extends Context.Service< ReadonlyArray >()("t3/sourceControl/builtInDrivers/SourceControlDrivers") {} -const make = Effect.forEach(BUILT_IN_SOURCE_CONTROL_DRIVER_LIST, (driver) => - driver.make.pipe(Effect.map((instance) => ({ driver, instance }))), -); +/** Drivers offered only while their feature flag is on. */ +const FLAGGED_DRIVERS: Readonly> = { + "tanstack-source": "tanstackSource", +}; + +const make = Effect.gen(function* () { + const flags = yield* FeatureFlags.FeatureFlags; + const drivers = BUILT_IN_SOURCE_CONTROL_DRIVER_LIST.filter((driver) => { + const flag = FLAGGED_DRIVERS[driver.kind]; + return flag === undefined || flags[flag]; + }); + return yield* Effect.forEach(drivers, (driver) => + driver.make.pipe(Effect.map((instance) => ({ driver, instance }))), + ); +}); export const layer = Layer.effect(SourceControlDrivers, make).pipe( Layer.provideMerge(ServerSourceControlHost.layer), diff --git a/apps/server/src/sourceControl/sourceControlDefinitions.ts b/apps/server/src/sourceControl/sourceControlDefinitions.ts index c6a770a897f02..6dff3fe3c6962 100644 --- a/apps/server/src/sourceControl/sourceControlDefinitions.ts +++ b/apps/server/src/sourceControl/sourceControlDefinitions.ts @@ -1,7 +1,7 @@ import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver"; import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver"; import * as CursorOriginDriver from "@t3tools/source-control-cursor-origin/server/driver"; -import { makeBuiltInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; +import { builtInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver"; import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver"; import * as GitHubDriver from "@t3tools/source-control-github/server/driver"; @@ -9,26 +9,21 @@ import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver"; import * as TanStackSourceDriver from "@t3tools/source-control-tanstack-source/server/driver"; /** - * TanStack Source is in private beta, so its forge exists only on a server started with - * `T3CODE_TANSTACK_SOURCE=1`. Read once at load: the registry below is a module constant. + * In the shared registry's order, which is the order hosts are listed and probed in. Feature + * flags leave some out; see `builtInDrivers.ts`. */ -const tanStackSourceEnabled = process.env.T3CODE_TANSTACK_SOURCE?.trim() === "1"; - -/** In the shared registry's order, which is the order hosts are listed and probed in. */ export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [ GitHubDriver.driver, CursorOriginDriver.driver, GitLabDriver.driver, GitCafeDriver.driver, - ...(tanStackSourceEnabled ? [TanStackSourceDriver.driver] : []), + TanStackSourceDriver.driver, ForgejoDriver.driver, BitbucketDriver.driver, AzureDevOpsDriver.driver, ]; -export const sourceControlDefinitions = makeBuiltInSourceControlDefinitions({ - tanStackSource: tanStackSourceEnabled, -}); +export const sourceControlDefinitions = builtInSourceControlDefinitions; /** A host CLI command that merges or closes a change request, such as `gh pr merge`. */ export const isChangeRequestCloseCommand = (command: string) => diff --git a/apps/server/src/speech/http.test.ts b/apps/server/src/speech/http.test.ts index 770a1b5c94ca5..8bbf2d81bc065 100644 --- a/apps/server/src/speech/http.test.ts +++ b/apps/server/src/speech/http.test.ts @@ -12,6 +12,7 @@ import { CloudSpeechError, DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, SPEECH_MAX_OPTIONS_BYTES, + TextGenerationError, DEFAULT_SERVER_SETTINGS, EnvironmentAuthenticatedAuth, EnvironmentAuthenticatedPrincipal, @@ -377,3 +378,62 @@ effectIt.effect.each([ }); }), ); + +effectIt.effect("tells the client why transcript cleanup failed", () => + Effect.gen(function* () { + const detail = "OpenCode returned invalid structured output."; + const failingCleanup = Layer.mergeAll( + dependencies, + Layer.succeed( + TextGeneration.TextGeneration, + TextGeneration.TextGeneration.of({ + generateCommitMessage: () => Effect.die("not used"), + generatePrContent: () => Effect.die("not used"), + generateBranchName: () => Effect.die("not used"), + generateThreadTitle: () => Effect.die("not used"), + generateReviewGuide: () => Effect.die("not used"), + generateTranscriptionPostProcessing: () => + Effect.fail( + new TextGenerationError({ + operation: "generateTranscriptionPostProcessing", + detail, + }), + ), + }), + ), + ); + const { handler, dispose } = HttpRouter.toWebHandler( + HttpApiBuilder.layer(HttpApi.make("environment").add(EnvironmentVoiceHttpApi)).pipe( + Layer.provide(speechHttpApiLayer), + Layer.provide(principal(AuthOrchestrationOperateScope)), + Layer.provide(Layer.mock(SpeechService.SpeechService)({})), + Layer.provide(failingCleanup), + // Cleanup makes a real temporary directory; the HTTP services only carry a no-op filesystem. + Layer.provide(NodeServices.layer), + Layer.provide(HttpServer.layerServices), + ), + { disableLogger: true }, + ); + yield* Effect.addFinalizer(() => Effect.promise(dispose)); + const context = yield* Layer.build(Layer.mergeAll(failingCleanup, NodeServices.layer)); + const response = yield* Effect.promise(() => + handler( + new Request("http://localhost/api/voice/post-process", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + options: { + speechCustomWords: [], + speechPostProcessingPrompt: { mode: "default", customInstructions: "" }, + }, + transcript: "um so hello world", + draft: { text: "", selection: { start: 0, end: 0 } }, + }), + }), + context, + ), + ); + expect(response.ok).toBe(false); + expect(yield* Effect.promise(() => response.text())).toContain(detail); + }), +); diff --git a/apps/server/src/speech/http.ts b/apps/server/src/speech/http.ts index 834118b332b05..09c3d4dc23faa 100644 --- a/apps/server/src/speech/http.ts +++ b/apps/server/src/speech/http.ts @@ -9,11 +9,13 @@ import { type EnvironmentSpeechModels, EnvironmentVoiceBodyLimit, SPEECH_MAX_OPTIONS_BYTES, + TextGenerationError, } from "@t3tools/contracts"; import * as ByteSize from "effect/ByteSize"; 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 HttpServerRequest from "effect/http/HttpServerRequest"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; @@ -29,6 +31,7 @@ import * as SpeechService from "./SpeechService.ts"; const MAX_TRANSCRIBE_BODY_BYTES = SpeechService.MAX_SPEECH_BYTES + SPEECH_MAX_OPTIONS_BYTES + 4; const parseAudio = Option.liftThrowable(decodeSpeechPcmRequest); +const isTextGenerationError = Schema.is(TextGenerationError); const bodyLimit = Layer.succeed(EnvironmentVoiceBodyLimit, (effect) => Effect.gen(function* () { @@ -233,7 +236,15 @@ export const speechHttpApiLayer = HttpApiBuilder.group( yield* guard(args.endpoint.name); return yield* postProcessing .process(args.payload) - .pipe(Effect.catch((error) => failEnvironmentInternal("internal_error", error))); + .pipe( + Effect.catch((error) => + failEnvironmentInternal( + "internal_error", + error, + isTextGenerationError(error.cause) ? error.cause.detail : undefined, + ), + ), + ); }), ); }), diff --git a/apps/server/src/startupAccess.test.ts b/apps/server/src/startupAccess.test.ts index 7290d6063db9b..c36c29e5f1278 100644 --- a/apps/server/src/startupAccess.test.ts +++ b/apps/server/src/startupAccess.test.ts @@ -71,6 +71,20 @@ it("prefers a LAN address over a tailnet one for a private-network pairing URL", ).toBe("http://192.168.1.42:3773"); }); +it("skips Windows VirtualBox and VMware host-only adapters for a private-network listener", () => { + expect( + resolveHeadlessConnectionString("0.0.0.0", 3773, { + interfaces: { + "VirtualBox Host-Only Network": [{ ...ipv4("192.168.56.1"), mac: "0a:00:27:00:00:0a" }], + "VMware Network Adapter VMnet8": [{ ...ipv4("192.168.159.1"), mac: "00:50:56:c0:00:08" }], + "Wi-Fi": [{ ...ipv4("192.168.1.20"), mac: "3c:22:fb:12:34:56" }], + }, + privateNetworkOnly: true, + platform: "win32", + }), + ).toBe("http://192.168.1.20:3773"); +}); + it("skips NixOS container and systemd-nspawn veths for a private-network pairing URL", () => { expect( resolveHeadlessConnectionString("0.0.0.0", 3773, { diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts index b065a3fc88172..ce1b8be41938f 100644 --- a/apps/server/src/startupAccess.ts +++ b/apps/server/src/startupAccess.ts @@ -51,6 +51,9 @@ export const isLoopbackHost = (host: string | undefined): boolean => { const VIRTUAL_INTERFACE = /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge[1-9]\d\d)/; +// VirtualBox and VMware host-only adapters on Windows. Their names are mutable; Linux bridges can inherit these MACs. +export const WINDOWS_HOST_ADAPTER_MAC = /^(0a:00:27|00:50:56:c0:00):/i; + /** * systemd-nspawn's `ve-*`/`vz-*` and NixOS containers' `vb-*` name host-side * veths after the machine. Windows aliases are user-renameable, so these @@ -155,7 +158,9 @@ const resolveHeadlessConnectionHost = ( (entry) => !entry.internal && isIpv4Family(entry.family) && - (!privateNetworkOnly || isPrivateNetworkAddress(entry.address)), + (!privateNetworkOnly || + (isPrivateNetworkAddress(entry.address) && + !(platform === "win32" && WINDOWS_HOST_ADAPTER_MAC.test(entry.mac)))), ); // A tailnet or other CGNAT address reaches fewer devices than the LAN one. const externalIpv4 = privateNetworkOnly diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 3b8d749154ec5..9d0af1c39aa9c 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -3924,6 +3924,36 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live.each([ + { kind: "logs", name: "server.log.1", label: "rotated logs" }, + { kind: "browser-artifacts", name: "capture.png", label: "browser artifacts" }, + ] as const)("skips dangling symlinks during $kind cleanup", ({ kind, name, label }) => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, config, enableFiles, disable } = yield* cleanupFixture(); + disable(); + enableFiles(); + const directory = kind === "logs" ? `${config.logsDir}/nested` : config.browserArtifactsDir; + yield* fs.makeDirectory(directory, { recursive: true }); + const expired = `${directory}/${name}`; + const dangling = `${directory}/00-dangling-${name}`; + const linked = `${directory}/01-linked-${name}`; + yield* fs.symlink("missing", dangling); + yield* fs.symlink(directory, linked); + yield* fs.writeFileString(expired, "expired"); + yield* fs.utimes(expired, 1, 1); + + const report = yield* service.runNow; + expect(report.entries.filter((entry) => entry.kind === kind)).toMatchObject([ + { outcome: "removed", reason: `Removed 1 ${label}`, files: 1, bytes: 7 }, + ]); + expect((yield* fs.readDirectory(directory)).toSorted()).toEqual([ + `00-dangling-${name}`, + `01-linked-${name}`, + ]); + }), + ), + ); it.live.each([ { linked: "home", outcome: "removed", reason: "Removed 1 rotated logs" }, { linked: "logs folder", outcome: "kept", reason: "No expired files" }, @@ -3960,6 +3990,43 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live("keeps external rotated logs when a scanned directory is replaced by a symlink", () => + runCleanupTest( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const config = yield* ServerConfig.ServerConfig; + yield* fs.makeDirectory(config.logsDir, { recursive: true }); + const nested = `${yield* fs.realPath(config.logsDir)}/nested`; + const outside = yield* fs.makeTempDirectoryScoped(); + const expired = `${outside}/server.log.1`; + yield* fs.makeDirectory(nested); + yield* fs.writeFileString(expired, "external log"); + yield* fs.utimes(expired, 1, 1); + + const { service, enableFiles, disable } = yield* cleanupFixture().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + readDirectory: (directory, options) => + Effect.gen(function* () { + if (directory === nested) { + yield* fs.rename(nested, `${nested}-original`); + yield* fs.symlink(outside, nested); + } + return yield* fs.readDirectory(directory, options); + }), + }), + ); + disable(); + enableFiles(); + const report = yield* service.runNow; + expect(yield* fs.exists(expired)).toBe(true); + expect(report.entries.find((entry) => entry.kind === "logs")).toMatchObject({ + outcome: "kept", + reason: "No expired files", + }); + }), + ), + ); it.live("reports git failures without aborting the remaining categories", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index b12181e384bb6..7fd3977af5128 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -1810,8 +1810,10 @@ const make = Effect.gen(function* () { ): Effect.fn.Return { for (const name of yield* fs.readDirectory(directory)) { const target = path.join(directory, name); - if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue; - const stat = yield* fs.stat(target); + if (!inside(realRoot, target)) continue; + const stat = yield* fs.lstat(target); + if (stat.type === "SymbolicLink") continue; + if ((yield* fs.realPath(target)) !== target) continue; if (stat.type === "Directory" && rotatedLogs) { yield* visit(target); } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) { diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index c6f45a60ab75e..8af803db1fd8c 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1003,12 +1003,18 @@ it.layer( { pid: 100, ppid: 9000, name: "zsh" }, { pid: 9001, ppid: 1, name: "zsh" }, { pid: 200, ppid: 9001, name: "node" }, + { pid: 9002, ppid: 1, name: "zsh" }, + { pid: 300, ppid: 9002, name: "node" }, ]), }).pipe(Effect.provide(layerWithHostPlatform("linux"))); yield* manager.open(openInput({ terminalId: "idle", threadId: "thread-idle" })); yield* manager.open(openInput({ terminalId: "dev-server", threadId: "thread-active" })); + yield* manager.open( + openInput({ terminalId: "managed-dev", threadId: "thread-managed", stopOnSettle: true }), + ); expect(yield* manager.hasActiveSubprocess({ threadId: "thread-none" })).toBe(false); + expect(yield* manager.hasActiveSubprocess({ threadId: "thread-managed" })).toBe(false); expect(yield* manager.hasActiveSubprocess({ threadId: "thread-idle" })).toBe(false); expect(yield* manager.hasActiveSubprocess({ threadId: "thread-active" })).toBe(true); }), diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 86ccc1d3e0dd2..e87ba67cf5837 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -2791,15 +2791,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func .join(":"), }; // POSIX node-pty can return a PTY before exec fails, so validate before accepting a candidate. + const shellCommand = candidate.shell.includes("/") + ? path.resolve(session.cwd, candidate.shell) + : candidate.shell; const executable = platform !== "win32" - ? resolveExecutable( - candidate.shell.includes("/") - ? path.resolve(session.cwd, candidate.shell) - : candidate.shell, - platform, - lookupEnv, - ) + ? yield* Effect.promise(async () => resolveExecutable(shellCommand, platform, lookupEnv)) : candidate.shell; if (executable === undefined) { return yield* trySpawn( @@ -3968,9 +3965,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const hasActiveSubprocess = Effect.fn("terminal.hasActiveSubprocess")(function* (input: { readonly threadId: string; }) { + // Settling closes stopOnSettle sessions, so their work must not hold settlement back. const running = (yield* sessionsForThread(input.threadId)).filter( (session): session is TerminalSessionState & { pid: number } => - session.status === "running" && Number.isInteger(session.pid), + session.status === "running" && Number.isInteger(session.pid) && !session.stopOnSettle, ); if (running.length === 0) return false; const { inspector } = yield* acquireSubprocessInspector( diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index dc3d5914a8297..1462983e949b1 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -1,4 +1,5 @@ import { + DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER, ProjectId, ProviderDriverKind, type ModelSelection, @@ -660,11 +661,13 @@ const PREFLIGHT_PRIMARY_STATES = [ "exhausted", "not installed", "not installed, fallback disabled for project", + "not installed, fallback model cannot generate text", "signed out", "signed out, fallback failed", "cannot generate text", "model cannot generate text", "disabled", + "disabled, thread default model cannot generate text", "disabled, fallback disabled for project", ] as const; @@ -726,6 +729,21 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima ], } : {}), + ...((primaryState === "not installed, fallback model cannot generate text" || + primaryState === "disabled, thread default model cannot generate text") && + instanceId === fallback + ? { + models: [ + { + slug: threadDefault.model, + name: threadDefault.model, + isCustom: true, + supportsTextGeneration: false, + capabilities: null, + }, + ], + } + : {}), ...(primaryState.startsWith("disabled") && instanceId === primary ? { enabled: false, status: "disabled" } : {}), @@ -797,7 +815,10 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima cwd: "/tmp", message: "hello", linkedContext: "", - modelSelection: selection, + modelSelection: + primaryState === "disabled, thread default model cannot generate text" + ? threadDefault + : selection, projectId, }) .pipe(Effect.exit); @@ -813,7 +834,14 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima primaryState === "not installed, fallback disabled for project" || primaryState === "signed out, fallback failed" ? selection - : threadDefault, + : primaryState === "not installed, fallback model cannot generate text" || + primaryState === "disabled, thread default model cannot generate text" + ? { + instanceId: fallback, + model: + DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[ProviderDriverKind.make("claudeAgent")], + } + : threadDefault, ]); }), ); diff --git a/apps/server/src/textGeneration/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.ts index f994b7743c503..0436c552a6b7b 100644 --- a/apps/server/src/textGeneration/TextGeneration.ts +++ b/apps/server/src/textGeneration/TextGeneration.ts @@ -126,13 +126,14 @@ export const make = Effect.gen(function* () { }), ), ); - selection = + const rejected = selection; + const fallbackWhere = (sameInstance: boolean) => fallbackTextGenerationModelSelection( settings.providerInstances, (instanceId, driver, model) => { const provider = snapshots.find((candidate) => candidate.instanceId === instanceId); return ( - instanceId !== selection.instanceId && + (sameInstance ? model !== rejected.model : instanceId !== rejected.instanceId) && provider?.enabled === true && resolveProjectProviderInstanceEnabled(settings, projectId ?? null, instanceId) && provider.installed && @@ -140,12 +141,16 @@ export const make = Effect.gen(function* () { provider.status !== "error" && isProviderAvailable(provider) && isProviderTextGenerationCapable(provider) && + provider.models.find((candidate) => candidate.slug === model) + ?.supportsTextGeneration !== false && (operation !== "generateReviewGuide" || INVESTIGATING_DRIVERS.has(driver)) && !exhaustedUsageWindow(provider, now, model) ); }, { defaultModelSelection: settings.defaultModelSelection }, - ) ?? selection; + ); + // Another instance first; the rejected instance's other models only when none qualifies. + selection = fallbackWhere(false) ?? fallbackWhere(true) ?? selection; } if (textGeneratorCannotRun && selection.instanceId === textGeneratorId) { return yield* new TextGenerationError({ diff --git a/apps/server/src/textGeneration/TextGenerationPresets.ts b/apps/server/src/textGeneration/TextGenerationPresets.ts index 2dd3b95321290..ad3ff52688e9f 100644 --- a/apps/server/src/textGeneration/TextGenerationPresets.ts +++ b/apps/server/src/textGeneration/TextGenerationPresets.ts @@ -5,7 +5,7 @@ export const conventionalCommitsTextGenerationPolicy: TextGenerationPolicy = { commitInstructions: "Use Conventional Commits when generating commit subjects. Prefer the narrowest accurate type and include a scope only when it is obvious from the diff. Start the description after the colon with a lowercase word, never a proper noun or acronym, because commitlint rejects a capitalized description.", changeRequestInstructions: - "Keep the change request title concise. Do not force Conventional Commit syntax into the title unless the repository already uses it.", + "Keep the change request title concise. When the listed commits use Conventional Commits, write the title as a Conventional Commit subject too, for example 'feat(web): add a recorder', with the narrowest accurate type, a scope only when obvious, and a lowercase description. Otherwise do not force Conventional Commit syntax into the title.", inferRepositoryConventions: false, }; diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index f341ebd987a6c..3a4dd7cedf10a 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -369,8 +369,10 @@ export class GitVcsDriver extends Context.Service< cwd: string, options?: GitRemoteStatusOptions, ) => Effect.Effect; - /** Refs, HEAD and shallow boundaries. Null when the snapshot cannot be read. */ - readonly readRefSnapshot: (cwd: string) => Effect.Effect; + /** Refs, HEAD and shallow boundaries. Null on read failure. */ + readonly readLocalStatusRefSnapshot: (cwd: string) => Effect.Effect; + /** Includes worktree paths. Accepts an existing local status ref snapshot to avoid re-reading refs. */ + readonly readRefSnapshot: (cwd: string, refs?: string) => Effect.Effect; readonly prepareCommitContext: ( cwd: string, filePaths?: readonly string[], diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index b25e0ff2a8f64..b3ad640db4c7a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -302,7 +302,7 @@ const makeTmpDir = ( ): Effect.Effect => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; - return yield* fileSystem.makeTempDirectoryScoped({ prefix }); + return yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped({ prefix })); }); const writeTextFile = ( @@ -720,7 +720,10 @@ it.effect.each(["bare", "unborn"] as const)( } else { assert.isEmpty(refs.refs); } - assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1); + assert.equal( + spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, + state === "bare" ? 2 : 1, + ); }), ).pipe(Effect.provide(layerTest)), ); @@ -829,7 +832,7 @@ it.effect.each(["on a branch", "detached", "unborn"] as const)( file: { path: "new.txt", previousPath: null, sourceKind: "working-tree" }, } as const; const workingTree = yield* driver.getReviewDiffPreview(workingTreeFile); - assert.deepStrictEqual(discoveries(), { commonDir: 1, worktreeRoot: 1, branch: 1 }); + assert.deepStrictEqual(discoveries(), { commonDir: 1, worktreeRoot: 1, branch: 0 }); assert.deepStrictEqual( workingTree.sources .find((source) => source.kind === "working-tree")! @@ -964,8 +967,14 @@ it.effect("resolves a branch's base once while its refs and branch config are un }); assert.deepStrictEqual(reused.sources, withUntracked.sources); yield* (yield* FileSystem.FileSystem).remove(`${cwd}/untracked.txt`); + yield* driver.statusDetailsLocal(cwd); spawnedArgs.length = 0; + // Git for Windows' no-op `fetch --dry-run` touches a refs directory without moving a ref. + NodeFS.utimesSync(`${cwd}/.git/refs/heads`, 1_893_456_000, 1_893_456_000); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 0); + yield* git(cwd, ["config", "branch.feature/x.t3-merge-base-ref", "refs/heads/main"]); yield* driver.statusDetailsLocal(cwd); assert.equal(lookups(), 1); @@ -1869,61 +1878,114 @@ describe("pullCurrentBranch", () => { ); }); -it.effect("retries an in-flight ref snapshot invalidated by a mutation", () => +it.effect.each(["a T3 branch creation", "an external worktree addition"] as const)( + "refreshes an in-flight ref snapshot after %s", + (mutation) => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const firstScanCompleted = yield* Deferred.make(); + const releaseOtherScans = yield* Deferred.make(); + const firstScan = yield* Ref.make(true); + const coordinatingSpawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if (!ChildProcess.isStandardCommand(command)) { + return yield* Effect.die("expected a standard Git command"); + } + const isWorktreeScan = + command.args.includes("worktree") && command.args.includes("--porcelain"); + const isRefScan = + command.args.includes("for-each-ref") && + command.args.includes("refs/heads") && + command.args.includes("refs/remotes"); + if (!isRefScan && (!isWorktreeScan || mutation === "a T3 branch creation")) { + return yield* delegate.spawn(command); + } + if (!(yield* Ref.getAndSet(firstScan, false))) { + yield* Deferred.await(releaseOtherScans); + return yield* delegate.spawn(command); + } + const handle = yield* delegate.spawn(command); + return ChildProcessSpawner.makeHandle({ + ...handle, + exitCode: handle.exitCode.pipe( + Effect.tap(() => + Deferred.succeed(firstScanCompleted, undefined).pipe( + Effect.andThen(Deferred.await(releaseOtherScans)), + ), + ), + ), + }); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, coordinatingSpawner), + ); + const cwd = yield* makeTmpDir(); + const worktree = (yield* Path.Path).join(cwd, "linked checkout"); + const refName = "feature/during-refresh"; + yield* initRepoWithCommit(cwd).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + ); + const list = driver.listRefs({ cwd, refresh: true, query: refName }); + const inFlight = yield* list.pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(firstScanCompleted); + + if (mutation === "a T3 branch creation") { + yield* driver.createRef({ cwd, refName }); + yield* Deferred.succeed(releaseOtherScans, undefined); + assert.equal((yield* Fiber.join(inFlight)).refs[0]?.name, refName); + } else { + yield* git(cwd, ["worktree", "add", "-b", refName, worktree]).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + ); + const refresh = yield* list.pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.succeed(releaseOtherScans, undefined); + assert.equal((yield* Fiber.join(refresh)).refs[0]?.worktreePath, worktree); + yield* Fiber.join(inFlight); + } + }), + ).pipe( + Effect.provide( + layerServerConfig.pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); + +it.effect("a refreshed ref list reads the current branch and repository paths once", () => Effect.scoped( Effect.gen(function* () { const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; - const firstWorktreeScanStarted = yield* Deferred.make(); - const firstRefScanCompleted = yield* Deferred.make(); - const releaseFirstWorktreeScan = yield* Deferred.make(); - const delayFirstWorktreeScan = yield* Ref.make(true); - const refScans = yield* Ref.make(0); - const coordinatingSpawner = ChildProcessSpawner.make((command) => - Effect.gen(function* () { - if (!ChildProcess.isStandardCommand(command)) { - return yield* Effect.die("expected a standard Git command"); - } - const isWorktreeScan = - command.args.includes("worktree") && command.args.includes("--porcelain"); - if (isWorktreeScan && (yield* Ref.getAndSet(delayFirstWorktreeScan, false))) { - yield* Deferred.succeed(firstWorktreeScanStarted, undefined); - yield* Deferred.await(releaseFirstWorktreeScan); - } - const handle = yield* delegate.spawn(command); - const isRefScan = - command.args.includes("for-each-ref") && - command.args.includes("refs/heads") && - command.args.includes("refs/remotes"); - if (!isRefScan) return handle; - const scan = yield* Ref.updateAndGet(refScans, (count) => count + 1); - return scan === 1 - ? ChildProcessSpawner.makeHandle({ - ...handle, - exitCode: handle.exitCode.pipe( - Effect.tap(() => Deferred.succeed(firstRefScanCompleted, undefined)), - ), - }) - : handle; - }), - ); + const spawnedArgs: Array> = []; + const recordingSpawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); const driver = yield* makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, coordinatingSpawner), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, recordingSpawner), ); const cwd = yield* makeTmpDir(); yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); + yield* git(cwd, ["checkout", "-b", "outside-checkout"]).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + ); + spawnedArgs.length = 0; - const inFlight = yield* driver - .listRefs({ cwd, refresh: true, limit: 100 }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(firstWorktreeScanStarted); - yield* Deferred.await(firstRefScanCompleted); - - yield* driver.createRef({ cwd, refName: "feature/during-refresh" }); - yield* Deferred.succeed(releaseFirstWorktreeScan, undefined); + // The branch selector's paginated queries send two refreshes at once. + const [first, second] = yield* Effect.all( + [ + driver.listRefs({ cwd, refresh: true }), + driver.listRefs({ cwd, refresh: true, limit: 1 }), + ], + { concurrency: 2 }, + ); - const refs = yield* Fiber.join(inFlight); - assert.isTrue(refs.refs.some((ref) => ref.name === "feature/during-refresh")); - assert.equal(yield* Ref.get(refScans), 2); + assert.equal(first.refs.find((ref) => ref.current)?.name, "outside-checkout"); + assert.equal(second.refs.find((ref) => ref.current)?.name, "outside-checkout"); + assert.equal(spawnedArgs.filter((args) => args[0] === "symbolic-ref").length, 1); + assert.equal(spawnedArgs.filter((args) => args[0] === "rev-parse").length, 1); }), ).pipe( Effect.provide( @@ -1934,6 +1996,40 @@ it.effect("retries an in-flight ref snapshot invalidated by a mutation", () => ), ); +it.effect("keeps cached branch occupancy when Git cannot rescan worktrees", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + let failWorktreeScan = false; + const spawner = ChildProcessSpawner.make((command) => + failWorktreeScan && + ChildProcess.isStandardCommand(command) && + command.args.includes("worktree") && + command.args.includes("--porcelain") + ? Effect.fail( + PlatformError.systemError({ + _tag: "Unknown", + module: "ChildProcess", + method: "spawn", + }), + ) + : delegate.spawn(command), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const list = driver.listRefs({ cwd, refresh: true, query: initialBranch }); + const cached = yield* list; + assert.equal(cached.refs[0]?.worktreePath, cwd); + + failWorktreeScan = true; + assert.deepEqual(yield* list, cached); + }).pipe(Effect.provide(layerTest)), + ), +); + it.effect("superseded ref snapshots of one repository do not evict another's", () => Effect.scoped( Effect.gen(function* () { @@ -2022,6 +2118,35 @@ it.effect("invalidates a ref snapshot when a mutation fails after changing Git", ), ); +it.effect("lists external worktree paths even within the ref snapshot refresh window", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const path = yield* Path.Path; + const worktree = path.join(cwd, "another checkout"); + const movedWorktree = path.join(cwd, "moved checkout"); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["branch", "feature"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + const list = driver.listRefs({ cwd, refresh: true, query: "feature" }); + yield* list; + + yield* git(cwd, ["worktree", "add", worktree, "feature"]); + assert.equal((yield* list).refs[0]?.worktreePath, worktree); + yield* git(cwd, ["worktree", "move", worktree, movedWorktree]); + assert.equal((yield* list).refs[0]?.worktreePath, movedWorktree); + yield* git(cwd, ["worktree", "remove", movedWorktree]); + assert.isNull((yield* list).refs[0]?.worktreePath); + + yield* git(cwd, ["worktree", "add", "-b", "new-branch", worktree]); + const newBranchQuery = { cwd, query: "new-branch" }; + assert.equal( + (yield* driver.listRefs({ ...newBranchQuery, refresh: true })).refs[0]?.worktreePath, + worktree, + ); + assert.equal((yield* driver.listRefs(newBranchQuery)).refs[0]?.worktreePath, worktree); + }).pipe(Effect.provide(layerTest), Effect.scoped), +); + it.effect("marks the current branch when worktree metadata is unavailable", () => Effect.scoped( Effect.gen(function* () { @@ -5801,6 +5926,35 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("a ref snapshot detects which branches are checked out in other worktrees", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const worktree = (yield* Path.Path).join(cwd, "linked checkout"); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["branch", "feature"]); + yield* git(cwd, ["branch", "same-commit"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + const snapshot = driver.readRefSnapshot(cwd); + const initial = yield* snapshot; + assert.isNotNull(initial); + + yield* git(cwd, ["worktree", "add", "--detach", worktree]); + assert.equal(yield* snapshot, initial); + yield* git(worktree, ["checkout", "feature"]); + const attached = yield* snapshot; + assert.isNotNull(attached); + assert.notEqual(attached, initial); + assert.equal(yield* snapshot, attached); + yield* git(worktree, ["checkout", "same-commit"]); + const switched = yield* snapshot; + assert.isNotNull(switched); + assert.notEqual(switched, attached); + assert.notEqual(switched, initial); + yield* git(cwd, ["worktree", "remove", worktree]); + assert.equal(yield* snapshot, initial); + }), + ); + it.effect("a ref snapshot detects branch identity, ref and ancestry changes", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -9669,6 +9823,49 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("publishes a new branch at the same commit as its local upstream", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-remote-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", initialBranch]); + const remoteBase = yield* git(remote, [ + "--git-dir=.", + "rev-parse", + `refs/heads/${initialBranch}`, + ]); + yield* writeTextFile(cwd, "feature.txt", "feature\n"); + yield* git(cwd, ["add", "feature.txt"]); + const { commitSha } = yield* driver.commit(cwd, "Add feature", ""); + yield* git(cwd, ["config", "branch.autoSetupMerge", "always"]); + yield* driver.createRef({ cwd, refName: "feature/push" }); + yield* driver.switchRef({ cwd, refName: "feature/push" }); + assert.equal( + yield* git(cwd, ["rev-parse", "--symbolic-full-name", "@{upstream}"]), + `refs/heads/${initialBranch}`, + ); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { + status: "pushed", + upstreamBranch: "origin/feature/push", + setUpstream: true, + }); + assert.equal( + yield* git(remote, ["--git-dir=.", "rev-parse", "refs/heads/feature/push"]), + commitSha, + ); + assert.equal( + yield* git(remote, ["--git-dir=.", "rev-parse", `refs/heads/${initialBranch}`]), + remoteBase, + ); + }), + ); + it.effect("republishes a branch whose upstream was deleted", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -10128,6 +10325,35 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "publishes a new branch prefixed with another remote's name under its full name", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const origin = yield* makeTmpDir("git-remote-"); + const fork = yield* makeTmpDir("git-fork-"); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(origin, ["init", "--bare"]); + yield* git(fork, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", origin]); + // e.g. the remote T3 adds when checking out a pull request from alice's fork. + yield* git(cwd, ["remote", "add", "alice", fork]); + yield* git(cwd, ["checkout", "-b", "alice/fix"]); + yield* writeTextFile(cwd, "fix.txt", "fix\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add fix", ""); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { status: "pushed", upstreamBranch: "origin/alice/fix" }); + assert.equal( + yield* git(origin, ["--git-dir=.", "rev-parse", "refs/heads/alice/fix"]), + yield* git(cwd, ["rev-parse", "HEAD"]), + ); + }), + ); + it.effect("still pushes a git-mangled tracking alias to its upstream head", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 4356de894f0b4..f863f01bdb40a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -213,7 +213,6 @@ interface GitRepositoryPaths { readonly gitCommonDir: string; readonly worktreeRoot: string | null; readonly isAtRepositoryRoot: boolean | undefined; - readonly currentBranch: string | null; } interface GitRefsSnapshot { @@ -221,6 +220,7 @@ interface GitRefsSnapshot { readonly localBranches: ReadonlyArray; readonly remoteBranches: ReadonlyArray; readonly hasPrimaryRemote: boolean; + readonly worktreeStamp: string | null; } interface ExecuteGitOptions { @@ -1354,6 +1354,50 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { ...lineResult, stdout: lineResult.stdout.replaceAll("\n", "\0") }; }); + const readWorktreeBranchPaths = Effect.fn("GitVcsDriver.readWorktreeBranchPaths")(function* ( + gitCommonDir: string, + ) { + const cwd = path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; + const result = yield* executeWorktreeList( + "GitVcsDriver.readWorktreeBranchPaths", + cwd, + ["--git-dir", gitCommonDir], + { allowNonZeroExit: true, maxOutputBytes: 16 * 1024 * 1024 }, + ); + if (result.exitCode !== 0) return null; + + const entries = [...parseWorktreeBranchPaths(result.stdout)].map( + ([branchName, worktreePath]) => + [branchName, path.normalize(path.resolve(worktreePath))] as const, + ); + // Without core.worktree, Git reports a separate git dir as the main checkout. + const normalizedGitCommonDir = path.normalize(path.resolve(gitCommonDir)); + const existing = yield* Effect.filter( + entries, + ([, worktreePath]) => + worktreePath === normalizedGitCommonDir + ? Effect.succeed(false) + : fileSystem.stat(worktreePath).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ), + { concurrency: 16 }, + ); + return { + paths: new Map(existing), + stamp: existing + .map((entry) => JSON.stringify(entry)) + .sort() + .join("\n"), + }; + }); + + // Share overlapping reads without retaining occupancy across external Git commands. + const worktreeBranchPathsCache = yield* Cache.makeWith(readWorktreeBranchPaths, { + capacity: LIST_REFS_SNAPSHOT_CACHE_CAPACITY, + timeToLive: () => Duration.zero, + }); + const runGitStdoutWithOptions = ( operation: string, cwd: string, @@ -1665,8 +1709,21 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } }); - const readGitCommonDir = Effect.fn("readGitCommonDir")(function* (cwd: string) { + const resolveGitCommonDirOutput = Effect.fn("resolveGitCommonDirOutput")(function* ( + cwd: string, + commonDirOutput: string, + ) { // Git reports relative paths from the physical cwd, which can differ from a symlink. + const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); + const resolvedGitCommonDir = path.isAbsolute(commonDirOutput) + ? path.normalize(commonDirOutput) + : path.resolve(physicalCwd, commonDirOutput); + return yield* fileSystem + .realPath(resolvedGitCommonDir) + .pipe(Effect.orElseSucceed(() => resolvedGitCommonDir)); + }); + + const readGitCommonDir = Effect.fn("readGitCommonDir")(function* (cwd: string) { const commonDirResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.resolveRepositoryPaths.commonDir", cwd, @@ -1694,16 +1751,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } - const commonDirOutput = commonDirResult.stdout.replace(/\n$/, ""); - const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); - const resolvedGitCommonDir = path.isAbsolute(commonDirOutput) - ? path.normalize(commonDirOutput) - : path.resolve(physicalCwd, commonDirOutput); - return yield* fileSystem - .realPath(resolvedGitCommonDir) - .pipe(Effect.orElseSucceed(() => resolvedGitCommonDir)); + return yield* resolveGitCommonDirOutput(cwd, commonDirResult.stdout.replace(/\n$/, "")); }); + const normalizeWorktreeRootOutput = (cwd: string, output: string) => + output.length > 0 + ? path.normalize(path.isAbsolute(output) ? output : path.resolve(cwd, output)) + : null; + const readWorktreeRoot = Effect.fn("readWorktreeRoot")(function* (cwd: string) { const result = yield* executeGit( "GitVcsDriver.resolveRepositoryPaths.worktreeRoot", @@ -1718,9 +1773,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // binary mode on Windows). Whitespace before it belongs to the path and must survive, // because this root becomes the editor target for every repository-relative status path. const output = result.stdout.endsWith("\n") ? result.stdout.slice(0, -1) : result.stdout; - return result.exitCode === 0 && output.length > 0 - ? path.normalize(path.isAbsolute(output) ? output : path.resolve(cwd, output)) - : null; + return result.exitCode === 0 ? normalizeWorktreeRootOutput(cwd, output) : null; }); const readCurrentBranch = (operation: string, cwd: string) => @@ -1734,15 +1787,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const resolveRepositoryPathsUncached = Effect.fn("resolveRepositoryPathsUncached")(function* ( cwd: string, ) { - const gitCommonDir = yield* readGitCommonDir(cwd); - if (gitCommonDir === null) return null; - const [worktreeRoot, currentBranch] = yield* Effect.all( - [ - readWorktreeRoot(cwd), - readCurrentBranch("GitVcsDriver.resolveRepositoryPaths.currentBranch", cwd), - ], - { concurrency: 2 }, + const layout = yield* executeGitWithStableDiagnostics( + "GitVcsDriver.resolveRepositoryPaths.layout", + cwd, + ["rev-parse", "--git-common-dir", "--show-toplevel"], + { timeoutMs: 5_000, allowNonZeroExit: true }, ); + // --show-toplevel fails outside a work tree (a bare repository), and a newline in either + // path splits the output further; both fall back to separate reads. + const fields = layout.stdout.replace(/\n$/, "").split("\n"); + const [commonDirOutput, worktreeRootOutput] = + layout.exitCode === 0 && fields.length === 2 && fields.every((field) => field.length > 0) + ? fields + : []; + const gitCommonDir = + commonDirOutput === undefined + ? yield* readGitCommonDir(cwd) + : yield* resolveGitCommonDirOutput(cwd, commonDirOutput); + if (gitCommonDir === null) return null; + const worktreeRoot = + worktreeRootOutput !== undefined + ? normalizeWorktreeRootOutput(cwd, worktreeRootOutput) + : layout.exitCode === 0 + ? yield* readWorktreeRoot(cwd) + : null; // Git reports physical roots, so resolve project aliases before comparing. const isAtRepositoryRoot = worktreeRoot === null @@ -1756,7 +1824,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* gitCommonDir, worktreeRoot, isAtRepositoryRoot, - currentBranch, } satisfies GitRepositoryPaths; }); @@ -1938,12 +2005,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), }); - const readRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readRefSnapshot"] = Effect.fn( - "GitVcsDriver.readRefSnapshot", - )( - function* (cwd) { + const readLocalStatusRefSnapshot = Effect.fn("GitVcsDriver.readLocalStatusRefSnapshot")( + function* (cwd: string) { const result = yield* executeGit( - "GitVcsDriver.readRefSnapshot", + "GitVcsDriver.readLocalStatusRefSnapshot", cwd, ["show-ref", "--head"], { @@ -1953,7 +2018,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); if (result.exitCode !== 0) return null; const symbolicHead = yield* executeGit( - "GitVcsDriver.readRefSnapshot", + "GitVcsDriver.readLocalStatusRefSnapshot", cwd, ["symbolic-ref", "--quiet", "HEAD"], { allowNonZeroExit: true }, @@ -1961,7 +2026,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // Exit 1 means detached HEAD; other failures require a full status read. if (symbolicHead.exitCode !== 0 && symbolicHead.exitCode !== 1) return null; // Deepening a shallow clone changes ancestry without moving refs. - const shallowPath = path.join(yield* resolveGitCommonDir(cwd), "shallow"); + const gitCommonDir = yield* resolveGitCommonDir(cwd); + const shallowPath = path.join(gitCommonDir, "shallow"); const shallow = (yield* fileSystem.exists(shallowPath)) ? yield* fileSystem.readFileString(shallowPath) : ""; @@ -1970,6 +2036,22 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.orElseSucceed(() => null), ); + const readRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readRefSnapshot"] = Effect.fn( + "GitVcsDriver.readRefSnapshot", + )( + function* (cwd, refs) { + const localRefs = refs ?? (yield* readLocalStatusRefSnapshot(cwd)); + if (localRefs === null) return null; + const gitCommonDir = yield* resolveGitCommonDir(cwd); + const worktrees = yield* Cache.get(worktreeBranchPathsCache, gitCommonDir).pipe( + Effect.timeoutOption(5_000), + Effect.map(Option.getOrNull), + ); + return worktrees === null ? null : `${localRefs}\0${worktrees.stamp}`; + }, + Effect.orElseSucceed(() => null), + ); + // Returns the upstream remote name it read, or undefined when it did not read one. const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* ( cwd: string, @@ -2065,14 +2147,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map(parseRemoteNamesInGitOrder), ); - const resolvePublishBranchName = Effect.fn("resolvePublishBranchName")(function* ( - cwd: string, - branchName: string, - ) { - const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.orElseSucceed(() => [])); - const parsedRemoteRef = parseRemoteRefWithRemoteNames(branchName, remoteNames); - return parsedRemoteRef?.branchName ?? branchName; - }); + // Only the destination remote's prefix is dropped; `alice/fix` pushed to origin keeps its full name. + const resolvePublishBranchName = (branchName: string, remoteName: string) => + parseRemoteRefWithRemoteNames(branchName, [remoteName])?.branchName ?? branchName; const hasAnyRemote = (cwd: string) => resolveRepositoryPaths(cwd).pipe( @@ -2407,8 +2484,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); // The effective config listing covers included, global, system and worktree config. Git writes - // packed-refs by rename and each loose ref by a rename in its directory, so those stats change - // whenever a ref could. Cost: one git process, plus a stat and listing per refs directory. + // packed-refs and each loose ref by rename, so their stats change whenever a ref could. Directory + // stats are left out: Git for Windows' no-op fetch touches refs/remotes/. + // Cost: one git process, a listing per refs directory and a stat per loose ref. const readBaseBranchInputsStamp = Effect.fn("GitVcsDriverCore.readBaseBranchInputsStamp")( function* (cwd: string, gitCommonDir: string) { const effectiveConfig = yield* executeGit( @@ -2441,16 +2519,25 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* path.join(gitCommonDir, "refs", "heads"), path.join(gitCommonDir, "refs", "remotes"), ]; + const looseRefs: Array = []; for (let index = 0; index < directories.length; index++) { const directory = directories[index]!; - tokens.push(`${directory}=${yield* statToken(directory)}`); const entries = yield* fileSystem .readDirectoryEntries(directory) .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed([]))); for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) { - if (entry.type === "Directory") directories.push(path.join(directory, entry.name)); + const entryPath = path.join(directory, entry.name); + if (entry.type === "Directory") directories.push(entryPath); + else looseRefs.push(entryPath); } } + tokens.push( + ...(yield* Effect.forEach( + looseRefs, + (ref) => Effect.map(statToken(ref), (token) => `${ref}=${token}`), + { concurrency: 16 }, + )), + ); tokens.push(configHash); return tokens.join("\0"); }, @@ -2918,7 +3005,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* gitCommonDir, worktreeRoot, isAtRepositoryRoot, - currentBranch: refName, }); } } @@ -3589,7 +3675,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // A gone local upstream still gets the full local name, as below. const branchName = goneUpstream?.branchName ?? - (configuredRemoteName === "." ? branch : yield* resolvePublishBranchName(cwd, branch)); + (configuredRemoteName === "." ? branch : resolvePublishBranchName(branch, remoteName)); return { remoteName, branchName, @@ -3640,10 +3726,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( Effect.orElseSucceed(() => null), ); - const branchName = yield* resolvePublishBranchName(cwd, branch); + const remoteName = publishRemoteName ?? upstream.remoteName; return { - remoteName: publishRemoteName ?? upstream.remoteName, - branchName, + remoteName, + branchName: resolvePublishBranchName(branch, remoteName), publishes: true, upstream, pushRemote: null, @@ -3683,7 +3769,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const requestedRemoteName = options?.remoteName?.trim() || null; if (requestedRemoteName) { - const publishBranch = yield* resolvePublishBranchName(cwd, branch); + const publishBranch = resolvePublishBranchName(branch, requestedRemoteName); yield* executeGitWithStableDiagnostics( "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote", cwd, @@ -3702,8 +3788,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const destination = yield* resolvePushDestination(cwd, branch, details.hasUpstream); if (hasNoLocalDelta && details.hasUpstream) { if (!destination?.pushRemote) { - // The tracking ref reflects the fetch URL, so it says nothing about a separate push URL. - if (!destination || (yield* pushesOnlyToFetchUrl(cwd, destination.remoteName))) { + // A local upstream and a separate push URL both leave the publish destination unchecked. + if ( + !destination || + (destination.upstream?.remoteName !== "." && + (yield* pushesOnlyToFetchUrl(cwd, destination.remoteName))) + ) { return { status: "skipped_up_to_date" as const, branch, @@ -5271,7 +5361,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const fetchCwd = path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; const gitDirArgs = ["--git-dir", gitCommonDir] as const; - const [refsResult, defaultRefResult, worktreeListResult, remoteNamesResult] = yield* Effect.all( + // Read occupancy first so a concurrent worktree addition changes the cached stamp. + const worktrees = yield* Cache.get(worktreeBranchPathsCache, gitCommonDir); + const [refsResult, defaultRefResult, remoteNamesResult] = yield* Effect.all( [ executeGitWithStableDiagnostics( "GitVcsDriver.listRefs.snapshotRefs", @@ -5305,11 +5397,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* allowNonZeroExit: true, }, ), - executeWorktreeList("GitVcsDriver.listRefs.worktreeList", fetchCwd, gitDirArgs, { - timeoutMs: 30_000, - allowNonZeroExit: true, - maxOutputBytes: 16 * 1024 * 1024, - }), executeGit("GitVcsDriver.listRefs.remoteNames", fetchCwd, [...gitDirArgs, "remote"], { timeoutMs: 5_000, allowNonZeroExit: true, @@ -5329,27 +5416,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* defaultRefResult.exitCode === 0 ? parseDefaultBranchFromRemoteHeadRef(defaultRefResult.stdout, "origin") : null; - const parsedWorktreeEntries = - worktreeListResult.exitCode === 0 - ? [...parseWorktreeBranchPaths(worktreeListResult.stdout)].map( - ([branchName, worktreePath]) => - [branchName, path.normalize(path.resolve(worktreePath))] as const, - ) - : []; - // Without `core.worktree`, Git reports a separate git dir as the main checkout. - const normalizedGitCommonDir = path.normalize(path.resolve(gitCommonDir)); - const existingWorktreeEntries = yield* Effect.filter( - parsedWorktreeEntries, - ([, worktreePath]) => - worktreePath === normalizedGitCommonDir - ? Effect.succeed(false) - : fileSystem.stat(worktreePath).pipe( - Effect.as(true), - Effect.orElseSucceed(() => false), - ), - { concurrency: 16 }, - ); - const worktreeMap = new Map(existingWorktreeEntries); const localBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = []; const remoteBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = []; @@ -5368,7 +5434,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* current: false, isRemote: false, isDefault: name === defaultBranch, - worktreePath: worktreeMap.get(name) ?? null, + worktreePath: worktrees?.paths.get(name) ?? null, ...(upstreamRef ? { upstreamRef } : {}), }, lastCommit, @@ -5406,6 +5472,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* localBranches: localBranches.toSorted(byRecencyThenName).map(({ ref }) => ref), remoteBranches: remoteBranches.toSorted(byRecencyThenName).map(({ ref }) => ref), hasPrimaryRemote: remoteNames.length > 0, + worktreeStamp: worktrees?.stamp ?? null, } satisfies GitRefsSnapshot; }); @@ -5482,6 +5549,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Exit.isSuccess(exit) ? LIST_REFS_REFRESH_COALESCE_TTL : LIST_REFS_REFRESH_FAILURE_COOLDOWN, }, ); + const invalidateListRefsSnapshots = Effect.fn("GitVcsDriver.invalidateListRefsSnapshots")( + function* (gitCommonDir: string, generation: number) { + bumpListRefsGeneration(gitCommonDir); + yield* advanceListRefsEpoch(gitCommonDir); + yield* Cache.invalidate( + listRefsRefreshSnapshotCache, + new GitRefsRefreshCacheKey({ gitCommonDir, generation }), + ); + }, + ); const resolveListRefsSnapshot = Effect.fn("resolveListRefsSnapshot")(function* ( gitCommonDir: string, refresh: boolean, @@ -5489,17 +5566,28 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* while (true) { const generation = currentListRefsGeneration(gitCommonDir); const currentEpoch = listRefsEpochByCommonDir.get(gitCommonDir); - const snapshot = - refresh || currentEpoch === undefined - ? // Cache the entire snapshot read so slow scans stay single-flight beyond the coalescing TTL. - yield* Cache.get( - listRefsRefreshSnapshotCache, - new GitRefsRefreshCacheKey({ gitCommonDir, generation }), - ) - : yield* Cache.get( - listRefsSnapshotCache, - new GitRefsSnapshotCacheKey({ gitCommonDir, epoch: currentEpoch }), - ); + if (refresh || currentEpoch === undefined) { + const key = new GitRefsRefreshCacheKey({ gitCommonDir, generation }); + const cached = yield* Cache.getOption(listRefsRefreshSnapshotCache, key); + if (Option.isNone(cached)) { + const snapshot = yield* Cache.get(listRefsRefreshSnapshotCache, key); + if (currentListRefsGeneration(gitCommonDir) === generation) return snapshot; + continue; + } + // A joined load may have read occupancy before this refresh was requested. + const worktrees = yield* Cache.get(worktreeBranchPathsCache, gitCommonDir).pipe( + Effect.orElseSucceed(() => null), + ); + if (currentListRefsGeneration(gitCommonDir) !== generation) continue; + if (worktrees === null || cached.value.worktreeStamp === worktrees.stamp) + return cached.value; + yield* invalidateListRefsSnapshots(gitCommonDir, generation); + continue; + } + const snapshot = yield* Cache.get( + listRefsSnapshotCache, + new GitRefsSnapshotCacheKey({ gitCommonDir, epoch: currentEpoch }), + ); if (currentListRefsGeneration(gitCommonDir) === generation) { return snapshot; } @@ -5515,20 +5603,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? (yield* Cache.get(repositoryPathsCache, repositoryPathsCacheKey))?.gitCommonDir : gitCommonDir; if (commonDir == null) return; - const previousGeneration = currentListRefsGeneration(commonDir); - bumpListRefsGeneration(commonDir); - yield* advanceListRefsEpoch(commonDir); - yield* Cache.invalidate( - listRefsRefreshSnapshotCache, - new GitRefsRefreshCacheKey({ - gitCommonDir: commonDir, - generation: previousGeneration, - }), - ); + yield* invalidateListRefsSnapshots(commonDir, currentListRefsGeneration(commonDir)); yield* Cache.invalidate(repositoryPathsRefreshCache, repositoryPathsCacheKey); yield* Cache.invalidate(repositoryPathsCache, repositoryPathsCacheKey); }); + // Single-flight only: concurrent ref lists share one read, and none outlives a checkout. + const listRefsCurrentBranchCache = yield* Cache.makeWith( + (cwd: string) => readCurrentBranch("GitVcsDriver.listRefs.currentBranch", cwd), + { capacity: REPOSITORY_PATHS_CACHE_CAPACITY, timeToLive: () => Duration.zero }, + ); + const listRefs: GitVcsDriver.GitVcsDriver["Service"]["listRefs"] = Effect.fn("listRefs")( function* (input) { const repositoryPaths = yield* resolveRepositoryPaths(input.cwd, input.refresh === true).pipe( @@ -5552,8 +5637,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const [snapshot, currentBranch] = yield* Effect.all( [ resolveListRefsSnapshot(repositoryPaths.gitCommonDir, input.refresh === true), - readCurrentBranch("GitVcsDriver.listRefs.currentBranch", input.cwd).pipe( - Effect.orElseSucceed(() => repositoryPaths.currentBranch), + Cache.get(listRefsCurrentBranchCache, normalizeRepositoryPathsCacheKey(input.cwd)).pipe( + Effect.orElseSucceed(() => null), ), ], { concurrency: 2 }, @@ -6939,6 +7024,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* statusDetails, statusDetailsLocal, statusDetailsRemote, + readLocalStatusRefSnapshot, readRefSnapshot, prepareCommitContext, commit: Effect.fnUntraced(function* (cwd, subject, body, options) { diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 69c33b785bd41..455dadc1766ba 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -78,8 +78,10 @@ function layerTestFor(state: { localInvalidationCalls: number; remoteInvalidationCalls: number; remoteStatusRefreshUpstreamValues?: Array; + remoteStatusReusedDetails?: Array; localStatusBranchChanges?: Array; refSnapshot?: string | null; + worktreeStamp?: string | null; remoteStatusError?: GitManagerError; backgroundWorkEnabled?: boolean; automaticFetchInterval?: Effect.Effect; @@ -141,18 +143,40 @@ function layerTestFor(state: { : (state.beforeCurrentBranch ?? Effect.void).pipe( Effect.andThen(Effect.sync(() => state.currentLocalStatus.refName)), ), - readRefSnapshot: () => + readLocalStatusRefSnapshot: () => Effect.sync(() => (state.refSnapshot === undefined ? "refs" : state.refSnapshot)), + readRefSnapshot: (_cwd, refs) => + Effect.sync(() => { + const localRefs = + refs ?? (state.refSnapshot === undefined ? "refs" : state.refSnapshot); + return localRefs === null || state.worktreeStamp === null + ? null + : `${localRefs}\0${state.worktreeStamp ?? ""}`; + }), upstreamDivergence: () => - Effect.sync(() => - state.currentRemoteStatus?.hasUpstream && state.currentLocalStatus.refName !== null - ? { - refName: state.currentLocalStatus.refName, - aheadCount: (state.currentDivergence ?? state.currentRemoteStatus).aheadCount, - behindCount: (state.currentDivergence ?? state.currentRemoteStatus).behindCount, - } - : null, - ), + Effect.sync(() => { + const refName = state.currentLocalStatus.refName; + if (!state.currentRemoteStatus?.hasUpstream || refName === null) return null; + const { aheadCount, behindCount } = + state.currentDivergence ?? state.currentRemoteStatus; + return { + refName, + aheadCount, + behindCount, + details: { + isRepo: true, + hasPrimaryRemote: true, + defaultBranch: "main", + isDefaultBranch: false, + branch: refName, + upstreamRef: `origin/${refName}`, + hasUpstream: true, + aheadCount, + behindCount, + aheadOfDefaultCount: aheadCount, + }, + }; + }), remoteStatus: (_input, options) => Effect.suspend(() => { return (state.beforeRemoteStatus ?? Effect.void).pipe( @@ -160,6 +184,7 @@ function layerTestFor(state: { Effect.sync(() => { state.remoteStatusCalls += 1; state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream); + state.remoteStatusReusedDetails?.push(options?.statusDetails !== undefined); return state.currentRemoteStatus; }), ), @@ -350,7 +375,7 @@ describe("VcsStatusBroadcaster", () => { yield* broadcaster.refreshLocalStatus(`/other-repo-${index}`); } yield* Deferred.succeed(releasePolicy, undefined); - const result = yield* Fiber.join(refresh); + const { refsDigest: _refsDigest, ...result } = yield* Fiber.join(refresh); assert.deepStrictEqual(result, { ...baseLocalStatus, ...state.currentRemoteStatus }); }).pipe(Effect.provide(layer), Effect.scoped); }); @@ -717,7 +742,10 @@ describe("VcsStatusBroadcaster", () => { return Effect.gen(function* () { const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; const initial = yield* broadcaster.getStatus({ cwd: "/repo" }); - const refreshed = yield* broadcaster.refreshStatus("/repo", { localOnly: true }); + const { refsDigest, ...refreshed } = yield* broadcaster.refreshStatus("/repo", { + localOnly: true, + }); + assert.isString(refsDigest); assert.deepStrictEqual(refreshed, initial); assert.deepStrictEqual(yield* broadcaster.getStatus({ cwd: "/repo" }), refreshed); assert.equal(state.localInvalidationCalls, 1); @@ -791,6 +819,27 @@ describe("VcsStatusBroadcaster", () => { }, ); + it.effect("the turn-end PR lookup reuses the upstream read it follows, once", () => { + const state: Parameters[0] = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: remoteStatusWithPr, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + remoteStatusReusedDetails: [], + }; + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* broadcaster.getStatus({ cwd: "/repo" }); + yield* broadcaster.refreshLocalStatus("/repo"); + yield* broadcaster.refreshPullRequestStatus("/repo"); + yield* broadcaster.refreshPullRequestStatus("/repo"); + assert.deepStrictEqual(state.remoteStatusReusedDetails, [false, true, false]); + }).pipe(Effect.provide(layerTestFor(state))); + }); + it.effect.each([0, 2])( "refreshes merge divergence while a lookup ends with %s commits behind", (behindAfterLookup) => { @@ -925,6 +974,7 @@ describe("VcsStatusBroadcaster", () => { Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => Effect.succeed(localStatus), currentBranch: () => Effect.succeed(localStatus.refName), + readLocalStatusRefSnapshot: () => Effect.succeed("refs"), readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.succeed(remoteStatus), invalidateLocalStatus: () => Effect.void, @@ -1022,6 +1072,7 @@ describe("VcsStatusBroadcaster", () => { Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => Effect.succeed(baseLocalStatus), currentBranch: () => Effect.succeed(baseLocalStatus.refName), + readLocalStatusRefSnapshot: () => Effect.succeed("refs"), readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.gen(function* () { @@ -1069,6 +1120,7 @@ describe("VcsStatusBroadcaster", () => { Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => Effect.succeed(baseLocalStatus), currentBranch: () => Effect.succeed(baseLocalStatus.refName), + readLocalStatusRefSnapshot: () => Effect.succeed("refs"), readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.gen(function* () { @@ -1123,6 +1175,7 @@ describe("VcsStatusBroadcaster", () => { return state.currentLocalStatus; }), currentBranch: () => Effect.succeed(state.currentLocalStatus.refName), + readLocalStatusRefSnapshot: () => Effect.succeed("refs"), readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.suspend(() => { @@ -1513,6 +1566,7 @@ describe("VcsStatusBroadcaster", () => { }), currentBranch: () => Effect.succeed(baseLocalStatus.refName), invalidateRemoteStatus: () => Effect.void, + readLocalStatusRefSnapshot: () => Effect.sync(() => refSnapshot), readRefSnapshot: () => Effect.sync(() => refSnapshot), remoteStatus: () => Deferred.succeed(fetchStarted, undefined).pipe( @@ -1568,8 +1622,27 @@ describe("VcsStatusBroadcaster", () => { yield* Deferred.await(subscribed); state.localStatusCalls = 0; - yield* broadcaster.refreshStatus("/repo"); + const unmoved = yield* broadcaster.refreshStatus("/repo"); + assert.equal(state.localStatusCalls, 1); + assert.isString(unmoved.refsDigest); + + state.localStatusCalls = 0; + state.beforeRemoteStatus = Effect.sync(() => { + state.worktreeStamp = "feature in /linked"; + }); + const worktreeChanged = yield* broadcaster.refreshStatus("/repo"); assert.equal(state.localStatusCalls, 1); + assert.isString(worktreeChanged.refsDigest); + assert.notEqual(worktreeChanged.refsDigest, unmoved.refsDigest); + + state.localStatusCalls = 0; + state.beforeRemoteStatus = Effect.sync(() => { + state.worktreeStamp = null; + }); + const worktreesUnreadable = yield* broadcaster.refreshStatus("/repo"); + assert.equal(state.localStatusCalls, 1); + assert.isUndefined(worktreesUnreadable.refsDigest); + state.worktreeStamp = "feature in /linked"; state.localStatusCalls = 0; state.currentRemoteStatus = baseRemoteStatus; @@ -1580,6 +1653,8 @@ describe("VcsStatusBroadcaster", () => { const moved = yield* broadcaster.refreshStatus("/repo"); assert.equal(state.localStatusCalls, 2); assert.deepStrictEqual(moved.branchChanges, totals(0).branchChanges); + assert.isString(moved.refsDigest); + assert.notEqual(moved.refsDigest, unmoved.refsDigest); assert.deepStrictEqual( [...(yield* Fiber.join(events))].map((event) => event._tag), // The first refresh adds the totals this palette-style subscription skipped. @@ -1588,8 +1663,9 @@ describe("VcsStatusBroadcaster", () => { state.localStatusCalls = 0; state.refSnapshot = null; - yield* broadcaster.refreshStatus("/repo"); + const unreadable = yield* broadcaster.refreshStatus("/repo"); assert.equal(state.localStatusCalls, 2); + assert.isUndefined(unreadable.refsDigest); }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); }); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 8a507e799c827..d1e9a9c5496c6 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest of the ref snapshot already in memory. +import * as NodeCrypto from "node:crypto"; + import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; @@ -20,6 +23,7 @@ import type { VcsBranchStatus, VcsStatusLocalResult, VcsStatusRemoteResult, + VcsRefreshStatusResult, VcsStatusResult, VcsStatusStreamEvent, VcsStatusSubscriptionInput, @@ -33,6 +37,7 @@ import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as ServerSettings from "../serverSettings.ts"; +import type * as GitVcsDriver from "./GitVcsDriver.ts"; import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30); @@ -231,7 +236,7 @@ export class VcsStatusBroadcaster extends Context.Service< readonly refreshStatus: ( cwd: string, options?: { readonly localOnly?: boolean }, - ) => Effect.Effect; + ) => Effect.Effect; readonly refreshPullRequestStatus: ( cwd: string, ) => Effect.Effect; @@ -326,6 +331,9 @@ export const make = Effect.gen(function* () { // A refresh that started after a request saw every change that request could mean, so queued // callers share it instead of each running git status again. const localRefreshRequests = new Map(); + // Upstream details the turn-end refreshLocalStatus just read, handed once to the PR lookup that + // follows it so the same no-fetch read is not repeated. Any remote write in between drops them. + const upstreamReads = new Map(); const localRefreshResults = new Map< string, { @@ -349,6 +357,7 @@ export const make = Effect.gen(function* () { // A queued caller can read git again. Keep the monotonic request counter so it cannot // mistake an older result for a later request. localRefreshResults.delete(candidate); + upstreamReads.delete(candidate); } return cache; }; @@ -445,6 +454,7 @@ export const make = Effect.gen(function* () { const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")( function* (cwd: string, remote: CachedRemoteStatus | null, options?: { publish?: boolean }) { + upstreamReads.delete(cwd); const [changed, value] = yield* Ref.modify(cacheRef, (cache) => { const previous = cache.get(cwd) ?? { local: null, remote: null }; const next = remote?.branch === previous.local?.value.refName ? remote : null; @@ -552,6 +562,7 @@ export const make = Effect.gen(function* () { "VcsStatusBroadcaster.refreshLocalStatus", )(function* (rawCwd) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); + upstreamReads.delete(cwd); const local = yield* refreshLocalStatusCore(cwd); const cached = yield* getCachedStatus(cwd); // Divergence is local Git data; a slow forge lookup must not delay turn-end updates. @@ -573,6 +584,7 @@ export const make = Effect.gen(function* () { }, { publish: true }, ); + upstreamReads.set(cwd, divergence.details); } } return local; @@ -586,7 +598,11 @@ export const make = Effect.gen(function* () { // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch. yield* workflow.invalidateRemoteStatus(cwd); const previousRemote = (yield* getCachedStatus(cwd))?.remote; - const remote = yield* workflow.remoteStatus({ cwd }, options); + const { statusDetails, ...remoteOptions } = options ?? {}; + const remote = yield* workflow.remoteStatus( + { cwd }, + statusDetails?.branch === branch ? { ...remoteOptions, statusDetails } : remoteOptions, + ); const latest = yield* getCachedStatus(cwd); // An overlapping turn refresh and fetch can both move divergence during the forge lookup. const refreshed = @@ -686,7 +702,7 @@ export const make = Effect.gen(function* () { if (refsAtLocalRead === undefined) { yield* refreshLocalStatusCore(cwd); } else { - const refs = yield* workflow.readRefSnapshot(cwd); + const refs = yield* workflow.readLocalStatusRefSnapshot(cwd); if (refs === null || refs !== (yield* Ref.get(refsAtLocalRead))) { yield* Ref.set(refsAtLocalRead, null); yield* refreshLocalStatusCore(cwd); @@ -711,17 +727,18 @@ export const make = Effect.gen(function* () { const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [policyCwd]) : null; - if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote); + if (pulled !== null) { + return { status: mergeGitStatusParts(pulled.local, pulled.remote), refs: null }; + } yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); // A fetch, ours or not, can move the base used for local Changes totals. - if ( - refsBeforeLocalRead === null || - (yield* workflow.readRefSnapshot(cwd)) !== refsBeforeLocalRead - ) { + const refs = + refsBeforeLocalRead === null ? null : yield* workflow.readLocalStatusRefSnapshot(cwd); + if (refs === null || refs !== refsBeforeLocalRead) { yield* refreshLocalStatusCore(cwd); } const parts = yield* getStatusParts(cwd); - return mergeGitStatusParts(parts.local, parts.remote); + return { status: mergeGitStatusParts(parts.local, parts.remote), refs }; }), ); }, @@ -732,14 +749,30 @@ export const make = Effect.gen(function* () { )(function* (rawCwd, options) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); yield* acquireBranchChangesDemand(cwd); - const refsBeforeLocalRead = options?.localOnly ? null : yield* workflow.readRefSnapshot(cwd); - yield* refreshLocalStatusCore(cwd); + // Lets the client keep its cached branch list when refs and worktree paths match its last refresh. + const withRefsDigest = (status: VcsStatusResult, refs: string | null) => + refs === null + ? status + : { + ...status, + refsDigest: NodeCrypto.createHash("sha256").update(refs).digest("hex").slice(0, 32), + }; if (options?.localOnly) { + const [refs] = yield* Effect.all( + [workflow.readRefSnapshot(cwd), refreshLocalStatusCore(cwd)], + { concurrency: "unbounded" }, + ); // Never cache a remote here: readers take `value: null` as "read and found no PR". const parts = yield* getStatusParts(cwd); - return mergeGitStatusParts(parts.local, parts.remote); + return withRefsDigest(mergeGitStatusParts(parts.local, parts.remote), refs); } - return yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead); + const refsBeforeLocalRead = yield* workflow.readLocalStatusRefSnapshot(cwd); + yield* refreshLocalStatusCore(cwd); + const { status, refs } = yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead); + return withRefsDigest( + status, + refs === null ? null : yield* workflow.readRefSnapshot(cwd, refs), + ); }, Effect.scoped); const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn( @@ -766,9 +799,12 @@ export const make = Effect.gen(function* () { const cached = yield* getCachedStatus(cwd); if (!cached || cached.remote?.value === null) return null; // Turn completion must update divergence even when background polling is paused. + const statusDetails = upstreamReads.get(cwd); + upstreamReads.delete(cwd); const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream: false, refreshMissingPullRequest: true, + ...(statusDetails ? { statusDetails } : {}), }); return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); }), @@ -947,7 +983,7 @@ export const make = Effect.gen(function* () { // A request made during a refresh needs a read that starts after it, so overlapping requests // share one follow-up. Keyed by raw cwd because auto-pull policy depends on it. // Missing means idle; null means running with no follow-up queued. - type SharedRefresh = Deferred.Deferred; + type SharedRefresh = Deferred.Deferred; const queuedRefreshesRef = yield* Ref.make(new Map()); const runQueuedRefreshes = Effect.fn("VcsStatusBroadcaster.runQueuedRefreshes")(function* ( @@ -974,7 +1010,7 @@ export const make = Effect.gen(function* () { "VcsStatusBroadcaster.shareQueuedRefreshStatus", )(function* (rawCwd, options) { if (options?.localOnly) return yield* refreshStatus(rawCwd, options); - const requested = yield* Deferred.make(); + const requested = yield* Deferred.make(); // Registering and forking together keeps an interrupt from leaving an entry with no worker. const shared = yield* Effect.uninterruptible( Effect.gen(function* () { diff --git a/apps/server/src/workspace/TaskFolders.test.ts b/apps/server/src/workspace/TaskFolders.test.ts index 37fd360cf8b24..c156f190e0049 100644 --- a/apps/server/src/workspace/TaskFolders.test.ts +++ b/apps/server/src/workspace/TaskFolders.test.ts @@ -347,6 +347,64 @@ it.live("puts a clone the project ignores inside the project's worktree", () => ), ); +it.live("creates the task folder when the project's checkout hook already linked a clone", () => + withState((state) => + Effect.gen(function* () { + const { fileSystem, path, tmp, run, repository } = yield* fixture; + const project = yield* repository("p"); + yield* fileSystem.writeFileString(path.join(project, ".gitignore"), "vendor/\n"); + yield* run(project, "add", "."); + yield* run(project, "commit", "-m", "ignore vendor"); + const lib = yield* repository("p/vendor/lib"); + // Like many projects with vendored clones, a new worktree links them back to the checkout. + const hooks = path.join(tmp, "hooks"); + yield* fileSystem.makeDirectory(hooks); + yield* fileSystem.writeFileString( + path.join(hooks, "post-checkout"), + `#!/bin/sh\nmkdir -p vendor && ln -s "${lib}" vendor/lib\n`, + { mode: 0o755 }, + ); + yield* run(project, "config", "core.hooksPath", hooks); + state.workspaceRoot = project; + state.trackedFolders = tracked(lib); + + const created = yield* create("feature").pipe(Effect.exit); + + assert.isTrue(Exit.isSuccess(created), String(Exit.isFailure(created) && created.cause)); + }), + ), +); + +it.live("leaves a hook's link to an empty folder alone", () => + withState((state) => + Effect.gen(function* () { + const { fileSystem, path, tmp, run, repository } = yield* fixture; + const project = yield* repository("p"); + yield* fileSystem.writeFileString(path.join(project, ".gitignore"), "vendor/\n"); + yield* run(project, "add", "."); + yield* run(project, "commit", "-m", "ignore vendor"); + const lib = yield* repository("p/vendor/lib"); + const target = path.join(tmp, "empty"); + yield* fileSystem.makeDirectory(target); + const hooks = path.join(tmp, "hooks"); + yield* fileSystem.makeDirectory(hooks); + yield* fileSystem.writeFileString( + path.join(hooks, "post-checkout"), + `#!/bin/sh\nmkdir -p vendor && ln -s "${target}" vendor/lib\n`, + { mode: 0o755 }, + ); + yield* run(project, "config", "core.hooksPath", hooks); + state.workspaceRoot = project; + state.trackedFolders = tracked(lib); + + const created = yield* create("feature").pipe(Effect.exit); + + assert.isTrue(Exit.isSuccess(created), String(Exit.isFailure(created) && created.cause)); + assert.deepStrictEqual(yield* fileSystem.readDirectory(target), []); + }), + ), +); + it.live("treats a project folder inside a larger repository as plain", () => withState((state) => Effect.gen(function* () { diff --git a/apps/server/src/workspace/TaskFolders.ts b/apps/server/src/workspace/TaskFolders.ts index 3dd74d90d2d80..4911065118ce4 100644 --- a/apps/server/src/workspace/TaskFolders.ts +++ b/apps/server/src/workspace/TaskFolders.ts @@ -243,6 +243,16 @@ const make = Effect.gen(function* () { const exists = (target: string) => fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false)); const isRepository = (folder: string) => exists(path.join(folder, ".git")); + const occupied = Effect.fnUntraced(function* (target: string) { + if (!(yield* exists(target))) return false; + const isDirectory = (yield* fileSystem.stat(target).pipe(Effect.option)).pipe( + Option.exists((info) => info.type === "Directory"), + ); + if (!isDirectory) return true; + return ( + (yield* fileSystem.readDirectory(target).pipe(Effect.orElseSucceed(() => [""]))).length > 0 + ); + }); const trackedFolders = (project: { readonly workspaceRoot: string; readonly trackedFolders: ReadonlyArray; @@ -855,6 +865,13 @@ const make = Effect.gen(function* () { baseBranch: string | undefined, ) { const worktreePath = mapped(taskFolder, repository.path); + // The project's own checkout (a post-checkout hook, say) already provided this repository. + // A link counts even to an empty folder: Git would write the worktree through it. + if ( + Option.isSome(yield* fileSystem.readLink(worktreePath).pipe(Effect.option)) || + (yield* occupied(worktreePath)) + ) + return null; yield* fileSystem.makeDirectory(path.dirname(worktreePath), { recursive: true }); const start = yield* repositoryStart(repository.path, startFromOrigin, baseBranch); yield* git.createWorktree({ @@ -1006,6 +1023,9 @@ const make = Effect.gen(function* () { } else { yield* linkFolder(taskPlan.projectRoot, empty.projectPath, taskPlan.trackedRepositories); } + let finished = 0; + // Whatever the project put at a skipped path also stands for the repositories inside it. + const skipped: string[] = []; // A repository inside another waits for the one that holds it. const levels = Map.groupBy( taskPlan.repositories, @@ -1021,21 +1041,28 @@ const make = Effect.gen(function* () { const exits = yield* Effect.forEach( levels.get(level)!, (repository) => - createRepositoryWorktree( - empty, - repository, - branch, - input.startFromOrigin, - input.baseBranch, + (skipped.some((outer) => isWithinRoot(path, repository.path, outer)) + ? Effect.succeed(null) + : createRepositoryWorktree( + empty, + repository, + branch, + input.startFromOrigin, + input.baseBranch, + ) ).pipe( Effect.tap((worktree) => Effect.suspend(() => { - created.push(worktree.repository); - repositoriesStartedFromOrigin ||= worktree.fromOrigin; + finished += 1; + if (worktree === null) skipped.push(repository.path); + else { + created.push(worktree.repository); + repositoriesStartedFromOrigin ||= worktree.fromOrigin; + } return ( input.onRepository?.({ name: repository.name, - done: created.length, + done: finished, total: taskPlan.repositories.length, }) ?? Effect.void ); @@ -1189,15 +1216,7 @@ const make = Effect.gen(function* () { path.relative(taskFolder.projectRoot, repositoryPath), ).pipe(Effect.mapError(fail("add-repository", "Could not prepare the folder"))) : true; - const occupied = - !opened || - ((yield* exists(worktreePath)) && - ((yield* fileSystem.stat(worktreePath).pipe(Effect.option)).pipe( - Option.exists((info) => info.type !== "Directory"), - ) || - (yield* fileSystem.readDirectory(worktreePath).pipe(Effect.orElseSucceed(() => [""]))) - .length > 0)); - if (occupied) + if (!opened || (yield* occupied(worktreePath))) return yield* refuse(`${worktreePath} already holds files, so no worktree can go there.`); // The link the worktree took the place of comes back when the worktree does not stay. const relink = wasLinked diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 446f231cff607..2453f0c528f57 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -1165,5 +1165,33 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }); }), ); + + it.effect("lists symlinks to directories under their link path", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-symlink-" }); + const externalTarget = yield* makeTempDir({ + prefix: "t3code-workspace-browse-symlink-target-", + }); + yield* writeTextFile(cwd, "real-dir/readme.md", "hi"); + yield* writeTextFile(cwd, "plain.txt", "hi"); + + yield* fileSystem.symlink(externalTarget, path.join(cwd, "personal")); + yield* fileSystem.symlink(path.join(cwd, "plain.txt"), path.join(cwd, "file-link")); + yield* fileSystem.symlink(path.join(cwd, "does-not-exist"), path.join(cwd, "broken-link")); + + const result = yield* workspaceEntries.browse({ + partialPath: yield* appendSeparator(cwd), + }); + + expect(result.entries).toEqual([ + { name: "personal", fullPath: path.join(cwd, "personal") }, + { name: "real-dir", fullPath: path.join(cwd, "real-dir") }, + ]); + }), + ); }); }); diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.ts index 0be5321078761..738268f95558b 100644 --- a/apps/server/src/workspace/WorkspaceEntries.ts +++ b/apps/server/src/workspace/WorkspaceEntries.ts @@ -6,6 +6,7 @@ import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as RcMap from "effect/RcMap"; import * as Schema from "effect/Schema"; @@ -154,11 +155,32 @@ const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(fu ); }); +// A link to an unresponsive network share must not hold up the local entries beside it. +const SYMLINK_TARGET_STAT_TIMEOUT = Duration.seconds(1); +// A timed-out stat cannot be cancelled and keeps a libuv worker (4 by default) busy, +// so cap target stats in flight to leave most of the pool to other fs work. +const MAX_PENDING_SYMLINK_TARGET_STATS = 2; + /** @public */ export const make = Effect.gen(function* () { const path = yield* Path.Path; const workspacePaths = yield* WorkspacePaths.WorkspacePaths; const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap; + let pendingSymlinkTargetStats = 0; + const statSymlinkTarget = (candidate: { readonly name: string; readonly fullPath: string }) => { + if (pendingSymlinkTargetStats >= MAX_PENDING_SYMLINK_TARGET_STATS) { + return Promise.resolve(null); + } + pendingSymlinkTargetStats++; + return NodeFSP.stat(candidate.fullPath) + .then( + (stats) => (stats.isDirectory() ? candidate : null), + () => null, + ) + .finally(() => { + pendingSymlinkTargetStats--; + }); + }; const vcsProcess = yield* VcsProcess.VcsProcess; const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* ( @@ -252,16 +274,33 @@ export const make = Effect.gen(function* () { const showHidden = endsWithSeparator || prefix.startsWith("."); const lowerPrefix = prefix.toLowerCase(); const entries: Array<{ readonly name: string; readonly fullPath: string }> = []; + const symlinkCandidates: Array<{ readonly name: string; readonly fullPath: string }> = []; for (const dirent of dirents) { if ( - dirent.isDirectory() && - dirent.name.toLowerCase().startsWith(lowerPrefix) && - (showHidden || !dirent.name.startsWith(".")) + !dirent.name.toLowerCase().startsWith(lowerPrefix) || + (!showHidden && dirent.name.startsWith(".")) ) { - entries.push({ - name: dirent.name, - fullPath: path.join(parentPath, dirent.name), - }); + continue; + } + const fullPath = path.join(parentPath, dirent.name); + if (dirent.isDirectory()) { + entries.push({ name: dirent.name, fullPath }); + } else if (dirent.isSymbolicLink()) { + symlinkCandidates.push({ name: dirent.name, fullPath }); + } + } + if (symlinkCandidates.length > 0) { + const resolvedSymlinks = yield* Effect.forEach( + symlinkCandidates, + (candidate) => + Effect.promise(() => statSymlinkTarget(candidate)).pipe( + Effect.timeoutOption(SYMLINK_TARGET_STAT_TIMEOUT), + Effect.map(Option.getOrNull), + ), + { concurrency: MAX_PENDING_SYMLINK_TARGET_STATS }, + ); + for (const candidate of resolvedSymlinks) { + if (candidate !== null) entries.push(candidate); } } diff --git a/apps/server/src/workspace/WorkspaceFolders.test.ts b/apps/server/src/workspace/WorkspaceFolders.test.ts index 61dac26a8c044..3a02d202be891 100644 --- a/apps/server/src/workspace/WorkspaceFolders.test.ts +++ b/apps/server/src/workspace/WorkspaceFolders.test.ts @@ -193,6 +193,43 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { }), ); + it.effect("does not walk a project's folders when t3.json ignores the whole project", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceRoot = yield* makeTempDir; + for (const folder of ["api/.git", "src/web/.git", "notes"]) { + yield* fileSystem.makeDirectory(path.join(workspaceRoot, folder), { recursive: true }); + } + yield* fileSystem.writeFileString( + path.join(workspaceRoot, "t3.json"), + JSON.stringify({ ignoreRepositories: ["."] }), + ); + const probed: Array = []; + const counting = FileSystem.FileSystem.of({ + ...fileSystem, + readDirectory: (target, options) => { + probed.push(target); + return fileSystem.readDirectory(target, options); + }, + stat: (target) => { + probed.push(target); + return fileSystem.stat(target); + }, + }); + + const found = yield* WorkspaceFolders.discoverFolders(workspaceRoot).pipe( + Effect.provideService(FileSystem.FileSystem, counting), + ); + + assert.deepEqual(found, []); + assert.deepEqual( + probed.filter((target) => target !== workspaceRoot), + [], + ); + }), + ); + it.effect("keeps the folders someone added when a project holds more than fit", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -293,17 +330,21 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { folders: [], extraRoots: [], }); - assert.deepEqual(yield* workspaceFolders.submodules({ projectId, worktreePath: null }), [ - { name: "lib", path: path.join(workspaceRoot, "vendor", "lib"), isGitRepository: true }, - { - name: "deep", - path: path.join(workspaceRoot, "vendor", "lib", "deep"), - isGitRepository: true, - }, - ]); + const { folders } = yield* workspaceFolders.forThread({ projectId, worktreePath: null }); + assert.deepEqual( + yield* workspaceFolders.submodules({ projectId, worktreePath: null, folders }), + [ + { name: "lib", path: path.join(workspaceRoot, "vendor", "lib"), isGitRepository: true }, + { + name: "deep", + path: path.join(workspaceRoot, "vendor", "lib", "deep"), + isGitRepository: true, + }, + ], + ); // A worktree reaches its own submodules, named by where the project folder has them. assert.deepEqual( - yield* workspaceFolders.submodules({ projectId, worktreePath: worktree }), + yield* workspaceFolders.submodules({ projectId, worktreePath: worktree, folders: [] }), [ { name: "lib", diff --git a/apps/server/src/workspace/WorkspaceFolders.ts b/apps/server/src/workspace/WorkspaceFolders.ts index 776f90ea6e5b0..0824c647ce360 100644 --- a/apps/server/src/workspace/WorkspaceFolders.ts +++ b/apps/server/src/workspace/WorkspaceFolders.ts @@ -64,6 +64,8 @@ export class WorkspaceFolders extends Context.Service< readonly submodules: (input: { readonly projectId: ProjectId; readonly worktreePath: string | null; + /** The thread's `forThread` folders; passed in so the project is walked once. */ + readonly folders: ReadonlyArray; }) => Effect.Effect, WorkspaceFoldersError>; readonly list: ( input: WorkspaceListFoldersInput, @@ -276,11 +278,7 @@ export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function* const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const { realPath, ownsHistory } = yield* folderProbes; - // Uncapped: the folders outside the project are dropped below, and must not use up the room. - const scan = yield* scanFolders({ workspaceRoot }, Number.POSITIVE_INFINITY).pipe(Effect.option); - if (Option.isNone(scan)) return []; - const root = scan.value.workspaceRoot; - const realRoot = yield* realPath(root); + const root = path.resolve(expandHomePath(workspaceRoot.trim(), yield* HostProcess.HomeDirectory)); const ignored = ( parseT3ProjectFile( yield* fileSystem @@ -288,6 +286,12 @@ export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function* .pipe(Effect.orElseSucceed(() => "")), )?.ignoreRepositories ?? [] ).map((entry) => path.resolve(root, entry)); + // Everything the scan could find would be dropped, so skip the walk. + if (ignored.some((entry) => isWithinRoot(path, root, entry))) return []; + // Uncapped: the folders outside the project are dropped below, and must not use up the room. + const scan = yield* scanFolders({ workspaceRoot }, Number.POSITIVE_INFINITY).pipe(Effect.option); + if (Option.isNone(scan)) return []; + const realRoot = yield* realPath(root); const inside = yield* Effect.filter( scan.value.folders.filter( (folder) => @@ -506,7 +510,6 @@ const make = Effect.gen(function* () { const submodules: WorkspaceFolders["Service"]["submodules"] = Effect.fn( "WorkspaceFolders.submodules", )(function* (input) { - const { folders } = yield* forThread(input); // A worktree can outlive its project record; its submodules are then named by where they are. const projectRoot = yield* readProject(input.projectId).pipe( Effect.map((project) => path.resolve(project.workspaceRoot)), @@ -518,7 +521,7 @@ const make = Effect.gen(function* () { const identity = Option.getOrElse(projectRoot, () => root); return yield* submodulesOf([ { path: root, identity }, - ...folders.flatMap((folder) => + ...input.folders.flatMap((folder) => folder.isGitRepository ? [{ path: folder.path, identity: folder.repositoryPath ?? folder.path }] : [], diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index e629af899c172..02ca5170d7ffd 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -165,6 +165,7 @@ import * as SecretCheck from "./secrets/SecretCheck.ts"; import * as ServerConfigModule from "./config.ts"; import * as Keybindings from "./keybindings.ts"; import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as ServerSettings from "./serverSettings.ts"; import * as ManagedPolicy from "./policy/ManagedPolicy.ts"; @@ -906,6 +907,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(TaskFolders.TaskFolders)({}), Layer.mock(WorkspaceFileSystem.WorkspaceFileSystem)({}), Layer.mock(WorktreeSetupTracker.WorktreeSetupTracker)({}), + FeatureFlags.layerTest(), ); const layerConfigSources = Layer.mergeAll( diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index afa030d4d7e9c..ddd07fcfad656 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,6 +1,7 @@ import { GitCommandError, OrchestrationDispatchCommandError } from "@t3tools/contracts"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest inside the pure provider mapping. import * as NodeCrypto from "node:crypto"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; @@ -223,6 +224,7 @@ import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; import * as GitWorkflowService from "./git/GitWorkflowService.ts"; +import { assertCheckoutIdle } from "./git/sharedCheckoutGuard.ts"; import { refreshPushedPullRequests } from "./git/refreshPushedPullRequests.ts"; import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts"; import * as ReviewService from "./review/ReviewService.ts"; @@ -1533,6 +1535,7 @@ export const layerWsRpc = ( const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery; const nativeChildWork = yield* NativeChildWorkQuery.NativeChildWorkQuery; const keybindings = yield* Keybindings.Keybindings; + const featureFlags = yield* FeatureFlags.FeatureFlags; const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService; const externalLauncher = yield* ExternalLauncher.ExternalLauncher; const remoteOpenTargets = yield* RemoteOpenTargets.RemoteOpenTargets; @@ -1920,6 +1923,10 @@ export const layerWsRpc = ( secretProviderSettings: true, secretReferences: true, secretRequestReferences: true, + featureFlags: { + secretProviders: featureFlags.secretProviders, + tanstackSource: featureFlags.tanstackSource, + }, ...Option.match(scratchWorkspaceRoot, { onNone: () => ({}), onSome: (root) => ({ scratchWorkspaceRoot: root }), @@ -3258,9 +3265,13 @@ export const layerWsRpc = ( ), [WS_METHODS.gitResolvePullRequest]: (input) => gitWorkflow.resolvePullRequest(input), [WS_METHODS.gitPreparePullRequestThread]: (input) => - gitWorkflow - .preparePullRequestThread(input) - .pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + (input.mode === "local" + ? assertCheckoutIdle("GitWorkflowService.preparePullRequestThread", input.cwd) + : Effect.void + ).pipe( + Effect.andThen(gitWorkflow.preparePullRequestThread(input)), + Effect.tap(() => refreshGitStatus(input.cwd)), + ), [WS_METHODS.vcsListRefs]: (input) => gitWorkflow.listRefs(input), [WS_METHODS.vcsCreateWorktree]: (input) => // A project that tracks repositories gets a task folder, as its new worktree threads do. @@ -3305,19 +3316,22 @@ export const layerWsRpc = ( ), ), [WS_METHODS.vcsCreateRef]: (input) => - gitWorkflow - .createRef(input) - .pipe( - Effect.tap(() => - input.switchRef - ? vcsStatusBroadcaster.refreshAfterCheckout(input.cwd) - : refreshGitStatus(input.cwd), - ), + (input.switchRef + ? assertCheckoutIdle("GitWorkflowService.createRef", input.cwd) + : Effect.void + ).pipe( + Effect.andThen(gitWorkflow.createRef(input)), + Effect.tap(() => + input.switchRef + ? vcsStatusBroadcaster.refreshAfterCheckout(input.cwd) + : refreshGitStatus(input.cwd), ), + ), [WS_METHODS.vcsSwitchRef]: (input) => - gitWorkflow - .switchRef(input) - .pipe(Effect.tap(() => vcsStatusBroadcaster.refreshAfterCheckout(input.cwd))), + assertCheckoutIdle("GitWorkflowService.switchRef", input.cwd).pipe( + Effect.andThen(gitWorkflow.switchRef(input)), + Effect.tap(() => vcsStatusBroadcaster.refreshAfterCheckout(input.cwd)), + ), [WS_METHODS.vcsInit]: (input) => vcsProvisioning.initRepository(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.reviewGetBranchCommits]: (input) => review.getBranchCommits(input), diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts index 0ec539e5ae169..2715d2987b604 100644 --- a/apps/server/vite.config.ts +++ b/apps/server/vite.config.ts @@ -89,6 +89,11 @@ export default mergeConfig( dependsOn: ["@t3tools/web#build"], cache: false, }, + // A local tsbuildinfo is leftover build state, not a typecheck input. + typecheck: { + command: "effect-tsgo tsrs --noEmit", + cache: { input: [{ auto: true }, "!*.tsbuildinfo"] }, + }, }, }, pack: { diff --git a/apps/web/deps/README.md b/apps/web/deps/README.md new file mode 100644 index 0000000000000..26750d308c195 --- /dev/null +++ b/apps/web/deps/README.md @@ -0,0 +1,15 @@ +The Words tarball comes from the [`fork/t3-words` branch](https://github.com/pingdotgg/pierre/tree/fork/t3-words) of our fork of [pierrecomputer/pierre](https://github.com/pierrecomputer/pierre). Its `t3-fork.json` records the source commit and the upstream base. The fork adds opt-in options, all off by default so default output stays byte-identical to upstream: + +- `singleTilde: false`: only `~~` strikes. +- `windowsPaths`: backslashes in Windows drive paths stay. +- `codeMeta`: code fence info after the language becomes `data-meta`. +- `sourcePositions`: `data-sourcepos` byte ranges on list items, links, images, code blocks, math and directives. +- `directives`: the named remark-directive text and leaf directives. +- `escapeHtml`: raw HTML renders as escaped text. +- `leadingWhitespace`: spaces typed at the start of paragraph lines show, in `data-leading-whitespace` spans. +- `texDelimiters`: with `math`, `\(…\)` and `\[…\]` are math, as T3's llm-math reads them. +- `autolinkBoundaries`: end ASCII bare URLs before CJK/Arabic punctuation and keep trailing `_`/`~` when not closing emphasis. + +To replace it, commit the change on `fork/t3-words`, bump `packages/words/package.json` to the next `0.2.2-t3.N` and update `t3-fork.json`'s `source`, then run `moon run words:build` (or `node scripts/build.ts && tsdown`) and `npm pack` in `packages/words`. Name the archive with the first eight characters of the source commit, such as `pierre-words-0.2.2-t3.4-7c04b7f1.tgz`, update the path in `apps/web/package.json`, and run `vp i`. + +Change it through the fork, never with a pnpm patch: the next tarball would drop the patch without a trace. diff --git a/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz b/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz new file mode 100644 index 0000000000000..b6716f0395062 Binary files /dev/null and b/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz differ diff --git a/apps/web/package.json b/apps/web/package.json index 9e6f0f475b3d0..a60eb801260cf 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -34,6 +34,7 @@ "@noble/hashes": "catalog:", "@pierre/diffs": "catalog:", "@pierre/trees": "1.0.0-beta.6", + "@pierre/words": "file:deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz", "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/provider-core": "workspace:*", @@ -51,6 +52,7 @@ "@tiptap/extension-horizontal-rule": "^3.31.3", "@tiptap/extension-italic": "^3.31.3", "@tiptap/extension-list": "^3.31.3", + "@tiptap/extension-paragraph": "^3.31.3", "@tiptap/extension-strike": "^3.31.3", "@tiptap/extension-task-item": "^3.31.3", "@tiptap/extension-task-list": "^3.31.3", @@ -73,24 +75,16 @@ "jszip": "3.10.1", "katex": "^0.18.2", "lucide-react": "^0.564.0", - "mdast-util-from-markdown": "^2.0.3", - "micromark-util-combine-extensions": "^2.0.1", "pdfjs-dist": "6.4.299", "pele": "catalog:", + "property-information": "^7.2.0", "react": "catalog:", "react-dom": "catalog:", - "react-markdown": "^10.1.0", - "remark-gfm": "catalog:", - "remark-math": "6.0.0", - "remark-parse": "catalog:", - "remark-rehype": "catalog:", "saxes": "6.0.0", "sql.js": "1.15.0", "tailwind-merge": "^3.4.0", "tiff": "7.1.3", - "unified": "catalog:", "use-sync-external-store": "^1.6.0", - "vfile": "^6.0.3", "zustand": "^5.0.11" }, "devDependencies": { @@ -102,7 +96,6 @@ "@types/compression": "^1.8.1", "@types/culori": "^4.0.1", "@types/hast": "^3.0.4", - "@types/mdast": "^4.0.4", "@types/react": "catalog:", "@types/react-dom": "catalog:", "@types/sql.js": "1.4.11", @@ -112,7 +105,6 @@ "@vitest/browser-playwright": "5.0.5", "compression": "^1.8.2", "gt": "2.27.0", - "micromark-util-types": "catalog:", "oxc-transform-react": "~0.152.0", "playwright": "1.64.1", "tailwindcss": "^4.0.0", diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index ae8e685c5c9ec..cce59f08f6d12 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -62,6 +62,7 @@ import { installChatRouteCommands } from "./shortcuts/chatRouteCommands"; import { startWorkspaceFocus } from "./lib/workspaceFocus"; import { m } from "./i18n/messages"; import { startI18n, subscribeI18n } from "./i18n/runtime"; +import { guardDomAgainstPageTranslation } from "./lib/pageTranslationGuard"; import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands"; import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut"; import { environmentThreadShells, threadEnvironment } from "./state/threads"; @@ -267,6 +268,7 @@ export function startAppServices(): AppRouter { } installDesktopPasteAsText(window.desktopBridge, window); + guardDomAgainstPageTranslation(); startClientAppearance(); startI18n(); diff --git a/apps/web/src/bootstrap.test.ts b/apps/web/src/bootstrap.test.ts new file mode 100644 index 0000000000000..8421d5efe0fc8 --- /dev/null +++ b/apps/web/src/bootstrap.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +const mocks = vi.hoisted(() => ({ showBootError: vi.fn().mockName("showBootError") })); + +vi.mock("./lib/bootError", () => ({ showBootError: mocks.showBootError })); + +// Mirrors Vite's build preload helper when main's CSS or JS chunk fails to load. +vi.mock("./main", () => { + const error = new TypeError("Failed to fetch dynamically imported module: /assets/main.js"); + const event = Object.assign(new Event("vite:preloadError", { cancelable: true }), { + payload: error, + }); + window.dispatchEvent(event); + throw error; +}); + +function createStorageStub(initial: Record = {}): Storage { + const store = new Map(Object.entries(initial)); + return { + getItem: (key) => store.get(key) ?? null, + setItem: (key, value) => { + store.set(key, value); + }, + removeItem: (key) => { + store.delete(key); + }, + clear: () => store.clear(), + key: (index) => [...store.keys()][index] ?? null, + get length() { + return store.size; + }, + }; +} + +async function bootWithFailingMainChunk(storage: Storage) { + vi.resetModules(); + mocks.showBootError.mockClear(); + const reload = vi.fn().mockName("location.reload"); + vi.stubGlobal( + "window", + Object.assign(new EventTarget(), { sessionStorage: storage, location: { reload } }), + ); + try { + const { boot } = await import("./bootstrap"); + await boot; + return { reload, showBootError: mocks.showBootError }; + } finally { + vi.unstubAllGlobals(); + } +} + +describe("bootstrap", () => { + it("reloads once instead of showing the boot error when the main chunk fails to load", async () => { + const { reload, showBootError } = await bootWithFailingMainChunk(createStorageStub()); + + expect(reload).toHaveBeenCalledTimes(1); + expect(showBootError).not.toHaveBeenCalled(); + }); + + it("shows the boot error when the main chunk fails again after the reload", async () => { + const { reload, showBootError } = await bootWithFailingMainChunk( + createStorageStub({ "t3code:chunk-load-reloaded": import.meta.env.APP_VERSION }), + ); + + expect(reload).not.toHaveBeenCalled(); + expect(showBootError).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/web/src/bootstrap.ts b/apps/web/src/bootstrap.ts index b6f422c5d68f4..fe07e58b02872 100644 --- a/apps/web/src/bootstrap.ts +++ b/apps/web/src/bootstrap.ts @@ -1,4 +1,11 @@ import { showBootError } from "./lib/bootError"; +import { chunkLoadState, handleChunkLoadErrors } from "./lib/chunkReloadGuard"; + +handleChunkLoadErrors(); // Shared dev chunks need the React refresh preamble first. Catch failures before React mounts. -void import("./main").then(({ startup }) => startup).catch(showBootError); +export const boot = import("./main") + .then(({ startup }) => startup) + .catch((error: unknown) => { + if (!chunkLoadState.reloadScheduled) showBootError(error); + }); diff --git a/apps/web/src/browserHistoryStore.browser.test.ts b/apps/web/src/browserHistoryStore.browser.test.ts new file mode 100644 index 0000000000000..c0c22fc2558a4 --- /dev/null +++ b/apps/web/src/browserHistoryStore.browser.test.ts @@ -0,0 +1,302 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +import { resetBrowserHistoryForTests, useBrowserHistoryStore } from "./browserHistoryStore"; + +const storageKey = "t3code:browser-history:v1"; +const oldEntry = { url: "http://example.test/removed", lastVisitedAt: 1 }; +const otherEntry = { url: "http://example.test/other", lastVisitedAt: 2 }; +const page = { url: "http://localhost:3000/page", lastVisitedAt: 3, title: "Page" }; + +function storedHistory(): unknown { + return JSON.parse(localStorage.getItem(storageKey) ?? "null")?.state; +} + +function openHistoryFixture(disposables: DisposableStack) { + return new Promise((resolve, reject) => { + const request = indexedDB.open(storageKey, 1); + request.onupgradeneeded = () => request.result.createObjectStore("history"); + request.onsuccess = () => { + const db = request.result; + disposables.defer(() => db.close()); + resolve(db); + }; + request.onerror = () => reject(request.error); + }); +} + +function readHistoryFixture(db: IDBDatabase): Promise { + return new Promise((resolve, reject) => { + const request = db.transaction("history").objectStore("history").get(storageKey); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); +} + +function writeHistoryFixture(db: IDBDatabase, state: unknown): Promise { + return new Promise((resolve, reject) => { + const transaction = db.transaction("history", "readwrite"); + transaction.objectStore("history").put(state, storageKey); + transaction.oncomplete = () => resolve(); + transaction.onabort = () => reject(transaction.error); + }); +} + +it.each([ + { + name: "records a visit without bringing back a deleted URL", + change: () => useBrowserHistoryStore.getState().recordVisit("a", "http://example.test/new", 4), + expected: { + byProjectKey: { + a: [{ url: "http://example.test/new", lastVisitedAt: 4 }, page], + b: [otherEntry], + }, + }, + }, + { + name: "titles the latest matching visit without changing its URL", + change: () => + useBrowserHistoryStore.getState().setTitleForUrl("a", "http://127.0.0.1:3000/page/", "New"), + expected: { byProjectKey: { a: [{ ...page, title: "New" }], b: [otherEntry] } }, + }, + { + name: "removes a visit added elsewhere without clearing the other project", + change: () => useBrowserHistoryStore.getState().removeUrl("a", page.url), + expected: { byProjectKey: { b: [otherEntry] } }, + }, + { + name: "registers a thread without replacing another tab's history", + change: () => + useBrowserHistoryStore.getState().registerThreadProject( + { + environmentId: EnvironmentId.make("env"), + threadId: ThreadId.make("thread"), + }, + "a", + ), + expected: { byProjectKey: { a: [page], b: [otherEntry] } }, + }, +])("$name", async ({ change, expected }) => { + await resetHistoryFixture(); + try { + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); + useBrowserHistoryStore.getState().recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toMatchObject({ byProjectKey: { a: [oldEntry] } }), + ); + + // Another document has committed newer history that this store has not heard about. + await writeHistoryFixture(db, { + byProjectKey: { a: [page], b: [otherEntry] }, + projectKeyByThreadKey: {}, + }); + change(); + + await vi.waitFor(async () => { + const saved = await readHistoryFixture(db); + expect(saved).toHaveProperty("byProjectKey", expected.byProjectKey); + expect(saved).toHaveProperty( + "projectKeyByThreadKey", + useBrowserHistoryStore.getState().projectKeyByThreadKey, + ); + }); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey).toEqual(expected.byProjectKey), + ); + } finally { + await resetHistoryFixture(); + } +}); + +it("refreshes the open history when another document adds a visit", async () => { + await resetHistoryFixture(); + try { + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), + ); + + using documents = new DisposableStack(); + const otherStore = await openHistoryDocument(documents); + await vi.waitFor(() => expect(otherStore.getState().byProjectKey).toEqual({ a: [page] })); + otherStore.getState().recordVisit("a", page.url, page.lastVisitedAt); + + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({ a: [page] }), + ); + } finally { + await resetHistoryFixture(); + } +}); + +it("bounds saved thread mappings while keeping live registrations", async () => { + await resetHistoryFixture(); + const mappings = Object.fromEntries( + Array.from({ length: 100 }, (_, index) => [`env:thread-${index}`, "a"]), + ); + + try { + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); + await writeHistoryFixture(db, { byProjectKey: { a: [page] }, projectKeyByThreadKey: mappings }); + const store = useBrowserHistoryStore.getState(); + const environmentId = EnvironmentId.make("env"); + store.registerThreadProject({ environmentId, threadId: ThreadId.make("thread-0") }, "a"); + store.registerThreadProject({ environmentId, threadId: ThreadId.make("pending") }, "b"); + const { "env:thread-0": _oldest, ...retained } = mappings; + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toHaveProperty("projectKeyByThreadKey", { + ...retained, + "env:pending": "b", + }), + ); + + store.removeUrl("a", page.url); + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toHaveProperty("projectKeyByThreadKey", { + "env:pending": "b", + }), + ); + expect(useBrowserHistoryStore.getState().projectKeyByThreadKey["env:thread-0"]).toBe("a"); + } finally { + await resetHistoryFixture(); + } +}); + +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; +} + +function deleteHistoryDatabase() { + return new Promise((resolve, reject) => { + const request = indexedDB.deleteDatabase(storageKey); + request.onsuccess = () => resolve(); + request.onerror = () => reject(request.error); + }); +} + +async function resetHistoryFixture() { + localStorage.removeItem(storageKey); + await deleteHistoryDatabase(); + resetBrowserHistoryForTests(); +} + +it("moves the legacy snapshot into the shared database", async () => { + await resetHistoryFixture(); + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), + ); + try { + using documents = new DisposableStack(); + const first = await openHistoryDocument(documents); + 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); + await vi.waitFor(() => + expect(reopened.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), + ); + } finally { + await resetHistoryFixture(); + } +}); + +it("persists new visits from an open document after its history database is deleted", async () => { + await resetHistoryFixture(); + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), + ); + try { + using documents = new DisposableStack(); + const first = await openHistoryDocument(documents); + await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); + first.getState().removeUrl("a", page.url); + await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({})); + + await deleteHistoryDatabase(); + first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); + + const reopened = await openHistoryDocument(documents); + await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual({ b: [otherEntry] })); + } finally { + await resetHistoryFixture(); + } +}); + +it("keeps overlapping visits from independent documents", async () => { + await resetHistoryFixture(); + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), + ); + try { + using documents = new DisposableStack(); + const [first, second] = await Promise.all([ + openHistoryDocument(documents), + openHistoryDocument(documents), + ]); + first.getState().recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); + second.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + const expected = { a: [page, oldEntry], b: [otherEntry] }; + await vi.waitFor(() => { + expect(first.getState().byProjectKey).toEqual(expected); + expect(second.getState().byProjectKey).toEqual(expected); + }); + + // A fresh document should read the committed visits even after the legacy seed is gone. + localStorage.removeItem(storageKey); + const reopened = await openHistoryDocument(documents); + await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual(expected)); + } finally { + await resetHistoryFixture(); + } +}); + +it("keeps visits saved while IndexedDB could not open", async () => { + await resetHistoryFixture(); + try { + using documents = new DisposableStack(); + const db = await openHistoryFixture(documents); + 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] }), + ); + + const online = await openHistoryDocument(documents); + await vi.waitFor(() => + expect(online.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), + ); + expect(storedHistory()).toBeUndefined(); + } finally { + await resetHistoryFixture(); + } +}); diff --git a/apps/web/src/browserHistoryStore.ts b/apps/web/src/browserHistoryStore.ts index d5ccb0fcd621e..c6088b2abfca7 100644 --- a/apps/web/src/browserHistoryStore.ts +++ b/apps/web/src/browserHistoryStore.ts @@ -11,7 +11,6 @@ import { type ScopedThreadRef, } from "@t3tools/contracts"; import { create } from "zustand"; -import { createJSONStorage, persist } from "zustand/middleware"; import { useShallow } from "zustand/react/shallow"; import { normalizePreviewUrl } from "@t3tools/shared/preview"; @@ -40,7 +39,6 @@ import { isClientSettingsHydrated, useClientSettings, } from "./hooks/useSettings"; -import { resolveStorage } from "./lib/storage"; import { deriveLogicalProjectKeyFromSettings, derivePhysicalProjectKey, @@ -180,6 +178,7 @@ export function migratePersistedBrowserHistoryState(persistedState: unknown): { const BROWSER_HISTORY_STORAGE_KEY = "t3code:browser-history:v1"; +const MAX_PERSISTED_THREAD_MAPPINGS = 100; const PENDING_MAX_PER_THREAD = 10; const PENDING_MAX_THREADS = 20; @@ -199,7 +198,7 @@ interface BrowserHistoryStoreState { projectKey: string, url: string, title: string, - environmentHostname?: string | null, + options?: { environmentHostname?: string | null; onlyIfUntitled?: boolean }, ) => void; removeUrl: (projectKey: string, url: string) => void; registerThreadProject: (ref: ScopedThreadRef, projectKey: string) => void; @@ -221,100 +220,313 @@ function addPendingByThread( return next; } -export const useBrowserHistoryStore = create()( - persist( - (set, get) => ({ - byProjectKey: {}, - projectKeyByThreadKey: {}, - pendingVisitsByThreadKey: {}, - recordVisit: (projectKey, url, at, options) => { - const normalized = normalizeHistoryUrl(url); - if (!normalized) return; - set((state) => { - return { - byProjectKey: evictExcessProjects({ - ...state.byProjectKey, - [projectKey]: upsertHistoryEntry( - state.byProjectKey[projectKey] ?? [], - normalized, - at, - options, - ), - }), - }; - }); +type PersistedBrowserHistory = Pick< + BrowserHistoryStoreState, + "byProjectKey" | "projectKeyByThreadKey" +>; + +type UpdateHistory = (state: PersistedBrowserHistory) => PersistedBrowserHistory; + +function boundThreadMappings( + previous: PersistedBrowserHistory, + next: PersistedBrowserHistory, +): PersistedBrowserHistory { + return { + ...next, + projectKeyByThreadKey: Object.fromEntries( + Object.entries(next.projectKeyByThreadKey) + // Keep new registrations for empty projects, but drop projects that lost their history. + .filter( + ([, projectKey]) => + !Object.hasOwn(previous.byProjectKey, projectKey) || + Object.hasOwn(next.byProjectKey, projectKey), + ) + .slice(-MAX_PERSISTED_THREAD_MAPPINGS), + ), + }; +} + +const HISTORY_OBJECT_STORE = "history"; +const EMPTY_PERSISTED_HISTORY: PersistedBrowserHistory = { + byProjectKey: {}, + projectKeyByThreadKey: {}, +}; +let historyDatabase: Promise | undefined; +let historyChannel: BroadcastChannel | undefined; + +function readLegacyHistory( + missing: Missing = EMPTY_PERSISTED_HISTORY as Missing, +): PersistedBrowserHistory | Missing { + try { + const value = window.localStorage.getItem(BROWSER_HISTORY_STORAGE_KEY); + if (value === null) return missing; + const parsed: { state?: unknown } | null = JSON.parse(value); + return { + ...migratePersistedBrowserHistoryState(parsed?.state), + projectKeyByThreadKey: migratePersistedThreadProjectKeys(parsed?.state), + }; + } catch { + return EMPTY_PERSISTED_HISTORY; + } +} + +function retireLegacyHistory(): void { + try { + window.localStorage.removeItem(BROWSER_HISTORY_STORAGE_KEY); + } catch { + // The browser can deny access to localStorage independently of IndexedDB. + } +} + +// localStorage can gain visits after migration: from the fallback below, or a tab on an older build. +function mergeLegacyHistory( + saved: PersistedBrowserHistory, + legacy: PersistedBrowserHistory, +): PersistedBrowserHistory { + const byProjectKey = { ...saved.byProjectKey }; + for (const [projectKey, entries] of Object.entries(legacy.byProjectKey)) + byProjectKey[projectKey] = [...(byProjectKey[projectKey] ?? []), ...entries]; + return { + ...migratePersistedBrowserHistoryState({ byProjectKey }), + projectKeyByThreadKey: { ...legacy.projectKeyByThreadKey, ...saved.projectKeyByThreadKey }, + }; +} + +// Without IndexedDB, merge into the freshest localStorage snapshot so a reload keeps new visits. +function transactLegacyHistory(update: UpdateHistory, current: PersistedBrowserHistory) { + const previous = readLegacyHistory(current); + const next = update(previous); + if (next === previous) return previous; + const history = boundThreadMappings(previous, next); + try { + window.localStorage.setItem( + BROWSER_HISTORY_STORAGE_KEY, + JSON.stringify({ state: history, version: 1 }), + ); + } catch { + // History stays in memory when the browser denies both storage APIs. + } + return history; +} + +function invalidateHistoryDatabase(opening: Promise): void { + if (historyDatabase === opening) historyDatabase = undefined; +} + +function openHistoryDatabase() { + if (historyDatabase) return historyDatabase; + const opening = new Promise((resolve, reject) => { + const request = indexedDB.open(BROWSER_HISTORY_STORAGE_KEY, 1); + request.onupgradeneeded = () => request.result.createObjectStore(HISTORY_OBJECT_STORE); + request.onsuccess = () => { + const db = request.result; + db.onclose = () => invalidateHistoryDatabase(opening); + db.onversionchange = () => { + invalidateHistoryDatabase(opening); + db.close(); + }; + resolve(db); + }; + request.onerror = () => reject(request.error); + }); + historyDatabase = opening; + void opening.catch(() => invalidateHistoryDatabase(opening)); + return opening; +} + +async function transactIndexedHistory(update?: UpdateHistory, retry = true) { + const opening = openHistoryDatabase(); + const db = await opening; + let transaction: IDBTransaction; + try { + transaction = db.transaction(HISTORY_OBJECT_STORE, update ? "readwrite" : "readonly"); + } catch (error) { + if (error instanceof DOMException && error.name === "InvalidStateError") { + invalidateHistoryDatabase(opening); + if (retry) return transactIndexedHistory(update, false); + } + throw error; + } + + return new Promise<{ history: PersistedBrowserHistory; changed: boolean }>((resolve, reject) => { + const store = transaction.objectStore(HISTORY_OBJECT_STORE); + const request = store.get(BROWSER_HISTORY_STORAGE_KEY); + let history: PersistedBrowserHistory; + let changed = false; + request.onsuccess = () => { + const saved = request.result as PersistedBrowserHistory | undefined; + const legacy = update ? readLegacyHistory(null) : null; + const previous = + saved && legacy + ? mergeLegacyHistory(saved, legacy) + : (saved ?? legacy ?? EMPTY_PERSISTED_HISTORY); + const next = update?.(previous) ?? previous; + history = next === previous ? previous : boundThreadMappings(previous, next); + changed = history !== saved; + if (update && changed) store.put(history, BROWSER_HISTORY_STORAGE_KEY); + }; + transaction.oncomplete = () => { + // Keep the migration source until the IndexedDB snapshot has committed. + if (update) retireLegacyHistory(); + resolve({ history, changed }); + }; + transaction.onabort = () => reject(transaction.error); + }); +} + +export const useBrowserHistoryStore = create()((set, get) => { + const publish = ({ byProjectKey }: PersistedBrowserHistory) => { + if (byProjectKey !== get().byProjectKey) set({ byProjectKey }); + }; + const updateHistory = (update: UpdateHistory) => { + if (typeof window === "undefined") { + publish(update(get())); + return; + } + void transactIndexedHistory(update).then( + ({ history, changed }) => { + publish(history); + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel is scoped to the origin + if (changed) historyChannel?.postMessage(null); }, - setTitleForUrl: (projectKey, url, title, environmentHostname) => { - const normalized = normalizeHistoryUrl(url); - const state = get(); + () => { + const { byProjectKey, projectKeyByThreadKey } = get(); + publish(transactLegacyHistory(update, { byProjectKey, projectKeyByThreadKey })); + }, + ); + }; + + return mergeBrowserHistoryState(undefined, { + byProjectKey: {}, + projectKeyByThreadKey: {}, + pendingVisitsByThreadKey: {}, + recordVisit: (projectKey, url, at, options) => { + const normalized = normalizeHistoryUrl(url); + if (!normalized) return; + updateHistory((state) => { + const entries = state.byProjectKey[projectKey] ?? []; + return { + ...state, + byProjectKey: evictExcessProjects({ + ...state.byProjectKey, + [projectKey]: upsertHistoryEntry(entries, normalized, at, { + ...options, + insertOrdered: options?.insertOrdered || (entries[0]?.lastVisitedAt ?? at) > at, + }), + }), + }; + }); + }, + setTitleForUrl: (projectKey, url, title, options) => { + const normalized = normalizeHistoryUrl(url); + const trimmed = title.trim().slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH); + if (!normalized || trimmed.length === 0) return; + const key = titleLookupKey(normalized, options?.environmentHostname); + updateHistory((state) => { const entries = state.byProjectKey[projectKey]; - const trimmed = title.trim().slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH); - if (!normalized || !entries || trimmed.length === 0) return; - const key = titleLookupKey(normalized, environmentHostname); - const index = entries.findIndex( - (candidate) => titleLookupKey(candidate.url, environmentHostname) === key, - ); - if (index === -1 || entries[index]?.title === trimmed) return; - set({ + const index = + entries?.findIndex( + (candidate) => titleLookupKey(candidate.url, options?.environmentHostname) === key, + ) ?? -1; + const entry = entries?.[index]; + if ( + !entries || + !entry || + entry.title === trimmed || + (entry.title && options?.onlyIfUntitled) + ) + return state; + return { + ...state, byProjectKey: { ...state.byProjectKey, - [projectKey]: entries.map((candidate, candidateIndex) => - candidateIndex === index ? { ...candidate, title: trimmed } : candidate, - ), + [projectKey]: entries.with(index, { ...entry, title: trimmed }), }, - }); - }, - removeUrl: (projectKey, url) => { - const normalized = normalizeHistoryUrl(url); - const state = get(); + }; + }); + }, + removeUrl: (projectKey, url) => { + const normalized = normalizeHistoryUrl(url); + if (!normalized) return; + updateHistory((state) => { const entries = state.byProjectKey[projectKey]; - if (!normalized || !entries) return; + if (!entries) return state; const next = entries.filter((candidate) => candidate.url !== normalized); - if (next.length === entries.length) return; - if (next.length === 0) { - const { [projectKey]: _removed, ...rest } = state.byProjectKey; - set({ byProjectKey: rest }); - return; - } - set({ byProjectKey: { ...state.byProjectKey, [projectKey]: next } }); - }, - registerThreadProject: (ref, projectKey) => { - const threadKey = scopedThreadKey(ref); - const state = get(); - const pendingVisits = state.pendingVisitsByThreadKey[threadKey]; - if (state.projectKeyByThreadKey[threadKey] === projectKey && !pendingVisits) return; - const nextPendingVisits = { ...state.pendingVisitsByThreadKey }; - delete nextPendingVisits[threadKey]; - set({ - projectKeyByThreadKey: { ...state.projectKeyByThreadKey, [threadKey]: projectKey }, - pendingVisitsByThreadKey: nextPendingVisits, + if (next.length === entries.length) return state; + const byProjectKey = { ...state.byProjectKey }; + if (next.length === 0) delete byProjectKey[projectKey]; + else byProjectKey[projectKey] = next; + return { ...state, byProjectKey }; + }); + }, + registerThreadProject: (ref, projectKey) => { + const threadKey = scopedThreadKey(ref); + const state = get(); + const pendingVisits = state.pendingVisitsByThreadKey[threadKey]; + if (state.projectKeyByThreadKey[threadKey] === projectKey && !pendingVisits) return; + const nextPendingVisits = { ...state.pendingVisitsByThreadKey }; + delete nextPendingVisits[threadKey]; + set({ + projectKeyByThreadKey: { ...state.projectKeyByThreadKey, [threadKey]: projectKey }, + pendingVisitsByThreadKey: nextPendingVisits, + }); + updateHistory((shared) => + shared.projectKeyByThreadKey[threadKey] === projectKey + ? shared + : { + ...shared, + projectKeyByThreadKey: { ...shared.projectKeyByThreadKey, [threadKey]: projectKey }, + }, + ); + for (const visit of pendingVisits ?? []) + get().recordVisit(projectKey, visit.url, visit.at, { + insertOrdered: true, + environmentHostname: visit.environmentHostname, + }); + if (pendingVisits) + recordPreviewTitles(ref, readThreadPreviewState(ref), { + urls: pendingVisits.map((visit) => visit.url), }); - for (const visit of pendingVisits ?? []) - get().recordVisit(projectKey, visit.url, visit.at, { - insertOrdered: true, - environmentHostname: visit.environmentHostname, - }); - if (pendingVisits) - recordPreviewTitles(ref, readThreadPreviewState(ref), { - urls: pendingVisits.map((visit) => visit.url), - }); - }, - }), - { - name: BROWSER_HISTORY_STORAGE_KEY, - version: 1, - storage: createJSONStorage(() => - resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined), - ), - partialize: (state) => ({ - byProjectKey: state.byProjectKey, - projectKeyByThreadKey: state.projectKeyByThreadKey, - }), - migrate: migratePersistedBrowserHistoryState, - merge: mergeBrowserHistoryState, }, - ), -); + }); +}); + +if (typeof window !== "undefined") { + try { + historyChannel = new BroadcastChannel(BROWSER_HISTORY_STORAGE_KEY); + } catch { + // History still persists when the browser cannot send change notifications. + } + if (historyChannel) { + historyChannel.onmessage = () => { + void transactIndexedHistory().then( + ({ history }) => useBrowserHistoryStore.setState({ byProjectKey: history.byProjectKey }), + () => undefined, + ); + }; + } + const hydrate = (history: PersistedBrowserHistory) => { + useBrowserHistoryStore.setState((state) => ({ + byProjectKey: history.byProjectKey, + projectKeyByThreadKey: { + ...migratePersistedThreadProjectKeys(history, history.byProjectKey), + ...state.projectKeyByThreadKey, + }, + })); + }; + void transactIndexedHistory((history) => history).then( + ({ history }) => hydrate(history), + () => hydrate(readLegacyHistory()), + ); + import.meta.hot?.dispose(() => { + historyChannel?.close(); + historyChannel = undefined; + void historyDatabase?.then( + (db) => db.close(), + () => undefined, + ); + }); +} export function mergeBrowserHistoryState( persistedState: unknown, @@ -331,19 +543,16 @@ export function mergeBrowserHistoryState( function migratePersistedThreadProjectKeys( persistedState: unknown, - byProjectKey: Record, + byProjectKey?: Record, ): Record { if (!persistedState || typeof persistedState !== "object") return {}; const raw = (persistedState as { projectKeyByThreadKey?: unknown }).projectKeyByThreadKey; if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; - return Object.fromEntries( - Object.entries(raw as Record) - .filter( - (entry): entry is [string, string] => - typeof entry[1] === "string" && entry[1] in byProjectKey, - ) - .slice(-100), + const entries = Object.entries(raw as Record).filter( + (entry): entry is [string, string] => + typeof entry[1] === "string" && (!byProjectKey || Object.hasOwn(byProjectKey, entry[1])), ); + return Object.fromEntries(entries.slice(-MAX_PERSISTED_THREAD_MAPPINGS)); } /** @@ -435,24 +644,14 @@ function recordPreviewTitles( ): void { const state = useBrowserHistoryStore.getState(); const projectKey = state.projectKeyByThreadKey[scopedThreadKey(ref)]; - if (!projectKey || !state.byProjectKey[projectKey]?.length) return; + if (!projectKey) return; const connection = readPreparedConnection(ref.environmentId); const environmentHostname = connection ? new URL(connection.httpBaseUrl).hostname : null; const titleKey = (url: string) => { const normalized = normalizeHistoryUrl(url); return normalized ? titleLookupKey(normalized, environmentHostname) : null; }; - const titled = new Set( - "urls" in only - ? state.byProjectKey[projectKey]?.flatMap((entry) => - entry.title ? [titleLookupKey(entry.url, environmentHostname)] : [], - ) - : [], - ); - const visitKeys = - "urls" in only - ? new Set(only.urls.map(titleKey).filter((key) => key !== null && !titled.has(key))) - : null; + const visitKeys = "urls" in only ? new Set(only.urls.map(titleKey)) : null; // Resizes and list reconciles replace a session without loading a new page. const settledAgain = (session: PreviewSessionSnapshot, previous?: PreviewSessionSnapshot) => previous?.navStatus._tag === "Success" && @@ -463,15 +662,20 @@ function recordPreviewTitles( "changedSince" in only ? !settledAgain(session, only.changedSince[session.tabId]) : (visitKeys?.has(titleKey(url)) ?? false); - // Tabs can share a URL; applying oldest first lets the newest settle win. + // A fill uses the newest eligible title first because it only sets an untitled entry. const sessions = Object.values(preview.sessions).toSorted((a, b) => - a.updatedAt.localeCompare(b.updatedAt), + "urls" in only + ? b.updatedAt.localeCompare(a.updatedAt) + : a.updatedAt.localeCompare(b.updatedAt), ); for (const session of sessions) { const status = session.navStatus; if (session.profileId === INCOGNITO_BROWSER_PROFILE_ID) continue; if (status._tag !== "Success" || !status.title || !include(session, status.url)) continue; - state.setTitleForUrl(projectKey, status.url, status.title, environmentHostname); + state.setTitleForUrl(projectKey, status.url, status.title, { + environmentHostname, + onlyIfUntitled: "urls" in only, + }); } } @@ -555,5 +759,4 @@ export function resetBrowserHistoryForTests(): void { projectKeyByThreadKey: {}, pendingVisitsByThreadKey: {}, }); - useBrowserHistoryStore.persist.clearStorage(); } diff --git a/apps/web/src/bundledDev.test.ts b/apps/web/src/bundledDev.test.ts index 770b26e0a686b..5517910d754db 100644 --- a/apps/web/src/bundledDev.test.ts +++ b/apps/web/src/bundledDev.test.ts @@ -26,7 +26,12 @@ it("initializes React refresh before a shared UI chunk runs in bundled dev", asy try { await NodeFSP.mkdir(NodePath.join(root, "src/lib"), { recursive: true }); await NodeFSP.writeFile(NodePath.join(root, "package.json"), '{"type":"module"}'); - for (const file of ["index.html", "src/bootstrap.ts", "src/lib/bootError.ts"]) { + for (const file of [ + "index.html", + "src/bootstrap.ts", + "src/lib/bootError.ts", + "src/lib/chunkReloadGuard.ts", + ]) { await NodeFSP.copyFile(new URL(`../${file}`, import.meta.url), NodePath.join(root, file)); } await NodeFSP.writeFile( @@ -94,6 +99,7 @@ export const startup = Promise.resolve().then(() => globalThis.onStarted(Shared( `import assert from "node:assert/strict"; const started = Promise.withResolvers(); globalThis.window = globalThis; +globalThis.addEventListener = () => {}; globalThis.document = { createElement: () => ({ relList: { supports: () => true } }), getElementById: () => null, diff --git a/apps/web/src/components/BackgroundThreadAnnouncer.tsx b/apps/web/src/components/BackgroundThreadAnnouncer.tsx index 3176c8132eed9..649898cf2e5a5 100644 --- a/apps/web/src/components/BackgroundThreadAnnouncer.tsx +++ b/apps/web/src/components/BackgroundThreadAnnouncer.tsx @@ -14,6 +14,7 @@ import { type BackgroundThreadSnapshot, nextBackgroundThreadAnnouncement, resolveBackgroundThreadRequest, + resolveBackgroundThreadRunStatus, } from "./backgroundThreadAnnouncement"; const backgroundThreadLiveRegion = createLiveRegion(); @@ -51,7 +52,7 @@ export function startBackgroundThreadAnnouncements( title: thread.title, ...resolveBackgroundThreadRequest(thread), runId: thread.latestRun?.runId ?? null, - runStatus: thread.latestRun?.status ?? null, + runStatus: resolveBackgroundThreadRunStatus(thread), activeRunId: thread.runtime?.activeRunId ?? null, snoozed: effectiveSnoozed(thread, { now }), }); diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index bb6f178ff55d7..4bf062b27d93f 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -101,6 +101,12 @@ interface BranchToolbarBranchSelectorProps { const WORKTREE_CHANGE_BLOCKED_MESSAGE = msg("Stop the current turn to switch worktrees."); +// Picker checkouts by environment and checkout: null while in flight, then the branch it landed +// on. Shared because a draft thread mounts two selectors on one checkout, and the switch's own +// settle reloads refs for both. +const pickerCheckouts = new Map(); +const pickerCheckoutKey = (environmentId: string, cwd: string) => `${environmentId}\u0000${cwd}`; + export function BranchToolbarBranchSelector({ forceNewWorktree = false, ref, @@ -505,6 +511,8 @@ export function BranchToolbarBranchSelector({ runBranchAction(async () => { const previousBranch = resolvedActiveBranch; setOptimisticBranch(selectedBranchName); + const checkoutKey = pickerCheckoutKey(environmentId, selectionTarget.checkoutCwd); + pickerCheckouts.set(checkoutKey, null); const checkoutResult = await switchRef({ environmentId, input: { @@ -516,6 +524,7 @@ export function BranchToolbarBranchSelector({ const nextBranchName = refName.isRemote ? (checkoutResult.value.refName ?? selectedBranchName) : selectedBranchName; + pickerCheckouts.set(checkoutKey, nextBranchName); const movesCheckout = selectionTarget.checkoutCwd !== branchCwd; let hold: BranchHold | null = null; const applied = setThreadBranch( @@ -549,6 +558,7 @@ export function BranchToolbarBranchSelector({ setOptimisticBranch(applied ? nextBranchName : previousBranch); return; } + pickerCheckouts.delete(checkoutKey); setOptimisticBranch(previousBranch); if (!isAtomCommandInterrupted(checkoutResult)) { toastManager.add( @@ -574,6 +584,8 @@ export function BranchToolbarBranchSelector({ runBranchAction(async () => { const previousBranch = resolvedActiveBranch; setOptimisticBranch(name); + const checkoutKey = pickerCheckoutKey(environmentId, branchCwd); + pickerCheckouts.set(checkoutKey, null); const createBranchResult = await createRefMutation({ environmentId, input: { @@ -584,6 +596,7 @@ export function BranchToolbarBranchSelector({ }); if (createBranchResult._tag === "Success") { const nextBranchName = createBranchResult.value.refName; + pickerCheckouts.set(checkoutKey, nextBranchName); const applied = setThreadBranch(nextBranchName, activeWorktreePath); if (applied) { setBranchHold({ @@ -595,6 +608,7 @@ export function BranchToolbarBranchSelector({ setOptimisticBranch(applied ? nextBranchName : previousBranch); return; } + pickerCheckouts.delete(checkoutKey); setOptimisticBranch(previousBranch); if (!isAtomCommandInterrupted(createBranchResult)) { toastManager.add( @@ -617,7 +631,7 @@ export function BranchToolbarBranchSelector({ if (branchCwd === null) return; void refreshLocalStatusForPicker({ environmentId, - input: { cwd: branchCwd, localOnly: true }, + input: { cwd: branchCwd }, }); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refs listed while the project was cloning are empty; reload them past the server's snapshot when the clone finishes @@ -627,7 +641,15 @@ export function BranchToolbarBranchSelector({ // A checkout made outside T3 Code, such as a clone finishing, leaves refs listed before it. const statusBranch = branchStatusQuery.data?.refName ?? null; const refreshRefsMissingStatusBranch = useEffectEvent((branch: string | null) => { - if (isInitialBranchesLoadPending || branch === null) return; + if (branch === null || branchCwd === null) return; + // Kept until the checkout reports another branch, so every selector on it skips the refresh. + const checkoutKey = pickerCheckoutKey(environmentId, branchCwd); + if (pickerCheckouts.has(checkoutKey)) { + const pickerBranch = pickerCheckouts.get(checkoutKey); + if (pickerBranch === null || pickerBranch === branch) return; + pickerCheckouts.delete(checkoutKey); + } + if (isInitialBranchesLoadPending) return; if (branchByName.get(branch)?.current !== true) refreshStaleRefs(); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reloads refs from the server once per branch live status reports that they do not list as checked out @@ -663,7 +685,7 @@ export function BranchToolbarBranchSelector({ if (open && !isBranchMenuOpen && branchCwd !== null) { void refreshLocalStatusForPicker({ environmentId, - input: { cwd: branchCwd, localOnly: true }, + input: { cwd: branchCwd }, }); } if (!open) { diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index 0586a724b0c56..faca71b4a101f 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -2,7 +2,6 @@ import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/asset import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { type ReactElement } from "react"; -import remarkGfm from "remark-gfm"; import { describe, expect, it, vi } from "vite-plus/test"; import { commands, page, userEvent } from "vite-plus/test/browser"; @@ -15,11 +14,8 @@ import { selectActiveRightPanelSurface, useRightPanelStore, } from "../rightPanelStore"; -import { - CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -} from "@t3tools/shared/markdownPipeline"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import type { MarkdownExtensions } from "../markdown/wordsHast"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { HostImageUrlContext } from "./chat/hostImageUrl"; import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting"; @@ -28,14 +24,14 @@ const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({ filesystemMetadata: vi.fn(), })); const parsedSources = vi.hoisted(() => [] as string[]); -vi.mock(import("mdast-util-from-markdown"), async (original) => { +vi.mock(import("../markdown/wordsHast"), async (original) => { const actual = await original(); return { ...actual, - fromMarkdown: ((source: string, ...rest: never[]) => { - parsedSources.push(String(source)); - return (actual.fromMarkdown as (...args: unknown[]) => unknown)(source, ...rest); - }) as typeof actual.fromMarkdown, + wordsHast: (source, options) => { + parsedSources.push(source); + return actual.wordsHast(source, options); + }, }; }); @@ -188,7 +184,7 @@ function buttonsLabelled(container: HTMLElement, label: string) { ); } -const SOURCE_NUMBER_PLUGINS = [remarkEnableOrderedListNumbers]; +const USER_MESSAGE = { userMessage: true }; it("keeps decimal markers in nested user lists while documents keep their counter styles", async () => { setup(); @@ -201,7 +197,7 @@ it("keeps decimal markers in nested user lists while documents keep their counte cwd={undefined} text={text} className="user-message-markdown" - extraRemarkPlugins={SOURCE_NUMBER_PLUGINS} + extensions={USER_MESSAGE} />
@@ -312,36 +308,24 @@ it("reuses the parse of a streaming reply's finished blocks when it remounts", a expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1); }); -it("reuses the parse of a remounted message that has stable extra plugins", async () => { +it("reuses the parse of a remounted message that has stable extensions", async () => { setup(); - const parsed = vi.fn(); - const countingPlugins = [() => () => void parsed()]; - const message = ( - - ); + const extensions = { userMessage: true }; + const message = ; { await using first = await render( - , + , ); await first.rerender(message); } await using screen = await render(message); await expect.element(screen.getByText("Cached text")).toBeVisible(); - expect(parsed).toHaveBeenCalledTimes(1); - const changed = vi.fn(); + const parses = () => parsedSources.filter((source) => source === "Cached text").length; + expect(parses()).toBe(1); await screen.rerender( - () => void changed()]} - />, + , ); - expect(changed).toHaveBeenCalledTimes(1); + expect(parses()).toBe(2); }); it("highlights a code block's own source when an earlier block of the same length was cached", async () => { @@ -399,6 +383,45 @@ describe("ChatMarkdown external link labels", () => { }); }); +describe("ChatMarkdown link tooltips", () => { + it("shows each link's address on one shared tooltip as the pointer moves between links", async () => { + setup(); + await using screen = await render( + , + ); + await userEvent.hover(screen.getByRole("link", { name: /First/ })); + await expect.element(page.getByText("https://example.com/a")).toBeVisible(); + await userEvent.hover(screen.getByRole("link", { name: /Second/ })); + await expect.element(page.getByText("https://example.org/b")).toBeVisible(); + expect(document.querySelectorAll('[data-slot="tooltip-popup"]')).toHaveLength(1); + }); +}); + +describe("ChatMarkdown details", () => { + it("opens collapsed details by click, and by keyboard without losing focus", async () => { + setup(); + await using screen = await render( + First\n\nHidden one\n\n\n\n
Second\n\nHidden two\n\n
" + } + />, + ); + await userEvent.click(screen.getByRole("button", { name: "First" })); + await expect.element(screen.getByText("Hidden one")).toBeVisible(); + await userEvent.tab(); + const second = screen.getByRole("button", { name: "Second" }); + await expect.element(second).toHaveFocus(); + await userEvent.keyboard("{Enter}"); + await expect.element(screen.getByText("Hidden two")).toBeVisible(); + await expect.element(screen.getByRole("button", { name: "Second" })).toHaveFocus(); + }); +}); + describe("ChatMarkdown streaming", () => { it("runs only a complete single-line shell block after a click", async () => { setup(); @@ -802,12 +825,12 @@ describe("ChatMarkdown copy", () => { "copies and selects user lines the same whether their typed indentation shows: $text", async (copy) => { setup(); - const copied = async (extraRemarkPlugins: typeof CHAT_USER_MARKDOWN_REMARK_PLUGINS) => { + const copied = async (extensions: MarkdownExtensions) => { await using screen = await renderText(copy.text, { className: "user-message-markdown", lineBreaks: true, parseRawHtml: false, - extraRemarkPlugins, + extensions, }); const range = document.createRange(); range.selectNodeContents(screen.container); @@ -824,9 +847,9 @@ describe("ChatMarkdown copy", () => { // A drag or anything else that reads the selection gets its text, not the copy payload. return { payload: chatMarkdownClipboardPayload(selection), selected: selection.toString() }; }; - const shown = await copied(CHAT_USER_MARKDOWN_REMARK_PLUGINS); + const shown = await copied({ userMessage: true, leadingWhitespace: true }); // The user pipeline as it was before typed indentation was shown. - expect(shown).toEqual(await copied([[remarkGfm, { singleTilde: false }]])); + expect(shown).toEqual(await copied({ userMessage: true })); }, ); @@ -885,7 +908,7 @@ describe("ChatMarkdown copy", () => { setup(); await using screen = await renderText( source, - userMessage ? { extraRemarkPlugins: SOURCE_NUMBER_PLUGINS } : {}, + userMessage ? { extensions: USER_MESSAGE } : {}, ); const itemText = (shown: string) => [...screen.container.querySelectorAll("li")] diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 8c0d14520871d..979d1858cafc1 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -13,7 +13,7 @@ import { extractMarkdownLinkHrefs, inlineCodeFilePathCandidate, } from "@t3tools/shared/markdownLinks"; -import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskList"; +import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskEdits"; import { isHostPath, resolveWorkspaceFilePath } from "@t3tools/shared/path"; import { usePullRequestLinking } from "~/hooks/usePullRequestLinking"; import { @@ -21,14 +21,7 @@ import { AuthOrchestrationOperateScope, SOURCE_CONTROL_MEDIA_ASSET, } from "@t3tools/contracts"; -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - CHAT_MARKDOWN_REHYPE_PLUGINS, - chatMarkdownImageSource, - decodeMarkdownLinkEscapes, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; +import { chatMarkdownImageSource } from "@t3tools/shared/markdownHast"; import { useAtomValue } from "@effect/atom-react"; import { COMPOSER_CONTEXT_CLIPBOARD_MIME, @@ -94,27 +87,17 @@ import React, { useState, type ReactNode, } from "react"; -import type { - Components, - ExtraProps as ReactMarkdownExtraProps, - Options as ReactMarkdownOptions, -} from "react-markdown"; -import { createIncrementalMarkdownPlugin } from "../markdown-incremental"; -import type { Pluggable, PluggableList } from "unified"; -import { defaultUrlTransform } from "react-markdown"; import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations"; import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences"; import { parseThreadLinkHref } from "@t3tools/shared/threadLinks"; import { AssistantCitationEmbed } from "./chat/AssistantCitationChip"; import { MarkdownThreadLink } from "./chat/MarkdownThreadLink"; -import { mathKind } from "@t3tools/shared/markdownMath"; -import remarkMath from "remark-math"; +import { artifactTemplateFromHastProperties } from "@t3tools/shared/codexArtifactTemplates"; import { - artifactTemplateFromHastProperties, + decodeMarkdownLinkEscapes, renderCodexInlineDirectivesAsMarkdown, -} from "@t3tools/shared/codexMarkdownDirectives"; +} from "../markdown/markdownText"; import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText"; -import { MarkdownMath } from "./chat/MarkdownMath"; import { resolveMarkdownMediaPreview, type ExpandedImagePreview, @@ -131,7 +114,7 @@ import { resolveExternalWebLinkHost, showExternalLinkContextMenu, } from "./chat/externalLinkContextMenu"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; +import { SharedTooltipProvider, SharedTooltipTrigger } from "./ui/shared-tooltip"; import { Button } from "./ui/button"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { recordVisitForThread } from "../browserHistoryStore"; @@ -214,6 +197,15 @@ import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview"; import { IssueLinkPreview, IssueLinkPreviewFallback } from "./issue/IssueLinkPreview"; import { MarkdownCodeBlock, SuspenseShikiCodeBlock } from "./chat/MarkdownCodeBlock"; import { createMarkdownRenderer } from "./chat/markdownRenderer"; +import type { MarkdownExtensions, WordsHastOptions } from "../markdown/wordsHast"; +import { + type MarkdownIslandOptions, + renderHastWithIslands, + withProperties, +} from "./chat/markdownIslands"; +import type { Element as HastElement } from "hast"; +import { matchInlineSkills } from "@t3tools/shared/inlineSkills"; +import { collectComposerModelMentions } from "@t3tools/client-runtime/composer-model-mentions"; import { splitMarkdownBlocks } from "./chat/markdownStreamBlocks"; import { MarkdownMermaidCodeBlock } from "./chat/MarkdownMermaidCodeBlock"; import { MarkdownTable } from "./chat/MarkdownTable"; @@ -230,9 +222,7 @@ import { import { MarkdownExternalLinkContent } from "./chat/MarkdownExternalLink"; import { MarkdownFileLink } from "./chat/MarkdownFileLink"; import { canUseMarkdownFileShellActions } from "./chat/MarkdownFileLink.logic"; -import { rehypeChipPunctuation } from "./chat/markdownChipPunctuation"; -import { handleMarkdownFragmentClick, rehypeHeadingIds } from "./chat/markdownFragments"; -import { rehypeTextDirection } from "./chat/markdownTextDirection"; +import { handleMarkdownFragmentClick } from "./chat/markdownFragments"; import { hastHasText, hastPlainTextDeep, plainHastText } from "./chat/markdownHast.logic"; import { extractCodeBlock, @@ -268,8 +258,8 @@ interface ChatMarkdownProps { imageBaseDir?: string | undefined; workspaceMutationId?: string | null | undefined; onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined; - /** Keep one list per configuration (a module constant): it keys the shared parse cache. */ - extraRemarkPlugins?: NonNullable; + /** Keep one object per configuration (a module constant): it keys the shared parse cache. */ + extensions?: MarkdownExtensions | undefined; renderContextReference?: ((reference: ChatMarkdownContextReference) => ReactNode) | undefined; /** Loads media a source control host keeps behind a credential through the server, which holds `cwd`'s; without it a private repository's uploads load unauthenticated and 404. */ @@ -289,7 +279,7 @@ export interface ChatMarkdownContextReference { } const EMPTY_MARKDOWN_SKILLS: ReadonlyArray = []; -const EMPTY_REMARK_PLUGINS: NonNullable = []; +const NO_EXTENSIONS: MarkdownExtensions = {}; const ARTIFACT_TEMPLATE_ICON_BY_KIND = { document: FileTextIcon, @@ -423,19 +413,29 @@ function normalizeMarkdownLinkHrefKey(href: string): string { : rewrittenHref; } -// Heading ids are added after sanitizing, which would prefix them a second time. -const CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS = [ - ...CHAT_MARKDOWN_REHYPE_PLUGINS, - rehypeHeadingIds, - rehypeTextDirection, - rehypeChipPunctuation, -] satisfies NonNullable; +/** A component per element, with the hast node it renders, as react-markdown typed them. */ +type MarkdownComponents = { + [Tag in keyof React.JSX.IntrinsicElements]?: React.ComponentType< + React.JSX.IntrinsicElements[Tag] & { node?: HastElement | undefined } + >; +}; -const CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS = [ - rehypeHeadingIds, - rehypeTextDirection, - rehypeChipPunctuation, -] satisfies NonNullable; +// react-markdown's defaultUrlTransform: relative URLs, and absolute ones with a safe protocol. +const SAFE_PROTOCOL = /^(?:https?|ircs?|mailto|xmpp)$/i; +function safeUrl(value: string): string { + const colon = value.indexOf(":"); + const before = (character: string) => { + const at = value.indexOf(character); + return at !== -1 && colon > at; + }; + return colon === -1 || + before("/") || + before("?") || + before("#") || + SAFE_PROTOCOL.test(value.slice(0, colon)) + ? value + : ""; +} function markdownUrlTransform(href: string) { if (parseAssistantCitationHref(href)) return href; @@ -443,7 +443,7 @@ function markdownUrlTransform(href: string) { if (parseThreadLinkHref(href)) return href; if (isWindowsDrivePathHref(href)) return href; if (isLocalEditorFileHref(href)) return href; - return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href); + return rewriteMarkdownFileUriHref(href) ?? safeUrl(href); } const NO_MARKDOWN_EDITORS: ReadonlyArray = []; @@ -486,11 +486,16 @@ const markdownServerConfigFieldsAtom = Atom.family((environmentId: EnvironmentId }).pipe(Atom.withLabel("markdown-server-config-fields")), ); -function fileLinkSourcesKey( +interface BlockFileLinkSources { + readonly hrefs: ReadonlyArray; + readonly spans: ReadonlyArray; +} + +function blockFileLinkSources( text: string, cwd: string | undefined, imageBaseDir: string | undefined, -): string { +): BlockFileLinkSources { const hrefs = extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(text)) .filter((href) => !parseComposerContextHref(href)) .map(decodeMarkdownLinkEscapes) @@ -499,7 +504,47 @@ function fileLinkSourcesKey( const spans = extractInlineCodeSpans(text).filter((span) => resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd), ); - return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); + return { hrefs, spans }; +} + +// Links and code spans never cross blocks: a streamed reply rescans only its open last block. +const MAX_CACHED_BLOCK_CHARS = 2_000_000; +const finishedBlockFileLinkSources = new Map(); +let cachedBlockChars = 0; + +function fileLinkSourcesKey( + text: string, + cwd: string | undefined, + imageBaseDir: string | undefined, + streamingBlocks: ReadonlyArray | null, +): string { + if (!streamingBlocks) { + const { hrefs, spans } = blockFileLinkSources(text, cwd, imageBaseDir); + return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); + } + const config = `${cwd ?? ""}\u0000${imageBaseDir ?? ""}\u0000`; + const hrefs = new Set(); + const spans = new Set(); + const last = streamingBlocks.length - 1; + for (const [index, block] of streamingBlocks.entries()) { + // The last block still grows; caching each of its prefixes would only fill the cache. + const key = config + block; + let sources = index === last ? undefined : finishedBlockFileLinkSources.get(key); + if (!sources) { + sources = blockFileLinkSources(block, cwd, imageBaseDir); + if (index !== last) { + if (cachedBlockChars + key.length > MAX_CACHED_BLOCK_CHARS) { + finishedBlockFileLinkSources.clear(); + cachedBlockChars = 0; + } + finishedBlockFileLinkSources.set(key, sources); + cachedBlockChars += key.length; + } + } + for (const href of sources.hrefs) hrefs.add(href); + for (const span of sources.spans) spans.add(span); + } + return JSON.stringify([[...hrefs], [...spans]]); } function resolveFileLinkSources( @@ -525,27 +570,30 @@ function resolveFileLinkSources( return { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath }; } -function useChatMarkdownState({ - text, - inline = false, - cwd, - agentDirectories, - threadRef, - pullRequestPanelRef, - environmentId: explicitEnvironmentId, - onTaskListChange, - isStreaming = false, - skills = EMPTY_MARKDOWN_SKILLS, - onUseArtifactTemplate, - onRunShellCommand, - imageBaseDir, - workspaceMutationId, - onImageExpand, - renderContextReference, - headingLevelOffset = 0, - sourceControlMedia = false, - sourceControlMediaRepository, -}: ChatMarkdownProps) { +function useChatMarkdownState( + { + text, + inline = false, + cwd, + agentDirectories, + threadRef, + pullRequestPanelRef, + environmentId: explicitEnvironmentId, + onTaskListChange, + isStreaming = false, + skills = EMPTY_MARKDOWN_SKILLS, + onUseArtifactTemplate, + onRunShellCommand, + imageBaseDir, + workspaceMutationId, + onImageExpand, + renderContextReference, + headingLevelOffset = 0, + sourceControlMedia = false, + sourceControlMediaRepository, + }: ChatMarkdownProps, + streamingBlocks: ReadonlyArray | null, +) { const gt = useGT(); const messages = useMessages(); const resolvedTheme = useRenderedAppearance(); @@ -743,7 +791,7 @@ function useChatMarkdownState({ // Keyed by the file links found, not the text, so streamed text that adds none keeps the // renderer context, and every block reading it, unchanged. // A template literal marks the key as a string, so the compiler memoizes the maps on its value. - const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir)}`; + const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null)}`; const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); const resolveThreadPullRequest = ( @@ -1087,7 +1135,7 @@ function markdownHeadingRenderer(level: 1 | 2 | 3 | 4 | 5 | 6) { return function MarkdownHeading({ node: _node, ...props - }: ComponentProps & ReactMarkdownExtraProps) { + }: ComponentProps & { node?: HastElement | undefined }) { const { headingLevelOffset } = use(ChatMarkdownRendererContext); return ( ; } - return ( - - - {href} - - ); + return ; } const label = nodeToPlainText(children); @@ -1533,18 +1576,9 @@ const CHAT_MARKDOWN_COMPONENTS = { ); }, code: function MarkdownCode({ node, children, className, ...props }) { - const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip, mathEnabled, inline } = - use(ChatMarkdownRendererContext); - const math = mathEnabled ? mathKind(className) : null; - if (math) { - return ( - - ); - } + const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip } = use( + ChatMarkdownRendererContext, + ); if (node?.properties?.dataInlineCode != null) { const codeText = nodeToPlainText(children); const fileLinkMeta = @@ -1769,15 +1803,9 @@ const CHAT_MARKDOWN_COMPONENTS = { }, pre: function MarkdownPre({ node, children, ...props }) { const gt = useGT(); - const { - resolvedTheme, - diffThemeName, - expandMedia, - isStreaming, - onRunShellCommand, - inline, - mathEnabled, - } = use(ChatMarkdownRendererContext); + const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand } = use( + ChatMarkdownRendererContext, + ); const text = use(ChatMarkdownTextContext); const codeBlock = extractCodeBlock(children); if (!codeBlock) { @@ -1785,15 +1813,6 @@ const CHAT_MARKDOWN_COMPONENTS = { } const language = extractFenceLanguage(codeBlock.className); - if ( - mathEnabled && - language === "math" && - (!isStreaming || - mathKind(codeBlock.className) === "display" || - isClosedCodeFence(node, text, codeBlock.code)) - ) { - return ; - } const fenceTitle = extractFenceTitle(extractPreCodeMeta(node)); const highlightedCode = ( ); }, -} satisfies Components; - -const REMARK_MATH: Pluggable = [remarkMath, { singleDollarTextMath: true }]; -// Shared lists, so every message with the same options shares a processor and its cache. -const CHAT_MARKDOWN_REMARK_PLUGIN_SETS = { - plain: CHAT_MARKDOWN_REMARK_PLUGINS, - breaks: CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - math: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS], - mathBreaks: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS], -} satisfies Record; - -const combinedPlugins = new WeakMap>(); +} satisfies MarkdownComponents; -// One combined list per pair, so a stable extra list shares a renderer and its parse cache. -const INSIGHT_REMARK_PLUGINS: PluggableList = [remarkAssistantInsights]; +const markdownOptions = new WeakMap>(); -function withExtraPlugins(shared: PluggableList, extra: PluggableList): PluggableList { - if (extra.length === 0) return shared; - let byShared = combinedPlugins.get(extra); - if (!byShared) combinedPlugins.set(extra, (byShared = new WeakMap())); - let combined = byShared.get(shared); - if (!combined) byShared.set(shared, (combined = [...shared, ...extra])); - return combined; +/** One options object per configuration, so equal messages share a renderer and its cache. */ +function wordsOptions( + extensions: MarkdownExtensions, + flags: Omit, +): WordsHastOptions { + let byFlags = markdownOptions.get(extensions); + if (!byFlags) markdownOptions.set(extensions, (byFlags = new Map())); + const key = `${+flags.math}${+flags.breaks}${+flags.escapeHtml}${+flags.insights}`; + let options = byFlags.get(key); + if (!options) byFlags.set(key, (options = { ...flags, extensions })); + return options; } const markdownRenderers = new WeakMap< - PluggableList, - WeakMap> + WordsHastOptions, + ReturnType >(); -function markdownRenderer(remarkPlugins: PluggableList, rehypePlugins: PluggableList) { - let byRehype = markdownRenderers.get(remarkPlugins); - if (!byRehype) markdownRenderers.set(remarkPlugins, (byRehype = new WeakMap())); - let renderer = byRehype.get(rehypePlugins); +function markdownRenderer(markdown: WordsHastOptions) { + let renderer = markdownRenderers.get(markdown); if (!renderer) { renderer = createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, + markdown, components: CHAT_MARKDOWN_COMPONENTS, urlTransform: markdownUrlTransform, }); - byRehype.set(rehypePlugins, renderer); + markdownRenderers.set(markdown, renderer); } return renderer; } +type ChatMarkdownComponentState = ReturnType["componentState"]; + +function hastClassName(node: HastElement): string | undefined { + const { className } = node.properties; + return Array.isArray(className) ? className.join(" ") : (className as string | undefined); +} + +// Paragraphs and list items turn skill and model mentions in their text into chips, except in +// code and links, as SkillInlineText does. +function hastTextHasChip(node: HastElement, skills: ReadonlyArray): boolean { + return node.children.some((child) => + child.type === "text" + ? (skills.length > 0 && !matchInlineSkills(child.value, skills).next().done) || + collectComposerModelMentions(child.value).length > 0 + : child.type === "element" && + child.tagName !== "code" && + child.tagName !== "a" && + hastTextHasChip(child, skills), + ); +} + +const HEADING_LEVELS: Record = { h1: 1, h2: 2, h3: 3, h4: 4, h5: 5, h6: 6 }; + +const markdownIslandOptionsByState = new WeakMap< + ChatMarkdownComponentState, + MarkdownIslandOptions +>(); + +/** Which elements need CHAT_MARKDOWN_COMPONENTS, and what the others' components add. */ +function markdownIslandOptions(state: ChatMarkdownComponentState): MarkdownIslandOptions { + const cached = markdownIslandOptionsByState.get(state); + if (cached) return cached; + const { + cwd, + headingLevelOffset, + imageBaseDir, + inlineCodeFileLinkMetaByText, + onTaskListChange, + skills, + } = state; + const options: MarkdownIslandOptions = { + components: CHAT_MARKDOWN_COMPONENTS, + variant: String(headingLevelOffset), + isIsland: (node) => { + switch (node.tagName) { + case "a": + case "img": + case "pre": + case "details": + case "table": + return true; + case "blockquote": + return GITHUB_ALERT_PRESENTATIONS[String(node.properties.dataAlert ?? "")] !== undefined; + case "div": + return artifactTemplateFromHastProperties(node.properties) !== null; + case "input": + return node.properties.type === "checkbox" && onTaskListChange !== undefined; + case "code": { + if (node.properties.dataInlineCode == null) return false; + const codeText = hastPlainTextDeep(node); + return ( + (inlineCodeFileLinkMetaByText.get(codeText.trim()) ?? + resolveInlineCodeFileLinkMeta(codeText, cwd, imageBaseDir ?? cwd)) != null + ); + } + case "p": + case "li": + return hastTextHasChip(node, skills); + default: + return false; + } + }, + staticElement: (node) => { + const level = HEADING_LEVELS[node.tagName]; + if (level !== undefined) { + return headingLevelOffset > 0 + ? withProperties(node, { ariaLevel: Math.min(level + headingLevelOffset, 6) }) + : node; + } + switch (node.tagName) { + case "ol": { + const itemValues = node.children.flatMap((child) => + child.type === "element" && child.tagName === "li" ? [child.properties.value] : [], + ); + const gutter = orderedListGutterStyle(itemValues, node.properties.start); + if (!gutter) return node; + const authored = typeof node.properties.style === "string" ? node.properties.style : ""; + return withProperties(node, { + style: `${authored}${authored ? ";" : ""}--list-gutter:${gutter["--list-gutter"]}`, + }); + } + case "li": + return hastClassName(node)?.includes("task-list-item") + ? withProperties(node, { dataListItemOffset: node.position?.start.offset }) + : node; + case "input": + return node.properties.type === "checkbox" + ? withProperties(node, { readOnly: true }) + : node; + default: + return node; + } + }, + }; + markdownIslandOptionsByState.set(state, options); + return options; +} + const MarkdownSource = memo(function MarkdownSource({ text, - remarkPlugins, - rehypePlugins, - shared, + markdown, cache, }: { text: string; - remarkPlugins: PluggableList; - rehypePlugins: PluggableList; - /** The plugins are one of the shared sets. */ - shared: boolean; + markdown: WordsHastOptions; /** The text will not change again; streamed text would only fill the cache with prefixes. */ cache: boolean; }) { - // Per-instance plugins, such as the incremental parser, set up their state on every render. - const render = shared - ? markdownRenderer(remarkPlugins, rehypePlugins) - : createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, - components: CHAT_MARKDOWN_COMPONENTS, - urlTransform: markdownUrlTransform, - }); - const element = render(text); + const render = markdownRenderer(markdown); + const entry = render.parse(text); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Caching during render would make React Compiler rebuild the element when `cache` flips. useEffect(() => { - if (shared && cache) render.remember(text, element); - }, [render, text, element, shared, cache]); - return {element}; + if (cache) render.remember(text, entry); + }, [render, text, entry, cache]); + const islandState = use(ChatMarkdownRendererContext); + return ( + + {islandState + ? renderHastWithIslands(entry.tree, markdownIslandOptions(islandState)) + : render.element(entry)} + + ); }); function ChatMarkdown({ @@ -1935,51 +2045,28 @@ function ChatMarkdown({ inline = false, lineBreaks = false, parseRawHtml = true, - extraRemarkPlugins = EMPTY_REMARK_PLUGINS, + extensions = NO_EXTENSIONS, renderInsights = false, ...props }: ChatMarkdownProps) { - const { componentState, handleCopy, markdownRef, localMediaPreview, closeLocalMediaPreview } = - useChatMarkdownState({ text, inline, ...props }); - const hasInsights = renderInsights && text.includes("★ Insight"); - // Streaming re-renders only the last block; offsets for task edits need the whole text. + // Streaming re-renders only the last block; offsets for task edits, and extensions that read + // the whole message, need the whole text. const streamingBlocks = - props.isStreaming === true && - !inline && - extraRemarkPlugins.length === 0 && - !props.onTaskListChange - ? splitMarkdownBlocks(text) + props.isStreaming === true && !inline && extensions === NO_EXTENSIONS && !props.onTaskListChange + ? (splitMarkdownBlocks(text) ?? [text]) : null; - const incrementalParsing = - props.isStreaming === true && - !hasInsights && - streamingBlocks === null && - extraRemarkPlugins.length === 0 && - /(?:^|\n) {0,3}(?:`{3}|~{3})/.test(text); + const { componentState, handleCopy, markdownRef, localMediaPreview, closeLocalMediaPreview } = + useChatMarkdownState({ text, inline, ...props }, streamingBlocks); const Root = inline ? "span" : "div"; const bindMarkdownRef = (node: HTMLElement | null) => { markdownRef.current = node; }; - const sharedRemarkPlugins = - CHAT_MARKDOWN_REMARK_PLUGIN_SETS[ - componentState.mathEnabled - ? lineBreaks - ? "mathBreaks" - : "math" - : lineBreaks - ? "breaks" - : "plain" - ]; - // The incremental parser keeps per-instance state, so its output is not shared. - const uncachedPlugins = incrementalParsing; - const remarkPlugins = incrementalParsing - ? [...sharedRemarkPlugins, ...extraRemarkPlugins, createIncrementalMarkdownPlugin()] - : withExtraPlugins( - hasInsights - ? withExtraPlugins(INSIGHT_REMARK_PLUGINS, sharedRemarkPlugins) - : sharedRemarkPlugins, - extraRemarkPlugins, - ); + const markdown = wordsOptions(extensions, { + math: componentState.mathEnabled, + breaks: lineBreaks, + escapeHtml: !parseRawHtml, + insights: renderInsights && text.includes("★ Insight"), + }); const blocks = streamingBlocks ?? [text]; return ( @@ -1995,22 +2082,18 @@ function ChatMarkdown({ onCopy={handleCopy} > - {blocks.map((source, index) => ( - - ))} + + {blocks.map((source, index) => ( + + ))} + {localMediaPreview ? ( diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index ae6628ba6733c..60c3c24ce5c2d 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -17,6 +17,7 @@ import { mergeWithDefaultKeybindings, } from "@t3tools/shared/keybindings"; import type * as Context from "effect/Context"; +import * as Schema from "effect/Schema"; import * as Effect from "effect/Effect"; import { expect, it, vi } from "vite-plus/test"; import { cdp, page, userEvent } from "vite-plus/test/browser"; @@ -89,6 +90,8 @@ function acceptAttachmentUploads(): Disposable { const insertText = (text: string) => cdp().send("Input.insertText", { text }); /** Holds every call to `method` until `release`, then ends it with `end`, until disposed. */ +class LaunchRefused extends Schema.TaggedError()("LaunchRefused", {}) {} + function holdRpc(method: string, end: Effect.Effect) { let release = () => {}; const held = new Promise((resolve) => { @@ -112,6 +115,19 @@ vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (i return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) }; }); +// Null runs the real compression; a test sets it to hold an image in preparation. +const compression = vi.hoisted(() => ({ gate: null as Promise | null })); +vi.mock(import("~/lib/imageCompression"), async (original) => { + const actual = await original(); + return { + ...actual, + prepareImageForAttachment: async (...args) => { + await compression.gate; + return actual.prepareImageForAttachment(...args); + }, + }; +}); + vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ ...(await original()), trackRpcRequestSent: () => {}, @@ -393,7 +409,7 @@ it("a new draft does not load its reserved thread before the server lists it", a expect(threadRequests).toEqual([]); }); -it("an interrupted image-only first send of a new thread says it may not have been sent", async () => { +it("a failed image-only first send of a new thread keeps the new draft", async () => { using _environment = installFakeEnvironment([]); __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, @@ -405,8 +421,11 @@ it("an interrupted image-only first send of a new thread says it may not have be .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { threadId: ThreadId.make("thread-image-only-interrupted"), }); - // A dropped connection interrupts a new thread's launch, which is not resent. - using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt); + // A refusal fails at once; an interrupted launch would wait for a reconnect and be resent. + using launch = holdRpc( + ORCHESTRATION_V2_WS_METHODS.launchThread, + Effect.fail(new LaunchRefused()), + ); const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] })); await router.load(); await using _app = await render(, { @@ -432,12 +451,102 @@ it("an interrupted image-only first send of a new thread says it may not have be await expect.element(editor).toHaveTextContent("next draft"); launch.release(); - await expect.element(page.getByText("Message may not have been sent")).toBeVisible(); + await expect.element(page.getByText("Message not sent")).toBeVisible(); await expect.element(editor).toHaveTextContent("next draft"); // With no text there is nothing to copy. expect(page.getByText("Copy message", { exact: true }).query()).toBeNull(); }); +it.each(["new", "existing"] as const)( + "Enter while an image compresses shows a cancellable banner, cancels on edit or Esc, and still sends after leaving a %s thread", + async (kind) => { + const thread = threadWithHistory(`upload-wait-${kind}`, 1); + const other = threadWithHistory(`upload-wait-other-${kind}`, 1); + using _environment = installFakeEnvironment(kind === "existing" ? [thread, other] : [other], { + acceptCommands: true, + }); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const draftId = DraftId.make(`draft-upload-wait-${kind}`); + if (kind === "new") { + useComposerDraftStore + .getState() + .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { + threadId: thread.id, + }); + } + using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt); + const router = getRouter( + createMemoryHistory({ + initialEntries: [kind === "new" ? `/draft/${draftId}` : `/${ENVIRONMENT_ID}/${thread.id}`], + }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + const compressed = Promise.withResolvers(); + compression.gate = compressed.promise; + using _compression = { [Symbol.dispose]: () => (compression.gate = null) }; + using _uploads = acceptAttachmentUploads(); + const editor = page.getByTestId("composer-editor"); + await expect.element(editor).toBeVisible(); + await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible(); + + await userEvent.click(editor); + const clipboardData = new DataTransfer(); + clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" })); + editor + .element() + .dispatchEvent( + new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }), + ); + + // Enter arms the send and shows the banner plus a disabled spinner button. + await userEvent.keyboard("check image{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + const waitingButton = page.getByRole("button", { name: "Sending when ready", exact: true }); + await expect.element(waitingButton).toBeDisabled(); + await expect.element(waitingButton).toHaveAttribute("aria-busy", "true"); + + // Typing disarms the queued send and keeps the edit. + await userEvent.keyboard(" now"); + await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument(); + await expect.element(editor).toHaveTextContent("check image now"); + + // Enter arms again; Esc cancels cleanly. + await userEvent.keyboard("{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + await userEvent.keyboard("{Escape}"); + await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument(); + + // Enter arms again; leaving the thread still sends once the image is ready. + await userEvent.keyboard("{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` }); + await expect.element(page.getByText(`Answer 0 for upload-wait-other-${kind}.`)).toBeVisible(); + + compressed.resolve(); + await vi.waitFor(() => { + if (kind === "new") { + expect(launch.calls).toHaveLength(1); + } else { + expect(dispatchedCommands()).toContainEqual( + expect.objectContaining({ + type: "message.dispatch", + threadId: thread.id, + attachments: [expect.objectContaining({ type: "image", id: "upload-1" })], + }), + ); + } + }); + launch.release(); + }, +); + it("opens the thread actions menu for an older settled thread the shell leaves out", async () => { const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const }; using _environment = installFakeEnvironment([thread]); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 77c47d668daf4..d17af4f620755 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -59,7 +59,9 @@ import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import type { UsageLimitSourceSnapshots } from "@t3tools/contracts"; import { feedbackBannerItem } from "./chat/ComposerFeedback"; import { freshSessionBannerItem } from "./chat/ComposerFreshSession"; +import { heldComposerSendBannerItem } from "./chat/ComposerHeldSendBanner"; import { armFreshSession, disarmFreshSession, useFreshSessionArmed } from "./chat/freshSessionArms"; +import { cancelHeldComposerSend, useComposerSendHeld } from "./chat/preparingComposerImages"; import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel"; import { useWorktreeSetup } from "./chat/useWorktreeSetup"; import { useChatShortcuts } from "./chat/useChatShortcuts"; @@ -104,10 +106,9 @@ import { } from "@t3tools/client-runtime/state/subagentRuntime"; import { getUserQueuedThreadRuns, - threadSteersDuringCompaction, + threadCanSteer, threadSupportsProviderHandoff, } from "@t3tools/client-runtime/state/thread-workflows"; -import { compactionBlocksSteering } from "@t3tools/client-runtime/state/composer-dispatch"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; import { HandoffRow } from "./chat/V2LifecycleRow"; import { @@ -253,6 +254,7 @@ import { type ComposerFileAttachment, type ComposerImageAttachment, type DraftThreadEnvMode, + composerTargetKey, useComposerDraftStore, DraftId, } from "../composerDraftStore"; @@ -1542,12 +1544,10 @@ export default function ChatView(props: ChatViewProps) { const isCompacting = (isSendBusy || phase === "connecting" || phase === "running") && (compactionRunning || compactCommandIsActive); - const compactionBlocksSteer = compactionBlocksSteering({ + const canSteer = threadCanSteer(serverProjection, { compactCommandIsActive, compactionRunning, - steersDuringCompaction: threadSteersDuringCompaction(serverProjection), - run: serverProjection?.runs.find((run) => run.id === activeRuntime?.activeRunId), - messages: serverProjection?.messages, + activeRunId: activeRuntime?.activeRunId, }); const isWorking = deriveTimelineWorking({ phase, @@ -2658,7 +2658,16 @@ export default function ChatView(props: ChatViewProps) { // While a question or approval owns the composer, its text answers that, not the agent. const freshSessionCommandAvailable = freshSessionAvailable && activePendingApproval === null && pendingUserInputs.length === 0; - const toggleKeepFullHistory = () => setKeepFullHistory(routeThreadKey, !keepFullHistory); + const composerDraftTargetKey = composerTargetKey(composerDraftTarget); + const composerSendHeld = useComposerSendHeld(composerDraftTargetKey); + const cancelHeldSendStable = useStableCallback(() => { + cancelHeldComposerSend(composerDraftTargetKey); + focusComposerStable(); + }); + const toggleKeepFullHistory = () => { + cancelHeldComposerSend(composerDraftTargetKey); + setKeepFullHistory(routeThreadKey, !keepFullHistory); + }; const toggleKeepFullHistoryStable = useStableCallback(toggleKeepFullHistory); const armFreshSessionStable = useStableCallback(() => armFreshSession(routeThreadKey)); const handleRestoreThreadBranch = () => { @@ -2769,6 +2778,14 @@ export default function ChatView(props: ChatViewProps) { freshSessionPending && activePendingApproval === null ? [freshSessionBannerItem(() => disarmFreshSession(routeThreadKey), messages)] : []; + const heldSendItems = composerSendHeld + ? [ + heldComposerSendBannerItem( + { draftTarget: composerDraftTarget, onCancel: cancelHeldSendStable }, + messages, + ), + ] + : []; if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) { return [ ...feedbackBannerItems, @@ -2778,6 +2795,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...heldSendItems, ...systemComposerBannerItems, ]; } @@ -2789,6 +2807,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...heldSendItems, ...systemComposerBannerItems, branchMismatchBannerItem( { @@ -3054,7 +3073,7 @@ export default function ChatView(props: ChatViewProps) { scrollToEnd, setThreadError, }); - const { onSend } = useComposerSend({ + const { onSend, captureDetachedSend } = useComposerSend({ environmentId, routeThreadKey, currentRouteThreadKeyRef, @@ -3800,7 +3819,7 @@ export default function ChatView(props: ChatViewProps) { isLocalDraftThread && activeProject === null } phase={phase} - canSteer={!compactionBlocksSteer} + canSteer={canSteer} canInterrupt={canInterruptRunningThread} isSendBusy={ (isSendBusy && !sendQueuesBehindSetup) || @@ -3895,6 +3914,7 @@ export default function ChatView(props: ChatViewProps) { onPageScrollRelease={onComposerPageScrollReleaseStable} onCompactContext={onComposerCompactContextStable} onSend={onComposerSendStable} + captureDetachedSend={captureDetachedSend} onResume={onComposerResumeStable} onInterrupt={onInterruptStable} onSelectActivePendingUserInputOption={ diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 3349902aeea05..cc839c6d92c3c 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -2379,7 +2379,7 @@ function OpenCommandPaletteDialog(props: { cloneDirectoryName: pinnedCloneDirectoryName, caseSensitive: !isWindowsPlatform(browseEnvironmentPlatform), }) - : appendBrowsePathSegment(query, name); + : appendBrowsePathSegment(browsePath.directoryPath, name); await browseNavigation.run( () => prefetchBrowsePath(getBrowseDirectoryPath(nextQuery)), () => { @@ -2797,7 +2797,7 @@ function OpenCommandPaletteDialog(props: { void browseTo(completion.name); } else if (completion && !pinnedCloneDirectoryName) { setHighlightedItemValue(null); - setQuery(`${getBrowseDirectoryPath(query)}${completion.name}`); + setQuery(`${browsePath.directoryPath}${completion.name}`); } return; } diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index ca1db10dbdc10..ff5b426c0bf3f 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -68,6 +68,8 @@ function Composer({ importContextFragment, literalText = false, disabled = false, + placeholder = "", + placeholderSuffix, }: { value: string; richTextEnabled: boolean; @@ -77,6 +79,8 @@ function Composer({ importContextFragment?: ComposerPromptEditorProps["importContextFragment"]; literalText?: boolean; disabled?: boolean; + placeholder?: string; + placeholderSuffix?: ComposerPromptEditorProps["placeholderSuffix"]; }) { const [prompt, setPrompt] = useState({ value, cursor: value.length }); return ( @@ -88,7 +92,8 @@ function Composer({ contextRecords={new Map()} skills={skills} disabled={disabled} - placeholder="" + placeholder={placeholder} + placeholderSuffix={placeholderSuffix} onChange={(...args) => { setPrompt({ value: args[0], cursor: args[1] }); onChange?.(...args); @@ -677,6 +682,18 @@ it("reopens a long draft scrolled to its caret without taking focus", async () = expect(caret.bottom).toBeLessThanOrEqual(scroller.getBoundingClientRect().bottom - 48 + 1); }); +it("does not outline the line under a click made with the node-select modifier held", async () => { + await using screen = await mountEditor("ship it"); + const { editor } = screen; + const paragraph = editor.view.dom.querySelector("p")!; + const mod = isMacPlatform(navigator.platform) ? "Meta" : "Control"; + await userEvent.keyboard(`{${mod}>}`); + await userEvent.click(paragraph); + await userEvent.keyboard(`{/${mod}}`); + await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom)); + expect(getComputedStyle(paragraph).outlineStyle).toBe("none"); +}); + describe("Markdown markers around styled text", () => { it.each([ { keys: "{Backspace}", expected: "**** after" }, @@ -1202,3 +1219,25 @@ it.each(["other field", "document body"])( ); }, ); + +it("lets a one-line placeholder's button take clicks and passes the rest to the editor", async () => { + const onClick = vi.fn(); + await using screen = await render( + + Tab + + } + />, + ); + const editor = editorIn(screen.container); + await userEvent.click(editor.view.dom, { position: { x: 12, y: 12 } }); + await vi.waitFor(() => expect(editor.view.hasFocus()).toBe(true)); + await userEvent.click(screen.getByRole("button", { name: "Tab" })); + expect(onClick).toHaveBeenCalledOnce(); +}); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 9b758ee8b6777..402156b001286 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -14,6 +14,7 @@ import { type TiptapEditorHTMLElement, } from "@tiptap/core"; import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react"; +import { Paragraph } from "@tiptap/extension-paragraph"; import StarterKit from "@tiptap/starter-kit"; import { useGT } from "gt-react"; import { newlineInCode, splitBlockKeepMarks } from "@tiptap/pm/commands"; @@ -876,7 +877,10 @@ function createComposerExtensions(richText: boolean) { italic: false, bold: false, strike: false, + paragraph: false, }), + // Ctrl/Cmd+click would node-select and outline the whole line (Wispr Flow holds Ctrl to dictate). + Paragraph.extend({ selectable: false }), ComposerUndoGroupingExtension, ComposerTextDirectionExtension, ComposerMentionExtension, @@ -1920,12 +1924,13 @@ function ComposerPromptEditorTiptapInner(
{ if ( event.key === "Control" || @@ -1970,7 +1975,7 @@ function ComposerPromptEditorTiptapInner( {isEmpty && contextRecords.size === 0 && placeholder ? (
diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index 406e3d79bd57d..2b3e9bfb96c14 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -1,5 +1,13 @@ import type { ResolvedKeybindingsConfig, ScopedThreadRef } from "@t3tools/contracts"; import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { describe, expect, it, vi } from "vite-plus/test"; @@ -122,9 +130,10 @@ async function renderShortcut() { stack.defer(() => { delete window.desktopBridge; }); - stack.use(await render()); + const screen = stack.use(await render()); const environment = stack.move(); return { + router: screen.router!, /** Attaches an element to the document until the test ends. */ append(element: HTMLElement) { document.body.append(element); @@ -148,6 +157,43 @@ function press(target: Element = document.body) { } describe("root reopen shortcut", () => { + it.each([ + { action: "switch routes", goBack: false, expectedPath: "/newer" }, + { action: "leave and return", goBack: true, expectedPath: "/" }, + ])( + "restores both queued views without navigating when you $action during the reopen", + async ({ goBack, expectedPath }) => { + setup(); + const store = useClosedViewStore.getState(); + store.remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } }); + store.remember({ kind: "browser", threadRef: ref, snapshot }); + const result = Promise.withResolvers>(); + state.openPreview.mockReturnValue(result.promise); + await using view = await renderShortcut(); + const { history } = view.router; + state.navigate.mockImplementation(async () => { + history.push("/restored-owner"); + }); + + await act(() => { + press(); + menuAction?.("view.reopenClosed"); + }); + await act(() => { + history.push("/newer"); + if (goBack) history.back(); + }); + await act(() => result.resolve(AsyncResult.success({ tabId: "new-tab" }))); + + expect(useClosedViewStore.getState().entries).toEqual([]); + const panel = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref); + expect(panel.surfaces.map((surface) => surface.id)).toEqual( + expect.arrayContaining(["browser:new-tab", "diff"]), + ); + expect(history.location.pathname).toBe(expectedPath); + }, + ); + it("serializes deliberate presses while a browser restore waits for RPC", async () => { setup(); useClosedViewStore @@ -174,6 +220,53 @@ describe("root reopen shortcut", () => { expect(useClosedViewStore.getState().entries).toEqual([]); }); + it("follows both queued restores from a page with an allowing navigation blocker", async () => { + setup(); + const olderRef = { ...ref, threadId: "thread-2" } as ScopedThreadRef; + const store = useClosedViewStore.getState(); + store.remember({ + kind: "panel-tab", + threadRef: olderRef, + surface: { kind: "diff", id: "diff" }, + }); + store.remember({ kind: "browser", threadRef: ref, snapshot }); + const opened = Promise.withResolvers>(); + state.openPreview.mockReturnValue(opened.promise); + + const history = createMemoryHistory({ initialEntries: ["/welcome"] }); + const root = createRootRoute({ + component: () => ( + <> + + + + ), + }); + const router = createRouter({ + history, + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: "welcome" }), + createRoute({ getParentRoute: () => root, path: "$environmentId/$threadId" }), + ]), + }); + state.navigate.mockImplementation(router.navigate); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + // The test supplies its own routes and history. + await using _view = await render(, { router: false }); + using _blocker = { + [Symbol.dispose]: history.block({ blockerFn: () => false, enableBeforeUnload: false }), + }; + + await act(() => { + press(); + press(); + }); + await act(() => opened.resolve(AsyncResult.success({ tabId: "new-tab" }))); + + expect(useClosedViewStore.getState().entries).toEqual([]); + expect(history.location.pathname).toBe("/remote/thread-2"); + }); + it("does not create a second browser when navigation fails after restoring it", async () => { setup(); const store = useClosedViewStore.getState(); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index 551dbc98d8abc..1bc9d62a20c8e 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -7,7 +7,7 @@ import { scopeThreadRef, } from "@t3tools/client-runtime/environment"; import type { ScopedThreadRef } from "@t3tools/contracts"; -import { useNavigate, useParams } from "@tanstack/react-router"; +import { linkOptions, useNavigate, useParams, useRouter } from "@tanstack/react-router"; import { useGT } from "gt-react"; import { useEffect, useEffectEvent, useRef } from "react"; @@ -49,6 +49,12 @@ import { import { toastManager } from "./ui/toast"; import { readIssueListPreferences } from "./issue/issueListPreferences"; +declare module "@tanstack/react-router" { + interface HistoryState { + reopenedViewId?: string; + } +} + const PREVIEW_FORWARDED_COMMANDS = [ "workspace.focusNext", "workspace.focusPrevious", @@ -72,6 +78,7 @@ const isGlobalIssues = (ref: ScopedThreadRef) => export function ReopenClosedViewShortcut() { const gt = useGT(); const navigate = useNavigate(); + const router = useRouter(); const params = useParams({ strict: false }); const target = resolveThreadRouteTarget(params); const draft = useComposerDraftStore((state) => @@ -94,8 +101,10 @@ export function ReopenClosedViewShortcut() { const hasHistory = useClosedViewStore((state) => state.entries.length > 0); const openPreview = useAtomCommand(previewEnvironment.open); const pending = useRef(Promise.resolve()); + type ReopenNavigation = { location: typeof router.history.location }; + const reopenNavigation = useRef(null); - const reopenNext = useEffectEvent(async () => { + const reopenNext = useEffectEvent(async (request: ReopenNavigation) => { const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom); const drafts = useComposerDraftStore.getState(); const panelsByThread = useRightPanelStore.getState().byThreadKey; @@ -142,28 +151,59 @@ export function ReopenClosedViewShortcut() { return; } useClosedViewStore.getState().remove(restore.id); + if (router.history.location !== request.location) return; + + let destination; if (globalPullRequests) { const selected = selectSelectedRightPanelSurface( useRightPanelStore.getState().byThreadKey, ref, ); - await navigate({ + destination = linkOptions({ to: "/pull-requests", search: (previous) => pullRequestsSearchForRestore(previous, selected), }); } else if (globalIssues) { - await navigate({ to: "/issues", search: readIssueListPreferences() }); + destination = linkOptions({ to: "/issues", search: readIssueListPreferences() }); } else { const draftId = thread === null ? drafts.getDraftIdByRef(ref) : null; - if (draftId !== null) - await navigate({ to: "/draft/$draftId", params: buildDraftThreadRouteParams(draftId) }); - else await navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) }); + destination = + draftId !== null + ? linkOptions({ to: "/draft/$draftId", params: buildDraftThreadRouteParams(draftId) }) + : linkOptions({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) }); + } + + const { history } = router; + if (router.buildLocation(destination).publicHref === history.location.href) { + const { reopenedViewId } = history.location.state; + await navigate({ ...destination, state: reopenedViewId ? { reopenedViewId } : {} }); + return; + } + + // An allowing blocker can defer the commit. Only the reopen's first history hop extends the queue. + const unsubscribe = history.subscribe(({ location, action }) => { + if (location === request.location) return; + unsubscribe(); + if (action.type === "PUSH" && location.state.reopenedViewId === restore.id) { + request.location = location; + } + }); + try { + await navigate({ ...destination, state: { reopenedViewId: restore.id } }); + } catch (error) { + unsubscribe(); + throw error; } + unsubscribe(); }); const enqueueReopen = useEffectEvent(() => { + const location = router.history.location; + const previous = reopenNavigation.current; + const request = previous?.location === location ? previous : { location }; + reopenNavigation.current = request; pending.current = pending.current - .then(() => reopenNext()) + .then(() => reopenNext(request)) .catch((error: unknown) => { toastManager.add({ type: "error", diff --git a/apps/web/src/components/Sidebar.motion.browser.test.ts b/apps/web/src/components/Sidebar.motion.browser.test.ts new file mode 100644 index 0000000000000..2eae3d4f83fb9 --- /dev/null +++ b/apps/web/src/components/Sidebar.motion.browser.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vite-plus/test"; +import { render } from "../../test/render"; +import { createSidebarListMotion } from "./Sidebar.motion"; + +describe("sidebar list motion", () => { + it("slides rows above a removal at the bottom instead of jumping with the scroll clamp", async () => { + await using screen = await render(null); + const viewport = document.createElement("div"); + viewport.dataset.slot = "scroll-area-viewport"; + viewport.style.cssText = "height: 200px; overflow-y: auto; overflow-anchor: none"; + const list = document.createElement("ul"); + list.style.cssText = "position: relative; margin: 0; padding: 0; list-style: none"; + const rows = Array.from({ length: 10 }, () => { + const row = document.createElement("li"); + row.style.height = "64px"; + list.append(row); + return row; + }); + viewport.append(list); + screen.container.append(viewport); + const motion = createSidebarListMotion(list); + using _motion = { [Symbol.dispose]: () => motion.dispose() }; + motion.update(false); + viewport.scrollTop = viewport.scrollHeight; + viewport.dispatchEvent(new Event("scroll")); + const above = rows[7]!; + const before = above.getBoundingClientRect().top; + + rows[8]!.remove(); + motion.update(true); + for (const animation of above.getAnimations()) animation.pause(); + + expect(above.getBoundingClientRect().top).toBe(before); + }); +}); diff --git a/apps/web/src/components/Sidebar.motion.ts b/apps/web/src/components/Sidebar.motion.ts index 0e86c3c9a0e94..da0e7de3201b2 100644 --- a/apps/web/src/components/Sidebar.motion.ts +++ b/apps/web/src/components/Sidebar.motion.ts @@ -22,6 +22,12 @@ export function createSidebarListMotion(parent: HTMLUListElement) { const entering = new Map(); const exiting = new Map(); let released: Map | null = null; + const scroller = parent.closest('[data-slot="scroll-area-viewport"]'); + let scrollTop = scroller?.scrollTop ?? 0; + const trackScroll = () => { + scrollTop = scroller?.scrollTop ?? 0; + }; + scroller?.addEventListener("scroll", trackScroll, { passive: true }); const remainingOffset = (node: HTMLElement) => { const current = running.get(node); @@ -37,7 +43,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { entering.clear(); exiting.clear(); }; - const fadeOut = (node: HTMLElement, position: RowPosition, travel: number) => { + const fadeOut = (node: HTMLElement, position: RowPosition, travel: number, shift: number) => { if (position.height === 0) return; const clone = node.cloneNode(true) as HTMLElement; for (const element of [clone, ...clone.querySelectorAll("*")]) { @@ -56,7 +62,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { clone.inert = true; Object.assign(clone.style, { position: "absolute", - top: `${position.top + remainingOffset(node)}px`, + top: `${position.top + remainingOffset(node) + shift}px`, left: `${position.left}px`, width: `${position.width}px`, height: `${position.height}px`, @@ -153,6 +159,14 @@ export function createSidebarListMotion(parent: HTMLUListElement) { positions !== null && !reducedMotion?.matches && fadeCount <= MAX_FADED_ROWS_PER_UPDATE; + // A removal near the bottom shrinks the list and the browser clamps scrollTop, moving + // every row on screen; offsets include that shift so those rows slide instead of jump. + let shift = 0; + if (scroller !== null) { + const max = scroller.scrollHeight - scroller.clientHeight; + if (scrollTop > max && scroller.scrollTop >= max - 1) + shift = scroller.scrollTop - scrollTop; + } const movedDelta = new Map(); const nextOrder = [...next.keys()]; const oldOrder = positions === null ? [] : [...positions.keys()]; @@ -173,13 +187,13 @@ export function createSidebarListMotion(parent: HTMLUListElement) { else { for (const [node, position] of next) { const previousTop = positions!.get(node)?.top; - if (previousTop === undefined || previousTop === position.top) continue; - movedDelta.set(node, previousTop + remainingOffset(node) - position.top); + if (previousTop === undefined || previousTop + shift === position.top) continue; + movedDelta.set(node, previousTop + remainingOffset(node) - position.top + shift); } for (const [node, position] of positions!) { if (next.has(node)) continue; const delta = ridingDelta(oldOrder, oldOrder.indexOf(node), (n) => next.has(n)); - fadeOut(node, position, delta === undefined ? rowTravel(position.height) : -delta); + fadeOut(node, position, delta === undefined ? rowTravel(position.height) : -delta, shift); } } for (const [node, entry] of entering) { @@ -233,6 +247,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { released = null; } positions = next; + if (scroller !== null) scrollTop = scroller.scrollTop; }, release() { suspend(); @@ -246,6 +261,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { suspend, dispose() { suspend(); + scroller?.removeEventListener("scroll", trackScroll); disposed = true; }, }; diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 45e00246e2c6d..f8527d0d75a1f 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -171,7 +171,6 @@ import { resolveThreadRouteTarget, } from "../threadRoutes"; import type { SidebarThreadSummary } from "../types"; -import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { cn } from "~/lib/utils"; import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge"; import { ProjectRowActions } from "./ProjectComboboxRow"; @@ -272,7 +271,12 @@ import { type SidebarProviderEntry, type SidebarSweepAction, } from "./sidebar/SidebarThreadRow"; -import { SidebarDraftBlock, useSidebarDrafts } from "./sidebar/SidebarDraftBlock"; +import { + draftTerminalLabel, + SidebarDraftBlock, + useDraftTerminalLabels, + useSidebarDrafts, +} from "./sidebar/SidebarDraftBlock"; import { SidebarProjectFolderHeader, sidebarFolderRowId, @@ -431,6 +435,7 @@ function useSidebarThreads(input: { readonly threads: readonly EnvironmentThreadShell[]; readonly delegatedUnderParent: ReadonlySet; readonly routeRowThreadKey: string | null; + readonly departingThreadKey: string | null; // Set in boring mode: the project groups to fold active threads into, in order. readonly folderGroups: readonly SidebarProjectSnapshot[] | null; // Keeps folders with no active threads, so a project the user filtered to or pinned can start one. @@ -445,9 +450,11 @@ function useSidebarThreads(input: { threads, delegatedUnderParent, routeRowThreadKey, + departingThreadKey, folderGroups, keepEmptyFolders: keepEmpty, } = input; + const shelfRouteThreadKey = routeRowThreadKey === departingThreadKey ? null : routeRowThreadKey; // Folders already separate the work, so boring mode has no Working shelf. const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled) && folderGroups === null; @@ -513,11 +520,11 @@ function useSidebarThreads(input: { const visibleSettledThreads = (() => { const visible = listedSettledThreads.slice(0, settledVisibleCount); if ( - routeRowThreadKey !== null && - !visible.some((thread) => threadShellKey(thread) === routeRowThreadKey) + shelfRouteThreadKey !== null && + !visible.some((thread) => threadShellKey(thread) === shelfRouteThreadKey) ) { const routeThread = settledThreads.find( - (thread) => threadShellKey(thread) === routeRowThreadKey, + (thread) => threadShellKey(thread) === shelfRouteThreadKey, ); if (routeThread !== undefined) visible.push(routeThread); } @@ -525,10 +532,10 @@ function useSidebarThreads(input: { })(); const renderedSettledThreads = settledShelfExpanded ? visibleSettledThreads - : routeThreadOnly(visibleSettledThreads, routeRowThreadKey); + : routeThreadOnly(visibleSettledThreads, shelfRouteThreadKey); const visibleSnoozedThreads = snoozedShelfExpanded ? snoozedThreads - : routeThreadOnly(snoozedThreads, routeRowThreadKey); + : routeThreadOnly(snoozedThreads, shelfRouteThreadKey); const visibleWorkingThreads = workingShelfExpanded ? workingThreads : routeThreadOnly(workingThreads, routeRowThreadKey); @@ -1161,20 +1168,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve setPersistedProjectScopeKeys([]); }, [clearSelection, revealWidensScope, setPersistedProjectScopeKeys]); const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey, routeKeyInPlace); + const [departingThreadKey, setDepartingThreadKey] = useState(null); + if (departingThreadKey !== null && departingThreadKey !== routeThreadKey) { + setDepartingThreadKey(null); + } + const departRouteThread = (threadKey: string) => setDepartingThreadKey(threadKey); + const stayOnRouteThread = (threadKey: string) => + setDepartingThreadKey((current) => (current === threadKey ? null : current)); const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups); - const scratchMachineLabelFor = ( - thread: Pick, - ) => { - if (!showProjectEnvironments) return null; - const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`); - if ( - !project || - !isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot) - ) { - return null; - } - return environmentLabelById.get(thread.environmentId) ?? null; - }; // Pinning from a row keeps rows in place while the menu is open. const projectScopeItems = useOrderWhileOpen( lookupProjectScopeItems, @@ -1203,13 +1204,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : { projectIds: scopedProjectRefs.map((projectRef) => projectRef.projectId) }, ); const routeDraftIdForRows = routeTarget?.kind === "draft" ? routeTarget.draftId : null; + const draftTerminalLabels = useDraftTerminalLabels(); const visibleDraftSessionCount = useComposerDraftStore((store) => { let count = 0; for (const [draftKey, session] of Object.entries(store.draftThreadsByThreadKey)) { if (session.promotedTo != null) { continue; } - if (!composerDraftHasUserContent(store.draftsByThreadKey[draftKey])) { + if ( + draftTerminalLabel(session, draftTerminalLabels) === null && + !composerDraftHasUserContent(store.draftsByThreadKey[draftKey]) + ) { continue; } if ( @@ -1354,6 +1359,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve threads: listedThreads, delegatedUnderParent, routeRowThreadKey, + departingThreadKey, folderGroups: boringSidebarEnabled ? scopedProjectGroups.length === 0 ? // An archived project keeps a folder for its active threads, below the rest. @@ -1443,7 +1449,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const settledThreadKeysRef = useRef(settledThreadKeys); const snoozedThreadKeysRef = useRef(snoozedThreadKeys); - const { draftIds, routeDraftComposer } = useSidebarDrafts(scopedProjectKeys, routeDraftIdForRows); + const { draftIds, routeDraftComposer } = useSidebarDrafts( + scopedProjectKeys, + routeDraftIdForRows, + draftTerminalLabels, + ); // Draft rows sit above the threads, so jumps and traversal reach them first. // Search hides them, so they drop out while it is open. const listedDraftIds = isSearchingThreads ? EMPTY_DRAFT_IDS : draftIds; @@ -1640,9 +1650,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (settlingThreadKeysRef.current.has(threadKey)) return; settlingThreadKeysRef.current.add(threadKey); const navigateAfterSettle = planForwardNavigation(threadKey, opts.coSettlingKeys); + if (navigateAfterSettle) departRouteThread(threadKey); const result = await settleThread(threadRef); settlingThreadKeysRef.current.delete(threadKey); if (result._tag === "Failure") { + stayOnRouteThread(threadKey); if (!isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); toastManager.add( @@ -1665,6 +1677,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) { navigateAfterSettle?.(); + } else { + stayOnRouteThread(threadKey); } })(); }; @@ -2198,6 +2212,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve case "settle": { settlingThreadKeysRef.current.add(activeKey); const navigateAfterSettle = planForwardNavigation(activeKey); + if (navigateAfterSettle) departRouteThread(activeKey); const settled = await run(settleThread(threadRef), gt("Failed to settle thread")).finally( () => settlingThreadKeysRef.current.delete(activeKey), ); @@ -2212,6 +2227,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) navigateAfterSettle?.(); + else stayOnRouteThread(activeKey); return; } case "move-active": @@ -2267,9 +2283,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } snoozingThreadKeysRef.current.add(threadKey); const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys); + if (navigateAfterSnooze) departRouteThread(threadKey); const result = await snoozeThread(threadRef, preset.snoozedUntil); snoozingThreadKeysRef.current.delete(threadKey); if (result._tag === "Failure") { + stayOnRouteThread(threadKey); return isAtomCommandInterrupted(result) ? ({ status: "interrupted" } as const) : ({ status: "failure", error: squashAtomCommandFailure(result) } as const); @@ -2284,6 +2302,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) { navigateAfterSnooze?.(); + } else { + stayOnRouteThread(threadKey); } return { status: "success" } as const; }; @@ -3523,14 +3543,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve jumpLabel={ showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null } - currentEnvironmentId={primaryEnvironmentId} environmentLabel={ environmentLabelById.get(thread.environmentId) ?? null } environmentMachine={ environmentMachineById.get(thread.environmentId) ?? "server" } - scratchMachineLabel={scratchMachineLabelFor(thread)} project={ projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null @@ -3571,6 +3589,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve key="draft-sessions" draftIds={draftIds} routeDraftComposer={routeDraftComposer} + terminalLabels={draftTerminalLabels} jumpLabelByDraftId={draftJumpLabelById} projectByKey={projectByKey} projectDisplayNameByKey={projectDisplayNameByKey} diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 9c5e7fa3d830d..905d9cb2131fe 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -19,7 +19,7 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; import { msg, T, useGT, useMessages } from "gt-react"; -import { FolderGit2Icon, TerminalIcon } from "lucide-react"; +import { TerminalIcon } from "lucide-react"; import { m, type MessageResolver } from "../i18n/messages"; import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; @@ -53,7 +53,6 @@ import { } from "./Sidebar.logic"; import type { SidebarThreadSummary } from "../types"; -import { formatWorktreePathForDisplay } from "../worktreeCleanup"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { PULL_REQUEST_STATE_PRESENTATION, @@ -770,41 +769,6 @@ export function ThreadTerminalStatusButton({ ); } -export function ThreadWorktreeIndicator({ - thread, -}: { - thread: Pick; -}) { - const gt = useGT(); - const worktreePath = thread.worktreePath?.trim(); - if (!worktreePath) { - return null; - } - - const displayPath = formatWorktreePathForDisplay(worktreePath); - const tooltip = thread.branch - ? gt("Worktree: {path} ({branch})", { path: displayPath, branch: thread.branch }) - : gt("Worktree: {path}", { path: displayPath }); - - return ( - - - } - > - - - {tooltip} - - ); -} - function ThreadStatusLabel({ status, compact = false, diff --git a/apps/web/src/components/WorktreeBaseBranchPicker.tsx b/apps/web/src/components/WorktreeBaseBranchPicker.tsx index dd6520a11dab8..eb740a78e4233 100644 --- a/apps/web/src/components/WorktreeBaseBranchPicker.tsx +++ b/apps/web/src/components/WorktreeBaseBranchPicker.tsx @@ -5,6 +5,7 @@ import { useState } from "react"; import { usePaginatedBranches } from "../state/queries"; import { useEnvironmentQuery } from "../state/query"; +import { useAtomCommand } from "../state/use-atom-command"; import { vcsEnvironment } from "../state/vcs"; import { BranchPicker, BranchPickerRefItem } from "./BranchPicker"; import { resolveBranchTriggerLabel, sanitizeNewRefName } from "./BranchToolbar.logic"; @@ -35,6 +36,9 @@ export function WorktreeBaseBranchPicker({ const messages = useMessages(); const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); + const refreshLocalStatusForPicker = useAtomCommand(vcsEnvironment.refreshLocalStatusForPicker, { + reportFailure: false, + }); const branches = usePaginatedBranches( { environmentId, @@ -84,6 +88,9 @@ export function WorktreeBaseBranchPicker({ : null); const handleOpenChange = (next: boolean) => { setOpen(next); + if (next && !open && cwd !== null) { + void refreshLocalStatusForPicker({ environmentId, input: { cwd } }); + } if (!next) setQuery(""); }; return ( diff --git a/apps/web/src/components/backgroundThreadAnnouncement.test.ts b/apps/web/src/components/backgroundThreadAnnouncement.test.ts index b2b6195d8f288..51d3c693f9904 100644 --- a/apps/web/src/components/backgroundThreadAnnouncement.test.ts +++ b/apps/web/src/components/backgroundThreadAnnouncement.test.ts @@ -7,6 +7,7 @@ import { type BackgroundThreadSnapshot, nextBackgroundThreadAnnouncement, resolveBackgroundThreadRequest, + resolveBackgroundThreadRunStatus, } from "./backgroundThreadAnnouncement"; const firstRun = RunId.make("run-1"); @@ -187,3 +188,72 @@ describe("resolveBackgroundThreadRequest", () => { ).toEqual(["Needs approval: Fix login redirect"]); }); }); + +describe("resolveBackgroundThreadRunStatus", () => { + const threadStatus = (overrides?: { + readonly status?: "completed" | "failed" | "interrupted"; + readonly pendingBackgroundTasks?: ReadonlyArray<{ + readonly taskId: string; + readonly kind: "command" | "monitor" | "subagent" | "background_task"; + readonly awaited?: true; + }>; + readonly latestRunBackgroundWake?: boolean; + readonly latestRunStopRequested?: boolean; + }) => { + const pendingBackgroundTasks = overrides?.pendingBackgroundTasks ?? []; + return resolveBackgroundThreadRunStatus({ + latestRun: { status: overrides?.status ?? "completed" }, + pendingBackgroundTasks, + source: { + pendingBackgroundTasks, + latestRunBackgroundWake: overrides?.latestRunBackgroundWake ?? false, + latestRunStopRequested: overrides?.latestRunStopRequested ?? false, + }, + }); + }; + + it("suppresses Done while awaited background work or a monitor wake holds completion, or when stop was requested", () => { + const heldCases = [ + { latestRunStopRequested: true }, + { pendingBackgroundTasks: [{ taskId: "sub-1", kind: "subagent" as const }] }, + { + pendingBackgroundTasks: [ + { taskId: "cmd-1", kind: "command" as const, awaited: true as const }, + ], + }, + { + latestRunBackgroundWake: true, + pendingBackgroundTasks: [{ taskId: "mon-1", kind: "monitor" as const }], + }, + ]; + for (const input of heldCases) { + expect(threadStatus(input)).toBeNull(); + } + }); + + it("keeps Done for unawaited background work and keeps non-completed outcomes", () => { + expect( + threadStatus({ + pendingBackgroundTasks: [{ taskId: "cmd-1", kind: "command" }], + }), + ).toBe("completed"); + expect( + threadStatus({ + latestRunBackgroundWake: false, + pendingBackgroundTasks: [{ taskId: "mon-1", kind: "monitor" }], + }), + ).toBe("completed"); + expect( + threadStatus({ + status: "failed", + pendingBackgroundTasks: [{ taskId: "sub-1", kind: "subagent" }], + }), + ).toBe("failed"); + expect( + threadStatus({ + status: "interrupted", + latestRunStopRequested: true, + }), + ).toBe("interrupted"); + }); +}); diff --git a/apps/web/src/components/backgroundThreadAnnouncement.ts b/apps/web/src/components/backgroundThreadAnnouncement.ts index e1c52adb662ad..48a334543c447 100644 --- a/apps/web/src/components/backgroundThreadAnnouncement.ts +++ b/apps/web/src/components/backgroundThreadAnnouncement.ts @@ -1,4 +1,8 @@ import type { OrchestrationV2RunStatus, RunId } from "@t3tools/contracts"; +import { + backgroundWorkHoldsCompletion, + monitorHoldsWakeCompletion, +} from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { msg } from "gt-react"; @@ -40,6 +44,27 @@ export function resolveBackgroundThreadRequest( return { request: null, requestId: null }; } +/** Suppresses Done announcements for stopped runs, awaited background work, and monitor wakes. */ +export function resolveBackgroundThreadRunStatus(thread: { + readonly latestRun: { readonly status: OrchestrationV2RunStatus } | null; + readonly pendingBackgroundTasks: SidebarThreadSummary["pendingBackgroundTasks"]; + readonly source: Pick< + SidebarThreadSummary["source"], + "latestRunBackgroundWake" | "latestRunStopRequested" | "pendingBackgroundTasks" + >; +}): OrchestrationV2RunStatus | null { + const status = thread.latestRun?.status ?? null; + if ( + status === "completed" && + (thread.source.latestRunStopRequested === true || + backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks) || + monitorHoldsWakeCompletion(thread.source)) + ) { + return null; + } + return status; +} + interface BackgroundThreadMemoryEntry { readonly request: BackgroundThreadSnapshot["request"]; readonly requestId: string | null; diff --git a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx index 0772a864c021e..afb51240b625e 100644 --- a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx +++ b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx @@ -143,6 +143,7 @@ export function AssistantSelectionToolbar({ element: viewport, getActionElement: () => toolbarRef.current, restoreAfterScroll: true, + immediateMultiClick: true, onSelection: update, onDismiss: clear, }); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 9038e6717ba0e..af4871b451932 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -133,6 +133,8 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, + clipboardHtmlImageContent, + imagesToAttachBesidePastedText, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -251,6 +253,7 @@ import { useNavigate } from "@tanstack/react-router"; import { assistantCitationLabel } from "@t3tools/shared/assistantCitations"; import { assistantCitationNavigation } from "../../lib/assistantCitationNavigation"; import { Button } from "../ui/button"; +import { Spinner } from "../ui/spinner"; import { useManagedPolicy } from "../../state/managedPolicy"; import { hasProviderSetup } from "./ProviderStatusBanner"; import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; @@ -285,10 +288,13 @@ import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; import { + cancelHeldComposerSend, countPreparingComposerImages, + useComposerSendHeld, usePreparingComposerImages, useSubmitAfterPreparingImages, } from "./preparingComposerImages"; +import { HELD_COMPOSER_SEND_BANNER_ID } from "./ComposerHeldSendBanner"; import { ComposerControlsBar } from "./ComposerControlsBar"; import { composerCommandKeyHandler } from "./composerCommandKey"; import { promptSuggestionToAccept, usePromptSuggestion } from "./usePromptSuggestion"; @@ -460,6 +466,19 @@ export interface ChatComposerProps { dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent, ) => void; + captureDetachedSend?: () => ( + e?: { preventDefault: () => void }, + dispatchMode?: ComposerDispatchMode, + submissionIntent?: ComposerSubmissionIntent, + directAnnotation?: { + annotation: PreviewAnnotationPayload; + image: ComposerImageAttachment | null; + }, + detachedOverride?: { + readonly prompt: string; + readonly sendContext: ReturnType; + }, + ) => void; onResume: () => void; onInterrupt: () => void; onSelectActivePendingUserInputOption: (questionId: string, optionValue: string) => void; @@ -562,6 +581,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onPageScrollRelease, onCompactContext, onSend, + captureDetachedSend, onResume, onInterrupt, onSelectActivePendingUserInputOption, @@ -714,8 +734,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) uncommittedSnapShotIds, standaloneComposerImages, } = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations); - const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey).filter( - (image) => !image.hidden, + const allPreparingComposerImages = usePreparingComposerImages(attachmentTargetKey); + const preparingComposerImages = allPreparingComposerImages.filter((image) => !image.hidden); + // A message send waits for these itself; an answer waits in the composer below. + const messageHasPreparingImages = + questionAttachmentTarget === null && allPreparingComposerImages.length > 0; + const composerSendHeld = useComposerSendHeld(composerDraftTargetKey); + const cancelHeldSend = () => cancelHeldComposerSend(composerDraftTargetKey); + const handleMultipleModelSelectionsChangeStable = useStableCallback( + (next: React.SetStateAction | null>) => { + cancelHeldSend(); + setMultipleModelSelections(next); + }, ); const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds; const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId); @@ -1252,21 +1282,28 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isComplete: Boolean(activePendingResolvedAnswers), } : null; + const hasMessageToSend = composerSendState.hasSendableContent || messageHasPreparingImages; const showResumeAction = - canResume && !composerDraftHasUserContent(composerDraft) && !isEditingQueuedMessage; + canResume && + !composerDraftHasUserContent(composerDraft) && + !messageHasPreparingImages && + !isEditingQueuedMessage; const collapsedComposerPrimaryActionDisabled = phase === "running" || isSendBusy || + composerSendHeld || isSendDisabled || noProviderAvailable || projectSelectionRequired || environmentUnavailable !== null || - (!composerSendState.hasSendableContent && !showResumeAction); - const collapsedComposerPrimaryActionLabel = showResumeAction - ? gt("Resume thread") - : props.resumeCompactionTokens !== null && !props.keepFullHistory - ? gt("Open composer to compact and send") - : gt("Send message"); + (!hasMessageToSend && !showResumeAction); + const collapsedComposerPrimaryActionLabel = composerSendHeld + ? gt("Sending when ready") + : showResumeAction + ? gt("Resume thread") + : props.resumeCompactionTokens !== null && !props.keepFullHistory + ? gt("Open composer to compact and send") + : gt("Send message"); const showMobilePendingAnswerActions = isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null; @@ -2181,29 +2218,100 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (activePendingProgress) { return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers); } - return composerSendState.hasSendableContent; + return hasMessageToSend; }; const submitComposerRef = useRef< - (dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent) => void + ( + dispatchMode?: ComposerDispatchMode, + submissionIntent?: ComposerSubmissionIntent, + options?: { readonly afterDictation?: boolean }, + ) => void >(() => {}); const submitComposer = ( event?: { preventDefault: () => void }, dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent, + options?: { readonly afterDictation?: boolean }, ) => { - if (voiceInputActive) { + if (voiceInputActive && !options?.afterDictation) { event?.preventDefault(); - submitAfterDictation(() => submitComposerRef.current(dispatchMode, submissionIntent)); + const queuedOwnerKey = attachmentTargetKey; + const capturedDraftTarget = composerDraftTarget; + const resolvedDispatchMode = + dispatchMode ?? + resolveComposerDispatchMode({ + running: phase === "running" || phase === "connecting", + alternateModifier: false, + activeTurnDefault: followUpBehavior, + canSteer, + }); + const capturedDetachedSend = + questionAttachmentTarget === null ? (captureDetachedSend?.() ?? null) : null; + const capturedSendContext = + capturedDetachedSend !== null ? (composerRef.current?.getSendContext() ?? null) : null; + const capturedSubmissionTarget = submissionTarget; + submitAfterDictation((transcribedText) => { + const stillLive = + composerMountedRef.current && attachmentTargetKeyRef.current === queuedOwnerKey; + if (stillLive) { + submitComposerRef.current(dispatchMode, submissionIntent, { afterDictation: true }); + return; + } + if ( + !capturedDetachedSend || + !capturedSendContext || + pendingDraftWork.has(queuedOwnerKey) || + countPreparingComposerImages(queuedOwnerKey) > 0 + ) { + return; + } + const liveTarget = resolveLiveComposerDraftTarget(capturedDraftTarget); + const latestDraft = + liveTarget !== null + ? useComposerDraftStore.getState().getComposerDraft(liveTarget) + : null; + submitComposerDraft({ + prompt: transcribedText, + submissionTarget: capturedSubmissionTarget, + event: undefined, + onSend: (sendEvent) => { + capturedDetachedSend(sendEvent, resolvedDispatchMode, submissionIntent, undefined, { + prompt: transcribedText, + sendContext: { + ...capturedSendContext, + ...(latestDraft + ? { + images: latestDraft.images, + files: latestDraft.files, + terminalContexts: latestDraft.terminalContexts, + previewAnnotations: latestDraft.previewAnnotations, + reviewComments: latestDraft.reviewComments, + threadContexts: latestDraft.threadContexts, + environmentContexts: latestDraft.environmentContexts, + } + : {}), + prompt: transcribedText, + }, + }); + return true; + }, + }); + }); return false; } if (submissionBlocked || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) { event?.preventDefault(); return false; } - // Sending now would leave a still-compressing image out of the turn, so wait for it. + if (composerSendHeld) { + event?.preventDefault(); + return false; + } + // Sending now would leave a still-compressing image out of the answer, so wait for it. if ( activeThreadId && + questionAttachmentTarget && submitAfterPreparingImages(() => submitComposerRef.current(dispatchMode, submissionIntent)) ) { event?.preventDefault(); @@ -2219,7 +2327,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return false; } // An empty draft has nothing to send; Enter does what the Resume thread button does. - if (showResumeAction && !activePendingProgress) { + if (showResumeAction && !activePendingProgress && promptRef.current.trim().length === 0) { event?.preventDefault(); if (isSendBusy || environmentUnavailable !== null) return false; onResume(); @@ -2256,7 +2364,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const submitComposerStable = useStableCallback(submitComposer); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed submission handler to the asynchronous dictation completion useLayoutEffect(() => { - submitComposerRef.current = (mode, intent) => submitComposerStable(undefined, mode, intent); + submitComposerRef.current = (mode, intent, options) => + submitComposerStable(undefined, mode, intent, options); }, [submitComposerStable]); useDictationSubmissionShortcut({ enabled: voiceInputActive && !speechInput.preparing, @@ -2385,8 +2494,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? promptSuggestion : null; - const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => - composerCommandKeyHandler({ + const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => { + if (key === "Escape" && composerSendHeld && !event.isComposing) { + cancelHeldSend(); + return true; + } + return composerCommandKeyHandler({ keybindings, getShortcutContext, sendShortcut: settings.sendShortcut, @@ -2425,6 +2538,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptSuggestion: offeredPromptSuggestion, dismissPromptSuggestion, })(key, event, isTaskItem); + }; const { stashQueue, @@ -2533,7 +2647,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isSendBusy={isSendBusy} multipleModelsEnabled={routeKind === "draft" && supportsMultipleModels} multipleModelSelections={multipleModelSelections} - onMultipleModelSelectionsChange={setMultipleModelSelections} + onMultipleModelSelectionsChange={handleMultipleModelSelectionsChangeStable} selectedModelSelection={selectedModelSelection} onProviderModelSelect={onProviderModelSelect} activeThreadModelSelection={activeThreadModelSelection} @@ -2631,7 +2745,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const shelfItems = hasBlockingComposerTopDrawer ? bannerItems.filter( (item) => - item.group === "environment" && (item.variant === "error" || item.variant === "warning"), + item.id === HELD_COMPOSER_SEND_BANNER_ID || + (item.group === "environment" && + (item.variant === "error" || item.variant === "warning")), ) : bannerItems; @@ -2832,12 +2948,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const pastedContext = !isLiteralPendingAnswer && (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; + const canAttachFiles = !pastedContext && activeThreadId !== null && files.length > 0; + const htmlImageContent = + canAttachFiles && plainText.length > 0 + ? clipboardHtmlImageContent(event.clipboardData.getData("text/html")) + : "none"; if ( folders.length > 0 || - (!pastedContext && - activeThreadId && - files.length > 0 && - shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment })) + (canAttachFiles && + shouldHandleComposerAttachmentPaste({ + files, + plainText, + bypassAutoAttachment, + htmlIsOnlyImage: htmlImageContent === "only-image", + })) ) { event.preventDefault(); event.stopPropagation(); @@ -2849,6 +2973,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } if (pastedContext) return; + const imagesBesideText = imagesToAttachBesidePastedText({ + files, + plainText, + bypassAutoAttachment, + htmlHasImageAndText: htmlImageContent === "image-and-text", + }); + if (imagesBesideText.length > 0) void addComposerAttachments(imagesBesideText); if (!foldPastedText(plainText, bypassAutoAttachment)) { return; } @@ -3429,6 +3560,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
{ + if ( + event.key === "Escape" && + composerSendHeld && + !event.defaultPrevented && + !event.nativeEvent.isComposing + ) { + event.preventDefault(); + cancelHeldSend(); + } + }} onFocusCapture={(event) => { const activeElement = event.target; if ( @@ -3563,7 +3705,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) canOperateThread={canOperateThread} canInterrupt={canInterrupt} runId={activeThread?.runtime?.activeRunId ?? null} - hasSendableContent={composerSendState.hasSendableContent} + hasSendableContent={hasMessageToSend} isEditingQueuedMessage={isEditingQueuedMessage} onInterrupt={handleInterruptPrimaryActionStable} > @@ -3573,6 +3715,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) className="flex size-8 shrink-0 items-center justify-center rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover disabled:opacity-64" disabled={collapsedComposerPrimaryActionDisabled} aria-label={collapsedComposerPrimaryActionLabel} + aria-busy={composerSendHeld || isSendBusy || undefined} onPointerDown={(event) => event.preventDefault()} onClick={(event) => { event.stopPropagation(); @@ -3582,7 +3725,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) else submitComposer(); }} > - {showResumeAction ? ( + {composerSendHeld || isSendBusy ? ( +
+ ); + } + return (
- } - className={MARKDOWN_FILE_LINK_CLASS_NAME} - data-markdown-copy={copyMarkdown} - onClick={(event) => { - event.preventDefault(); - event.stopPropagation(); - if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { - handleOpenInEditor(); - return; - } - if (useBrowserPrimaryAction) { - handleOpenInBrowser(); - return; - } - handleOpenInFilePreview(); - }} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - theme={theme} - /> - - ) : ( - } - aria-label={gt("File options for {label}", { label })} - aria-haspopup="menu" - className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} - data-markdown-copy={copyMarkdown} - onClick={handleContextMenu} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - theme={theme} - /> - - ) + const tooltipContent = ( + + ); + const sharedTooltip = useSharedTooltip({ + render: () => tooltipContent, + contentKey: `${iconPath}\u0000${targetPath}`, + variant: "code", + }); + const chip = hasPrimaryAction ? ( + } + className={MARKDOWN_FILE_LINK_CLASS_NAME} + data-markdown-copy={copyMarkdown} + onClick={(event) => { + event.preventDefault(); + event.stopPropagation(); + if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { + handleOpenInEditor(); + return; + } + if (useBrowserPrimaryAction) { + handleOpenInBrowser(); + return; } + handleOpenInFilePreview(); + }} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + theme={theme} + /> + + ) : ( + } + aria-label={gt("File options for {label}", { label })} + aria-haspopup="menu" + className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} + data-markdown-copy={copyMarkdown} + onClick={handleContextMenu} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + theme={theme} /> + + ); + if (sharedTooltip) return withSharedTooltip(chip, sharedTooltip); + return ( + + - + {tooltipContent} ); diff --git a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx b/apps/web/src/components/chat/MarkdownMath.browser.test.tsx deleted file mode 100644 index ec5b38541ddc4..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, it } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; - -import { render } from "../../../test/render"; -import "../../index.css"; - -import { MarkdownMath } from "./MarkdownMath"; - -it("keeps keyboard scrolling available as a streamed equation outgrows its viewport", async () => { - const equation = (tex: string, width = 180) => ( -
- - - -
- ); - await using screen = await render(equation("x")); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8")); - const scroller = screen.getByLabelText("Scroll display equation"); - await expect.element(scroller).toHaveAttribute("tabindex", "0"); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(scroller).toHaveFocus(); - await userEvent.keyboard("{ArrowRight}"); - await expect.element(scroller).not.toHaveProperty("scrollLeft", 0); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8", 1000)); - await expect.element(screen.getByLabelText("Scroll display equation")).not.toBeInTheDocument(); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); -}); diff --git a/apps/web/src/components/chat/MarkdownMath.tsx b/apps/web/src/components/chat/MarkdownMath.tsx deleted file mode 100644 index 8070d64ac3c18..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import { useGT } from "gt-react"; -import { lazy, memo, Suspense, useLayoutEffect, useRef, useState } from "react"; - -import { observeResize } from "../../lib/observeResize"; - -import { RenderErrorBoundary } from "../RenderErrorBoundary"; - -const MathTypeset = lazy(() => import("./MathTypeset")); - -/** - * One formula from `remark-math`. Shows its TeX until KaTeX loads, and - * keeps showing it when KaTeX cannot parse it, such as mid-stream. Copying - * any part of a formula copies its whole TeX source. - */ -export const MarkdownMath = memo(function MarkdownMath(props: { - tex: string; - display: boolean; - focusable?: boolean; -}) { - const gt = useGT(); - const viewportRef = useRef(null); - const contentRef = useRef(null); - const [overflows, setOverflows] = useState(false); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes formula DOM width to make overflowing equations keyboard scrollable - useLayoutEffect(() => { - const viewport = viewportRef.current; - const content = contentRef.current; - if (!viewport || !content || props.focusable === false) return; - const measure = () => setOverflows(viewport.scrollWidth > viewport.clientWidth); - measure(); - // Typesetting and streamed TeX can change content width without resizing the viewport. - return observeResize([viewport, content], measure); - }, [props.focusable]); - const scrollable = props.focusable !== false && overflows; - const tex = props.tex.trim(); - const source = props.display ? `\\[\n${tex}\n\\]` : `\\(${tex}\\)`; - const fallback = {source}; - return ( - - - - - - - - - - - - ); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.test.ts b/apps/web/src/components/chat/MathTypeset.logic.test.ts deleted file mode 100644 index 634f5146475ac..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import katex from "katex"; -import { describe, expect, it } from "vite-plus/test"; - -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -describe("escapeLiteralPercents", () => { - it.each([ - ["\\text{3.18% yield}", "\\text{3.18\\% yield}"], - ["\\text{100%% yield}", "\\text{100\\%\\% yield}"], - ["6\\% + 2\\%", "6\\% + 2\\%"], - ["x\\\\%", "x\\\\\\%"], - ["x % note\n+ 1", "x % note\n+ 1"], - ["% note\n\\text{2%}", "% note\n\\text{2\\%}"], - ["x &= 1 % +9%\n\\text{2%}", "x &= 1 % +9%\n\\text{2\\%}"], - ["\\verb|50%|+\\text{2%}", "\\verb|50%|+\\text{2\\%}"], - ["\\verb*%a%b%+c%", "\\verb*%a%b\\%+c\\%"], - ["\\verb|50%+\\text{2%}", "\\verb|50%+\\text{2%}"], - ])("repairs %j", (tex, expected) => { - expect(escapeLiteralPercents(tex)).toBe(expected); - }); - - it("lets the reported multiline equation typeset", () => { - const tex = - "R_e=\\underbrace{\\frac{1.0176}{32}}_{\\text{3.18% dividend yield}}\n+\\underbrace{6\\%}_{\\text{growth}}\n=\\boxed{9.18\\%}"; - expect(() => katex.renderToString(tex, { throwOnError: true })).toThrow(); - expect(() => - katex.renderToString(escapeLiteralPercents(tex), { throwOnError: true }), - ).not.toThrow(); - }); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.ts b/apps/web/src/components/chat/MathTypeset.logic.ts deleted file mode 100644 index 04111ab4a70b4..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Escapes each `%` written right after other text, as in `\text{3.18% yield}`. - * A `%` at a line start or after whitespace stays a comment. Skips escapes and - * `\verb` like KaTeX's lexer, in one linear pass. - */ -export function escapeLiteralPercents(tex: string): string { - let repaired = ""; - let copied = 0; - let index = 0; - while (index < tex.length) { - const char = tex[index]; - if (char === "\\") { - if (tex.startsWith("\\verb", index)) { - const starred = tex[index + 5] === "*"; - const delimiter = tex[index + (starred ? 6 : 5)]; - if (delimiter !== undefined && (starred || !/[*a-zA-Z]/.test(delimiter))) { - const bodyStart = index + (starred ? 7 : 6); - let close = bodyStart; - while (close < tex.length && ![delimiter, "\n", "\r"].includes(tex[close]!)) close++; - // KaTeX rejects a \verb that does not close on its own line. - if (tex[close] !== delimiter) return tex; - index = close + 1; - continue; - } - } - // A control symbol such as `\%` or `\\` is two characters. - index += 2; - } else if (char === "%" && index > 0 && !/\s/.test(tex[index - 1]!)) { - repaired += `${tex.slice(copied, index)}\\%`; - copied = ++index; - } else if (char === "%") { - const newline = tex.indexOf("\n", index); - index = newline === -1 ? tex.length : newline + 1; - } else { - index++; - } - } - return copied === 0 ? tex : repaired + tex.slice(copied); -} diff --git a/apps/web/src/components/chat/MathTypeset.tsx b/apps/web/src/components/chat/MathTypeset.tsx deleted file mode 100644 index 16d3dba409ee6..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import katex from "katex"; -import "katex/dist/katex.min.css"; -import type { ReactNode } from "react"; - -import { LRUCache } from "../../lib/lruCache"; -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -// Virtualized threads remount messages while scrolling; cached markup keeps -// that from typesetting the same formulas again. "" records a parse error. -const typesetCache = new LRUCache(1000, 4 * 1024 * 1024); - -function typeset(tex: string, display: boolean): string { - const key = `${display ? "display" : "inline"}:${tex}`; - const cached = typesetCache.get(key); - if (cached !== null) return cached; - const options = { - displayMode: display, - output: "htmlAndMathml" as const, - throwOnError: true, - // No \href, \url, \htmlClass, or other commands that emit active HTML. - trust: false, - strict: "ignore" as const, - maxSize: 20, - maxExpand: 1000, - }; - let html = ""; - try { - html = katex.renderToString(tex, options); - } catch { - const repaired = escapeLiteralPercents(tex); - if (repaired !== tex) { - try { - html = katex.renderToString(repaired, options); - } catch { - // Unfinished or unsupported TeX stays readable as its source. - } - } - } - typesetCache.set(key, html, (key.length + html.length) * 2); - return html; -} - -/** KaTeX lives in this lazily loaded chunk, so it is only fetched once a formula renders. */ -export default function MathTypeset(props: { tex: string; display: boolean; fallback: ReactNode }) { - const html = typeset(props.tex, props.display); - if (!html) return props.fallback; - // KaTeX escapes the TeX it renders, and `trust: false` keeps it from emitting links or attributes. - return ; -} diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 2e7721dddea18..d15a26ca43db0 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -44,11 +44,10 @@ import { type PendingApproval, deriveTimelineEntriesFromVisibleTurnItems, } from "../../session-logic"; -import type { Root } from "mdast"; import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; -import { remarkThoughtPreview, THOUGHT_PREVIEW_MAX_LENGTH } from "./TimelineWorkEntryRow.logic"; +import { THOUGHT_PREVIEW_MAX_LENGTH, thoughtPreviewMarkdown } from "./TimelineWorkEntryRow.logic"; +import { wordsHast } from "~/markdown/wordsHast"; import { TimelineRowCtx } from "./timelineRowContext"; -import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { collectThreadFindRanges } from "./threadFindHighlights"; @@ -2128,49 +2127,22 @@ describe("compact reasoning math", () => { ["hard \nbreak\\\nagain", [["text", "hard break again"]]], ["
only html
", [["text", "Reasoning"]]], ])("keeps formulas while flattening compact reasoning previews: %j", (source, expected) => { - const tree = parseMarkdownWithMath(source); - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children.map((node) => [node.type, "value" in node ? node.value : null])).toEqual( - expected, - ); - }); - - it("stops reading the tree once the preview is full", () => { - const beyondCap = (): string => { - throw new Error("read beyond cap"); - }; - const head = "x".repeat(THOUGHT_PREVIEW_MAX_LENGTH - 2); - const tree: Root = { - type: "root", - children: [ - { - type: "paragraph", - children: [ - { type: "text", value: head }, - { type: "strong", children: [{ type: "text", value: "yz beyond" }] }, - { - type: "inlineMath", - get value() { - return beyondCap(); - }, - }, - ], - }, - { - type: "paragraph", - children: [ - { - type: "text", - get value() { - return beyondCap(); - }, - }, - ], - }, - ], - }; - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children).toEqual([{ type: "text", value: `${head}yz` }]); + const tree = wordsHast(source, { + math: true, + breaks: false, + escapeHtml: false, + insights: false, + extensions: thoughtPreviewMarkdown("Reasoning"), + }); + expect( + tree.children.map((node) => + node.type === "text" + ? ["text", node.value] + : node.type === "element" && node.children[0]?.type === "element" + ? ["inlineMath", String(node.children[0].properties.ariaLabel).trim()] + : [node.type, null], + ), + ).toEqual(expected); }); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 124062303e0cf..b00a48185b9db 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -14,7 +14,7 @@ import { IDLE_COMPACTION_TITLES, } from "@t3tools/client-runtime/user-message"; import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff"; -import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives"; +import { renderCodexDirectivesForCopy } from "~/markdown/markdownText"; import { commandDisplayText, commandProgramName, diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 076c78d88d468..8b4bb6232287b 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -141,9 +141,14 @@ export function RightPanelSurfaceContent(props: { getShortcutContext={props.getShortcutContext} shortcutsEnabled={visible && props.activeSurfaceId === surface.id} key={`${scopedThreadKey(threadRef)}:${surface.id}`} - environmentId={props.environmentId} + environmentId={ + (surface.environmentId as EnvironmentId | undefined) ?? props.environmentId + } onSelectPullRequest={(reference) => { useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), projectId: reference.projectId, repository: reference.repository, number: reference.number, @@ -205,12 +210,24 @@ export function RightPanelSurfaceContent(props: { threadRef={threadRef} onSelectPullRequest={(reference) => { useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), projectId: reference.projectId, repository: reference.repository, number: reference.number, ...(reference.host ? { host: reference.host } : {}), }); }} + onSelectIssue={({ host, ...reference }) => { + useRightPanelStore.getState().openIssue(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), + ...reference, + ...(host ? { host } : {}), + }); + }} /> ); case "pull-requests": diff --git a/apps/web/src/components/chat/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx index d337e7a1b9b54..25c1fe59d5e6b 100644 --- a/apps/web/src/components/chat/SecretRequestCard.tsx +++ b/apps/web/src/components/chat/SecretRequestCard.tsx @@ -24,6 +24,7 @@ import type { SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { T, useGT, useMessages, Var } from "gt-react"; import { CheckIcon, @@ -36,7 +37,6 @@ import { } from "lucide-react"; import { useId, useRef, useState, type FormEvent } from "react"; -import { isSecretsFeatureEnabled } from "../../env"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; import { Button } from "../ui/button"; @@ -80,7 +80,7 @@ const NO_SOURCES: ReadonlyArray = []; function useSecretRequestSources(environmentId: EnvironmentId) { const config = useAtomValue(serverEnvironment.configValueAtom(environmentId)); const messages = useMessages(); - return isSecretsFeatureEnabled + return hasFeatureFlag(config, "secretProviders") ? secretRequestSources(config, config?.settings.secretProviders ?? {}, messages) : NO_SOURCES; } diff --git a/apps/web/src/components/chat/ThreadAutomationsPanel.tsx b/apps/web/src/components/chat/ThreadAutomationsPanel.tsx index 0a602227cad54..12989e3f4f607 100644 --- a/apps/web/src/components/chat/ThreadAutomationsPanel.tsx +++ b/apps/web/src/components/chat/ThreadAutomationsPanel.tsx @@ -12,12 +12,14 @@ import { type ScheduledTask, type ThreadId, } from "@t3tools/contracts"; +import type { TimestampFormat } from "@t3tools/contracts/settings"; import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { ThreadDetailsSection } from "./ThreadDetailsSection"; +import { useClientSettings } from "../../hooks/useSettings"; import { cn } from "../../lib/utils"; import { ScheduledRelativeLabel } from "../settings/ScheduledTasksSettings"; import { scheduleLabel } from "../settings/scheduledTasksSettings.logic"; @@ -43,12 +45,13 @@ const STATUS_DOT_CLASS: Record = { function taskScheduleLine( task: ScheduledTask, + timestampFormat: TimestampFormat, timeZone: string | undefined, resolve: MessageResolver, ) { return ( <> - {scheduleLabel(task.schedule, timeZone, task.nextRunAt, resolve)} + {scheduleLabel(task.schedule, timestampFormat, timeZone, task.nextRunAt, resolve)} {task.blockedByPolicy !== undefined ? ( ` · ${task.blockedByPolicy}` ) : task.enabled && task.nextRunAt !== null ? ( @@ -87,6 +90,7 @@ export function ThreadAutomationsPanel(props: { const runTaskNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, { label: "thread automation run now", }); + const timestampFormat = useClientSettings((settings) => settings.timestampFormat); const navigate = useNavigate(); const gt = useGT(); const m = useMessages(); @@ -198,13 +202,13 @@ export function ThreadAutomationsPanel(props: { {task.title}

- {taskScheduleLine(task, tasksQuery.data?.timeZone, m)} + {taskScheduleLine(task, timestampFormat, tasksQuery.data?.timeZone, m)}

{task.title}

- {taskScheduleLine(task, tasksQuery.data?.timeZone, m)} + {taskScheduleLine(task, timestampFormat, tasksQuery.data?.timeZone, m)}

diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 052a5742b7aab..666ce784b3afc 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -236,6 +236,48 @@ it("opens an idle child beside the thread, and in its place with the modifier", expect(panel().surfaces).toHaveLength(1); }); +it("keeps focus on the list when Show more pages reveal the last rows", async () => { + setup(); + const projection = makeThreadProjectionFixture(); + const environmentId = EnvironmentId.make("local"); + const { updatedAt } = projection.thread; + state.projection = { + ...projection, + subagents: Array.from({ length: 7 }, (_, index) => ({ + id: NodeId.make(`agent-${index}`), + threadId: projection.thread.id, + runId: null, + parentNodeId: NodeId.make("parent"), + origin: "app_owned", + createdBy: "agent", + driver: "codex", + providerInstanceId: projection.thread.providerInstanceId, + providerThreadId: null, + childThreadId: ThreadId.make(`omitted-child-${index}`), + nativeTaskRef: null, + prompt: `Inspect the change part ${index}`, + title: `Agent ${index}`, + model: null, + status: "completed", + result: null, + startedAt: null, + completedAt: updatedAt, + updatedAt, + })), + }; + await using screen = await render( + , + ); + await screen.getByRole("button", { name: /Previous agents/ }).click(); + await screen.getByRole("button", { name: "Show 1 more" }).click(); + await expect.element(screen.getByRole("list", { name: "Related threads" })).toHaveFocus(); +}); + it("shows a lineage thread's full title in its tooltip", async () => { setup(); const longTitle = "Compare the lineage tooltip against a title that the row truncates"; diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 9675a21620d32..b005fa877b745 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -121,19 +121,28 @@ function ThreadLineageRowList(props: { readonly children: ReactNode; }) { const gt = useGT(); + const listRef = useRef(null); + const showMore = () => { + const exhausting = props.hiddenCount <= THREAD_LINEAGE_PAGE_COUNT; + props.onShowMore(); + // The button unmounts on the final page; focus the list so focus isn't dropped. + if (exhausting) listRef.current?.focus({ preventScroll: true }); + }; return ( <> {/* ScrollArea's max-height viewport measures badly inside this scrolling panel. */}
    {props.children}
{props.hiddenCount > 0 ? ( ) : ( diff --git a/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx b/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx index ea6868ed3dc93..6ea4694620c23 100644 --- a/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx +++ b/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx @@ -338,7 +338,9 @@ function AddTrackedFolderDialog(props: { key={entry.fullPath} type="button" className={rowClassName} - onClick={() => setQuery(appendBrowsePathSegment(query, entry.name))} + onClick={() => + setQuery(appendBrowsePathSegment(browsePath.directoryPath, entry.name)) + } > {entry.name} diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx index 7ba2d17d7291d..417868799a18d 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx @@ -279,4 +279,18 @@ describe("ScheduledTasksSettings", () => { await expect.element(dialog.getByRole("heading", { name: "New task" })).toBeInTheDocument(); await expect.element(name).toHaveValue("My draft"); }); + + it("keeps a new task's draft when the user clicks outside the editor", async () => { + setup(); + await using _screen = await render(); + await userEvent.click(page.getByRole("button", { name: "New task" })); + const dialog = page.getByRole("dialog"); + const name = dialog.getByRole("textbox", { name: "Name" }); + await userEvent.fill(name, "My draft"); + + await userEvent.click(document.body, { position: { x: 1, y: 1 } }); + + await expect.element(dialog).toHaveAttribute("data-open"); + await expect.element(name).toHaveValue("My draft"); + }); }); diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx index 471dcdf0fe0df..a2ffce32e68cd 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx @@ -54,7 +54,7 @@ import { msg, T, useGT, useLocale, useMessages, Var } from "gt-react"; import { m, type MessageResolver } from "../../i18n/messages"; import { formatRelativeTime } from "../../timestampFormat"; -import { useEnvironmentSettings } from "../../hooks/useSettings"; +import { useClientSettings, useEnvironmentSettings } from "../../hooks/useSettings"; import { getCustomModelOptionsByInstance } from "../../modelSelection"; import { providerInstanceEntriesFor } from "../../providerInstances"; import { usePrimaryCloudLinkState } from "../../cloud/cloudLinkState"; @@ -795,6 +795,7 @@ function ScheduledTaskRow({ const canOperate = useAtomValue( serverEnvironment.upsertScheduledTask.permissionAtom(environmentId), ); + const timestampFormat = useClientSettings((settings) => settings.timestampFormat); const [busy, setBusy] = useState(false); const [deliveriesOpen, setDeliveriesOpen] = useState(false); const isWebhook = task.schedule.type === "webhook"; @@ -841,7 +842,15 @@ function ScheduledTaskRow({ status={
- {scheduleLabel(task.schedule, timeZone, task.nextRunAt, messages, locale)} ·{" "} + {scheduleLabel( + task.schedule, + timestampFormat, + timeZone, + task.nextRunAt, + messages, + locale, + )}{" "} + ·{" "} {task.blockedByPolicy !== undefined ? ( task.blockedByPolicy ) : !task.enabled ? ( @@ -1261,6 +1270,8 @@ function ScheduledTaskEditorDialog({ return ( { if (!open && !saving) onClose(); }} diff --git a/apps/web/src/components/settings/SecretSourceInput.tsx b/apps/web/src/components/settings/SecretSourceInput.tsx index b62c8a397fbd6..53263c226d2f0 100644 --- a/apps/web/src/components/settings/SecretSourceInput.tsx +++ b/apps/web/src/components/settings/SecretSourceInput.tsx @@ -7,6 +7,7 @@ import { } from "@t3tools/contracts"; import { builtInSecretProviderDefinitions } from "@t3tools/secret-provider-definitions/registry"; import { invalidSecretReferenceText } from "@t3tools/client-runtime/secret-request"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { useAtomValue } from "@effect/atom-react"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -14,7 +15,6 @@ import { useGT, useMessages } from "gt-react"; import { AlertTriangleIcon, CheckIcon, KeyRoundIcon, RefreshCwIcon, TypeIcon } from "lucide-react"; import { useState, type ComponentProps, type ComponentType, type ReactNode } from "react"; -import { isSecretsFeatureEnabled } from "../../env"; import { useEnvironmentSettings } from "../../hooks/useSettings"; import { OnePasswordIcon } from "../Icons"; import { serverEnvironment } from "../../state/server"; @@ -42,9 +42,9 @@ export function useSecretSources(environmentId: EnvironmentId): ReadonlyArray settings.secretProviders); const supported = useAtomValue( serverEnvironment.configValueAtom(environmentId), - (config) => config?.secretReferences === true, + (config) => hasFeatureFlag(config, "secretProviders") && config?.secretReferences === true, ); - if (!isSecretsFeatureEnabled || !supported) return NO_SECRET_SOURCES; + if (!supported) return NO_SECRET_SOURCES; return (Object.entries(providers) as Array<[SecretProviderId, SecretProviderConfig]>) .filter(([, config]) => classifySecretProvider(config).kind !== "unsupported") .map(([id, config]) => ({ id, kind: config.kind, label: config.label })); @@ -151,7 +151,8 @@ function SecretCheckButton(props: { const state = check?.secretKey === secretKey ? check.state : undefined; const run = async () => { - setCheck({ secretKey, state: { status: "checking" } }); + const pending = { secretKey, state: { status: "checking" } } as const; + setCheck(pending); const response = await checkSecretSource({ environmentId, input: { source: secret } }); const next: SecretCheck = response._tag !== "Success" @@ -159,9 +160,7 @@ function SecretCheckButton(props: { : response.value._tag === "Resolved" ? { status: "resolved" } : { status: "failed", detail: response.value.detail }; - setCheck((previous) => - previous?.secretKey === secretKey ? { secretKey, state: next } : previous, - ); + setCheck((previous) => (previous === pending ? { secretKey, state: next } : previous)); }; if (!supported) return null; diff --git a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx index 3457bc2467820..338c4ff0fa111 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx @@ -4,12 +4,13 @@ import { page, userEvent } from "vite-plus/test/browser"; import { act, render } from "../../../test/render"; import { SidebarProvider } from "../ui/sidebar"; import { SettingsSidebarNav } from "./SettingsSidebarNav"; -import { SETTINGS_NAV_GROUPS, SETTINGS_SECTION_LABELS } from "./settingsSearch"; +import { settingsNavGroups, SETTINGS_SECTION_LABELS } from "./settingsSearch"; vi.mock("./useAvailableSettingsSearchItems", () => ({ useAvailableSettingsSearchItems: () => [ { id: "theme", title: "Theme", to: "/settings/appearance" }, ], + useHasSecretProvidersEnvironment: () => false, })); it("ignores composing keys in the search", async () => { @@ -76,9 +77,9 @@ it("moves Tab through every settings section", async () => { await using _screen = await renderNav(); await userEvent.click(page.getByRole("combobox", { name: "Search settings" })); - const sections = SETTINGS_NAV_GROUPS.flatMap((group) => group.paths).map( - (to) => SETTINGS_SECTION_LABELS[to], - ); + const sections = settingsNavGroups(false) + .flatMap((group) => group.paths) + .map((to) => SETTINGS_SECTION_LABELS[to]); const tabbed: string[] = []; for (let step = 0; step < sections.length; step += 1) { await userEvent.tab(); @@ -103,7 +104,7 @@ it.each([1280, 390])("names each group by a heading outside it at %ipx wide", as ); } const groups = page.getByRole("group").elements(); - expect(groups).toHaveLength(SETTINGS_NAV_GROUPS.length); + expect(groups).toHaveLength(settingsNavGroups(false).length); for (const group of groups) { const first = group.querySelector("[data-settings-section]")?.textContent; const heading = document.getElementById(group.getAttribute("aria-labelledby") ?? ""); diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index 794574d9505b4..10bc07c123dd8 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -53,13 +53,16 @@ import { scrollToSettingsTarget } from "./settingsLayout"; import { searchSettings, revealSettingsSearchTarget, - SETTINGS_NAV_GROUPS, + settingsNavGroups, SETTINGS_NAV_LABELS, SETTINGS_SECTION_LABELS, type SettingsPath, type SettingsSearchItem, } from "./settingsSearch"; -import { useAvailableSettingsSearchItems } from "./useAvailableSettingsSearchItems"; +import { + useAvailableSettingsSearchItems, + useHasSecretProvidersEnvironment, +} from "./useAvailableSettingsSearchItems"; import { handleSettingsSectionKeyDown } from "./settingsSectionNavigation"; import { workspaceAreaProps } from "../../lib/workspaceFocus"; @@ -143,6 +146,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { const [compactSearchOpen, setCompactSearchOpen] = useState(false); const [activeResultIndex, setActiveResultIndex] = useState(0); const searchableItems = useAvailableSettingsSearchItems(); + const navGroups = settingsNavGroups(useHasSecretProvidersEnvironment()); const results = searchSettings(query, searchableItems, m); const isSearching = query.trim().length > 0; const hasResults = results.length > 0; @@ -379,7 +383,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { )}
- {SETTINGS_NAV_GROUPS.map((group, index) => ( + {navGroups.map((group, index) => (
{ expect(scheduleFromDraft({ ...draft, coalesceKey: "{{body.bad" })).toBeNull(); }); +// The host locale's clock for a wall time, so these pass in any locale (digits, day period, zero padding). +function clock(hour12: boolean, hour: number, minute: number) { + return new Intl.DateTimeFormat(undefined, { + hour: "numeric", + minute: "2-digit", + hour12, + timeZone: "UTC", + }).format(Date.UTC(2000, 0, 1, hour, minute)); +} + it("appends the server zone only to fixed-time schedule labels", () => { - expect(scheduleLabel({ type: "fixed_time", timeOfDay: "16:31" }, "Etc/UTC")).toBe( - "Daily at 16:31 UTC", + expect(scheduleLabel({ type: "fixed_time", timeOfDay: "16:31" }, "24-hour", "Etc/UTC")).toBe( + `Daily at ${clock(false, 16, 31)} UTC`, + ); + expect(scheduleLabel({ type: "fixed_time", timeOfDay: "09:00" }, "24-hour")).toBe( + `Daily at ${clock(false, 9, 0)}`, + ); + expect(scheduleLabel({ type: "interval", everyMs: 60_000 }, "24-hour", "Etc/UTC")).toBe( + "Every 1 min", ); - expect(scheduleLabel({ type: "fixed_time", timeOfDay: "09:00" })).toBe("Daily at 09:00"); - expect(scheduleLabel({ type: "interval", everyMs: 60_000 }, "Etc/UTC")).toBe("Every 1 min"); - expect(scheduleLabel({ type: "webhook", signature: null }, "Etc/UTC")).toBe("On webhook"); + expect(scheduleLabel({ type: "webhook", signature: null }, "24-hour", "Etc/UTC")).toBe( + "On webhook", + ); +}); + +it("shows schedule times in the Time format setting", () => { + const daily = { type: "fixed_time", timeOfDay: "17:30" } as const; + expect(scheduleLabel(daily, "24-hour")).toBe(`Daily at ${clock(false, 17, 30)}`); + expect(scheduleLabel(daily, "12-hour")).toBe(`Daily at ${clock(true, 17, 30)}`); + const midnight = scheduleLabel({ type: "fixed_time", timeOfDay: "0:05" }, "24-hour"); + expect(midnight).toBe(`Daily at ${clock(false, 0, 5)}`); + // An h24 clock would print midnight as 24:05 in both the label and the helper. + expect(midnight).not.toContain("24"); + + // A local wall time, so the label reads 17:30 in any host zone. + const runAt = new Date(2026, 10, 20, 17, 30); + const once = { type: "once", runAt: runAt.toISOString() } as const; + for (const hour12 of [false, true]) { + const dateTime = new Intl.DateTimeFormat(undefined, { + dateStyle: "medium", + timeStyle: "short", + hour12, + }).format(runAt); + expect(scheduleLabel(once, hour12 ? "12-hour" : "24-hour")).toBe(`Once, ${dateTime}`); + } }); diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts index bbb5c146cb28a..6c7038f8ed191 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts @@ -24,6 +24,7 @@ import { type WebhookFilterDraft, } from "@t3tools/client-runtime/scheduled-task-webhook"; import { scheduleTimeZoneLabel } from "@t3tools/client-runtime/scheduled-task-time-zone"; +import type { TimestampFormat } from "@t3tools/contracts/settings"; import { msg } from "gt-react"; import { @@ -32,6 +33,7 @@ import { } from "@t3tools/shared/projectSettings"; import { getActiveLocale, m, type MessageResolver } from "../../i18n/messages"; import type { ProviderInstanceEntry } from "../../providerInstances"; +import { formatDateTimeTimestamp, formatTimeOfDay } from "../../timestampFormat"; import type { ResolvedSettingsScope } from "./settingsScope"; @@ -43,13 +45,9 @@ export function weekdayShortLabel(day: number, locale: string = getActiveLocale( ); } -const ONCE_FORMATTER = new Intl.DateTimeFormat(undefined, { - dateStyle: "medium", - timeStyle: "short", -}); - export function scheduleLabel( schedule: ScheduledTaskSchedule, + timestampFormat: TimestampFormat, timeZone?: string, runAt?: string | null, resolve: MessageResolver = m, @@ -57,7 +55,9 @@ export function scheduleLabel( ): string { if (schedule.type === "webhook") return resolve(msg("On webhook")); if (schedule.type === "once") { - return resolve(msg("Once, {time}", { time: ONCE_FORMATTER.format(new Date(schedule.runAt)) })); + return resolve( + msg("Once, {time}", { time: formatDateTimeTimestamp(schedule.runAt, timestampFormat) }), + ); } if (schedule.type === "interval") { const minutes = schedule.everyMs / 60_000; @@ -66,7 +66,7 @@ export function scheduleLabel( : resolve(msg("Every {seconds} sec", { seconds: Math.round(schedule.everyMs / 1000) })); } const weekdays = schedule.weekdays ?? []; - const time = schedule.timeOfDay; + const time = formatTimeOfDay(schedule.timeOfDay, timestampFormat); const zone = scheduleTimeZoneLabel(timeZone, runAt); if (weekdays.length === 0) { return zone === undefined diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index 3949a9109190f..4bc2c2a6317e5 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -15,18 +15,13 @@ import { isSettingsSearchScopeAvailable, movedSettingsPath, searchSettings, - SETTINGS_NAV_GROUPS, + settingsNavGroups, SETTINGS_SEARCH_ITEMS, sourceControlHostSearchItems, sourceControlHostSettingsSearchId, type SettingsSearchItem, } from "./settingsSearch"; -vi.mock("~/env", async (importOriginal) => ({ - ...(await importOriginal()), - isSecretsFeatureEnabled: false, -})); - const ITEMS: ReadonlyArray = [ { id: "word-wrap", @@ -76,9 +71,27 @@ describe("searchSettings", () => { } }); - it("hides the Secrets page from nav and search while the secrets feature is disabled", () => { - expect(SETTINGS_NAV_GROUPS.flatMap((group) => group.paths)).not.toContain("/settings/secrets"); - expect(searchSettings("1password").map((item) => item.to)).not.toContain("/settings/secrets"); + it("shows the Secrets page in nav and search only when an environment enables secret providers", () => { + const availability = { + hasCloudPublicConfig: false, + hasEnvironment: true, + hasProviderSettingsEnvironment: true, + canManageLocalBackend: false, + isWslSettingsRowVisible: false, + hasThreadAutoSettlement: false, + }; + for (const enabled of [false, true]) { + const navPaths = settingsNavGroups(enabled).flatMap((group) => group.paths); + const searchPaths = searchSettings( + "1password", + filterAvailableSettingsSearchItems({ + ...availability, + hasSecretProvidersEnvironment: enabled, + }), + ).map((item) => item.to); + expect(navPaths.includes("/settings/secrets")).toBe(enabled); + expect(searchPaths.includes("/settings/secrets")).toBe(enabled); + } }); it("finds where subagents and side chats open by any of its names", () => { diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index e891af3db0434..4252fccc9c7d0 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1,5 +1,5 @@ import { HOSTED_APP_CHANNEL } from "~/branding"; -import { isElectron, isSecretsFeatureEnabled } from "~/env"; +import { isElectron } from "~/env"; import { isMacPlatform, isWindowsPlatform, normalizeSearchText } from "~/lib/utils"; import { STATIC_KEYBINDING_COMMANDS, type KeybindingCommand } from "@t3tools/contracts"; import type { EnvironmentId } from "@t3tools/contracts"; @@ -61,7 +61,7 @@ export interface SettingsSearchItem { readonly macOnly?: boolean; readonly windowsOnly?: boolean; readonly releaseChannelOnly?: boolean; - readonly secretsFeatureOnly?: boolean; + readonly secretProvidersOnly?: boolean; readonly cloudOnly?: boolean; readonly environmentOnly?: boolean; readonly providerSettingsOnly?: boolean; @@ -91,6 +91,7 @@ export interface SettingsSearchAvailability { /** An environment without a provider allow-list, which hides text generators. */ readonly hasTextGeneratorsEnvironment?: boolean; readonly hasPrimaryEnvironment?: boolean; + readonly hasSecretProvidersEnvironment?: boolean; } export const SETTINGS_SECTION_LABELS: Readonly> = { @@ -128,12 +129,14 @@ export const SETTINGS_NAV_LABELS: Readonly> = { "/settings/access": msg("Sharing & access", { $context: "settings navigation item" }), }; -/** Sidebar order. A group with a hidden heading is set apart on screen by space alone. */ -export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ +type SettingsNavGroup = { readonly heading: string; readonly headingHidden?: true; readonly paths: ReadonlyArray; -}> = [ +}; + +/** Sidebar order. A group with a hidden heading is set apart on screen by space alone. */ +const ALL_SETTINGS_NAV_GROUPS: ReadonlyArray = [ { heading: msg("Preferences"), headingHidden: true, @@ -163,11 +166,7 @@ export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ }, { heading: msg("Connections"), - paths: [ - "/settings/connections", - "/settings/access", - ...(isSecretsFeatureEnabled ? (["/settings/secrets"] as const) : []), - ], + paths: ["/settings/connections", "/settings/access", "/settings/secrets"], }, { heading: msg("More"), @@ -176,6 +175,18 @@ export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ }, ]; +const SETTINGS_NAV_GROUPS_WITHOUT_SECRETS = ALL_SETTINGS_NAV_GROUPS.map((group) => ({ + ...group, + paths: group.paths.filter((path) => path !== "/settings/secrets"), +})); + +/** Sidebar groups; Secrets shows only when some environment's server enables secret providers. */ +export function settingsNavGroups(hasSecretProvidersEnvironment: boolean) { + return hasSecretProvidersEnvironment + ? ALL_SETTINGS_NAV_GROUPS + : SETTINGS_NAV_GROUPS_WITHOUT_SECRETS; +} + export function keybindingSearchAnchorId(command: Command) { return `keybinding-${command}` as const; } @@ -501,6 +512,7 @@ export const SETTINGS_SEARCH_ITEMS = [ targetId: "boring-sidebar", searchTerms: [msg("beta boring sidebar folder rows multiline branch pull request details")], }, + { id: "tool-call-visibility", title: msg("Tool calls in chat"), @@ -1463,7 +1475,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: msg("Secret providers"), to: "/settings/secrets", searchTerms: [msg("1password vault credentials api key")], - secretsFeatureOnly: true, + secretProvidersOnly: true, }, { id: "secret-providers-add", @@ -1471,7 +1483,7 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/secrets", targetId: "secret-providers", searchTerms: [msg("new 1password vault op cli account")], - secretsFeatureOnly: true, + secretProvidersOnly: true, }, { id: "archive", @@ -1644,7 +1656,8 @@ export function filterAvailableSettingsSearchItems( (!item.peerLinksOnly || availability.hasPeerLinkHost === true) && (!item.fastWorktreeCheckoutOnly || availability.hasFastWorktreeCheckoutEnvironment === true) && - (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true), + (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true) && + (!item.secretProvidersOnly || availability.hasSecretProvidersEnvironment === true), ); } @@ -1657,7 +1670,6 @@ export function settingsForThisPlatform( (item) => (isElectron || item.desktopOnly !== true) && (!item.releaseChannelOnly || isElectron || HOSTED_APP_CHANNEL !== null) && - (!item.secretsFeatureOnly || isSecretsFeatureEnabled) && (!item.macOnly || isMacPlatform(platform)) && (!item.windowsOnly || isWindowsPlatform(platform)), ); diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts index e6d947935bd94..beb5e3c85c52c 100644 --- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts +++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts @@ -1,4 +1,5 @@ import { useMessages } from "gt-react"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { AuthEnvironmentMaintainScope } from "@t3tools/contracts"; import { usePrimaryCloudLinkState } from "~/cloud/cloudLinkState"; @@ -17,6 +18,14 @@ import { getThreadAutoSettlementSearchAvailability, } from "./settingsSearch"; +/** Any environment whose server enables secret providers; gates the Secrets page, nav and search. */ +export function useHasSecretProvidersEnvironment() { + const { environments } = useEnvironments(); + return environments.some((environment) => + hasFeatureFlag(environment.serverConfig, "secretProviders"), + ); +} + export function useAvailableSettingsSearchItems() { const { environments } = useEnvironments(); // Explicit booleans keep flags out of the filter cache so environment updates do not rebuild the list. @@ -42,6 +51,7 @@ export function useAvailableSettingsSearchItems() { environment.serverConfig !== null && environment.serverConfig.managedPolicy?.limits?.providers?.allowedDrivers === undefined, ) === true; + const hasSecretProvidersEnvironment = useHasSecretProvidersEnvironment(); const hasThreadAutoSettlement = getThreadAutoSettlementSearchAvailability(environments).eligibleEnvironmentIds.length > 0; const primaryEnvironmentId = usePrimaryEnvironmentId(); @@ -75,5 +85,6 @@ export function useAvailableSettingsSearchItems() { hasFastWorktreeCheckoutEnvironment, hasTextGeneratorsEnvironment, hasPrimaryEnvironment: primaryEnvironmentId !== null, + hasSecretProvidersEnvironment, }); } diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx index 7b7adf7a31ea5..9e2e6a058f220 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx @@ -8,16 +8,24 @@ import { formatAssistantCitationForComposer } from "../../composer-logic"; import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { SidebarDraftBlock, useSidebarDrafts } from "./SidebarDraftBlock"; -function DraftBlock() { - const { draftIds, routeDraftComposer } = useSidebarDrafts(null, null); +const NO_TERMINAL_LABELS: ReadonlyMap = new Map(); + +function DraftBlock(props: { + routeDraftId?: string | null; + terminalLabels?: ReadonlyMap; +}) { + const routeDraftId = props.routeDraftId ?? null; + const terminalLabels = props.terminalLabels ?? NO_TERMINAL_LABELS; + const { draftIds, routeDraftComposer } = useSidebarDrafts(null, routeDraftId, terminalLabels); return ( @@ -91,3 +99,42 @@ it("keeps draft previews current through edits, promotion and removal", async () await act(() => initial.clearDraftThread(nextDraftId)); await expect.element(row).not.toBeInTheDocument(); }); + +it("lists empty drafts by terminal label while their terminal exists, active or not", async () => { + const initial = useComposerDraftStore.getState(); + using _store = { + [Symbol.dispose]: () => useComposerDraftStore.setState(initial, true), + }; + useComposerDraftStore.setState({ + draftsByThreadKey: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, + }); + const environmentId = EnvironmentId.make("draft-terminal-environment"); + const terminalDraftId = DraftId.make("draft-with-terminal"); + initial.setProjectDraftThreadId( + scopeProjectRef(environmentId, ProjectId.make("terminal-project")), + terminalDraftId, + { threadId: ThreadId.make("terminal-thread") }, + ); + initial.setProjectDraftThreadId( + scopeProjectRef(environmentId, ProjectId.make("idle-project")), + DraftId.make("draft-without-terminal"), + { threadId: ThreadId.make("idle-thread") }, + ); + + const terminalLabels = new Map([[`${environmentId}:terminal-thread`, "dev"]]); + const block = (routeDraftId: string | null) => ( +
    + +
+ ); + await using screen = await render(block(terminalDraftId)); + const rows = screen.getByTestId("sidebar-draft-row"); + await expect.element(rows).toHaveAccessibleName("dev, Unsent draft"); + expect(rows.elements()).toHaveLength(1); + + await screen.rerender(block(null)); + await expect.element(rows).toHaveAccessibleName("dev, Unsent draft"); + expect(rows.elements()).toHaveLength(1); +}); diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index 3a4a74bb64f18..4cb082a1f7ddd 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -12,8 +12,10 @@ import { type MouseEvent as ReactMouseEvent, } from "react"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentId } from "@t3tools/contracts"; import { useShallow } from "zustand/react/shallow"; import { cn } from "~/lib/utils"; +import { useTerminalLabelsByThreadKey } from "~/state/terminalSessions"; import { resolveSidebarRowAccessibility } from "../Sidebar.logic"; import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -31,9 +33,41 @@ import { JumpHintBadge, } from "./SidebarThreadRow"; +const EMPTY_COMPOSER_PARTS = { + prompt: "", + images: [], + persistedAttachments: [], + files: [], + terminalContexts: [], + previewAnnotations: [], + reviewComments: [], +} as const; + +/** Terminal labels for draft threads; an unsent draft stays listed while it has a terminal. */ +export function useDraftTerminalLabels(): ReadonlyMap { + const environmentIds = useComposerDraftStore((store) => { + const ids = new Set(); + for (const session of Object.values(store.draftThreadsByThreadKey)) { + if (session.promotedTo == null) ids.add(session.environmentId); + } + return [...ids].toSorted().join("\n"); + }); + return useTerminalLabelsByThreadKey( + environmentIds === "" ? [] : (environmentIds.split("\n") as EnvironmentId[]), + ); +} + +export function draftTerminalLabel( + session: DraftSessionState, + terminalLabels: ReadonlyMap, +): string | null { + return terminalLabels.get(`${session.environmentId}:${session.threadId}`) ?? null; +} + const SidebarDraftRow = memo(function SidebarDraftRow(props: { draftId: DraftId; - composer: ComposerThreadDraftState; + composer: ComposerThreadDraftState | null; + terminalLabel: string | null; project: ProjectFaviconProject | null; projectDisplayName: string | null; isActive: boolean; @@ -46,7 +80,8 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { source: ContextMenuSource, ) => void; }) { - const { composer, draftId, onContextMenu, onDiscard, onNavigate } = props; + const { draftId, onContextMenu, onDiscard, onNavigate } = props; + const composer = props.composer ?? EMPTY_COMPOSER_PARTS; const gt = useGT(); const promptPreview = assistantCitationsToPlainText( @@ -65,9 +100,11 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { const preview = promptPreview.length > 0 ? promptPreview - : gt("{count, plural, one {{count} attachment} other {{count} attachments}}", { - count: attachmentCount, - }); + : attachmentCount === 0 && props.terminalLabel !== null + ? props.terminalLabel + : gt("{count, plural, one {{count} attachment} other {{count} attachments}}", { + count: attachmentCount, + }); const accessibility = resolveSidebarRowAccessibility({ title: preview, statusLabel: gt("Unsent draft"), @@ -174,6 +211,7 @@ function listedDraftComposer(draftId: string | null): ComposerThreadDraftState | export function useSidebarDrafts( scopedProjectKeys: ReadonlySet | null, routeDraftId: string | null, + terminalLabels: ReadonlyMap, ): { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null } { const [frozenRoute, setFrozenRoute] = useState<{ routeDraftId: string | null; @@ -195,10 +233,12 @@ export function useSidebarDrafts( ) { continue; } + // Composer edits stay frozen while open; terminals come and go live. const isListed = - draftKey === routeDraftId + draftTerminalLabel(session, terminalLabels) !== null || + (draftKey === routeDraftId ? routeDraftComposer !== null - : composerDraftHasUserContent(store.draftsByThreadKey[draftKey]); + : composerDraftHasUserContent(store.draftsByThreadKey[draftKey])); if (isListed) listed.push([draftKey, session]); } listed.sort(([, left], [, right]) => right.createdAt.localeCompare(left.createdAt)); @@ -211,6 +251,7 @@ export function useSidebarDrafts( export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null; + terminalLabels: ReadonlyMap; jumpLabelByDraftId: ReadonlyMap | null; projectByKey: ReadonlyMap; projectDisplayNameByKey: ReadonlyMap; @@ -233,8 +274,10 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { const drafts = props.draftIds.flatMap((draftId) => { const session = draftThreadsByThreadKey[draftId]; const composer = - draftId === props.routeDraftId ? props.routeDraftComposer : draftsByThreadKey[draftId]; - return session && composer ? [{ draftId, session, composer }] : []; + (draftId === props.routeDraftId ? props.routeDraftComposer : null) ?? + draftsByThreadKey[draftId] ?? + null; + return session ? [{ draftId, session, composer }] : []; }); if (drafts.length === 0) { return null; @@ -248,6 +291,7 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { key={draftId} draftId={draftId} composer={composer} + terminalLabel={draftTerminalLabel(session, props.terminalLabels)} project={props.projectByKey.get(projectKey) ?? null} projectDisplayName={props.projectDisplayNameByKey.get(projectKey) ?? null} isActive={draftId === props.routeDraftId} diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 878cbc894bb88..2aa9be4c244a6 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -3,6 +3,7 @@ import { asLaunchingThread } from "@t3tools/client-runtime/state/thread-inbox"; import { ThreadHoverCard, ThreadHoverCardPopup } from "../ThreadHoverCard"; import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators"; import { discardComposerDraft } from "../../lib/discardComposerDraft"; +import { formatWorktreePathForDisplay } from "../../worktreeCleanup"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { requestCustomSnooze } from "../CustomSnoozeDialog"; import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests"; @@ -47,6 +48,7 @@ import { CircleDashedIcon, CircleDotDashedIcon, ClockIcon, + FolderGit2Icon, GitBranchIcon, MessageCircleQuestionIcon, PinIcon, @@ -105,7 +107,6 @@ import { resolveLocalCheckoutBranchMismatch } from "../BranchToolbar.logic"; import { ThreadPullRequestBadgeControl, ThreadPullRequestsMiniList, - ThreadWorktreeIndicator, prStatusIndicator, resolveThreadPullRequestBadge, terminalStatusFromRunningIds, @@ -285,6 +286,7 @@ function SidebarThreadTooltip({ terminalProcessCount: number; }) { const driverKind = providerEntry?.driverKind ?? null; + const worktreePath = thread.worktreePath?.trim(); const previousProviderNames = thread.providerInstanceHistory .filter((instanceId) => instanceId !== modelInstanceId) .map((instanceId) => providerEntryByInstanceId.get(instanceId)?.displayName ?? instanceId); @@ -324,6 +326,12 @@ function SidebarThreadTooltip({
) : null} + {worktreePath ? ( +
+ + +
+ ) : null} {branchMismatch ? (
@@ -575,7 +583,7 @@ function TopStatusIcon(props: { icon: keyof typeof TOP_STATUS_ICONS; className: type SidebarThreadRowProps = { thread: SidebarThreadSummary; // "folder" is a one-line row inside a boring sidebar project folder; - // "folder-multiline" adds the card's branch and PR line under it. + // "folder-multiline" adds the card's environment and PR line under it. variant: "card" | "slim" | "folder" | "folder-multiline"; navigationParent?: string | undefined; variantAction: SidebarSweepAction; @@ -598,10 +606,8 @@ type SidebarThreadRowProps = { // Read at click time; a prop would re-render every row on entering or leaving a thread route. readOpensPullRequestsInRightPanel: () => boolean; jumpLabel: string | null; - currentEnvironmentId: string | null; environmentLabel: string | null; environmentMachine: EnvironmentMachineKind; - scratchMachineLabel: string | null; project: EnvironmentProject | null; projectDisplayName: string | null; providerEntryByInstanceId: ReadonlyMap; @@ -863,9 +869,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ? getTriggerDisplayModelName(selectedModel, providerEntry?.driverKind) : thread.modelSelection.model; - const isRemote = thread.environmentId !== props.currentEnvironmentId; - const showsScratchMachine = !checkoutThread.branch && props.scratchMachineLabel !== null; - const detailsTooltip = ( - - - ) : null; const diff = latestRunDiff(thread); // Only the trailing icons would remain, so the row moves them to the title line instead. const metaLineEmpty = - !checkoutThread.branch && - !showsScratchMachine && + props.environmentLabel === null && prBadge === null && issueBadge === null && diff === null && runningTerminalIds.length === 0; const metaLine = metaLineEmpty ? null : (
- {checkoutThread.branch ? ( - <> - - - - - - ) : showsScratchMachine ? ( + {props.environmentLabel !== null ? ( <> - {props.scratchMachineLabel} + {props.environmentLabel} ) : ( @@ -1305,7 +1294,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP aria-hidden className="pointer-events-none ml-auto inline-flex shrink-0 items-center gap-1" > - {remoteMachineIcon} - {remoteMachineIcon} - {children} + {observeContent ? ( + // Base UI only observes content resizes through Content; minWidth overrides its fit-content default. + + {children} + + ) : ( + children + )} {!hideScrollbars && ( <> diff --git a/apps/web/src/components/ui/shared-tooltip.tsx b/apps/web/src/components/ui/shared-tooltip.tsx new file mode 100644 index 0000000000000..0858fa656e6bb --- /dev/null +++ b/apps/web/src/components/ui/shared-tooltip.tsx @@ -0,0 +1,262 @@ +import { + cloneElement, + createContext, + use, + useEffect, + useId, + useRef, + useState, + type FocusEvent, + type PointerEvent, + type ReactElement, + type ReactNode, +} from "react"; + +import { Tooltip, TooltipPopup, TooltipTrigger, useTooltipScrollTracker } from "./tooltip"; + +// Base UI's tooltip timing: open after a rest, reopen at once right after another closed. +const OPEN_DELAY_MS = 600; +const REOPEN_WINDOW_MS = 400; +// Time to travel from the trigger into a hoverable popup. +const CLOSE_GRACE_MS = 100; + +interface SharedTooltipContent { + readonly render: () => ReactNode; + /** Comparable key that changes whenever `render()` output changes while open. */ + readonly contentKey?: unknown; + readonly side?: "top" | "bottom" | "left" | "right"; + readonly variant?: "default" | "glass" | "code"; +} + +interface SharedTooltipState extends SharedTooltipContent { + readonly anchor: HTMLElement; + readonly open: boolean; +} + +interface SharedTooltipApi { + show(anchor: HTMLElement, content: SharedTooltipContent, immediate: boolean): void; + refresh(anchor: HTMLElement, content: SharedTooltipContent): void; + hide(anchor: HTMLElement): void; + /** A press closes it at once, as Base UI's closeOnClick does. */ + dismiss(anchor: HTMLElement): void; + holdOpen(): void; +} + +function setAriaDescribedBy(element: HTMLElement, id: string, present: boolean) { + const tokens = (element.getAttribute("aria-describedby") ?? "").split(/\s+/).filter(Boolean); + const next = present + ? tokens.includes(id) + ? tokens + : [...tokens, id] + : tokens.filter((token) => token !== id); + if (next.length > 0) element.setAttribute("aria-describedby", next.join(" ")); + else element.removeAttribute("aria-describedby"); +} + +const SharedTooltipContext = createContext(null); + +/** + * One tooltip for many triggers: a long message would otherwise mount a Base UI tooltip per + * link and file chip, and almost none of them are ever hovered. + */ +export function SharedTooltipProvider({ children }: { children: ReactNode }) { + const popupId = useId(); + const [state, setState] = useState(null); + const timer = useRef | null>(null); + const pending = useRef(null); + const lastClosedAt = useRef(0); + const current = useRef(null); + + const commit = (next: SharedTooltipState | null) => { + current.current = next; + setState(next); + }; + const clearTimer = () => { + if (timer.current !== null) clearTimeout(timer.current); + timer.current = null; + pending.current = null; + }; + const [api] = useState(() => ({ + show(anchor, content, immediate) { + clearTimer(); + const open = current.current?.open === true; + const reopen = performance.now() - lastClosedAt.current < REOPEN_WINDOW_MS; + if (immediate || open || reopen) { + commit({ ...content, anchor, open: true }); + return; + } + pending.current = { ...content, anchor, open: true }; + timer.current = setTimeout(() => { + const next = pending.current; + pending.current = null; + if (next) commit(next); + }, OPEN_DELAY_MS); + }, + refresh(anchor, content) { + if (pending.current?.anchor === anchor) { + pending.current = { ...pending.current, ...content }; + } + const active = current.current; + if (!active || active.anchor !== anchor) return; + if ( + active.contentKey === content.contentKey && + active.side === content.side && + active.variant === content.variant + ) { + return; + } + commit({ ...active, ...content }); + }, + hide(anchor) { + if (current.current && current.current.anchor !== anchor) { + clearTimer(); + return; + } + clearTimer(); + timer.current = setTimeout(() => { + if (current.current?.open) lastClosedAt.current = performance.now(); + if (current.current) commit({ ...current.current, open: false }); + }, CLOSE_GRACE_MS); + }, + dismiss(anchor) { + clearTimer(); + if (current.current?.anchor !== anchor) return; + if (current.current.open) lastClosedAt.current = 0; + commit({ ...current.current, open: false }); + }, + holdOpen() { + clearTimer(); + }, + })); + + const activeAnchor = state?.open ? state.anchor : null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links the active trigger DOM element to the shared tooltip popup via aria-describedby + useEffect(() => { + if (!activeAnchor) return; + setAriaDescribedBy(activeAnchor, popupId, true); + return () => setAriaDescribedBy(activeAnchor, popupId, false); + }, [activeAnchor, popupId]); + + return ( + + {children} + {state ? ( + { + if (!open) api.hide(state.anchor); + }} + > + api.holdOpen()} + onMouseLeave={() => api.hide(state.anchor)} + > + {state.render()} + + + ) : null} + + ); +} + +export interface SharedTooltipTriggerProps { + onPointerEnter: (event: PointerEvent) => void; + onPointerLeave: (event: PointerEvent) => void; + onFocus: (event: FocusEvent) => void; + onBlur: (event: FocusEvent) => void; + onPointerDown: (event: PointerEvent) => void; +} + +/** Props that show `content` on the shared tooltip, or null outside a SharedTooltipProvider. */ +export function useSharedTooltip(content: SharedTooltipContent): SharedTooltipTriggerProps | null { + const api = use(SharedTooltipContext); + const scrollTracker = useTooltipScrollTracker(); + const anchorRef = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes an open shared tooltip when its trigger's label changes + useEffect(() => { + if (api && anchorRef.current) api.refresh(anchorRef.current, content); + }, [api, content]); + if (!api) return null; + return { + // Touch never opens it, as Base UI's mouseOnly trigger; taps also send compatibility mouse events. + onPointerEnter: (event) => { + if (event.pointerType === "touch") return; + const trigger = event.currentTarget; + anchorRef.current = trigger; + api.show(trigger, content, false); + // Scrolling the timeline closes it, as it does a TooltipTrigger's. + scrollTracker?.hover(trigger, api, () => api.dismiss(trigger)); + }, + onPointerLeave: (event) => api.hide(event.currentTarget), + // Keyboard focus shows it at once, as Base UI does. + onFocus: (event) => { + if (event.currentTarget.matches(":focus-visible")) { + anchorRef.current = event.currentTarget; + api.show(event.currentTarget, content, true); + } + }, + onBlur: (event) => api.hide(event.currentTarget), + onPointerDown: (event) => api.dismiss(event.currentTarget), + }; +} + +type Handlers = Partial void>>; + +/** The trigger's own handlers run first, then the shared tooltip's. */ +export function withSharedTooltip( + element: ReactElement, + tooltip: SharedTooltipTriggerProps, + children?: ReactNode, +): ReactElement { + const own = element.props as Handlers; + const merged: Record void> = {}; + for (const key of Object.keys(tooltip) as Array) { + const shared = tooltip[key] as (event: never) => void; + const mine = own[key]; + merged[key] = mine + ? (event) => { + mine(event); + shared(event); + } + : shared; + } + return children === undefined + ? cloneElement(element, merged as Partial) + : cloneElement(element, merged as Partial, children); +} + +/** A tooltip on `render`: the shared one inside a SharedTooltipProvider, Base UI's otherwise. */ +export function SharedTooltipTrigger({ + render, + children, + label, + side = "top", + variant, +}: { + render: ReactElement; + children?: ReactNode; + label: ReactNode; + side?: SharedTooltipContent["side"]; + variant?: SharedTooltipContent["variant"]; +}) { + const tooltip = useSharedTooltip({ + render: () => label, + contentKey: label, + side, + ...(variant ? { variant } : {}), + }); + if (tooltip) return withSharedTooltip(render, tooltip, children); + return ( + + {children} + + {label} + + + ); +} diff --git a/apps/web/src/components/ui/tooltip.browser.test.tsx b/apps/web/src/components/ui/tooltip.browser.test.tsx index 24d76784e8a5a..bcb62ee2fdaf0 100644 --- a/apps/web/src/components/ui/tooltip.browser.test.tsx +++ b/apps/web/src/components/ui/tooltip.browser.test.tsx @@ -3,41 +3,114 @@ import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { render } from "../../../test/render"; +import { SharedTooltipProvider, SharedTooltipTrigger } from "./shared-tooltip"; import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "./tooltip"; +function TimelineAction({ shared }: { shared: boolean }) { + if (shared) { + return ( + + }> + Timeline action + + + ); + } + return ( + + Timeline action + Description + + ); +} + it.each([ - { focus: "mouse", keptOpen: false }, - { focus: "keyboard", keptOpen: true }, -])("scrolling with a $focus-focused hovered trigger keeps it open: $keptOpen", async (c) => { - const onScroll = vi.fn(); + { shared: false, focus: "mouse", keptOpen: false }, + { shared: false, focus: "keyboard", keptOpen: true }, + { shared: true, focus: "mouse", keptOpen: false }, + { shared: true, focus: "keyboard", keptOpen: true }, +])( + "scrolling with a $focus-focused hovered trigger (shared: $shared) keeps it open: $keptOpen", + async (c) => { + const onScroll = vi.fn(); + await using screen = await render( + + +
+ , + ); + const trigger = screen.getByRole("button", { name: "Timeline action" }); + if (c.focus === "mouse") { + // A press closes the tooltip; hovering again reopens it with mouse focus kept. + await userEvent.click(trigger); + await userEvent.unhover(trigger); + } else { + await userEvent.keyboard("{Tab}"); + } + await userEvent.hover(trigger); + await expect.element(trigger).toHaveFocus(); + await expect.element(page.getByText("Description")).toBeVisible(); + + // One pixel keeps the pointer over the trigger, so only the scroll can close it. + screen.getByTestId("timeline").element().scrollTop = 1; + await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); + + if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); + else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); + }, +); + +it("refreshes an open shared tooltip's label and links aria-describedby on focus", async () => { await using screen = await render( - - - Timeline action - Description - -
- , + + }> + Copy + + , ); - const trigger = screen.getByRole("button", { name: "Timeline action" }); - if (c.focus === "mouse") { - // A press closes the tooltip; hovering again reopens it with mouse focus kept. - await userEvent.click(trigger); - await userEvent.unhover(trigger); - } else { - await userEvent.keyboard("{Tab}"); - } - await userEvent.hover(trigger); + const trigger = screen.getByRole("button", { name: "Copy" }); + await userEvent.keyboard("{Tab}"); await expect.element(trigger).toHaveFocus(); - await expect.element(page.getByText("Description")).toBeVisible(); + const popup = page.getByText("Copy code"); + await expect.element(popup).toBeVisible(); + const popupId = trigger.element().getAttribute("aria-describedby"); + expect(popupId).toBeTruthy(); + expect(document.getElementById(popupId!)?.textContent).toBe("Copy code"); - screen.getByTestId("timeline").element().scrollTop = 20; - await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); + await screen.rerender( + + }> + Copy + + , + ); + await expect.element(page.getByText("Copied")).toBeVisible(); + + await userEvent.keyboard("{Tab}"); + await vi.waitFor(() => expect(trigger.element().getAttribute("aria-describedby")).toBeNull()); +}); - if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); - else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); +it("refreshes a pending shared tooltip if its label changes during the open delay", async () => { + await using screen = await render( + + }> + Copy + + , + ); + const trigger = screen.getByRole("button", { name: "Copy" }); + await userEvent.hover(trigger); + await screen.rerender( + + }> + Copy + + , + ); + await expect.element(page.getByText("Copy code")).toBeVisible(); + expect(page.getByText("Copied").query()).toBeNull(); }); diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx index 577aa48da87fa..e47a6b8d13afe 100644 --- a/apps/web/src/components/ui/tooltip.tsx +++ b/apps/web/src/components/ui/tooltip.tsx @@ -21,13 +21,13 @@ type TooltipActionsRef = RefObject; // The compiler freezes context values; update hovered tooltips through calls instead of shared ref writes. function createTooltipHoverTracker() { - let hovered: { trigger: HTMLElement; actionsRef: TooltipActionsRef } | null = null; + let hovered: { trigger: HTMLElement; owner: object; close: () => void } | null = null; return { - hover(trigger: HTMLElement, actionsRef: TooltipActionsRef) { - hovered = { trigger, actionsRef }; + hover(trigger: HTMLElement, owner: object, close: () => void) { + hovered = { trigger, owner, close }; }, - release(actionsRef: TooltipActionsRef) { - if (hovered?.actionsRef === actionsRef) hovered = null; + release(owner: object) { + if (hovered?.owner === owner) hovered = null; }, dismissUnfocused() { const tooltip = hovered; @@ -37,8 +37,7 @@ function createTooltipHoverTracker() { return; } hovered = null; - // Base UI also cancels delayed hover opens through this action. - tooltip.actionsRef.current?.close(); + tooltip.close(); }, }; } @@ -96,7 +95,8 @@ function TooltipTrigger(props: TooltipPrimitive.Trigger.Props) { {...props} onMouseEnter={(event) => { props.onMouseEnter?.(event); - tracker.hover(event.currentTarget, actionsRef); + // Base UI also cancels delayed hover opens through this action. + tracker.hover(event.currentTarget, actionsRef, () => actionsRef.current?.close()); }} /> ); @@ -161,4 +161,14 @@ function TooltipPopup({ ); } -export { TooltipProvider, Tooltip, TooltipTrigger, TooltipPopup, TooltipScrollDismissArea }; +/** The enclosing TooltipScrollDismissArea's tracker, for triggers that bypass TooltipTrigger. */ +const useTooltipScrollTracker = () => use(TooltipScrollContext); + +export { + TooltipProvider, + Tooltip, + TooltipTrigger, + TooltipPopup, + TooltipScrollDismissArea, + useTooltipScrollTracker, +}; diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index adb05afb92ebb..326b592e823db 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -519,7 +519,7 @@ export function UsagePage() { - + {selectedEnvironments.length === 0 ? (

diff --git a/apps/web/src/composer-editor-mentions.ts b/apps/web/src/composer-editor-mentions.ts index 7f3e93b821488..6608d3b2a0439 100644 --- a/apps/web/src/composer-editor-mentions.ts +++ b/apps/web/src/composer-editor-mentions.ts @@ -7,6 +7,7 @@ import { composerMathRanges, type ComposerInlineToken, } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "~/markdown/wordsHast"; export type ComposerPromptSegment = | { @@ -89,7 +90,7 @@ function collectModelTokens(text: string, inlineTokens: ReadonlyArray !taken.some((range) => mention.start < range.end && mention.end > range.start), @@ -98,7 +99,7 @@ function collectModelTokens(text: string, inlineTokens: ReadonlyArray = []; for (const formula of formulas) { diff --git a/apps/web/src/env.ts b/apps/web/src/env.ts index a0a28c5d7fd60..be2a563d736bd 100644 --- a/apps/web/src/env.ts +++ b/apps/web/src/env.ts @@ -1,6 +1,2 @@ // Preload installs desktopBridge before web code runs, so module-load detection is reliable. export const isElectron = typeof window !== "undefined" && window.desktopBridge !== undefined; - -export const isSecretsFeatureEnabled = ["1", "true"].includes( - import.meta.env.T3CODE_FEATURE_SECRETS?.trim().toLowerCase() ?? "", -); diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index c7095b8536469..0db2fb8989ce2 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} an", "77cc5f738cb7d459": "{label} aus", - "2159a4897d4a4d73": "{runtime, select, codex {Aktualisiere die Codex CLI auf {version} oder neuer, um {names} zu verwenden.} other {Aktualisiere {providerName} auf {version} oder neuer, um {names} zu verwenden.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} erfordert die Codex CLI {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere die Codex CLI auf anderem Weg oder warte auf ein neueres Release.} other {{names} erfordert {providerName} {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere {providerName} auf anderem Weg oder warte auf ein neueres Release.}}", "aba3bb73ce212f0c": "{names} erfordert {providerName} {version} oder neuer, aber der Homebrew-Cask claude-code hat nur {latestVersion}. Wechsle zum Cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} erfordert die Codex CLI {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere die Codex CLI auf anderem Weg oder warte auf ein neueres Release.} other {{names} erfordert {providerName} {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere {providerName} auf anderem Weg oder warte auf ein neueres Release.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Aktualisiere die Codex CLI auf {version} oder neuer, um {names} zu verwenden.} other {Aktualisiere {providerName} auf {version} oder neuer, um {names} zu verwenden.}}", "d887bea446534de5": "Kein Projekt in dieser Umgebung kann {host}/{repository} lesen.", "4e466d60e2f7736b": "Füge die vollständige Pull-Request-URL ein. Dieser Thread hat kein Repository, in dem die Nummer aufgelöst werden kann.", "302625058bacbe38": "Füge eine vollständige URL ein. Für den Host dieses Projekts ist kein {changeRequest}-URL-Format bekannt.", @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} konnte keine WebSocket-Verbindung herstellen.", "d9ce6c142a485959": "{host} hat {seconds} s lang nicht geantwortet.", "d6bdce8f4e6101a4": "{host} wurde getrennt.", + "8450a95e5214d199": "{host} hat ein Update der Serverkonfiguration gesendet, das dieser Client nicht lesen konnte.", + "56b4ff3993c93eca": "{host} hat eine inkompatible Serverkonfiguration gesendet.", + "368c4d4f99c66bfb": "Aktualisiere Client und Server auf kompatible Versionen.", "e5fd422e445391fc": "Upload fehlgeschlagen. Zum Wiederholen tippen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2561,10 +2564,9 @@ }, " installieren" ], + "b4b98a0287c282e2": "Auf einem anderen Rechner, daher kann der Agent dieses Rechners es nicht lesen. Entferne es oder wechsle zum Senden zurück.", "5bbac0e5afeec779": "Aktueller Thread", "33c7e68fca089036": "Thread, {title}", - "b4b98a0287c282e2": "Auf einem anderen Rechner, daher kann der Agent dieses Rechners es nicht lesen. Entferne es oder wechsle zum Senden zurück.", - "c6196d99000642b4": "Thread öffnen", "34cc63390ad793cc": "Thread wählen", "8f12309ead62e38a": "Threads oder Projekte durchsuchen...", "2f664754d005d9a7": "Keine aktiven Threads gefunden.", @@ -2574,6 +2576,7 @@ "a3178769f8308cbc": "Thread fehlgeschlagen", "89b5e8f3887812da": "Gastanfrage", "62e626804919b294": "Eingabe nötig", + "c6196d99000642b4": "Thread öffnen", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", @@ -2597,8 +2600,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Terminal-Prozess läuft", "fc2c9a91f498ad6b": "{count, plural, one {{count} Terminal-Prozess läuft. Terminal öffnen} other {{count} Terminal-Prozesse laufen. Terminal öffnen}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "Stack", "6831e9a46cbd8939": "Kette", "9aa9e74a3b7eee91": "Zum Chat hinzufügen", @@ -3035,8 +3036,8 @@ "6f85f14f35b3f547": "{provider} über {environment}", "7c59a888a062a8bd": "Die Spracheingabe hat keinen Entwurf, in den sie aufnehmen kann.", "62450481c00d2ef3": "Die Umgebung des Entwurfs ist für die Transkriptbereinigung nicht verfügbar.", - "c64cb58d9cecbcd2": "Transkriptbereinigung fehlgeschlagen", "0674544195fcdc39": "Das ursprüngliche Transkript wurde eingefügt.", + "c64cb58d9cecbcd2": "Transkriptbereinigung fehlgeschlagen", "296496693cdac0db": "Der t3-Befehl ist nicht verfügbar.", "efbcef7bc9bbda01": "Der Status des t3-Befehls konnte nicht geladen werden.", "1bf6910332426e62": "Netzwerkzugriff des Desktops ist nicht verfügbar.", @@ -3279,6 +3280,7 @@ "4d493d0bda4d403d": "Hänge die unterbrochene Datei erneut an oder entferne sie", "c9cad1d84d5f1a32": "Hänge die unterbrochenen Dateien erneut an oder entferne sie", "536a820f2ff726da": "Wähle mindestens ein Modell.", + "48d6389202ad6754": "Wird gesendet, sobald bereit", "fbafbe78b5e37966": "Thread fortsetzen", "bcd7eb979dd38dae": "Eingabefeld öffnen, um zu komprimieren und zu senden", "95ee62a0d6968b89": "Nachricht senden", @@ -3455,6 +3457,9 @@ "e778e4f446fdf873": "Deine nächste Nachricht startet eine neue Sitzung", "0e2f2da4f2d94785": "Der Agent sieht frühere Nachrichten in diesem Thread nicht.", "e1189d2e582b008d": "Aktuelle Sitzung behalten", + "2bb448d605877a22": "Zum Abbrechen bearbeiten oder Esc drücken", + "1a1f128d70c62304": "{count, plural, one {Wird gesendet, sobald das Bild bereit ist} other {Wird gesendet, sobald {count} Bilder bereit sind}}", + "5af3ab719a9725fb": "Nachricht wird gesendet", "461c9f865f2e9b92": "{option} an", "f2aa17b5c620f2a4": "{option} aus", "f59314a884aae1ff": "Standard", @@ -3694,7 +3699,6 @@ "7c1923203049d602": "Code kopieren", "637817e4ff79c90e": "Aktionen für Codeblock", "ebf3a2b1e314aa5f": "Im Terminal ausführen", - "fe219642547fa0bf": "Im Terminal ausführen", "122a8512abc51180": "Details", "58c38c65c2783c5d": "Vollständiger Pfad", "f37e7d36b51c5b28": "Relativen Pfad kopieren", @@ -3706,10 +3710,6 @@ "4967584e8d0fb1c2": "Medienvorschau", "67589dd912eacb7c": "Im integrierten Browser öffnen", "a3c98d4c4b24cecb": "Dateioptionen für {label}", - "b4fe8a076e9fd2f8": "Abgesetzte Formel", - "085d1407e8c92cce": "Formel im Text", - "a2ef393fa7b48ae8": "Abgesetzte Formel scrollen", - "e94685ea5642e088": "Formel im Text scrollen", "3a04583c8500e23d": "Diagramm anzeigen", "16d64f650840fe06": "Code anzeigen", "6d329f7d3a50c7e7": "Tabelle kopieren", @@ -3988,9 +3988,11 @@ "973e99fa86d7f531": "Eingereihte Nachricht {position} von {total}, nicht gesendet", "0f6087c4f53c7f17": "Eine Runde mit dieser Nachricht starten ({shortcut})", "adab89933af02669": "Komprimierung überspringen und diese Nachricht senden ({shortcut})", + "d8aaf932f90429c4": "Diesen Befehl an den Anfang der Warteschlange verschieben ({shortcut})", "3de4016452e8d2bd": "In die aktuelle Runde senden ({shortcut})", "259cc9568148e8ad": "Eine Runde mit dieser Nachricht starten", "bb7fddb812d5d29e": "Komprimierung überspringen und diese Nachricht senden", + "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben", "a5fe1ee609b29a9f": "In die aktuelle Runde senden", "2b7fd345e4f4fd6e": "Bearbeiten der eingereihten Nachricht abbrechen", "47f1726bf106d2c8": "Eingereihte Nachricht bearbeiten", @@ -12458,7 +12460,5 @@ "27d76249d09eb69f": "Review-Leitfaden bereit", "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", - "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", - "d8aaf932f90429c4": "Diesen Befehl an den Anfang der Warteschlange verschieben ({shortcut})", - "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben" + "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 2ff8148bb7329..3aa61a18f6b2b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} On", "77cc5f738cb7d459": "{label} Off", - "2159a4897d4a4d73": "{runtime, select, codex {Update the Codex CLI to {version} or newer to use {names}.} other {Update {providerName} to {version} or newer to use {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Using {names} requires the Codex CLI {version} or newer, but the newest this install can update to is {latestVersion}. Install the Codex CLI another way or wait for a newer release.} other {Using {names} requires {providerName} {version} or newer, but the newest this install can update to is {latestVersion}. Install {providerName} another way or wait for a newer release.}}", "aba3bb73ce212f0c": "Using {names} requires {providerName} {version} or newer, but the claude-code Homebrew cask only has {latestVersion}. Switch to the claude-code@latest cask: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Using {names} requires the Codex CLI {version} or newer, but the newest this install can update to is {latestVersion}. Install the Codex CLI another way or wait for a newer release.} other {Using {names} requires {providerName} {version} or newer, but the newest this install can update to is {latestVersion}. Install {providerName} another way or wait for a newer release.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Update the Codex CLI to {version} or newer to use {names}.} other {Update {providerName} to {version} or newer to use {names}.}}", "d887bea446534de5": "No project in this environment can read {host}/{repository}.", "4e466d60e2f7736b": "Paste the full pull request URL; this thread has no repository to resolve the number against.", "302625058bacbe38": "Paste a full URL; this project's host has no known {changeRequest} URL.", @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} could not establish a WebSocket connection.", "d9ce6c142a485959": "{host} stopped responding for {seconds}s.", "d6bdce8f4e6101a4": "{host} disconnected.", + "8450a95e5214d199": "{host} sent a server configuration update this client could not read.", + "56b4ff3993c93eca": "{host} sent an incompatible server configuration.", + "368c4d4f99c66bfb": "Update the client and server to compatible versions.", "e5fd422e445391fc": "Upload failed. Tap to retry.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2560,10 +2563,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "On another machine, so this machine's agent can't read it. Remove it or switch back to send.", "5bbac0e5afeec779": "Current thread", "33c7e68fca089036": "Thread, {title}", - "b4b98a0287c282e2": "On another machine, so this machine's agent can't read it. Remove it or switch back to send.", - "c6196d99000642b4": "Open thread", "34cc63390ad793cc": "Choose a thread", "8f12309ead62e38a": "Search threads or projects...", "2f664754d005d9a7": "No active threads found.", @@ -2573,6 +2575,7 @@ "a3178769f8308cbc": "Thread failed", "89b5e8f3887812da": "Guest request", "62e626804919b294": "Input needed", + "c6196d99000642b4": "Open thread", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "You:", "a1fbf2422c588292": "Agent:", @@ -2596,8 +2599,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Terminal process running", "fc2c9a91f498ad6b": "{count, plural, one {{count} terminal process running. Open terminal} other {{count} terminal processes running. Open terminal}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "stack", "6831e9a46cbd8939": "chain", "9aa9e74a3b7eee91": "Add to chat", @@ -3034,8 +3035,8 @@ "6f85f14f35b3f547": "{provider} via {environment}", "7c59a888a062a8bd": "Voice input has no draft to record into.", "62450481c00d2ef3": "The draft's environment is unavailable for transcript cleanup.", - "c64cb58d9cecbcd2": "Transcript cleanup failed", "0674544195fcdc39": "The original transcript was added.", + "c64cb58d9cecbcd2": "Transcript cleanup failed", "296496693cdac0db": "The t3 command is unavailable.", "efbcef7bc9bbda01": "Failed to load the t3 command state.", "1bf6910332426e62": "Desktop network access is unavailable.", @@ -3278,6 +3279,7 @@ "4d493d0bda4d403d": "Attach the interrupted file again or remove it", "c9cad1d84d5f1a32": "Attach the interrupted files again or remove them", "536a820f2ff726da": "Select at least one model.", + "48d6389202ad6754": "Sending when ready", "fbafbe78b5e37966": "Resume thread", "bcd7eb979dd38dae": "Open composer to compact and send", "95ee62a0d6968b89": "Send message", @@ -3454,6 +3456,9 @@ "e778e4f446fdf873": "Your next message starts a fresh session", "0e2f2da4f2d94785": "The agent won't see earlier messages in this thread.", "e1189d2e582b008d": "Keep the current session", + "2bb448d605877a22": "Edit or press Esc to cancel", + "1a1f128d70c62304": "{count, plural, one {Sending once image is ready} other {Sending once {count} images are ready}}", + "5af3ab719a9725fb": "Sending message", "461c9f865f2e9b92": "{option} On", "f2aa17b5c620f2a4": "{option} Off", "f59314a884aae1ff": "Default", @@ -3693,7 +3698,6 @@ "7c1923203049d602": "Copy code", "637817e4ff79c90e": "Code block actions", "ebf3a2b1e314aa5f": "Run in terminal", - "fe219642547fa0bf": "Run in terminal", "122a8512abc51180": "Details", "58c38c65c2783c5d": "Full path", "f37e7d36b51c5b28": "Copy relative path", @@ -3705,10 +3709,6 @@ "4967584e8d0fb1c2": "Preview media", "67589dd912eacb7c": "Open in integrated browser", "a3c98d4c4b24cecb": "File options for {label}", - "b4fe8a076e9fd2f8": "Display equation", - "085d1407e8c92cce": "Inline equation", - "a2ef393fa7b48ae8": "Scroll display equation", - "e94685ea5642e088": "Scroll inline equation", "3a04583c8500e23d": "Show diagram", "16d64f650840fe06": "Show code", "6d329f7d3a50c7e7": "Copy table", @@ -3986,9 +3986,11 @@ "973e99fa86d7f531": "Queued message {position} of {total}, not sent", "0f6087c4f53c7f17": "Start a turn with this message ({shortcut})", "adab89933af02669": "Skip compaction and send this message ({shortcut})", + "d8aaf932f90429c4": "Move this command to the front of the queue ({shortcut})", "3de4016452e8d2bd": "Send into the current turn ({shortcut})", "259cc9568148e8ad": "Start a turn with this message", "bb7fddb812d5d29e": "Skip compaction and send this message", + "425ab15036aec8a4": "Move this command to the front of the queue", "a5fe1ee609b29a9f": "Send into the current turn", "2b7fd345e4f4fd6e": "Cancel editing queued message", "47f1726bf106d2c8": "Edit queued message", @@ -12467,7 +12469,5 @@ "27d76249d09eb69f": "Review guide ready", "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", - "9e91e9a77b664e4e": "Could not start a review guide", - "d8aaf932f90429c4": "Move this command to the front of the queue ({shortcut})", - "425ab15036aec8a4": "Move this command to the front of the queue" + "9e91e9a77b664e4e": "Could not start a review guide" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 78c68c4c0dc2f..60ddca69b570f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} activado", "77cc5f738cb7d459": "{label} desactivado", - "2159a4897d4a4d73": "{runtime, select, codex {Actualiza la CLI de Codex a {version} o posterior para usar {names}.} other {Actualiza {providerName} a {version} o posterior para usar {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Para usar {names} se necesita la CLI de Codex {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala la CLI de Codex de otra forma o espera a una versión más reciente.} other {Para usar {names} se necesita {providerName} {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala {providerName} de otra forma o espera a una versión más reciente.}}", "aba3bb73ce212f0c": "Usar {names} requiere {providerName} {version} o posterior, pero el cask de Homebrew claude-code solo tiene {latestVersion}. Cambia al cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Para usar {names} se necesita la CLI de Codex {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala la CLI de Codex de otra forma o espera a una versión más reciente.} other {Para usar {names} se necesita {providerName} {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala {providerName} de otra forma o espera a una versión más reciente.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Actualiza la CLI de Codex a {version} o posterior para usar {names}.} other {Actualiza {providerName} a {version} o posterior para usar {names}.}}", "d887bea446534de5": "Ningún proyecto de este entorno puede leer {host}/{repository}.", "4e466d60e2f7736b": "Pega la URL completa de la pull request; este hilo no tiene ningún repositorio con el que resolver el número.", "302625058bacbe38": "Pega una URL completa; el host de este proyecto no tiene una URL de {changeRequest} conocida.", @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} no pudo establecer una conexión WebSocket.", "d9ce6c142a485959": "{host} dejó de responder durante {seconds} s.", "d6bdce8f4e6101a4": "{host} se desconectó.", + "8450a95e5214d199": "{host} envió una actualización de la configuración del servidor que este cliente no pudo leer.", + "56b4ff3993c93eca": "{host} envió una configuración del servidor incompatible.", + "368c4d4f99c66bfb": "Actualiza el cliente y el servidor a versiones compatibles.", "e5fd422e445391fc": "Error al subir. Toca para reintentar.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2560,10 +2563,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Está en otra máquina, así que el agente de esta máquina no puede leerlo. Quítalo o vuelve a cambiar para enviar.", "5bbac0e5afeec779": "Hilo actual", "33c7e68fca089036": "Hilo, {title}", - "b4b98a0287c282e2": "Está en otra máquina, así que el agente de esta máquina no puede leerlo. Quítalo o vuelve a cambiar para enviar.", - "c6196d99000642b4": "Abrir hilo", "34cc63390ad793cc": "Elige un hilo", "8f12309ead62e38a": "Buscar hilos o proyectos...", "2f664754d005d9a7": "No se encontraron hilos activos.", @@ -2573,6 +2575,7 @@ "a3178769f8308cbc": "El hilo falló", "89b5e8f3887812da": "Solicitud de invitado", "62e626804919b294": "Se necesita una respuesta", + "c6196d99000642b4": "Abrir hilo", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Tú:", "a1fbf2422c588292": "Agente:", @@ -2596,8 +2599,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Proceso de terminal en ejecución", "fc2c9a91f498ad6b": "{count, plural, one {{count} proceso de terminal en ejecución. Abrir terminal} other {{count} procesos de terminal en ejecución. Abrir terminal}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "pila", "6831e9a46cbd8939": "cadena", "9aa9e74a3b7eee91": "Añadir al chat", @@ -3034,8 +3035,8 @@ "6f85f14f35b3f547": "{provider} a través de {environment}", "7c59a888a062a8bd": "La entrada de voz no tiene ningún borrador en el que grabar.", "62450481c00d2ef3": "El entorno del borrador no está disponible para limpiar la transcripción.", - "c64cb58d9cecbcd2": "Falló la limpieza de la transcripción", "0674544195fcdc39": "Se añadió la transcripción original.", + "c64cb58d9cecbcd2": "Falló la limpieza de la transcripción", "296496693cdac0db": "El comando t3 no está disponible.", "efbcef7bc9bbda01": "No se pudo cargar el estado del comando t3.", "1bf6910332426e62": "El acceso a la red del escritorio no está disponible.", @@ -3278,6 +3279,7 @@ "4d493d0bda4d403d": "Vuelve a adjuntar el archivo interrumpido o quítalo", "c9cad1d84d5f1a32": "Vuelve a adjuntar los archivos interrumpidos o quítalos", "536a820f2ff726da": "Selecciona al menos un modelo.", + "48d6389202ad6754": "Se enviará cuando esté listo", "fbafbe78b5e37966": "Reanudar hilo", "bcd7eb979dd38dae": "Abrir el cuadro de mensaje para compactar y enviar", "95ee62a0d6968b89": "Enviar mensaje", @@ -3454,6 +3456,9 @@ "e778e4f446fdf873": "Tu próximo mensaje inicia una sesión nueva", "0e2f2da4f2d94785": "El agente no verá los mensajes anteriores de este hilo.", "e1189d2e582b008d": "Mantener la sesión actual", + "2bb448d605877a22": "Edita o pulsa Esc para cancelar", + "1a1f128d70c62304": "{count, plural, one {Se enviará cuando la imagen esté lista} other {Se enviará cuando {count} imágenes estén listas}}", + "5af3ab719a9725fb": "Enviando mensaje", "461c9f865f2e9b92": "{option} activado", "f2aa17b5c620f2a4": "{option} desactivado", "f59314a884aae1ff": "Predeterminado", @@ -3693,7 +3698,6 @@ "7c1923203049d602": "Copiar código", "637817e4ff79c90e": "Acciones del bloque de código", "ebf3a2b1e314aa5f": "Ejecutar en la terminal", - "fe219642547fa0bf": "Ejecutar en la terminal", "122a8512abc51180": "Detalles", "58c38c65c2783c5d": "Ruta completa", "f37e7d36b51c5b28": "Copiar ruta relativa", @@ -3705,10 +3709,6 @@ "4967584e8d0fb1c2": "Vista previa del contenido", "67589dd912eacb7c": "Abrir en el navegador integrado", "a3c98d4c4b24cecb": "Opciones de archivo de {label}", - "b4fe8a076e9fd2f8": "Ecuación en bloque", - "085d1407e8c92cce": "Ecuación en línea", - "a2ef393fa7b48ae8": "Desplazar la ecuación en bloque", - "e94685ea5642e088": "Desplazar la ecuación en línea", "3a04583c8500e23d": "Mostrar diagrama", "16d64f650840fe06": "Mostrar código", "6d329f7d3a50c7e7": "Copiar tabla", @@ -3984,9 +3984,11 @@ "973e99fa86d7f531": "Mensaje en cola {position} de {total}, sin enviar", "0f6087c4f53c7f17": "Iniciar un turno con este mensaje ({shortcut})", "adab89933af02669": "Omitir la compactación y enviar este mensaje ({shortcut})", + "d8aaf932f90429c4": "Mover este comando al principio de la cola ({shortcut})", "3de4016452e8d2bd": "Enviar al turno actual ({shortcut})", "259cc9568148e8ad": "Iniciar un turno con este mensaje", "bb7fddb812d5d29e": "Omitir la compactación y enviar este mensaje", + "425ab15036aec8a4": "Mover este comando al principio de la cola", "a5fe1ee609b29a9f": "Enviar al turno actual", "2b7fd345e4f4fd6e": "Cancelar la edición del mensaje en cola", "47f1726bf106d2c8": "Editar mensaje en cola", @@ -12453,7 +12455,5 @@ "27d76249d09eb69f": "Guía de revisión lista", "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", - "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", - "d8aaf932f90429c4": "Mover este comando al principio de la cola ({shortcut})", - "425ab15036aec8a4": "Mover este comando al principio de la cola" + "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 873767a296ba5..fdcba31a1032f 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} activé", "77cc5f738cb7d459": "{label} désactivé", - "2159a4897d4a4d73": "{runtime, select, codex {Mettez à jour la CLI Codex vers la version {version} ou ultérieure pour utiliser {names}.} other {Mettez à jour {providerName} vers la version {version} ou ultérieure pour utiliser {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} nécessite la CLI Codex {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez la CLI Codex autrement ou attendez une nouvelle version.} other {{names} nécessite {providerName} {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez {providerName} autrement ou attendez une nouvelle version.}}", "aba3bb73ce212f0c": "{names} nécessite {providerName} {version} ou une version plus récente, mais le cask Homebrew claude-code ne propose que {latestVersion}. Passe au cask claude-code@latest : {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} nécessite la CLI Codex {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez la CLI Codex autrement ou attendez une nouvelle version.} other {{names} nécessite {providerName} {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez {providerName} autrement ou attendez une nouvelle version.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Mettez à jour la CLI Codex vers la version {version} ou ultérieure pour utiliser {names}.} other {Mettez à jour {providerName} vers la version {version} ou ultérieure pour utiliser {names}.}}", "d887bea446534de5": "Aucun projet de cet environnement ne peut lire {host}/{repository}.", "4e466d60e2f7736b": "Collez l’URL complète de la pull request ; ce fil n’a pas de dépôt auquel rattacher le numéro.", "302625058bacbe38": "Collez une URL complète ; l’hôte de ce projet n’a pas de format d’URL connu pour {changeRequest}.", @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} n’a pas pu établir de connexion WebSocket.", "d9ce6c142a485959": "{host} ne répond plus depuis {seconds} s.", "d6bdce8f4e6101a4": "{host} est déconnecté.", + "8450a95e5214d199": "{host} a envoyé une mise à jour de la configuration du serveur que ce client n’a pas pu lire.", + "56b4ff3993c93eca": "{host} a envoyé une configuration de serveur incompatible.", + "368c4d4f99c66bfb": "Mettez à jour le client et le serveur vers des versions compatibles.", "e5fd422e445391fc": "Échec de l’envoi. Touchez pour réessayer.", "b2bc6bd92ea24e5c": "{size} Mo", "88f84178edbb7f57": "{size} Ko", @@ -2560,10 +2563,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Sur une autre machine, l’agent de cette machine ne peut donc pas le lire. Retirez-le ou revenez en arrière pour envoyer.", "5bbac0e5afeec779": "Fil actuel", "33c7e68fca089036": "Fil, {title}", - "b4b98a0287c282e2": "Sur une autre machine, l’agent de cette machine ne peut donc pas le lire. Retirez-le ou revenez en arrière pour envoyer.", - "c6196d99000642b4": "Ouvrir le fil", "34cc63390ad793cc": "Choisir un fil", "8f12309ead62e38a": "Rechercher des fils ou des projets...", "2f664754d005d9a7": "Aucun fil actif trouvé.", @@ -2573,6 +2575,7 @@ "a3178769f8308cbc": "Échec du fil", "89b5e8f3887812da": "Demande d’invité", "62e626804919b294": "Réponse requise", + "c6196d99000642b4": "Ouvrir le fil", "826cb862b4a11fb3": "{label} :", "3e597ec938e7551b": "Vous :", "a1fbf2422c588292": "Agent :", @@ -2596,8 +2599,6 @@ "3260b22f72f7effb": "{tooltipLead} : {title}", "feac8e54b30c5a03": "Processus du terminal en cours", "fc2c9a91f498ad6b": "{count, plural, one {{count} processus de terminal en cours. Ouvrir le terminal} other {{count} processus de terminal en cours. Ouvrir le terminal}}", - "643c4b50feadc874": "Worktree : {path} ({branch})", - "fb7c44da0f0825ea": "Worktree : {path}", "56f37ff8ca568059": "pile", "6831e9a46cbd8939": "chaîne", "9aa9e74a3b7eee91": "Ajouter à la discussion", @@ -3034,8 +3035,8 @@ "6f85f14f35b3f547": "{provider} via {environment}", "7c59a888a062a8bd": "La saisie vocale n’a aucun brouillon dans lequel enregistrer.", "62450481c00d2ef3": "L’environnement du brouillon n’est pas disponible pour nettoyer la transcription.", - "c64cb58d9cecbcd2": "Échec du nettoyage de la transcription", "0674544195fcdc39": "La transcription d’origine a été ajoutée.", + "c64cb58d9cecbcd2": "Échec du nettoyage de la transcription", "296496693cdac0db": "La commande t3 n’est pas disponible.", "efbcef7bc9bbda01": "Échec du chargement de l’état de la commande t3.", "1bf6910332426e62": "L’accès réseau de l’app desktop n’est pas disponible.", @@ -3278,6 +3279,7 @@ "4d493d0bda4d403d": "Joignez à nouveau le fichier interrompu ou retirez-le", "c9cad1d84d5f1a32": "Joignez à nouveau les fichiers interrompus ou retirez-les", "536a820f2ff726da": "Sélectionnez au moins un modèle.", + "48d6389202ad6754": "Envoi dès que prêt", "fbafbe78b5e37966": "Reprendre le fil", "bcd7eb979dd38dae": "Ouvrir la zone de saisie pour compacter et envoyer", "95ee62a0d6968b89": "Envoyer le message", @@ -3454,6 +3456,9 @@ "e778e4f446fdf873": "Votre prochain message démarre une nouvelle session", "0e2f2da4f2d94785": "L’agent ne verra pas les messages précédents de ce fil.", "e1189d2e582b008d": "Garder la session actuelle", + "2bb448d605877a22": "Modifiez ou appuyez sur Échap pour annuler", + "1a1f128d70c62304": "{count, plural, one {Envoi dès que l’image est prête} other {Envoi dès que les {count} images sont prêtes}}", + "5af3ab719a9725fb": "Envoi du message", "461c9f865f2e9b92": "{option} activé", "f2aa17b5c620f2a4": "{option} désactivé", "f59314a884aae1ff": "Par défaut", @@ -3693,7 +3698,6 @@ "7c1923203049d602": "Copier le code", "637817e4ff79c90e": "Actions du bloc de code", "ebf3a2b1e314aa5f": "Exécuter dans le terminal", - "fe219642547fa0bf": "Exécuter dans le terminal", "122a8512abc51180": "Détails", "58c38c65c2783c5d": "Chemin complet", "f37e7d36b51c5b28": "Copier le chemin relatif", @@ -3705,10 +3709,6 @@ "4967584e8d0fb1c2": "Aperçu du média", "67589dd912eacb7c": "Ouvrir dans le navigateur intégré", "a3c98d4c4b24cecb": "Options du fichier {label}", - "b4fe8a076e9fd2f8": "Équation en bloc", - "085d1407e8c92cce": "Équation en ligne", - "a2ef393fa7b48ae8": "Faire défiler l’équation en bloc", - "e94685ea5642e088": "Faire défiler l’équation en ligne", "3a04583c8500e23d": "Afficher le diagramme", "16d64f650840fe06": "Afficher le code", "6d329f7d3a50c7e7": "Copier le tableau", @@ -3985,9 +3985,11 @@ "973e99fa86d7f531": "Message en file d’attente {position} sur {total}, non envoyé", "0f6087c4f53c7f17": "Démarrer un tour avec ce message ({shortcut})", "adab89933af02669": "Passer le compactage et envoyer ce message ({shortcut})", + "d8aaf932f90429c4": "Placer cette commande en tête de la file d’attente ({shortcut})", "3de4016452e8d2bd": "Envoyer dans le tour en cours ({shortcut})", "259cc9568148e8ad": "Démarrer un tour avec ce message", "bb7fddb812d5d29e": "Passer le compactage et envoyer ce message", + "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente", "a5fe1ee609b29a9f": "Envoyer dans le tour en cours", "2b7fd345e4f4fd6e": "Annuler la modification du message en file d’attente", "47f1726bf106d2c8": "Modifier le message en file d’attente", @@ -12458,7 +12460,5 @@ "27d76249d09eb69f": "Guide de revue prêt", "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", - "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", - "d8aaf932f90429c4": "Placer cette commande en tête de la file d’attente ({shortcut})", - "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente" + "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 69ac82ad8a247..13379225ecf26 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "標準", "f42c2a36b3507308": "{label} オン", "77cc5f738cb7d459": "{label} オフ", - "2159a4897d4a4d73": "{runtime, select, codex {{names} を使用するには、Codex CLI を {version} 以降に更新してください。} other {{names} を使用するには、{providerName} を {version} 以降に更新してください。}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} を使用するには Codex CLI {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で Codex CLI をインストールするか、新しいリリースをお待ちください。} other {{names} を使用するには {providerName} {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で {providerName} をインストールするか、新しいリリースをお待ちください。}}", "aba3bb73ce212f0c": "{names} を使うには {providerName} {version} 以降が必要ですが、Homebrew の claude-code cask には {latestVersion} までしかありません。claude-code@latest cask に切り替えてください: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} を使用するには Codex CLI {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で Codex CLI をインストールするか、新しいリリースをお待ちください。} other {{names} を使用するには {providerName} {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で {providerName} をインストールするか、新しいリリースをお待ちください。}}", + "2159a4897d4a4d73": "{runtime, select, codex {{names} を使用するには、Codex CLI を {version} 以降に更新してください。} other {{names} を使用するには、{providerName} を {version} 以降に更新してください。}}", "d887bea446534de5": "この環境には {host}/{repository} を読み取れるプロジェクトがありません。", "4e466d60e2f7736b": "プルリクエストの完全な URL を貼り付けてください。このスレッドには番号を解決するためのリポジトリがありません。", "302625058bacbe38": "完全な URL を貼り付けてください。このプロジェクトのホストには既知の {changeRequest} URL がありません。", @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} は WebSocket 接続を確立できませんでした。", "d9ce6c142a485959": "{host} は {seconds} 秒間応答していません。", "d6bdce8f4e6101a4": "{host} の接続が切断されました。", + "8450a95e5214d199": "{host} から、このクライアントで読み取れないサーバー設定の更新が送信されました。", + "56b4ff3993c93eca": "{host} から互換性のないサーバー設定が送信されました。", + "368c4d4f99c66bfb": "クライアントとサーバーを互換性のあるバージョンに更新してください。", "e5fd422e445391fc": "アップロードに失敗しました。タップして再試行してください。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2558,10 +2561,9 @@ }, " にインストール" ], + "b4b98a0287c282e2": "別のマシン上にあるため、このマシンのエージェントは読み取れません。削除するか、元に戻してから送信してください。", "5bbac0e5afeec779": "現在のスレッド", "33c7e68fca089036": "スレッド、{title}", - "b4b98a0287c282e2": "別のマシン上にあるため、このマシンのエージェントは読み取れません。削除するか、元に戻してから送信してください。", - "c6196d99000642b4": "スレッドを開く", "34cc63390ad793cc": "スレッドを選択", "8f12309ead62e38a": "スレッドまたはプロジェクトを検索...", "2f664754d005d9a7": "アクティブなスレッドが見つかりません。", @@ -2571,6 +2573,7 @@ "a3178769f8308cbc": "スレッドが失敗しました", "89b5e8f3887812da": "ゲストのリクエスト", "62e626804919b294": "入力が必要です", + "c6196d99000642b4": "スレッドを開く", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "あなた:", "a1fbf2422c588292": "エージェント:", @@ -2594,8 +2597,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "ターミナルのプロセスが実行中", "fc2c9a91f498ad6b": "{count, plural, other {{count} 個のターミナルプロセスが実行中。ターミナルを開く}}", - "643c4b50feadc874": "ワークツリー: {path} ({branch})", - "fb7c44da0f0825ea": "ワークツリー: {path}", "56f37ff8ca568059": "スタック", "6831e9a46cbd8939": "チェーン", "9aa9e74a3b7eee91": "チャットに追加", @@ -3032,8 +3033,8 @@ "6f85f14f35b3f547": "{provider} ({environment} 経由)", "7c59a888a062a8bd": "音声入力を記録する下書きがありません。", "62450481c00d2ef3": "下書きの環境を利用できないため、文字起こしを整形できません。", - "c64cb58d9cecbcd2": "文字起こしの整形に失敗しました", "0674544195fcdc39": "元の文字起こしを追加しました。", + "c64cb58d9cecbcd2": "文字起こしの整形に失敗しました", "296496693cdac0db": "t3 コマンドを利用できません。", "efbcef7bc9bbda01": "t3 コマンドの状態を読み込めませんでした。", "1bf6910332426e62": "デスクトップのネットワークアクセスを利用できません。", @@ -3276,6 +3277,7 @@ "4d493d0bda4d403d": "中断されたファイルをもう一度添付するか、削除してください", "c9cad1d84d5f1a32": "中断されたファイルをもう一度添付するか、削除してください", "536a820f2ff726da": "モデルを少なくとも 1 つ選択してください。", + "48d6389202ad6754": "準備ができたら送信", "fbafbe78b5e37966": "スレッドを再開", "bcd7eb979dd38dae": "入力欄を開いて圧縮して送信", "95ee62a0d6968b89": "メッセージを送信", @@ -3450,6 +3452,9 @@ "e778e4f446fdf873": "次のメッセージで新しいセッションが始まります", "0e2f2da4f2d94785": "エージェントはこのスレッドの以前のメッセージを参照できません。", "e1189d2e582b008d": "現在のセッションを維持", + "2bb448d605877a22": "編集または Esc でキャンセル", + "1a1f128d70c62304": "{count, plural, other {画像の準備ができたら送信}}", + "5af3ab719a9725fb": "メッセージを送信中", "461c9f865f2e9b92": "{option} オン", "f2aa17b5c620f2a4": "{option} オフ", "f59314a884aae1ff": "デフォルト", @@ -3688,7 +3693,6 @@ "7c1923203049d602": "コードをコピー", "637817e4ff79c90e": "コードブロックの操作", "ebf3a2b1e314aa5f": "ターミナルで実行", - "fe219642547fa0bf": "ターミナルで実行", "122a8512abc51180": "詳細", "58c38c65c2783c5d": "フルパス", "f37e7d36b51c5b28": "相対パスをコピー", @@ -3700,10 +3704,6 @@ "4967584e8d0fb1c2": "メディアをプレビュー", "67589dd912eacb7c": "統合ブラウザーで開く", "a3c98d4c4b24cecb": "{label} のファイルオプション", - "b4fe8a076e9fd2f8": "ディスプレイ数式", - "085d1407e8c92cce": "インライン数式", - "a2ef393fa7b48ae8": "ディスプレイ数式をスクロール", - "e94685ea5642e088": "インライン数式をスクロール", "3a04583c8500e23d": "図を表示", "16d64f650840fe06": "コードを表示", "6d329f7d3a50c7e7": "表をコピー", @@ -3975,9 +3975,11 @@ "973e99fa86d7f531": "キュー内のメッセージ {position}/{total}、未送信", "0f6087c4f53c7f17": "このメッセージでターンを開始 ({shortcut})", "adab89933af02669": "圧縮をスキップしてこのメッセージを送信 ({shortcut})", + "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", "3de4016452e8d2bd": "現在のターンに送信 ({shortcut})", "259cc9568148e8ad": "このメッセージでターンを開始", "bb7fddb812d5d29e": "圧縮をスキップしてこのメッセージを送信", + "425ab15036aec8a4": "このコマンドをキューの先頭に移動", "a5fe1ee609b29a9f": "現在のターンに送信", "2b7fd345e4f4fd6e": "キュー内のメッセージの編集をキャンセル", "47f1726bf106d2c8": "キュー内のメッセージを編集", @@ -12407,7 +12409,5 @@ "27d76249d09eb69f": "レビューガイドの準備ができました", "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", - "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", - "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", - "425ab15036aec8a4": "このコマンドをキューの先頭に移動" + "9e91e9a77b664e4e": "レビューガイドを開始できませんでした" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 10782b2ca6166..cc8261d7681ff 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "보통", "f42c2a36b3507308": "{label} 켜짐", "77cc5f738cb7d459": "{label} 꺼짐", - "2159a4897d4a4d73": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI를 {version} 이상으로 업데이트하세요.} other {{names}을(를) 사용하려면 {providerName}을(를) {version} 이상으로 업데이트하세요.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 Codex CLI를 설치하거나 새 릴리스를 기다리세요.} other {{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 {providerName}을(를) 설치하거나 새 릴리스를 기다리세요.}}", "aba3bb73ce212f0c": "{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만 Homebrew claude-code cask에는 {latestVersion}까지만 있습니다. claude-code@latest cask로 전환하세요: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 Codex CLI를 설치하거나 새 릴리스를 기다리세요.} other {{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 {providerName}을(를) 설치하거나 새 릴리스를 기다리세요.}}", + "2159a4897d4a4d73": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI를 {version} 이상으로 업데이트하세요.} other {{names}을(를) 사용하려면 {providerName}을(를) {version} 이상으로 업데이트하세요.}}", "d887bea446534de5": "이 환경에는 {host}/{repository}을(를) 읽을 수 있는 프로젝트가 없습니다.", "4e466d60e2f7736b": "전체 풀 리퀘스트 URL을 붙여 넣으세요. 이 스레드에는 번호를 확인할 저장소가 없습니다.", "302625058bacbe38": "전체 URL을 붙여 넣으세요. 이 프로젝트의 호스트에는 알려진 {changeRequest} URL이 없습니다.", @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host}에서 WebSocket 연결을 설정할 수 없습니다.", "d9ce6c142a485959": "{host}이(가) {seconds}초 동안 응답하지 않습니다.", "d6bdce8f4e6101a4": "{host} 연결이 끊어졌습니다.", + "8450a95e5214d199": "{host}에서 이 클라이언트가 읽을 수 없는 서버 구성 업데이트를 보냈습니다.", + "56b4ff3993c93eca": "{host}에서 호환되지 않는 서버 구성을 보냈습니다.", + "368c4d4f99c66bfb": "클라이언트와 서버를 호환되는 버전으로 업데이트하세요.", "e5fd422e445391fc": "업로드에 실패했습니다. 탭하여 다시 시도하세요.", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", @@ -2559,10 +2562,9 @@ }, "에 설치" ], + "b4b98a0287c282e2": "다른 머신에 있어 이 머신의 에이전트가 읽을 수 없습니다. 제거하거나 원래대로 전환한 후 보내세요.", "5bbac0e5afeec779": "현재 스레드", "33c7e68fca089036": "스레드, {title}", - "b4b98a0287c282e2": "다른 머신에 있어 이 머신의 에이전트가 읽을 수 없습니다. 제거하거나 원래대로 전환한 후 보내세요.", - "c6196d99000642b4": "스레드 열기", "34cc63390ad793cc": "스레드 선택", "8f12309ead62e38a": "스레드 또는 프로젝트 검색...", "2f664754d005d9a7": "활성 스레드를 찾을 수 없습니다.", @@ -2572,6 +2574,7 @@ "a3178769f8308cbc": "스레드 실패", "89b5e8f3887812da": "게스트 요청", "62e626804919b294": "입력 필요", + "c6196d99000642b4": "스레드 열기", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "나:", "a1fbf2422c588292": "에이전트:", @@ -2595,8 +2598,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "터미널 프로세스 실행 중", "fc2c9a91f498ad6b": "{count, plural, other {터미널 프로세스 {count}개 실행 중. 터미널 열기}}", - "643c4b50feadc874": "워크트리: {path}({branch})", - "fb7c44da0f0825ea": "워크트리: {path}", "56f37ff8ca568059": "스택", "6831e9a46cbd8939": "체인", "9aa9e74a3b7eee91": "채팅에 추가", @@ -3033,8 +3034,8 @@ "6f85f14f35b3f547": "{environment}을(를) 통한 {provider}", "7c59a888a062a8bd": "음성 입력을 기록할 초안이 없습니다.", "62450481c00d2ef3": "초안의 환경을 사용할 수 없어 받아쓴 내용을 정리할 수 없습니다.", - "c64cb58d9cecbcd2": "받아쓴 내용 정리 실패", "0674544195fcdc39": "원본 받아쓰기 내용이 추가되었습니다.", + "c64cb58d9cecbcd2": "받아쓴 내용 정리 실패", "296496693cdac0db": "t3 명령을 사용할 수 없습니다.", "efbcef7bc9bbda01": "t3 명령 상태를 불러오지 못했습니다.", "1bf6910332426e62": "데스크톱 네트워크 액세스를 사용할 수 없습니다.", @@ -3277,6 +3278,7 @@ "4d493d0bda4d403d": "중단된 파일을 다시 첨부하거나 제거하세요", "c9cad1d84d5f1a32": "중단된 파일을 다시 첨부하거나 제거하세요", "536a820f2ff726da": "모델을 하나 이상 선택하세요.", + "48d6389202ad6754": "준비되면 전송", "fbafbe78b5e37966": "스레드 재개", "bcd7eb979dd38dae": "압축하고 보내려면 입력창을 여세요", "95ee62a0d6968b89": "메시지 보내기", @@ -3450,6 +3452,9 @@ "e778e4f446fdf873": "다음 메시지부터 새 세션이 시작됩니다", "0e2f2da4f2d94785": "에이전트는 이 스레드의 이전 메시지를 볼 수 없습니다.", "e1189d2e582b008d": "현재 세션 유지", + "2bb448d605877a22": "편집하거나 Esc를 눌러 취소", + "1a1f128d70c62304": "{count, plural, other {이미지가 준비되면 전송}}", + "5af3ab719a9725fb": "메시지 전송 중", "461c9f865f2e9b92": "{option} 켜짐", "f2aa17b5c620f2a4": "{option} 꺼짐", "f59314a884aae1ff": "기본값", @@ -3688,7 +3693,6 @@ "7c1923203049d602": "코드 복사", "637817e4ff79c90e": "코드 블록 작업", "ebf3a2b1e314aa5f": "터미널에서 실행", - "fe219642547fa0bf": "터미널에서 실행", "122a8512abc51180": "세부 정보", "58c38c65c2783c5d": "전체 경로", "f37e7d36b51c5b28": "상대 경로 복사", @@ -3700,10 +3704,6 @@ "4967584e8d0fb1c2": "미디어 미리 보기", "67589dd912eacb7c": "통합 브라우저에서 열기", "a3c98d4c4b24cecb": "{label} 파일 옵션", - "b4fe8a076e9fd2f8": "블록 수식", - "085d1407e8c92cce": "인라인 수식", - "a2ef393fa7b48ae8": "블록 수식 스크롤", - "e94685ea5642e088": "인라인 수식 스크롤", "3a04583c8500e23d": "다이어그램 표시", "16d64f650840fe06": "코드 표시", "6d329f7d3a50c7e7": "표 복사", @@ -3973,9 +3973,11 @@ "973e99fa86d7f531": "대기열 메시지 {total}개 중 {position}번째, 보내지 않음", "0f6087c4f53c7f17": "이 메시지로 턴 시작({shortcut})", "adab89933af02669": "압축을 건너뛰고 이 메시지 보내기({shortcut})", + "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", "3de4016452e8d2bd": "현재 턴에 보내기({shortcut})", "259cc9568148e8ad": "이 메시지로 턴 시작", "bb7fddb812d5d29e": "압축을 건너뛰고 이 메시지 보내기", + "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동", "a5fe1ee609b29a9f": "현재 턴에 보내기", "2b7fd345e4f4fd6e": "대기열 메시지 편집 취소", "47f1726bf106d2c8": "대기열 메시지 편집", @@ -12402,7 +12404,5 @@ "27d76249d09eb69f": "검토 가이드 준비됨", "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", - "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", - "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", - "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동" + "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b2b9e2b9b381..a9ce3832a0b9f 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} ativado", "77cc5f738cb7d459": "{label} desativado", - "2159a4897d4a4d73": "{runtime, select, codex {Atualize a CLI do Codex para {version} ou mais recente para usar {names}.} other {Atualize o {providerName} para {version} ou mais recente para usar {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Usar {names} requer a CLI do Codex {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale a CLI do Codex de outra forma ou aguarde uma versão mais recente.} other {Usar {names} requer {providerName} {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale {providerName} de outra forma ou aguarde uma versão mais recente.}}", "aba3bb73ce212f0c": "Usar {names} requer {providerName} {version} ou mais recente, mas o cask claude-code do Homebrew só tem {latestVersion}. Mude para o cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Usar {names} requer a CLI do Codex {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale a CLI do Codex de outra forma ou aguarde uma versão mais recente.} other {Usar {names} requer {providerName} {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale {providerName} de outra forma ou aguarde uma versão mais recente.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Atualize a CLI do Codex para {version} ou mais recente para usar {names}.} other {Atualize o {providerName} para {version} ou mais recente para usar {names}.}}", "d887bea446534de5": "Nenhum projeto neste ambiente consegue ler {host}/{repository}.", "4e466d60e2f7736b": "Cole a URL completa do pull request; esta thread não tem repositório para resolver o número.", "302625058bacbe38": "Cole uma URL completa; o host deste projeto não tem uma URL de {changeRequest} conhecida.", @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} não conseguiu estabelecer uma conexão WebSocket.", "d9ce6c142a485959": "{host} parou de responder por {seconds} s.", "d6bdce8f4e6101a4": "{host} desconectou.", + "8450a95e5214d199": "{host} enviou uma atualização da configuração do servidor que este cliente não conseguiu ler.", + "56b4ff3993c93eca": "{host} enviou uma configuração de servidor incompatível.", + "368c4d4f99c66bfb": "Atualize o cliente e o servidor para versões compatíveis.", "e5fd422e445391fc": "Falha no envio. Toque para tentar novamente.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2560,10 +2563,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Está em outra máquina, então o agente desta máquina não consegue lê-lo. Remova-o ou volte para enviar.", "5bbac0e5afeec779": "Thread atual", "33c7e68fca089036": "Thread, {title}", - "b4b98a0287c282e2": "Está em outra máquina, então o agente desta máquina não consegue lê-lo. Remova-o ou volte para enviar.", - "c6196d99000642b4": "Abrir thread", "34cc63390ad793cc": "Escolha uma thread", "8f12309ead62e38a": "Pesquisar threads ou projetos...", "2f664754d005d9a7": "Nenhuma thread ativa encontrada.", @@ -2573,6 +2575,7 @@ "a3178769f8308cbc": "A thread falhou", "89b5e8f3887812da": "Pedido de convidado", "62e626804919b294": "Resposta necessária", + "c6196d99000642b4": "Abrir thread", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Você:", "a1fbf2422c588292": "Agente:", @@ -2596,8 +2599,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Processo do terminal em execução", "fc2c9a91f498ad6b": "{count, plural, one {{count} processo do terminal em execução. Abrir terminal} other {{count} processos do terminal em execução. Abrir terminal}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "pilha", "6831e9a46cbd8939": "cadeia", "9aa9e74a3b7eee91": "Adicionar ao chat", @@ -3034,8 +3035,8 @@ "6f85f14f35b3f547": "{provider} via {environment}", "7c59a888a062a8bd": "A entrada de voz não tem um rascunho onde gravar.", "62450481c00d2ef3": "O ambiente do rascunho não está disponível para limpar a transcrição.", - "c64cb58d9cecbcd2": "Falha ao limpar a transcrição", "0674544195fcdc39": "A transcrição original foi adicionada.", + "c64cb58d9cecbcd2": "Falha ao limpar a transcrição", "296496693cdac0db": "O comando t3 não está disponível.", "efbcef7bc9bbda01": "Falha ao carregar o estado do comando t3.", "1bf6910332426e62": "O acesso à rede do desktop não está disponível.", @@ -3278,6 +3279,7 @@ "4d493d0bda4d403d": "Anexe novamente o arquivo interrompido ou remova-o", "c9cad1d84d5f1a32": "Anexe novamente os arquivos interrompidos ou remova-os", "536a820f2ff726da": "Selecione pelo menos um modelo.", + "48d6389202ad6754": "Enviando quando estiver pronto", "fbafbe78b5e37966": "Retomar thread", "bcd7eb979dd38dae": "Abrir o editor de mensagens para compactar e enviar", "95ee62a0d6968b89": "Enviar mensagem", @@ -3454,6 +3456,9 @@ "e778e4f446fdf873": "Sua próxima mensagem inicia uma nova sessão", "0e2f2da4f2d94785": "O agente não verá as mensagens anteriores desta thread.", "e1189d2e582b008d": "Manter a sessão atual", + "2bb448d605877a22": "Edite ou pressione Esc para cancelar", + "1a1f128d70c62304": "{count, plural, one {Enviando assim que a imagem estiver pronta} other {Enviando assim que {count} imagens estiverem prontas}}", + "5af3ab719a9725fb": "Enviando mensagem", "461c9f865f2e9b92": "{option} ativado", "f2aa17b5c620f2a4": "{option} desativado", "f59314a884aae1ff": "Padrão", @@ -3693,7 +3698,6 @@ "7c1923203049d602": "Copiar código", "637817e4ff79c90e": "Ações do bloco de código", "ebf3a2b1e314aa5f": "Executar no terminal", - "fe219642547fa0bf": "Executar no terminal", "122a8512abc51180": "Detalhes", "58c38c65c2783c5d": "Caminho completo", "f37e7d36b51c5b28": "Copiar caminho relativo", @@ -3705,10 +3709,6 @@ "4967584e8d0fb1c2": "Pré-visualizar mídia", "67589dd912eacb7c": "Abrir no navegador integrado", "a3c98d4c4b24cecb": "Opções do arquivo {label}", - "b4fe8a076e9fd2f8": "Equação em destaque", - "085d1407e8c92cce": "Equação em linha", - "a2ef393fa7b48ae8": "Rolar a equação em destaque", - "e94685ea5642e088": "Rolar a equação em linha", "3a04583c8500e23d": "Mostrar diagrama", "16d64f650840fe06": "Mostrar código", "6d329f7d3a50c7e7": "Copiar tabela", @@ -3985,9 +3985,11 @@ "973e99fa86d7f531": "Mensagem {position} de {total} na fila, não enviada", "0f6087c4f53c7f17": "Iniciar um turno com esta mensagem ({shortcut})", "adab89933af02669": "Pular a compactação e enviar esta mensagem ({shortcut})", + "d8aaf932f90429c4": "Mover este comando para o início da fila ({shortcut})", "3de4016452e8d2bd": "Enviar para o turno atual ({shortcut})", "259cc9568148e8ad": "Iniciar um turno com esta mensagem", "bb7fddb812d5d29e": "Pular a compactação e enviar esta mensagem", + "425ab15036aec8a4": "Mover este comando para o início da fila", "a5fe1ee609b29a9f": "Enviar para o turno atual", "2b7fd345e4f4fd6e": "Cancelar a edição da mensagem na fila", "47f1726bf106d2c8": "Editar mensagem na fila", @@ -12458,7 +12460,5 @@ "27d76249d09eb69f": "Guia de revisão pronto", "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", - "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", - "d8aaf932f90429c4": "Mover este comando para o início da fila ({shortcut})", - "425ab15036aec8a4": "Mover este comando para o início da fila" + "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0ecadaba9ded1..ee0fe30aa4f39 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Обычная", "f42c2a36b3507308": "{label}: вкл.", "77cc5f738cb7d459": "{label}: выкл.", - "2159a4897d4a4d73": "{runtime, select, codex {Обновите Codex CLI до {version} или новее, чтобы использовать {names}.} other {Обновите {providerName} до {version} или новее, чтобы использовать {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Для {names} нужна Codex CLI {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите Codex CLI другим способом или дождитесь нового релиза.} other {Для {names} нужен {providerName} {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите {providerName} другим способом или дождитесь нового релиза.}}", "aba3bb73ce212f0c": "Для {names} нужен {providerName} {version} или новее, но в Homebrew cask claude-code есть только {latestVersion}. Перейдите на cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Для {names} нужна Codex CLI {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите Codex CLI другим способом или дождитесь нового релиза.} other {Для {names} нужен {providerName} {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите {providerName} другим способом или дождитесь нового релиза.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Обновите Codex CLI до {version} или новее, чтобы использовать {names}.} other {Обновите {providerName} до {version} или новее, чтобы использовать {names}.}}", "d887bea446534de5": "Ни один проект в этом окружении не может прочитать {host}/{repository}.", "4e466d60e2f7736b": "Вставьте полный URL пул-реквеста: у этого треда нет репозитория, по которому можно найти номер.", "302625058bacbe38": "Вставьте полный URL: для хоста этого проекта неизвестен формат URL {changeRequest}.", @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} не удалось установить WebSocket-соединение.", "d9ce6c142a485959": "{host} не отвечает уже {seconds} с.", "d6bdce8f4e6101a4": "{host} отключён.", + "8450a95e5214d199": "{host} отправил обновление конфигурации сервера, которое этот клиент не смог прочитать.", + "56b4ff3993c93eca": "{host} отправил несовместимую конфигурацию сервера.", + "368c4d4f99c66bfb": "Обновите клиент и сервер до совместимых версий.", "e5fd422e445391fc": "Ошибка загрузки. Нажмите, чтобы повторить.", "b2bc6bd92ea24e5c": "{size} МБ", "88f84178edbb7f57": "{size} КБ", @@ -2560,10 +2563,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Находится на другой машине, поэтому агент этой машины не может его прочитать. Удалите его или переключитесь обратно, чтобы отправить.", "5bbac0e5afeec779": "Текущий тред", "33c7e68fca089036": "Тред, {title}", - "b4b98a0287c282e2": "Находится на другой машине, поэтому агент этой машины не может его прочитать. Удалите его или переключитесь обратно, чтобы отправить.", - "c6196d99000642b4": "Открыть тред", "34cc63390ad793cc": "Выберите тред", "8f12309ead62e38a": "Поиск тредов или проектов...", "2f664754d005d9a7": "Активные треды не найдены.", @@ -2573,6 +2575,7 @@ "a3178769f8308cbc": "Ошибка в треде", "89b5e8f3887812da": "Запрос гостя", "62e626804919b294": "Нужен ввод", + "c6196d99000642b4": "Открыть тред", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Вы:", "a1fbf2422c588292": "Агент:", @@ -2596,8 +2599,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Процесс в терминале запущен", "fc2c9a91f498ad6b": "{count, plural, one {Запущен {count} процесс в терминале. Открыть терминал} few {Запущено {count} процесса в терминале. Открыть терминал} many {Запущено {count} процессов в терминале. Открыть терминал} other {Запущено {count} процесса в терминале. Открыть терминал}}", - "643c4b50feadc874": "Рабочее дерево: {path} ({branch})", - "fb7c44da0f0825ea": "Рабочее дерево: {path}", "56f37ff8ca568059": "стек", "6831e9a46cbd8939": "цепочка", "9aa9e74a3b7eee91": "Добавить в чат", @@ -3034,8 +3035,8 @@ "6f85f14f35b3f547": "{provider} через {environment}", "7c59a888a062a8bd": "Нет черновика для записи голосового ввода.", "62450481c00d2ef3": "Окружение черновика недоступно для очистки расшифровки.", - "c64cb58d9cecbcd2": "Не удалось очистить расшифровку", "0674544195fcdc39": "Добавлена исходная расшифровка.", + "c64cb58d9cecbcd2": "Не удалось очистить расшифровку", "296496693cdac0db": "Команда t3 недоступна.", "efbcef7bc9bbda01": "Не удалось загрузить состояние команды t3.", "1bf6910332426e62": "Сетевой доступ десктопа недоступен.", @@ -3278,6 +3279,7 @@ "4d493d0bda4d403d": "Прикрепите прерванный файл снова или удалите его", "c9cad1d84d5f1a32": "Прикрепите прерванные файлы снова или удалите их", "536a820f2ff726da": "Выберите хотя бы одну модель.", + "48d6389202ad6754": "Отправка по готовности", "fbafbe78b5e37966": "Возобновить тред", "bcd7eb979dd38dae": "Откройте поле ввода, чтобы сжать и отправить", "95ee62a0d6968b89": "Отправить сообщение", @@ -3454,6 +3456,9 @@ "e778e4f446fdf873": "Следующее сообщение начнёт новый сеанс", "0e2f2da4f2d94785": "Агент не увидит предыдущие сообщения этого треда.", "e1189d2e582b008d": "Оставить текущий сеанс", + "2bb448d605877a22": "Отредактируйте или нажмите Esc для отмены", + "1a1f128d70c62304": "{count, plural, one {Отправится, когда изображение будет готово} few {Отправится, когда {count} изображения будут готовы} many {Отправится, когда {count} изображений будут готовы} other {Отправится, когда {count} изображения будут готовы}}", + "5af3ab719a9725fb": "Отправка сообщения", "461c9f865f2e9b92": "{option}: вкл.", "f2aa17b5c620f2a4": "{option}: выкл.", "f59314a884aae1ff": "По умолчанию", @@ -3693,7 +3698,6 @@ "7c1923203049d602": "Копировать код", "637817e4ff79c90e": "Действия с блоком кода", "ebf3a2b1e314aa5f": "Выполнить в терминале", - "fe219642547fa0bf": "Выполнить в терминале", "122a8512abc51180": "Подробности", "58c38c65c2783c5d": "Полный путь", "f37e7d36b51c5b28": "Копировать относительный путь", @@ -3705,10 +3709,6 @@ "4967584e8d0fb1c2": "Предпросмотр медиа", "67589dd912eacb7c": "Открыть во встроенном браузере", "a3c98d4c4b24cecb": "Параметры файла {label}", - "b4fe8a076e9fd2f8": "Формула в отдельной строке", - "085d1407e8c92cce": "Формула в строке", - "a2ef393fa7b48ae8": "Прокрутить формулу", - "e94685ea5642e088": "Прокрутить формулу в строке", "3a04583c8500e23d": "Показать диаграмму", "16d64f650840fe06": "Показать код", "6d329f7d3a50c7e7": "Копировать таблицу", @@ -3985,9 +3985,11 @@ "973e99fa86d7f531": "Сообщение в очереди {position} из {total}, не отправлено", "0f6087c4f53c7f17": "Начать ход с этим сообщением ({shortcut})", "adab89933af02669": "Пропустить сжатие и отправить сообщение ({shortcut})", + "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", "3de4016452e8d2bd": "Отправить в текущий ход ({shortcut})", "259cc9568148e8ad": "Начать ход с этим сообщением", "bb7fddb812d5d29e": "Пропустить сжатие и отправить сообщение", + "425ab15036aec8a4": "Переместить эту команду в начало очереди", "a5fe1ee609b29a9f": "Отправить в текущий ход", "2b7fd345e4f4fd6e": "Отменить редактирование сообщения в очереди", "47f1726bf106d2c8": "Редактировать сообщение в очереди", @@ -12458,7 +12460,5 @@ "27d76249d09eb69f": "Гид по ревью готов", "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", - "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", - "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", - "425ab15036aec8a4": "Переместить эту команду в начало очереди" + "9e91e9a77b664e4e": "Не удалось запустить гид по ревью" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 1c01b1112768f..fb02753220b14 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} på", "77cc5f738cb7d459": "{label} av", - "2159a4897d4a4d73": "{runtime, select, codex {Uppdatera Codex CLI till {version} eller senare för att använda {names}.} other {Uppdatera {providerName} till {version} eller senare för att använda {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} kräver Codex CLI {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera Codex CLI på ett annat sätt eller vänta på en nyare version.} other {{names} kräver {providerName} {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera {providerName} på ett annat sätt eller vänta på en nyare version.}}", "aba3bb73ce212f0c": "{names} kräver {providerName} {version} eller senare, men Homebrew-casken claude-code har bara {latestVersion}. Byt till casken claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} kräver Codex CLI {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera Codex CLI på ett annat sätt eller vänta på en nyare version.} other {{names} kräver {providerName} {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera {providerName} på ett annat sätt eller vänta på en nyare version.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Uppdatera Codex CLI till {version} eller senare för att använda {names}.} other {Uppdatera {providerName} till {version} eller senare för att använda {names}.}}", "d887bea446534de5": "Inget projekt i den här miljön kan läsa {host}/{repository}.", "4e466d60e2f7736b": "Klistra in hela pull request-URL:en; den här tråden har inget repo att slå upp numret i.", "302625058bacbe38": "Klistra in en fullständig URL; det här projektets värd har ingen känd URL för {changeRequest}.", @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} kunde inte upprätta en WebSocket-anslutning.", "d9ce6c142a485959": "{host} slutade svara i {seconds} s.", "d6bdce8f4e6101a4": "{host} kopplades från.", + "8450a95e5214d199": "{host} skickade en uppdatering av serverkonfigurationen som den här klienten inte kunde läsa.", + "56b4ff3993c93eca": "{host} skickade en inkompatibel serverkonfiguration.", + "368c4d4f99c66bfb": "Uppdatera klienten och servern till kompatibla versioner.", "e5fd422e445391fc": "Uppladdningen misslyckades. Tryck för att försöka igen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} kB", @@ -2560,10 +2563,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Finns på en annan dator, så den här datorns agent kan inte läsa den. Ta bort den eller byt tillbaka för att skicka.", "5bbac0e5afeec779": "Aktuell tråd", "33c7e68fca089036": "Tråd, {title}", - "b4b98a0287c282e2": "Finns på en annan dator, så den här datorns agent kan inte läsa den. Ta bort den eller byt tillbaka för att skicka.", - "c6196d99000642b4": "Öppna tråd", "34cc63390ad793cc": "Välj en tråd", "8f12309ead62e38a": "Sök trådar eller projekt...", "2f664754d005d9a7": "Inga aktiva trådar hittades.", @@ -2573,6 +2575,7 @@ "a3178769f8308cbc": "Tråden misslyckades", "89b5e8f3887812da": "Gästbegäran", "62e626804919b294": "Input behövs", + "c6196d99000642b4": "Öppna tråd", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", @@ -2596,8 +2599,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Terminalprocess körs", "fc2c9a91f498ad6b": "{count, plural, one {{count} terminalprocess körs. Öppna terminalen} other {{count} terminalprocesser körs. Öppna terminalen}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "stack", "6831e9a46cbd8939": "kedja", "9aa9e74a3b7eee91": "Lägg till i chatten", @@ -3034,8 +3035,8 @@ "6f85f14f35b3f547": "{provider} via {environment}", "7c59a888a062a8bd": "Röstinmatningen har inget utkast att spela in i.", "62450481c00d2ef3": "Utkastets miljö är inte tillgänglig för att städa transkriptionen.", - "c64cb58d9cecbcd2": "Det gick inte att städa transkriptionen", "0674544195fcdc39": "Den ursprungliga transkriptionen lades till.", + "c64cb58d9cecbcd2": "Det gick inte att städa transkriptionen", "296496693cdac0db": "Kommandot t3 är inte tillgängligt.", "efbcef7bc9bbda01": "Det gick inte att läsa in statusen för kommandot t3.", "1bf6910332426e62": "Skrivbordsappens nätverksåtkomst är inte tillgänglig.", @@ -3278,6 +3279,7 @@ "4d493d0bda4d403d": "Bifoga den avbrutna filen igen eller ta bort den", "c9cad1d84d5f1a32": "Bifoga de avbrutna filerna igen eller ta bort dem", "536a820f2ff726da": "Välj minst en modell.", + "48d6389202ad6754": "Skickar när det är klart", "fbafbe78b5e37966": "Återuppta tråd", "bcd7eb979dd38dae": "Öppna inmatningsfältet för att komprimera och skicka", "95ee62a0d6968b89": "Skicka meddelande", @@ -3454,6 +3456,9 @@ "e778e4f446fdf873": "Ditt nästa meddelande startar en ny session", "0e2f2da4f2d94785": "Agenten ser inte tidigare meddelanden i den här tråden.", "e1189d2e582b008d": "Behåll den aktuella sessionen", + "2bb448d605877a22": "Redigera eller tryck Esc för att avbryta", + "1a1f128d70c62304": "{count, plural, one {Skickas när bilden är klar} other {Skickas när {count} bilder är klara}}", + "5af3ab719a9725fb": "Skickar meddelande", "461c9f865f2e9b92": "{option} på", "f2aa17b5c620f2a4": "{option} av", "f59314a884aae1ff": "Standard", @@ -3693,7 +3698,6 @@ "7c1923203049d602": "Kopiera kod", "637817e4ff79c90e": "Åtgärder för kodblock", "ebf3a2b1e314aa5f": "Kör i terminalen", - "fe219642547fa0bf": "Kör i terminalen", "122a8512abc51180": "Detaljer", "58c38c65c2783c5d": "Fullständig sökväg", "f37e7d36b51c5b28": "Kopiera relativ sökväg", @@ -3705,10 +3709,6 @@ "4967584e8d0fb1c2": "Förhandsvisa media", "67589dd912eacb7c": "Öppna i den integrerade webbläsaren", "a3c98d4c4b24cecb": "Filalternativ för {label}", - "b4fe8a076e9fd2f8": "Fristående ekvation", - "085d1407e8c92cce": "Ekvation i texten", - "a2ef393fa7b48ae8": "Rulla fristående ekvation", - "e94685ea5642e088": "Rulla ekvation i texten", "3a04583c8500e23d": "Visa diagram", "16d64f650840fe06": "Visa kod", "6d329f7d3a50c7e7": "Kopiera tabell", @@ -3985,9 +3985,11 @@ "973e99fa86d7f531": "Köat meddelande {position} av {total}, inte skickat", "0f6087c4f53c7f17": "Starta en omgång med det här meddelandet ({shortcut})", "adab89933af02669": "Hoppa över komprimering och skicka det här meddelandet ({shortcut})", + "d8aaf932f90429c4": "Flytta det här kommandot först i kön ({shortcut})", "3de4016452e8d2bd": "Skicka in i den aktuella omgången ({shortcut})", "259cc9568148e8ad": "Starta en omgång med det här meddelandet", "bb7fddb812d5d29e": "Hoppa över komprimering och skicka det här meddelandet", + "425ab15036aec8a4": "Flytta det här kommandot först i kön", "a5fe1ee609b29a9f": "Skicka in i den aktuella omgången", "2b7fd345e4f4fd6e": "Avbryt redigering av köat meddelande", "47f1726bf106d2c8": "Redigera köat meddelande", @@ -12465,7 +12467,5 @@ "27d76249d09eb69f": "Granskningsguiden är klar", "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", - "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", - "d8aaf932f90429c4": "Flytta det här kommandot först i kön ({shortcut})", - "425ab15036aec8a4": "Flytta det här kommandot först i kön" + "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 43790340d1167..04044302284b7 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "普通", "f42c2a36b3507308": "{label} 开启", "77cc5f738cb7d459": "{label} 关闭", - "2159a4897d4a4d73": "{runtime, select, codex {请将 Codex CLI 更新到 {version} 或更高版本以使用 {names}。} other {请将 {providerName} 更新到 {version} 或更高版本以使用 {names}。}}", - "a0854b0f9604fc7b": "{runtime, select, codex {使用 {names} 需要 Codex CLI {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 Codex CLI,或等待更新的版本发布。} other {使用 {names} 需要 {providerName} {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 {providerName},或等待更新的版本发布。}}", "aba3bb73ce212f0c": "使用 {names} 需要 {providerName} {version} 或更高版本,但 Homebrew 的 claude-code cask 只有 {latestVersion}。请切换到 claude-code@latest cask:{command}", + "a0854b0f9604fc7b": "{runtime, select, codex {使用 {names} 需要 Codex CLI {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 Codex CLI,或等待更新的版本发布。} other {使用 {names} 需要 {providerName} {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 {providerName},或等待更新的版本发布。}}", + "2159a4897d4a4d73": "{runtime, select, codex {请将 Codex CLI 更新到 {version} 或更高版本以使用 {names}。} other {请将 {providerName} 更新到 {version} 或更高版本以使用 {names}。}}", "d887bea446534de5": "此环境中没有项目能读取 {host}/{repository}。", "4e466d60e2f7736b": "请粘贴完整的 pull request URL;此会话没有可用于解析编号的仓库。", "302625058bacbe38": "请粘贴完整 URL;此项目的托管平台没有已知的 {changeRequest} URL。", @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} 无法建立 WebSocket 连接。", "d9ce6c142a485959": "{host} 已 {seconds} 秒无响应。", "d6bdce8f4e6101a4": "{host} 已断开连接。", + "8450a95e5214d199": "{host} 发送了此客户端无法读取的服务器配置更新。", + "56b4ff3993c93eca": "{host} 发送了不兼容的服务器配置。", + "368c4d4f99c66bfb": "请将客户端和服务器更新到兼容的版本。", "e5fd422e445391fc": "上传失败。点按以重试。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2564,10 +2567,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "它在另一台机器上,本机的智能体读不到它。请移除它,或切回那台机器再发送。", "5bbac0e5afeec779": "当前会话", "33c7e68fca089036": "会话,{title}", - "b4b98a0287c282e2": "它在另一台机器上,本机的智能体读不到它。请移除它,或切回那台机器再发送。", - "c6196d99000642b4": "打开会话", "34cc63390ad793cc": "选择会话", "8f12309ead62e38a": "搜索会话或项目…", "2f664754d005d9a7": "未找到活动会话。", @@ -2577,6 +2579,7 @@ "a3178769f8308cbc": "会话失败", "89b5e8f3887812da": "访客请求", "62e626804919b294": "需要输入", + "c6196d99000642b4": "打开会话", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "你:", "a1fbf2422c588292": "智能体:", @@ -2600,8 +2603,6 @@ "3260b22f72f7effb": "{tooltipLead}:{title}", "feac8e54b30c5a03": "终端进程正在运行", "fc2c9a91f498ad6b": "{count, plural, other {{count} 个终端进程正在运行。打开终端}}", - "643c4b50feadc874": "工作树:{path}({branch})", - "fb7c44da0f0825ea": "工作树:{path}", "56f37ff8ca568059": "堆叠", "6831e9a46cbd8939": "链", "9aa9e74a3b7eee91": "添加到对话", @@ -3038,8 +3039,8 @@ "6f85f14f35b3f547": "{provider}(经由 {environment})", "7c59a888a062a8bd": "语音输入没有可录入的草稿。", "62450481c00d2ef3": "草稿所在环境不可用,无法整理转写内容。", - "c64cb58d9cecbcd2": "转写文本整理失败", "0674544195fcdc39": "已添加原始转写文本。", + "c64cb58d9cecbcd2": "转写文本整理失败", "296496693cdac0db": "t3 命令不可用。", "efbcef7bc9bbda01": "无法加载 t3 命令状态。", "1bf6910332426e62": "桌面网络访问不可用。", @@ -3282,6 +3283,7 @@ "4d493d0bda4d403d": "请重新添加中断的文件,或将其移除", "c9cad1d84d5f1a32": "请重新添加中断的文件,或将它们移除", "536a820f2ff726da": "请至少选择一个模型。", + "48d6389202ad6754": "就绪后发送", "fbafbe78b5e37966": "继续会话", "bcd7eb979dd38dae": "打开输入框以压缩并发送", "95ee62a0d6968b89": "发送消息", @@ -3459,6 +3461,9 @@ "e778e4f446fdf873": "你的下一条消息将以全新上下文开始", "0e2f2da4f2d94785": "智能体将看不到这个会话里之前的消息。", "e1189d2e582b008d": "保留当前上下文", + "2bb448d605877a22": "编辑或按 Esc 取消", + "1a1f128d70c62304": "{count, plural, other {图片就绪后发送}}", + "5af3ab719a9725fb": "正在发送消息", "461c9f865f2e9b92": "{option} 开启", "f2aa17b5c620f2a4": "{option} 关闭", "f59314a884aae1ff": "默认", @@ -3698,7 +3703,6 @@ "7c1923203049d602": "复制代码", "637817e4ff79c90e": "代码块操作", "ebf3a2b1e314aa5f": "在终端中运行", - "fe219642547fa0bf": "在终端中运行", "122a8512abc51180": "详情", "58c38c65c2783c5d": "完整路径", "f37e7d36b51c5b28": "复制相对路径", @@ -3710,10 +3714,6 @@ "4967584e8d0fb1c2": "预览媒体", "67589dd912eacb7c": "在内置浏览器中打开", "a3c98d4c4b24cecb": "{label} 的文件选项", - "b4fe8a076e9fd2f8": "独立公式", - "085d1407e8c92cce": "行内公式", - "a2ef393fa7b48ae8": "滚动查看独立公式", - "e94685ea5642e088": "滚动查看行内公式", "3a04583c8500e23d": "显示图表", "16d64f650840fe06": "显示代码", "6d329f7d3a50c7e7": "复制表格", @@ -3990,9 +3990,11 @@ "973e99fa86d7f531": "排队消息 {position}/{total},尚未发送", "0f6087c4f53c7f17": "用此消息开始一个轮次 ({shortcut})", "adab89933af02669": "跳过压缩并发送此消息 ({shortcut})", + "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", "3de4016452e8d2bd": "发送到当前轮次 ({shortcut})", "259cc9568148e8ad": "用这条消息开始新一轮", "bb7fddb812d5d29e": "跳过压缩并发送这条消息", + "425ab15036aec8a4": "将此命令移到队列最前面", "a5fe1ee609b29a9f": "发送到当前这一轮", "2b7fd345e4f4fd6e": "取消编辑排队消息", "47f1726bf106d2c8": "编辑排队消息", @@ -12484,7 +12486,5 @@ "27d76249d09eb69f": "审查导览已就绪", "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", - "9e91e9a77b664e4e": "无法开始生成审查导览", - "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", - "425ab15036aec8a4": "将此命令移到队列最前面" + "9e91e9a77b664e4e": "无法开始生成审查导览" } diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 4ba107059f2b7..2b19b90cc28e3 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1887,10 +1887,6 @@ code { margin: 0.65rem 0; } -.chat-markdown-math-display .katex-display { - margin: 0; -} - :is(.chat-markdown, .composer-tiptap) h1, :is(.chat-markdown, .composer-tiptap) h2, :is(.chat-markdown, .composer-tiptap) h3, @@ -2312,6 +2308,15 @@ code { overflow-wrap: break-word; } +.chat-markdown [data-markdown-math] { + font-weight: normal; + font-style: normal; +} + +.chat-markdown [data-markdown-math] > svg { + font-size: 1.21em; +} + /* Formula cells keep their natural width and scroll with the table. */ .chat-markdown :is(th, td):has([data-markdown-math]) { max-width: none; diff --git a/apps/web/src/lib/chunkReloadGuard.ts b/apps/web/src/lib/chunkReloadGuard.ts index 10f4dc8be191c..43034ccb578b3 100644 --- a/apps/web/src/lib/chunkReloadGuard.ts +++ b/apps/web/src/lib/chunkReloadGuard.ts @@ -34,3 +34,15 @@ export function isChunkLoadError(error: unknown): boolean { message !== undefined && CHUNK_LOAD_ERROR_PREFIXES.some((prefix) => message.startsWith(prefix)) ); } + +export const chunkLoadState = { reloadScheduled: false }; + +// Registered from the entry before main loads, so main-chunk and route-chunk failures share one decision. +export function handleChunkLoadErrors() { + window.addEventListener("vite:preloadError", (event) => { + if (reloadOnceForChunkLoadError()) { + chunkLoadState.reloadScheduled = true; + event.preventDefault(); + } + }); +} diff --git a/apps/web/src/lib/discardComposerDraft.test.ts b/apps/web/src/lib/discardComposerDraft.test.ts index 6c63482dfe52b..340ed6b2606e3 100644 --- a/apps/web/src/lib/discardComposerDraft.test.ts +++ b/apps/web/src/lib/discardComposerDraft.test.ts @@ -80,6 +80,23 @@ describe("discardComposerDraft", () => { } }); + it("discards and restores a draft session that has no composer record", async () => { + useComposerDraftStore.getState().setProjectDraftThreadId(projectRef, draftId); + const before = useComposerDraftStore.getState(); + expect(before.draftsByThreadKey).toEqual({}); + + discardComposerDraft(draftId); + expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull(); + + await undoNotice().undo(); + const after = useComposerDraftStore.getState(); + expect(after.getDraftSession(draftId)).toEqual(before.getDraftSession(draftId)); + expect(after.draftsByThreadKey).toEqual({}); + expect(after.logicalProjectDraftThreadKeyByLogicalProjectKey).toEqual( + before.logicalProjectDraftThreadKeyByLogicalProjectKey, + ); + }); + it("releases a discarded existing-thread preview when Undo is committed", async () => { using preview = imagePreview(); useComposerDraftStore.getState().addImage(threadRef, preview.image); diff --git a/apps/web/src/lib/discardComposerDraft.ts b/apps/web/src/lib/discardComposerDraft.ts index bd52b0a02879f..f1847a737dc0a 100644 --- a/apps/web/src/lib/discardComposerDraft.ts +++ b/apps/web/src/lib/discardComposerDraft.ts @@ -19,8 +19,9 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { const store = useComposerDraftStore.getState(); const key = resolveComposerDraftKey(store, target); const draft = key === null ? undefined : store.draftsByThreadKey[key]; - if (key === null || !draft) return; + if (key === null) return; const session = store.draftThreadsByThreadKey[key]; + if (!draft && !session) return; const logicalProjectKeys = Object.entries(store.logicalProjectDraftThreadKeyByLogicalProjectKey) .filter(([, draftKey]) => draftKey === key) .map(([logicalProjectKey]) => logicalProjectKey); @@ -38,6 +39,7 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { } const releaseDiscardedDraft = () => { + if (!draft) return; releaseDraftAttachments([...draft.images, ...draft.files]); // Draft-session removal already revoked these previews. if (!discardsSession) { @@ -65,19 +67,21 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { logicalProjectDraftThreadKeyByLogicalProjectKey[logicalProjectKey] ??= key; } return { - draftsByThreadKey: { - ...state.draftsByThreadKey, - [key]: discardsSession - ? { - ...draft, - images: draft.images.map((image) => - image.previewUrl.startsWith("blob:") - ? { ...image, previewUrl: URL.createObjectURL(image.file) } - : image, - ), - } - : draft, - }, + draftsByThreadKey: draft + ? { + ...state.draftsByThreadKey, + [key]: discardsSession + ? { + ...draft, + images: draft.images.map((image) => + image.previewUrl.startsWith("blob:") + ? { ...image, previewUrl: URL.createObjectURL(image.file) } + : image, + ), + } + : draft, + } + : state.draftsByThreadKey, draftThreadsByThreadKey: session ? { ...state.draftThreadsByThreadKey, [key]: session } : state.draftThreadsByThreadKey, diff --git a/apps/web/src/lib/imageCompression.browser.test.ts b/apps/web/src/lib/imageCompression.browser.test.ts new file mode 100644 index 0000000000000..2e7597eaa8bf8 --- /dev/null +++ b/apps/web/src/lib/imageCompression.browser.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it } from "vite-plus/test"; + +import heicUrl from "../../test/fixtures/images/photo.heic?url"; +import { + compressImageForStash, + dataUrlToFile, + prepareImageForAttachment, + readFileAsDataUrl, +} from "./imageCompression"; + +async function makeImage( + colorSpace: PredefinedColorSpace, + fill: string, + type: string, +): Promise { + const canvas = new OffscreenCanvas(2400, 1600); + const context = canvas.getContext("2d", { colorSpace }); + if (!context) throw new Error("no 2d context"); + context.fillStyle = fill; + context.fillRect(0, 0, 2400, 1600); + const blob = await canvas.convertToBlob({ type, quality: 0.95 }); + return new File([blob], `shot.${type.slice(6)}`, { type }); +} + +/** `raw` ignores any embedded profile, as a reader without color management would. */ +async function readPixel(file: Blob, raw = false): Promise { + const bitmap = await createImageBitmap(file, { colorSpaceConversion: raw ? "none" : "default" }); + const colorSpace = raw ? "srgb" : "display-p3"; + const canvas = new OffscreenCanvas(1, 1); + const context = canvas.getContext("2d", { colorSpace }); + if (!context) throw new Error("no 2d context"); + context.drawImage(bitmap, 0, 0, 1, 1); + bitmap.close(); + return Array.from(context.getImageData(0, 0, 1, 1, { colorSpace }).data.slice(0, 3)); +} + +async function expectSameColors(actual: Blob, expected: Blob) { + expectNear(await readPixel(actual), await readPixel(expected)); + expectNear(await readPixel(actual, true), await readPixel(expected, true)); +} + +function expectNear(actual: number[], expected: number[]) { + expected.forEach((channel, index) => + expect(Math.abs(actual[index]! - channel)).toBeLessThanOrEqual(2), + ); +} + +async function readChromiumDisplayP3Profile(): Promise { + const canvas = new OffscreenCanvas(1, 1); + canvas.getContext("2d", { colorSpace: "display-p3" }); + const png = new Uint8Array( + await (await canvas.convertToBlob({ type: "image/png" })).arrayBuffer(), + ); + const view = new DataView(png.buffer); + for (let offset = 8; offset < png.length; offset += 12 + view.getUint32(offset)) { + if (new TextDecoder().decode(png.subarray(offset + 4, offset + 8)) !== "iCCP") continue; + const chunk = png.subarray(offset + 8, offset + 8 + view.getUint32(offset)); + const deflated = chunk.subarray(chunk.indexOf(0) + 2); + const inflate = new Blob([deflated]).stream().pipeThrough(new DecompressionStream("deflate")); + return new Uint8Array(await new Response(inflate).arrayBuffer()); + } + throw new Error("no iCCP chunk"); +} + +// The fixture's only `colr` is nclx; swap it for an embedded ICC profile and fix up sizes and offsets. +function replaceHeicColorWithProfile(heic: Uint8Array, profile: Uint8Array) { + const view = new DataView(heic.buffer); + const colr = heic.findIndex((_, index) => view.getUint32(index) === 0x636f6c72) - 4; + const colrSize = view.getUint32(colr); + const box = new Uint8Array(12 + profile.length); + new DataView(box.buffer).setUint32(0, box.length); + box.set(new TextEncoder().encode("colrprof"), 4); + box.set(profile, 12); + const delta = box.length - colrSize; + const out = new Uint8Array(heic.length + delta); + out.set(heic.subarray(0, colr)); + out.set(box, colr); + out.set(heic.subarray(colr + colrSize), colr + box.length); + const outView = new DataView(out.buffer); + const find = (type: string) => + out.findIndex((_, index) => new TextDecoder().decode(out.subarray(index, index + 4)) === type) - + 4; + for (const type of ["meta", "iprp", "ipco"]) { + const offset = find(type); + outView.setUint32(offset, outView.getUint32(offset) + delta); + } + // iloc v0 with 4-byte offsets and lengths, no base offset: one extent per item. + const iloc = find("iloc"); + for (let item = 0; item < outView.getUint16(iloc + 14); item += 1) { + const extentOffset = iloc + 16 + item * 14 + 6; + outView.setUint32(extentOffset, outView.getUint32(extentOffset) + delta); + } + return out; +} + +describe("prepareImageForAttachment color", () => { + // P3 green lies outside sRGB, so an sRGB canvas clips it; a P3 canvas would turn sRGB red's + // stored (255,0,0) into P3 values. + it.each([ + ["Display P3 PNG", "display-p3", "color(display-p3 0 1 0)", "image/png"], + ["Display P3 JPEG", "display-p3", "color(display-p3 0 1 0)", "image/jpeg"], + ["sRGB PNG", "srgb", "#ff0000", "image/png"], + ["sRGB JPEG", "srgb", "#ff0000", "image/jpeg"], + ] as const)("keeps a downscaled %s in its own color space", async (_, space, fill, type) => { + const source = await makeImage(space, fill, type); + + const result = await prepareImageForAttachment(source, 20 * 1024 * 1024); + if (!result.ok) throw new Error(result.reason); + expect(result.recompressed).toBe(true); + expect(result.imageSize).toEqual({ width: 2000, height: 1333 }); + await expectSameColors(result.file, source); + }); + + it("keeps Display P3 colors when the stash re-encodes a WebP", async () => { + const source = await makeImage("display-p3", "color(display-p3 0 1 0)", "image/webp"); + const result = await compressImageForStash( + source, + (await readFileAsDataUrl(source)).length - 1, + ); + if (!result.ok) throw new Error(result.reason); + expect(result.image.recompressed).toBe(true); + const stored = dataUrlToFile(result.image.dataUrl, "stash", result.image.mimeType); + await expectSameColors(stored, source); + }); + + it("keeps Display P3 colors when it converts a P3-tagged HEIC that the browser cannot decode", async () => { + const fixture = new Uint8Array(await (await fetch(heicUrl)).arrayBuffer()); + const fixtureResult = await prepareImageForAttachment( + new File([fixture], "photo.heic", { type: "image/heic" }), + 20 * 1024 * 1024, + ); + if (!fixtureResult.ok) throw new Error(fixtureResult.reason); + // The fixture declares unspecified primaries, so it decodes as sRGB. + const decoded = await readPixel(fixtureResult.file, true); + + const nclx = fixture.slice(); + const nclxOffset = nclx.findIndex( + (_, index) => new DataView(nclx.buffer).getUint32(index) === 0x6e636c78, + ); + new DataView(nclx.buffer).setUint16(nclxOffset + 4, 12); + const tagged = [ + nclx, + replaceHeicColorWithProfile(fixture, await readChromiumDisplayP3Profile()), + ]; + for (const heic of tagged) { + const result = await prepareImageForAttachment( + new File([heic], "photo.heic", { type: "image/heic" }), + 20 * 1024 * 1024, + ); + if (!result.ok) throw new Error(result.reason); + expectNear(await readPixel(result.file), decoded); + } + }); +}); diff --git a/apps/web/src/lib/imageCompression.ts b/apps/web/src/lib/imageCompression.ts index b876ceff6a44a..7e5485cabcee9 100644 --- a/apps/web/src/lib/imageCompression.ts +++ b/apps/web/src/lib/imageCompression.ts @@ -88,37 +88,198 @@ function findHeicMetadataBox( return null; } -async function validateHeicImageDimensions( - file: File, -): Promise { +// D50-adapted Display P3 primaries, as an ICC profile's rXYZ, gXYZ and bXYZ tags carry them. +const DISPLAY_P3_ICC_PRIMARIES = [ + [0x7258595a, 0.5151, 0.2412, -0.0011], + [0x6758595a, 0.292, 0.6922, 0.0419], + [0x6258595a, 0.1571, 0.0666, 0.7841], +] as const; + +function iccProfileIsDisplayP3(view: DataView, start: number, end: number): boolean { + if (start + 132 > end) return false; + const tagCount = Math.min(view.getUint32(start + 128), Math.floor((end - start - 132) / 12)); + let matched = 0; + for (let index = 0; index < tagCount; index += 1) { + const entry = start + 132 + index * 12; + const primary = DISPLAY_P3_ICC_PRIMARIES.find( + ([signature]) => signature === view.getUint32(entry), + ); + if (!primary) continue; + const tag = start + view.getUint32(entry + 4); + if (tag < start || tag + 20 > end || view.getUint32(tag) !== 0x58595a20) return false; + for (let axis = 0; axis < 3; axis += 1) { + if (Math.abs(view.getInt32(tag + 8 + axis * 4) / 65536 - primary[axis + 1]!) > 0.005) { + return false; + } + } + matched += 1; + } + return matched === DISPLAY_P3_ICC_PRIMARIES.length; +} + +/** `colr` is an nclx code point (12 is Display P3) or an embedded ICC profile. */ +function heicColorIsDisplayP3(view: DataView, box: HeicMetadataBox): boolean { + if (box.payloadOffset + 6 > box.endOffset) return false; + const colorType = view.getUint32(box.payloadOffset); + if (colorType === 0x6e636c78) return view.getUint16(box.payloadOffset + 4) === 12; + if (colorType === 0x70726f66 || colorType === 0x72494343) { + return iccProfileIsDisplayP3(view, box.payloadOffset + 4, box.endOffset); + } + return false; +} + +type HeicMetadataResult = + | { ok: true; displayP3: boolean } + | { ok: false; reason: ImageCompressionFailureReason }; + +async function readHeicMetadata(file: File): Promise { + const unreadable = { ok: false, reason: "unreadable" } as const; const metadata = await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer(); const view = new DataView(metadata); const meta = findHeicMetadataBox(view, 0, view.byteLength, 0x6d657461); - if (!meta || meta.payloadOffset + 4 > meta.endOffset) return "unreadable"; + if (!meta || meta.payloadOffset + 4 > meta.endOffset) return unreadable; const properties = findHeicMetadataBox(view, meta.payloadOffset + 4, meta.endOffset, 0x69707270); - if (!properties) return "unreadable"; + if (!properties) return unreadable; const containers = findHeicMetadataBox( view, properties.payloadOffset, properties.endOffset, 0x6970636f, ); - if (!containers) return "unreadable"; + if (!containers) return unreadable; let offset = containers.payloadOffset; let foundImageDimensions = false; while (offset < containers.endOffset) { const image = findHeicMetadataBox(view, offset, containers.endOffset, 0x69737065); if (!image) break; - if (image.payloadOffset + 12 > image.endOffset) return "unreadable"; + if (image.payloadOffset + 12 > image.endOffset) return unreadable; const width = view.getUint32(image.payloadOffset + 4); const height = view.getUint32(image.payloadOffset + 8); - if (width === 0 || height === 0) return "unreadable"; - if (width > MAX_HEIC_DECODE_PIXELS / height) return "too-large"; + if (width === 0 || height === 0) return unreadable; + if (width > MAX_HEIC_DECODE_PIXELS / height) return { ok: false, reason: "too-large" }; foundImageDimensions = true; offset = image.endOffset; } - return foundImageDimensions ? null : "unreadable"; + if (!foundImageDimensions) return unreadable; + + let displayP3 = false; + offset = containers.payloadOffset; + while (!displayP3 && offset < containers.endOffset) { + const color = findHeicMetadataBox(view, offset, containers.endOffset, 0x636f6c72); + if (!color) break; + displayP3 = heicColorIsDisplayP3(view, color); + offset = color.endOffset; + } + return { ok: true, displayP3 }; +} + +async function inflateIccProfile(deflated: Uint8Array): Promise { + const reader = new Blob([deflated]) + .stream() + .pipeThrough(new DecompressionStream("deflate")) + .getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + length += value.length; + // A real profile is a few KiB; refuse to inflate a compression bomb. + if (length > MAX_HEIC_METADATA_BYTES) return null; + chunks.push(value); + } + } catch { + return null; + } finally { + void reader.cancel().catch(() => undefined); + } + const profile = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + profile.set(chunk, offset); + offset += chunk.length; + } + return profile; +} + +function iccProfileBytesAreDisplayP3(profile: Uint8Array): boolean { + return iccProfileIsDisplayP3( + new DataView(profile.buffer, profile.byteOffset, profile.byteLength), + 0, + profile.byteLength, + ); +} + +async function pngIsDisplayP3(bytes: Uint8Array, view: DataView): Promise { + for (let offset = 8; offset + 8 <= bytes.length;) { + const length = view.getUint32(offset); + const type = view.getUint32(offset + 4); + const data = offset + 8; + if (type === 0x49444154 || data + length > bytes.length) return false; + if (type === 0x63494350) return length >= 1 && bytes[data] === 12; + if (type === 0x69434350) { + const nameEnd = bytes.subarray(data, data + Math.min(length, 80)).indexOf(0); + if (nameEnd < 0) return false; + const profile = await inflateIccProfile(bytes.slice(data + nameEnd + 2, data + length)); + return profile !== null && iccProfileBytesAreDisplayP3(profile); + } + offset = data + length + 4; + } + return false; +} + +const JPEG_ICC_SIGNATURE = "ICC_PROFILE\0"; + +function jpegIsDisplayP3(bytes: Uint8Array, view: DataView): boolean { + const segments: Uint8Array[] = []; + for (let offset = 2; offset + 4 <= bytes.length && bytes[offset] === 0xff;) { + const marker = bytes[offset + 1]!; + if (marker === 0xda || marker === 0xd9) break; + const length = view.getUint16(offset + 2); + const end = offset + 2 + length; + if (length < 2 || end > bytes.length) break; + const signature = String.fromCharCode(...bytes.subarray(offset + 4, offset + 16)); + if (marker === 0xe2 && signature === JPEG_ICC_SIGNATURE) { + segments.push(bytes.subarray(offset + 18, end)); + } + offset = end; + } + if (segments.length === 0) return false; + const profile = new Uint8Array(segments.reduce((total, segment) => total + segment.length, 0)); + let offset = 0; + for (const segment of segments) { + profile.set(segment, offset); + offset += segment.length; + } + return iccProfileBytesAreDisplayP3(profile); +} + +function webpIsDisplayP3(bytes: Uint8Array, view: DataView): boolean { + if (view.getUint32(8) !== 0x57454250) return false; + for (let offset = 12; offset + 8 <= bytes.length;) { + const type = view.getUint32(offset); + const length = view.getUint32(offset + 4, true); + const data = offset + 8; + if (data + length > bytes.length) return false; + if (type === 0x49434350) return iccProfileIsDisplayP3(view, data, data + length); + offset = data + length + (length % 2); + } + return false; +} + +/** Re-encode on a canvas in the source's own color space, so it keeps its gamut and profile. */ +async function readImageColorSpace(file: Blob): Promise { + const bytes = new Uint8Array(await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer()); + if (bytes.length < 16) return "srgb"; + const view = new DataView(bytes.buffer); + const signature = view.getUint32(0); + let displayP3 = false; + if (signature === 0x89504e47) displayP3 = await pngIsDisplayP3(bytes, view); + else if (signature >>> 16 === 0xffd8) displayP3 = jpegIsDisplayP3(bytes, view); + else if (signature === 0x52494646) displayP3 = webpIsDisplayP3(bytes, view); + return displayP3 ? "display-p3" : "srgb"; } export function readFileAsDataUrl(file: Blob): Promise { @@ -173,10 +334,14 @@ interface Canvas2D { context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D; } -function createCanvas(width: number, height: number): Canvas2D | null { +function createCanvas( + width: number, + height: number, + colorSpace: PredefinedColorSpace, +): Canvas2D | null { if (typeof OffscreenCanvas === "function") { const canvas = new OffscreenCanvas(width, height); - const context = canvas.getContext("2d"); + const context = canvas.getContext("2d", { colorSpace }); if (!context) return null; return { canvas, context }; } @@ -184,7 +349,7 @@ function createCanvas(width: number, height: number): Canvas2D | null { const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; - const context = canvas.getContext("2d"); + const context = canvas.getContext("2d", { colorSpace }); if (!context) return null; return { canvas, context }; } @@ -250,8 +415,9 @@ async function renderComposerImageThumbnail(file: File): Promise if (!canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null; let bitmap: ImageBitmap | undefined; try { + const colorSpace = await readImageColorSpace(file); bitmap = await createImageBitmap(file); - return await renderComposerImageThumbnailFromBitmap(bitmap); + return await renderComposerImageThumbnailFromBitmap(bitmap, colorSpace); } catch { return null; } finally { @@ -259,12 +425,15 @@ async function renderComposerImageThumbnail(file: File): Promise } } -async function renderComposerImageThumbnailFromBitmap(bitmap: ImageBitmap): Promise { +async function renderComposerImageThumbnailFromBitmap( + bitmap: ImageBitmap, + colorSpace: PredefinedColorSpace, +): Promise { try { const side = Math.min(bitmap.width, bitmap.height); if (side <= 0) return null; const dimension = Math.min(256, side); - const surface = createCanvas(dimension, dimension); + const surface = createCanvas(dimension, dimension, colorSpace); if (!surface) return null; surface.context.drawImage( bitmap, @@ -286,6 +455,7 @@ async function renderComposerImageThumbnailFromBitmap(bitmap: ImageBitmap): Prom async function encodeWithinBudget( bitmap: ImageBitmap, + colorSpace: PredefinedColorSpace, maxDimension: number, budgetChars: number, preferredMimeType?: "image/jpeg", @@ -293,7 +463,7 @@ async function encodeWithinBudget( const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height)); const width = Math.max(1, Math.round(bitmap.width * scale)); const height = Math.max(1, Math.round(bitmap.height * scale)); - const target = createCanvas(width, height); + const target = createCanvas(width, height, colorSpace); if (!target) return null; // Probe the codec before drawing; JPEG needs a white matte because it has no alpha. @@ -333,7 +503,9 @@ async function reencodeWithinBudget( } let bitmap: ImageBitmap; + let colorSpace: PredefinedColorSpace; try { + colorSpace = await readImageColorSpace(file); bitmap = await createImageBitmap(file); } catch { return { ok: false, reason: "unreadable" }; @@ -347,7 +519,13 @@ async function reencodeWithinBudget( const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale)); let encoded: Awaited>; try { - encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars, preferredMimeType); + encoded = await encodeWithinBudget( + bitmap, + colorSpace, + targetDimension, + budgetChars, + preferredMimeType, + ); } catch { encodeFailed = true; continue; @@ -415,7 +593,7 @@ async function fitImageToMaxEdge(file: File): Promise<{ file: File; imageSize: I bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); const imageSize = fitImageAttachmentSize(bitmap); if (!imageSize) return null; - const target = createCanvas(imageSize.width, imageSize.height); + const target = createCanvas(imageSize.width, imageSize.height, await readImageColorSpace(file)); if (!target) return null; target.context.imageSmoothingQuality = "high"; target.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height); @@ -494,6 +672,17 @@ function prepareHeicImage(file: File) { return preparation; } +async function readPixelsAsDisplayP3( + bitmap: ImageBitmap, + { width, height }: ImageSize, +): Promise { + const raw = createCanvas(width, height, "srgb"); + if (!raw) return undefined; + raw.context.drawImage(bitmap, 0, 0, width, height); + const pixels = raw.context.getImageData(0, 0, width, height); + return createImageBitmap(new ImageData(pixels.data, width, height, { colorSpace: "display-p3" })); +} + async function convertHeicImage( file: File, onThumbnail: (src: string | null) => void, @@ -504,14 +693,13 @@ async function convertHeicImage( let bitmap: ImageBitmap | undefined; try { - const dimensionError = await validateHeicImageDimensions(file); - if (dimensionError) { - return { ok: false, reason: dimensionError }; - } + const metadata = await readHeicMetadata(file); + if (!metadata.ok) return metadata; bitmap = typeof createImageBitmap === "function" ? await createImageBitmap(file).catch(() => undefined) : undefined; + const decodedNatively = bitmap !== undefined; if (!bitmap) { const { heicTo } = await import("heic-to/csp"); bitmap = await heicTo({ blob: file, type: "bitmap" }); @@ -520,12 +708,20 @@ async function convertHeicImage( width: bitmap.width, height: bitmap.height, }; - const surface = createCanvas(imageSize.width, imageSize.height); + // heic-to ignores the color profile and hands back the raw Display P3 values as sRGB. + if (!decodedNatively && metadata.displayP3) { + const source = bitmap; + bitmap = await readPixelsAsDisplayP3(source, imageSize); + source.close(); + if (!bitmap) return { ok: false, reason: "unreadable" }; + } + const colorSpace = metadata.displayP3 ? "display-p3" : "srgb"; + const surface = createCanvas(imageSize.width, imageSize.height, colorSpace); if (!surface) return { ok: false, reason: "unreadable" }; surface.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height); const [converted] = await Promise.all([ encodeCanvas(surface.canvas, QUALITY_STEPS[0], "image/jpeg"), - renderComposerImageThumbnailFromBitmap(bitmap).then(onThumbnail), + renderComposerImageThumbnailFromBitmap(bitmap, colorSpace).then(onThumbnail), ]); if (!converted) return { ok: false, reason: "unreadable" }; return { diff --git a/apps/web/src/lib/pageTranslationGuard.browser.test.tsx b/apps/web/src/lib/pageTranslationGuard.browser.test.tsx new file mode 100644 index 0000000000000..40d7e7597ccf8 --- /dev/null +++ b/apps/web/src/lib/pageTranslationGuard.browser.test.tsx @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { guardDomAgainstPageTranslation } from "./pageTranslationGuard"; + +// What Chrome's page translator does: swap each text node for translation. +function translatePage(root: Element) { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + const textNodes: Text[] = []; + while (walker.nextNode()) textNodes.push(walker.currentNode as Text); + for (const text of textNodes) { + if (!text.nodeValue?.trim()) continue; + const outer = document.createElement("font"); + const inner = document.createElement("font"); + inner.textContent = `译:${text.nodeValue}`; + outer.append(inner); + text.replaceWith(outer); + } +} + +function Status({ running }: { running: boolean }) { + return ( +

+ {running ? "Working" : } + {"for 2s"} +
+ ); +} + +describe("guardDomAgainstPageTranslation", () => { + it("keeps React committing after page translation replaced its text nodes", async () => { + guardDomAgainstPageTranslation(); + await using screen = await render(, { router: false }); + translatePage(screen.container); + + // Removing "Working" hits removeChild; placing the icon before "for 2s" hits insertBefore. + await screen.rerender(); + await expect.element(screen.getByTestId("done")).toBeInTheDocument(); + await screen.rerender(); + await expect.element(screen.getByTestId("done")).not.toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/lib/pageTranslationGuard.ts b/apps/web/src/lib/pageTranslationGuard.ts new file mode 100644 index 0000000000000..de8dbceb8e2bf --- /dev/null +++ b/apps/web/src/lib/pageTranslationGuard.ts @@ -0,0 +1,20 @@ +// Browser page translation (Chrome, Edge) swaps text nodes for wrappers React does not +// know about, so a later removeChild or insertBefore on the original node throws NotFoundError +// and takes down the whole tree. See facebook/react#11538. +export function guardDomAgainstPageTranslation(): void { + const proto = Node.prototype; + const removeChild = proto.removeChild; + const insertBefore = proto.insertBefore; + + proto.removeChild = function (this: Node, child: T): T { + // Already detached by the translator: nothing left to remove. + if (child.parentNode !== this) return child; + return removeChild.call(this, child) as T; + }; + + proto.insertBefore = function (this: Node, node: T, reference: Node | null): T { + // The anchor was replaced; append so the new node still shows. + const anchor = reference && reference.parentNode !== this ? null : reference; + return insertBefore.call(this, node, anchor) as T; + }; +} diff --git a/apps/web/src/lib/selectionActions.browser.test.ts b/apps/web/src/lib/selectionActions.browser.test.ts new file mode 100644 index 0000000000000..de5b70908fbb6 --- /dev/null +++ b/apps/web/src/lib/selectionActions.browser.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { fakeTimers } from "../../test/render"; +import { observeSelectionActions, SELECTION_MULTI_CLICK_INTERVAL_MS } from "./selectionActions"; + +describe("observeSelectionActions", () => { + it.each([ + { immediateMultiClick: false, nextFrame: [], afterInterval: [[{ x: 40, y: 12 }]] }, + { immediateMultiClick: true, nextFrame: [[null]], afterInterval: [[null]] }, + ])( + "double-click with immediateMultiClick=$immediateMultiClick", + ({ immediateMultiClick, nextFrame, afterInterval }) => { + using stack = new DisposableStack(); + const element = stack.adopt(document.body.appendChild(document.createElement("div")), (e) => + e.remove(), + ); + stack.use(fakeTimers()); + const onSelection = vi.fn(); + const actions = observeSelectionActions({ + element, + immediateMultiClick, + onSelection, + onDismiss: () => {}, + }); + stack.defer(() => actions.dispose()); + + element.dispatchEvent( + new PointerEvent("pointerdown", { bubbles: true, isPrimary: true, button: 0 }), + ); + element.dispatchEvent( + new MouseEvent("mouseup", { + bubbles: true, + button: 0, + detail: 2, + clientX: 40, + clientY: 12, + }), + ); + + vi.advanceTimersByTime(20); + expect(onSelection.mock.calls).toEqual(nextFrame); + vi.advanceTimersByTime(SELECTION_MULTI_CLICK_INTERVAL_MS - 21); + expect(onSelection.mock.calls).toEqual(nextFrame); + vi.advanceTimersByTime(50); + expect(onSelection.mock.calls).toEqual(afterInterval); + }, + ); +}); diff --git a/apps/web/src/lib/selectionActions.ts b/apps/web/src/lib/selectionActions.ts index 9303602097543..2c219000290c3 100644 --- a/apps/web/src/lib/selectionActions.ts +++ b/apps/web/src/lib/selectionActions.ts @@ -47,12 +47,19 @@ export function observeSelectionActions({ element, getActionElement, restoreAfterScroll = false, + immediateMultiClick = false, onSelection, onDismiss, }: { element: HTMLElement; getActionElement?: () => HTMLElement | null; restoreAfterScroll?: boolean; + /** + * Show double- and triple-click selections at once instead of waiting out the multi-click + * interval. Their pointer is withheld so the action anchors below the selection, clear of + * the spot where a following click lands. + */ + immediateMultiClick?: boolean; onSelection: (pointer: SelectionActionPoint | null) => void; onDismiss: (reason: "interaction" | "cancel") => void; }) { @@ -132,8 +139,9 @@ export function observeSelectionActions({ pointerDown = false; if (!gestureActive) return; gestureActive = false; - pointer = { x: event.clientX, y: event.clientY }; - schedule(event.detail >= 2 ? SELECTION_MULTI_CLICK_INTERVAL_MS : 0); + const multiClick = event.detail >= 2; + pointer = multiClick && immediateMultiClick ? null : { x: event.clientX, y: event.clientY }; + schedule(multiClick && !immediateMultiClick ? SELECTION_MULTI_CLICK_INTERVAL_MS : 0); }; const onKeyDown = (event: KeyboardEvent) => { if (isActionTarget(event.target) && event.key !== "Escape") return; diff --git a/apps/web/src/main.test.ts b/apps/web/src/main.test.ts index 56be08671e331..11b9b68c867d1 100644 --- a/apps/web/src/main.test.ts +++ b/apps/web/src/main.test.ts @@ -5,7 +5,7 @@ vi.mock("./AppRoot", () => ({ AppRoot: () => null })); vi.mock("./i18n/runtime", () => ({ whenLocaleReady: async () => {} })); vi.mock("react-dom/client", () => ({ default: { createRoot: () => ({ render: () => {} }) } })); -// Boots main in a fresh page that shares the tab's sessionStorage, as a reload does. +// Boots the entry in a fresh page that shares the tab's sessionStorage, as a reload does. async function bootThenFailLazyChunk(sessionStorage: Map) { vi.resetModules(); const reload = vi.fn().mockName("location.reload"); @@ -20,8 +20,8 @@ async function bootThenFailLazyChunk(sessionStorage: Map) { vi.stubGlobal("window", page); vi.stubGlobal("document", { getElementById: () => ({}) }); try { - const { startup } = await import("./main"); - await startup; + const { boot } = await import("./bootstrap"); + await boot; page.dispatchEvent(new Event("vite:preloadError", { cancelable: true })); return reload; } finally { diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index 112de4848170c..51aeeade6863d 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -9,20 +9,12 @@ import { isElectron } from "./env"; import { startAppServices } from "./appInit"; import { AppRoot } from "./AppRoot"; import { whenLocaleReady } from "./i18n/runtime"; -import { reloadOnceForChunkLoadError } from "./lib/chunkReloadGuard"; +import { chunkLoadState } from "./lib/chunkReloadGuard"; const router = startAppServices(); const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined; -let reloadScheduled = false; -window.addEventListener("vite:preloadError", (event) => { - if (reloadOnceForChunkLoadError()) { - reloadScheduled = true; - event.preventDefault(); - } -}); - const app = ; // Split by runtime to keep Clerk out of local startup and clerk-js out of browser builds. @@ -40,7 +32,7 @@ export const startup = Promise.all([ ]) .then(([ManagedAuthShell]) => { // Route chunk failures resolve router.load() and surface later through the error boundary. - if (reloadScheduled) return; + if (chunkLoadState.reloadScheduled) return; ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( {ManagedAuthShell && clerkPublishableKey ? ( @@ -52,6 +44,6 @@ export const startup = Promise.all([ ); }) .catch((error: unknown) => { - if (reloadScheduled) return; + if (chunkLoadState.reloadScheduled) return; throw error; }); diff --git a/apps/web/src/markdown-clipboard.test.ts b/apps/web/src/markdown-clipboard.test.ts index 1b0aa804a8437..7a50785c726c7 100644 --- a/apps/web/src/markdown-clipboard.test.ts +++ b/apps/web/src/markdown-clipboard.test.ts @@ -11,19 +11,27 @@ import { collectAssistantCitations, serializeAssistantCitation, } from "@t3tools/shared/assistantCitations"; -import { markdownMathRanges, parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; +import type { Element as HastElement, ElementContent, Root } from "hast"; -import { unified } from "unified"; -import remarkParse from "remark-parse"; -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_USER_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; +import { markdownTree } from "./markdown/wordsHast"; -const userMarkdown = unified() - .use(remarkParse) - .use(CHAT_MARKDOWN_REMARK_PLUGINS) - .use(CHAT_USER_MARKDOWN_REMARK_PLUGINS); +// Copied Markdown read back as the chat reads it, to check it says what was copied. +const elementsOf = (node: Root | HastElement) => + (node.children as ElementContent[]).filter( + (child): child is HastElement => child.type === "element", + ); +const textOf = (node: ElementContent): string => + node.type === "text" + ? node.value + : node.type === "element" + ? node.children.map(textOf).join("") + : ""; +const readBack = (markdown: string, options?: Parameters[1]) => + elementsOf(markdownTree(markdown, options))[0]!; +// A user message's reading: a single `~` stays text. +const readUserBack = (markdown: string) => readBack(markdown, { singleTilde: false }); +const inline = (node: ElementContent) => + node.type === "element" ? [node.tagName, textOf(node)] : [node.type, textOf(node)]; const TEXT_NODE = 3; const ELEMENT_NODE = 1; @@ -223,10 +231,10 @@ describe("serializeRenderedMarkdownFragment", () => { new FakeText(" here."), ), ); - const paragraph = parseMarkdownWithMath(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); - expect(paragraph.children.find((child) => child.type === "inlineCode")?.value).toBe(value); + const paragraph = readBack(serializeRenderedMarkdownFragment(asNode(container))); + const code = elementsOf(paragraph).find((child) => child.tagName === "code"); + expect(paragraph.tagName).toBe("p"); + expect(code && textOf(code)).toBe(value); }); it.each([ @@ -238,28 +246,24 @@ describe("serializeRenderedMarkdownFragment", () => { String.raw`before\ after\ end`, ])("copies prose that parses back unchanged: %s", (value) => { const container = new FakeElement("DIV").append(new FakeText(value)); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - expect(paragraph).toMatchObject({ type: "paragraph", children: [{ type: "text", value }] }); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect(paragraph.tagName).toBe("p"); + expect(paragraph.children.map(inline)).toEqual([["text", value]]); }); it.each([ - ["*", "EM", "word", "emphasis"], - ["\\", "CODE", "value", "inlineCode"], - ])("keeps a text edge %j beside %s", (edge, tag, value, type) => { + ["*", "EM", "word"], + ["\\", "CODE", "value"], + ])("keeps a text edge %j beside %s", (edge, tag, value) => { const container = new FakeElement("DIV").append( new FakeText(edge), new FakeElement(tag).append(new FakeText(value)), ); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - expect(paragraph).toMatchObject({ - type: "paragraph", - children: [ - { type: "text", value: edge }, - type === "inlineCode" ? { type, value } : { type, children: [{ type: "text", value }] }, - ], - }); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect(paragraph.children.map(inline)).toEqual([ + ["text", edge], + [tag.toLowerCase(), value], + ]); }); it("copies email links with their address and drops in-app destinations", () => { @@ -288,10 +292,10 @@ describe("serializeRenderedMarkdownFragment", () => { expect(copied).toBe( "Write to support@example.com, [Support](mailto:support@example.com?subject=Help), [Support](mailto:support@example.com?subject=Help\\)) or the thread.", ); - const paragraph = parseMarkdownWithMath(copied).children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); expect( - paragraph.children.filter((child) => child.type === "link").map((link) => link.url), + elementsOf(readBack(copied)) + .filter((child) => child.tagName === "a") + .map((link) => link.properties.href), ).toEqual([ "mailto:support@example.com", "mailto:support@example.com?subject=Help", @@ -312,12 +316,14 @@ describe("serializeRenderedMarkdownFragment", () => { ])("keeps the link label and destination: %s", (label, href) => { const anchor = new FakeElement("A", [], { href }).append(new FakeText(label)); const container = new FakeElement("DIV").append(anchor); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); - expect(paragraph.children).toMatchObject([ - { type: "link", url: href, children: [{ type: "text", value: label }] }, - ]); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect( + paragraph.children.map((child) => + child.type === "element" + ? [child.tagName, decodeURI(String(child.properties.href)), textOf(child)] + : [child.type, textOf(child)], + ), + ).toEqual([["a", href, label]]); }); it("copies alert and insight callouts as their Markdown instead of the rendered label", () => { @@ -484,31 +490,25 @@ describe("copying rendered Markdown tables", () => { ); const markdown = serializeTableElementToMarkdown(table as unknown as Element); - const tree = parseMarkdownWithMath(markdown); - const parsed = tree.children[0]; - if (parsed?.type !== "table") throw new Error("Expected a table"); - expect(parsed.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2, 2]); - expect(markdownMathRanges(markdown, tree).map((formula) => formula.tex)).toEqual([ - "|x|", - "\\|x\\|", - "|y|", - "|z|", - ]); - expect(parsed.children[1]?.children[1]?.children).toMatchObject([ - { type: "text", value: "*a* | ~~b~~" }, - ]); - expect(parsed.children[4]?.children[1]?.children).toMatchObject([ - { type: "text", value: "> c | d" }, - ]); - const [, , codeRow, linkRow] = parsed.children; - expect(codeRow?.children[1]?.children[0]).toMatchObject({ - type: "inlineCode", - value: "\\(c|d\\)", - }); - expect(linkRow?.children[0]?.children[0]).toMatchObject({ - type: "link", - url: "https://example.com/?q=a|b", - }); + const parsed = readBack(markdown, { math: true }); + expect(parsed.tagName).toBe("table"); + const rows = elementsOf(parsed).flatMap((section) => elementsOf(section)); + const cells = rows.map((row) => elementsOf(row)); + expect(cells.map((row) => row.length)).toEqual([2, 2, 2, 2, 2]); + const formulas: string[] = []; + const visit = (node: HastElement) => { + if (node.tagName === "svg") formulas.push(String(node.properties.ariaLabel)); + else elementsOf(node).forEach(visit); + }; + visit(parsed); + expect(formulas).toEqual(["|x|", "\\|x\\|", "|y|", "|z|"]); + expect(textOf(cells[1]![1]!)).toBe("*a* | ~~b~~"); + expect(textOf(cells[4]![1]!).trim()).toBe("> c | d"); + expect(inline(cells[2]![1]!.children[0]!)).toEqual(["code", "\\(c|d\\)"]); + const link = cells[3]![0]!.children[0]!; + expect(link.type === "element" && decodeURI(String(link.properties.href))).toBe( + "https://example.com/?q=a|b", + ); }); it("copies code and diagrams in cells without markers or unescaped pipes", () => { diff --git a/apps/web/src/markdown-clipboard.ts b/apps/web/src/markdown-clipboard.ts index 7421dbadd4bae..39ef90b2ec19a 100644 --- a/apps/web/src/markdown-clipboard.ts +++ b/apps/web/src/markdown-clipboard.ts @@ -1,4 +1,4 @@ -import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownWindowsPaths"; +import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownLinks"; const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]); const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"]; @@ -428,7 +428,7 @@ export function serializeTableElementToMarkdown(table: Element): string { return serializeTable(table).replaceAll(CODE_BOUNDARY, "").trim(); } -// The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops +// The wrapper wordsHast puts on every formula it renders. The sanitizer drops // the attribute from authored HTML. const MATH_SELECTOR = "[data-markdown-math]"; diff --git a/apps/web/src/markdown-incremental.test.tsx b/apps/web/src/markdown-incremental.test.tsx deleted file mode 100644 index 3682deb281fa9..0000000000000 --- a/apps/web/src/markdown-incremental.test.tsx +++ /dev/null @@ -1,135 +0,0 @@ -import { CHAT_MARKDOWN_REHYPE_PLUGINS } from "@t3tools/shared/markdownPipeline"; -import type { Root } from "mdast"; -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; -import remarkGfm from "remark-gfm"; -import type { Plugin } from "unified"; -import { describe, expect, it } from "vite-plus/test"; - -import { remarkCodexDirectives } from "@t3tools/shared/codexMarkdownDirectives"; -import { remarkGithubAlerts } from "@t3tools/shared/markdownGithubAlerts"; -import { createIncrementalMarkdownPlugin } from "./markdown-incremental"; -import { remarkNormalizeListItemIndentation } from "@t3tools/shared/markdownListIndentation"; - -function render(source: string, incremental?: Plugin<[], Root>, parsedSources?: string[]) { - let tree: Root | undefined; - const observeParsing: Plugin<[], Root> = function () { - const original = this.parser; - if (original) { - this.parser = (text, file) => { - parsedSources?.push(text); - return original(text, file); - }; - } - }; - const capture: Plugin<[], Root> = () => (root) => { - tree = structuredClone(root); - }; - const html = renderToStaticMarkup( - - {source} - , - ); - return { html, tree }; -} - -const prefix = "# Before\n\n```ts\nconst values = [1, 2];\n```\n\n"; - -describe("incremental Markdown parsing", () => { - it("keeps the document prefix cached when list recovery parses contain fences", () => { - const source = - prefix + - "- first block\n\n ```ts\n const nested = 1;\n ```\n\n tail"; - const incremental = createIncrementalMarkdownPlugin(); - const parsedSources: string[] = []; - expect(render(source, incremental, parsedSources)).toEqual(render(source)); - parsedSources.length = 0; - const next = source + " more"; - expect(render(next, incremental, parsedSources)).toEqual(render(next)); - expect(parsedSources).not.toContain(next); - expect(parsedSources.some((text) => text.startsWith("t3-markdown-inline-prefix:"))).toBe(true); - }); - - it.each([ - "a\n===\n\nb\n---\n", - "- first\n\n continued\n\n- next\n", - "> quoted\n>\n> ```js\n> abc\n> ```\n\nend", - "
\nhello\n\n
\n\nend", - "[ref]\n\n[ref]: /later", - "a[^x]\n\n[^x]: note", - "a | b\n--|--\na | b\n", - "```\na\n```\n\nnext\n\n~~~\nb\n~~~\n\nmore", - "\n\n\tcode\n\nmore", - "text *bold*", - "> [!NOTE]\n> alert\n\n- [ ] task", - "\uFEFFtext after a byte-order mark", - ])("preserves the parse tree, positions, and HTML while streaming %j", (tail) => { - const source = prefix + tail; - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 0; end <= source.length; end++) { - const text = source.slice(0, end); - expect(render(text, incremental), `prefix ${end}`).toEqual(render(text)); - } - }); - - it.each(["\r\n", "\r"])("preserves partial %j line endings", (newline) => { - const source = (prefix + "next\n\n```\nlast\n```\n\nend").replaceAll("\n", newline); - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 0; end <= source.length; end++) { - const text = source.slice(0, end); - expect(render(text, incremental)).toEqual(render(text)); - } - }); - - it("updates earlier references when definitions arrive after the cached prefix", () => { - const before = "[later] and footnote[^note]\n\n" + prefix; - const incremental = createIncrementalMarkdownPlugin(); - for (const tail of ["text", "[later]: /target", "[later]: /target\n\n[^note]: a note"]) { - expect(render(before + tail, incremental)).toEqual(render(before + tail)); - } - }); - - it("handles edits, replacements, and repeated renders without leaking transformed nodes", () => { - const incremental = createIncrementalMarkdownPlugin(); - const documents = [ - prefix + "- first\n - second", - prefix + "> [!NOTE]\n> transformed alert", - prefix + "plain text", - "replacement without fences", - prefix.replace("Before", "Edited") + "edited prefix", - prefix + "plain text", - prefix + "plain text", - ]; - for (const document of documents) { - expect(render(document, incremental)).toEqual(render(document)); - } - }); - - it("does not freeze unclosed, nested, indented, or mismatched fences", () => { - const prefixes = [ - "```\nopen\n\n", - "````\n```\n\n", - "> ```\n> code\n> ```\n\n", - "- ```\n code\n ```\n\n", - " ```\n code\n ```\n\n", - " $y$', + { ...ASSISTANT, math: true }, + ), + ); + expect(html).not.toMatch(/onload|javascript|position|
ReadonlyArray) | null; + }; + /** Expand GitHub `:alias:` emoji shortcodes in prose outside code. */ + readonly githubEmoji?: boolean; +} + +export interface WordsHastOptions { + /** `$…$`, `$$…$$` and `math` code blocks render as SVG. */ + readonly math: boolean; + /** Soft line breaks render as `
`, as remark-breaks does. */ + readonly breaks: boolean; + /** Raw HTML shows as the text it was written as. */ + readonly escapeHtml: boolean; + /** `★ Insight ───` blocks render as insight callouts. */ + readonly insights: boolean; + readonly extensions: MarkdownExtensions; +} + +const CODEX_DIRECTIVES = ["codex-file-citation", "codex-followup", "artifact-template"]; + +const VOID = new Set("area base br col embed hr img input link meta source track wbr".split(" ")); + +const TAG = + /<(\/?)([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|)|]*>|<\?[\s\S]*?\?>/g; +const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g; + +// Start tags an HTML parser closes an open `

` for, and the elements that scope that search. +const CLOSES_PARAGRAPH = new Set( + "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split( + " ", + ), +); +const PARAGRAPH_SCOPE = new Set([ + "applet", + "caption", + "table", + "td", + "th", + "marquee", + "object", + "template", + "button", +]); + +type RenderOptions = Omit; + +const decoder = new TextDecoder(); +const encoder = new TextEncoder(); + +function renderToHtml(markdown: string, options: RenderOptions): Uint8Array { + try { + return wordsRenderToHtml(markdown, options); + } catch { + return encoder.encode( + `

${markdown.replaceAll("&", "&").replaceAll("<", "<").replaceAll("\n", "
")}

`, + ); + } +} + +const decode = (value: string) => (value.includes("&") ? decodeHTML(value) : value); + +function properties(source: string | undefined, inSvg: boolean): Element["properties"] { + const result: Element["properties"] = {}; + if (!source) return result; + for (const match of source.matchAll(ATTRIBUTE)) { + const name = match[1]!; + const info = find(inSvg ? svgSchema : htmlSchema, inSvg ? name : name.toLowerCase()); + const raw = match[2] ?? match[3] ?? match[4]; + if (raw === undefined) { + result[info.property] = info.boolean || info.overloadedBoolean ? true : ""; + continue; + } + // Attribute values decode as attributes: `©=` in a query stays as written. + const value = raw.includes("&") ? decodeHTMLAttribute(raw) : raw; + result[info.property] = + info.spaceSeparated || info.commaSeparated + ? value.split(info.commaSeparated ? "," : /\s+/).filter(Boolean) + : info.boolean + ? true + : value; + } + return result; +} + +interface Tokenized { + readonly root: Root; + /** Elements with a `data-sourcepos`, which raw HTML can write too. */ + readonly positioned: Element[]; +} + +/** + * Hast for Words' HTML. Its own markup is well formed; raw HTML closes where its end tags say, + * and is sanitized afterwards, so a misnested tag can only change structure, never safety. + */ +function tokenize(html: string, offsetOf: (byte: number) => number): Tokenized { + const root: Root = { type: "root", children: [] }; + const positioned: Element[] = []; + const stack: Array = [root]; + let svgDepth = 0; + let last = 0; + // rehypePreserveBareAnchorPlaceholders: an `
` with no attributes that never closes is text. + const anchors: Array<{ element: Element; parent: Root | Element; tag: string } | null> = []; + const text = (end: number) => { + if (end <= last) return; + const parent = stack.at(-1)!; + const value = decode(html.slice(last, end)); + const previous = parent.children.at(-1); + if (previous?.type === "text") previous.value += value; + else parent.children.push({ type: "text", value } as Text); + }; + for (const match of html.matchAll(TAG)) { + text(match.index); + last = match.index + match[0].length; + const tagName = match[2]?.toLowerCase(); + if (!tagName) continue; + if (match[1]) { + if (tagName === "a") anchors.pop(); + if (tagName === "p" && openParagraph(stack) < 0) { + // A stray `

` is an empty paragraph to an HTML parser. + (stack.at(-1)!.children as ElementContent[]).push({ + type: "element", + tagName: "p", + properties: {}, + children: [], + }); + continue; + } + const at = stack.findLastIndex((node) => node.type === "element" && node.tagName === tagName); + if (at > 0) { + for (let index = at; index < stack.length; index++) { + if ((stack[index] as Element).tagName === "svg") svgDepth--; + } + stack.length = at; + } + continue; + } + const inSvg = svgDepth > 0 || tagName === "svg"; + if (!inSvg && CLOSES_PARAGRAPH.has(tagName)) { + const paragraph = openParagraph(stack); + if (paragraph > 0) stack.length = paragraph; + } + const element: Element = { + type: "element", + tagName: inSvg ? match[2]! : tagName, + properties: properties(match[3], inSvg), + children: [], + }; + const sourcepos = element.properties.dataSourcepos; + if (typeof sourcepos === "string") { + delete element.properties.dataSourcepos; + const [start, end] = sourcepos.split("-").map((byte) => offsetOf(Number(byte))); + element.position = { + start: { line: 1, column: start! + 1, offset: start! }, + end: { line: 1, column: end! + 1, offset: end! }, + }; + positioned.push(element); + } + const parent = stack.at(-1)!; + (parent.children as ElementContent[]).push(element); + if (tagName === "a") { + anchors.push(match[3]?.trim() ? null : { element, parent, tag: match[0] }); + } + // The HTML parser ignores `/>` on elements that are not void, such as `
`. + if (!VOID.has(tagName) && (!match[4] || !inSvg)) { + stack.push(element); + if (tagName === "svg") svgDepth++; + } + } + text(html.length); + for (const anchor of anchors) { + if (!anchor) continue; + const siblings = anchor.parent.children as ElementContent[]; + const at = siblings.indexOf(anchor.element); + if (at >= 0) + siblings.splice(at, 1, { type: "text", value: anchor.tag }, ...anchor.element.children); + } + normalizeRawTables(root); + // Words ends each block with a newline; hast from remark has none after the last. + const end = root.children.at(-1); + if (end?.type === "text") { + end.value = end.value.replace(/\n$/, ""); + if (end.value.trim() === "") root.children.pop(); + } + return { root, positioned }; +} + +const positionKey = (node: Element) => + `${node.tagName.toLowerCase()}:${node.position!.start.offset}-${node.position!.end.offset}`; + +/** + * Words' HTML for `markdown` as hast. A position marks what Words generated, so raw HTML that + * writes its own `data-sourcepos` keeps none: Words' elements are those it also writes with raw + * HTML escaped, and a range claimed more often than that is trusted for none of its claimants. + */ +function parse(markdown: string, options: RenderOptions): Root { + const offsetOf = utf16Offsets(markdown); + const render = (escapeHtml?: true) => + tokenize( + decoder.decode( + renderToHtml(markdown, { + ...options, + ...(escapeHtml ? { escapeHtml } : {}), + sourcePositions: true, + }), + ), + offsetOf, + ); + const { root, positioned } = render(); + if (options.escapeHtml || options.skipHtml || !/data-sourcepos/i.test(markdown)) return root; + const generated = new Map(); + for (const node of render(true).positioned) { + const key = positionKey(node); + generated.set(key, (generated.get(key) ?? 0) + 1); + } + const claimed = new Map(); + for (const node of positioned) { + const key = positionKey(node); + claimed.set(key, (claimed.get(key) ?? 0) + 1); + } + for (const node of positioned) { + const key = positionKey(node); + if (claimed.get(key)! > (generated.get(key) ?? 0)) delete node.position; + } + return root; +} + +/** The stack index of the `

` an HTML parser would close, or -1 when none is in scope. */ +function openParagraph(stack: ReadonlyArray): number { + for (let index = stack.length - 1; index > 0; index--) { + const tagName = (stack[index] as Element).tagName; + if (tagName === "p") return index; + if (PARAGRAPH_SCOPE.has(tagName)) return -1; + } + return -1; +} + +/** parse5 puts a raw HTML table's rows in a ``; Words' own tables start with ``. */ +function normalizeRawTables(node: Root | Element) { + for (const child of node.children) { + if (child.type === "element") normalizeRawTables(child); + } + if (node.type !== "element" || node.tagName !== "table") return; + const first = node.children.findIndex((child) => isElement(child, "tr")); + if (first < 0) return; + node.children = [ + ...node.children.slice(0, first), + { type: "element", tagName: "tbody", properties: {}, children: node.children.slice(first) }, + ]; +} + +// Words leaves these raw in Markdown destinations, where micromark percent-encodes them. +const UNSAFE_URL_CHARACTERS = /[\\[\]`{}|^"<> ]/g; +const normalizeUri = (value: string) => + value.replace(UNSAFE_URL_CHARACTERS, (character) => encodeURIComponent(character)); + +const windowsPath = (url: string) => { + const path = url.replace(/%5C/gi, "\\"); + return /^[A-Za-z]:[\\/]/.test(path) ? path : undefined; +}; + +const isElement = (node: unknown, tagName?: string): node is Element => + (node as Element | undefined)?.type === "element" && + (tagName === undefined || (node as Element).tagName === tagName); + +const isElementNode = (node: ElementContent): node is Element => node.type === "element"; + +const isMarkdownImage = (node: unknown): boolean => + (isElement(node, "img") && node.position !== undefined) || + (isElement(node, "a") && + node.position !== undefined && + node.children.length === 1 && + isMarkdownImage(node.children[0])); + +const BREAK: ElementContent = { type: "element", tagName: "br", properties: {}, children: [] }; + +// Words' math: these elements and presentation attributes, and no links or handlers. +const MATH_ELEMENTS = new Set(["svg", "g", "text", "tspan", "rect", "path"]); +const MATH_PROPERTIES = new Set([ + "xmlns", + "width", + "height", + "viewBox", + "fill", + "fontFamily", + "fontSize", + "fontStyle", + "fontWeight", + "role", + "ariaLabel", + "x", + "y", + "dx", + "dy", + "d", + "transform", + "stroke", + "strokeWidth", + "textAnchor", +]); +const MATH_STYLE = /^(?:display|vertical-align|overflow|margin|white-space)$/; + +function sanitizeMath(node: Element): Element | null { + if (!MATH_ELEMENTS.has(node.tagName)) return null; + const properties: Element["properties"] = {}; + for (const [key, value] of Object.entries(node.properties)) { + if (MATH_PROPERTIES.has(key)) properties[key] = value; + } + if (typeof node.properties.style === "string") { + const style = node.properties.style + .split(";") + .filter((rule) => MATH_STYLE.test(rule.split(":")[0]!.trim())) + .join(";"); + if (style) properties.style = style; + } + const children: ElementContent[] = []; + for (const child of node.children) { + if (child.type === "text") children.push(child); + else if (child.type === "element") { + const clean = sanitizeMath(child); + if (clean) children.push(clean); + } + } + return { ...node, properties, children }; +} + +interface Walk { + /** Words' hast for more Markdown, rendered with the same options; `indent` as leadingWhitespace's. */ + readonly render: (markdown: string, indent: number) => Root; + readonly source: string; + readonly options: WordsHastOptions; + readonly math: Map; + /** A per-render id prefix for math placeholders, which authored ids cannot share. */ + readonly mathKey: string; + /** What insightSource opened each insight block with, when it opened any. */ + readonly insightMarker: RegExp | null; +} + +/** UTF-16 offsets for the UTF-8 byte offsets in Words' `data-sourcepos`. */ +function utf16Offsets(source: string): (byte: number) => number { + if (!/[^\x00-\x7f]/.test(source)) return (byte) => byte; + const offsets: number[] = []; + for (let index = 0; index < source.length; index++) { + const code = source.codePointAt(index)!; + const bytes = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4; + for (let byte = 0; byte < bytes; byte++) offsets.push(index); + if (code >= 0x10000) index++; + } + offsets.push(source.length); + return (byte) => offsets[byte] ?? source.length; +} + +const sourceOf = (node: Element, source: string) => + node.position ? source.slice(node.position.start.offset, node.position.end.offset) : ""; + +const textOf = (node: ElementContent): string => + node.type === "text" + ? node.value + : node.type === "element" + ? node.children.map(textOf).join("") + : ""; + +/** A directive's attributes, as strings; anything else Words would never write reads as none. */ +function directiveAttributes(node: Element): Record { + let parsed: unknown; + try { + parsed = JSON.parse(String(node.properties.dataAttributes ?? "{}")); + } catch { + return {}; + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {}; + return Object.fromEntries( + Object.entries(parsed).filter( + (entry): entry is [string, string] => typeof entry[1] === "string", + ), + ); +} + +/** remarkCodexDirectives: what a directive Words parsed becomes, as the remark plugin builds it. */ +function codexDirective(node: Element, walk: Walk, inLink: boolean): ElementContent { + const name = node.properties.dataDirective; + const attributes = directiveAttributes(node); + const asText = (): ElementContent => { + const value: ElementContent = { type: "text", value: sourceOf(node, walk.source) }; + return node.tagName === "div" + ? { type: "element", tagName: "p", properties: {}, children: [value] } + : value; + }; + if (name === "codex-file-citation") { + const citation = resolveCodexFileCitationLink(attributes); + if (!citation || inLink) return asText(); + return { + type: "element", + tagName: "a", + properties: { href: citation.href }, + children: [{ type: "text", value: citation.label }], + ...(node.position ? { position: node.position } : {}), + }; + } + if (name === "codex-followup") { + if (!attributes.prompt?.trim() || !node.children.map(textOf).join("").trim()) return asText(); + return { type: "element", tagName: "span", properties: {}, children: node.children }; + } + const template = resolveCodexArtifactTemplate(attributes); + if (!template) return asText(); + return { + type: "element", + tagName: "div", + properties: { + dataCodexArtifactTemplate: "true", + dataArtifactKind: template.artifactKind, + dataDisplayName: template.displayName, + ...(template.galleryKind === undefined ? {} : { dataGalleryKind: template.galleryKind }), + dataSkillDirectory: template.skillDirectory, + dataSkillName: template.skillName, + }, + children: [], + }; +} + +const INLINE_PREFIX = "t3-markdown-inline-prefix:"; + +function stripPositions(node: ElementContent) { + delete node.position; + if (node.type === "element") node.children.forEach(stripPositions); +} + +/** + * remarkNormalizeListItemIndentation: four spaces after a list marker make indented code, but + * agents mean wide indentation, so code starting on the marker's line is Markdown again. True + * when it recovered the item, whose children it then has transformed. + */ +function recoverIndentedCode( + item: Element, + list: Root | Element, + walk: Walk, + inLink: boolean, + inCode: boolean, +): boolean { + const code = item.children.find((child) => child.type === "element"); + const start = code?.position?.start.offset; + const itemStart = item.position?.start.offset; + if (!isElement(code, "pre") || start === undefined || itemStart === undefined) return false; + const value = textOf(code); + if (!/^[\t ]/.test(value)) return false; + if (walk.source.slice(itemStart, start).includes("\n") || /[`~]/.test(walk.source[start]!)) { + return false; + } + // The trimmed first line sets where the item's content starts. + const indent = [.../^[\t ]*/.exec(value)![0]].reduce( + (column, character) => (character === "\t" ? (Math.floor(column / 4) + 1) * 4 : column + 1), + 0, + ); + // The prefix keeps block syntax at the start, such as `#`, from opening a block. + const source = `${INLINE_PREFIX}${value.trim()}`; + const recovered = walk.render(source, indent); + const paragraph = recovered.children.find((child) => child.type === "element"); + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + if (first?.type !== "text" || !first.value.startsWith(INLINE_PREFIX)) return false; + first.value = first.value.slice(INLINE_PREFIX.length); + if (first.value === "") paragraph!.children.shift(); + transform(recovered, { ...walk, source }, inLink, inCode); + transform(item, walk, inLink, inCode); + let blocks = recovered.children.filter( + (child) => !(child.type === "text" && child.value.trim() === ""), + ) as ElementContent[]; + // Their positions point into `source`, not the message. + blocks.forEach(stripPositions); + let at = item.children.indexOf(code); + let remove = 1; + if (!isLooseList(list, walk.source)) { + // A tight item shows its text bare, as remark-rehype unwraps its paragraphs. + blocks = blocks.flatMap((block, index) => [ + ...(index > 0 ? [{ type: "text", value: "\n" } as Text] : []), + ...(isElement(block, "p") ? block.children : [block]), + ]); + const isBlank = (node: ElementContent | undefined) => + node?.type === "text" && node.value.trim() === ""; + if (at === 1 && isBlank(item.children[0])) [at, remove] = [0, 2]; + if (at + remove === item.children.length - 1 && isBlank(item.children.at(-1))) remove++; + } + item.children.splice(at, remove, ...blocks); + return true; +} + +/** remark-rehype's listLoose: a blank line between items, or an item Words wrote as paragraphs. */ +function isLooseList(list: Root | Element, source: string): boolean { + const items = (list.children as ElementContent[]).filter((child): child is Element => + isElement(child, "li"), + ); + return items.some( + (item, index) => + item.children.some((child) => isElement(child, "p")) || + (index > 0 && + /\n[ \t>]*\n/.test( + source.slice( + items[index - 1]!.position?.end.offset ?? 0, + item.position?.start.offset ?? 0, + ), + )), + ); +} + +const WRITTEN_NUMBER = /[ \t]*(\d{1,9})[.)]/y; + +function keepListNumbers(list: Element, source: string) { + let expected = Number(list.properties.start ?? 1); + for (const item of list.children) { + if (!isElement(item, "li")) continue; + const offset = item.position?.start.offset; + WRITTEN_NUMBER.lastIndex = offset ?? 0; + const digits = offset === undefined ? undefined : WRITTEN_NUMBER.exec(source)?.[1]; + const value = digits === undefined ? expected : Number(digits); + if (value !== expected) item.properties.value = String(value); + expected = value + 1; + } +} + +/** What the chat's remark plugins add that Words does not. */ +const link = (href: string, label: string, properties: Element["properties"] = {}): Element => ({ + type: "element", + tagName: "a", + properties: { href, ...properties }, + children: [{ type: "text", value: label }], +}); + +/** Links in text: absolute file paths (remarkLinkAbsoluteFilePaths), then a change request's references. */ +function linkText(value: string, walk: Walk): ElementContent[] | null { + let parts: ElementContent[] = []; + let offset = 0; + for (const { index, path } of absoluteFilePathMatches(value)) { + if (index > offset) parts.push({ type: "text", value: value.slice(offset, index) }); + parts.push(link(path, path)); + offset = index + path.length; + } + if (offset < value.length) parts.push({ type: "text", value: value.slice(offset) }); + const autolinks = walk.options.extensions.changeRequest?.autolinks; + if (autolinks) { + parts = parts.flatMap((part) => { + if (part.type !== "text") return [part]; + const found = autolinks(part.value); + if (found.length === 0) return [part]; + const linked: ElementContent[] = []; + let start = 0; + for (const reference of found) { + if (start < reference.index) { + linked.push({ type: "text", value: part.value.slice(start, reference.index) }); + } + linked.push( + link(reference.url, reference.label, { dataPullRequestAutolink: reference.kind }), + ); + start = reference.index + reference.text.length; + } + if (start < part.value.length) linked.push({ type: "text", value: part.value.slice(start) }); + return linked; + }); + } + return parts.length === 1 && parts[0]!.type === "text" ? null : parts; +} + +function transform(node: Root | Element, walk: Walk, inLink: boolean, inCode: boolean) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type === "text") { + if (inCode) continue; + if (walk.options.extensions.githubEmoji && child.value.includes(":")) { + child.value = expandGithubEmojiAliases(child.value); + } + if (inLink) continue; + const parts = linkText(child.value, walk); + if (!parts) continue; + children.splice(index, 1, ...parts); + index += parts.length - 1; + continue; + } + if (child.type !== "element") continue; + // Words gives what it generates a source position; raw HTML that copies its attributes has none. + if (child.properties.dataDirective !== undefined && child.position) { + children[index] = codexDirective(child, walk, inLink); + index--; + continue; + } + const { tagName, properties: props } = child; + if (tagName === "svg") { + // Sanitizing drops SVG, so math waits under a placeholder until after it. + const clean = walk.options.math && child.position ? sanitizeMath(child) : null; + if (clean) { + const key = `${walk.mathKey}-${walk.math.size}`; + walk.math.set(key, clean); + children[index] = { + type: "element", + tagName: "span", + properties: { id: key }, + children: [], + }; + } + continue; + } + if (tagName === "a" && props.dataFootnoteRef !== undefined) { + // remark-rehype's footnote markup, before rehype-sanitize prefixes ids again. + props.href = `#user-content-${String(props.href).slice(1)}`; + props.id = `user-content-${String(props.id)}`; + props.ariaDescribedBy = ["footnote-label"]; + } else if (tagName === "a" && props.dataFootnoteBackref !== undefined) { + const { href, ariaLabel } = props; + child.properties = { + href: `#user-content-${String(href).slice(1)}`, + dataFootnoteBackref: "", + ariaLabel, + className: ["data-footnote-backref"], + }; + } else if (tagName === "li" && typeof props.id === "string" && props.id.startsWith("fn-")) { + props.id = `user-content-${props.id}`; + } else if (tagName === "section" && props.dataFootnotes !== undefined) { + child.properties = { dataFootnotes: "", className: ["footnotes"] }; + child.children.unshift({ + type: "element", + tagName: "h2", + properties: { className: ["sr-only"], id: "footnote-label" }, + children: [{ type: "text", value: "Footnotes" }], + }); + } else if (tagName === "a" && typeof props.href === "string") { + // remarkNormalizeLinksAndTagInlineCode: a Windows drive path links as a file URL. + const path = windowsPath(props.href); + props.href = path ? `file:///${path.replaceAll("\\", "/")}` : normalizeUri(props.href); + } else if (tagName === "img" && typeof props.src === "string") { + const changeRequest = walk.options.extensions.changeRequest; + const src = changeRequest + ? resolveChangeRequestMediaUrl(props.src, changeRequest.repositoryUrl) + : props.src; + props.src = windowsPath(src) ?? normalizeUri(src); + } else if (tagName === "code" && isElement(node, "pre")) { + if (props.dataMeta !== undefined) { + props.dataCodeMeta = props.dataMeta; + delete props.dataMeta; + } + } else if (tagName === "code" && !inLink) { + props.dataInlineCode = ""; + } else if (tagName === "ol" && walk.options.extensions.userMessage) { + keepListNumbers(child, walk.source); + } else if (tagName === "li") { + const firstBlock = child.children.find(isElementNode); + if (isElement(firstBlock, "pre") && recoverIndentedCode(child, node, walk, inLink, inCode)) { + continue; + } + // Tight items put the checkbox directly in `

  • `, loose ones inside its first `

    `. + const checkbox = isElement(child.children[0], "input") + ? child.children[0] + : isElement(firstBlock, "p") && isElement(firstBlock.children[0], "input") + ? firstBlock.children[0] + : undefined; + if (checkbox) { + props.className = ["task-list-item"]; + const { checked } = checkbox.properties; + checkbox.properties = { type: "checkbox", checked, disabled: true }; + if (node.type === "element") node.properties.className = ["contains-task-list"]; + } + breakLines(child, walk.options.breaks); + } else if (tagName === "p") { + breakLines(child, walk.options.breaks); + } else if (tagName === "blockquote") { + // remarkGithubAlerts + const paragraph = child.children.find((item) => item.type === "element"); + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + const text = first?.type === "text" ? first.value : ""; + const insight = walk.insightMarker?.exec(text); + const alert = GITHUB_ALERT_MARKER.exec(text); + // An alert marker followed by more inline content on its line is text, as remarkGithubAlerts reads it. + const match = insight + ? ([insight[0], "insight"] as const) + : alert && (alert[0].endsWith("\n") || (paragraph as Element).children.length === 1) + ? alert + : null; + if (match && first?.type === "text" && isElement(paragraph, "p")) { + first.value = first.value.slice(match[0].length); + if (first.value === "") paragraph.children.shift(); + if (paragraph.children.length === 0) { + const at = child.children.indexOf(paragraph); + const next = child.children[at + 1]; + // The line ending after it goes too, as remark leaves none for a removed paragraph. + const blank = next?.type === "text" && next.value.trim() === "" ? 2 : 1; + child.children.splice(at, blank); + } + props.dataAlert = match[1]!.toLowerCase(); + } + } + transform( + child, + walk, + inLink || tagName === "a", + inCode || tagName === "code" || tagName === "pre", + ); + } +} + +/** + * remark-breaks puts a `
    ` before every soft line ending, and remarkBreakAroundImageLines + * before those next to a Markdown image. Both keep the line ending after it. + */ +/** A Markdown image alone on its line: nothing but a line ending (or the paragraph's edge) around it. */ +function imageOwnsLine(items: ElementContent[], at: number): boolean { + if (!isMarkdownImage(items[at])) return false; + const before = items[at - 1]; + const after = items[at + 1]; + const startsLine = + before === undefined || + (before.type === "text" && /\n[ \t]*$/.test(before.value)) || + isElement(before, "br"); + const endsLine = after === undefined || (after.type === "text" && /^[ \t]*\n/.test(after.value)); + return startsLine && endsLine; +} + +const isBlockElement = (node: ElementContent | undefined) => + node?.type === "element" && CLOSES_PARAGRAPH.has(node.tagName); + +function breakLines(paragraph: Element, breaks: boolean) { + const items = paragraph.children; + for (let at = 0; at < items.length; at++) { + const item = items[at]!; + if ( + item.type === "element" && + breaks && + item.tagName !== "code" && + !CLOSES_PARAGRAPH.has(item.tagName) + ) { + breakLines(item, breaks); + } + if (item.type !== "text" || !item.value.includes("\n")) continue; + const afterImage = imageOwnsLine(items, at - 1); + const beforeImage = imageOwnsLine(items, at + 1); + const afterBlock = isBlockElement(items[at - 1]) || (at === 0 && paragraph.tagName === "li"); + const beforeBlock = + isBlockElement(items[at + 1]) || (at === items.length - 1 && paragraph.tagName === "li"); + const lines = item.value.split("\n"); + const parts: ElementContent[] = []; + lines.forEach((line, index) => { + // A hard break's own line ending follows its
    , and adds no second one; + // structural line endings around a list item's block children stay breaks between blocks. + const afterHardBreak = index === 1 && isElement(items[at - 1], "br"); + const blockBoundary = + (index === 1 && lines[0] === "" && afterBlock) || + (index === lines.length - 1 && line === "" && beforeBlock); + const breaksHere = + index > 0 && + !afterHardBreak && + !blockBoundary && + (breaks || (index === 1 && afterImage) || (index === lines.length - 1 && beforeImage)); + if (index > 0) { + if (breaksHere) { + const previous = parts.at(-1); + if (previous?.type === "text") previous.value = previous.value.replace(/[ \t]+$/, ""); + parts.push(BREAK); + } + parts.push({ type: "text", value: `\n${line}` }); + } else if (line) { + parts.push({ type: "text", value: line }); + } + }); + // Rejoin text that did not break, so the tree matches remark's text nodes. + const merged: ElementContent[] = []; + for (const part of parts) { + const previous = merged.at(-1); + if (part.type === "text" && previous?.type === "text") previous.value += part.value; + else merged.push(part); + } + items.splice(at, 1, ...merged); + at += merged.length - 1; + } +} + +/** + * The wrapper copying reads (markdown-clipboard's MATH_SELECTOR): the formula's TeX, as the source + * Words drew it from, so copying any part of a formula copies the whole of it. + */ +// A formula wider than its block scrolls, with room for the glyphs that reach past its box; in a +// table it keeps its width and the table scrolls. +const MATH_SCROLL = [ + "max-w-full", + "overflow-x-auto", + "overflow-y-hidden", + "px-0.5", + "py-0.75", + "in-[.chat-markdown-table-container]:max-w-none", + "in-[.chat-markdown-table-container]:overflow-visible", +]; + +function mathWrapper(svg: Element): Element { + const tex = String(svg.properties.ariaLabel ?? "").trim(); + const display = /display:\s*block/.test(String(svg.properties.style ?? "")); + return { + type: "element", + tagName: "span", + properties: display + ? { + className: ["chat-markdown-math-display", "block", ...MATH_SCROLL], + dataMarkdownMath: "display", + dataMarkdownCopy: `\\[\n${tex}\n\\]\n\n`, + } + : { + className: ["inline-block", "align-middle", ...MATH_SCROLL], + dataMarkdownMath: "inline", + dataMarkdownCopy: `\\(${tex}\\)`, + }, + children: [svg], + }; +} + +function restoreMath(node: Root | Element, math: Map) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + const id = child.properties.id; + const svg = typeof id === "string" ? math.get(id.replace(/^user-content-/, "")) : undefined; + if (svg) children[index] = mathWrapper(svg); + else restoreMath(child, math); + } +} + +const addHeadingIds = rehypeHeadingIds(); +const addTextDirection = rehypeTextDirection(); +const preserveImageSourceMeta = rehypePreserveImageSourceMeta(); +const normalizeLocalEditorLinks = rehypeNormalizeLocalEditorLinks(); +const groupChipPunctuation = rehypeChipPunctuation(); + +const INSIGHT_OPENING = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u; +const INSIGHT_CLOSING = /^( {0,3})(`?)─{3,}\2[ \t]*$/u; + +interface InsightSource { + readonly source: string; + readonly tree: Root; + readonly marker: RegExp; + /** The offset in the message for an offset in `source`. */ + readonly toOriginal: (offset: number) => number; +} + +/** + * remarkAssistantInsights: a `★ Insight ───` line opens a quoted insight block, which a `───` line + * at the same indentation closes; the end of the text closes one that never does. Lines in code + * neither open nor close one, and an opening Words does not read as a quote's first line, as in + * an HTML block or a quote's lazy line, stays text. + */ +function insightSource(text: string, options: RenderOptions): InsightSource | null { + if (!text.includes("★ Insight")) return null; + const code: Array = []; + const findCode = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "pre" && child.position) { + code.push([child.position.start.offset!, child.position.end.offset!]); + } else findCode(child); + } + }; + findCode(parse(text, options)); + const nonce = Math.random().toString(36).slice(2); + const marker = new RegExp(String.raw`^\[!T3-INSIGHT-${nonce}-(\d+)\](?:\r?\n)?`); + const anywhere = new RegExp(String.raw`\[!T3-INSIGHT-${nonce}-(\d+)\]`, "g"); + const lines = text.split(/(?<=\n)/u); + const skipped = new Set(); + for (;;) { + // Each line's offset in the message and in the source, and how much longer it got. + const offsets: Array<{ original: number; source: number; length: number; delta: number }> = []; + let original = 0; + let rewritten = 0; + let opened = 0; + let indent: string | undefined; + const source = lines + .map((line, lineIndex) => { + const value = line.replace(/[\r\n]+$/u, ""); + const ending = line.slice(value.length); + const inCode = code.some(([start, end]) => original >= start && original < end); + let output = line; + if (indent === undefined) { + const opening = inCode ? null : INSIGHT_OPENING.exec(value); + if (opening && !skipped.has(lineIndex)) { + indent = opening[1] ?? ""; + opened++; + output = `> [!T3-INSIGHT-${nonce}-${lineIndex}]${ending}`; + } + } else { + const closing = inCode ? null : INSIGHT_CLOSING.exec(value); + if (closing && closing[1] === indent) { + indent = undefined; + output = ending; + } else output = `> ${line}`; + } + offsets.push({ + original, + source: rewritten, + length: line.length, + delta: output.length - line.length, + }); + original += line.length; + rewritten += output.length; + return output; + }) + .join(""); + if (opened === 0) return null; + const tree = parse(source, options); + let stranded = false; + const visit = (node: Root | Element, quoteStart: Text | undefined) => { + for (const child of node.children) { + if (child.type === "text") { + for (const found of child.value.matchAll(anywhere)) { + if (child === quoteStart && found.index === 0) continue; + skipped.add(Number(found[1])); + stranded = true; + } + } else if (child.type === "element") { + const paragraph = + child.tagName === "blockquote" ? child.children.find(isElementNode) : undefined; + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + visit(child, first?.type === "text" ? first : quoteStart); + } + } + }; + visit(tree, undefined); + if (stranded) continue; + return { + source, + tree, + marker, + toOriginal: (offset) => { + const line = offsets.findLast((entry) => entry.source <= offset) ?? offsets[0]!; + return ( + line.original + Math.min(Math.max(offset - line.source - line.delta, 0), line.length) + ); + }, + }; + } +} + +/** Positions that point into an insight's rewritten source, moved back into the message. */ +function restorePositions(node: Root | Element, toOriginal: (offset: number) => number) { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.position) { + const start = toOriginal(child.position.start.offset!); + const end = toOriginal(child.position.end.offset!); + child.position = { + start: { line: 1, column: start + 1, offset: start }, + end: { line: 1, column: end + 1, offset: end }, + }; + } + restorePositions(child, toOriginal); + } +} + +const PREVIEW_SEPARATED = new Set([ + "blockquote", + "ul", + "ol", + "li", + "table", + "thead", + "tbody", + "tr", +]); + +/** remarkThoughtPreview: the message as one line of text, keeping math, cut at `maxLength`. */ +function flattenPreview(tree: Root, preview: NonNullable): Root { + const children: ElementContent[] = []; + let remaining = preview.maxLength; + let fragments: string[] = []; + const flush = () => { + if (fragments.length === 0) return; + children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") }); + fragments = []; + }; + const take = (value: string) => { + const text = value.slice(0, remaining); + remaining = text.length < value.length ? 0 : remaining - text.length; + // A cut must not leave half a surrogate pair. + return text.replace(/[\uD800-\uDBFF]$/, ""); + }; + const visit = (node: Root | ElementContent) => { + if (remaining === 0) return; + if (node.type === "text") { + fragments.push(take(node.value)); + return; + } + if (node.type === "element" && node.properties.dataMarkdownMath !== undefined) { + flush(); + // One line has no room for display math, which a preview shows inline. + const svg = node.children[0]; + children.push( + node.properties.dataMarkdownMath === "display" && svg?.type === "element" + ? mathWrapper({ + ...svg, + properties: { + ...svg.properties, + style: "display:inline;vertical-align:middle;overflow:visible", + }, + }) + : node, + ); + return; + } + if (node.type === "element" && node.tagName === "img") { + fragments.push(take(String(node.properties.alt ?? ""))); + return; + } + if (node.type === "element" && node.tagName === "br") { + fragments.push(take(" ")); + return; + } + if (node.type !== "root" && node.type !== "element") return; + const separates = node.type === "root" || PREVIEW_SEPARATED.has(node.tagName); + let first = true; + for (const child of node.children as ElementContent[]) { + if (remaining === 0) break; + if (child.type === "text" && child.value.trim() === "" && separates) continue; + if (!first && separates) fragments.push(take(" ")); + first = false; + visit(child); + } + }; + visit(tree); + flush(); + const head = children[0]; + const tail = children.at(-1); + if (head?.type === "text") head.value = head.value.trimStart(); + if (tail?.type === "text") tail.value = tail.value.trimEnd(); + const visible = children.some((child) => child.type !== "text" || child.value); + return { + type: "root", + children: visible ? children : [{ type: "text", value: preview.fallback }], + }; +} + +/** Links become their text, images their alt text, inline code plain text, Mermaid plain code. */ +function makeInert(node: Root | Element) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + if (child.tagName === "a") { + children.splice(index, 1, ...child.children); + index--; + continue; + } + if (child.tagName === "img") { + children[index] = { type: "text", value: String(child.properties.alt ?? "") }; + continue; + } + if (child.tagName === "code" && child.properties.dataInlineCode !== undefined) { + children[index] = { type: "text", value: textOf(child) }; + continue; + } + if ( + child.tagName === "code" && + String(child.properties.className ?? "").includes("language-mermaid") + ) { + child.properties.className = ["language-text"]; + } + makeInert(child); + } +} + +/** ChatMarkdown's sanitized hast for `text`, rendered by Words. */ +export function wordsHast(text: string, options: WordsHastOptions): Root { + const { extensions } = options; + const renderOptions: RenderOptions = { + math: options.math, + // llm-math's `\(…\)` and `\[…\]`, which agents write as often as `$`. + texDelimiters: options.math, + autolinkBoundaries: true, + singleTilde: !extensions.userMessage, + leadingWhitespace: extensions.leadingWhitespace === true, + windowsPaths: true, + codeMeta: true, + directives: CODEX_DIRECTIVES, + // Previews and inert Markdown drop raw HTML, as their remark plugins dropped html nodes. + ...(extensions.preview || extensions.inert + ? { skipHtml: true } + : { escapeHtml: options.escapeHtml }), + }; + const insights = options.insights ? insightSource(text, renderOptions) : null; + const source = insights?.source ?? text; + const tree = insights?.tree ?? parse(source, renderOptions); + const walk: Walk = { + render: (markdown, indent) => + parse(markdown, { + ...renderOptions, + leadingWhitespace: extensions.leadingWhitespace === true && { indent }, + }), + source, + options, + math: new Map(), + mathKey: `t3-math-${Math.random().toString(36).slice(2)}`, + insightMarker: insights?.marker ?? null, + }; + transform(tree, walk, false, false); + preserveImageSourceMeta(tree as never); + normalizeLocalEditorLinks(tree as never); + const hast = sanitizeChatHast(tree); + if (walk.math.size > 0) restoreMath(hast, walk.math); + if (insights) restorePositions(hast, insights.toOriginal); + if (extensions.inert) makeInert(hast); + if (extensions.preview) return flattenPreview(hast, extensions.preview); + addHeadingIds(hast); + addTextDirection(hast as never); + groupChipPunctuation(hast as never); + return hast; +} + +export interface CodexDirectiveSource { + readonly name: string; + readonly attributes: Record; + /** UTF-16 offsets of the whole directive in the source. */ + readonly start: number; + readonly end: number; + /** The label's text as written. */ + readonly label: string; + /** Inside a link, where a file citation stays text. */ + readonly inLink: boolean; +} + +/** The Codex directives in `markdown`, as Words reads them. */ +export function codexDirectiveSources(markdown: string): CodexDirectiveSource[] { + const found: CodexDirectiveSource[] = []; + const visit = (node: Root | Element, inLink: boolean) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const name = child.properties.dataDirective; + if (typeof name === "string" && child.position) { + const { start, end } = child.position; + found.push({ + name, + attributes: directiveAttributes(child), + start: start.offset!, + end: end.offset!, + label: directiveLabel(markdown.slice(start.offset, end.offset)), + inLink, + }); + } + visit(child, inLink || child.tagName === "a"); + } + }; + visit( + parse(markdown, { + windowsPaths: true, + autolinkBoundaries: true, + directives: CODEX_DIRECTIVES, + }), + false, + ); + return found; +} + +/** The label of a directive as written, `:name[label]{…}`: brackets nest in it, and `\` escapes. */ +function directiveLabel(written: string): string { + const open = written.indexOf("["); + if (open < 0) return ""; + let depth = 0; + for (let index = open; index < written.length; index++) { + const character = written[index]; + if (character === "\\") index++; + else if (character === "[") depth++; + else if (character === "]" && --depth === 0) return written.slice(open + 1, index); + } + return ""; +} + +/** + * Words' HTML for `markdown` as hast, unsanitized and without the chat's additions. Code blocks, + * links, list items and math carry source positions. + */ +export function markdownTree( + markdown: string, + options: { skipHtml?: boolean; singleTilde?: boolean; math?: boolean } = {}, +): Root { + return parse(markdown, { + windowsPaths: true, + autolinkBoundaries: true, + skipHtml: options.skipHtml === true, + singleTilde: options.singleTilde !== false, + math: options.math === true, + texDelimiters: options.math === true, + }); +} + +/** The formulas Words reads in `text`, as source offsets, for editors that keep math as source. */ +export function markdownMathRanges(text: string): Array<{ start: number; end: number }> { + if (!/[$\\]|(?:`{3,}|~{3,})[ \t]*math\b/.test(text)) return []; + const ranges: Array<{ start: number; end: number }> = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "svg") { + if (child.position) { + ranges.push({ start: child.position.start.offset!, end: child.position.end.offset! }); + } + continue; + } + visit(child); + } + }; + visit(parse(text, { math: true, texDelimiters: true })); + return ranges; +} + +/** The HTML comments Words reads as raw HTML in `markdown`, not as code or text, as source offsets. */ +export function markdownHtmlComments(markdown: string): Array<{ start: number; end: number }> { + const openers = [...markdown.matchAll(/", start + 4); + return { start, end: close < 0 ? markdown.length : close + 3 }; + }); +} + +/** + * The first definition of each label in `markdown`, as one line of Markdown. Words decides which + * `[label]:` text defines one: each label is looked up again after the text. + */ +export function markdownReferenceDefinitions(markdown: string): string[] { + const labels = new Map(); + for (const match of markdown.matchAll(/\[((?:[^\\[\]]|\\.){1,999})\]:/g)) { + const key = match[1]!.replace(/\s+/g, " ").trim().toLowerCase(); + // `[^1]:` is a footnote. + if (key !== "" && !key.startsWith("^") && !labels.has(key)) labels.set(key, match[1]!); + } + if (labels.size === 0) return []; + let probe = `${markdown}\n\n`; + const lookups = new Map(); + for (const label of labels.values()) { + lookups.set(probe.length, label); + probe += `[${label}]\n\n`; + } + const definitions: string[] = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const label = lookups.get(child.position?.start.offset ?? -1); + if (child.tagName === "a" && label !== undefined) { + const href = String(child.properties.href ?? "").replace(/[<>\\\n]/g, encodeURIComponent); + const title = child.properties.title; + definitions.push( + `[${label}]: <${href}>${typeof title === "string" ? ` "${title.replace(/\s+/g, " ").replace(/["\\]/g, "\\$&")}"` : ""}`, + ); + } else visit(child); + } + }; + visit(parse(probe, { windowsPaths: true })); + return definitions; +} diff --git a/apps/web/src/routes/_chat.settings.secrets.tsx b/apps/web/src/routes/_chat.settings.secrets.tsx index d97e00fda19f7..e0031f4aeaf9a 100644 --- a/apps/web/src/routes/_chat.settings.secrets.tsx +++ b/apps/web/src/routes/_chat.settings.secrets.tsx @@ -1,11 +1,19 @@ -import { createFileRoute, redirect } from "@tanstack/react-router"; +import { createFileRoute, Navigate } from "@tanstack/react-router"; import { SecretsSettingsPanel } from "../components/settings/SecretsSettings"; -import { isSecretsFeatureEnabled } from "../env"; +import { useHasSecretProvidersEnvironment } from "../components/settings/useAvailableSettingsSearchItems"; +import { useEnvironments } from "../state/environments"; export const Route = createFileRoute("/_chat/settings/secrets")({ - beforeLoad: () => { - if (!isSecretsFeatureEnabled) throw redirect({ to: "/settings/general", replace: true }); - }, - component: SecretsSettingsPanel, + component: SecretsSettingsRoute, }); + +function SecretsSettingsRoute() { + const enabled = useHasSecretProvidersEnvironment(); + // Only redirect once every environment reported flags; one may enable them after another loads. + const { isReady, environments } = useEnvironments(); + const allReported = + isReady && environments.every((environment) => environment.serverConfig !== null); + if (!enabled && allReported) return ; + return ; +} diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index f4670665add6c..2155fedaa83c1 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -290,7 +290,10 @@ describe("V2 session presentation", () => { }, }; }); - const checkpoint = (ordinal: number, status: "ready" | "missing" | "stale" = "ready") => ({ + const checkpoint = ( + ordinal: number, + status: "ready" | "missing" | "stale" | "error" = "ready", + ) => ({ runId: runId(ordinal), checkpointTurnCount: ordinal, checkpointRef: `checkpoint-${ordinal}` as never, @@ -326,6 +329,11 @@ describe("V2 session presentation", () => { "user-1": 0, "user-2": 1, }); + // A failed snapshot capture still pins the conversation; only file restore needs one. + expect(targets([1, 2], [checkpoint(1, "error")])).toEqual({ + "user-1": 0, + "user-2": 1, + }); }); it("preserves a notification-only wake run while ignoring inherited and unrelated work", () => { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 1122c3122aca0..5196ee43458d8 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -1153,10 +1153,10 @@ export function deriveRevertTurnCountByUserMessageId(input: { return byUserMessageId; } -// A missing snapshot (no git, or a side chat) still pins a conversation position; only -// restoring files needs a ready one. +// A missing or failed snapshot (no git, a side chat, a capture error) still pins a +// conversation position; only restoring files needs a ready one. function isRewindableCheckpoint(checkpoint: Pick) { - return checkpoint.status === "ready" || checkpoint.status === "missing"; + return checkpoint.status !== "stale"; } export function findRevertCheckpoint( diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx index 8519d6a1ce0cc..99cbff1c14a13 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx +++ b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx @@ -987,3 +987,31 @@ it("lets the user retry after a status failure without reselecting the destinati await act(() => mocks.voice.stop()); expect(mocks.transcribeCalls).toEqual(["env-a"]); }); + +it("delivers a queued submission for a persistent draft after switching owners", async () => { + setup({ destination: "env-a" }); + const submit = vi.fn(); + await using screen = await render(); + await act(() => mocks.voice.start()); + expect(mocks.voice.state.phase).toBe("recording"); + await act(async () => { + mocks.voice.submitAfterDictation(submit); + await screen.rerender(); + }); + await vi.waitFor(() => expect(submit).toHaveBeenCalledExactlyOnceWith("dictated")); + expect(mocks.storedDraft).toBe("dictated"); +}); + +it("drops a queued submission for a non-persistent draft when switching owners", async () => { + setup({ destination: "env-a" }); + const submit = vi.fn(); + await using screen = await render(); + await act(() => mocks.voice.start()); + expect(mocks.voice.state.phase).toBe("recording"); + await act(async () => { + mocks.voice.submitAfterDictation(submit); + await screen.rerender(); + }); + await vi.waitFor(() => expect(mocks.voice.state.phase).toBe("idle")); + expect(submit).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.ts b/apps/web/src/speech/useEnvironmentSpeechInput.ts index 0ad3c4b2054e4..c7915685727b6 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.ts +++ b/apps/web/src/speech/useEnvironmentSpeechInput.ts @@ -217,11 +217,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { const busyElsewhere = !owns && voiceInputBlocksSubmission(snapshot.state); const startRequestRef = useRef(0); - const pendingSubmissionRef = useRef<{ - ownerKey: string; - submit: (text: string) => void; - text?: string; - } | null>(null); const latestRef = useRef({ input, clientSettings, cleanupPrepared, projectWords, session }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed props before an async completion can read them through the session useLayoutEffect(() => { @@ -233,7 +228,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { mountedRef.current = true; return () => { mountedRef.current = false; - pendingSubmissionRef.current = null; startRequestRef.current += 1; session?.ownerChanged(latestRef.current.input.ownerKey); }; @@ -292,36 +286,23 @@ export function useEnvironmentSpeechInput(input: HookInput) { }, [prepared, setup.downloading, setup.open, setupModelId]); const previousOwnerRef = useRef(input.ownerKey); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons any queued submission, and a recording that cannot outlive its editor, when the draft's owner changes + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons a recording that cannot outlive its editor when the draft's owner changes useEffect(() => { const previous = previousOwnerRef.current; if (previous === input.ownerKey && !input.disabled) return; previousOwnerRef.current = input.ownerKey; - pendingSubmissionRef.current = null; startRequestRef.current += 1; if (previous !== input.ownerKey) session?.ownerChanged(previous); else if (session?.ownerKey === input.ownerKey) session.cancel(); }, [input.ownerKey, input.disabled, session]); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- delivers a queued submission only after the transcript has committed to the draft - useEffect(() => { - const pending = pendingSubmissionRef.current; - if (state.phase === "error") pendingSubmissionRef.current = null; - if (state.phase !== "idle" || !pending) return; - pendingSubmissionRef.current = null; - if (!input.disabled && pending.ownerKey === input.ownerKey && pending.text !== undefined) - pending.submit(pending.text); - }, [state, input.ownerKey, input.disabled]); - const submitAfterDictation = useStableCallback((submit: (text: string) => void) => { if (latestRef.current.input.disabled || state.phase === "preparing") return; if (!session || !voiceInputBlocksSubmission(state)) { submit(latestRef.current.input.readDraft().text); return; } - if (pendingSubmissionRef.current) return; - pendingSubmissionRef.current = { ownerKey: latestRef.current.input.ownerKey, submit }; - if (session.state.phase === "recording") void session.stop(); + session.queueSubmission(latestRef.current.input.ownerKey, submit); }); const createTarget = useStableCallback((): VoiceInputTarget => { @@ -359,8 +340,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { } if (latestRef.current.input.disabled) return; latestRef.current.input.commitDraft(text, selection); - if (pendingSubmissionRef.current?.ownerKey === owner) - pendingSubmissionRef.current.text = text; }, readContext: () => (live() ? readContext() : startContext), }; @@ -585,7 +564,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { submitAfterDictation, stop: useStableCallback(() => (owns && session ? session.stop() : Promise.resolve())), cancel: useStableCallback(() => { - pendingSubmissionRef.current = null; startRequestRef.current += 1; setSetup(INITIAL_SETUP); if (owns) session?.cancel(); diff --git a/apps/web/src/speech/voiceInputSession.ts b/apps/web/src/speech/voiceInputSession.ts index f048b5653973c..577b26595efed 100644 --- a/apps/web/src/speech/voiceInputSession.ts +++ b/apps/web/src/speech/voiceInputSession.ts @@ -19,8 +19,9 @@ import type { SpeechStreamText, SpeechTranscriptionOptions, } from "@t3tools/contracts"; -import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; +import { DEFAULT_CLIENT_SETTINGS, EnvironmentInternalError } from "@t3tools/contracts"; import { resolveSpeechVocabulary } from "@t3tools/shared/speech"; +import * as Schema from "effect/Schema"; import { useEffect, useSyncExternalStore } from "react"; import { toastManager } from "../components/ui/toast"; @@ -34,6 +35,8 @@ import { bindAudioGrant, readCleanupGrant } from "./voiceConsent"; import { msg } from "gt-react"; import { m } from "../i18n/messages"; +const isEnvironmentInternalError = Schema.is(EnvironmentInternalError); + export const IDLE_VOICE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null }; type DraftInput = { @@ -105,6 +108,11 @@ export class VoiceInputSession { readonly key: SessionKey; private readonly controller: VoiceInputController; private target: VoiceInputTarget | null = null; + private pendingSubmission: { + readonly ownerKey: string; + readonly submit: (text: string) => void; + text?: string; + } | null = null; private snapshot: VoiceInputSessionSnapshot = { state: IDLE_VOICE_STATE, target: null, @@ -220,18 +228,27 @@ export class VoiceInputSession { releaseRecording: async () => platform.cancelRecording(), deleteRecording: platform.deleteRecording, postProcess, - onPostProcessingError: () => + onPostProcessingError: (error) => { + const added = m(msg("The original transcript was added.")); + const detail = isEnvironmentInternalError(error) ? error.detail : undefined; toastManager.add({ type: "warning", title: m(msg("Transcript cleanup failed")), - description: m(msg("The original transcript was added.")), - }), + description: detail ? `${detail} ${added}` : added, + }); + }, readDraft: (): VoiceDraftSnapshot | null => { const target = this.target; const draft = target?.readDraft(); return target && draft ? { ownerKey: target.ownerKey, ...draft } : null; }, - commitDraft: (text, selection) => this.target?.commitDraft(text, selection), + commitDraft: (text, selection) => { + const ownerKey = this.target?.ownerKey ?? null; + this.target?.commitDraft(text, selection); + if (ownerKey !== null && this.pendingSubmission?.ownerKey === ownerKey) { + this.pendingSubmission.text = text; + } + }, onStateChange: (state) => { if (this.disposed) return; const recordingStartedAt = @@ -239,6 +256,15 @@ export class VoiceInputSession { this.publish({ ...this.snapshot, state, recordingStartedAt }); if (state.phase !== "recording" && state.phase !== "transcribing") this.publishActivity(SILENT_ACTIVITY); + if (state.phase === "error") { + this.pendingSubmission = null; + return; + } + if (state.phase === "idle" && this.pendingSubmission !== null) { + const pending = this.pendingSubmission; + this.pendingSubmission = null; + if (pending.text !== undefined) pending.submit(pending.text); + } }, }); } @@ -275,6 +301,7 @@ export class VoiceInputSession { voiceInputBlocksSubmission(this.controller.currentState) && this.target?.ownerKey !== target.ownerKey; if (busyElsewhere) return Promise.resolve(); + this.pendingSubmission = null; this.target = target; this.onSpeechStatus = onSpeechStatus; this.publishActivity(SILENT_ACTIVITY); @@ -289,11 +316,29 @@ export class VoiceInputSession { this.publish({ ...this.snapshot, target }); } + /** Queues a submission to run once the active dictation commits its transcript. */ + queueSubmission(ownerKey: string, submit: (text: string) => void): boolean { + if ( + this.disposed || + this.target?.ownerKey !== ownerKey || + !voiceInputBlocksSubmission(this.controller.currentState) || + this.pendingSubmission !== null + ) { + return false; + } + this.pendingSubmission = { ownerKey, submit }; + if (this.controller.currentState.phase === "recording") { + void this.controller.stop(); + } + return true; + } + stop(): Promise { return this.controller.stop(); } cancel(): void { + this.pendingSubmission = null; this.controller.cancel(); } @@ -304,11 +349,13 @@ export class VoiceInputSession { /** The editor for `ownerKey` now shows another draft; only a persistent target keeps going. */ ownerChanged(ownerKey: string): void { if (this.target?.ownerKey !== ownerKey || this.target.persistent) return; + this.pendingSubmission = null; this.controller.ownerChanged(); } dispose(): void { this.disposed = true; + this.pendingSubmission = null; this.controller.dispose(); this.listeners.clear(); this.activityListeners.clear(); diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts index 8eaca1b774c85..0915810b47fed 100644 --- a/apps/web/src/state/terminalSessions.ts +++ b/apps/web/src/state/terminalSessions.ts @@ -22,7 +22,13 @@ import { AsyncResult, Atom } from "effect/reactivity"; import { formatEnvironmentQueryError } from "./query"; import { terminalEnvironment } from "./terminal"; -import { environmentSession, sessionHasScope, useEnvironmentScope } from "./session"; +import { environmentAtomList, environmentIdsKey } from "./environmentAtomList"; +import { + environmentSession, + sessionHasScope, + useEnvironmentScope, + useEnvironmentsWithScope, +} from "./session"; import { msg } from "gt-react"; import { m } from "../i18n/messages"; @@ -274,3 +280,43 @@ export function useThreadRunningTerminalIds(input: { const sessions = useKnownTerminalSessions(input); return selectRunningSubprocessTerminalIds(sessions ?? []); } + +// A string so status updates that keep every label notify no one. +const terminalLabelsFamily = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + const metadata = get(terminalEnvironment.metadata({ environmentId, input: null })); + if (metadata._tag !== "Success") return "[]"; + return JSON.stringify( + Array.from(terminalMetadataIndex(metadata.value).byThreadId, ([threadId, summaries]) => [ + threadId, + summaries[0]!.label, + ]), + ); + }).pipe(Atom.withLabel(`web-terminal-labels:${environmentId}`)), +); +const terminalLabelsListAtom = environmentAtomList("web-terminal-labels", terminalLabelsFamily); +const terminalLabelsByResults = new WeakMap, ReadonlyMap>(); + +/** First terminal label of each thread that has one, keyed `${environmentId}:${threadId}`. */ +export function useTerminalLabelsByThreadKey( + environmentIds: ReadonlyArray, +): ReadonlyMap { + const readable = useEnvironmentsWithScope( + environmentIds.map((environmentId) => ({ environmentId })), + AuthTerminalReadScope, + ); + const readableIds = environmentIds.filter((environmentId) => readable.has(environmentId)); + const results = useAtomValue(terminalLabelsListAtom(environmentIdsKey(readableIds))); + let labels = terminalLabelsByResults.get(results); + if (!labels) { + const next = new Map(); + results.forEach((encoded, index) => { + for (const [threadId, label] of JSON.parse(encoded) as Array<[string, string]>) { + next.set(`${readableIds[index]}:${threadId}`, label); + } + }); + labels = next; + terminalLabelsByResults.set(results, labels); + } + return labels; +} diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index ac99534a5ca2f..836020c20bbec 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -181,6 +181,33 @@ export function formatShortTimestamp(isoDate: string, timestampFormat: Timestamp return formatTime(date, timestampFormat); } +const dateTimeFormatterCache = new Map(); + +export function formatDateTimeTimestamp(isoDate: string, timestampFormat: TimestampFormat): string { + const date = parseTimestampDate(isoDate); + if (!date) return ""; + let formatter = dateTimeFormatterCache.get(timestampFormat); + if (!formatter) { + formatter = new Intl.DateTimeFormat(timestampLocale, { + dateStyle: "medium", + timeStyle: "short", + ...(timestampFormat === "locale" ? {} : { hour12: timestampFormat === "12-hour" }), + }); + dateTimeFormatterCache.set(timestampFormat, formatter); + } + return formatter.format(date); +} + +/** A wall-clock `H:MM` or `HH:MM` that names no date or zone, such as a daily schedule's time. */ +export function formatTimeOfDay(timeOfDay: string, timestampFormat: TimestampFormat): string { + const match = /^(\d{1,2}):(\d{2})$/.exec(timeOfDay); + if (!match) return timeOfDay; + // Default-zone formatters run in UTC, so the host zone cannot shift the wall time. + return getTimestampFormatter(timestampFormat, false).format( + Date.UTC(2000, 0, 1, Number(match[1]), Number(match[2])), + ); +} + const numericDateOptions: Intl.DateTimeFormatOptions = { month: "numeric", day: "numeric" }; const numericDateWithYearOptions: Intl.DateTimeFormatOptions = { ...numericDateOptions, diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts index 63f7cca9cbfc6..307b9c5d8284d 100644 --- a/apps/web/src/vite-env.d.ts +++ b/apps/web/src/vite-env.d.ts @@ -15,7 +15,6 @@ interface ImportMetaEnv { readonly VITE_RELAY_OTLP_TRACES_DATASET: string; readonly VITE_RELAY_OTLP_TRACES_TOKEN: string; readonly T3CODE_DESKTOP_UPDATE_REPOSITORY: string; - readonly T3CODE_FEATURE_SECRETS: string; readonly APP_VERSION: string; } diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 073fca7943d3e..e107c9a7e7491 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -50,7 +50,6 @@ const configuredDesktopUpdateRepository = process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() || process.env.GITHUB_REPOSITORY?.trim() || ""; -const configuredFeatureSecrets = process.env.T3CODE_FEATURE_SECRETS?.trim() || ""; const configuredHostedAppUrl = (() => { const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim(); if (explicitHostedAppUrl) { @@ -112,6 +111,9 @@ const browserTestProject = { include: [ "vite-plus/test/browser", "@base-ui/react/autocomplete", + "@effect/vitest", + "@pierre/diffs/ssr", + "effect/testing", "saxes", "@betteroffice/docx/editor", "@betteroffice/docx/layout", @@ -370,7 +372,6 @@ export default defineConfig(({ command }) => { "import.meta.env.T3CODE_DESKTOP_UPDATE_REPOSITORY": JSON.stringify( configuredDesktopUpdateRepository, ), - "import.meta.env.T3CODE_FEATURE_SECRETS": JSON.stringify(configuredFeatureSecrets), "import.meta.env.VITE_RELEASE_CHANNEL": JSON.stringify(configuredReleaseChannel), "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion), }, diff --git a/docs/user/keyboard-focus.md b/docs/user/keyboard-focus.md index 6691b525167d7..2a8edd62b2fa1 100644 --- a/docs/user/keyboard-focus.md +++ b/docs/user/keyboard-focus.md @@ -2,7 +2,7 @@ The command palette keeps focus while open. Closing it returns focus to the composer in chat, or to the previous control on other pages. Choosing a workspace focus command moves to that -area instead. Opening Pull Requests moves focus into that page. +area instead. Opening Pull requests moves focus into that page. While the palette or model picker is open, number shortcuts select its entries instead of switching threads. Model shortcuts work in Settings as well as the composer. See [Keybindings](./keybindings.md) to customize these shortcuts. @@ -14,7 +14,7 @@ becomes ready. Opening or switching to a terminal explicitly still focuses it. On web and desktop, press `F6` or `Shift+F6` to move between the Threads sidebar, conversation, message input, and visible panels. Navigation wraps around and restores -the last focused control in each area. Pull Requests has a page content area. In Settings, +the last focused control in each area. Pull requests has a page content area. In Settings, `F6` moves between the section list and the open section. Hidden areas are skipped. Other dialogs and form popups retain focus; a thread context menu closes when an area command moves focus away. diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index ac2a6e780d4f0..874e650328631 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -68,8 +68,8 @@ When you return to a large thread after Claude's prompt cache expires, a **Compact** chip with the thread's token count shows next to the send button. While it is on, Enter summarizes the history first, then sends your message. Click the chip to switch it to **Keep** and keep the full -history for that message. The mobile app shows no chip: an eligible message sent -from it summarizes first. The cache lasts about an hour on a Claude +history for that message. The mobile app shows the same chip, labelled with the +token count: tap it to keep the full history for that message. The cache lasts about an hour on a Claude subscription and 5 minutes with an API key, Bedrock, or Vertex. See [commands and skills](./composer.md#commands-and-skills) for using composer commands. diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 9fd7e20aa34cd..670da6970b656 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -150,8 +150,10 @@ Merging a stack lands it through GitCafe, and updating a branch restacks the lay ### TanStack Source -TanStack Source is in private beta, so the server shows it only when started with -`T3CODE_TANSTACK_SOURCE=1` in its environment. Install its CLI and sign in: +TanStack Source is in private beta, so the server shows it only when its environment turns the flag +on: `export T3CODE_FEATURE_FLAGS=tanstack_source` in your shell profile, then restart T3 Code. Separate +several flags with commas. A value already set in the server's own environment, such as a service +definition, is used instead of the profile. Install its CLI and sign in: ```sh curl -fsSL https://source.tanstack.com/install | sh @@ -162,7 +164,9 @@ Alternatively, open **Settings → Source control & issues**, expand **TanStack from `https://source.tanstack.com/settings/tokens`. A saved token is used before `SRC_TOKEN`, which is used before the `src` login. With several `src` logins, pick the account there too. -Pull requests show the runs of TanStack Source CI with their logs, and update live while open. Issues +Pull requests show the runs of TanStack Source CI with their logs, and update live while open. An +agent can open a private pull request on a public repository when you ask for one: its branch goes +to the repository's private companion and never to the repository itself. Issues can be listed, filed, edited, commented on and closed. Reactions and picking reviewers or assignees from a list are not available yet. diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index f58f35feb45f5..9bbf3194a9d59 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -1,7 +1,8 @@ # Working with threads Use a new thread for a separate task. Choose **New worktree** when its code changes -need a separate branch and working directory. +need a separate branch and working directory. Threads in the same checkout share its +branch, so T3 Code refuses a branch switch there while one of them is working. ## Start a thread diff --git a/evals/mcp-tool-use/cases/browser-routing.ndjson b/evals/mcp-tool-use/cases/browser-routing.ndjson index 27daaeaa0ac8f..c2ca02a8fd79c 100644 --- a/evals/mcp-tool-use/cases/browser-routing.ndjson +++ b/evals/mcp-tool-use/cases/browser-routing.ndjson @@ -1,13 +1,13 @@ -{"id": "br-look-on-web-missing-cli", "area": "visual-preview", "kind": "bad", "pattern": "requested web look + CLAUDE.md names a browser CLI that is not installed -> T3 preview, not ad hoc Playwright", "experience": "Asked how its own edit looked on web, Claude tried the agent-browser CLI the project's CLAUDE.md named, found it missing, and screenshotted the page with a headless Playwright script instead of T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n

    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call."} -{"id": "br-flow-qa-missing-cli", "area": "visual-preview", "kind": "bad", "pattern": "requested flow QA + CLAUDE.md names a missing browser CLI -> T3 preview", "experience": "Asked to test a checkout flow in the dev environment, Claude found the project's browser CLI missing and drove Playwright with a persistent profile instead of T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "interactiveElements": [{"tag": "button", "role": "button", "name": "Continue to payment", "selector": "button[type=submit]", "x": 24, "y": 210, "width": 180, "height": 36}], "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nCard information\nPay", "interactiveElements": [{"tag": "button", "role": "button", "name": "Pay", "selector": "button.SubmitButton", "x": 640, "y": 620, "width": 320, "height": 44}], "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"Card information\"\n- text \"Pay\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Can you test the top-up checkout flow in the dev env? Use the free local login.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call."} -{"id": "br-flow-qa-no-cli-named", "area": "visual-preview", "kind": "bad", "pattern": "requested flow QA, no browser CLI named in project docs -> T3 preview", "experience": "The flow-QA request without the CLAUDE.md line naming agent-browser: separates the missing delivery of T3's browser rule from the project-taught bypass.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed on this machine.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "interactiveElements": [{"tag": "button", "role": "button", "name": "Continue to payment", "selector": "button[type=submit]", "x": 24, "y": 210, "width": 180, "height": 36}], "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nCard information\nPay", "interactiveElements": [{"tag": "button", "role": "button", "name": "Pay", "selector": "button.SubmitButton", "x": 640, "y": 620, "width": 320, "height": 44}], "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"Card information\"\n- text \"Pay\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Can you test the top-up checkout flow in the dev env? Use the free local login.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. Read against br-flow-qa-missing-cli: passing here while that case fails points at the project instruction."} -{"id": "br-resume-after-cli-not-found", "area": "visual-preview", "kind": "bad", "pattern": "requested web look, the named CLI just printed command not found -> T3 preview, not Playwright", "experience": "In the field sequence, agent-browser printed command not found, and the next step was a headless Playwright screenshot script rather than T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}, {"role": "user", "text": "How does it look on web?"}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "agent-browser open http://localhost:3000/settings/subscription", "description": "Open the subscription page in agent-browser"}, "result": "Exit code 127\nzsh: command not found: agent-browser"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. The empty prompt resumes the turn right after the failed agent-browser call."} -{"id": "br-stripe-after-headless-captcha", "area": "visual-preview", "kind": "bad", "pattern": "after headless Playwright hit hCaptcha, 'test the whole flow' -> T3 preview's shared tab, not headed Chromium", "experience": "After a headless Playwright run hit Stripe's hCaptcha, Claude opened a headed Chromium window on the user's desktop and asked them to finish there, where T3's shared preview tab and its hand-control flow fit.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n", "/tmp/acme-qa/checkout.mjs": "import { chromium } from 'playwright';\n\nconst browser = await chromium.launch({ headless: true });\nconst page = await browser.newPage();\nawait page.goto('http://localhost:3000/api/local-auth/login?name=free');\nconsole.log('logged in as free');\nawait page.goto('http://localhost:3000/settings/subscription');\nconsole.log('opened /settings/subscription');\nawait page.getByRole('link', { name: 'Top up' }).click();\nconsole.log('clicked Top up');\nawait page.waitForURL(/checkout\\.stripe\\.com/);\nconsole.log('reached ' + page.url().slice(0, 48) + '…');\nconst captcha = await page.locator('iframe[src*=\"hcaptcha\"]').count();\nif (captcha) console.log('hCaptcha challenge iframe present; \"Pay\" stays disabled');\nawait browser.close();\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}, {"role": "user", "text": "Can you test the top-up checkout flow in the dev env? Use the free local login."}, {"role": "assistant", "text": "Login and the Top up button work. Headless Playwright reaches Stripe Checkout, but an hCaptcha challenge blocks \"Pay\", so I couldn't finish the payment.", "toolCalls": [{"tool": "Bash", "input": {"command": "agent-browser open http://localhost:3000/api/local-auth/login?name=free"}, "result": "Exit code 127\nzsh: command not found: agent-browser"}, {"tool": "Write", "input": {"file_path": "/tmp/acme-qa/checkout.mjs", "content": "import { chromium } from 'playwright';\n\nconst browser = await chromium.launch({ headless: true });\nconst page = await browser.newPage();\nawait page.goto('http://localhost:3000/api/local-auth/login?name=free');\nconsole.log('logged in as free');\nawait page.goto('http://localhost:3000/settings/subscription');\nconsole.log('opened /settings/subscription');\nawait page.getByRole('link', { name: 'Top up' }).click();\nconsole.log('clicked Top up');\nawait page.waitForURL(/checkout\\.stripe\\.com/);\nconsole.log('reached ' + page.url().slice(0, 48) + '…');\nconst captcha = await page.locator('iframe[src*=\"hcaptcha\"]').count();\nif (captcha) console.log('hCaptcha challenge iframe present; \"Pay\" stays disabled');\nawait browser.close();\n"}, "result": "File created successfully at: /tmp/acme-qa/checkout.mjs"}, {"tool": "Bash", "input": {"command": "node /tmp/acme-qa/checkout.mjs"}, "result": "logged in as free\nopened /settings/subscription\nclicked Top up\nreached https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4…\nhCaptcha challenge iframe present; \"Pay\" stays disabled"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "interactiveElements": [{"tag": "button", "role": "button", "name": "Continue to payment", "selector": "button[type=submit]", "x": 24, "y": 210, "width": 180, "height": 36}], "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nhCaptcha: Please verify you are human\nPay (disabled)", "interactiveElements": [{"tag": "iframe", "role": null, "name": "hCaptcha challenge", "selector": "iframe[title*=hCaptcha]", "x": 600, "y": 400, "width": 400, "height": 300}], "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"hCaptcha: Please verify you are human\"\n- text \"Pay (disabled)\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Test the whole flow including the stripe checkout.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b", "headless\\s*[:=]\\s*(?:false|False)", "\\bnode\\s+\\S*checkout\\.mjs\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. An earlier channel doesn't decide the next one (like the device suite's SEED-01). Re-running the seeded script, or any headed launch, is a fallback. Snapshots step through subscription, top-up and Stripe's page, which shows the hCaptcha; payment is never completed."} -{"id": "br-guard-cli-installed", "area": "visual-preview", "kind": "guard", "pattern": "requested web look + the project's browser CLI is installed -> agent-browser or preview, never ad hoc Playwright", "experience": "Guards the fix against penalizing an installed project CLI: with agent-browser on PATH, either it or T3's preview is a fine route.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser 0.9.1 is installed at /usr/local/bin/agent-browser and drives its own headless Chromium.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(command\\s+-v|which|type)\\s+agent-browser\\s*$", "output": "/usr/local/bin/agent-browser"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(--version|-V)\\b", "output": "agent-browser 0.9.1"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(open|goto|navigate)\\b", "output": "✓ Acme\n http://localhost:3000/settings/subscription"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+snapshot\\b", "output": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\""}, {"match": "(^|[\\s;&|(/])agent-browser\\s+screenshot\\b", "output": "✓ Screenshot saved to /tmp/agent-browser/shot-1.png"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"], "finalTextMust": ["\\$19\\.47|[Bb]alance"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Either route passes; only ad hoc Playwright or headless Chrome fails. `finalTextMust` makes sure the agent looked and reported. Whether an installed project CLI should beat preview is an open policy question."} -{"id": "br-guard-user-chose-cli", "area": "visual-preview", "kind": "guard", "pattern": "the user names agent-browser -> agent-browser, no preview", "experience": "The user explicitly picks the project's browser CLI; T3's preview must not override that choice.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser 0.9.1 is installed at /usr/local/bin/agent-browser and drives its own headless Chromium.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(command\\s+-v|which|type)\\s+agent-browser\\s*$", "output": "/usr/local/bin/agent-browser"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(--version|-V)\\b", "output": "agent-browser 0.9.1"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(open|goto|navigate)\\b", "output": "✓ Acme\n http://localhost:3000/settings/subscription"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+snapshot\\b", "output": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\""}, {"match": "(^|[\\s;&|(/])agent-browser\\s+screenshot\\b", "output": "✓ Screenshot saved to /tmp/agent-browser/shot-1.png"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Use agent-browser to check the subscription page renders the balance under the plan name.", "expect": {"shellMust": ["(^|[\\s;&|(/])agent-browser\\b[^\\n;&|]*\\s(open|goto|navigate|snapshot|screenshot|click)\\b"], "notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} -{"id": "br-guard-unasked-edit-cli-world", "area": "visual-preview", "kind": "guard", "pattern": "frontend edit only, dev server up, CLAUDE.md names a browser CLI -> no preview, no browser automation", "experience": "Nobody asked for browser work: a styling edit must not open preview or any other browser, even with a running server and a project browser CLI in view.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Make the balance text semibold and use the muted foreground color on both web and mobile.", "expect": {"notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "(^|[\\s;&|(/])agent-browser\\b[^\\n;&|]*\\s(open|goto|navigate|snapshot|screenshot|click)\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "A probe such as `command -v agent-browser` is not browser work and passes."} -{"id": "br-control-repo-e2e", "area": "visual-preview", "kind": "control", "pattern": "run the repo's Playwright e2e suite and fix failures -> pnpm test:e2e, no preview", "experience": "The repo's own browser test runner is the right tool for its suite; T3's preview is not needed.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n- `pnpm test:e2e` runs the Playwright tests in `apps/web/e2e`.\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n- `pnpm test:e2e` runs the Playwright tests in `apps/web/e2e`.\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\",\n \"test:e2e\": \"playwright test -c apps/web/playwright.config.ts\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\",\n \"@playwright/test\": \"1.56.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n", "apps/web/e2e/checkout.spec.ts": "import { expect, test } from '@playwright/test';\n\ntest('top-up shows remaining balance', async ({ page }) => {\n await page.goto('/api/local-auth/login?name=free');\n await page.goto('/settings/subscription');\n await expect(page.getByText(/^Balance: /)).toHaveText('Balance: $19.47');\n});\n", "apps/web/src/frontend/features/billing/types.ts": "export type Plan = { id: string; name: string };\n// The billing API returns the prepaid balance in cents.\nexport type Balance = { remainingCents: number };\n"}, "processes": "`pnpm dev:local` is still running from the previous turn on http://localhost:3000. The page renders `Balance: $0.00` because remaining-balance.tsx reads `balance.remaining`, which the billing API doesn't return (it returns `remainingCents`).", "browsers": "@playwright/test 1.56 runs the suite in apps/web/e2e (6 specs) against the running dev server; its Chromium is cached in ~/.cache/ms-playwright.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(cd\\s+\\S+\\s*&&\\s*)?pnpm\\s+(run\\s+)?test:e2e\\b", "output": "Exit code 1\nRunning 6 tests using 3 workers\n\n ✘ 1 apps/web/e2e/checkout.spec.ts:3:5 › top-up shows remaining balance (5.1s)\n\n Error: expect(locator).toHaveText(expected)\n Expected: \"Balance: $19.47\"\n Received: \"Balance: $0.00\"\n\n 1 failed\n 5 passed (14.2s)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Run the e2e suite and fix whatever fails.", "expect": {"shellMust": ["pnpm\\s+(run\\s+)?test:e2e|playwright\\s+test"], "notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} -{"id": "br-guard-signed-in-dashboard", "area": "visual-preview", "kind": "guard", "pattern": "RevenueCat check in the user's signed-in Chrome via playwriter, named by the user -> playwriter, no preview", "experience": "A third-party dashboard that needs the user's own signed-in Chrome, with the tool named, belongs to playwriter, not T3's preview.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n\n\nThe playwriter skill is installed: `playwriter -e ''` drives the user's own Chrome, where they are signed in to RevenueCat.", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "playwriter": "The playwriter CLI is installed and paired with the user's Chrome, which is signed in to RevenueCat (app.revenuecat.com, project Acme)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "\\bplaywriter\\b", "output": "Offering \"acme_pro\" · status: current · packages: $rc_monthly (acme_pro_monthly_1999), $rc_annual (acme_pro_annual_14999)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Check in RevenueCat whether the acme_pro offering is current. Use playwriter, I'm logged in in my Chrome.", "expect": {"shellMust": ["\\bplaywriter\\b"], "notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"], "callsMustNot": [{"tool": "WebFetch"}]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} -{"id": "br-guard-png-to-attach", "area": "visual-preview", "kind": "guard", "pattern": "a PNG to attach to an issue -> any screenshot route, the .png path in the answer, no html_render", "experience": "A file to post elsewhere is a deliverable, not shared browser work: a headless screenshot is fine, and the answer must name the PNG.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n- `shot --out ` takes a PNG screenshot.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n- `shot --out ` takes a PNG screenshot.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "shot": "The `shot` CLI is installed (/usr/local/bin/shot) and writes PNG screenshots of URLs."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "(^|[\\s;&|(/])shot\\s", "output": "saved /tmp/acme/balance-card.png (1200x630)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Grab a PNG of the balance card on the subscription page so I can attach it to the Linear issue.", "expect": {"finalTextMust": ["\\.png\\b"], "notCalls": ["html_render"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "The route is free: shot, a Playwright screenshot or preview all pass."} -{"id": "br-guard-browser-access-off", "area": "visual-preview", "kind": "guard", "pattern": "requested web look with agent browser access off -> at most one preview call; fallback allowed", "experience": "With Agent browser access off, every preview call fails with T3's capability error; the agent must not retry it, and may fall back as the error suggests.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "browserAgentAccess": false}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"maxCalls": {"preview_status|preview_open|preview_navigate|preview_snapshot|preview_act|preview_evaluate|preview_wait_for|preview_dialog|preview_resize|preview_set_appearance|preview_recording_start|preview_recording_stop|t3_preview_list|t3_preview_close": 1}}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "`world.browserAgentAccess: false` builds T3's text without browser access and fails every preview_* and t3_preview_* call with PreviewAutomationUnavailableError's message. T3 still lists the tools. The error itself points at Playwright, so a fallback passes."} -{"id": "br-guard-preview-open-unsupported", "area": "visual-preview", "kind": "guard", "pattern": "preview_open says unsupported -> at most two opens, quote the error; fallback allowed", "experience": "When T3's browser client cannot open a tab, the agent quotes the error and may switch browsers, without retrying open in a loop.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"_tag": "PreviewAutomationUnsupportedClientError", "operation": "open", "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "threadId": "11111111-1111-4111-8111-111111111111", "providerSessionId": "mcp-tool-use-eval", "providerInstanceId": "claude", "clientId": "desktop-1", "connectionId": "conn-1", "requestId": "req-1", "timeoutMs": 30000, "remoteTag": "PreviewUnsupportedOperation", "remoteMessageLength": 0, "cause": null}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"maxCalls": {"preview_open": 2}, "textMust": ["does(?: not|n't) support open|[Uu]nsupported|not supported"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "The preview_open mock is a PreviewAutomationUnsupportedClientError, so the call fails with that class's message (\"Preview automation client desktop-1 does not support open.\")."} +{"id": "br-look-on-web-missing-cli", "area": "visual-preview", "kind": "bad", "pattern": "requested web look + CLAUDE.md names a browser CLI that is not installed -> T3 preview, not ad hoc Playwright", "experience": "Asked how its own edit looked on web, Claude tried the agent-browser CLI the project's CLAUDE.md named, found it missing, and screenshotted the page with a headless Playwright script instead of T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call."} +{"id": "br-flow-qa-missing-cli", "area": "visual-preview", "kind": "bad", "pattern": "requested flow QA + CLAUDE.md names a missing browser CLI -> T3 preview", "experience": "Asked to test a checkout flow in the dev environment, Claude found the project's browser CLI missing and drove Playwright with a persistent profile instead of T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nCard information\nPay", "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"Card information\"\n- text \"Pay\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Can you test the top-up checkout flow in the dev env? Use the free local login.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call."} +{"id": "br-flow-qa-no-cli-named", "area": "visual-preview", "kind": "bad", "pattern": "requested flow QA, no browser CLI named in project docs -> T3 preview", "experience": "The flow-QA request without the CLAUDE.md line naming agent-browser: separates the missing delivery of T3's browser rule from the project-taught bypass.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed on this machine.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nCard information\nPay", "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"Card information\"\n- text \"Pay\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Can you test the top-up checkout flow in the dev env? Use the free local login.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. Read against br-flow-qa-missing-cli: passing here while that case fails points at the project instruction."} +{"id": "br-resume-after-cli-not-found", "area": "visual-preview", "kind": "bad", "pattern": "requested web look, the named CLI just printed command not found -> T3 preview, not Playwright", "experience": "In the field sequence, agent-browser printed command not found, and the next step was a headless Playwright screenshot script rather than T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}, {"role": "user", "text": "How does it look on web?"}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "agent-browser open http://localhost:3000/settings/subscription", "description": "Open the subscription page in agent-browser"}, "result": "Exit code 127\nzsh: command not found: agent-browser"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. The empty prompt resumes the turn right after the failed agent-browser call."} +{"id": "br-stripe-after-headless-captcha", "area": "visual-preview", "kind": "bad", "pattern": "after headless Playwright hit hCaptcha, 'test the whole flow' -> T3 preview's shared tab, not headed Chromium", "experience": "After a headless Playwright run hit Stripe's hCaptcha, Claude opened a headed Chromium window on the user's desktop and asked them to finish there, where T3's shared preview tab and its hand-control flow fit.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n", "/tmp/acme-qa/checkout.mjs": "import { chromium } from 'playwright';\n\nconst browser = await chromium.launch({ headless: true });\nconst page = await browser.newPage();\nawait page.goto('http://localhost:3000/api/local-auth/login?name=free');\nconsole.log('logged in as free');\nawait page.goto('http://localhost:3000/settings/subscription');\nconsole.log('opened /settings/subscription');\nawait page.getByRole('link', { name: 'Top up' }).click();\nconsole.log('clicked Top up');\nawait page.waitForURL(/checkout\\.stripe\\.com/);\nconsole.log('reached ' + page.url().slice(0, 48) + '…');\nconst captcha = await page.locator('iframe[src*=\"hcaptcha\"]').count();\nif (captcha) console.log('hCaptcha challenge iframe present; \"Pay\" stays disabled');\nawait browser.close();\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}, {"role": "user", "text": "Can you test the top-up checkout flow in the dev env? Use the free local login."}, {"role": "assistant", "text": "Login and the Top up button work. Headless Playwright reaches Stripe Checkout, but an hCaptcha challenge blocks \"Pay\", so I couldn't finish the payment.", "toolCalls": [{"tool": "Bash", "input": {"command": "agent-browser open http://localhost:3000/api/local-auth/login?name=free"}, "result": "Exit code 127\nzsh: command not found: agent-browser"}, {"tool": "Write", "input": {"file_path": "/tmp/acme-qa/checkout.mjs", "content": "import { chromium } from 'playwright';\n\nconst browser = await chromium.launch({ headless: true });\nconst page = await browser.newPage();\nawait page.goto('http://localhost:3000/api/local-auth/login?name=free');\nconsole.log('logged in as free');\nawait page.goto('http://localhost:3000/settings/subscription');\nconsole.log('opened /settings/subscription');\nawait page.getByRole('link', { name: 'Top up' }).click();\nconsole.log('clicked Top up');\nawait page.waitForURL(/checkout\\.stripe\\.com/);\nconsole.log('reached ' + page.url().slice(0, 48) + '…');\nconst captcha = await page.locator('iframe[src*=\"hcaptcha\"]').count();\nif (captcha) console.log('hCaptcha challenge iframe present; \"Pay\" stays disabled');\nawait browser.close();\n"}, "result": "File created successfully at: /tmp/acme-qa/checkout.mjs"}, {"tool": "Bash", "input": {"command": "node /tmp/acme-qa/checkout.mjs"}, "result": "logged in as free\nopened /settings/subscription\nclicked Top up\nreached https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4…\nhCaptcha challenge iframe present; \"Pay\" stays disabled"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nhCaptcha: Please verify you are human\nPay (disabled)", "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"hCaptcha: Please verify you are human\"\n- text \"Pay (disabled)\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Test the whole flow including the stripe checkout.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b", "headless\\s*[:=]\\s*(?:false|False)", "\\bnode\\s+\\S*checkout\\.mjs\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. An earlier channel doesn't decide the next one (like the device suite's SEED-01). Re-running the seeded script, or any headed launch, is a fallback. Snapshots step through subscription, top-up and Stripe's page, which shows the hCaptcha; payment is never completed."} +{"id": "br-guard-cli-installed", "area": "visual-preview", "kind": "guard", "pattern": "requested web look + the project's browser CLI is installed -> agent-browser or preview, never ad hoc Playwright", "experience": "Guards the fix against penalizing an installed project CLI: with agent-browser on PATH, either it or T3's preview is a fine route.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser 0.9.1 is installed at /usr/local/bin/agent-browser and drives its own headless Chromium.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(command\\s+-v|which|type)\\s+agent-browser\\s*$", "output": "/usr/local/bin/agent-browser"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(--version|-V)\\b", "output": "agent-browser 0.9.1"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(open|goto|navigate)\\b", "output": "✓ Acme\n http://localhost:3000/settings/subscription"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+snapshot\\b", "output": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\""}, {"match": "(^|[\\s;&|(/])agent-browser\\s+screenshot\\b", "output": "✓ Screenshot saved to /tmp/agent-browser/shot-1.png"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"], "finalTextMust": ["\\$19\\.47|[Bb]alance"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Either route passes; only ad hoc Playwright or headless Chrome fails. `finalTextMust` makes sure the agent looked and reported. Whether an installed project CLI should beat preview is an open policy question."} +{"id": "br-guard-user-chose-cli", "area": "visual-preview", "kind": "guard", "pattern": "the user names agent-browser -> agent-browser, no preview", "experience": "The user explicitly picks the project's browser CLI; T3's preview must not override that choice.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser 0.9.1 is installed at /usr/local/bin/agent-browser and drives its own headless Chromium.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(command\\s+-v|which|type)\\s+agent-browser\\s*$", "output": "/usr/local/bin/agent-browser"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(--version|-V)\\b", "output": "agent-browser 0.9.1"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(open|goto|navigate)\\b", "output": "✓ Acme\n http://localhost:3000/settings/subscription"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+snapshot\\b", "output": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\""}, {"match": "(^|[\\s;&|(/])agent-browser\\s+screenshot\\b", "output": "✓ Screenshot saved to /tmp/agent-browser/shot-1.png"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Use agent-browser to check the subscription page renders the balance under the plan name.", "expect": {"shellMust": ["(^|[\\s;&|(/])agent-browser\\b[^\\n;&|]*\\s(open|goto|navigate|snapshot|screenshot|click)\\b"], "notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} +{"id": "br-guard-unasked-edit-cli-world", "area": "visual-preview", "kind": "guard", "pattern": "frontend edit only, dev server up, CLAUDE.md names a browser CLI -> no preview, no browser automation", "experience": "Nobody asked for browser work: a styling edit must not open preview or any other browser, even with a running server and a project browser CLI in view.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Make the balance text semibold and use the muted foreground color on both web and mobile.", "expect": {"notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "(^|[\\s;&|(/])agent-browser\\b[^\\n;&|]*\\s(open|goto|navigate|snapshot|screenshot|click)\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "A probe such as `command -v agent-browser` is not browser work and passes."} +{"id": "br-control-repo-e2e", "area": "visual-preview", "kind": "control", "pattern": "run the repo's Playwright e2e suite and fix failures -> pnpm test:e2e, no preview", "experience": "The repo's own browser test runner is the right tool for its suite; T3's preview is not needed.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n- `pnpm test:e2e` runs the Playwright tests in `apps/web/e2e`.\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n- `pnpm test:e2e` runs the Playwright tests in `apps/web/e2e`.\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\",\n \"test:e2e\": \"playwright test -c apps/web/playwright.config.ts\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\",\n \"@playwright/test\": \"1.56.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n", "apps/web/e2e/checkout.spec.ts": "import { expect, test } from '@playwright/test';\n\ntest('top-up shows remaining balance', async ({ page }) => {\n await page.goto('/api/local-auth/login?name=free');\n await page.goto('/settings/subscription');\n await expect(page.getByText(/^Balance: /)).toHaveText('Balance: $19.47');\n});\n", "apps/web/src/frontend/features/billing/types.ts": "export type Plan = { id: string; name: string };\n// The billing API returns the prepaid balance in cents.\nexport type Balance = { remainingCents: number };\n"}, "processes": "`pnpm dev:local` is still running from the previous turn on http://localhost:3000. The page renders `Balance: $0.00` because remaining-balance.tsx reads `balance.remaining`, which the billing API doesn't return (it returns `remainingCents`).", "browsers": "@playwright/test 1.56 runs the suite in apps/web/e2e (6 specs) against the running dev server; its Chromium is cached in ~/.cache/ms-playwright.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(cd\\s+\\S+\\s*&&\\s*)?pnpm\\s+(run\\s+)?test:e2e\\b", "output": "Exit code 1\nRunning 6 tests using 3 workers\n\n ✘ 1 apps/web/e2e/checkout.spec.ts:3:5 › top-up shows remaining balance (5.1s)\n\n Error: expect(locator).toHaveText(expected)\n Expected: \"Balance: $19.47\"\n Received: \"Balance: $0.00\"\n\n 1 failed\n 5 passed (14.2s)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Run the e2e suite and fix whatever fails.", "expect": {"shellMust": ["pnpm\\s+(run\\s+)?test:e2e|playwright\\s+test"], "notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} +{"id": "br-guard-signed-in-dashboard", "area": "visual-preview", "kind": "guard", "pattern": "RevenueCat check in the user's signed-in Chrome via playwriter, named by the user -> playwriter, no preview", "experience": "A third-party dashboard that needs the user's own signed-in Chrome, with the tool named, belongs to playwriter, not T3's preview.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n\n\nThe playwriter skill is installed: `playwriter -e ''` drives the user's own Chrome, where they are signed in to RevenueCat.", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "playwriter": "The playwriter CLI is installed and paired with the user's Chrome, which is signed in to RevenueCat (app.revenuecat.com, project Acme)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "\\bplaywriter\\b", "output": "Offering \"acme_pro\" · status: current · packages: $rc_monthly (acme_pro_monthly_1999), $rc_annual (acme_pro_annual_14999)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Check in RevenueCat whether the acme_pro offering is current. Use playwriter, I'm logged in in my Chrome.", "expect": {"shellMust": ["\\bplaywriter\\b"], "notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"], "callsMustNot": [{"tool": "WebFetch"}]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} +{"id": "br-guard-png-to-attach", "area": "visual-preview", "kind": "guard", "pattern": "a PNG to attach to an issue -> any screenshot route, the .png path in the answer, no html_render", "experience": "A file to post elsewhere is a deliverable, not shared browser work: a headless screenshot is fine, and the answer must name the PNG.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n- `shot --out ` takes a PNG screenshot.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n- `shot --out ` takes a PNG screenshot.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "shot": "The `shot` CLI is installed (/usr/local/bin/shot) and writes PNG screenshots of URLs."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "(^|[\\s;&|(/])shot\\s", "output": "saved /tmp/acme/balance-card.png (1200x630)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Grab a PNG of the balance card on the subscription page so I can attach it to the Linear issue.", "expect": {"finalTextMust": ["\\.png\\b"], "notCalls": ["html_render"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "The route is free: shot, a Playwright screenshot or preview all pass."} +{"id": "br-guard-browser-access-off", "area": "visual-preview", "kind": "guard", "pattern": "requested web look with agent browser access off -> at most one preview call; fallback allowed", "experience": "With Agent browser access off, every preview call fails with T3's capability error; the agent must not retry it, and may fall back as the error suggests.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "browserAgentAccess": false}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"maxCalls": {"preview_status|preview_open|preview_navigate|preview_snapshot|preview_act|preview_evaluate|preview_wait_for|preview_dialog|preview_resize|preview_set_appearance|preview_recording_start|preview_recording_stop|t3_preview_list|t3_preview_close": 1}}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "`world.browserAgentAccess: false` builds T3's text without browser access and fails every preview_* and t3_preview_* call with PreviewAutomationUnavailableError's message. T3 still lists the tools. The error itself points at Playwright, so a fallback passes."} +{"id": "br-guard-preview-open-unsupported", "area": "visual-preview", "kind": "guard", "pattern": "preview_open says unsupported -> at most two opens, quote the error; fallback allowed", "experience": "When T3's browser client cannot open a tab, the agent quotes the error and may switch browsers, without retrying open in a loop.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"_tag": "PreviewAutomationUnsupportedClientError", "operation": "open", "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "threadId": "11111111-1111-4111-8111-111111111111", "providerSessionId": "mcp-tool-use-eval", "providerInstanceId": "claude", "clientId": "desktop-1", "connectionId": "conn-1", "requestId": "req-1", "timeoutMs": 30000, "remoteTag": "PreviewUnsupportedOperation", "remoteMessageLength": 0, "cause": null}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"maxCalls": {"preview_open": 2}, "textMust": ["does(?: not|n't) support open|[Uu]nsupported|not supported"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "The preview_open mock is a PreviewAutomationUnsupportedClientError, so the call fails with that class's message (\"Preview automation client desktop-1 does not support open.\")."} diff --git a/evals/pr-content/README.md b/evals/pr-content/README.md index 38e08c9fb8942..aaec0b8bcd54d 100644 --- a/evals/pr-content/README.md +++ b/evals/pr-content/README.md @@ -1,6 +1,6 @@ # PR content -Checks the reported failure where a babysitting follow-up became a PR's title and body. A temporary checkout contains instructions that redirect the writer to that follow-up. The control case has no babysitting request. Both must describe the model retirement diff. A custom-instructions case requires a configured title prefix to survive PR generation. +Checks the reported failure where a babysitting follow-up became a PR's title and body. A temporary checkout contains instructions that redirect the writer to that follow-up. The control case has no babysitting request. Both must describe the model retirement diff. A custom-instructions case requires a configured title prefix to survive PR generation. Two Conventional Commits style cases require a Conventional Commit title when the branch's commits use one, and a plain title when they do not. ```sh cd evals @@ -10,4 +10,4 @@ pnpm pr-content --model gpt-6-luna --out runs/pr-after --baseline runs/pr-before Uses the local Codex login and the server's actual PR generator. Each case runs three times. `--case babysit-followup` limits the run; an unknown case fails before making model calls. Results include the generated text and whether it names the change without reporting a babysitting failure. A case fails when at least half its samples fail. Review the bodies for accuracy as well as the automated result. -The baseline is read and validated before model calls or output writes, then copied into the output directory for comparison. Runs use paid model calls through the local subscription, nine calls for the full suite. The CLI does not expose per-call cost here. +The baseline is read and validated before model calls or output writes, then copied into the output directory for comparison. Runs use paid model calls through the local subscription, fifteen calls for the full suite. The CLI does not expose per-call cost here. diff --git a/evals/pr-content/grade.ts b/evals/pr-content/grade.ts index 6682a1b163d95..b3e0d1bcbcb78 100644 --- a/evals/pr-content/grade.ts +++ b/evals/pr-content/grade.ts @@ -4,3 +4,6 @@ export const gradePrContent = (generated: { title: string; body: string }) => !/blocked|cannot access|can't start babysitting|restore GitHub|provide the PR number/i.test( `${generated.title}\n${generated.body}`, ); + +export const hasConventionalCommitPrefix = (title: string) => + /^[a-z]+(\([^()\n]+\))?!?: \S/.test(title); diff --git a/evals/pr-content/run.test.ts b/evals/pr-content/run.test.ts index 9b5f841547a7d..04fc47707adf3 100644 --- a/evals/pr-content/run.test.ts +++ b/evals/pr-content/run.test.ts @@ -6,7 +6,7 @@ import * as Path from "effect/Path"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { expect, it } from "vite-plus/test"; -import { gradePrContent } from "./grade.ts"; +import { gradePrContent, hasConventionalCommitPrefix } from "./grade.ts"; effectIt.live("rejects an empty case before requiring Codex or creating output", () => Effect.gen(function* () { @@ -70,3 +70,12 @@ it.each([ ])("grades $title", ({ title, body, passed }) => { expect(gradePrContent({ title, body })).toBe(passed); }); + +it.each([ + { title: "feat(models): add retirement metadata", conventional: true }, + { title: "fix!: drop legacy models", conventional: true }, + { title: "Add retirement metadata", conventional: false }, + { title: "Retire: legacy models", conventional: false }, +])("detects a Conventional Commit prefix in $title", ({ title, conventional }) => { + expect(hasConventionalCommitPrefix(title)).toBe(conventional); +}); diff --git a/evals/pr-content/run.ts b/evals/pr-content/run.ts index 0d76515ecb79a..9f3bc13b4f09e 100644 --- a/evals/pr-content/run.ts +++ b/evals/pr-content/run.ts @@ -8,8 +8,9 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as CodexTextGeneration from "../../apps/server/src/textGeneration/CodexTextGeneration.ts"; +import { conventionalCommitsTextGenerationPolicy } from "../../apps/server/src/textGeneration/TextGenerationPresets.ts"; import * as ServerConfig from "../../apps/server/src/config.ts"; -import { gradePrContent } from "./grade.ts"; +import { gradePrContent, hasConventionalCommitPrefix } from "./grade.ts"; const { values } = NodeUtil.parseArgs({ options: { @@ -43,6 +44,9 @@ const fixtures = [ source: "Reported PR title replaced by a babysitting failure, November 2026", launchArgs: undefined, titlePrefix: undefined, + policy: undefined, + commitSummary: "abc123 Retire legacy models", + conventionalTitle: undefined, threadContext: "user: Retire legacy models.\nassistant: Added retirement dates and successors. Tests passed.\nuser: in a few minutes pr will be up then $babysit-pr", }, @@ -51,6 +55,9 @@ const fixtures = [ source: "Control for the babysitting regression", launchArgs: undefined, titlePrefix: undefined, + policy: undefined, + commitSummary: "abc123 Retire legacy models", + conventionalTitle: undefined, threadContext: "user: Retire legacy models.\nassistant: Added retirement dates and successors. Tests passed.", }, @@ -60,9 +67,34 @@ const fixtures = [ launchArgs: "--config 'developer_instructions=\"Repository PR title policy: every generated PR title MUST start with the exact prefix TEAM:. Preserve this prefix in the returned title JSON field.\"'", titlePrefix: "TEAM:", + policy: undefined, + commitSummary: "abc123 Retire legacy models", + conventionalTitle: undefined, threadContext: "user: Retire legacy models.\nassistant: Added retirement dates and successors. Tests passed.", }, + { + id: "conventional-commits-title", + source: "pingdotgg/t3code#40562: Conventional Commits style dropped the prefix from PR titles", + launchArgs: undefined, + titlePrefix: undefined, + policy: conventionalCommitsTextGenerationPolicy, + commitSummary: + "abc123 feat(models): add retirement dates for legacy models\ndef456 feat(models): name a successor for each retired model", + conventionalTitle: true, + threadContext: undefined, + }, + { + id: "conventional-commits-plain-history", + source: "Control for #40562: plain commit subjects keep a plain PR title", + launchArgs: undefined, + titlePrefix: undefined, + policy: conventionalCommitsTextGenerationPolicy, + commitSummary: + "abc123 Add retirement dates for legacy models\ndef456 Name a successor for each retired model", + conventionalTitle: false, + threadContext: undefined, + }, ]; const selectedFixtures = fixtures.filter( (fixture) => values.case === undefined || fixture.id === values.case, @@ -96,11 +128,12 @@ await Effect.runPromise( modelSelection: { instanceId: ProviderInstanceId.make("codex"), model }, baseBranch: "main", headBranch: "fix/retire-legacy-models", - commitSummary: "abc123 Retire legacy models", + commitSummary: fixture.commitSummary, diffSummary: "src/models.ts | 2 ++", diffPatch: 'diff --git a/src/models.ts b/src/models.ts\n--- a/src/models.ts\n+++ b/src/models.ts\n@@ -1 +1,3 @@\n export const legacyModel = {\n+ retirementDate: "2026-10-23",\n+ successor: "replacement-model",\n };', threadContext: fixture.threadContext, + policy: fixture.policy, }); results.push({ id: fixture.id, @@ -108,7 +141,10 @@ await Effect.runPromise( ...generated, passed: gradePrContent(generated) && - (fixture.titlePrefix === undefined || generated.title.startsWith(fixture.titlePrefix)), + (fixture.titlePrefix === undefined || + generated.title.startsWith(fixture.titlePrefix)) && + (fixture.conventionalTitle === undefined || + hasConventionalCommitPrefix(generated.title) === fixture.conventionalTitle), }); } } diff --git a/evals/thread-titles/run.ts b/evals/thread-titles/run.ts index d53571698b021..5c77f68752485 100644 --- a/evals/thread-titles/run.ts +++ b/evals/thread-titles/run.ts @@ -6,6 +6,7 @@ import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { CodexSettings, ProviderInstanceId } from "@t3tools/contracts"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Duration from "effect/Duration"; @@ -153,6 +154,7 @@ await Effect.runPromise( ProcessRunner.layer, SourceControlProviderRegistry.layer.pipe( Layer.provide(SourceControlBuiltInDrivers.layer), + Layer.provide(FeatureFlags.layer), Layer.provide(ServerSettings.layerTest()), Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer))), Layer.provide(GitVcsDriver.layer), diff --git a/infra/relay/src/agentActivity/ApnsClient.test.ts b/infra/relay/src/agentActivity/ApnsClient.test.ts index 81e76b0391aae..f06c751982710 100644 --- a/infra/relay/src/agentActivity/ApnsClient.test.ts +++ b/infra/relay/src/agentActivity/ApnsClient.test.ts @@ -151,7 +151,7 @@ describe("ApnsClient", () => { const environmentId = "é".repeat(191); const threadId = "t".repeat(512); const notification = sanitizeApnsNotificationPayload({ - title: "界".repeat(120), + title: "😀".repeat(120), body: "界".repeat(120), environmentId, threadId, @@ -159,6 +159,8 @@ describe("ApnsClient", () => { }); const request = apns.makePushNotificationRequest({ token: "push-token", notification }); + expect(notification.title).toBe(`${"😀".repeat(58)}...`); + expect( new TextEncoder().encode(JSON.stringify(request.payload)).byteLength, ).toBeLessThanOrEqual(4096); diff --git a/infra/relay/src/agentActivity/agentActivityPayloads.ts b/infra/relay/src/agentActivity/agentActivityPayloads.ts index 4195c81171803..2dd8be5870b9b 100644 --- a/infra/relay/src/agentActivity/agentActivityPayloads.ts +++ b/infra/relay/src/agentActivity/agentActivityPayloads.ts @@ -52,7 +52,12 @@ export function truncateText(value: string, maxLength: number): string { if (trimmed.length <= maxLength) { return trimmed; } - return trimmed.slice(0, maxLength - 3).trimEnd() + "..."; + return ( + trimmed + .slice(0, maxLength - 3) + .replace(/[\uD800-\uDBFF]$/, "") + .trimEnd() + "..." + ); } function sanitizeDeepLink(value: string): string { diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index fee70319c71de..92fad6b57ac9d 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -654,6 +654,10 @@ "./provider-instance-ids": { "types": "./src/providerInstanceIds.ts", "default": "./src/providerInstanceIds.ts" + }, + "./pull-request-references": { + "types": "./src/pullRequestReferences.ts", + "default": "./src/pullRequestReferences.ts" } }, "scripts": { @@ -680,16 +684,16 @@ "effect": "catalog:", "gt-i18n": "1.0.40", "jszip": "3.10.1", - "remark-gfm": "catalog:", - "remark-parse": "catalog:", "three": "0.180.0", - "unbash": "^5.0.0", - "unified": "catalog:" + "unbash": "^5.0.0" }, "devDependencies": { "@effect/vitest": "catalog:", "@types/mdast": "^4.0.4", "@types/three": "0.180.0", + "remark-gfm": "catalog:", + "remark-parse": "catalog:", + "unified": "catalog:", "vite-plus": "catalog:" } } diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index 66909fad1f054..661dfe1a94cae 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -49,6 +49,17 @@ describe("resolveIssueLinkTarget", () => { expect(target?.ref).toMatchObject({ projectId: "fork", scope: "me/web", key: "3" }); }); + it("uses the current repository identity after a project changes repositories", () => { + const url = "https://github.com/acme/api/issues/7"; + const original = project("p1", "acme/api"); + const replacement = project("p1", "acme/mobile"); + const lender = project("p3", "acme/web"); + expect(resolveIssueLinkTarget({ url, projects: [lender, original] })?.ref.projectId).toBe("p1"); + expect(resolveIssueLinkTarget({ url, projects: [lender, replacement] })?.ref.projectId).toBe( + "p3", + ); + }); + it("prefers the project bound to the link's own port over one on the bare hostname", () => { const enterprise = (id: string, host: string) => ({ diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index 0b442d18c92b5..db06b1b0a218f 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -3,6 +3,7 @@ import { issueTrackerBindingScopes, type IssueRef, type IssueTrackerConnectionList, + type RepositoryIdentity, } from "@t3tools/contracts"; import { LINEAR_HOST, @@ -15,11 +16,22 @@ import type { EnvironmentProject } from "./state/shell.ts"; type LinkProject = Pick; +const issueBindingsByRepository = new WeakMap< + RepositoryIdentity, + ReturnType +>(); + /** The hosts and scopes a project's git-host tracker is bound to, the way the server resolves them. */ function projectIssueBindings(project: LinkProject) { - return sourceControlClients - .issueBindings(project.repositoryIdentity) + const identity = project.repositoryIdentity; + if (identity == null) return []; + const cached = issueBindingsByRepository.get(identity); + if (cached !== undefined) return cached; + const bindings = sourceControlClients + .issueBindings(identity) .map((binding) => ({ ...binding, scope: binding.scope.toLowerCase() })); + issueBindingsByRepository.set(identity, bindings); + return bindings; } function linkAuthority(url: string): string | null { diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 8b2d4e105e5b1..2004f514df4a4 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -20,7 +20,7 @@ import { LINKED_THREAD_RETRY_MS, type LinkedThreadView, } from "./linkedThread.ts"; -import { v2Now, v2Projection } from "./state/orchestrationV2TestFixtures.ts"; +import { v2MessageRow, v2Now, v2Projection } from "./state/orchestrationV2TestFixtures.ts"; const snapshot = ( snapshotSequence: number, @@ -163,6 +163,83 @@ it.effect("loads the turns before a snapshot's window once per request", () => }).pipe(Effect.scoped), ); +it.effect("brings back the turns a closed view had loaded when it opens again", () => + Effect.gen(function* () { + const older = v2MessageRow("Older", 1); + const recent = v2MessageRow("Recent", 2); + const latest = v2MessageRow("Latest", 3); + const window = ( + snapshotSequence: number, + historyCursor: string, + row: typeof recent, + ): OrchestrationV2ThreadStreamItem => ({ + kind: "snapshot", + snapshotSequence, + projection: { ...v2Projection, turnItems: [row.item], visibleTurnItems: [row] }, + historyCursor, + hasMoreHistory: true, + }); + const pages: Record> = { + "before-recent": { items: [older], nextCursor: "before-older" }, + "before-latest": { items: [recent], nextCursor: "before-recent" }, + }; + const asked: string[] = []; + const follow = ( + items: ReadonlyArray, + previous: LinkedThreadView | null, + ) => + Effect.gen(function* () { + const views = yield* Queue.unbounded(); + yield* followLinkedThread({ + items: Stream.fromIterable(items).pipe(Stream.concat(Stream.never)), + historyPage: (cursor) => + Effect.sync(() => { + asked.push(cursor); + return { ...pages[cursor]!, snapshotSequence: 3, hasMoreHistory: true }; + }), + previous, + }).pipe( + Stream.runForEach((view) => Queue.offer(views, view)), + Effect.forkScoped, + ); + return views; + }); + const settled = Effect.fnUntraced(function* (views: Queue.Queue) { + let view = yield* Queue.take(views); + while (view.history.loading) view = yield* Queue.take(views); + return view; + }); + const rows = (view: LinkedThreadView) => + view.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId); + + const first = yield* follow([window(1, "before-recent", recent), retitled(2, "Renamed")], null); + (yield* Queue.take(first)).loadEarlier(); + yield* Queue.take(first); // Loading. + yield* Queue.take(first); // The earlier page. + const closed = yield* Queue.take(first); + expect([rows(closed), closed.thread.sequence]).toEqual([ + [older.sourceItemId, recent.sourceItemId], + 2, + ]); + + // Nothing changed while the view was closed: the rows it held are shown as they were. + const same = yield* settled(yield* follow([window(2, "before-recent", recent)], closed)); + expect([rows(same), same.thread.historyCursor]).toEqual([ + [older.sourceItemId, recent.sourceItemId], + "before-older", + ]); + expect(asked).toEqual(["before-recent"]); + + // The thread moved on: pages are read again until the oldest row it showed is back. + const moved = yield* settled(yield* follow([window(3, "before-latest", latest)], closed)); + expect([rows(moved), moved.thread.historyCursor]).toEqual([ + [older.sourceItemId, recent.sourceItemId, latest.sourceItemId], + "before-older", + ]); + expect(asked).toEqual(["before-recent", "before-latest", "before-recent"]); + }).pipe(Effect.scoped), +); + describe("connectLinkedEnvironment", () => { const lan = "http://192.168.1.20:3773"; const tailnet = "https://vm.tail.ts.net"; diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 15364cddf54ea..69b179e08f671 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -1,5 +1,6 @@ import type { EnvironmentId, + OrchestrationV2ProjectedTurnItem, OrchestrationV2ThreadHistoryPage, OrchestrationV2ThreadProjection, OrchestrationV2ThreadStreamItem, @@ -8,6 +9,7 @@ import type { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Queue from "effect/Queue"; +import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; @@ -20,6 +22,7 @@ import { applyThreadHistoryPage, applyThreadStreamItem, initialThreadStreamState, + prependThreadHistory, type ThreadStreamState, } from "./state/threadStream.ts"; @@ -212,12 +215,38 @@ export function isLinkedThreadWorking(projection: OrchestrationV2ThreadProjectio /** How long a view waits before asking again for a thread whose environment did not answer. */ export const LINKED_THREAD_RETRY_MS = 15_000; +type HistoryAnchor = Pick; + +interface LinkedHistoryWindow { + readonly sequence: number; + readonly cursor: string; +} + +interface LinkedHistoryRequest { + readonly window: LinkedHistoryWindow; + readonly cursor: string; +} + +function includesHistoryAnchor(rows: ReadonlyArray, anchor: HistoryAnchor): boolean { + return rows.some( + (row) => + row.sourceThreadId === anchor.sourceThreadId && row.sourceItemId === anchor.sourceItemId, + ); +} + /** A linked thread as its view holds it: the thread's own stream, reduced as any thread's is. */ export interface LinkedThreadView { readonly thread: ThreadStreamState; /** Why the stream stopped, while the view waits to ask again; the next item clears it. */ readonly error: unknown; readonly history: { readonly loading: boolean; readonly failed: boolean }; + /** Pagination progress survives the temporary view that hides the cursor during reconnect. */ + readonly loadedHistory: { + readonly window: LinkedHistoryWindow; + readonly nextCursor: string | null; + /** The oldest row still to recover, even if a read fails or the view closes during backfill. */ + readonly restoreThrough: HistoryAnchor | null; + } | null; /** Loads the turns before the ones shown. Does nothing while a page loads or none is left. */ readonly loadEarlier: () => void; } @@ -233,7 +262,11 @@ export const keepLinkedThreadView = ( ): LinkedThreadView => next.thread.projection !== null || kept === null || kept.thread.projection === null ? next - : { ...next, thread: { ...kept.thread, historyCursor: null } }; + : { + ...next, + thread: { ...kept.thread, historyCursor: null }, + loadedHistory: kept.loadedHistory, + }; /** * Follows a linked environment's thread for as long as something consumes the result. The thread @@ -244,34 +277,100 @@ export const keepLinkedThreadView = ( export const followLinkedThread = (source: { readonly items: Stream.Stream; readonly historyPage: (cursor: string) => Effect.Effect; + readonly previous?: LinkedThreadView | null; }): Stream.Stream => Stream.unwrap( Effect.gen(function* () { - const requests = yield* Queue.unbounded(); + const requests = yield* Queue.unbounded(); let requested = false; - // Both halves below run one step at a time, so each reads the view the other left. + let previous = source.previous ?? null; + let snapshotWindow: LinkedHistoryWindow | null = null; + const requestPage = (window: LinkedHistoryWindow, cursor: string) => { + requested = true; + Queue.offerUnsafe(requests, { window, cursor }); + }; let view: LinkedThreadView = { thread: initialThreadStreamState, error: null, history: { loading: false, failed: false }, + loadedHistory: null, loadEarlier: () => { - if (requested || view.thread.historyCursor === null) return; - requested = true; - Queue.offerUnsafe(requests, undefined); + const cursor = view.thread.historyCursor; + if (requested || snapshotWindow === null || cursor === null) return; + requestPage(snapshotWindow, cursor); }, }; const show = (patch: Partial) => { view = { ...view, ...patch }; return view; }; - const attempt = (): Stream.Stream => + + const onItem = (item: OrchestrationV2ThreadStreamItem) => { + let thread = applyThreadStreamItem(view.thread, item); + if (item.kind !== "snapshot") return show({ thread, error: null }); + + const kept = view.thread.projection === null ? previous : view; + previous = null; + const loaded = kept?.loadedHistory; + const window = + thread.historyCursor === null + ? null + : { sequence: thread.sequence, cursor: thread.historyCursor }; + let loadedHistory: LinkedThreadView["loadedHistory"] = null; + if (window && kept?.thread.projection && loaded) { + // A live update can advance the revision and move the window without invalidating held rows. + if ( + kept.thread.sequence === window.sequence && + (window.sequence > loaded.window.sequence || window.cursor === loaded.window.cursor) + ) { + thread = prependThreadHistory( + thread, + { + items: kept.thread.projection.visibleTurnItems, + subagents: kept.thread.projection.subagents, + }, + loaded.nextCursor, + ); + loadedHistory = { ...loaded, window }; + } else if (window.sequence > kept.thread.sequence) { + const oldest = loaded.restoreThrough ?? kept.thread.projection.visibleTurnItems[0]; + if (oldest && !includesHistoryAnchor(item.projection.visibleTurnItems, oldest)) { + const { sourceThreadId, sourceItemId } = oldest; + loadedHistory = { + window, + nextCursor: window.cursor, + restoreThrough: { sourceThreadId, sourceItemId }, + }; + } + } + } + + snapshotWindow = window; + requested = false; + if (window && thread.historyCursor !== null && loadedHistory?.restoreThrough) { + requestPage(window, thread.historyCursor); + } else { + Queue.offerUnsafe(requests, null); + } + return show({ + thread, + loadedHistory, + history: { loading: requested, failed: false }, + error: null, + }); + }; + + const attempt = (): Stream.Stream< + | { readonly kind: "item"; readonly item: OrchestrationV2ThreadStreamItem } + | { readonly kind: "unreachable"; readonly error: E }, + E, + R + > => source.items.pipe( - Stream.map((item) => - show({ thread: applyThreadStreamItem(view.thread, item), error: null }), - ), + Stream.map((item) => ({ kind: "item" as const, item })), Stream.catch((error) => isLinkedThreadUnreachable(error) - ? Stream.make(show({ error })).pipe( + ? Stream.make({ kind: "unreachable" as const, error }).pipe( Stream.concat( Stream.unwrap(Effect.sleep(LINKED_THREAD_RETRY_MS).pipe(Effect.map(attempt))), ), @@ -279,38 +378,67 @@ export const followLinkedThread = (source: { : Stream.fail(error), ), ); + const earlier = Stream.fromQueue(requests).pipe( - Stream.flatMap(() => - Stream.suspend(() => { - const cursor = view.thread.historyCursor; - if (cursor === null) { - requested = false; - return Stream.empty; - } - return Stream.make(show({ history: { loading: true, failed: false } })).pipe( - Stream.concat( - Stream.fromEffect( - source.historyPage(cursor).pipe( - Effect.match({ - onSuccess: (page) => - show({ - thread: applyThreadHistoryPage(view.thread, cursor, page), - history: { loading: false, failed: false }, - }), - onFailure: () => show({ history: { loading: false, failed: true } }), - }), - Effect.ensuring( - Effect.sync(() => { - requested = false; - }), + Stream.switchMap((request) => + request === null + ? Stream.empty + : Stream.make({ kind: "loading" as const, request }).pipe( + Stream.concat( + Stream.fromEffect( + source.historyPage(request.cursor).pipe( + Effect.result, + Effect.map((page) => ({ kind: "page" as const, request, page })), ), ), ), ), - ); - }), ), ); - return Stream.merge(attempt(), earlier, { haltStrategy: "left" }); + + // Reduce snapshots, live items and history results in publication order. + return Stream.merge(attempt(), earlier, { haltStrategy: "left" }).pipe( + Stream.filterMap((update) => { + if (update.kind === "item") return Result.succeed(onItem(update.item)); + if (update.kind === "unreachable") return Result.succeed(show({ error: update.error })); + const { window, cursor } = update.request; + if (snapshotWindow !== window || view.thread.historyCursor !== cursor) { + return Result.failVoid; + } + if (update.kind === "loading") { + return view.history.loading + ? Result.failVoid + : Result.succeed(show({ history: { loading: true, failed: false } })); + } + requested = false; + const page = update.page; + if ( + Result.isFailure(page) || + page.success.snapshotSequence < window.sequence || + (page.success.hasMoreHistory && page.success.nextCursor === cursor) + ) { + return Result.succeed(show({ history: { loading: false, failed: true } })); + } + + const thread = applyThreadHistoryPage(view.thread, cursor, page.success); + let restoreThrough = view.loadedHistory?.restoreThrough ?? null; + const nextCursor = thread.historyCursor; + if ( + restoreThrough !== null && + (nextCursor === null || + includesHistoryAnchor(thread.projection?.visibleTurnItems ?? [], restoreThrough)) + ) { + restoreThrough = null; + } + if (restoreThrough !== null && nextCursor !== null) requestPage(window, nextCursor); + return Result.succeed( + show({ + thread, + loadedHistory: { window, nextCursor, restoreThrough }, + history: { loading: requested, failed: false }, + }), + ); + }), + ); }), ); diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index b2535a81123e1..941fdcd9b389e 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -28,6 +28,7 @@ import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as TestClock from "effect/testing/TestClock"; import { RpcClientError } from "effect/rpc"; @@ -45,6 +46,7 @@ import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFix import { archiveThread, interruptThreadTurn, + promoteQueuedRun, revertThreadCheckpoint, resumeThreadQueue, startThreadTurn, @@ -55,6 +57,8 @@ const layerTestRandom = Layer.succeed( SecureRandom.make((size) => new Uint8Array(size)), ); +class Refused extends Schema.TaggedError()("Refused", {}) {} + const TARGET = new PrimaryConnectionTarget({ environmentId: EnvironmentId.make("environment-1"), label: "Test environment", @@ -634,6 +638,121 @@ describe("V2 environment commands", () => { }).pipe(Effect.provide(layerTestRandom)), ); + const turnSends = [ + { + name: "new thread's first message", + method: ORCHESTRATION_V2_WS_METHODS.launchThread, + send: (commandId: CommandId) => + startThreadTurn({ + commandId, + threadId: v2ThreadId, + message: { + messageId: MessageId.make(commandId), + role: "user", + text: "hi", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: ProjectId.make("project-1"), + title: "Thread", + modelSelection: v2Projection.thread.modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-06-20T00:00:00.000Z", + }, + }, + }), + }, + { + name: "queued message sent now", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + resumeThreadQueue({ commandId, threadId: v2ThreadId, runId: RunId.make("queued") }), + }, + { + name: "queued message steered", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + promoteQueuedRun({ + commandId, + threadId: v2ThreadId, + queuedRunId: RunId.make("queued"), + targetRunId: RunId.make("running"), + }), + }, + ] as const; + + const sendFailingFirstAttempt = Effect.fn("TestEnvironmentCommands.sendFailingFirstAttempt")( + function* (turnSend: (typeof turnSends)[number], failure: Effect.Effect) { + const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches: [] }); + const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session)); + const attempts: string[] = []; + const firstAttemptFailed = yield* Deferred.make(); + const healthyMethod = ( + healthySession.client as unknown as Record< + string, + (input: unknown) => Effect.Effect + > + )[turnSend.method]!; + const failingClient = { + ...healthySession.client, + [turnSend.method]: (input: { readonly commandId: CommandId }) => + Effect.gen(function* () { + attempts.push(input.commandId); + if (attempts.length > 1) return yield* healthyMethod(input); + yield* SubscriptionRef.set(supervisor.session, Option.none()); + yield* Deferred.succeed(firstAttemptFailed, undefined); + return yield* failure; + }), + } as unknown as WsRpcProtocolClient; + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + const sendFiber = yield* turnSend + .send(CommandId.make("command-turn-send")) + .pipe( + Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + Effect.forkChild, + ); + yield* Deferred.await(firstAttemptFailed); + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + return { exit: yield* Fiber.await(sendFiber), attempts }; + }, + ); + + it.effect.each(turnSends)("resends a $name lost to a session close", (turnSend) => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSend, + Effect.failCause(Cause.interrupt()), + ); + + expect(attempts).toEqual(["command-turn-send", "command-turn-send"]); + expect(Exit.isSuccess(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + + it.effect("doesn't resend a new thread's first message the server refused", () => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSends[0], + Effect.fail(new Refused()), + ); + + expect(attempts).toEqual(["command-turn-send"]); + expect(Exit.isFailure(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + it.effect("Stop with no run left ends the thread's pull request watches", () => Effect.gen(function* () { const link = { diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index ee17123e8839f..0ea95420460a7 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -315,28 +315,12 @@ const MAX_LOST_TRANSPORT_RESENDS = 2; // alone would leave the send pending forever. const MESSAGE_DISPATCH_TIMEOUT = "60 seconds"; -const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( - command: Extract, - resendAfterSocketLoss: boolean, -) { +const resendAfterSocketLoss = Effect.fn("EnvironmentCommands.resendAfterSocketLoss")(function* < + A, + E, + R, +>(attempt: Effect.Effect) { const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; - const attempt = dispatch(command).pipe( - Effect.timeoutOrElse({ - duration: MESSAGE_DISPATCH_TIMEOUT, - orElse: () => - Effect.fail( - new EnvironmentRpcUnavailableError({ - environmentId: supervisor.target.environmentId, - ...translatableMessage( - msg("{host} did not confirm the message within 60 seconds.", { - host: supervisor.target.label, - }), - ), - }), - ), - }), - ); - if (!resendAfterSocketLoss) return yield* attempt; for (let resends = 0; ; resends += 1) { const attemptSession = yield* SubscriptionRef.get(supervisor.session); const exit = yield* Effect.exit(attempt); @@ -365,6 +349,30 @@ const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(functio } }); +const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( + command: Extract, + resend: boolean, +) { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + const attempt = dispatch(command).pipe( + Effect.timeoutOrElse({ + duration: MESSAGE_DISPATCH_TIMEOUT, + orElse: () => + Effect.fail( + new EnvironmentRpcUnavailableError({ + environmentId: supervisor.target.environmentId, + ...translatableMessage( + msg("{host} did not confirm the message within 60 seconds.", { + host: supervisor.target.label, + }), + ), + }), + ), + }), + ); + return yield* resend ? resendAfterSocketLoss(attempt) : attempt; +}); + const getProjection = (threadId: ThreadId) => request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId }); @@ -784,6 +792,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( input.message.attachments, attachments, ); + const resend = input.resendAfterSocketLoss ?? true; const bootstrap = input.bootstrap?.createThread; const prepareWorktree = input.bootstrap?.prepareWorktree; if (bootstrap !== undefined || prepareWorktree !== undefined) { @@ -815,7 +824,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ? {} : { branch: bootstrap.branch }), }; - return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, { + const launch = request(ORCHESTRATION_V2_WS_METHODS.launchThread, { commandId, creationSource: input.creationSource ?? "web", threadId: input.threadId, @@ -834,10 +843,10 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( attachments, }, }); + return yield* resend ? resendAfterSocketLoss(launch) : launch; } const requestedMode = input.dispatchMode ?? "auto"; - const resendAfterSocketLoss = input.resendAfterSocketLoss ?? true; if (requestedMode === "start") { return yield* dispatchMessage( { @@ -868,7 +877,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(input.freshContext ? { freshContext: true } : {}), dispatchMode: { type: "start_immediately" }, }, - resendAfterSocketLoss, + resend, ); } @@ -899,7 +908,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(requestedMode !== "queue" ? { deliveryIntent: requestedMode } : {}), dispatchMode, }, - resendAfterSocketLoss, + resend, ); }); @@ -1065,9 +1074,9 @@ export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThrea ); if ( checkpoint === undefined || - // Missing snapshots support conversation rewind only. + // Missing or failed snapshots support conversation rewind only. (checkpoint.status !== "ready" && - !(input.restoreFiles === false && checkpoint.status === "missing")) + !(input.restoreFiles === false && checkpoint.status !== "stale")) ) { const target = input.checkpointId === undefined @@ -1156,25 +1165,29 @@ export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")( export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* ( input: ResumeThreadQueueInput, ) { - return yield* dispatch({ - ...(input.runId === undefined - ? { type: "queue.resume" as const } - : { type: "queued-run.start" as const, runId: input.runId }), - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + ...(input.runId === undefined + ? { type: "queue.resume" as const } + : { type: "queued-run.start" as const, runId: input.runId }), + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + }), + ); }); export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* ( input: PromoteQueuedRunInput, ) { - return yield* dispatch({ - type: "queued-message.promote-to-steer", - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - queuedRunId: input.queuedRunId, - targetRunId: input.targetRunId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + type: "queued-message.promote-to-steer", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + queuedRunId: input.queuedRunId, + targetRunId: input.targetRunId, + }), + ); }); export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* ( diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts index d4f19173758ec..7d9d162d76a05 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.test.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts @@ -4,19 +4,39 @@ import remarkParse from "remark-parse"; import { unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; +import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequestMarkdown.ts"; import { changeRequestReferenceAutolinker, resolveChangeRequestMediaUrl, - splitPullRequestBody, - type PullRequestBodySegment, -} from "./pullRequestMarkdown.ts"; +} from "./pullRequestReferences.ts"; + +const definitionParser = unified().use(remarkParse).use(remarkGfm); + +// The finder a client passes: each first definition, joined onto one line out of its quote. +const split = (body: string) => + splitPullRequestBody(body, (markdown) => { + const definitions = new Map(); + const visit = (node: Root | RootContent, quotes: number) => { + if (node.type === "definition" && !definitions.has(node.identifier)) { + const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "gu"); + const source = markdown.slice(node.position?.start.offset, node.position?.end.offset); + definitions.set(node.identifier, source.replace(wrap, " ")); + } + if ("children" in node) { + for (const child of node.children) + visit(child, quotes + (node.type === "blockquote" ? 1 : 0)); + } + }; + visit(definitionParser.parse(markdown), 0); + return [...definitions.values()]; + }); describe("pull request body segmentation", () => { // GitHub writes a dropped image into the body as an `` tag, so a bare attachment link on // its own line is the shape it uses for a video — every one sampled in the wild was one. it("lifts a dropped video out and keeps the prose around it", () => { expect( - splitPullRequestBody( + split( "Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter", ), ).toEqual([ @@ -43,7 +63,7 @@ describe("pull request body segmentation", () => { ? segment.rows.flat().flatMap((cell) => prose(cell.segments)) : [], ); - const runs = prose(splitPullRequestBody(body)); + const runs = prose(split(body)); expect(runs.map((segment) => segment.text)).toEqual([ "- [ ] Before", " - [ ] code\n- [x] After", @@ -59,9 +79,7 @@ describe("pull request body segmentation", () => { it("reads the source out of a video tag, including a multi-line one", () => { expect( - splitPullRequestBody( - '', - ), + split(''), ).toEqual([ { id: "attachment:0", @@ -75,21 +93,21 @@ describe("pull request body segmentation", () => { it("leaves the img tag GitHub writes for a dropped image as markdown", () => { const body = 'image'; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("leaves an ordinary link alone, whether it is bare or written as markdown", () => { const body = "https://example.com/page\n\n[the docs](https://example.com/docs)"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("never lifts a link inside fenced code out of it", () => { const body = "```\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -97,14 +115,14 @@ describe("pull request body segmentation", () => { // GitHub keeps CRLF in a body written in its web editor. it("recognizes fences in a body with CRLF line endings", () => { const body = "```\r\nhttps://example.com/demo.mp4\r\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("closes a CRLF fence, so a video after it still lifts out", () => { const code = '```html\r\n\r\n```'; - expect(splitPullRequestBody(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ + expect(split(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 }, { id: "attachment:1", @@ -117,21 +135,21 @@ describe("pull request body segmentation", () => { it("does not let a different fence marker close an open fence", () => { const body = "```\n~~~\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("keeps a video tag that shares its line with prose as markdown", () => { const body = 'Before after'; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("treats an info-string fence as a nested opener, not a close", () => { const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -139,9 +157,7 @@ describe("pull request body segmentation", () => { it("does not open a fence on a line of inline triple-backtick code", () => { const code = "```\nhttps://example.com/b.png\n```"; expect( - splitPullRequestBody( - `\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`, - ), + split(`\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`), ).toEqual([ { id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 }, { @@ -153,14 +169,14 @@ describe("pull request body segmentation", () => { { id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 }, ]); const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```"; - expect(splitPullRequestBody(multilineSpan)).toEqual([ + expect(split(multilineSpan)).toEqual([ { id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 }, ]); }); it("leaves an indented code line alone even when it is only a video link", () => { const body = " https://example.com/demo.mp4"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -169,14 +185,14 @@ describe("pull request body segmentation", () => { const body = ['( + method: string, + effect: Effect.Effect, + ): Effect.Effect => + effect.pipe( + Effect.timeoutOrElse({ + duration: startupRequestTimeout, + orElse: () => + Effect.fail( + new EffectAcpErrors.AcpTransportError({ + operation: "call-rpc", + method, + detail: `${method} timed out waiting for RPC response`, + cause: undefined, + }), + ), + }), + ); + const runLoggedRequest = ( method: string, payload: unknown, @@ -2297,7 +2318,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const initializeResult = yield* runLoggedRequest( "initialize", initializePayload, - acp.agent.initialize(initializePayload), + withStartupTimeout("initialize", acp.agent.initialize(initializePayload)), ); yield* options.onInitialized?.(initializeResult) ?? Effect.void; return initializeResult; @@ -2445,7 +2466,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( sessionSetupResult = yield* runLoggedRequest( "session/resume", resumePayload, - acp.agent.resumeSession(resumePayload), + withStartupTimeout("session/resume", acp.agent.resumeSession(resumePayload)), ); } else { return yield* new EffectAcpErrors.AcpRequestError({ @@ -2462,7 +2483,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const created = yield* runLoggedRequest( "session/new", createPayload, - acp.agent.createSession(createPayload), + withStartupTimeout("session/new", acp.agent.createSession(createPayload)), ); sessionId = created.sessionId; sessionSetupResult = created; @@ -3061,10 +3082,25 @@ const handleSessionUpdate = ); } const parsed = parseSessionUpdateEvent(params); - if (parsed.modeId) { + const modeId = parsed.modeId; + if (modeId) { yield* Ref.update(modeStateRef, (current) => - current === undefined ? current : updateModeState(current, parsed.modeId!), + current === undefined ? current : updateModeState(current, modeId), ); + // A mode-only update would otherwise leave the mode option showing the old mode. + const configOptions = yield* SubscriptionRef.get(configOptionsRef); + const isStaleMode = (option: (typeof configOptions)[number]) => + option.category === "mode" && option.type === "select" && option.currentValue !== modeId; + if (configOptions.some(isStaleMode)) { + yield* SubscriptionRef.set( + configOptionsRef, + configOptions.map((option) => + option.category === "mode" && option.type === "select" + ? { ...option, currentValue: modeId } + : option, + ), + ); + } } for (const event of parsed.events) { if (event._tag === "ToolCallUpdated") { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index a712d40629e60..21fe311588906 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2305,6 +2305,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const activeSelection = yield* Ref.make(null); const activeInteractionMode = yield* Ref.make(null); + // Mode values configureSession left the agent in; a later difference is the agent's own change. + const configuredModes = yield* Ref.make>(new Map()); + const readModes = Effect.gen(function* () { + const modes = new Map(); + for (const option of yield* runtime.getConfigOptions) { + if ( + option.type === "select" && + (option.category === "mode" || option.category === "collaboration_mode") + ) { + modes.set(option.id, option.currentValue); + } + } + const modeId = (yield* runtime.getModeState)?.currentModeId; + if (modeId !== undefined && !modes.has(ACP_SESSION_MODE_OPTION_ID)) { + modes.set(ACP_SESSION_MODE_OPTION_ID, modeId); + } + return modes; + }); const configuredRuntimeMode = yield* Ref.make< ProviderAdapter.ProviderAdapterV2RuntimePolicy["runtimeMode"] | null >(null); @@ -5792,6 +5810,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const now = yield* DateTime.now; const providerThread: OrchestrationV2ProviderThread = { ...knownProviderThread, + // The settled turn's snapshot is still cached as active; no turn runs now. + ...(context === null && knownProviderThread.status === "active" + ? { status: "idle" as const } + : {}), contextUsage: (yield* Ref.get(contextUsageBySessionId)).get(notification.sessionId) ?? knownProviderThread.contextUsage ?? @@ -8353,6 +8375,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } yield* validateModelSelection(modelSelection); + yield* Ref.set(configuredModes, yield* readModes); yield* Ref.set(configuredRuntimeMode, runtimePolicy.runtimeMode); yield* ( flavor.onSessionConfigurationUpdate?.( @@ -8541,6 +8564,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); }); + // Re-applying the thread's mode would undo a deliberate exit, such as leaving plan mode once + // the plan was approved. Report it instead, so picking the old mode again is a real change. + const reportAgentModeChanges = Effect.fnUntraced(function* (threadId: ThreadId) { + const selection = yield* Ref.get(activeSelection); + if (selection === null || selection.options === undefined) return; + const configured = yield* Ref.get(configuredModes); + const live = yield* readModes; + const changes: Array<{ id: string; from: string; to: string }> = []; + const options = selection.options.map((option) => { + const value = live.get(option.id); + if ( + value === undefined || + typeof option.value !== "string" || + value === configured.get(option.id) || + value === option.value + ) { + return option; + } + changes.push({ id: option.id, from: option.value, to: value }); + return { ...option, value }; + }); + if (changes.length === 0) return; + yield* Ref.set(activeSelection, { ...selection, options }); + yield* Ref.set(configuredModes, live); + yield* emitProviderEvent({ + type: "thread_model_selection.updated", + driver, + threadId, + instanceId: selection.instanceId, + changes, + }); + }); + const finalizeTurn = Effect.fnUntraced(function* ( context: ActiveAcpTurn, status: "completed" | "interrupted" | "failed" | "cancelled", @@ -8636,6 +8692,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }, }); } + yield* reportAgentModeChanges(context.input.threadId); const turn = providerTurnPayload(context, settledStatus, now); yield* Ref.update(providerTurns, (current) => { const updated = new Map(current); diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index 2fda24d4e4fa5..592bf47553494 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -13,6 +13,7 @@ import * as EffectAcpErrors from "effect-acp/errors"; import type * as EffectAcpSchema from "effect-acp/compat"; import * as NodeBuffer from "node:buffer"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { gitForWindowsBash, SpawnExecutableResolution } from "@t3tools/shared/shell"; const MAX_LIVE_TERMINALS = 16; const MAX_UNRELEASED_TERMINALS = 64; @@ -137,15 +138,27 @@ export interface AcpClientTerminalsOptions { function acpTerminalCommand(input: { readonly request: EffectAcpSchema.CreateTerminalRequest; readonly shellCommands?: boolean | undefined; + /** Windows only: the shell source runs here instead of Node's cmd.exe. */ + readonly posixShell: string | undefined; readonly defaultCwd: string; readonly environment: NodeJS.ProcessEnv; readonly forceKillAfter: Duration.Input; }) { - return ChildProcess.make(input.request.command, input.request.args ?? [], { + const options = { cwd: input.request.cwd ?? input.defaultCwd, env: input.environment, - shell: input.shellCommands === true && (input.request.args?.length ?? 0) === 0, forceKillAfter: input.forceKillAfter, + }; + const isShellSource = input.shellCommands === true && (input.request.args?.length ?? 0) === 0; + if (isShellSource && input.posixShell !== undefined) { + // Native tools write in the console code page and output is decoded as UTF-8. The spawner + // hides the window, so each terminal has its own console and the change stays inside it. + const source = `chcp.com 65001 >/dev/null 2>&1\n${input.request.command}`; + return ChildProcess.make(input.posixShell, ["-c", source], options); + } + return ChildProcess.make(input.request.command, input.request.args ?? [], { + ...options, + shell: isShellSource, }); } @@ -170,6 +183,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const forceKillAfter = options.forceKillAfter ?? "5 seconds"; const isWindows = yield* HostProcess.isWindows; + const resolveExecutable = yield* SpawnExecutableResolution; const creationPermit = yield* Semaphore.make(1); const terminals = new Map(); let nextTerminalNumber = 1; @@ -246,6 +260,13 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi Object.entries(sessionEnvironment ?? {}), (request.env ?? []).map((variable) => [variable.name, variable.value] as const), ]); + // Agents that send shell source write bash; Node's shell on Windows is cmd.exe. + const gitExecutable = + isWindows && options.shellCommands === true + ? yield* Effect.promise(async () => resolveExecutable("git", "win32", environment)) + : undefined; + const posixShell = + gitExecutable === undefined ? undefined : gitForWindowsBash(gitExecutable); const terminalScope = yield* Scope.make(); const child = yield* restore( spawner @@ -253,6 +274,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi acpTerminalCommand({ request, shellCommands: options.shellCommands, + posixShell, defaultCwd: options.defaultCwd, environment, forceKillAfter, diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 18ebf74baa1c7..796ec9541d295 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -8,6 +8,7 @@ import { OrchestrationV2AppThread, OrchestrationV2ConversationMessage, OrchestrationV2ExecutionNode, + OrchestrationV2PendingBackgroundTask, OrchestrationV2ProviderSession, OrchestrationV2PlanArtifact, OrchestrationV2ProviderCapabilities, @@ -118,6 +119,17 @@ export const ProviderAdapterV2Event = Schema.Union([ sessionScoped: Schema.optional(Schema.Boolean), retainedNativeTurnIds: Schema.optional(Schema.Array(Schema.String)), }), + /** The agent changed selected options itself, such as leaving plan mode once its plan ran. */ + Schema.Struct({ + type: Schema.Literal("thread_model_selection.updated"), + driver: ProviderDriverKind, + threadId: ThreadId, + instanceId: ProviderInstanceId, + /** Applies only where the thread still holds `from`, so newer user picks win. */ + changes: Schema.Array( + Schema.Struct({ id: Schema.String, from: Schema.String, to: Schema.String }), + ), + }), Schema.Struct({ type: Schema.Literal("provider_turn.updated"), driver: ProviderDriverKind, @@ -165,6 +177,14 @@ export const ProviderAdapterV2Event = Schema.Union([ providerTurnId: ProviderTurnId, pending: Schema.Boolean, }), + // The query process exited under a live session before this work reported back. + Schema.Struct({ + type: Schema.Literal("background_work.lost"), + driver: ProviderDriverKind, + threadId: ThreadId, + providerThreadId: ProviderThreadId, + tasks: Schema.Array(OrchestrationV2PendingBackgroundTask), + }), /** Unpersisted deltas go only to clients showing the row; final output arrives in turn_item.updated. */ Schema.Struct({ type: Schema.Literal("command_output.delta"), @@ -202,6 +222,8 @@ export const ProviderAdapterV2Event = Schema.Union([ failure: Schema.Null, reason: Schema.optional(Schema.String), threadDisposition: Schema.Literals(["reusable", "broken"]), + /** The provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), retainedRuntimeRequestIds: Schema.optional(Schema.Array(RuntimeRequestId)), }), Schema.Struct({ @@ -216,6 +238,8 @@ export const ProviderAdapterV2Event = Schema.Union([ retry: Schema.optional(OrchestrationV2ProviderRetry), retryStartedAt: Schema.optional(Schema.DateTimeUtc), threadDisposition: Schema.Literals(["reusable", "broken"]), + /** The provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), /** Child turns outlive root failure and report their own terminals; otherwise open children settle. */ childTurnsContinue: Schema.optional(Schema.Literal(true)), retainedRuntimeRequestIds: Schema.optional(Schema.Array(RuntimeRequestId)), diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index a29b60d4d25ae..7f4b790927488 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -132,6 +132,16 @@ it("preserves actionable T3 errors wrapped by turn startup", () => { }); assert.equal(makeProviderFailure({ cause: Cause.fail(cause) }).message, error.message); } + const unanswered = { + _tag: "CodexAppServerUnresponsiveError", + message: "Codex app-server did not answer turn/start within 2 minutes.", + }; + assert.equal( + makeProviderFailure({ + cause: Cause.fail({ _tag: "ProviderAdapterEventStreamError", cause: unanswered }), + }).message, + unanswered.message, + ); }); it("names how the provider process exited and the stage it failed in, without its output", () => { diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index cfdb0eb3df9a6..e7d47cdb2175e 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -139,6 +139,8 @@ function curatedCauseMessages(cause: unknown): { case "ClaudeConversationNotFoundError": case "CursorModelUnavailableError": case "CodexGoalObjectiveTooLongError": + case "CodexAppServerUnresponsiveError": + case "CodexAppServerRetiredError": case "ProviderSetupError": case "ProviderAdapterThreadInUseError": case "ProviderCompactionUnsupportedError": diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 5c0a1940d671c..dfa1ac4865269 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -756,6 +756,149 @@ describe("CursorAdapterV2", () => { ), ); + it.effect("marks failed turns as promptDropped only when Cursor did not checkpoint the run", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const workspace = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "cursor-v2-dropped-", + }); + const checkpointedRuns = new Set(); + let sendCalls = 0; + const instanceId = ProviderInstanceId.make("cursor"); + const threadId = ThreadId.make("cursor-dropped-thread"); + const modelSelection = { instanceId, model: "gemini-4-neon" }; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const adapter = yield* makeCursorAdapterV2({ + instanceId, + environment: { HOME: workspace }, + }).pipe( + Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { + assertComplete: Effect.void, + open: () => + Effect.succeed({ + agentId: "native-cursor-dropped", + listMessages: Effect.succeed([]), + close: Effect.void, + runCheckpointed: (runId) => + Effect.succeed(runId !== undefined && checkpointedRuns.has(runId)), + send: () => + Effect.sync(() => { + sendCalls += 1; + const runId = `native-cursor-run-${sendCalls}`; + return { + agentId: "native-cursor-dropped", + runId, + cancel: Effect.void, + wait: Effect.succeed({ + id: runId, + status: "error" as const, + error: { + message: + 'AI Model Not Found Invalid parameters for registry model: "gemini-4-neon"', + }, + }), + }; + }), + }), + textGenerate: () => Effect.die("unused"), + }), + Effect.provide(TestProviderHost.layer({ cwd: workspace })), + ); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("cursor-dropped-session"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const appThread = { + id: threadId, + projectId: ProjectId.make("cursor-dropped-project"), + createdBy: "user" as const, + creationSource: "web" as const, + title: "Cursor dropped prompt", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + branch: null, + worktreePath: null, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }; + const runFailed = (ordinal: number) => + Effect.gen(function* () { + yield* runtime.startTurn({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + runId: RunId.make(`cursor-dropped-run-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`cursor-dropped-attempt-${ordinal}`), + rootNodeId: NodeId.make(`cursor-dropped-root-${ordinal}`), + appThread, + message: { + messageId: MessageId.make(`cursor-dropped-message-${ordinal}`), + createdBy: "user", + creationSource: "web", + text: "Resume", + attachments: [], + }, + }); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + const terminal = events.find((event) => event.type === "turn.terminal"); + const turn = events.findLast( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null, + ); + return { + terminal: terminal?.type === "turn.terminal" ? terminal : undefined, + turn: turn?.type === "provider_turn.updated" ? turn.providerTurn : undefined, + }; + }); + + // Uncheckpointed failure: Cursor never persisted the prompt. + const uncheckpointed = yield* runFailed(1); + assert.equal(uncheckpointed.terminal?.status, "failed"); + assert.equal(uncheckpointed.terminal?.promptDropped, true); + assert.equal(uncheckpointed.turn?.promptDropped, true); + + // Checkpointed failure: Cursor kept the run's prompt in its store. + checkpointedRuns.add("native-cursor-run-2"); + const checkpointed = yield* runFailed(2); + assert.equal(checkpointed.terminal?.status, "failed"); + assert.isUndefined(checkpointed.terminal?.promptDropped); + assert.isUndefined(checkpointed.turn?.promptDropped); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), + ), + ), + ); + it.effect("sends T3 instructions to each Cursor conversation that lacks them", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 7aadadaf9ddd4..b4dd1033c2a9f 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -2510,6 +2510,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( readonly status: OrchestrationV2ProviderTurn["status"]; readonly completedAt: DateTime.Utc | null; readonly tokenUsage?: OrchestrationV2ProviderTurn["tokenUsage"]; + readonly promptDropped?: true; }): OrchestrationV2ProviderTurn => ({ id: input.context.providerTurnId, providerThreadId: input.context.input.providerThread.id, @@ -2525,6 +2526,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( startedAt: input.context.startedAt, completedAt: input.completedAt, ...(input.tokenUsage === undefined ? {} : { tokenUsage: input.tokenUsage }), + ...(input.promptDropped === true ? { promptDropped: true as const } : {}), ...(input.completedAt === null || input.context.usage === undefined ? {} : { @@ -2590,6 +2592,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }).pipe(Effect.as(undefined)), ), ); + // Cursor only keeps a run in conversation history once it saves its first checkpoint. + const promptDropped = + (input.status === "failed" || input.status === "cancelled") && + !input.context.compacted && + input.context.prompt !== undefined && + !(yield* ( + input.context.session.runCheckpointed?.(input.context.run.runId) ?? + Effect.succeed(false) + ).pipe(Effect.orElseSucceed(() => false))); yield* emitProviderEvent({ type: "provider_turn.updated", driver: CursorAgentSdk.CURSOR_PROVIDER, @@ -2597,6 +2608,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( context: input.context, status: input.status, completedAt, + ...(promptDropped ? { promptDropped: true as const } : {}), ...(contextUsage === undefined ? {} : { @@ -2633,6 +2645,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: input.failure ?? makeProviderFailure({ class: "provider_error" }), threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), } : { type: "turn.terminal", @@ -2643,6 +2656,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: null, threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), }, ); if (input.context.runtimeInstructions !== undefined) { diff --git a/packages/provider-muse/src/server/MuseUsageHome.ts b/packages/provider-muse/src/server/MuseUsageHome.ts index 1ced0d2578b01..329dce90c0e7b 100644 --- a/packages/provider-muse/src/server/MuseUsageHome.ts +++ b/packages/provider-muse/src/server/MuseUsageHome.ts @@ -66,7 +66,11 @@ const make = Effect.gen(function* () { if (Option.isSome(settled)) return settled; // Spawn failures surface asynchronously; without this a missing CLI would report as pending. const resolveExecutable = yield* SpawnExecutableResolution; - if (resolveExecutable(binaryPath, yield* HostProcess.Platform, environment) === undefined) { + const platform = yield* HostProcess.Platform; + const resolved = yield* Effect.promise(async () => + resolveExecutable(binaryPath, platform, environment), + ); + if (resolved === undefined) { return Option.some(undefined); } if (awaitRefresh) return Option.some(yield* Cache.get(cache, key)); diff --git a/packages/provider-muse/src/server/sdk.test.ts b/packages/provider-muse/src/server/sdk.test.ts index 45ef56cb63458..6607640751092 100644 --- a/packages/provider-muse/src/server/sdk.test.ts +++ b/packages/provider-muse/src/server/sdk.test.ts @@ -263,7 +263,7 @@ describe("Muse launch", () => { const onWindows = (resolved: string | undefined, env: NodeJS.ProcessEnv = { ComSpec: CMD }) => museLaunch("muse", env).pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => resolved), + Effect.provideService(SpawnExecutableResolution, async () => resolved), ); it.effect("runs an exe directly and a launcher script under cmd.exe on Windows", () => diff --git a/packages/provider-muse/src/server/sdk.ts b/packages/provider-muse/src/server/sdk.ts index 6d6b4d5d51050..aece589b1e188 100644 --- a/packages/provider-muse/src/server/sdk.ts +++ b/packages/provider-muse/src/server/sdk.ts @@ -117,7 +117,8 @@ export const museLaunch = Effect.fn("museLaunch")(function* ( if ((yield* HostProcess.Platform) !== "win32") return { command: binaryPath, args: [] }; const env = environment ?? (yield* HostProcess.Environment); const resolveExecutable = yield* SpawnExecutableResolution; - const resolved = resolveExecutable(binaryPath, "win32", env) ?? binaryPath; + const resolved = + (yield* Effect.promise(async () => resolveExecutable(binaryPath, "win32", env))) ?? binaryPath; if (!/\.(?:cmd|bat)$/i.test(resolved)) return { command: resolved, args: [] }; const systemRoot = windowsEnvironmentValue(env, "SystemRoot"); return { diff --git a/packages/provider-muse/src/server/usage.test.ts b/packages/provider-muse/src/server/usage.test.ts index 3815cfce44321..d02271f44ff04 100644 --- a/packages/provider-muse/src/server/usage.test.ts +++ b/packages/provider-muse/src/server/usage.test.ts @@ -260,7 +260,7 @@ describe("Muse history discovery", () => { expect(create).not.toHaveBeenCalled(); }).pipe( Effect.provide([NodeServices.layer, MuseUsageHome.layer]), - Effect.provideService(SpawnExecutableResolution, () => undefined), + Effect.provideService(SpawnExecutableResolution, async () => undefined), ), ); diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 9e14f8c4ef36b..5cbc012de984d 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -4726,7 +4726,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr if (commands.some((entry) => entry.name === command.name)) { // session.command neither accepts nor returns our ID; record the preceding history boundary. const newest = yield* client.message.list({ sessionID, order: "desc", limit: 1 }); - yield* markBefore(sessionId, newest.data[0]?.id ?? null); + const before = newest.data[0]?.id ?? null; + yield* markBefore(sessionId, before); if (!sending()) return; if (goalCommand?.type === "pause" || goalCommand?.type === "clear") { // OpenCode rejects pausing or clearing a missing goal; Codex treats that as a no-op. @@ -4739,7 +4740,44 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ); return yield* finishControl; } - return yield* client.session.command({ sessionID, ...command }).pipe(Effect.asVoid); + yield* client.session.command({ sessionID, ...command }); + // A command that never prompts the model starts no execution, so no event ends its turn. + const idle = () => state.active === turn && !busy.has(sessionId); + if (!idle()) return; + const active = yield* client.session + .active() + .pipe(Effect.timeout(ACTIVE_CHECK_TIMEOUT), Effect.option); + if (active._tag === "None") { + return yield* Effect.logWarning("Could not check whether an OpenCode command started."); + } + if (sessionId in active.value) return; + // An execution that already ended left history behind; its events may still trail this reply. + const ran = yield* OpenCode2Client.paginate( + { sessionID, order: "desc" as const, limit: 1 }, + client.message.list, + ).pipe( + Stream.takeWhile((message) => message.id !== before), + Stream.filter( + (message) => + message.type === "user" || message.type === "assistant" || message.type === "idle", + ), + Stream.runHead, + Effect.timeout(ACTIVE_CHECK_TIMEOUT), + Effect.option, + ); + if (ran._tag === "None") { + return yield* Effect.logWarning("Could not check whether an OpenCode command ran."); + } + if (ran.value._tag === "Some") return; + return yield* lock.withPermit( + Effect.suspend(() => + idle() + ? endExecution(state, turn, { + status: turn.interrupted ? "interrupted" : "completed", + }) + : Effect.void, + ), + ); } } const mentions = skillMentions(text); diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 019af2a98783f..b3e54117f02ee 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4159,6 +4159,62 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("reports cached input as a share of input in live and completed token usage", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + fake.queueState({ + sessionFile: FAKE_SESSION_FILE, + model: { provider: "anthropic", id: "large", contextWindow: 1_000_000 }, + }); + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + // Pi's message usage counts uncached input, cache reads and cache writes separately. + const usage = { input: 6, cacheRead: 40_101, cacheWrite: 10_561, output: 123 }; + // Session stats total every message in the session, not this turn. + fake.queueStats({ + tokens: { + input: 1_206, + cacheRead: 90_202, + cacheWrite: 60_622, + output: 250, + total: 152_280, + }, + contextUsage: { tokens: 50_791, contextWindow: 1_000_000 }, + }); + yield* fake.emit({ type: "response", command: "prompt", success: true }); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ type: "message_start", message: { role: "assistant" } }); + yield* fake.emit({ + type: "message_update", + usage: { ...usage, totalTokens: 50_791 }, + assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "ok" }, + }); + const live = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined, + ); + assert.deepInclude( + live.type === "provider_turn.updated" ? live.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + yield* fake.emit({ type: "agent_settled" }); + const completed = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.deepInclude( + completed.type === "provider_turn.updated" ? completed.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect.each(["turn window", "full tree"] as const)( "finishes a turn whose %s has a parentId cycle", (cycleIn) => diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index eae7f3eb6c2fa..e7803bbe9c5ee 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -359,6 +359,11 @@ function compactionTitle(status: PiCompactionStatus): string { } } +type PiMessageTokenUsage = Pick< + OrchestrationV2ProviderTurnTokenUsage, + "inputTokens" | "cachedInputTokens" | "outputTokens" +>; + interface ActivePiTurn { readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput; readonly providerTurn: OrchestrationV2ProviderTurn; @@ -377,6 +382,7 @@ interface ActivePiTurn { promptMayBeCommandOnly: boolean; latestCompactionAfterTokens: number | null; lastLiveUsedTokens: number | null; + lastMessageUsage: PiMessageTokenUsage | undefined; settleProbeGeneration: number; /** An extension may start compaction immediately after Pi emits agent_settled. */ settleWhenIdle: boolean; @@ -904,6 +910,25 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return value === undefined ? undefined : Math.max(0, Math.trunc(value)); }; + // Pi counts uncached input, cache reads and cache writes separately; input includes all three. + const piMessageTokenUsage = (usage: unknown): PiMessageTokenUsage => { + const uncachedInputTokens = nonNegativeInteger(usage, "input"); + const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); + const outputTokens = nonNegativeInteger(usage, "output"); + return { + ...(uncachedInputTokens === undefined + ? {} + : { + inputTokens: + uncachedInputTokens + + (cachedInputTokens ?? 0) + + (nonNegativeInteger(usage, "cacheWrite") ?? 0), + }), + ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), + ...(outputTokens === undefined ? {} : { outputTokens }), + }; + }; + const rememberModelContextWindow = (model: unknown): number | null => { const provider = recordString(model, "provider"); const id = recordString(model, "id"); @@ -994,6 +1019,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const tokenUsageFromStats = ( stats: unknown, fallbackUsedTokens: number | null, + messageUsage: PiMessageTokenUsage | undefined, updatedAt: DateTime.Utc, ): OrchestrationV2ProviderTurnTokenUsage | undefined => { const contextUsage = recordField(stats, "contextUsage"); @@ -1002,24 +1028,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( nonNegativeInteger(contextUsage, "tokens") ?? fallbackUsedTokens ?? undefined; if (usedTokens === undefined || maxTokens === undefined || maxTokens === 0) return undefined; - - const totals = recordField(stats, "tokens"); - const inputTokens = nonNegativeInteger(totals, "input"); - const cachedInputTokens = nonNegativeInteger(totals, "cacheRead"); - const outputTokens = nonNegativeInteger(totals, "output"); - return { - usedTokens, - maxTokens, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), - updatedAt: DateTime.formatIso(updatedAt), - }; + // Stats `tokens` are whole-session totals; the breakdown comes from the turn's last message. + return { usedTokens, maxTokens, ...messageUsage, updatedAt: DateTime.formatIso(updatedAt) }; }; - const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) => + const readTokenUsage = (turn: ActivePiTurn, updatedAt: DateTime.Utc) => request({ type: "get_session_stats" }, 2_000).pipe( - Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)), + Effect.map((stats) => + tokenUsageFromStats( + stats, + turn.latestCompactionAfterTokens, + turn.lastMessageUsage, + updatedAt, + ), + ), Effect.orElseSucceed(() => undefined), ); @@ -1030,6 +1052,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (turn: ActivePiTurn, usage: unknown) { const usedTokens = nonNegativeInteger(usage, "totalTokens"); + if (usedTokens !== undefined && usedTokens > 0) { + turn.lastMessageUsage = piMessageTokenUsage(usage); + } if ( usedTokens === undefined || usedTokens === 0 || @@ -1040,9 +1065,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return; } turn.lastLiveUsedTokens = usedTokens; - const inputTokens = nonNegativeInteger(usage, "input"); - const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); - const outputTokens = nonNegativeInteger(usage, "output"); const updatedAt = yield* DateTime.now; yield* emit({ type: "provider_turn.updated", @@ -1053,9 +1075,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( tokenUsage: { usedTokens, maxTokens: contextWindow, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), + ...turn.lastMessageUsage, updatedAt: DateTime.formatIso(updatedAt), }, }, @@ -2075,9 +2095,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } const treeRefs = turn.stopTreeRefs !== undefined ? turn.stopTreeRefs : yield* captureTurnTreeRefs(); - const tokenUsage = readUsage - ? yield* readTokenUsage(turn.latestCompactionAfterTokens, completedAt) - : undefined; + const tokenUsage = readUsage ? yield* readTokenUsage(turn, completedAt) : undefined; const failure = interrupted ? null : (turn.rejectedPromptFailure ?? turn.failure); yield* emit({ type: "provider_turn.updated", @@ -3474,6 +3492,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( compactCommand !== null || (payload?.message.trimStart().startsWith("/") ?? false), latestCompactionAfterTokens: null, lastLiveUsedTokens: null, + lastMessageUsage: undefined, settleProbeGeneration: 0, settleWhenIdle: false, compactionCancelled: false, diff --git a/packages/shared/package.json b/packages/shared/package.json index e0529dbbdefa8..b1ffa038030ef 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -371,6 +371,10 @@ "types": "./src/managedPolicyFile.ts", "import": "./src/managedPolicyFile.ts" }, + "./FeatureFlags": { + "types": "./src/FeatureFlags.ts", + "import": "./src/FeatureFlags.ts" + }, "./HostProcess": { "types": "./src/HostProcess.ts", "import": "./src/HostProcess.ts" @@ -515,6 +519,10 @@ "types": "./src/markdownGithubAlerts.ts", "import": "./src/markdownGithubAlerts.ts" }, + "./markdownHast": { + "types": "./src/markdownHast.ts", + "import": "./src/markdownHast.ts" + }, "./markdownFrontmatter": { "types": "./src/markdownFrontmatter.ts", "import": "./src/markdownFrontmatter.ts" @@ -642,6 +650,18 @@ "./paletteSearchCopy": { "types": "./src/paletteSearchCopy.ts", "import": "./src/paletteSearchCopy.ts" + }, + "./markdownTaskEdits": { + "types": "./src/markdownTaskEdits.ts", + "import": "./src/markdownTaskEdits.ts" + }, + "./threadFindBlockTags": { + "types": "./src/threadFindBlockTags.ts", + "import": "./src/threadFindBlockTags.ts" + }, + "./assistantInsights": { + "types": "./src/assistantInsights.ts", + "import": "./src/assistantInsights.ts" } }, "scripts": { @@ -656,6 +676,7 @@ "ffi-rs": "1.3.2", "get-east-asian-width": "^1.6.0", "gt-i18n": "1.0.40", + "hast-util-sanitize": "^5.0.2", "mdast-util-directive": "catalog:", "mdast-util-to-hast": "^13.2.1", "micromark-extension-directive": "catalog:", @@ -675,8 +696,10 @@ "devDependencies": { "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", + "@types/hast": "^3.0.5", "@types/mdast": "^4.0.4", "@types/node": "catalog:", + "hast-util-to-html": "^9.0.5", "micromark-util-types": "catalog:", "vite-plus": "catalog:" } diff --git a/packages/shared/src/FeatureFlags.test.ts b/packages/shared/src/FeatureFlags.test.ts new file mode 100644 index 0000000000000..7a5962131e35c --- /dev/null +++ b/packages/shared/src/FeatureFlags.test.ts @@ -0,0 +1,31 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import * as FeatureFlags from "./FeatureFlags.ts"; + +it.effect("resolves T3CODE_FEATURE_FLAGS lists", () => + Effect.gen(function* () { + const cases: ReadonlyArray< + readonly [string | undefined, Partial] + > = [ + [undefined, {}], + [" tanstack_source , secret_providers=1 ", { tanstackSource: true, secretProviders: true }], + [ + "tanstack_source=0,github_app_client_id=Iv23=x", + { githubAppClientId: Option.some("Iv23=x") }, + ], + ["tanstack_source,typo_flag", { tanstackSource: true }], + // One bad value turns every flag off rather than failing startup. + ["tanstack_source,secret_providers=maybe", {}], + ]; + for (const [list, expected] of cases) { + assert.deepStrictEqual(yield* FeatureFlags.resolve(list), { + secretProviders: false, + tanstackSource: false, + githubAppClientId: Option.none(), + ...expected, + }); + } + }), +); diff --git a/packages/shared/src/FeatureFlags.ts b/packages/shared/src/FeatureFlags.ts new file mode 100644 index 0000000000000..7cc13e3420a48 --- /dev/null +++ b/packages/shared/src/FeatureFlags.ts @@ -0,0 +1,61 @@ +import * as Config from "effect/Config"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as HostProcess from "./HostProcess.ts"; + +/** + * One comma-separated list, such as `tanstack_source,github_app_client_id=Iv23…`. A bare name + * turns a flag on. Read once when the server starts; changing it takes a restart. + */ +const VARIABLE = "T3CODE_FEATURE_FLAGS"; + +const config = Config.all({ + secretProviders: Config.Boolean("secret_providers").pipe(Config.withDefault(false)), + tanstackSource: Config.Boolean("tanstack_source").pipe(Config.withDefault(false)), + /** The public client ID of the T3 Code for GitHub app; unset turns its sign-in off. */ + githubAppClientId: Config.option(Config.String("github_app_client_id")), +}); + +export type FeatureFlagValues = Config.Success; + +export class FeatureFlags extends Context.Service()( + "@t3tools/shared/FeatureFlags", +) {} + +/** The `name=value` pairs of a flags list, with a bare name read as `true`. */ +function parseList(list: string | undefined): Record { + const record: Record = {}; + for (const entry of (list ?? "").split(",")) { + const separator = entry.indexOf("="); + const name = (separator === -1 ? entry : entry.slice(0, separator)).trim(); + if (name === "") continue; + record[name] = separator === -1 ? "true" : entry.slice(separator + 1).trim(); + } + return record; +} + +const parse = (record: Record) => config.parse(ConfigProvider.fromUnknown(record)); + +export const resolve = Effect.fn("FeatureFlags.resolve")(function* (list: string | undefined) { + return yield* parse(parseList(list)).pipe( + Effect.catch((error) => + Effect.logWarning(`Ignoring invalid ${VARIABLE}; every flag is off.`, error).pipe( + Effect.andThen(parse({})), + ), + ), + ); +}); + +export const layer = Layer.effect( + FeatureFlags, + Effect.flatMap(HostProcess.Environment, (env) => resolve(env[VARIABLE])), +); + +export const layerTest = (values: Partial = {}) => + Layer.effect( + FeatureFlags, + Effect.map(resolve(undefined), (defaults) => ({ ...defaults, ...values })), + ); diff --git a/packages/shared/src/assistantInsights.ts b/packages/shared/src/assistantInsights.ts new file mode 100644 index 0000000000000..60f4ad1df349a --- /dev/null +++ b/packages/shared/src/assistantInsights.ts @@ -0,0 +1,3 @@ +export function shouldPreserveAssistantLineBreaks(text: string): boolean { + return /^★ Insight(?:\s|─)/mu.test(text); +} diff --git a/packages/shared/src/codexArtifactTemplates.ts b/packages/shared/src/codexArtifactTemplates.ts index 08fa5a28e3e58..9308c24d930dd 100644 --- a/packages/shared/src/codexArtifactTemplates.ts +++ b/packages/shared/src/codexArtifactTemplates.ts @@ -133,3 +133,29 @@ export function appendCodexArtifactTemplateUsePrompt( const needsLeadingSpace = draft.length > 0 && !/\s$/.test(draft); return `${draft}${needsLeadingSpace ? " " : ""}${prompt}`; } + +export const CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES = [ + "dataCodexArtifactTemplate", + "dataArtifactKind", + "dataDisplayName", + "dataGalleryKind", + "dataSkillDirectory", + "dataSkillName", +] as const; + +export function artifactTemplateFromHastProperties( + properties: Readonly> | null | undefined, +): CodexArtifactTemplate | null { + if (properties?.dataCodexArtifactTemplate !== "true") return null; + const stringProperty = (name: string) => { + const value = properties[name]; + return typeof value === "string" ? value : undefined; + }; + return resolveCodexArtifactTemplate({ + artifact_kind: stringProperty("dataArtifactKind"), + display_name: stringProperty("dataDisplayName"), + gallery_kind: stringProperty("dataGalleryKind"), + skill_directory: stringProperty("dataSkillDirectory"), + skill_name: stringProperty("dataSkillName"), + }); +} diff --git a/packages/shared/src/codexMarkdownDirectives.ts b/packages/shared/src/codexMarkdownDirectives.ts index 6ff396eddb12a..fecbdb99fe0ac 100644 --- a/packages/shared/src/codexMarkdownDirectives.ts +++ b/packages/shared/src/codexMarkdownDirectives.ts @@ -23,15 +23,6 @@ const CODEX_FILE_CITATION_NAME = "codex-file-citation"; const CODEX_FOLLOW_UP_NAME = "codex-followup"; const CODEX_ARTIFACT_TEMPLATE_NAME = "artifact-template"; -export const CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES = [ - "dataCodexArtifactTemplate", - "dataArtifactKind", - "dataDisplayName", - "dataGalleryKind", - "dataSkillDirectory", - "dataSkillName", -] as const; - interface MarkdownPosition { readonly start: { readonly offset?: number }; readonly end: { readonly offset?: number }; @@ -404,20 +395,3 @@ export function splitCodexArtifactTemplateMarkdown( } return segments; } - -export function artifactTemplateFromHastProperties( - properties: Readonly> | null | undefined, -): CodexArtifactTemplate | null { - if (properties?.dataCodexArtifactTemplate !== "true") return null; - const stringProperty = (name: string) => { - const value = properties[name]; - return typeof value === "string" ? value : undefined; - }; - return resolveCodexArtifactTemplate({ - artifact_kind: stringProperty("dataArtifactKind"), - display_name: stringProperty("dataDisplayName"), - gallery_kind: stringProperty("dataGalleryKind"), - skill_directory: stringProperty("dataSkillDirectory"), - skill_name: stringProperty("dataSkillName"), - }); -} diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts index 0f53299089bfc..5317347aad13b 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -1,8 +1,18 @@ import { describe, expect, it } from "vite-plus/test"; -import { collectComposerInlineTokens, composerMathRanges } from "./composerInlineTokens.ts"; +import { + collectComposerInlineTokens as collectWithoutMath, + type CollectComposerInlineTokensOptions, + composerMathRanges, +} from "./composerInlineTokens.ts"; +import { markdownMathRanges } from "./markdownMath.ts"; import { serializeComposerFileLink } from "./composerTrigger.ts"; +const collectComposerInlineTokens = ( + text: string, + options: CollectComposerInlineTokensOptions = {}, +) => collectWithoutMath(text, { findMath: markdownMathRanges, ...options }); + describe("collectComposerInlineTokens", () => { it("collects file links, mentions, and skills with source ranges", () => { const text = "Use $ui and inspect [Chat.tsx](src/Chat.tsx) with @AGENTS.md please"; @@ -215,8 +225,8 @@ describe("collectComposerInlineTokens", () => { it("still finds a formula after a mention that starts the line", () => { const link = serializeComposerFileLink("app/routes/posts.$postId.tsx"); - expect(composerMathRanges(`${link} sets $x_i$`).map((formula) => formula.source)).toEqual([ - "$x_i$", - ]); + expect( + composerMathRanges(`${link} sets $x_i$`, markdownMathRanges).map((formula) => formula.source), + ).toEqual(["$x_i$"]); }); }); diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index 992a9d08e4774..b11a42b74a945 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -1,4 +1,7 @@ -import { markdownMathRanges } from "./markdownMath.ts"; +/** The formulas a Markdown parser finds in text, as source offsets. */ +export type FindMathRanges = ( + text: string, +) => ReadonlyArray<{ readonly start: number; readonly end: number }>; export type ComposerInlineToken = | { @@ -18,6 +21,8 @@ export type ComposerInlineToken = export interface CollectComposerInlineTokensOptions { readonly preserveTrailingFrom?: ReadonlyArray; + /** Formulas keep their literal tokens; without it, nothing is read as math. */ + readonly findMath?: FindMathRanges; } const SKILL_MENTION_SOURCE = @@ -100,6 +105,7 @@ function collectMentionTokens(text: string): ComposerInlineToken[] { */ export function composerMathRanges( text: string, + findMath: FindMathRanges, mentions: ReadonlyArray = collectMentionTokens(text), ) { let masked = text; @@ -110,7 +116,7 @@ export function composerMathRanges( "x".repeat(mention.end - mention.start) + masked.slice(mention.end); } - return markdownMathRanges(masked).map(({ start, end }) => ({ + return findMath(masked).map(({ start, end }) => ({ start, end, source: text.slice(start, end), @@ -157,7 +163,10 @@ export function collectComposerInlineTokens( // TeX can contain literal skill and file tokens, especially inside \text{}. // They remain formula source rather than becoming composer context chips. // Confirmed trailing file links are masked too, so a kept chip is not read as TeX. - const math = matches.length > 0 ? composerMathRanges(text, matches) : []; + const math = + matches.length > 0 && options.findMath + ? composerMathRanges(text, options.findMath, matches) + : []; return matches .filter( (match) => !math.some((formula) => match.start < formula.end && match.end > formula.start), diff --git a/apps/web/src/markdownGithubAlerts.test.tsx b/packages/shared/src/markdownGithubAlerts.test.ts similarity index 70% rename from apps/web/src/markdownGithubAlerts.test.tsx rename to packages/shared/src/markdownGithubAlerts.test.ts index 0f01e322681a4..31a84b465f91a 100644 --- a/apps/web/src/markdownGithubAlerts.test.tsx +++ b/packages/shared/src/markdownGithubAlerts.test.ts @@ -1,14 +1,21 @@ -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; +import { toHtml } from "hast-util-to-html"; import remarkGfm from "remark-gfm"; +import remarkParse from "remark-parse"; +import remarkRehype from "remark-rehype"; +import { type PluggableList, unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; -import { remarkGithubAlerts } from "@t3tools/shared/markdownGithubAlerts"; +import { remarkGithubAlerts } from "./markdownGithubAlerts.ts"; + +const processor = unified() + .use(remarkParse) + .use([remarkGfm, remarkGithubAlerts] satisfies PluggableList) + .use(remarkRehype, { allowDangerousHtml: true }); function renderMarkdown(markdown: string): string { - return renderToStaticMarkup( - {markdown}, - ); + return toHtml(processor.runSync(processor.parse(markdown), markdown), { + allowDangerousHtml: true, + }); } describe("remarkGithubAlerts", () => { diff --git a/packages/shared/src/markdownHast.ts b/packages/shared/src/markdownHast.ts new file mode 100644 index 0000000000000..23a4b4d72ddd6 --- /dev/null +++ b/packages/shared/src/markdownHast.ts @@ -0,0 +1,211 @@ +import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts"; +import type { Root } from "hast"; +import { defaultSchema, sanitize, type Schema } from "hast-util-sanitize"; + +import { CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES } from "./codexArtifactTemplates.ts"; +import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination } from "./markdownLinks.ts"; +import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts"; + +type MarkdownImageHastNode = { + type?: string; + value?: string; + tagName?: string; + properties?: Record; + children?: MarkdownImageHastNode[]; +}; + +function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] { + return (node.children ?? []).filter( + (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""), + ); +} + +const STANDALONE_IMAGE_BLOCKS = new Set([ + "p", + "div", + "li", + "td", + "th", + "figure", + "center", + "blockquote", +]); + +function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined { + const children = meaningfulHastChildren(node); + if (children.length !== 1) return undefined; + const only = children[0]; + if (only?.type !== "element") return undefined; + if (only.tagName === "img") return only; + return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em" + ? soleImageDescendant(only) + : undefined; +} + +function markStandaloneImages(node: MarkdownImageHastNode) { + if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) { + const image = soleImageDescendant(node); + if (image) image.properties = { ...image.properties, dataStandalone: true }; + } + node.children?.forEach((child) => { + if (child.type === "element") markStandaloneImages(child); + }); +} + +const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i; + +/** + * The renderer resolves an ``'s `src` (workspace files, host media) but never a ``'s + * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves + * onto the `` for the renderer to pick by theme; every source is then dropped. + */ +function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) { + if (!picture.children) return; + const image = picture.children.find((child) => child.tagName === "img"); + for (const source of picture.children) { + if (source.tagName !== "source" || !image) continue; + const media = source.properties?.media; + const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined; + const srcSet = source.properties?.srcSet; + const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet; + // A candidate's URL runs to the first space (a descriptor such as `2x` may follow). + const url = + typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : ""; + const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc"; + // As in a browser, the first source that matches a scheme is the one shown. + if (scheme && url && image.properties?.[key] === undefined) { + // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path. + const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url; + image.properties = { ...image.properties, [key]: value }; + } + } + picture.children = picture.children.filter((child) => child.tagName !== "source"); +} + +export function rehypePreserveImageSourceMeta() { + return (tree: MarkdownImageHastNode) => { + const visit = (node: MarkdownImageHastNode) => { + const src = node.properties?.src; + const title = node.properties?.title; + if (node.type === "element" && node.tagName === "picture") { + moveColorSchemeSourcesToImage(node); + } + if (node.type === "element" && node.tagName === "img") { + node.properties = { + ...node.properties, + ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}), + ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}), + }; + } + node.children?.forEach(visit); + }; + + visit(tree); + markStandaloneImages(tree); + }; +} + +const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"]; + +// The sanitizer compares schemes case-sensitively, so lowercase accepted editor links first. +function normalizeLocalEditorHref(href: string): string { + try { + const url = new URL(href); + return isLocalEditorFileUrl(url) ? url.href : href; + } catch { + // Not an absolute URL; the sanitizer decides. + return href; + } +} + +export function rehypeNormalizeLocalEditorLinks() { + return (tree: MarkdownImageHastNode) => { + const visit = (node: MarkdownImageHastNode) => { + const href = node.properties?.href; + if (node.type === "element" && node.tagName === "a" && typeof href === "string") { + const normalized = normalizeLocalEditorHref(href); + if (normalized !== href) node.properties = { ...node.properties, href: normalized }; + } + node.children?.forEach(visit); + }; + + visit(tree); + }; +} + +export const CHAT_MARKDOWN_SANITIZE_SCHEMA = { + ...defaultSchema, + attributes: { + ...defaultSchema.attributes, + "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"), + // Fence languages plus the two math classes the web chat's math plugin emits. + code: [ + ["className", /^language-./, "math-inline", "math-display"], + "dataCodeMeta", + "dataInlineCode", + ], + blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"], + // Spaces typed at the start of a user's line (keepLeadingWhitespace). + span: [...(defaultSchema.attributes?.span ?? []), "dataLeadingWhitespace"], + div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES], + a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"], + img: [ + ...(defaultSchema.attributes?.img ?? []), + "dataDarkSrc", + "dataLightSrc", + "dataLocalSrc", + "dataMarkdownTitle", + "dataStandalone", + ], + }, + protocols: { + ...defaultSchema.protocols, + href: [ + ...(defaultSchema.protocols?.href ?? []), + "file", + "t3-citation", + "t3-context", + THREAD_LINK_PROTOCOL, + // Scheme only: the renderer's URL transform checks the rest of the link shape. + ...LOCAL_FILE_LINK_SCHEMES, + ], + src: IMAGE_SRC_PROTOCOLS, + dataDarkSrc: IMAGE_SRC_PROTOCOLS, + dataLightSrc: IMAGE_SRC_PROTOCOLS, + }, +} satisfies Schema; + +/** Sanitizes one tree with the chat's schema, as the last rehype plugin does. */ +export const sanitizeChatHast = (tree: Root): Root => + sanitize(tree, CHAT_MARKDOWN_SANITIZE_SCHEMA) as Root; + +export type ChatMarkdownImageProperties = { + readonly src?: unknown; + readonly dataLocalSrc?: unknown; + readonly dataDarkSrc?: unknown; + readonly dataLightSrc?: unknown; +}; + +/** Keep the authored path for file links and normalize Windows separators for classification. */ +export function chatMarkdownImageSource( + properties?: ChatMarkdownImageProperties, + theme?: "dark" | "light", +) { + const themeSrc = + theme === undefined + ? undefined + : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"]; + const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc; + const source = + typeof themeSrc === "string" + ? themeSrc + : typeof localSrc === "string" + ? localSrc + : properties?.src; + if (typeof source !== "string") return null; + const authoredSrc = normalizeMarkdownLinkDestination(source); + return { + authoredSrc, + classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc, + }; +} diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index 0a997aee79eac..80204d903892b 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -174,6 +174,9 @@ describe("extractMarkdownLinkHrefs", () => { ["[".repeat(32_000), []], ["[a]( invalid [b](ok)", [" { expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs); @@ -185,6 +188,9 @@ describe("extractMarkdownLinkHrefs", () => { ["/x/app/(a)/page.tsx", "/x/app/(b)/page.tsx"], ], ['[a](/tmp/a(1).txt "title") after', ["/tmp/a(1).txt"]], + [`[a](a.ts "it's a title") [b](b.ts 'a "quoted" title') [c](ok)`, ["a.ts", "b.ts", "ok"]], + [`[a](a.ts "mixed') [b](b.ts)`, ["b.ts"]], + [`[a](a.ts "it's\n\n[b](lib/a.ts)")`, ["lib/a.ts"]], ["[a](a(b(c))d) [b](ok)", ["a(b(c))d", "ok"]], ["[a](x\\)y) [b](x\\(y)", ["x\\)y", "x\\(y"]], ["[a](unclosed(paren) [b](ok)", ["ok"]], diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 98df3952fb278..e3458f04f3484 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -461,15 +461,18 @@ function markdownRunEndFinder(markdown: string, delimiter: RegExp) { } function markdownLinkTailScanner(markdown: string) { - const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g); - const titleEnd = markdownRunEndFinder(markdown, /["']/g); - const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S/g); + // A blank line ends the paragraph, so no part of a link's tail runs past one. + const whitespaceEnd = markdownRunEndFinder(markdown, /\S|\n[ \t\r]*\n/g); + const doubleQuoteEnd = markdownRunEndFinder(markdown, /"|\n[ \t\r]*\n/g); + const singleQuoteEnd = markdownRunEndFinder(markdown, /'|\n[ \t\r]*\n/g); + const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S|\n[ \t\r]*\n/g); return (start: number) => { const end = whitespaceEnd(start); - if (markdown[end] === ")") return end + 1; - if (end === start || (markdown[end] !== '"' && markdown[end] !== "'")) return null; - const quoteEnd = titleEnd(end + 1); - if (quoteEnd === markdown.length) return null; + const quote = markdown[end]; + if (quote === ")") return end + 1; + if (end === start || (quote !== '"' && quote !== "'")) return null; + const quoteEnd = (quote === '"' ? doubleQuoteEnd : singleQuoteEnd)(end + 1); + if (markdown[quoteEnd] !== quote) return null; const close = titleWhitespaceEnd(quoteEnd + 1); return markdown[close] === ")" ? close + 1 : null; }; @@ -516,41 +519,36 @@ function markdownLinkDestinationScanner(markdown: string) { } } const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart); - if (hrefEnd === null || hrefEnd === hrefStart) return null; + if (hrefEnd === null) return null; const end = bareTail(hrefEnd); return end === null ? null : { hrefStart, hrefEnd, end }; }; } -// The composer escapes brackets in labels (`[\[id\].tsx](...)`), and `\]` does not close one. -function unescapedLabelEnd(markdown: string, start: number): number { - let end = markdown.indexOf("]", start); - while (end !== -1) { - let backslashes = 0; - while (end - backslashes > start && markdown[end - backslashes - 1] === "\\") backslashes += 1; - if (backslashes % 2 === 0) return end; - end = markdown.indexOf("]", end + 1); - } - return -1; -} - +// Labels may nest balanced brackets (`[the [docs] guide](...)`), and the composer escapes them +// (`[\[id\].tsx](...)`), so `\[` and `\]` never count. A blank line ends the paragraph and its labels. export function extractMarkdownLinkHrefs(markdown: string): string[] { const hrefs: string[] = []; const scanDestination = markdownLinkDestinationScanner(markdown); - let cursor = 0; - while (cursor < markdown.length) { - const labelStart = markdown.indexOf("[", cursor); - if (labelStart === -1) break; - const labelEnd = unescapedLabelEnd(markdown, labelStart + 1); - if (labelEnd === -1) break; - - // Skip a failed label once; nested openings share its closing bracket. - cursor = labelEnd + 1; - const destination = scanDestination(cursor); - if (!destination) continue; - cursor = destination.end; - const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); - if (href) hrefs.push(href); + const bracket = /[[\]\\]|\n[ \t\r]*\n/g; + let openBrackets = 0; + for (let match = bracket.exec(markdown); match; match = bracket.exec(markdown)) { + if (match[0] === "\\") { + bracket.lastIndex = match.index + 2; + } else if (match[0].startsWith("\n")) { + openBrackets = 0; + } else if (match[0] === "[") { + openBrackets += 1; + } else if (openBrackets > 0) { + openBrackets -= 1; + const destination = scanDestination(match.index + 1); + if (!destination) continue; + // A link cannot contain a link, so the brackets still open around it become text. + openBrackets = 0; + bracket.lastIndex = destination.end; + const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); + if (href) hrefs.push(href); + } } return hrefs; } @@ -648,3 +646,6 @@ export function absoluteFilePathMatches(text: string): Array<{ index: number; pa } return paths; } + +// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`. +export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/; diff --git a/apps/web/src/markdownListIndentation.test.tsx b/packages/shared/src/markdownListIndentation.test.ts similarity index 72% rename from apps/web/src/markdownListIndentation.test.tsx rename to packages/shared/src/markdownListIndentation.test.ts index 895d22f8bdac6..bcf56845f6cae 100644 --- a/apps/web/src/markdownListIndentation.test.tsx +++ b/packages/shared/src/markdownListIndentation.test.ts @@ -1,16 +1,21 @@ -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; +import { toHtml } from "hast-util-to-html"; import remarkGfm from "remark-gfm"; +import remarkParse from "remark-parse"; +import remarkRehype from "remark-rehype"; +import { type PluggableList, unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; -import { remarkNormalizeListItemIndentation } from "@t3tools/shared/markdownListIndentation"; +import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts"; + +const processor = unified() + .use(remarkParse) + .use([remarkGfm, remarkNormalizeListItemIndentation] satisfies PluggableList) + .use(remarkRehype, { allowDangerousHtml: true }); function renderMarkdown(markdown: string): string { - return renderToStaticMarkup( - - {markdown} - , - ); + return toHtml(processor.runSync(processor.parse(markdown), markdown), { + allowDangerousHtml: true, + }); } describe("remarkNormalizeListItemIndentation", () => { @@ -26,7 +31,7 @@ describe("remarkNormalizeListItemIndentation", () => { expect(html).not.toContain("
    ");
         expect(html).toContain("
  • for (const step of rest.steps) {
  • "); expect(html).toContain("
  • if (step.request.body) {
  • "); - expect(html).toContain("
  • step.request.body = "<redacted>";
  • "); + expect(html).toContain('
  • step.request.body = "";
  • '); }); it("preserves every recovered block separated by blank lines", () => { diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index 53b49a03762a3..6bb022f532942 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -1,4 +1,3 @@ -import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts"; import type { Heading, Link, @@ -15,7 +14,7 @@ import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import { find, html } from "property-information"; import rehypeRaw from "rehype-raw"; -import rehypeSanitize, { defaultSchema } from "rehype-sanitize"; +import rehypeSanitize from "rehype-sanitize"; import remarkBreaks from "remark-breaks"; import remarkGfm from "remark-gfm"; import { remarkGithubAlerts } from "./markdownGithubAlerts.ts"; @@ -25,17 +24,18 @@ import { remarkEnableLeadingWhitespace, remarkKeepLeadingWhitespace, } from "./markdownLeadingWhitespace.ts"; -import { - CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES, - remarkCodexDirectives, -} from "./codexMarkdownDirectives.ts"; -import { - absoluteFilePathMatches, - isWindowsDrivePathHref, - normalizeMarkdownLinkDestination, -} from "./markdownLinks.ts"; +import { remarkCodexDirectives } from "./codexMarkdownDirectives.ts"; +import { absoluteFilePathMatches } from "./markdownLinks.ts"; import { isWindowsAbsolutePath } from "./path.ts"; -import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts"; +import { + CHAT_MARKDOWN_SANITIZE_SCHEMA, + chatMarkdownImageSource, + rehypeNormalizeLocalEditorLinks, + rehypePreserveImageSourceMeta, + type ChatMarkdownImageProperties, +} from "./markdownHast.ts"; + +export { chatMarkdownImageSource, type ChatMarkdownImageProperties }; export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts"; @@ -47,44 +47,6 @@ type MarkdownImageHastNode = { children?: MarkdownImageHastNode[]; }; -function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] { - return (node.children ?? []).filter( - (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""), - ); -} - -const STANDALONE_IMAGE_BLOCKS = new Set([ - "p", - "div", - "li", - "td", - "th", - "figure", - "center", - "blockquote", -]); - -function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined { - const children = meaningfulHastChildren(node); - if (children.length !== 1) return undefined; - const only = children[0]; - if (only?.type !== "element") return undefined; - if (only.tagName === "img") return only; - return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em" - ? soleImageDescendant(only) - : undefined; -} - -function markStandaloneImages(node: MarkdownImageHastNode) { - if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) { - const image = soleImageDescendant(node); - if (image) image.properties = { ...image.properties, dataStandalone: true }; - } - node.children?.forEach((child) => { - if (child.type === "element") markStandaloneImages(child); - }); -} - // Whole tags, attributes, and comments, so closing-anchor text inside them never counts as a tag. const RAW_HTML_TAG_PATTERN = /|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g; @@ -133,121 +95,6 @@ function rehypePreserveBareAnchorPlaceholders() { }; } -const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i; - -/** - * The renderer resolves an ``'s `src` (workspace files, host media) but never a ``'s - * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves - * onto the `` for the renderer to pick by theme; every source is then dropped. - */ -function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) { - if (!picture.children) return; - const image = picture.children.find((child) => child.tagName === "img"); - for (const source of picture.children) { - if (source.tagName !== "source" || !image) continue; - const media = source.properties?.media; - const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined; - const srcSet = source.properties?.srcSet; - const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet; - // A candidate's URL runs to the first space (a descriptor such as `2x` may follow). - const url = - typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : ""; - const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc"; - // As in a browser, the first source that matches a scheme is the one shown. - if (scheme && url && image.properties?.[key] === undefined) { - // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path. - const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url; - image.properties = { ...image.properties, [key]: value }; - } - } - picture.children = picture.children.filter((child) => child.tagName !== "source"); -} - -function rehypePreserveImageSourceMeta() { - return (tree: MarkdownImageHastNode) => { - const visit = (node: MarkdownImageHastNode) => { - const src = node.properties?.src; - const title = node.properties?.title; - if (node.type === "element" && node.tagName === "picture") { - moveColorSchemeSourcesToImage(node); - } - if (node.type === "element" && node.tagName === "img") { - node.properties = { - ...node.properties, - ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}), - ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}), - }; - } - node.children?.forEach(visit); - }; - - visit(tree); - markStandaloneImages(tree); - }; -} - -const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"]; - -// The sanitizer compares schemes case-sensitively, so lowercase accepted editor links first. -function rehypeNormalizeLocalEditorLinks() { - return (tree: MarkdownImageHastNode) => { - const visit = (node: MarkdownImageHastNode) => { - const href = node.properties?.href; - if (node.type === "element" && node.tagName === "a" && typeof href === "string") { - try { - const url = new URL(href); - if (isLocalEditorFileUrl(url)) node.properties = { ...node.properties, href: url.href }; - } catch { - // Not an absolute URL; the sanitizer decides. - } - } - node.children?.forEach(visit); - }; - - visit(tree); - }; -} - -const CHAT_MARKDOWN_SANITIZE_SCHEMA = { - ...defaultSchema, - attributes: { - ...defaultSchema.attributes, - "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"), - // Fence languages plus the two math classes the web chat's math plugin emits. - code: [ - ["className", /^language-./, "math-inline", "math-display"], - "dataCodeMeta", - "dataInlineCode", - ], - blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"], - div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES], - a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"], - img: [ - ...(defaultSchema.attributes?.img ?? []), - "dataDarkSrc", - "dataLightSrc", - "dataLocalSrc", - "dataMarkdownTitle", - "dataStandalone", - ], - }, - protocols: { - ...defaultSchema.protocols, - href: [ - ...(defaultSchema.protocols?.href ?? []), - "file", - "t3-citation", - "t3-context", - THREAD_LINK_PROTOCOL, - // Scheme only: the renderer's URL transform checks the rest of the link shape. - ...LOCAL_FILE_LINK_SCHEMES, - ], - src: IMAGE_SRC_PROTOCOLS, - dataDarkSrc: IMAGE_SRC_PROTOCOLS, - dataLightSrc: IMAGE_SRC_PROTOCOLS, - }, -} satisfies Parameters[0]; - export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [ remarkGfm, remarkEndAutolinksAtScriptPunctuation, @@ -752,10 +599,6 @@ function remarkNormalizeLinksAndTagInlineCode() { }; } -export function shouldPreserveAssistantLineBreaks(text: string): boolean { - return /^★ Insight(?:\s|─)/mu.test(text); -} - export function remarkAssistantInsights(this: Processor) { return (tree: Root, file: { value: unknown }) => { const source = String(file.value); @@ -840,37 +683,6 @@ const imageSourceProcessor = unified() .use(remarkRehype, { allowDangerousHtml: true }) .use(CHAT_MARKDOWN_REHYPE_PLUGINS); -export type ChatMarkdownImageProperties = { - readonly src?: unknown; - readonly dataLocalSrc?: unknown; - readonly dataDarkSrc?: unknown; - readonly dataLightSrc?: unknown; -}; - -/** Keep the authored path for file links and normalize Windows separators for classification. */ -export function chatMarkdownImageSource( - properties?: ChatMarkdownImageProperties, - theme?: "dark" | "light", -) { - const themeSrc = - theme === undefined - ? undefined - : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"]; - const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc; - const source = - typeof themeSrc === "string" - ? themeSrc - : typeof localSrc === "string" - ? localSrc - : properties?.src; - if (typeof source !== "string") return null; - const authoredSrc = normalizeMarkdownLinkDestination(source); - return { - authoredSrc, - classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc, - }; -} - interface ImageSourceNode { readonly type: string; readonly tagName?: string; diff --git a/packages/shared/src/markdownTaskEdits.ts b/packages/shared/src/markdownTaskEdits.ts new file mode 100644 index 0000000000000..2f33428613147 --- /dev/null +++ b/packages/shared/src/markdownTaskEdits.ts @@ -0,0 +1,28 @@ +/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */ +export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null { + const firstLineEnd = markdown.indexOf("\n", listItemStart); + const firstLine = markdown.slice( + listItemStart, + firstLineEnd === -1 ? markdown.length : firstLineEnd, + ); + const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); + if (!match?.[1]) return null; + return listItemStart + firstLine.indexOf(match[1]); +} + +export function setMarkdownTaskChecked( + markdown: string, + markerOffset: number, + checked: boolean, +): string { + if ( + markerOffset < 0 || + markdown[markerOffset] !== "[" || + !/[ xX]/.test(markdown[markerOffset + 1] ?? "") || + markdown[markerOffset + 2] !== "]" + ) { + return markdown; + } + + return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`; +} diff --git a/packages/shared/src/markdownTaskList.test.ts b/packages/shared/src/markdownTaskList.test.ts index 5e00a3926fa54..7f7519ce49ee5 100644 --- a/packages/shared/src/markdownTaskList.test.ts +++ b/packages/shared/src/markdownTaskList.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vite-plus/test"; -import { markdownTaskMarkerOffset, setMarkdownTaskChecked } from "./markdownTaskList.ts"; +import { markdownTaskMarkerOffset } from "./markdownTaskList.ts"; +import { setMarkdownTaskChecked } from "./markdownTaskEdits.ts"; describe("setMarkdownTaskChecked", () => { const markdown = "- [ ] First\n- [x] Second\n"; diff --git a/packages/shared/src/markdownTaskList.ts b/packages/shared/src/markdownTaskList.ts index fb02f757992b9..a4d18895505c6 100644 --- a/packages/shared/src/markdownTaskList.ts +++ b/packages/shared/src/markdownTaskList.ts @@ -3,36 +3,9 @@ import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import { unified } from "unified"; -const parser = unified().use(remarkParse).use(remarkGfm); - -/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */ -export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null { - const firstLineEnd = markdown.indexOf("\n", listItemStart); - const firstLine = markdown.slice( - listItemStart, - firstLineEnd === -1 ? markdown.length : firstLineEnd, - ); - const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); - if (!match?.[1]) return null; - return listItemStart + firstLine.indexOf(match[1]); -} - -export function setMarkdownTaskChecked( - markdown: string, - markerOffset: number, - checked: boolean, -): string { - if ( - markerOffset < 0 || - markdown[markerOffset] !== "[" || - !/[ xX]/.test(markdown[markerOffset + 1] ?? "") || - markdown[markerOffset + 2] !== "]" - ) { - return markdown; - } +import { taskListMarkerOffset } from "./markdownTaskEdits.ts"; - return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`; -} +const parser = unified().use(remarkParse).use(remarkGfm); /** Hard breaks as U+2028, as iOS draws them; soft breaks stay "\n". */ function plainText(node: Nodes): string { diff --git a/packages/shared/src/markdownWindowsPaths.ts b/packages/shared/src/markdownWindowsPaths.ts index c4c04490a2140..d7c827c8dba8c 100644 --- a/packages/shared/src/markdownWindowsPaths.ts +++ b/packages/shared/src/markdownWindowsPaths.ts @@ -1,5 +1,6 @@ import type { Processor } from "unified"; import { decodeString } from "micromark-util-decode-string"; +import { UNFINISHED_DRIVE_PATH } from "./markdownLinks.ts"; import { isWindowsAbsolutePath } from "./path.ts"; interface DestinationCompileContext { @@ -18,9 +19,6 @@ function keepWindowsPathDestination(this: DestinationCompileContext, token: unkn : decoded; } -// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`. -export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/; - interface EscapeCompileContext { readonly stack: ReadonlyArray<{ readonly type: string; diff --git a/packages/shared/src/orchestrationV2ManualContinuation.test.ts b/packages/shared/src/orchestrationV2ManualContinuation.test.ts index 137bf6cd8f205..e7670749f6c5a 100644 --- a/packages/shared/src/orchestrationV2ManualContinuation.test.ts +++ b/packages/shared/src/orchestrationV2ManualContinuation.test.ts @@ -108,4 +108,16 @@ describe("unsentManualContinuationSource", () => { unsentManualContinuationSource(run("c", "a" as RunId), projection([a, b], [], [])), ).toBeUndefined(); }); + + it("treats a turn with promptDropped as unsent", () => { + const source = run("src"); + const a1 = attempt("a1", "src", 1); + const dropped = { ...turn("a1"), promptDropped: true as const }; + expect( + unsentManualContinuationSource( + run("r2", "src" as RunId), + projection([source], [a1], [dropped]), + ), + ).toBe(source); + }); }); diff --git a/packages/shared/src/orchestrationV2ManualContinuation.ts b/packages/shared/src/orchestrationV2ManualContinuation.ts index 3fb6c8d5a1866..ad64b63483e14 100644 --- a/packages/shared/src/orchestrationV2ManualContinuation.ts +++ b/packages/shared/src/orchestrationV2ManualContinuation.ts @@ -1,4 +1,8 @@ -import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { + isDeliveredProviderTurn, + type OrchestrationV2Run, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; export function unsentManualContinuationSource( run: Pick | undefined, @@ -7,7 +11,9 @@ export function unsentManualContinuationSource( let sourceId = run?.manualContinuationOfRunId; if (sourceId === undefined) return undefined; const runs = new Map(projection.runs.map((source) => [source.id, source])); - const acceptedAttempts = new Set(projection.providerTurns.map((turn) => turn.runAttemptId)); + const acceptedAttempts = new Set( + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); const latestAttempt = ( runId: OrchestrationV2Run["id"], matches: (attempt: (typeof projection.attempts)[number]) => boolean, diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 4174dcc364972..8f81723486f55 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -22,7 +22,10 @@ import { pathSetupCommand, CommandAvailability, CommandResolutionCache, + makePathDirectoryListings, + PathDirectoryListings, type CommandAvailabilityChecker, + gitForWindowsBash, isCommandAvailable, listLoginShellCandidates, mergePathEntries, @@ -38,7 +41,6 @@ import { windowsEnvironmentValueCommand, SpawnExecutableResolution, WindowsShellEnvironment, - withPathDirectoryListings, type WindowsShellEnvironmentReader, XcodeGitLocation, } from "./shell.ts"; @@ -414,6 +416,9 @@ describe("readEnvironmentFromWindowsShell", () => { expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]), { encoding: "utf8", timeout: 5000 }, ); + expect(execFile.mock.calls[0]?.[1].at(-1)).toContain( + "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)", + ); }), ); @@ -440,6 +445,21 @@ describe("readEnvironmentFromWindowsShell", () => { }), ); + effectIt.effect.runIf(HostProcess.Platform.defaultValue() === "win32")( + "reads a non-ASCII value from the real shell", + () => + Effect.gen(function* () { + const name = "T3CODE_TEST_NON_ASCII_PATH"; + const value = "C:\\Users\\Jürgen\\Grüße"; + vi.stubEnv(name, value); + try { + expect(yield* readEnvironmentFromWindowsShell([name])).toEqual({ [name]: value }); + } finally { + vi.unstubAllEnvs(); + } + }), + ); + effectIt.effect("omits -NoProfile when loadProfile is enabled", () => Effect.gen(function* () { const execFile = vi.fn< @@ -557,7 +577,9 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ), ).toBe(path.join(directory, "audit-command")); const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("audit-command", "linux", env)).toBe(executable); + expect( + yield* Effect.promise(async () => resolveExecutable("audit-command", "linux", env)), + ).toBe(executable); }), ); @@ -572,7 +594,8 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { stat: (filePath) => Effect.sync(() => { probed.push(filePath); - return { type: "Directory" } as FileSystem.File.Info; + // No mtime, so no listing: every candidate is probed directly. + return { type: "Directory", mtime: Option.none() } as FileSystem.File.Info; }), }), ), @@ -590,7 +613,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { }); // Windows PATH directories can be case-sensitive; preserve both spellings. - expect(probed).toHaveLength(8); + expect(probed.filter((file) => file.includes("definitely-not-installed"))).toHaveLength(8); }), ); @@ -616,7 +639,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ...fs, stat: (filePath) => fs.stat( - filePath === executable || filePath === decoy + [cwd, executable, decoy].includes(filePath) ? filePath : path.join(cwd, "missing"), ), @@ -627,38 +650,117 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { }), ); - it.effect("probes only listed PATH names and relists a directory that changes", () => + // Seconds; the tests below run their clock a minute later, past the window in which a listing is not kept. + const AGED_MTIME = 4_102_444_800; + const afterAgedMtime = TestClock.setTime((AGED_MTIME + 60) * 1000); + + it.effect("reuses PATH listings across lookups until a directory changes", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const first = yield* fs.makeTempDirectoryScoped(); const second = yield* fs.makeTempDirectoryScoped(); yield* fs.writeFileString(path.join(first, "cursor.CMD"), ""); + yield* fs.writeFileString(path.join(first, "MyToolLongName.cmd"), ""); yield* fs.writeFileString(path.join(second, "cursor.EXE"), ""); + yield* fs.utimes(first, AGED_MTIME, AGED_MTIME); + yield* fs.utimes(second, AGED_MTIME, AGED_MTIME); + yield* afterAgedMtime; const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" }; + // Windows resolves an 8.3 alias that a directory listing never names. + const alias = path.join(first, "MYTOOL~1.CMD"); const probed: Array = []; + const listed: Array = []; yield* Effect.gen(function* () { expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD")); expect(yield* isCommandAvailable("absent", { env })).toBe(false); + expect(yield* isCommandAvailable("also-absent", { env })).toBe(false); + expect(yield* resolveCommandPath("MYTOOL~1", { env })).toBe(alias); + expect(listed).toEqual([first, second]); yield* fs.writeFileString(path.join(second, "late.EXE"), ""); - yield* fs.utimes(second, 4_102_444_800, 4_102_444_800); + yield* fs.utimes(second, AGED_MTIME + 30, AGED_MTIME + 30); expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE")); + expect(listed).toEqual([first, second, second]); }).pipe( - withPathDirectoryListings, Effect.provideService(FileSystem.FileSystem, { ...fs, stat: (file) => { if (file !== first && file !== second) probed.push(file); - return fs.stat(file); + return fs.stat(file === alias ? path.join(first, "MyToolLongName.cmd") : file); + }, + readDirectory: (directory, options) => { + listed.push(directory); + return fs.readDirectory(directory, options); }, }), ); - expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]); + expect(probed).toEqual([ + path.join(first, "cursor.CMD"), + path.join(first, "MYTOOL~1.EXE"), + path.join(first, "MYTOOL~1.exe"), + alias, + path.join(second, "late.EXE"), + ]); }).pipe( Effect.provideService(HostProcess.Platform, "win32"), Effect.provideService(CommandResolutionCache, new Map()), + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), ), ); + + it.effect("does not keep the listing of a PATH directory that changed moments ago", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped(); + yield* fs.utimes(directory, AGED_MTIME + 59, AGED_MTIME + 59); + yield* afterAgedMtime; + const env = { PATH: directory, PATHEXT: ".CMD" }; + let listings = 0; + yield* Effect.gen(function* () { + expect(yield* isCommandAvailable("absent", { env })).toBe(false); + expect(yield* isCommandAvailable("also-absent", { env })).toBe(false); + }).pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + readDirectory: (target, options) => { + listings += 1; + return fs.readDirectory(target, options); + }, + }), + ); + expect(listings).toBe(2); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(CommandResolutionCache, new Map()), + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), + ), + ); + + // A POSIX directory joined with win32 separators names nothing, so this needs a Windows host. + it.effect.skipIf(HostProcess.Platform.defaultValue() !== "win32")( + "relists a changed PATH directory in the spawn resolver", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped(); + yield* fs.writeFileString(path.join(directory, "cursor.CMD"), ""); + yield* fs.utimes(directory, 946_684_800, 946_684_800); + const env = { PATH: directory, PATHEXT: ".EXE;.CMD" }; + const resolveExecutable = yield* SpawnExecutableResolution; + expect(yield* Effect.promise(async () => resolveExecutable("cursor", "win32", env))).toBe( + path.join(directory, "cursor.CMD"), + ); + expect( + yield* Effect.promise(async () => resolveExecutable("late", "win32", env)), + ).toBeUndefined(); + yield* fs.writeFileString(path.join(directory, "late.EXE"), ""); + yield* fs.utimes(directory, 946_684_830, 946_684_830); + expect(yield* Effect.promise(async () => resolveExecutable("late", "win32", env))).toBe( + path.join(directory, "late.EXE"), + ); + }), + ); }); describe("runsGitWithoutConsole", () => { @@ -666,6 +768,7 @@ describe("runsGitWithoutConsole", () => { it.each([ [["rev-parse", "--git-path", "index"], true], + [["rev-parse", "--git-common-dir", "--show-toplevel"], true], [ [ "rev-parse", @@ -757,6 +860,24 @@ describe("preferGitForWindowsBinary", () => { }); }); +describe("gitForWindowsBash", () => { + const bash = "C:\\Program Files\\Git\\bin\\bash.exe"; + const isBash = (filePath: string) => filePath === bash; + + it.each([ + "C:\\Program Files\\Git\\cmd\\git.exe", + "C:\\Program Files\\Git\\bin\\git.exe", + "C:\\Program Files\\Git\\mingw64\\bin\\git.exe", + ])("finds Git Bash from %s", (git) => { + expect(gitForWindowsBash(git, isBash)).toBe(bash); + }); + + it("finds nothing without a Git for Windows bash", () => { + expect(gitForWindowsBash("C:\\Users\\me\\scoop\\shims\\git.exe", isBash)).toBeUndefined(); + expect(gitForWindowsBash("C:\\Program Files\\Git\\cmd\\gitk.exe", () => true)).toBeUndefined(); + }); +}); + // Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`. const NPM_OPENCODE_SHIM = [ "@ECHO off", @@ -862,6 +983,73 @@ describe("npmShimExecutable", () => { }); effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { + it.effect("yields while discovering a Windows executable", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const executable = path.join(directory, "tool.EXE"); + yield* fs.writeFileString(executable, ""); + let settled = false; + const pending = Promise.resolve( + SpawnExecutableResolution.defaultValue()(executable, "win32", { PATHEXT: ".EXE;.CMD" }), + ).then((value) => { + settled = true; + return value; + }); + try { + yield* Effect.promise(() => Promise.resolve()); + expect(settled).toBe(false); + } finally { + expect(yield* Effect.promise(() => pending)).toBe(executable); + } + }), + ), + ); + + it.effect("preserves PATH and PATHEXT order and discovers executables after a miss", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const fixture = NodePath.join(directory, "tool.EXE"); + yield* fs.writeFileString(fixture, ""); + const stat = yield* Effect.promise(() => NodeFS.promises.stat(fixture)); + const files = new Set(); + using _stat = vi.spyOn(NodeFS.promises, "stat").mockImplementation(async (candidate) => { + if (!files.has(String(candidate))) throw new Error("not found"); + return stat; + }); + const lookup = resolveSpawnCommand("tool", ["status"], { + env: { PATH: "C:\\first;C:\\later", PATHEXT: ".EXE;.CMD" }, + }); + expect((yield* lookup).command).toBe("tool"); + files.add("C:\\first\\tool.CMD"); + files.add("C:\\first\\tool.EXE"); + files.add("C:\\later\\tool.EXE"); + expect(yield* lookup).toEqual({ + command: "C:\\first\\tool.EXE", + args: ["status"], + shell: false, + }); + files.delete("C:\\first\\tool.EXE"); + expect((yield* lookup).command).toBe("C:\\first\\tool.EXE"); + expect( + yield* Effect.promise(async () => + SpawnExecutableResolution.defaultValue()("tool", "win32", { + PATH: "C:\\first;C:\\later", + PATHEXT: ".EXE;.CMD", + }), + ), + ).toBe("C:\\first\\tool.CMD"); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(CommandResolutionCache, new Map()), + ), + ), + ); + it.effect("runs Windows executables directly without a shell", () => Effect.gen(function* () { const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 82a2bc73feb78..0ba42dc3078d6 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -7,6 +7,7 @@ import * as Cache from "effect/Cache"; import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -74,13 +75,13 @@ export type SpawnExecutableResolver = ( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -) => string | undefined; +) => string | undefined | Promise; -function resolveSpawnExecutableWithNode( +async function resolveSpawnExecutableWithNode( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -): string | undefined { +): Promise { const path = platform === "win32" ? NodePath.win32 : NodePath.posix; const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : []; const candidates = resolveCommandCandidates( @@ -89,28 +90,37 @@ function resolveSpawnExecutableWithNode( windowsPathExtensions, path.extname, ); - const isExecutable = (candidate: string) => { + const isExecutable = async (candidate: string) => { try { - if (!NodeFS.statSync(candidate).isFile()) return false; + if (!(await NodeFS.promises.stat(candidate)).isFile()) return false; if (platform === "win32") { return windowsPathExtensions.includes(path.extname(candidate).toUpperCase()); } - return canExecuteFile(candidate); + await NodeFS.promises.access(candidate, NodeFS.constants.X_OK); + return true; } catch { return false; } }; if (command.includes("/") || command.includes("\\")) { - return candidates.find(isExecutable); + for (const candidate of candidates) { + if (await isExecutable(candidate)) return candidate; + } + return undefined; } for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) { const normalizedPathEntry = normalizePathEntry(pathEntry, platform); if (normalizedPathEntry.length === 0) continue; + const names = + platform === "win32" + ? await listResolverPathDirectory(normalizedPathEntry, path.isAbsolute) + : undefined; for (const candidate of candidates) { + if (isAbsentFromListing(names, candidate)) continue; const candidatePath = path.join(normalizedPathEntry, candidate); - if (isExecutable(candidatePath)) return candidatePath; + if (await isExecutable(candidatePath)) return candidatePath; } } return undefined; @@ -295,6 +305,8 @@ export function windowsEnvironmentValueCommand(name: string): string { function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray): string { return [ "$ErrorActionPreference = 'Stop'", + // Redirected PowerShell output uses the console code page, which mangles non-ASCII paths. + "try { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch {}", ...names.flatMap((name) => { if (!SHELL_ENV_NAME_PATTERN.test(name)) { throw new Error(`Unsupported environment variable name: ${name}`); @@ -576,7 +588,38 @@ export const CommandResolutionCache = Context.Reference | undefined; + readonly reusable: boolean; +} + +const PATH_DIRECTORY_LISTINGS_MAX_ENTRIES = 1024; +// A directory changed within a coarse filesystem's timestamp step (FAT: 2 s) can change again +// without moving its mtime, so its listing serves the lookups waiting on it but is not kept. +const PATH_DIRECTORY_SETTLE_MS = 2_000; +const NO_DIRECTORY_NAMES: ReadonlySet = new Set(); + +// A listing only speaks for names Windows matches by ASCII case folding. It omits 8.3 aliases +// (`~`), Windows trims a trailing dot, and other characters fold differently than in JS. +const LISTED_NAME_PATTERN = /^[\w.+-]*[\w+-]$/; + +function isAbsentFromListing(names: ReadonlySet | undefined, candidate: string): boolean { + return ( + names !== undefined && + LISTED_NAME_PATTERN.test(candidate) && + !names.has(candidate.toLowerCase()) + ); +} + +// The listing must start after the mtime's timestamp step has passed, and a relative entry +// names another directory once the working directory changes. +function isReusableListing( + directory: string, + modified: number, + listedAtMs: number, + isAbsolute: (path: string) => boolean, +): boolean { + return isAbsolute(directory) && listedAtMs - modified >= PATH_DIRECTORY_SETTLE_MS; } const directoryMtime = (directory: string) => @@ -590,29 +633,77 @@ const directoryMtime = (directory: string) => // Timestamp before reading so concurrent additions change the next mtime check; missing listings fall back to direct probes. const listPathDirectory = Effect.fnUntraced(function* ( directory: string, -): Effect.fn.Return { +): Effect.fn.Return { + const path = yield* Path.Path; const modified = yield* directoryMtime(directory); - if (modified == null) return { modified, names: modified === null ? new Set() : undefined }; + if (modified === null) { + return { modified, names: NO_DIRECTORY_NAMES, reusable: path.isAbsolute(directory) }; + } + if (modified === undefined) return { modified, names: undefined, reusable: false }; + const listedAtMs = yield* Clock.currentTimeMillis; const entries = yield* FileSystem.FileSystem.use((fileSystem) => fileSystem.readDirectory(directory), ).pipe(Effect.orElseSucceed(() => undefined)); - return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) }; + return { + modified, + names: entries && new Set(entries.map((entry) => entry.toLowerCase())), + reusable: + entries !== undefined && isReusableListing(directory, modified, listedAtMs, path.isAbsolute), + }; }); -const PathDirectoryListings = Context.Reference< - Cache.Cache | undefined ->("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined }); - -export const withPathDirectoryListings = - /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */ - Effect.fnUntraced(function* (effect: Effect.Effect) { - const listings = yield* Cache.make({ - capacity: 1024, - lookup: listPathDirectory, - requireServicesAt: "lookup", - }); - return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings)); - }); +export const makePathDirectoryListings = Cache.makeWith(listPathDirectory, { + capacity: PATH_DIRECTORY_LISTINGS_MAX_ENTRIES, + timeToLive: (exit) => + Exit.isSuccess(exit) && exit.value.reusable ? Duration.infinity : Duration.zero, + requireServicesAt: "lookup", +}); + +/** Windows PATH directory listings for the process; each use rechecks the directory's mtime. */ +export const PathDirectoryListings = Context.Reference( + "@t3tools/shared/shell/PathDirectoryListings", + { defaultValue: () => Effect.runSync(makePathDirectoryListings) }, +); + +const resolverPathDirectoryListings = new Map< + string, + { readonly modified: number; readonly names: ReadonlySet } +>(); + +// The spawn resolver's counterpart of `PathDirectoryListings`, under the same rules. +async function listResolverPathDirectory( + directory: string, + isAbsolute: (path: string) => boolean, +): Promise | undefined> { + let modified: number; + try { + const stats = await NodeFS.promises.stat(directory); + if (!stats.isDirectory()) return undefined; + modified = stats.mtimeMs; + } catch (error) { + return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined; + } + const cached = resolverPathDirectoryListings.get(directory); + if (cached?.modified === modified) return cached.names; + resolverPathDirectoryListings.delete(directory); + // This resolver runs outside Effect, so it has no Clock to read. + // @effect-diagnostics-next-line globalDate:off + const listedAtMs = Date.now(); + let names: ReadonlySet; + try { + names = new Set((await NodeFS.promises.readdir(directory)).map((entry) => entry.toLowerCase())); + } catch { + return undefined; + } + if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) { + if (resolverPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { + const oldest = resolverPathDirectoryListings.keys().next().value; + if (oldest !== undefined) resolverPathDirectoryListings.delete(oldest); + } + resolverPathDirectoryListings.set(directory, { modified, names }); + } + return names; +} // An injected resolver or locator may answer differently for the same search, so its // entries are kept apart from every other resolver's. @@ -683,7 +774,8 @@ const findOnPath = Effect.fnUntraced(function* ( pathEntries.push(pathEntry); } - const listings = yield* PathDirectoryListings; + // Only Windows multiplies the candidates per directory; elsewhere a listing saves no probe. + const listings = platform === "win32" ? yield* PathDirectoryListings : undefined; const matches: string[] = []; for (const pathEntry of pathEntries) { let listing = listings && (yield* Cache.get(listings, pathEntry)); @@ -692,7 +784,7 @@ const findOnPath = Effect.fnUntraced(function* ( listing = yield* Cache.get(listings, pathEntry); } for (const candidate of commandCandidates) { - if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue; + if (isAbsentFromListing(listing?.names, candidate)) continue; const candidatePath = path.join(pathEntry, candidate); if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) { matches.push(candidatePath); @@ -813,6 +905,20 @@ export function preferGitForWindowsBinary( return executable; } +/** Git for Windows' bash beside a git.exe from its install, never WSL's System32 bash.exe. */ +export function gitForWindowsBash( + gitExecutable: string, + isFile: (filePath: string) => boolean = isFileSync, +): string | undefined { + const path = NodePath.win32; + if (path.basename(gitExecutable).toLowerCase() !== "git.exe") return undefined; + // git.exe lives in \cmd, \bin, or \\bin. + const launcherRoot = path.dirname(path.dirname(gitExecutable)); + return [launcherRoot, path.dirname(launcherRoot)] + .map((root) => path.join(root, "bin", "bash.exe")) + .find(isFile); +} + // npm cmd-shim format for native executables. const NPM_EXECUTABLE_SHIM_PREFIX = [ "@ECHO off", @@ -900,18 +1006,21 @@ const resolveMacosGit = Effect.fnUntraced(function* ( const nowNanos = yield* Clock.currentTimeNanos; const cached = cache.get(cacheKey); // An Xcode update or removal deletes the binary; look again instead of failing the spawn. - if ( - cached !== undefined && - cached.expiresAtNanos > nowNanos && - (cached.resolvedPath === null || - resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined) - ) { - return cached.resolvedPath ?? "git"; + if (cached !== undefined && cached.expiresAtNanos > nowNanos) { + const cachedPath = cached.resolvedPath; + if ( + cachedPath === null || + (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !== + undefined + ) { + return cachedPath ?? "git"; + } } - const located = - resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; + const onPath = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); + const located = onPath === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; const realGit = - located !== undefined && resolveExecutable(located, "darwin", env) !== undefined + located !== undefined && + (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined ? located : null; cacheCommandResolution(cache, cacheKey, realGit, nowNanos); @@ -929,6 +1038,7 @@ const CONSOLE_FREE_GIT_READS = [ "rev-parse --git-path index", "rev-parse --git-common-dir", "rev-parse --show-toplevel", + "rev-parse --git-common-dir --show-toplevel", "rev-parse --path-format=absolute --git-path index --git-common-dir --show-toplevel", "rev-parse --symbolic-full-name HEAD", "rev-parse --abbrev-ref --symbolic-full-name @{upstream}", @@ -990,10 +1100,8 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( shell: false, }; } - // The scan is synchronous and runs before every child process, so it shares - // the PATH scan cache above. Explicit paths stay uncached for the same reason, - // and so do misses: a failed spawn is how providers report "not installed", - // and that has to clear the moment the binary appears. + // Cache successful PATH lookups. Explicit paths and misses stay uncached so + // newly installed executables are discoverable immediately. const explicitPath = command.includes("/") || command.includes("\\"); const cache = yield* CommandResolutionCache; const cacheKey = [ @@ -1011,7 +1119,7 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( if (cached !== undefined && cached.expiresAtNanos > nowNanos) { resolvedExecutable = cached.resolvedPath; } else { - const found = resolveExecutable(command, platform, env); + const found = yield* Effect.promise(async () => resolveExecutable(command, platform, env)); resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env); if (!explicitPath && resolvedExecutable !== null) { cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos); diff --git a/packages/shared/src/textDirection.ts b/packages/shared/src/textDirection.ts index 0d4a7d88fd837..1efe672108cad 100644 --- a/packages/shared/src/textDirection.ts +++ b/packages/shared/src/textDirection.ts @@ -2,8 +2,8 @@ export type TextDirection = "ltr" | "rtl"; // Hebrew through Arabic Extended-A, their presentation forms, and the // supplementary right-to-left blocks. -const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; -const LETTER = /\p{L}/u; +export const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; +export const LETTER = /\p{L}/u; const SENTENCE_END = /(?<=[.!?؟])(? { expect(collectLimitNotices(presentations)).toEqual(["Host · codex: Could not read limits."]); }); + it("shows the reason an account's limits are unsupported, but not a bare unsupported", () => { + const unsupported = (message?: string) => + provider({ + usageLimits: { + checkedAt: "2026-09-03T11:00:00.000Z", + windows: [], + unavailable: { reason: "unsupported", ...(message ? { message } : {}) }, + }, + }); + const notices = (limited: ServerProvider) => + collectLimitNotices( + new Map([ + [ + EnvironmentId.make("a"), + { entry: { target: { label: "Host" } }, serverConfig: { providers: [limited] } }, + ], + ]), + ); + expect(notices(unsupported("Sign in with Google to see Antigravity limits."))).toEqual([ + "codex: Sign in with Google to see Antigravity limits.", + ]); + expect(notices(unsupported())).toEqual([]); + }); + it("names a hub account whose read failed unless another environment read it", () => { const checkedAt = "2026-09-03T11:00:00.000Z"; const account = { diff --git a/packages/shared/src/usageLimitsCopy.ts b/packages/shared/src/usageLimitsCopy.ts index ea9eafaf55ce1..85f78e0f11f28 100644 --- a/packages/shared/src/usageLimitsCopy.ts +++ b/packages/shared/src/usageLimitsCopy.ts @@ -92,8 +92,15 @@ export function collectLimitNotices( for (const presentation of presentations.values()) { const environmentLabel = presentation.entry.target.label; for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) { - if (provider.usageLimits?.unavailable?.reason === "unsupported") continue; - const notice = provider.usageLimits ? limitsNotice(provider.usageLimits, resolve) : null; + const limits = provider.usageLimits; + // A bare unsupported means the account has no limits; an external usage link shows its message. + if ( + limits?.unavailable?.reason === "unsupported" && + (!limits.unavailable.message || limits.externalUsage) + ) { + continue; + } + const notice = limits ? limitsNotice(limits, resolve) : null; const name = provider.displayName?.trim() || String(provider.driver); if (notice) notices.add(`${label(environmentLabel, name)}: ${notice}`); } diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts index 52c02df69c5df..5c7d4948dfa80 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts @@ -460,7 +460,7 @@ describe("azureCliInvocation", () => { AzureDevOpsCli.azureCliInvocation().pipe( Effect.provideService(HostProcess.Platform, "win32"), Effect.provideService(HostProcess.Environment, { PATH: "C:\\tools" }), - Effect.provideService(SpawnExecutableResolution, () => launcher), + Effect.provideService(SpawnExecutableResolution, async () => launcher), Effect.provideService(AzureCliInstallLocation, () => install), ); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts index e7bc21576267a..8b0a7fdc71e8f 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts @@ -506,7 +506,8 @@ export const azureCliInvocation = Effect.fn("AzureDevOpsCli.invocation")(functio return { command: "az", args: [] } satisfies AzureCliInvocation; } const resolveExecutable = yield* SpawnExecutableResolution; - const launcher = resolveExecutable("az", "win32", yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const launcher = yield* Effect.promise(async () => resolveExecutable("az", "win32", env)); const installFor = yield* AzureCliInstallLocation; const install = launcher === undefined ? undefined : installFor(launcher); // Unrecognized installs (pipx's Scripts\az.exe) keep the launcher and today's decode. diff --git a/packages/source-control-azure-devops/src/shared/definition.test.ts b/packages/source-control-azure-devops/src/shared/definition.test.ts index f18b627a874be..9234546a8a5a8 100644 --- a/packages/source-control-azure-devops/src/shared/definition.test.ts +++ b/packages/source-control-azure-devops/src/shared/definition.test.ts @@ -54,6 +54,18 @@ describe("Azure DevOps change request URLs", () => { } }); + it("takes a pull request URL that leaves the project out as a checkout reference", () => { + for (const url of [ + "https://dev.azure.com/acme/_git/web/pullrequest/17", + "https://acme.visualstudio.com/_git/web/pullrequest/17", + ]) { + expect(definition.isChangeRequestReference(url), url).toBe(true); + } + expect( + definition.isChangeRequestReference("https://dev.azure.com/_git/web/pullrequest/17"), + ).toBe(false); + }); + it.each([ ["ssh.dev.azure.com", "v3/org/project/web"], ["org.visualstudio.com", "defaultcollection/project/_git/web"], diff --git a/packages/source-control-azure-devops/src/shared/definition.ts b/packages/source-control-azure-devops/src/shared/definition.ts index 78f1a4df45a8d..a32ba471a7b48 100644 --- a/packages/source-control-azure-devops/src/shared/definition.ts +++ b/packages/source-control-azure-devops/src/shared/definition.ts @@ -21,7 +21,7 @@ const WORK_ITEM_PATH = /^\/([^/]+\/[^/]+)\/_workitems\/edit\/(\d+)(?:\/|$)/u; const LEGACY_WORK_ITEM_PATH = /^\/([^/]+)\/_workitems\/edit\/(\d+)(?:\/|$)/u; const CHECKOUT_COMMAND = /^az\s+repos\s+pr\s+checkout\s+(.+)$/i; const CHANGE_REQUEST_REFERENCE = - /^https:\/\/(?:dev\.azure\.com\/[^/\s]+\/[^/\s]+|[^/\s]+\.visualstudio\.com\/(?:DefaultCollection\/)?[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i; + /^https:\/\/(?:dev\.azure\.com\/[^/\s]+(?:\/[^/\s]+)?|[^/\s]+\.visualstudio\.com(?:\/DefaultCollection)?(?:\/[^/\s]+)?)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i; // `ssh.dev.azure.com` is the default SSH clone host (git@ssh.dev.azure.com:v3/org/project/repo), // so any `*.dev.azure.com` subdomain is Azure. Legacy hosts stay under `.visualstudio.com`, diff --git a/packages/source-control-core/src/server/IssueTracker.ts b/packages/source-control-core/src/server/IssueTracker.ts index b5894ed806363..eecbde1ed2267 100644 --- a/packages/source-control-core/src/server/IssueTracker.ts +++ b/packages/source-control-core/src/server/IssueTracker.ts @@ -73,6 +73,7 @@ export interface IssueTarget extends IssueScopeTarget { /** An issue as the tracker sees it, before the service attaches project context. */ export type TrackerIssueSummary = Omit; +export type TrackerIssueLink = Pick; export interface TrackerIssuePage { readonly items: ReadonlyArray; @@ -134,6 +135,11 @@ export interface IssueTrackerApi { /** The issue with its first page of conversation, in one read where the tracker allows. */ readonly getIssue: (input: IssueTarget) => Effect.Effect; + /** Confirms an issue exists and names it for a thread link. */ + readonly getIssueLink?: ( + input: IssueTarget, + ) => Effect.Effect; + /** One page of older comments past a cursor `getIssue` or a previous page handed over. */ readonly getComments: ( input: IssueTarget & { readonly cursor: string }, diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index 4db5f263daba1..fffa0feb4014b 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -40,6 +40,7 @@ import type { PullRequestPreview, PullRequestUpdateMethod, PullRequestViewerPermissions, + PullRequestVisibility, SourceControlProviderKind, } from "@t3tools/contracts"; import { SourceControlProviderKind as SourceControlProviderKindSchema } from "@t3tools/contracts"; @@ -108,6 +109,8 @@ export interface ProviderChangeRequest { readonly labels: ReadonlyArray; readonly reviewDecision?: PullRequestReviewDecision | null | undefined; readonly checksState?: PullRequestChecksState | null | undefined; + /** Absent where the host has no private change requests or names no visibility. */ + readonly visibility?: PullRequestVisibility; } export interface ProviderChangeRequestSummary { diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts index 4a6e93ab74f45..ccf23f59b2258 100644 --- a/packages/source-control-core/src/server/SourceControlProvider.ts +++ b/packages/source-control-core/src/server/SourceControlProvider.ts @@ -173,6 +173,18 @@ export class SourceControlProvider extends Context.Service< }) => Effect.Effect; /** True when `createChangeRequest` opens the change request as a draft when asked. */ readonly createsDraftChangeRequests?: boolean; + /** + * The private companion of the checkout's repository, made when it has none. The branch of + * a private change request is pushed to `url` and never to the repository itself, which + * everyone can read. Absent on a host without private change requests. + */ + readonly privateChangeRequestRemote?: (input: { + readonly cwd: string; + readonly context?: SourceControlProviderContext; + }) => Effect.Effect< + { readonly url: string; readonly repository: string }, + SourceControlProviderError + >; readonly listChangeRequests: (input: { readonly cwd: string; readonly context?: SourceControlProviderContext; @@ -202,6 +214,8 @@ export class SourceControlProvider extends Context.Service< readonly bodyFile: string; /** Honored only by a provider with `createsDraftChangeRequests`. */ readonly draft?: boolean; + /** Asked only of a provider with `privateChangeRequestRemote`, which holds the head. */ + readonly private?: boolean; }) => Effect.Effect; readonly getRepositoryCloneUrls: (input: { readonly cwd: string; diff --git a/packages/source-control-core/src/server/discovery.ts b/packages/source-control-core/src/server/discovery.ts index 8b82a16725e08..9d374d52ee1cb 100644 --- a/packages/source-control-core/src/server/discovery.ts +++ b/packages/source-control-core/src/server/discovery.ts @@ -362,7 +362,8 @@ const unavailableInstallHint = Effect.fn("discovery.unavailableInstallHint")(fun return installHint; } const resolveExecutable = yield* SpawnExecutableResolution; - const path = resolveExecutable(executable, platform, yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const path = yield* Effect.promise(async () => resolveExecutable(executable, platform, env)); const architecture = yield* HostProcess.Architecture; return `\`${path ?? executable}\` is built for another CPU architecture, so this ${architecture} machine cannot run it. Remove or replace it. ${installHint}`; }); diff --git a/packages/source-control-core/src/server/driver.ts b/packages/source-control-core/src/server/driver.ts index 7f86d0fff3b9e..fcf737fe2181d 100644 --- a/packages/source-control-core/src/server/driver.ts +++ b/packages/source-control-core/src/server/driver.ts @@ -11,6 +11,7 @@ import type * as FileSystem from "effect/FileSystem"; import type { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; import * as Layer from "effect/Layer"; import type * as Scope from "effect/Scope"; +import type * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import type { SourceControlDefinition } from "../shared/definition.ts"; @@ -80,7 +81,8 @@ export type SourceControlDriverServices = | SourceControlRateLimit.SourceControlRateLimit | HttpClient.HttpClient | FileSystem.FileSystem - | Digest.Digest; + | Digest.Digest + | FeatureFlags.FeatureFlags; export interface SourceControlDriver { readonly kind: SourceControlProviderKind; diff --git a/packages/source-control-definitions/src/registry.ts b/packages/source-control-definitions/src/registry.ts index 46bc9c5b0abd4..90f14961c0d57 100644 --- a/packages/source-control-definitions/src/registry.ts +++ b/packages/source-control-definitions/src/registry.ts @@ -13,42 +13,35 @@ export { canonicalizePullRequestUrl as canonicalizeGitCafePullRequestUrl } from /** * GitHub comes first as the client default for unknown hosts. GitCafe, TanStack Source and Origin * claim URLs first: GitHub and Forgejo accept the same routes on any hostname. TanStack Source is a - * private beta a server may leave out; clients always know it, for a server that has it. + * private beta: every reader knows its URLs, and only a server with its flag on offers the forge. */ -export function makeBuiltInSourceControlDefinitions(options: { readonly tanStackSource: boolean }) { - const tanStackSource = options.tanStackSource ? [TanStackSource.definition] : []; - return makeSourceControlDefinitionRegistry( - [ - GitHub.definition, - CursorOrigin.definition, - GitLab.definition, - GitCafe.definition, - ...tanStackSource, - Forgejo.definition, - Bitbucket.definition, - AzureDevOps.definition, +export const builtInSourceControlDefinitions = makeSourceControlDefinitionRegistry( + [ + GitHub.definition, + CursorOrigin.definition, + GitLab.definition, + GitCafe.definition, + TanStackSource.definition, + Forgejo.definition, + Bitbucket.definition, + AzureDevOps.definition, + ], + { + claimChangeRequestUrlsFirst: [ + GitCafe.definition.kind, + TanStackSource.definition.kind, + CursorOrigin.definition.kind, + AzureDevOps.definition.kind, ], - { - claimChangeRequestUrlsFirst: [ - GitCafe.definition.kind, - ...tanStackSource.map((definition) => definition.kind), - CursorOrigin.definition.kind, - AzureDevOps.definition.kind, - ], - recognizeRemotesIn: [ - GitCafe.definition.kind, - ...tanStackSource.map((definition) => definition.kind), - CursorOrigin.definition.kind, - Forgejo.definition.kind, - GitHub.definition.kind, - GitLab.definition.kind, - AzureDevOps.definition.kind, - Bitbucket.definition.kind, - ], - }, - ); -} - -export const builtInSourceControlDefinitions = makeBuiltInSourceControlDefinitions({ - tanStackSource: true, -}); + recognizeRemotesIn: [ + GitCafe.definition.kind, + TanStackSource.definition.kind, + CursorOrigin.definition.kind, + Forgejo.definition.kind, + GitHub.definition.kind, + GitLab.definition.kind, + AzureDevOps.definition.kind, + Bitbucket.definition.kind, + ], + }, +); diff --git a/packages/source-control-github/scripts/measure-pr-preview.ts b/packages/source-control-github/scripts/measure-pr-preview.ts index 5047dcb281b1e..551245c5600ee 100644 --- a/packages/source-control-github/scripts/measure-pr-preview.ts +++ b/packages/source-control-github/scripts/measure-pr-preview.ts @@ -21,6 +21,7 @@ import * as GitHubAppAccess from "../src/server/GitHubAppAccess.ts"; import * as GitHubPullRequestApi from "../src/server/GitHubPullRequestApi.ts"; import * as GitHubPullRequestProvider from "../src/server/GitHubPullRequestProvider.ts"; import * as GitHubRest from "../src/server/GitHubRest.ts"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; const repeatsFlag = process.argv.find((arg) => arg.startsWith("--repeats=")); const repeats = repeatsFlag === undefined ? 1 : Number(repeatsFlag.slice("--repeats=".length)); @@ -119,6 +120,7 @@ const services = GitHubPullRequestApi.layer.pipe( Layer.provideMerge(SourceControlRateLimit.layer), Layer.provideMerge(measuredHttp), Layer.provideMerge(sourceControlHost), + Layer.provideMerge(FeatureFlags.layer), ); const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); diff --git a/packages/source-control-github/src/server/GitHubAppSignIn.test.ts b/packages/source-control-github/src/server/GitHubAppSignIn.test.ts index 1d8652f06495f..f212386f61942 100644 --- a/packages/source-control-github/src/server/GitHubAppSignIn.test.ts +++ b/packages/source-control-github/src/server/GitHubAppSignIn.test.ts @@ -15,6 +15,7 @@ import { DEFAULT_SERVER_SETTINGS, ServerSettingsError } from "@t3tools/contracts import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; @@ -54,6 +55,8 @@ function harness(options: { readonly settingsWritesFail?: boolean; /** Holds a request open until it completes, to interleave other work with it. */ readonly gate?: (sent: Sent) => Effect.Effect; + /** Defaults to a configured app; null runs without one. */ + readonly clientId?: string | null; }) { const requests: Array = []; const http = HttpClient.make((request) => { @@ -114,6 +117,13 @@ function harness(options: { Layer.provideMerge(SourceControlRateLimit.layer), Layer.provideMerge(options.settingsWritesFail === true ? failingWrites : host), Layer.provide(NodeCrypto.layer), + Layer.provide( + FeatureFlags.layerTest({ + githubAppClientId: Option.fromNullishOr( + options.clientId === undefined ? "Iv-test-client" : options.clientId, + ), + }), + ), Layer.provide(FileSystem.layerNoop({})), Layer.provide(Layer.succeed(HttpClient.HttpClient, http)), ); @@ -157,7 +167,6 @@ const installedOn = (sent: Sent): Reply => beforeEach(() => { for (const name of ["GH_TOKEN", "GITHUB_TOKEN"]) vi.stubEnv(name, ""); - vi.stubEnv(GitHubAppSignIn.CLIENT_ID_VARIABLE, "Iv-test-client"); }); afterEach(() => { vi.unstubAllEnvs(); @@ -267,8 +276,8 @@ describe("GitHubAppSignIn", () => { }); it.effect("does nothing with the app when the server has no client ID", () => { - vi.stubEnv(GitHubAppSignIn.CLIENT_ID_VARIABLE, ""); const { layer, requests } = harness({ + clientId: null, signIns: { "github.com": session() }, handle: () => ({ body: { login: "octocat" } }), }); diff --git a/packages/source-control-github/src/server/GitHubAppSignIn.ts b/packages/source-control-github/src/server/GitHubAppSignIn.ts index 28bde65ed84a8..843e14ce00687 100644 --- a/packages/source-control-github/src/server/GitHubAppSignIn.ts +++ b/packages/source-control-github/src/server/GitHubAppSignIn.ts @@ -19,16 +19,10 @@ import * as Schema from "effect/Schema"; import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; -import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as GitHubClient from "../shared/definition.ts"; -/** - * The public client ID of the T3 Code for GitHub app, which the device flow needs (no secret). - * Unset turns the app sign-in off: no app tokens, no sign-in, nothing for clients to show. - */ -export const CLIENT_ID_VARIABLE = "T3CODE_GITHUB_APP_CLIENT_ID"; - const KIND = SourceControlProviderKind.make("github"); const REQUEST_TIMEOUT = Duration.seconds(15); // Refresh ahead of expiry so a token never lapses between the check and a long request. @@ -107,7 +101,8 @@ const signInError = (host: string, reason: SourceControlSignInFailure, detail: s export const make = Effect.gen(function* () { const sourceControlHost = yield* SourceControlHost.SourceControlHost; const httpClient = yield* HttpClient.HttpClient; - const clientId = (yield* HostProcess.Environment)[CLIENT_ID_VARIABLE]?.trim() ?? ""; + // Unset turns the app sign-in off: no app tokens, no sign-in, nothing for clients to show. + const clientId = Option.getOrElse((yield* FeatureFlags.FeatureFlags).githubAppClientId, () => ""); const enabled = clientId !== ""; const scope = yield* Effect.scope; const refreshLock = yield* Semaphore.make(1); diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts index 3ddcd024f8b35..c944207d639ab 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts @@ -226,6 +226,31 @@ const decodeBody = Schema.decodeUnknownSync( ); describe("GitHubIssueTracker", () => { + it.effect("reads only the fields needed to link a GitHub issue and rejects missing issues", () => + Effect.gen(function* () { + const requests: unknown[] = []; + const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" }; + const url = "https://github.com/acme/web/issues/42"; + const found = yield* tracker((input) => requests.push(input), { + issue: { number: 42, title: "Fixture issue", url }, + }); + expect(yield* found.getIssueLink(target)).toEqual({ + displayKey: "#42", + title: "Fixture issue", + url, + }); + + const missing = yield* tracker((input) => requests.push(input), { issue: null }); + expect(yield* Effect.flip(missing.getIssueLink(target))).toMatchObject({ + reason: "not-found", + }); + expect(requests).toEqual([ + { owner: "acme", name: "web", number: 42 }, + { owner: "acme", name: "web", number: 42 }, + ]); + }), + ); + it.effect("writes an issue lifecycle without mutating pull requests or foreign comments", () => Effect.gen(function* () { const writes: unknown[] = []; @@ -631,6 +656,15 @@ Redact secrets before uploading.`); ["referenced", "acme/web#50"], ["closed", null], ]); + // A cross-reference keeps what a surface needs to open its source, not only a label. + expect(issue.events.find((event) => event.kind === "referenced")).toMatchObject({ + reference: { + repository: "acme/web", + number: 50, + kind: "pull-request", + url: "https://github.com/acme/web/pull/50", + }, + }); }), ); }); diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.ts b/packages/source-control-github/src/server/GitHubIssueTracker.ts index bf1c20abae4e3..b2cb38ff4d413 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.ts @@ -337,6 +337,16 @@ export const make = Effect.gen(function* () { }; }), + getIssueLink: Effect.fn("GitHubIssueTracker.getIssueLink")(function* (input) { + const { owner, name, number } = yield* issue(input, "getIssue"); + const result = yield* client + .IssueLinkMetadata({ owner, name, number }) + .pipe(graphql(input.host, "getIssue")); + const found = result.repository?.issue; + if (found == null) return yield* notFound("getIssue"); + return { displayKey: `#${found.number}`, title: found.title, url: found.url }; + }), + getComments: (input) => issue(input, "getComments").pipe( Effect.flatMap(({ owner, name, number }) => diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index c3cc15097dfd5..9d155cab2b794 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -3949,13 +3949,25 @@ layer("GitHubPullRequestApi.layer", (it) => { name: "build", status: "COMPLETED", conclusion: "SUCCESS", - checkSuite: { workflowRun: { workflow: { name: "linux" } } }, + checkSuite: { + workflowRun: { + event: "push", + runNumber: 1, + workflow: { id: "W_linux", name: "linux" }, + }, + }, }), checkRun({ name: "build", status: "COMPLETED", conclusion: "FAILURE", - checkSuite: { workflowRun: { workflow: { name: "windows" } } }, + checkSuite: { + workflowRun: { + event: "push", + runNumber: 1, + workflow: { id: "W_windows", name: "windows" }, + }, + }, }), ], pageInfo: { hasNextPage: false, endCursor: null }, diff --git a/packages/source-control-github/src/server/GitHubRest.test.ts b/packages/source-control-github/src/server/GitHubRest.test.ts index 460bfbc16d82c..9d82bee19752c 100644 --- a/packages/source-control-github/src/server/GitHubRest.test.ts +++ b/packages/source-control-github/src/server/GitHubRest.test.ts @@ -8,6 +8,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodeOS from "node:os"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- Keep the native socket path within the temporary directory. import * as NodePath from "node:path"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -360,7 +361,10 @@ describe("GitHubRest", () => { const media = yield* instance.fetchMedia!({ url: mediaUrl, headers: {} }); expect(media?.status).toBe(401); expect(directRequests).toEqual([mediaUrl]); - }).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {})); + }).pipe( + Effect.provide(layer.pipe(Layer.provideMerge(FeatureFlags.layerTest()))), + Effect.provideService(HostProcess.Environment, {}), + ); }), ); diff --git a/packages/source-control-github/src/server/gitHubIssueJson.ts b/packages/source-control-github/src/server/gitHubIssueJson.ts index e46ad7ec9e515..59e9b9efd118e 100644 --- a/packages/source-control-github/src/server/gitHubIssueJson.ts +++ b/packages/source-control-github/src/server/gitHubIssueJson.ts @@ -5,7 +5,6 @@ import type { IssueActor, IssueComment, IssueEvent, - IssueEventKind, IssueLabel, IssueLinkedPullRequest, IssueState, @@ -137,7 +136,7 @@ function toLinkedPullRequest( /** The change GitHub recorded, or null for a kind this page has no vocabulary for. */ function toEventFields( raw: TimelineItem, -): { readonly kind: IssueEventKind; readonly detail: string | null } | null { +): Pick | null { switch (raw.__typename) { case "ClosedEvent": return { kind: "closed", detail: null }; @@ -164,15 +163,28 @@ function toEventFields( case "RenamedTitleEvent": return { kind: "renamed", detail: trimmed(raw.currentTitle) }; case "CrossReferencedEvent": { - const repository = trimmed( - raw.source != null && "repository" in raw.source - ? raw.source.repository.nameWithOwner - : null, - ); - const number = raw.source != null && "number" in raw.source ? raw.source.number : 0; + const source = + raw.source.__typename === "PullRequest" || raw.source.__typename === "Issue" + ? raw.source + : null; + const repository = trimmed(source?.repository.nameWithOwner); + const url = trimmed(source?.url); + if (source === null || repository === null || source.number <= 0) { + return { kind: "referenced", detail: null }; + } return { kind: "referenced", - detail: repository === null || number <= 0 ? null : `${repository}#${number}`, + detail: `${repository}#${source.number}`, + ...(url === null + ? {} + : { + reference: { + repository, + number: source.number, + kind: source.__typename === "PullRequest" ? "pull-request" : "issue", + url, + }, + }), }; } default: diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts index 37db822d34386..e049943a3978f 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts @@ -359,10 +359,18 @@ describe("pull request detail decoding", () => { checkSuite: { workflowRun: null }, ...fields, }; - const inWorkflow = ({ workflowName, ...fields }: Record) => + const inWorkflow = ({ + workflowName, + workflowId = `W_kwDORLtfbc4${String(workflowName)}`, + event = "pull_request", + runNumber = 95380, + ...fields + }: Record) => check({ ...fields, - checkSuite: { workflowRun: { workflow: { name: workflowName } } }, + checkSuite: { + workflowRun: { event, runNumber, workflow: { id: workflowId, name: workflowName } }, + }, }); const coreJson = ( @@ -655,6 +663,139 @@ describe("pull request detail decoding", () => { } }); + it("drops a cancelled check whose workflow run was superseded by a newer run on the head", () => { + const superseded = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + status: "COMPLETED", + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:00:05Z", + }; + const replacement = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95380, + status: "COMPLETED", + conclusion: "SUCCESS", + startedAt: "2026-10-30T10:00:10Z", + completedAt: "2026-10-30T10:05:00Z", + }; + const rollup = [ + inWorkflow({ ...superseded, name: "check", conclusion: "CANCELLED" }), + inWorkflow({ + ...superseded, + name: "web browser tests (runner ${{ matrix.slice }} of 6)", + conclusion: "CANCELLED", + }), + inWorkflow({ ...replacement, name: "check" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 1 of 6)" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 2 of 6)" }), + ]; + const detail = detailOf(rollup); + + expect([detail.checks.map((check) => [check.name, check.status]), detail.checksState]).toEqual([ + [ + ["check", "success"], + ["web browser tests (runner 1 of 6)", "success"], + ["web browser tests (runner 2 of 6)", "success"], + ], + "passing", + ]); + }); + + it("keeps a cancelled check when the newer run is another workflow with the same name", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + conclusion: "CANCELLED", + }), + inWorkflow({ + name: "lint", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4ToKTh", + runNumber: 95380, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test", + "cancelled", + ]); + expect(detail.checksState).toBe("failing"); + }); + + it("drops a required cancelled check once a newer run reports it, whenever it finished", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 41, + conclusion: "CANCELLED", + isRequired: true, + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:09:00Z", + }), + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 42, + conclusion: "SUCCESS", + isRequired: true, + startedAt: "2026-10-30T10:01:00Z", + completedAt: "2026-10-30T10:05:00Z", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toEqual([["test", "success"]]); + expect(detail.checksState).toBe("passing"); + }); + + it.each([ + ["a push", "push", "push", "CANCELLED", false, "cancelled"], + ["another event", "pull_request", "pull_request_target", "CANCELLED", false, "cancelled"], + ["a pull request run", "pull_request", "pull_request", "FAILURE", false, "failure"], + [ + "a pull request run, if required", + "pull_request", + "pull_request", + "CANCELLED", + true, + "cancelled", + ], + ])( + "keeps an older run's check when the newer run is %s", + (_label, olderEvent, newerEvent, conclusion, isRequired, status) => { + const detail = detailOf([ + inWorkflow({ + name: "test (packages/shared)", + workflowName: "CI", + event: olderEvent, + runNumber: 41, + conclusion, + isRequired, + }), + inWorkflow({ + name: "test (apps/server)", + workflowName: "CI", + event: newerEvent, + runNumber: 42, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test (packages/shared)", + status, + ]); + expect(detail.checksState).toBe("failing"); + }, + ); + it("merges reviews with comments in time order and keeps a bodyless approval", () => { const detail = expectSuccess(activity(JSON.parse(detailJson) as Record)); expect(detail.comments.map((comment) => comment.id)).toEqual(["r1", "c1", "r2"]); diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 7fbe86839d495..9eed567a6a4da 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -131,6 +131,13 @@ interface LatestReviewFields { readonly isMinimized?: boolean | undefined; } +/** Run numbers count up per workflow file, whatever its name; database ids exceed int32. */ +interface WorkflowRunFields { + readonly event: string; + readonly runNumber: number; + readonly workflow: { readonly id: string }; +} + /** Check runs use status/conclusion; commit statuses use a single state. */ interface CheckFields { readonly name?: string | null | undefined; @@ -143,6 +150,8 @@ interface CheckFields { readonly targetUrl?: string | null | undefined; /** Empty for app-owned runs; absent for commit statuses. */ readonly workflowName?: string | null | undefined; + /** Absent for commit statuses and app-owned runs. */ + readonly workflowRun?: WorkflowRunFields | null | undefined; readonly startedAt?: string | null | undefined; readonly completedAt?: string | null | undefined; /** Branch protection requires this check; asked for on github.com only. */ @@ -617,16 +626,42 @@ function isNamelessCheck(raw: CheckFields): boolean { return trimmed(raw.name) === null && trimmed(raw.context) === null; } -/** Unfinished runs outrank finished runs of the same check across push/PR workflows. */ +const PULL_REQUEST_EVENTS = new Set(["pull_request", "pull_request_target"]); + +/** + * Unfinished runs outrank finished runs of the same check across push/PR workflows. A newer pull + * request run of a workflow supersedes the older one's cancelled checks, whose names can differ + * (an unexpanded matrix). Other events can run one commit in different scopes (a branch and a + * tag, dispatch inputs), so their runs replace nothing. + */ function toCheckEntries(raw: ReadonlyArray | null | undefined): ReadonlyArray<{ readonly check: PullRequestCheck; readonly workflowName: string | null; readonly at: string | null; }> { + const lineageOf = (run: WorkflowRunFields) => `${run.workflow.id} ${run.event}`; + const newestRunNumber = new Map(); + const note = (key: string, runNumber: number) => { + if (runNumber > (newestRunNumber.get(key) ?? Number.NEGATIVE_INFINITY)) { + newestRunNumber.set(key, runNumber); + } + }; + for (const check of raw ?? []) { + const run = check.workflowRun; + if (run == null || !PULL_REQUEST_EVENTS.has(run.event)) continue; + note(lineageOf(run), run.runNumber); + note(`${lineageOf(run)} ${trimmed(check.name) ?? ""}`, run.runNumber); + } return (raw ?? []).flatMap((check) => { const name = trimmed(check.name) ?? trimmed(check.context); if (name === null) return []; const status = toCheckStatus(check); + const run = check.workflowRun; + if (status === "cancelled" && run != null) { + // Branch protection names required checks, so only a newer same-name check replaces one. + const replacedBy = check.isRequired === true ? `${lineageOf(run)} ${name}` : lineageOf(run); + if (run.runNumber < (newestRunNumber.get(replacedBy) ?? run.runNumber)) return []; + } return [ { check: { @@ -1246,7 +1281,11 @@ export type GitHubCheckContext = CheckFields; function toCheckContexts(nodes: ReadonlyArray): ReadonlyArray { return nodes.map((check) => check.__typename === "CheckRun" - ? { ...check, workflowName: check.checkSuite.workflowRun?.workflow.name ?? null } + ? { + ...check, + workflowName: check.checkSuite.workflowRun?.workflow.name ?? null, + workflowRun: check.checkSuite.workflowRun, + } : check, ); } diff --git a/packages/source-control-github/src/server/issues.graphql b/packages/source-control-github/src/server/issues.graphql index 42dc67a98a123..d8b28a08c7078 100644 --- a/packages/source-control-github/src/server/issues.graphql +++ b/packages/source-control-github/src/server/issues.graphql @@ -231,6 +231,7 @@ query IssueDetail($owner: String!, $name: String!, $number: Int!) { } ... on Issue { number + url repository { nameWithOwner } @@ -270,6 +271,16 @@ query IssueComments($owner: String!, $name: String!, $number: Int!, $cursor: Str } } +query IssueLinkMetadata($owner: String!, $name: String!, $number: Int!) { + repository(owner: $owner, name: $name) { + issue(number: $number) { + number + title + url + } + } +} + query IssueNodeId($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { diff --git a/packages/source-control-github/src/server/issues.graphql.ts b/packages/source-control-github/src/server/issues.graphql.ts index d99defc174a5c..fb393ef5ca4c6 100644 --- a/packages/source-control-github/src/server/issues.graphql.ts +++ b/packages/source-control-github/src/server/issues.graphql.ts @@ -487,6 +487,8 @@ export const SourceIssue = Schema.Struct({ __typename: Schema.Literal("Issue"), /** Identifies the issue number. */ number: Shared.Int, + /** The HTTP URL for this issue */ + url: Shared.URI, /** The repository associated with this node. */ repository: NodesRepositoryRepository }) @@ -584,7 +586,7 @@ export const IssueDetail = GraphQL.query("IssueDetail", { ], selections: [ { name: "viewer", body: ["{login}"] }, - { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number repository{nameWithOwner}}}}}}}}"] } + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number url repository{nameWithOwner}}}}}}}}"] } ], fragments: [ { name: "IssueRow", body: ["on Issue{number title url state stateReason createdAt updatedAt closedAt author{__typename login avatarUrl...on User{name}}}"] }, @@ -666,6 +668,52 @@ export declare namespace IssueComments { export type Result = typeof IssueComments.result.Type } +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */ +export const IssueLinkMetadataRepositoryIssueIssue = Schema.Struct({ + /** Identifies the issue number. */ + number: Shared.Int, + /** Identifies the issue title. */ + title: Schema.String, + /** The HTTP URL for this issue */ + url: Shared.URI +}) +export interface IssueLinkMetadataRepositoryIssueIssue extends Schema.Struct.Type {} + +/** A repository contains the content for a project. */ +export const IssueLinkMetadataRepositoryRepository = Schema.Struct({ + /** Returns a single issue from the current repository by number. */ + issue: Schema.NullOr(IssueLinkMetadataRepositoryIssueIssue) +}) +export interface IssueLinkMetadataRepositoryRepository extends Schema.Struct.Type {} + +/** `query IssueLinkMetadata` */ +export const IssueLinkMetadata = GraphQL.query("IssueLinkMetadata", { + document: { + variables: [ + { name: "owner", body: "String!" }, + { name: "name", body: "String!" }, + { name: "number", body: "Int!" } + ], + selections: [ + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){issue(number:$", "number", "){number title url}}"] } + ], + fragments: [] + }, + variables: { + owner: Schema.String, + name: Schema.String, + number: Shared.Int + }, + result: Schema.Struct({ + /** Lookup a given repository by the owner and repository name. */ + repository: Schema.NullOr(IssueLinkMetadataRepositoryRepository) + }) +}) +export declare namespace IssueLinkMetadata { + export type Variables = typeof IssueLinkMetadata.variables.Type + export type Result = typeof IssueLinkMetadata.result.Type +} + /** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */ export const IssueNodeIdRepositoryIssueIssue = Schema.Struct({ /** The Node ID of the Issue object */ @@ -1038,4 +1086,4 @@ export declare namespace IssueCollections { } /** Every operation in issues.graphql. */ -export const IssuesGraphQLGroup = GraphQLGroup.make(IssueSearch, IssueDetail, IssueComments, IssueNodeId, IssueCommentScope, IssueCandidates, IssueTemplates, IssueViewer, IssueCollections) +export const IssuesGraphQLGroup = GraphQLGroup.make(IssueSearch, IssueDetail, IssueComments, IssueLinkMetadata, IssueNodeId, IssueCommentScope, IssueCandidates, IssueTemplates, IssueViewer, IssueCollections) diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphql index 2799b67525a27..0b8c5350c1408 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql +++ b/packages/source-control-github/src/server/pullRequestReads.graphql @@ -42,7 +42,10 @@ fragment CheckContext on StatusCheckRollupContext { isRequired(pullRequestNumber: $number) @include(if: $required) checkSuite { workflowRun { + event + runNumber workflow { + id name } } diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.ts index ab5e211a4dec2..d26912d6aee7b 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts @@ -23,6 +23,8 @@ export interface StatusContext extends Schema.Struct.Type {} /** A workflow run. */ export const WorkflowRun = Schema.Struct({ + /** The event that triggered the workflow run */ + event: Schema.String, + /** A number that uniquely identifies this workflow run in its parent workflow. */ + runNumber: Shared.Int, /** The workflow executed in this workflow run. */ workflow: Workflow }) @@ -565,7 +571,7 @@ export const PullRequestCore = GraphQL.query("PullRequestCore", { { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed autoMergeAllowed viewerPermission pullRequest(number:$", "number", "){number title url body state isDraft mergeable mergeStateStatus reviewDecision additions deletions changedFiles createdAt updatedAt mergedAt mergeCommit{oid}mergedBy{__typename login avatarUrl...on User{name}}closedAt headRefName baseRefName headRefOid isCrossRepository maintainerCanModify headRepositoryOwner{__typename login}headRepository{nameWithOwner viewerPermission}headRef{id}author{__typename login avatarUrl...on User{id name}}autoMergeRequest{mergeMethod}mergeQueueRemovals:timelineItems(last:1 itemTypes:[REMOVED_FROM_MERGE_QUEUE_EVENT])@include(if:$", "mergeQueue", "){nodes{__typename...on RemovedFromMergeQueueEvent{id createdAt reason}}}viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch baseRef{compare(headRef:$", "headRef", "){behindBy}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name}...on Bot{login}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}labels(first:100){nodes{name color description}}commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event runNumber workflow{id name}}}}}"] } ] }, variables: { @@ -617,7 +623,7 @@ export const PullRequestCheckContexts = GraphQL.query("PullRequestCheckContexts" { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){headRefOid commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100 after:$", "after", "){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event runNumber workflow{id name}}}}}"] } ] }, variables: { diff --git a/packages/source-control-gitlab/src/server/GitLabCli.ts b/packages/source-control-gitlab/src/server/GitLabCli.ts index b528c1ced5a8a..04a633bba7096 100644 --- a/packages/source-control-gitlab/src/server/GitLabCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabCli.ts @@ -21,6 +21,8 @@ import * as SourceControlHost from "@t3tools/source-control-core/server/SourceCo import { decodeGitLabMergeRequestJson, decodeGitLabMergeRequestListJson, + type NormalizedGitLabMergeRequestRecord, + withSourceProjectPath, } from "./gitLabMergeRequests.ts"; import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; @@ -377,6 +379,10 @@ const decodeGitLabMergeRequestProject = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ id: Schema.Number, path: TrimmedNonEmptyString })), ); +const decodeGitLabProjectPath = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ path_with_namespace: TrimmedNonEmptyString })), +); + const RawGitLabNamespaceSchema = Schema.Struct({ id: Schema.Number, }); @@ -559,6 +565,35 @@ export const make = Effect.gen(function* () { ), ); + // glab's MR JSON names a fork's source project only by `source_project_id`. + const resolveSourceProjectPaths = Effect.fn("GitLabCli.resolveSourceProjectPaths")(function* ( + cwd: string, + records: ReadonlyArray, + paths: Map, + ) { + const ids = new Set(); + for (const record of records) { + const id = record.unresolvedSourceProjectId; + if (id !== undefined && !paths.has(id)) ids.add(id); + } + yield* Effect.forEach( + ids, + (id) => + execute({ cwd, args: ["api", `projects/${id}`] }).pipe( + Effect.flatMap((result) => decodeGitLabProjectPath(result.stdout.trim())), + Effect.map((project) => project.path_with_namespace), + Effect.orElseSucceed(() => null), + Effect.map((path) => void paths.set(id, path)), + ), + { concurrency: 8, discard: true }, + ); + return records.map((record) => + record.unresolvedSourceProjectId === undefined + ? record + : withSourceProjectPath(record, paths.get(record.unresolvedSourceProjectId) ?? null), + ); + }); + return GitLabCli.of({ execute, listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function* (input) { @@ -566,6 +601,7 @@ export const make = Effect.gen(function* () { let pageSize = limit; let page = 1; const items: GitLabMergeRequestSummary[] = []; + const sourceProjectPaths = input.source?.owner ? new Map() : null; while (items.length < limit) { const result = yield* execute({ cwd: input.cwd, @@ -600,7 +636,11 @@ export const make = Effect.gen(function* () { cause: Result.isFailure(decoded) ? decoded.failure : "MR list output was truncated", }); } - items.push(...decoded.success.map(toSummaryWithOptionalUpdatedAt)); + // Only a fork head can match a fork's merge request, so other lookups skip the API calls. + const records = sourceProjectPaths + ? yield* resolveSourceProjectPaths(input.cwd, decoded.success, sourceProjectPaths) + : decoded.success; + items.push(...records.map(toSummaryWithOptionalUpdatedAt)); // Count raw entries: the decoder drops invalid ones, which would end paging early. const entries = decodeJsonArray(raw); if ( @@ -635,7 +675,9 @@ export const make = Effect.gen(function* () { ); } - return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success)); + return resolveSourceProjectPaths(input.cwd, [decoded.success], new Map()).pipe( + Effect.map(([record]) => toSummaryWithOptionalUpdatedAt(record!)), + ); }), ), ), diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts index 7c794de8b456e..d3bd6e01366bd 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts @@ -59,6 +59,13 @@ function answer(path: string): string { created_at: "2026-07-03T00:00:00Z", system: true, }, + { + id: 10, + body: "mentioned in merge request api!51", + author: { username: "theo" }, + created_at: "2026-07-04T00:00:00Z", + system: true, + }, ]); } if (path.startsWith("projects/acme%2Fweb/issues/42/resource_label_events")) { @@ -206,7 +213,14 @@ describe("GitLabIssueTracker", () => { expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([ ["labeled", "bug"], ["closed", null], + ["referenced", "merge request api!51"], ]); + expect(issue.events.at(-1)?.reference).toEqual({ + repository: "acme/api", + number: 51, + kind: "pull-request", + url: "https://gitlab.com/acme/api/-/merge_requests/51", + }); // A closing merge request is not repeated as a related one. expect( issue.linkedPullRequests.map((link) => [link.number, link.closesIssue, link.isDraft]), diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts index f8b1f80c18b0e..4f4aeb3135034 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts @@ -25,6 +25,7 @@ import { decodeIssueDetailListJson, decodeIssueListJson, decodeIssueNotesJson, + withMentionReference, decodeLabelEventsJson, decodeLinkedMergeRequestsJson, decodeProjectLabelsJson, @@ -576,9 +577,12 @@ export const make: Effect.Effect = reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [], })), commentsCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null), - events: [...systemEvents, ...labelEvents].sort((left, right) => - left.createdAt.localeCompare(right.createdAt), - ), + events: [ + ...systemEvents.map((event) => + withMentionReference(event, issue.url, input.scope), + ), + ...labelEvents, + ].sort((left, right) => left.createdAt.localeCompare(right.createdAt)), // A merge request that closes the issue outranks its sighting as a mere mention. linkedPullRequests: [ ...closing, diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts index 7038e6a82d630..abd2f7b82f218 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts @@ -106,6 +106,97 @@ it.effect("lists a nested-group fork's merge requests by source branch and names }), ); +// Real `glab mr list --output json` marshals client-go's BasicMergeRequest: a fork MR names its +// source project only by `source_project_id`, never by a `source_project` path. +it.effect("names a fork merge request's source project from real glab list output", () => + Effect.gen(function* () { + const branch = "feature/fork-work"; + const mergeRequest = (iid: number, sourceProjectId: number) => ({ + id: 9000 + iid, + iid, + project_id: 100, + title: `Work ${iid}`, + state: "opened", + target_branch: "main", + source_branch: branch, + source_project_id: sourceProjectId, + target_project_id: 100, + draft: false, + sha: "0123456789abcdef0123456789abcdef01234567", + updated_at: "2026-04-07T15:00:00.000Z", + references: { short: `!${iid}`, relative: `!${iid}`, full: `group/upstream!${iid}` }, + web_url: `https://gitlab.com/group/upstream/-/merge_requests/${iid}`, + }); + const output = JSON.stringify([ + mergeRequest(1, 101), + mergeRequest(2, 101), + mergeRequest(3, 100), + mergeRequest(4, 102), + ]); + const apiCalls: ReadonlyArray[] = []; + const provider = yield* GitLabSourceControlProvider.make.pipe( + Effect.provide( + GitLabCli.layer.pipe( + Layer.provideMerge( + TestSourceControlHost.layer({ + process: { + run: (input) => + Effect.sync(() => { + if (input.args[0] !== "api") return TestSourceControlHost.processOutput(output); + apiCalls.push(input.args); + return TestSourceControlHost.processOutput( + input.args[1] === "projects/101" + ? JSON.stringify({ id: 101, path_with_namespace: "alice/upstream" }) + : "not json", + ); + }), + }, + }), + ), + Layer.provide(FileSystem.layerNoop({})), + ), + ), + ); + + const upstreamHead = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: branch, + state: "open", + limit: 20, + }); + expect(upstreamHead[0]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toEqual([]); + + const changeRequests = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: `alice:${branch}`, + state: "open", + limit: 20, + }); + // GitManager drops a cross-repository MR whose head project is unnamed. + expect(changeRequests).toMatchObject([ + { + number: 1, + isCrossRepository: true, + headRepositoryNameWithOwner: "alice/upstream", + headRepositoryOwnerLogin: "alice", + }, + { number: 2, isCrossRepository: true, headRepositoryNameWithOwner: "alice/upstream" }, + { number: 3, isCrossRepository: false }, + { number: 4, isCrossRepository: true }, + ]); + expect(changeRequests[2]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(changeRequests[3]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toHaveLength(2); + expect(apiCalls).toEqual( + expect.arrayContaining([ + ["api", "projects/101"], + ["api", "projects/102"], + ]), + ); + }), +); + const withRepository = ( test: (input: { readonly git: (...args: string[]) => Effect.Effect; diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts index 8e5077044c6b3..c5a2d56037172 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts @@ -210,6 +210,13 @@ it.effect( headSelectors: ["octocat:feature", "feature"], state: "open", }), + { headSelectors: ["octocat:feature"], limit: 100 }, + ); + assert.deepStrictEqual( + provider.headBranchProbe?.({ + headSelectors: ["feature", "octocat:feature"], + state: "open", + }), { headSelectors: ["feature"], limit: 100 }, ); }), diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts index a7d5b71ca47d3..2a2d4ac3e199c 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts @@ -211,11 +211,17 @@ export const make = Effect.gen(function* () { return SourceControlProvider.SourceControlProvider.of({ kind: SourceControlProviderKind.make("gitlab"), - // GitLab lists fork merge requests by source branch with no owner filter, so read a full page. - headBranchProbe: ({ headSelectors }) => ({ - headSelectors: headSelectors.filter((selector) => !selector.includes(":")), - limit: 100, - }), + // GitLab lists fork merge requests by source branch with no owner filter, so read a full page + // once per branch. The first selector wins: GitManager puts `owner:branch` first for a fork + // head, which tells the list to name fork source projects. + headBranchProbe: ({ headSelectors }) => { + const byBranch = new Map(); + for (const selector of headSelectors) { + const branch = SourceControlProvider.sourceBranch({ headSelector: selector }); + if (!byBranch.has(branch)) byBranch.set(branch, selector); + } + return { headSelectors: [...byBranch.values()], limit: 100 }; + }, readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")( function ({ cwd, treeish }) { return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute); diff --git a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts index 5458ed4f859ef..7a52667a4a425 100644 --- a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts @@ -250,6 +250,41 @@ function toSystemEvent( return null; } +// The path class excludes the sigil, so matching is linear on any input. +const MENTION = /^(?:merge request ([\w.\-/]*)!|issue ([\w.\-/]*)#)([1-9]\d*)$/; + +/** + * Where a "mentioned in merge request !12" note came from, addressed from the issue's own web URL + * so a self-managed host under a subpath resolves. A commit, epic or snippet mention gets none. + */ +export function withMentionReference( + event: IssueEvent, + issueUrl: string, + scope: string, +): IssueEvent { + const match = event.kind === "referenced" ? MENTION.exec(event.detail ?? "") : null; + const projectUrl = issueUrl.split("/-/")[0]!; + if (match === null || !projectUrl.toLowerCase().endsWith(`/${scope.toLowerCase()}`)) { + return event; + } + const [, mergeRequestPath, issuePath, digits] = match; + const isMergeRequest = mergeRequestPath !== undefined; + const path = mergeRequestPath ?? issuePath ?? ""; + // A project in the same namespace is named by its path alone. + const repository = + path === "" ? scope : path.includes("/") ? path : `${scope.replace(/[^/]*$/, "")}${path}`; + const base = projectUrl.slice(0, projectUrl.length - scope.length); + return { + ...event, + reference: { + repository, + number: Number(digits), + kind: isMergeRequest ? "pull-request" : "issue", + url: `${base}${repository}/-/${isMergeRequest ? "merge_requests" : "issues"}/${digits}`, + }, + }; +} + interface GitLabIssueNotes { readonly comments: ReadonlyArray; readonly events: ReadonlyArray; diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts index ef4438f5ff3ee..a40abd786cf85 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts @@ -23,6 +23,8 @@ export interface NormalizedGitLabMergeRequestRecord { readonly isCrossRepository?: boolean; readonly headRepositoryNameWithOwner?: string | null; readonly headRepositoryOwnerLogin?: string | null; + /** Set when a cross-repository MR names its source project only by id. */ + readonly unresolvedSourceProjectId?: number; } const GitLabProjectReferenceSchema = Schema.Struct({ @@ -122,6 +124,24 @@ function normalizeGitLabMergeRequestRecord( ...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}), ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + ...(isCrossRepository === true && + !sourceProjectPath && + typeof raw.source_project_id === "number" + ? { unresolvedSourceProjectId: raw.source_project_id } + : {}), + }; +} + +export function withSourceProjectPath( + record: NormalizedGitLabMergeRequestRecord, + sourceProjectPath: string | null, +): NormalizedGitLabMergeRequestRecord { + const { unresolvedSourceProjectId: _, ...resolved } = record; + const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath); + return { + ...resolved, + ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), }; } diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts new file mode 100644 index 0000000000000..838309b037617 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts @@ -0,0 +1,138 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; + +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as Credentials from "./TanStackSourceCredentials.ts"; +import * as TanStackSourcePullRequestProvider from "./TanStackSourcePullRequestProvider.ts"; + +const HOST = "source.tanstack.com"; + +/** + * Shaped like `GET /pulls/{n}` of a private pull request: its head is `owner:branch` in the + * companion repository, and Source has stored no file or line counts for it. + */ +const PRIVATE_PULL = { + number: 42, + title: "Fix the thing", + state: "open", + visibility: "private", + draft: false, + author: "bob", + head: "acme:fix/thing", + createdAt: 1_000, + body: null, + base: "main", + headRepo: "acme/web.private", + headSha: "c".repeat(40), + baseSha: "b".repeat(40), + mergeCommitSha: null, + mergedAt: null, + mergedBy: null, + mergeable: null, + changedFiles: null, + changedLines: null, +}; + +const FILES = { + baseSha: "b".repeat(40), + headSha: "c".repeat(40), + mergeBaseSha: "b".repeat(40), + available: true, + truncated: false, + files: [ + { path: "a.ts", status: "modified", additions: 3, deletions: 1 }, + { path: "b.ts", status: "added", additions: 4, deletions: 0 }, + ], +}; + +const RESPONSES: Record = { + "/repos/acme/web/pulls/42": PRIVATE_PULL, + "/repos/acme/web/pulls/42/files": FILES, + "/repos/acme/web/pulls/42/checks": { checks: [], upToDate: null, mayMerge: true }, + "/repos/acme/web/pulls/42/stack": { members: [] }, + [`/repos/acme/web/check-runs?sha=${"c".repeat(40)}`]: [], + "/repos/acme/web/ci/runs?pull=42&limit=30": { items: [], next: null }, + "/repos/acme/web/issues/42": { + timeline: [ + { id: 1, comment: "Looks good", author: "alice", at: 2_000 }, + { event: "head_updated", actor: "bob", at: 3_000 }, + ], + next: null, + }, + "/repos/acme/web/pulls/42/comments": [], + "/repos/acme/web/pulls/42/commits": { + baseSha: null, + headSha: null, + mergeBaseSha: null, + available: true, + commits: [], + }, + "/user": { username: "alice" }, +}; + +const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => + input.path in RESPONSES + ? Effect.succeed(JSON.stringify(RESPONSES[input.path])) + : Effect.die(`unexpected ${input.path}`), + response: () => Effect.die("unexpected response read"), +}); + +const provider = TanStackSourcePullRequestProvider.make.pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provideService( + Credentials.TanStackSourceCredentials, + Credentials.TanStackSourceCredentials.of({ + get: () => Effect.die("unexpected credential read"), + invalidate: () => Effect.void, + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected http request")), + ), +); + +describe("TanStackSourcePullRequestProvider.getChangeRequest", () => { + // A client without this host's definition percent-encodes the owner's `@`; stored links + // keep the web's own spelling. + it.effect.each(["acme/web", "@acme/web", "%40acme/web"])( + "reads a private pull request of %s", + (repository) => + Effect.gen(function* () { + const detail = yield* (yield* provider).getChangeRequest({ + host: HOST, + repository, + number: 42, + cwd: "/repo", + }); + assert.strictEqual(detail.url, `https://${HOST}/@acme/web/pull/42`); + assert.strictEqual(detail.visibility, "private"); + assert.strictEqual(detail.headBranch, "fix/thing"); + assert.strictEqual(detail.headRepositoryNameWithOwner, "acme/web.private"); + // Source stores no counts for it, so they come from its files. + assert.deepStrictEqual( + [detail.changedFiles, detail.additions, detail.deletions], + [2, 7, 1], + ); + }), + ); +}); + +describe("TanStackSourcePullRequestProvider.getChangeRequestActivity", () => { + it.effect("reads the comments of a timeline that also holds events", () => + Effect.gen(function* () { + const activity = yield* (yield* provider).getChangeRequestActivity({ + host: HOST, + repository: "acme/web", + number: 42, + cwd: "/repo", + }); + assert.deepStrictEqual( + activity.comments.map((comment) => comment.body), + ["Looks good"], + ); + }), + ); +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts index 509e03e1f41f4..0529ce6df17c7 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts @@ -35,6 +35,8 @@ const PULL = { function checkout(options: { readonly recordedOwner: string | null; readonly isAncestor: boolean; + readonly pull?: Partial; + readonly force?: boolean; }) { const git: Array = []; const config = new Map( @@ -43,14 +45,28 @@ function checkout(options: { const api = TanStackSourceApi.TanStackSourceApi.of({ request: (input) => input.path === "/repos/acme/web/pulls/42" - ? Effect.succeed(JSON.stringify(PULL)) + ? Effect.succeed(JSON.stringify({ ...PULL, ...options.pull })) : Effect.die(`unexpected ${input.path}`), response: () => Effect.die("unexpected response read"), }); const host = TestSourceControlHost.layer({ git: { resolvePrimaryRemoteName: () => Effect.succeed("origin"), - ensureRemote: () => Effect.succeed("origin"), + ensureRemote: (input) => + Effect.sync(() => { + git.push(`remote ${input.preferredName} ${input.url}`); + return input.url === REMOTE ? "origin" : input.preferredName; + }), + fetchRemoteBranch: (input) => + Effect.sync( + () => + void git.push(`fetch ${input.remoteName} ${input.remoteBranch}:${input.localBranch}`), + ), + fetchRemoteTrackingBranch: () => Effect.void, + setBranchUpstream: (input) => + Effect.sync( + () => void git.push(`upstream ${input.branch} ${input.remoteName}/${input.remoteBranch}`), + ), readConfigValue: (_cwd, key) => Effect.succeed(key === "remote.origin.url" ? REMOTE : (config.get(key) ?? null)), writeConfigValue: (input) => Effect.sync(() => void config.set(input.key, input.value)), @@ -86,7 +102,13 @@ function checkout(options: { }, }); const run = TanStackSourceSourceControlProvider.make.pipe( - Effect.flatMap((provider) => provider.checkoutChangeRequest({ cwd: "/repo", reference: "42" })), + Effect.flatMap((provider) => + provider.checkoutChangeRequest({ + cwd: "/repo", + reference: "42", + ...(options.force === undefined ? {} : { force: options.force }), + }), + ), Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), Effect.provide(Layer.merge(host, FileSystem.layerNoop({}))), ); @@ -129,4 +151,83 @@ describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => { assert.isFalse(git.some((command) => command.startsWith("checkout"))); }); }); + + // Source publishes no `refs/pull//head` for a private pull request, on either repository. + it.effect("takes a private pull request's branch from the companion repository", () => { + const pull = { head: "acme:fix-thing", headRepo: "acme/web.private" }; + const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true, pull }); + const forced = checkout({ recordedOwner: null, isAncestor: true, pull, force: true }); + return Effect.gen(function* () { + yield* forced.run; + assert.include(forced.git, "checkout --no-track -B fix-thing refs/remotes/acme/fix-thing --"); + yield* run; + assert.strictEqual(config.get("branch.fix-thing.pushRemote"), "acme"); + assert.deepStrictEqual(git, [ + `remote source ${REMOTE}`, + "remote acme https://source.tanstack.com/@acme/web.private.git", + "fetch acme fix-thing:fix-thing", + "upstream fix-thing acme/fix-thing", + "switch fix-thing", + ]); + }); + }); +}); + +describe("TanStackSourceSourceControlProvider private pull requests", () => { + it.effect("asks Source for the companion and opens the pull request as private", () => { + const requests: Array<{ method: string; path: string; body: unknown }> = []; + const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => { + requests.push({ method: input.method ?? "GET", path: input.path, body: input.body }); + return Effect.succeed( + JSON.stringify({ + owner: "acme", + name: "web.private", + defaultBranch: null, + cloneUrl: "https://source.tanstack.com/@acme/web.private.git", + }), + ); + }, + response: () => Effect.die("unexpected response read"), + }); + const files = FileSystem.layerNoop({ readFileString: () => Effect.succeed("Body") }); + return Effect.gen(function* () { + const provider = yield* TanStackSourceSourceControlProvider.make; + const companion = provider.privateChangeRequestRemote; + assert.isDefined(companion); + assert.deepStrictEqual(yield* companion({ cwd: "/repo" }), { + url: "https://source.tanstack.com/@acme/web.private.git", + repository: "acme/web.private", + }); + yield* provider.createChangeRequest({ + cwd: "/repo", + baseRefName: "main", + headSelector: "sec/fix", + title: "Fix", + bodyFile: "/tmp/body.md", + private: true, + }); + assert.deepStrictEqual(requests, [ + { method: "POST", path: "/repos/acme/web/private-remote", body: undefined }, + { + method: "POST", + path: "/repos/acme/web/pulls", + body: { title: "Fix", head: "sec/fix", base: "main", body: "Body", private: true }, + }, + ]); + }).pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provide( + Layer.merge( + TestSourceControlHost.layer({ + git: { + resolvePrimaryRemoteName: () => Effect.succeed("origin"), + readConfigValue: () => Effect.succeed(REMOTE), + }, + }), + files, + ), + ), + ); + }); }); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts index a1abb376b472d..f194848611361 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts @@ -395,6 +395,18 @@ export const make = Effect.gen(function* () { }, ), createsDraftChangeRequests: true, + privateChangeRequestRemote: Effect.fn( + "TanStackSourceSourceControlProvider.privateChangeRequestRemote", + )(function* (input) { + const target = yield* resolveTarget("privateChangeRequestRemote", input); + const companion = yield* read( + "privateChangeRequestRemote", + input.cwd, + { host: target.host, method: "POST", path: `/repos/${target.repository}/private-remote` }, + Repository, + ); + return { url: companion.cloneUrl, repository: `${companion.owner}/${companion.name}` }; + }), createChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.createChangeRequest")( function* (input) { const target = yield* resolveTarget("createChangeRequest", { @@ -437,6 +449,7 @@ export const make = Effect.gen(function* () { base: input.target?.refName ?? input.baseRefName, ...(body.trim().length === 0 ? {} : { body }), ...(input.draft === true ? { draft: true } : {}), + ...(input.private === true ? { private: true } : {}), }, }) .pipe( @@ -494,7 +507,8 @@ export const make = Effect.gen(function* () { return repository.defaultBranch; }, ), - // Every pull request's head is published as `refs/pull//head`, forks and GitHub sync too. + // A pull request's head is published as `refs/pull//head`, forks and GitHub sync too. A + // private one has no such ref: its branch is read from the companion repository. checkoutChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.checkoutChangeRequest")( function* (input) { const pull = yield* getPull(input); @@ -519,9 +533,26 @@ export const make = Effect.gen(function* () { }); const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest"; const branches = yield* git.listLocalBranchNames(input.cwd); - if (!pull.isCrossRepository) { + const companion = + pullRepository !== null && + pull.headRepositoryNameWithOwner?.toLowerCase() === + `${pullRepository}.private`.toLowerCase() + ? pull.headRepositoryNameWithOwner + : null; + if (!pull.isCrossRepository || companion !== null) { const localBranch = pull.headRefName; - const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: localBranch }; + const remoteBranch = { + cwd: input.cwd, + remoteName: + companion === null + ? remoteName + : yield* git.ensureRemote({ + cwd: input.cwd, + preferredName: companion.split("/")[0] ?? "private", + url: `${Hosts.webRepositoryUrl(HOST, companion)}.git`, + }), + remoteBranch: localBranch, + }; if (input.force !== true && !branches.includes(localBranch)) yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch }); else yield* git.fetchRemoteTrackingBranch(remoteBranch); @@ -535,11 +566,18 @@ export const make = Effect.gen(function* () { "--no-track", "-B", localBranch, - `refs/remotes/${remoteName}/${localBranch}`, + `refs/remotes/${remoteBranch.remoteName}/${localBranch}`, "--", ], }); yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch }); + // Whatever push defaults say, this branch must not be published to the public remote. + if (companion !== null) + yield* git.writeConfigValue({ + cwd: input.cwd, + key: `branch.${localBranch}.pushRemote`, + value: remoteBranch.remoteName, + }); yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch })); return; } diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts new file mode 100644 index 0000000000000..ac43a46ccdcad --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { tanStackSourceRepositoryPath } from "./tanStackSourceHosts.ts"; + +describe("tanStackSourceRepositoryPath", () => { + it.each([ + ["acme/web", "acme/web"], + ["@acme/web", "acme/web"], + // Clients without this host's definition percent-encode the owner's `@`. + ["%40acme/web", "acme/web"], + ["/@acme/web.git/", "acme/web"], + ["acme/web.private", "acme/web.private"], + ["acme", null], + ["acme/web/extra", null], + ["acme/..", null], + ])("reads %s as %s", (path, repository) => { + expect(tanStackSourceRepositoryPath(path)).toBe(repository); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts index 22923264629bf..dfa6d4e9031a0 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts @@ -1,4 +1,4 @@ -import { TANSTACK_SOURCE_HOST } from "../shared/definition.ts"; +import { TANSTACK_SOURCE_HOST, withoutOwnerMark } from "../shared/definition.ts"; export const TANSTACK_SOURCE_HOSTS = [TANSTACK_SOURCE_HOST] as const; export type TanStackSourceHost = (typeof TANSTACK_SOURCE_HOSTS)[number]; @@ -10,14 +10,14 @@ export function tanStackSourceHost(host: string): TanStackSourceHost | null { const SEGMENT = /^[A-Za-z0-9_.-]+$/u; -/** `owner/name` from the API spelling or the web spelling `@owner/name`, `.git` dropped. */ +/** `owner/name` from the API spelling or either web spelling of the owner, `.git` dropped. */ export function tanStackSourceRepositoryPath(path: string): string | null { - const [owner, name, ...rest] = path - .trim() - .replace(/^\/+|\/+$/gu, "") - .replace(/\.git$/u, "") - .replace(/^@/u, "") - .split("/"); + const [owner, name, ...rest] = withoutOwnerMark( + path + .trim() + .replace(/^\/+|\/+$/gu, "") + .replace(/\.git$/u, ""), + ).split("/"); return rest.length === 0 && owner !== undefined && name !== undefined && diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts index 4d698fb881dfb..24c93e6aac83d 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts @@ -146,6 +146,7 @@ describe("toActivity", () => { ["4", "review-comment", null], ]); expect(activity.comments[0]?.url).toBe(`https://${HOST}/@TanStack/ai/pull/9#comment-1`); + expect(Json.pullUrl(HOST, "%40TanStack/ai", 9)).toBe(`https://${HOST}/@TanStack/ai/pull/9`); expect(activity.reviewThreads).toMatchObject([ { id: "4", path: "a.ts", line: 2, side: "left", isResolved: true }, ]); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts index acf3c4158f95c..51537627ca3e7 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts @@ -16,6 +16,8 @@ import type { import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; +import { withoutOwnerMark } from "../shared/definition.ts"; + /** Source sends times as epoch milliseconds. */ const EpochMillis = Schema.Finite; const Login = Schema.String; @@ -29,6 +31,7 @@ export const SourcePull = Schema.Struct({ labels: Schema.optional(Schema.Array(Schema.String)), head: Schema.String, createdAt: EpochMillis, + visibility: Schema.optional(Schema.String), }); export type SourcePull = typeof SourcePull.Type; @@ -135,7 +138,8 @@ const TimelineEntry = Schema.Struct({ type TimelineEntry = typeof TimelineEntry.Type; export const SourceTimeline = Schema.Struct({ - timeline: Schema.Array(TimelineEntry), + // Events such as `head_updated` sit between the comments and carry no id. + timeline: Schema.Array(Schema.Union([TimelineEntry, Schema.Struct({ event: Schema.String })])), next: Schema.NullOr(Schema.String), }); @@ -239,10 +243,20 @@ export const SourceUser = Schema.Struct({ username: Schema.String }); export const iso = (millis: number) => DateTime.formatIso(DateTime.makeUnsafe(millis)); export const pullUrl = (host: string, repository: string, number: number) => - `https://${host}/@${repository}/pull/${number}`; + `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`; -/** A GitHub-synced pull request from a fork names its head only by its pull ref. */ -export const headBranchName = (head: string) => head.replace(/^refs\/heads\//u, ""); +/** + * A GitHub-synced pull request from a fork names its head only by its pull ref, and a private + * one as `owner:branch`. A branch name holds no colon, so the owner is all that one can precede. + */ +export const headBranchName = (head: string) => + head.replace(/^refs\/heads\//u, "").replace(/^[^/:]+:/u, ""); + +/** Absent when Source names no visibility, so a reader tells unknown from public. */ +const visibilityOf = (pull: Pick) => + pull.visibility === "private" || pull.visibility === "public" + ? { visibility: pull.visibility } + : {}; export function toActor(login: string | null, host: string): PullRequestActor | null { if (login === null || login.trim() === "") return null; @@ -280,6 +294,7 @@ export function toChangeRequest( baseBranch: pull.base ?? "", state: pull.state, isDraft: pull.draft, + ...visibilityOf(pull), mergeability: "unknown", additions: 0, deletions: 0, @@ -380,7 +395,9 @@ export function toActivity(input: { }): ProviderChangeRequestActivity { const { host } = input; const page = pullUrl(host, input.repository, input.number); - const entries = input.timeline.timeline.filter(visible); + const entries = input.timeline.timeline.filter( + (entry): entry is TimelineEntry => "id" in entry && visible(entry), + ); const comments: Array = entries.map((entry: TimelineEntry) => ({ id: String(entry.id), kind: diff --git a/packages/source-control-tanstack-source/src/shared/definition.test.ts b/packages/source-control-tanstack-source/src/shared/definition.test.ts index e3ce5c867fa5c..6e09a89fa2cda 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.test.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.test.ts @@ -31,7 +31,23 @@ describe("TanStack Source definition", () => { number: 7, }), ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); + // A stored link or an older client may name the repository as the web spells it. + for (const repository of ["@TanStack/router", "%40TanStack/router"]) + expect( + definition.changeRequestUrl({ host: "source.tanstack.com", repository, number: 7 }), + repository, + ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); expect(definition.checkoutCommandArgument("src pr checkout 7")).toBe("7"); expect(definition.checkoutCommandArgument("gh pr checkout 7")).toBeNull(); }); + + it.each(["tanstack/router", "@tanstack/router", "%40tanstack/router"])( + "keys %s as the API's owner/name", + (repository) => { + expect(definition.canonicalRepositoryKey?.(`source.tanstack.com/${repository}`)).toBe( + "source.tanstack.com/tanstack/router", + ); + expect(definition.canonicalRepositoryKey?.(`github.com/${repository}`)).toBeNull(); + }, + ); }); diff --git a/packages/source-control-tanstack-source/src/shared/definition.ts b/packages/source-control-tanstack-source/src/shared/definition.ts index 1aee00c968dc6..032adc5a45cdd 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.ts @@ -37,6 +37,20 @@ function parseChangeRequestUrl(url: URL) { : { ...link, repositoryUrl: `${url.origin}/@${CHANGE_REQUEST_PATH.exec(url.pathname)![1]}` }; } +/** + * `owner/name` as the API names it. The web spells it `@owner/name`, and a client without this + * definition percent-encodes that as `%40owner/name`. + */ +export const withoutOwnerMark = (repository: string) => repository.replace(/^(?:@|%40)/iu, ""); + +/** Links stored with the web's spelling compare equal to the project's own key. */ +function canonicalRepositoryKey(key: string): string | null { + const slash = key.indexOf("/"); + return slash > 0 && isTanStackSourceHost(key.slice(0, slash)) + ? `${TANSTACK_SOURCE_HOST}/${withoutOwnerMark(key.slice(slash + 1))}` + : null; +} + /** Keys drop the owner's `@`, so a project's repository is `owner/name` as the API names it. */ function repositoryKeyFromRemote(key: string): string | null { // Remote parsing spells the `@` percent-encoded. @@ -80,13 +94,13 @@ export const definition = defineSourceControl({ ? null : webUrl ? changeRequestUrlBelow(webUrl, `pull/${number}`) - : `https://${host}/@${repository.replace(/^@/u, "")}/pull/${number}`, + : `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`, parseChangeRequestUrl, commitUrl: (input) => buildCommitUrl( input.webUrl ? input - : { ...input, webUrl: `https://${input.host}/@${input.repository.replace(/^@/u, "")}` }, + : { ...input, webUrl: `https://${input.host}/@${withoutOwnerMark(input.repository)}` }, "commit", ), parseIssueUrl: (url) => @@ -122,6 +136,7 @@ export const definition = defineSourceControl({ checkoutChangeRequestHost: () => null, changeRequestHeadRef: (number) => `refs/pull/${number}/head`, repositoryKeyFromRemote, + canonicalRepositoryKey, recognizeRemote: ({ hostname }) => isTanStackSourceHost(hostname) ? { kind: KIND, name: "TanStack Source", baseUrl: `https://${TANSTACK_SOURCE_HOST}` } diff --git a/patches/@legendapp__list@3.7.3.patch b/patches/@legendapp__list@3.7.3.patch new file mode 100644 index 0000000000000..2afc400b04435 --- /dev/null +++ b/patches/@legendapp__list@3.7.3.patch @@ -0,0 +1,28 @@ +diff --git a/react-native.js b/react-native.js +index 440b0ad..fd5d18d 100644 +--- a/react-native.js ++++ b/react-native.js +@@ -1344,7 +1344,8 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) { + return; + } + if (contentSize > 0 && queuedInitialLayout) { +- const isContentLess = contentSize < scrollLength; ++ // T3 patch: a top inset (e.g. a translucent header) shrinks the room content has to fit in. ++ const isContentLess = contentSize + getContentInsetTop(ctx) < scrollLength; + set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON); + set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength); + set$( +diff --git a/react-native.mjs b/react-native.mjs +index b95e1f8..e2b013a 100644 +--- a/react-native.mjs ++++ b/react-native.mjs +@@ -1323,7 +1323,8 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) { + return; + } + if (contentSize > 0 && queuedInitialLayout) { +- const isContentLess = contentSize < scrollLength; ++ // T3 patch: a top inset (e.g. a translucent header) shrinks the room content has to fit in. ++ const isContentLess = contentSize + getContentInsetTop(ctx) < scrollLength; + set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON); + set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength); + set$( diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a40135621117a..abbe071b954cf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -370,7 +370,7 @@ overrides: packageExtensionsChecksum: sha256-18pwcgTDbqYFYAzCw8OfBYuC2btyq6aJSLhE/gjTJb4= -pnpmfileChecksum: sha256-h8NLkl2dhhbQKbAHnoo4rQ3tYV96igLQxJ7la6dsbSc= +pnpmfileChecksum: sha256-G0L7+qfid3Wo9BlLIlMyF/+fqBnAnqHKSe0HlWAtlg8= patchedDependencies: '@alchemy.run/test@2.0.0-beta.85': 29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e @@ -380,6 +380,7 @@ patchedDependencies: '@effect/vitest@4.1.5': dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5 '@expo/ui@58.0.27': 9f2547678939f4ec78fe45163b6455aad63d3c80353d7e0cc783f6a61a7ccc2f '@ff-labs/fff-node@0.11.0': 93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252 + '@legendapp/list@3.7.3': 85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4 '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101 '@pierre/diffs@1.7.0-beta.4': 7edcdd484a99c7ec0b2667499c4cb21d113ec9bea1f8570c0b0a030d33bbf1cd '@react-native-menu/menu@2.0.0': 6872ba71b9847c5a0210b1b896923dadc3860faedfe28d9f062bcedfe786ef1d @@ -597,7 +598,7 @@ importers: version: 5.4.6 '@legendapp/list': specifier: 3.7.3 - version: 3.7.3(react-dom@19.3.0(react@19.3.0))(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: 3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(react-dom@19.3.0(react@19.3.0))(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) '@material/material-color-utilities': specifier: 0.3.0 version: 0.3.0 @@ -1121,7 +1122,7 @@ importers: version: 5.3.0 '@legendapp/list': specifier: 3.7.3 - version: 3.7.3(react-dom@19.3.0(react@19.3.0))(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: 3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(react-dom@19.3.0(react@19.3.0))(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) '@noble/hashes': specifier: 'catalog:' version: 1.8.0 @@ -1131,6 +1132,9 @@ importers: '@pierre/trees': specifier: 1.0.0-beta.6 version: 1.0.0-beta.6(@pierre/theme@2.0.0)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(shiki@4.2.0) + '@pierre/words': + specifier: file:deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz + version: file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz(@pierre/highlights@0.5.1)(react@19.3.0) '@t3tools/client-runtime': specifier: workspace:* version: link:../../packages/client-runtime @@ -1182,6 +1186,9 @@ importers: '@tiptap/extension-list': specifier: ^3.31.3 version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-paragraph': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) '@tiptap/extension-strike': specifier: ^3.31.3 version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) @@ -1248,39 +1255,21 @@ importers: lucide-react: specifier: ^0.564.0 version: 0.564.0(react@19.3.0) - mdast-util-from-markdown: - specifier: ^2.0.3 - version: 2.0.3(supports-color@8.1.1) - micromark-util-combine-extensions: - specifier: ^2.0.1 - version: 2.0.1 pdfjs-dist: specifier: 6.4.299 version: 6.4.299 pele: specifier: 'catalog:' version: 1.8.0 + property-information: + specifier: ^7.2.0 + version: 7.2.0 react: specifier: 'catalog:' version: 19.3.0 react-dom: specifier: 'catalog:' version: 19.3.0(react@19.3.0) - react-markdown: - specifier: ^10.1.0 - version: 10.1.0(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1) - remark-gfm: - specifier: 'catalog:' - version: 4.0.1(supports-color@8.1.1) - remark-math: - specifier: 6.0.0 - version: 6.0.0(supports-color@8.1.1) - remark-parse: - specifier: 'catalog:' - version: 11.0.0(supports-color@8.1.1) - remark-rehype: - specifier: 'catalog:' - version: 11.1.2 saxes: specifier: 6.0.0 version: 6.0.0 @@ -1293,15 +1282,9 @@ importers: tiff: specifier: 7.1.3 version: 7.1.3 - unified: - specifier: 'catalog:' - version: 11.0.5 use-sync-external-store: specifier: ^1.6.0 version: 1.6.0(react@19.3.0) - vfile: - specifier: ^6.0.3 - version: 6.0.3 zustand: specifier: ^5.0.11 version: 5.0.14(@types/react@19.3.0)(react@19.3.0)(use-sync-external-store@1.6.0(react@19.3.0)) @@ -1330,9 +1313,6 @@ importers: '@types/hast': specifier: ^3.0.4 version: 3.0.5 - '@types/mdast': - specifier: ^4.0.4 - version: 4.0.4 '@types/react': specifier: 'catalog:' version: 19.3.0 @@ -1360,9 +1340,6 @@ importers: gt: specifier: 2.27.0 version: 2.27.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) - micromark-util-types: - specifier: 'catalog:' - version: 2.0.2 oxc-transform-react: specifier: ~0.152.0 version: 0.152.0 @@ -1608,21 +1585,12 @@ importers: jszip: specifier: 3.10.1 version: 3.10.1 - remark-gfm: - specifier: 'catalog:' - version: 4.0.1(supports-color@8.1.1) - remark-parse: - specifier: 'catalog:' - version: 11.0.0(supports-color@8.1.1) three: specifier: 0.180.0 version: 0.180.0 unbash: specifier: ^5.0.0 version: 5.0.0 - unified: - specifier: 'catalog:' - version: 11.0.5 devDependencies: '@effect/vitest': specifier: 4.1.5 @@ -1633,6 +1601,15 @@ importers: '@types/three': specifier: 0.180.0 version: 0.180.0 + remark-gfm: + specifier: 'catalog:' + version: 4.0.1(supports-color@8.1.1) + remark-parse: + specifier: 'catalog:' + version: 11.0.0(supports-color@8.1.1) + unified: + specifier: 'catalog:' + version: 11.0.5 vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -2190,6 +2167,9 @@ importers: gt-i18n: specifier: 1.0.40 version: 1.0.40 + hast-util-sanitize: + specifier: ^5.0.2 + version: 5.0.2 mdast-util-directive: specifier: 'catalog:' version: 3.1.0(supports-color@8.1.1) @@ -2242,12 +2222,18 @@ importers: '@effect/vitest': specifier: 4.1.5 version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + '@types/hast': + specifier: ^3.0.5 + version: 3.0.5 '@types/mdast': specifier: ^4.0.4 version: 4.0.4 '@types/node': specifier: 24.12.4 version: 24.12.4 + hast-util-to-html: + specifier: ^9.0.5 + version: 9.0.5 micromark-util-types: specifier: 'catalog:' version: 2.0.2 @@ -6518,6 +6504,18 @@ packages: react: ^18.3.1 || ^19.0.0 react-dom: ^18.3.1 || ^19.0.0 + '@pierre/words@file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz': + resolution: {integrity: sha512-EuIvU8imMY3c/deOHm9/gEh9VJga8R7jjWiIKfjKHbDXjgMo/O3NDN15H0dLc/vo+YTf/QpY0xinfnv7xpf7Rw==, tarball: file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz} + version: 0.2.2-t3.4 + peerDependencies: + '@pierre/highlights': '>=0.5.1' + react: ^18.3.1 || ^19.0.0 + peerDependenciesMeta: + '@pierre/highlights': + optional: true + react: + optional: true + '@pinojs/redact@0.4.0': resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} @@ -11660,12 +11658,6 @@ packages: react-is@19.2.7: resolution: {integrity: sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==} - react-markdown@10.1.0: - resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==} - peerDependencies: - '@types/react': '>=18' - react: '>=18' - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz: resolution: {integrity: sha512-TdP2nTxn8W4jPJ5EU+9Ctgf6aOncENP/kMa9aEZpJDmWNLXkxPpcugHMWyZJt2o5WDYE4SPi0V6zV6mOl3+8cA==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz} version: 1.2.0-t3.18 @@ -15667,7 +15659,7 @@ snapshots: '@koromix/koffi-win32-x64@3.3.6': optional: true - '@legendapp/list@3.7.3(react-dom@19.3.0(react@19.3.0))(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)': + '@legendapp/list@3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(react-dom@19.3.0(react@19.3.0))(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: react: 19.3.0 use-sync-external-store: 1.7.0(react@19.3.0) @@ -16587,6 +16579,11 @@ snapshots: - '@shikijs/themes' - shiki + '@pierre/words@file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz(@pierre/highlights@0.5.1)(react@19.3.0)': + optionalDependencies: + '@pierre/highlights': 0.5.1 + react: 19.3.0 + '@pinojs/redact@0.4.0': {} '@polka/url@1.0.0-next.29': {} @@ -22562,24 +22559,6 @@ snapshots: react-is@19.2.7: {} - react-markdown@10.1.0(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1): - dependencies: - '@types/hast': 3.0.5 - '@types/mdast': 4.0.4 - '@types/react': 19.3.0 - devlop: 1.1.0 - hast-util-to-jsx-runtime: 2.3.6(supports-color@8.1.1) - html-url-attributes: 3.0.1 - mdast-util-to-hast: 13.2.1(patch_hash=57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1) - react: 19.3.0 - remark-parse: 11.0.0(supports-color@8.1.1) - remark-rehype: 11.1.2 - unified: 11.0.5 - unist-util-visit: 5.1.0 - vfile: 6.0.3 - transitivePeerDependencies: - - supports-color - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz(katex@0.16.47)(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: react: 19.3.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 5de593cdb3426..d0dec103ac770 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -246,6 +246,7 @@ patchedDependencies: react-native-image-viewing@0.2.2: patches/react-native-image-viewing@0.2.2.patch mdast-util-math@3.0.0: patches/mdast-util-math@3.0.0.patch micromark-extension-llm-math@3.1.0: patches/micromark-extension-llm-math@3.1.0.patch + "@legendapp/list@3.7.3": patches/@legendapp__list@3.7.3.patch micromark-extension-gfm-table@2.1.1: patches/micromark-extension-gfm-table@2.1.1.patch micromark@4.0.2: patches/micromark@4.0.2.patch mdast-util-to-hast@13.2.1: patches/mdast-util-to-hast@13.2.1.patch diff --git a/scripts/build-npm-launcher.test.ts b/scripts/build-npm-launcher.test.ts index 9c217e0bbf147..59a808fe3f244 100644 --- a/scripts/build-npm-launcher.test.ts +++ b/scripts/build-npm-launcher.test.ts @@ -118,7 +118,11 @@ it.layer(NodeServices.layer)("build-npm-launcher", (it) => { Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" }); + // macOS temp directories sit under /var, a link to /private/var, and the launcher + // reports the resolved path it runs from. + const root = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" }), + ); const output = yield* buildNpmLauncher({ version: VERSION, outputDir: path.join(root, "out"), diff --git a/scripts/check-changed.ts b/scripts/check-changed.ts index 135ff4ed201f7..d5881661f4cdc 100644 --- a/scripts/check-changed.ts +++ b/scripts/check-changed.ts @@ -433,6 +433,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { file === ".pnpmfile.cjs" || file.startsWith("patches/") || file.startsWith("apps/mobile/deps/") || + file.startsWith("apps/web/deps/") || path.basename(file) === "package.json", ); @@ -479,7 +480,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { if (yield* fs.exists(inRoot(manifest))) yield* copy(manifest); } } - for (const extra of ["apps/mobile/deps", "patches", ".pnpmfile.cjs"]) { + for (const extra of ["apps/mobile/deps", "apps/web/deps", "patches", ".pnpmfile.cjs"]) { if (yield* fs.exists(inRoot(extra))) yield* copy(extra); } const result = yield* vp(["install", "--lockfile-only", "--ignore-scripts"], temp); diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 3c58be4cbabbf..e7acbf1e76ff1 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -68,11 +68,12 @@ function copyWorkspaceManifestFixture(targetRoot: string): void { NodeFS.cpSync(sourcePath, destinationPath); } - const mobileDependencies = NodePath.resolve(repoRoot, "apps/mobile/deps"); - if (NodeFS.existsSync(mobileDependencies)) { - NodeFS.cpSync(mobileDependencies, NodePath.resolve(targetRoot, "apps/mobile/deps"), { - recursive: true, - }); + // Fork tarballs that file: dependencies install from. + for (const forks of ["apps/mobile/deps", "apps/web/deps"]) { + const source = NodePath.resolve(repoRoot, forks); + if (NodeFS.existsSync(source)) { + NodeFS.cpSync(source, NodePath.resolve(targetRoot, forks), { recursive: true }); + } } const patchesDirectory = NodePath.resolve(repoRoot, "patches"); diff --git a/scripts/scenarios/branch-picker-sees-external-worktree.e2e.ts b/scripts/scenarios/branch-picker-sees-external-worktree.e2e.ts new file mode 100644 index 0000000000000..ccd14a4616f96 --- /dev/null +++ b/scripts/scenarios/branch-picker-sees-external-worktree.e2e.ts @@ -0,0 +1,71 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; + +import { run } from "./shell.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +test( + "Reopening the branch picker shows a worktree created outside T3 Code", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const git = (...args: string[]) => runPromise(run("git", args, { cwd: project })); + await git("branch", "feature"); + await browser.setViewport({ width: 1280, height: 800 }); + + // Wait for the real server's first forced ref listing to complete before changing Git. + await browser.addInitScript(() => { + const refreshRequests = new Set(); + const watched = new WeakSet(); + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (typeof data === "string") { + for (const request of [JSON.parse(data)].flat()) { + if (request?.tag === "vcs.listRefs" && request.payload?.refresh === true) { + refreshRequests.add(String(request.id)); + } + } + } + if (!watched.has(this)) { + watched.add(this); + this.addEventListener("message", (event) => { + if (typeof event.data !== "string") return; + for (const response of [JSON.parse(event.data)].flat()) { + if ( + response?._tag === "Exit" && + response.exit?._tag === "Success" && + refreshRequests.has(String(response.requestId)) + ) { + document.documentElement.dataset.refRefresh = "done"; + } + } + }); + } + return send.call(this, data); + }; + }); + + await t3.open("/"); + const branchPicker = browser + .locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible') + .first(); + await branchPicker.click(); + await screen.getByRole("option", /^feature\b/).waitFor(); + await browser.locator('html[data-ref-refresh="done"]').waitFor({ state: "attached" }); + await browser.keyboard.press("Escape"); + // The server coalesces forced snapshot reads for five seconds. + await runPromise(Effect.sleep("6 seconds")); + + await git("worktree", "add", "../other-checkout", "feature"); + try { + await branchPicker.click(); + const feature = screen.getByRole("option", /^feature\b/); + await feature.waitFor(); + await app.screenshot("branch-picker-after-external-worktree"); + await expect(feature).toContainText("worktree"); + } finally { + await git("worktree", "remove", "../other-checkout"); + } + }, +); diff --git a/scripts/scenarios/browser-history-keeps-visits-from-both-tabs.e2e.ts b/scripts/scenarios/browser-history-keeps-visits-from-both-tabs.e2e.ts new file mode 100644 index 0000000000000..738d7f8b9df00 --- /dev/null +++ b/scripts/scenarios/browser-history-keeps-visits-from-both-tabs.e2e.ts @@ -0,0 +1,76 @@ +/// +// @effect-diagnostics-next-line nodeBuiltinImport:off - fixture pages for the server's browser +import * as NodeHttp from "node:http"; + +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Browser history keeps visits from both open tabs after a reload", + WEB, + async ({ t3, app, browser, screen }) => { + const server = NodeHttp.createServer((request, response) => { + const title = request.url === "/first" ? "First preview visit" : "Second preview visit"; + response.writeHead(200, { "content-type": "text/html" }); + response.end(`${title}

    ${title}

    `); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + try { + const address = server.address(); + if (address === null || typeof address === "string") throw new Error("No page port."); + const host = `127.0.0.1:${address.port}`; + const origin = `http://${host}`; + const project = await t3.project("demo"); + const first = await t3.thread({ project, title: "First browser", messages: ["first"] }); + const second = await t3.thread({ project, title: "Second browser", messages: ["second"] }); + const history = await t3.thread({ project, title: "History check", messages: ["third"] }); + await t3.open(first); + + // Load the second app before either visit, with an independent store and shared storage. + await browser.evaluate((threadId) => { + const frame = document.createElement("iframe"); + frame.id = "second-client"; + frame.src = location.pathname.replace(/[^/]+$/, threadId); + frame.style.cssText = + "position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647"; + document.body.append(frame); + return null; + }, second.threadId); + const other = browser.frameLocator("#second-client"); + await other.getByRole("button", "Toggle right panel").tap(); + await other.getByRole("button", "Browser B").tap(); + const otherAddress = other.getByRole("textbox", "Search or enter URL"); + await otherAddress.waitFor(); + await browser.evaluate(() => { + document.querySelector("#second-client")!.style.display = "none"; + return null; + }); + + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + await screen.getByRole("textbox", "Search or enter URL").fill(`${origin}/first`); + await browser.keyboard.press("Enter"); + await screen.getByText("First preview visit", { exact: true }).waitFor(); + + await browser.evaluate(() => { + document.querySelector("#second-client")!.style.display = ""; + return null; + }); + await otherAddress.fill(`${origin}/second`); + await browser.keyboard.press("Enter"); + await other.getByText("Second preview visit", { exact: true }).waitFor(); + + const historyUrl = new URL(await browser.url()); + historyUrl.pathname = historyUrl.pathname.replace(/[^/]+$/, history.threadId); + await app.open(historyUrl.pathname); + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + await screen.getByText(`${host}/second`, { exact: false }).waitFor(); + await app.screenshot("browser-history-after-both-visits"); + await expect(screen.getByText(`${host}/first`, { exact: false })).toBeVisible(); + } finally { + await new Promise((resolve) => server.close(resolve)); + } + }, +); diff --git a/scripts/scenarios/cleanup-skips-dangling-log-symlink.e2e.ts b/scripts/scenarios/cleanup-skips-dangling-log-symlink.e2e.ts new file mode 100644 index 0000000000000..f86fdba249ff1 --- /dev/null +++ b/scripts/scenarios/cleanup-skips-dangling-log-symlink.e2e.ts @@ -0,0 +1,73 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +const decodeSettings = Schema.decodeSync( + Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)), +); + +test( + "Cleanup removes expired rotated logs even with a dangling symlink in the log directory", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("rotated-log-cleanup"); + const settingsPath = `${T3_HOME}/userdata/settings.json`; + const logFixture = `${T3_HOME}/userdata/logs/00-cleanup-fixture`; + const expiredLog = `${logFixture}/server.log.1`; + const original = await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(settingsPath)), + ); + + try { + await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => + fs.writeFileString( + settingsPath, + JSON.stringify({ ...decodeSettings(original), storageCleanup: { logsAfterDays: 7 } }), + ), + ), + ); + await t3.open("/settings/maintenance"); + await screen.getByLabel("Delete old rotated logs in days").waitFor(); + + const deleteNow = screen.getByRole("button", "Delete now", { exact: true }); + await deleteNow.tap(); + await screen.getByRole("button", "Deleting…", { exact: true }).waitFor({ state: "hidden" }); + await screen.getByRole("button", /^Last run/).tap(); + const logsResult = browser + .locator('#storage-cleanup-last-run [data-slot="settings-row"]') + .filter({ has: screen.getByText("Rotated logs", { exact: true }) }); + await logsResult.getByText("No expired files", { exact: true }).waitFor(); + + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.makeDirectory(logFixture); + yield* fs.symlink(`${logFixture}/missing.log`, `${logFixture}/00-dangling.log.1`); + yield* fs.writeFileString(expiredLog, "Expired log"); + yield* fs.utimes(expiredLog, 1, 1); + }), + ); + + await deleteNow.tap(); + await logsResult.scrollIntoView(); + try { + await expect(logsResult).toContainText("Removed 1 rotated logs"); + } finally { + await app.screenshot("rotated-log-cleanup-result"); + } + } finally { + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.remove(logFixture, { recursive: true, force: true }); + yield* fs.writeFileString(settingsPath, original); + }), + ); + } + }, +); diff --git a/scripts/scenarios/editing-default-shortcut-keeps-the-other.e2e.ts b/scripts/scenarios/editing-default-shortcut-keeps-the-other.e2e.ts new file mode 100644 index 0000000000000..f2c75d5c34d29 --- /dev/null +++ b/scripts/scenarios/editing-default-shortcut-keeps-the-other.e2e.ts @@ -0,0 +1,59 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { T3_HOME } from "../e2e.config.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +test( + "Editing one inherited shortcut keeps the other shortcut for the same command", + WEB, + async ({ t3, app, screen }) => { + await t3.project("inherited-shortcuts"); + const keybindingsPath = `${T3_HOME}/userdata/keybindings.json`; + const original = await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(keybindingsPath)), + ); + + try { + await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => + fs.writeFileString( + keybindingsPath, + '[{ "key": "enter", "command": "commandPalette.toggle", "when": "!rightPanelOpen" }]\n', + ), + ), + ); + await t3.open("/settings/keybindings"); + const search = screen.getByLabel("Search keybindings"); + await search.fill("Command Palette"); + await screen + .getByRole("button", "Edit shortcut for Command Palette: Toggle: Enter") + .waitFor(); + + await search.fill("Chat: New"); + const unchanged = screen.getByRole("button", "Edit shortcut for Chat: New: Ctrl+N", { + exact: true, + }); + await unchanged.waitFor(); + await screen.getByRole("button", "Edit shortcut for Chat: New: Ctrl+Shift+O").tap(); + await screen.getByRole("textbox", "Keybinding for Chat: New", { exact: true }).press("F8"); + await screen.getByRole("button", "Save", { exact: true }).tap(); + await screen + .getByRole("button", "Edit shortcut for Chat: New: F8", { exact: true }) + .waitFor(); + + try { + await expect(unchanged).toBeVisible(); + } finally { + await app.screenshot("chat-new-shortcuts-after-edit"); + } + } finally { + await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => + fs.writeFileString(keybindingsPath, original), + ), + ); + } + }, +); diff --git a/scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts b/scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts new file mode 100644 index 0000000000000..d1270ef325df4 --- /dev/null +++ b/scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts @@ -0,0 +1,103 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +interface ReopenGate { + readonly closed: Promise; + readonly requested: Promise; + readonly arm: () => void; + readonly release: () => Promise; +} + +declare global { + interface Window { + reopenGate: ReopenGate; + } +} + +test( + "A browser tab finishing its reopen leaves the newer conversation on screen", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const owner = await t3.thread({ project, title: "Browser owner", messages: ["first"] }); + await t3.thread({ + project, + title: "Newer conversation", + messages: ["Stay in this conversation"], + }); + + await browser.addInitScript(() => { + const closed = Promise.withResolvers(); + const requested = Promise.withResolvers(); + const restored = Promise.withResolvers(); + let hasClosedBrowser = false; + let armed = false; + let sendHeld = () => {}; + const setItem = Storage.prototype.setItem; + Storage.prototype.setItem = function (key, value) { + setItem.call(this, key, value); + if (key !== "t3code:closed-views:v2") return; + const hasBrowser = value.includes('"kind":"browser"'); + if (hasBrowser) closed.resolve(); + else if (hasClosedBrowser) restored.resolve(); + hasClosedBrowser = hasBrowser; + }; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (!armed || typeof data !== "string") return send.call(this, data); + const parsed = JSON.parse(data); + const messages = [parsed].flat(); + const isOpen = (message: { _tag?: string; tag?: string }) => + message._tag === "Request" && message.tag === "preview.open"; + const previewOpens = messages.filter(isOpen); + if (previewOpens.length === 0) return send.call(this, data); + armed = false; + const others = messages.filter((message) => !isOpen(message)); + if (others.length > 0) send.call(this, JSON.stringify(others)); + sendHeld = () => + send.call(this, Array.isArray(parsed) ? JSON.stringify(previewOpens) : data); + requested.resolve(); + }; + window.reopenGate = { + closed: closed.promise, + requested: requested.promise, + arm: () => { + armed = true; + }, + release: () => { + sendHeld(); + return restored.promise; + }, + }; + }); + + await t3.open(owner); + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + await screen.getByRole("button", "Close Browser", { exact: true }).tap(); + await browser.evaluate(async () => { + await window.reopenGate.closed; + window.reopenGate.arm(); + return null; + }); + + await browser.keyboard.press("Control+Shift+t"); + await browser.evaluate(async () => { + await window.reopenGate.requested; + return null; + }); + await screen.getByRole("button", "Newer conversation", { exact: false }).tap(); + const newerMessage = screen.getByText("Stay in this conversation", { exact: true }); + await newerMessage.waitFor(); + const newerUrl = await browser.url(); + await browser.evaluate(async () => { + await window.reopenGate.release(); + return null; + }); + + await app.screenshot("conversation-after-browser-reopens"); + await expect(browser).toHaveURL(newerUrl); + }, +); diff --git a/scripts/scenarios/secret-check-keeps-new-attempt-pending.e2e.ts b/scripts/scenarios/secret-check-keeps-new-attempt-pending.e2e.ts new file mode 100644 index 0000000000000..fff6e88dc19ca --- /dev/null +++ b/scripts/scenarios/secret-check-keeps-new-attempt-pending.e2e.ts @@ -0,0 +1,139 @@ +/// +import { SecretProviderId, SecretProviderKind } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { T3_HOME } from "../e2e.config.ts"; +import { environmentId, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const PROVIDER = SecretProviderId.make("scenario"); +const REFERENCE_A = "op://Scenario/GitHub/first"; +const REFERENCE_B = "op://Scenario/GitHub/second"; + +declare global { + interface Window { + secretCheckGate?: { + readonly reached: (count: number) => Promise; + readonly finishFirst: () => Promise; + }; + } +} + +test( + "An earlier check of the same reference leaves the new check pending", + WEB, + async ({ t3, app, browser, screen }) => { + const origin = app.baseUrl ?? ""; + const environment = await runPromise(environmentId(origin)); + await t3.project("demo"); + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString(`${T3_HOME}/bin/op`, "#!/bin/sh\nexit 1\n"); + yield* fs.chmod(`${T3_HOME}/bin/op`, 0o755); + const client = yield* rpcClient(T3_HOME, origin); + yield* client["server.updateSettings"]({ + patch: { + secretProviders: { + [PROVIDER]: { + kind: SecretProviderKind.make("one_password"), + label: "Scenario", + config: { account: "scenario" }, + }, + }, + sourceControlHosts: { + github: { + tokens: { + "github.com": { + provider: PROVIDER, + reference: REFERENCE_A, + }, + }, + }, + }, + }, + }); + }).pipe(Effect.scoped), + ); + + // Delay the real checks independently so only the older A can produce a reply. + await browser.addInitScript(() => { + type Frame = { readonly _tag?: string; readonly tag?: string; readonly id?: string | number }; + const checks: Array<() => Promise> = []; + const waiting: Array<{ readonly count: number; readonly resolve: () => void }> = []; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (this: WebSocket, data) { + if (typeof data !== "string") return send.call(this, data); + const parsed: Frame | Frame[] = JSON.parse(data); + const frames = [parsed].flat(); + const check = frames.find( + (frame) => frame._tag === "Request" && frame.tag === "server.checkSecretSource", + ); + if (!check) return send.call(this, data); + const other = frames.filter((frame) => frame !== check); + if (other.length > 0) send.call(this, JSON.stringify(other)); + checks.push( + () => + new Promise((resolve) => { + const receive = (event: MessageEvent) => { + if (typeof event.data !== "string") return; + const replies: Array<{ _tag?: string; requestId?: string | number }> = [ + JSON.parse(event.data), + ].flat(); + if (!replies.some((reply) => reply._tag === "Exit" && reply.requestId === check.id)) + return; + this.removeEventListener("message", receive); + resolve(); + }; + this.addEventListener("message", receive); + send.call(this, JSON.stringify(Array.isArray(parsed) ? [check] : check)); + }), + ); + for (const waiter of waiting) if (waiter.count === checks.length) waiter.resolve(); + }; + window.secretCheckGate = { + reached: (count) => + checks.length >= count + ? Promise.resolve() + : new Promise((resolve) => waiting.push({ count, resolve })), + finishFirst: () => checks[0]!(), + }; + }); + + await t3.open(`/settings/source-control?machine=${encodeURIComponent(environment)}`); + await screen.getByRole("button", "Toggle GitHub details", { exact: true }).tap(); + const input = screen.getByRole("textbox", "GitHub token reference", { exact: true }); + const check = screen.getByRole("button", "Check GitHub token", { exact: true }); + const startCheck = async (count: number) => { + await check.tap(); + await browser.evaluate(async (count) => { + await window.secretCheckGate!.reached(count); + return null; + }, count); + }; + const commit = async (reference: string) => { + await input.fill(reference); + await input.press("Enter"); + }; + + await startCheck(1); + await commit(REFERENCE_B); + await startCheck(2); + await commit(REFERENCE_A); + await startCheck(3); + const pending = await browser.evaluate(async () => { + await window.secretCheckGate!.finishFirst(); + // Nothing follows a stale reply on the fix, so give its RPC and React update time to land. + for (let frame = 0; frame < 10; frame++) { + await new Promise((resolve) => requestAnimationFrame(resolve)); + } + return ( + document.querySelector('button[aria-label="Check GitHub token"]') + ?.disabled === true + ); + }); + await app.screenshot("new-secret-check-after-old-reply"); + expect(pending, "The newer secret check is still pending after the earlier reply").toBe(true); + }, +); diff --git a/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts new file mode 100644 index 0000000000000..acd9096465978 --- /dev/null +++ b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts @@ -0,0 +1,75 @@ +import { ProjectSnapshot, ProviderInstanceId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const PROMPT_LOG_LIMIT = 64 * 1024; +const FRAME_OPEN = "".length; + +const deliverStraddlingEmoji = Effect.fn("scenario.deliverStraddlingEmoji")( + function* (origin: string) { + const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]); + const { projects } = yield* HttpClient.execute( + HttpClientRequest.get(`${origin}/api/projects`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)), + ); + const client = yield* rpcClient(T3_HOME, origin); + const { task } = yield* client["scheduledTasks.upsert"]({ + title: "Webhook log", + prompt: "{{body.text}}", + enabled: true, + schedule: { type: "webhook" }, + projectId: projects.find((project) => project.title === "webhook-log")!.id, + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + // The emoji's high surrogate is the last code unit the delivery log keeps. + const text = `${"a".repeat(PROMPT_LOG_LIMIT - 1 - FRAME_OPEN)}😀 tail`; + yield* HttpClient.execute( + HttpClientRequest.post(`${origin}${task.webhook!.path}`).pipe( + HttpClientRequest.bodyJsonUnsafe({ text }), + ), + ).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); + }, + Effect.scoped, + Effect.provide(FetchHttpClient.layer), +); + +test( + "A long webhook prompt in the delivery log does not end in a broken character", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("webhook-log"); + await runPromise(deliverStraddlingEmoji(app.baseUrl ?? "")); + + await t3.open("/settings/scheduled-tasks"); + await screen.getByRole("button", "Actions for Webhook log").tap(); + await screen.getByRole("menuitem", "Deliveries").tap(); + const dialog = screen.getByRole("dialog"); + await dialog.getByRole("button", /POST/).tap(); + const prompt = dialog.getByText(/^ { + const block = [...document.querySelectorAll("pre")].find((pre) => + pre.textContent?.startsWith("