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..dda8e058b7179 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -66,10 +66,11 @@ const fakeAppImage = (canMount = true, app = REPORTER) => { return { root, image, appImage, shim }; }; -// Stays up after a signal until the test lets it finish, like a server shutting down. +// Stays up after a signal until the test lets it finish, like a server shutting down. A group +// signal and the launcher's forwarded one can both arrive; a re-run trap would read stdin's EOF. const SLOW_SERVER = [ "#!/bin/sh", - "trap 'echo stopping >&3; read go; echo stopped >&3; exit 0' TERM HUP", + 'trap \'trap "" TERM HUP; echo stopping >&3; read go; echo "stopped $go" >&3; exit 7\' TERM HUP', "echo ready", "while :; do sleep 0.05; done", "", @@ -101,9 +102,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 +122,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 +136,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 +164,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 9c12690f31351..5474583be9976 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/electron/ElectronMenu.test.ts b/apps/desktop/src/electron/ElectronMenu.test.ts new file mode 100644 index 0000000000000..df98bdf4e9e85 --- /dev/null +++ b/apps/desktop/src/electron/ElectronMenu.test.ts @@ -0,0 +1,45 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import type * as Electron from "electron"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import { vi } from "vite-plus/test"; + +const { menu } = vi.hoisted(() => ({ + menu: { template: [] as Electron.MenuItemConstructorOptions[] }, +})); + +vi.mock("electron", () => ({ + Menu: { + buildFromTemplate: (template: Electron.MenuItemConstructorOptions[]) => { + menu.template = template; + return { popup: (options: Electron.PopupOptions) => options.callback?.() }; + }, + }, +})); + +import * as ElectronMenu from "./ElectronMenu.ts"; + +describe("ElectronMenu", () => { + it.effect("shows ampersands in labels instead of reading them as mnemonics", () => + Effect.gen(function* () { + const electronMenu = yield* ElectronMenu.make; + yield* electronMenu.showContextMenu({ + window: { webContents: { getZoomFactor: () => 1 } } as Electron.BrowserWindow, + items: [ + { id: "filter", label: "Filter by R&D" }, + { id: "more", label: "A&B", children: [{ id: "child", label: "C && D" }] }, + ], + position: Option.none(), + source: Option.none(), + }); + + assert.deepEqual( + menu.template.map((item) => item.label), + ["Filter by R&&D", "A&&B"], + ); + const submenu = menu.template[1]!.submenu as Electron.MenuItemConstructorOptions[]; + assert.equal(submenu[0]!.label, "C &&&& D"); + }).pipe(Effect.provideService(HostProcess.Platform, "win32")), + ); +}); diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index 540326346edf8..873281685054d 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -168,7 +168,8 @@ export const make = Effect.gen(function* () { } const itemOption: Electron.MenuItemConstructorOptions = { - label: item.label, + // Electron reads a single & as a mnemonic marker and drops it. + label: item.label.replaceAll("&", "&&"), enabled: !item.disabled, ...(typeof item.checked === "boolean" ? { type: "checkbox", checked: item.checked } : {}), }; diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts index 7563898f43efc..43208638f12d8 100644 --- a/apps/desktop/src/electron/ElectronProtocol.ts +++ b/apps/desktop/src/electron/ElectronProtocol.ts @@ -20,7 +20,7 @@ export function getDesktopScheme(isDevelopment: boolean): string { return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME; } -function getDesktopOrigin(isDevelopment: boolean): string { +export function getDesktopOrigin(isDevelopment: boolean): string { return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`; } 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 7878d7b6ebd6d..503190ae22c6d 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/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 572997a02c576..6c00607a4eb40 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -74,6 +74,12 @@ function makeFakeBrowserWindow() { const webContentsListeners = new Map void>(); let zoomLevel = 0; const webContents = { + id: 1, + session: { + webRequest: { + onBeforeSendHeaders: vi.fn(), + }, + }, copyImageAt: vi.fn(), focus: vi.fn(), isDestroyed: vi.fn(() => false), @@ -902,7 +908,7 @@ describe("DesktopWindow", () => { attach({}, otherGuest.window.webContents); const openPopup = guest.webContentsListeners.get("did-create-window"); if (!openPopup) return yield* Effect.die("did-create-window listener was not registered"); - openPopup(popup.window); + openPopup(popup.window, { url: "https://example.com/" }); const pages = [main, guest, otherGuest, popup]; for (const page of pages) { diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index e6c282b35cfc3..c4c26fa00f6fc 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -14,12 +14,13 @@ import { msg } from "gt-i18n"; import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; import * as DesktopAssets from "../app/DesktopAssets.ts"; +import * as DesktopClerk from "../app/DesktopClerk.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopPrimaryPaste from "../app/DesktopPrimaryPaste.ts"; import { makeComponentLogger } from "../app/DesktopObservability.ts"; import * as DesktopState from "../app/DesktopState.ts"; import * as ElectronMenu from "../electron/ElectronMenu.ts"; -import { getDesktopUrl } from "../electron/ElectronProtocol.ts"; +import { getDesktopOrigin, getDesktopUrl } from "../electron/ElectronProtocol.ts"; import * as ElectronShell from "../electron/ElectronShell.ts"; import * as ElectronTheme from "../electron/ElectronTheme.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; @@ -46,6 +47,7 @@ import { makeQuitShortcutHandler } from "./QuitHold.ts"; import { isThreadPopoutUrl, resolvePopoutWindowOptions } from "./popoutWindow.ts"; import { readForkNormalBounds } from "./forkWindowDisplay.ts"; import { copyContextMenuImage } from "./ContextMenuImage.ts"; +import { installMainWindowRemoteRequestHeaderPolicy } from "./RemoteRequestHeaders.ts"; const TITLEBAR_HEIGHT = 40; @@ -410,6 +412,7 @@ export const make = Effect.gen(function* () { Effect.suspend(() => pendingMainReveals.get(window) ?? electronWindow.reveal(window)), ); let flushMainWindowBounds: Effect.Effect = Effect.void; + let remoteRequestHeaderOwner: Electron.BrowserWindow | null = null; const dismissConnectingSplash = Effect.gen(function* () { const splash = yield* Ref.getAndSet(splashWindowRef, Option.none()); @@ -1075,6 +1078,19 @@ export const make = Effect.gen(function* () { // Desktop IPC only answers the main window, so register it before its renderer can call in. yield* electronWindow.setMain(window); + remoteRequestHeaderOwner = window; + const detachRemoteRequestHeaders = installMainWindowRemoteRequestHeaderPolicy( + window.webContents.session, + { + desktopOrigin: getDesktopOrigin(environment.isDevelopment), + mainWebContentsId: window.webContents.id, + clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname, + devServerOrigin: Option.getOrUndefined( + Option.map(environment.devServerUrl, (url) => url.origin), + ), + isDevelopment: environment.isDevelopment, + }, + ); loadApplication(); if (environment.isDevelopment) { window.webContents.openDevTools({ mode: "detach" }); @@ -1084,6 +1100,10 @@ export const make = Effect.gen(function* () { if (!backendHasStarted) mainClosedDuringStartup = true; clearDevelopmentLoadRetry(); clearBoundsPersist(); + if (remoteRequestHeaderOwner === window) { + remoteRequestHeaderOwner = null; + detachRemoteRequestHeaders(); + } void runPromise(electronWindow.clearMain(Option.some(window))); }); diff --git a/apps/desktop/src/window/RemoteRequestHeaders.test.ts b/apps/desktop/src/window/RemoteRequestHeaders.test.ts new file mode 100644 index 0000000000000..fee9aedb16c63 --- /dev/null +++ b/apps/desktop/src/window/RemoteRequestHeaders.test.ts @@ -0,0 +1,186 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { + stripDesktopOriginHeaders, + type MainWindowRequestHeaderPolicy, +} from "./RemoteRequestHeaders.ts"; + +const packagedPolicy: MainWindowRequestHeaderPolicy = { + desktopOrigin: "t3code://app", + mainWebContentsId: 42, + clerkFrontendApiHostname: "clerk.t3.codes", + isDevelopment: false, +}; + +const devPolicy: MainWindowRequestHeaderPolicy = { + desktopOrigin: "t3code-dev://app", + mainWebContentsId: 42, + clerkFrontendApiHostname: "clerk.t3.codes", + devServerOrigin: "http://devbox.internal:5733", + isDevelopment: true, +}; + +describe("RemoteRequestHeaders", () => { + it.each([ + "https://remote.example.com/.well-known/t3/environment", + "http://127.0.0.1:8080/api/auth/bootstrap", + "ws://127.0.0.1:8080/ws?ticket=abc", + "wss://remote.example.com/ws?ticket=abc", + ])("strips Origin and Sec-Fetch-* on outbound main-window %s requests", (url) => { + const headers = stripDesktopOriginHeaders(packagedPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Dest": "empty", + "sec-fetch-user": "?1", + Authorization: "Bearer secret", + DPoP: "proof-jwt", + }, + }); + + assert.deepEqual(headers, { + Authorization: "Bearer secret", + DPoP: "proof-jwt", + }); + }); + + it("strips lowercase origin headers and allows null frames (WebSocket upgrades and workers)", () => { + const headers = stripDesktopOriginHeaders(packagedPolicy, { + url: "wss://remote.example.com/ws", + webContentsId: 42, + frame: null, + requestHeaders: { + origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + Upgrade: "websocket", + }, + }); + + assert.deepEqual(headers, { + Upgrade: "websocket", + }); + }); + + it("preserves headers for Clerk frontend API requests", () => { + for (const url of ["https://clerk.t3.codes/v1/client", "https://CLERK.T3.CODES./v1/client"]) { + const headers = stripDesktopOriginHeaders(packagedPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }); + assert.isUndefined(headers); + } + }); + + it("preserves headers for dev loopback and exact devServerOrigin, while stripping other ports and remote hosts", () => { + for (const url of [ + "http://localhost:3773/api/health", + "http://app.localhost:3773/api/health", + "http://127.0.0.1:3773/api/health", + "http://[::1]:3773/api/health", + "ws://127.0.0.1:3773/ws", + "http://devbox.internal:5733/api/health", + "ws://devbox.internal:5733/ws", + ]) { + assert.isUndefined( + stripDesktopOriginHeaders(devPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code-dev://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + } + + for (const url of [ + "http://devbox.internal:8080/api/auth/bootstrap", + "https://remote.example.com/api/auth/bootstrap", + ]) { + assert.deepEqual( + stripDesktopOriginHeaders(devPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code-dev://app", + "Sec-Fetch-Site": "cross-site", + "Content-Type": "application/json", + }, + }), + { "Content-Type": "application/json" }, + ); + } + }); + + it("never touches sandboxed iframes (Origin: null), subframes, or other webContents", () => { + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "null", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 42, + frame: { parent: {} }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 99, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: undefined, + frame: null, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + }); +}); diff --git a/apps/desktop/src/window/RemoteRequestHeaders.ts b/apps/desktop/src/window/RemoteRequestHeaders.ts new file mode 100644 index 0000000000000..61df4c3535160 --- /dev/null +++ b/apps/desktop/src/window/RemoteRequestHeaders.ts @@ -0,0 +1,129 @@ +import * as NetAddress from "effect/net/NetAddress"; +import * as Result from "effect/Result"; +import type * as Electron from "electron"; + +// `*://` matches only http and https, so WebSocket schemes are listed separately. +const REMOTE_REQUEST_URL_PATTERNS = ["http://*/*", "https://*/*", "ws://*/*", "wss://*/*"]; + +export interface MainWindowRequestHeaderPolicy { + readonly desktopOrigin: string; + readonly mainWebContentsId: number; + readonly clerkFrontendApiHostname?: string | undefined; + readonly devServerOrigin?: string | undefined; + readonly isDevelopment: boolean; +} + +export interface MainWindowRequestHeaderDetails { + readonly url: string; + readonly webContentsId?: number | undefined; + readonly frame?: { readonly parent: unknown } | null | undefined; + readonly requestHeaders: Record; +} + +function normalizeHostname(hostname: string): string { + return hostname + .toLowerCase() + .replace(/^\[(.*)\]$/, "$1") + .replace(/\.$/, ""); +} + +function isLoopbackHostname(hostname: string): boolean { + return ( + hostname === "localhost" || + hostname.endsWith(".localhost") || + Result.match(NetAddress.ipFromString(hostname), { + onSuccess: NetAddress.isLoopback, + onFailure: () => false, + }) + ); +} + +function toHttpOrigin(url: URL): string { + if (url.protocol === "ws:") { + return `http://${url.host}`; + } + if (url.protocol === "wss:") { + return `https://${url.host}`; + } + return url.origin; +} + +function isSubframe(details: MainWindowRequestHeaderDetails): boolean { + try { + return details.frame != null && details.frame.parent !== null; + } catch { + return true; + } +} + +function hasExactDesktopOriginHeader( + requestHeaders: Record, + desktopOrigin: string, +): boolean { + let matched = false; + for (const [name, value] of Object.entries(requestHeaders)) { + if (name.toLowerCase() !== "origin") continue; + if (value !== desktopOrigin) return false; + matched = true; + } + return matched; +} + +function shouldPreserveOriginHeader(policy: MainWindowRequestHeaderPolicy, url: URL): boolean { + const hostname = normalizeHostname(url.hostname); + if ( + policy.clerkFrontendApiHostname !== undefined && + hostname === normalizeHostname(policy.clerkFrontendApiHostname) + ) { + return true; + } + if (!policy.isDevelopment) return false; + if (policy.devServerOrigin !== undefined && toHttpOrigin(url) === policy.devServerOrigin) { + return true; + } + return isLoopbackHostname(hostname); +} + +/** + * Strips Electron's synthetic `Origin` (`t3code://app`) and `Sec-Fetch-*` headers on outbound + * main-window requests so origin-checking reverse proxies treat Desktop like native T3 clients. + */ +export function stripDesktopOriginHeaders( + policy: MainWindowRequestHeaderPolicy, + details: MainWindowRequestHeaderDetails, +): Record | undefined { + if (details.webContentsId !== policy.mainWebContentsId) return undefined; + if (isSubframe(details)) return undefined; + if (!hasExactDesktopOriginHeader(details.requestHeaders, policy.desktopOrigin)) { + return undefined; + } + + const parsedUrl = URL.parse(details.url); + if (parsedUrl === null || shouldPreserveOriginHeader(policy, parsedUrl)) { + return undefined; + } + + const nextHeaders: Record = {}; + for (const [name, value] of Object.entries(details.requestHeaders)) { + const lowerName = name.toLowerCase(); + if (lowerName === "origin" || lowerName.startsWith("sec-fetch-")) continue; + nextHeaders[name] = value; + } + return nextHeaders; +} + +export function installMainWindowRemoteRequestHeaderPolicy( + session: Pick, + policy: MainWindowRequestHeaderPolicy, +): () => void { + session.webRequest.onBeforeSendHeaders( + { urls: REMOTE_REQUEST_URL_PATTERNS }, + (details, callback) => { + const requestHeaders = stripDesktopOriginHeaders(policy, details); + callback(requestHeaders === undefined ? {} : { requestHeaders }); + }, + ); + return () => { + session.webRequest.onBeforeSendHeaders(null); + }; +} diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index a563b6a4ee3a7..470091f334fb7 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -555,8 +555,40 @@ describe("parseResolvedPath", () => { // Path.layer joins with POSIX separators here, so the test windir is a POSIX path. const WSL_EXE = "/windows/System32/wsl.exe"; +const STORE_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService"; +const INBOX_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager"; + +const registrySpawner = (keys: ReadonlyArray) => + ChildProcessSpawner.make((command) => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Effect.succeed( + ChildProcessSpawner.ExitCode( + command._tag === "StandardCommand" && + command.command === "reg.exe" && + keys.some((key) => command.args.includes(key)) + ? 0 + : 1, + ), + ), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), + ); -const isAvailable = (policy?: Parameters[0]) => +const isAvailable = ( + policy?: Parameters[0], + serviceKeys: ReadonlyArray = [STORE_SERVICE], +) => makeIsAvailable("win32", "/windows").pipe( Effect.provide( Layer.mergeAll( @@ -565,9 +597,17 @@ const isAvailable = (policy?: Parameters[ DesktopManagedPolicy.layerTest(policy), ), ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, registrySpawner(serviceKeys)), ); describe("makeIsAvailable", () => { + it.effect("needs a registered WSL service, not just the System32 install stub", () => + Effect.gen(function* () { + assert.isFalse(yield* isAvailable(undefined, [])); + assert.isTrue(yield* isAvailable(undefined, [INBOX_SERVICE])); + }), + ); + it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () => Effect.gen(function* () { assert.isTrue(yield* isAvailable()); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index f1d2fccde537b..9d9540a65dc7d 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -1119,13 +1119,50 @@ const getUserHomeImpl = ( Effect.orElseSucceed(() => Option.none()), ); +// Store/MSI WSL registers WSLService and inbox WSL registers LxssManager; either key means installed. +const WSL_SERVICE_KEYS = [ + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService", + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager", +] as const; +const SERVICE_QUERY_TIMEOUT = Duration.seconds(5); + +const wslServiceRegistered = Effect.scoped( + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const registered = yield* Effect.forEach( + WSL_SERVICE_KEYS, + (key) => + spawner + .spawn( + ChildProcess.make("reg.exe", ["query", key], { + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + killSignal: "SIGTERM", + forceKillAfter: PROCESS_TERMINATE_GRACE, + }), + ) + .pipe(Effect.flatMap((handle) => handle.exitCode)), + { concurrency: "unbounded" }, + ); + return registered.some((exitCode) => (exitCode as unknown as number) === 0); + }), +).pipe( + Effect.timeoutOption(SERVICE_QUERY_TIMEOUT), + Effect.map(Option.getOrElse(() => false)), + Effect.orElseSucceed(() => false), +); + export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* ( platform: NodeJS.Platform, windir: string, ): Effect.fn.Return< boolean, never, - FileSystem.FileSystem | Path.Path | DesktopManagedPolicy.DesktopManagedPolicy + | FileSystem.FileSystem + | Path.Path + | DesktopManagedPolicy.DesktopManagedPolicy + | ChildProcessSpawner.ChildProcessSpawner > { if (platform !== "win32") return false; const path = yield* Path.Path; @@ -1134,6 +1171,8 @@ export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable" if (!(yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false)))) { return false; } + // System32\wsl.exe is also an install stub on Windows without WSL, so check for its service. + if (!(yield* wslServiceRegistered)) return false; // A server in WSL reads Linux's policy, never this machine's, so a managed machine runs none. return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( Effect.map((found) => found === undefined), @@ -1245,6 +1284,7 @@ export const layer = Layer.effect( // Cache availability so synchronous IPC bootstrap can read it without yielding to filesystem I/O. const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(Path.Path, environment.path), Effect.provideService( DesktopManagedPolicy.DesktopManagedPolicy, diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 9244e98594256..5145cdb23dd67 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -472,9 +472,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-composer-editor/ios/T3ComposerEditorModule.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift index c54a1a84e9644..d07908a4b27fa 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift @@ -117,6 +117,7 @@ public class T3ComposerEditorModule: Module { "onComposerBlur", "onComposerSubmit", "onComposerPasteImages", + "onComposerPasteImagesPending", "onComposerContextPress", "onComposerPasteContext", "onComposerPasteText", diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift index 253376fe5e4d3..2f24b0d98752c 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift @@ -86,6 +86,8 @@ private final class ComposerTextView: UITextView { ]) var onPasteImages: (([String]) -> Void)? + /// Change in how many pasted images are still loading: +n when a paste is accepted, -n once it settles. + var onPasteImagesPending: ((Int) -> Void)? var onPasteContext: (([String: String]) -> Void)? var onPasteText: ((String, NSRange) -> Void)? var clipboardFragment = "" @@ -308,6 +310,8 @@ private final class ComposerTextView: UITextView { } func loadImages(from providers: [NSItemProvider]) { + guard !providers.isEmpty else { return } + onPasteImagesPending?(providers.count) let group = DispatchGroup() let lock = NSLock() var images = [(data: Data, fileExtension: String)?](repeating: nil, count: providers.count) @@ -325,10 +329,11 @@ private final class ComposerTextView: UITextView { store((object as? UIImage)?.pngData().map { ($0, "png") }) } } - // Decoding a GIF to UIImage keeps only its first frame, so pass its bytes through. - if provider.hasItemConformingToTypeIdentifier(UTType.gif.identifier) { - _ = provider.loadDataRepresentation(forTypeIdentifier: UTType.gif.identifier) { data, _ in - if let data { store((data, "gif")) } else { loadPNG() } + // Re-encoding a photo as PNG inflates it several times and keeps only a GIF's first frame, + // so pass the provider's own encoding through when it is one the attachment path reads. + if let original = Self.passthroughImageType(of: provider) { + _ = provider.loadDataRepresentation(forTypeIdentifier: original.type.identifier) { data, _ in + if let data { store((data, original.fileExtension)) } else { loadPNG() } } } else { loadPNG() @@ -336,7 +341,11 @@ private final class ComposerTextView: UITextView { } group.notify(queue: .main) { [weak self] in - guard let self, !self.isReadOnly else { + guard let self else { + return + } + defer { self.onPasteImagesPending?(-providers.count) } + guard !self.isReadOnly else { return } let urls = images.compactMap { $0 }.compactMap { @@ -418,6 +427,23 @@ private final class ComposerTextView: UITextView { return sourceOffset } + private static let passthroughImageTypes: [(type: UTType, fileExtension: String)] = [ + (.gif, "gif"), (.jpeg, "jpg"), (.heic, "heic"), (.png, "png"), (.webP, "webp"), + ] + + /// Providers list representations best first, so the first supported one is the original. + private static func passthroughImageType( + of provider: NSItemProvider + ) -> (type: UTType, fileExtension: String)? { + for identifier in provider.registeredTypeIdentifiers { + guard let registered = UTType(identifier) else { continue } + if let match = passthroughImageTypes.first(where: { registered.conforms(to: $0.type) }) { + return match + } + } + return nil + } + private static func writeTemporaryImage(_ image: UIImage) -> String? { image.pngData().flatMap { writeTemporaryImage($0, fileExtension: "png") } } @@ -507,6 +533,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro let onComposerBlur = EventDispatcher() let onComposerSubmit = EventDispatcher() let onComposerPasteImages = EventDispatcher() + let onComposerPasteImagesPending = EventDispatcher() let onComposerContextPress = EventDispatcher() let onComposerPasteContext = EventDispatcher() let onComposerPasteText = EventDispatcher() @@ -537,6 +564,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro textView.onPasteImages = { [weak self] urls in self?.onComposerPasteImages(["uris": urls]) } + textView.onPasteImagesPending = { [weak self] delta in + self?.onComposerPasteImagesPending(["delta": delta]) + } textView.onPasteContext = { [weak self] context in guard let self else { return } let selection = self.sourceSelection() diff --git a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift index 6b69f29d308d5..83c1920bfd133 100644 --- a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift +++ b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift @@ -271,6 +271,17 @@ gifEditor.onPasteImages = { urls in exit(0) } +// A provider that finishes on a later main-queue turn, like a full-size photo still loading. +private let deferredPNG = image.pngData()! +private let deferredProvider = NSItemProvider() +deferredProvider.registerDataRepresentation(forTypeIdentifier: UTType.png.identifier, visibility: .all) { completion in + DispatchQueue.main.async { completion(deferredPNG, nil) } + return nil +} +private var pendingDeltas: [Int] = [] +private let deferredEditor = ComposerTextView() +deferredEditor.onPasteImagesPending = { pendingDeltas.append($0) } + // Inline provider completion places the attachment callback before this main-queue check. DispatchQueue.main.async { check(pastedImages.count == 1, "An accepted provider-based paste must emit exactly one attachment batch") @@ -287,7 +298,16 @@ DispatchQueue.main.async { "The attachment must contain the pasted image's pixels") check(pasteEditor.text == "Keep this draft", "Image paste must preserve the draft text") print("Composer provider-paste checks passed") - check(gifProvider.canLoadObject(ofClass: UIImage.self), "A GIF provider must take the image paste path") - gifEditor.paste(itemProviders: [gifProvider, ImmediateImageProvider(image: image)]) + deferredEditor.onPasteImages = { urls in + urls.compactMap(URL.init(string:)).forEach { try? FileManager.default.removeItem(at: $0) } + DispatchQueue.main.async { + check(pendingDeltas == [1, -1], "A finished paste must settle its preparation: \(pendingDeltas)") + print("Composer paste-preparation checks passed") + check(gifProvider.canLoadObject(ofClass: UIImage.self), "A GIF provider must take the image paste path") + gifEditor.paste(itemProviders: [gifProvider, ImmediateImageProvider(image: image)]) + } + } + deferredEditor.paste(itemProviders: [deferredProvider]) + check(pendingDeltas == [1], "Preparation must be reported before the provider finishes: \(pendingDeltas)") } dispatchMain() 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..3b45931f87eb3 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 @@ -416,12 +416,13 @@ class T3WorkspaceNavigationView( "threads" -> "Chats" "pullRequests" -> "Pulls" "issues" -> "Issues" + "workflows" -> "Workflows" "usage" -> "Usage" else -> "Settings" } 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( @@ -429,6 +430,7 @@ class T3WorkspaceNavigationView( "threads" -> R.drawable.t3_chats "pullRequests" -> R.drawable.t3_pull_requests "issues" -> R.drawable.t3_issues + "workflows" -> R.drawable.t3_workflows "usage" -> R.drawable.t3_usage else -> R.drawable.t3_settings } diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_workflows.xml b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_workflows.xml new file mode 100644 index 0000000000000..a6f6ea7edcfc5 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_workflows.xml @@ -0,0 +1,3 @@ + + + diff --git a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift index 9df738d37fa67..666f59df83485 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift @@ -109,9 +109,15 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { private func prepareItems() { let iconBundle = Bundle(for: Self.self).url(forResource: "T3NativeControlIcons", withExtension: "bundle").flatMap(Bundle.init(url:)) let pullRequestIcon = UIImage(named: "pull-request", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) - let labels = ["threads": "Chats", "pullRequests": "PRs", "issues": "Issues", "usage": "Usage", "settings": "Settings"] + let labels = [ + "threads": "Chats", "pullRequests": "PRs", "issues": "Issues", "workflows": "Workflows", + "usage": "Usage", "settings": "Settings", + ] let issueIcon = UIImage(named: "issue", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) - let symbols = ["threads": "text.bubble", "usage": "chart.bar.xaxis", "settings": "gearshape"] + let symbols = [ + "threads": "text.bubble", "workflows": "point.3.connected.trianglepath.dotted", + "usage": "chart.bar.xaxis", "settings": "gearshape", + ] for (tab, label) in labels { let icon = tab == "pullRequests" ? pullRequestIcon : tab == "issues" ? issueIcon : UIImage(systemName: symbols[tab] ?? "circle") let item = UITabBarItem(title: nil, image: tabIcon(icon), tag: 0) diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt index d86861018c77d..3334efd268bc3 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt @@ -70,6 +70,11 @@ internal class ReviewDiffCanvasDrawing(context: Context) { ) } + fun fileHeaderCheckboxHitRect(top: Int, bottom: Int, width: Int, style: DiffStyle): RectF { + val checkbox = fileHeaderCheckboxRect(top, bottom, width, style) + return RectF(checkbox.left - 14f * density, top.toFloat(), width.toFloat(), bottom.toFloat()) + } + fun drawDisclosureChevron( canvas: Canvas, rect: RectF, diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt index 8b0a84a952caf..2888917a89044 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -766,7 +766,7 @@ private class DiffCanvasView(context: Context) : View(context) { rowHitAt(event.y)?.let { hit -> val target = if ( hit.row.kind == "file" && - drawing.fileHeaderCheckboxRect( + drawing.fileHeaderCheckboxHitRect( hit.top, hit.bottom, width, @@ -1314,12 +1314,13 @@ private class DiffCanvasView(context: Context) : View(context) { } val selected = selectedRowIds.contains(row.id) if (selected) { + // Source files hide the change bar (width 0); the selection marker still needs to show. fill( canvas, withAlpha(theme.hunkText, 242), 0f, top.toFloat(), - style.changeBarWidthPx, + maxOf(style.changeBarWidthPx, 4f * density), bottom.toFloat() ) } diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index 7fe4a068f9bbb..07d9a58a3553c 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -1029,6 +1029,7 @@ private struct ReviewDiffFileHeaderInteractiveRects { let chevron: CGRect let icon: CGRect let checkbox: CGRect + let checkboxHitTarget: CGRect } private struct ReviewDiffStickyFileHeaderIndex { @@ -1643,7 +1644,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let interactiveRects = fileHeaderInteractiveRects(for: row, cardRect: rect) let fileId = resolvedFileId(for: row) - if interactiveRects.checkbox.contains(point) { + if interactiveRects.checkboxHitTarget.contains(point) { onToggleViewedFile?(fileId) return } @@ -2349,10 +2350,17 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let chevronRect = CGRect(x: cardRect.minX + horizontalPadding, y: centerY - 10, width: 20, height: 20) let iconRect = CGRect(x: chevronRect.maxX + 8, y: centerY - 10, width: 20, height: 20) let checkboxRect = CGRect(x: cardRect.maxX - horizontalPadding - 20, y: centerY - 10, width: 20, height: 20) + let checkboxHitMinX = checkboxRect.minX - 14 return ReviewDiffFileHeaderInteractiveRects( chevron: chevronRect, icon: iconRect, - checkbox: checkboxRect + checkbox: checkboxRect, + checkboxHitTarget: CGRect( + x: checkboxHitMinX, + y: cardRect.minY, + width: cardRect.maxX - checkboxHitMinX, + height: cardRect.height + ) ) } @@ -2661,8 +2669,9 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { return } + // Source files hide the change bar (width 0); the selection marker still needs to show. theme.hunkText.withAlphaComponent(0.95).setFill() - context.fill(CGRect(x: 0, y: rect.minY, width: style.changeBarWidth, height: rect.height)) + context.fill(CGRect(x: 0, y: rect.minY, width: max(style.changeBarWidth, 4), height: rect.height)) } private func drawWordDiffRanges( diff --git a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt index f2992979bf522..63e1acece9074 100644 --- a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt +++ b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt @@ -149,6 +149,18 @@ class ReviewDiffGeometryTest { } } + @Test + fun viewedCheckboxHitTargetSpansTheHeaderHeightAndTrailingEdge() { + val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication()) + val style = DiffStyle.defaults(1f) + val glyph = drawing.fileHeaderCheckboxRect(100, 144, 320, style) + val hit = drawing.fileHeaderCheckboxHitRect(100, 144, 320, style) + assertTrue(hit.contains(glyph)) + assertTrue(hit.contains(glyph.left - 13f, 101f)) + assertTrue(hit.contains(319f, 143f)) + assertTrue(!hit.contains(glyph.left - 15f, 122f)) + } + @Test fun asciiWidthCacheDoesNotRetainPerRowMeasurementObjects() { val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication()) diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 42403edbb1e7d..38eba55e812ed 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -139,6 +139,8 @@ import { SettingsProjectGroupingRouteScreen } from "./features/settings/Settings import { SettingsProjectOverviewRouteScreen } from "./features/settings/SettingsProjectOverviewRouteScreen"; import { UsageLimitAccountScreen } from "./features/usage/UsageLimitsPooled"; import { UsageRouteScreen } from "./features/usage/UsageRouteScreen"; +import { WorkflowRunRouteScreen } from "./features/workflows/WorkflowRunRouteScreen"; +import { WorkflowStepSheet } from "./features/workflows/WorkflowStepSheet"; import { SettingsAboutRouteScreen } from "./features/settings/SettingsAboutRouteScreen"; import { SettingsNotificationsRouteScreen } from "./features/settings/SettingsNotificationsRouteScreen"; import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen"; @@ -210,6 +212,7 @@ const ROUTE_TITLES: Readonly> = { NewTaskRepositories: msg("Repositories"), AddProject: msg("Add project"), ThreadFiles: msg("Files"), + WorkflowRun: msg("Run", { $context: "noun, page title for one workflow run" }), SettingsLegal: msg("Legal"), ConnectOnboarding: msg("Set up {product}", { product: "T3 Connect" }), Connections: msg("Environments"), @@ -784,6 +787,15 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: ThreadQueueSheet, options: sheetRoute({ detent: 0.65, androidMaxDetent: 0.95 }), }), + WorkflowRun: createNativeStackScreen({ + screen: WorkflowRunRouteScreen, + linking: { path: "workflows/:environmentId/:runId" }, + options: pageRoute(), + }), + WorkflowStep: createNativeStackScreen({ + screen: WorkflowStepSheet, + options: sheetRoute({ detent: 0.6, androidMaxDetent: 0.95 }), + }), ThreadBackgroundWork: createNativeStackScreen({ screen: ThreadBackgroundWorkSheet, options: sheetRoute({ detent: 0.5, androidMaxDetent: 0.9 }), diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx index ba7d9790c4120..95a2d928e4c10 100644 --- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx +++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx @@ -10,6 +10,7 @@ import { Paths } from "expo-file-system"; import { Image, Pressable, ScrollView, View } from "react-native"; import { AppText as Text } from "./ui/AppText"; +import { AppActivityIndicator } from "./ui/AppActivityIndicator"; import { MaterializedPreviewKey, materializedPreviewAtom } from "../lib/composerImagePreview"; import { PierreEntryIcon } from "./PierreEntryIcon"; import { @@ -44,6 +45,8 @@ export interface ComposerAttachmentStripProps { readonly imageSize?: number; readonly imageBorderRadius?: number; readonly removeButtonPlacement?: "overlay" | "gutter"; + /** Pasted images still being prepared, shown as placeholders after the attachments. */ + readonly pendingImageCount?: number; } type ComposerAttachmentThumbnailProps = { @@ -301,7 +304,8 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) { const removeButtonPlacement = props.removeButtonPlacement ?? "overlay"; const removeButtonGutter = removeButtonPlacement === "gutter" ? 10 : 0; - if (props.attachments.length === 0) { + const pendingImageCount = props.pendingImageCount ?? 0; + if (props.attachments.length === 0 && pendingImageCount === 0) { return null; } @@ -353,6 +357,21 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) { ))} + {Array.from({ length: pendingImageCount }, (_, index) => ( + + + + ))} diff --git a/apps/mobile/src/components/ComposerToolbar.tsx b/apps/mobile/src/components/ComposerToolbar.tsx index 0dca70141f23b..902f4b628a6e9 100644 --- a/apps/mobile/src/components/ComposerToolbar.tsx +++ b/apps/mobile/src/components/ComposerToolbar.tsx @@ -378,6 +378,7 @@ export function ComposerToolbarButton(props: { {providerInstanceInitials(props.displayName)} diff --git a/apps/mobile/src/components/ui/FilePreviewModal.android.tsx b/apps/mobile/src/components/ui/FilePreviewModal.android.tsx index 017dbdb1456fb..d9f732853dddd 100644 --- a/apps/mobile/src/components/ui/FilePreviewModal.android.tsx +++ b/apps/mobile/src/components/ui/FilePreviewModal.android.tsx @@ -2,7 +2,7 @@ import { T, useGT } from "gt-react-native"; import { Button } from "./Button"; import * as Dialog from "./Dialog"; -import { createContext, useContext, useEffect, useEffectEvent } from "react"; +import { createContext, useContext, useEffect, useEffectEvent, useRef } from "react"; import { Modal, View } from "react-native"; import ImageViewing from "react-native-image-viewing"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -133,14 +133,23 @@ type ImagePreviewProps = { readonly onRequestClose: () => void; }; -const ImagePreviewContext = createContext(null); +const ImagePreviewContext = createContext< + (ImagePreviewProps & { readonly getSaveImageSignal: () => AbortSignal }) | null +>(null); +// Keyed by page so swiping away clears the busy state and aborts pending share preparation. function ImagePreviewHeader(header: { readonly imageIndex: number }) { + return ; +} + +function ImagePreviewPageHeader(header: { readonly imageIndex: number }) { const props = useContext(ImagePreviewContext)!; const source = props.source.images[header.imageIndex]; const gt = useGT(); const insets = useSafeAreaInsets(); - const mediaActions = useMediaActions(source?.actionsSource, props.onRequestClose); + const mediaActions = useMediaActions(source?.actionsSource, props.onRequestClose, { + getSaveImageSignal: props.getSaveImageSignal, + }); return ( (null); + const getSaveImageSignal = () => { + if (saveController.current === null) { + saveController.current = new AbortController(); + } + return saveController.current.signal; + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- saves survive a page change but stop when the gallery unmounts + useEffect( + () => () => { + saveController.current?.abort(); + saveController.current = null; + }, + [], + ); return ( - + ({ refreshAssetUrl: vi.fn<(environmentId: string, resource: { url: string }) => Promise>(), alert: vi.fn(), + share: vi.fn(), + download: vi.fn(), previews: [] as unknown[], mounts: 0, presentationFinished: false, })); -vi.mock("../../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl })); +vi.mock("../../state/assets", () => ({ + refreshAssetUrl: harness.refreshAssetUrl, + useRefreshAssetUrl: (environmentId: string, resource: { url: string }) => () => + harness.refreshAssetUrl(environmentId, resource), +})); vi.mock("../../lib/localAttachmentPreview", () => ({ loadLocalAttachmentPreview: vi.fn() })); vi.mock("../../lib/attachmentDownload", () => ({ - downloadAndShareAttachment: vi.fn(), + downloadAndShareAttachment: harness.share, + downloadAttachmentForPreview: harness.download, nativeViewerErrorMessage: () => "", shareLocalAttachment: vi.fn(), })); @@ -30,14 +46,46 @@ vi.mock("./Button", () => ({ Button: () => null })); vi.mock("./SheetHeader", () => ({ SheetHeader: () => null })); vi.mock("./AppText", () => ({ AppText: () => null })); vi.mock("../PdfPreview", () => ({ PdfPreview: () => null })); -vi.mock("../MediaPreviewHeader", () => ({ MediaPreviewHeader: () => null })); -vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: [] }) })); -vi.mock("react-native", () => ({ Modal: () => null, View: () => null })); +vi.mock("../MediaPreviewHeader", () => ({ + MediaPreviewHeader: ({ media }: { media: ReturnType }) => + media.actions + .filter(({ id }) => id === "save" || id === "save-image") + .map(({ id, disabled, run, title }) => ( + + )), +})); +vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({ navigate: vi.fn() }) })); +vi.mock("../../state/session", () => ({ + environmentSession: { sessionStateAtom: (environmentId: string) => environmentId }, +})); +const grant = { authenticated: true, scopes: [AuthFilesystemReadScope] }; +vi.mock("../../state/query", () => ({ + useEnvironmentQuery: () => ({ data: grant, error: null }), +})); +vi.mock("../../state/atom-registry", () => ({ + appAtomRegistry: { get: () => AsyncResult.success(grant) }, +})); +vi.mock("expo", () => ({ requireNativeModule: vi.fn() })); +vi.mock("expo-clipboard", () => ({ setStringAsync: vi.fn() })); +vi.mock("expo-haptics", () => ({ notificationAsync: vi.fn() })); +vi.mock("react-native", () => ({ + Modal: () => null, + Platform: { OS: "android", Version: 35 }, + View: ({ children }: { children: ReactNode }) => children, +})); vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0 }) })); vi.mock("react-native-image-viewing", () => ({ default: function ImageViewing(props: { images: readonly { uri?: string }[]; imageIndex: number; + HeaderComponent?: ComponentType<{ imageIndex: number }>; }) { useState(() => harness.mounts++); harness.previews.push({ @@ -45,7 +93,17 @@ vi.mock("react-native-image-viewing", () => ({ images: props.images, selectedIndex: props.imageIndex, }); - return null; + const [index, setIndex] = useState(props.imageIndex); + const Header = props.HeaderComponent; + if (!Header) return null; + return ( + <> +
+ {props.images.map(({ uri }, imageIndex) => ( + + ), +})); +vi.mock("../../components/ui/ScreenContent", () => ({ + ScreenContent: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../native/SelectableMarkdownText", () => ({ SelectableMarkdownText: () => null })); +vi.mock("../../state/environments", () => ({ useEnvironments: () => ({ environments: [] }) })); +vi.mock("../../state/linkedThread", () => ({ + useConnectLinkedEnvironment: () => ({ state: { phase: "idle" } }), + useLinkedThreadView: vi.fn(), +})); +vi.mock("../../state/peerLinks", () => ({ peerLinkEnvironment: {} })); +vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({}) })); +vi.mock("../files/FileMarkdownPreview", () => ({ useMarkdownPreviewStyles: () => ({}) })); +vi.mock("./ReadOnlyComposerBar", () => ({ + ReadOnlyComposerBar: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("./thread-inspector-header", () => ({ ThreadInspectorHeader: () => null })); +vi.mock("./useOpenLinkedThread", () => ({ useOpenLinkedThread: () => undefined })); + +it.effect( + "shows a page error after Load earlier fails on an already disconnected linked chat", + () => + Effect.gen(function* () { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const container = document.createElement("div"); + const root = createRoot(container); + const target = { + viaEnvironmentId: EnvironmentId.make("via"), + environmentId: EnvironmentId.make("linked"), + threadId: v2Projection.thread.id, + label: "Linked test environment", + title: null, + }; + const warning = "Linked test environment is not answering this environment"; + const pageError = "Could not load earlier turns. Try again."; + const loadEarlier = () => + [...container.querySelectorAll("button")].find( + (button) => button.textContent === "Load earlier", + )!; + + try { + const unavailable = { _tag: "PeerLinkThreadReadError", reason: "unreachable" }; + const pages = + yield* Queue.unbounded< + Effect.Effect + >(); + const views = yield* Queue.unbounded(); + yield* followLinkedThread({ + items: Stream.make({ + kind: "snapshot", + snapshotSequence: 1, + projection: v2Projection, + historyCursor: "before-recent", + hasMoreHistory: true, + } as const).pipe(Stream.concat(Stream.fail(unavailable))), + historyPage: () => Queue.take(pages).pipe(Effect.flatten), + }).pipe( + Stream.runForEach((view) => Queue.offer(views, view)), + Effect.forkScoped, + ); + + const renderNext = Effect.gen(function* () { + const view = yield* Queue.take(views); + vi.mocked(useLinkedThreadView).mockReturnValue({ + view, + error: view.error ?? null, + retry() {}, + }); + act(() => root.render()); + }); + + yield* renderNext; // Initial snapshot. + yield* renderNext; // Connection warning. + expect(container.textContent).toContain(warning); + expect(container.textContent).not.toContain(pageError); + + act(() => loadEarlier().click()); + yield* renderNext; + yield* Queue.offer(pages, Effect.fail(unavailable)); + yield* renderNext; + expect(loadEarlier().parentElement?.textContent).toContain(pageError); + expect(container.textContent).toContain(warning); + + act(() => loadEarlier().click()); + yield* renderNext; + expect(container.textContent).not.toContain(pageError); + expect(loadEarlier().disabled).toBe(true); + } finally { + act(() => root.unmount()); + vi.unstubAllGlobals(); + } + }).pipe(Effect.scoped), +); diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx index 0096c9d576a91..7ec2c4dac2cc8 100644 --- a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -286,6 +286,9 @@ export function LinkedThreadView(props: { const scroll = useRef>(null); // Follows new items only while the reader is already at the end. const atEnd = useRef(true); + const showHistoryError = + view !== null && view.thread.historyCursor !== null && view.history.failed; + const lastLayoutHadHistoryError = useRef(false); const working = projection !== null && isLinkedThreadWorking(projection); const connection = useConnectLinkedEnvironment(target); const connectState = connection.state; @@ -334,7 +337,12 @@ export function LinkedThreadView(props: { atEnd.current = contentSize.height - layoutMeasurement.height - contentOffset.y < 80; }} onContentSizeChange={() => { - if (atEnd.current) scroll.current?.scrollToEnd({ animated: false }); + // A page error can resize the top of a short feed whose reader is also near the end. + const historyErrorChanged = lastLayoutHadHistoryError.current !== showHistoryError; + lastLayoutHadHistoryError.current = showHistoryError; + if (atEnd.current && !historyErrorChanged) { + scroll.current?.scrollToEnd({ animated: false }); + } }} > {view === null || projection === null ? ( @@ -351,7 +359,7 @@ export function LinkedThreadView(props: { ) : ( <> {view.thread.historyCursor !== null ? ( - + `).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/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index debd800e57300..14840a8576442 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import { ProviderInstanceId } from "@t3tools/contracts"; import { McpProviderSessions } from "@t3tools/provider-core/server/McpProviderSessions"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { McpServer } from "effect/ai"; @@ -32,6 +33,7 @@ import { PeerLinkRequests } from "../peer/PeerLinkRequests.ts"; import { PeerLinks } from "../peer/PeerLinks.ts"; import { RemoteDelegation } from "../peer/RemoteDelegation.ts"; import { PreviewManager } from "../preview/Manager.ts"; +import { Workflows } from "../workflows/Workflows.ts"; import { PreviewBrowser } from "../preview/PreviewBrowser.ts"; import { ManagedProjectFolders } from "../project/ManagedProjectFolders.ts"; import { ProjectCloneTracker } from "../project/ProjectCloneTracker.ts"; @@ -42,6 +44,8 @@ import { PullRequestReviewGuideService } from "../pullRequest/PullRequestReviewG import { PullRequestService } from "../pullRequest/PullRequestService.ts"; import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts"; import { SecretRequests } from "../secrets/SecretRequests.ts"; +import { FeedbackStore } from "../feedback/FeedbackStore.ts"; +import { AnalyticsService } from "../telemetry/AnalyticsService.ts"; import { ServerSettingsService } from "../serverSettings.ts"; import { SourceControlRepositoryService } from "../sourceControl/SourceControlRepositoryService.ts"; import { GitVcsDriver } from "../vcs/GitVcsDriver.ts"; @@ -57,6 +61,7 @@ import budget from "./agentContextBudget.fork.json" with { type: "json" }; // Registration only stores tool definitions, so the handlers' services are never called. const toolHandlerServices = Layer.mergeAll( + Layer.mock(AnalyticsService)({}), Layer.mock(AssetSigner)({}), Layer.mock(DeviceService)({}), Layer.mock(DocumentText)({}), @@ -74,6 +79,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(PreviewAutomationBroker)({}), Layer.mock(PreviewBrowser)({}), Layer.mock(PreviewManager)({}), + Layer.mock(Workflows)({}), Layer.mock(ProjectCloneTracker)({}), Layer.mock(ProjectService)({}), Layer.mock(ProjectSetupScriptRunner)({}), @@ -85,6 +91,8 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(RemoteDelegation)({}), Layer.mock(ScheduledTaskService)({}), Layer.mock(SecretRequests)({}), + Layer.mock(FeedbackStore)({}), + NodeSqliteClient.layer({ filename: ":memory:" }), ServerConfig.layerTest(process.cwd(), { prefix: "t3-agent-context-budget-" }), Layer.mock(ServerEnvironment)({}), Layer.mock(ServerSecretStore)({}), 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/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.ts index 45ea557b00b5a..5426fa8398242 100644 --- a/apps/server/src/provider/CodexChatGptAuth.test.ts +++ b/apps/server/src/provider/CodexChatGptAuth.test.ts @@ -234,6 +234,7 @@ const makeHarnessFor = Effect.fnUntraced(function* ( ? Effect.die("analytics unavailable") : Effect.sync(() => { analyticsEvents.push({ event, properties }); + return true; }), flush: Effect.void, recordOwners: () => Effect.void, diff --git a/apps/server/src/provider/CodexDeveloperInstructions.ts b/apps/server/src/provider/CodexDeveloperInstructions.ts index 1ac4a78cdef45..1bcb6c115ec38 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.ts @@ -1,3 +1,4 @@ +import type { AgentFeedbackMode } from "@t3tools/contracts"; import type { V2TurnStartParams__AdditionalContextEntry } from "effect-codex-app-server/schema"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; import { esveoAgentText } from "./esveoAgentText.ts"; @@ -39,6 +40,7 @@ const toolInstructions = (availability: boolean | T3CodeToolAvailability): strin }; export interface CodexRuntimeInfo { + readonly agentFeedback?: AgentFeedbackMode; readonly model: string; readonly modelName?: string | undefined; readonly reasoningEffort?: string | undefined; 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 96dd2c5dbaa44..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" }, @@ -435,8 +431,16 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { yield* fileSystem.writeFileString( path.join(input.cwd, ".agents", "skills.json"), JSON.stringify({ + entries: null, + inherits: [{ path: "workspace-skills.json", include_only: null }], + }), + ); + yield* fileSystem.writeFileString( + path.join(input.cwd, "workspace-skills.json"), + JSON.stringify({ + inherits: null, entries: [ - { path: "tools/skills/deploy/SKILL.md" }, + { path: "tools/skills/deploy/SKILL.md", exclude: null }, { path: "tools/skills/internal/SKILL.md", exclude: ["internal"] }, ], }), @@ -444,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 51fd5535c8226..edbe5e34a7343 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -48,14 +48,14 @@ const SkillFrontmatter = Schema.Struct({ const decodeSkillFrontmatter = Schema.decodeUnknownSync(SkillFrontmatter); const SkillConfigEntry = Schema.Struct({ path: Schema.String, - include_only: Schema.optional(Schema.Array(Schema.String)), - exclude: Schema.optional(Schema.Array(Schema.String)), + include_only: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), + exclude: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), }); const decodeSkillsConfig = Schema.decodeUnknownOption( Schema.fromJsonString( Schema.Struct({ - inherits: Schema.optional(Schema.Array(SkillConfigEntry)), - entries: Schema.optional(Schema.Array(SkillConfigEntry)), + inherits: Schema.optional(Schema.NullOr(Schema.Array(SkillConfigEntry))), + entries: Schema.optional(Schema.NullOr(Schema.Array(SkillConfigEntry))), }), ), ); @@ -185,124 +185,36 @@ 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( parent: SkillEntryFilter, - entry: { - readonly include_only?: ReadonlyArray | undefined; - readonly exclude?: ReadonlyArray | undefined; - }, + entry: typeof SkillConfigEntry.Type, ): 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/AntigravityUsage.ts b/apps/server/src/provider/Drivers/AntigravityUsage.ts index 2eb9744a3e42a..087dbb7added8 100644 --- a/apps/server/src/provider/Drivers/AntigravityUsage.ts +++ b/apps/server/src/provider/Drivers/AntigravityUsage.ts @@ -68,7 +68,7 @@ const make = Effect.gen(function* () { }) { const roots: Array = []; for (const instance of instances) roots.push(...(yield* dataRoots(instance.environment))); - for (const { instanceId } of instances.filter((instance) => instance.configured)) { + for (const { instanceId } of instances) { const directories = yield* resolveAntigravityInstanceDirectories( host.paths.stateDir, instanceId, diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts index b6dc61470e497..205f4610759da 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts @@ -1,9 +1,20 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; +import * as FileSystem from "effect/FileSystem"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import * as Effect from "effect/Effect"; -import { ClaudeExecutableFileCheck, resolveClaudeSdkExecutablePath } from "./ClaudeExecutable.ts"; +import { + ClaudeExecutableFileCheck, + claudeProgramReader, + claudeProgramWasReplaced, + resolveClaudeSdkExecutablePath, +} from "./ClaudeExecutable.ts"; const NPM_DIR = "C:\\Users\\dev\\AppData\\Roaming\\npm"; const NPM_SHIM = `${NPM_DIR}\\claude.cmd`; @@ -21,7 +32,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)), ); } @@ -101,3 +112,42 @@ describe("resolveClaudeSdkExecutablePath", () => { }), ); }); + +describe("claudeProgramReader", () => { + /** An install as the Claude installer lays it out: one file per version and a link. */ + const makeInstall = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "claude-program-" }); + const bin = NodePath.join(root, "bin"); + const link = NodePath.join(bin, "claude"); + const version = (name: string) => { + const file = NodePath.join(root, "versions", name); + NodeFS.mkdirSync(NodePath.dirname(file), { recursive: true }); + NodeFS.writeFileSync(file, "#!/bin/sh\n", { mode: 0o755 }); + return file; + }; + NodeFS.mkdirSync(bin); + NodeFS.symlinkSync(version("1.0.0"), link); + return { + bin, + update: () => { + NodeFS.unlinkSync(link); + NodeFS.symlinkSync(version("1.0.1"), link); + }, + }; + }); + + it.effect("follows a bare command name through PATH", () => + Effect.scoped( + Effect.gen(function* () { + const { bin, update } = yield* makeInstall; + const readProgram = yield* claudeProgramReader("claude", { PATH: bin }); + const startedFrom = yield* readProgram; + expect(startedFrom).toBeDefined(); + expect(claudeProgramWasReplaced(startedFrom, yield* readProgram)).toBe(false); + update(); + expect(claudeProgramWasReplaced(startedFrom, yield* readProgram)).toBe(true); + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.ts index 5797066446b99..3de63c9372f4e 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; @@ -71,3 +73,33 @@ export const resolveClaudeSdkExecutablePath = Effect.fn("resolveClaudeSdkExecuta return binaryPath; }, ); + +/** + * Returns an effect reading the real path of the installed Claude binary. + * Updates repoint the installed link to a new version file, so comparing this + * detects when a live CLI process was started from an older version. + */ +export const claudeProgramReader = Effect.fn("claudeProgramReader")(function* ( + binaryPath: string, + environment: NodeJS.ProcessEnv, +): Effect.fn.Return> { + const platform = yield* HostProcess.Platform; + const resolveExecutable = yield* SpawnExecutableResolution; + return Effect.promise(async () => { + try { + const resolved = await resolveExecutable(binaryPath, platform, environment); + return resolved === undefined ? undefined : await NodeFS.promises.realpath(resolved); + } catch { + return undefined; + } + }); +}); + +/** + * Reports whether an update replaced the program a live CLI process started + * from. An unreadable path on either side reports no update. + */ +export const claudeProgramWasReplaced = ( + startedFrom: string | undefined, + now: string | undefined, +): boolean => startedFrom !== undefined && now !== undefined && startedFrom !== now; diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts index d0def84f1efe0..88e076d98f208 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts @@ -383,6 +383,9 @@ describe("readAntigravityUsage", () => { "gemini-3-flash-agent", "gemini-3-flash", "gemini-default", + "gemini-pro-orchestrator-neon", + "gemini-4-hydrogen-orchestrator", + "gemini-pro-orchestrator-g1-pro", ].entries()) { yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [ idx, @@ -393,6 +396,11 @@ describe("readAntigravityUsage", () => { new Uint8Array(protoBytes(9, protoNumber(2, 10 + idx))), ]); } + // Orchestrator (Neon), MODEL_PLACEHOLDER_M537, with no name in the metadata. + yield* db.run("INSERT INTO steps VALUES (?, ?)", [ + 20, + new Uint8Array(protoBytes(9, [...protoNumber(1, 1537), ...protoNumber(2, 30)])), + ]); }), ); const result = yield* readAntigravityUsage(dir, 0); @@ -405,6 +413,10 @@ describe("readAntigravityUsage", () => { ["gemini-3-flash-agent", "gemini-3.5-flash"], ["gemini-3-flash", "gemini-3-flash-preview"], ["gemini-default", undefined], + ["gemini-pro-orchestrator-neon", "gemini-4-neon"], + ["gemini-4-hydrogen-orchestrator", "gemini-4-hydrogen"], + ["gemini-pro-orchestrator-g1-pro", "gemini-4-argon"], + ["gemini-pro-orchestrator-neon", "gemini-4-neon"], ], ); }).pipe(Effect.provide(NodeServices.layer)), diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index 4a71c8ed2b056..5dff65928ad24 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -126,18 +126,26 @@ const MODEL_IDS: Record = { 1417: "gemini-4-argon", 1418: "gemini-4-argon", 1419: "gemini-4-argon", + 1537: "gemini-pro-orchestrator-neon", }; // Effort and routing variants share the base model's price. export const antigravityRateModel = (model: string) => { - const base = model.replace(/-(?:extra-low|low|medium|high|tiered|control|thinking|agent)$/, ""); + const base = model.replace( + /-(?:extra-low|low|medium|high|tiered|control|thinking|agent|orchestrator)$/, + "", + ); return /^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(model) ? "gemini-3.5-flash" : model === "gemini-3.7-flash-safety-le" ? "gemini-3.7-flash" - : base === "gemini-3-flash" - ? "gemini-3-flash-preview" - : base; + : model === "gemini-pro-orchestrator-neon" + ? "gemini-4-neon" + : model === "gemini-pro-orchestrator-g1-pro" + ? "gemini-4-argon" + : base === "gemini-3-flash" + ? "gemini-3-flash-preview" + : base; }; function withRateModel(record: UsageRecord): UsageRecord { diff --git a/apps/server/src/provider/Drivers/codexUsage.test.ts b/apps/server/src/provider/Drivers/codexUsage.test.ts index 1cdbe05d07669..2326b6749f4a6 100644 --- a/apps/server/src/provider/Drivers/codexUsage.test.ts +++ b/apps/server/src/provider/Drivers/codexUsage.test.ts @@ -98,7 +98,7 @@ describe("parseCodexLine", () => { parseCodexLine(line.replace("2026-08-01T05:17:49.919Z", "invalid"), cumulativeState), ).toBeNull(); expect(parseCodexLine(line, cumulativeState)?.totals.outputTokens).toBe(20); - expect(codexUsageFormat.readMalformedRecords?.(cumulativeState)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(cumulativeState).length).toBe(0); }); it("ignores stale changed requests but counts equal requests when totals advance across contexts", () => { @@ -141,7 +141,7 @@ describe("parseCodexLine", () => { totals: { uncachedInputTokens: 100, outputTokens: 20 }, }); } - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }); it.each([false, true])( @@ -160,7 +160,7 @@ describe("parseCodexLine", () => { expect( parseCodexLine(counted(counters(10, 2), counters(130, 27)), state)?.totals.outputTokens, ).toBe(2); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }, ); @@ -187,10 +187,10 @@ describe("parseCodexLine", () => { total[field] += 1; if (field === "input_tokens" || field === "output_tokens") total.total_tokens += 1; expect(parseCodexLine(counted(request, total), state), field).toBeNull(); - expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length, field).toBe(1); for (const key of fields) total[key] += request[key]; expect(parseCodexLine(counted(request, total), state)?.totals.outputTokens, field).toBe(20); - expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length, field).toBe(1); } }); @@ -250,7 +250,7 @@ describe("parseCodexLine", () => { state, )?.totals.outputTokens, ).toBe(2); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }, ); @@ -307,7 +307,7 @@ describe("parseCodexLine", () => { reasoning_output_tokens: 5, }; expect(parseCodexLine(counted(request, cumulative), state)).toBeNull(); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(1); expect(state.lastCumulativeUsage).toEqual(cumulative); }); @@ -327,14 +327,14 @@ describe("parseCodexLine", () => { state, ), ).toBeNull(); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(1); expect( parseCodexLine( counted(request, malformed === "request" ? counters(300, 60) : counters(200, 40)), state, )?.totals.outputTokens, ).toBe(20); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(1); }); it("bills only the reported request when usage records sit between reconciling snapshots", () => { @@ -520,7 +520,7 @@ describe("parseCodexLine", () => { parseCodexLine(counted(counters(10, 2), { ...counters(10, 2), total_tokens: 1012 }), state) ?.totals.outputTokens, ).toBe(2); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }); it.each([false, true])( @@ -536,7 +536,7 @@ describe("parseCodexLine", () => { expect( parseCodexLine(counted(counters(30, 5), counters(30, 5)), state)?.totals.outputTokens, ).toBe(5); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }, ); @@ -550,7 +550,7 @@ describe("parseCodexLine", () => { expect( parseCodexLine(counted(counters(10, 2), counters(40, 7)), state)?.totals.outputTokens, ).toBe(2); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }); const later = (line: string) => line.replace("05:17:49.919Z", "07:17:49.919Z"); @@ -583,7 +583,10 @@ describe("parseCodexLine", () => { return record === null ? 0 : totalTokens(record.totals); }); - expect({ processed: billed, skipped: codexUsageFormat.readMalformedRecords?.(state) }).toEqual({ + expect({ + processed: billed, + skipped: codexUsageFormat.readMalformedRecords?.(state).length, + }).toEqual({ processed, skipped, }); @@ -675,7 +678,10 @@ describe("parseCodexLine", () => { return record === null ? 0 : totalTokens(record.totals); }); - expect({ processed: billed, skipped: codexUsageFormat.readMalformedRecords?.(state) }).toEqual({ + expect({ + processed: billed, + skipped: codexUsageFormat.readMalformedRecords?.(state).length, + }).toEqual({ processed, skipped, }); @@ -697,7 +703,7 @@ describe("parseCodexLine", () => { expect({ processed, - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed: [120, 120, 0, 120], skipped: 0 }); }); @@ -715,7 +721,7 @@ describe("parseCodexLine", () => { const record = parseCodexLine(line, state); return record === null ? 0 : totalTokens(record.totals); }); - expect({ processed, skipped: codexUsageFormat.readMalformedRecords?.(state) }).toEqual({ + expect({ processed, skipped: codexUsageFormat.readMalformedRecords?.(state).length }).toEqual({ processed: [120, 120, 120, 35], skipped: 0, }); @@ -756,7 +762,7 @@ describe("parseCodexLine", () => { expect({ processed: billed, - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed, skipped: 0 }); }, ); @@ -777,7 +783,7 @@ describe("parseCodexLine", () => { expect({ processed, - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed: [120, 0, 120, 35], skipped: 1 }); }); @@ -917,7 +923,7 @@ describe("parseCodexLine", () => { state, ); expect(next).not.toBeNull(); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }); it("recognizes subagent spawns without forked_from_id", () => { @@ -968,7 +974,7 @@ describe("parseCodexLine", () => { expect({ processed: [first, copied, afterBurst, next], - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed: [120, 0, 120, 35], skipped: 0 }); }); @@ -989,7 +995,7 @@ describe("parseCodexLine", () => { expect({ processed: billed.map((record) => totalTokens(record.totals)), - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed: [160, 230], skipped: 0 }); }); }); diff --git a/apps/server/src/provider/Drivers/codexUsage.ts b/apps/server/src/provider/Drivers/codexUsage.ts index a2977d3080fee..7fafc555aac56 100644 --- a/apps/server/src/provider/Drivers/codexUsage.ts +++ b/apps/server/src/provider/Drivers/codexUsage.ts @@ -148,6 +148,9 @@ export const CodexScanState = Schema.Struct({ ), requestLedgerActive: Schema.mutableKey(Schema.optionalKey(Schema.Boolean)), malformedRecords: Schema.mutableKey(TokenCount), + malformedRecordTimestamps: Schema.mutableKey( + Schema.optionalKey(Schema.mutable(Schema.Array(Schema.Finite))), + ), sawSessionMeta: Schema.mutableKey(Schema.Boolean), modelProvider: Schema.mutableKey(Schema.String), turnId: Schema.mutableKey(Schema.String), @@ -331,7 +334,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag // A valid snapshot remains the next baseline even when its paired request is malformed. if (cumulative !== null) rebaseCodexUsage(state, cumulative, timestampMs); if (last === null || (hasCumulative && cumulative === null)) { - state.malformedRecords += 1; + noteMalformedRecord(state, timestampMs); return []; } @@ -351,7 +354,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag } if (last.total_tokens !== last.input_tokens + last.output_tokens) { - state.malformedRecords += 1; + noteMalformedRecord(state, timestampMs); return []; } @@ -397,12 +400,12 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag state.lastCumulativeUsage = previous; if (pending !== undefined) state.unreportedRequests = pending; } - state.malformedRecords += 1; + noteMalformedRecord(state, timestampMs); return []; } unreported = bridged; } else if (!restarted && rewound) { - state.malformedRecords += discardedRequests(pending, last); + noteMalformedRecord(state, timestampMs, discardedRequests(pending, last)); } if (restarted) state.sequenceStartSignature = sequenceStart; } else { @@ -410,7 +413,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag // Advance expected totals for billed legacy requests so a cumulative re-emission is stale. const advanced = advanceCodexUsage(previous, last); if (advanced === null) { - state.malformedRecords += 1; + noteMalformedRecord(state, timestampMs); return []; } state.lastCumulativeUsage = advanced; @@ -424,6 +427,12 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag ]; } +function noteMalformedRecord(state: CodexScanState, timestampMs: number, count = 1) { + state.malformedRecords += count; + const timestamps = (state.malformedRecordTimestamps ??= []); + for (let index = 0; index < count; index++) timestamps.push(timestampMs); +} + function codexAttribution(state: CodexScanState, timestampMs: number): CodexRequestAttribution { return { timestampMs, @@ -509,7 +518,7 @@ export const codexUsageFormat: TranscriptUsageFormat = { parseLine: parseCodexLine, parseProjected: parseCodexRecord, state: { initial: initialCodexScanState, schema: CodexScanState }, - readMalformedRecords: (state) => state.malformedRecords, + readMalformedRecords: (state) => state.malformedRecordTimestamps ?? [], // A rollout that moved after it was read leaves a copy in both places. sharedSessionsAcrossFiles: true, }; diff --git a/apps/server/src/provider/ProviderInstanceRegistry.test.ts b/apps/server/src/provider/ProviderInstanceRegistry.test.ts index ce6416332bae0..94c5f3f8c3cfd 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.test.ts @@ -347,6 +347,41 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect.each([{ displayName: "Renamed" }, { accentColor: "#ff0000" }])( + "keeps the live instance when only %o changes", + (presentation) => + Effect.gen(function* () { + let closed = 0; + const driver: typeof CodexDriver = { + ...CodexDriver, + create: (input) => + Effect.gen(function* () { + const instance = yield* CodexDriver.create(input); + yield* Effect.addFinalizer(() => Effect.sync(() => closed++)); + return instance; + }), + }; + const instanceId = ProviderInstanceId.make("account-a"); + const entry = { + driver: CodexDriver.driverKind, + enabled: false, + displayName: "Account A", + config: makeCodexConfig({}), + }; + const { registry, mutator } = yield* makeProviderInstanceRegistry({ + drivers: [driver], + configMap: { [instanceId]: entry }, + }); + const instance = yield* registry.getInstance(instanceId); + const changes = yield* registry.subscribeChanges; + yield* mutator.reconcile({ [instanceId]: { ...entry, ...presentation } }); + expect(closed).toBe(0); + expect(yield* registry.getInstance(instanceId)).toBe(instance); + yield* PubSub.take(changes); + expect(yield* instance!.snapshot.getSnapshot).toMatchObject(presentation); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("treats an explicit in-config enabled:false as disabling despite the envelope", () => Effect.gen(function* () { const staleId = ProviderInstanceId.make("codex_stale"); diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.ts index 9ab3f56aedcd5..f343093d7c9ef 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.ts @@ -55,6 +55,7 @@ interface LiveEntry { readonly scope: Scope.Closeable; readonly entry: ProviderInstanceConfig; readonly secrets: InstanceSecrets; + readonly setPresentation: (entry: ProviderInstanceConfig) => void; } interface RegistryState { @@ -69,6 +70,55 @@ interface RegistryState { const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean => Equal.equals(a, b); +const withoutPresentation = ({ + displayName: _displayName, + accentColor: _accentColor, + ...runtime +}: ProviderInstanceConfig) => runtime; + +// Display name and accent colour are only labels; changing them must not stop the instance's sessions. +const runtimeEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean => + Equal.equals(withoutPresentation(a), withoutPresentation(b)); + +// Drivers stamp the presentation they were created with into every snapshot, so a renamed +// instance kept live restamps what it reports. +const withLivePresentation = (instance: ProviderInstance, created: ProviderInstanceConfig) => { + let current = created; + const restamp = (snapshot: S): S => { + const next: { -readonly [K in keyof S]: S[K] } = { ...snapshot }; + for (const key of ["displayName", "accentColor"] as const) { + const value = current[key]; + if (value === created[key]) continue; + if (value) next[key] = value; + else delete next[key]; + } + return next; + }; + const { snapshot, snapshotForCwd } = instance; + const wrapped: ProviderInstance = { + ...instance, + get displayName() { + return current.displayName; + }, + get accentColor() { + return current.accentColor; + }, + snapshot: { + ...snapshot, + getSnapshot: Effect.suspend(() => snapshot.getSnapshot).pipe(Effect.map(restamp)), + refresh: Effect.suspend(() => snapshot.refresh).pipe(Effect.map(restamp)), + streamChanges: Stream.suspend(() => snapshot.streamChanges).pipe(Stream.map(restamp)), + }, + ...(snapshotForCwd + ? { snapshotForCwd: (cwd: string) => snapshotForCwd(cwd).pipe(Effect.map(restamp)) } + : {}), + }; + const setPresentation = (entry: ProviderInstanceConfig) => { + current = entry; + }; + return { instance: wrapped, setPresentation }; +}; + const secretReferencesIn = (environment: ProviderInstanceEnvironment): Array => environment.flatMap((variable) => (typeof variable.value === "string" ? [] : [variable.value])); @@ -350,14 +400,10 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* (input: { const nextEntry = configMap[instanceId]; if ( rebuild.has(instanceId) || - (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) + (nextEntry !== undefined && !runtimeEqual(live.entry, nextEntry)) ) { replacedIds.add(instanceId); } @@ -440,6 +486,7 @@ const makeReconcile = (input: { const builtUnavailable = new Map(); const builtSecretsUnreadable = new Map(); let orderChanged = false; + let presentationChanged = false; const previousOrder = [...previousEntries.keys()]; const nextOrder: Array = []; @@ -449,7 +496,13 @@ const makeReconcile = (input: { const existing = previousEntries.get(instanceId); if (existing !== undefined && !replacedIds.has(instanceId)) { - builtEntries.set(instanceId, existing); + if (entryEqual(existing.entry, entry)) { + builtEntries.set(instanceId, existing); + } else { + existing.setPresentation(entry); + builtEntries.set(instanceId, { ...existing, entry }); + presentationChanged = true; + } continue; } const parked = parkedSnapshot(instanceId, entry); @@ -489,6 +542,7 @@ const makeReconcile = (input: { } const entriesChanged = + presentationChanged || orderChanged || removedIds.length > 0 || replacedIds.size > 0 || diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index e4ec16b77dde0..4fe6da7f791a9 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -20,6 +20,7 @@ import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Option from "effect/Option"; import * as Scope from "effect/Scope"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; @@ -565,6 +566,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 +2568,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 +2660,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 +2671,91 @@ 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("publishes a new label for an instance the registry kept live", () => + Effect.gen(function* () { + const driver = ProviderDriverKind.make("antigravity"); + const instanceId = ProviderInstanceId.make("account-a"); + let displayName = "Account A"; + const instance: ProviderInstance = { + instanceId, + driverKind: driver, + continuationIdentity: { driverKind: driver, continuationKey: "antigravity:account-a" }, + get displayName() { + return displayName; + }, + enabled: true, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: driver, + packageName: null, + }), + ), + getSnapshot: Effect.sync(() => ({ + instanceId, + driver, + displayName, + status: "ready" as const, + enabled: true, + installed: true, + auth: { status: "authenticated" as const }, + checkedAt: "1970-01-01T00:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + })), + refresh: Effect.die("unused"), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + }; + const changes = yield* PubSub.unbounded(); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const services = yield* Layer.build( + ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), + Layer.provideMerge( + Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, { + getInstance: () => Effect.succeed(instance), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.fromPubSub(changes), + subscribeChanges: PubSub.subscribe(changes), + }), + ), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-label-" }), + ), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ).pipe(Scope.provide(scope)); + const registry = yield* ProviderRegistry.ProviderRegistry.pipe(Effect.provide(services)); + const relabelled = yield* registry.streamChanges.pipe( + Stream.filter((providers) => providers[0]?.displayName === "Account B"), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + displayName = "Account B"; + yield* PubSub.publish(changes, undefined); + assert.isTrue(Option.isSome(yield* Fiber.join(relabelled))); + }), ); 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..172599fd29c88 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( @@ -1035,6 +1050,27 @@ export const layer = Layer.effect( }).pipe(Effect.ignoreCause({ log: true })), { concurrency: "unbounded", discard: true }, ); + // A rename keeps the instance live, so its new label only arrives from a fresh read. + const published = new Map( + (yield* Ref.get(providersRef)).map((provider) => [provider.instanceId, provider]), + ); + yield* Effect.forEach( + carriedOver.values(), + (instance) => + Effect.gen(function* () { + // Its first check publishes the new label anyway; the placeholder must not replace the cache. + if (yield* instance.snapshot.isAwaitingFirstCheck ?? Effect.succeed(false)) return; + const provider = yield* instance.snapshot.getSnapshot; + const previous = published.get(instance.instanceId); + if ( + previous?.displayName !== provider.displayName || + previous?.accentColor !== provider.accentColor + ) { + yield* syncProvider(provider); + } + }).pipe(Effect.ignoreCause({ log: true })), + { concurrency: "unbounded", discard: true }, + ); yield* upsertProviders(unavailableProviders, { persist: false, replace: true, 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..a68c1334c473f 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", () => { @@ -467,29 +508,31 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => { }), ); - it.effect("sends supported audio files as native audio content", () => - Effect.gen(function* () { - const fixture = yield* makeAttachmentFixture(); - const audioAttachment = { - ...textAttachment, - id: "recording-1", - name: "recording.wav", - mimeType: "audio/wav", - } satisfies ChatAttachment; - const bytes = Buffer.from("RIFF....WAVEfmt ", "latin1"); - yield* fixture.write(audioAttachment, bytes); - const prompt = yield* buildAntigravityPrompt({ - input: "Transcribe this.", - attachments: [audioAttachment], - resolveAttachmentPath: fixture.resolve, - promptCapabilities: { image: true, audio: true, embeddedContext: true }, - }); + it.effect.each(["audio/wav", "audio/wav;codecs=1", "Audio/WAV \t; codecs=1"])( + "sends supported audio files as native audio content (%s)", + (mimeType) => + Effect.gen(function* () { + const fixture = yield* makeAttachmentFixture(); + const audioAttachment = { + ...textAttachment, + id: "recording-1", + name: "recording.wav", + mimeType, + } satisfies ChatAttachment; + const bytes = Buffer.from("RIFF....WAVEfmt ", "latin1"); + yield* fixture.write(audioAttachment, bytes); + const prompt = yield* buildAntigravityPrompt({ + input: "Transcribe this.", + attachments: [audioAttachment], + resolveAttachmentPath: fixture.resolve, + promptCapabilities: { image: true, audio: true, embeddedContext: true }, + }); - expect(prompt).toEqual([ - { type: "text", text: "Transcribe this." }, - { type: "audio", data: bytes.toString("base64"), mimeType: "audio/wav" }, - ]); - }), + expect(prompt).toEqual([ + { type: "text", text: "Transcribe this." }, + { type: "audio", data: bytes.toString("base64"), mimeType: "audio/wav" }, + ]); + }), ); it.effect.each([{ image: true }])( diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 7434e23b5eda9..f16c143cc278c 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`. */ @@ -399,7 +428,7 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi "source" in attachment && attachment.source?._tag === "pasted-text"; // The text already carries the path; keep folded pastes lazy so agents can search without embedding the whole file. - const mimeType = attachment.mimeType.toLowerCase().split(";", 1)[0] ?? ""; + const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? ""; const image = attachment.type === "image" && IMAGE_MIME_TYPES.has(mimeType); const audio = attachment.type === "file" && AUDIO_MIME_TYPES.has(mimeType); const pdf = attachment.type === "file" && mimeType === "application/pdf"; diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.ts index cfe47280fc4f1..d86ca3ead0f3c 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts @@ -253,17 +253,23 @@ describe("Antigravity permissions and questions", () => { }); it("bounds question text without changing choice IDs", () => { + const title = "Q".repeat(7_994) + "🧪"; + const label = "O".repeat(506) + "🧪"; const request = { ...questionRequest, - toolCall: { ...questionRequest.toolCall, title: "Question ".repeat(2_000) }, + toolCall: { ...questionRequest.toolCall, title: title + "🚀 continued" }, options: [ - { optionId: "stable-choice", name: "Choice ".repeat(2_000), kind: "allow_once" as const }, + { optionId: "stable-choice", name: label + "🚀 continued", kind: "allow_once" as const }, ], }; const question = extractAntigravityUserInputQuestion(request); - expect(question?.question.length).toBeLessThanOrEqual(8_000); - expect(question?.options[0]?.label.length).toBeLessThanOrEqual(512); - expect(question?.options[0]?.value).toBe("stable-choice"); + expect(question?.question).toBe(title + "..."); + expect(question?.options).toEqual([ + { value: "stable-choice", label: label + "...", description: label + "..." }, + ]); + expect( + makeAntigravityUserInputResponse(request, { interaction_9960062f: label + "..." }), + ).toEqual({ outcome: { outcome: "selected", optionId: "stable-choice" } }); }); }); @@ -535,24 +541,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..008579d087f05 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({ @@ -54,6 +55,12 @@ const ANTIGRAVITY_SCHEDULE_TITLES = new Set(["Run schedule", "Running schedule"] */ export function antigravityToolOutlivesPrompt(toolCall: AcpToolCallState): boolean { if (toolCall.title !== undefined && ANTIGRAVITY_SCHEDULE_TITLES.has(toolCall.title)) return true; + return antigravityCommandOutlivesPrompt(toolCall); +} + +/** A non-daemon command the agent awaits; unlike a schedule, it reports progress while it runs. */ +export function antigravityCommandOutlivesPrompt(toolCall: AcpToolCallState): boolean { + if (toolCall.title !== undefined && ANTIGRAVITY_SCHEDULE_TITLES.has(toolCall.title)) return false; const input = toolCall.data.rawInput; return toolCall.kind === "execute" && !(Predicate.isObject(input) && input.IsDaemon === true); } @@ -118,11 +125,14 @@ function copyBoundedText(text: string): string { return Buffer.from(text, "utf16le").toString("utf16le"); } +function boundQuestionText(text: string, limit: number): string { + if (text.length <= limit) return text; + const prefix = text.slice(0, limit - 3).replace(/[\uD800-\uDBFF]$/u, ""); + return copyBoundedText(`${prefix}...`); +} + function questionLabel(option: EffectAcpSchema.PermissionOption): string { - const label = option.name.trim() || option.optionId; - return label.length > QUESTION_LABEL_LIMIT - ? copyBoundedText(`${label.slice(0, QUESTION_LABEL_LIMIT - 3)}...`) - : label; + return boundQuestionText(option.name.trim() || option.optionId, QUESTION_LABEL_LIMIT); } export function extractAntigravityUserInputQuestion( @@ -142,10 +152,7 @@ export function extractAntigravityUserInputQuestion( return { id: request.toolCall.toolCallId, header: "Question", - question: - question.length > TOOL_TEXT_LIMIT - ? copyBoundedText(`${question.slice(0, TOOL_TEXT_LIMIT - 3)}...`) - : question, + question: boundQuestionText(question, TOOL_TEXT_LIMIT), multiSelect: false, allowCustomAnswer: false, options: request.options.map((option) => ({ @@ -194,11 +201,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 +248,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 +491,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/acp/AntigravityTurnOutcome.test.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts index b6094e638285d..962da73bfc2bd 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts @@ -30,9 +30,19 @@ const QUOTA_ERROR = errorPayload( const RATE_LIMIT_ERROR = errorPayload( "Error 429, Message: Resource has been exhausted (e.g. check quota)., Status: RESOURCE_EXHAUSTED, Details: [map[@type:type.googleapis.com/google.rpc.ErrorInfo domain:cloudcode-pa.googleapis.com reason:RATE_LIMIT_EXCEEDED] map[@type:type.googleapis.com/google.rpc.RetryInfo retryDelay:42s]]", ); +const RETIRED_QUOTA_ERROR = errorPayload( + "Error 429, Message: Quota exhausted for test model., Status: RESOURCE_EXHAUSTED, Details: [map[@type:type.googleapis.com/google.rpc.ErrorInfo domain:googleapis.com metadata:map[quotaResetDelay:3600s quotaResetTimeStamp:2026-11-09T01:05:00Z] reason:QUOTA_EXHAUSTED]]", +); const INVALID_ARGUMENT_ERROR = errorPayload( "Error 400, Message: Request contains an invalid argument., Status: INVALID_ARGUMENT, Details: []", ); +// The harness renders a gateway failure with its HTTP status line in place of a gRPC status. +const BAD_GATEWAY_ERROR = Buffer.concat([ + errorPayload( + "Error 502, Message: Bad Gateway: Failed to connect to backend API, Status: 502 Bad Gateway, Details: []", + ), + Buffer.from("\nThe model is currently unreachable."), +]); // Vertex Claude rejects a resumed history whose saved thinking block lost its signature. const MISSING_SIGNATURE_ERROR = errorPayload( 'Error 400, Message: {"type":"error","error":{"type":"invalid_request_error","message":"messages.1.content.0.thinking.signature: Field required"},"request_id":"req_vrtx_test"}, Status: INVALID_ARGUMENT, Details: []', @@ -82,11 +92,12 @@ describe("watchAntigravityPromptOutcome", () => { const turn = ( steps: ReadonlyArray, result: EffectAcpSchema.PromptResponse = { stopReason: "end_turn" }, + options?: { readonly retired?: boolean }, ) => Effect.gen(function* () { const check = yield* watchAntigravityPromptOutcome(profileDirectory, sessionId); appendSteps(steps); - return yield* check(result); + return yield* check(result, options); }); const input = Buffer.from("Run the fixture."); const reply = Buffer.from("FIXTURE_OK"); @@ -149,6 +160,40 @@ describe("watchAntigravityPromptOutcome", () => { retryable: false, }), ); + assert.deepInclude( + (yield* turn([ + [USER_INPUT, input], + [ERROR_MESSAGE, BAD_GATEWAY_ERROR], + ]))?.failure, + { + class: "provider_error", + message: "Bad Gateway: Failed to connect to backend API", + retryable: true, + }, + ); + // A prompt the watchdog retired keeps an absolute reset time but drops a relative one. + assert.deepEqual( + (yield* turn( + [ + [USER_INPUT, input], + [ERROR_MESSAGE, RATE_LIMIT_ERROR], + ], + undefined, + { retired: true }, + ))?.failure.resetAt, + undefined, + ); + assert.equal( + (yield* turn( + [ + [USER_INPUT, input], + [ERROR_MESSAGE, RETIRED_QUOTA_ERROR], + ], + undefined, + { retired: true }, + ))?.failure.resetAt, + "2026-11-09T01:05:00.000Z", + ); // A 404 after the turn already reached the model is a transient edge error, not a bad model. for (const error of [NOT_FOUND_ERROR, STATUS_NOT_FOUND_ERROR]) { assert.deepEqual( diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts index 32eee40f008ae..35ed2f347df1d 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts @@ -20,7 +20,10 @@ const PLANNER_RESPONSE_STEP_TYPE = 15; // The harness error text leads the payload; a Go stack trace follows it. const MAX_ERROR_PAYLOAD_BYTES = 16_384; // The Go harness's rendering of a Google API error, as the agent's api_errors.py reads it. -const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s; +// Status is a gRPC code, or an HTTP status line such as "502 Bad Gateway". A message +// stops at the next error, so each start scans its own span and the match stays linear. +const API_ERROR = + /Error (\d{3}), Message: ((?:(?!, Status: |Error \d{3}, Message: ).)+), Status: ([A-Z_]+|\d{3}[^,\n]*)/s; // Antigravity 1.5 with a Google account writes "STATUS (code NNN): message". const STATUS_ERROR = /(? undefined), ) : undefined; - return turnFailure(result.stopReason, step, yield* DateTime.now); + // A retired prompt's check runs long after the error, so a relative delay has no anchor. + const now = options?.retired === true ? undefined : yield* DateTime.now; + return turnFailure(result.stopReason, step, now); }); }); diff --git a/apps/server/src/provider/agentContextBudget.fork.json b/apps/server/src/provider/agentContextBudget.fork.json index acee62d40446e..9036b0be8951e 100644 --- a/apps/server/src/provider/agentContextBudget.fork.json +++ b/apps/server/src/provider/agentContextBudget.fork.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6419, "codexAdditionalContextBytes": 7819, - "mcpToolListJsonBytes": 67725 + "mcpToolListJsonBytes": 70423 } diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index e089e5a84218a..169fac6ce2a85 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59026 + "mcpToolListJsonBytes": 61724 } diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 9cec14dadd67e..0acffd168c07d 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,11 +440,37 @@ 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, + hiddenText: false, + uc: 1, + font: 0, + fontTable: false, + decoder: new TextDecoder("windows-1252"), + }; const stack: Array = []; - const hidden = () => state.skip || state.deleted; + // 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 || state.hiddenText; const symbols = new Map([ ["endash", "–"], ["emdash", characterEntities.mdash], @@ -454,7 +504,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 +539,22 @@ 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 === "v") state.hiddenText = value !== 0; + else if (control === "plain") { + state.deleted = false; + state.hiddenText = false; + state.font = defaultFont; + } if (control === "mac" || (control === "ansicpg" && value === 10000)) state.decoder = new TextDecoder("macintosh"); else if (control === "ansicpg") { @@ -524,9 +588,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 +619,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 +638,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 +773,16 @@ async function* document(path: string, extension: string): AsyncGenerator { String.raw`{\rtf1\ansi\trowd\cellx1000\cellx2000\intbl A\deleted\cell\deleted0 B\cell\deleted\row\deleted0 C\cell}`, "A\tB\t\nC", ], + [ + "hidden text", + String.raw`{\rtf1\ansi A {\v B{\v0 C}D} E\v F\v0 G\v1 H\plain I}`, + "A C E G I", + ], + [ + "hidden text table and escapes", + String.raw`{\rtf1\ansi\trowd\cellx1000\cellx2000\intbl A\v B\u945?\'e9\cell\v0 C\cell\v\row\v0 D\cell}`, + "A\tC\t\nD", + ], [ "document breaks", String.raw`{\rtf1\ansi\sectd\cols2\pard North quota: 120\column South quota: 240\page East quota: 360\sect\sectd\pard West quota: 480\par}`, @@ -344,6 +354,17 @@ describe("question answer paths", () => { 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 +595,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 +799,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 +818,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 +1021,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 +1033,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 +1105,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 +1171,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/Schedule.ts b/apps/server/src/scheduledTasks/Schedule.ts index f8fb648aaaaa9..ec1f3c2adbd97 100644 --- a/apps/server/src/scheduledTasks/Schedule.ts +++ b/apps/server/src/scheduledTasks/Schedule.ts @@ -4,7 +4,7 @@ import * as Option from "effect/Option"; const MINUTE_MS = 60_000; -function parseTimeOfDay(value: string): { hour: number; minute: number } | null { +export function parseTimeOfDay(value: string): { hour: number; minute: number } | null { const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(value.trim()); if (!match) return null; return { hour: Number(match[1]), minute: Number(match[2]) }; diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index c7072d3e53e4c..8cafad8931249 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"; @@ -98,6 +99,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; @@ -1964,7 +1972,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 @@ -2653,7 +2661,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/scheduledTasks/webhookRoute.test.ts b/apps/server/src/scheduledTasks/webhookRoute.test.ts index ace3d93b9ac39..7fb2552a56074 100644 --- a/apps/server/src/scheduledTasks/webhookRoute.test.ts +++ b/apps/server/src/scheduledTasks/webhookRoute.test.ts @@ -31,6 +31,8 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as RelayDeliveryProof from "./RelayDeliveryProof.ts"; import { WEBHOOK_MAX_BODY_BYTES } from "./webhookRoute.ts"; import * as WebhookRoute from "./webhookRoute.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as Workflows from "../workflows/Workflows.ts"; class WebhookTestApi extends HttpApi.make("environment").add(EnvironmentHttpApi.groups.webhooks) {} @@ -70,6 +72,15 @@ const relayProof = Effect.fn("relayProof")(function* (claims: { }).pipe(Effect.provide(PlatformNodeCrypto.layerSignature)); }); +const workflowDeliveries: Array[0]> = []; +const hooks = Layer.mock(Workflows.Workflows)({ + deliver: (delivery) => + Effect.sync(() => { + workflowDeliveries.push(delivery); + return delivery.token === "tok" ? Option.some({ runId: "run-1" }) : Option.none(); + }), +}); + const handlerFor = ( trigger: ( request: WebhookTriggerRequest, @@ -81,6 +92,7 @@ const handlerFor = ( Layer.provide(WebhookRoute.layer), Layer.provide(RelayDeliveryProof.layer), Layer.provide(Layer.mock(ScheduledTaskService)({ triggerWebhook: trigger })), + Layer.provide([hooks, ManagedPolicy.layerTest()]), Layer.provide( Layer.mock(ServerSecretStore.ServerSecretStore)({ get: (name) => @@ -114,6 +126,30 @@ const post = ( ) => new Request(`http://env.local${path}`, { method: "POST", body, headers }); describe("webhook route", () => { + it.live("a workflow's hook starts a run and never reaches the scheduled tasks", () => + Effect.gen(function* () { + let tasks = 0; + const { handler, dispose } = handlerFor(() => { + tasks += 1; + return Effect.succeed({ _tag: "not_found" }); + }); + const send = (token: string) => + Effect.promise(() => + handler(post(`/api/hooks/wf-inbound.push/${token}?a=1`, "hello", { "X-Delivery": "d1" })), + ); + const accepted = yield* send("tok"); + expect(accepted.status).toBe(202); + expect(yield* Effect.promise(() => accepted.json())).toEqual({ runId: "run-1" }); + expect((yield* send("wrong")).status).toBe(404); + expect(tasks).toBe(0); + expect(workflowDeliveries[0]).toMatchObject({ + hookId: "wf-inbound.push", + request: { method: "POST", query: "a=1", body: "hello", headers: { "x-delivery": "d1" } }, + }); + yield* Effect.promise(dispose); + }), + ); + it.live("trusts the relay's delivery id and receive time only with its signed proof", () => Effect.gen(function* () { const received: Array = []; diff --git a/apps/server/src/scheduledTasks/webhookRoute.ts b/apps/server/src/scheduledTasks/webhookRoute.ts index a7e0c512cbe41..e1650219eb598 100644 --- a/apps/server/src/scheduledTasks/webhookRoute.ts +++ b/apps/server/src/scheduledTasks/webhookRoute.ts @@ -2,6 +2,7 @@ import { EnvironmentHttpApi } from "@t3tools/contracts"; import * as ByteSize from "effect/ByteSize"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; +import * as Result from "effect/Result"; import * as Tracer from "effect/Tracer"; import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"; import type * as HttpServerRequest from "effect/http/HttpServerRequest"; @@ -11,6 +12,8 @@ import { withRelayClientTracing } from "@t3tools/shared/relayTracing"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import * as Metrics from "../observability/Metrics.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as Workflows from "../workflows/Workflows.ts"; import * as RelayDeliveryProof from "./RelayDeliveryProof.ts"; import * as ScheduledTaskService from "./ScheduledTaskService.ts"; @@ -37,6 +40,8 @@ export const layer = HttpApiBuilder.group( Effect.fnUntraced(function* (handlers) { const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService; const relayDeliveryProof = yield* RelayDeliveryProof.RelayDeliveryProof; + const workflows = yield* Workflows.Workflows; + const managedPolicy = yield* ManagedPolicy.ManagedPolicy; /** * The endpoint is raw so the signature is checked over the exact body * bytes; the service checks the token and signature. @@ -95,6 +100,39 @@ export const layer = HttpApiBuilder.group( const relayParent = Option.isSome(relay) ? HttpTraceContext.fromHeaders(request.headers) : Option.none(); + if (params.hookId.startsWith(Workflows.HOOK_PREFIX)) { + if (ManagedPolicy.deniedBy(managedPolicy, "webhookTasks") !== undefined) { + return json(403, { error: "blocked_by_policy" }, "blocked_by_policy"); + } + // Answered only once the run is stored, so a sender that hears nothing may send again. + const started = yield* workflows + .deliver({ + hookId: params.hookId, + token: params.token, + request: { + method: request.method, + headers, + query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1), + body: new TextDecoder().decode(body.value), + }, + ...(relayDeliveryId ? { deliveryId: `relay:${relayDeliveryId}` } : {}), + }) + .pipe(Effect.result); + if (Result.isFailure(started)) { + if (started.failure._tag === "WorkflowInputError") { + return json( + 400, + { error: "invalid_request", problem: started.failure.problem }, + "invalid", + ); + } + yield* Effect.logWarning("Workflow hook delivery failed", { hookId: params.hookId }); + return json(500, { error: "internal_error" }, "error"); + } + return Option.isNone(started.success) + ? json(404, { error: "hook_not_found" }, "not_found") + : json(202, { runId: started.success.value.runId }, "accepted"); + } const result = yield* scheduledTasks .triggerWebhook({ hookId: params.hookId, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index cdf6569051f21..db067d9c8e582 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -9,6 +9,8 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; import * as DelegatedTaskQuestionReactor from "./orchestration-v2/DelegatedTaskQuestionReactor.ts"; +import * as MilestoneHub from "./milestones/MilestoneHub.ts"; +import * as OrchestrationMilestones from "./milestones/OrchestrationMilestones.ts"; // Effect wraps this raw Node HTTP server after its startup and write-error guards attach. // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; @@ -17,6 +19,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"; @@ -239,6 +242,7 @@ import * as UsageService from "./usage/UsageService.ts"; import * as CodexUsageHistory from "./usage/CodexUsageHistory.ts"; import * as RuntimeLayer from "./orchestration-v2/runtimeLayer.ts"; import * as ThreadViewers from "./orchestration-v2/ThreadViewers.ts"; +import * as WorkflowForge from "./workflows/WorkflowForge.ts"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts"; @@ -650,6 +654,13 @@ const layerTaskFolders = TaskFolders.layer.pipe( ); const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe( + Layer.provide( + WorkflowForge.layer.pipe( + Layer.provide(layerIssueService), + Layer.provide(layerPullRequestService), + Layer.provide(RuntimeLayer.layerProjectService), + ), + ), Layer.provide(UsageLimitSources.layerResetFallback), Layer.provide(layerTaskFolders), Layer.provide(layerScheduledTaskWebhookOrigin), @@ -767,6 +778,11 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( yield* service.start(); }), ).pipe(Layer.provide(DelegatedTaskQuestionReactor.layer), Layer.provide(ProjectionStoreV2.layer)), + Layer.effectDiscard( + Effect.gen(function* () { + yield* (yield* OrchestrationMilestones.OrchestrationMilestones).start(); + }), + ).pipe(Layer.provide(OrchestrationMilestones.layer), Layer.provide(ProjectionStoreV2.layer)), ProviderUsageLimitsIngestion.layer, layerProviderInstallationRefresh, ProviderInstallation.layer, @@ -798,6 +814,8 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( Layer.effectDiscard(ProjectSettingsOverrideSweep.sweep), ).pipe( Layer.provideMerge(layerOrchestrationApplication), + // One hub, which the feeders above and the workflow store inside the runtime publish to. + Layer.provideMerge(MilestoneHub.layer), Layer.provideMerge(layerTaskFolders), Layer.provideMerge(RuntimeLayer.layerEventInfrastructure), Layer.provideMerge(Layer.merge(ProjectStore.layer, ThreadSearch.layer)), @@ -1447,6 +1465,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/serverRuntimeStartup.autoPull.test.ts b/apps/server/src/serverRuntimeStartup.autoPull.test.ts index 563bf47f8ae6f..baf5e11569d9d 100644 --- a/apps/server/src/serverRuntimeStartup.autoPull.test.ts +++ b/apps/server/src/serverRuntimeStartup.autoPull.test.ts @@ -158,7 +158,7 @@ it.effect("parks automatic pull until activation without delaying command readin Effect.onInterrupt(() => Deferred.succeed(statusInterrupted, undefined)), ), }), - Layer.mock(AnalyticsService.AnalyticsService)({ record: () => Effect.void }), + Layer.mock(AnalyticsService.AnalyticsService)({ record: () => Effect.succeed(true) }), // No provider logins or Connect link, so startup records no owners. FileSystem.layerNoop({}), Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }), diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index f837fd8ca9722..5d46c916c3990 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1065,6 +1065,22 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" }).pipe(Effect.provide(layerServerSettings())), ); + it.effect("falls back to the defaults when only a legacy field is rejected", () => + Effect.gen(function* () { + const serverConfig = yield* ServerConfig.ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const serverSettings = yield* ServerSettingsModule.ServerSettingsService; + const raw = '{"agentFeedback":{"mode":"auto"},"providers":1}'; + yield* fileSystem.writeFileString(serverConfig.settingsPath, raw); + + const settings = yield* serverSettings.getSettings; + + assert.equal(settings.agentFeedback.mode, "off"); + assert.isFalse(settings.continueThreadsAfterServerUpdate); + assert.equal(yield* fileSystem.readFileString(serverConfig.settingsPath), raw); + }).pipe(Effect.provide(layerServerSettings())), + ); + it.effect("keeps a default-off provider's new instance disabled and sparse on disk", () => Effect.gen(function* () { const serverConfig = yield* ServerConfig.ServerConfig; diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index d4ddfd8b5c0c1..14a64a1aa783c 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -382,6 +382,20 @@ const PersistedServerSettings = Schema.Struct({ // Parse first and decode second, so a managed policy can fill its defaults in between. const decodeSettingsFileJsonExit = Schema.decodeUnknownExit(fromLenientJson(Schema.Unknown)); const decodePersistedServerSettingsExit = Schema.decodeUnknownExit(PersistedServerSettings); + +/** + * The settings on disk with the managed policy laid over them, read without the service: no + * database, no write, no legacy migration. A missing or unreadable file reads as the defaults. + */ +export const readServerSettingsFromDisk = Effect.gen(function* () { + const { settingsPath } = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const { settings: managed } = yield* ManagedPolicy.ManagedPolicy; + const raw = yield* fs.readFileString(settingsPath).pipe(Effect.option); + return managed.applyLocks( + Option.isNone(raw) ? managed.defaults : decodeSettingsFile(raw.value, managed).settings, + ); +}).pipe(Effect.withSpan("ServerSettings.readServerSettingsFromDisk")); const LegacyProviderSettingsJson = fromLenientJson( Schema.Struct({ providers: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)), @@ -391,6 +405,36 @@ const LegacyProviderSettingsJson = fromLenientJson( ); const decodeLegacyProviderSettingsJsonExit = Schema.decodeUnknownExit(LegacyProviderSettingsJson); +/** + * A settings file as the server reads it: its settings, or the defaults when the file or its + * legacy fields are rejected, with the cause. Pure, so the CLI reads files as the server does. + */ +function decodeSettingsFile( + raw: string, + managed: ManagedPolicy.ManagedPolicy["Service"]["settings"], +) { + const parsed = decodeSettingsFileJsonExit(raw); + const decoded = Exit.isFailure(parsed) + ? parsed + : decodePersistedServerSettingsExit(managed.withDefaults(parsed.value)); + const legacy = decodeLegacyProviderSettingsJsonExit(raw); + const failure = Exit.isFailure(decoded) + ? decoded.cause + : Exit.isFailure(legacy) + ? legacy.cause + : undefined; + const settings: ServerSettings = + Exit.isSuccess(decoded) && failure === undefined + ? decoded.value + : // The file may hold an opt-out we can no longer read; never resume threads on a guess. + { + ...managed.defaults, + continueThreadsAfterServerUpdate: false, + usageHistoryRetentionDays: "unlimited", + }; + return { settings, legacy: Exit.isSuccess(legacy) ? legacy.value : undefined, failure }; +} + const LEGACY_BITBUCKET_SECRET_NAMES: Readonly> = { accessToken: "bitbucket-access-token", apiToken: "bitbucket-api-token", @@ -792,37 +836,19 @@ const make = Effect.gen(function* () { let parseFailure = Option.none(); if (yield* readConfigExists) { - const raw = yield* readRawConfig; - const parsed = decodeSettingsFileJsonExit(raw); - const decoded = Exit.isFailure(parsed) - ? parsed - : decodePersistedServerSettingsExit(managed.withDefaults(parsed.value)); - const legacySettings = decodeLegacyProviderSettingsJsonExit(raw); - if (legacySettings._tag === "Success") { - legacyProviders = legacySettings.value.providers; - legacySourceControl = { - bitbucket: legacySettings.value.bitbucket, - github: legacySettings.value.github, - }; + const file = decodeSettingsFile(yield* readRawConfig, managed); + if (file.legacy !== undefined) { + legacyProviders = file.legacy.providers; + legacySourceControl = { bitbucket: file.legacy.bitbucket, github: file.legacy.github }; } - if (decoded._tag === "Failure" || legacySettings._tag === "Failure") { - const failure = decoded._tag === "Failure" ? decoded : legacySettings; - // The file may hold an opt-out we can no longer read; never resume threads on a guess. - settings = { - ...managed.defaults, - continueThreadsAfterServerUpdate: false, - usageHistoryRetentionDays: "unlimited", - }; - if (failure._tag === "Failure") { - parseFailure = Option.some(Cause.squash(failure.cause)); - yield* Effect.logWarning("failed to parse settings.json, using defaults", { - path: settingsPath, - issues: Cause.pretty(failure.cause), - cause: failure.cause, - }); - } - } else { - settings = decoded.value; + settings = file.settings; + if (file.failure !== undefined) { + parseFailure = Option.some(Cause.squash(file.failure)); + yield* Effect.logWarning("failed to parse settings.json, using defaults", { + path: settingsPath, + issues: Cause.pretty(file.failure), + cause: file.failure, + }); } } // Settings saved by a server that kept the mode in `compactIdleThreads` move diff --git a/apps/server/src/socketHeartbeat.test.ts b/apps/server/src/socketHeartbeat.test.ts new file mode 100644 index 0000000000000..2cb002bbf8862 --- /dev/null +++ b/apps/server/src/socketHeartbeat.test.ts @@ -0,0 +1,39 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Scope from "effect/Scope"; +import * as Socket from "effect/socket/Socket"; +import * as TestClock from "effect/testing/TestClock"; + +import { + SOCKET_HEARTBEAT_FRAME, + SOCKET_HEARTBEAT_INTERVAL, + withSocketHeartbeat, +} from "./socketHeartbeat.ts"; + +describe("withSocketHeartbeat", () => { + it.effect("writes a heartbeat each interval until the writer's scope closes", () => + Effect.gen(function* () { + const written: Array = []; + const socket = withSocketHeartbeat( + Socket.make({ + reader: Effect.never, + writer: Effect.succeed({ + write: (chunk) => Effect.sync(() => void written.push(chunk)), + writeAll: (chunks) => Effect.sync(() => void written.push(...chunks)), + }), + }), + ); + const scope = yield* Scope.make(); + yield* Scope.provide(socket.writer, scope); + + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + assert.deepStrictEqual(written, [SOCKET_HEARTBEAT_FRAME, SOCKET_HEARTBEAT_FRAME]); + + yield* Scope.close(scope, Exit.void); + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + assert.strictEqual(written.length, 2); + }), + ); +}); diff --git a/apps/server/src/socketHeartbeat.ts b/apps/server/src/socketHeartbeat.ts new file mode 100644 index 0000000000000..6ffd9c9cf785c --- /dev/null +++ b/apps/server/src/socketHeartbeat.ts @@ -0,0 +1,27 @@ +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Socket from "effect/socket/Socket"; + +// Reverse proxies close a socket after 60 seconds without upstream bytes +// (nginx proxy_read_timeout, AWS ALB), and a suspended client stops pinging. +export const SOCKET_HEARTBEAT_INTERVAL = Duration.seconds(20); + +// RPC clients count any decoded frame as liveness and ignore unsolicited pongs. +export const SOCKET_HEARTBEAT_FRAME = '{"_tag":"Pong"}'; + +/** Server side: writes a heartbeat frame on an interval for as long as the writer is open. */ +export function withSocketHeartbeat(socket: Socket.Socket): Socket.Socket { + return Socket.make({ + reader: socket.reader, + writer: Effect.tap(socket.writer, (writer) => + writer + .write(SOCKET_HEARTBEAT_FRAME) + .pipe( + Effect.delay(SOCKET_HEARTBEAT_INTERVAL), + Effect.forever, + Effect.ignore, + Effect.forkScoped, + ), + ), + }); +} 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 ca23849363133..91b7504cebe25 100644 --- a/apps/server/src/sourceControl/builtInDrivers.ts +++ b/apps/server/src/sourceControl/builtInDrivers.ts @@ -4,6 +4,7 @@ import type { } from "@t3tools/source-control-core/server/driver"; import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli"; 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"; @@ -22,9 +23,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 }))), + ); +}); const azureDevOpsCliLayer = AzureDevOpsCli.layer.pipe(Layer.provide(ServerSourceControlHost.layer)); export const layer = Layer.effect(SourceControlDrivers, make).pipe( 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/speech/stream.test.ts b/apps/server/src/speech/stream.test.ts index 71d2fdca91310..7ce8b76dd15d2 100644 --- a/apps/server/src/speech/stream.test.ts +++ b/apps/server/src/speech/stream.test.ts @@ -1,9 +1,12 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import { it } from "@effect/vitest"; import { expect } from "vite-plus/test"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; +import * as Socket from "effect/socket/Socket"; +import * as TestClock from "effect/testing/TestClock"; import { HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; import { SpeechStreamEvent, DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS } from "@t3tools/contracts"; import type { SpeechService, SpeechStream } from "./SpeechService.ts"; @@ -167,3 +170,31 @@ it.live("processes pipelined audio before the finish command", () => { }, ).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)); }); + +it.effect("releases the stream when a started client goes silent", () => + Effect.gen(function* () { + const released = yield* Deferred.make(); + let pulls = 0; + const socket = Socket.make({ + reader: Effect.succeed({ + pull: Effect.suspend(() => + pulls++ === 0 + ? Effect.succeed([ + JSON.stringify({ type: "start", options: DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS }), + ] as const) + : Effect.never, + ), + upgrade: () => Effect.void, + }), + writer: Effect.succeed({ write: () => Effect.void, writeAll: () => Effect.void }), + }); + const stream: SpeechStream = { feed: () => Effect.never, finish: Effect.never }; + yield* runSpeechSocket(socket, { + startStream: () => + Effect.acquireRelease(Effect.succeed(stream), () => Deferred.succeed(released, undefined)), + }).pipe(Effect.scoped, Effect.forkChild); + + yield* TestClock.adjust("1 minute"); + expect(yield* Deferred.isDone(released)).toBe(true); + }), +); diff --git a/apps/server/src/speech/stream.ts b/apps/server/src/speech/stream.ts index 60d5acb2334e2..8eb9b9626010b 100644 --- a/apps/server/src/speech/stream.ts +++ b/apps/server/src/speech/stream.ts @@ -8,6 +8,7 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; @@ -16,6 +17,10 @@ import * as Socket from "effect/socket/Socket"; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as SpeechService from "./SpeechService.ts"; +// A recording client streams audio continuously; behind a proxy a vanished +// client never closes the server side, so silence is the only sign it is gone. +const SPEECH_SOCKET_IDLE_TIMEOUT = "15 seconds"; + const decodeCommand = Schema.decodeUnknownEffect(Schema.fromJsonString(SpeechStreamCommand)); /** One socket owns one stream. Audio is processed and acknowledged in arrival order. */ @@ -68,18 +73,38 @@ export const runSpeechSocket = Effect.fn("speech.runSocket")(function* ( ); }; const reader = yield* socket.reader; - yield* Effect.gen(function* () { + // Silence only counts while every received frame has been answered. + let unanswered = 0; + const activity = yield* Queue.sliding(1); + const idle = Effect.gen(function* () { + while (true) { + const heard = yield* Queue.take(activity).pipe( + Effect.timeoutOption(SPEECH_SOCKET_IDLE_TIMEOUT), + ); + if (Option.isNone(heard) && unanswered === 0) return; + } + }); + const read = Effect.gen(function* () { const pending = yield* Queue.bounded(2); - yield* Effect.forever(Queue.take(pending).pipe(Effect.flatMap(receive))).pipe( - Effect.forkScoped, - ); + yield* Effect.forever( + Queue.take(pending).pipe( + Effect.flatMap(receive), + Effect.andThen(() => { + unanswered--; + return Queue.offer(activity, undefined); + }), + ), + ).pipe(Effect.forkScoped); while (true) { const frames = yield* reader.pull; + unanswered += frames.length; + yield* Queue.offer(activity, undefined); yield* Effect.forEach(frames, (frame) => Queue.offer(pending, frame), { discard: true, }); } - }).pipe( + }); + yield* Effect.raceFirst(read, idle).pipe( Effect.timeoutOrElse({ duration: "10 minutes", // The socket read loop is already interrupted here; its writer can no longer send. 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/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.ts index 413f1947cc3b2..c895104a5903b 100644 --- a/apps/server/src/telemetry/AnalyticsService.ts +++ b/apps/server/src/telemetry/AnalyticsService.ts @@ -83,10 +83,11 @@ const TelemetryEnvConfig = Config.all({ export class AnalyticsService extends Context.Service< AnalyticsService, { + /** Whether the event was queued to send; false when telemetry is off. */ readonly record: ( event: string, properties?: Readonly>, - ) => Effect.Effect; + ) => Effect.Effect; readonly flush: Effect.Effect; @@ -312,11 +313,11 @@ export const make = Effect.gen(function* () { const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")( function* (event, properties) { - if (!(yield* telemetryEnabled) || !distinctId) return; + if (!(yield* telemetryEnabled) || !distinctId) return false; // Catch Node UUID defects too; best-effort telemetry drops events without UUIDs. const uuid = yield* Effect.exit(crypto.uuidV7()); - if (Exit.isFailure(uuid)) return; + if (Exit.isFailure(uuid)) return false; const enqueueResult = yield* enqueueBufferedEvent(uuid.value, event, properties); if (enqueueResult.dropped) { @@ -325,6 +326,7 @@ export const make = Effect.gen(function* () { event, }); } + return true; }, ); diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts index 3e4a1edf38540..249ec86f3724c 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts @@ -113,7 +113,10 @@ describe("provider usage reporting", () => { Layer.mergeAll( Layer.mock(AnalyticsService.AnalyticsService)({ record: (event, properties) => - Effect.sync(() => void recorded.push([event, properties])), + Effect.sync(() => { + recorded.push([event, properties]); + return true; + }), }), Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed(providers), 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 31c9018eaf409..2c93b90ac6809 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -2800,15 +2800,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( @@ -3977,9 +3974,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/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 0a9b9611eea06..d2bc0c296fbc1 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -2509,7 +2509,11 @@ describe("UsageService", () => { ); const summary = yield* service.readSummary(WINDOW); const sourcesFor = (provider: "opencode" | "antigravity") => - summary.sources.filter((source) => source.fingerprint.provider === provider); + summary.sources.filter( + (source) => + source.fingerprint.provider === provider && + !source.fingerprint.resolvedHomePath.endsWith("antigravity-acp"), + ); assert.strictEqual(sourcesFor("opencode").length, 1); assert.strictEqual(sourcesFor("antigravity").length, 1); assert.strictEqual( @@ -2594,6 +2598,61 @@ describe("UsageService", () => { }), ); + it.effect("reads Antigravity history from the default instance's T3-managed profile", () => + Effect.gen(function* () { + const { settings, home } = yield* setup; + const prefix = "usage-service-antigravity-default-profile-test"; + const stateDir = NodePath.join(home, prefix, "userdata"); + const conversations = NodePath.join( + stateDir, + "providers", + "antigravity", + // sha256("antigravity"), the default instance's profile key. + "ac0a3dfd6dddb20962cecff6ee5fe65e19d3923be20e52c5ab52ff877f7e4c32", + "antigravity-acp", + "conversations", + ); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(conversations, { recursive: true }); + const db = new NodeSqlite.DatabaseSync(NodePath.join(conversations, "profile.db")); + try { + db.exec("CREATE TABLE steps (idx INTEGER, metadata BLOB)"); + // Step protobuf: 100 input tokens, 7 output tokens, and 2026-08-01T10:00Z. + const metadata = new Uint8Array([ + 0x4a, + 4, + 0x10, + 100, + 0x18, + 7, + ...Buffer.from("420608a087b7d306", "hex"), + ]); + db.prepare("INSERT INTO steps VALUES (?, ?)").run(0, metadata); + } finally { + db.close(); + } + }); + yield* Effect.gen(function* () { + assert.strictEqual((yield* ServerConfig.ServerConfig).stateDir, stateDir); + const service = yield* UsageService.make; + const summary = yield* service.readSummary(WINDOW); + const root = yield* Effect.promise(() => NodeFSP.realpath(conversations)); + assert.include( + summary.sources + .filter((source) => source.fingerprint.provider === "antigravity") + .map((source) => source.fingerprint.resolvedHomePath), + root, + ); + assert.strictEqual( + summary.buckets + .filter((bucket) => bucket.provider === "antigravity" && bucket.sourcePath === root) + .reduce((sum, bucket) => sum + bucket.totals.outputTokens, 0), + 7, + ); + }).pipe(Effect.provide(layerService({ prefix, home, settings }))); + }), + ); + it.effect("reads configured and disabled accounts once across shared and aliased homes", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; @@ -3239,6 +3298,72 @@ describe("UsageService", () => { }), ); + it.effect("limits cached transcript work and diagnostics to the requested dates", () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + const dir = NodePath.join(home, "codex", "sessions"); + const transcript = NodePath.join(dir, "rollout.jsonl"); + const line = (timestamp: string, input: number, total: number) => + JSON.stringify({ + type: "event_msg", + timestamp, + payload: { + type: "token_count", + info: { + last_token_usage: { input_tokens: input, output_tokens: 1 }, + total_token_usage: { input_tokens: total, output_tokens: total / 10 }, + }, + }, + }); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(dir, { recursive: true }); + await NodeFSP.writeFile( + transcript, + [ + JSON.stringify({ type: "turn_context", payload: { model: "gpt-6-astra" } }), + line("2026-08-01T10:00:00Z", 10, 10), + line("2026-08-01T11:00:00Z", 10, 40), + ].join("\n") + "\n", + ); + }); + yield* Effect.gen(function* () { + const first = yield* UsageService.make; + const source = (summary: UsageSummary) => + summary.sources.find((s) => s.fingerprint.provider === "codex")!; + assert.strictEqual(source(yield* first.readSummary(WINDOW)).malformedRecords, 1); + const hour = { + ...WINDOW, + resolution: "hour" as const, + sinceTime: "2026-08-01T10:00:00Z", + untilTime: "2026-08-01T11:00:00Z", + }; + assert.strictEqual(source(yield* first.readSummary(hour)).malformedRecords, 0); + + yield* first.awaitPersisted; + const restarted = yield* UsageService.make; + const nextDay = { + ...WINDOW, + sinceDay: UsageDay.make("2026-08-02"), + untilDay: UsageDay.make("2026-08-02"), + }; + const outside = source(yield* restarted.readSummary(nextDay)); + assert.strictEqual(outside.malformedRecords, 0); + assert.strictEqual(outside.scannedFiles, 0); + assert.strictEqual(outside.message, null); + yield* Effect.promise(() => + NodeFSP.appendFile(transcript, line("2026-08-02T10:00:00Z", 10, 10)), + ); + const mixed = yield* restarted.readSummary(nextDay); + assert.strictEqual(totalOutputTokens(mixed), 1); + assert.strictEqual(source(mixed).malformedRecords, 0); + yield* restarted.awaitPersisted; + const saved = yield* UsageService.make; + assert.strictEqual(source(yield* saved.readSummary(nextDay)).malformedRecords, 0); + assert.strictEqual(source(yield* saved.readSummary(WINDOW)).malformedRecords, 1); + }).pipe(Effect.provide(layerService({ prefix: "usage-window-diagnostics", home, settings }))); + }), + ); + it.effect( "merges partial Claude copies through tail replacement, newline completion and restart", () => @@ -3833,6 +3958,32 @@ describe("UsageService", () => { }), ); + it.effect("leaves a duplicate uncounted when its first copy is before the window", () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + const dir = NodePath.dirname(transcript); + yield* Effect.promise(async () => { + await NodeFSP.writeFile(NodePath.join(dir, "a.jsonl"), ""); + await NodeFSP.writeFile(NodePath.join(dir, "b.jsonl"), ""); + const [first = "", second = ""] = (await NodeFSP.readdir(dir)).map((name) => + NodePath.join(dir, name), + ); + const nextDay = (line: string) => line.replace("2026-08-01", "2026-08-02"); + await NodeFSP.writeFile(first, claudeLine(1, 5)); + await NodeFSP.writeFile(second, nextDay(claudeLine(1, 5)) + nextDay(claudeLine(2, 7))); + }); + yield* Effect.gen(function* () { + const summary = yield* (yield* UsageService.make).readSummary({ + ...WINDOW, + sinceDay: UsageDay.make("2026-08-02"), + }); + assert.strictEqual(totalOutputTokens(summary), 7); + }).pipe( + Effect.provide(layerService({ prefix: "usage-service-early-copy-test", home, settings })), + ); + }), + ); + it.effect("credits the same copy of a duplicate from the last scan as an exact read does", () => Effect.gen(function* () { yield* TestClock.setTime(Date.parse("2026-08-15T00:00:00Z")); @@ -3943,7 +4094,7 @@ describe("UsageService", () => { provider: "claude" as const, records: [], tailRecords: [], - malformedRecords: 2, + malformedRecords: [mtimeMs, mtimeMs], position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }, ], diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 7151f614ad64b..dab386210ad5a 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -39,7 +39,12 @@ import type { TranscriptUsageFormat, UsageRecord, } from "@t3tools/provider-core/server/usage"; -import { canonicalModelFilter, resolveModelAliases, UsageAggregator } from "./usageAggregation.ts"; +import { + canonicalModelFilter, + resolveModelAliases, + usageTimestampFilter, + UsageAggregator, +} from "./usageAggregation.ts"; import { createOverrideRateTable, isUnlistedModel, @@ -427,7 +432,8 @@ export const make = Effect.gen(function* () { ([filePath, entry]) => entry.provider === provider && entry.mtimeMs >= retentionCutoffMs && - (entry.records.length + entry.tailRecords.length > 0 || entry.malformedRecords > 0) && + (entry.records.length + entry.tailRecords.length > 0 || + entry.malformedRecords.length > 0) && isWithinDirectory(filePath, dir), ); const volumeId = @@ -572,7 +578,7 @@ export const make = Effect.gen(function* () { format: TranscriptUsageFormat, ): Effect.fn.Return<{ readonly records: readonly UsageRecord[]; - readonly malformedRecords: number; + readonly malformedRecords: readonly number[]; readonly failed?: true; readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined }; }> { @@ -607,7 +613,7 @@ export const make = Effect.gen(function* () { if (parsed === null) return { records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [], - malformedRecords: cached?.provider === provider ? cached.malformedRecords : 0, + malformedRecords: cached?.provider === provider ? cached.malformedRecords : [], failed: true, }; @@ -695,7 +701,7 @@ export const make = Effect.gen(function* () { | readonly { readonly path: string; readonly records: readonly UsageRecord[]; - readonly malformedRecords: number; + readonly malformedRecords: readonly number[]; }[] | null; /** Every transcript path the walk listed, in walk order, whatever its mtime. */ @@ -808,7 +814,7 @@ export const make = Effect.gen(function* () { : Effect.succeed<[string, string | undefined]>([volumeId, undefined]), ([resolved, sourceId]): ScannedDir => ({ ...source, - files: source.files?.map((file) => ({ ...file, malformedRecords: 0 })) ?? null, + files: source.files?.map((file) => ({ ...file, malformedRecords: [] })) ?? null, provider: reader.provider, volumeId: resolved, ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }), @@ -884,6 +890,11 @@ export const make = Effect.gen(function* () { ? 0 : Math.max(0, startedAtMs - settings.usageHistoryRetentionDays * 24 * 60 * 60 * 1000); + const inWindow = usageTimestampFilter({ ...input, ...hourlyWindow }); + const windowEndMs = + hourlyWindow?.untilTimeMs ?? + Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS; + const awaitRefresh = input.awaitRefresh === true; const collect = Effect.gen(function* () { const resolved = yield* resolveTranscriptDirs(settings, retentionCutoffMs, awaitRefresh).pipe( @@ -959,7 +970,16 @@ export const make = Effect.gen(function* () { malformedRecords: entry.malformedRecords, }); } - return retainedFiles; + return retainedFiles.flatMap((file) => { + // A keyed copy outside the window still claims its key, so a later copy is not counted. + const records = file.records.filter( + (record) => record.dedupeKey !== null || inWindow(record.timestampMs), + ); + const malformedRecords = file.malformedRecords.filter(inWindow); + return records.length === 0 && malformedRecords.length === 0 + ? [] + : [{ ...file, records, malformedRecords }]; + }); }); // Usage two transcripts share counts in the first one, so saved files take the order an exact // scan reads them in: walked files in walk order, then the directory's deleted files. @@ -1017,9 +1037,6 @@ export const make = Effect.gen(function* () { ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }), }); - const windowEndMs = - hourlyWindow?.untilTimeMs ?? - Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS; let resolvedAny = false; for (const { reader } of transcriptReaders) { if (reader.resolveServiceTiers === undefined || fromMemory) continue; @@ -1085,7 +1102,7 @@ export const make = Effect.gen(function* () { let counted = false; for (const file of filesByDir[index] ?? []) { - malformedRecords += file.malformedRecords; + malformedRecords += file.malformedRecords.length; if (file.records.length === 0) { skippedFiles += 1; continue; diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts index f4c39753548fd..9ba0a22fd7a32 100644 --- a/apps/server/src/usage/usageAggregation.ts +++ b/apps/server/src/usage/usageAggregation.ts @@ -77,6 +77,22 @@ export interface AggregateOptions { readonly untilTimeMs?: number; } +export function usageTimestampFilter( + options: Pick< + AggregateOptions, + "timeZone" | "sinceDay" | "untilDay" | "sinceTimeMs" | "untilTimeMs" + >, +) { + const toDay = makeDayFormatter(options.timeZone); + return (timestampMs: number) => { + if (options.sinceTimeMs !== undefined && options.untilTimeMs !== undefined) { + return timestampMs >= options.sinceTimeMs && timestampMs < options.untilTimeMs; + } + const day = toDay(timestampMs); + return day >= options.sinceDay && day <= options.untilDay; + }; +} + export function resolveModelAliases( aliases: Readonly>, ): ReadonlyMap { diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index 36864768eb525..6acc49e0657cf 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -52,7 +52,7 @@ function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][]) provider: "claude", records, tailRecords: [], - malformedRecords: 0, + malformedRecords: [], position: position(), }); } @@ -95,7 +95,7 @@ describe("scan cache round trip", () => { ]); original.set("/grok.jsonl", { size: 40, - malformedRecords: 2, + malformedRecords: [1, 2], mtimeMs: 300, provider: "grok", records: [ @@ -131,7 +131,7 @@ describe("scan cache round trip", () => { const pendingTail = { ...pending, unresolvedServiceTierTurnId: "native-tail" }; original.set("/codex.jsonl", { size: 80, - malformedRecords: 3, + malformedRecords: [1, 2, 3], mtimeMs: 400, provider: "codex", records: [ @@ -166,6 +166,16 @@ describe("scan cache round trip", () => { expect(restored.size).toBe(4); expect(restored).toEqual(original); + const encoded = parse(makeScanCacheWriter()(original, {})); + const { mt: _dates, ...undated } = encoded.files["/codex.jsonl"]!; + const reparsed = decodeScanCache( + { ...encoded, files: { ...encoded.files, "/codex.jsonl": undated } }, + TEST_FORMAT_MAP, + ).get("/codex.jsonl")!; + expect(reparsed.size).toBe(-1); + expect(reparsed.position.resumeOffset).toBe(0); + expect(reparsed.records).toEqual(original.get("/codex.jsonl")!.records); + expect(reparsed.malformedRecords).toEqual([]); }); it.each([5, 6, 7, 8, 10, 11, 12, 13])( @@ -175,7 +185,7 @@ describe("scan cache round trip", () => { original.set("/gone-codex.jsonl", { ...original.get("/gone.jsonl")!, provider: "codex", - malformedRecords: 1, + malformedRecords: [1], records: [record({ provider: "codex", speed: "fast", dedupeKey: null })], position: position({ state: { @@ -195,12 +205,12 @@ describe("scan cache round trip", () => { size: 256, provider: "pi", records: [record({ provider: "pi", model: "anthropic/claude-fable-5" })], - malformedRecords: 3, + malformedRecords: [1, 2, 3], position: position({ state: { sessionId: "session-a" } }), }); const cleanCodex = { ...original.get("/gone-codex.jsonl")!, - malformedRecords: 0, + malformedRecords: [], }; original.set("/clean-codex.jsonl", cleanCodex); const encoded = parse(makeScanCacheWriter()(original, {})); @@ -257,7 +267,7 @@ describe("scan cache round trip", () => { ); it("re-parses a v14 Codex entry that skipped records and restarts a clean one when it grows", () => { - const codex = (malformedRecords: number): CachedFile => ({ + const codex = (malformedRecords: readonly number[]): CachedFile => ({ size: 10, mtimeMs: 100, provider: "codex", @@ -269,20 +279,20 @@ describe("scan cache round trip", () => { }), }); const original: ScanCache = new Map([ - ["/skipped-codex.jsonl", codex(1)], - ["/clean-codex.jsonl", codex(0)], + ["/skipped-codex.jsonl", codex([1])], + ["/clean-codex.jsonl", codex([])], ]); const v14 = { ...parse(makeScanCacheWriter()(original, {})), version: 14 }; const restored = decodeScanCache(JSON.parse(JSON.stringify(v14)), TEST_FORMAT_MAP); expect(restored.get("/skipped-codex.jsonl")).toEqual({ - ...codex(1), + ...codex([1]), size: -1, position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }); // Served while unchanged, but its state predates the latest snapshot time, so it cannot resume. expect(restored.get("/clean-codex.jsonl")).toEqual({ - ...codex(0), + ...codex([]), position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }); // The migrated entries persist without a state and load again under the current version. @@ -306,7 +316,7 @@ describe("scan cache round trip", () => { provider: "codex", records: [record({ provider: "codex", model: "gpt-6-astra", dedupeKey: null })], tailRecords: [], - malformedRecords: 0, + malformedRecords: [], position: position({ state: { ...initialCodexScanState(), @@ -368,14 +378,14 @@ describe("scan cache round trip", () => { ["/a.jsonl", 100, [record()]], ["/b.jsonl", 200, [record({ sessionId: "session-b" })]], ]); - cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, malformedRecords: 2 }); + cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, malformedRecords: [1, 2] }); const sources = { "claude\u0000/projects": { dir: "/projects", volumeId: "1:2" } }; expect(decodeScanCache(parse(write(cache, { sources })), TEST_FORMAT_MAP)).toEqual(cache); cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, size: 30, - malformedRecords: 4, + malformedRecords: [1, 2, 3, 4], records: [record({ sessionId: "session-c", model: "claude-opus-5-5", dedupeKey: "msg_3:" })], }); const document = parse(write(cache, { sources })); diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts index 843b414b97f32..cc6068b72f164 100644 --- a/apps/server/src/usage/usageScanCache.ts +++ b/apps/server/src/usage/usageScanCache.ts @@ -44,8 +44,8 @@ export interface CachedFile { readonly records: readonly UsageRecord[]; /** Unterminated tail records stay separate because incremental parsing rereads them. */ readonly tailRecords: readonly UsageRecord[]; - /** Whole-file count, including diagnostics from the tentative tail. */ - readonly malformedRecords: number; + /** Whole-file timestamps, including diagnostics from the tentative tail. */ + readonly malformedRecords: readonly number[]; readonly position: TranscriptParsePosition; } @@ -75,6 +75,7 @@ interface SerializedFile { readonly r: readonly SerializedRecord[]; readonly t: readonly SerializedRecord[]; readonly mr: number; + readonly mt?: readonly number[]; readonly o: number; readonly gl: number; readonly gh: number; @@ -136,7 +137,8 @@ function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile p: entry.provider, r: entry.records.map(serializeRecord), t: entry.tailRecords.map(serializeRecord), - mr: entry.malformedRecords, + mr: entry.malformedRecords.length, + ...(entry.malformedRecords.length === 0 ? {} : { mt: entry.malformedRecords }), o: entry.position.resumeOffset, gl: entry.position.guardLength, gh: entry.position.guardHash, @@ -288,8 +290,18 @@ export function decodeScanCache( const format = formats.get(entry.p); if (format === undefined) continue; if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue; - const malformedRecords = entry.mr === undefined ? 0 : entry.mr; - if (!Number.isSafeInteger(malformedRecords) || malformedRecords < 0) continue; + const malformedCount = entry.mr === undefined ? 0 : entry.mr; + if (!Number.isSafeInteger(malformedCount) || malformedCount < 0) continue; + const malformedRecords = entry.mt ?? (malformedCount === 0 ? [] : undefined); + if ( + malformedRecords !== undefined && + (!Array.isArray(malformedRecords) || + malformedRecords.length !== malformedCount || + !malformedRecords.every(Number.isFinite)) + ) + continue; + // A count saved without dates cannot be limited to a window, so the file re-parses whole. + const undated = malformedRecords === undefined; // Position fields feed byte offsets and a Buffer allocation in the reader, // so anything outside their real ranges must reject the entry: a bogus // guard length would otherwise fail every parse of the file, silently @@ -317,14 +329,14 @@ export function decodeScanCache( (entry.p === "grok" && version < 17) || (format.state !== undefined && (version < 6 || - (entry.p === "codex" && (version < 14 || (version < 15 && malformedRecords > 0))))); + (entry.p === "codex" && (version < 14 || (version < 15 && malformedCount > 0))))); // A corrupt state disqualifies the entry: resuming with it would attach // appended usage to the wrong model or replay fork-copied history. if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue; // Before v16 a Codex baseline can lack the time of its latest move, or carry an older one, // and that time keeps a re-emitted older snapshot from billing twice. A grown file re-parses // whole instead of resuming. - const resumable = !legacy && !(entry.p === "codex" && version < 16); + const resumable = !legacy && !undated && !(entry.p === "codex" && version < 16); const provider = entry.p; const records = decodeRecords(entry.r, provider); @@ -332,12 +344,12 @@ export function decodeScanCache( if (records === null || tailRecords === null) continue; cache.set(path, { - size: legacy ? -1 : entry.s, + size: legacy || undated ? -1 : entry.s, mtimeMs: entry.m, provider, records, tailRecords, - malformedRecords, + malformedRecords: malformedRecords ?? [], position: resumable ? { resumeOffset: entry.o, diff --git a/apps/server/src/usage/usageTranscriptReader.test.ts b/apps/server/src/usage/usageTranscriptReader.test.ts index ca994dd3ac5b2..1896991a9b835 100644 --- a/apps/server/src/usage/usageTranscriptReader.test.ts +++ b/apps/server/src/usage/usageTranscriptReader.test.ts @@ -162,8 +162,8 @@ describe("compressed transcripts", () => { assert.strictEqual(expected.tailRecords.length, 1); assert.deepStrictEqual(actual.records, expected.records); assert.deepStrictEqual(actual.tailRecords, expected.tailRecords); - assert.strictEqual(expected.malformedRecords, 1); - assert.strictEqual(actual.malformedRecords, expected.malformedRecords); + assert.strictEqual(expected.malformedRecords.length, 1); + assert.deepStrictEqual(actual.malformedRecords, expected.malformedRecords); assert.strictEqual(actual.records[0]?.speed, "ultrafast"); assert.isFalse(actual.resumed); assert.strictEqual(actual.position.resumeOffset, 0); @@ -226,7 +226,7 @@ describe("readTranscriptRecords resume", () => { } return TEST_FORMATS.claude.parseProjected(value, undefined); }, - readMalformedRecords: (state: { errors: number }) => state.errors, + readMalformedRecords: (state: { errors: number }) => Array(state.errors).fill(0), }; const path = NodePath.join(dir, "diagnostics.jsonl"); const malformed = JSON.stringify({ usage: "malformed" }); @@ -243,7 +243,7 @@ describe("readTranscriptRecords resume", () => { assert.deepStrictEqual(first.tailRecords, []); assert.strictEqual(first.position.resumeOffset, Buffer.byteLength(committed)); assert.deepStrictEqual(first.position.state, { errors: 1 }); - assert.strictEqual(first.malformedRecords, 2); + assert.strictEqual(first.malformedRecords.length, 2); const savedPosition = JSON.parse(JSON.stringify(first.position)); await NodeFSP.appendFile(path, `\n${claudeLine(2, 7)}${malformed}\n`); @@ -255,14 +255,14 @@ describe("readTranscriptRecords resume", () => { [7], ); assert.deepStrictEqual(resumed.position.state, { errors: 3 }); - assert.strictEqual(resumed.malformedRecords, 3); + assert.strictEqual(resumed.malformedRecords.length, 3); const full = await readTranscriptRecords(path, format, undefined, options); assert.isNotNull(full); assert.deepStrictEqual([...first.records, ...resumed.records], full.records); assert.deepStrictEqual(resumed.tailRecords, full.tailRecords); assert.deepStrictEqual(resumed.position, full.position); - assert.strictEqual(resumed.malformedRecords, full.malformedRecords); + assert.deepStrictEqual(resumed.malformedRecords, full.malformedRecords); }); it("parses only appended lines when resuming a grown file", async () => { @@ -272,7 +272,7 @@ describe("readTranscriptRecords resume", () => { assert.isNotNull(first); assert.strictEqual(first.records.length, 2); assert.isFalse(first.resumed); - assert.strictEqual(first.malformedRecords, 0); + assert.deepStrictEqual(first.malformedRecords, []); await NodeFSP.appendFile(path, claudeLine(3, 11)); const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position); @@ -380,7 +380,7 @@ describe("readTranscriptRecords resume", () => { first.tailRecords.map((r) => [r.totals.outputTokens, r.speed]), [[20, "ultrafast"]], ); - assert.strictEqual(first.malformedRecords, 0); + assert.deepStrictEqual(first.malformedRecords, []); await NodeFSP.appendFile(path, `\n${firstLine}\n${event(usage(10, 2), usage(510, 62))}\n`); const resumed = await readTranscriptRecords( @@ -402,7 +402,7 @@ describe("readTranscriptRecords resume", () => { ], ); assert.deepStrictEqual(resumed.tailRecords, []); - assert.strictEqual(resumed.malformedRecords, 0); + assert.deepStrictEqual(resumed.malformedRecords, []); assert.deepStrictEqual(resumed.position, full.position); }, ); @@ -476,7 +476,7 @@ describe("readTranscriptRecords resume", () => { { billedTokens: requests.reduce((sum, tokens) => sum + tokens, 0), requests, - malformedRecords: result.malformedRecords, + malformedRecords: result.malformedRecords.length, }, { billedTokens: 510, requests: [120, 160, 230], malformedRecords: 0 }, ); diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.ts index 43597513e5240..263f6701a47c0 100644 --- a/apps/server/src/usage/usageTranscriptReader.ts +++ b/apps/server/src/usage/usageTranscriptReader.ts @@ -36,8 +36,8 @@ export interface TranscriptParseResult { readonly records: readonly UsageRecord[]; /** Unterminated tail records stay outside records/position so the next scan rereads them. */ readonly tailRecords: readonly UsageRecord[]; - /** Includes tentative tail diagnostics; position.state only includes committed lines. */ - readonly malformedRecords: number; + /** Timestamps, including tentative tail diagnostics; position.state only includes committed lines. */ + readonly malformedRecords: readonly number[]; readonly position: TranscriptParsePosition; readonly resumed: boolean; } @@ -464,7 +464,7 @@ export async function readTranscriptRecords( return { records, tailRecords, - malformedRecords: format.readMalformedRecords?.(tailState) ?? 0, + malformedRecords: format.readMalformedRecords?.(tailState) ?? [], position: { resumeOffset: compressed ? 0 : resumeOffset, guardLength, diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 21b4d23a37bda..882469b57a5c0 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -1427,7 +1427,7 @@ it.effect.each([1_700_000_000, 1_700_000_000.9999])( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); -it.effect.each(["local", "mixed", "exit"] as const)( +it.effect.each(["local", "mixed", "exit", "non-UTF-8 refs", "pruned ref"] as const)( "checkpoint authorship uses local evidence or full fallback ($0)", (mode) => Effect.gen(function* () { @@ -1441,7 +1441,7 @@ it.effect.each(["local", "mixed", "exit"] as const)( const fromCheckpointRef = CheckpointRef.make("refs/t3/checkpoints/authorship/from"); const toCheckpointRef = CheckpointRef.make("refs/t3/checkpoints/authorship/to"); yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef: fromCheckpointRef }); - if (mode === "mixed") { + if (mode !== "local" && mode !== "exit") { yield* fs.writeFileString(path.join(cwd, "imported.txt"), "upstream\n"); yield* git(["add", "."]); const tree = (yield* git(["write-tree"])).stdout.trim(); @@ -1476,10 +1476,30 @@ it.effect.each(["local", "mixed", "exit"] as const)( const queryDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( Effect.provideService(VcsProcess.VcsProcess, { run: (input) => { + if (mode === "non-UTF-8 refs" && input.args.includes("for-each-ref")) { + return liveProcess + .run(input) + .pipe(Effect.map((result) => ({ ...result, stdoutInvalidUtf8: true }))); + } + // Pruned between listing the refs and walking their reflogs. + if (mode === "pruned ref" && input.args.includes("for-each-ref")) { + return liveProcess.run(input).pipe( + Effect.map((result) => ({ + ...result, + stdout: `refs/remotes/origin/pruned\n${result.stdout}`, + })), + ); + } if (!input.args.includes("--walk-reflogs")) return liveProcess.run(input); - const scope = input.args.includes("--all") ? "--all" : "HEAD"; + const scope = input.args.includes("--all") + ? `worktree HEADs${input.args.includes("--branches") ? " and --branches" : ""}` + : input.args.includes("--remotes") + ? "--remotes" + : input.args.includes("--stdin") + ? "refs" + : "HEAD"; reflogScopes.push(scope); - if (scope === "--all" || mode !== "exit") return liveProcess.run(input); + if (scope !== "HEAD" || mode !== "exit") return liveProcess.run(input); return Effect.fail( new VcsProcessExitError({ operation: input.operation, @@ -1500,10 +1520,115 @@ it.effect.each(["local", "mixed", "exit"] as const)( }), new Set(["local.txt"]), ); - assert.deepEqual(reflogScopes, mode === "local" ? ["HEAD"] : ["HEAD", "--all"]); + assert.deepEqual( + reflogScopes, + { + local: ["HEAD"], + mixed: ["HEAD", "refs", "worktree HEADs"], + // Without an import no remote-tracking ref holds the turn's commits, so none is read. + exit: ["HEAD"], + "non-UTF-8 refs": ["HEAD", "--remotes", "worktree HEADs and --branches"], + "pruned ref": ["HEAD", "refs", "worktree HEADs"], + }[mode], + ); }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect("checkpoint authorship reads only reflogs of refs holding the turn's commits", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const liveProcess = yield* VcsProcess.VcsProcess; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-imports-" }); + const upstream = path.join(root, "upstream"); + const primary = path.join(root, "primary"); + const cwd = path.join(root, "turn"); + const git = (repo: string, args: ReadonlyArray, stdin?: string) => + driver.execute({ + operation: "checkpoint-test", + cwd: repo, + args: ["-c", "user.name=Test", "-c", "user.email=test@test.com", ...args], + ...(stdin === undefined ? {} : { stdin }), + }); + const commitFile = (repo: string, file: string) => + Effect.gen(function* () { + yield* fs.writeFileString(path.join(repo, file), `${file}\n`); + yield* git(repo, ["add", "."]); + yield* git(repo, ["commit", "-m", file]); + }); + yield* fs.makeDirectory(upstream); + yield* git(upstream, ["init"]); + yield* commitFile(upstream, "base.txt"); + yield* git(root, ["clone", upstream, primary]); + yield* git(primary, ["worktree", "add", cwd, "-b", "turn"]); + const fromCheckpointRef = CheckpointRef.make("refs/t3/checkpoints/imports/from"); + const toCheckpointRef = CheckpointRef.make("refs/t3/checkpoints/imports/to"); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef: fromCheckpointRef }); + + // Refs updated during the turn that hold none of its commits. + const base = (yield* git(cwd, ["rev-parse", "HEAD"])).stdout.trim(); + const unrelated = Array.from({ length: 200 }, (_, index) => [ + `create refs/remotes/origin/unrelated-${index} ${base}`, + `create refs/heads/unrelated-${index} ${base}`, + `create refs/t3/checkpoints/unrelated-${index} ${base}`, + ]).flat(); + yield* git( + cwd, + ["update-ref", "--create-reflog", "-m", "fetch origin: storing head", "--stdin"], + `${unrelated.join("\n")}\n`, + ); + + // Fetched and fast-forwarded: imported. + yield* git(upstream, ["checkout", "-b", "release"]); + yield* commitFile(upstream, "fetched.txt"); + // Made in another worktree that then moved on, pushed, and fetched back: local. + yield* git(primary, ["checkout", "--detach"]); + yield* commitFile(primary, "own.txt"); + yield* git(primary, ["push", "origin", "HEAD:refs/heads/pushed"]); + yield* git(primary, ["checkout", "-"]); + yield* git(upstream, ["merge", "pushed", "--no-edit"]); + yield* git(upstream, ["checkout", "-b", "feature"]); + yield* commitFile(upstream, "picked.txt"); + yield* git(cwd, ["fetch", "origin"]); + yield* git(cwd, ["merge", "--ff-only", "origin/release"]); + // Cherry-picked from a fetched branch: a new local commit. + yield* git(cwd, ["cherry-pick", "origin/feature"]); + yield* commitFile(cwd, "local.txt"); + // Pushing imported commits elsewhere must not make them look local. + yield* git(cwd, ["push", "origin", "HEAD:refs/heads/mirror"]); + yield* driver.checkpoints.captureCheckpoint({ + cwd, + checkpointRef: toCheckpointRef, + previousCheckpointRef: fromCheckpointRef, + }); + + const reflogWalks: Array<{ args: ReadonlyArray; refs: ReadonlyArray }> = []; + const queryDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => { + if (input.args.includes("--walk-reflogs")) { + reflogWalks.push({ args: input.args, refs: (input.stdin ?? "").split("\n") }); + } + return liveProcess.run(input); + }, + }), + ); + assert.deepEqual( + yield* queryDriver.checkpoints.listAuthoredPaths({ cwd, fromCheckpointRef, toCheckpointRef }), + new Set(["own.txt", "picked.txt", "local.txt"]), + ); + assert.isNotEmpty(reflogWalks); + for (const { args, refs } of reflogWalks) { + // Refs come only from the explicit list; --all is limited to worktree HEADs. + const selectors = args.filter((arg) => /^--(?:all|branches|remotes|glob|tags)\b/.test(arg)); + assert.deepEqual(selectors, args.includes("--all") ? ["--all"] : []); + if (args.includes("--all")) assert.include(args, "--exclude=refs/*"); + for (const ref of refs) assert.notInclude(ref, "unrelated"); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect("checkpoint authorship works with git that rejects --diff-merges=remerge", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index ab0e830e400ce..d513cf772b775 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1,5 +1,6 @@ import * as NodeBuffer from "node:buffer"; +import * as Arr from "effect/Array"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -339,6 +340,8 @@ export interface GitSetBranchUpstreamInput { export interface GitRemoteStatusOptions { readonly refreshUpstream?: boolean; + /** False skips the base-branch lookup and reports `aheadOfDefaultCount` as 0. */ + readonly includeAheadOfDefault?: boolean; } /** @@ -369,8 +372,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[], @@ -2369,36 +2374,102 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( outputMode: "error", }).pipe(Effect.map((result) => result.stdout.split("\0"))); - // A commit is an import when a fetch delivered it since the previous checkpoint and no - // reflog in any worktree shows this repository creating it. --all covers every worktree's - // HEAD, and with --walk-reflogs --max-age compares each entry's own time. --since would - // guess at a date, and reads a timestamp before 1973 as the current time. - const listImportedCommits = Effect.gen(function* () { - const entries = (yield* listLines([ - "log", - "--walk-reflogs", - "--all", - `--max-age=${capturedAt}`, - "--format=%H %gD %gs", - ])).map(parseCheckpointReflogEntry); - // A push records commits this repository already had. - const fetchedTips = new Set( - entries - .filter((entry) => entry.fetched && entry.subject !== "update by push") - .map((entry) => entry.commit), - ); - if (fetchedTips.size === 0) return fetchedTips; - // Fetching another branch can deliver a commit that was made here and pushed. - const createdHere = new Set( - entries.filter(isLocalReflogCreation).map((entry) => entry.commit), - ); - const fetched = yield* listLines( - ["rev-list", `--max-age=${capturedAt}`, "--stdin"], - `${[...fetchedTips, `^${startHead}`].join("\n")}\n`, + // Refs under `namespace` that contain any of `commits`. Only the oldest commits of the set + // are passed on, since a ref containing a descendant also contains its ancestors. + const listRefsContaining = Effect.fn("GitVcsDriver.checkpoints.listRefsContaining")( + function* (commits: ReadonlySet, namespace: "refs/remotes" | "refs/heads") { + const roots = (yield* listLines( + ["rev-list", "--no-walk=unsorted", "--parents", "--stdin"], + `${[...commits].join("\n")}\n`, + )).flatMap((line) => { + const [commit = "", ...parents] = line.split(" "); + return parents.some((parent) => commits.has(parent)) ? [] : [commit]; + }); + const outputs = yield* Effect.forEach(Arr.chunksOf(roots, 256), (chunk) => + execute({ + operation, + cwd: input.cwd, + args: [ + "for-each-ref", + "--format=%(refname)", + ...chunk.flatMap((commit) => ["--contains", commit]), + namespace, + ], + maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, + outputMode: "error", + }), + ); + // A ref name that is not UTF-8 would not survive the round trip, so Git lists them. + if (outputs.some((output) => output.stdoutInvalidUtf8)) { + return { + revisionArgs: [namespace === "refs/heads" ? "--branches" : "--remotes"], + refs: [], + }; + } + const refs = outputs.flatMap((output) => output.stdout.split("\n")); + return { revisionArgs: [], refs: [...new Set(refs.filter((ref) => ref !== ""))] }; + }, + ); + // With --walk-reflogs, --max-age compares each entry's own time; --since would guess at a + // date and reads a timestamp before 1973 as now. Walking many reflogs at once slows down + // quadratically with the refs passed: --all took 40 s in a repository with 29k refs. + const walkReflogs = Effect.fn("GitVcsDriver.checkpoints.walkReflogs")(function* ( + revisionArgs: ReadonlyArray, + refs: ReadonlyArray, + ) { + const lines = yield* listLines( + [ + "log", + "--walk-reflogs", + ...revisionArgs, + `--max-age=${capturedAt}`, + "--format=%H %gD %gs", + // A listed ref may be pruned before this walk reads it. + "--ignore-missing", + "--stdin", + ], + `${refs.join("\n")}\n`, ); - return new Set(fetched.filter((commit) => !createdHere.has(commit))); + return lines.map(parseCheckpointReflogEntry); }); + // A commit is an import when a fetch delivered it since the previous checkpoint and no + // reflog shows this repository creating it. Only refs containing a turn commit are read; + // a remote-tracking ref force-moved off one after the fetch is missed, which keeps that + // commit attributed to the turn. + const listImportedCommits = Effect.fn("GitVcsDriver.checkpoints.listImportedCommits")( + function* (candidates: ReadonlySet) { + const remote = yield* listRefsContaining(candidates, "refs/remotes"); + if (remote.revisionArgs.length === 0 && remote.refs.length === 0) { + return new Set(); + } + // A push records commits this repository already had. + const fetchedTips = new Set( + (yield* walkReflogs(remote.revisionArgs, remote.refs)) + .filter((entry) => entry.fetched && entry.subject !== "update by push") + .map((entry) => entry.commit), + ); + if (fetchedTips.size === 0) return fetchedTips; + const fetched = new Set( + (yield* listLines( + ["rev-list", `--max-age=${capturedAt}`, "--stdin"], + `${[...fetchedTips, `^${startHead}`].join("\n")}\n`, + )).filter((commit) => candidates.has(commit)), + ); + if (fetched.size === 0) return fetched; + // Fetching another branch can deliver a commit that was made here and pushed. Every + // worktree's HEAD reflog is read, since a detached HEAD may have moved off the commit + // it made; --all with refs/* excluded yields exactly those HEADs. + const local = yield* listRefsContaining(fetched, "refs/heads"); + const createdHere = new Set( + (yield* walkReflogs(["--exclude=refs/*", "--all", ...local.revisionArgs], local.refs)) + .filter(isLocalReflogCreation) + .map((entry) => entry.commit), + ); + return new Set([...fetched].filter((commit) => !createdHere.has(commit))); + }, + ); + // Remerge diffs retain merge conflict fixes while excluding clean upstream changes. // Older Git gets dense combined diffs, which miss a conflict resolved to one side's // version, so it also keeps every path more than one parent changed since the merge base. @@ -2484,7 +2555,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const importedCommits = unprovenCommits.size === 0 ? new Set() - : yield* listImportedCommits.pipe(Effect.orElseSucceed(() => new Set())); + : yield* listImportedCommits(unprovenCommits).pipe( + Effect.orElseSucceed(() => new Set()), + ); const ownCommits = recentCommits.filter((commit) => !importedCommits.has(commit)); const ownCommitPaths = ownCommits.length === 0 diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 53b706a3d3015..9792ea72b4a4a 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 = ( @@ -728,7 +728,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)), ); @@ -837,7 +840,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")! @@ -972,8 +975,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); @@ -1638,6 +1647,56 @@ describe("pullCurrentBranch", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("does not scan the working tree to pull", () => + Effect.gen(function* () { + const { cwd, initialBranch, remoteHead } = yield* cloneBehindRemote; + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const spawner = 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, spawner), + ); + + const result = yield* driver.pullCurrentBranch(cwd); + + assert.deepEqual(result, { + status: "pulled", + refName: initialBranch, + upstreamRef: `origin/${initialBranch}`, + }); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + // The status broadcast after a pull re-reads the working tree for the UI. + assert.deepEqual( + spawnedArgs.filter((args) => args.includes("status") || args.includes("--numstat")), + [], + ); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect("pulls into an unborn branch that tracks an unfetched upstream", () => + Effect.gen(function* () { + const { remote, initialBranch, remoteHead } = yield* cloneBehindRemote; + const cwd = yield* makeTmpDir(); + yield* git(cwd, ["init", "--initial-branch", initialBranch]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["config", `branch.${initialBranch}.remote`, "origin"]); + yield* git(cwd, ["config", `branch.${initialBranch}.merge`, `refs/heads/${initialBranch}`]); + const driver = yield* makeGitVcsDriverCore(); + + const result = yield* driver.pullCurrentBranch(cwd); + + assert.deepEqual(result, { + status: "pulled", + refName: initialBranch, + upstreamRef: `origin/${initialBranch}`, + }); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + }).pipe(Effect.provide(layerTest)), + ); + it.effect.each([false, true])( "pulls past an unrelated lock with custom fetch mapping=%s", (customMapping) => @@ -1827,61 +1886,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( @@ -1892,6 +2004,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* () { @@ -1980,6 +2126,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* () { @@ -5811,6 +5986,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(); @@ -7917,6 +8121,23 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reports a rename as done when Git moved the ref but kept the config locked", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["checkout", "-b", "t3/abcd1234"]); + yield* writeTextFile(cwd, ".git/config.lock", ""); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const renamed = yield* TestClock.withLive( + driver.renameBranch({ cwd, oldBranch: "t3/abcd1234", newBranch: "t3/fix-login" }), + ); + + assert.equal(renamed.branch, "t3/fix-login"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "t3/fix-login"); + }), + ); + it.effect.each([false, true])( "cleans up links left by successful worktree removal, preserving ordinary files: %s", (keepFile) => @@ -9662,6 +9883,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(); @@ -10121,6 +10385,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 07561ee8fa1d1..556fd06f1945b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -215,7 +215,6 @@ interface GitRepositoryPaths { readonly gitCommonDir: string; readonly worktreeRoot: string | null; readonly isAtRepositoryRoot: boolean | undefined; - readonly currentBranch: string | null; } interface GitRefsSnapshot { @@ -223,6 +222,7 @@ interface GitRefsSnapshot { readonly localBranches: ReadonlyArray; readonly remoteBranches: ReadonlyArray; readonly hasPrimaryRemote: boolean; + readonly worktreeStamp: string | null; } interface ExecuteGitOptions { @@ -1356,6 +1356,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, @@ -1667,8 +1711,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, @@ -1696,16 +1753,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", @@ -1720,9 +1775,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) => @@ -1736,15 +1789,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 @@ -1758,7 +1826,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* gitCommonDir, worktreeRoot, isAtRepositoryRoot, - currentBranch, } satisfies GitRepositoryPaths; }); @@ -1940,12 +2007,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"], { @@ -1955,7 +2020,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 }, @@ -1963,7 +2028,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) : ""; @@ -1972,6 +2038,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, @@ -2067,14 +2149,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( @@ -2409,8 +2486,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( @@ -2443,16 +2521,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"); }, @@ -2542,6 +2629,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* ( cwd: string, refreshUpstream: boolean, + includeAheadOfDefault = true, ) { const branchResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.statusDetailsRemote.branch", @@ -2642,7 +2730,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* (branch === defaultBranch || (defaultBranch === null && (branch === "main" || branch === "master"))); const aheadOfDefaultCount = - branch && !isDefaultBranch + branch && !isDefaultBranch && includeAheadOfDefault ? upstreamRef === null ? aheadCount : yield* computeAheadCountAgainstBase(cwd, branch).pipe(Effect.orElseSucceed(() => 0)) @@ -2919,7 +3007,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* gitCommonDir, worktreeRoot, isAtRepositoryRoot, - currentBranch: refName, }); } } @@ -3006,22 +3093,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* readStatusDetailsLocal(cwd, options); }); - const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn( - "statusDetails", - )(function* (cwd) { - yield* refreshStatusUpstreamIfStale(cwd).pipe( + const refreshStatusUpstream = (cwd: string) => + refreshStatusUpstreamIfStale(cwd).pipe( Effect.catchTags({ GitCommandError: (error) => isMissingGitCwdError(error) ? Effect.void : Effect.fail(error), }), Effect.ignoreCause({ log: true }), ); + + const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn( + "statusDetails", + )(function* (cwd) { + yield* refreshStatusUpstream(cwd); return yield* readStatusDetailsLocal(cwd); }); const statusDetailsRemote: GitVcsDriver.GitVcsDriver["Service"]["statusDetailsRemote"] = Effect.fn("statusDetailsRemote")(function* (cwd, options) { - return yield* readStatusDetailsRemote(cwd, options?.refreshUpstream !== false); + return yield* readStatusDetailsRemote( + cwd, + options?.refreshUpstream !== false, + options?.includeAheadOfDefault !== false, + ); }); const status: GitVcsDriver.GitVcsDriver["Service"]["status"] = (input) => @@ -3583,7 +3677,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, @@ -3634,10 +3728,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, @@ -3660,7 +3754,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const pushCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pushCurrentBranch"] = Effect.fn( "pushCurrentBranch", )(function* (cwd, fallbackBranch, options) { - const details = yield* statusDetails(cwd); + // Refresh first so the branch, upstream and divergence reads below stay close together. + yield* refreshStatusUpstream(cwd); + const details = yield* readStatusDetailsRemote(cwd, false, false); const branch = details.branch ?? fallbackBranch; if (!branch) { return yield* new GitCommandError({ @@ -3675,7 +3771,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, @@ -3694,8 +3790,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, @@ -3837,8 +3937,34 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const pullCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pullCurrentBranch"] = Effect.fn( "pullCurrentBranch", )(function* (cwd) { - const details = yield* readStatusDetailsLocal(cwd); - const refName = details.branch; + const [refName, currentUpstreamRef] = yield* Effect.all( + [ + readCurrentBranch("GitVcsDriver.pullCurrentBranch.branch", cwd), + readCurrentUpstreamRef(cwd), + ], + { concurrency: 2 }, + ); + let upstreamRef = currentUpstreamRef; + // `@{upstream}` needs the tracking ref, which an unborn branch's first pull has not fetched. + if (upstreamRef === null && refName) { + const head = yield* executeGit( + "GitVcsDriver.pullCurrentBranch.head", + cwd, + ["rev-parse", "--verify", "--quiet", "HEAD"], + { allowNonZeroExit: true }, + ); + if (head.exitCode !== 0) { + const [configuredRemote, mergeRef] = yield* Effect.all([ + readConfigValue(cwd, `branch.${refName}.remote`), + readConfigValue(cwd, `branch.${refName}.merge`), + ]); + const mergeBranch = mergeRef?.replace(/^refs\/heads\//, ""); + if (configuredRemote && mergeBranch) { + upstreamRef = + configuredRemote === "." ? mergeBranch : `${configuredRemote}/${mergeBranch}`; + } + } + } if (!refName) { return yield* new GitCommandError({ ...gitCommandContext({ @@ -3849,7 +3975,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* detail: "Cannot pull from detached HEAD.", }); } - if (!details.hasUpstream) { + if (upstreamRef === null) { return yield* new GitCommandError({ ...gitCommandContext({ operation: "GitVcsDriver.pullCurrentBranch", @@ -3965,14 +4091,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* true, ).pipe(Effect.map((stdout) => stdout.trim())); - const refreshed = yield* readStatusDetailsLocal(cwd); return { status: beforeSha.length > 0 && beforeSha === afterSha ? ("skipped_up_to_date" as const) : ("pulled" as const), refName, - upstreamRef: refreshed.upstreamRef, + upstreamRef, }; }, Effect.scoped); @@ -5283,7 +5408,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", @@ -5317,11 +5444,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, @@ -5341,27 +5463,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 }> = []; @@ -5380,7 +5481,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, @@ -5418,6 +5519,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; }); @@ -5494,6 +5596,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, @@ -5501,17 +5613,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; } @@ -5527,20 +5650,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( @@ -5564,8 +5684,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 }, @@ -5772,13 +5892,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } const limit = input.limit ?? VCS_COMMIT_GRAPH_DEFAULT_LIMIT; - const [logStdout, headResult] = yield* Effect.all( + const [logStdout, headResult, currentRefName] = yield* Effect.all( [ runGitStdout("GitVcsDriver.listCommitGraph", input.cwd, commitGraphLogArgs({ limit })), executeGit("GitVcsDriver.listCommitGraph.head", input.cwd, ["rev-parse", "HEAD"], { timeoutMs: 5_000, allowNonZeroExit: true, }), + readCurrentBranch("GitVcsDriver.listCommitGraph.currentBranch", input.cwd), ], { concurrency: 2 }, ); @@ -5790,7 +5911,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* hasMore: parsed.length > limit, isRepo: true, headSha: headSha.length > 0 ? headSha : null, - currentRefName: repositoryPaths.currentBranch, + currentRefName, }; }); @@ -6709,6 +6830,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* timeoutMs: 10_000, fallbackErrorDetail: "git branch rename failed", }, + ).pipe( + // Git exits non-zero after moving the ref when it cannot rewrite the locked config. + Effect.catch((error) => + Effect.all( + [branchExists(input.cwd, input.oldBranch), branchExists(input.cwd, targetBranch)], + { concurrency: "unbounded" }, + ).pipe( + Effect.orElseSucceed(() => [true, false] as const), + Effect.flatMap(([oldExists, newExists]) => + !oldExists && newExists + ? Effect.logWarning( + "GitVcsDriver.renameBranch: renamed the branch but could not move its config entries", + ) + : Effect.fail(error), + ), + ), + ), ); return { branch: targetBranch }; @@ -6970,6 +7108,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/workflows/WorkflowAgentLinks.test.ts b/apps/server/src/workflows/WorkflowAgentLinks.test.ts new file mode 100644 index 0000000000000..92b7a4f7b2fff --- /dev/null +++ b/apps/server/src/workflows/WorkflowAgentLinks.test.ts @@ -0,0 +1,292 @@ +import { EnvironmentId, OrchestratorMcpFailure } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; + +import * as PeerLinks from "../peer/PeerLinks.ts"; +import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; +import * as WorkflowAgentLinks from "./WorkflowAgentLinks.ts"; + +const isFailure = Schema.is(OrchestratorMcpFailure); + +interface Call { + readonly environmentId: string; + readonly tool: string; + readonly arguments: Record; + readonly runtimeMode: string; +} + +/** The other environment, played by the test: each tool answers from a list, in order. */ +const peer = (answers: Record>, enabled = true) => { + const calls: Array = []; + const left = new Map(Object.entries(answers).map(([tool, list]) => [tool, [...list]])); + const layer = Layer.merge( + Layer.succeed( + PeerMcpClient.PeerMcpClient, + PeerMcpClient.PeerMcpClient.of({ + call: (input) => + Effect.suspend(() => { + calls.push({ + environmentId: input.environmentId, + tool: input.tool, + arguments: input.arguments, + runtimeMode: input.limits.runtimeMode, + }); + const answer = left.get(input.tool)?.shift(); + return isFailure(answer) ? Effect.fail(answer) : Effect.succeed(answer as never); + }), + }), + ), + Layer.mock(PeerLinks.PeerLinks)({ enabled: Effect.succeed(enabled) }), + ); + return { calls, layer }; +}; + +const input = { + key: "run-1/write/0", + origin: { runId: "run-1", workflow: "fix", step: "write" }, + title: "fix: write", + prompt: "Write the fix.", + outputSchema: { type: "object" }, + model: undefined, + project: "/work/app", + environment: "env-b", + thread: undefined, +}; +const run = (status: string) => ({ recentRuns: [{ runId: "turn-1", status }], items: [] }); +const waited = { threadId: "thread-1", runId: "turn-1", status: "idle" }; + +it.effect("starts a thread there by the project's folder, with the step's key as the request", () => + Effect.gen(function* () { + const there = peer({ + t3_project_list: [ + { projects: [{ id: "p-other", workspaceRoot: "/work/other" }], nextCursor: 1 }, + { projects: [{ id: "p-app", workspaceRoot: "/work/app" }], nextCursor: null }, + ], + t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], + }); + const options = { + workspace: { type: "worktree", baseRef: "origin/main", startFromOrigin: true }, + runtimeMode: "auto-accept-edits", + } as const; + const [turn, continued] = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + Effect.all([ + links.start( + { ...input, launch: options }, + "env-b", + "workflow:k", + EnvironmentId.make("env-a"), + ), + // A thread keeps how it started. + links + .start( + { ...input, thread: "thread-1", launch: options }, + "env-b", + "workflow:c", + EnvironmentId.make("env-a"), + ) + .pipe(Effect.flip), + ]), + ), + there.layer, + ); + assert.deepStrictEqual(turn, { threadId: "thread-1", turnId: "turn-1", environment: "env-b" }); + assert.include(continued.reason, "A continued `thread` keeps how it started"); + const launch = there.calls.at(-1); + assert.deepStrictEqual(launch?.arguments, { + projectId: "p-app", + title: "fix: write", + runtimeMode: "auto-accept-edits", + workspaceStrategy: { type: "worktree", baseRef: "origin/main", startFromOrigin: true }, + message: "Write the fix.", + outputSchema: { type: "object" }, + clientRequestId: "workflow:k", + workflowRun: { environmentId: "env-a", runId: "run-1", workflow: "fix", step: "write" }, + }); + // The link's own access is the ceiling, not a mode narrower than it. + assert.equal(launch?.runtimeMode, "full-access"); + }), +); + +it.effect("registers a folder that is not a project there yet", () => + Effect.gen(function* () { + const there = peer({ + t3_project_list: [{ projects: [], nextCursor: null }], + t3_project_create: [{ id: "p-new", workspaceRoot: "/work/app" }], + t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], + }); + yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")), + ), + there.layer, + ); + assert.deepStrictEqual( + there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]), + [ + ["t3_project_list", undefined], + ["t3_project_create", "app"], + ["t3_thread_launch", "p-new"], + ], + ); + }), +); + +it.effect("does not start anything while linked environments is off", () => + Effect.gen(function* () { + const there = peer({}, false); + const error = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")), + ), + there.layer, + ).pipe(Effect.flip); + assert.match(error.reason, /Linked environments is off/); + assert.deepStrictEqual(there.calls, []); + }), +); + +it.effect("waits in pieces, rides out a dropped route, and returns the output and reply", () => + Effect.gen(function* () { + const there = peer({ + t3_thread_wait: [ + { ...waited, timedOut: true }, + new OrchestratorMcpFailure({ code: "orchestration_error", message: "unreachable" }), + { ...waited, timedOut: false, output: { branch: "fix/1" } }, + ], + t3_thread_read: [ + run("completed"), + { + recentRuns: [], + hasMore: false, + nextPosition: null, + items: [ + { type: "assistant_message", runId: "turn-0", text: "earlier", textTruncated: false }, + { + type: "assistant_message", + runId: "turn-1", + itemId: "item-9", + text: "Done, ", + textTruncated: true, + nextTextOffset: 6, + }, + ], + }, + { recentRuns: [], items: [{ text: "pushed.", textTruncated: false }] }, + ], + }); + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"), + ), + there.layer, + ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second")))); + assert.deepStrictEqual(result, { + ending: "completed", + detail: "", + reply: "Done, pushed.", + output: { branch: "fix/1" }, + }); + assert.equal(there.calls.filter((call) => call.tool === "t3_thread_wait").length, 3); + }), +); + +it.effect("a turn someone stopped there is stopped, and a refused link fails at once", () => + Effect.gen(function* () { + const stopped = peer({ + t3_thread_wait: [{ ...waited, timedOut: false }], + t3_thread_read: [run("interrupted")], + t3_thread_interrupt: [{ threadId: "thread-1", runId: "turn-1", status: "interrupted" }], + }); + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"), + ), + stopped.layer, + ); + assert.deepStrictEqual(result, { ending: "stopped", detail: "interrupted", reply: "" }); + // Stopping names the step's turn, so a person's turn on that thread keeps going. + yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.interrupt("thread-1", "env-b", "turn-1"), + ), + stopped.layer, + ); + assert.deepInclude(stopped.calls.at(-1)?.arguments, { threadId: "thread-1", runId: "turn-1" }); + + const revoked = peer({ + t3_thread_wait: [ + new OrchestratorMcpFailure({ code: "capability_denied", message: "link revoked" }), + ], + }); + const error = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"), + ), + revoked.layer, + ).pipe(Effect.flip); + assert.match(error.reason, /link revoked/); + assert.equal(revoked.calls.length, 1); + }), +); + +it.effect("a turn that ended without its result is waited past until a later turn gives it", () => + Effect.gen(function* () { + const there = peer({ + t3_thread_wait: [ + // The turn ended. The agent is waiting to be woken, and has submitted nothing. + { ...waited, timedOut: false }, + // Quiet for five minutes, in pieces. A turn that woke in between is under way... + ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })), + // ...so the wait starts over, and that turn submits. + { ...waited, timedOut: false, output: { head: "abc" } }, + ], + t3_thread_read: [ + run("completed"), + { recentRuns: [{ runId: "turn-2", status: "running" }], items: [] }, + { recentRuns: [], hasMore: false, nextPosition: null, items: [] }, + ], + }); + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", { + quiet: Duration.minutes(5), + }), + ), + there.layer, + ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second")))); + assert.deepStrictEqual(result.output, { head: "abc" }); + const waits = there.calls.filter((call) => call.tool === "t3_thread_wait"); + assert.isTrue(waits.slice(1).every((call) => call.arguments.untilOutput === true)); + }), +); + +it.effect("a thread that stays quiet gives the turn back without a result", () => + Effect.gen(function* () { + const there = peer({ + t3_thread_wait: [ + { ...waited, timedOut: false }, + ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })), + ], + t3_thread_read: [ + run("completed"), + // Nothing has run since the turn the step knows. + run("completed"), + { recentRuns: [], hasMore: false, nextPosition: null, items: [] }, + ], + }); + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", { + quiet: Duration.minutes(5), + }), + ), + there.layer, + ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second")))); + assert.deepStrictEqual(result, { ending: "completed", detail: "", reply: "" }); + }), +); diff --git a/apps/server/src/workflows/WorkflowAgentLinks.ts b/apps/server/src/workflows/WorkflowAgentLinks.ts new file mode 100644 index 0000000000000..6a0836fc0162c --- /dev/null +++ b/apps/server/src/workflows/WorkflowAgentLinks.ts @@ -0,0 +1,313 @@ +// Agent steps in a linked environment: the same three operations, as that environment's T3 tools. +import { + type EnvironmentId, + OrchestratorMcpFailure, + OrchestratorMcpThreadInterruptResult, + OrchestratorMcpThreadReadResult, + OrchestratorMcpThreadSendResult, + OrchestratorMcpThreadWaitResult, +} from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; +import type * as Schema from "effect/Schema"; + +import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts"; +import * as PeerLinks from "../peer/PeerLinks.ts"; +import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; +import { + type AgentResult, + type AgentTurn, + isProjectPath, + launchOnContinue, + WorkflowAgentError, + type WorkflowAgents, +} from "./WorkflowAgents.ts"; + +// A run acts for whoever owns this environment, not for an agent with modes of its own, so the +// only ceiling on what it starts there is the access the link was paired with. +const LIMITS = { runtimeMode: "full-access", interactionMode: "default" } as const; + +// T3 Connect's edge drops a request that is idle for about 100 s, so a wait goes out in pieces. +const WAIT_PIECE = Duration.seconds(50); + +/** The link is gone or the thread is: asking again cannot help. */ +const isFinal = (error: OrchestratorMcpFailure) => + error.code === "capability_denied" || + error.code === "thread_not_found" || + error.code === "run_not_found" || + error.code === "invalid_request"; + +// The other machine asleep or a dropped route is worth a few more tries before the run pauses. +const retried = { schedule: Schedule.exponential("2 seconds"), times: 5 }; + +type Service = WorkflowAgents["Service"]; + +export const make = Effect.gen(function* () { + const peers = yield* PeerMcpClient.PeerMcpClient; + const links = yield* PeerLinks.PeerLinks; + + const call = >( + environment: string, + tool: string, + success: S, + args: Record, + ) => + peers + .call({ + environmentId: environment as EnvironmentId, + tool, + arguments: args, + limits: LIMITS, + success, + }) + .pipe( + Effect.retry({ ...retried, while: (error) => !isFinal(error) }), + Effect.mapError( + (error) => + new WorkflowAgentError({ + reason: `Environment ${environment} refused ${tool}: ${error.message}`, + }), + ), + ); + + const listed = Effect.fn("WorkflowAgentLinks.listed")(function* ( + environment: string, + path: string, + ) { + let cursor: number | null = 0; + while (cursor !== null) { + const page: Schema.Schema.Type = + yield* call( + environment, + "t3_project_list", + ProjectToolkit.tools.t3_project_list.successSchema, + { cursor, limit: 100 }, + ); + const found = page.projects.find((project) => project.workspaceRoot === path); + if (found !== undefined) return found.id; + cursor = page.nextCursor; + } + return undefined; + }); + + /** + * The project at a folder there. A machine made for one run has the folder and no project yet, + * so a folder that is not one is registered. Two steps may do that at once; the one that is + * refused finds the other's. + */ + const projectAt = Effect.fn("WorkflowAgentLinks.projectAt")(function* ( + environment: string, + path: string, + ) { + const known = yield* listed(environment, path); + if (known !== undefined) return known; + const title = path.split("/").findLast((part) => part.length > 0) ?? path; + const created = yield* call( + environment, + "t3_project_create", + ProjectToolkit.tools.t3_project_create.successSchema, + { title, workspaceRoot: path }, + ).pipe(Effect.result); + if (Result.isSuccess(created)) return created.success.id; + return (yield* listed(environment, path)) ?? (yield* created.failure); + }); + + /** The whole text of the run's last assistant message. */ + const reply = Effect.fn("WorkflowAgentLinks.reply")(function* ( + turn: AgentTurn, + environment: string, + ) { + let last: OrchestratorMcpThreadReadResult["items"][number] | undefined; + let afterPosition: number | undefined; + while (true) { + const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { + threadId: turn.threadId, + view: "messages", + limit: 100, + ...(afterPosition === undefined ? {} : { afterPosition }), + }); + last = + read.items.findLast( + (item) => item.type === "assistant_message" && item.runId === turn.turnId, + ) ?? last; + if (!read.hasMore || read.nextPosition === null) break; + afterPosition = read.nextPosition; + } + if (last === undefined) return ""; + let text = last.text ?? ""; + let textOffset = last.textTruncated ? (last.nextTextOffset ?? null) : null; + while (textOffset !== null) { + const rest = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { + threadId: turn.threadId, + itemId: last.itemId, + textOffset, + maxCharsPerItem: 50_000, + }); + const part = rest.items[0]; + if (part === undefined) break; + text += part.text ?? ""; + textOffset = part.textTruncated ? (part.nextTextOffset ?? null) : null; + } + return text; + }); + + const start = Effect.fn("WorkflowAgentLinks.start")(function* ( + input: Parameters[0], + environment: string, + requestId: string, + here: EnvironmentId, + ) { + if (!(yield* links.enabled)) { + return yield* new WorkflowAgentError({ + reason: + "Linked environments is off on this machine, so an agent step cannot run in another one. Turn it on in Settings → Labs.", + }); + } + const outputSchema = + input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }; + if (input.thread !== undefined) { + if (input.launch !== undefined) return yield* launchOnContinue; + const sent = yield* call(environment, "t3_thread_send", OrchestratorMcpThreadSendResult, { + threadId: input.thread, + message: input.prompt, + mode: "queue", + ...outputSchema, + clientRequestId: requestId, + }); + return { threadId: sent.threadId, turnId: sent.runId, environment }; + } + if (input.project === undefined) { + return yield* new WorkflowAgentError({ + reason: "An agent step needs a `project` to start in, or a `thread` to continue.", + }); + } + const projectId = isProjectPath(input.project) + ? yield* projectAt(environment, input.project) + : input.project; + const launched = yield* call( + environment, + "t3_thread_launch", + ProjectToolkit.tools.t3_thread_launch.successSchema, + { + projectId, + title: input.title, + ...(input.model === undefined ? {} : { modelSelection: input.model }), + ...(input.launch?.runtimeMode === undefined + ? {} + : { runtimeMode: input.launch.runtimeMode }), + ...(input.launch?.interactionMode === undefined + ? {} + : { interactionMode: input.launch.interactionMode }), + ...(input.launch?.workspace === undefined + ? {} + : { workspaceStrategy: input.launch.workspace }), + message: input.prompt, + ...outputSchema, + clientRequestId: requestId, + // The thread there says which run it is a step of, and where that run lives. + workflowRun: { environmentId: here, ...input.origin }, + }, + ); + if (launched.runId === null) { + return yield* new WorkflowAgentError({ + reason: `Thread ${launched.threadId} in ${environment} started without a turn for its first message.`, + }); + } + return { threadId: launched.threadId, turnId: launched.runId, environment }; + }); + + const result = Effect.fn("WorkflowAgentLinks.result")(function* ( + turn: AgentTurn, + environment: string, + options?: { readonly quiet?: Duration.Duration | undefined }, + ): Effect.fn.Return { + const ended = new Set(["completed", "failed", "interrupted", "cancelled", "rolled_back"]); + /** The result a later turn submits, or nothing once the thread has been quiet. */ + const owed = Effect.fn("WorkflowAgentLinks.owed")(function* (quiet: Duration.Duration) { + let left = Duration.toMillis(quiet); + // The newest turn already seen to end without the result, so quiet is not restarted by it. + let counted = turn.turnId; + while (true) { + const piece = Math.min(left, Duration.toMillis(WAIT_PIECE)); + const waited = yield* call(environment, "t3_thread_wait", OrchestratorMcpThreadWaitResult, { + threadId: turn.threadId, + runId: turn.turnId, + untilOutput: true, + timeoutMs: piece, + }); + if (waited.output !== undefined) return Option.some(waited.output); + // An environment that does not know `untilOutput` answers at once: nothing to wait on. + if (!waited.timedOut) return Option.none(); + left -= piece; + if (left > 0) continue; + const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { + threadId: turn.threadId, + limit: 1, + runLimit: 1, + }); + const latest = read.recentRuns[0]; + if (latest === undefined || latest.runId === counted) return Option.none(); + // Quiet is counted from the thread's last turn: one under way, or one not yet counted. + if (ended.has(latest.status)) counted = latest.runId; + left = Duration.toMillis(quiet); + } + }); + while (true) { + const waited = yield* call(environment, "t3_thread_wait", OrchestratorMcpThreadWaitResult, { + threadId: turn.threadId, + runId: turn.turnId, + timeoutMs: Duration.toMillis(WAIT_PIECE), + }); + if (waited.timedOut) continue; + const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { + threadId: turn.threadId, + limit: 1, + runLimit: 50, + }); + const status = read.recentRuns.find((run) => run.runId === turn.turnId)?.status; + if (status === undefined) { + return yield* new WorkflowAgentError({ + reason: `Thread ${turn.threadId} in ${environment} no longer lists turn ${turn.turnId}.`, + }); + } + if (status === "completed") { + const output = + waited.output !== undefined || options?.quiet === undefined + ? Option.fromUndefinedOr(waited.output) + : yield* owed(options.quiet); + return { + ending: "completed", + detail: "", + reply: yield* reply(turn, environment), + ...(Option.isNone(output) ? {} : { output: output.value }), + }; + } + if ( + status === "failed" || + status === "interrupted" || + status === "cancelled" || + status === "rolled_back" + ) { + return { ending: status === "failed" ? "failed" : "stopped", detail: status, reply: "" }; + } + // The wait answered for a turn that has not ended. Asking again at once would spin. + yield* Effect.sleep("5 seconds"); + } + }); + + const interrupt = (threadId: string, environment: string, runId?: string) => + Effect.map( + call(environment, "t3_thread_interrupt", OrchestratorMcpThreadInterruptResult, { + threadId, + ...(runId === undefined ? {} : { runId }), + reason: "Its workflow run was cancelled", + }), + (stopped): "stopped" | "ended" => + stopped.status === "interrupt_requested" ? "stopped" : "ended", + ); + + return { start, result, interrupt }; +}); diff --git a/apps/server/src/workflows/WorkflowAgentThreads.ts b/apps/server/src/workflows/WorkflowAgentThreads.ts new file mode 100644 index 0000000000000..ce4a7510b88c0 --- /dev/null +++ b/apps/server/src/workflows/WorkflowAgentThreads.ts @@ -0,0 +1,335 @@ +// Agent steps as threads: a step's turn is an ordinary thread turn that was asked for a result. +import { + CommandId, + MessageId, + type ModelSelection, + ProjectId, + ProviderInstanceId, + type RunId, + ThreadId, +} from "@t3tools/contracts"; +import { subagentResultForRun } from "@t3tools/provider-core/server/subagentProjection"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; +import * as Digest from "effect/crypto/Digest"; +import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Hex from "effect/encoding/Hex"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as ThreadIssueService from "../orchestration-v2/ThreadIssueService.ts"; +import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as WorkflowAgentLinks from "./WorkflowAgentLinks.ts"; +import { + isProjectPath, + launchOnContinue, + WorkflowAgentError, + WorkflowAgents, +} from "./WorkflowAgents.ts"; +import { noteReference } from "./runReferences.ts"; +import { type IssueAddress, linkedPullRequestReferences, WorkflowForge } from "./WorkflowForge.ts"; + +// A turn can run for hours. Each look is bounded so a wait that lost its event is asked again. +const WAIT_SLICE = Duration.minutes(10); + +const failed = (reason: string) => (cause: unknown) => + new WorkflowAgentError({ + reason: `${reason}: ${cause instanceof Error ? cause.message : String(cause)}`, + }); + +const make = Effect.gen(function* () { + const threads = yield* ThreadManagement.ThreadManagementService; + const launches = yield* ThreadLaunch.ThreadLaunchService; + const projects = yield* ProjectService.ProjectService; + const providers = yield* ProviderRegistry.ProviderRegistry; + const settings = yield* ServerSettings.ServerSettingsService; + const digest = yield* Digest.Digest; + const linked = yield* WorkflowAgentLinks.make; + const forge = yield* WorkflowForge; + const threadIssues = yield* ThreadIssueService.ThreadIssueService; + // A tracker that is down must not cost the step its agent. + const showIssue = (issue: IssueAddress | undefined, threadId: string) => + issue === undefined + ? Effect.void + : forge.issues.read(issue).pipe( + Effect.flatMap((detail) => + threadIssues.link({ + threadId: ThreadId.make(threadId), + ref: { + projectId: detail.projectId, + tracker: detail.tracker, + host: detail.host, + scope: detail.scope, + key: detail.key, + }, + url: detail.url, + displayKey: detail.displayKey, + title: detail.title, + source: "agent", + }), + ), + Effect.catch((error) => + Effect.logWarning("Could not link a workflow agent's thread to its issue", { + threadId, + reason: error.message, + }), + ), + ); + // What the agent opened or linked while it worked is part of what its step touched. + const noteLinked = (threadId: ThreadId, sinceMillis: number | undefined) => + threads.getThreadShell(threadId).pipe( + Effect.flatMap((shell) => + shell === null + ? Effect.void + : Effect.forEach(linkedPullRequestReferences(shell, sinceMillis), noteReference, { + discard: true, + }), + ), + Effect.ignore, + ); + const here = yield* ServerEnvironment.ServerEnvironment.pipe( + Effect.flatMap((environment) => environment.getEnvironmentId), + ); + /** The linked environment a step names, or nothing when it names this one. */ + const elsewhere = (environment: string | undefined) => + environment === here ? undefined : environment; + + // Thread, message and command ids all derive from the step's key, so a start that is asked for + // again after a crash finds the turn it already started. + const idOf = Effect.fn("WorkflowAgentThreads.idOf")(function* (key: string) { + const hash = yield* digest + .digest(Digest.sha256, new TextEncoder().encode(key)) + .pipe(Effect.mapError(failed("Could not derive the turn's id"))); + return `workflow:${Hex.encode(hash)}`; + }); + + const projectDefaults = Effect.fn("WorkflowAgentThreads.projectDefaults")(function* ( + projectId: ProjectId, + ) { + const project = yield* projects + .getById(projectId) + .pipe(Effect.mapError(failed("Could not read the project"))); + if (Option.isNone(project)) { + return yield* new WorkflowAgentError({ reason: `Project ${projectId} was not found.` }); + } + const current = yield* settings.getSettings.pipe( + Effect.mapError(failed("Could not read settings")), + ); + return resolveProjectSettings(current, projectId, project.value).settings; + }); + + const projectIdOf = Effect.fn("WorkflowAgentThreads.projectIdOf")(function* (project: string) { + if (!isProjectPath(project)) return ProjectId.make(project); + const found = yield* projects + .getByWorkspaceRoot(project) + .pipe(Effect.mapError(failed("Could not read the project"))); + if (Option.isNone(found)) { + return yield* new WorkflowAgentError({ + reason: `No project is registered at ${project}.`, + }); + } + return found.value.id; + }); + + return WorkflowAgents.of({ + start: Effect.fn("WorkflowAgentThreads.start")(function* (input) { + const id = yield* idOf(input.key); + const environment = elsewhere(input.environment); + if (environment !== undefined) return yield* linked.start(input, environment, id, here); + const commandId = CommandId.make(id); + const messageId = MessageId.make(id); + const outputSchema = + input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }; + + if (input.thread !== undefined) { + if (input.launch !== undefined) return yield* launchOnContinue; + const threadId = ThreadId.make(input.thread); + const shell = yield* threads + .getThreadShell(threadId) + .pipe(Effect.mapError(failed("Could not read the thread to continue"))); + if (shell === null || shell.deletedAt !== null) { + return yield* new WorkflowAgentError({ + reason: `Thread ${input.thread} no longer exists, so it cannot be continued.`, + }); + } + const sent = yield* threads + .sendToThread({ + projectId: shell.projectId, + commandId, + threadId, + messageId, + text: input.prompt, + attachments: [], + mode: "queue", + ...outputSchema, + createdBy: "system", + creationSource: "server", + }) + .pipe(Effect.mapError(failed("Could not send to the thread"))); + yield* showIssue(input.issue, threadId); + return { threadId, turnId: sent.run.id }; + } + + if (input.project === undefined) { + return yield* new WorkflowAgentError({ + reason: "An agent step needs a `project` to start in, or a `thread` to continue.", + }); + } + const projectId = yield* projectIdOf(input.project); + const defaults = yield* projectDefaults(projectId); + const modelSelection: ModelSelection | undefined = + input.model === undefined + ? (resolveNewThreadModelSelection({ + defaultSelection: defaults.defaultModelSelection, + fallbackSelection: defaults.fallbackModelSelection, + providers: yield* providers.getProviders, + settings: defaults, + projectId, + now: DateTime.toEpochMillis(yield* DateTime.now), + }).selection ?? undefined) + : { + instanceId: ProviderInstanceId.make(input.model.instanceId), + model: input.model.model, + ...(input.model.options === undefined ? {} : { options: input.model.options }), + }; + if (modelSelection === undefined) { + return yield* new WorkflowAgentError({ + reason: `Project ${input.project} has no default model. Give the agent step a \`model\`.`, + }); + } + const launched = yield* launches + .launch({ + commandId, + threadId: ThreadId.make(id), + projectId, + title: input.title, + modelSelection, + runtimeMode: input.launch?.runtimeMode ?? defaults.defaultRuntimeMode, + interactionMode: input.launch?.interactionMode ?? "default", + workspaceStrategy: input.launch?.workspace ?? { type: "root" }, + initialMessage: { messageId, text: input.prompt, attachments: [], ...outputSchema }, + createdBy: "system", + creationSource: "server", + workflowRun: { environmentId: here, ...input.origin }, + }) + .pipe(Effect.mapError(failed("Could not start the thread"))); + const run = launched.projection.runs.find( + (candidate) => candidate.userMessageId === messageId, + ); + if (run === undefined) { + return yield* new WorkflowAgentError({ + reason: `Thread ${launched.threadId} started without a turn for its first message.`, + }); + } + yield* showIssue(input.issue, launched.threadId); + return { threadId: launched.threadId, turnId: run.id }; + }), + result: Effect.fn("WorkflowAgentThreads.result")(function* (turn, options) { + const environment = elsewhere(turn.environment); + if (environment !== undefined) return yield* linked.result(turn, environment, options); + const threadId = ThreadId.make(turn.threadId); + const shell = yield* threads + .getThreadShell(threadId) + .pipe(Effect.mapError(failed("Could not read the thread"))); + if (shell === null) { + return yield* new WorkflowAgentError({ + reason: `Thread ${turn.threadId} no longer exists.`, + }); + } + // The newest turn already seen to end without the result, so quiet is not restarted by it. + let quietSince = -1; + while (true) { + const waited = yield* threads + .waitForThread({ + projectId: shell.projectId, + threadId, + runId: turn.turnId as RunId, + timeoutMs: Duration.toMillis(WAIT_SLICE), + }) + .pipe(Effect.mapError(failed("Could not wait for the turn"))); + let run = waited.run; + if (waited.timedOut || run === null) continue; + // The agent may have ended its turn to wait for something that will wake it. + const quiet = options?.quiet; + const owes = (candidate: NonNullable) => + candidate.status === "completed" && + candidate.outputSchema !== undefined && + candidate.output === undefined; + while (owes(run)) { + if (quiet === undefined) break; + const owed: ThreadManagement.ThreadManagementWaitResult = yield* threads + .waitForThread({ + projectId: shell.projectId, + threadId, + runId: run.id, + untilOutput: true, + timeoutMs: Duration.toMillis(quiet), + }) + .pipe(Effect.mapError(failed("Could not wait for the turn's result"))); + if (owed.run === null) break; + run = owed.run; + if (!owed.timedOut) continue; + // Quiet is counted from the thread's last turn, so one under way is waited out first. + const latest = yield* threads + .waitForThread({ + projectId: shell.projectId, + threadId, + timeoutMs: Duration.toMillis(WAIT_SLICE), + }) + .pipe(Effect.mapError(failed("Could not wait for the thread"))); + if (latest.run === null || latest.run.id === run.id) break; + if (!latest.timedOut && latest.run.ordinal <= quietSince) break; + quietSince = latest.timedOut ? quietSince : latest.run.ordinal; + } + yield* noteLinked(threadId, turn.startedAt); + if (run.status !== "completed") { + // Interrupted or cancelled is someone stopping it; the rest is the turn dying. + const ending = run.status === "failed" ? ("failed" as const) : ("stopped" as const); + return { ending, detail: run.status, reply: "" }; + } + const records = yield* threads + .getThreadRecords(threadId, ["messages", "turnItems", "providerTurns"]) + .pipe(Effect.mapError(failed("Could not read the turn's reply"))); + return { + ending: "completed" as const, + detail: "", + reply: subagentResultForRun(records, run).text, + ...(run.output === undefined ? {} : { output: run.output.value }), + }; + } + }), + interrupt: Effect.fn("WorkflowAgentThreads.interrupt")(function* (target) { + const environment = elsewhere(target.environment); + if (environment !== undefined) + return yield* linked.interrupt(target.threadId, environment, target.turnId); + const thread = target.threadId; + const threadId = ThreadId.make(thread); + const shell = yield* threads + .getThreadShell(threadId) + .pipe(Effect.mapError(failed("Could not read the thread"))); + if (shell === null) return "ended" as const; + const stopped = yield* threads + .interruptThread({ + projectId: shell.projectId, + threadId, + commandId: CommandId.make( + `workflow:interrupt:${thread}:${target.turnId ?? ""}:${yield* Clock.currentTimeMillis}`, + ), + reason: "Its workflow run was cancelled", + ...(target.turnId === undefined ? {} : { runId: target.turnId as RunId }), + }) + .pipe(Effect.mapError(failed("Could not stop the thread"))); + return stopped.type === "interrupt_requested" ? ("stopped" as const) : ("ended" as const); + }), + }); +}); + +export const layer = Layer.effect(WorkflowAgents, make); diff --git a/apps/server/src/workflows/WorkflowAgents.ts b/apps/server/src/workflows/WorkflowAgents.ts new file mode 100644 index 0000000000000..674b72c69aa3d --- /dev/null +++ b/apps/server/src/workflows/WorkflowAgents.ts @@ -0,0 +1,117 @@ +import type { + ModelSelection, + OrchestrationV2ThreadLaunchWorkspaceStrategy, + ProviderInteractionMode, + RuntimeMode, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import type * as Duration from "effect/Duration"; +import type * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import type { IssueAddress } from "./WorkflowForge.ts"; + +export class WorkflowAgentError extends Schema.TaggedError()( + "WorkflowAgentError", + { reason: Schema.String }, +) { + override get message(): string { + return this.reason; + } +} + +export interface AgentModel { + readonly instanceId: string; + readonly model: string; + /** The model's own options, such as reasoning effort, as `{ id, value }` pairs. */ + readonly options?: ModelSelection["options"]; +} + +/** How a new thread starts, as `t3_thread_launch` takes it. Unset fields follow the project. */ +export interface AgentLaunch { + /** Where its files are: the project's checkout by default, or a worktree of its own. */ + readonly workspace?: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined; + readonly runtimeMode?: RuntimeMode | undefined; + readonly interactionMode?: ProviderInteractionMode | undefined; +} + +export const AgentTurn = Schema.Struct({ + threadId: Schema.String, + turnId: Schema.String, + /** The linked environment the thread is in. Absent for this one. */ + environment: Schema.optional(Schema.String), + /** When the step's first turn started, which its time limit counts from. */ + startedAt: Schema.optional(Schema.Number), + /** Why no turn was started, for a step that takes that as an answer. The ids are then empty. */ + failed: Schema.optional(Schema.String), +}); +export type AgentTurn = typeof AgentTurn.Type; + +export const AgentResult = Schema.Struct({ + /** + * How the turn ended. `stopped` is someone ending it on purpose, which is not a reason to try + * again; `failed` is the turn dying underneath the agent. + */ + ending: Schema.Literals(["completed", "failed", "stopped"]), + detail: Schema.String, + reply: Schema.String, + /** What the agent submitted against the output schema, when it did. */ + output: Schema.optional(Schema.Json), +}); +export type AgentResult = typeof AgentResult.Type; + +/** What a continued thread says to options that only shape a new one. */ +export const launchOnContinue = new WorkflowAgentError({ + reason: + "`workspace`, `runtimeMode` and `interactionMode` shape a new thread. A continued `thread` keeps how it started.", +}); + +/** A project named by its folder instead of its id. */ +export const isProjectPath = (project: string) => project.startsWith("/"); + +/** Where agent steps run. The server implements it with threads; tests stand in for it. */ +export class WorkflowAgents extends Context.Service< + WorkflowAgents, + { + /** Start a turn. The same `key` is the same turn, however often it is asked for. */ + readonly start: (input: { + readonly key: string; + /** The run and step this turn is for, which a new thread is marked with. */ + readonly origin: { readonly runId: string; readonly workflow: string; readonly step: string }; + readonly title: string; + readonly prompt: string; + readonly outputSchema: Readonly> | undefined; + readonly model: AgentModel | undefined; + /** The project a new thread is made in: its id, or its folder. Not needed to continue `thread`. */ + readonly project: string | undefined; + /** The linked environment to run in. Absent for this one. */ + readonly environment: string | undefined; + /** Continue this thread instead of starting one. */ + readonly thread: string | undefined; + /** An issue the thread is about, which it is linked to. */ + readonly issue?: IssueAddress | undefined; + /** How a new thread starts. Refused with `thread`, which keeps how it started. */ + readonly launch?: AgentLaunch | undefined; + }) => Effect.Effect; + /** + * Wait for the turn to end and return what it produced. With `quiet`, a turn that ended + * without the output it owes is waited past: its agent may be waiting to be woken, and + * submits from a later turn. Only once the thread has done nothing for `quiet` is the turn + * returned without output. + */ + readonly result: ( + turn: AgentTurn, + options?: { readonly quiet?: Duration.Duration | undefined }, + ) => Effect.Effect; + /** + * Stop whatever the thread is doing, when its run is cancelled. `ended` when there was nothing + * to stop: the turn had already ended. + */ + readonly interrupt: (thread: { + readonly threadId: string; + readonly environment?: string | undefined; + /** The step's own turn. With it, a turn of someone else's on the same thread is left alone. */ + readonly turnId?: string | undefined; + }) => Effect.Effect<"stopped" | "ended", WorkflowAgentError>; + } +>()("t3/workflows/WorkflowAgents") {} diff --git a/apps/server/src/workflows/WorkflowEngine.ts b/apps/server/src/workflows/WorkflowEngine.ts new file mode 100644 index 0000000000000..77ff4cf0ada2e --- /dev/null +++ b/apps/server/src/workflows/WorkflowEngine.ts @@ -0,0 +1,1056 @@ +// The workflow service on Effect's workflow engine. Loaded only when workflows are enabled: the +// engine's modules are not worth their load time on a server that registers none. +import * as Cause from "effect/Cause"; +import { + ClusterWorkflowEngine, + EntityAddress, + EntityId, + EntityType, + MessageStorage, + Sharding, + SingleRunner, +} from "effect/cluster"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +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 PubSub from "effect/PubSub"; +import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; +import { DurableDeferred, WorkflowEngine } from "effect/workflow"; + +import { checkOutput, rejectionText } from "../orchestration-v2/runOutput.ts"; +import { isMissedFixedTimeRun, nextScheduledRunAt } from "../scheduledTasks/Schedule.ts"; +import { constantTimeEquals } from "../scheduledTasks/webhookVerification.ts"; +import { + END_STEP, + type EngineWorkflow, + engineTag, + engineWorkflow, + layerDefinition, + text, + wakeOf, + type Woke, + type WorkflowDefinition, +} from "./workflow.ts"; +import { issueReference, noteFor, stepReferences } from "./runReferences.ts"; +import { forStep, KeyValues, layerKeyValues, EngineLink, layerEngineLink } from "./stepServices.ts"; +import { WorkflowAgents } from "./WorkflowAgents.ts"; +import { + type Issue, + isSettled, + type PullRequest, + type PullRequestAddress, + type PullRequestWatch, + pullRequestReferenceOf, + standingOf, + unavailable, + WorkflowForge, +} from "./WorkflowForge.ts"; +import { + hookId as hookIdOf, + WorkflowInputError, + WorkflowNotRegisteredError, + WorkflowRunNotFoundError, + Workflows, +} from "./Workflows.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; + +const SWEEP_EVERY = Duration.seconds(15); +const LOOK_EVERY = Duration.minutes(1); +const LOOK_AT_MOST = 100; +const DEFAULT_SIGNAL_TTL = Duration.days(7); +const RESUME_LOOK_EVERY = Duration.millis(25); +const RESUME_LOOKS = 80; +const WATCH_SETTLE = Duration.millis(100); +const END_TRIES = 5; +// How long a cancelled run's cleanup rests after each failed try before the sweep tries again. +const END_AFTER = ["5 minutes", "20 minutes", "80 minutes", "5 hours"] as const; +// An ended run's engine journal only answers replays that will not come; the run's own rows stay. +const PRUNE_AFTER = Duration.hours(1); +const PRUNE_BATCH = 100; +// Delivery ids that common senders put on a request and keep when they send it again. +const DELIVERY_HEADERS = [ + "x-github-delivery", + "x-gitea-delivery", + "x-gitlab-event-uuid", + "linear-delivery", + "webhook-id", + "idempotency-key", +]; +const CANCEL_WAITS = Duration.seconds(30); +// Times of day are the server's own, as they are for scheduled tasks. +const localNow = DateTime.withCurrentZoneLocal(DateTime.nowInCurrentZone); + +const make = Effect.fn("WorkflowEngine.make")(function* ( + registered: ReadonlyArray, +) { + const store = yield* WorkflowStore.WorkflowStore; + const keyValues = yield* KeyValues; + const link = yield* EngineLink; + const trackers = Option.getOrElse(yield* Effect.serviceOption(WorkflowForge), () => unavailable); + const messages = yield* Effect.serviceOption(MessageStorage.MessageStorage); + const sharding = yield* Effect.serviceOption(Sharding.Sharding); + // The engine reads its own tables as BigInts. The rest of the server's queries must not. + const plain = + , A, E>(call: (...args: Args) => Effect.Effect) => + (...args: Args) => + call(...args).pipe(Effect.provideService(SqlClient.SafeIntegers, false)); + const forge = WorkflowForge.of({ + issues: { + list: plain(trackers.issues.list), + read: plain(trackers.issues.read), + comment: plain(trackers.issues.comment), + setState: plain(trackers.issues.setState), + create: plain(trackers.issues.create), + }, + pullRequests: { + list: plain(trackers.pullRequests.list), + read: plain(trackers.pullRequests.read), + comment: plain(trackers.pullRequests.comment), + act: plain(trackers.pullRequests.act), + }, + }); + const scope = yield* Scope.Scope; + const agents = yield* WorkflowAgents; + const stopTurn = plain(agents.interrupt); + const random = yield* SecureRandom.SecureRandom; + const digest = yield* Digest.Digest; + const context = yield* Effect.context(); + // The engine keeps 64-bit ids, which this SQLite client only reads when asked for BigInts. + const withEngine = (effect: Effect.Effect) => + effect.pipe( + Effect.provideContext(context), + Effect.provideService(SqlClient.SafeIntegers, true), + ); + const byTag = new Map(registered.map(([, engine]) => [engine._tag, engine] as const)); + const definitionByTag = new Map( + registered.map(([definition]) => [engineTag(definition), definition] as const), + ); + const latest = (name: string) => + registered + .filter(([definition]) => definition.name === name) + .toSorted(([left], [right]) => right.version - left.version)[0]; + + /** When the sweep resumes a paused run; undefined once it has used up its tries. */ + const resumesAt = (row: WorkflowStore.RunRow) => { + if (row.status !== "paused" || Number(row.held) === 1) return undefined; + const rest = definitionByTag.get(row.engine_tag)?.resumeAfter[Number(row.pauses) - 1]; + return rest === undefined + ? undefined + : DateTime.addDuration(DateTime.makeUnsafe(row.updated_at), Duration.fromInputUnsafe(rest)); + }; + const toRun = (row: WorkflowStore.RunRow): WorkflowStore.WorkflowRun => { + const resumes = resumesAt(row); + return toRunAt(row, resumes === undefined ? null : DateTime.formatIso(resumes)); + }; + const toRunAt = ( + row: WorkflowStore.RunRow, + resumes: string | null, + ): WorkflowStore.WorkflowRun => ({ + runId: row.run_id, + workflow: row.workflow, + version: Number(row.version), + title: row.title, + status: row.status, + detail: row.detail, + result: row.result_json === null ? null : WorkflowStore.jsonValue(row.result_json), + pauses: Number(row.pauses), + retired: row.ended_at === null && !byTag.has(row.engine_tag), + resumesAt: resumes, + parentRunId: row.parent_run_id, + parentStep: row.parent_wait, + startedAt: row.started_at, + updatedAt: row.updated_at, + endedAt: row.ended_at, + }); + const requireRun = Effect.fn("WorkflowEngine.requireRun")(function* (runId: string) { + const row = yield* store.run(runId); + if (row === undefined) return yield* new WorkflowRunNotFoundError({ runId }); + return row; + }); + const send = (wait: WorkflowStore.WaitRow, value: typeof Woke.Type) => + withEngine( + DurableDeferred.succeed(wakeOf(wait.name), { + token: wait.token as DurableDeferred.Token, + value, + }), + ); + // Runs being resumed now: until the engine has them, the sweep must not take them for paused. + const resuming = new Set(); + // The engine would replay a paused run for the wake and run its failed step again unasked. The + // claim keeps the value, and the resume sends it. + const wake = Effect.fnUntraced(function* (wait: WorkflowStore.WaitRow, value: typeof Woke.Type) { + if (resuming.has(wait.run_id) || (yield* store.run(wait.run_id))?.status === "paused") return; + yield* send(wait, value); + }); + + const start: Workflows["Service"]["start"] = Effect.fn("Workflows.start")( + function* (name, input, options) { + // A parent written against one version of a child must not get another one's payload. + const found = + options.version === undefined + ? latest(name) + : registered.find( + ([candidate]) => candidate.name === name && candidate.version === options.version, + ); + if (found === undefined) { + return yield* new WorkflowNotRegisteredError({ + workflow: name, + ...(options.version === undefined ? {} : { version: options.version }), + }); + } + const [definition, engine] = found; + // A key is one run of the workflow: the engine's own id also counts the version, so a + // start after a new version would otherwise begin the same work again. + const other = Effect.fnUntraced(function* (earlier: WorkflowStore.RunRow) { + if ( + options.parent !== undefined && + (earlier.parent_run_id !== options.parent.runId || + earlier.parent_wait !== options.parent.wait) + ) { + return yield* new WorkflowInputError({ + problem: `Run ${earlier.run_id} of ${name} was started by something else under this key, so it cannot be invoked. Give the invoke a key of its own.`, + }); + } + // A start cut off between its row and the engine left a run nothing executes. Executing + // one the engine has is a no-op. + const its = byTag.get(earlier.engine_tag); + if (earlier.ended_at === null && its !== undefined && earlier.input_json !== null) { + yield* withEngine( + its.execute( + { + idempotencyKey: earlier.idempotency_key, + input: WorkflowStore.jsonValue(earlier.input_json), + }, + { discard: true }, + ), + ); + } + return { runId: earlier.run_id }; + }); + const earlier = yield* store.runByKey(name, options.idempotencyKey); + // An ended run's journal may be pruned, so executing it again would start the work over. + if ( + earlier !== undefined && + (earlier.engine_tag !== engineTag(definition) || earlier.ended_at !== null) + ) { + return yield* other(earlier); + } + const payloadCodec = Schema.toCodecJson(definition.payload); + const encode = Schema.encodeUnknownEffect(payloadCodec); + const encoded = yield* encode(input).pipe( + Effect.mapError( + (error) => + new WorkflowInputError({ + problem: `The payload does not fit workflow ${name}: ${text(error)}`, + }), + ), + ); + const payload = { idempotencyKey: options.idempotencyKey, input: encoded as Schema.Json }; + // The row is written first, with who waits for it: the run's own first step writes the same + // row without that, and whichever write lands first is the one that stays. + const runId = yield* engine.executionId(payload); + yield* store.runStarted({ + runId, + workflow: definition.name, + version: definition.version, + engineTag: engineTag(definition), + idempotencyKey: options.idempotencyKey, + input: payload.input, + parent: options.parent, + }); + // The key is unique, so the row holding it is the run, even one another version started. + const holder = yield* store.runByKey(name, options.idempotencyKey); + if (holder !== undefined && holder.run_id !== runId) return yield* other(holder); + yield* withEngine(engine.execute(payload, { discard: true })); + if (options.parent !== undefined) { + // The key named a run that someone else started: it would never tell this parent. + const row = yield* store.run(runId); + if ( + row?.parent_run_id !== options.parent.runId || + row.parent_wait !== options.parent.wait + ) { + return yield* new WorkflowInputError({ + problem: `Run ${runId} of ${name} was started by something else under this key, so it cannot be invoked. Give the invoke a key of its own.`, + }); + } + } + return { runId }; + }, + ); + + const latestDefinitions = [...new Set(registered.map(([definition]) => definition.name))].map( + (name) => latest(name)![0], + ); + // A schedule taken out and put back is new again: its first run is one interval away. + yield* store.triggersKeep( + latestDefinitions.flatMap((definition) => + definition.triggers.flatMap((trigger) => + trigger.kind === "webhook" ? [] : [`${definition.name}/${trigger.id}`], + ), + ), + ); + /** Start what each schedule is due for, once, however long ago that was. */ + const fireSchedules = Effect.gen(function* () { + const now = yield* localNow; + for (const definition of latestDefinitions) { + for (const trigger of definition.triggers) { + if (trigger.kind !== "schedule") continue; + const id = `${definition.name}/${trigger.id}`; + const due = yield* store.triggerNext(id); + if (due !== undefined) { + const dueAt = DateTime.makeUnsafe(due); + if (DateTime.isLessThan(now, dueAt)) continue; + if (!isMissedFixedTimeRun(trigger.schedule, dueAt, now)) { + // The key is the time it was due, so a crash before the next line starts no second run. + const started = yield* start( + definition.name, + { scheduledAt: due }, + { idempotencyKey: `trigger:${id}:${due}` }, + ).pipe( + Effect.as(true), + Effect.catch((error) => + Effect.as( + Effect.logWarning("A scheduled workflow run did not start", { + trigger: id, + error, + }), + false, + ), + ), + ); + // Not moved past a time it has not started: the next sweep tries that one again. + if (!started) continue; + } + } + const next = nextScheduledRunAt(trigger.schedule, now); + if (next !== null) { + yield* store.triggerSet(id, DateTime.formatIso(DateTime.toUtc(next))); + } + } + } + }).pipe(Effect.withSpan("Workflows.fireSchedules")); + + // Trackers and hosts count requests, and nothing here is in that much of a hurry. + const lookedAt = new Map(); + // Said once per engine: the same item is in every look until newer ones push it out. + const turnedDown = new Set(); + const millisOf = (at: string) => + Option.match(DateTime.make(at), { onNone: () => undefined, onSome: DateTime.toEpochMillis }); + /** + * Start a run for each issue or pull request opened since the trigger last looked. The first + * look only notes the time, so a workflow never starts on everything that was already there. + */ + const fireOpened = Effect.gen(function* () { + const now = yield* DateTime.now; + for (const definition of latestDefinitions) { + for (const trigger of definition.triggers) { + if (trigger.kind !== "issues" && trigger.kind !== "pullRequests") continue; + const id = `${definition.name}/${trigger.id}`; + const since = yield* store.triggerNext(id); + if (since === undefined) { + yield* store.triggerSet(id, DateTime.formatIso(now)); + continue; + } + const last = lookedAt.get(id); + const at = DateTime.toEpochMillis(now); + if (last !== undefined && at - last < Duration.toMillis(LOOK_EVERY)) continue; + lookedAt.set(id, at); + const found = + trigger.kind === "issues" + ? forge.issues.list({ + project: trigger.project, + // Closed ones too: an item can open and close between two looks. + state: "all", + sort: "created", + limit: LOOK_AT_MOST, + labels: trigger.labels, + query: trigger.query, + }) + : forge.pullRequests.list({ + project: trigger.project, + state: "all", + limit: LOOK_AT_MOST, + query: trigger.query, + }); + const sinceMillis = millisOf(since) ?? at; + yield* found.pipe( + Effect.flatMap( + Effect.fnUntraced(function* (entries: ReadonlyArray) { + // From the mark on, not after it: two items can share a moment. As times, since a + // host writes them in its own format and the mark is ours. + const fresh = entries + .flatMap((entry) => { + const created = millisOf(entry.createdAt); + return created === undefined || created < sinceMillis ? [] : [{ entry, created }]; + }) + .toSorted((a, b) => a.created - b.created); + if (entries.length >= LOOK_AT_MOST && fresh.length === entries.length) { + yield* Effect.logWarning( + "More new items than one look reads; older ones among them start no run", + { trigger: id, read: entries.length }, + ); + } + for (const { entry, created } of fresh) { + // The key is the address, so an issue seen twice is still one run. One the + // workflow turns down is passed over, so it does not hold back the ones after it. + const key = `trigger:${id}:${entry.url}`; + if ( + !turnedDown.has(key) && + (yield* store.runByKey(definition.name, key)) === undefined + ) { + yield* start(definition.name, entry, { idempotencyKey: key }).pipe( + // What started the run is the first thing it touched. + Effect.flatMap(({ runId }) => + noteFor( + store, + runId, + null, + "tracker" in entry + ? issueReference(entry, entry) + : pullRequestReferenceOf(entry, entry), + ), + ), + Effect.catchTags({ + WorkflowInputError: (error) => + Effect.andThen( + Effect.sync(() => turnedDown.add(key)), + Effect.logWarning("A workflow turned down an item it was started on", { + trigger: id, + item: entry.url, + error, + }), + ), + }), + ); + } + yield* store.triggerSet(id, DateTime.formatIso(DateTime.makeUnsafe(created))); + } + }), + ), + Effect.catch((error) => + Effect.logWarning("A workflow could not look for new work", { trigger: id, error }), + ), + ); + } + } + }).pipe(Effect.withSpan("Workflows.fireOpened")); + + const noChecksSince = new Map(); + /** End each wait on a pull request that has got where the wait wanted it. */ + const fireWatches = Effect.gen(function* () { + const now = DateTime.toEpochMillis(yield* DateTime.now); + for (const wait of yield* store.watches) { + const id = `watch:${wait.run_id}/${wait.name}`; + const last = lookedAt.get(id); + if (last !== undefined && now - last < Duration.toMillis(LOOK_EVERY)) continue; + lookedAt.set(id, now); + const watch = WorkflowStore.jsonValue( + wait.watch_json ?? "null", + ) as unknown as PullRequestWatch; + yield* forge.pullRequests.read(watch.pullRequest as PullRequestAddress).pipe( + // Each look keeps where the pull request stands on the wait's own step. + Effect.provideContext(stepReferences(store, wait.run_id, wait.name)), + Effect.flatMap( + Effect.fnUntraced(function* (detail) { + const standing = standingOf(detail); + // How long the host has listed no checks, not how long the wait is open: a push can + // clear the list for a moment in the middle of a long wait. + if (standing.checks !== "none") noChecksSince.delete(id); + else if (!noChecksSince.has(id)) noChecksSince.set(id, now); + const without = now - (noChecksSince.get(id) ?? now); + if (!isSettled(watch.until, standing, without)) return; + const woke = { expired: false, value: standing }; + if (!(yield* store.waitSignalled(wait.run_id, wait.name, woke))) return; + lookedAt.delete(id); + noChecksSince.delete(id); + yield* wake(wait, woke); + }), + ), + // The wait's own timeout is what ends a wait on something that cannot be read. + Effect.catch((error) => + Effect.logWarning("A workflow could not look at a pull request", { wait: id, error }), + ), + ); + } + }).pipe(Effect.withSpan("Workflows.fireWatches")); + + const hooks = yield* Effect.forEach( + latestDefinitions.flatMap((definition) => + definition.triggers.flatMap((trigger) => + trigger.kind === "webhook" ? [{ definition, trigger }] : [], + ), + ), + Effect.fnUntraced(function* ({ definition, trigger }) { + const hookId = hookIdOf(definition.name, trigger.name); + const token = yield* store.hookToken(hookId, yield* random.uuidV4()); + return { + hookId, + token, + trigger, + workflow: definition.name, + name: trigger.name, + path: `/api/hooks/${encodeURIComponent(hookId)}/${token}`, + }; + }), + ); + const deliver: Workflows["Service"]["deliver"] = Effect.fn("Workflows.deliver")( + function* (delivery) { + const hook = hooks.find((candidate) => candidate.hookId === delivery.hookId); + // A wrong token reads the same as an unknown hook, so the URL does not say which exist. + const known = + hook !== undefined && + (yield* constantTimeEquals(delivery.token, hook.token).pipe( + Effect.provideService(Digest.Digest, digest), + Effect.orElseSucceed(() => false), + )); + if (!known) return Option.none(); + const authored = yield* Effect.try({ + try: () => hook.trigger.key?.(delivery.request), + catch: (error) => + new WorkflowInputError({ + problem: `The key of hook ${hook.name} could not be read from the request: ${text(error)}`, + }), + }); + // A sender's own delivery id is kept on its retry, so the retry is the same run. + const sent = DELIVERY_HEADERS.find((header) => delivery.request.headers[header]); + const key = + authored ?? + (sent === undefined ? undefined : `${sent}:${delivery.request.headers[sent]}`) ?? + delivery.deliveryId ?? + (yield* random.uuidV4()); + return Option.some( + yield* start(hook.workflow, delivery.request, { + idempotencyKey: `hook:${hook.hookId}:${key}`, + }), + ); + }, + ); + + /** With `pause`, the sweep's own resume, which only resumes that pause and not a later one. */ + const resumeRun = Effect.fn("WorkflowEngine.resumeRun")(function* ( + runId: string, + pause?: WorkflowStore.RunRow, + ) { + const row = yield* requireRun(runId); + const engine = byTag.get(row.engine_tag); + if (engine === undefined) { + return yield* new WorkflowNotRegisteredError({ workflow: row.engine_tag }); + } + if (row.ended_at !== null) return; + resuming.add(runId); + const resumed = yield* Effect.gen(function* () { + // Marked first: once the engine is resumed, the step may fail again and pause the run, and + // that must be the last word. A crash in between leaves `running`, which the sweep corrects. + if (row.status === "paused") { + const unpaused = yield* store.runUnpaused( + runId, + pause === undefined + ? undefined + : { pauses: Number(pause.pauses), updatedAt: pause.updated_at }, + ); + if (!unpaused && pause !== undefined) return false; + } + // The step marks its run paused from inside the engine, a moment before the engine records + // the failure. Resuming in that moment would do nothing, so the record is waited for. + yield* withEngine(engine.poll(runId)).pipe( + Effect.repeat({ + until: (result) => Option.isSome(result) && result.value._tag === "Suspended", + schedule: Schedule.spaced(RESUME_LOOK_EVERY), + times: RESUME_LOOKS, + }), + ); + yield* withEngine(engine.resume(runId)); + yield* store.runUnheld(runId); + return true; + }).pipe(Effect.ensuring(Effect.sync(() => resuming.delete(runId)))); + // Read once `resuming` is clear, so a wake held back meanwhile is among them. + if (!resumed) return; + for (const wait of yield* store.waitsClaimed(runId)) { + yield* send(wait, WorkflowStore.jsonValue(wait.woke_json ?? "null") as typeof Woke.Type); + } + }); + const resume: Workflows["Service"]["resume"] = (runId) => resumeRun(runId); + + /** A run the engine holds as failed while its row says it goes on: paused, after all. */ + const reconcile = Effect.fn("WorkflowEngine.reconcile")(function* (row: WorkflowStore.RunRow) { + if (resuming.has(row.run_id)) return; + const engine = byTag.get(row.engine_tag); + if (engine === undefined) return; + const result = yield* withEngine(engine.poll(row.run_id)); + if (Option.isNone(result) || result.value._tag !== "Suspended") return; + if (result.value.failed !== true) return; + const cause = result.value.cause; + // Held as it was: a run that waited for a person still does. + yield* store.runPaused( + row.run_id, + cause === undefined ? "A step failed." : text(Cause.squash(cause)), + ); + }); + + // A cancelled run's body is gone, so its `onEnd` runs here, outside the engine. The sweep asks + // again after a failure or a restart, and `ending` keeps the two from running it at once. + const ending = new Set(); + const endCancelled = Effect.fn("WorkflowEngine.endCancelled")(function* ( + row: WorkflowStore.RunRow, + ) { + const definition = definitionByTag.get(row.engine_tag); + if (definition?.onEnd === undefined || ending.has(row.run_id)) return; + const onEnd = definition.onEnd; + ending.add(row.run_id); + // A step still running would race the cleanup: a machine deleted before it is made. + yield* link.inFlight.settled(row.run_id); + // The body may have run its own `onEnd` just as the run was cancelled: once is enough. + const steps = yield* store.steps(row.run_id); + if (steps.some((step) => step.name === END_STEP && step.status === "completed")) { + ending.delete(row.run_id); + return; + } + yield* store.stepStarted(row.run_id, END_STEP, "step"); + const payloadCodec = Schema.toCodecJson(definition.payload); + const decode = Schema.decodeEffect(payloadCodec); + yield* decode(row.input_json === null ? null : WorkflowStore.jsonValue(row.input_json)).pipe( + Effect.flatMap((input) => + onEnd(input as never, { + id: row.run_id, + outcome: "cancelled", + reason: row.detail ?? undefined, + }), + ), + Effect.provideContext(forStep(store, keyValues, link, forge, row.run_id, END_STEP)), + // The sweep that runs it reads the engine's BigInts; the cleanup's own code must not. + Effect.provideService(SqlClient.SafeIntegers, false), + Effect.matchCauseEffect({ + onSuccess: () => store.stepEnded(row.run_id, END_STEP, "completed", null), + onFailure: (cause) => + store.stepEnded(row.run_id, END_STEP, "failed", text(Cause.squash(cause))), + }), + Effect.ensuring(Effect.sync(() => ending.delete(row.run_id))), + ); + }); + + const prune = Effect.fn("WorkflowEngine.prune")(function* (at: DateTime.Utc) { + if (Option.isNone(messages) || Option.isNone(sharding)) return; + const before = DateTime.formatIso(DateTime.subtractDuration(at, PRUNE_AFTER)); + for (const row of yield* store.prunable(before, PRUNE_BATCH)) { + const entityId = EntityId.make(row.run_id); + const shardId = sharding.value.getShardId(entityId, "default"); + // Its sleeps are entities of their own under the same id. + yield* Effect.forEach( + [`Workflow/${row.engine_tag}`, "Workflow/-/DurableClock"], + (type) => + messages.value.clearAddress( + EntityAddress.make({ shardId, entityType: EntityType.make(type), entityId }), + ), + { discard: true }, + ).pipe( + Effect.andThen(store.enginePruned(row.run_id)), + // Left unmarked, so the next sweep tries it again. + Effect.catchCause((cause) => + Effect.logWarning("Could not prune a workflow run's engine journal", cause), + ), + ); + } + }); + + const sweep: Workflows["Service"]["sweep"] = Effect.gen(function* () { + for (const wait of yield* store.waitsPastDeadline) { + const woke = { expired: true, value: null }; + if (yield* store.waitSignalled(wait.run_id, wait.name, woke)) yield* wake(wait, woke); + } + // A claim whose wake a crash swallowed: the wake is made again. Waking twice is harmless. + for (const wait of yield* store.waitsToWake) { + if (wait.woke_json === null) continue; + yield* wake(wait, WorkflowStore.jsonValue(wait.woke_json) as typeof Woke.Type); + } + // A cancel that was cut short before it reached what the run had invoked. + for (const child of yield* store.orphans) { + yield* Effect.ignore(cancel(child.run_id, "the run that invoked it was cancelled")); + } + // A cancel cut short after the run was ended: what it had not stopped yet is stopped here. + for (const row of yield* store.cancelsCutShort(END_STEP)) { + if (cancelling.has(row.run_id) || ending.has(row.run_id)) continue; + const engine = byTag.get(row.engine_tag); + if (engine !== undefined) yield* withEngine(engine.interrupt(row.run_id)); + yield* stopSteps(row.run_id, yield* store.runningThreads(row.run_id)); + } + // A run that ended without its parent hearing of it. Telling twice is harmless. + for (const child of yield* store.untold) yield* ended(child.run_id); + yield* store.mailExpire; + yield* fireSchedules; + yield* fireOpened; + yield* fireWatches; + const at = yield* DateTime.now; + // A run with a step still going is ended by its cancel, which waits for that step. + for (const row of yield* store.runsToEnd(END_STEP, END_TRIES)) { + const rest = END_AFTER[Number(row.end_attempts ?? 0) - 1]; + if (row.end_ended_at !== null && rest !== undefined) { + const due = DateTime.addDuration( + DateTime.makeUnsafe(row.end_ended_at), + Duration.fromInputUnsafe(rest), + ); + if (DateTime.isLessThan(at, due)) continue; + } + if (!link.inFlight.busy(row.run_id)) yield* endCancelled(row); + } + for (const row of yield* store.everyRun("running")) yield* reconcile(row); + for (const row of yield* store.everyRun("waiting")) yield* reconcile(row); + for (const row of yield* store.everyRun("paused")) { + const due = resumesAt(row); + if (due === undefined || DateTime.isLessThan(at, due)) continue; + yield* Effect.ignore(resumeRun(row.run_id, row)); + } + yield* prune(at); + }).pipe(Effect.withSpan("Workflows.sweep")); + + // With nothing registered there is nothing to resume, end or start: only history to read. + if (registered.length > 0) { + yield* sweep.pipe( + Effect.catchCause((cause) => Effect.logWarning("Workflow sweep failed", cause)), + Effect.andThen(Effect.sleep(SWEEP_EVERY)), + Effect.forever, + Effect.forkScoped, + ); + } + + const questions = Effect.flatMap(store.requests, (waits) => + Effect.forEach( + waits.filter((wait) => wait.request_json !== null), + (wait) => + Effect.map(store.latestThread(wait.run_id), (thread) => ({ + runId: wait.run_id, + name: wait.name, + request: WorkflowStore.jsonValue(wait.request_json ?? "null"), + askedAt: wait.opened_at, + thread, + })), + ), + ); + const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + const triggerText = (trigger: WorkflowDefinition["triggers"][number]) => { + if (trigger.kind === "webhook") return `webhook ${trigger.name}`; + if (trigger.kind !== "schedule") { + return `new ${trigger.kind === "issues" ? "issues" : "pull requests"} in ${trigger.project}`; + } + if (trigger.schedule.type === "interval") { + return `every ${Duration.format(Duration.millis(trigger.schedule.everyMs))}`; + } + const days = trigger.schedule.weekdays; + return `daily at ${trigger.schedule.timeOfDay}${ + days === undefined ? "" : ` on ${days.map((day) => WEEKDAYS[day] ?? day).join(", ")}` + }`; + }; + const summaries = [...new Set(registered.map(([definition]) => definition.name))].flatMap( + (name) => { + const found = latest(name); + return found === undefined + ? [] + : [{ name, version: found[0].version, triggers: found[0].triggers.map(triggerText) }]; + }, + ); + const snapshot = Effect.all({ + workflows: Effect.succeed(summaries), + runs: Effect.map(store.runs(undefined), (rows) => rows.map(toRun)), + questions, + }); + const watch: Workflows["Service"]["watch"] = Stream.unwrap( + Effect.gen(function* () { + // Subscribed before the first look, so a change in between is not missed. + const changes = yield* PubSub.subscribe(store.changes); + return Stream.concat( + Stream.fromEffect(snapshot), + // A run writes several rows per step; one list answers a burst of them. + Stream.fromSubscription(changes).pipe( + Stream.debounce(WATCH_SETTLE), + Stream.mapEffect(() => snapshot), + ), + ); + }), + ); + + const counts: Workflows["Service"]["counts"] = Stream.unwrap( + Effect.gen(function* () { + const changes = yield* PubSub.subscribe(store.changes); + return Stream.concat( + Stream.fromEffect(store.counts), + Stream.fromSubscription(changes).pipe( + Stream.debounce(WATCH_SETTLE), + Stream.mapEffect(() => store.counts), + ), + // Most changes move no count, and a badge has no use for hearing of those. + ).pipe(Stream.changesWith((left, right) => JSON.stringify(left) === JSON.stringify(right))); + }), + ); + + const signal: Workflows["Service"]["signal"] = Effect.fn("Workflows.signal")( + function* (address, value, options) { + // A sender's retry of a signal that already woke a wait is not a second signal. + if (yield* store.signalSeen(options.id)) return "delivered" as const; + const valueJson = WorkflowStore.jsonText(value); + const woke = { expired: false, value }; + // One signal per wait: a wait another signal took first sends this one to the next. + while (true) { + const wait = yield* store.waitAt(address); + if (wait === undefined) break; + const schema = WorkflowStore.jsonValue(wait.schema_json) as Record; + const checked = yield* checkOutput(schema, valueJson); + if (Result.isFailure(checked)) { + return yield* new WorkflowInputError({ + problem: `The value does not fit what ${wait.name} waits for. ${rejectionText(checked.failure)}`, + }); + } + if (yield* store.waitSignalled(wait.run_id, wait.name, woke, options.id)) { + yield* wake(wait, woke); + return "delivered" as const; + } + // Refused for its id: the same signal, sent again at once, woke a wait. + if (yield* store.signalSeen(options.id)) return "delivered" as const; + } + const expiresAt = DateTime.formatIso( + DateTime.addDuration( + yield* DateTime.now, + Duration.fromInputUnsafe(options.ttl ?? DEFAULT_SIGNAL_TTL), + ), + ); + if (yield* store.signalSeen(options.id)) return "delivered" as const; + yield* store.mailPut({ signalId: options.id, address, valueJson, expiresAt }); + // The wait may have opened and looked for mail between the look above and this write. + while (true) { + const late = yield* store.waitAt(address); + if (late === undefined) return "buffered" as const; + const schema = WorkflowStore.jsonValue(late.schema_json) as Record; + // Kept for a wait it fits; this one, the oldest on the channel, is not it. + if (Result.isFailure(yield* checkOutput(schema, valueJson))) return "buffered" as const; + const outcome = yield* store.mailDeliver(options.id, late.run_id, late.name, woke); + if (outcome === "delivered") { + yield* wake(late, woke); + return "delivered" as const; + } + // The kept copy went to a wait that opened, or was dropped as already delivered. + if (outcome === "gone") return "delivered" as const; + } + }, + ); + const answer: Workflows["Service"]["answer"] = Effect.fn("Workflows.answer")( + function* (runId, name, value) { + const wait = yield* store.waitAt({ runId, wait: name }); + // Answered already, or never asked: kept, it would answer whatever asks there next. + if (wait === undefined || wait.request_json === null) return; + // Named by this asking of the question, so every answer to it is one signal. + yield* signal({ runId, wait: name }, value, { id: `answer:${wait.token}` }); + }, + ); + const signalAll = Effect.fn("WorkflowEngine.signalAll")(function* ( + address: { readonly channel: string; readonly workflow?: string | undefined }, + value: Schema.Json, + ) { + const valueJson = WorkflowStore.jsonText(value); + let woken = 0; + for (const wait of yield* store.waitsOn(address.channel, address.workflow)) { + const schema = WorkflowStore.jsonValue(wait.schema_json) as Record; + // A wait this value does not fit was not waiting for it; the others are still woken. + if (Result.isFailure(yield* checkOutput(schema, valueJson))) continue; + const woke = { expired: false, value }; + if (!(yield* store.waitSignalled(wait.run_id, wait.name, woke))) continue; + yield* wake(wait, woke); + woken++; + } + return woken; + }); + /** Tell the run that invoked this one, if one did, how it ended. */ + const ended = Effect.fn("WorkflowEngine.ended")(function* (runId: string) { + const row = yield* store.run(runId); + if (row === undefined || row.parent_run_id === null || row.parent_wait === null) return; + if (row.ended_at === null) return; + yield* signal( + { runId: row.parent_run_id, wait: row.parent_wait }, + { + outcome: row.status, + value: row.result_json === null ? null : WorkflowStore.jsonValue(row.result_json), + ...(row.detail === null ? {} : { reason: row.detail }), + }, + { id: `${runId}/ended` }, + ).pipe(Effect.ignore); + }); + + /** A step in flight cannot be interrupted, so the agent it waits on is stopped instead. */ + const stopSteps = Effect.fn("WorkflowEngine.stopSteps")(function* ( + runId: string, + threads: ReadonlyArray[0]>, + ) { + yield* Effect.forEach(threads, (thread) => Effect.ignore(stopTurn(thread)), { + discard: true, + }); + yield* store.stepsCancelled(runId, END_STEP); + }); + + // Cancels under way, whose slow part the sweep must not take for one cut short. + const cancelling = new Set(); + const cancel: Workflows["Service"]["cancel"] = Effect.fn("Workflows.cancel")( + function* (runId, reason) { + const row = yield* requireRun(runId); + if (row.ended_at !== null) return; + const threads = yield* store.runningThreads(runId); + const engine = byTag.get(row.engine_tag); + cancelling.add(runId); + yield* Effect.gen(function* () { + // Ended first, so nothing the run still does can be recorded as its outcome. A run that + // finished in the meantime keeps its own ending, and its cleanup is its own. Not cut off + // midway: the engine would go on with a cancelled run, or its parent wait forever. + const cancelled = yield* Effect.uninterruptible( + Effect.gen(function* () { + if (!(yield* store.runEnded(runId, "cancelled", reason ?? null, null))) return false; + if (engine !== undefined) yield* withEngine(engine.interrupt(runId)); + yield* ended(runId); + return true; + }), + ); + if (!cancelled) return; + yield* stopSteps(runId, threads); + // What this run invoked was part of it. + yield* Effect.forEach( + yield* store.children(runId), + (child) => Effect.ignore(cancel(child.run_id, reason)), + { discard: true }, + ); + // Waited for briefly, so the caller usually hears of a run that is cleaned up. A cleanup + // can take minutes; it goes on by itself, and the sweep finishes one that is cut short. + const cleanup = yield* Effect.forkIn( + endCancelled({ ...row, detail: reason ?? null }), + scope, + ); + yield* Fiber.join(cleanup).pipe(Effect.timeoutOption(CANCEL_WAITS)); + }).pipe(Effect.ensuring(Effect.sync(() => cancelling.delete(runId)))); + }, + ); + + // Steps were registered before this engine existed; now they can reach it. + link.current = { + signal, + signalAll, + start, + ended, + cancel: (runId, reason) => cancel(runId, reason), + list: Effect.fn("WorkflowEngine.list")(function* (filter) { + return (yield* store.runsWhere(filter)).map((row) => ({ + id: row.run_id, + workflow: row.workflow, + key: row.idempotency_key, + title: row.title, + status: row.status, + detail: row.detail, + startedAt: row.started_at, + endedAt: row.ended_at, + })); + }), + }; + + return Workflows.of({ + start, + hooks: Effect.succeed(hooks.map(({ workflow, name, path }) => ({ workflow, name, path }))), + // A cancelled run whose cleanup has not worked yet still needs its version to run it. + unfinished: Effect.map( + Effect.all([store.unfinished, store.runsToEnd(END_STEP, END_TRIES)]), + ([open, ending]) => [ + ...open, + ...ending + .filter((row) => definitionByTag.get(row.engine_tag)?.onEnd !== undefined) + .map((row) => ({ workflow: row.workflow, version: Number(row.version) })), + ], + ), + deliver, + signal, + answer, + resume, + cancel, + get: Effect.fn("Workflows.get")(function* (runId) { + const row = yield* requireRun(runId); + const steps = yield* store.steps(runId); + return { + run: toRun(row), + references: yield* store.references(runId), + steps: steps.map((step) => ({ + name: step.name, + kind: step.kind, + status: step.status, + attempts: Number(step.attempts), + detail: step.detail, + threadId: step.thread_id, + environmentId: step.environment_id, + result: step.result_json === null ? null : WorkflowStore.jsonValue(step.result_json), + said: step.said, + startedAt: step.started_at, + endedAt: step.ended_at, + })), + }; + }), + list: Effect.fn("Workflows.list")(function* (filter) { + return (yield* store.runs(filter?.status)).map(toRun); + }), + waitFor: Effect.fn("Workflows.waitFor")(function* (runId, done) { + // Subscribed before the first look, so a change in between is not missed. + const changes = yield* PubSub.subscribe(store.changes); + while (true) { + const row = yield* store.run(runId); + if (row !== undefined && done(toRun(row))) return toRun(row); + yield* Effect.repeat(PubSub.take(changes), { until: (changed) => changed === runId }); + } + }, Effect.scoped), + questions, + counts, + stored: Effect.fn("Workflows.stored")(function* (prefix) { + return (yield* keyValues.list(prefix)).map((row) => ({ + key: row.key, + value: WorkflowStore.jsonValue(row.valueJson), + })); + }), + storeSet: Effect.fn("Workflows.storeSet")(function* (key, value) { + yield* keyValues.set(key, WorkflowStore.jsonText(value)); + }), + storeDelete: Effect.fn("Workflows.storeDelete")(function* (key) { + yield* keyValues.delete(key); + }), + watch, + sweep, + }); +}); + +/** + * The workflow service with these definitions registered, on the SQLite database provided to it. + * Only one process may run this layer against a database. + */ +export const layer = ( + definitions: ReadonlyArray, + store: typeof WorkflowStore.layer = WorkflowStore.layer, +) => { + const registered = definitions.map( + (definition) => [definition, engineWorkflow(definition)] as const, + ); + const layerDefinitions = Layer.mergeAll( + Layer.empty, + ...registered.map(([definition, engine]) => layerDefinition(definition, engine)), + ); + return Layer.effect(Workflows, make(registered)).pipe( + Layer.provide(layerDefinitions), + Layer.provide(store), + Layer.provide(Layer.merge(layerKeyValues, layerEngineLink)), + Layer.provide( + registered.length === 0 + ? WorkflowEngine.layerMemory + : ClusterWorkflowEngine.layer.pipe( + // Merged so the sweep can prune ended runs' journals from the same storage. + Layer.provideMerge(SingleRunner.layer({ runnerStorage: "sql" })), + ), + ), + Layer.provide(Layer.succeed(SqlClient.SafeIntegers, true)), + ); +}; diff --git a/apps/server/src/workflows/WorkflowForge.test.ts b/apps/server/src/workflows/WorkflowForge.test.ts new file mode 100644 index 0000000000000..58f9626423510 --- /dev/null +++ b/apps/server/src/workflows/WorkflowForge.test.ts @@ -0,0 +1,113 @@ +import { assert, it } from "@effect/vitest"; +import { IssueTrackerKind, ProjectId } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as IssueService from "../issue/IssueService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as PullRequestService from "../pullRequest/PullRequestService.ts"; +import { StepReferences } from "./runReferences.ts"; +import * as WorkflowForge from "./WorkflowForge.ts"; +import type { ReferenceInput } from "./WorkflowStore.ts"; + +const projectId = ProjectId.make("project-1"); +const forge = WorkflowForge.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(IssueService.IssueService)({ comment: () => Effect.void }), + Layer.mock(PullRequestService.PullRequestService)({ + runAction: () => Effect.void as never, + detail: () => + Effect.succeed({ + projectId, + repository: "Me/App", + number: 7, + title: "Minutes wrap at the hour", + url: "https://github.com/Me/App/pull/7", + state: "merged", + } as never), + }), + Layer.mock(ProjectService.ProjectService)({ + getByWorkspaceRoot: () => Effect.succeedSome({ id: projectId } as never), + }), + ), + ), +); + +it.effect("what a step does through the forge is kept against it, one key per thing", () => + Effect.gen(function* () { + const { issues, pullRequests } = yield* WorkflowForge.WorkflowForge; + const noted: Array = []; + const inStep = Context.make(StepReferences, { + note: (reference) => Effect.sync(() => void noted.push(reference)), + }); + const issue = { + projectId, + tracker: IssueTrackerKind.make("github"), + host: "github.com", + scope: "me/app", + key: "3", + }; + yield* Effect.provideContext( + Effect.all([ + // By its address, then as a listing names it: the same pull request either way. + pullRequests.act( + { project: "/home/me/app", url: "https://github.com/Me/App/pull/7" }, + "merge", + ), + pullRequests.read({ projectId, host: "github.com", repository: "me/app", number: 7 }), + issues.comment(issue, "Looking at it."), + ]), + inStep, + ); + // Outside a step nothing is kept. + yield* issues.comment(issue, "Again."); + assert.deepStrictEqual( + noted.map(({ kind, key, title, state }) => ({ kind, key, title, state })), + [ + { kind: "pullRequest", key: noted[1]!.key, title: "", state: undefined }, + { + kind: "pullRequest", + key: '["github.com","me/app",7]', + title: "Minutes wrap at the hour", + state: "merged", + }, + { kind: "issue", key: '["github","github.com","me/app","3"]', title: "", state: undefined }, + ], + ); + assert.deepStrictEqual(noted[1]!.address, { + projectId, + host: "github.com", + repository: "me/app", + number: 7, + }); + }).pipe(Effect.provide(forge)), +); + +it("a step's pull requests are the ones its thread was linked to while it ran", () => { + const link = (number: number, linkedAt: string, source = "agent") => ({ + host: "github.com", + repository: "me/app", + number, + url: `https://github.com/me/app/pull/${number}`, + source, + linkedAt, + snapshot: null, + }); + const references = WorkflowForge.linkedPullRequestReferences( + { + projectId, + pullRequests: [ + link(1, "2026-01-01T00:00:00.000Z"), + link(2, "2026-01-01T00:10:00.000Z"), + link(3, "2026-01-01T00:10:00.000Z", "stack-dismissed"), + ] as never, + }, + Date.parse("2026-01-01T00:05:00.000Z"), + ); + assert.deepStrictEqual( + references.map((reference) => [reference.key, reference.url]), + [['["github.com","me/app",2]', "https://github.com/me/app/pull/2"]], + ); +}); diff --git a/apps/server/src/workflows/WorkflowForge.ts b/apps/server/src/workflows/WorkflowForge.ts new file mode 100644 index 0000000000000..dab867593b4dd --- /dev/null +++ b/apps/server/src/workflows/WorkflowForge.ts @@ -0,0 +1,455 @@ +// Issues and pull requests for workflows: the same trackers and hosts the app's own Issues and +// Pull requests pages read, through the project's credentials. A step names a project the way +// an agent step does, by id or by folder. +import { + IssueDetail, + IssueListEntry, + type IssueCreateResult, + type IssueListState, + type IssueRef, + type PullRequestAction, + type PullRequestDetail, + PullRequestListEntry, + type PullRequestListState, + type PullRequestMergeMethod, + type PullRequestRef, + ProjectId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +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 IssueService from "../issue/IssueService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as PullRequestService from "../pullRequest/PullRequestService.ts"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; +import { + normalizeThreadPullRequestKey, + threadPullRequestsOf, +} from "../sourceControl/threadPullRequests.ts"; +import { issueReference, noteReference, pullRequestReference } from "./runReferences.ts"; +import { isProjectPath } from "./WorkflowAgents.ts"; + +export class WorkflowForgeError extends Schema.TaggedError()( + "WorkflowForgeError", + { reason: Schema.String }, +) { + override get message(): string { + return this.reason; + } +} + +/** What an issue trigger gives its run, and what `issues.list` returns rows of. */ +export const Issue = IssueListEntry; +export type Issue = typeof Issue.Type; +/** What a pull request trigger gives its run, and what `pullRequests.list` returns rows of. */ +export const PullRequest = PullRequestListEntry; +export type PullRequest = typeof PullRequest.Type; +export { IssueDetail }; + +/** An issue by its web address, or as a trigger or a listing gave it. */ +export type IssueAddress = + | { readonly project: string; readonly url: string } + | Pick; +/** A pull request by its web address, or as a trigger or a listing gave it. */ +export type PullRequestAddress = + | { readonly project: string; readonly url: string } + | Pick; + +/** Where a pull request stands, as a wait on it gives it. */ +export const PullRequestStanding = Schema.Struct({ + state: Schema.Literals(["open", "closed", "merged"]), + /** `none` when the host lists no checks for it. */ + checks: Schema.Literals(["passing", "failing", "pending", "none"]), + mergeability: Schema.Literals(["mergeable", "conflicting", "unknown"]), + url: Schema.String, +}); +export type PullRequestStanding = typeof PullRequestStanding.Type; +export type PullRequestUntil = "checks" | "merged" | "closed"; +/** What a wait on a pull request keeps for the engine to look at. */ +export interface PullRequestWatch { + readonly kind: "pullRequest"; + readonly until: PullRequestUntil; + readonly pullRequest: + | { readonly project: string; readonly url: string } + | { + readonly projectId: string; + readonly host: string; + readonly repository: string; + readonly number: number; + }; +} + +// Checks take a moment to be listed after a push, so "none" only counts once it has stayed none. +const NO_CHECKS_AFTER_MS = 2 * 60_000; + +/** Required checks decide when the host marks any as required; otherwise all of them do. */ +export const standingOf = ( + detail: Pick, +): PullRequestStanding => { + const listed = detail.checks.filter((check) => check.placeholder !== true); + const counted = listed.some((check) => check.required === true) + ? listed.filter((check) => check.required === true) + : listed; + const failing = counted.some( + (check) => + check.status === "failure" || + check.status === "cancelled" || + // Nothing moves it but a person, so a run waiting for it would wait for good. + check.status === "action-required", + ); + const pending = counted.some((check) => check.status === "pending"); + return { + state: detail.state, + // Pending first: the wait is for none of them still running, even once one has failed. + checks: counted.length === 0 ? "none" : pending ? "pending" : failing ? "failing" : "passing", + mergeability: detail.mergeability, + url: detail.url, + }; +}; + +/** Whether a wait `until` this is over, the host having listed no checks for `withoutChecksMs`. */ +export const isSettled = ( + until: PullRequestUntil, + standing: PullRequestStanding, + withoutChecksMs: number, +): boolean => { + if (standing.state !== "open") return true; + if (until !== "checks") return false; + if (standing.checks === "none") return withoutChecksMs >= NO_CHECKS_AFTER_MS; + return standing.checks !== "pending"; +}; + +export interface IssueQuery { + readonly project: string; + /** Defaults to open. */ + readonly state?: IssueListState | undefined; + /** Label names an issue must carry, every one of them. */ + readonly labels?: ReadonlyArray | undefined; + /** Free text the tracker matches itself. */ + readonly query?: string | undefined; + readonly assignee?: string | undefined; + readonly sort?: "updated" | "created" | undefined; + readonly limit?: number | undefined; +} +export interface PullRequestQuery { + readonly project: string; + /** Defaults to open. */ + readonly state?: PullRequestListState | undefined; + readonly query?: string | undefined; + readonly limit?: number | undefined; +} + +type PullRequestSeen = Parameters[1]; +/** A pull request as a run's reference, under the key every way of naming it shares. */ +export const pullRequestReferenceOf = ( + ref: Pick, + seen?: PullRequestSeen, +) => + pullRequestReference( + { + projectId: ref.projectId, + ...normalizeThreadPullRequestKey({ + host: ref.host ?? "", + repository: ref.repository, + number: ref.number, + ...(seen?.url === undefined ? {} : { url: seen.url }), + }), + }, + seen, + ); + +/** The pull requests linked to a thread from `sinceMillis` on, as references of its step. */ +export const linkedPullRequestReferences = ( + thread: Parameters[0] & { readonly projectId: ProjectId }, + sinceMillis: number | undefined, +) => + threadPullRequestsOf(thread) + .filter( + (link) => + link.source !== "stack-dismissed" && + (sinceMillis === undefined || Date.parse(link.linkedAt) >= sinceMillis), + ) + .map((link) => + pullRequestReferenceOf( + { + projectId: thread.projectId, + host: link.host, + repository: link.repository, + number: link.number, + }, + link.snapshot === null + ? { url: link.url } + : { url: link.url, title: link.snapshot.title, state: link.snapshot.state }, + ), + ); + +export class WorkflowForge extends Context.Service< + WorkflowForge, + { + readonly issues: { + readonly list: (query: IssueQuery) => Effect.Effect, WorkflowForgeError>; + readonly read: (issue: IssueAddress) => Effect.Effect; + readonly comment: ( + issue: IssueAddress, + body: string, + ) => Effect.Effect; + readonly setState: ( + issue: IssueAddress, + state: string, + ) => Effect.Effect; + readonly create: (input: { + readonly project: string; + readonly title: string; + readonly body?: string | undefined; + readonly labels?: ReadonlyArray | undefined; + readonly assignees?: ReadonlyArray | undefined; + }) => Effect.Effect; + }; + readonly pullRequests: { + readonly list: ( + query: PullRequestQuery, + ) => Effect.Effect, WorkflowForgeError>; + readonly read: ( + pullRequest: PullRequestAddress, + ) => Effect.Effect; + readonly comment: ( + pullRequest: PullRequestAddress, + body: string, + ) => Effect.Effect; + readonly act: ( + pullRequest: PullRequestAddress, + action: PullRequestAction, + options?: { readonly mergeMethod?: PullRequestMergeMethod | undefined }, + ) => Effect.Effect; + }; + } +>()("t3/workflows/WorkflowForge") {} + +const failed = + (what: string) => + (cause: unknown): WorkflowForgeError => + new WorkflowForgeError({ + reason: `${what}: ${cause instanceof Error ? cause.message : String(cause)}`, + }); + +const missing = (what: string) => () => + Effect.fail( + new WorkflowForgeError({ + reason: `${what} are not available to workflows on this server.`, + }), + ); +/** For an engine with no trackers behind it: every call says so. */ +export const unavailable = WorkflowForge.of({ + issues: { + list: missing("Issues"), + read: missing("Issues"), + comment: missing("Issues"), + setState: missing("Issues"), + create: missing("Issues"), + }, + pullRequests: { + list: missing("Pull requests"), + read: missing("Pull requests"), + comment: missing("Pull requests"), + act: missing("Pull requests"), + }, +}); + +export const layer = Layer.effect( + WorkflowForge, + Effect.gen(function* () { + const issues = yield* IssueService.IssueService; + const pullRequests = yield* PullRequestService.PullRequestService; + const projects = yield* ProjectService.ProjectService; + + const projectIdOf = Effect.fn("WorkflowForge.projectIdOf")(function* (project: string) { + if (!isProjectPath(project)) return ProjectId.make(project); + const found = yield* projects + .getByWorkspaceRoot(project) + .pipe(Effect.mapError(failed("Could not read the project"))); + if (Option.isNone(found)) { + return yield* new WorkflowForgeError({ reason: `No project is registered at ${project}.` }); + } + return found.value.id; + }); + + const issueRef = Effect.fn("WorkflowForge.issueRef")(function* (issue: IssueAddress) { + if (!("project" in issue)) { + return { + projectId: issue.projectId, + tracker: issue.tracker, + host: issue.host, + scope: issue.scope, + key: issue.key, + } satisfies IssueRef; + } + const resolved = yield* issues + .resolveUrl(issue.url, yield* projectIdOf(issue.project)) + .pipe(Effect.mapError(failed(`Could not find the issue at ${issue.url}`))); + return { + projectId: resolved.projectId, + tracker: resolved.tracker, + host: resolved.host, + scope: resolved.scope, + key: resolved.key, + } satisfies IssueRef; + }); + + const pullRequestRef = Effect.fn("WorkflowForge.pullRequestRef")(function* ( + pullRequest: PullRequestAddress, + ) { + if (!("project" in pullRequest)) { + return { + projectId: pullRequest.projectId, + host: pullRequest.host, + repository: pullRequest.repository, + number: pullRequest.number, + } satisfies PullRequestRef; + } + const parsed = sourceControlDefinitions.parseChangeRequestUrl(pullRequest.url)?.link; + if (parsed === undefined) { + return yield* new WorkflowForgeError({ + reason: `${pullRequest.url} is not a pull request address.`, + }); + } + const key = normalizeThreadPullRequestKey(parsed); + return { + projectId: yield* projectIdOf(pullRequest.project), + host: key.host, + repository: key.repository, + number: key.number, + } satisfies PullRequestRef; + }); + + // An address that is a whole listing row already says what the item is called. + const seenOf = (address: object) => ({ + ...("title" in address && typeof address.title === "string" ? { title: address.title } : {}), + ...("url" in address && typeof address.url === "string" ? { url: address.url } : {}), + }); + const issueTouched = (ref: IssueRef, address: IssueAddress) => + noteReference({ ...issueReference(ref), ...seenOf(address) }); + const pullRequestTouched = (ref: PullRequestRef, seen: PullRequestSeen) => + noteReference(pullRequestReferenceOf(ref, seen)); + + return WorkflowForge.of({ + issues: { + list: Effect.fn("WorkflowForge.issues.list")(function* (query) { + const result = yield* issues + .list({ + projectId: yield* projectIdOf(query.project), + state: query.state ?? "open", + ...(query.labels === undefined ? {} : { labels: [...query.labels] }), + ...(query.query === undefined ? {} : { query: query.query }), + ...(query.assignee === undefined ? {} : { assignee: query.assignee }), + ...(query.sort === undefined ? {} : { sort: query.sort }), + ...(query.limit === undefined ? {} : { limit: query.limit }), + }) + .pipe(Effect.mapError(failed("Could not list issues"))); + // A listing answers with what it could read. One that read nothing is a failure. + const problem = result.errors[0]; + if (result.entries.length === 0 && problem !== undefined) { + return yield* new WorkflowForgeError({ + reason: `Could not list issues: ${problem.message}`, + }); + } + return result.entries; + }), + read: Effect.fn("WorkflowForge.issues.read")(function* (issue) { + const ref = yield* issueRef(issue); + const detail = yield* issues + .detail(ref) + .pipe(Effect.mapError(failed("Could not read the issue"))); + yield* noteReference(issueReference(ref, detail)); + return detail; + }), + comment: Effect.fn("WorkflowForge.issues.comment")(function* (issue, body) { + const ref = yield* issueRef(issue); + yield* issues + .comment({ ...ref, body }) + .pipe(Effect.mapError(failed("Could not comment on the issue"))); + yield* issueTouched(ref, issue); + }), + setState: Effect.fn("WorkflowForge.issues.setState")(function* (issue, state) { + const ref = yield* issueRef(issue); + yield* issues + .setState({ ...ref, state }) + .pipe(Effect.mapError(failed("Could not change the issue's state"))); + yield* issueTouched(ref, issue); + }), + create: Effect.fn("WorkflowForge.issues.create")(function* (input) { + const scope = yield* issues + .projectScope(yield* projectIdOf(input.project)) + .pipe(Effect.mapError(failed("Could not find the project's issue tracker"))); + const created = yield* issues + .create({ + projectId: scope.projectId, + tracker: scope.tracker, + host: scope.host, + scope: scope.scope, + title: input.title, + body: input.body ?? "", + labels: [...(input.labels ?? [])], + assignees: [...(input.assignees ?? [])], + }) + .pipe(Effect.mapError(failed("Could not file the issue"))); + yield* noteReference({ + ...issueReference({ ...scope, key: created.key }), + title: input.title, + url: created.url, + state: "open", + }); + return created; + }), + }, + pullRequests: { + list: Effect.fn("WorkflowForge.pullRequests.list")(function* (query) { + const result = yield* pullRequests + .list({ + projectId: yield* projectIdOf(query.project), + state: query.state ?? "open", + ...(query.query === undefined ? {} : { query: query.query }), + ...(query.limit === undefined ? {} : { limit: query.limit }), + }) + .pipe(Effect.mapError(failed("Could not list pull requests"))); + const problem = result.errors[0]; + if (result.entries.length === 0 && problem !== undefined) { + return yield* new WorkflowForgeError({ + reason: `Could not list pull requests: ${problem.message}`, + }); + } + return result.entries; + }), + read: Effect.fn("WorkflowForge.pullRequests.read")(function* (pullRequest) { + const ref = yield* pullRequestRef(pullRequest); + // Fresh, not a held copy: checks that passed before a push must not end a wait after it. + const detail = yield* pullRequests + .detail({ ...ref, allowStale: false }) + .pipe(Effect.mapError(failed("Could not read the pull request"))); + yield* pullRequestTouched(ref, detail); + return detail; + }), + comment: Effect.fn("WorkflowForge.pullRequests.comment")(function* (pullRequest, body) { + const ref = yield* pullRequestRef(pullRequest); + yield* pullRequests + .comment({ ...ref, body }) + .pipe(Effect.mapError(failed("Could not comment on the pull request"))); + yield* pullRequestTouched(ref, seenOf(pullRequest)); + }), + act: Effect.fn("WorkflowForge.pullRequests.act")(function* (pullRequest, action, options) { + const ref = yield* pullRequestRef(pullRequest); + yield* pullRequests + .runAction({ + ...ref, + action, + ...(options?.mergeMethod === undefined ? {} : { mergeMethod: options.mergeMethod }), + }) + .pipe(Effect.mapError(failed(`Could not ${action} the pull request`))); + yield* pullRequestTouched(ref, seenOf(pullRequest)); + }), + }, + }); + }), +); diff --git a/apps/server/src/workflows/WorkflowRuntime.test.ts b/apps/server/src/workflows/WorkflowRuntime.test.ts new file mode 100644 index 0000000000000..344e6d871efd9 --- /dev/null +++ b/apps/server/src/workflows/WorkflowRuntime.test.ts @@ -0,0 +1,464 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; +import { WorkflowAgents } from "./WorkflowAgents.ts"; +import * as WorkflowEngine from "./WorkflowEngine.ts"; +import * as WorkflowRuntime from "./WorkflowRuntime.ts"; +import { engineTag, type WorkflowDefinition } from "./workflow.ts"; +import * as Workflows from "./Workflows.ts"; + +/** Waits to be let go. */ +const hold = `T3.workflow("hold", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.map(T3.wait("go", { returns: Schema.String }), (said) => Option.getOrElse(said, () => "nobody")), +); +`; +const greet = (says: string) => `const { workflow } = T3; +workflow("greet", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.succeed(${JSON.stringify(says)}), +); +`; + +/** + * A folder holding `hold.ts`, and the workflow runtime over it on a fresh database. `engine` + * stands in for the real one, which needs the clock to run for as long as it is up. + */ +const setup = Effect.fn("setup")(function* ( + wrap: (fileSystem: FileSystem.FileSystem) => FileSystem.FileSystem = (fileSystem) => fileSystem, + engine?: (definitions: ReadonlyArray) => Layer.Layer, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-defs-" }); + const directory = path.join(home, "workflows"); + const at = (name: string) => path.join(directory, name); + yield* fileSystem.makeDirectory(directory); + yield* fileSystem.writeFileString(at("hold.ts"), hold); + const database = NodeSqliteClient.layer({ filename: path.join(home, "state.sqlite") }); + yield* Effect.provide(WorkflowsMigration, database); + const made = WorkflowRuntime.make( + Effect.succeed( + (definitions: ReadonlyArray) => + engine?.(definitions) ?? + WorkflowEngine.layer(definitions).pipe( + Layer.provide(Layer.mock(WorkflowAgents)({})), + Layer.provide(database), + Layer.provide(NodeCrypto.layer), + ), + ), + directory, + Effect.succeed(true), + ).pipe(Effect.provideService(FileSystem.FileSystem, wrap(fileSystem))); + return { fileSystem, at, directory, made, runtime: Layer.effectContext(made) }; +}); + +it.effect( + "every file in the folder defines workflows, and a saved file is verified before it runs", + () => + Effect.gen(function* () { + const { fileSystem, at, runtime } = yield* setup(); + + yield* Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const definitions = yield* WorkflowRuntime.WorkflowDefinitions; + const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" }); + yield* workflows.waitFor(held.runId, (run) => run.status === "waiting"); + + // A file that does not parse is not written, and says where it breaks. + const broken = yield* definitions.save("greet.ts", "T3.workflow(\n 'x',\n];\n"); + assert.isFalse(broken.changed); + assert.deepStrictEqual( + broken.problems.map((problem) => [problem.file, problem.line]), + [["greet.ts", 3]], + ); + // Nor is one that defines what another file already does, or drops what a run needs. + const twice = yield* definitions.save("again.ts", hold); + assert.include( + twice.problems[0]?.message ?? "", + "hold@1 is defined twice, in again.ts and hold.ts", + ); + const dropped = yield* definitions.save("hold.ts", greet("hello")); + assert.include( + dropped.problems[0]?.message ?? "", + "hold@1 is no longer defined, and 1 of its runs", + ); + // Nor one that exports something shaped like a workflow without what the engine walks. + const shaped = yield* definitions.save( + "shaped.ts", + 'export default [{ name: "shaped", version: 1, body: () => Effect.void }];\n', + ); + assert.include(shaped.problems[0]?.message ?? "", "is not a workflow"); + // Nor one with an option nothing reads, or a time a schedule cannot fire at. + const misspelt = yield* definitions.save( + "misspelt.ts", + 'T3.workflow("misspelt", { version: 1, payload: Schema.Struct({}), retries: 2 }, () => Effect.void);\n', + ); + assert.include(misspelt.problems[0]?.message ?? "", "does not take `retries`"); + const late = yield* definitions.save( + "late.ts", + 'T3.workflow("late", { version: 1, payload: T3.Tick, triggers: [T3.daily("9am")] }, () => Effect.void);\n', + ); + assert.include(late.problems[0]?.message ?? "", "24-hour time"); + const banana = yield* definitions.save( + "banana.ts", + 'T3.workflow("banana", { version: 1, payload: T3.Tick, triggers: [T3.every("banana")] }, () => Effect.void);\n', + ); + assert.include(banana.problems[0]?.message ?? "", 'Write one such as "5 minutes"'); + const twoHooks = yield* definitions.save( + "hooks.ts", + 'T3.workflow("hooks", { version: 1, payload: T3.WebhookRequest, triggers: [T3.webhook("in"), T3.webhook("in")] }, () => Effect.void);\n', + ); + assert.include(twoHooks.problems[0]?.message ?? "", 'two hooks named "in"'); + assert.include((yield* definitions.remove("hold.ts")).problems[0]?.message ?? "", "hold@1"); + assert.deepStrictEqual( + (yield* definitions.read).files.map((file) => file.name), + ["hold.ts"], + ); + // The same change made outside the app is refused as a whole: the file still reads as the + // version that runs, until it is put back. + const told = (wanted: boolean) => + workflows.watch.pipe( + Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted), + Stream.runHead, + ); + yield* fileSystem.writeFileString(at("hold.ts"), greet("hello")); + yield* told(true); + assert.deepStrictEqual( + (yield* definitions.read).files.map((file) => file.workflows), + [["hold@1"]], + ); + // Only that file is held back: another file's change still runs, and the held one says why. + const other = + 'T3.workflow("other", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n'; + // A file the folder's naming leaves out says so, instead of never running without a word. + yield* fileSystem.writeFileString(at("my flow.ts"), other); + assert.deepStrictEqual(yield* definitions.save("other.ts", other), { + changed: true, + problems: [], + }); + yield* workflows.start("other", {}, { idempotencyKey: "o" }); + assert.deepStrictEqual( + (yield* definitions.read).files.map((file) => [file.name, file.problems.length]), + [ + ["hold.ts", 1], + ["other.ts", 0], + ], + ); + assert.deepStrictEqual( + (yield* definitions.read).problems.map((problem) => problem.file), + ["my flow.ts"], + ); + yield* fileSystem.remove(at("my flow.ts")); + assert.deepStrictEqual(yield* definitions.remove("other.ts"), { + changed: true, + problems: [], + }); + yield* fileSystem.writeFileString(at("hold.ts"), hold); + yield* told(false); + + // A new file that passes is there from now on, and what it defines can be started. + const saved = { changed: true, problems: [] }; + assert.deepStrictEqual(yield* definitions.save("greet.ts", greet("hello")), saved); + assert.equal(yield* fileSystem.readFileString(at("greet.ts")), greet("hello")); + const greeted = yield* workflows.start("greet", {}, { idempotencyKey: "g" }); + const done = yield* workflows.waitFor(greeted.runId, (run) => run.status === "completed"); + assert.equal(done.result, "hello"); + // The run that was waiting came through the reload and can still be let go. + yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" }); + const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed"); + assert.equal(freed.result, "go on"); + + // Someone breaks a file outside the app: its last good version keeps running, and the + // other files go on changing. + const problem = (wanted: boolean) => + workflows.watch.pipe( + Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted), + Stream.runHead, + ); + yield* fileSystem.writeFileString(at("greet.ts"), "T3.workflow("); + yield* problem(true); + const read = yield* definitions.read; + assert.deepStrictEqual( + read.files.map((file) => [file.name, file.problems.length]), + [ + ["greet.ts", 1], + ["hold.ts", 0], + ], + ); + const still = yield* workflows.start("greet", {}, { idempotencyKey: "g2" }); + assert.equal( + (yield* workflows.waitFor(still.runId, (run) => run.status === "completed")).result, + "hello", + ); + // And fixes it, saying something else, this time as the file's one default export. + yield* fileSystem.writeFileString( + at("greet.ts"), + greet("hi").replace("\nworkflow(", "\nexport default workflow("), + ); + yield* problem(false); + const fixed = yield* workflows.start("greet", {}, { idempotencyKey: "g3" }); + assert.equal( + (yield* workflows.waitFor(fixed.runId, (run) => run.status === "completed")).result, + "hi", + ); + // A file taken away takes its workflows with it. + assert.deepStrictEqual(yield* definitions.remove("greet.ts"), saved); + const gone = yield* workflows + .start("greet", {}, { idempotencyKey: "g4" }) + .pipe(Effect.flip); + assert.equal(gone._tag, "WorkflowNotRegisteredError"); + // With no file left, nothing runs, and the runs that ended can still be read. + assert.deepStrictEqual(yield* definitions.remove("hold.ts"), saved); + assert.equal((yield* workflows.get(held.runId)).run.status, "completed"); + assert.includeMembers( + (yield* workflows.list()).map((run) => run.runId), + [held.runId, greeted.runId], + ); + }).pipe( + Effect.provide(runtime), + Effect.scoped, + Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "a folder that cannot be listed keeps its workflows and is looked at again, and an engine that cannot start leaves the last one running", + () => + Effect.gen(function* () { + let refuse = false; + // What each engine was built to run. One that registers `broken` does not come up. + const builds: Array> = []; + // No file events: only the runtime's own retry can pick up what changed. + const { at, fileSystem, runtime } = yield* setup( + (real) => ({ + ...real, + exists: (target) => + refuse + ? Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "exists", + pathOrDescriptor: target, + }), + ) + : real.exists(target), + watch: () => Stream.never, + }), + (definitions) => + definitions.some((definition) => definition.name === "broken") + ? Layer.effect(Workflows.Workflows, Effect.die(new Error("broken took it down"))) + : Layer.sync(Workflows.Workflows, () => { + builds.push(definitions.map(engineTag)); + return Workflows.disabled; + }), + ); + + yield* Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const definitions = yield* WorkflowRuntime.WorkflowDefinitions; + const revision = Effect.map( + Stream.runHead(workflows.watch), + (snapshot) => Option.getOrThrow(snapshot).definition?.revision ?? 0, + ); + refuse = true; + // Written, but the folder could not be listed, so it is not said to run. + const unlisted = yield* definitions.save("greet.ts", greet("hi")); + assert.isTrue(unlisted.changed); + assert.include(unlisted.problems[0]?.message ?? "", "could not be read"); + // What was loaded stays, and greet is not taken in yet. + assert.deepStrictEqual(builds, [["hold@1"]]); + const before = yield* revision; + refuse = false; + yield* TestClock.adjust("30 seconds"); + yield* workflows.watch.pipe( + Stream.filter((snapshot) => (snapshot.definition?.revision ?? 0) > before), + Stream.runHead, + ); + assert.deepStrictEqual(builds.at(-1), ["greet@1", "hold@1"]); + + // A definition that passes the checks but takes the engine down at start changes nothing. + yield* fileSystem.writeFileString( + at("broken.ts"), + 'T3.workflow("broken", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n', + ); + const fellBack = yield* definitions.save("greet.ts", greet("hello")); + assert.isTrue(fellBack.changed); + assert.include(fellBack.problems[0]?.message ?? "", "did not start"); + assert.deepStrictEqual(builds.slice(1), [ + ["greet@1", "hold@1"], + ["greet@1", "hold@1"], + ]); + assert.include( + (yield* Stream.runHead(workflows.watch)).pipe(Option.getOrThrow).definition?.problem ?? + "", + "did not start", + ); + }).pipe(Effect.provide(runtime), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a file that never finishes loading is given up on, and later files still load", () => + Effect.gen(function* () { + const { at, fileSystem } = yield* setup(); + yield* fileSystem.writeFileString(at("stuck.ts"), "await new Promise(() => {});\n"); + yield* fileSystem.writeFileString(at("greet.ts"), greet("hi")); + const stuck = yield* WorkflowRuntime.loadDefinitions(at("stuck.ts"), 0, 50).pipe(Effect.flip); + assert.include(String(stuck.cause), "did not finish loading"); + const loaded = yield* WorkflowRuntime.loadDefinitions(at("greet.ts")); + assert.deepStrictEqual( + loaded.map((definition) => definition.name), + ["greet"], + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a file given up on registers nothing into the file that loads after it", () => + Effect.gen(function* () { + const { at, fileSystem } = yield* setup(); + yield* fileSystem.writeFileString( + at("slow.ts"), + 'await new Promise((resolve) => { globalThis.t3TestResume = resolve; });\nT3.workflow("slow", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n', + ); + // The second file goes on loading until the first one's top level has run to its end. + yield* fileSystem.writeFileString( + at("next.ts"), + `${greet("hi")}globalThis.t3TestResume();\nawait new Promise((resolve) => setImmediate(resolve));\n`, + ); + yield* WorkflowRuntime.loadDefinitions(at("slow.ts"), 0, 50).pipe(Effect.flip); + const loaded = yield* WorkflowRuntime.loadDefinitions(at("next.ts")); + assert.deepStrictEqual( + loaded.map((definition) => definition.name), + ["greet"], + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +// Vitest's module runner loads a file its own way; only Node keeps a CommonJS file by its path. +it.live("a file without imports or exports loads again after it changes", () => + Effect.gen(function* () { + const { at, fileSystem } = yield* setup(); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + yield* fileSystem.writeFileString(at("greet.ts"), greet("hi")); + const twice = ` + import * as NodeFS from "node:fs"; + import * as NodeServices from "@effect/platform-node/NodeServices"; + import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; + import { loadDefinitions } from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)}; + const file = process.argv.at(-1); + const program = Effect.gen(function* () { + const first = yield* loadDefinitions(file, 1); + NodeFS.writeFileSync(file, NodeFS.readFileSync(file, "utf8").replace('"hi"', '"hello"')); + const second = yield* loadDefinitions(file, 2); + return [first.length, second.length]; + }); + console.log(JSON.stringify(await Effect.runPromise(Effect.provide(program, NodeServices.layer)))); + `; + const child = yield* spawner.spawn( + ChildProcess.make( + process.execPath, + ["--input-type=module", "--eval", twice, at("greet.ts")], + { cwd: import.meta.dirname }, + ), + ); + const [stdout, stderr] = yield* Effect.all( + [ + child.stdout.pipe(Stream.decodeText(), Stream.mkString), + child.stderr.pipe(Stream.decodeText(), Stream.mkString), + ], + { concurrency: "unbounded" }, + ); + assert.equal(stdout.trim(), "[1,1]", stderr); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a change held back by a run goes in once that run ends, with no further edit", () => + Effect.gen(function* () { + // The folder's changes are told by hand, so the test does not hang on a watcher starting. + const changed = yield* Queue.unbounded(); + const { fileSystem, at, runtime } = yield* setup((fileSystem) => ({ + ...fileSystem, + watch: () => Stream.fromQueue(changed), + })); + yield* Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const definitions = yield* WorkflowRuntime.WorkflowDefinitions; + const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" }); + yield* workflows.waitFor(held.runId, (run) => run.status === "waiting"); + const problem = (wanted: boolean) => + workflows.watch.pipe( + Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted), + Stream.runHead, + ); + yield* fileSystem.writeFileString(at("hold.ts"), greet("hello")); + yield* Queue.offer(changed, { _tag: "Update", path: at("hold.ts") }); + yield* problem(true); + yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" }); + yield* workflows.waitFor(held.runId, (run) => run.status === "completed"); + // Nothing is told of the folder now: the held change goes in on its own. + yield* problem(false); + assert.deepStrictEqual( + (yield* definitions.read).files.map((file) => file.workflows), + [["greet@1"]], + ); + }).pipe( + Effect.provide(runtime), + Effect.scoped, + Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "workflows are off until turned on, and a run left waiting when they are turned off goes on once they are on again", + () => + Effect.gen(function* () { + const { fileSystem, at, directory, made } = yield* setup(); + // Its top level counts the times it was loaded. + yield* fileSystem.writeFileString( + at("counted.ts"), + "globalThis.t3GatedLoads = (globalThis.t3GatedLoads ?? 0) + 1;\nexport default [];\n", + ); + const loads = () => (globalThis as { t3GatedLoads?: number }).t3GatedLoads ?? 0; + yield* Effect.gen(function* () { + const { turn, context } = yield* WorkflowRuntime.gate(made, directory); + const workflows = Context.get(context, Workflows.Workflows); + const definitions = Context.get(context, WorkflowRuntime.WorkflowDefinitions); + const start = workflows.start("hold", {}, { idempotencyKey: "h" }); + + assert.equal((yield* Effect.flip(start)).message, Workflows.OFF); + assert.equal((yield* Effect.flip(workflows.list())).message, Workflows.OFF); + assert.deepStrictEqual((yield* definitions.read).files, []); + assert.equal(loads(), 0); + + yield* turn(true); + assert.equal(loads(), 1); + const held = yield* start; + yield* workflows.waitFor(held.runId, (run) => run.status === "waiting"); + + yield* turn(false); + const signal = workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" }); + assert.equal((yield* Effect.flip(signal)).message, Workflows.OFF); + + yield* turn(true); + yield* signal; + const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed"); + assert.equal(freed.result, "go on"); + }).pipe(Effect.scoped, Effect.raceFirst(Effect.forever(TestClock.adjust("1 second")))); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); diff --git a/apps/server/src/workflows/WorkflowRuntime.ts b/apps/server/src/workflows/WorkflowRuntime.ts new file mode 100644 index 0000000000000..8a7502789189f --- /dev/null +++ b/apps/server/src/workflows/WorkflowRuntime.ts @@ -0,0 +1,978 @@ +// Workflows in the running server: every file in one folder defines some, and the folder can +// change while the server runs. A file that loads replaces what it defined before; one that does +// not keeps its last good version running. With no definitions there is no engine, unless runs +// from before are kept: then one with nothing registered serves their history. +import * as NodeAsyncHooks from "node:async_hooks"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- the CommonJS cache is cleared in the same tick as the import. +import * as NodeFS from "node:fs"; +import * as NodeModule from "node:module"; +import * as NodeURL from "node:url"; + +import type { + WorkflowDefinitionChangeResult, + WorkflowDefinitionFiles, + WorkflowDefinitionProblem, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Config from "effect/Config"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; +import * as Semaphore from "effect/Semaphore"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; + +import * as ServerConfig from "../config.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { engineTag, text, type WorkflowDefinition } from "./workflow.ts"; +import type * as WorkflowEngine from "./WorkflowEngine.ts"; +import * as WorkflowAgentThreads from "./WorkflowAgentThreads.ts"; +import * as WorkflowForge from "./WorkflowForge.ts"; +import * as Workflows from "./Workflows.ts"; + +/** A folder of definition files, or one file, in place of the folder in the T3 home. */ +const definitionsOverride = Config.String("T3CODE_WORKFLOWS").pipe(Config.option); + +// An editor saves in several writes, and a save from here is followed by its own file event. +const RELOAD_SETTLE = "300 millis"; +// How often a change held back by unfinished runs is tried again, so it goes in once they end. +const HELD_RETRY = "15 seconds"; +// A folder that could not be listed is looked at again, since no file event may follow. +const LIST_RETRY = "30 seconds"; +// A leading dot is how a file is kept out: a draft being checked, an editor's swap file. +// One name in the folder, never a path: the name is also the key a save and a removal go by. +const DEFINITION_FILE = /^[A-Za-z0-9_][\w.-]*\.(ts|mts|js|mjs)$/; +const NAMING = + "Name the file with letters, digits, dashes, underscores and dots, ending in .ts: for example release.ts."; + +export class WorkflowDefinitionsLoadError extends Schema.TaggedError()( + "WorkflowDefinitionsLoadError", + { module: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `Could not load workflow definitions from ${this.module}.`; + } +} + +/** The definition files of this server, for a person to read and change. */ +export class WorkflowDefinitions extends Context.Service< + WorkflowDefinitions, + { + /** The files as they are on disk now, with what is wrong with them. */ + readonly read: Effect.Effect; + /** + * Verify `source` as the file `name`, and when nothing is wrong write it and run it from now + * on. A file that was written can still fail to run, and then says why. + */ + readonly save: (name: string, source: string) => Effect.Effect; + /** Take a file away, unless runs still need what it defines. */ + readonly remove: (name: string) => Effect.Effect; + } +>()("t3/workflows/WorkflowRuntime/WorkflowDefinitions") {} + +const isDefinition = (value: unknown): value is WorkflowDefinition => + typeof value === "object" && + value !== null && + typeof (value as WorkflowDefinition).name === "string" && + typeof (value as WorkflowDefinition).version === "number" && + typeof (value as WorkflowDefinition).body === "function" && + // The engine walks these at start, and a file can export an object that only looks like one. + Array.isArray((value as WorkflowDefinition).triggers) && + Array.isArray((value as WorkflowDefinition).resumeAfter); + +// The API is handed to a file as globals, which the whole process shares, so files load one at +// a time. A load that was given up on still runs, so `T3.workflow` registers with the load whose +// code calls it, and with none once that load is over. +const loading = Semaphore.makeUnsafe(1); +// A file whose top-level code never settles would otherwise hold every later load. Real time, +// since importing a module is. +const LOAD_DEADLINE_MS = 20_000; + +interface Evaluation { + readonly registered: Array; + open: boolean; +} +const evaluating = new NodeAsyncHooks.AsyncLocalStorage(); +// Counts loads across runtimes: one started again would otherwise get back the modules of the last. +let loads = 0; +const required = NodeModule.createRequire(import.meta.url); + +/** A file with no `import` or `export` loads as CommonJS, which Node keeps by path, not address. */ +const forget = (file: string) => { + delete required.cache[file]; + try { + delete required.cache[NodeFS.realpathSync(file)]; + } catch { + // Gone already, so nothing can be kept under its real path either. + } +}; + +const within = (work: Promise, ms: number): Promise => { + let timer: ReturnType | undefined; + const late = new Promise((resolve) => { + // @effect-diagnostics-next-line globalTimers:off -- an import runs on real time, not a test clock. + timer = setTimeout(resolve, ms, undefined); + }); + return Promise.race([work, late]).finally(() => clearTimeout(timer)); +}; + +const evaluate = async (url: string, evaluation: Evaluation): Promise> => { + const api = await import("./api.ts"); + const { Duration, Effect: effect, Option: option, Schedule, Schema: schema, ...t3 } = api; + const workflow = ((...input: Parameters) => { + const current = evaluating.getStore(); + if (current === undefined || !current.open) { + throw new Error( + "T3.workflow was called after its file finished loading. Call it at the top of the file.", + ); + } + const definition = api.workflow(...input); + current.registered.push(definition); + return definition; + }) as typeof api.workflow; + Object.assign(globalThis, { + T3: { ...t3, workflow }, + Effect: effect, + Schema: schema, + Option: option, + Duration, + Schedule, + }); + const loaded = (await evaluating.run(evaluation, () => import(url))) as { + readonly default?: unknown; + "module.exports"?: unknown; + }; + // A file with no `import` or `export` loads as CommonJS, whose default is its `module.exports`: + // an empty object unless the file set one, which says nothing about what it defines. + const commonJs = "module.exports" in loaded; + const exported = + commonJs && + typeof loaded.default === "object" && + loaded.default !== null && + !Array.isArray(loaded.default) && + Object.keys(loaded.default).length === 0 + ? undefined + : loaded.default; + // One workflow exported by itself is as good as a list of one. + const listed = + exported === undefined + ? [] + : Array.isArray(exported) + ? exported + : isDefinition(exported) + ? [exported] + : undefined; + if (listed === undefined) { + throw new Error( + "The default export is not a workflow or a list of them. Call T3.workflow(…), or export what it returned.", + ); + } + return [...new Set([...evaluation.registered, ...listed])]; +}; + +/** + * The workflows a file defines: every `T3.workflow(…)` it calls, and any list it exports. + * `load` tells one loading of a file from the next: Node keeps a module by its address, so the + * same address would give back the file as it was the first time. + */ +export const loadDefinitions = Effect.fn("WorkflowRuntime.loadDefinitions")(function* ( + module: string, + load = 0, + deadlineMs = LOAD_DEADLINE_MS, +) { + const path = yield* Path.Path; + const file = path.resolve(module); + const url = NodeURL.pathToFileURL(file).href + (load === 0 ? "" : `?${load}`); + const definitions = yield* Effect.tryPromise({ + try: () => { + const evaluation: Evaluation = { registered: [], open: true }; + forget(file); + return within(evaluate(url, evaluation), deadlineMs).finally(() => { + evaluation.open = false; + forget(file); + }); + }, + catch: (cause) => new WorkflowDefinitionsLoadError({ module, cause }), + }).pipe(loading.withPermits(1)); + if (definitions === undefined) { + return yield* new WorkflowDefinitionsLoadError({ + module, + cause: `It did not finish loading within ${deadlineMs / 1000} seconds. Something at the top of the file waits for good.`, + }); + } + if (!definitions.every(isDefinition)) { + return yield* new WorkflowDefinitionsLoadError({ + module, + cause: "Something it exports is not a workflow. Export only what `T3.workflow` returned.", + }); + } + return definitions; +}); + +/** What a load error says, with the line of `file` it points at when it names one. */ +const loadProblem = ( + error: WorkflowDefinitionsLoadError, + loadedFrom: string, + file: string, +): WorkflowDefinitionProblem => { + const cause = error.cause; + const stack = cause instanceof Error ? (cause.stack ?? "") : ""; + const name = loadedFrom.split(/[\\/]/).at(-1) ?? loadedFrom; + // Node names the place as `file:///…/name.ts:12` or `…/name.ts:12:5`, with a `?n` when reloaded. + const at = stack.split(name).find((rest) => /^(\?\d+)?:\d+/.test(rest)); + const line = at === undefined ? undefined : Number(/^(?:\?\d+)?:(\d+)/.exec(at)?.[1]); + return { message: text(cause), file, ...(line === undefined ? {} : { line }) }; +}; + +/** + * What is wrong between files that each loaded, given the runs that have not ended, with the + * files that could each be the cause. + */ +const definitionProblems = ( + files: ReadonlyArray<{ + readonly name: string; + readonly definitions: ReadonlyArray; + }>, + unfinished: ReadonlyArray<{ readonly workflow: string; readonly version: number }>, + before: ReadonlyMap> = new Map(), +): ReadonlyArray<{ + readonly problem: WorkflowDefinitionProblem; + readonly files: ReadonlyArray; + readonly clash: boolean; +}> => { + const where = new Map>(); + for (const file of files) { + for (const definition of file.definitions) { + where.set(engineTag(definition), [...(where.get(engineTag(definition)) ?? []), file.name]); + } + } + const waiting = new Map(); + for (const run of unfinished) { + const tag = engineTag({ name: run.workflow, version: run.version }); + if (!where.has(tag)) waiting.set(tag, (waiting.get(tag) ?? 0) + 1); + } + return [ + ...[...where] + .filter(([, names]) => names.length > 1) + .map(([tag, names]) => ({ + problem: { + message: `${tag} is defined twice, in ${[...new Set(names)].join(" and ")}. A workflow's name and version name one body.`, + }, + files: [...new Set(names)], + clash: true, + })), + ...[...waiting].map(([tag, runs]) => ({ + problem: { + message: `${tag} is no longer defined, and ${runs} of its runs ${runs === 1 ? "has" : "have"} not ended. Keep that version until they end, or cancel them first.`, + }, + files: [...before] + .filter(([, definitions]) => + definitions.some((definition) => engineTag(definition) === tag), + ) + .map(([name]) => name), + clash: false, + })), + ]; +}; + +/** + * `engine` gives the layer that runs a set of definitions. It is asked for only once there is + * something to run or `kept` says there are runs to read, since the engine's modules are not worth + * loading for nothing. `where` is the folder of definition files, or one file. + */ +export const make = Effect.fn("WorkflowRuntime.make")(function* ( + engine: Effect.Effect< + (definitions: ReadonlyArray) => Layer.Layer + >, + where: string, + kept: Effect.Effect, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const target = path.resolve(where); + const single = DEFINITION_FILE.test(path.basename(target)); + const directory = single ? path.dirname(target) : target; + yield* Effect.ignore(fileSystem.makeDirectory(directory, { recursive: true })); + const outer = yield* Scope.Scope; + const services = yield* Effect.context(); + + // One reload at a time, and callers during one wait for the engine that comes out of it. + const lock = yield* Semaphore.make(1); + let ready = Deferred.makeUnsafe(); + let engineScope: Scope.Closeable | undefined; + let running: ReadonlyArray = []; + let imported = false; + /** Each file as it was last looked at, so one that did not change is not loaded again. */ + const seen = new Map(); + /** The last version of each file that loaded, which runs while a newer one does not. */ + const good = new Map>(); + /** Files that loaded or went away since, kept apart until the change as a whole is taken. */ + const pending = new Map | null>(); + const broken = new Map(); + /** Files whose change clashes with another file or drops what a run needs, and why. */ + const held = new Map>(); + let between: ReadonlyArray = []; + /** Code files in the folder that are not loaded because of their name. */ + let misnamed: ReadonlyArray = []; + let retrying = false; + let unstarted = false; + const state = yield* SubscriptionRef.make<{ revision: number; problem: string | null }>({ + revision: 0, + problem: null, + }); + const told = (problem: WorkflowDefinitionProblem) => + problem.file === undefined ? problem.message : `${problem.file}: ${problem.message}`; + const report = Effect.suspend(() => { + const problems = [...broken.values(), ...[...held.values()].flat(), ...misnamed, ...between]; + return SubscriptionRef.update(state, (current) => ({ + revision: current.revision + 1, + problem: problems.length === 0 ? null : problems.map(told).join("\n"), + })); + }); + + /** Every name in the folder, or the one file. */ + const entries = Effect.gen(function* () { + if (single) { + return (yield* fileSystem.exists(target)) ? [path.basename(target)] : []; + } + // A folder that is not there yet is empty. One that cannot be read just now is not: it + // fails, and what was loaded stays. + if (!(yield* fileSystem.exists(directory))) return []; + return (yield* fileSystem.readDirectory(directory)).toSorted(); + }); + const definitionNames = (all: ReadonlyArray) => + all.filter((entry) => DEFINITION_FILE.test(entry)); + const names = Effect.map(entries, definitionNames); + + /** A fresh engine for these definitions in its own scope, or the failure that stopped it. */ + const build = Effect.fn("WorkflowRuntime.build")(function* ( + definitions: ReadonlyArray, + ) { + const scope = yield* Scope.fork(outer); + const layerEngine = yield* engine; + imported = true; + const built = yield* Effect.suspend(() => + Layer.buildWithScope(layerEngine(definitions), scope), + ).pipe(Effect.provideContext(services), Effect.exit); + if (Exit.isFailure(built)) yield* Scope.close(scope, Exit.void); + else engineScope = scope; + return built; + }); + + const boot = Effect.fn("WorkflowRuntime.boot")( + function* (definitions: ReadonlyArray) { + const next = Deferred.makeUnsafe(); + ready = next; + const previous = running; + if (engineScope !== undefined) yield* Scope.close(engineScope, Exit.void); + engineScope = undefined; + running = []; + if (definitions.length === 0 && !imported && !(yield* kept)) { + yield* Deferred.succeed(next, Workflows.disabled); + return null; + } + const built = yield* build(definitions); + if (Exit.isSuccess(built)) { + running = definitions; + yield* Deferred.succeed(next, Context.get(built.value, Workflows.Workflows)); + if (definitions.length > 0) { + yield* Effect.logInfo("Workflows registered", { + directory, + workflows: definitions.map(engineTag), + }); + } + return null; + } + // What ran before comes back, so definitions that cannot start take nothing down. + const restored = yield* build(previous); + if (Exit.isSuccess(restored)) { + running = previous; + yield* Deferred.succeed(next, Context.get(restored.value, Workflows.Workflows)); + } else { + // Nobody may be left waiting on an engine that never came up. + yield* Deferred.succeed(next, Workflows.disabled); + } + return `The workflow engine did not start: ${text(Cause.squash(built.cause))}`; + }, + // Once `ready` is replaced it must be settled, or every caller waits on it for good. + Effect.uninterruptible, + ); + + const unfinished = Effect.suspend(() => + running.length === 0 + ? Effect.succeed([]) + : Effect.flatMap(Deferred.await(ready), (service) => service.unfinished), + ); + /** The workflows the file at `from` defines, or what is wrong with it as the file `name`. */ + const load = Effect.fn("WorkflowRuntime.load")(function* (from: string, name: string) { + const definitions = yield* loadDefinitions(from, ++loads).pipe( + Effect.provideContext(services), + Effect.result, + ); + return definitions._tag === "Failure" + ? ({ problem: loadProblem(definitions.failure, from, name) } as const) + : ({ definitions: definitions.success } as const); + }); + /** What would run with these files, in the folder's order. */ + const gathered = (files: ReadonlyMap>) => + [...files] + .toSorted(([left], [right]) => left.localeCompare(right)) + .map(([name, definitions]) => ({ name, definitions })); + + // Set once `reload` exists, which it schedules again; the indirection keeps its type inferred. + let retryLater: Effect.Effect = Effect.void; + /** Take in what changed in the folder, and run the result unless something is wrong with it. */ + const reload = Effect.fn("WorkflowRuntime.reload")(function* () { + const listed = yield* Effect.option(entries); + if (Option.isNone(listed)) { + yield* Effect.logWarning( + "The workflows folder could not be read; its workflows stay as they are", + ); + yield* retryLater; + return false; + } + const present = definitionNames(listed.value); + // A leading dot keeps a file out on purpose; any other code file left out is a surprise. + const wasMisnamed = misnamed; + misnamed = listed.value + .filter((entry) => /^[^.].*\.(ts|mts|js|mjs)$/.test(entry) && !DEFINITION_FILE.test(entry)) + .map((entry) => ({ message: `It is not loaded. ${NAMING}`, file: entry })); + const renamed = + misnamed.map((problem) => problem.file).join("/") !== + wasMisnamed.map((problem) => problem.file).join("/"); + let changed = false; + for (const problem of misnamed) { + if (!wasMisnamed.some((known) => known.file === problem.file)) { + yield* Effect.logWarning( + "A file in the workflows folder is not loaded because of its name", + problem, + ); + } + } + for (const name of present) { + const file = path.join(directory, name); + const source = yield* fileSystem.readFileString(file).pipe(Effect.option); + if (Option.isNone(source) || seen.get(name) === source.value) continue; + seen.set(name, source.value); + changed = true; + const loaded = yield* load(file, name); + if (loaded.definitions === undefined) { + broken.set(name, loaded.problem); + pending.delete(name); + yield* Effect.logWarning("A workflow definitions file was not loaded", loaded.problem); + continue; + } + broken.delete(name); + pending.set(name, loaded.definitions); + } + for (const name of [...seen.keys()].filter((known) => !present.includes(known))) { + seen.delete(name); + pending.set(name, null); + broken.delete(name); + changed = true; + } + // Asked again while something stands between files: the runs that held a version may be over. + if (!changed && between.length === 0 && held.size === 0) { + if (renamed) yield* report; + return true; + } + const runs = yield* unfinished; + // A change that clashes is held back like a file that does not load: that file keeps its last + // good version, a new one stays out, and every other change is taken. + held.clear(); + let next = new Map(good); + let problems: ReturnType = []; + let blamed = true; + while (blamed) { + blamed = false; + next = new Map(good); + for (const [name, definitions] of pending) { + if (held.has(name)) continue; + if (definitions === null) next.delete(name); + else next.set(name, definitions); + } + problems = definitionProblems(gathered(next), runs, good); + for (const { problem, files: involved, clash } of problems) { + const changing = involved.filter((name) => pending.has(name) && !held.has(name)); + // Between new files that define the same workflow, the first in the folder's order stays. + const culprits = + clash && changing.length === involved.length ? changing.slice(1) : changing; + for (const name of culprits) { + held.set(name, [...(held.get(name) ?? []), { ...problem, file: name }]); + blamed = true; + } + } + } + if (held.size > 0) { + yield* Effect.logWarning("Some workflow definition changes were not taken", { + problems: [...held.values()].flat(), + }); + } + // What is left was so before any of these changes, so it holds none of them back. + const standing = problems.map((entry) => entry.problem); + if (standing.length > 0) { + yield* Effect.logWarning("Workflow definitions have problems", { problems: standing }); + } + const taking = [...pending.keys()].filter((name) => !held.has(name)); + // An engine that did not start is tried again, as the runs it tripped on may have ended. + if (taking.length === 0 && !unstarted) { + between = standing; + yield* report; + return true; + } + good.clear(); + for (const [name, definitions] of next) good.set(name, definitions); + for (const name of taking) pending.delete(name); + const failed = yield* boot(gathered(next).flatMap((file) => file.definitions)); + unstarted = failed !== null; + between = failed === null ? standing : [...standing, { message: failed }]; + yield* report; + return true; + }); + + retryLater = Effect.suspend(() => { + if (retrying) return Effect.void; + retrying = true; + return Effect.suspend(() => { + retrying = false; + return lock.withPermits(1)(reload()); + }).pipe( + Effect.delay(LIST_RETRY), + Effect.catchCause((cause) => + Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)), + ), + Effect.forkIn(outer), + Effect.asVoid, + ); + }); + + yield* lock.withPermits(1)(reload()); + // No file defines anything yet, though runs kept from before may still be read. + if (!(yield* Deferred.isDone(ready))) yield* boot([]); + + // The folder, not a file: an editor that saves by renaming replaces the file it was watching. + yield* fileSystem.watch(directory).pipe( + Stream.debounce(RELOAD_SETTLE), + Stream.runForEach(() => + lock + .withPermits(1)(reload()) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)), + ), + ), + ), + Effect.catchCause((cause) => + Effect.logWarning("Workflow definitions are not watched for changes", Cause.pretty(cause)), + ), + Effect.forkIn(outer), + ); + + yield* Effect.sleep(HELD_RETRY).pipe( + Effect.andThen( + Effect.suspend(() => (held.size > 0 ? lock.withPermits(1)(reload()) : Effect.void)), + ), + Effect.catchCause((cause) => + Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)), + ), + Effect.forever, + Effect.forkIn(outer), + ); + + const current = Effect.suspend(() => Deferred.await(ready)); + // A watcher outlives the engine it began on: each reload hands it the next one's stream. + const followed = (pick: (service: Workflows.Workflows["Service"]) => Stream.Stream) => + SubscriptionRef.changes(state).pipe( + Stream.switchMap((at) => + Stream.unwrap(Effect.map(current, pick)).pipe(Stream.map((value) => [value, at] as const)), + ), + ); + const service = Workflows.Workflows.of({ + start: Effect.fn("Workflows.start")(function* (...input) { + return yield* (yield* current).start(...input); + }), + signal: Effect.fn("Workflows.signal")(function* (...input) { + return yield* (yield* current).signal(...input); + }), + answer: Effect.fn("Workflows.answer")(function* (...input) { + return yield* (yield* current).answer(...input); + }), + resume: Effect.fn("Workflows.resume")(function* (...input) { + return yield* (yield* current).resume(...input); + }), + cancel: Effect.fn("Workflows.cancel")(function* (...input) { + return yield* (yield* current).cancel(...input); + }), + get: Effect.fn("Workflows.get")(function* (...input) { + return yield* (yield* current).get(...input); + }), + list: Effect.fn("Workflows.list")(function* (...input) { + return yield* (yield* current).list(...input); + }), + waitFor: Effect.fn("Workflows.waitFor")(function* (...input) { + // A reload replaces the engine, and a wait on the old one would never hear of the run again. + while (true) { + // Noted before the engine is read, so a reload that lands in between is still heard of. + const { revision } = yield* SubscriptionRef.get(state); + const live = yield* current; + const reloaded = SubscriptionRef.changes(state).pipe( + Stream.filter((at) => at.revision !== revision), + Stream.runHead, + ); + const waited = yield* live + .waitFor(...input) + .pipe(Effect.asSome, Effect.raceFirst(Effect.as(reloaded, Option.none()))); + if (Option.isSome(waited)) return waited.value; + } + }), + questions: Effect.flatMap(current, (live) => live.questions), + unfinished: Effect.flatMap(current, (live) => live.unfinished), + hooks: Effect.flatMap(current, (live) => live.hooks), + deliver: Effect.fn("Workflows.deliver")(function* (...input) { + return yield* (yield* current).deliver(...input); + }), + stored: Effect.fn("Workflows.stored")(function* (...input) { + return yield* (yield* current).stored(...input); + }), + storeSet: Effect.fn("Workflows.storeSet")(function* (...input) { + return yield* (yield* current).storeSet(...input); + }), + storeDelete: Effect.fn("Workflows.storeDelete")(function* (...input) { + return yield* (yield* current).storeDelete(...input); + }), + watch: followed((live) => live.watch).pipe( + Stream.map(([snapshot, at]) => ({ ...snapshot, definition: at })), + ), + counts: followed((live) => live.counts).pipe(Stream.map(([counts]) => counts)), + sweep: Effect.flatMap(current, (live) => live.sweep), + }); + + const alone = { message: `This server reads its workflows from ${target} alone.` }; + /** Why `name` cannot be a file here, if it cannot. */ + const refused = (name: string): WorkflowDefinitionProblem | undefined => + single && name !== path.basename(target) + ? alone + : DEFINITION_FILE.test(name) + ? undefined + : { message: NAMING }; + /** What is wrong with the folder once `change` is made to the files that load. */ + const wouldBreak = Effect.fn("WorkflowRuntime.wouldBreak")(function* ( + change: (files: Map>) => void, + ) { + const files = new Map(good); + change(files); + return definitionProblems(gathered(files), yield* unfinished, good).map( + (entry) => entry.problem, + ); + }); + + const refusal = (problems: ReadonlyArray) => ({ + changed: false, + problems, + }); + /** What keeps a change to the file `name` from running, once it is made on disk. */ + const taken = Effect.fn("WorkflowRuntime.taken")(function* (name: string) { + const listed = yield* reload(); + const problem = broken.get(name); + return { + changed: true, + problems: listed + ? [...(problem === undefined ? [] : [problem]), ...(held.get(name) ?? []), ...between] + : [{ message: `${directory} could not be read just now, so the change does not run yet.` }], + }; + }); + + const save = Effect.fn("WorkflowRuntime.save")(function* (name: string, source: string) { + const no = refused(name); + if (no !== undefined) return refusal([no]); + const file = path.join(directory, name); + // Beside the real file, so what it imports resolves the same way. The dot keeps it out. + const draft = path.join(directory, `.${name}.check-${loads + 1}${path.extname(name)}`); + const checked = yield* fileSystem.writeFileString(draft, source).pipe( + Effect.andThen(load(draft, name)), + Effect.ensuring(Effect.ignore(fileSystem.remove(draft))), + Effect.catchTags({ + PlatformError: (error) => + Effect.succeed({ + problem: { message: `Could not write in ${directory}: ${text(error)}` }, + } as const), + }), + ); + if (!("definitions" in checked)) return refusal([checked.problem]); + const definitions = checked.definitions; + const problems = yield* wouldBreak((files) => files.set(name, definitions)); + if (problems.length > 0) return refusal(problems); + const written = yield* fileSystem.writeFileString(file, source).pipe(Effect.result); + if (written._tag === "Failure") { + return refusal([{ message: `Could not write ${file}: ${text(written.failure)}` }]); + } + return yield* taken(name); + }); + + const remove = Effect.fn("WorkflowRuntime.remove")(function* (name: string) { + const no = single ? alone : refused(name); + if (no !== undefined) return refusal([no]); + const problems = yield* wouldBreak((files) => files.delete(name)); + if (problems.length > 0) return refusal(problems); + const removed = yield* fileSystem.remove(path.join(directory, name)).pipe(Effect.result); + if (removed._tag === "Failure") { + return refusal([{ message: `Could not delete ${name}: ${text(removed.failure)}` }]); + } + return yield* taken(name); + }); + + return Context.make(Workflows.Workflows, service).pipe( + Context.add( + WorkflowDefinitions, + WorkflowDefinitions.of({ + read: Effect.gen(function* () { + const files = yield* Effect.forEach( + yield* Effect.orElseSucceed(names, () => []), + (name) => + fileSystem.readFileString(path.join(directory, name)).pipe( + Effect.orElseSucceed(() => ""), + Effect.map((source) => { + const problem = broken.get(name); + return { + name, + source, + workflows: (good.get(name) ?? []).map(engineTag), + problems: [ + ...(problem === undefined ? [] : [problem]), + ...(held.get(name) ?? []), + ], + }; + }), + ), + ); + const at = yield* SubscriptionRef.get(state); + // A file held back after it was deleted has no entry of its own to say so. + const gone = [...held] + .filter(([name]) => !files.some((file) => file.name === name)) + .flatMap(([, problems]) => problems); + return { directory, single, files, problems: [...misnamed, ...between, ...gone], ...at }; + }), + save: Effect.fn("WorkflowDefinitions.save")(function* (name, source) { + return yield* lock.withPermits(1)(save(name, source)); + }), + remove: Effect.fn("WorkflowDefinitions.remove")(function* (name) { + return yield* lock.withPermits(1)(remove(name)); + }), + }), + ), + ); +}); + +/** + * Workflows behind the Labs switch. While off, `runtime` is not run: no definition file loads and + * no engine runs, and every request is refused. Turning on runs it in a scope of its own, which + * turning off closes; runs stay stored and go on once it is on again. `where` is as for `make`. + */ +export const gate = Effect.fn("WorkflowRuntime.gate")(function* ( + runtime: Effect.Effect< + Context.Context, + E, + R | Scope.Scope + >, + where: string, +) { + const path = yield* Path.Path; + const outer = yield* Scope.Scope; + const services = yield* Effect.context(); + const target = path.resolve(where); + const single = DEFINITION_FILE.test(path.basename(target)); + const off = { message: Workflows.OFF }; + const offDefinitions = WorkflowDefinitions.of({ + read: Effect.succeed({ + directory: single ? path.dirname(target) : target, + single, + files: [], + problems: [off], + revision: 0, + problem: null, + }), + save: Effect.fn("WorkflowDefinitions.save")(function* () { + return yield* Effect.succeed({ changed: false, problems: [off] }); + }), + remove: Effect.fn("WorkflowDefinitions.remove")(function* () { + return yield* Effect.succeed({ changed: false, problems: [off] }); + }), + }); + const offContext = Context.make(Workflows.Workflows, Workflows.off).pipe( + Context.add(WorkflowDefinitions, offDefinitions), + ); + + const lock = yield* Semaphore.make(1); + let ready = Deferred.makeUnsafe>(); + Deferred.doneUnsafe(ready, Exit.succeed(offContext)); + let scope: Scope.Closeable | undefined; + const turns = yield* SubscriptionRef.make(0); + + const turn = Effect.fn("WorkflowRuntime.turn")( + function* (on: boolean) { + if (on === (scope !== undefined)) return; + const next = + Deferred.makeUnsafe>(); + ready = next; + if (scope !== undefined) yield* Scope.close(scope, Exit.void); + scope = undefined; + if (on) { + const opened = yield* Scope.fork(outer); + const started = yield* runtime.pipe( + Effect.provideService(Scope.Scope, opened), + Effect.provideContext(services), + Effect.exit, + ); + if (Exit.isSuccess(started)) { + scope = opened; + yield* Deferred.succeed(next, started.value); + } else { + yield* Scope.close(opened, Exit.void); + yield* Effect.logWarning("Workflows did not start", Cause.pretty(started.cause)); + } + } + if (scope === undefined) yield* Deferred.succeed(next, offContext); + yield* SubscriptionRef.update(turns, (count) => count + 1); + yield* Effect.logInfo(scope === undefined ? "Workflows are off" : "Workflows are on"); + }, + // Once `ready` is replaced it must be settled, or every caller waits on it for good. + Effect.uninterruptible, + lock.withPermits(1), + ); + + const live = Effect.suspend(() => Deferred.await(ready)); + const current = Effect.map(live, Context.get(Workflows.Workflows)); + const definitions = Effect.map(live, Context.get(WorkflowDefinitions)); + // A watcher outlives a turn: each one hands it the next service's stream. + const followed = (pick: (service: Workflows.Workflows["Service"]) => Stream.Stream) => + SubscriptionRef.changes(turns).pipe( + Stream.switchMap(() => Stream.unwrap(Effect.map(current, pick))), + ); + const service = Workflows.Workflows.of({ + start: Effect.fn("Workflows.start")(function* (...input) { + return yield* (yield* current).start(...input); + }), + signal: Effect.fn("Workflows.signal")(function* (...input) { + return yield* (yield* current).signal(...input); + }), + answer: Effect.fn("Workflows.answer")(function* (...input) { + return yield* (yield* current).answer(...input); + }), + resume: Effect.fn("Workflows.resume")(function* (...input) { + return yield* (yield* current).resume(...input); + }), + cancel: Effect.fn("Workflows.cancel")(function* (...input) { + return yield* (yield* current).cancel(...input); + }), + get: Effect.fn("Workflows.get")(function* (...input) { + return yield* (yield* current).get(...input); + }), + list: Effect.fn("Workflows.list")(function* (...input) { + return yield* (yield* current).list(...input); + }), + waitFor: Effect.fn("Workflows.waitFor")(function* (...input) { + // Off, nothing changes a run; a wait goes on once workflows are on again. + while (true) { + const turned = yield* SubscriptionRef.get(turns); + const service = yield* current; + const next = SubscriptionRef.changes(turns).pipe( + Stream.filter((count) => count !== turned), + Stream.runHead, + ); + const waited = yield* service + .waitFor(...input) + .pipe(Effect.asSome, Effect.raceFirst(Effect.as(next, Option.none()))); + if (Option.isSome(waited)) return waited.value; + } + }), + questions: Effect.flatMap(current, (service) => service.questions), + unfinished: Effect.flatMap(current, (service) => service.unfinished), + hooks: Effect.flatMap(current, (service) => service.hooks), + deliver: Effect.fn("Workflows.deliver")(function* (...input) { + return yield* (yield* current).deliver(...input); + }), + stored: Effect.fn("Workflows.stored")(function* (...input) { + return yield* (yield* current).stored(...input); + }), + storeSet: Effect.fn("Workflows.storeSet")(function* (...input) { + return yield* (yield* current).storeSet(...input); + }), + storeDelete: Effect.fn("Workflows.storeDelete")(function* (...input) { + return yield* (yield* current).storeDelete(...input); + }), + watch: followed((service) => service.watch), + counts: followed((service) => service.counts), + sweep: Effect.flatMap(current, (service) => service.sweep), + }); + + return { + turn, + context: Context.make(Workflows.Workflows, service).pipe( + Context.add( + WorkflowDefinitions, + WorkflowDefinitions.of({ + read: Effect.flatMap(definitions, (files) => files.read), + save: Effect.fn("WorkflowDefinitions.save")(function* (name, source) { + return yield* (yield* definitions).save(name, source); + }), + remove: Effect.fn("WorkflowDefinitions.remove")(function* (name) { + return yield* (yield* definitions).remove(name); + }), + }), + ), + ), + }; +}); + +/** + * The workflow service for this server, and its definition files: those in the `workflows` + * folder of the T3 home, or wherever `T3CODE_WORKFLOWS` points instead. A file that does not + * load is reported and never stops the server. Nothing runs until `workflowsEnabled` is on. + */ +export const layer = Layer.effectContext( + Effect.gen(function* () { + const override = yield* definitionsOverride; + const config = yield* ServerConfig.ServerConfig; + const forge = Layer.succeed(WorkflowForge.WorkflowForge, yield* WorkflowForge.WorkflowForge); + const sql = yield* SqlClient.SqlClient; + const settings = yield* ServerSettings.ServerSettingsService; + const where = Option.getOrElse(override, () => config.workflowsDir); + const changes = yield* settings.subscribeChanges; + const gated = yield* gate( + make( + Effect.map( + Effect.promise((): Promise => import("./WorkflowEngine.ts")), + (engine) => (definitions) => + engine + .layer(definitions) + .pipe(Layer.provide(WorkflowAgentThreads.layer), Layer.provide(forge)), + ), + where, + sql`SELECT 1 FROM workflow_runs LIMIT 1`.pipe( + Effect.map((rows) => rows.length > 0), + Effect.orElseSucceed(() => true), + ), + ), + where, + ); + const enabled = yield* settings.getSettings.pipe( + Effect.map((current) => current.workflowsEnabled), + Effect.orElseSucceed(() => false), + ); + yield* gated.turn(enabled); + yield* changes.pipe( + Stream.map((current) => current.workflowsEnabled), + Stream.runForEach(gated.turn), + Effect.forkScoped, + ); + return gated.context; + }), +); diff --git a/apps/server/src/workflows/WorkflowStore.test.ts b/apps/server/src/workflows/WorkflowStore.test.ts new file mode 100644 index 0000000000000..7fa6daa8c0208 --- /dev/null +++ b/apps/server/src/workflows/WorkflowStore.test.ts @@ -0,0 +1,424 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as PubSub from "effect/PubSub"; +import type * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; + +import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; +import * as MilestoneHub from "../milestones/MilestoneHub.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; + +const withStore = ( + use: Effect.Effect, +) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-store-" }); + const database = NodeSqliteClient.layer({ filename: path.join(directory, "state.sqlite") }); + const migrated = Layer.effectDiscard(WorkflowsMigration); + return yield* Effect.provide( + use, + WorkflowStore.layer.pipe( + Layer.provideMerge(Layer.merge(migrated, MilestoneHub.layer)), + Layer.provide(database), + ), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); + +it.effect("a run still waits while one of the things it started side by side is out", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + yield* store.runStarted({ + runId: "r1", + workflow: "duo", + version: 1, + engineTag: "duo@1", + idempotencyKey: "k", + input: {}, + }); + // Started again under its key: nothing changed, so nobody is told. + yield* Effect.scoped( + Effect.gen(function* () { + const told = yield* PubSub.subscribe(store.changes); + yield* store.runStarted({ + runId: "r1", + workflow: "duo", + version: 1, + engineTag: "duo@1", + idempotencyKey: "k", + input: {}, + }); + assert.equal(yield* PubSub.remaining(told), 0); + }), + ); + const now = Effect.map(store.run("r1"), (run) => [run?.status, run?.detail]); + yield* store.stepStarted("r1", "left", "agent"); + yield* store.stepStarted("r1", "right", "agent"); + yield* store.stepStarted("r1", "approve", "ask"); + yield* store.runStatus("r1", "waiting", "agent left"); + + yield* store.stepEnded("r1", "left", "completed", null); + yield* store.runResumed("r1"); + assert.deepStrictEqual(yield* now, ["waiting", "agent right"]); + + yield* store.stepEnded("r1", "right", "completed", null); + yield* store.runResumed("r1"); + assert.deepStrictEqual(yield* now, ["waiting", "approve"]); + + yield* store.stepEnded("r1", "approve", "completed", null); + yield* store.runResumed("r1"); + assert.deepStrictEqual(yield* now, ["running", null]); + + // One of them failed and paused the run: the others ending do not take that back. + yield* store.stepStarted("r1", "again", "agent"); + yield* store.stepStarted("r1", "beside", "agent"); + yield* store.stepStarted("r1", "later", "wait"); + yield* store.runPaused("r1", "again gave up", true); + yield* store.stepEnded("r1", "beside", "completed", null); + yield* store.runResumed("r1"); + yield* store.runStatus("r1", "waiting", "later"); + const paused = yield* store.run("r1"); + assert.deepStrictEqual( + [paused?.status, paused?.detail, Number(paused?.pauses), Number(paused?.held)], + ["paused", "again gave up", 1, 1], + ); + // The sweep's resume is for the pause it read, not for one that came after it. + assert.isTrue(yield* store.runUnpaused("r1")); + yield* store.runPaused("r1", "gave up again"); + assert.isFalse( + yield* store.runUnpaused("r1", { pauses: 1, updatedAt: paused?.updated_at ?? "" }), + ); + assert.equal((yield* store.run("r1"))?.status, "paused"); + }), + ), +); + +it.effect("a key is taken by the first run started under it, whatever its version", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + for (const version of [1, 2]) { + yield* store.runStarted({ + runId: `r${version}`, + workflow: "fix", + version, + engineTag: `fix@${version}`, + idempotencyKey: "k", + input: {}, + }); + } + assert.isUndefined(yield* store.run("r2")); + assert.equal((yield* store.runByKey("fix", "k"))?.run_id, "r1"); + }), + ), +); + +it.effect("keeps each thing a run touched once, with what the latest touch knew", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const issue = { kind: "issue", key: "i1", address: { scope: "me/app", key: "1" } }; + yield* store.referenceNoted("r1", null, { + ...issue, + title: "Crash", + url: "https://x/1", + state: "open", + }); + yield* store.referenceNoted("r1", "triage", { ...issue, title: "" }); + // A kind the engine has never heard of comes back as it went in. + const machine = { kind: "machine", key: "m1", address: { id: [1, 2] }, title: "box" }; + yield* store.referenceNoted("r1", "make", machine); + yield* store.referenceNoted("r1", "fix", { + ...issue, + title: "Crash at noon", + state: "closed", + }); + yield* Effect.scoped( + Effect.gen(function* () { + const told = yield* PubSub.subscribe(store.changes); + // Seen again by a step that already touched it, with nothing new: nobody is told. + yield* store.referenceNoted("r1", "triage", { ...issue, title: "" }); + assert.equal(yield* PubSub.remaining(told), 0); + }), + ); + assert.deepStrictEqual(yield* store.references("r1"), [ + { + ...issue, + title: "Crash at noon", + url: "https://x/1", + state: "closed", + steps: ["triage", "fix"], + origin: "trigger", + }, + { ...machine, url: null, state: null, steps: ["make"], origin: "step" }, + ]); + assert.deepStrictEqual(yield* store.references("r2"), []); + }), + ), +); + +it.effect("counts what waits on a person, and finds the run's latest agent thread", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const start = (runId: string) => + store.runStarted({ + runId, + workflow: "fix", + version: 1, + engineTag: "fix@1", + idempotencyKey: runId, + input: {}, + }); + assert.deepStrictEqual(yield* store.counts, { needsYou: 0, active: 0, total: 0 }); + yield* Effect.forEach(["r1", "r2", "r3"], start); + yield* store.runPaused("r1", "the build failed"); + assert.isTrue(yield* store.runEnded("r3", "completed", null, null)); + // A second ending, such as a cancel that lost the race, is not recorded and says so. + assert.isFalse(yield* store.runEnded("r3", "cancelled", "late", null)); + assert.equal((yield* store.run("r3"))?.status, "completed"); + // Every run still going, with no list limit: the guard on dropping a version reads this. + assert.equal((yield* store.unfinished).length, 2); + yield* store.waitOpened({ + runId: "r2", + name: "merge", + workflow: "fix", + key: undefined, + token: "t", + schemaJson: "{}", + requestJson: '{"title":"Merge?"}', + watchJson: null, + deadline: null, + }); + // A paused run and an open question each wait on someone; a plain wait does not. + yield* store.waitOpened({ + runId: "r2", + name: "ci", + workflow: "fix", + key: undefined, + token: "u", + schemaJson: "{}", + requestJson: null, + watchJson: null, + deadline: null, + }); + assert.deepStrictEqual(yield* store.counts, { needsYou: 2, active: 2, total: 3 }); + + assert.isNull(yield* store.latestThread("r2")); + yield* store.stepStarted("r2", "write", "agent"); + yield* store.stepThread("r2", "write", "thread-1", null, "turn-1"); + yield* store.stepStarted("r2", "review", "agent"); + yield* store.stepThread("r2", "review", "thread-2", "env-b", "turn-2"); + assert.deepStrictEqual(yield* store.latestThread("r2"), { + threadId: "thread-2", + environmentId: "env-b", + }); + }), + ), +); + +it.effect("one buffered signal goes to one wait, and a claimed wait keeps what woke it", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const open = (runId: string) => + Effect.andThen( + store.runStarted({ + runId, + workflow: "gate", + version: 1, + engineTag: "gate@1", + idempotencyKey: runId, + input: {}, + }), + store.waitOpened({ + runId, + name: "go", + workflow: "gate", + key: "ready", + token: `token-${runId}`, + schemaJson: "{}", + requestJson: null, + watchJson: null, + deadline: null, + }), + ); + yield* open("r1"); + yield* open("r2"); + // The parts of an address are kept apart: this one is for another workflow's other key. + yield* store.mailPut({ + signalId: "other", + address: { workflow: "gate:ready", channel: "x" }, + valueJson: "1", + expiresAt: "2999-01-01T00:00:00.000Z", + }); + assert.isUndefined(yield* store.mailNext([{ workflow: "gate", channel: "ready:x" }])); + + yield* store.mailPut({ + signalId: "s1", + address: { workflow: "gate", channel: "ready" }, + valueJson: '"yes"', + expiresAt: "2999-01-01T00:00:00.000Z", + }); + const woke = { expired: false, value: "yes" }; + assert.equal(yield* store.mailDeliver("s1", "r1", "go", woke), "delivered"); + // The second wait finds the signal gone and stays open for the next one. + assert.equal(yield* store.mailDeliver("s1", "r2", "go", woke), "gone"); + assert.isDefined(yield* store.waitAt({ runId: "r2", wait: "go" })); + assert.isTrue(yield* store.signalSeen("s1")); + // Nor can the id, sent again straight to that wait, claim it: one id wakes one wait. + assert.isFalse(yield* store.waitSignalled("r2", "go", woke, "s1")); + assert.isDefined(yield* store.waitAt({ runId: "r2", wait: "go" })); + // And a kept copy of an id that already woke a wait straight wakes none: the two sends of a + // retry that overlapped, one buffered and one delivered. + yield* store.mailPut({ + signalId: "s1", + address: { workflow: "gate", channel: "ready" }, + valueJson: '"yes"', + expiresAt: "2999-01-01T00:00:00.000Z", + }); + assert.equal(yield* store.mailDeliver("s1", "r2", "go", woke), "gone"); + assert.isDefined(yield* store.waitAt({ runId: "r2", wait: "go" })); + // It is dropped, so a wait looking through its mail is not handed it again. + assert.isUndefined(yield* store.mailNext([{ workflow: "gate", channel: "ready" }])); + // A wait that is already claimed takes no second wake. + assert.equal(yield* store.mailDeliver("other", "r1", "go", woke), "claimed"); + + // Its wake is redone once the claim has gone unanswered for a while. + assert.deepStrictEqual(yield* store.waitsToWake, []); + yield* TestClock.adjust("1 minute"); + const again = yield* store.waitsToWake; + assert.deepStrictEqual( + again.map((wait) => [wait.run_id, wait.woke_json]), + [["r1", JSON.stringify(woke)]], + ); + + // An id is remembered as long as its signal could have been kept, so a sender's retry + // within a long time to live is still the same signal. + yield* open("r3"); + yield* store.mailPut({ + signalId: "long", + address: { runId: "r3", wait: "go" }, + valueJson: '"yes"', + expiresAt: "1970-01-31T00:00:00.000Z", + }); + assert.equal(yield* store.mailDeliver("long", "r3", "go", woke), "delivered"); + yield* TestClock.adjust("10 days"); + yield* store.mailExpire; + assert.isTrue(yield* store.signalSeen("long")); + }), + ), +); + +it.effect("tells the milestone hub of each run and question transition once", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const hub = yield* MilestoneHub.MilestoneHub; + const start = { + runId: "r1", + workflow: "review", + version: 1, + engineTag: "review@1", + idempotencyKey: "k", + input: {}, + }; + const ask = (name: string, request: Schema.Json) => + store.waitOpened({ + runId: "r1", + name, + workflow: "review", + key: undefined, + token: `token-${name}`, + schemaJson: "{}", + requestJson: WorkflowStore.jsonText(request), + watchJson: null, + deadline: null, + }); + yield* store.runStarted(start); + yield* store.runStarted(start); + yield* ask("approve", { title: "Ship it?" }); + yield* ask("approve", { title: "Ship it?" }); + // A wait nobody is asked is no question. + yield* store.waitOpened({ + runId: "r1", + name: "checks", + workflow: "review", + key: undefined, + token: "token-checks", + schemaJson: "{}", + requestJson: null, + watchJson: null, + deadline: null, + }); + yield* store.waitSignalled("r1", "approve", { expired: false, value: true }); + yield* store.waitSignalled("r1", "approve", { expired: false, value: false }); + yield* store.waitSignalled("r1", "checks", { expired: false, value: null }); + yield* ask("later", {}); + yield* store.waitSignalled("r1", "later", { expired: true, value: null }); + yield* ask("last", { title: "Anything else?" }); + yield* store.runPaused("r1", "agent failed"); + yield* store.runPaused("r1", "agent failed again"); + yield* store.runUnpaused("r1"); + yield* store.runUnpaused("r1"); + // A run another run invoked is muted unless asked for, as a subagent's thread is. + yield* store.runStarted({ + ...start, + runId: "r2", + idempotencyKey: "child", + parent: { runId: "r1", wait: "child" }, + }); + yield* store.runEnded("r1", "cancelled", "stopped by a person", null); + yield* store.runEnded("r1", "completed", null, null); + + assert.notInclude( + (yield* hub.recent()).events.map((event) => event.workflowRunId), + "r2", + ); + const { events } = yield* hub.recent({ filter: { includeSubagentChildren: true } }); + assert.deepStrictEqual( + events.map((event): unknown => { + const { id: _id, occurredAt: _at, ...rest } = event; + return rest; + }), + [ + { type: "workflow.run_started" }, + { type: "workflow.needs_input", step: "approve", question: "Ship it?" }, + { type: "workflow.input_resolved", step: "approve", resolution: "answered" }, + { type: "workflow.needs_input", step: "later", question: "later" }, + { type: "workflow.input_resolved", step: "later", resolution: "expired" }, + { type: "workflow.needs_input", step: "last", question: "Anything else?" }, + { type: "workflow.run_paused", reason: "agent failed" }, + { type: "workflow.run_resumed" }, + { + type: "workflow.run_started", + isSubagentChild: true, + workflowRunId: "r2", + runTitle: "review child", + parentWorkflowRunId: "r1", + }, + { type: "workflow.input_resolved", step: "last", resolution: "cancelled" }, + { type: "workflow.run_ended", outcome: "cancelled", detail: "stopped by a person" }, + ].map((news) => ({ + projectId: null, + threadId: null, + parentThreadId: null, + actor: { type: "system" }, + isSubagentChild: false, + workflowRunId: "r1", + workflow: "review", + runTitle: "review k", + parentWorkflowRunId: null, + ...news, + })), + ); + }), + ), +); diff --git a/apps/server/src/workflows/WorkflowStore.ts b/apps/server/src/workflows/WorkflowStore.ts new file mode 100644 index 0000000000000..17d2b4c4bf358 --- /dev/null +++ b/apps/server/src/workflows/WorkflowStore.ts @@ -0,0 +1,1142 @@ +import { + type MilestoneEvent, + MilestoneId, + type WorkflowCounts, + WorkflowRun, + type WorkflowRunReference, + WorkflowRunStatus, + WorkflowStep, +} from "@t3tools/contracts"; +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 Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as PubSub from "effect/PubSub"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as MilestoneHub from "../milestones/MilestoneHub.ts"; + +export { WorkflowRun, WorkflowRunStatus, WorkflowStep }; + +/** Where a signal goes: one wait of one run, or whichever run of a workflow waits on a channel. */ +export type SignalAddress = + | { readonly runId: string; readonly wait: string } + | { readonly workflow: string; readonly channel: string }; + +/** The run that invoked another, and the wait in it that hears how the other ended. */ +export interface RunParent { + readonly runId: string; + readonly wait: string; +} + +export interface RunRow { + readonly run_id: string; + readonly workflow: string; + readonly idempotency_key: string; + readonly version: number | bigint; + readonly engine_tag: string; + readonly title: string; + readonly status: WorkflowRunStatus; + readonly detail: string | null; + readonly result_json: string | null; + readonly input_json: string | null; + readonly parent_run_id: string | null; + readonly parent_wait: string | null; + readonly pauses: number | bigint; + /** Paused until a person resumes it, whatever the workflow's `resumeAfter` says. */ + readonly held: number | bigint; + readonly started_at: string; + readonly updated_at: string; + readonly ended_at: string | null; +} +export interface StepRow { + readonly name: string; + readonly kind: WorkflowStep["kind"]; + readonly status: WorkflowStep["status"]; + readonly attempts: number | bigint; + readonly detail: string | null; + readonly thread_id: string | null; + readonly environment_id: string | null; + readonly result_json: string | null; + readonly said: string | null; + readonly started_at: string; + readonly ended_at: string | null; +} +export interface WaitRow { + readonly run_id: string; + readonly name: string; + readonly token: string; + readonly schema_json: string; + readonly request_json: string | null; + readonly watch_json: string | null; + readonly deadline: string | null; + readonly opened_at: string; + /** What it was woken with, once it has been. */ + readonly woke_json: string | null; +} + +/** Something a run touched, as the one that touched it knows it. */ +export interface ReferenceInput { + readonly kind: string; + readonly key: string; + readonly address: Schema.Json; + /** Empty when the toucher does not know it; a title already kept stays. */ + readonly title: string; + readonly url?: string | null | undefined; + readonly state?: string | null | undefined; +} +interface ReferenceRow { + readonly kind: string; + readonly key: string; + readonly address_json: string; + readonly title: string; + readonly url: string | null; + readonly state: string | null; + readonly steps_json: string; + readonly origin: WorkflowRunReference["origin"]; +} + +// Rows keep JSON as text. Everything stored was a JSON value when it was written. +export const jsonText = (value: Schema.Json): string => JSON.stringify(value); +export const jsonValue = (text: string): Schema.Json => JSON.parse(text) as Schema.Json; + +const now = Effect.map(DateTime.now, DateTime.formatIso); + +type WorkflowMilestone = Extract; +/** What a workflow milestone says beyond its envelope and its run. */ +type WorkflowMilestoneNews = WorkflowMilestone extends infer Event + ? Event extends WorkflowMilestone + ? Omit< + Event, + | "id" + | "occurredAt" + | "projectId" + | "threadId" + | "parentThreadId" + | "actor" + | "isSubagentChild" + | "workflowRunId" + | "workflow" + | "runTitle" + | "parentWorkflowRunId" + > + : never + : never; +// A wake is one write away from its claim. A claim this old without its run moving had none. +const WAKE_REDONE_AFTER = Duration.seconds(30); +// Long enough for a sender's retries, short enough that the table stays small. +// Enough to read what a step said; the page that shows it is not a place for a whole report. +const STEP_RESULT_KEPT = 8_000; +const SIGNAL_IDS_KEPT = Duration.days(7); +const REFERENCE_TITLE_KEPT = 300; +const idsKeptUntil = Effect.map(DateTime.now, (at) => + DateTime.formatIso(DateTime.addDuration(at, SIGNAL_IDS_KEPT)), +); +// A tuple, so no name or key can be read as part of the other. +const mailAddress = (address: SignalAddress) => + JSON.stringify( + "runId" in address + ? ["run", address.runId, address.wait] + : ["key", address.workflow, address.channel], + ); + +export class WorkflowStore extends Context.Service< + WorkflowStore, + { + readonly changes: PubSub.PubSub; + readonly runStarted: (run: { + readonly runId: string; + readonly workflow: string; + readonly version: number; + readonly engineTag: string; + readonly idempotencyKey: string; + readonly input: Schema.Json; + readonly parent?: RunParent | undefined; + }) => Effect.Effect; + readonly runStatus: ( + runId: string, + status: "running" | "waiting", + detail: string | null, + ) => Effect.Effect; + /** + * A wait or an agent of the run is over. The run is running again, unless another it started + * side by side is still out, which it then waits on. + */ + readonly runResumed: (runId: string) => Effect.Effect; + /** `held` unsaid keeps what the run had: a run put back to paused is still held. */ + readonly runPaused: (runId: string, detail: string, held?: boolean) => Effect.Effect; + /** + * A paused run is running again. With `current`, only while that is still the pause: the + * sweep's deadline was worked out from it. False when the run was not changed. + */ + readonly runUnpaused: ( + runId: string, + current?: { readonly pauses: number; readonly updatedAt: string }, + ) => Effect.Effect; + /** The person's resume has reached the engine, so the run no longer waits for one. */ + readonly runUnheld: (runId: string) => Effect.Effect; + readonly runEnded: ( + runId: string, + status: "completed" | "stopped" | "skipped" | "cancelled", + detail: string | null, + result: Schema.Json, + ) => Effect.Effect; + readonly runTitle: (runId: string, title: string) => Effect.Effect; + /** Marks the step running and returns how many times it has now been started. */ + readonly stepStarted: ( + runId: string, + name: string, + kind: WorkflowStep["kind"], + ) => Effect.Effect; + readonly stepEnded: ( + runId: string, + name: string, + status: "completed" | "failed", + detail: string | null, + ) => Effect.Effect; + readonly waitOpened: (wait: { + readonly runId: string; + readonly name: string; + readonly workflow: string; + readonly key: string | undefined; + readonly token: string; + readonly schemaJson: string; + /** What a person is asked, when this wait is a question. */ + readonly requestJson: string | null; + /** What the engine looks at to end this wait by itself. */ + readonly watchJson: string | null; + readonly deadline: string | null; + }) => Effect.Effect; + readonly waitClosed: (runId: string, name: string) => Effect.Effect; + /** The wait takes signals again, under a fresh wake: what woke it was not for it. */ + readonly waitReopened: (runId: string, name: string, token: string) => Effect.Effect; + /** Takes the wait for one signal. False when another signal already has it. */ + /** + * Claims an open wait for one wake and keeps what it is woken with. False when something else + * already claimed it. A signal's id is recorded with the claim, so a retry never claims twice. + */ + readonly waitSignalled: ( + runId: string, + name: string, + woke: Schema.Json, + signalId?: string, + ) => Effect.Effect; + /** Waits claimed a while ago whose runs are still not past them: their wake is redone. */ + readonly waitsToWake: Effect.Effect>; + /** The run's waits that were claimed and are still open, whose wakes a resume sends. */ + readonly waitsClaimed: (runId: string) => Effect.Effect>; + /** + * Hands one buffered signal to one wait, or to none: the claim and the removal happen + * together. `gone` when another wait took the signal, `claimed` when the wait was already woken. + */ + readonly mailDeliver: ( + signalId: string, + runId: string, + name: string, + woke: Schema.Json, + ) => Effect.Effect<"delivered" | "gone" | "claimed">; + /** Runs that were not ended while the run that invoked them was cancelled. */ + readonly orphans: Effect.Effect>; + /** Runs ended before `before`, with no step still going, whose engine journal is still kept. */ + readonly prunable: ( + before: string, + limit: number, + ) => Effect.Effect>; + readonly enginePruned: (runId: string) => Effect.Effect; + /** Every run in this state, however many: the sweep must not miss old ones past a page. */ + readonly everyRun: ( + status: "running" | "waiting" | "paused", + ) => Effect.Effect>; + /** What each run that has not ended is a run of, with no limit. */ + readonly unfinished: Effect.Effect< + ReadonlyArray<{ readonly workflow: string; readonly version: number }> + >; + /** Whether a signal with this id already woke a wait. */ + readonly signalSeen: (signalId: string) => Effect.Effect; + /** Counts one more arrival at `name` in this run and returns the count. */ + readonly mark: (runId: string, name: string) => Effect.Effect; + /** The runs this one invoked that have not ended. */ + readonly children: (runId: string) => Effect.Effect>; + /** The steps a cancelled run left in flight are over: nothing will end them. */ + readonly stepsCancelled: (runId: string, except: string) => Effect.Effect; + /** Cancelled runs whose `onEnd` has not completed and may still be tried, with its tries. */ + readonly runsToEnd: ( + step: string, + tries: number, + ) => Effect.Effect< + ReadonlyArray< + RunRow & { + readonly end_attempts: number | bigint | null; + readonly end_ended_at: string | null; + } + > + >; + /** Cancelled runs with a step other than `except` still going: their cancel was cut short. */ + readonly cancelsCutShort: (except: string) => Effect.Effect>; + /** Ended runs whose parent still waits to hear of it. */ + readonly untold: Effect.Effect>; + readonly stepThread: ( + runId: string, + name: string, + threadId: string, + environment: string | null, + turnId: string, + ) => Effect.Effect; + /** The threads of agent steps still running in this run, with each step's own turn. */ + readonly runningThreads: (runId: string) => Effect.Effect< + ReadonlyArray<{ + readonly threadId: string; + readonly environment?: string; + readonly turnId?: string; + }> + >; + readonly waitAt: (address: SignalAddress) => Effect.Effect; + /** Every open wait on `key`, in one workflow or in all of them. */ + readonly waitsOn: ( + key: string, + workflow: string | undefined, + ) => Effect.Effect>; + readonly waitsPastDeadline: Effect.Effect>; + readonly requests: Effect.Effect>; + /** Open waits the engine ends by looking at something. */ + readonly watches: Effect.Effect>; + /** The thread of the run's latest agent step, if it has had one. */ + readonly latestThread: ( + runId: string, + ) => Effect.Effect<{ readonly threadId: string; readonly environmentId: string | null } | null>; + readonly counts: Effect.Effect; + /** Keep what a step produced for a person to read. A large value is kept as its start. */ + readonly stepResult: ( + runId: string, + name: string, + value: Schema.Json, + /** What an agent said in closing, when its result is data and not that reply. */ + said?: string, + ) => Effect.Effect; + /** Say something about a step that is under way, such as when its sleep ends. */ + readonly stepDetail: (runId: string, name: string, detail: string) => Effect.Effect; + readonly mailPut: (mail: { + readonly signalId: string; + readonly address: SignalAddress; + readonly valueJson: string; + readonly expiresAt: string; + }) => Effect.Effect; + /** The oldest signal kept for any of these addresses, but `passed`. It stays until `mailDelete`. */ + readonly mailNext: ( + addresses: ReadonlyArray, + passed?: ReadonlySet, + ) => Effect.Effect< + | { + readonly signalId: string; + readonly valueJson: string; + readonly address: SignalAddress; + } + | undefined + >; + readonly mailDelete: (signalId: string) => Effect.Effect; + readonly mailExpire: Effect.Effect; + readonly run: (runId: string) => Effect.Effect; + /** The run a workflow was started as under `key`, of whichever version. */ + readonly runByKey: (workflow: string, key: string) => Effect.Effect; + readonly runs: (status: WorkflowRunStatus | undefined) => Effect.Effect>; + /** Runs by what they are a run of and what they were started as, newest first. */ + readonly runsWhere: (filter: { + readonly workflow?: string | undefined; + readonly status?: WorkflowRunStatus | undefined; + readonly keyPrefix?: string | undefined; + }) => Effect.Effect>; + readonly triggerNext: (triggerId: string) => Effect.Effect; + readonly triggerSet: (triggerId: string, nextAt: string) => Effect.Effect; + /** Forgets every trigger but these, so one that comes back starts over. */ + readonly triggersKeep: (triggerIds: ReadonlyArray) => Effect.Effect; + /** The hook's token: the one kept for it, or `fresh` from now on. */ + readonly hookToken: (hookId: string, fresh: string) => Effect.Effect; + readonly steps: (runId: string) => Effect.Effect>; + /** + * Keep that the run touched something: from a step, or with no step from what started it. A + * later touch of the same thing keeps what it knows that is new and adds its step. + */ + readonly referenceNoted: ( + runId: string, + step: string | null, + reference: ReferenceInput, + ) => Effect.Effect; + /** What the run touched, in the order it first did. */ + readonly references: (runId: string) => Effect.Effect>; + } +>()("t3/workflows/WorkflowStore") {} + +export const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const changes = yield* PubSub.unbounded(); + // A write here is bookkeeping for a run the engine already journaled: failing it would park a + // healthy run, so a database that cannot take it is a defect of the process instead. + const write = (runId: string, effect: Effect.Effect) => + effect.pipe(Effect.orDie, Effect.andThen(PubSub.publish(changes, runId)), Effect.asVoid); + const waitColumns = sql`run_id, name, token, schema_json, request_json, watch_json, deadline, opened_at, woke_json`; + + const hub = yield* Effect.serviceOption(MilestoneHub.MilestoneHub); + /** Tells the milestone hub of a transition this store just wrote, under an id stable for it. */ + const tell = Effect.fn("WorkflowStore.tell")(function* ( + runId: string, + key: string, + at: string, + news: WorkflowMilestoneNews, + ) { + if (Option.isNone(hub)) return; + const [run] = yield* sql>` + SELECT workflow, title, parent_run_id FROM workflow_runs WHERE run_id = ${runId} + `.pipe(Effect.orDie); + if (run === undefined) return; + yield* hub.value.publish({ + id: MilestoneId.make(`${news.type}:${key}`), + occurredAt: at, + projectId: null, + threadId: null, + parentThreadId: null, + actor: { type: "system" }, + isSubagentChild: run.parent_run_id !== null, + workflowRunId: runId, + workflow: run.workflow, + runTitle: run.title, + parentWorkflowRunId: run.parent_run_id, + ...news, + } as WorkflowMilestone); + }); + const questionTitle = (wait: Pick) => { + const request = wait.request_json === null ? null : jsonValue(wait.request_json); + const title = + request !== null && typeof request === "object" && !Array.isArray(request) + ? (request as { readonly title?: unknown }).title + : undefined; + return typeof title === "string" && title.trim() !== "" ? title : wait.name; + }; + /** A question claimed by an answer or its timeout is resolved, whichever claimed it. */ + const questionClaimed = Effect.fn("WorkflowStore.questionClaimed")(function* ( + runId: string, + name: string, + woke: Schema.Json, + at: string, + ) { + if (Option.isNone(hub)) return; + const [wait] = yield* sql>` + SELECT request_json, opened_at FROM workflow_waits WHERE run_id = ${runId} AND name = ${name} + `.pipe(Effect.orDie); + if (wait === undefined || wait.request_json === null) return; + const expired = + woke !== null && + typeof woke === "object" && + (woke as { readonly expired?: unknown }).expired === true; + yield* tell(runId, `${runId}:${name}:${wait.opened_at}`, at, { + type: "workflow.input_resolved", + step: name, + resolution: expired ? "expired" : "answered", + }); + }); + + return WorkflowStore.of({ + changes, + runStarted: Effect.fn("WorkflowStore.runStarted")(function* (run) { + const at = yield* now; + // A start under a key that already has its run changes nothing, and tells nobody. + const inserted = yield* sql` + INSERT INTO workflow_runs ( + run_id, workflow, version, engine_tag, idempotency_key, title, status, input_json, + parent_run_id, parent_wait, started_at, updated_at + ) VALUES ( + ${run.runId}, ${run.workflow}, ${run.version}, ${run.engineTag}, + ${run.idempotencyKey}, ${`${run.workflow} ${run.idempotencyKey}`}, 'running', + ${jsonText(run.input)}, ${run.parent?.runId ?? null}, ${run.parent?.wait ?? null}, + ${at}, ${at} + ) + ON CONFLICT DO NOTHING + RETURNING run_id + `.pipe(Effect.orDie); + if (inserted.length === 0) return; + yield* PubSub.publish(changes, run.runId); + yield* tell(run.runId, run.runId, at, { type: "workflow.run_started" }); + }), + runStatus: Effect.fn("WorkflowStore.runStatus")(function* (runId, status, detail) { + const at = yield* now; + yield* write( + runId, + sql` + UPDATE workflow_runs + SET status = ${status}, detail = ${detail}, updated_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL AND status != 'paused' + `, + ); + }), + runResumed: Effect.fn("WorkflowStore.runResumed")(function* (runId) { + const at = yield* now; + // One statement, so two of them ending at once cannot leave the run on one that has ended. + yield* write( + runId, + sql` + WITH out AS ( + SELECT CASE WHEN kind IN ('agent', 'sleep') THEN kind || ' ' || name ELSE name END + AS detail + FROM workflow_steps + WHERE run_id = ${runId} AND status = 'running' + AND kind IN ('wait', 'ask', 'agent', 'sleep') + ORDER BY started_at, rowid LIMIT 1 + ) + UPDATE workflow_runs + SET status = CASE WHEN EXISTS (SELECT 1 FROM out) THEN 'waiting' ELSE 'running' END, + detail = (SELECT detail FROM out), updated_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL AND status != 'paused' + `, + ); + }), + runPaused: Effect.fn("WorkflowStore.runPaused")(function* (runId, detail, held) { + const at = yield* now; + const reason = detail.slice(0, 2000); + const paused = yield* sql` + UPDATE workflow_runs + SET status = 'paused', detail = ${reason}, pauses = pauses + 1, + held = ${held === undefined ? sql`held` : held ? 1 : 0}, updated_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL AND status != 'paused' + RETURNING run_id + `.pipe(Effect.orDie); + yield* PubSub.publish(changes, runId); + if (paused.length > 0) { + yield* tell(runId, `${runId}:${at}`, at, { type: "workflow.run_paused", reason }); + } + }), + runUnpaused: Effect.fn("WorkflowStore.runUnpaused")(function* (runId, current) { + const at = yield* now; + const rows = yield* sql` + UPDATE workflow_runs SET status = 'running', detail = NULL, updated_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL AND status = 'paused' + AND (${current === undefined ? 1 : 0} = 1 + OR (pauses = ${current?.pauses ?? 0} AND updated_at = ${current?.updatedAt ?? ""})) + RETURNING run_id + `.pipe(Effect.orDie); + yield* PubSub.publish(changes, runId); + if (rows.length === 0) return false; + yield* tell(runId, `${runId}:${at}`, at, { type: "workflow.run_resumed" }); + return true; + }), + runUnheld: Effect.fn("WorkflowStore.runUnheld")(function* (runId) { + // A pause since then set its own `held`. + yield* write( + runId, + sql`UPDATE workflow_runs SET held = 0 WHERE run_id = ${runId} AND status != 'paused'`, + ); + }), + runEnded: Effect.fn("WorkflowStore.runEnded")(function* (runId, status, detail, result) { + const at = yield* now; + const resultJson = jsonText(result); + // False when another outcome was recorded first: the run ended some other way. + const ended = yield* sql + .withTransaction( + Effect.gen(function* () { + const rows = yield* sql` + UPDATE workflow_runs + SET status = ${status}, detail = ${detail}, result_json = ${resultJson}, + pauses = 0, updated_at = ${at}, ended_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL + RETURNING run_id + `; + const closed = yield* sql>` + DELETE FROM workflow_waits WHERE run_id = ${runId} + RETURNING name, request_json, opened_at + `; + return { ended: rows.length > 0, closed }; + }), + ) + .pipe(Effect.orDie); + yield* PubSub.publish(changes, runId); + if (!ended.ended) return false; + for (const wait of ended.closed) { + if (wait.request_json === null) continue; + yield* tell(runId, `${runId}:${wait.name}:${wait.opened_at}`, at, { + type: "workflow.input_resolved", + step: wait.name, + resolution: "cancelled", + }); + } + yield* tell(runId, runId, at, { type: "workflow.run_ended", outcome: status, detail }); + return true; + }), + runTitle: Effect.fn("WorkflowStore.runTitle")(function* (runId, title) { + yield* write( + runId, + sql`UPDATE workflow_runs SET title = ${title.slice(0, 200)} WHERE run_id = ${runId}`, + ); + }), + stepStarted: Effect.fn("WorkflowStore.stepStarted")(function* (runId, name, kind) { + const at = yield* now; + const rows = yield* sql<{ attempts: number | bigint }>` + INSERT INTO workflow_steps (run_id, name, kind, status, attempts, started_at) + VALUES (${runId}, ${name}, ${kind}, 'running', 1, ${at}) + ON CONFLICT (run_id, name) DO UPDATE + SET status = 'running', attempts = attempts + 1, detail = NULL, ended_at = NULL, + started_at = excluded.started_at + RETURNING attempts + `.pipe(Effect.orDie); + yield* PubSub.publish(changes, runId); + return Number(rows[0]?.attempts ?? 1); + }), + stepEnded: Effect.fn("WorkflowStore.stepEnded")(function* (runId, name, status, detail) { + const at = yield* now; + yield* write( + runId, + sql.withTransaction( + Effect.andThen( + sql` + UPDATE workflow_steps + SET status = ${status}, detail = ${detail === null ? null : detail.slice(0, 2000)}, ended_at = ${at} + WHERE run_id = ${runId} AND name = ${name} + `, + // A step that finished is progress: the next pause is the first in a row again. + status === "completed" + ? // Not while paused: a step beside the one that failed is no progress past it. + sql` + UPDATE workflow_runs SET pauses = 0 + WHERE run_id = ${runId} AND ended_at IS NULL AND status != 'paused' + ` + : Effect.void, + ), + ), + ); + }), + waitOpened: Effect.fn("WorkflowStore.waitOpened")(function* (wait) { + const at = yield* now; + const opened = yield* sql` + INSERT INTO workflow_waits ( + run_id, name, workflow, token, key, schema_json, request_json, watch_json, deadline, + opened_at + ) VALUES ( + ${wait.runId}, ${wait.name}, ${wait.workflow}, ${wait.token}, ${wait.key ?? null}, + ${wait.schemaJson}, ${wait.requestJson}, ${wait.watchJson}, ${wait.deadline}, ${at} + ) + ON CONFLICT (run_id, name) DO NOTHING + RETURNING name + `.pipe(Effect.orDie); + yield* PubSub.publish(changes, wait.runId); + if (opened.length === 0 || wait.requestJson === null) return; + yield* tell(wait.runId, `${wait.runId}:${wait.name}:${at}`, at, { + type: "workflow.needs_input", + step: wait.name, + question: questionTitle({ name: wait.name, request_json: wait.requestJson }), + }); + }), + waitClosed: Effect.fn("WorkflowStore.waitClosed")(function* (runId, name) { + yield* write( + runId, + sql`DELETE FROM workflow_waits WHERE run_id = ${runId} AND name = ${name}`, + ); + }), + waitReopened: Effect.fn("WorkflowStore.waitReopened")(function* (runId, name, token) { + yield* write( + runId, + sql` + UPDATE workflow_waits SET token = ${token}, signalled_at = NULL, woke_json = NULL + WHERE run_id = ${runId} AND name = ${name} + `, + ); + }), + waitSignalled: Effect.fn("WorkflowStore.waitSignalled")( + function* (runId, name, woke, signalId) { + const at = yield* now; + const taken = yield* sql` + UPDATE workflow_waits SET signalled_at = ${at}, woke_json = ${jsonText(woke)} + WHERE run_id = ${runId} AND name = ${name} AND signalled_at IS NULL + RETURNING name + `; + if (taken.length > 0 && signalId !== undefined) { + const receipt = yield* sql` + INSERT INTO workflow_signals (signal_id, kept_until) + VALUES (${signalId}, MAX(${yield* idsKeptUntil}, COALESCE( + (SELECT expires_at FROM workflow_mail WHERE signal_id = ${signalId}), '' + ))) + ON CONFLICT (signal_id) DO NOTHING + RETURNING signal_id + `; + // The id already woke a wait, so this one is not claimed: the transaction undoes it. + if (receipt.length === 0) return yield* Effect.fail("seen" as const); + } + return taken.length > 0; + }, + (effect, runId, name, woke) => + sql.withTransaction(effect).pipe( + Effect.catchIf( + (error) => error === "seen", + () => Effect.succeed(false), + ), + Effect.orDie, + Effect.tap((taken) => + taken + ? Effect.flatMap(now, (at) => questionClaimed(runId, name, woke, at)) + : Effect.void, + ), + ), + ), + waitsToWake: Effect.gen(function* () { + const before = DateTime.formatIso( + DateTime.subtractDuration(yield* DateTime.now, WAKE_REDONE_AFTER), + ); + return yield* sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE woke_json IS NOT NULL AND signalled_at <= ${before} + AND run_id IN (SELECT run_id FROM workflow_runs WHERE ended_at IS NULL) + `.pipe(Effect.orDie); + }), + waitsClaimed: Effect.fn("WorkflowStore.waitsClaimed")(function* (runId) { + return yield* sql` + SELECT ${waitColumns} FROM workflow_waits WHERE run_id = ${runId} AND woke_json IS NOT NULL + `.pipe(Effect.orDie); + }), + mailDeliver: Effect.fn("WorkflowStore.mailDeliver")(function* (signalId, runId, name, woke) { + const at = yield* now; + const outcome = yield* sql + .withTransaction( + Effect.gen(function* () { + // A kept copy of an id that already woke a wait straight is spent: it is dropped, so + // it wakes no second wait and is not offered again. + const seen = yield* sql`SELECT 1 FROM workflow_signals WHERE signal_id = ${signalId}`; + if (seen.length > 0) { + yield* sql`DELETE FROM workflow_mail WHERE signal_id = ${signalId}`; + return "gone" as const; + } + const claimed = yield* sql` + UPDATE workflow_waits SET signalled_at = ${at}, woke_json = ${jsonText(woke)} + WHERE run_id = ${runId} AND name = ${name} AND signalled_at IS NULL + RETURNING name + `; + if (claimed.length === 0) return "claimed" as const; + const taken = yield* sql<{ expires_at: string }>` + DELETE FROM workflow_mail WHERE signal_id = ${signalId} RETURNING expires_at + `; + // Failing undoes the claim: the wait stays open for a signal that is still there. + const copy = taken[0]; + if (copy === undefined) return yield* Effect.fail("gone" as const); + const keep = yield* idsKeptUntil; + const receipt = yield* sql` + INSERT INTO workflow_signals (signal_id, kept_until) + VALUES (${signalId}, ${copy.expires_at > keep ? copy.expires_at : keep}) + ON CONFLICT (signal_id) DO NOTHING + RETURNING signal_id + `; + // Delivered straight in the meantime: undone, and the next look drops the copy above. + if (receipt.length === 0) return yield* Effect.fail("gone" as const); + return "delivered" as const; + }), + ) + .pipe( + Effect.catchIf( + (error) => error === "gone", + () => Effect.succeed("gone" as const), + ), + Effect.orDie, + ); + if (outcome === "delivered") yield* questionClaimed(runId, name, woke, at); + return outcome; + }), + prunable: Effect.fn("WorkflowStore.prunable")(function* (before, limit) { + return yield* sql<{ run_id: string; engine_tag: string }>` + SELECT run_id, engine_tag FROM workflow_runs r + WHERE ended_at IS NOT NULL AND ended_at < ${before} AND engine_pruned_at IS NULL + AND NOT EXISTS ( + SELECT 1 FROM workflow_steps s WHERE s.run_id = r.run_id AND s.status = 'running' + ) + ORDER BY ended_at LIMIT ${limit} + `.pipe(Effect.orDie); + }), + enginePruned: Effect.fn("WorkflowStore.enginePruned")(function* (runId) { + const at = yield* now; + yield* sql` + UPDATE workflow_runs SET engine_pruned_at = ${at} WHERE run_id = ${runId} + `.pipe(Effect.orDie); + }), + orphans: sql` + SELECT c.* FROM workflow_runs c + JOIN workflow_runs p ON p.run_id = c.parent_run_id + WHERE c.ended_at IS NULL AND p.status = 'cancelled' + `.pipe(Effect.orDie), + unfinished: sql<{ workflow: string; version: number | bigint }>` + SELECT workflow, version FROM workflow_runs WHERE ended_at IS NULL + `.pipe( + Effect.map((rows) => + rows.map((row) => ({ workflow: row.workflow, version: Number(row.version) })), + ), + Effect.orDie, + ), + everyRun: Effect.fn("WorkflowStore.everyRun")(function* (status) { + return yield* sql`SELECT * FROM workflow_runs WHERE status = ${status}`.pipe( + Effect.orDie, + ); + }), + signalSeen: Effect.fn("WorkflowStore.signalSeen")(function* (signalId) { + const rows = yield* sql` + SELECT 1 FROM workflow_signals WHERE signal_id = ${signalId} + `.pipe(Effect.orDie); + return rows.length > 0; + }), + mark: Effect.fn("WorkflowStore.mark")(function* (runId, name) { + const rows = yield* sql<{ count: number | bigint }>` + INSERT INTO workflow_marks (run_id, name, count) VALUES (${runId}, ${name}, 1) + ON CONFLICT (run_id, name) DO UPDATE SET count = count + 1 + RETURNING count + `.pipe(Effect.orDie); + return Number(rows[0]?.count ?? 1); + }), + children: Effect.fn("WorkflowStore.children")(function* (runId) { + return yield* sql` + SELECT * FROM workflow_runs WHERE parent_run_id = ${runId} AND ended_at IS NULL + `.pipe(Effect.orDie); + }), + stepsCancelled: Effect.fn("WorkflowStore.stepsCancelled")(function* (runId, except) { + const at = yield* now; + yield* write( + runId, + sql` + UPDATE workflow_steps SET status = 'failed', detail = 'cancelled', ended_at = ${at} + WHERE run_id = ${runId} AND status = 'running' AND name != ${except} + `, + ); + }), + runsToEnd: Effect.fn("WorkflowStore.runsToEnd")(function* (step, tries) { + return yield* sql< + RunRow & { end_attempts: number | bigint | null; end_ended_at: string | null } + >` + SELECT r.*, s.attempts AS end_attempts, s.ended_at AS end_ended_at + FROM workflow_runs r + LEFT JOIN workflow_steps s ON s.run_id = r.run_id AND s.name = ${step} + WHERE r.status = 'cancelled' + AND (s.status IS NULL OR (s.status != 'completed' AND s.attempts < ${tries})) + `.pipe(Effect.orDie); + }), + cancelsCutShort: Effect.fn("WorkflowStore.cancelsCutShort")(function* (except) { + return yield* sql` + SELECT r.* FROM workflow_runs r + WHERE r.status = 'cancelled' AND EXISTS ( + SELECT 1 FROM workflow_steps s + WHERE s.run_id = r.run_id AND s.status = 'running' AND s.name != ${except} + ) + `.pipe(Effect.orDie); + }), + untold: sql` + SELECT c.* FROM workflow_waits w + JOIN workflow_runs c ON c.parent_run_id = w.run_id AND c.parent_wait = w.name + WHERE w.signalled_at IS NULL AND c.ended_at IS NOT NULL + `.pipe(Effect.orDie), + stepThread: Effect.fn("WorkflowStore.stepThread")( + function* (runId, name, threadId, environment, turnId) { + yield* write( + runId, + sql` + UPDATE workflow_steps + SET thread_id = ${threadId}, environment_id = ${environment}, turn_id = ${turnId} + WHERE run_id = ${runId} AND name = ${name} + `, + ); + }, + ), + runningThreads: Effect.fn("WorkflowStore.runningThreads")(function* (runId) { + const rows = yield* sql<{ + thread_id: string; + environment_id: string | null; + turn_id: string | null; + }>` + SELECT thread_id, environment_id, turn_id FROM workflow_steps + WHERE run_id = ${runId} AND status = 'running' AND thread_id IS NOT NULL + `.pipe(Effect.orDie); + return rows.map((row) => ({ + threadId: row.thread_id, + ...(row.environment_id === null ? {} : { environment: row.environment_id }), + ...(row.turn_id === null ? {} : { turnId: row.turn_id }), + })); + }), + waitAt: Effect.fn("WorkflowStore.waitAt")(function* (address) { + const rows = yield* ( + "runId" in address + ? sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE run_id = ${address.runId} AND name = ${address.wait} AND signalled_at IS NULL + ` + : sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE workflow = ${address.workflow} AND key = ${address.channel} AND signalled_at IS NULL + ORDER BY opened_at LIMIT 1 + ` + ).pipe(Effect.orDie); + return rows[0]; + }), + waitsOn: Effect.fn("WorkflowStore.waitsOn")(function* (key, workflow) { + return yield* sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE key = ${key} AND signalled_at IS NULL + AND (${workflow ?? null} IS NULL OR workflow = ${workflow ?? null}) + ORDER BY opened_at + `.pipe(Effect.orDie); + }), + waitsPastDeadline: Effect.flatMap(now, (at) => + sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE deadline IS NOT NULL AND deadline <= ${at} AND signalled_at IS NULL + `.pipe(Effect.orDie), + ), + latestThread: Effect.fn("WorkflowStore.latestThread")(function* (runId) { + const rows = yield* sql<{ thread_id: string; environment_id: string | null }>` + SELECT thread_id, environment_id FROM workflow_steps + WHERE run_id = ${runId} AND thread_id IS NOT NULL + ORDER BY started_at DESC, rowid DESC LIMIT 1 + `.pipe(Effect.orDie); + const row = rows[0]; + return row === undefined + ? null + : { threadId: row.thread_id, environmentId: row.environment_id }; + }), + counts: sql<{ questions: number; paused: number; active: number; total: number }>` + SELECT + (SELECT COUNT(*) FROM workflow_waits + WHERE request_json IS NOT NULL AND signalled_at IS NULL) AS questions, + (SELECT COUNT(*) FROM workflow_runs WHERE status = 'paused') AS paused, + (SELECT COUNT(*) FROM workflow_runs WHERE ended_at IS NULL) AS active, + (SELECT COUNT(*) FROM workflow_runs) AS total + `.pipe( + Effect.orDie, + Effect.map((rows) => ({ + needsYou: Number(rows[0]?.questions ?? 0) + Number(rows[0]?.paused ?? 0), + active: Number(rows[0]?.active ?? 0), + total: Number(rows[0]?.total ?? 0), + })), + ), + stepResult: Effect.fn("WorkflowStore.stepResult")(function* (runId, name, value, said) { + const full = jsonText(value); + const kept = + full.length <= STEP_RESULT_KEPT ? full : jsonText(`${full.slice(0, STEP_RESULT_KEPT)}…`); + const words = said?.trim() ?? ""; + const keptSaid = + words === "" + ? null + : words.length <= STEP_RESULT_KEPT + ? words + : `${words.slice(0, STEP_RESULT_KEPT)}…`; + yield* sql` + UPDATE workflow_steps SET result_json = ${kept}, said = ${keptSaid} + WHERE run_id = ${runId} AND name = ${name} + `.pipe(Effect.orDie); + }), + stepDetail: Effect.fn("WorkflowStore.stepDetail")(function* (runId, name, detail) { + yield* write( + runId, + sql`UPDATE workflow_steps SET detail = ${detail} WHERE run_id = ${runId} AND name = ${name}`, + ); + }), + requests: sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE request_json IS NOT NULL AND signalled_at IS NULL ORDER BY opened_at + `.pipe(Effect.orDie), + watches: sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE watch_json IS NOT NULL AND signalled_at IS NULL ORDER BY opened_at + `.pipe(Effect.orDie), + mailPut: Effect.fn("WorkflowStore.mailPut")(function* (mail) { + yield* sql + .withTransaction( + Effect.andThen( + sql` + INSERT INTO workflow_mail (signal_id, address, value_json, expires_at) + VALUES (${mail.signalId}, ${mailAddress(mail.address)}, ${mail.valueJson}, ${mail.expiresAt}) + ON CONFLICT (signal_id) DO NOTHING + `, + // A copy kept by a retry that raced the first delivery outlives no receipt of it. + sql` + UPDATE workflow_signals SET kept_until = ${mail.expiresAt} + WHERE signal_id = ${mail.signalId} AND kept_until < ${mail.expiresAt} + `, + ), + ) + .pipe(Effect.orDie); + }), + mailNext: Effect.fn("WorkflowStore.mailNext")(function* (addresses, passed = new Set()) { + for (const address of addresses) { + const rows = yield* sql<{ signal_id: string; value_json: string }>` + SELECT signal_id, value_json FROM workflow_mail + WHERE address = ${mailAddress(address)} ORDER BY rowid + `.pipe(Effect.orDie); + const mail = rows.find((row) => !passed.has(row.signal_id)); + if (mail !== undefined) { + return { signalId: mail.signal_id, valueJson: mail.value_json, address }; + } + } + return undefined; + }), + mailDelete: Effect.fn("WorkflowStore.mailDelete")(function* (signalId) { + yield* sql`DELETE FROM workflow_mail WHERE signal_id = ${signalId}`.pipe(Effect.orDie); + }), + mailExpire: Effect.gen(function* () { + const at = yield* DateTime.now; + yield* sql`DELETE FROM workflow_mail WHERE expires_at <= ${DateTime.formatIso(at)}`; + yield* sql`DELETE FROM workflow_signals WHERE kept_until <= ${DateTime.formatIso(at)}`; + }).pipe(Effect.orDie), + run: Effect.fn("WorkflowStore.run")(function* (runId) { + const rows = yield* sql`SELECT * FROM workflow_runs WHERE run_id = ${runId}`.pipe( + Effect.orDie, + ); + return rows[0]; + }), + runByKey: Effect.fn("WorkflowStore.runByKey")(function* (workflow, key) { + const rows = yield* sql` + SELECT * FROM workflow_runs WHERE workflow = ${workflow} AND idempotency_key = ${key} + ORDER BY started_at LIMIT 1 + `.pipe(Effect.orDie); + return rows[0]; + }), + runsWhere: Effect.fn("WorkflowStore.runsWhere")(function* (filter) { + const prefix = filter.keyPrefix ?? null; + // A range, not LIKE, which would read `%` and `_` in a key as patterns. + return yield* sql` + SELECT * FROM workflow_runs + WHERE (${filter.workflow ?? null} IS NULL OR workflow = ${filter.workflow ?? null}) + AND (${filter.status ?? null} IS NULL OR status = ${filter.status ?? null}) + AND (${prefix} IS NULL OR ( + idempotency_key >= ${prefix} AND idempotency_key < ${`${prefix ?? ""}\u{10FFFF}`} + )) + ORDER BY started_at DESC, rowid DESC LIMIT 500 + `.pipe(Effect.orDie); + }), + runs: Effect.fn("WorkflowStore.runs")(function* (status) { + return yield* ( + status === undefined + ? // Skipped runs are counted apart, so a trigger that skips most of what it brings does + // not push the runs that did something out of the list. + sql` + SELECT * FROM ( + SELECT * FROM workflow_runs + WHERE NOT (status = 'skipped' AND parent_run_id IS NULL) + ORDER BY started_at DESC LIMIT 500 + ) + UNION ALL + SELECT * FROM ( + SELECT * FROM workflow_runs + WHERE status = 'skipped' AND parent_run_id IS NULL + ORDER BY started_at DESC LIMIT 500 + ) + ORDER BY started_at DESC + ` + : sql` + SELECT * FROM workflow_runs WHERE status = ${status} + ORDER BY started_at DESC LIMIT 500 + ` + ).pipe(Effect.orDie); + }), + triggerNext: Effect.fn("WorkflowStore.triggerNext")(function* (triggerId) { + const rows = yield* sql<{ next_at: string }>` + SELECT next_at FROM workflow_triggers WHERE trigger_id = ${triggerId} + `.pipe(Effect.orDie); + return rows[0]?.next_at; + }), + triggerSet: Effect.fn("WorkflowStore.triggerSet")(function* (triggerId, nextAt) { + yield* sql` + INSERT INTO workflow_triggers (trigger_id, next_at) VALUES (${triggerId}, ${nextAt}) + ON CONFLICT (trigger_id) DO UPDATE SET next_at = excluded.next_at + `.pipe(Effect.orDie); + }), + triggersKeep: Effect.fn("WorkflowStore.triggersKeep")(function* (triggerIds) { + const kept = yield* sql<{ trigger_id: string }>`SELECT trigger_id FROM workflow_triggers`; + for (const { trigger_id } of kept) { + if (triggerIds.includes(trigger_id)) continue; + yield* sql`DELETE FROM workflow_triggers WHERE trigger_id = ${trigger_id}`; + } + }, Effect.orDie), + hookToken: Effect.fn("WorkflowStore.hookToken")(function* (hookId, fresh) { + yield* sql` + INSERT INTO workflow_hooks (hook_id, token) VALUES (${hookId}, ${fresh}) + ON CONFLICT (hook_id) DO NOTHING + `; + const rows = yield* sql<{ token: string }>` + SELECT token FROM workflow_hooks WHERE hook_id = ${hookId} + `; + return rows[0]?.token ?? fresh; + }, Effect.orDie), + steps: Effect.fn("WorkflowStore.steps")(function* (runId) { + return yield* sql` + SELECT name, kind, status, attempts, detail, thread_id, environment_id, result_json, + said, started_at, ended_at + FROM workflow_steps WHERE run_id = ${runId} ORDER BY started_at, rowid + `.pipe(Effect.orDie); + }), + referenceNoted: Effect.fn("WorkflowStore.referenceNoted")(function* (runId, step, reference) { + const at = yield* now; + const addressJson = jsonText(reference.address); + const title = reference.title.slice(0, REFERENCE_TITLE_KEPT); + const changed = yield* sql + .withTransaction( + Effect.gen(function* () { + const rows = yield* sql` + SELECT kind, key, address_json, title, url, state, steps_json, origin + FROM workflow_run_references + WHERE run_id = ${runId} AND kind = ${reference.kind} AND key = ${reference.key} + `; + const row = rows[0]; + if (row === undefined) { + yield* sql` + INSERT INTO workflow_run_references ( + run_id, kind, key, address_json, title, url, state, steps_json, origin, noted_at + ) VALUES ( + ${runId}, ${reference.kind}, ${reference.key}, ${addressJson}, ${title}, + ${reference.url ?? null}, ${reference.state ?? null}, + ${jsonText(step === null ? [] : [step])}, ${step === null ? "trigger" : "step"}, + ${at} + ) + `; + return true; + } + const steps = jsonValue(row.steps_json) as ReadonlyArray; + const next = { + address_json: addressJson, + title: title === "" ? row.title : title, + url: reference.url ?? row.url, + state: reference.state ?? row.state, + steps_json: + step === null || steps.includes(step) ? row.steps_json : jsonText([...steps, step]), + }; + // A touch that says nothing new is no change, so a look every minute costs no list. + if ( + next.address_json === row.address_json && + next.title === row.title && + next.url === row.url && + next.state === row.state && + next.steps_json === row.steps_json + ) { + return false; + } + yield* sql` + UPDATE workflow_run_references + SET address_json = ${next.address_json}, title = ${next.title}, url = ${next.url}, + state = ${next.state}, steps_json = ${next.steps_json} + WHERE run_id = ${runId} AND kind = ${reference.kind} AND key = ${reference.key} + `; + return true; + }), + ) + .pipe(Effect.orDie); + if (changed) yield* PubSub.publish(changes, runId); + }), + references: Effect.fn("WorkflowStore.references")(function* (runId) { + const rows = yield* sql` + SELECT kind, key, address_json, title, url, state, steps_json, origin + FROM workflow_run_references WHERE run_id = ${runId} ORDER BY rowid + `.pipe(Effect.orDie); + return rows.map((row) => ({ + kind: row.kind, + key: row.key, + address: jsonValue(row.address_json), + title: row.title, + url: row.url, + state: row.state, + steps: jsonValue(row.steps_json) as ReadonlyArray, + origin: row.origin, + })); + }), + }); +}); + +export const layer = Layer.effect(WorkflowStore, make); diff --git a/apps/server/src/workflows/Workflows.test.ts b/apps/server/src/workflows/Workflows.test.ts new file mode 100644 index 0000000000000..cc56f6cd79a8a --- /dev/null +++ b/apps/server/src/workflows/Workflows.test.ts @@ -0,0 +1,2424 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import { ProjectId } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +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 FileSystem from "effect/FileSystem"; +import * as Latch from "effect/Latch"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import { daily, every, Tick, webhook, WebhookRequest } from "./triggers.ts"; +import { issues, pullRequests } from "./forgeApi.ts"; +import { cancel, runs, signal, signalAll, start, store } from "./stepServices.ts"; +import { type InRun, invoke, skip, sleep, step, stop, title, wait, workflow } from "./workflow.ts"; +import { type AgentResult, WorkflowAgentError, WorkflowAgents } from "./WorkflowAgents.ts"; +import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; +import * as WorkflowEngine from "./WorkflowEngine.ts"; +import { + Issue, + pullRequestReferenceOf, + unavailable, + WorkflowForge, + WorkflowForgeError, +} from "./WorkflowForge.ts"; +import { issueReference, noteReference } from "./runReferences.ts"; +import { agent, ask } from "./workflowAgent.ts"; +import * as Workflows from "./Workflows.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; +import type { WorkflowRun, WorkflowRunStatus } from "./WorkflowStore.ts"; + +const once = { retry: { times: 0 } } as const; + +/** Holds the `work` step of an `owned` run in `busy` mode until the test lets it go. */ +interface Latch { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + readonly cleaned: Deferred.Deferred; + /** Holds the `bad` step of a `sibling` run until the test lets it go. */ + readonly bad: Deferred.Deferred; +} + +/** A workflow whose `flaky` step fails until `failures` reaches zero, counting every execution. */ +const definitions = ( + counts: Ref.Ref>, + failures: Ref.Ref, + latch: Latch, +) => { + const count = (name: string) => + Ref.updateAndGet(counts, (all) => ({ ...all, [name]: (all[name] ?? 0) + 1 })).pipe( + Effect.map((all) => all[name]!), + ); + return [ + workflow( + "owned", + { + version: 1, + payload: Schema.Struct({ mode: Schema.Literals(["finish", "stop", "hold", "busy"]) }), + // Counted by how the run ended, and failing for as long as `failures` says. + onEnd: (payload, end) => + Effect.gen(function* () { + // The engine's setting for reading integers must not reach a cleanup either. + if (yield* SqlClient.SafeIntegers) return yield* Effect.fail("SafeIntegers leaked"); + if (payload.mode === "busy") { + // Says whether the step it cleans up after had finished. + const all = yield* Ref.get(counts); + yield* count(`end:busy:${all["work"] === 1 ? "after" : "before"} work`); + return yield* Deferred.succeed(latch.cleaned, undefined); + } + const left = yield* Ref.getAndUpdate(failures, (rest) => Math.max(0, rest - 1)); + if (left > 0) return yield* Effect.fail("the machine would not go"); + yield* count(`end:${payload.mode}:${end.outcome}:${end.reason ?? ""}`); + }), + }, + (payload) => + Effect.gen(function* () { + if (payload.mode === "busy") { + yield* step( + "work", + { returns: Schema.Number }, + Effect.andThen( + Effect.andThen( + Deferred.succeed(latch.entered, undefined), + Deferred.await(latch.release), + ), + count("work"), + ), + ); + } + yield* step("take", { returns: Schema.Number, ...once }, count("take")); + if (payload.mode === "stop") return yield* stop("no need"); + if (payload.mode === "hold") yield* wait("go", { returns: Schema.String }); + }), + ), + workflow( + "flaky", + { + version: 1, + payload: Schema.Struct({ id: Schema.String, settle: Schema.optional(Schema.Boolean) }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + if (payload.settle === true) { + const tried = yield* step.try( + "settled", + { returns: Schema.Number }, + Effect.flatMap( + Ref.getAndUpdate(failures, (left) => Math.max(0, left - 1)), + (left) => (left > 0 ? Effect.fail("the dependency is down") : count("settled")), + ), + ); + return tried.outcome === "done" ? `settled ${tried.value}` : `gave up: ${tried.reason}`; + } + yield* step("before", { returns: Schema.Number, ...once }, count("before")); + const attempt = yield* step( + "flaky", + { returns: Schema.Number, ...once }, + Effect.flatMap( + Ref.getAndUpdate(failures, (left) => Math.max(0, left - 1)), + (left) => (left > 0 ? Effect.fail("the dependency is down") : count("flaky")), + ), + ); + return `done on attempt ${attempt}`; + }), + ), + /** Fails `bad` beside an open wait, as long as `failures` says. */ + workflow("sibling", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.map( + Effect.all( + [ + step( + "bad", + { returns: Schema.Number, ...once }, + Effect.andThen( + Effect.andThen(Deferred.await(latch.bad), count("bad tries")), + Effect.flatMap( + Ref.getAndUpdate(failures, (left) => Math.max(0, left - 1)), + (left) => (left > 0 ? Effect.fail("the dependency is down") : count("bad")), + ), + ), + ), + wait("sib", { returns: Schema.String }), + ], + { concurrency: 2 }, + ), + ([bad, sib]) => `${bad} ${Option.getOrElse(sib, () => "none")}`, + ), + ), + workflow( + "review", + { + version: 1, + payload: Schema.Struct({ change: Schema.String, timeout: Schema.optional(Schema.String) }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + yield* title(`review of ${payload.change}`); + yield* sleep("settle", "1 millis"); + const [a, b] = yield* Effect.all( + [ + step("check/a", { returns: Schema.Number, ...once }, count("check/a")), + step("check/b", { returns: Schema.Number, ...once }, count("check/b")), + ], + { concurrency: 2 }, + ); + const verdict = yield* wait("verdict", { + returns: Schema.Struct({ merge: Schema.Boolean }), + channel: payload.change, + ...(payload.timeout === undefined ? {} : { timeout: "0 millis" }), + }); + if (Option.isNone(verdict)) return yield* stop("nobody answered"); + yield* step("after", { returns: Schema.Number, ...once }, count("after")); + return `${a + b} checks, merge: ${verdict.value.merge}`; + }), + ), + /** Reads a number from text, which its JSON Schema cannot say: any string fits that. */ + workflow("reading", { version: 1, payload: Schema.Struct({}), returns: Schema.Number }, () => + Effect.map( + wait("count", { returns: Schema.FiniteFromString }), + Option.getOrElse(() => -1), + ), + ), + workflow( + "broken", + { + version: 1, + payload: Schema.Struct({ + how: Schema.Literals(["dies", "unstorable", "undefined", "nested"]), + }), + }, + (payload): Effect.Effect => { + if (payload.how === "dies") { + return step( + "dies", + { returns: Schema.Void, ...once }, + Effect.die(new Error("null dereference")), + ); + } + if (payload.how === "undefined") { + // No `returns`: read as JSON reads it, without the undefined fields. + return Effect.map( + step.try("void", { returns: Schema.Void, ...once }, Effect.void), + (r) => ({ r, id: undefined, list: [undefined] }), + ); + } + if (payload.how === "nested") { + return step( + "nested", + { returns: Schema.Json, ...once }, + Effect.succeed({ deep: [{ id: undefined }] } as unknown as Schema.Json), + ); + } + return Effect.asVoid( + step("unstorable", { returns: Schema.Int, ...once }, Effect.succeed(1.5)), + ); + }, + ), + workflow("twice", { version: 1, payload: Schema.Struct({}) }, () => + Effect.gen(function* () { + yield* step("same", { returns: Schema.Void, ...once }, Effect.void); + yield* step("same", { returns: Schema.Void, ...once }, Effect.void); + }), + ), + workflow("reserved", { version: 1, payload: Schema.Struct({}) }, () => + step("onEnd", { returns: Schema.Void, ...once }, Effect.void), + ), + ...[1, 2].map((version) => + workflow("versioned", { version, payload: Schema.Struct({}), returns: Schema.Number }, () => + Effect.succeed(version), + ), + ), + ]; +}; + +/** Write a change, ask a person whether to merge it, then land it in the writer's own thread. */ +const tally = store.entry("tally", Schema.Number); +const stored = [ + /** Counts itself in the store, with the first try of the step failing after it counted. */ + workflow( + "tally", + { + version: 1, + payload: Schema.Struct({ wrong: Schema.optional(Schema.Boolean) }), + returns: Schema.Number, + }, + (payload) => + payload.wrong === true + ? step( + "read", + { returns: Schema.Number, ...once }, + Effect.as(store.entry("tally", Schema.String).get, 0), + ) + : step( + "count", + { returns: Schema.Number, ...once }, + tally + .update((current) => Option.getOrElse(current, () => 0) + 1) + .pipe(Effect.map(Option.getOrElse(() => 0))), + ), + ), + /** Waits in line for a door that `opener` opens. */ + workflow( + "door", + { version: 1, payload: Schema.Struct({ door: Schema.String }), returns: Schema.String }, + (payload) => + Effect.map( + wait("open", { returns: Schema.String, channel: payload.door }), + Option.getOrElse(() => "never"), + ), + ), + workflow( + "opener", + { version: 1, payload: Schema.Struct({ door: Schema.String, fail: Schema.Boolean }) }, + (payload) => + step( + "open", + { returns: Schema.Void, retry: { times: 1 } }, + Effect.gen(function* () { + // Written and taken back together when the step fails after writing. + yield* store.transaction( + Effect.gen(function* () { + yield* store.entry(`doors/${payload.door}`, Schema.String).set("open"); + const tries = yield* store + .entry(`tries/${payload.door}`, Schema.Number) + .update((current) => Option.getOrElse(current, () => 0) + 1); + if (payload.fail && Option.contains(tries, 1)) return yield* Effect.fail("slipped"); + }), + ); + yield* signal({ workflow: "door", channel: payload.door }, "came in"); + }), + ), + ), + /** Opens two doors, fails, and on its second try opens the second and a third. */ + workflow( + "relay", + { version: 1, payload: Schema.Struct({ doors: Schema.Array(Schema.String) }) }, + (payload) => + step( + "pass", + { returns: Schema.Void, retry: { times: 1 } }, + Effect.gen(function* () { + const tries = yield* store + .entry("relay-tries", Schema.Number) + .update((current) => Option.getOrElse(current, () => 0) + 1); + const [a, b, c] = payload.doors; + const doors = Option.contains(tries, 1) ? [a!, b!] : [b!, c!]; + for (const door of doors) yield* signal({ workflow: "door", channel: door }, "came in"); + if (Option.contains(tries, 1)) return yield* Effect.fail("slipped"); + }), + ), + ), +]; + +const kid = workflow( + "kid", + { + version: 1, + payload: Schema.Struct({ mode: Schema.Literals(["finish", "stop", "hold"]) }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + if (payload.mode === "stop") return yield* stop("nothing to do"); + if (payload.mode === "hold") yield* wait("go", { returns: Schema.String }); + return "grown"; + }), +); +const family = [ + kid, + /** Runs a kid as part of itself and reports how the kid ended. */ + workflow( + "parent", + { + version: 1, + payload: Schema.Struct({ mode: Schema.Literals(["finish", "stop", "hold"]) }), + returns: Schema.String, + }, + (payload) => + Effect.map(invoke("kid", kid, payload), (ended) => + ended.outcome === "completed" ? ended.value : `${ended.outcome}: ${ended.reason}`, + ), + ), + /** Invokes under a name a step of its own already has, or by a name and not the definition. */ + workflow( + "clash", + { version: 1, payload: Schema.Struct({ byName: Schema.optional(Schema.Boolean) }) }, + (payload) => + payload.byName === true + ? // Files are not type-checked, so this is what one that passes a name does. + invoke("child", "kid" as unknown as typeof kid, { mode: "finish" }) + : Effect.andThen( + step("kid", { returns: Schema.Void, ...once }, Effect.void), + invoke("kid", kid, { mode: "finish" }), + ), + ), + /** Starts two kids and does not wait for them. */ + workflow( + "spawner", + { version: 1, payload: Schema.Struct({}), returns: Schema.Array(Schema.String) }, + () => + step( + "spawn", + { returns: Schema.Array(Schema.String), ...once }, + Effect.forEach(["one", "two"], (key) => + Effect.map(start(kid, { mode: "finish" }, { key: `spawned/${key}` }), (run) => run.runId), + ), + ), + ), + /** Two agents at once, the second with a minute to finish. */ + workflow("pair", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.map( + Effect.all( + [ + agent("left", { brief: "Left.", project: "p1" }), + agent("right", { brief: "Right.", project: "p1", timeout: "1 minute" }), + ], + { concurrency: 2 }, + ), + ([left, right]) => `${left.value} ${right.value}`, + ), + ), +]; + +const fix = workflow( + "fix", + { + version: 1, + payload: Schema.Struct({ + project: Schema.String, + environment: Schema.optional(Schema.String), + // Lands with a model of its own, which a continued thread cannot take. + reshape: Schema.optional(Schema.Boolean), + /** The address of the issue the fix is for. */ + issue: Schema.optional(Schema.String), + }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + const written = yield* agent("write", { + brief: "Write the fix.", + project: payload.project, + ...(payload.environment === undefined ? {} : { environment: payload.environment }), + ...(payload.issue === undefined + ? {} + : { issue: { project: payload.project, url: payload.issue } }), + returns: Schema.Struct({ + branch: Schema.String, + commits: Schema.optional(Schema.Number.check(Schema.isGreaterThan(0))), + }), + }); + const answer = yield* ask("merge", { + title: `Merge ${written.value.branch}?`, + choices: ["Merge", "Leave"], + data: { branch: written.value.branch }, + }); + if (Option.isNone(answer) || answer.value.choice !== "Merge") return yield* stop("left"); + const landed = yield* agent("land", { + brief: "Land it.", + thread: written.thread, + ...(payload.reshape === true ? { model: { instanceId: "codex", model: "gpt" } } : {}), + }); + return `${written.value.branch}: ${landed.value}`; + }), +); + +/** Waits at a gate with others, until whoever keeps it lets everyone through. */ +const gate = workflow( + "gate", + { version: 1, payload: Schema.Struct({ gate: Schema.String }), returns: Schema.String }, + (payload) => + Effect.map( + wait("through", { returns: Schema.String, channel: payload.gate }), + Option.getOrElse(() => "never"), + ), +); +const control = [ + gate, + /** Looks at the runs at the gates, lets one gate's through, or sends one run away. */ + workflow( + "keeper", + { + version: 1, + payload: Schema.Struct({ act: Schema.Literals(["look", "open", "dismiss", "leave"]) }), + returns: Schema.Json, + }, + (payload, run) => + step( + "act", + { returns: Schema.Json, ...once }, + Effect.gen(function* () { + const waiting = yield* runs({ workflow: gate, keyPrefix: "visit/" }); + if (payload.act === "open") return yield* signalAll({ channel: "north" }, "go on"); + if (payload.act === "leave") return yield* Effect.as(cancel(run.id, "done here"), null); + if (payload.act === "dismiss") { + const last = waiting.find((visit) => visit.key === "visit/3"); + return yield* Effect.as(cancel(last?.id ?? "", "the gate is closed"), null); + } + return waiting.map((visit) => `${visit.key} ${visit.status}`).toSorted(); + }), + ), + ), + /** Gives the job to a second agent when the first one fails, and says how it went. */ + workflow( + "fallback", + { + version: 1, + payload: Schema.Struct({ + project: Schema.String, + timeout: Schema.optional(Schema.Literal("1 minute")), + /** Says which thread the first agent's failure came back with. */ + thread: Schema.optional(Schema.Boolean), + }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + const output = Schema.Struct({ head: Schema.String }); + const first = yield* agent.try("first", { + brief: "Fix it.", + project: payload.project, + returns: output, + ...(payload.timeout === undefined ? {} : { timeout: payload.timeout }), + }); + if (first.outcome === "done") return first.value.head; + const second = yield* agent.try("second", { + brief: "Fix it.", + project: "p1", + returns: output, + }); + if (second.outcome === "failed") return yield* stop(second.reason); + const where = payload.thread === true ? ` in ${first.thread?.threadId ?? "no thread"}` : ""; + return `${second.value.head} after: ${first.reason}${where}`; + }), + ), +]; + +type Started = Parameters[0]; + +/** Agents the test plays: it sees each turn start and decides how that turn ends. */ +const fakeAgents = () => { + const turns = new Map< + string, + { started: Deferred.Deferred; ended: Deferred.Deferred } + >(); + const interrupted: Array<{ + readonly threadId: string; + readonly environment?: string | undefined; + readonly turnId?: string | undefined; + }> = []; + let threads = 0; + let refusals = 0; + const unreadable = new Set(); + const unanswered = new Set(); + const unstartable = new Set(); + const turn = (key: string) => { + const known = turns.get(key); + if (known !== undefined) return known; + const made = { + started: Deferred.makeUnsafe(), + ended: Deferred.makeUnsafe(), + }; + turns.set(key, made); + return made; + }; + return { + service: WorkflowAgents.of({ + start: (input) => + Effect.gen(function* () { + // The engine's own setting for reading integers must not reach what a step calls. + if (yield* SqlClient.SafeIntegers) { + return yield* new WorkflowAgentError({ reason: "SafeIntegers leaked into a step" }); + } + if (input.project === "nowhere" || unstartable.delete(input.key)) { + return yield* new WorkflowAgentError({ reason: "No project is registered there." }); + } + yield* Deferred.succeed(turn(input.key).started, input); + // As the threads do: the issue a thread is linked to is what its step touched. + if (input.issue !== undefined && "url" in input.issue) { + yield* noteReference({ + kind: "issue", + key: input.issue.url, + address: { url: input.issue.url }, + title: "", + }); + } + return { + threadId: input.thread ?? `thread-${++threads}`, + turnId: input.key, + ...(input.environment === undefined ? {} : { environment: input.environment }), + }; + }), + result: (started) => { + const once = (keys: Set) => + [...keys].some((key) => started.turnId.endsWith(`/${key}`) && keys.delete(key)); + if (once(unreadable)) { + return Effect.fail(new WorkflowAgentError({ reason: "the result could not be read" })); + } + return once(unanswered) ? Effect.never : Deferred.await(turn(started.turnId).ended); + }, + // Counted per try, so a retry of the same stop uses up a refusal too. + interrupt: (thread) => + Effect.gen(function* () { + if (yield* SqlClient.SafeIntegers) { + return yield* new WorkflowAgentError({ reason: "SafeIntegers leaked into a stop" }); + } + if (refusals-- > 0) return yield* new WorkflowAgentError({ reason: "the link is down" }); + interrupted.push(thread); + const ended = + thread.turnId !== undefined && turns.has(thread.turnId) + ? yield* Deferred.isDone(turns.get(thread.turnId)!.ended) + : false; + return ended ? ("ended" as const) : ("stopped" as const); + }), + }), + interrupted, + /** The next read of a turn with this key fails. */ + unreadableResult: (key: string) => { + unreadable.add(key); + }, + /** The next read of a turn with this key never answers, as one that is waited past. */ + unansweredResult: (key: string) => { + unanswered.add(key); + }, + /** The turn of `runId` with this key cannot be started. */ + unstartable: (runId: string, key: string) => { + unstartable.add(`${runId}/${key}`); + }, + /** Turns down the next `count` stops. */ + refuseStops: (count: number) => { + refusals = count; + }, + /** The turn of `runId` with this key, once it has been started. */ + started: (runId: string, key: string) => Deferred.await(turn(`${runId}/${key}`).started), + end: (runId: string, key: string, result: Partial) => + Deferred.succeed(turn(`${runId}/${key}`).ended, { + ending: "completed" as const, + detail: "", + reply: "", + ...result, + }), + }; +}; + +/** While set, `nightly` turns down every tick, so its start fails. */ +const ticks = { refused: false }; +const triggered = [ + workflow( + "nightly", + { + version: 1, + payload: Tick.check(Schema.makeFilter(() => !ticks.refused || "not now")), + returns: Schema.String, + triggers: [every("1 hour")], + }, + (tick) => Effect.succeed(tick.scheduledAt), + ), + workflow( + "morning", + { version: 1, payload: Tick, triggers: [daily("09:00", { weekdays: [1, 2, 3, 4, 5] })] }, + () => Effect.void, + ), + workflow( + "inbound", + { + version: 1, + payload: WebhookRequest, + triggers: [ + webhook("push", { + key: (request) => + request.headers["x-delivery"] ?? + (JSON.parse(request.body) as { readonly delivery?: string }).delivery, + }), + ], + }, + (request) => (request.body === "ping" ? skip("only a ping") : Effect.succeed(request.body)), + ), +]; + +const PROJECT = "/home/me/app"; +const triage = workflow( + "triage", + { + version: 1, + payload: Issue, + returns: Schema.String, + triggers: [issues.opened({ project: PROJECT, labels: ["bug"] })], + }, + Effect.fn(function* (issue) { + yield* step( + "thank", + { returns: Schema.Void }, + issues.comment(issue, `Looking at ${issue.title}.`), + ); + return issue.displayKey; + }), +); +const decodeIssue = Schema.decodeSync(Issue); +const land = workflow( + "land", + { version: 1, payload: Schema.Struct({ url: Schema.String }), returns: Schema.String }, + Effect.fn(function* (payload) { + const standing = yield* pullRequests.wait( + "checks", + { project: PROJECT, url: payload.url }, + { until: "checks", timeout: "1 hour" }, + ); + return Option.match(standing, { onNone: () => "gave up", onSome: (at) => at.checks }); + }), +); +const issueAt = (key: string, createdAt: string) => + decodeIssue({ + projectId: "project-1", + projectTitle: "app", + tracker: "github", + host: "github.com", + scope: "me/app", + key, + displayKey: `#${key}`, + title: `Issue ${key}`, + url: `https://github.com/me/app/issues/${key}`, + author: null, + state: { name: "open", category: "open" }, + createdAt, + updatedAt: createdAt, + closedAt: null, + assignees: [], + labels: [], + commentCount: 0, + }); +/** A tracker that lists what the test put in it and remembers what was said. */ +// The real trackers read the server's own tables, which do not decode under the engine's BigInts. +const asTheServerReads = (answer: () => A) => + Effect.flatMap(SqlClient.SafeIntegers, (bigInts) => + bigInts + ? Effect.fail(new WorkflowForgeError({ reason: "called with the engine's BigInts on" })) + : Effect.sync(answer), + ); + +const fakeForge = () => { + const open: Array = []; + const asked: Array[0]> = []; + const comments: Array = []; + const pullRequest = { + state: "open", + mergeability: "mergeable", + url: "https://github.com/me/app/pull/7", + checks: [{ name: "test", status: "pending", description: null, url: null }], + }; + return { + open, + asked, + comments, + pullRequest, + service: WorkflowForge.of({ + ...unavailable, + pullRequests: { + ...unavailable.pullRequests, + // Only what a wait looks at; the rest of a pull request is the host's business. + read: () => + asTheServerReads(() => structuredClone(pullRequest)).pipe( + Effect.tap((read) => + noteReference( + pullRequestReferenceOf( + { + projectId: ProjectId.make("project-1"), + host: "github.com", + repository: "me/app", + number: 7, + }, + { url: read.url, state: read.state }, + ), + ), + ), + Effect.map((read) => read as never), + ), + }, + issues: { + ...unavailable.issues, + list: (query) => + asTheServerReads(() => { + asked.push(query); + return open; + }), + comment: (issue, body) => + asTheServerReads( + () => void comments.push(`${"key" in issue ? issue.key : issue.url}: ${body}`), + ).pipe( + Effect.andThen("key" in issue ? noteReference(issueReference(issue)) : Effect.void), + ), + }, + }), + }; +}; + +const harness = Effect.fnUntraced(function* (store?: typeof WorkflowStore.layer) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflows-" }); + const database = NodeSqliteClient.layer({ filename: path.join(directory, "state.sqlite") }); + yield* Effect.provide(WorkflowsMigration, database); + const counts = yield* Ref.make>({}); + const failures = yield* Ref.make(0); + const latch: Latch = { + entered: yield* Deferred.make(), + release: yield* Deferred.make(), + cleaned: yield* Deferred.make(), + bad: yield* Deferred.make(), + }; + // One database file, so a second engine built from it is the server after a restart. + const agents = fakeAgents(); + const forge = fakeForge(); + const all = [ + triage, + land, + ...definitions(counts, failures, latch), + fix, + ...triggered, + ...stored, + ...family, + ...control, + ]; + const engineOf = (registered: typeof all) => + WorkflowEngine.layer(registered, store).pipe( + Layer.provide(Layer.succeed(WorkflowAgents, agents.service)), + Layer.provide(Layer.succeed(WorkflowForge, forge.service)), + Layer.provide(database), + Layer.provide(NodeCrypto.layer), + ); + // The engine polls its message store, backs off between retries and bounds its shutdown, all + // on the clock, so time runs for as long as a server is up, shutdown included. A test closes + // `clock` to hold time still until it has seen what it waits for. + const clock = yield* Latch.make(true); + /** With `registered`, a server whose files define only those. */ + const boot = (use: Effect.Effect, registered = all) => + Effect.raceFirst( + Effect.scoped(Effect.provide(use, engineOf(registered))), + Effect.forever(Effect.andThen(clock.await, TestClock.adjust("1 second"))), + ); + return { counts, failures, latch, boot, agents, forge, clock, database }; +}); + +/** The store the engine writes to, for a test to leave what a crash would have left. */ +const exposedStore = () => { + const made = Deferred.makeUnsafe(); + return { + layer: Layer.effect( + WorkflowStore.WorkflowStore, + Effect.tap(WorkflowStore.make, (store) => Deferred.succeed(made, store)), + ), + store: Deferred.await(made), + }; +}; + +/** The review workflow sleeps first, which is waiting too; this is its wait for a verdict. */ +const atVerdict = (run: WorkflowRun) => run.status === "waiting" && run.detail === "verdict"; +const status = + (...statuses: ReadonlyArray) => + (run: WorkflowRun) => + statuses.includes(run.status); + +it.effect( + "a failing step pauses its run, and resuming runs that step again and nothing before it", + () => + Effect.gen(function* () { + const { counts, failures, boot, database } = yield* harness(); + yield* Ref.set(failures, 2); + const runId = yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start("flaky", { id: "a" }, { idempotencyKey: "a" }); + const again = yield* workflows.start("flaky", { id: "a" }, { idempotencyKey: "a" }); + assert.equal(again.runId, runId); + + const paused = yield* workflows.waitFor(runId, status("paused")); + assert.include(paused.detail ?? "", "the dependency is down"); + assert.equal(paused.pauses, 1); + // It says when it tries again by itself, which is after it paused. + assert.isTrue(paused.resumesAt !== null && paused.resumesAt > paused.updatedAt); + + yield* workflows.resume(runId); + const pausedAgain = yield* workflows.waitFor(runId, (run) => run.pauses === 2); + assert.equal(pausedAgain.status, "paused"); + return runId; + }), + ); + + // The server restarts while the run is paused. Nothing retries it until it is resumed. + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + assert.equal((yield* workflows.get(runId)).run.status, "paused"); + yield* workflows.resume(runId); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "done on attempt 1"); + assert.equal(done.pauses, 0); + const { steps } = yield* workflows.get(runId); + assert.deepStrictEqual( + steps.map((step) => [step.name, step.status, step.attempts]), + [ + ["before", "completed", 1], + ["flaky", "completed", 3], + ], + ); + }), + ); + assert.deepStrictEqual(yield* Ref.get(counts), { before: 1, flaky: 1 }); + + // An hour after it ended its engine journal goes, and starting its key again is still that run. + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const journal = Effect.flatMap( + SqlClient.SqlClient, + (sql) => sql<{ readonly n: number | bigint }>` + SELECT COUNT(*) AS n FROM cluster_messages WHERE entity_id = ${runId} + `, + ).pipe( + Effect.map((rows) => Number(rows[0]?.n ?? 0)), + Effect.provide(database), + ); + assert.isAbove(yield* journal, 0); + yield* TestClock.adjust("2 hours"); + yield* workflows.sweep; + assert.equal(yield* journal, 0); + const again = yield* workflows.start("flaky", { id: "a" }, { idempotencyKey: "a" }); + assert.equal(again.runId, runId); + assert.equal((yield* workflows.get(runId)).run.status, "completed"); + }), + ); + assert.deepStrictEqual(yield* Ref.get(counts), { before: 1, flaky: 1 }); + + // `step.try` hands the failure to the workflow instead of pausing, and runs once by default. + yield* Ref.set(failures, 1); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "flaky", + { id: "b", settle: true }, + { idempotencyKey: "b" }, + ); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "gave up: the dependency is down"); + assert.equal(done.pauses, 0); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a signal to a paused run is kept for the resume and does not run the failed step", () => + Effect.gen(function* () { + const { counts, failures, latch, boot } = yield* harness(); + yield* Ref.set(failures, 2); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start("sibling", {}, { idempotencyKey: "sib" }); + yield* workflows.waitFor(runId, (run) => run.status === "waiting" && run.detail === "sib"); + yield* Deferred.succeed(latch.bad, undefined); + yield* workflows.waitFor(runId, status("paused")); + assert.equal( + yield* workflows.signal({ runId, wait: "sib" }, "x", { id: "sib-x" }), + "delivered", + ); + yield* workflows.resume(runId); + const again = yield* workflows.waitFor(runId, (run) => run.pauses === 2); + assert.equal(again.status, "paused"); + yield* workflows.resume(runId); + const done = yield* workflows.waitFor(runId, status("completed", "paused")); + assert.deepStrictEqual([done.status, done.result], ["completed", "1 x"]); + const bad = (yield* workflows.get(runId)).steps.find((step) => step.name === "bad"); + assert.equal(bad?.attempts, 3); + }), + ); + assert.deepStrictEqual(yield* Ref.get(counts), { "bad tries": 3, bad: 1 }); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a wait survives a restart, checks what it is signalled with, and steps run once", () => + Effect.gen(function* () { + const { counts, boot } = yield* harness(); + const runId = yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "review", + { change: "c1" }, + { idempotencyKey: "c1" }, + ); + const waiting = yield* workflows.waitFor(runId, atVerdict); + assert.equal(waiting.title, "review of c1"); + // The sleep before the wait is a step a person can see. + const slept = (yield* workflows.get(runId)).steps.find((step) => step.name === "settle"); + assert.deepStrictEqual([slept?.kind, slept?.status], ["sleep", "completed"]); + const wrong = yield* workflows + .signal({ runId, wait: "verdict" }, { merge: "yes" }, { id: "s0" }) + .pipe(Effect.flip); + assert.include(wrong.message, "merge"); + return runId; + }), + ); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // Addressed by key: the sender knows the change, not the run. + assert.equal( + yield* workflows.signal( + { workflow: "review", channel: "c1" }, + { merge: true }, + { id: "s1" }, + ), + "delivered", + ); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "2 checks, merge: true"); + }), + ); + assert.deepStrictEqual(yield* Ref.get(counts), { "check/a": 1, "check/b": 1, after: 1 }); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a signal its wait cannot read leaves the wait open for one it can", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start("reading", {}, { idempotencyKey: "t1" }); + yield* workflows.waitFor(runId, status("waiting")); + yield* workflows.signal({ runId, wait: "count" }, "many", { id: "t-many" }); + // Delivered straight or kept until the wait opens again: either way it is read. + yield* workflows.signal({ runId, wait: "count" }, "5", { id: "t-5" }); + const done = yield* workflows.waitFor(runId, status("completed", "paused")); + assert.deepStrictEqual([done.status, done.result], ["completed", 5]); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a signal sent before its wait opens is delivered when it does", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + assert.equal( + yield* workflows.signal( + { workflow: "review", channel: "c2" }, + { merge: false }, + { id: "s2" }, + ), + "buffered", + ); + const { runId } = yield* workflows.start( + "review", + { change: "c2" }, + { idempotencyKey: "c2" }, + ); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "2 checks, merge: false"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a signal buffered as its wait opens is still delivered to that wait", () => + Effect.gen(function* () { + const looked = yield* Deferred.make(); + const opened = yield* Deferred.make(); + const checked = yield* Deferred.make(); + // Holds the signal between finding no wait and buffering, while the wait opens and finds no mail. + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.gen(function* () { + const real = yield* WorkflowStore.make; + let first = true; + return WorkflowStore.WorkflowStore.of({ + ...real, + waitAt: (address) => + Effect.tap(real.waitAt(address), () => { + if (!("channel" in address) || address.channel !== "c9" || !first) return Effect.void; + first = false; + return Effect.andThen(Deferred.succeed(looked, undefined), Deferred.await(opened)); + }), + mailNext: (addresses, passed) => + Effect.tap(real.mailNext(addresses, passed), (mail) => + mail === undefined && !first ? Deferred.succeed(checked, undefined) : Effect.void, + ), + }); + }), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const sent = yield* Effect.forkChild( + workflows.signal({ workflow: "review", channel: "c9" }, { merge: true }, { id: "s9" }), + ); + yield* Deferred.await(looked); + const { runId } = yield* workflows.start( + "review", + { change: "c9" }, + { idempotencyKey: "c9" }, + ); + // Released once the open wait has looked for mail and found none. + yield* Deferred.await(checked); + yield* Deferred.succeed(opened, undefined); + assert.equal(yield* Fiber.join(sent), "delivered"); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "2 checks, merge: true"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a wait another signal claimed first wakes with that signal's value", () => + Effect.gen(function* () { + // A second signal claims the wait just before the early mail is handed to it. + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.gen(function* () { + const real = yield* WorkflowStore.make; + return WorkflowStore.WorkflowStore.of({ + ...real, + mailDeliver: (signalId, runId, name, woke) => + Effect.andThen( + real.waitSignalled(runId, name, { expired: false, value: { merge: true } }), + real.mailDeliver(signalId, runId, name, woke), + ), + }); + }), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + assert.equal( + yield* workflows.signal( + { workflow: "review", channel: "c8" }, + { merge: false }, + { id: "s8" }, + ), + "buffered", + ); + const { runId } = yield* workflows.start( + "review", + { change: "c8" }, + { idempotencyKey: "c8" }, + ); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "2 checks, merge: true"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a wait past its timeout wakes with nothing, and a workflow may stop on its own", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "review", + { change: "c3", timeout: "now" }, + { idempotencyKey: "c3" }, + ); + yield* workflows.waitFor(runId, atVerdict); + yield* workflows.sweep; + const stopped = yield* workflows.waitFor(runId, status("stopped")); + assert.equal(stopped.detail, "nobody answered"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a cancelled run ends, and two steps with one name pause their run", () => + Effect.gen(function* () { + // The start of `v3` is cut off once its row is written, before the engine has it. + const cutOff = new Set(["v3"]); + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.map(WorkflowStore.make, (real) => + WorkflowStore.WorkflowStore.of({ + ...real, + runStarted: (run) => + Effect.tap(real.runStarted(run), () => + cutOff.delete(run.idempotencyKey) ? Effect.die("the server stopped") : Effect.void, + ), + }), + ), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const waiting = yield* workflows.start( + "review", + { change: "c4" }, + { idempotencyKey: "c4" }, + ); + yield* workflows.waitFor(waiting.runId, atVerdict); + yield* workflows.cancel(waiting.runId, "not needed"); + const cancelled = (yield* workflows.get(waiting.runId)).run; + assert.equal(cancelled.status, "cancelled"); + assert.equal(cancelled.detail, "not needed"); + // A cancel with no reason gives none, rather than repeating that the run was cancelled. + const unexplained = yield* workflows.start( + "review", + { change: "c5" }, + { idempotencyKey: "c5" }, + ); + yield* workflows.waitFor(unexplained.runId, atVerdict); + yield* workflows.cancel(unexplained.runId); + assert.equal((yield* workflows.get(unexplained.runId)).run.detail, null); + // A signal for the wait it had is kept as mail, not delivered to a run that ended. + assert.equal( + yield* workflows.signal( + { runId: waiting.runId, wait: "verdict" }, + { merge: true }, + { id: "s4" }, + ), + "buffered", + ); + // A file written for the old `title(name, text)` is refused, not titled with the name. + assert.throws( + () => (title as (...args: ReadonlyArray) => unknown)("name", "Release v1"), + /takes only the text/, + ); + + const twice = yield* workflows.start("twice", {}, { idempotencyKey: "t1" }); + const paused = yield* workflows.waitFor(twice.runId, status("paused")); + assert.include(paused.detail ?? "", 'named "same"'); + // The cleanup step's name is taken by nothing else. + const reserved = yield* workflows.start("reserved", {}, { idempotencyKey: "r1" }); + const refusedName = yield* workflows.waitFor(reserved.runId, status("paused")); + assert.include(refusedName.detail ?? "", "cleanup step"); + + const missing = yield* workflows + .start("nothing", {}, { idempotencyKey: "n1" }) + .pipe(Effect.flip); + assert.equal(missing._tag, "WorkflowNotRegisteredError"); + // A version asked for by name is that version or nothing, never the latest instead. + const unknownVersion = yield* workflows + .start("twice", {}, { idempotencyKey: "t2", version: 2 }) + .pipe(Effect.flip); + assert.equal(unknownVersion.message, "Version 2 of workflow twice is not registered."); + const older = yield* workflows.start("versioned", {}, { idempotencyKey: "v1", version: 1 }); + const latest = yield* workflows.start("versioned", {}, { idempotencyKey: "v2" }); + assert.equal((yield* workflows.waitFor(older.runId, status("completed"))).result, 1); + assert.equal((yield* workflows.waitFor(latest.runId, status("completed"))).result, 2); + // A key is one run of the workflow, whichever version starts it again. + assert.deepStrictEqual( + yield* workflows.start("versioned", {}, { idempotencyKey: "v1" }), + older, + ); + // A start cut off between its row and the engine is executed by the next start. + const cut = yield* Effect.exit( + workflows.start("versioned", {}, { idempotencyKey: "v3", version: 1 }), + ); + assert.isTrue(Exit.isFailure(cut)); + const again = yield* workflows.start("versioned", {}, { idempotencyKey: "v3" }); + assert.equal((yield* workflows.waitFor(again.runId, status("completed"))).result, 1); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "an agent returns checked data, a person answers, and a later step continues the thread", + () => + Effect.gen(function* () { + let kept: WorkflowStore.WorkflowStore["Service"] | undefined; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.tap(WorkflowStore.make, (real) => Effect.sync(() => void (kept = real))), + ); + const { boot, agents } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "fix", + { project: "p1", issue: "https://github.com/me/app/issues/9" }, + { idempotencyKey: "f1" }, + ); + + const write = yield* agents.started(runId, "write/0"); + assert.equal(write.project, "p1"); + assert.equal(write.thread, undefined); + assert.deepStrictEqual( + [write.outputSchema?.required, write.outputSchema?.additionalProperties], + [["branch"], false], + ); + // The number's own check reaches the agent, without the text JSON spells Infinity in. + assert.deepStrictEqual( + (write.outputSchema?.properties as Record | undefined)?.commits, + { anyOf: [{ type: "number", exclusiveMinimum: 0 }, { type: "null" }] }, + ); + // It ended its turn without a result: the same thread is asked for it, not for the work. + yield* agents.end(runId, "write/0", { reply: "done" }); + const correction = yield* agents.started(runId, "write/0/correct/0"); + assert.equal(correction.thread, "thread-1"); + assert.include(correction.prompt, "without an accepted result"); + // What it then submitted does not fit, and it is told so, not that nothing came. + yield* agents.end(runId, "write/0/correct/0", { output: { branch: 1 } }); + const misfit = yield* agents.started(runId, "write/0/correct/1"); + assert.include(misfit.prompt, "The result you submitted does not fit: Expected string"); + yield* agents.end(runId, "write/0/correct/1", { + output: { branch: "fix/1" }, + reply: "Pushed fix/1.", + }); + + yield* workflows.waitFor(runId, (run) => run.detail === "merge"); + // A person reads what the agent said beside the data it returned. + const detail = yield* workflows.get(runId); + const written = detail.steps.find((step) => step.name === "write"); + assert.deepStrictEqual( + [written?.result, written?.said], + [{ branch: "fix/1" }, "Pushed fix/1."], + ); + // Asked three times on its issue's thread, the step touched the issue once. + assert.deepStrictEqual( + detail.references.map(({ key, steps, origin }) => ({ key, steps, origin })), + [{ key: "https://github.com/me/app/issues/9", steps: ["write"], origin: "step" }], + ); + const [question] = yield* workflows.questions; + // The agent whose work raised the question is one click from it. + assert.deepStrictEqual(question?.thread, { threadId: "thread-1", environmentId: null }); + assert.deepStrictEqual(question?.request, { + title: "Merge fix/1?", + choices: ["Merge", "Leave"], + data: { branch: "fix/1" }, + }); + const refused = yield* workflows + .signal({ runId, wait: "merge" }, { choice: "Maybe" }, { id: "a0" }) + .pipe(Effect.flip); + assert.include(refused.message, "merge waits for"); + // Clicked twice: one answer, and nothing kept to answer it again. + yield* Effect.all( + [ + workflows.answer(runId, "merge", { choice: "Merge" }), + workflows.answer(runId, "merge", { choice: "Merge" }), + ], + { concurrency: "unbounded" }, + ); + yield* workflows.answer(runId, "merge", { choice: "Leave" }); + assert.isUndefined(yield* kept!.mailNext([{ runId, wait: "merge" }])); + + const land = yield* agents.started(runId, "land/0"); + assert.equal(land.thread, "thread-1"); + assert.equal(land.outputSchema, undefined); + yield* agents.end(runId, "land/0", { reply: "merged as abc123" }); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "fix/1: merged as abc123"); + assert.deepStrictEqual(yield* workflows.questions, []); + // Each step keeps what it produced, for a person reading the run afterwards. + const { steps } = yield* workflows.get(runId); + assert.deepStrictEqual( + steps.map((step) => [step.name, step.result]), + [ + ["write", { branch: "fix/1" }], + ["merge", { choice: "Merge" }], + ["land", "merged as abc123"], + ], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "an agent whose turn dies is tried on a new thread, then its run pauses until resumed", + () => + Effect.gen(function* () { + const exposed = exposedStore(); + const { boot, agents } = yield* harness(exposed.layer); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "fix", + { project: "p1" }, + { idempotencyKey: "f2" }, + ); + yield* agents.started(runId, "write/0"); + // Its turn is stopped before the next one starts; a stop that fails pauses the run. + agents.refuseStops(3); + yield* agents.end(runId, "write/0", { ending: "failed", detail: "failed" }); + const refused = yield* workflows.waitFor(runId, status("paused")); + assert.include(refused.detail ?? "", "the link is down"); + // A stop that did not get through is tried again by itself. + assert.isNotNull(refused.resumesAt); + assert.equal(agents.interrupted.length, 0); + yield* agents.started(runId, "write/1"); + assert.equal(agents.interrupted.length, 1); + yield* agents.end(runId, "write/1", { ending: "failed", detail: "provider error" }); + + const paused = yield* workflows.waitFor(runId, status("paused")); + assert.include(paused.detail ?? "", "provider error"); + // An agent that gave up starts its whole job again on resume: a person decides that. + assert.isNull(paused.resumesAt); + // A resume cut off before it reached the engine is put back by the sweep, still held. + yield* (yield* exposed.store).runUnpaused(runId); + const putBack = yield* workflows.waitFor(runId, status("paused")); + assert.deepStrictEqual([putBack.status, putBack.resumesAt], ["paused", null]); + yield* workflows.resume(runId); + yield* agents.started(runId, "write/2"); + yield* agents.end(runId, "write/2", { output: { branch: "fix/2" } }); + yield* workflows.waitFor(runId, (run) => run.detail === "merge"); + yield* workflows.signal({ runId, wait: "merge" }, { choice: "Leave" }, { id: "a2" }); + const stopped = yield* workflows.waitFor(runId, status("stopped")); + assert.equal(stopped.detail, "left"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "a step that dies, or whose result cannot be stored, pauses its run like any failure", + () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const dies = yield* workflows.start("broken", { how: "dies" }, { idempotencyKey: "b1" }); + const died = yield* workflows.waitFor(dies.runId, status("paused")); + assert.include(died.detail ?? "", "null dereference"); + const unstorable = yield* workflows.start( + "broken", + { how: "unstorable" }, + { idempotencyKey: "b2" }, + ); + const refused = yield* workflows.waitFor(unstorable.runId, status("paused")); + assert.include(refused.detail ?? "", "unstorable"); + assert.equal((yield* workflows.get(unstorable.runId)).steps[0]?.status, "failed"); + // Never marked done on the way, so each try counts as one more pause. + yield* workflows.waitFor(unstorable.runId, (run) => run.pauses >= 2); + + const loose = yield* workflows.start( + "broken", + { how: "undefined" }, + { idempotencyKey: "b3" }, + ); + const done = yield* workflows.waitFor(loose.runId, status("completed", "paused")); + assert.deepStrictEqual( + [done.status, done.result], + ["completed", { r: { outcome: "done" }, list: [null] }], + ); + const nested = yield* workflows.start( + "broken", + { how: "nested" }, + { idempotencyKey: "b4" }, + ); + const where = yield* workflows.waitFor(nested.runId, status("paused")); + assert.include(where.detail ?? "", "the result.deep[0].id is undefined"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "signals: one per wait, a retried id is not a second one, and early mail a wait cannot read is kept", + () => + Effect.gen(function* () { + let kept: WorkflowStore.WorkflowStore["Service"] | undefined; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.tap(WorkflowStore.make, (real) => Effect.sync(() => void (kept = real))), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const key = { workflow: "review", channel: "k1" }; + // Two signals before any run waits: the first is not what the wait expects. + yield* workflows.signal(key, { merge: "x" }, { id: "bad" }); + yield* workflows.signal(key, { merge: true }, { id: "good" }); + const first = yield* workflows.start( + "review", + { change: "k1" }, + { idempotencyKey: "k1a" }, + ); + const done = yield* workflows.waitFor(first.runId, status("completed")); + assert.equal(done.result, "2 checks, merge: true"); + // Left for whichever wait on the channel reads it, another version's perhaps. + assert.equal((yield* kept!.mailNext([key]))?.signalId, "bad"); + // The sender retries the signal that was already delivered from the mail. + assert.equal(yield* workflows.signal(key, { merge: true }, { id: "good" }), "delivered"); + + const second = yield* workflows.start( + "review", + { change: "k1" }, + { idempotencyKey: "k1b" }, + ); + const third = yield* workflows.start( + "review", + { change: "k1" }, + { idempotencyKey: "k1c" }, + ); + yield* workflows.waitFor(second.runId, atVerdict); + yield* workflows.waitFor(third.runId, atVerdict); + // Nothing was left over for them, and each new signal wakes one run. + assert.equal(yield* workflows.signal(key, { merge: false }, { id: "s1" }), "delivered"); + assert.equal(yield* workflows.signal(key, { merge: true }, { id: "s2" }), "delivered"); + const results = [ + (yield* workflows.waitFor(second.runId, status("completed"))).result, + (yield* workflows.waitFor(third.runId, status("completed"))).result, + ]; + // Each new signal woke one of the two runs, whichever opened its wait first. + assert.sameMembers( + results.map((result) => String(result).split(", ")[1]), + ["merge: false", "merge: true"], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("signals that race for the waits on one channel each wake one of them", () => + Effect.gen(function* () { + // All three senders look before any claims, and the two that lose look again together. + const barriers = [ + { at: 3, all: Deferred.makeUnsafe() }, + { at: 5, all: Deferred.makeUnsafe() }, + ]; + let looked = 0; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.map(WorkflowStore.make, (real) => + WorkflowStore.WorkflowStore.of({ + ...real, + waitAt: (address) => + Effect.tap(real.waitAt(address), () => { + if (!("channel" in address) || address.channel !== "k3") return Effect.void; + const at = ++looked; + const barrier = barriers.find((candidate) => at <= candidate.at); + if (barrier === undefined) return Effect.void; + return at === barrier.at + ? Deferred.succeed(barrier.all, undefined) + : Deferred.await(barrier.all); + }), + }), + ), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const runs = yield* Effect.forEach(["k3a", "k3b", "k3c"], (key) => + workflows.start("review", { change: "k3" }, { idempotencyKey: key }), + ); + yield* Effect.forEach(runs, (run) => workflows.waitFor(run.runId, atVerdict)); + const sent = yield* Effect.forEach( + ["r1", "r2", "r3"], + (id) => workflows.signal({ workflow: "review", channel: "k3" }, { merge: true }, { id }), + { concurrency: "unbounded" }, + ); + assert.deepStrictEqual(sent, ["delivered", "delivered", "delivered"]); + for (const run of runs) yield* workflows.waitFor(run.runId, status("completed")); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "onEnd runs once however the run ends, and a cancelled run's is tried until it works", + () => + Effect.gen(function* () { + const { boot, counts, failures, latch, clock } = yield* harness(); + const ended = (step: { readonly name: string }) => step.name === "onEnd"; + const heldId = yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const finished = yield* workflows.start( + "owned", + { mode: "finish" }, + { idempotencyKey: "f" }, + ); + const stopped = yield* workflows.start( + "owned", + { mode: "stop" }, + { idempotencyKey: "s" }, + ); + yield* workflows.waitFor(finished.runId, status("completed")); + yield* workflows.waitFor(stopped.runId, status("stopped")); + + const held = yield* workflows.start("owned", { mode: "hold" }, { idempotencyKey: "h" }); + yield* workflows.waitFor(held.runId, status("waiting")); + yield* Ref.set(failures, 1); + // Time stands still from here, so no sweep tries again before the first try is read. + yield* clock.close; + yield* workflows.cancel(held.runId, "not needed"); + // The first try failed, which is on the run for a person to see. + const firstTry = (yield* workflows.get(held.runId)).steps.find(ended); + assert.deepStrictEqual( + [firstTry?.status, firstTry?.detail], + ["failed", "the machine would not go"], + ); + // The next try rests a while however often the sweep looks, and needs its version. + yield* workflows.sweep; + const rested = (yield* workflows.get(held.runId)).steps.find(ended); + assert.deepStrictEqual([rested?.status, rested?.attempts], ["failed", 1]); + assert.deepInclude(yield* workflows.unfinished, { workflow: "owned", version: 1 }); + yield* clock.open; + return held.runId; + }), + ); + // Days with the server down do not end the tries. + yield* TestClock.adjust("2 days"); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The server's own sweep makes the next try. + const { steps } = Option.getOrThrow( + yield* workflows.watch.pipe( + Stream.mapEffect(() => workflows.get(heldId)), + Stream.filter((run) => + run.steps.some((step) => ended(step) && step.status === "completed"), + ), + Stream.runHead, + ), + ); + assert.deepStrictEqual( + steps.map((step) => [step.name, step.status, step.attempts]), + [ + ["take", "completed", 1], + ["go", "failed", 1], + ["onEnd", "completed", 2], + ], + ); + assert.notDeepInclude(yield* workflows.unfinished, { workflow: "owned", version: 1 }); + // Nothing is left to do, so another look changes nothing. + yield* workflows.sweep; + // A cleanup that works the first time is told why the run was cancelled, too. + const second = yield* workflows.start( + "owned", + { mode: "hold" }, + { idempotencyKey: "h2" }, + ); + yield* workflows.waitFor(second.runId, status("waiting")); + yield* workflows.cancel(second.runId, "changed my mind"); + const all = yield* Ref.get(counts); + assert.deepStrictEqual( + Object.entries(all).filter(([name]) => name.startsWith("end:")), + [ + ["end:finish:completed:", 1], + ["end:stop:stopped:no need", 1], + ["end:hold:cancelled:not needed", 1], + ["end:hold:cancelled:changed my mind", 1], + ], + ); + + // Cancelled with a step still going: the cleanup waits for that step to finish. + const busy = yield* workflows.start("owned", { mode: "busy" }, { idempotencyKey: "b" }); + yield* Deferred.await(latch.entered); + // The cancel itself comes back after a while, the step still going. + yield* workflows.cancel(busy.runId, "not needed"); + yield* Deferred.succeed(latch.release, undefined); + yield* Deferred.await(latch.cleaned); + assert.equal((yield* Ref.get(counts))["end:busy:after work"], 1); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "the store is shared by runs, survives a restart, and a failed transaction writes nothing", + () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const runs = yield* Effect.forEach(["a", "b", "c"], (key) => + workflows.start("tally", {}, { idempotencyKey: key }), + ); + const counted = yield* Effect.forEach(runs, (run) => + workflows.waitFor(run.runId, status("completed")), + ); + assert.sameMembers( + counted.map((run) => run.result), + [1, 2, 3], + ); + }), + ); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const next = yield* workflows.start("tally", {}, { idempotencyKey: "d" }); + assert.equal((yield* workflows.waitFor(next.runId, status("completed"))).result, 4); + // A key read with another schema is the step's failure, with the key in the reason. + const wrong = yield* workflows.start("tally", { wrong: true }, { idempotencyKey: "w" }); + const paused = yield* workflows.waitFor(wrong.runId, status("paused")); + assert.include(paused.detail ?? "", "The stored value at tally does not fit its schema"); + + // The first try fails inside the transaction, so the door it opened is not there, and + // the try count it raised is 1 again on the second try, which is the one that signals. + const waiting = yield* workflows.start("door", { door: "east" }, { idempotencyKey: "e" }); + yield* workflows.waitFor(waiting.runId, status("waiting")); + const opener = yield* workflows.start( + "opener", + { door: "east", fail: true }, + { idempotencyKey: "o" }, + ); + yield* workflows.waitFor(opener.runId, status("paused")); + assert.equal((yield* workflows.get(waiting.runId)).run.status, "waiting"); + const clean = yield* workflows.start( + "opener", + { door: "east", fail: false }, + { idempotencyKey: "o2" }, + ); + yield* workflows.waitFor(clean.runId, status("completed")); + assert.equal( + (yield* workflows.waitFor(waiting.runId, status("completed"))).result, + "came in", + ); + + // A retry sends again what the first try sent, and what it sends anew is new. + const doors = ["ra", "rb", "rc"]; + const held = yield* Effect.forEach(doors, (door) => + workflows.start("door", { door }, { idempotencyKey: door }), + ); + yield* Effect.forEach(held, (run) => workflows.waitFor(run.runId, status("waiting"))); + const relay = yield* workflows.start("relay", { doors }, { idempotencyKey: "relay" }); + yield* workflows.waitFor(relay.runId, status("completed")); + // Each try is an attempt, though both were one run of the step. + assert.equal((yield* workflows.get(relay.runId)).steps[0]?.attempts, 2); + assert.equal( + yield* workflows.signal({ workflow: "door", channel: "rc" }, "late", { id: "rc-late" }), + "buffered", + ); + const opened = yield* Effect.forEach(held, (run) => + workflows.waitFor(run.runId, status("completed")), + ); + assert.deepStrictEqual( + opened.map((run) => run.result), + ["came in", "came in", "came in"], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("an invoked run reports how it ended, and cancelling the parent cancels it", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The kid of a parent that waits on it, once the kid itself waits. + const heldKid = Effect.gen(function* () { + const kid = (yield* workflows.list({})).find( + (run) => + run.workflow === "kid" && (run.status === "running" || run.status === "waiting"), + ); + return yield* workflows.waitFor(kid!.runId, status("waiting")); + }); + const finished = yield* workflows.start( + "parent", + { mode: "finish" }, + { idempotencyKey: "f" }, + ); + const stopped = yield* workflows.start("parent", { mode: "stop" }, { idempotencyKey: "s" }); + assert.equal( + (yield* workflows.waitFor(finished.runId, status("completed"))).result, + "grown", + ); + assert.equal( + (yield* workflows.waitFor(stopped.runId, status("completed"))).result, + "stopped: nothing to do", + ); + + const held = yield* workflows.start("parent", { mode: "hold" }, { idempotencyKey: "h" }); + yield* workflows.waitFor(held.runId, (run) => run.detail === "kid"); + const child = yield* heldKid; + yield* workflows.cancel(held.runId, "not needed"); + assert.equal((yield* workflows.get(child.runId)).run.status, "cancelled"); + + // A kid cancelled by itself is an outcome its parent hears, not a failure. + const second = yield* workflows.start("parent", { mode: "hold" }, { idempotencyKey: "h2" }); + yield* workflows.waitFor(second.runId, (run) => run.detail === "kid"); + const lone = yield* heldKid; + yield* workflows.cancel(lone.runId, "changed my mind"); + assert.equal( + (yield* workflows.waitFor(second.runId, status("completed"))).result, + "cancelled: changed my mind", + ); + + const spawner = yield* workflows.start("spawner", {}, { idempotencyKey: "sp" }); + const spawned = (yield* workflows.waitFor(spawner.runId, status("completed"))) + .result as ReadonlyArray; + assert.equal(spawned.length, 2); + for (const runId of spawned) { + assert.equal((yield* workflows.waitFor(runId, status("completed"))).result, "grown"); + } + + // A name taken twice pauses the run before the kid it names is started. + const clash = yield* workflows.start("clash", {}, { idempotencyKey: "c" }); + assert.include( + (yield* workflows.waitFor(clash.runId, status("paused"))).detail ?? "", + 'named "kid"', + ); + assert.deepStrictEqual( + (yield* workflows.list()).filter((run) => run.parentRunId === clash.runId), + [], + ); + const byName = yield* workflows.start("clash", { byName: true }, { idempotencyKey: "n" }); + assert.include( + (yield* workflows.waitFor(byName.runId, status("paused"))).detail ?? "", + "invoke takes the workflow definition, not its name", + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a cancel cut off midway still tells the run that invoked it", () => + Effect.gen(function* () { + // The cancel is cut off where it stops the run's steps, as a client that went away would. + const reached = yield* Deferred.make(); + let first = true; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.map(WorkflowStore.make, (real) => + WorkflowStore.WorkflowStore.of({ + ...real, + stepsCancelled: (runId, except) => { + if (!first) return real.stepsCancelled(runId, except); + first = false; + return Effect.andThen(Deferred.succeed(reached, undefined), Effect.never); + }, + }), + ), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const parent = yield* workflows.start("parent", { mode: "hold" }, { idempotencyKey: "h" }); + yield* workflows.waitFor(parent.runId, (run) => run.detail === "kid"); + const kid = (yield* workflows.list({})).find((run) => run.workflow === "kid"); + yield* workflows.waitFor(kid!.runId, status("waiting")); + const cancelling = yield* Effect.forkChild(workflows.cancel(kid!.runId, "changed my mind")); + yield* Deferred.await(reached); + yield* Fiber.interrupt(cancelling); + assert.equal( + (yield* workflows.waitFor(parent.runId, status("completed"))).result, + "cancelled: changed my mind", + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("two agents run side by side, and one past its time limit is stopped", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const run = yield* workflows.start("pair", {}, { idempotencyKey: "p" }); + // Both have started before either has ended. + yield* agents.started(run.runId, "left/0"); + yield* agents.started(run.runId, "right/0"); + yield* agents.end(run.runId, "left/0", { reply: "done" }); + // The right one never answers. Its minute passes, and a stop that cannot get through + // pauses the run without giving the turn up, so the next try stops it. + agents.refuseStops(3); + const refused = yield* workflows.waitFor(run.runId, status("paused")); + assert.include(refused.detail ?? "", "the link is down"); + assert.equal(agents.interrupted.length, 0); + const paused = yield* workflows.waitFor( + run.runId, + (current) => current.status === "paused" && current.detail !== refused.detail, + ); + assert.include(paused.detail ?? "", "it was not done after 1m"); + assert.equal(agents.interrupted.length, 1); + const { steps } = yield* workflows.get(run.runId); + assert.deepStrictEqual(steps.map((step) => [step.name, step.status]).toSorted(), [ + ["left", "completed"], + ["right", "failed"], + ]); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a continued thread keeps how it started", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const run = yield* workflows.start( + "fix", + { project: "p1", reshape: true }, + { idempotencyKey: "r1" }, + ); + yield* agents.started(run.runId, "write/0"); + yield* agents.end(run.runId, "write/0", { output: { branch: "fix/1" } }); + yield* workflows.waitFor(run.runId, (current) => current.detail === "merge"); + yield* workflows.signal( + { runId: run.runId, wait: "merge" }, + { choice: "Merge" }, + { id: "m" }, + ); + const paused = yield* workflows.waitFor(run.runId, status("paused")); + assert.include(paused.detail ?? "", "Drop `model`"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("an agent step in a linked environment keeps its thread there", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const run = yield* workflows.start( + "fix", + { project: "/work/app", environment: "env-b" }, + { idempotencyKey: "e1" }, + ); + const write = yield* agents.started(run.runId, "write/0"); + assert.equal(write.environment, "env-b"); + yield* agents.end(run.runId, "write/0", { output: { branch: "fix/1" } }); + yield* workflows.waitFor(run.runId, status("waiting")); + yield* workflows.signal( + { runId: run.runId, wait: "merge" }, + { choice: "Merge" }, + { id: "m1" }, + ); + + // The step that continues the thread names no environment: the thread carries it. + const land = yield* agents.started(run.runId, "land/0"); + assert.equal(land.environment, "env-b"); + assert.equal(land.thread, "thread-1"); + yield* workflows.waitFor(run.runId, (current) => current.detail === "agent land"); + const { steps } = yield* workflows.get(run.runId); + assert.deepStrictEqual( + steps.filter((step) => step.kind === "agent").map((step) => step.environmentId), + ["env-b", "env-b"], + ); + yield* workflows.cancel(run.runId, "not needed"); + // Only the step's own turn: someone else's turn on that thread is left alone. + assert.deepStrictEqual(agents.interrupted, [ + { threadId: "thread-1", environment: "env-b", turnId: `${run.runId}/land/0` }, + ]); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("cancelling a run stops its agent, and a turn a person stopped is not tried again", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const cancelled = yield* workflows.start( + "fix", + { project: "p1" }, + { idempotencyKey: "x1" }, + ); + yield* agents.started(cancelled.runId, "write/0"); + yield* workflows.waitFor(cancelled.runId, (run) => run.detail === "agent write"); + const { steps } = yield* workflows.get(cancelled.runId); + yield* workflows.cancel(cancelled.runId, "not needed"); + assert.deepStrictEqual(agents.interrupted, [ + { threadId: steps[0]?.threadId ?? "no thread", turnId: `${cancelled.runId}/write/0` }, + ]); + + const stopped = yield* workflows.start("fix", { project: "p1" }, { idempotencyKey: "x2" }); + yield* agents.started(stopped.runId, "write/0"); + yield* agents.end(stopped.runId, "write/0", { ending: "stopped", detail: "interrupted" }); + const paused = yield* workflows.waitFor(stopped.runId, status("paused")); + assert.include(paused.detail ?? "", "stopped"); + // Resuming is the person saying go on: the next round starts. + yield* workflows.resume(stopped.runId); + yield* agents.started(stopped.runId, "write/1"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a watcher is sent the runs again when one changes", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const first = Option.getOrThrow(yield* Stream.runHead(workflows.watch)); + assert.deepStrictEqual([first.runs, first.questions], [[], []]); + // What exists is listed before anything has run, with what starts it. + assert.deepInclude(first.workflows, { + name: "inbound", + version: 1, + triggers: ["webhook push"], + }); + const { runId } = yield* workflows.start( + "review", + { change: "c9", timeout: "1 hour" }, + { idempotencyKey: "c9" }, + ); + const seen = yield* workflows.watch.pipe( + Stream.filter((snapshot) => snapshot.runs.some((run) => run.status === "waiting")), + Stream.runHead, + ); + assert.deepStrictEqual( + Option.getOrThrow(seen).runs.map((run) => run.runId), + [runId], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "a schedule starts one run when it is due, and one for all the times a restart missed", + () => + Effect.gen(function* () { + const { boot } = yield* harness(); + const nightly = (workflows: Workflows.Workflows["Service"]) => + Effect.map(workflows.list(), (runs) => runs.filter((run) => run.workflow === "nightly")); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The first look only notes when it is next due. + yield* workflows.sweep; + assert.deepStrictEqual(yield* nightly(workflows), []); + // A start that fails is tried again, not passed over for the next time it is due. + ticks.refused = true; + yield* TestClock.adjust("61 minutes"); + yield* workflows.sweep; + assert.deepStrictEqual(yield* nightly(workflows), []); + ticks.refused = false; + yield* workflows.sweep; + yield* workflows.sweep; + const [run] = yield* nightly(workflows); + assert.equal((yield* nightly(workflows)).length, 1); + const done = yield* workflows.waitFor(run!.runId, status("completed")); + assert.match(String(done.result), /^1970-01-01T01:/); + }), + ); + yield* TestClock.adjust("3 hours"); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + yield* workflows.sweep; + yield* workflows.sweep; + assert.equal((yield* nightly(workflows)).length, 2); + }), + ); + // Taken out of the file and put back long after it was due: due one interval from then. + const others = triggered.filter((definition) => definition.name !== "nightly"); + yield* boot( + Effect.flatMap(Workflows.Workflows, (workflows) => workflows.sweep), + others, + ); + yield* TestClock.adjust("3 hours"); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + yield* workflows.sweep; + yield* workflows.sweep; + assert.equal((yield* nightly(workflows)).length, 2); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("an issue opened after the workflow loaded starts one run, which can comment on it", () => + Effect.gen(function* () { + const starts: Array = []; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.map(WorkflowStore.make, (real) => + WorkflowStore.WorkflowStore.of({ + ...real, + runStarted: (run) => + Effect.andThen( + Effect.sync(() => starts.push(run.idempotencyKey)), + real.runStarted(run), + ), + }), + ), + ); + const { boot, forge } = yield* harness(store); + const triaged = (workflows: Workflows.Workflows["Service"]) => + Effect.map(workflows.list(), (runs) => runs.filter((run) => run.workflow === "triage")); + forge.open.push(issueAt("1", "1969-12-31T23:00:00.000Z")); + // Before the mark too, written the way some hosts write a time. + forge.open.push(issueAt("3", "1970-01-01T00:30:00+01:00")); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The first look only notes the time: what was there already starts nothing. + yield* workflows.sweep; + yield* TestClock.adjust("2 minutes"); + // One the workflow turns down comes first, and does not hold back the one after it. + forge.open.push({ ...issueAt("bad", "1970-01-01T00:00:30.000Z"), title: 5 } as never); + forge.open.push(issueAt("2", "1970-01-01T00:01:00.000Z")); + yield* workflows.sweep; + yield* TestClock.adjust("2 minutes"); + yield* workflows.sweep; + const [run, ...others] = yield* triaged(workflows); + assert.deepStrictEqual(others, []); + const done = yield* workflows.waitFor(run!.runId, status("completed")); + assert.equal(done.result, "#2"); + assert.deepStrictEqual(forge.comments, ["2: Looking at Issue 2."]); + // The issue that started the run is the one its step commented on. + assert.deepStrictEqual( + (yield* workflows.get(run!.runId)).references.map( + ({ kind, title, state, steps, origin }) => ({ kind, title, state, steps, origin }), + ), + [{ kind: "issue", title: "Issue 2", state: "open", steps: ["thank"], origin: "trigger" }], + ); + // A later look still lists it, and leaves the run it has alone. + const before = starts.length; + yield* TestClock.adjust("2 minutes"); + yield* workflows.sweep; + assert.deepStrictEqual(starts.slice(before), []); + assert.deepStrictEqual(forge.asked.at(-1), { + project: PROJECT, + state: "all", + sort: "created", + limit: 100, + labels: ["bug"], + query: undefined, + }); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a wait on a pull request ends when its checks have, and says how", () => + Effect.gen(function* () { + const { boot, forge } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "land", + { url: forge.pullRequest.url }, + { idempotencyKey: "pr-7" }, + ); + yield* workflows.waitFor(runId, status("waiting")); + yield* workflows.sweep; + assert.equal((yield* workflows.waitFor(runId, () => true)).status, "waiting"); + // Not a question for anyone: nothing waits on a person. + assert.deepStrictEqual(yield* workflows.questions, []); + forge.pullRequest.checks[0]!.status = "success"; + yield* TestClock.adjust("2 minutes"); + yield* workflows.sweep; + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "passing"); + // Each look kept it on the wait's step, and the replay after the wake added nothing. + assert.deepStrictEqual( + (yield* workflows.get(runId)).references.map(({ kind, steps, state }) => ({ + kind, + steps, + state, + })), + [{ kind: "pullRequest", steps: ["checks"], state: "open" }], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a step or sleep with an option it cannot read says which and what it takes", () => + Effect.gen(function* () { + assert.throws( + () => + step( + "push", + { returns: Schema.Void, retry: { times: 2, shedule: 1 } as never }, + Effect.void, + ), + 'step("push")\'s retry does not take `shedule`', + ); + const slept = yield* Effect.exit(sleep("z", "soon" as never) as unknown as Effect.Effect); + assert.include( + String(Exit.isFailure(slept) ? Cause.squash(slept.cause) : ""), + 'sleep("z") cannot read "soon" as a duration. Write one such as "5 minutes".', + ); + }), +); + +it("hooks of different workflows never share an id", () => { + assert.notEqual(Workflows.hookId("a.b", "c"), Workflows.hookId("a", "b.c")); + assert.equal(Workflows.hookId("inbound", "push"), "wf-inbound.push"); +}); + +it.effect("a request to a hook starts a run, its retry is the same run, and a bad token none", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + const request = (body: string, delivery: string) => ({ + method: "POST", + headers: { "x-delivery": delivery }, + query: "", + body, + }); + const token = yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const [hook] = yield* workflows.hooks; + assert.equal(hook?.workflow, "inbound"); + const [hookId, token] = hook!.path.split("/").slice(-2).map(decodeURIComponent); + const deliver = (body: string, delivery: string, withToken = token!) => + workflows.deliver({ + hookId: hookId!, + token: withToken, + request: request(body, delivery), + }); + + assert.isTrue(Option.isNone(yield* deliver("hello", "d1", "not the token"))); + const first = Option.getOrThrow(yield* deliver("hello", "d1")); + assert.deepStrictEqual(Option.getOrThrow(yield* deliver("hello", "d1")), first); + const done = yield* workflows.waitFor(first.runId, status("completed")); + assert.equal(done.result, "hello"); + + const ping = Option.getOrThrow(yield* deliver("ping", "d2")); + const skipped = yield* workflows.waitFor(ping.runId, status("skipped")); + assert.equal(skipped.detail, "only a ping"); + + const send = (headers: Record, body: string) => + workflows.deliver({ + hookId: hookId!, + token: token!, + request: { method: "POST", headers, query: "", body }, + }); + // With no key from the workflow, the id the sender keeps on its retry makes it one run. + const github = { "x-github-delivery": "g1" }; + const sent = Option.getOrThrow(yield* send(github, "{}")); + assert.deepStrictEqual(Option.getOrThrow(yield* send(github, "{}")), sent); + // A key the workflow cannot read off the request turns the request down. + const unreadable = yield* send({}, "not json").pipe(Effect.flip); + assert.equal(unreadable._tag, "WorkflowInputError"); + return token; + }), + ); + // The URL a sender was given still works after a restart. + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + assert.isTrue((yield* workflows.hooks)[0]?.path.endsWith(`/${token}`)); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a step finds runs by their key, wakes everyone at a key, and cancels another run", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const visit = (key: string, at: string) => + workflows.start("gate", { gate: at }, { idempotencyKey: key }); + const keeper = Effect.fn(function* (act: "look" | "open" | "dismiss" | "leave") { + const run = yield* workflows.start("keeper", { act }, { idempotencyKey: act }); + return yield* workflows.waitFor(run.runId, status("completed", "paused")); + }); + const [one, two, three] = yield* Effect.all([ + visit("visit/1", "north"), + visit("visit/2", "north"), + visit("visit/3", "south"), + ]); + // Not at a gate, and not started as a visit: none of the keeper's business. + yield* workflows.start("review", { change: "north" }, { idempotencyKey: "other" }); + for (const run of [one, two, three]) yield* workflows.waitFor(run.runId, status("waiting")); + + assert.deepStrictEqual((yield* keeper("look")).result, [ + "visit/1 waiting", + "visit/2 waiting", + "visit/3 waiting", + ]); + // Both at the north gate go through on one signal; the one at the south gate stays. + assert.equal((yield* keeper("open")).result, 2); + for (const run of [one, two]) { + assert.equal((yield* workflows.waitFor(run.runId, status("completed"))).result, "go on"); + } + assert.equal((yield* workflows.get(three.runId)).run.status, "waiting"); + + yield* keeper("dismiss"); + const dismissed = (yield* workflows.get(three.runId)).run; + assert.deepStrictEqual( + [dismissed.status, dismissed.detail], + ["cancelled", "the gate is closed"], + ); + // A run ends itself with `stop`; cancelling itself would cut the cancel short. + const left = yield* keeper("leave"); + assert.equal(left.status, "paused"); + assert.include(left.detail ?? "", "cannot cancel itself"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a workflow can take an agent's failure as an answer and go on", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The first agent's turn dies, and so does the one more try it gets. + const died = yield* workflows.start("fallback", { project: "p1" }, { idempotencyKey: "d" }); + yield* agents.started(died.runId, "first/0"); + yield* agents.end(died.runId, "first/0", { ending: "failed", detail: "failed" }); + yield* agents.started(died.runId, "first/1"); + yield* agents.end(died.runId, "first/1", { ending: "failed", detail: "failed" }); + yield* agents.started(died.runId, "second/0"); + yield* agents.end(died.runId, "second/0", { output: { head: "abc" } }); + const done = yield* workflows.waitFor(died.runId, status("completed", "paused")); + assert.deepStrictEqual( + [done.status, done.pauses, done.result], + ["completed", 0, "abc after: the agent's turn was cut short: failed"], + ); + const { steps } = yield* workflows.get(died.runId); + assert.deepStrictEqual( + steps.map((step) => [step.name, step.status]), + [ + ["first", "failed"], + ["second", "completed"], + ], + ); + + // An agent that cannot be started at all is an answer too. + const lost = yield* workflows.start( + "fallback", + { project: "nowhere" }, + { idempotencyKey: "n" }, + ); + yield* agents.started(lost.runId, "second/0"); + yield* agents.end(lost.runId, "second/0", { output: { head: "def" } }); + const found = yield* workflows.waitFor(lost.runId, status("completed", "paused")); + assert.equal( + found.result, + "def after: the agent could not be started: No project is registered there.", + ); + + // A result that cannot be read leaves the turn maybe running: a stop that fails gives up + // the step, and no second turn starts beside it. + const stopsBefore = agents.interrupted.length; + agents.refuseStops(3); + agents.unreadableResult("first/0"); + const unread = yield* workflows.start( + "fallback", + { project: "p1" }, + { idempotencyKey: "u" }, + ); + yield* agents.started(unread.runId, "second/0"); + assert.equal(agents.interrupted.length, stopsBefore); + yield* agents.end(unread.runId, "second/0", { output: { head: "jkl" } }); + const gaveUp = yield* workflows.waitFor(unread.runId, status("completed", "paused")); + assert.include(gaveUp.result as string, "its turn could not be stopped"); + + // One past its time whose turn cannot be stopped says so, for the workflow to weigh. + agents.refuseStops(3); + const stuck = yield* workflows.start( + "fallback", + { project: "p1", timeout: "1 minute" }, + { idempotencyKey: "s" }, + ); + yield* agents.started(stuck.runId, "second/0"); + yield* agents.end(stuck.runId, "second/0", { output: { head: "ghi" } }); + const weighed = yield* workflows.waitFor(stuck.runId, status("completed", "paused")); + assert.include(weighed.result as string, "its turn could not be stopped"); + + // A stop turned down once gets through on its retry, and the step says it was stopped. + const before = agents.interrupted.length; + agents.refuseStops(1); + const late = yield* workflows.start( + "fallback", + { project: "p1", timeout: "1 minute" }, + { idempotencyKey: "l" }, + ); + yield* agents.started(late.runId, "second/0"); + assert.equal(agents.interrupted.length, before + 1); + yield* agents.end(late.runId, "second/0", { output: { head: "mno" } }); + const retried = yield* workflows.waitFor(late.runId, status("completed", "paused")); + assert.equal(retried.status, "completed"); + assert.notInclude(retried.result as string, "could not be stopped"); + + // A result that arrived as its time ran out, before it was read, is still the answer. + agents.unansweredResult("first/0"); + const lastMinute = yield* workflows.start( + "fallback", + { project: "p1", timeout: "1 minute" }, + { idempotencyKey: "m" }, + ); + yield* agents.started(lastMinute.runId, "first/0"); + yield* agents.end(lastMinute.runId, "first/0", { output: { head: "pqr" } }); + yield* agents.end(lastMinute.runId, "second/0", { output: { head: "not needed" } }); + const answered = yield* workflows.waitFor(lastMinute.runId, status("completed", "paused")); + assert.equal(answered.result, "pqr"); + + // One whose turn had ended without its result is not said to be stopped: the agent may + // answer from a later turn nobody stopped. + agents.unansweredResult("first/0"); + const owing = yield* workflows.start( + "fallback", + { project: "p1", timeout: "1 minute" }, + { idempotencyKey: "o" }, + ); + yield* agents.started(owing.runId, "first/0"); + yield* agents.end(owing.runId, "first/0", {}); + yield* agents.started(owing.runId, "second/0"); + yield* agents.end(owing.runId, "second/0", { output: { head: "stu" } }); + const owed = yield* workflows.waitFor(owing.runId, status("completed", "paused")); + assert.include(owed.result as string, "may still be at work"); + + // One that did the work and never gave its result is not given the job again: it may + // have acted on it already. + const silent = yield* workflows.start( + "fallback", + { project: "p1", thread: true }, + { idempotencyKey: "q" }, + ); + for (const key of ["first/0", "first/0/correct/0", "first/0/correct/1"]) { + yield* agents.started(silent.runId, key); + yield* agents.end(silent.runId, key, {}); + } + yield* agents.end(silent.runId, "first/1", { output: { head: "twice" } }); + yield* agents.end(silent.runId, "second/0", { output: { head: "vwx" } }); + const once = yield* workflows.waitFor(silent.runId, status("completed", "paused")); + assert.match( + once.result as string, + /^vwx after: the agent did not return a result: .* in thread-\d+$/, + ); + + // A correction that cannot be sent leaves the failure with the thread the work is in. + const unasked = yield* workflows.start( + "fallback", + { project: "p1", thread: true }, + { idempotencyKey: "c" }, + ); + agents.unstartable(unasked.runId, "first/0/correct/0"); + yield* agents.started(unasked.runId, "first/0"); + yield* agents.end(unasked.runId, "first/0", {}); + yield* agents.end(unasked.runId, "second/0", { output: { head: "yz" } }); + const kept = yield* workflows.waitFor(unasked.runId, status("completed", "paused")); + assert.match(kept.result as string, /could not be asked again: .* in thread-\d+$/); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); diff --git a/apps/server/src/workflows/Workflows.ts b/apps/server/src/workflows/Workflows.ts new file mode 100644 index 0000000000000..1b26479d6bd7a --- /dev/null +++ b/apps/server/src/workflows/Workflows.ts @@ -0,0 +1,221 @@ +import { + type WorkflowCounts, + type WorkflowHook, + WorkflowQuestion, + type WorkflowRunReference, + type WorkflowRunsSnapshot, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import type * 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 Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import type { WebhookRequest } from "./triggers.ts"; +import type * as WorkflowStore from "./WorkflowStore.ts"; + +/** Hook ids of workflows start with this; a scheduled task's hook id never does. */ +export const HOOK_PREFIX = "wf-"; + +// The dot between the two parts is never in either, so no two hooks share an id. +const hookPart = (part: string) => encodeURIComponent(part).replaceAll(".", "%2E"); +/** The id of the hook `name` of `workflow`, which its URL and its secret are kept by. */ +export const hookId = (workflow: string, name: string) => + `${HOOK_PREFIX}${hookPart(workflow)}.${hookPart(name)}`; + +export class WorkflowNotRegisteredError extends Schema.TaggedError()( + "WorkflowNotRegisteredError", + { workflow: Schema.String, version: Schema.optional(Schema.Number) }, +) { + override get message(): string { + return this.version === undefined + ? `No workflow named ${this.workflow} is registered.` + : `Version ${this.version} of workflow ${this.workflow} is not registered.`; + } +} + +export class WorkflowRunNotFoundError extends Schema.TaggedError()( + "WorkflowRunNotFoundError", + { runId: Schema.String }, +) { + override get message(): string { + return `Workflow run ${this.runId} was not found.`; + } +} + +export class WorkflowInputError extends Schema.TaggedError()( + "WorkflowInputError", + { problem: Schema.String }, +) { + override get message(): string { + return this.problem; + } +} + +export { WorkflowQuestion }; + +export type WorkflowError = + | WorkflowNotRegisteredError + | WorkflowRunNotFoundError + | WorkflowInputError; + +export class Workflows extends Context.Service< + Workflows, + { + /** Start a run. A second start with the same key is the same run. */ + readonly start: ( + workflow: string, + input: unknown, + options: { + readonly idempotencyKey: string; + /** The run that waits for this one. A run started with a key has one parent or none. */ + readonly parent?: WorkflowStore.RunParent; + /** The version to run, when the caller holds a definition. Without it, the newest. */ + readonly version?: number; + }, + ) => Effect.Effect<{ readonly runId: string }, WorkflowError>; + /** + * Say that something a run waits on happened. `delivered` woke a wait; `buffered` is kept for + * a wait that has not opened yet, for `ttl` (seven days by default). + */ + readonly signal: ( + address: WorkflowStore.SignalAddress, + value: Schema.Json, + options: { readonly id: string; readonly ttl?: Duration.Input }, + ) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>; + /** + * Answer the question a run asks a person. One answer per time it is asked: a second, a + * double click, wakes nothing and is not kept for later. + */ + readonly answer: ( + runId: string, + name: string, + value: Schema.Json, + ) => Effect.Effect; + /** Run a paused run's failed step again. */ + readonly resume: (runId: string) => Effect.Effect; + readonly cancel: (runId: string, reason?: string) => Effect.Effect; + readonly get: (runId: string) => Effect.Effect< + { + readonly run: WorkflowStore.WorkflowRun; + readonly steps: ReadonlyArray; + readonly references: ReadonlyArray; + }, + WorkflowRunNotFoundError | WorkflowInputError + >; + readonly list: (filter?: { + readonly status?: WorkflowStore.WorkflowRunStatus; + }) => Effect.Effect, WorkflowInputError>; + /** The run once `done` holds for it. Looks now, then on every change to the run. */ + readonly waitFor: ( + runId: string, + done: (run: WorkflowStore.WorkflowRun) => boolean, + ) => Effect.Effect; + /** The questions runs are waiting on a person to answer, oldest first. */ + readonly questions: Effect.Effect, WorkflowInputError>; + /** What each run that has not ended is a run of, however many: no list limit applies. */ + readonly unfinished: Effect.Effect< + ReadonlyArray<{ readonly workflow: string; readonly version: number }> + >; + /** The hook URLs of the registered workflows. */ + readonly hooks: Effect.Effect, WorkflowInputError>; + /** + * Start the run a request to a hook asks for. Nothing, for a hook or token that is not known. + * `deliveryId` names the delivery when its carrier vouches for one, so its retry is one run. + */ + readonly deliver: (delivery: { + readonly hookId: string; + readonly token: string; + readonly request: WebhookRequest; + readonly deliveryId?: string; + }) => Effect.Effect, WorkflowError>; + /** What workflows keep in the store under keys starting with `prefix`, for a person to see. */ + readonly stored: ( + prefix: string, + ) => Effect.Effect< + ReadonlyArray<{ readonly key: string; readonly value: Schema.Json }>, + WorkflowInputError + >; + /** Set a key of the store from outside a run, as a person flipping a switch does. */ + readonly storeSet: (key: string, value: Schema.Json) => Effect.Effect; + readonly storeDelete: (key: string) => Effect.Effect; + /** Recent runs and open questions, now and again after every change. */ + readonly watch: Stream.Stream; + /** How much is going on, now and again whenever a count changes. */ + readonly counts: Stream.Stream; + /** + * Deliver timeouts to waits past their deadline, drop expired mail, and resume paused runs + * whose rest is over. Runs by itself every few seconds. + */ + readonly sweep: Effect.Effect; + } +>()("t3/workflows/Workflows") {} + +const refuse = Effect.fn("Workflows.disabled")(function* () { + return yield* new WorkflowInputError({ + problem: + "This server defines no workflows yet. Add a file to the workflows folder of its T3 home.", + }); +}); + +/** The service with nothing registered and no engine behind it. */ +export const disabled = Workflows.of({ + start: refuse, + signal: refuse, + answer: refuse, + resume: refuse, + cancel: refuse, + get: Effect.fn("Workflows.get")(function* (runId) { + return yield* new WorkflowRunNotFoundError({ runId }); + }), + list: Effect.fn("Workflows.list")(function* () { + return yield* Effect.succeed>([]); + }), + waitFor: Effect.fn("Workflows.waitFor")(function* () { + return yield* Effect.never; + }), + questions: Effect.succeed([]), + unfinished: Effect.succeed([]), + hooks: Effect.succeed([]), + deliver: Effect.fn("Workflows.deliver")(function* () { + return yield* Effect.succeed(Option.none<{ readonly runId: string }>()); + }), + stored: Effect.fn("Workflows.stored")(function* () { + return yield* Effect.succeed>([]); + }), + storeSet: refuse, + storeDelete: refuse, + watch: Stream.concat(Stream.make({ workflows: [], runs: [], questions: [] }), Stream.never), + counts: Stream.concat(Stream.make({ needsYou: 0, active: 0, total: 0 }), Stream.never), + sweep: Effect.void, +}); +export const layerDisabled = Layer.succeed(Workflows, disabled); + +export const OFF = + 'Workflows are off on this server. Turn them on in its Settings → Labs → Workflows, or without a desktop, set "workflowsEnabled": true in userdata/settings.json in its T3 home (~/.t3 by default).'; + +const refuseOff = Effect.fn("Workflows.off")(function* () { + return yield* new WorkflowInputError({ problem: OFF }); +}); + +/** + * The service while workflows are off: every request is refused, and a hook answers as one that + * is not there. + */ +export const off = Workflows.of({ + ...disabled, + start: refuseOff, + signal: refuseOff, + answer: refuseOff, + resume: refuseOff, + cancel: refuseOff, + get: refuseOff, + list: refuseOff, + questions: refuseOff(), + hooks: refuseOff(), + stored: refuseOff, + storeSet: refuseOff, + storeDelete: refuseOff, +}); diff --git a/apps/server/src/workflows/api.ts b/apps/server/src/workflows/api.ts new file mode 100644 index 0000000000000..9f1bfd72b15ca --- /dev/null +++ b/apps/server/src/workflows/api.ts @@ -0,0 +1,15 @@ +// Everything a definitions module is handed. A workflow file imports nothing: an installed server +// is one bundle, with no package for it to import these from, and its own copy of `effect` would +// not be the one the engine runs. +export * as Duration from "effect/Duration"; +export * as Effect from "effect/Effect"; +export * as Option from "effect/Option"; +export * as Schedule from "effect/Schedule"; +export * as Schema from "effect/Schema"; + +export { daily, every, Tick, webhook, WebhookRequest } from "./triggers.ts"; +export { issues, pullRequests } from "./forgeApi.ts"; +export { cancel, runs, signal, signalAll, start, store } from "./stepServices.ts"; +export { Issue, IssueDetail, PullRequest, PullRequestStanding } from "./WorkflowForge.ts"; +export { invoke, skip, sleep, step, stop, title, wait, workflow } from "./workflow.ts"; +export { agent, ask } from "./workflowAgent.ts"; diff --git a/apps/server/src/workflows/forgeApi.ts b/apps/server/src/workflows/forgeApi.ts new file mode 100644 index 0000000000000..a7e0839730201 --- /dev/null +++ b/apps/server/src/workflows/forgeApi.ts @@ -0,0 +1,109 @@ +// Issues and pull requests as a workflow file sees them: triggers, calls for inside a step, and a +// wait on a pull request for the body. +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import type * as Option from "effect/Option"; + +import { checkOptions } from "./options.ts"; +import { issuesOpened, pullRequestsOpened } from "./triggers.ts"; +import type { InRun } from "./workflow.ts"; +import { waitAs } from "./workflow.ts"; +import { + type IssueAddress, + type PullRequestAddress, + PullRequestStanding, + type PullRequestUntil, + type PullRequestWatch, + WorkflowForge, +} from "./WorkflowForge.ts"; + +const forge = (use: (forge: WorkflowForge["Service"]) => Effect.Effect) => + Effect.flatMap(WorkflowForge, use); + +/** + * The project's issues, in whichever tracker it uses. `opened` is a trigger; the rest are for + * inside `step` or `onEnd`. An issue is named by what a trigger or `list` gave, or by + * `{ project, url }`. + */ +export const issues = { + opened: issuesOpened, + list: (query: Parameters[0]) => { + checkOptions("issues.list", query, [ + "project", + "state", + "labels", + "query", + "assignee", + "sort", + "limit", + ]); + return forge((all) => all.issues.list(query)); + }, + read: (issue: IssueAddress) => forge((all) => all.issues.read(issue)), + comment: (issue: IssueAddress, body: string) => forge((all) => all.issues.comment(issue, body)), + /** Move the issue to one of its `states`, as `read` lists them. */ + setState: (issue: IssueAddress, state: string) => + forge((all) => all.issues.setState(issue, state)), + create: (input: Parameters[0]) => { + checkOptions("issues.create", input, ["project", "title", "body", "labels", "assignees"]); + return forge((all) => all.issues.create(input)); + }, +}; + +/** + * The project's pull requests on its git host. `opened` is a trigger; the rest are for inside + * `step` or `onEnd`. A pull request is named by what a trigger or `list` gave, or by + * `{ project, url }`. + */ +export const pullRequests = { + opened: pullRequestsOpened, + list: (query: Parameters[0]) => { + checkOptions("pullRequests.list", query, ["project", "state", "query", "limit"]); + return forge((all) => all.pullRequests.list(query)); + }, + read: (pullRequest: PullRequestAddress) => forge((all) => all.pullRequests.read(pullRequest)), + comment: (pullRequest: PullRequestAddress, body: string) => + forge((all) => all.pullRequests.comment(pullRequest, body)), + /** `merge`, `close`, `ready`, `update-branch` and the host's other actions on a pull request. */ + act: ( + pullRequest: PullRequestAddress, + action: Parameters[1], + options?: Parameters[2], + ) => { + checkOptions("pullRequests.act", options, ["mergeMethod"]); + return forge((all) => all.pullRequests.act(pullRequest, action, options)); + }, + /** + * Wait in the body until the pull request gets somewhere, without holding anything: `checks` + * until none of its checks is still running, `merged` or `closed` until it is no longer open. + * A pull request that is merged or closed ends any of them. Gives where it stands, or nothing + * after `timeout`. The host is asked about once a minute. + */ + wait: ( + name: string, + pullRequest: PullRequestAddress, + options: { readonly until: PullRequestUntil; readonly timeout?: Duration.Input }, + ): Effect.Effect, never, InRun> => { + checkOptions(`pullRequests.wait("${name}")`, options, ["until", "timeout"]); + return Effect.orDie( + waitAs("wait", name, { + returns: PullRequestStanding, + timeout: options.timeout, + watch: { + kind: "pullRequest", + until: options.until, + // Only the address: a listing's row carries far more than a wait needs to keep. + pullRequest: + "url" in pullRequest && "project" in pullRequest + ? { project: pullRequest.project, url: pullRequest.url } + : { + projectId: pullRequest.projectId, + host: pullRequest.host, + repository: pullRequest.repository, + number: pullRequest.number, + }, + } satisfies PullRequestWatch, + }), + ); + }, +}; diff --git a/apps/server/src/workflows/options.ts b/apps/server/src/workflows/options.ts new file mode 100644 index 0000000000000..7ba47abf65f27 --- /dev/null +++ b/apps/server/src/workflows/options.ts @@ -0,0 +1,28 @@ +import * as Duration from "effect/Duration"; +import * as Option from "effect/Option"; + +/** The duration `input` is, or an error that names `what` and shows one that reads. */ +export const durationOf = (what: string, input: Duration.Input): Duration.Duration => + Option.getOrThrowWith( + Duration.fromInput(input), + () => + new Error( + `${what} cannot read ${JSON.stringify(input)} as a duration. Write one such as "5 minutes".`, + ), + ); + +/** + * Refuses an option the call does not take. A workflow file is not type-checked, so a misspelt or + * renamed option would otherwise be dropped without a word. + */ +export const checkOptions = ( + what: string, + options: object | undefined, + allowed: ReadonlyArray, +) => { + if (options === undefined || options === null) return; + const unknown = Object.keys(options).filter((key) => !allowed.includes(key)); + if (unknown.length === 0) return; + const listed = (keys: ReadonlyArray) => keys.map((key) => `\`${key}\``).join(", "); + throw new Error(`${what} does not take ${listed(unknown)}. It takes ${listed(allowed)}.`); +}; diff --git a/apps/server/src/workflows/runReferences.ts b/apps/server/src/workflows/runReferences.ts new file mode 100644 index 0000000000000..8599a3a6cae5b --- /dev/null +++ b/apps/server/src/workflows/runReferences.ts @@ -0,0 +1,90 @@ +// What a run touched, for a person reading the run: the issue that started it, the pull request a +// step merged. Anything that touches something calls `noteReference`; a new kind of thing is a +// new caller, and nothing else changes. +import { + type IssueRef, + type IssueState, + type PullRequestRef, + WorkflowReferenceKind, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import type * as Schema from "effect/Schema"; + +import type { ReferenceInput, WorkflowStore } from "./WorkflowStore.ts"; + +/** Keeps what the step whose code is running touches, against that step. */ +export class StepReferences extends Context.Service< + StepReferences, + { readonly note: (reference: ReferenceInput) => Effect.Effect } +>()("t3/workflows/runReferences/StepReferences") {} + +/** Keep that `runId` touched `reference`, from `step` or, with none, from what started it. */ +export const noteFor = ( + store: WorkflowStore["Service"], + runId: string, + step: string | null, + reference: ReferenceInput, +): Effect.Effect => + store.referenceNoted(runId, step, reference).pipe( + // Only for a person to read: a step must never fail or wait over it. + Effect.catchCause((cause) => + Effect.logWarning("Could not keep what a workflow run touched", { + runId, + step, + kind: reference.kind, + cause: Cause.pretty(cause), + }), + ), + ); + +/** Keep that the running step touched `reference`. Outside a step it does nothing. */ +export const noteReference = (reference: ReferenceInput): Effect.Effect => + Effect.flatMap(Effect.serviceOption(StepReferences), (current) => + current._tag === "None" ? Effect.void : current.value.note(reference), + ); + +export const stepReferences = ( + store: WorkflowStore["Service"], + runId: string, + step: string, +): Context.Context => + Context.make(StepReferences, { note: (reference) => noteFor(store, runId, step, reference) }); + +/** An issue, with its title and where it stands when the toucher read them. */ +export const issueReference = ( + ref: IssueRef, + seen?: { readonly title: string; readonly url: string; readonly state: IssueState }, +): ReferenceInput => ({ + kind: WorkflowReferenceKind.issue, + key: JSON.stringify([ref.tracker, ref.host ?? "", ref.scope.toLowerCase(), ref.key]), + address: { + projectId: ref.projectId, + tracker: ref.tracker, + ...(ref.host === undefined ? {} : { host: ref.host }), + scope: ref.scope, + key: ref.key, + } satisfies Schema.Json, + title: seen?.title ?? "", + url: seen?.url, + state: seen?.state.category, +}); + +/** A pull request by its normalized host and repository, so every way of naming it is one. */ +export const pullRequestReference = ( + ref: Pick & { readonly host: string }, + seen?: { readonly title?: string; readonly url?: string; readonly state?: string }, +): ReferenceInput => ({ + kind: WorkflowReferenceKind.pullRequest, + key: JSON.stringify([ref.host, ref.repository, ref.number]), + address: { + projectId: ref.projectId, + host: ref.host, + repository: ref.repository, + number: ref.number, + }, + title: seen?.title ?? "", + url: seen?.url, + state: seen?.state, +}); diff --git a/apps/server/src/workflows/stepServices.ts b/apps/server/src/workflows/stepServices.ts new file mode 100644 index 0000000000000..53c6773494c3b --- /dev/null +++ b/apps/server/src/workflows/stepServices.ts @@ -0,0 +1,458 @@ +// What a step's own code may use besides plain Effect: state shared between runs, and a way to +// wake a run that waits. Both touch the world, so they are for inside `step` and `onEnd`. +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import type * 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 Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { checkOptions } from "./options.ts"; +import { type StepReferences, stepReferences } from "./runReferences.ts"; +import type { WorkflowDefinition } from "./workflow.ts"; +import { WorkflowForge } from "./WorkflowForge.ts"; +import type { WorkflowError, WorkflowInputError } from "./Workflows.ts"; +import type { + RunParent, + SignalAddress, + WorkflowRunStatus, + WorkflowStore, +} from "./WorkflowStore.ts"; + +/** The shared store as rows of JSON text. `store` puts schemas on top. */ +export class KeyValues extends Context.Service< + KeyValues, + { + readonly get: (key: string) => Effect.Effect; + readonly set: (key: string, valueJson: string) => Effect.Effect; + readonly delete: (key: string) => Effect.Effect; + readonly list: ( + prefix: string, + ) => Effect.Effect>; + readonly transaction: (effect: Effect.Effect) => Effect.Effect; + } +>()("t3/workflows/stepServices/KeyValues") {} + +export type SendSignal = ( + address: SignalAddress, + value: Schema.Json, + options: { readonly id: string; readonly ttl?: Duration.Input }, +) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>; + +/** Everyone who waits on a key, in one workflow or in all of them. */ +export interface EveryoneAt { + readonly channel: string; + readonly workflow?: string | undefined; +} +export type SendSignalToAll = (address: EveryoneAt, value: Schema.Json) => Effect.Effect; + +/** A run as a step of another run sees it. `key` is what it was started with. */ +export interface RunSummary { + readonly id: string; + readonly workflow: string; + readonly key: string; + readonly title: string; + readonly status: WorkflowRunStatus; + readonly detail: string | null; + readonly startedAt: string; + readonly endedAt: string | null; +} +export interface RunFilter { + readonly workflow?: string | undefined; + readonly status?: WorkflowRunStatus | undefined; + readonly keyPrefix?: string | undefined; +} + +/** Signals from the step that is running. Its signals are numbered, so a retry sends the same ones. */ +export class Signals extends Context.Service< + Signals, + { + readonly sendAll: SendSignalToAll; + readonly send: ( + address: SignalAddress, + value: Schema.Json, + options?: { readonly id?: string; readonly ttl?: Duration.Input }, + ) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>; + } +>()("t3/workflows/stepServices/Signals") {} + +export type StartRun = ( + workflow: string, + input: unknown, + options: { + readonly idempotencyKey: string; + readonly parent?: RunParent; + /** The version the caller was written against. Without it, the newest registered. */ + readonly version?: number; + }, +) => Effect.Effect<{ readonly runId: string }, WorkflowError>; + +export type CancelRun = (runId: string, reason: string) => Effect.Effect; +export type ListRuns = (filter: RunFilter) => Effect.Effect>; + +/** Other runs, from the step that is running: starting, finding and cancelling them. */ +export class Runs extends Context.Service< + Runs, + { readonly start: StartRun; readonly cancel: CancelRun; readonly list: ListRuns } +>()("t3/workflows/stepServices/Runs") {} + +export type InStep = KeyValues | Signals | Runs | WorkflowForge | StepReferences; + +/** + * What a step needs of the engine, which exists only once the engine does, while the workflows + * that use it are registered before. The engine fills this in when it starts. + */ +export class EngineLink extends Context.Service< + EngineLink, + { + current: + | { + readonly signal: SendSignal; + readonly signalAll: SendSignalToAll; + readonly start: StartRun; + readonly cancel: CancelRun; + readonly list: ListRuns; + /** Tell the run that invoked `runId`, if one did, how it ended. */ + readonly ended: (runId: string) => Effect.Effect; + } + | undefined; + /** The steps of each run that are running in this process right now. */ + readonly inFlight: InFlight; + } +>()("t3/workflows/stepServices/EngineLink") {} +export interface InFlight { + readonly track: ( + runId: string, + effect: Effect.Effect, + ) => Effect.Effect; + /** Whether a step of `runId` is running now. */ + readonly busy: (runId: string) => boolean; + /** Waits until no step of `runId` is running. */ + readonly settled: (runId: string) => Effect.Effect; +} + +// A step cannot be interrupted, so whatever cleans up after a cancelled run waits for it here. +const makeInFlight = (): InFlight => { + const running = new Map }>(); + return { + track: (runId, effect) => + Effect.acquireUseRelease( + Effect.sync(() => { + const entry = running.get(runId) ?? { count: 0, idle: Deferred.makeUnsafe() }; + entry.count++; + running.set(runId, entry); + return entry; + }), + () => effect, + (entry) => + Effect.suspend(() => { + if (--entry.count > 0) return Effect.void; + running.delete(runId); + return Deferred.succeed(entry.idle, undefined); + }), + ), + busy: (runId) => running.has(runId), + settled: (runId) => + Effect.suspend(() => { + const entry = running.get(runId); + return entry === undefined ? Effect.void : Deferred.await(entry.idle); + }), + }; +}; + +export const layerEngineLink = Layer.sync(EngineLink, () => ({ + current: undefined, + inFlight: makeInFlight(), +})); + +const engineOf = (link: EngineLink["Service"]) => + link.current === undefined + ? Effect.die(new Error("The workflow engine is not up.")) + : Effect.succeed(link.current); + +/** + * The services for the step `name` of `runId`. Each signal it sends is the two, where it goes, + * and how many it sent there before, so a retry that sends the same again is not new. What it + * touches through the forge is kept against it. + */ +export const forStep = ( + store: WorkflowStore["Service"], + keyValues: KeyValues["Service"], + link: EngineLink["Service"], + forge: WorkflowForge["Service"], + runId: string, + name: string, +): Context.Context => { + const owner = `${runId}/${name}`; + const sent = new Map(); + return Context.make(KeyValues, keyValues).pipe( + Context.add(WorkflowForge, forge), + Context.merge(stepReferences(store, runId, name)), + Context.add( + Signals, + Signals.of({ + send: Effect.fn("Signals.send")(function* (address, value, options) { + const { signal: send } = yield* engineOf(link); + const to = ( + "runId" in address + ? ["run", address.runId, address.wait] + : ["key", address.workflow, address.channel] + ) + .map(encodeURIComponent) + .join("/"); + const before = sent.get(to) ?? 0; + sent.set(to, before + 1); + return yield* send(address, value, { + id: options?.id ?? `${owner}/signal/${to}/${before}`, + ...(options?.ttl === undefined ? {} : { ttl: options.ttl }), + }); + }), + sendAll: Effect.fn("Signals.sendAll")(function* (address, value) { + const engine = yield* engineOf(link); + return yield* engine.signalAll(address, value); + }), + }), + ), + Context.add( + Runs, + Runs.of({ + start: Effect.fn("Runs.start")(function* (workflow, input, options) { + const engine = yield* engineOf(link); + return yield* engine.start(workflow, input, options); + }), + cancel: Effect.fn("Runs.cancel")(function* (target, reason) { + // Cancelling interrupts the run, and this step is the run: it would cut itself off + // halfway through the cancel. + if (target === runId) { + return yield* Effect.die( + new Error("A run cannot cancel itself. End it from its body with `stop`."), + ); + } + const engine = yield* engineOf(link); + return yield* engine.cancel(target, reason); + }), + list: Effect.fn("Runs.list")(function* (filter) { + const engine = yield* engineOf(link); + return yield* engine.list(filter); + }), + }), + ), + ); +}; + +export const layerKeyValues = Layer.effect( + KeyValues, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + // LIKE would read `%` and `_` in a prefix as patterns; a range does not. + const after = (prefix: string) => `${prefix}\u{10FFFF}`; + return KeyValues.of({ + get: Effect.fn("KeyValues.get")(function* (key) { + const rows = yield* sql<{ value_json: string }>` + SELECT value_json FROM workflow_store WHERE key = ${key} + `.pipe(Effect.orDie); + return rows[0]?.value_json; + }), + set: Effect.fn("KeyValues.set")(function* (key, valueJson) { + const at = DateTime.formatIso(yield* DateTime.now); + yield* sql` + INSERT INTO workflow_store (key, value_json, updated_at) + VALUES (${key}, ${valueJson}, ${at}) + ON CONFLICT (key) DO UPDATE + SET value_json = excluded.value_json, updated_at = excluded.updated_at + `.pipe(Effect.orDie); + }), + delete: Effect.fn("KeyValues.delete")(function* (key) { + yield* sql`DELETE FROM workflow_store WHERE key = ${key}`.pipe(Effect.orDie); + }), + list: Effect.fn("KeyValues.list")(function* (prefix) { + const rows = yield* sql<{ key: string; value_json: string }>` + SELECT key, value_json FROM workflow_store + WHERE key >= ${prefix} AND key < ${after(prefix)} ORDER BY key + `.pipe(Effect.orDie); + return rows.map((row) => ({ key: row.key, valueJson: row.value_json })); + }), + transaction: Effect.fn("KeyValues.transaction")(function* (effect) { + return yield* sql.withTransaction(effect).pipe(Effect.catchTags({ SqlError: Effect.die })); + }), + }); + }), +); + +/** A value that no longer fits its schema, or never did. */ +export class StoreValueError extends Schema.TaggedError()("StoreValueError", { + key: Schema.String, + problem: Schema.String, +}) { + override get message(): string { + return `The stored value at ${this.key} does not fit its schema: ${this.problem}`; + } +} + +/** + * One key of the store, with the schema of what it holds. `update` reads and writes as one + * action, so two runs counting on the same key never lose a count; returning `undefined` from it + * deletes the key. + */ +const entry = (key: string, schema: Schema.Codec) => { + const codec = Schema.fromJsonString(Schema.toCodecJson(schema)); + const decode = Schema.decodeEffect(codec); + const encode = Schema.encodeEffect(codec); + const invalid = (error: unknown) => new StoreValueError({ key, problem: String(error) }); + const read = (store: KeyValues["Service"]) => + Effect.flatMap(store.get(key), (text) => + text === undefined + ? Effect.succeed(Option.none()) + : Effect.mapBoth(decode(text), { onFailure: invalid, onSuccess: Option.some }), + ); + const write = (store: KeyValues["Service"], value: A) => + encode(value).pipe( + Effect.mapError(invalid), + Effect.flatMap((text) => store.set(key, text)), + ); + return { + key, + get: Effect.flatMap(KeyValues, read), + set: (value: A) => Effect.flatMap(KeyValues, (store) => write(store, value)), + delete: Effect.flatMap(KeyValues, (store) => store.delete(key)), + update: (change: (current: Option.Option) => A | undefined) => + Effect.flatMap(KeyValues, (store) => + store.transaction( + Effect.gen(function* () { + const next = change(yield* read(store)); + if (next === undefined) { + yield* store.delete(key); + return Option.none(); + } + yield* write(store, next); + return Option.some(next); + }), + ), + ), + }; +}; + +/** Every key that starts with `prefix`, in key order, with what it holds. */ +const entries = (prefix: string, schema: Schema.Codec) => { + const codec = Schema.fromJsonString(Schema.toCodecJson(schema)); + const decode = Schema.decodeEffect(codec); + return Effect.flatMap(KeyValues, (store) => + Effect.flatMap(store.list(prefix), (rows) => + Effect.forEach(rows, (row) => + Effect.mapBoth(decode(row.valueJson), { + onFailure: (error) => new StoreValueError({ key: row.key, problem: String(error) }), + onSuccess: (value) => ({ key: row.key, value }), + }), + ), + ), + ); +}; + +/** Several reads and writes as one: all of them happen, or none. */ +const transaction = (effect: Effect.Effect) => + Effect.flatMap(KeyValues, (store) => store.transaction(effect)); + +/** + * State that outlives a run and is shared by every workflow on this server. Use it inside `step` + * or `onEnd`: what it returns changes over time, so the body itself must not read it. + */ +export const store = { entry, entries, transaction }; + +/** A workflow by its name or its definition, wherever one is named. */ +export type WorkflowName = string | Pick; +const nameOf = (workflow: WorkflowName) => + typeof workflow === "string" ? workflow : workflow.name; + +/** + * Wake a run that waits: `{ runId, wait }` for one wait of one run, `{ workflow, channel }` for + * whichever run of a workflow waits on a channel. Inside `step` or `onEnd` only. + */ +export const signal = ( + address: + | { readonly runId: string; readonly wait: string } + | { readonly workflow: WorkflowName; readonly channel: string }, + value: Schema.Json, + options?: { readonly id?: string; readonly ttl?: Duration.Input }, +) => + Effect.flatMap(Signals, (signals) => { + checkOptions( + "signal's address", + address, + "runId" in address ? ["runId", "wait"] : ["workflow", "channel"], + ); + checkOptions("signal", options, ["id", "ttl"]); + return signals.send( + "runId" in address + ? address + : { workflow: nameOf(address.workflow), channel: address.channel }, + value, + options, + ); + }); + +/** + * Start a run of another workflow and go on without it. The same `key` is the same run. Inside + * `step` or `onEnd` only; to wait for the run's result, use `invoke` in the body instead. + */ +export const start =

( + workflow: WorkflowDefinition

, + payload: P, + options: { readonly key: string }, +) => + Effect.flatMap(Runs, (runs) => { + checkOptions("start", options, ["key"]); + return runs.start(workflow.name, payload, { + idempotencyKey: options.key, + version: workflow.version, + }); + }); + +/** + * Wake every run that waits on `channel`, in one workflow or, without `workflow`, in all of them. + * Returns how many it woke. Nothing is kept for a wait that opens later, so a run that waits on + * a condition checks the condition in a step first, and gives its wait a timeout to check again. + * Inside `step` or `onEnd` only. + */ +export const signalAll = ( + address: { readonly channel: string; readonly workflow?: WorkflowName }, + value: Schema.Json, +) => + Effect.flatMap(Signals, (signals) => { + checkOptions("signalAll's address", address, ["channel", "workflow"]); + return signals.sendAll( + { + channel: address.channel, + workflow: address.workflow === undefined ? undefined : nameOf(address.workflow), + }, + value, + ); + }); + +/** + * Cancel another run, as a person would: its agents are stopped, its questions withdrawn, what + * it invoked is cancelled, and its `onEnd` runs. A run that has ended is left alone. Inside + * `step` or `onEnd` only. + */ +export const cancel = (runId: string, reason: string) => + Effect.flatMap(Runs, (runs) => runs.cancel(runId, reason)); + +/** + * Find runs: of one workflow, in one status, or started with a key that begins with `keyPrefix`. + * Newest first, 500 at most. Inside `step` or `onEnd` only: the answer changes over time. + */ +export const runs = (filter?: { + readonly workflow?: WorkflowName; + readonly status?: WorkflowRunStatus; + readonly keyPrefix?: string; +}) => + Effect.flatMap(Runs, (all) => { + checkOptions("runs", filter, ["workflow", "status", "keyPrefix"]); + return all.list({ + workflow: filter?.workflow === undefined ? undefined : nameOf(filter.workflow), + status: filter?.status, + keyPrefix: filter?.keyPrefix, + }); + }); diff --git a/apps/server/src/workflows/triggers.ts b/apps/server/src/workflows/triggers.ts new file mode 100644 index 0000000000000..9e90842ab7fda --- /dev/null +++ b/apps/server/src/workflows/triggers.ts @@ -0,0 +1,156 @@ +// What starts a run by itself. A trigger hands its workflow one value, so a workflow that lists +// a trigger takes that value as its payload: `Tick` for a schedule, `WebhookRequest` for a hook. +import * as Duration from "effect/Duration"; +import * as Schema from "effect/Schema"; + +import { parseTimeOfDay } from "../scheduledTasks/Schedule.ts"; +import { checkOptions, durationOf } from "./options.ts"; +import type { Issue, PullRequest } from "./WorkflowForge.ts"; + +/** The time a scheduled run was due, which is not the time it started. */ +export const Tick = Schema.Struct({ scheduledAt: Schema.String }); +export type Tick = typeof Tick.Type; + +/** A request to a workflow's hook URL, as it arrived. Header names are lower case. */ +export const WebhookRequest = Schema.Struct({ + method: Schema.String, + headers: Schema.Record(Schema.String, Schema.String), + query: Schema.String, + body: Schema.String, +}); +export type WebhookRequest = typeof WebhookRequest.Type; + +export interface ScheduleTrigger { + readonly kind: "schedule"; + /** Stable across restarts: where this trigger's next time is kept. */ + readonly id: string; + readonly schedule: + | { readonly type: "interval"; readonly everyMs: number } + | { + readonly type: "fixed_time"; + readonly timeOfDay: string; + readonly weekdays?: ReadonlyArray; + }; +} +export interface WebhookTrigger { + readonly kind: "webhook"; + readonly name: string; + readonly key: ((request: WebhookRequest) => string | undefined) | undefined; +} +/** New issues or pull requests of a project, which the engine looks for by itself. */ +export interface OpenedTrigger { + readonly kind: "issues" | "pullRequests"; + /** Stable across restarts: where this trigger keeps how far it has looked. */ + readonly id: string; + readonly project: string; + readonly labels?: ReadonlyArray | undefined; + readonly query?: string | undefined; +} +/** `Fires` is what the trigger gives the run it starts. */ +export type Trigger = (ScheduleTrigger | WebhookTrigger | OpenedTrigger) & { + readonly fires?: (value: Fires) => void; +}; + +/** A run every so often, counted from when the last one was started. At least a minute. */ +export const every = (interval: Duration.Input): Trigger => { + const everyMs = Duration.toMillis(durationOf(`every(${JSON.stringify(interval)})`, interval)); + // The sweep would quietly stretch a shorter one to a minute. + if (everyMs < 60_000) { + throw new Error(`every(${JSON.stringify(interval)}) is shorter than the shortest, one minute.`); + } + return { kind: "schedule", id: `every:${everyMs}`, schedule: { type: "interval", everyMs } }; +}; + +/** + * A run at a time of day (`"09:00"`) on the server's clock, on every day or on the given weekdays + * (0 is Sunday). A time missed by more than ten minutes, for a server that was down, is skipped. + */ +export const daily = ( + timeOfDay: string, + options?: { readonly weekdays?: ReadonlyArray }, +): Trigger => { + checkOptions(`daily("${timeOfDay}")`, options, ["weekdays"]); + const weekdays = options?.weekdays; + // Read once here: a time the schedule cannot read would otherwise never fire, without a word. + if (parseTimeOfDay(timeOfDay) === null) { + throw new Error(`daily("${timeOfDay}") needs a 24-hour time such as "09:00".`); + } + if (weekdays?.some((day) => !Number.isInteger(day) || day < 0 || day > 6)) { + throw new Error(`daily's weekdays are 0 (Sunday) to 6 (Saturday), not ${weekdays.join(", ")}.`); + } + return { + kind: "schedule", + id: `daily:${timeOfDay}:${weekdays?.toSorted().join(",") ?? "all"}`, + schedule: { type: "fixed_time", timeOfDay, ...(weekdays === undefined ? {} : { weekdays }) }, + }; +}; + +/** + * A run for each request to this workflow's hook URL (`t3 workflow hooks` prints it). The run + * decides what the request means, `stop` included. Two requests for which `key` gives the same + * text are one run, which is how a sender's retries are told from new deliveries. + */ +export const webhook = ( + name: string, + options?: { readonly key?: (request: WebhookRequest) => string | undefined }, +): Trigger => { + checkOptions(`webhook("${name}")`, options, ["key"]); + return { kind: "webhook", name, key: options?.key }; +}; + +/** Refuses two hooks of one name, or two triggers that would fire on the same thing. */ +export const checkTriggers = ( + workflow: string, + triggers: ReadonlyArray, +) => { + const seen = new Set(); + for (const trigger of triggers) { + const id = trigger.kind === "webhook" ? `webhook:${trigger.name}` : trigger.id; + if (seen.has(id)) { + throw new Error( + trigger.kind === "webhook" + ? `workflow("${workflow}") has two hooks named "${trigger.name}". Give each its own name.` + : `workflow("${workflow}") lists the same ${trigger.kind === "schedule" ? "schedule" : "trigger"} twice. List it once.`, + ); + } + seen.add(id); + } +}; + +const openedId = ( + kind: OpenedTrigger["kind"], + options: { + readonly project: string; + readonly labels?: ReadonlyArray; + readonly query?: string; + }, +) => + // A tuple, so no label or query can be read as part of another. + JSON.stringify([kind, options.project, options.labels?.toSorted() ?? [], options.query ?? ""]); + +/** + * A run for each issue opened in the project's tracker from now on, with the issue as its + * payload (`Issue`). Issues that were already there when the workflow was first loaded start + * nothing. `labels` are ones the issue must carry, all of them; `query` is free text for the + * tracker. The tracker is asked about once a minute. + */ +export const issuesOpened = (options: { + readonly project: string; + readonly labels?: ReadonlyArray; + readonly query?: string; +}): Trigger => { + checkOptions("issues.opened", options, ["project", "labels", "query"]); + return { kind: "issues", id: openedId("issues", options), ...options }; +}; + +/** + * A run for each pull request opened against the project's repository from now on, with the pull + * request as its payload (`PullRequest`). `query` is free text for the host. + */ +export const pullRequestsOpened = (options: { + readonly project: string; + readonly query?: string; +}): Trigger => { + checkOptions("pullRequests.opened", options, ["project", "query"]); + return { kind: "pullRequests", id: openedId("pullRequests", options), ...options }; +}; diff --git a/apps/server/src/workflows/workflow.ts b/apps/server/src/workflows/workflow.ts new file mode 100644 index 0000000000000..3359307875999 --- /dev/null +++ b/apps/server/src/workflows/workflow.ts @@ -0,0 +1,897 @@ +// The author-facing primitives. A workflow body is replayed after a restart, so anything that +// touches the world goes through `step`; these are all a body may use. +import * as Cause from "effect/Cause"; +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 Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as SchemaAST from "effect/SchemaAST"; +import * as SqlClient from "effect/sql/SqlClient"; +import { Activity, DurableClock, DurableDeferred, Workflow, WorkflowEngine } from "effect/workflow"; + +import { checkOptions, durationOf } from "./options.ts"; +import { + EngineLink, + forStep, + type InFlight, + type InStep, + KeyValues, + Runs, +} from "./stepServices.ts"; +import { + checkTriggers, + type OpenedTrigger, + type ScheduleTrigger, + type Trigger, + type WebhookTrigger, +} from "./triggers.ts"; +import type { WorkflowAgents } from "./WorkflowAgents.ts"; +import { unavailable, WorkflowForge } from "./WorkflowForge.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; + +/** A step that could not be completed. Its run is paused until someone resumes it. */ +export class StepFailed extends Schema.TaggedError()("StepFailed", { + step: Schema.String, + reason: Schema.String, +}) { + override get message(): string { + return `${this.step}: ${this.reason}`; + } +} + +/** The workflow's own decision to end without a result. */ +export class WorkflowStop extends Schema.TaggedError()("WorkflowStop", { + reason: Schema.String, + /** The run was never for this workflow to do, which lists leave out. */ + skipped: Schema.optional(Schema.Boolean), +}) { + override get message(): string { + return this.reason; + } +} + +/** What the primitives need from the run they are called in. */ +export class RunContext extends Context.Service< + RunContext, + { + readonly runId: string; + readonly workflow: string; + readonly store: WorkflowStore.WorkflowStore["Service"]; + /** Names used so far in this pass over the body: two steps with one name would share a result. */ + readonly names: Set; + /** What the code of the step `name` may use. */ + readonly forStep: (name: string) => Context.Context; + /** The steps running now, which a cancelled run's cleanup waits for. */ + readonly inFlight: InFlight; + } +>()("t3/workflows/workflow/RunContext") {} + +/** What a workflow body may require: the run it is in, the engine, and somewhere to run agents. */ +export type InRun = + | RunContext + | WorkflowAgents + | WorkflowEngine.WorkflowEngine + | WorkflowEngine.WorkflowInstance; + +/** Takes `name` for one step of the run. Step results and the step list are both kept by name. */ +export const claim = (name: string, cleanup = false) => + Effect.flatMap(RunContext, (run) => { + // The cleanup step's name is its own, or a body step would take it and cleanup never run. + if (name === END_STEP && !cleanup) { + return Effect.die( + new Error( + `"${END_STEP}" is the name of workflow ${run.workflow}'s cleanup step. Name this step something else.`, + ), + ); + } + if (run.names.has(name)) { + return Effect.die( + new Error( + `Two steps in workflow ${run.workflow} are named "${name}". Names are unique in a run.`, + ), + ); + } + run.names.add(name); + return Effect.succeed(run); + }); + +/** An error as one line for a person, with what caused it when the error only wraps something. */ +export const text = (error: unknown): string => { + if (typeof error === "string") return error.slice(0, 2000); + if (typeof error !== "object" || error === null) return String(error); + // Also an error that came back from the journal, which is its fields and no longer an Error. + const fields = error as { + readonly message?: unknown; + readonly reason?: unknown; + cause?: unknown; + }; + const message = + typeof fields.message === "string" && fields.message !== "" + ? fields.message + : typeof fields.reason === "string" + ? fields.reason + : "Unknown error"; + return (fields.cause === undefined ? message : `${message}: ${text(fields.cause)}`).slice( + 0, + 2000, + ); +}; + +// What a workflow without `returns` returns: any JSON value, or nothing. +const ANY_JSON = Schema.UndefinedOr(Schema.Json); + +/** Where in `value` JSON cannot hold what it finds, with `undefined` counted only when `strict`. */ +const notJson = (value: unknown, at: string, strict: boolean): string | undefined => { + if (value === null || typeof value === "string" || typeof value === "boolean") return undefined; + if (typeof value === "number") return Number.isFinite(value) ? undefined : `${at} is ${value}`; + if (value === undefined) return strict ? `${at} is undefined` : undefined; + if (Array.isArray(value)) { + for (const [index, item] of value.entries()) { + const found = notJson(item, `${at}[${index}]`, strict); + if (found !== undefined) return found; + } + return undefined; + } + const proto = typeof value === "object" ? Object.getPrototypeOf(value) : undefined; + if (proto !== Object.prototype && proto !== null) { + return `${at} is ${typeof value === "object" ? (proto?.constructor?.name ?? "an object") : `a ${typeof value}`}`; + } + for (const [key, field] of Object.entries(value as object)) { + const found = notJson(field, `${at}.${key}`, strict); + if (found !== undefined) return found; + } + return undefined; +}; + +/** A value that did not encode, said with where JSON could not hold it, which `Schema.Json` omits. */ +const encodeFailure = (what: string, error: unknown, value: unknown) => { + const where = notJson(value, what, true); + return where === undefined ? text(error) : `${text(error)}: ${where}`; +}; + +/** A step result the journal cannot store, which fails the step it came from. */ +const unstorable = (error: unknown, value: unknown) => + Effect.die(new Error(encodeFailure("the result", error, value))); + +/** What a run without `returns` returns, read as `JSON.stringify` reads it. */ +const untypedResult = (value: unknown): Effect.Effect => { + const where = notJson(value, "the run's result", false); + if (where !== undefined) return Effect.die(new Error(`The run's result is not JSON: ${where}.`)); + return Effect.succeed( + value === undefined ? null : (JSON.parse(JSON.stringify(value)) as Schema.Json), + ); +}; + +/** + * One journaled action of the step `name`: it happens once, and a replay returns what it stored. + * A failure marks the step failed and pauses the run here; resuming the run executes it again. + */ +export const journaled = ( + run: RunContext["Service"], + name: string, + action: string, + returns: Schema.Codec, + execute: Effect.Effect, + // The run waits for a person after this fails, not for `resumeAfter`. + held = false, +) => { + const codec = Schema.toCodecJson(returns); + const encodable = Schema.encodeEffect(codec); + return Activity.make({ + name: action, + success: returns, + error: StepFailed, + execute: run.inFlight.track(run.runId, execute).pipe( + // A result the journal cannot store is this step's failure, found before it is journaled. + Effect.tap((value) => Effect.catch(encodable(value), (error) => unstorable(error, value))), + // The engine reads its own 64-bit ids as BigInt. What a step calls must not inherit that. + Effect.provideService(SqlClient.SafeIntegers, false), + // Also a step that dies: left as a defect the engine would park the run without a word. + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause as Cause.Cause) + : Effect.fail(new StepFailed({ step: name, reason: text(Cause.squash(cause)) })), + ), + Effect.tapError((error) => + Effect.andThen( + run.store.stepEnded(run.runId, name, "failed", error.reason), + run.store.runPaused(run.runId, error.message, held), + ), + ), + ), + }); +}; + +/** How an invoked run ended, as its parent's wait receives it. */ +export const ChildEnd = Schema.Struct({ + outcome: Schema.Literals(["completed", "stopped", "skipped", "cancelled"]), + value: Schema.Json, + reason: Schema.optional(Schema.String), +}); + +export interface StepRetry { + /** How many more times to try before the run is paused. */ + readonly times: number; + readonly schedule?: Schedule.Schedule; +} +// Once, unless asked: a step that posts or merges must not do it again after a lost reply. +const DEFAULT_RETRY: StepRetry = { times: 0 }; + +const checkStepOptions = (what: string, options: { readonly retry?: StepRetry | undefined }) => { + checkOptions(what, options, ["returns", "retry"]); + checkOptions(`${what}'s retry`, options?.retry, ["times", "schedule"]); +}; + +/** How `step.try` ended: its value, or why it failed once its retries were used up. */ +export type StepAttempt = + | { readonly outcome: "done"; readonly value: A } + | { readonly outcome: "failed"; readonly reason: string }; + +const attemptOf = (returns: Schema.Codec) => + Schema.Union([ + Schema.Struct({ outcome: Schema.Literal("done"), value: returns }), + Schema.Struct({ outcome: Schema.Literal("failed"), reason: Schema.String }), + ]); + +/** + * Do something once per run. The result is stored, and a replay returns the stored result. + * + * A failure is retried by `retry`, then pauses the run at this step: resuming the run runs the step + * again. Nothing in the body can catch that. For a failure the workflow decides about, use + * `step.try`. + */ +export const step = Object.assign( + ( + name: string, + options: { readonly returns: Schema.Codec; readonly retry?: StepRetry }, + code: Effect.Effect, + ): Effect.Effect => { + checkStepOptions(`step("${name}")`, options); + return Effect.orDie(stepAs(claim(name), name, options, code)); + }, + { + /** As `step`, but a failure left after the retries comes back as `failed` with the reason. */ + try: ( + name: string, + options: { readonly returns: Schema.Codec; readonly retry?: StepRetry }, + code: Effect.Effect, + ): Effect.Effect, never, InRun> => { + checkStepOptions(`step.try("${name}")`, options); + return Effect.orDie( + stepAs( + claim(name), + name, + { returns: attemptOf(options.returns), retry: options.retry }, + code, + (tried) => + tried.pipe( + Effect.map((value): StepAttempt => ({ outcome: "done", value })), + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause as Cause.Cause) + : Effect.succeed>({ + outcome: "failed", + reason: text(Cause.squash(cause)), + }), + ), + ), + ), + ); + }, + }, +); + +const stepAs = ( + claimed: Effect.Effect, + name: string, + options: { readonly returns: Schema.Codec; readonly retry?: StepRetry | undefined }, + code: Effect.Effect, + // What the step makes of its tries: by default their value, or their failure. + settle: (tried: Effect.Effect) => Effect.Effect = (tried) => + tried as unknown as Effect.Effect, +): Effect.Effect => + Effect.flatMap(claimed, (run) => { + const retry = options.retry ?? DEFAULT_RETRY; + const resultCodec = Schema.toCodecJson(options.returns); + const encodeResult = Schema.encodeEffect(resultCodec); + // Made per try, so a retry numbers its signals from the start again and counts as an attempt. + const execute = Effect.andThen( + run.store.stepStarted(run.runId, name, "step"), + Effect.suspend(() => Effect.provideContext(code, run.forStep(name))), + ); + return journaled( + run, + name, + `step/${name}`, + options.returns, + settle( + retry.times === 0 + ? execute + : Effect.retry(execute, { + times: retry.times, + ...(retry.schedule === undefined ? {} : { schedule: retry.schedule }), + }), + ).pipe( + // A value that does not encode fails the step, so it is never marked done first. + Effect.tap((value) => + Effect.flatMap( + Effect.catch(encodeResult(value), (error) => unstorable(error, value)), + (json) => + Effect.andThen( + run.store.stepEnded(run.runId, name, "completed", null), + // For a person reading the run. + Effect.ignore(run.store.stepResult(run.runId, name, json as Schema.Json)), + ), + ), + ), + ), + ); + }); + +/** A sleep that survives a restart. */ +export const sleep = Effect.fn("workflow.sleep")(function* ( + name: string, + duration: Duration.Input, +): Effect.fn.Return { + const length = durationOf(`sleep("${name}")`, duration); + const run = yield* claim(name); + // Listed like any step, with when it wakes, so a run that sleeps for days says so. + yield* Activity.make({ + name: `sleep/${name}/open`, + execute: Effect.gen(function* () { + const wakes = DateTime.addDuration(yield* DateTime.now, length); + yield* run.store.stepStarted(run.runId, name, "sleep"); + yield* run.store.stepDetail(run.runId, name, DateTime.formatIso(wakes)); + yield* run.store.runStatus(run.runId, "waiting", `sleep ${name}`); + }), + }); + // Effect keeps a short sleep in memory, where a restart would start it over. + yield* DurableClock.sleep({ + name: `sleep/${name}`, + duration: length, + inMemoryThreshold: Duration.zero, + }); + yield* Activity.make({ + name: `sleep/${name}/close`, + execute: Effect.andThen( + run.store.stepEnded(run.runId, name, "completed", null), + run.store.runResumed(run.runId), + ), + }); +}); + +export const Woke = Schema.Struct({ expired: Schema.Boolean, value: Schema.Json }); +export const wakeOf = (name: string) => DurableDeferred.make(`wait/${name}`, { success: Woke }); +const finite = [Schema.isFinite()] as const; +// JSON carries a bare `Schema.Number` as a number or the text "Infinity", "-Infinity" or "NaN", +// and that form drops the number's own checks. Whoever writes the value is told a finite number +// with its checks instead. Transformations and recursion keep their own form. +const finiteNumbers = (ast: SchemaAST.AST): SchemaAST.AST => { + if (ast.encoding !== undefined) return ast; + if (SchemaAST.isNumber(ast)) { + return new SchemaAST.Number( + ast.annotations, + ast.checks === undefined ? finite : [...ast.checks, ...finite], + undefined, + ast.context, + ); + } + if (SchemaAST.isObjects(ast)) { + return new SchemaAST.Objects( + ast.propertySignatures.map( + (field) => new SchemaAST.PropertySignature(field.name, finiteNumbers(field.type)), + ), + ast.indexSignatures.map( + (index) => new SchemaAST.IndexSignature(index.parameter, finiteNumbers(index.type)), + ), + ast.annotations, + ast.checks, + undefined, + ast.context, + ast.encodingChecks, + ); + } + if (SchemaAST.isArrays(ast)) { + return new SchemaAST.Arrays( + ast.isMutable, + ast.elements.map(finiteNumbers), + ast.rest.map(finiteNumbers), + ast.annotations, + ast.checks, + undefined, + ast.context, + ast.encodingChecks, + ); + } + if (SchemaAST.isUnion(ast)) { + return new SchemaAST.Union( + ast.types.map(finiteNumbers), + ast.options, + ast.annotations, + ast.checks, + undefined, + ast.context, + ast.encodingChecks, + ); + } + return ast; +}; + +/** What a value must look like, as JSON Schema; `closed` objects turn down keys they do not name. */ +export const jsonSchemaOf = (schema: Schema.Top, closed = false): Record => { + const document = Schema.toJsonSchemaDocument( + Schema.make(finiteNumbers(schema.ast)), + closed ? { onExcessProperty: "error" } : undefined, + ); + return { ...document.schema, $defs: document.definitions } as Record; +}; + +/** `wait`, also as the question a person answers: `request` is what an inbox shows them. */ +export const waitAs = Effect.fn("workflow.wait")(function* ( + kind: "wait" | "ask", + name: string, + options: WaitOptions, +): Effect.fn.Return, StepFailed, InRun> { + return yield* waitClaimed(yield* claim(name), kind, name, options); +}); + +interface WaitOptions { + readonly returns: Schema.Codec; + readonly timeout?: Duration.Input | undefined; + readonly channel?: string | undefined; + readonly request?: Schema.Json | undefined; + /** What the engine looks at to end the wait by itself. */ + readonly watch?: Schema.Json | undefined; +} + +const sameAddress = (left: WorkflowStore.SignalAddress, right: WorkflowStore.SignalAddress) => + "runId" in left + ? "runId" in right && left.runId === right.runId && left.wait === right.wait + : "channel" in right && left.workflow === right.workflow && left.channel === right.channel; + +const waitClaimed = Effect.fnUntraced(function* ( + run: RunContext["Service"], + kind: "wait" | "ask", + name: string, + options: WaitOptions, +): Effect.fn.Return, StepFailed, InRun> { + const here: WorkflowStore.SignalAddress = { runId: run.runId, wait: name }; + const schema = jsonSchemaOf(options.returns); + const codec = Schema.toCodecJson(options.returns); + const decode = Schema.decodeEffect(codec); + const fits = (value: Schema.Json) => Effect.result(decode(value)); + const addresses: ReadonlyArray = + options.channel === undefined + ? [here] + : [here, { workflow: run.workflow, channel: options.channel }]; + // Whatever arrived early is delivered now, checked as this wait reads it. The mail goes only + // after the wake: waking twice is harmless, and losing the signal is not. + const deliverEarly = Effect.fnUntraced(function* ( + wake: ReturnType, + token: DurableDeferred.Token, + ) { + const passed = new Set(); + while (true) { + const early = yield* run.store.mailNext(addresses, passed); + if (early === undefined) return; + const value = WorkflowStore.jsonValue(early.valueJson); + if (Result.isFailure(yield* fits(value))) { + // Kept when it went to a channel: another run, or another version, may read it. + if (sameAddress(early.address, here)) yield* run.store.mailDelete(early.signalId); + passed.add(early.signalId); + continue; + } + const woke = { expired: false, value }; + const outcome = yield* run.store.mailDeliver(early.signalId, run.runId, name, woke); + // Another wait on the same key took that one; there may be a next. + if (outcome === "gone") continue; + // Another signal claimed this wait first: its wake, or the sweep, carries what it claimed. + if (outcome === "claimed") return; + yield* DurableDeferred.succeed(wake, { token, value: woke }); + return; + } + }); + const first = wakeOf(name); + const firstToken = yield* DurableDeferred.token(first); + yield* Activity.make({ + name: `wait/${name}/open`, + execute: Effect.gen(function* () { + const deadline = + options.timeout === undefined + ? null + : DateTime.formatIso( + DateTime.addDuration(yield* DateTime.now, Duration.fromInputUnsafe(options.timeout)), + ); + yield* run.store.stepStarted(run.runId, name, kind); + yield* run.store.waitOpened({ + runId: run.runId, + name, + workflow: run.workflow, + key: options.channel, + token: firstToken, + schemaJson: WorkflowStore.jsonText(schema), + requestJson: options.request === undefined ? null : WorkflowStore.jsonText(options.request), + watchJson: options.watch === undefined ? null : WorkflowStore.jsonText(options.watch), + deadline, + }); + yield* run.store.runStatus(run.runId, "waiting", name); + yield* deliverEarly(first, firstToken); + }), + }); + // A value that fit the wait's JSON Schema can still fail its codec. It was not for this wait, + // so the wait opens again under a fresh wake instead of breaking the run on every replay. + let wake = first; + for (let again = 1; ; again++) { + const woke = yield* DurableDeferred.await(wake); + const value = woke.expired ? undefined : yield* fits(woke.value); + if (value !== undefined && Result.isFailure(value)) { + const problem = `It was signalled with a value it cannot read, and waits again: ${text(value.failure)}`; + wake = wakeOf(`${name}/again/${again}`); + const token = yield* DurableDeferred.token(wake); + const next = wake; + yield* Activity.make({ + name: `wait/${name}/again/${again}`, + execute: Effect.gen(function* () { + yield* run.store.waitReopened(run.runId, name, token); + yield* run.store.stepDetail(run.runId, name, problem.slice(0, 2000)); + yield* deliverEarly(next, token); + }), + }); + continue; + } + yield* Activity.make({ + name: `wait/${name}/close`, + execute: Effect.gen(function* () { + yield* run.store.waitClosed(run.runId, name); + yield* run.store.stepEnded(run.runId, name, "completed", woke.expired ? "timed out" : null); + if (!woke.expired) yield* run.store.stepResult(run.runId, name, woke.value); + yield* run.store.runResumed(run.runId); + }), + }); + return value === undefined ? Option.none() : Option.some(value.success); + } +}); + +/** + * Sleep until something outside signals this wait; `None` when the timeout passes first. + * Addressed by run and wait name, or by `channel` (scoped to the workflow's name) when the sender + * cannot know the run. A signal sent before the wait opened is delivered when it opens. + */ +export const wait = ( + name: string, + options: { + readonly returns: Schema.Codec; + readonly timeout?: Duration.Input; + readonly channel?: string; + }, +): Effect.Effect, never, InRun> => { + checkOptions(`wait("${name}")`, options, ["returns", "timeout", "channel"]); + return Effect.orDie(waitAs("wait", name, options)); +}; + +/** End the run by the workflow's own decision. It ends as `stopped`, which is not a failure. */ +export const stop = (reason: string): Effect.Effect => + Effect.fail(new WorkflowStop({ reason })); + +/** + * End the run because it was not this workflow's to do: a webhook delivery it ignores, a pull + * request it opened itself. It ends as `skipped`, which lists leave out unless asked. Use `stop` + * for a run that did something and then decided to end. + */ +export const skip = (reason: string): Effect.Effect => + Effect.fail(new WorkflowStop({ reason, skipped: true })); + +/** Name the run in lists. Defaults to the workflow's name and the run's key. */ +export const title = ( + value: string, + ...rest: ReadonlyArray +): Effect.Effect => { + // Files are not type-checked, so `title("name", text)` would title the run "name". + if (typeof value !== "string" || rest.length > 0) { + throw new Error("title takes only the text, as in title(`Release ${name}`), and no step name."); + } + return Effect.flatMap(RunContext, (current) => { + // Numbered by how many came before in the body, which a replay walks the same way. + let n = 0; + while (current.names.has(`title/${n}`)) n++; + const name = `title/${n}`; + return Effect.flatMap(claim(name), (run) => + Activity.make({ name, execute: run.store.runTitle(run.runId, value) }), + ); + }).pipe(Effect.orDie); +}; + +// The defaults are every workflow: a registry holds workflows of every payload and result type. +export interface WorkflowDefinition

{ + /** Types only: what a run is started with and what it returns, for `start` and `invoke`. */ + readonly "~types"?: { readonly payload: (payload: P) => void; readonly returns: A }; + readonly name: string; + readonly version: number; + readonly payload: Schema.Codec; + readonly returns: Schema.Codec; + /** How long a paused run rests before it is resumed by itself, per pause in a row. */ + readonly resumeAfter: ReadonlyArray; + readonly triggers: ReadonlyArray; + /** Fails with the reason as text: by here nothing reads the error but a person. */ + readonly onEnd: + | ((payload: never, end: RunEnd) => Effect.Effect) + | undefined; + // The registry holds workflows of every payload type; `workflow` is where the types are checked. + readonly body: ( + payload: never, + run: { readonly id: string }, + ) => Effect.Effect; +} + +/** How a run ended, as its `onEnd` is told. A paused run has not ended. */ +export interface RunEnd { + readonly id: string; + readonly outcome: "completed" | "stopped" | "skipped" | "cancelled"; + readonly reason: string | undefined; +} + +/** + * Run another workflow as part of this one and wait for how it ends. The other run is a run of + * its own, listed and resumable by itself; cancelling this run cancels it. A run that paused has + * not ended, so this waits on while someone resumes it. + */ +export const invoke = ( + name: string, + workflow: WorkflowDefinition, + payload: P, + options?: { readonly key?: string }, +): Effect.Effect< + | { readonly outcome: "completed"; readonly value: A } + | { readonly outcome: "stopped" | "skipped" | "cancelled"; readonly reason: string }, + never, + InRun +> => { + // Files are not type-checked, and a name would start nothing until its first step failed. + if (typeof workflow !== "object" || workflow === null || typeof workflow.name !== "string") { + return Effect.die( + new Error( + `invoke takes the workflow definition, not its name: invoke("${name}", …) was given ${JSON.stringify(workflow)}. Pass what workflow(…) returned.`, + ), + ); + } + checkOptions(`invoke("${name}")`, options, ["key"]); + return Effect.orDie(invokeAs(name, workflow, payload, options)); +}; + +const invokeAs = Effect.fn("workflow.invoke")(function* ( + name: string, + workflow: WorkflowDefinition, + payload: P, + options?: { readonly key?: string }, +): Effect.fn.Return< + | { readonly outcome: "completed"; readonly value: A } + | { readonly outcome: "stopped" | "skipped" | "cancelled"; readonly reason: string }, + StepFailed, + InRun +> { + // Taken before the child starts: a name already used would refuse the wait after the start. + const run = yield* claim(name); + yield* step( + `${name}/start`, + { returns: Schema.String }, + Effect.flatMap(Runs, (runs) => + runs.start(workflow.name, payload, { + version: workflow.version, + idempotencyKey: options?.key ?? `${run.runId}/${name}`, + parent: { runId: run.runId, wait: name }, + }), + ).pipe(Effect.map((started) => started.runId)), + ); + const ended = yield* waitClaimed(run, "wait", name, { returns: ChildEnd }); + if (Option.isNone(ended)) { + return yield* new StepFailed({ step: name, reason: "the wait ended without an outcome" }); + } + if (ended.value.outcome !== "completed") { + return { outcome: ended.value.outcome, reason: ended.value.reason ?? "" }; + } + const returnsCodec = Schema.toCodecJson(workflow.returns); + const decode = Schema.decodeEffect(returnsCodec); + const value = yield* decode(ended.value.value).pipe( + Effect.mapError((error) => new StepFailed({ step: name, reason: text(error) })), + ); + return { outcome: "completed", value: value as A }; +}); + +/** The step `onEnd` runs as. */ +export const END_STEP = "onEnd"; +const END_RETRY: StepRetry = { times: 3, schedule: Schedule.exponential("2 seconds") }; + +const DEFAULT_RESUME_AFTER: ReadonlyArray = [ + "5 minutes", + "20 minutes", + "80 minutes", +]; + +/** + * A workflow: a name, a version, and a body. + * + * A run keeps the version it started with. To change the order of steps or the shape of a stored + * result, register the new body under a higher version and keep the old one registered until its + * runs have ended. + */ +export const workflow = ( + name: string, + options: { + readonly version: number; + readonly payload: Schema.Codec; + readonly returns?: Schema.Codec; + readonly resumeAfter?: ReadonlyArray; + /** What starts a run by itself. Each must give what `payload` takes. */ + readonly triggers?: ReadonlyArray>; + /** + * Runs once when the run ends, however it ends, to give back what the run took: a machine, a + * lock. It gets the payload and the run's id, not the body's values, so name what the run + * takes after its id. It must be safe to run for a run that took nothing. + */ + readonly onEnd?: (payload: P, end: RunEnd) => Effect.Effect; + }, + body: ( + payload: P, + run: { readonly id: string }, + ) => Effect.Effect, +): WorkflowDefinition => { + checkOptions(`workflow("${name}")`, options, [ + "version", + "payload", + "returns", + "resumeAfter", + "triggers", + "onEnd", + ]); + // Read once now, so a duration that does not parse fails the file and not a paused run later. + for (const rest of options.resumeAfter ?? []) + durationOf(`workflow("${name}")'s resumeAfter`, rest); + checkTriggers(name, options.triggers ?? []); + return definitionOf(name, options, body); +}; + +const definitionOf = ( + name: string, + options: Parameters>[1], + body: Parameters>[2], +): WorkflowDefinition => ({ + name, + version: options.version, + // Erased here, once: the registry holds workflows of every payload and result type. + payload: options.payload as Schema.Codec, + // Without a schema the result is whatever JSON the body returned: dropping it would be a + // surprise, and a value that is not JSON pauses the run with the reason. + returns: (options.returns ?? ANY_JSON) as Schema.Codec, + resumeAfter: options.resumeAfter ?? DEFAULT_RESUME_AFTER, + triggers: options.triggers ?? [], + onEnd: + options.onEnd === undefined + ? undefined + : (payload, end) => options.onEnd!(payload, end).pipe(Effect.asVoid, Effect.mapError(text)), + body, +}); + +export const engineTag = (definition: Pick) => + `${definition.name}@${definition.version}`; + +const Outcome = Schema.Struct({ + outcome: Schema.Literals(["completed", "stopped", "skipped"]), + value: Schema.Json, + reason: Schema.optional(Schema.String), +}); + +export const engineWorkflow = (definition: WorkflowDefinition) => + Workflow.make(engineTag(definition), { + payload: { idempotencyKey: Schema.String, input: Schema.Json }, + idempotencyKey: (payload) => payload.idempotencyKey, + success: Outcome, + error: Schema.Union([StepFailed, WorkflowStop]), + // A failure parks the run instead of ending it; only an explicit resume wakes it. + }).annotate(Workflow.SuspendOnFailure, true); +export type EngineWorkflow = ReturnType; + +export const layerDefinition = (definition: WorkflowDefinition, engine: EngineWorkflow) => { + const payloadCodec = Schema.toCodecJson(definition.payload); + const decodePayload = Schema.decodeEffect(payloadCodec); + const returnsCodec = Schema.toCodecJson(definition.returns); + const encodeResult = Schema.encodeUnknownEffect(returnsCodec); + return engine.toLayer((payload, runId) => + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const keyValues = yield* KeyValues; + const link = yield* EngineLink; + const forge = Option.getOrElse(yield* Effect.serviceOption(WorkflowForge), () => unavailable); + yield* Activity.make({ + name: "run/begin", + execute: store.runStarted({ + runId, + workflow: definition.name, + version: definition.version, + engineTag: engineTag(definition), + idempotencyKey: payload.idempotencyKey, + input: payload.input, + }), + }); + const input = (yield* Effect.orDie(decodePayload(payload.input))) as never; + const outcome = yield* definition.body(input, { id: runId }).pipe( + Effect.flatMap((value) => + definition.returns === ANY_JSON + ? untypedResult(value) + : encodeResult(value).pipe( + Effect.mapError( + (error) => + new Error( + `The run's result does not fit its returns: ${encodeFailure("the run's result", error, value)}`, + ), + ), + Effect.orDie, + ), + ), + Effect.map((value): typeof Outcome.Type => ({ + outcome: "completed", + value: (value ?? null) as Schema.Json, + })), + Effect.catchTags({ + WorkflowStop: (stopped) => + Effect.succeed({ + outcome: stopped.skipped === true ? "skipped" : "stopped", + value: null, + reason: stopped.reason, + }), + }), + // A step like any other: a cleanup that fails pauses the run, and resuming tries it again. + Effect.tap((ended) => + definition.onEnd === undefined + ? Effect.void + : stepAs( + claim(END_STEP, true), + END_STEP, + // A cleanup is safe to run again, and has nobody else to try it. + { returns: Schema.Void, retry: END_RETRY }, + definition.onEnd(input, { + id: runId, + outcome: ended.outcome, + reason: ended.reason, + }), + ), + ), + Effect.provideService( + RunContext, + RunContext.of({ + runId, + workflow: definition.name, + store, + names: new Set(), + forStep: (name) => forStep(store, keyValues, link, forge, runId, name), + inFlight: link.inFlight, + }), + ), + ); + yield* Activity.make({ + name: "run/end", + execute: Effect.asVoid( + store.runEnded(runId, outcome.outcome, outcome.reason ?? null, outcome.value), + ), + }); + yield* Activity.make({ + name: "run/told", + execute: Effect.suspend(() => link.current?.ended(runId) ?? Effect.void), + }); + return outcome; + }).pipe( + // A failing step marked the run paused itself. What reaches here otherwise is the body + // breaking outside a step: a duplicate name, a payload that no longer decodes. + Effect.tapCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.void + : Effect.flatMap(WorkflowStore.WorkflowStore, (store) => + store.runPaused(runId, text(Cause.squash(cause))), + ), + ), + ), + ); +}; diff --git a/apps/server/src/workflows/workflowAgent.ts b/apps/server/src/workflows/workflowAgent.ts new file mode 100644 index 0000000000000..03956086b03c8 --- /dev/null +++ b/apps/server/src/workflows/workflowAgent.ts @@ -0,0 +1,442 @@ +// The steps that involve someone else: an agent that returns data, and a person who answers. +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import { identity } from "effect/Function"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; + +import { checkOptions } from "./options.ts"; +import { stepReferences } from "./runReferences.ts"; +import { + claim, + type InRun, + journaled, + jsonSchemaOf, + type StepFailed, + text, + waitAs, +} from "./workflow.ts"; +import type { IssueAddress } from "./WorkflowForge.ts"; +import { + type AgentLaunch, + type AgentModel, + AgentResult, + AgentTurn, + WorkflowAgents, +} from "./WorkflowAgents.ts"; + +/** A thread an agent step ran in, to hand to a later step that should continue it. */ +export interface AgentThread { + readonly threadId: string; + /** The linked environment it is in. Absent for this one. */ + readonly environment?: string | undefined; +} + +const CORRECTIONS = 2; + +export interface AgentOptions extends AgentLaunch { + readonly brief: string; + /** The new thread's title. `: ` by default. */ + readonly title?: string; + readonly returns?: Schema.Codec; + readonly model?: AgentModel; + readonly project?: string; + readonly environment?: string; + readonly thread?: AgentThread; + /** + * The issue this job is about. Its thread shows the issue, and the issue's page lists the + * thread. Only for a thread on this server, not one in a linked `environment`. + */ + readonly issue?: IssueAddress; + /** How long the agent has. Past it the thread is stopped and the step has failed. */ + readonly timeout?: Duration.Input; + /** + * Let the agent end a turn without its `returns` and answer from a later one, as an agent does + * that waits to be woken: by a pull request it watches, by work it left running. Only when + * its thread has done nothing for this long is it asked for the result. Without it, a turn + * that ends without the result is asked at once. + */ + readonly quiet?: Duration.Input; +} + +type Attempt = + | { readonly outcome: "done"; readonly value: A; readonly thread: AgentThread } + | { readonly outcome: "failed"; readonly reason: string; readonly thread?: AgentThread }; + +const AGENT_OPTIONS = [ + "brief", + "returns", + "model", + "project", + "environment", + "thread", + "issue", + "timeout", + "quiet", + "title", + "workspace", + "runtimeMode", + "interactionMode", +]; + +// What only shapes a new thread: a continued one keeps its project, machine, model and modes. +const NEW_THREAD_OPTIONS = [ + "project", + "environment", + "model", + "title", + "workspace", + "runtimeMode", + "interactionMode", +] as const; + +const attempt = Effect.fn("workflow.agent")(function* ( + name: string, + options: AgentOptions, + /** What a failure does: pause the run at this step, or come back as the step's answer. */ + onFailure: "pause" | "return", +): Effect.fn.Return, StepFailed, InRun> { + checkOptions(`agent("${name}")`, options, AGENT_OPTIONS); + if (options.thread !== undefined) { + const shaping = NEW_THREAD_OPTIONS.filter((key) => options[key] !== undefined); + if (shaping.length > 0) { + return yield* Effect.die( + new Error( + `agent("${name}") continues \`thread\`, which keeps how it started. Drop ${shaping.map((key) => `\`${key}\``).join(", ")}.`, + ), + ); + } + } + const run = yield* claim(name); + const agents = yield* WorkflowAgents; + const outputSchema = + options.returns === undefined ? undefined : jsonSchemaOf(options.returns, true); + // Only a turn asked for a result can owe one from a later turn. + const quiet = + options.quiet === undefined || outputSchema === undefined + ? undefined + : Duration.fromInputUnsafe(options.quiet); + const outputCodec = + options.returns === undefined ? undefined : Schema.toCodecJson(options.returns); + const decodeOutput = outputCodec === undefined ? undefined : Schema.decodeEffect(outputCodec); + const threadOf = (turn: AgentTurn): AgentThread => ({ + threadId: turn.threadId, + ...(turn.environment === undefined ? {} : { environment: turn.environment }), + }); + const launch: AgentLaunch | undefined = + options.workspace === undefined && + options.runtimeMode === undefined && + options.interactionMode === undefined + ? undefined + : { + workspace: options.workspace, + runtimeMode: options.runtimeMode, + interactionMode: options.interactionMode, + }; + // What the agent's thread touches, its issue and the pull requests it links, is this step's. + const touches = stepReferences(run.store, run.runId, name); + const start = (key: string, prompt: string, thread: AgentThread | undefined) => + agents + .start({ + key: `${run.runId}/${name}/${key}`, + origin: { runId: run.runId, workflow: run.workflow, step: name }, + title: options.title ?? `${run.workflow}: ${name}`, + // Only the step's own `thread` is refused them; a correction on the thread it made is not. + launch: thread === undefined || thread === options.thread ? launch : undefined, + prompt, + outputSchema, + model: options.model, + project: options.project, + environment: thread === undefined ? options.environment : thread.environment, + thread: thread?.threadId, + issue: options.issue, + }) + .pipe( + Effect.provideContext(touches), + Effect.tap((turn) => + run.store.stepThread( + run.runId, + name, + turn.threadId, + turn.environment ?? null, + turn.turnId, + ), + ), + Effect.flatMap((turn) => + Effect.map(Clock.currentTimeMillis, (startedAt): AgentTurn => ({ ...turn, startedAt })), + ), + // No machine, no project, no link: for a step that takes failure as an answer, that is one. + onFailure === "pause" + ? identity + : Effect.catch((error) => + Effect.succeed({ threadId: "", turnId: "", failed: text(error) }), + ), + ); + const resultOf = (turn: AgentTurn, wait = { quiet }) => + agents + .result(turn, wait) + .pipe( + Effect.provideContext(touches), + onFailure === "pause" + ? identity + : Effect.catch((error) => + Effect.succeed({ ending: "failed", detail: text(error), reply: "" }), + ), + ); + /** The turn's result, or its thread stopped when the step's time is up. */ + const within = Effect.fn("workflow.agent.within")(function* ( + turn: AgentTurn, + startedAt: number | undefined, + ) { + if (options.timeout === undefined || startedAt === undefined) return yield* resultOf(turn); + const limit = Duration.fromInputUnsafe(options.timeout); + const left = startedAt + Duration.toMillis(limit) - (yield* Clock.currentTimeMillis); + const result = yield* resultOf(turn).pipe( + Effect.timeoutOption(Duration.millis(Math.max(0, left))), + ); + if (Option.isSome(result)) return result.value; + // A stop that still fails pauses the run unrecorded, so resuming tries the stop again. A step + // that returns its failure says the turn may still be running. + const stopping = agents + .interrupt({ ...threadOf(turn), turnId: turn.turnId }) + .pipe(Effect.retry({ times: 2 })); + const stop: "stopped" | "ended" | "failed" = yield* onFailure === "pause" + ? stopping + : stopping.pipe(Effect.orElseSucceed(() => "failed" as const)); + const late = `it was not done after ${Duration.format(limit)}`; + if (stop === "ended") { + // The turn ended before it could be stopped, maybe long ago, as a run that resumes late + // finds it. What it left is the answer when it is one. + const ended = yield* resultOf(turn, { quiet: undefined }); + if ( + ended.ending !== "completed" || + outputSchema === undefined || + ended.output !== undefined + ) { + return ended; + } + // Stopping the later turn it may answer from could stop someone else's. + return { + ending: "stopped" as const, + detail: `${late}: its turn ended without its result, and the agent may still be at work on its thread`, + reply: "", + }; + } + return { + ending: "stopped" as const, + detail: `${late}${stop === "stopped" ? "" : ", and its turn could not be stopped"}`, + reply: "", + }; + }); + const done = (round: number, produced: Schema.Json, said?: string) => + journaled( + run, + name, + `agent/${name}/${round}/done`, + Schema.Void, + Effect.all( + [ + run.store.stepEnded(run.runId, name, "completed", null), + run.store.stepResult(run.runId, name, produced, said), + run.store.runResumed(run.runId), + ], + { discard: true }, + ), + ); + + for (let round = 0; ; round++) { + let turn = yield* journaled( + run, + name, + `agent/${name}/${round}/start`, + AgentTurn, + Effect.andThen( + run.store.stepStarted(run.runId, name, "agent"), + start(`${round}`, options.brief, options.thread), + ), + ); + // Counted from the step's first turn, so corrections do not buy more time. + const startedAt = turn.startedAt; + let problem = turn.failed === undefined ? "" : `the agent could not be started: ${turn.failed}`; + let stopped = false; + let died = false; + for (let correction = 0; turn.failed === undefined; correction++) { + const result = yield* journaled( + run, + name, + `agent/${name}/${round}/result/${correction}`, + AgentResult, + Effect.andThen( + run.store.runStatus(run.runId, "waiting", `agent ${name}`), + within(turn, startedAt), + ), + ); + if (result.ending !== "completed") { + stopped = result.ending === "stopped"; + died = result.ending === "failed"; + problem = `the agent's turn was ${stopped ? "stopped" : "cut short"}: ${result.detail}`; + break; + } + if (decodeOutput === undefined) { + yield* done(round, result.reply); + return { outcome: "done", value: result.reply as A, thread: threadOf(turn) }; + } + // What the submitted result got wrong; undefined when nothing was submitted. + let misfit: string | undefined; + if (result.output !== undefined) { + const decoded = yield* Effect.result(decodeOutput(result.output)); + if (Result.isSuccess(decoded)) { + yield* done(round, result.output, result.reply); + return { outcome: "done", value: decoded.success, thread: threadOf(turn) }; + } + misfit = text(decoded.failure); + } + problem = + misfit === undefined + ? "the agent did not return a result: its turn ended with none accepted" + : `the agent's result did not fit: ${misfit}`; + if (correction >= CORRECTIONS) break; + // Back to the same thread: it has the context and only owes the result. + const corrected = yield* journaled( + run, + name, + `agent/${name}/${round}/correct/${correction}`, + AgentTurn, + start( + `${round}/correct/${correction}`, + misfit === undefined + ? "Your turn ended without an accepted result. Do not redo the work: call `t3_submit_output` now with the result of what you did." + : `The result you submitted does not fit: ${misfit}\nDo not redo the work: call \`t3_submit_output\` again with a corrected result.`, + threadOf(turn), + ), + ); + if (corrected.failed !== undefined) { + problem = `${problem}, and it could not be asked again: ${corrected.failed}`; + break; + } + turn = corrected; + } + // The turn may only be out of sight, not dead: it is stopped before another does its work again. + // A stop that does not get through pauses the run unrecorded, or gives up a step that returns. + let lingers = false; + if (died && turn.failed === undefined) { + const lost = turn; + lingers = !(yield* journaled( + run, + name, + `agent/${name}/${round}/stop`, + Schema.Boolean, + agents + .interrupt({ ...threadOf(lost), turnId: lost.turnId }) + .pipe( + Effect.retry({ times: 2 }), + Effect.as(true), + onFailure === "pause" ? identity : Effect.catch(() => Effect.succeed(false)), + ), + )); + if (lingers) problem = `${problem}; its turn could not be stopped`; + } + // A turn that died is not the job's fault the first time: once more, on a thread of its own, + // or on the same thread for a step that continues one, since only that thread has its project. + // Anything else is not tried again behind a person's back: one they stopped, one that never + // started, or one that did its work and would not give its result, which may have acted. + if (round % 2 === 0 && died && !lingers) continue; + if (onFailure === "return") { + yield* journaled( + run, + name, + `agent/${name}/${round}/failed`, + Schema.Void, + Effect.andThen( + run.store.stepEnded(run.runId, name, "failed", problem), + run.store.runResumed(run.runId), + ), + ); + return { + outcome: "failed", + reason: problem, + ...(turn.failed === undefined ? { thread: threadOf(turn) } : {}), + }; + } + // Fails the first time it is reached, which pauses the run here. Resuming the run reaches it + // again, and the next round starts. + yield* journaled( + run, + name, + `agent/${name}/${round}/pause`, + Schema.Void, + Effect.flatMap(run.store.mark(run.runId, `${name}/pause/${round}`), (arrivals) => + arrivals > 1 ? Effect.void : Effect.fail(problem), + ), + // Resuming starts the agent's job again from the top, which is a person's call. + true, + ); + } +}); + +const orPause = ( + name: string, + options: AgentOptions, +): Effect.Effect<{ readonly value: A; readonly thread: AgentThread }, never, InRun> => + Effect.flatMap(Effect.orDie(attempt(name, options, "pause")), (result) => + result.outcome === "done" + ? Effect.succeed({ value: result.value, thread: result.thread }) + : // `pause` never returns a failure: the step fails first, which pauses the run. + Effect.die(new Error(`Agent step ${name} failed without pausing: ${result.reason}`)), + ); + +/** + * An agent doing one job in a thread a person can open. It returns data checked against `returns`, + * or its last message without one. It starts a thread in `project`, in the linked `environment` + * when one is named, or continues `thread` where that is. Past `timeout` it is stopped. A turn + * that dies is tried once more, then the run pauses at this step. + */ +export const agent = Object.assign(orPause, { + /** + * For a workflow that decides for itself what a failed agent means: another model, another + * machine, or stop. An agent that could not be started, died twice, ran out of time or never + * gave its result comes back as `failed` with the reason, and the run goes on. + */ + try: ( + name: string, + options: AgentOptions, + ): Effect.Effect, never, InRun> => Effect.orDie(attempt(name, options, "return")), +}); + +/** + * A question a person answers with one of `choices`; `None` when the timeout passes first. The run + * holds nothing while it waits. `data` is the same facts as the title, for whatever lays the + * question out. + */ +export const ask = >( + name: string, + options: { + readonly title: string; + readonly choices: Choices; + readonly data?: Schema.Json; + readonly timeout?: Parameters[2]["timeout"]; + }, +): Effect.Effect< + Option.Option<{ readonly choice: Choices[number]; readonly reason?: string | undefined }>, + never, + InRun +> => + Effect.suspend(() => { + checkOptions(`ask("${name}")`, options, ["title", "choices", "data", "timeout"]); + return Effect.orDie( + waitAs("ask", name, { + returns: Schema.Struct({ + choice: Schema.Literals(options.choices), + reason: Schema.optional(Schema.String), + }), + timeout: options.timeout, + request: { + title: options.title, + choices: [...options.choices], + ...(options.data === undefined ? {} : { data: options.data }), + }, + }), + ); + }); diff --git a/apps/server/src/workspace/TaskFolders.test.ts b/apps/server/src/workspace/TaskFolders.test.ts index 37fd360cf8b24..2be3e39c09817 100644 --- a/apps/server/src/workspace/TaskFolders.test.ts +++ b/apps/server/src/workspace/TaskFolders.test.ts @@ -248,32 +248,35 @@ it.effect("finds no common folder for two Windows drives instead of climbing for }).pipe(Effect.provide(NodePath.layerWin32)), ); -it.live("gives two creations on one branch a folder each", () => - withState((state) => - Effect.gen(function* () { - const { fileSystem, path, tmp, repository } = yield* fixture; - const api = yield* repository("shop/api"); - state.workspaceRoot = path.join(tmp, "shop"); - state.trackedFolders = tracked(api); +it.live.each([{ projectIsRepository: false }, { projectIsRepository: true }])( + "gives two creations on one branch a folder each, project is a repository=$projectIsRepository", + ({ projectIsRepository }) => + withState((state) => + Effect.gen(function* () { + const { fileSystem, path, tmp, repository } = yield* fixture; + const shop = projectIsRepository ? yield* repository("shop") : path.join(tmp, "shop"); + const api = yield* repository("shop/api"); + state.workspaceRoot = shop; + state.trackedFolders = tracked(api); - // Git gives the branch to one of them; the other's rollback must leave that one's folder. - const exits = yield* Effect.all( - [Effect.exit(create("feature")), Effect.exit(create("feature"))], - { - concurrency: 2, - }, - ); + // Git gives the branch to one of them; the other's rollback must leave that one's folder. + const exits = yield* Effect.all( + [Effect.exit(create("feature")), Effect.exit(create("feature"))], + { + concurrency: 2, + }, + ); - const created = exits.flatMap((exit) => - Exit.isSuccess(exit) ? [exit.value.taskFolder] : [], - ); - assert.isAtLeast(created.length, 1); - assert.equal(new Set(created.map((taskFolder) => taskFolder.root)).size, created.length); - for (const taskFolder of created) { - assert.isTrue(yield* fileSystem.exists(path.join(taskFolder.root, "api", "README.md"))); - } - }), - ), + const created = exits.flatMap((exit) => + Exit.isSuccess(exit) ? [exit.value.taskFolder] : [], + ); + assert.isAtLeast(created.length, 1); + assert.equal(new Set(created.map((taskFolder) => taskFolder.root)).size, created.length); + for (const taskFolder of created) { + assert.isTrue(yield* fileSystem.exists(path.join(taskFolder.root, "api", "README.md"))); + } + }), + ), ); it.live.each([{ projectIsRepository: true }, { projectIsRepository: false }])( @@ -347,6 +350,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..75c12d8a7409b 100644 --- a/apps/server/src/workspace/TaskFolders.ts +++ b/apps/server/src/workspace/TaskFolders.ts @@ -1,4 +1,5 @@ import { + GitCommandError, type ProjectId, type ProjectTrackedFolder, TASK_FOLDER_DEFAULT_REPOSITORIES_MAX, @@ -15,6 +16,7 @@ import { flattenTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; @@ -224,6 +226,8 @@ export const layoutAnchor = ( return { anchor, unreachable }; }; +const isGitCommandError = Schema.is(GitCommandError); + const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -243,6 +247,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; @@ -853,17 +867,27 @@ const make = Effect.gen(function* () { branch: string, startFromOrigin: boolean, baseBranch: string | undefined, + recordBranch: (exit: Exit.Exit) => Effect.Effect, ) { 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({ - cwd: repository.path, - refName: start.refName, - newRefName: branch, - baseRefName: start.baseRefName, - path: worktreePath, - }); + yield* git + .createWorktree({ + cwd: repository.path, + refName: start.refName, + newRefName: branch, + baseRefName: start.baseRefName, + path: worktreePath, + }) + .pipe(Effect.onExit(recordBranch)); return { repository: { repositoryPath: repository.path, @@ -916,15 +940,32 @@ const make = Effect.gen(function* () { // A layout command may check out a branch that was already there; a rollback leaves it. const hadBranch = new Set(); let layoutStarted = false; - // Where this attempt makes the branch: a checkout that fails halfway leaves it behind. - let branchMadeIn = [ + // Where this attempt may make the branch: none of them had it when listed. + const branchMissingIn = new Set([ ...taskPlan.repositories .filter((_, index) => !names[index]!.includes(branch)) .map((repository) => repository.path), ...(taskPlan.projectIsRepository && !projectNames.includes(branch) ? [taskPlan.projectRoot] : []), - ]; + ]); + // Where this attempt made the branch: a checkout that fails halfway leaves it behind. Only + // a checkout it ran counts, and not one Git refused because another creation made it first. + let branchMadeIn: string[] = []; + const recordBranch = + (cwd: string) => + (exit: Exit.Exit) => + Effect.sync(() => { + const refused = + Exit.isFailure(exit) && + exit.cause.reasons.some( + (reason) => + Cause.isFailReason(reason) && + isGitCommandError(reason.error) && + reason.error.operation === "GitVcsDriver.createWorktree.createBranch", + ); + if (branchMissingIn.has(cwd) && !refused) branchMadeIn.push(cwd); + }); return yield* Effect.gen(function* () { yield* fileSystem.makeDirectory(root, { recursive: true }); // Recorded before any checkout, so an interrupted creation is still found and removed. @@ -993,19 +1034,24 @@ const make = Effect.gen(function* () { } if (taskPlan.projectIsRepository) { yield* fileSystem.makeDirectory(path.dirname(empty.projectPath), { recursive: true }); - yield* git.createWorktree( - { - cwd: taskPlan.projectRoot, - refName: input.projectStart.refName, - newRefName: branch, - baseRefName: input.projectStart.baseRefName, - path: empty.projectPath, - }, - input.projectProgress === undefined ? {} : { progress: input.projectProgress }, - ); + yield* git + .createWorktree( + { + cwd: taskPlan.projectRoot, + refName: input.projectStart.refName, + newRefName: branch, + baseRefName: input.projectStart.baseRefName, + path: empty.projectPath, + }, + input.projectProgress === undefined ? {} : { progress: input.projectProgress }, + ) + .pipe(Effect.onExit(recordBranch(taskPlan.projectRoot))); } 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 +1067,29 @@ 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, + recordBranch(repository.path), + ) ).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 +1243,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..806a045898ddc 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -8,8 +8,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { AuthAccessReadScope, + type AuthEnvironmentScope, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, + type WorkflowRun, + type WorkflowStep, AuthSessionId, AuthSourceControlWriteScope, ORCHESTRATION_PROTOCOL_VERSION, @@ -130,7 +133,10 @@ import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolve import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; import * as ReviewService from "./review/ReviewService.ts"; import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; +import * as Workflows from "./workflows/Workflows.ts"; +import * as WorkflowRuntime from "./workflows/WorkflowRuntime.ts"; import * as SecretRequests from "./secrets/SecretRequests.ts"; +import * as FeedbackStore from "./feedback/FeedbackStore.ts"; import * as GuestShareService from "./guest/GuestShareService.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; @@ -165,6 +171,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"; @@ -881,7 +888,10 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(ResourceTelemetry.ResourceTelemetry)({}), Layer.mock(ReviewService.ReviewService)({}), Layer.mock(ScheduledTasks.ScheduledTaskService)({}), + Workflows.layerDisabled, + Layer.mock(WorkflowRuntime.WorkflowDefinitions)({}), Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(FeedbackStore.FeedbackStore)({}), Layer.mock(SecretResolver.SecretResolver)({}), Layer.mock(GuestShareService.GuestShareService)({}), Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({}), @@ -906,6 +916,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(TaskFolders.TaskFolders)({}), Layer.mock(WorkspaceFileSystem.WorkspaceFileSystem)({}), Layer.mock(WorktreeSetupTracker.WorktreeSetupTracker)({}), + FeatureFlags.layerTest(), ); const layerConfigSources = Layer.mergeAll( @@ -2641,3 +2652,161 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i ), ), ); + +const workflowTags = [ + WS_METHODS.workflowsGet, + WS_METHODS.workflowsAnswer, + WS_METHODS.workflowsResume, + WS_METHODS.workflowsCancel, +] as const; +const workflowRpcs = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RpcAuthorization.RPC_REQUIRED_SCOPES, + (typeof workflowTags)[number] + > => !(workflowTags as ReadonlyArray).includes(tag), + ), +); +const workflowRun: WorkflowRun = { + runId: "run-1", + workflow: "release", + version: 1, + title: "Release 1.2", + status: "paused", + detail: "build failed: exit 1", + result: null, + pauses: 1, + retired: false, + resumesAt: null, + parentRunId: null, + parentStep: null, + startedAt: "2026-11-01T00:00:00.000Z", + updatedAt: "2026-11-01T00:01:00.000Z", + endedAt: null, +}; +const workflowStep: WorkflowStep = { + name: "build", + kind: "step", + status: "failed", + attempts: 2, + detail: "exit 1", + threadId: null, + environmentId: null, + result: null, + said: null, + startedAt: "2026-11-01T00:00:10.000Z", + endedAt: "2026-11-01T00:01:00.000Z", +}; + +/** A client for the workflow RPCs whose session holds `scopes`; `calls` records what reached the service. */ +const makeWorkflowClient = Effect.fn("test.makeWorkflowClient")(function* ( + scopes: ReadonlyArray, + calls: Array, +) { + const services = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + Layer.mock(Workflows.Workflows)({ + get: (runId) => + runId === workflowRun.runId + ? Effect.succeed({ run: workflowRun, steps: [workflowStep], references: [] }) + : Effect.fail(new Workflows.WorkflowRunNotFoundError({ runId })), + answer: (runId, name, value) => + Effect.sync(() => calls.push({ answer: [runId, name], value })), + resume: (runId) => Effect.sync(() => calls.push({ resume: runId })), + cancel: (runId, reason) => Effect.sync(() => calls.push({ cancel: runId, reason })), + }), + ); + return yield* RpcTest.makeClient(workflowRpcs).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("workflow-test"), + subject: "workflow-test", + method: "browser-session-cookie", + scopes: [...scopes], + }, + {}, + yield* ServerBrowser.ServerBrowser, + () => Effect.void, + { secretReferences: true }, + ).pipe(Layer.provide(services), Layer.merge(RpcAuthorization.layer(scopes))), + ), + ); +}); +const layerWorkflowRpcTest = Layer.mergeAll( + Layer.fresh(layerConfigSources), + Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}), + Layer.mock(ServerBrowser.ServerBrowser)({}), +); + +it.effect("workflow RPCs read a run and pass an answer, a resume and a cancel to the service", () => + Effect.gen(function* () { + const calls: Array = []; + const client = yield* makeWorkflowClient( + [AuthOrchestrationReadScope, AuthOrchestrationOperateScope], + calls, + ); + + assert.deepEqual(yield* client[WS_METHODS.workflowsGet]({ runId: "run-1" }), { + run: workflowRun, + steps: [workflowStep], + references: [], + }); + const missing = yield* client[WS_METHODS.workflowsGet]({ runId: "gone" }).pipe(Effect.flip); + assert.deepEqual( + [missing._tag, missing.message], + ["WorkflowRequestError", "Workflow run gone was not found."], + ); + + yield* client[WS_METHODS.workflowsAnswer]({ + runId: "run-1", + name: "approve", + choice: "yes", + reason: "Looks good", + }); + yield* client[WS_METHODS.workflowsAnswer]({ runId: "run-1", name: "approve", choice: "no" }); + yield* client[WS_METHODS.workflowsResume]({ runId: "run-1" }); + yield* client[WS_METHODS.workflowsCancel]({ runId: "run-1" }); + yield* client[WS_METHODS.workflowsCancel]({ runId: "run-1", reason: "Wrong branch" }); + + assert.deepEqual(calls, [ + { answer: ["run-1", "approve"], value: { choice: "yes", reason: "Looks good" } }, + { answer: ["run-1", "approve"], value: { choice: "no" } }, + { resume: "run-1" }, + { cancel: "run-1", reason: undefined }, + { cancel: "run-1", reason: "Wrong branch" }, + ]); + }).pipe(Effect.provide(layerWorkflowRpcTest), Effect.scoped), +); + +it.effect("a session that can only read sees a workflow run but cannot steer it", () => + Effect.gen(function* () { + const calls: Array = []; + const client = yield* makeWorkflowClient([AuthOrchestrationReadScope], calls); + + assert.equal((yield* client[WS_METHODS.workflowsGet]({ runId: "run-1" })).run.runId, "run-1"); + const refused = yield* Effect.all([ + client[WS_METHODS.workflowsAnswer]({ runId: "run-1", name: "approve", choice: "yes" }).pipe( + Effect.flip, + ), + client[WS_METHODS.workflowsResume]({ runId: "run-1" }).pipe(Effect.flip), + client[WS_METHODS.workflowsCancel]({ runId: "run-1" }).pipe(Effect.flip), + ]); + assert.deepEqual( + refused.map((error) => error._tag), + Array.from({ length: 3 }, () => "EnvironmentAuthorizationError"), + ); + assert.deepEqual(calls, []); + }).pipe(Effect.provide(layerWorkflowRpcTest), Effect.scoped), +); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index ae5f2def92660..7da83f3950c70 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"; @@ -36,6 +37,7 @@ import { AuthProvidersManageScope, type AuthEnvironmentScope, type ScheduledTaskListResult, + WorkflowRequestError, AuthSessionId, ClientConnectionMethod, ClientDeviceType, @@ -143,7 +145,10 @@ import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts" import * as ThreadMessageIntake from "./orchestration-v2/ThreadMessageIntake.ts"; import * as DocumentText from "./provider/DocumentText.ts"; import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; +import * as Workflows from "./workflows/Workflows.ts"; +import * as WorkflowRuntime from "./workflows/WorkflowRuntime.ts"; import * as SecretRequests from "./secrets/SecretRequests.ts"; +import * as FeedbackStore from "./feedback/FeedbackStore.ts"; import * as GuestShareService from "./guest/GuestShareService.ts"; import { bufferShellLiveStream, @@ -213,6 +218,7 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { makePrepareTerminalLaunch } from "./workspace/restoreMissingWorktree.ts"; import { terminalOutputStream, withOutputWindow } from "./terminal/OutputProtocol.ts"; +import { withSocketHeartbeat } from "./socketHeartbeat.ts"; import * as ServerBrowser from "./preview/ServerBrowser.ts"; import * as DeviceService from "./device/DeviceService.ts"; import { remoteSshDeviceHosts } from "./device/localSshDeviceHost.ts"; @@ -245,6 +251,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"; @@ -1549,7 +1556,13 @@ export const layerWsRpc = ( const threadViewers = yield* ThreadViewers.ThreadViewers; const providerSessionManager = yield* ProviderSessionManager.ProviderSessionManagerV2; const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService; + const workflows = yield* Workflows.Workflows; + const workflowDefinitions = yield* WorkflowRuntime.WorkflowDefinitions; + // The service's messages are built from its own attributes, so they are safe to send. + const toWorkflowRequestError = (error: Workflows.WorkflowError) => + new WorkflowRequestError({ message: error.message }); const secretRequests = yield* SecretRequests.SecretRequests; + const feedbackStore = yield* FeedbackStore.FeedbackStore; const guestShares = yield* GuestShareService.GuestShareService; const pullRequests = yield* PullRequestService.PullRequestService; const issues = yield* IssueService.IssueService; @@ -1597,6 +1610,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; @@ -1984,6 +1998,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 }), @@ -2417,6 +2435,25 @@ export const layerWsRpc = ( ), [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: (input) => providerSessionManager.subscribePromptSuggestion(input.threadId), + [WS_METHODS.workflowsSubscribe]: (_input) => workflows.watch, + [WS_METHODS.workflowsCounts]: (_input) => workflows.counts, + [WS_METHODS.workflowsGet]: (input) => + workflows.get(input.runId).pipe(Effect.mapError(toWorkflowRequestError)), + [WS_METHODS.workflowsAnswer]: (input) => + workflows + .answer(input.runId, input.name, { + choice: input.choice, + ...(input.reason === undefined ? {} : { reason: input.reason }), + }) + .pipe(Effect.mapError(toWorkflowRequestError)), + [WS_METHODS.workflowsResume]: (input) => + workflows.resume(input.runId).pipe(Effect.mapError(toWorkflowRequestError)), + [WS_METHODS.workflowsCancel]: (input) => + workflows.cancel(input.runId, input.reason).pipe(Effect.mapError(toWorkflowRequestError)), + [WS_METHODS.workflowsGetDefinition]: (_input) => workflowDefinitions.read, + [WS_METHODS.workflowsSaveDefinition]: (input) => + workflowDefinitions.save(input.name, input.source), + [WS_METHODS.workflowsDeleteDefinition]: (input) => workflowDefinitions.remove(input.name), [WS_METHODS.scheduledTasksSubscribe]: (_input) => scheduledTasks.subscribeList().pipe(Stream.map(withVisibleWebhookUrls)), [WS_METHODS.scheduledTasksUpsert]: (input) => scheduledTasks.upsert(input), @@ -2444,6 +2481,7 @@ export const layerWsRpc = ( Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen(secretRequests.answer(input)), ), + [WS_METHODS.agentFeedbackAnswerRequest]: (input) => feedbackStore.answer(input), [WS_METHODS.scheduledTasksListWebhookDeliveries]: (input) => Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe( Effect.andThen(scheduledTasks.listWebhookDeliveries(input)), @@ -2452,7 +2490,8 @@ export const layerWsRpc = ( Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe( Effect.andThen(scheduledTasks.getWebhookDelivery(input)), ), - [WS_METHODS.serverProbe]: (_input) => Effect.succeed({}), + [WS_METHODS.serverProbe]: (_input) => + Effect.map(DateTime.now, (now) => ({ serverTime: DateTime.formatIso(now) })), [WS_METHODS.serverGetConfig]: (_input) => loadServerConfig({ usageLimitsCommand: false, @@ -2790,8 +2829,7 @@ export const layerWsRpc = ( [WS_METHODS.peerLinksNames]: (_input) => peerLinks.names.pipe(Effect.map((links) => ({ links }))), [WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input), - [WS_METHODS.peerLinksUnlink]: ({ environmentId }) => - peerLinks.unlink(environmentId).pipe(Effect.map((removed) => ({ removed }))), + [WS_METHODS.peerLinksUnlink]: ({ environmentId }) => peerLinks.unlink(environmentId), [WS_METHODS.peerLinksSubscribeThread]: (input) => peerThreadRelay.subscribe(input), [WS_METHODS.peerLinksThreadHistoryPage]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( @@ -3328,9 +3366,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.vcsListCommitGraph]: (input) => gitWorkflow.listCommitGraph(input), [WS_METHODS.vcsCreateWorktree]: (input) => @@ -3366,7 +3408,8 @@ export const layerWsRpc = ( Effect.flatMap((removed) => removed ? Effect.void : gitWorkflow.removeWorktree(input), ), - Effect.tap(() => refreshGitStatus(input.cwd)), + // No project-root refresh here: the client awaits vcs.refreshStatus right after, and a + // second refresh would queue behind this one and reread an unchanged repository. // Subscribers of the removed checkout learn it is no longer a repository. Effect.tap(() => vcsStatusBroadcaster @@ -3375,19 +3418,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), @@ -3939,20 +3985,21 @@ export const layer = Layer.unwrap( ), ), ); - const framedRpcWebSocketHttpEffect = url.value.searchParams.has( - SOCKET_FRAME_PARTS_QUERY_PARAM, - ) - ? rpcWebSocketHttpEffect.pipe( - Effect.provideService( - HttpServerRequest.HttpServerRequest, - // The RPC server upgrades the request itself, so its socket is - // wrapped through the request it reads. - Object.create(request, { - upgrade: { value: Effect.map(request.upgrade, splitLargeSocketFrames) }, - }), - ), - ) - : rpcWebSocketHttpEffect; + const splitFrames = url.value.searchParams.has(SOCKET_FRAME_PARTS_QUERY_PARAM); + const framedRpcWebSocketHttpEffect = rpcWebSocketHttpEffect.pipe( + Effect.provideService( + HttpServerRequest.HttpServerRequest, + // The RPC server upgrades the request itself, so its socket is + // wrapped through the request it reads. + Object.create(request, { + upgrade: { + value: Effect.map(request.upgrade, (socket) => + withSocketHeartbeat(splitFrames ? splitLargeSocketFrames(socket) : socket), + ), + }, + }), + ), + ); return yield* Effect.acquireUseRelease( sessions.markConnected(session.sessionId), () => 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 9dae691d6b23f..fbce1c3058e6a 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,25 +75,16 @@ "jszip": "3.10.1", "katex": "^0.18.2", "lucide-react": "^0.564.0", - "mdast-util-from-markdown": "^2.0.3", - "mermaid": "^12.0.0", - "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": { @@ -103,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/react-test-renderer": "^19.3.0", @@ -114,7 +106,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", "react-test-renderer": "19.3.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..b0aa293812d6d 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); + }, }; }); @@ -94,6 +90,17 @@ vi.mock(import("../state/filesystem"), async (original) => { : actual.useFilesystemReadAccess(environmentId)) as never, }; }); +const threadWorktrees = vi.hoisted(() => new Map()); +vi.mock(import("../state/entities"), async (original) => { + const actual = await original(); + return { + ...actual, + readThreadShell: ((ref: { threadId: string }) => { + const worktreePath = threadWorktrees.get(ref.threadId); + return worktreePath === undefined ? actual.readThreadShell(ref as never) : { worktreePath }; + }) as never, + }; +}); vi.mock(import("../remoteOpen"), async (original) => ({ ...(await original()), useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never, @@ -174,6 +181,7 @@ function setup() { parsedSources.length = 0; settingsOverrides.mathRenderingEnabled = false; renderDiagram.mockReset(); + threadWorktrees.clear(); workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] })); filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] })); } @@ -188,7 +196,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 +209,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 +320,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 +395,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(); @@ -536,6 +571,27 @@ describe("ChatMarkdown workspace file opens", () => { expect(workspaceSearch).toHaveBeenCalledOnce(); }); + it("opens a path from markdown rendered in another checkout under that checkout", async () => { + setup(); + const scratchThread = { ...threadRef, threadId: ThreadId.make("scratch-thread") }; + threadWorktrees.set(scratchThread.threadId, "/scratch/thread"); + filesystemMetadata.mockResolvedValue(AsyncResult.success({ entries: [{ kind: "file" }] })); + using openFile = vi.spyOn(useRightPanelStore.getState(), "openFile"); + await using screen = await renderText("[State](packages/state/filesystem.ts)", { + cwd: "/repo-a", + threadRef: scratchThread, + }); + await act(async () => screen.container.querySelector("a")!.click()); + + await vi.waitFor(() => + expect(openFile).toHaveBeenCalledExactlyOnceWith( + scratchThread, + "/repo-a/packages/state/filesystem.ts", + undefined, + ), + ); + }); + it.each([ ["its own panel", "thread-own-panel", false], ["its parent's panel from a side chat", "thread-side-chat", true], @@ -802,12 +858,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 +880,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 +941,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 4e6339889d250..89b08b7b60aeb 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 { @@ -24,17 +24,7 @@ import { import { parseThreadLinkHref as parseForkThreadLinkHref } from "@t3tools/shared/threadOrchestration"; import { ThreadLinkChip } from "./threadOrchestration/ThreadLinkChip"; import { pullRequestMediaResource } from "./pullRequest/pullRequestMediaResource"; -// Fork: upstream's shared pipeline plus rich markdown (math, mermaid). -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - CHAT_MARKDOWN_REHYPE_PLUGINS, - chatMarkdownImageSource, - decodeMarkdownLinkEscapes, - remarkAssistantInsights, -} from "./richMarkdown/chatMarkdownPipeline"; -// Fork: math and mermaid diagrams. -import { RICH_MARKDOWN_COMPONENTS } from "./richMarkdown/RichMarkdownComponents"; +import { chatMarkdownImageSource } from "./richMarkdown/chatMarkdownPipeline"; import { useAtomValue } from "@effect/atom-react"; import { COMPOSER_CONTEXT_CLIPBOARD_MIME, @@ -100,27 +90,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, @@ -137,7 +117,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"; @@ -224,8 +204,17 @@ 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 { MarkdownMermaidCodeBlock } from "./richMarkdown/RichMarkdownComponents"; import { MarkdownTable } from "./chat/MarkdownTable"; import { MarkdownDetails } from "./chat/MarkdownDetails"; import { @@ -240,9 +229,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, @@ -278,8 +265,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. */ @@ -299,7 +286,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, @@ -433,19 +420,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; @@ -453,7 +450,7 @@ function markdownUrlTransform(href: string) { if (parseThreadLinkHref(href) || parseForkThreadLinkHref(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 = []; @@ -496,11 +493,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): href is string => @@ -515,7 +517,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( @@ -541,27 +583,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(); @@ -759,7 +804,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 = ( @@ -852,9 +897,10 @@ function useChatMarkdownState({ } const query = workspaceLinkLookupQuery(workspaceRelativePath, cwd); if (query === null) return null; + const basenameLookup = needsWorkspaceBasenameLookup(workspaceRelativePath); // Search can be truncated or still scanning, so it cannot rule out the literal // path. A path with a folder opens as written whenever it exists. - if (!needsWorkspaceBasenameLookup(workspaceRelativePath)) { + if (!basenameLookup) { const metadata = await getFilesystemMetadata({ environmentId, input: { paths: [resolveWorkspaceFilePath(workspaceRelativePath, cwd)] }, @@ -889,34 +935,48 @@ function useChatMarkdownState({ const agentRoots = (agentDirectories?.() ?? []).filter((root) => root !== cwd); if (otherRoots.length === 0 && agentRoots.length === 0) return null; // Another project's file never replaces a thread-local file the search missed. - if (needsWorkspaceBasenameLookup(workspaceRelativePath)) { + if (basenameLookup) { const metadata = await getFilesystemMetadata({ environmentId, input: { paths: [resolveWorkspaceFilePath(workspaceRelativePath, cwd)] }, }); if (metadata._tag !== "Success" || metadata.value.entries[0] !== null) return null; } - const projectMatch = pickProjectLinkMatch( - workspaceRelativePath, - await Promise.all(otherRoots.map(searchRoot)), - ); + const projectSearches = await Promise.all(otherRoots.map(searchRoot)); + const projectMatch = pickProjectLinkMatch(workspaceRelativePath, [own, ...projectSearches]); if (projectMatch !== null || agentRoots.length === 0) return projectMatch; - // No project has the file, so it opens where the agent last worked, as written. + // An unresolved project lookup falls back to the agent's working directories. const agentPaths = agentRoots.map((root) => resolveWorkspaceFilePath(workspaceRelativePath, root), ); const metadata = await getFilesystemMetadata({ environmentId, input: { paths: agentPaths } }); if (metadata._tag !== "Success") return null; const literal = agentPaths.find((_, index) => metadata.value.entries[index]?.kind === "file"); - if (literal !== undefined || !needsWorkspaceBasenameLookup(workspaceRelativePath)) { + if (literal !== undefined || !basenameLookup) { return literal ?? null; } return findAgentDirectoryMatch(workspaceRelativePath, agentRoots, searchRoot); }; const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => { if (!threadRef) return; + // The panel reads relative paths from the thread's folder. A pull request body's `cwd` is the + // checkout of its repository, which can be another folder. + const shell = readThreadShell(threadRef); + const panelRoot = + shell?.worktreePath ?? + projects.find( + (project) => project.environmentId === environmentId && project.id === shell?.projectId, + )?.workspaceRoot; const openAt = (path: string) => - useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line); + useRightPanelStore + .getState() + .openFile( + threadRef, + cwd && panelRoot !== undefined && cwd !== panelRoot + ? resolveWorkspaceFilePath(path, cwd) + : path, + fileLinkMeta.line, + ); if ( fileLinkMeta.workspaceLookupPath === null || !cwd || @@ -1107,7 +1167,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 ( ); } @@ -1538,12 +1597,7 @@ const CHAT_MARKDOWN_COMPONENTS = { if (issuePreviewTarget !== null) { return ; } - return ( - - - {href} - - ); + return ; } const label = nodeToPlainText(children); @@ -1565,18 +1619,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 = @@ -1809,15 +1854,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) { @@ -1825,15 +1864,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; +} satisfies MarkdownComponents; -const combinedPlugins = new WeakMap>(); +const markdownOptions = new WeakMap>(); -// One combined list per pair, so a stable extra list shares a renderer and its parse cache. -const INSIGHT_REMARK_PLUGINS: PluggableList = [remarkAssistantInsights]; - -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({ @@ -1975,51 +2096,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 ( @@ -2035,22 +2133,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..b6e473521fc92 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: () => {}, @@ -147,10 +163,23 @@ it("opens a linked Linear issue from an inactive thread's sidebar badge", async title: "Keep tabs visible", }; const grouped = threadWithHistory("issue-grouped", 1); + const asWorking = (thread: Thread): Thread => ({ + ...thread, + runs: thread.runs.map((run, index) => + index === thread.runs.length - 1 + ? { ...run, status: "running" as const, completedAt: null } + : run, + ), + items: thread.items.map((item, index) => + index === thread.items.length - 1 + ? { ...item, status: "running" as const, completedAt: null, streaming: true } + : item, + ), + }); using _environment = installFakeEnvironment([ first, - { ...linked, issues: [issue] }, - { ...grouped, issues: [completed, issue] }, + asWorking({ ...linked, issues: [issue] }), + asWorking({ ...grouped, issues: [completed, issue] }), ]); const liveTitle = "Add keyboard shortcuts to the sidebar"; using _detail = answerRpc(WS_METHODS.issuesDetail, (input: IssueRef) => { @@ -202,6 +231,7 @@ it("opens a linked Linear issue from an inactive thread's sidebar badge", async __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + sidebarWorkingShelfEnabled: false, }); await page.viewport(1400, 900); const router = getRouter( @@ -393,7 +423,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 +435,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 +465,139 @@ 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("a file picked after the phone composer collapses still attaches", async () => { + const thread = threadWithHistory("thread-40993", 1); + using _environment = installFakeEnvironment([thread]); + await page.viewport(390, 844); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + using _uploads = acceptAttachmentUploads(); + const editor = page.getByTestId("composer-editor"); + await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible(); + await userEvent.click(editor); + await expect.element(page.getByRole("button", { name: "Attach files" })).toBeVisible(); + const input = document.querySelector( + 'form[data-chat-composer-form] input[type="file"]', + ); + expect(input).not.toBeNull(); + + // Opening the native picker blurs the editor, which collapses the phone composer. + (editor.element() as HTMLElement).blur(); + await expect.element(page.getByRole("button", { name: "Attach files" })).not.toBeInTheDocument(); + const files = new DataTransfer(); + files.items.add(new File([PNG], "picked.png", { type: "image/png" })); + input!.files = files.files; + input!.dispatchEvent(new Event("change", { bubbles: true })); + + await expect.element(page.getByRole("img", { name: "picked.png" })).toBeVisible(); +}); + 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]); @@ -810,6 +970,14 @@ it("a subagent tab shows its read-only bar under no header of its own", async () const subagent = { ...threadWithHistory("subagent-child", 1), providerSubagentOf: parent.id, + creationSource: "provider" as const, + lineage: { + rootThreadId: parent.id, + parentThreadId: parent.id, + relationshipToParent: "subagent" as const, + forkedFrom: null, + sideChat: false, + }, olderSettled: true as const, }; await page.viewport(1400, 900); @@ -831,7 +999,7 @@ it("a subagent tab shows its read-only bar under no header of its own", async () const pane = screen.getByTestId("side-thread-pane"); // No header of its own: the tab names it, and only a side chat has actions to put in one. await expect.element(pane.getByRole("heading", { name: subagent.title })).not.toBeInTheDocument(); - await expect.element(pane.getByText("Runs on its own")).toBeVisible(); + await expect.element(pane.getByLabelText("Subagent")).toBeVisible(); await expect.element(pane.getByRole("button", { name: "Add to chat" })).not.toBeInTheDocument(); await expect .element(screen.getByRole("textbox", { name: `Message ${subagent.title}`, exact: true })) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 3035ebd2503a9..539b35542b8dd 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"; @@ -105,10 +107,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 { @@ -263,6 +264,7 @@ import { type ComposerFileAttachment, type ComposerImageAttachment, type DraftThreadEnvMode, + composerTargetKey, useComposerDraftStore, DraftId, } from "../composerDraftStore"; @@ -988,6 +990,20 @@ export default function ChatView(props: ChatViewProps) { }, }; } + // An agent step of a workflow run leads back to the run, which is where its work is read. + const workflowRun = activeThread?.workflowRun ?? null; + if (workflowRun !== null) { + return { + title: `${workflowRun.workflow} · ${workflowRun.step}`, + relation: { label: gt("Step of the workflow run"), actionLabel: gt("Open run") }, + open: (): void => { + void navigate({ + to: "/workflows", + search: { env: workflowRun.environmentId, run: workflowRun.runId }, + }); + }, + }; + } if (delegatedFrom === null || delegatedFromRef === null) return null; const parentRef = delegatedFromRef; return { @@ -1099,6 +1115,11 @@ export default function ChatView(props: ChatViewProps) { recovery: activeThreadShell?.limitRecovery, snoozedUntil: activeThreadShell?.snoozedUntil, }); + // The run whose limit rows client-runtime hides (deriveUsageLimitNoticeRows). + const usageLimitRunId = + serverRuntime?.status === "failed" && serverRuntime.lastErrorClass === "usage_limit" + ? (serverLatestRun?.runId ?? null) + : null; const timelineThreadError = limitRecoveryRun !== null && visibleThreadError === serverRuntime?.lastError ? null @@ -1558,12 +1579,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, @@ -2713,7 +2732,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 = () => { @@ -2824,6 +2852,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, @@ -2833,6 +2869,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...heldSendItems, ...systemComposerBannerItems, ]; } @@ -2844,6 +2881,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...heldSendItems, ...systemComposerBannerItems, branchMismatchBannerItem( { @@ -3136,7 +3174,7 @@ export default function ChatView(props: ChatViewProps) { scrollToEnd, setThreadError, }); - const { onSend } = useComposerSend({ + const { onSend, captureDetachedSend } = useComposerSend({ environmentId, routeThreadKey, currentRouteThreadKeyRef, @@ -3726,6 +3764,7 @@ export default function ChatView(props: ChatViewProps) { listRef={legendListRef} runs={serverProjection?.runs ?? []} latestRun={activeActivityRun} + usageLimitRunId={usageLimitRunId} announcedRun={announcedRun(activeActivityRun, serverProjection?.runs ?? [])} detailBehindShell={isDetailBehindShell( activeLatestRun, @@ -3914,7 +3953,7 @@ export default function ChatView(props: ChatViewProps) { isLocalDraftThread && activeProject === null } phase={phase} - canSteer={!compactionBlocksSteer} + canSteer={canSteer} canInterrupt={canInterruptRunningThread} isSendBusy={ (isSendBusy && !sendQueuesBehindSetup) || @@ -4011,6 +4050,7 @@ export default function ChatView(props: ChatViewProps) { onPageScrollRelease={onComposerPageScrollReleaseStable} onCompactContext={onComposerCompactContextStable} onSend={onComposerSendStable} + captureDetachedSend={captureDetachedSend} onResume={onComposerResumeStable} onInterrupt={onInterruptStable} onSelectActivePendingUserInputOption={ @@ -4036,9 +4076,15 @@ export default function ChatView(props: ChatViewProps) { onExpandImage={onExpandTimelineImageStable} onFileOpen={openFileAttachmentStable} editingQueuedAttachments={queuedRunEdit.editingAttachments} + removedEditingQueuedAttachments={ + queuedRunEdit.removedEditingAttachments + } onRemoveEditingQueuedAttachment={ queuedRunEdit.removeEditingAttachment } + onRestoreEditingQueuedAttachment={ + queuedRunEdit.restoreEditingAttachment + } /> )} diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 25e5ee852fe69..5455d0446754e 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -86,6 +86,7 @@ import { SquarePenIcon, TextSearchIcon, UserPlusIcon, + WorkflowIcon, } from "lucide-react"; import { openThreadFind } from "./chat/threadFindStore"; import { dispatchPreviewAction } from "./preview/previewActionBus"; @@ -136,6 +137,7 @@ import { useAtomCommand } from "../state/use-atom-command"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useAtomQueryRunner } from "../state/use-atom-query-runner"; import { useScratchProject } from "../hooks/useScratchProject"; +import { useWorkflowEnvironmentIds } from "./workflows/useWorkflowEnvironmentIds"; import { useStartTriage } from "../hooks/useStartTriage"; import { pickTriageEnvironment } from "../lib/triageTarget"; import { useNewProject } from "../hooks/useNewProject"; @@ -532,6 +534,7 @@ function OpenCommandPaletteDialog(props: { : null; const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(referenceThreadRef); const serverConfigs = useServerConfigs(); + const workflowsReachable = useWorkflowEnvironmentIds().length > 0; const activeThreadServerConfig = serverConfigs.get( activeThread?.environmentId ?? ("" as EnvironmentId), ); @@ -1426,7 +1429,7 @@ function OpenCommandPaletteDialog(props: { kind: "action", value: "action:open-git-graph", searchTerms: ["git", "graph", "commits", "history", "branches", "log"], - title: "Open Git graph", + title: gt("Open Git graph"), icon: , shortcutCommand: "gitGraph.open", run: async () => { @@ -1454,7 +1457,7 @@ function OpenCommandPaletteDialog(props: { kind: "action", value: "action:open-agent-stage", searchTerms: ["agent", "stage", "visual", "sprites", "subagents"], - title: "Open agent stage", + title: gt("Open agent stage"), icon: , run: async () => { useRightPanelStore @@ -1836,6 +1839,19 @@ function OpenCommandPaletteDialog(props: { }, }); + if (workflowsReachable) { + actionItems.push({ + kind: "action", + value: "action:workflows", + searchTerms: ["workflows", "workflow", "runs", "automation", "definitions", "schedule"], + title: gt("Open workflows"), + icon: , + run: async () => { + await navigate({ to: "/workflows" }); + }, + }); + } + actionItems.push({ kind: "action", value: "action:usage", @@ -2458,7 +2474,7 @@ function OpenCommandPaletteDialog(props: { cloneDirectoryName: pinnedCloneDirectoryName, caseSensitive: !isWindowsPlatform(browseEnvironmentPlatform), }) - : appendBrowsePathSegment(query, name); + : appendBrowsePathSegment(browsePath.directoryPath, name); await browseNavigation.run( () => prefetchBrowsePath(getBrowseDirectoryPath(nextQuery)), () => { @@ -2876,7 +2892,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..230603dfe46dd 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,66 @@ it("reopens a long draft scrolled to its caret without taking focus", async () = expect(caret.bottom).toBeLessThanOrEqual(scroller.getBoundingClientRect().bottom - 48 + 1); }); +it.each(["none", "caret", "selection"] as const)( + "keeps the reading position when a draft rewraps (focus: %s)", + async (focus) => { + const focused = focus !== "none"; + const value = "A long wrapped paragraph should keep the sentence being read in view. ".repeat( + 100, + ); + const style = document.head.appendChild(document.createElement("style")); + style.textContent = ".composer-tiptap { width: 700px; max-height: 160px; overflow-y: auto; }"; + using _style = { [Symbol.dispose]: () => style.remove() }; + await using screen = await mountEditor(value); + const { editor } = screen; + const scroller = editor.view.dom; + await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(500)); + if (focused) await focusAt(editor, 2000); + scroller.scrollTop = 300; + scroller.dispatchEvent(new Event("scroll")); + const box = scroller.getBoundingClientRect(); + const position = editor.view.posAtCoords({ + left: box.left + box.width / 2, + top: box.top + 25, + })!; + const before = editor.view.coordsAtPos(position.pos).top - box.top; + if (focused) await focusAt(editor, position.pos); + if (focus === "selection") { + editor.commands.setTextSelection({ from: position.pos, to: position.pos + 20 }); + } + document.dispatchEvent(new Event("selectionchange")); + const selection = editor.state.selection.toJSON(); + for (const width of [420, 700]) { + // The panel toggle shortcut reaches the focused editor before the width changes. + if (focused) { + scroller.dispatchEvent( + new KeyboardEvent("keydown", { key: "b", ctrlKey: true, altKey: true, bubbles: true }), + ); + } + scroller.style.width = `${width}px`; + await vi.waitFor(() => { + const after = + editor.view.coordsAtPos(position.pos).top - scroller.getBoundingClientRect().top; + expect(Math.abs(after - before)).toBeLessThan(25); + }); + expect(editor.state.selection.toJSON()).toEqual(selection); + expect(editor.view.hasFocus()).toBe(focused); + } + }, +); + +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 +1267,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..8ce568c117dce 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"; @@ -63,6 +64,7 @@ import { pastedPathQueryLength, } from "~/composer-logic"; import { useStableCallback } from "~/hooks/useStableCallback"; +import { preserveReadingPosition } from "~/lib/preserveReadingPosition"; import { caretLineDirection, ComposerTextDirectionExtension } from "~/composer-text-direction"; import { collapseShownMarkdownSource, @@ -202,6 +204,8 @@ export interface ComposerPromptEditorProps { contextIds: string[], /** False when only the caret or selection moved. */ textChanged: boolean, + /** True when the change came from undo or redo. */ + fromHistory?: boolean, ) => void; onVisibleSelectionChange?: () => void; onCommandKeyDown?: (key: string, event: KeyboardEvent, isTaskItem?: boolean) => boolean; @@ -876,7 +880,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, @@ -1123,6 +1130,7 @@ function ComposerPromptEditorTiptapInner( suppressTrigger, contextIds, previousSnapshot.value !== nextValue, + isHistoryTransaction(transaction), ); }; @@ -1758,6 +1766,11 @@ function ComposerPromptEditorTiptapInner( if (replacements.length > 0) replaceSkillChips(editor, replacements); }, [editor, literalText, modelKeys, skills]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the mounted editor's visible text anchored while its DOM width changes + useLayoutEffect(() => { + if (editor) return preserveReadingPosition(editor.view.dom); + }, [editor]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores ProseMirror focus and caret scroll when the keyed editor remounts, capturing focus on teardown useLayoutEffect(() => { if (!editor) return; @@ -1920,12 +1933,13 @@ function ComposerPromptEditorTiptapInner(
{ if ( event.key === "Control" || @@ -1970,7 +1984,7 @@ function ComposerPromptEditorTiptapInner( {isEmpty && contextRecords.size === 0 && placeholder ? (
diff --git a/apps/web/src/components/CustomSnoozeDialog.tsx b/apps/web/src/components/CustomSnoozeDialog.tsx index 727a55f96fd23..f9c5c9423cbbf 100644 --- a/apps/web/src/components/CustomSnoozeDialog.tsx +++ b/apps/web/src/components/CustomSnoozeDialog.tsx @@ -13,6 +13,7 @@ import { CalendarIcon, Settings2Icon } from "lucide-react"; import { Calendar } from "./ui/calendar"; import { weekStartsOn } from "../timestampFormat"; import { useNowMinute } from "../hooks/useNowMinute"; +import { useFormattingLocale } from "../i18n/I18nProvider"; import { Popover, PopoverTrigger, PopoverPopup } from "./ui/popover"; import { Input } from "./ui/input"; import { Label } from "./ui/label"; @@ -65,6 +66,7 @@ export function CustomSnoozeDialogHost() { function CustomSnoozeDialog() { const gt = useGT(); + const locale = useFormattingLocale(); const id = useId(); const navigate = useNavigate(); const [initial] = useState(() => new Date(Date.now() + 3_600_000)); @@ -148,7 +150,7 @@ function CustomSnoozeDialog() { /> } > - {date.toLocaleDateString(undefined, { + {date.toLocaleDateString(locale, { month: "short", day: "numeric", year: "numeric", diff --git a/apps/web/src/components/ProjectCloneToastCoordinator.tsx b/apps/web/src/components/ProjectCloneToastCoordinator.tsx index 846644c537a12..778c195e2d29e 100644 --- a/apps/web/src/components/ProjectCloneToastCoordinator.tsx +++ b/apps/web/src/components/ProjectCloneToastCoordinator.tsx @@ -45,6 +45,8 @@ interface TrackedToast { readonly toastId: ReturnType; readonly renderedKey: string; readonly phase: ProjectCloneSnapshot["phase"]; + readonly startedAt: ProjectCloneSnapshot["startedAt"]; + readonly closed?: true; } function renderKey(clone: ProjectCloneSnapshot): string { @@ -98,6 +100,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI seen.add(clone.projectId); const key = renderKey(clone); const tracked = toasts.current.get(clone.projectId); + const sameAttempt = tracked?.startedAt === clone.startedAt; const name = projectCloneDisplayName(clone); const closeToast = () => { const current = toasts.current.get(clone.projectId); @@ -111,7 +114,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } - if (tracked?.renderedKey === key) continue; + if (sameAttempt && tracked.renderedKey === key) continue; if ( isProjectCloneToastSilenced(ref) && (clone.phase === "running" || clone.phase === "done") @@ -119,6 +122,34 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } + if ( + sameAttempt && + tracked.closed && + (tracked.phase !== "running" || clone.phase !== "failed") + ) { + continue; + } + + const showToast = (options: ReturnType) => { + const rendered = { renderedKey: key, phase: clone.phase, startedAt: clone.startedAt }; + if (tracked && !tracked.closed) { + toastManager.update(tracked.toastId, options); + toasts.current.set(clone.projectId, { toastId: tracked.toastId, ...rendered }); + return; + } + + const toastId = toastManager.add({ + ...options, + // Updates to a closing toast are ignored, even before it has been removed. + onClose: () => { + const current = toasts.current.get(clone.projectId); + if (current?.toastId === toastId) { + toasts.current.set(clone.projectId, { ...current, closed: true }); + } + }, + }); + toasts.current.set(clone.projectId, { toastId, ...rendered }); + }; if (clone.phase === "running") { const options = stackedThreadToast({ @@ -136,13 +167,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "running" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "running" }); - } + showToast(options); continue; } @@ -161,13 +186,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "done" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "done" }); - } + showToast(options); continue; } @@ -199,13 +218,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: clone.phase }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: clone.phase }); - } + showToast(options); } for (const [projectId, tracked] of toasts.current) { 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/RightPanelTabs.keyboard.browser.test.tsx b/apps/web/src/components/RightPanelTabs.keyboard.browser.test.tsx index 3de4b480f7938..d0d7afae404de 100644 --- a/apps/web/src/components/RightPanelTabs.keyboard.browser.test.tsx +++ b/apps/web/src/components/RightPanelTabs.keyboard.browser.test.tsx @@ -123,9 +123,7 @@ describe("right panel new-tab shortcut", () => { platform === "MacIntel" ? { metaKey: true } : { ctrlKey: true }, ); expect(event.defaultPrevented).toBe(true); - expect(document.querySelector('[role="menu"]')?.textContent).toContain( - "Linked pull requests", - ); + expect(document.querySelector('[role="menu"]')?.textContent).toContain("Linked items"); expect(document.activeElement?.closest('[role="menu"]')).not.toBeNull(); expect( ( diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 1a0b4c588d64c..9cc52068df45d 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -138,6 +138,11 @@ describe("sidebar numbered jumps", () => { const initial = useComposerDraftStore.getState(); using stack = new DisposableStack(); stack.defer(() => useComposerDraftStore.setState(initial, true)); + useComposerDraftStore.setState({ + draftsByThreadKey: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, + }); const previousSettings = getClientSettings(); stack.defer(() => __setClientSettingsForTests(previousSettings)); __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); @@ -158,11 +163,12 @@ describe("sidebar numbered jumps", () => { routeThreadRef: threadRef, }); const draftId = DraftId.make("unsent-draft"); - initial.setProjectDraftThreadId(scopeProjectRef(web.environmentId, web.id), draftId, { + const drafts = useComposerDraftStore.getState(); + drafts.setProjectDraftThreadId(scopeProjectRef(web.environmentId, web.id), draftId, { threadId: ThreadId.make("unsent-draft-thread"), createdAt: "2026-01-02T00:00:00.000Z", }); - initial.setPrompt(draftId, "Unsent prompt"); + drafts.setPrompt(draftId, "Unsent prompt"); await using screen = await render( @@ -207,6 +213,16 @@ describe("sidebar render isolation", () => { // regression: #33100 Cmd+J re-rendered every sidebar row, which took hundreds of ms with many threads it("does not re-render thread rows when a quick Mod shortcut opens and focuses the terminal", async () => { using stack = new DisposableStack(); + const previousSettings = getClientSettings(); + stack.defer(() => __setClientSettingsForTests(previousSettings)); + __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); + const initialDrafts = useComposerDraftStore.getState(); + stack.defer(() => useComposerDraftStore.setState(initialDrafts, true)); + useComposerDraftStore.setState({ + draftsByThreadKey: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, + }); const activeProject = project("active"); const threads = Array.from({ length: 5 }, (_, index) => threadShell(activeProject.id, index)); const routeThreadRef: ScopedThreadRef = { diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index af006833c8134..a17427fcdb54e 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -7,6 +7,8 @@ import { describe, expect, it } from "vite-plus/test"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { + ADD_PROJECT_SCOPE_ITEM_VALUE, + filterSidebarProjectScopeItems, shouldCreateNewThreadInCurrentProject, resolveScopedNewThreadProjectRef, deleteSelectedThreadEntries, @@ -1811,3 +1813,22 @@ describe("resolveScopedNewThreadProjectRef", () => { ).toBeNull(); }); }); + +describe("filterSidebarProjectScopeItems", () => { + it("hides Add project and All projects while searching", () => { + const items = [ + { value: ADD_PROJECT_SCOPE_ITEM_VALUE, label: "Add project" }, + { value: "all", label: "All projects" }, + { value: "p1", label: "project" }, + ]; + const filter = (query: string) => + filterSidebarProjectScopeItems({ + items, + query, + matches: (item, q) => item.label.includes(q), + }).map((item) => item.value); + + expect(filter("")).toEqual([ADD_PROJECT_SCOPE_ITEM_VALUE, "all", "p1"]); + expect(filter("project")).toEqual(["p1"]); + }); +}); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 49109eb4ac2b0..0771ea2e33d5d 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1183,6 +1183,8 @@ export function pullRequestMatchesSearchQuery( return normalizedQuery.split(" ").every((token) => haystack.includes(token)); } +export const ADD_PROJECT_SCOPE_ITEM_VALUE = "add-project"; + export function filterSidebarProjectScopeItems(input: { items: readonly TItem[]; query: string; @@ -1190,7 +1192,12 @@ export function filterSidebarProjectScopeItems item.value !== "all" && input.matches(item, query)); + return input.items.filter( + (item) => + item.value !== "all" && + item.value !== ADD_PROJECT_SCOPE_ITEM_VALUE && + input.matches(item, query), + ); } interface SidebarProjectScopeMenuState { 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.snooze.ts b/apps/web/src/components/Sidebar.snooze.ts index 34cdc0077cd3d..abe2e3934659d 100644 --- a/apps/web/src/components/Sidebar.snooze.ts +++ b/apps/web/src/components/Sidebar.snooze.ts @@ -9,6 +9,7 @@ import { } from "@t3tools/client-runtime/state/thread-settled"; import { m, type MessageResolver } from "../i18n/messages"; +import { getFormattingLocale } from "../i18n/runtime"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { serverEnvironment } from "../state/server"; import { formatShortTimestamp } from "../timestampFormat"; @@ -52,11 +53,13 @@ export function pickSnoozePreset( } function snoozeOptions(timestampFormat: TimestampFormat, environmentId: EnvironmentId) { + const locale = getFormattingLocale(); const presets = appAtomRegistry.get( serverEnvironment.settingsValueAtom(environmentId), )?.snoozePresets; return { ...(presets ? { presets } : {}), - formatTime: (date: Date) => formatShortTimestamp(date.toISOString(), timestampFormat), + formatTime: (date: Date) => formatShortTimestamp(date.toISOString(), timestampFormat, locale), + locale, }; } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index b49ffcdbda7d1..18346918e07b9 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -72,7 +72,7 @@ import { CheckIcon, ChevronDownIcon, FolderIcon, - ListFilterIcon, + FolderPlusIcon, PlusIcon, SettingsIcon, } from "lucide-react"; @@ -175,7 +175,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"; @@ -199,6 +198,7 @@ import { buildBulkTitleRegenerationContextMenuItem, buildBulkUnpinContextMenuItem, deleteSelectedThreadEntries, + ADD_PROJECT_SCOPE_ITEM_VALUE, filterSidebarProjectScopeItems, firstValidTimestampMs, isSidebarNestedLinkClick, @@ -295,7 +295,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, @@ -456,6 +461,7 @@ function useSidebarThreads(input: { readonly childThreadGroups: ChildThreadGroups; 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. @@ -471,9 +477,11 @@ function useSidebarThreads(input: { childThreadGroups, 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; @@ -540,11 +548,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); } @@ -552,10 +560,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); @@ -867,6 +875,7 @@ function useSidebarLookups() { projectGroups.map((project) => [project.projectKey, project] as const), ); const projectScopeItems = [ + { value: ADD_PROJECT_SCOPE_ITEM_VALUE, label: gt("Add project") }, { value: "all", label: gt("All projects") }, ...pickableProjectGroups(projectGroups).map((project) => ({ value: project.projectKey, @@ -1195,20 +1204,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, @@ -1219,7 +1222,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve projectScopeKeys.length > 1 ? null : (projectScopeItems.find((item) => item.value === (projectScopeKeys[0] ?? "all")) ?? - projectScopeItems[0]!); + projectScopeItems.find((item) => item.value === "all")!); const filteredProjectScopeItems = filterSidebarProjectScopeItems({ items: projectScopeItems, query: projectScopeMenuState.query, @@ -1237,13 +1240,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 ( @@ -1389,6 +1396,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve childThreadGroups, delegatedUnderParent, routeRowThreadKey, + departingThreadKey, folderGroups: boringSidebarEnabled ? scopedProjectGroups.length === 0 ? // An archived project keeps a folder for its active threads, below the rest. @@ -1518,7 +1526,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; @@ -1718,9 +1730,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( @@ -1743,6 +1757,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) { navigateAfterSettle?.(); + } else { + stayOnRouteThread(threadKey); } })(); }; @@ -2288,6 +2304,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), ); @@ -2302,6 +2319,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) navigateAfterSettle?.(); + else stayOnRouteThread(activeKey); return; } case "move-active": @@ -2357,9 +2375,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); @@ -2374,6 +2394,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) { navigateAfterSnooze?.(); + } else { + stayOnRouteThread(threadKey); } return { status: "success" } as const; }; @@ -3160,7 +3182,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve return; } if (!item) return; - if (item.value === "all") { + if (item.value === ADD_PROJECT_SCOPE_ITEM_VALUE) { + dispatchProjectScopeMenu({ type: "open-changed", open: false }); + openAddProjectCommandPalette(); + } else if (item.value === "all") { setProjectScopeKeys([]); } else if ( eventDetails.event instanceof MouseEvent && @@ -3179,12 +3204,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve 0 - ? gt("Filter threads by project: {projects}", { + ? gt("Projects: {projects}", { projects: scopedProjectGroups .map((project) => project.displayName) .join(", "), }) - : gt("Filter threads by project") + : gt("Projects") } /> } @@ -3209,7 +3234,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ) : ( - + )} {/* Refocusing the trigger after a pointer close shows its focus ring and opens its tooltip. */} @@ -3271,6 +3296,16 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve {(item: (typeof projectScopeItems)[number]) => { + if (item.value === ADD_PROJECT_SCOPE_ITEM_VALUE) { + return ( + + + {item.label} + {/* Keeps "Add project" as tall as the project rows. */} + + + ); + } const project = projectGroupByScopeKey.get(item.value) ?? null; const isSelected = project ? projectScopeKeys.includes(item.value) @@ -3346,7 +3381,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } - onNewProject={openAddProjectCommandPalette} onNewThread={handleNewThreadClick} newThreadDisabled={projects.length === 0} newThreadShortcutLabel={newThreadShortcutLabel} @@ -3622,14 +3656,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 @@ -3671,6 +3703,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 118e96d33a868..5be451fd17bfc 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -23,6 +23,7 @@ import { import type { KeybindingCommand, AssistantCitation, + ComposerContextId, ResponseContextRecord, ChatAttachment as ContractChatAttachment, ChatFileAttachment, @@ -120,6 +121,7 @@ import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; import { + type QueuedAttachmentContextBinding, reconcileAttachmentContextReferences, useRetainedContextPayloads, } from "./composerContextUndo"; @@ -133,6 +135,8 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, + clipboardHtmlImageContent, + imagesToAttachBesidePastedText, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -212,6 +216,7 @@ import { } from "./ComposerCommandMenu"; import { ComposerAttachButton, + ComposerAttachInput, ComposerAttachmentFileList, ComposerAttachmentMediaRow, ComposerFilePreviewDialog, @@ -251,6 +256,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"; @@ -284,11 +290,15 @@ import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; 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 { VoiceCallButton } from "../voiceCall/VoiceCallButton"; @@ -461,8 +471,11 @@ export interface ChatComposerProps { editingQueuedAttachments: ReadonlyArray<{ readonly attachment: ContractChatAttachment; readonly url: string | null; + readonly contextIds?: ReadonlyArray | undefined; }> | null; + removedEditingQueuedAttachments?: ReadonlyArray | undefined; onRemoveEditingQueuedAttachment: (attachmentId: string) => void; + onRestoreEditingQueuedAttachment?: ((attachment: ContractChatAttachment) => void) | undefined; onCompactContext: () => void; onSend: ( @@ -470,6 +483,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; @@ -574,6 +600,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onPageScrollRelease, onCompactContext, onSend, + captureDetachedSend, onResume, onInterrupt, onSelectActivePendingUserInputOption, @@ -591,7 +618,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onExpandImage, onFileOpen, editingQueuedAttachments, + removedEditingQueuedAttachments, onRemoveEditingQueuedAttachment, + onRestoreEditingQueuedAttachment, } = props; const { activePendingProgress: incomingPendingProgress, @@ -649,6 +678,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingProgress.activeQuestion.id, ) : null; + const queuedEditOwnsComposer = + questionAttachmentTarget === null && pendingUserInputs.length === 0; + const activeEditingQueuedAttachments = queuedEditOwnsComposer ? editingQueuedAttachments : null; + const activeRemovedEditingQueuedAttachments = queuedEditOwnsComposer + ? removedEditingQueuedAttachments + : undefined; const attachmentDraftTarget = questionAttachmentTarget ?? composerDraftTarget; const attachmentDraft = useComposerThreadDraft(attachmentDraftTarget); const questionTakesSnapShots = @@ -726,8 +761,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); @@ -739,33 +784,55 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cwd: gitCwd ?? undefined, projectId: activeProjectId ?? undefined, expandImage: (imageId: string) => { - const preview = buildExpandedImagePreview( - composerImages, - imageId, - copyComposerSnapshotStable, - ); + const preview = + buildExpandedImagePreview(composerImages, imageId, copyComposerSnapshotStable) ?? + buildExpandedImagePreview( + (activeEditingQueuedAttachments ?? []).flatMap(({ attachment, url }) => + isQueuedImageAttachment(attachment) && url ? [{ ...attachment, previewUrl: url }] : [], + ), + imageId, + ); if (preview) onExpandImage(preview); }, - openFile: setPreviewFileId, + openFile: (fileId: string) => { + if (composerFiles.some((file) => file.id === fileId)) { + setPreviewFileId(fileId); + return; + } + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (queuedFile && isQueuedFileAttachment(queuedFile)) onFileOpen(queuedFile); + }, openMention: (path: string) => useRightPanelStore.getState().openFile(routeThreadRef, path), expandVideo: (fileId: string) => { const file = composerFiles.find((candidate) => candidate.id === fileId); - if (!file || !isVideoAttachment(file)) return; - const localPreview = buildExpandedImagePreview([file], file.id); - if (localPreview) { - onExpandImage(localPreview); + if (file && isVideoAttachment(file)) { + const localPreview = buildExpandedImagePreview([file], file.id); + if (localPreview) { + onExpandImage(localPreview); + return; + } + if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + return; + } + const persistedPreview = buildAttachmentVideoPreview(environmentId, { + type: "file", + id: file.uploadedAttachmentId, + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, + }); + if (persistedPreview) onExpandImage(persistedPreview); return; } - if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (!queuedFile || !isQueuedFileAttachment(queuedFile) || !isVideoAttachment(queuedFile)) { return; } - const persistedPreview = buildAttachmentVideoPreview(environmentId, { - type: "file", - id: file.uploadedAttachmentId, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - }); + const persistedPreview = buildAttachmentVideoPreview(environmentId, queuedFile); if (persistedPreview) onExpandImage(persistedPreview); }, openPullRequest: (event: React.MouseEvent, url: string) => { @@ -780,6 +847,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentContexts: composerEnvironmentContexts, images: composerImages, files: composerFiles, + existingAttachments: activeEditingQueuedAttachments ?? undefined, + environmentId, uploadsByImageId, }); const needsReattachFileCount = composerFiles.filter(composerFileNeedsReattach).length; @@ -1070,6 +1139,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerEditorRef = useRef(null); const pasteAsTextShortcutUntilRef = useRef(0); const composerFormRef = useRef(null); + const composerAttachInputRef = useRef(null); const composerSurfaceRef = useRef(null); const providerInputRejectedRef = useRef(false); const composerSelectLockRef = useRef(false); @@ -1271,21 +1341,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; @@ -1375,12 +1452,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : null); if (!record) return []; if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file); - return [ - record.kind === "image" && attachment.type === "image" && attachment.source - ? { ...record, source: attachment.source } - : record, - ]; + return [record]; }), + ...(activeEditingQueuedAttachments ?? []).flatMap(({ attachment, contextIds }) => { + if (!isQueuedImageAttachment(attachment) && !isQueuedFileAttachment(attachment)) return []; + return (contextIds ?? []) + .filter((contextId) => wanted.has(contextId)) + .map((contextId) => + attachmentContextRecord({ + attachment, + attachmentId: attachment.id, + contextId, + }), + ); + }), ]; if (records.length === 0) return null; const fragment = encodeComposerContextFragment({ @@ -1429,6 +1514,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + removedQueuedAttachments: activeRemovedEditingQueuedAttachments, + onRestoreQueuedAttachment: onRestoreEditingQueuedAttachment, }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared prompt ref in step with the committed draft prompt for imperative handlers @@ -1634,6 +1721,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cursorAdjacentToMention: boolean, contextIds: string[], textChanged: boolean, + fromHistory = false, ) => { refreshWorkspaceSnapshotOnTyping(); const trigger = cursorAdjacentToMention @@ -1744,6 +1832,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const attachmentChanges = reconcileAttachmentContextReferences({ referencedContextIds: referenced, files: composerFiles, + queuedAttachments: (activeEditingQueuedAttachments ?? []).map( + ({ attachment, contextIds }) => ({ + attachment, + contextIds: contextIds ?? [], + }), + ), + removedQueuedAttachments: activeRemovedEditingQueuedAttachments ?? [], + fromHistory, images: composerImages, previewAnnotations: composerPreviewAnnotations, retained: retainedContextPayloads, @@ -1763,6 +1859,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (attachmentChanges.filesToRestore.length > 0) { addComposerDraftFiles(attachmentDraftTarget, attachmentChanges.filesToRestore); } + for (const attachmentId of attachmentChanges.queuedAttachmentIdsToRemove) { + onRemoveEditingQueuedAttachment(attachmentId); + } + for (const attachment of attachmentChanges.queuedAttachmentsToRestore) { + onRestoreEditingQueuedAttachment?.(attachment); + } setComposerCursor(nextCursor); updateTrigger(trigger); }; @@ -2200,29 +2302,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(); @@ -2238,7 +2411,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(); @@ -2275,7 +2448,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, @@ -2404,8 +2578,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, @@ -2444,6 +2622,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptSuggestion: offeredPromptSuggestion, dismissPromptSuggestion, })(key, event, isTaskItem); + }; const { stashQueue, @@ -2552,7 +2731,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} @@ -2659,7 +2838,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; @@ -2860,12 +3041,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(); @@ -2877,6 +3066,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; } @@ -3458,15 +3654,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ) : undefined; const composerAttachButton = showComposerAttachAction ? ( - + composerAttachInputRef.current?.click()} /> ) : null; return (
{ + if ( + event.key === "Escape" && + composerSendHeld && + !event.defaultPrevented && + !event.nativeEvent.isComposing + ) { + event.preventDefault(); + cancelHeldSend(); + } + }} onFocusCapture={(event) => { const activeElement = event.target; if ( @@ -3551,6 +3755,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onToggleMenu={toggleStashMenuStable} /> + {showComposerAttachAction ? ( + + ) : null}
@@ -3611,6 +3822,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(); @@ -3620,7 +3832,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) else submitComposer(); }} > - {showResumeAction ? ( + {composerSendHeld || isSendBusy ? ( +
+ ); +} + +function FeedbackPreview({ preview }: { readonly preview: AgentFeedbackPreview }) { + const m = useMessages(); + + return ( +
+
+ {feedbackPreviewFields(preview, m).map((field) => ( +
+
{field.label}
+
{field.value}
+
+ ))} +
+ {preview.trace !== null ? ( + + + + {feedbackTraceSummary(preview.trace, m)} + + +
    + {feedbackTraceLines(preview.trace, m).map((entry) => ( +
  1. + {entry.line} + {entry.text !== undefined ? ( +

    + {entry.text} +

    + ) : null} +
  2. + ))} +
+
+
+ ) : null} +
+ ); +} diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts b/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts index fcee475c2886a..0a45cd6ac5659 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts +++ b/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts @@ -1,5 +1,5 @@ import { Children, isValidElement, type ReactNode } from "react"; -import type { ExtraProps as ReactMarkdownExtraProps } from "react-markdown"; +import type { Element } from "hast"; import type { DiffThemeName } from "../../lib/diffRendering"; @@ -44,11 +44,7 @@ export function extractPreCodeMeta(node: unknown): string | undefined { return typeof meta === "string" && meta.trim().length > 0 ? meta.trim() : undefined; } -export function isClosedCodeFence( - node: ReactMarkdownExtraProps["node"], - text: string, - code: string, -): boolean { +export function isClosedCodeFence(node: Element | undefined, text: string, code: string): boolean { const start = node?.position?.start.offset; const end = node?.position?.end.offset; if (start === undefined || end === undefined) return false; @@ -98,7 +94,7 @@ export function extractCodeBlock( return null; } // With a custom `code` component the child's type is that component, not - // the "code" tag — the hast node react-markdown attaches still names it. + // the "code" tag — the hast node the renderer passes still names it. if (onlyChild.type !== "code" && onlyChild.props.node?.tagName !== "code") { return null; } diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.tsx b/apps/web/src/components/chat/MarkdownCodeBlock.tsx index d6c8a7aaba2eb..726c34cbf029e 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.tsx +++ b/apps/web/src/components/chat/MarkdownCodeBlock.tsx @@ -1,4 +1,4 @@ -import { T, useGT } from "gt-react"; +import { useGT } from "gt-react"; import { PlayIcon, WrapTextIcon, CheckIcon, CopyIcon } from "lucide-react"; import { toHtml } from "hast-util-to-html"; import React, { use, useEffect, useState, type ReactNode } from "react"; @@ -18,7 +18,7 @@ import { syntheticFileNameForLanguageId, } from "../../pierre-icons"; import { Button } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { HighlightedCodeLines } from "./HighlightedCodeLines"; import { createHighlightCacheKey, @@ -115,19 +115,17 @@ function MarkdownCodeBlockTitleContent({ return {language}; } return ( - - - } - > - - - {language} - + + } + > + + ); } @@ -187,22 +185,20 @@ export function MarkdownCodeBlock({ const handleCopy = () => copyToClipboard(code.endsWith("\n") ? code.slice(0, -1) : code); const copyButton = ( - - - } - > - {copied ? : } - - {copyLabel} - + + } + > + {copied ? : } + ); if (diagram) { @@ -231,43 +227,37 @@ export function MarkdownCodeBlock({ aria-label={gt("Code block actions")} > {canWrap ? ( - - setWrapOverride(!wrapped)} - aria-label={wrapLabel} - /> - } - > - - - {wrapLabel} - + setWrapOverride(!wrapped)} + aria-label={wrapLabel} + /> + } + > + + ) : null} {canRun ? ( - - onRunShellCommand(command)} - aria-label={gt("Run in terminal")} - /> - } - > - - - - Run in terminal - - + onRunShellCommand(command)} + aria-label={gt("Run in terminal")} + /> + } + > + + ) : null} {viewToggle} {copyButton} diff --git a/apps/web/src/components/chat/MarkdownDetails.tsx b/apps/web/src/components/chat/MarkdownDetails.tsx index 5ec510c3a4306..b6fa2b1d8d1f1 100644 --- a/apps/web/src/components/chat/MarkdownDetails.tsx +++ b/apps/web/src/components/chat/MarkdownDetails.tsx @@ -1,5 +1,6 @@ import { useGT } from "gt-react"; import { ChevronRightIcon } from "lucide-react"; +import { flushSync } from "react-dom"; import { Children, isValidElement, @@ -12,6 +13,11 @@ import { import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { findRevealRef, MarkdownFindContext } from "./markdownFindContext"; +const focusOnMount = (element: HTMLElement | null) => { + if (element && element.ownerDocument.activeElement === element.ownerDocument.body) + element.focus(); +}; + export function MarkdownDetails({ children, open = false, @@ -19,6 +25,7 @@ export function MarkdownDetails({ }: Pick, "children" | "open" | "dir">) { const gt = useGT(); const [isOpen, setIsOpen] = useState(open); + const [armed, setArmed] = useState<"hover" | "focus" | null>(null); const searching = use(MarkdownFindContext); const expanded = isOpen; const revealForFind = () => setIsOpen(true); @@ -36,6 +43,36 @@ export function MarkdownDetails({ : gt("Details", { $context: "fallback title of a collapsible section" }); const content = childNodes.filter((_, index) => index !== summaryIndex); + // Most details stay closed: mount Base UI on hover or focus, before the first click. + if (!armed && !expanded && !searching) { + return ( +
+
+ +
+
+ ); + } + 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 f9bf9850ce5e1..68a44340f9ad6 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"; @@ -628,6 +627,48 @@ describe("MessagesTimeline messages", () => { await vi.waitFor(() => expect(viewport.scrollTop).toBeLessThan(atEnd)); }); + it("keeps the visible sentence in a long message when the chat width changes", async () => { + setup(); + const size = { width: window.innerWidth, height: window.innerHeight }; + onTestFinished(() => page.viewport(size.width, size.height)); + await page.viewport(1200, 1400); + const props = { ...baseProps(), liveFollowEnabled: false }; + const paragraphs = Array.from( + { length: 30 }, + (_, index) => + `Paragraph ${index + 1}. ${"A side panel should not move the sentence being read out of view. ".repeat(5)}`, + ); + await using screen = await renderTimeline( + [message(paragraphs.join("\n\n"), { role: "assistant" })], + props, + ); + screen.container.style.width = "900px"; + const viewport = props.listRef.current!.getScrollableNode()!; + const target = page.getByText(paragraphs[15]!.trim(), { exact: true }).element(); + await vi.waitFor(() => { + expect(viewport.scrollHeight).toBeGreaterThan(1000); + expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2); + }); + await props.listRef.current!.scrollToOffset({ + offset: + viewport.scrollTop + + target.getBoundingClientRect().top - + viewport.getBoundingClientRect().top - + 24, + animated: false, + }); + viewport.dispatchEvent(new Event("scroll")); + const before = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top; + expect(Math.abs(before - 24)).toBeLessThan(2); + for (const width of [500, 900]) { + screen.container.style.width = `${width}px`; + await vi.waitFor(() => { + const after = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top; + expect(Math.abs(after - before)).toBeLessThan(30); + }); + } + }); + it("disables the minimap's next turn button at the bottom of the thread", async () => { setup(); const props = baseProps(); @@ -2129,49 +2170,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.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 0a703a675f0ac..f1726cbbb92b2 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1785,7 +1785,7 @@ describe("deriveMessagesTimelineRows", () => { expect(rows.at(-1)).toMatchObject({ kind: "thinking" }); }); - it("does not show Thinking once the open run's provider turn has ended", () => { + it("does not show Thinking once the provider turn has ended or its reply is streaming", () => { const input = { timelineEntries: [ { @@ -1821,6 +1821,29 @@ describe("deriveMessagesTimelineRows", () => { latestRun: { ...input.latestRun, turnEnded: true }, }); expect(ended.some((row) => row.kind === "thinking")).toBe(false); + + const streamingReply = deriveMessagesTimelineRows({ + ...input, + timelineEntries: [ + ...input.timelineEntries, + { + id: "assistant-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:05Z", + message: { + id: "assistant" as never, + role: "assistant" as const, + text: "Here is the first paragraph of the answer", + runId: "turn-1" as never, + createdAt: "2026-01-01T00:00:05Z", + updatedAt: "2026-01-01T00:00:06Z", + streaming: true, + }, + }, + ], + }); + expect(streamingReply.at(-1)?.id).toBe("assistant-entry"); + expect(streamingReply.some((row) => row.kind === "thinking")).toBe(false); }); it("keeps a promptless restart in one active visual response", () => { @@ -4548,7 +4571,6 @@ it("keeps the working header in place across worktree setup handoff", () => { "worktree-setup", "working", "message", - "thinking", ]); const stage = (id: "agent" | "setup-script", status: "done" | "running") => @@ -4744,7 +4766,29 @@ describe("failed turn transcript", () => { ); expect(work.at(-1)?.detail).toBe("The provider stopped this turn.\nRetry later."); expect(work.at(-1)?.createdAt).toBe("2026-09-20T12:00:00.000Z"); - if (isLatest) return; + if (isLatest) { + // The recovery notice hides the failure row; the run's work stays grouped. + const noticeRows = deriveMessagesTimelineRows({ + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: items.filter((row) => row.item.type !== "error"), + optimisticMessages: [], + }), + latestRun: { + runId, + status: "failed", + startedAt: DateTime.formatIso(at), + completedAt: DateTime.formatIso(at), + }, + usageLimitRunId: runId, + isWorking: false, + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + expect(noticeRows.find((row) => row.kind === "work-toggle")).toEqual( + expect.objectContaining({ hiddenCount: 3, expanded: false }), + ); + return; + } const entriesWithoutTools = deriveTimelineEntriesFromVisibleTurnItems({ visibleTurnItems: items.filter((row) => row.item.type !== "command_execution"), optimisticMessages: [], diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 734d5e6e112a6..b944c0513b63a 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, @@ -1056,8 +1056,9 @@ function failedTimelineRunIds( function itemizedFailedRunIds( entries: ReadonlyArray, failedRunIds: ReadonlySet, + usageLimitRunId: RunId | null, ) { - const usageLimited = new Set(); + const usageLimited = new Set(usageLimitRunId ? [usageLimitRunId] : []); const otherFailures = new Set(); for (const entry of entries) { const item = timelineEntryFailedItem(entry); @@ -1612,6 +1613,8 @@ export function deriveMessagesTimelineRows( timelineEntries: ReadonlyArray; pendingApprovalRequestIds?: ReadonlySet; latestRun?: TimelineLatestRun | null; + /** The usage-limited run whose failure row the recovery notice replaces. */ + usageLimitRunId?: RunId | null; runningRunId?: RunId | null; expandedRunIds?: ReadonlySet; expandedAttemptIds?: ReadonlySet; @@ -1663,7 +1666,11 @@ export function deriveMessagesTimelineRows( const nextRows: MessagesTimelineRow[] = []; const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(timelineEntries); const failedRunIds = failedTimelineRunIds(timelineEntries, input.latestRun ?? null); - const itemizedRunIds = itemizedFailedRunIds(timelineEntries, failedRunIds); + const itemizedRunIds = itemizedFailedRunIds( + timelineEntries, + failedRunIds, + input.usageLimitRunId ?? null, + ); const liveSubagentEntryIds = liveSubagentCardEntryIds(timelineEntries); const retainedAssistantReplyIds = retainedAssistantReplyEntryIds(timelineEntries); const supersededFoldsByAnchorEntryId = deriveSupersededAttemptFolds( @@ -2376,6 +2383,11 @@ export function deriveMessagesTimelineRows( } } + const latestTimelineEntry = timelineEntries.at(-1); + const replyIsStreaming = + latestTimelineEntry?.kind === "message" && + latestTimelineEntry.message.role === "assistant" && + latestTimelineEntry.message.streaming; const hasWorkingRow = nextRows.some((row) => row.kind === "working"); if (input.isWorking && !hasWorkingRow && activeTurnHeaderIndex === timelineEntries.length) { appendWorkingRow(); @@ -2383,6 +2395,7 @@ export function deriveMessagesTimelineRows( if ( input.isWorking && input.latestRun?.turnEnded !== true && + !replyIsStreaming && !setupOwnsWorkingSlot && !hasActiveCompaction && !compactionOnlyRunFinished && diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 61917d98d2d1e..4ff180d39a604 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -33,6 +33,7 @@ import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor"; import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime"; import { observeResize } from "~/lib/observeResize"; +import { preserveReadingPosition } from "~/lib/preserveReadingPosition"; import { useStableCallback } from "~/hooks/useStableCallback"; const NOOP_USE_ARTIFACT_TEMPLATE = () => {}; @@ -267,6 +268,7 @@ interface MessagesTimelineProps { listRef: React.RefObject; timelineEntries: ReadonlyArray; latestRun: TimelineLatestRun | null; + usageLimitRunId?: RunId | null; /** The run the screen reader announcer follows; see announcedRun. */ announcedRun?: { readonly runId: RunId; readonly status: TimelineLatestRun["status"] } | null; /** See isDetailBehindShell. */ @@ -297,6 +299,8 @@ interface MessagesTimelineProps { readonly sideChat?: boolean; /** Where it runs, when that is another environment. */ readonly environmentLabel?: string; + /** What this thread is to it, when not its subagent or side chat: `Step of`, say. */ + readonly relation?: { readonly label: string; readonly actionLabel: string }; readonly open?: () => void; } | null; workflowOpening?: WorkflowOpening | null; @@ -392,6 +396,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ activeFindMatch = null, findNavigationId = 0, latestRun, + usageLimitRunId = null, announcedRun = null, detailBehindShell = false, runningRunId = null, @@ -760,6 +765,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ timelineEntries, pendingApprovalRequestIds, latestRun, + usageLimitRunId, runningRunId, expandedRunIds: visibleExpandedRunIds, expandedAttemptIds: visibleExpandedAttemptIds, @@ -1258,13 +1264,14 @@ const ConversationTimeline = memo(function ConversationTimeline({
@@ -1292,6 +1302,14 @@ const ConversationTimeline = memo(function ConversationTimeline({ const canvas = useChatCanvas(); const registerTimeline = canvas?.registerTimeline; + const shouldPreserveReadingPosition = useStableCallback( + () => + !liveFollowEnabled && + !anchoredEndSpace && + !findActive && + !citationPositioning && + !restoringThreadPosition, + ); // Stable so the list attaches once per mount, not on every render. const setTimelineList = useStableCallback((list: LegendListRef | null) => { listRef.current = list; @@ -1307,6 +1325,9 @@ const ConversationTimeline = memo(function ConversationTimeline({ }) : null; viewportRef.current = viewport; + const stopPreservingReadingPosition = scrollNode + ? preserveReadingPosition(scrollNode, shouldPreserveReadingPosition) + : undefined; const detachViewport = viewport ? onViewportAttach?.(viewport) : undefined; const stopRememberingRelease = viewport?.onFollowReleased(rememberReleasedPosition); const stopDisclosureReveal = viewport?.subscribe(() => { @@ -1335,6 +1356,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ scheduleContentSizeChanged(); return () => { stopListeningToContentSize?.(); + stopPreservingReadingPosition?.(); stopRememberingRelease?.(); stopDisclosureReveal?.(); if (contentSizeFrame !== null) cancelAnimationFrame(contentSizeFrame); diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index fb82f9c858d61..20ea71f88adcd 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -5,16 +5,19 @@ import { } from "@t3tools/client-runtime/state/runtime"; import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; -import type { - ChatAttachment as ContractChatAttachment, - EnvironmentId, - MessageId, - RunId, - ThreadId, +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; +import { + parseGoalCommand, + type ChatAttachment as ContractChatAttachment, + type EnvironmentId, + type MessageId, + type RunId, + type ThreadId, } from "@t3tools/contracts"; import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message"; import { Link } from "@tanstack/react-router"; @@ -270,9 +273,14 @@ export function QueuedRunsControl({ const previewText = isAttachmentOnlyBootstrapPrompt(item.text) ? "" : assistantCitationsToPlainText( - replaceComposerContextReferences(item.text, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(item.text, (reference) => reference.label), + ), ).trim(); const isEditing = item.runId !== null && item.runId === props.editingRunId; + // The server decides on the agent's text, and a goal command can stop the turn. + const sentText = { text: item.message?.text ?? item.text, attachments: item.attachments }; + const movesCommandFirst = isSlashCommand(sentText) && parseGoalCommand(sentText) === null; return (
  • 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 b7976d9702414..e1d9c1f5d7bc5 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -122,19 +122,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 ? (
    + } + /> + ); + } + return ( + {tracker.credential.label}} + description={gt("For the new {tracker} account.", { tracker: tracker.displayName })} + control={ + { + if (next.trim()) void onAdd(next.trim()).then((added) => added && setAdding(false)); + }} + /> + } + /> + ); +} diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts index 4468d0ee66a14..64984a238c251 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts @@ -14,6 +14,7 @@ import { keybindingFromKeyboardEvent, parseWhenExpressionDraft, shortcutToKeybindingInput, + shortcutToKeybindingParts, unknownWhenVariables, whenAstToExpression, } from "./KeybindingsSettings.logic"; @@ -250,6 +251,15 @@ describe("KeybindingsSettings.logic", () => { ).toBe("mod+m"); }); + it("keeps a literal plus key as its own part", () => { + expect(shortcutToKeybindingParts(parseKeybindingShortcut("mod++")!)).toEqual(["mod", "+"]); + expect(shortcutToKeybindingParts(parseKeybindingShortcut("mod+shift++")!)).toEqual([ + "mod", + "shift", + "+", + ]); + }); + it("serializes shortcuts and when expressions for upserts", () => { expect( shortcutToKeybindingInput({ diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 99ff61182d626..55d4278b0fe16 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -88,7 +88,7 @@ export const DEFAULT_WHEN_VARIABLE = ) ?? "terminalFocus"; const KNOWN_WHEN_VARIABLES = new Set(DEFAULT_WHEN_VARIABLES); -export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string { +export function shortcutToKeybindingParts(shortcut: KeybindingShortcut): ReadonlyArray { const parts: string[] = []; if (shortcut.modKey) parts.push("mod"); if (shortcut.metaKey) parts.push("meta"); @@ -96,7 +96,11 @@ export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string if (shortcut.altKey) parts.push("alt"); if (shortcut.shiftKey) parts.push("shift"); parts.push(shortcut.key === " " ? "space" : shortcut.key === "escape" ? "esc" : shortcut.key); - return parts.join("+"); + return parts; +} + +export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string { + return shortcutToKeybindingParts(shortcut).join("+"); } export function whenAstToExpression(node: KeybindingWhenNode | undefined): string { diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index 6e78c7c1935a6..0b6cc7ed41f81 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.tsx @@ -28,6 +28,7 @@ import { AuthOrchestrationOperateScope, AuthSettingsWriteScope, type KeybindingCommand, + type KeybindingShortcut, type KeybindingWhenNode, type ServerRemoveKeybindingInput, type ServerUpsertKeybindingInput, @@ -86,6 +87,7 @@ import { keybindingFromKeyboardEvent, parseWhenExpressionDraft, groupKeybindingRows, + shortcutToKeybindingParts, type KeybindingCommandOption, type KeybindingGroup, type KeybindingRow, @@ -100,35 +102,34 @@ import { keybindingSearchAnchorId, useSearchableSetting } from "./settingsSearch import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { useAtomCommand } from "../../state/use-atom-command"; -function KeybindingPill({ value }: { value: string }) { - // Keys dedupe repeated parts; a literal "+" in a shortcut splits into empty strings. - const seenParts = new Map(); - const parts = value.split("+").map((part) => { - const seen = seenParts.get(part) ?? 0; - seenParts.set(part, seen + 1); - return { part, key: seen === 0 ? part : `${part}-${seen}` }; - }); +function KeybindingPill({ shortcut }: { shortcut: KeybindingShortcut }) { + const isMac = navigator.platform.toLowerCase().includes("mac"); + const parts = shortcutToKeybindingParts(shortcut); + const modifierParts = parts.slice(0, -1); + const keyPart = parts.at(-1); + return ( - {parts.map(({ part, key }) => ( - + {modifierParts.map((part) => ( + {part === "mod" - ? navigator.platform.toLowerCase().includes("mac") + ? isMac ? "⌘" : "Ctrl" : part === "shift" ? "⇧" : part === "alt" - ? navigator.platform.toLowerCase().includes("mac") + ? isMac ? "⌥" : "Alt" : part === "ctrl" ? "⌃" - : part.length === 1 - ? part.toUpperCase() - : part} + : part} ))} + {keyPart !== undefined ? ( + {keyPart.length === 1 ? keyPart.toUpperCase() : keyPart} + ) : null} ); } @@ -915,7 +916,7 @@ function KeybindingKeyControl({ Unassigned ) : ( - + )} ) : ( diff --git a/apps/web/src/components/settings/LabsSettingsPanel.tsx b/apps/web/src/components/settings/LabsSettingsPanel.tsx index 293435976974a..f6354fb880ea0 100644 --- a/apps/web/src/components/settings/LabsSettingsPanel.tsx +++ b/apps/web/src/components/settings/LabsSettingsPanel.tsx @@ -1,16 +1,23 @@ +import { msg } from "gt-react"; import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels"; import { useAuth } from "@clerk/react"; import { Link } from "@tanstack/react-router"; +import { AgentFeedbackMode } from "@t3tools/contracts"; import { T, useGT, useMessages } from "gt-react"; import { hasCloudPublicConfig } from "~/cloud/publicConfig"; import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt"; import { Button } from "../ui/button"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; import { Switch } from "../ui/switch"; import { ScopedSwitch } from "./ScopedSwitch"; import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; import { useSearchableSetting } from "./settingsSearch"; -import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings"; +import { + useScopedSettings, + useScopedSettingsMixed, + useUpdateScopedSettings, +} from "./useScopedSettings"; import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext"; import { firstManagedDenial, usePrimaryManagedPolicy } from "~/state/managedPolicy"; @@ -24,9 +31,11 @@ export function LabsSettingsPanel() { {/* Clerk is only mounted when this build has T3 Connect. */} {hasCloudPublicConfig() ? : } + + ); @@ -186,6 +195,31 @@ function LinkedEnvironmentsRow() { ); } +function WorkflowsRow() { + const searchableSetting = useSearchableSetting(); + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + const gt = useGT(); + return ( + updateSettings({ workflowsEnabled: Boolean(checked) })} + aria-label={gt("Workflows")} + /> + } + /> + ); +} + function PromptSuggestionsRow() { const searchableSetting = useSearchableSetting(); const settings = useScopedSettings(); @@ -291,3 +325,74 @@ function FastWorktreeCheckoutRow() { /> ); } + +/** Shows only when every machine in scope honors it; older servers drop the setting. */ +const AGENT_FEEDBACK_MODES = AgentFeedbackMode.literals; +const AGENT_FEEDBACK_MODE_LABELS: Record = { + off: msg("Off"), + "on-request": msg("When I ask"), + auto: msg("Automatic"), +}; +const AGENT_FEEDBACK_MODE_DESCRIPTIONS: Record = { + off: msg("Agents send no feedback to the T3 team."), + "on-request": msg( + "When you ask, agents show you a short report about T3 Code and send it to the T3 team if you approve.", + ), + auto: msg( + "Agents also report T3 Code problems they hit on their own, such as a T3 tool that failed.", + ), +}; + +function AgentFeedbackRow() { + const searchableSetting = useSearchableSetting(); + const { scope, connectedEnvironments } = useSettingsScope(); + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + const gt = useGT(); + const m = useMessages(); + const mixed = useScopedSettingsMixed(["agentFeedback"]); + if ( + scope.kind === "project" || + scope.kind === "checkout" || + connectedEnvironments.length === 0 || + connectedEnvironments.some( + (environment) => environment.serverConfig?.environment.capabilities.agentFeedback !== true, + ) + ) + return null; + return ( + { + if (mode !== null) updateSettings({ agentFeedback: { mode } }); + }} + > + + + {(mode: AgentFeedbackMode | null) => + mode === null ? gt("Mixed") : m(AGENT_FEEDBACK_MODE_LABELS[mode]) + } + + + + {AGENT_FEEDBACK_MODES.map((mode) => ( + + {m(AGENT_FEEDBACK_MODE_LABELS[mode])} + + ))} + + + } + /> + ); +} diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 954c0e1c4ee3c..5ab6debec7255 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -659,7 +659,7 @@ export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSu const forget = async () => { const confirmed = await (requestConfirmDialog( gt( - "Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + "Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.", { label: link.label }, ), { variant: "destructive" }, @@ -668,7 +668,18 @@ export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSu setBusy(true); const result = await unlink({ environmentId, input: { environmentId: link.environmentId } }); setBusy(false); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + if (result._tag === "Success") { + if (result.value.removed && result.value.endedThere !== true) { + toastManager.add({ + type: "warning", + title: gt("{label} did not answer", { label: link.label }), + description: gt( + "Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + { label: link.label }, + ), + }); + } + } else if (!isAtomCommandInterrupted(result)) { failureToast(gt("Could not forget the link"), String(squashAtomCommandFailure(result))); } }; 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 de6a5c68abbc4..c26f920b8d352 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"; @@ -809,6 +809,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"; @@ -855,7 +856,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 ? ( @@ -1275,6 +1284,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 ed7f90154547f..d2ac0da345d17 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 { useEsveoSettingsSearchRequest } from "../esveoSettings/esveoSettingsSearch"; // Fork import { handleSettingsSectionKeyDown } from "./settingsSectionNavigation"; import { workspaceAreaProps } from "../../lib/workspaceFocus"; @@ -150,6 +153,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { setCompactSearchOpen(true); }); const searchableItems = useAvailableSettingsSearchItems(); + const navGroups = settingsNavGroups(useHasSecretProvidersEnvironment()); const results = searchSettings(query, searchableItems, m); const isSearching = query.trim().length > 0; const hasResults = results.length > 0; @@ -386,7 +390,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { )}
    - {SETTINGS_NAV_GROUPS.map((group, index) => ( + {navGroups.map((group, index) => (
    - formatShortTimestamp(date.toISOString(), props.timestampFormat); + formatShortTimestamp(date.toISOString(), props.timestampFormat, locale); const seenIds = new Set(); const seenWakes = new Set(); const previews = props.presets.map((preset) => { - const resolved = resolveSnoozePreset(preset, now, formatTime, m); + const resolved = resolveSnoozePreset(preset, now, formatTime, m, locale); if (resolved === null) return { tone: "muted", text: gt("Passed for today") } as const; if (seenIds.has(resolved.id)) { return { tone: "muted", text: gt("Duplicate of an option above") } as const; @@ -269,7 +271,7 @@ function SnoozePresetList(props: { return { tone: "menu", label: resolved.label, when: resolved.whenLabel } as const; }); - const menuPresets = resolveSnoozePresets(now, { presets: props.presets, formatTime }, m); + const menuPresets = resolveSnoozePresets(now, { presets: props.presets, formatTime, locale }, m); const repeatedLabels = new Set( menuPresets .map((preset) => preset.label) diff --git a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx index 8eecf79f5d33a..fd5b90f9c6c19 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx @@ -157,6 +157,58 @@ it("sizes an oversized theme file just under 1 MB as 1.00 MB", async () => { ); }); +it.each(["failed read", "batch install"])( + "keeps the oversized replacement warning after a superseded %s", + async (earlierImport) => { + using _themes = isolateThemes(); + await using _screen = await render( + {}} + onImported={() => true} + onImportedMany={() => {}} + />, + ); + const earlierRead = Promise.withResolvers(); + const readStarted = Promise.withResolvers(); + const earlierFile = Object.assign(themeFile("Dusk"), { + text() { + readStarted.resolve(); + return earlierRead.promise; + }, + }); + const input = document.querySelector('input[type="file"]')!; + const files = new DataTransfer(); + if (earlierImport === "batch install") files.items.add(themeFile("Dawn")); + files.items.add(earlierFile); + await act(async () => { + input.files = files.files; + input.dispatchEvent(new Event("change", { bubbles: true })); + await readStarted.promise; + }); + await expect.element(page.getByRole("button", { name: "Reading…" })).toBeDisabled(); + await userEvent.upload( + input, + new File([" ".repeat(256 * 1024 + 1)], earlierFile.name, { type: "application/json" }), + ); + const warning = page.getByText(/^That file is/); + await expect.element(warning).toBeVisible(); + + await act(async () => { + if (earlierImport === "batch install") { + earlierRead.resolve(JSON.stringify(theme("Dusk"))); + } else { + earlierRead.reject(new Error("Could not read Dusk")); + } + await earlierRead.promise.catch(() => {}); + }); + + expect(getCustomThemes().map((theme) => theme.label)).toEqual([]); + expect(page.getByRole("alert").element().textContent).toMatch(/^That file is/); + await expect.element(page.getByRole("button", { name: "Choose files" })).toBeEnabled(); + }, +); + function themeJsonc(name: string, background: string) { return `{ // VS Code themes use JSONC even with a .json extension. diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsx index 189560efdee9e..aeac23821884f 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.tsx @@ -233,19 +233,20 @@ function ThemeImportBody({ const [isReading, setIsReading] = useState(false); const [isDropTarget, setIsDropTarget] = useState(false); const [conflicts, setConflicts] = useState | null>(null); - // A newer read supersedes an older one still in flight. + // A new file selection supersedes a pending import even if the selection is rejected. const importRequestRef = useRef(0); const isCurrentRequest = (requestId: number) => requestId === importRequestRef.current && !signal.aborted; const readThemeFile = async (file: ImportableThemeFile) => { + const requestId = ++importRequestRef.current; const oversized = describeOversizedThemeFile(file.size); if (oversized) { + setIsReading(false); setError(oversized); return; } - const requestId = ++importRequestRef.current; setIsReading(true); const fileText = await settlePromise(() => file.text()); if (!isCurrentRequest(requestId)) return; diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts index d01b47078dbe2..2bbdd7867c3c7 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts @@ -424,11 +424,49 @@ it("rejects dedupe templates without a request placeholder", () => { 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 3f5ffe1bdfe50..23bb22fad01cd 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..3249b67624234 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", () => { @@ -155,6 +168,7 @@ describe("searchSettings", () => { "auto-settle-merged-threads", "days-before-auto-settle", "linked-environments", + "agent-feedback", ]); expect(available.map((item) => item.id).filter((id) => gatedIds.has(id))).toEqual([]); }); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 71ce1f0afd6d7..dc0a86c37f423 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"; @@ -62,7 +62,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; @@ -73,6 +73,7 @@ export interface SettingsSearchItem { readonly managedTunnelOnly?: boolean; readonly peerLinksOnly?: boolean; readonly fastWorktreeCheckoutOnly?: boolean; + readonly agentFeedbackOnly?: boolean; readonly textGeneratorsOnly?: boolean; readonly secondary?: boolean; readonly requiresThreadAutoSettlement?: boolean; @@ -91,9 +92,11 @@ export interface SettingsSearchAvailability { readonly managedTunnelActive?: boolean; readonly hasPeerLinkHost?: boolean; readonly hasFastWorktreeCheckoutEnvironment?: boolean; + readonly hasAgentFeedbackEnvironment?: boolean; /** 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> = { @@ -131,12 +134,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, @@ -166,11 +171,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"), @@ -179,6 +180,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; } @@ -358,24 +371,24 @@ export const SETTINGS_SEARCH_ITEMS = [ }, { id: "esveo-notion", - title: "Notion", + title: msg("Notion"), to: "/settings/source-control", fork: true, - searchTerms: ["notion integration secret pages links viewer connect token ntn"], + searchTerms: [msg("notion integration secret pages links viewer connect token ntn")], }, { id: "two-line-thread-cards", - title: "Two-line thread cards", + title: msg("Two-line thread cards"), to: "/settings/appearance", fork: true, - searchTerms: ["sidebar compact row height branch provider icon diff pull request"], + searchTerms: [msg("sidebar compact row height branch provider icon diff pull request")], }, { id: "group-sidebar-threads-by-project", - title: "Group threads by project", + title: msg("Group threads by project"), to: "/settings/appearance", fork: true, - searchTerms: ["sidebar project folder runs grouping collapse header repository"], + searchTerms: [msg("sidebar project folder runs grouping collapse header repository")], }, { id: "diff-color-scheme", @@ -415,10 +428,10 @@ export const SETTINGS_SEARCH_ITEMS = [ }, { id: "thread-details-open-by-default", - title: "Open thread details by default", + title: msg("Open thread details by default"), to: "/settings/appearance", fork: true, - searchTerms: ["thread details card panel workspace version control closed collapsed hide"], + searchTerms: [msg("thread details card panel workspace version control closed collapsed hide")], }, { id: "panel-animations", @@ -532,6 +545,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"), @@ -576,6 +590,13 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "environment", searchTerms: [msg("beta link another machine vps peer agents work there delegate")], }, + { + id: "workflows-beta", + title: msg("Workflows"), + to: "/settings/labs", + scope: "environment", + searchTerms: [msg("beta workflow durable runs automation steps schedule webhook folder")], + }, { id: "prompt-suggestions-beta", title: msg("Suggest next prompt"), @@ -848,53 +869,55 @@ export const SETTINGS_SEARCH_ITEMS = [ }, { id: "context-window-control", - title: "Context window usage", + title: msg("Context window usage"), to: "/settings/chat", fork: true, - searchTerms: ["composer tokens usage meter percentage compaction"], + searchTerms: [msg("composer tokens usage meter percentage compaction")], }, { id: "prompt-cache-timer", - title: "Prompt cache timer", + title: msg("Prompt cache timer"), to: "/settings/chat", fork: true, - searchTerms: ["composer claude cache ttl expire minutes warm cold tokens"], + searchTerms: [msg("composer claude cache ttl expire minutes warm cold tokens")], }, { id: "agent-stage", - title: "Agent stage", + title: msg("Agent stage"), to: "/settings/general", fork: true, - searchTerms: ["sprites stations subagents thinking editing terminal right panel everything"], + searchTerms: [ + msg("sprites stations subagents thinking editing terminal right panel everything"), + ], }, // Fork: easter eggs. { id: "easter-eggs", - title: "Easter eggs", + title: msg("Easter eggs"), to: "/settings/general", fork: true, - searchTerms: ["surprise fun rocket animation message send hidden"], + searchTerms: [msg("surprise fun rocket animation message send hidden")], }, { id: "voice-call-enabled", - title: "Voice calls", + title: msg("Voice calls"), to: "/settings/voice", fork: true, - searchTerms: ["voice call phone gpt live feature flag anruf telefon schalter"], + searchTerms: [msg("voice call phone gpt live feature flag anruf telefon schalter")], }, { id: "voice-call-voice", - title: "Voice call voice", + title: msg("Voice call voice"), to: "/settings/voice", fork: true, - searchTerms: ["voice call phone gpt live speaker stimme anruf telefon"], + searchTerms: [msg("voice call phone gpt live speaker stimme anruf telefon")], }, { id: "voice-call-follow-up", - title: "Voice call follow-up", + title: msg("Voice call follow-up"), to: "/settings/voice", fork: true, - searchTerms: ["voice call queue steer follow-up warteschlange anruf"], + searchTerms: [msg("voice call queue steer follow-up warteschlange anruf")], }, { id: "provider-update-checks", @@ -908,48 +931,48 @@ export const SETTINGS_SEARCH_ITEMS = [ // Fork: coordinator threads nested in the sidebar. { id: "sidebar-child-threads", - title: "Child threads in the sidebar", + title: msg("Child threads in the sidebar"), to: "/settings/general", fork: true, - searchTerms: ["coordinator subthreads nested group expand sidebar orchestration children"], + searchTerms: [msg("coordinator subthreads nested group expand sidebar orchestration children")], }, // Fork: coordinator decisions. { id: "thread-decisions", - title: "Coordinator decisions", + title: msg("Coordinator decisions"), to: "/settings/threads", fork: true, - searchTerms: ["inbox questions answers decide approve coordinator open items"], + searchTerms: [msg("inbox questions answers decide approve coordinator open items")], }, // Fork: cross-project threads. { id: "cross-project-threads", - title: "Cross-project threads", + title: msg("Cross-project threads"), to: "/settings/threads", fork: true, - searchTerms: ["agents coordinator other projects read message start threads repositories"], + searchTerms: [msg("agents coordinator other projects read message start threads repositories")], }, // Fork: idle auto-compact. { id: "idle-auto-compact", - title: "Auto-compact idle Claude threads", + title: msg("Auto-compact idle Claude threads"), to: "/settings/threads", fork: true, - searchTerms: ["compact context prompt cache idle claude tokens cost expire"], + searchTerms: [msg("compact context prompt cache idle claude tokens cost expire")], }, { id: "idle-auto-compact-after", - title: "Minutes idle before auto-compact", + title: msg("Minutes idle before auto-compact"), to: "/settings/threads", fork: true, - searchTerms: ["compact idle minutes prompt cache ttl"], + searchTerms: [msg("compact idle minutes prompt cache ttl")], }, { id: "idle-auto-compact-threshold", - title: "Minimum context for auto-compact", + title: msg("Minimum context for auto-compact"), to: "/settings/threads", fork: true, - searchTerms: ["compact context tokens threshold size"], + searchTerms: [msg("compact context tokens threshold size")], }, { id: "continue-threads-after-server-update", @@ -1113,6 +1136,16 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/maintenance", searchTerms: [msg("logs traces processes resource history failures spans cpu memory")], }, + { + id: "agent-feedback", + title: msg("Agent feedback"), + to: "/settings/labs", + scope: "environment-defaults", + agentFeedbackOnly: true, + searchTerms: [ + msg("report bug problem t3 team send feedback agents tools automatic when i ask"), + ], + }, { id: "open-source-licenses", title: msg("Open source licenses"), @@ -1590,7 +1623,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", @@ -1598,7 +1631,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", @@ -1679,6 +1712,7 @@ export function getSettingsSearchTargetScope(targetId: string) { title: item.title, scope: item.scope ?? SETTINGS_CATEGORY_SCOPES[item.to], ...(item.requiresThreadAutoSettlement ? { requiresThreadAutoSettlement: true } : {}), + ...(item.agentFeedbackOnly ? { agentFeedbackOnly: true } : {}), } : null; } @@ -1771,7 +1805,9 @@ export function filterAvailableSettingsSearchItems( (!item.peerLinksOnly || availability.hasPeerLinkHost === true) && (!item.fastWorktreeCheckoutOnly || availability.hasFastWorktreeCheckoutEnvironment === true) && - (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true), + (!item.agentFeedbackOnly || availability.hasAgentFeedbackEnvironment === true) && + (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true) && + (!item.secretProvidersOnly || availability.hasSecretProvidersEnvironment === true), ); } @@ -1784,7 +1820,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..279dbd39d51e3 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. @@ -36,12 +45,19 @@ export function useAvailableSettingsSearchItems() { environment.connection.phase === "connected" && environment.serverConfig?.environment.capabilities.fastWorktreeCheckout === true, ) === true; + const hasAgentFeedbackEnvironment = + environments.some( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ) === true; const hasTextGeneratorsEnvironment = environments.some( (environment) => environment.serverConfig !== null && environment.serverConfig.managedPolicy?.limits?.providers?.allowedDrivers === undefined, ) === true; + const hasSecretProvidersEnvironment = useHasSecretProvidersEnvironment(); const hasThreadAutoSettlement = getThreadAutoSettlementSearchAvailability(environments).eligibleEnvironmentIds.length > 0; const primaryEnvironmentId = usePrimaryEnvironmentId(); @@ -73,7 +89,9 @@ export function useAvailableSettingsSearchItems() { managedTunnelActive, hasPeerLinkHost, hasFastWorktreeCheckoutEnvironment, + hasAgentFeedbackEnvironment, 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 d592cbf1c0837..34f2144ecafe0 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -3,6 +3,7 @@ import type { ContextMenuSource } from "@t3tools/contracts"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { T, useGT } from "gt-react"; import { SquarePenIcon, XIcon } from "lucide-react"; import { @@ -12,8 +13,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"; @@ -33,9 +36,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; @@ -48,11 +83,14 @@ 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( - replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + ), ) .trim() .split("\n", 1)[0] ?? ""; @@ -67,9 +105,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, + }); // Fork: the draft card matches the thread cards so the list stays flush. const twoLineThreadCards = useTwoLineThreadCards(); const accessibility = resolveSidebarRowAccessibility({ @@ -183,6 +223,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; @@ -204,10 +245,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)); @@ -220,6 +263,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; @@ -242,8 +286,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; @@ -257,6 +303,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/SidebarThreadHeader.tsx b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx index 28e68b28e5d98..a048ab2f341c2 100644 --- a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx @@ -1,5 +1,5 @@ import { useGT } from "gt-react"; -import { FolderPlusIcon, SearchIcon, SquarePenIcon, XIcon } from "lucide-react"; +import { SearchIcon, SquarePenIcon, XIcon } from "lucide-react"; import { type ComponentProps, type KeyboardEvent as ReactKeyboardEvent, @@ -18,7 +18,6 @@ export interface SidebarThreadHeaderProps { projectScope: ReactNode; /** Fork: icons in front of the project scope, such as split view's auto arrange. */ forkLeadingActions?: ReactNode; - onNewProject: () => void; onNewThread: (event: ReactMouseEvent) => void; newThreadDisabled: boolean; newThreadShortcutLabel: string | null | undefined; @@ -38,7 +37,6 @@ export function SidebarThreadHeader({ hasProjects, projectScope, forkLeadingActions, - onNewProject, onNewThread, newThreadDisabled, newThreadShortcutLabel, @@ -106,9 +104,6 @@ export function SidebarThreadHeader({ <> {forkLeadingActions} {projectScope} - - - ) : null} instanceId !== modelInstanceId) .map((instanceId) => providerEntryByInstanceId.get(instanceId)?.displayName ?? instanceId); @@ -340,6 +342,12 @@ function SidebarThreadTooltip({
    ) : null} + {worktreePath ? ( +
    + + +
    + ) : null} {branchMismatch ? (
    @@ -591,7 +599,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; @@ -614,10 +622,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; @@ -898,9 +904,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} ) : ( @@ -1340,7 +1329,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} - {isRemote ? ( + + {issueBadge} + {props.environmentLabel !== null ? ( - ) : metaLineEmpty ? ( - - - - ) : null} + ) : ( + titleLineIcons + )}
    {/* Fork: two-line cards leave the third line out. */} - {metaLineEmpty || twoLineThreadCards ? null : ( -
    - {thread.branch ? ( - <> - - - - - - ) : showsScratchMachine ? ( - <> - - {props.scratchMachineLabel} - - ) : ( - - )} - {terminalStatusIcon} - {prBadge} - {diff ? ( - - - +{formatDiffCount(diff.insertions)} - {" "} - - −{formatDiffCount(diff.deletions)} - - - ) : null} - - {isRemote && !showsScratchMachine ? ( - - - - ) : null} - - -
    - )} + {twoLineThreadCards ? null : metaLine}
    {detailsTooltip} diff --git a/apps/web/src/components/sidebar/ThreadWorktreeIndicator.tsx b/apps/web/src/components/sidebar/ThreadWorktreeIndicator.tsx new file mode 100644 index 0000000000000..1df49341bd306 --- /dev/null +++ b/apps/web/src/components/sidebar/ThreadWorktreeIndicator.tsx @@ -0,0 +1,39 @@ +import { useGT } from "gt-react"; +import { FolderGit2Icon } from "lucide-react"; + +import type { SidebarThreadSummary } from "../../types"; +import { formatWorktreePathForDisplay } from "../../worktreeCleanup"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; + +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} + + ); +} diff --git a/apps/web/src/components/sidebar/mainAppLocation.ts b/apps/web/src/components/sidebar/mainAppLocation.ts index daa18b618a41a..0ef545f76b772 100644 --- a/apps/web/src/components/sidebar/mainAppLocation.ts +++ b/apps/web/src/components/sidebar/mainAppLocation.ts @@ -11,7 +11,10 @@ export function isAppModalPage(pathname: string) { export function isSidebarUtilityPage(pathname: string) { return ( - pathname.startsWith("/projects/") || pathname === "/pull-requests" || pathname === "/issues" + pathname.startsWith("/projects/") || + pathname === "/pull-requests" || + pathname === "/issues" || + pathname === "/workflows" ); } diff --git a/apps/web/src/components/sidebarProjectRuns/SidebarProjectRunRowLead.tsx b/apps/web/src/components/sidebarProjectRuns/SidebarProjectRunRowLead.tsx index e99b05c49f0b6..fd642b7f7cab8 100644 --- a/apps/web/src/components/sidebarProjectRuns/SidebarProjectRunRowLead.tsx +++ b/apps/web/src/components/sidebarProjectRuns/SidebarProjectRunRowLead.tsx @@ -1,20 +1,11 @@ import { NetworkIcon } from "lucide-react"; +import { T } from "gt-react"; import type { SidebarThreadSummary } from "../../types"; -import { ThreadWorktreeIndicator } from "../ThreadStatusIndicators"; +import { ThreadWorktreeIndicator } from "../sidebar/ThreadWorktreeIndicator"; import { MiddleTruncate } from "../ui/middle-truncate"; import { cn } from "~/lib/utils"; -/** - * Fork: what a row inside a project run puts where its project label used to - * be. The run header carries the project now, so the slot goes to the branch — - * the row's other stable identifier, and the one two-line cards otherwise drop - * with their third line. Rows without a branch fall back to a spacer, which - * keeps the status slot hard right. - * - * A coordinator whose children span projects shows "Cross-project" instead, - * in and outside a run, like its children below it show their projects: its - * own project would say less (see `sidebarRowLead`). - */ +/** The run header owns the project label, so rows use this slot for their distinguishing branch. */ export function SidebarProjectRunRowLead(props: { thread: Pick; crossProject?: boolean; @@ -30,7 +21,7 @@ export function SidebarProjectRunRowLead(props: { props.recede ? "font-normal" : "font-medium", )} > - Cross-project + Cross-project ); diff --git a/apps/web/src/components/ui/scroll-area.tsx b/apps/web/src/components/ui/scroll-area.tsx index ab31b7ca31d88..b391f8bc274fb 100644 --- a/apps/web/src/components/ui/scroll-area.tsx +++ b/apps/web/src/components/ui/scroll-area.tsx @@ -27,6 +27,7 @@ function ScrollArea({ scrollbarGutter = false, hideScrollbars = false, chainVerticalScroll = false, + observeContent = false, radius = "inherit", viewportTabIndex, ...props @@ -36,6 +37,7 @@ function ScrollArea({ scrollbarGutter?: boolean; hideScrollbars?: boolean; chainVerticalScroll?: boolean; + observeContent?: boolean; radius?: "inherit" | "none"; viewportTabIndex?: number; }) { @@ -63,7 +65,14 @@ function ScrollArea({ )} data-slot="scroll-area-viewport" > - {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..cca4d8a43fd61 --- /dev/null +++ b/apps/web/src/components/ui/shared-tooltip.tsx @@ -0,0 +1,265 @@ +import { + cloneElement, + createContext, + use, + useEffect, + useId, + useRef, + useState, + type FocusEvent, + type PointerEvent, + type ReactElement, + type ReactNode, +} from "react"; +import { flushSync } from "react-dom"; + +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(); + // A Root that mounts open skips Base UI's mount transition, so the popup would slide in from (0,0). + if (!current.current) flushSync(() => commit({ ...content, anchor, open: false })); + 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..344ddcea7f0f1 100644 --- a/apps/web/src/components/ui/tooltip.browser.test.tsx +++ b/apps/web/src/components/ui/tooltip.browser.test.tsx @@ -3,41 +3,136 @@ 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"); + + 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()); +}); - screen.getByTestId("timeline").element().scrollTop = 20; - await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); +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(); +}); - if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); - else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); +it("opens a shared tooltip in place the first time", async () => { + await using _screen = await render( + // Away from the corner the unpositioned popup sits in, so a slide from there is a real move. +
    + + }> + Target + + +
    , + ); + // Focus opens it at once, while a position transition would still be running. + await userEvent.keyboard("{Tab}"); + await expect.element(page.getByText("Description")).toBeVisible(); + const moving = document + .getAnimations() + .filter((animation) => animation instanceof CSSTransition) + .map((transition) => transition.transitionProperty) + .filter((property) => ["top", "left", "right", "bottom", "transform"].includes(property)); + expect(moving).toEqual([]); }); 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 e2bc469b67758..97b870ea8e44d 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -521,7 +521,7 @@ export function UsagePage() {
  • - + {selectedEnvironments.length === 0 ? (

    diff --git a/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.test.ts b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.test.ts new file mode 100644 index 0000000000000..736aa4648aaf9 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { diskChange, staleAfterSave } from "./WorkflowDefinitionEditor.logic"; + +describe("diskChange", () => { + it.each([ + [ + "a clean editor follows the file", + { source: "B", baseline: "A", dirty: false, saving: null }, + "follow", + ], + [ + "edits over a change are stale", + { source: "B", baseline: "A", dirty: true, saving: null }, + "stale", + ], + [ + "the file it already holds is nothing", + { source: "A", baseline: "A", dirty: true, saving: null }, + "ignore", + ], + [ + "the save's own text is nothing", + { source: "C", baseline: "A", dirty: true, saving: "C" }, + "ignore", + ], + // The disk went A → B → A while C was being saved: back at the baseline, but not what was saved. + [ + "a change back to the baseline during a save is stale", + { source: "A", baseline: "A", dirty: true, saving: "C" }, + "stale", + ], + ] as const)("%s", (_, input, expected) => { + expect(diskChange(input)).toBe(expected); + }); +}); + +describe("staleAfterSave", () => { + it("settles the change the person saved over and keeps a newer one", () => { + const b = { source: "B" }; + expect(staleAfterSave(b, b)).toBeNull(); + const a = { source: "A" }; + expect(staleAfterSave(a, b)).toBe(a); + expect(staleAfterSave(a, null)).toBe(a); + // The disk went B → A → B while the save was out: back at the same text, but a change of its own. + const bAgain = { source: "B" }; + expect(staleAfterSave(bAgain, b)).toBe(bAgain); + }); +}); diff --git a/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.ts b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.ts new file mode 100644 index 0000000000000..c056c6576f061 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.ts @@ -0,0 +1,23 @@ +/** + * What a new version of the file on disk means for an editor holding `baseline`. A change that + * lands while a save is out is never the save's own unless it is the saved text itself. + */ +export function diskChange(input: { + readonly source: string; + readonly baseline: string; + readonly dirty: boolean; + readonly saving: string | null; +}): "follow" | "stale" | "ignore" { + if (input.saving !== null) return input.source === input.saving ? "ignore" : "stale"; + if (input.source === input.baseline) return "ignore"; + return input.dirty ? "stale" : "follow"; +} + +/** One change on disk the person has not settled. Each change is its own, even with the same text. */ +export interface DiskChange { + readonly source: string; +} + +/** The warning after a save: the change the person saved over is settled, any later one stays. */ +export const staleAfterSave = (now: DiskChange | null, overwrote: DiskChange | null) => + now === overwrote ? null : now; diff --git a/apps/web/src/components/workflows/WorkflowDefinitionEditor.tsx b/apps/web/src/components/workflows/WorkflowDefinitionEditor.tsx new file mode 100644 index 0000000000000..da810dd5c93ac --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowDefinitionEditor.tsx @@ -0,0 +1,575 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { FileContents } from "@pierre/diffs"; +import { Editor, type EditorFactory, type EditorOptions, type Marker } from "@pierre/diffs/edit"; +import { EditProvider, File, Virtualizer } from "@pierre/diffs/react"; +import { type EnvironmentId, type WorkflowDefinitionProblem } from "@t3tools/contracts"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { useBlocker } from "@tanstack/react-router"; +import { T, useGT, Var } from "gt-react"; +import { FileCode2Icon, PlusIcon } from "lucide-react"; +import { useEffect, useRef, useState, type KeyboardEvent } from "react"; +import { createPortal } from "react-dom"; + +import { requestConfirmDialog } from "../../confirmDialog"; +import { useTheme } from "../../hooks/useTheme"; +import { resolveDiffThemeName } from "../../lib/diffRendering"; +import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting"; +import { isMacPlatform } from "../../lib/utils"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider"; +import { useEditableAfterHighlight } from "../files/useEditableAfterHighlight"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; +import { type DiskChange, diskChange, staleAfterSave } from "./WorkflowDefinitionEditor.logic"; +import { WorkflowsEmpty } from "./WorkflowRunsView"; + +type DefinitionEditor = Editor<"file", undefined, undefined>; +const createEditor: EditorFactory = (editorType, options, editStateKey) => + new Editor(editorType, options, editStateKey); + +const fileOf = (path: string, contents: string, revision: number): FileContents => ({ + name: path, + contents, + cacheKey: `workflow-definition:${path}:${revision}:${contents.length}`, +}); + +/** A problem that names a line, as a squiggle under that line. */ +const markersOf = (problems: ReadonlyArray): Array => + problems.flatMap((problem) => + problem.line === undefined + ? [] + : [ + { + start: { line: problem.line - 1, character: 0 }, + end: { line: problem.line - 1, character: Number.MAX_SAFE_INTEGER }, + severity: "error" as const, + message: problem.message, + source: "workflows", + }, + ], + ); + +function ProblemList({ + title, + problems, +}: { + readonly title: string; + readonly problems: ReadonlyArray; +}) { + return ( +

    +

    {title}

    +
      + {problems.map((problem) => ( +
    • + {problem.line === undefined ? null : ( + + + Line {problem.line}: + {" "} + + )} + {problem.message} +
    • + ))} +
    +
    + ); +} + +function Surface({ + environmentId, + name, + path, + source, + revision, + onDisk, + draft, + offline, + onDelete, + onClose, + actions, +}: { + readonly environmentId: EnvironmentId; + readonly name: string; + readonly path: string; + readonly source: string; + readonly revision: number; + /** Why the file on disk is not what runs, when it is not. */ + readonly onDisk: ReadonlyArray; + /** What a file that is not on disk yet starts as. */ + readonly draft?: string; + /** The environment is away: the draft stays, and nothing is sent until it is back. */ + readonly offline: boolean; + /** Take the file away, saying whether it went. Absent where that cannot be done. */ + readonly onDelete?: (() => Promise) | undefined; + /** Leave the file for the list. */ + readonly onClose: () => void; + /** Where in the page's header the file's status and its actions go. */ + readonly actions: HTMLElement | null; +}) { + const { resolvedTheme } = useTheme(); + const gt = useGT(); + const canSave = useAtomValue( + serverEnvironment.saveWorkflowDefinition.permissionAtom(environmentId), + ); + const save = useAtomCommand(serverEnvironment.saveWorkflowDefinition, { + label: "workflow definition save", + }); + // What the draft started from. The file on disk moving past it is someone else's edit. + const [baseline, setBaseline] = useState(source); + // The file as this editor last took note of it, so only a real change on disk is acted on: after + // a save, `source` is still the old text until the server's answer is read again. + const [seen, setSeen] = useState(source); + // The disk text that changed under the person's edits, until they settle it. + const [staleAt, setStaleAt] = useState(null); + const stale = staleAt !== null; + const [shown, setShown] = useState(() => fileOf(path, draft ?? source, revision)); + const [edited, setEdited] = useState(draft ?? null); + const [problems, setProblems] = useState>([]); + // The last save wrote the file, so its problems are why it does not run, not why it was refused. + const [written, setWritten] = useState(false); + const [failure, setFailure] = useState(null); + // The text a save in flight is writing, so its own echo from disk is told from a real change. + const [savingText, setSavingText] = useState(null); + const saving = savingText !== null; + const [savedOnce, setSavedOnce] = useState(false); + const [deleting, setDeleting] = useState(false); + // Set once the file is deleted, so leaving it does not ask about a draft of a file that is gone. + const released = useRef(false); + const [seenRevision, setSeenRevision] = useState(revision); + const editorRef = useRef(null); + const dirty = edited !== null && edited !== baseline; + const adopt = () => { + setBaseline(source); + setShown(fileOf(path, source, revision)); + setEdited(null); + setProblems([]); + setStaleAt(null); + }; + if (source !== seen) { + setSeen(source); + // With nothing of the person's own in the editor, it follows the file. + const change = diskChange({ source, baseline, dirty, saving: savingText }); + if (change === "stale") setStaleAt({ source }); + else if (change === "follow") adopt(); + } + // Why a saved file did not run is old news once the server loads it cleanly. + if (revision !== seenRevision) { + setSeenRevision(revision); + if (written && onDisk.length === 0) setProblems([]); + } + const { ready: editable, onPostRender } = useEditableAfterHighlight(shown); + + const saveNow = async () => { + if (!dirty || saving || deleting || offline || !canSave || edited === null) return; + // Saving over a change on disk that was already shown is a choice. One that lands while this + // save is out is not, and stays shown. + const overwrote = staleAt; + setSavingText(edited); + setFailure(null); + const result = await save({ environmentId, input: { name, source: edited } }); + setSavingText(null); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) setFailure(String(squashAtomCommandFailure(result))); + return; + } + setProblems(result.value.problems); + setWritten(result.value.changed); + if (!result.value.changed) return; + setBaseline(edited); + setStaleAt((now) => staleAfterSave(now, overwrote)); + setSavedOnce(true); + }; + const onKeyDown = (event: KeyboardEvent) => { + const mac = isMacPlatform(navigator.platform); + if (event.key.toLowerCase() !== "s" || !(mac ? event.metaKey : event.ctrlKey)) return; + event.preventDefault(); + void saveNow(); + }; + const deleteNow = async () => { + if (onDelete === undefined || deleting || saving) return; + // Busy from the dialog on, so a save cannot slip in while it asks. + setDeleting(true); + const gone = await onDelete(); + setDeleting(false); + if (!gone) return; + released.current = true; + onClose(); + }; + // Leaving with an unsaved draft, by a link in the app or by closing the tab, asks first. + useBlocker({ + shouldBlockFn: async () => + dirty && + !released.current && + !(await (requestConfirmDialog( + gt("Leave without saving? Your changes to this file are lost."), + { + variant: "destructive", + }, + ) ?? Promise.resolve(false))), + enableBeforeUnload: () => dirty && !released.current, + }); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the editor draws markers itself and takes them only through its own method + useEffect(() => { + editorRef.current?.setMarkers(markersOf(problems)); + }, [problems]); + + const editorOptions: EditorOptions<"file", undefined, undefined> = { + onAttach: (editor) => { + editorRef.current = editor; + editor.setMarkers(markersOf(problems)); + }, + onComplete: () => { + editorRef.current = null; + }, + }; + const status = offline + ? gt("Not connected") + : saving + ? gt("Checking…") + : dirty + ? gt("Unsaved changes") + : savedOnce && problems.length === 0 + ? gt("Saved and running") + : null; + + return ( +
    + {actions === null + ? null + : createPortal( + <> + + {canSave || offline ? status : gt("Read-only")} + + {canSave && onDelete !== undefined ? ( + + ) : null} + {canSave ? ( + + ) : null} + , + actions, + )} + {stale ? ( +
    + + The file changed on disk while you were editing. Saving replaces that change. + + +
    + ) : null} + {onDisk.length > 0 && problems.length === 0 ? ( + + ) : null} + {problems.length > 0 ? ( + + ) : null} + {failure === null ? null : ( + + )} + + + setEdited(file.contents)} + options={{ + disableFileHeader: true, + overflow: "scroll", + theme: resolveDiffThemeName(resolvedTheme), + preferredHighlighter: PREFERRED_HIGHLIGHTER, + themeType: resolvedTheme, + onPostRender: (_container, instance, phase) => onPostRender(instance.file, phase), + }} + className="min-h-full" + /> + + +
    + ); +} + +const NEW_FILE = `const { workflow, step, agent, ask, stop } = T3; + +workflow( + "my-workflow", + { version: 1, payload: Schema.Struct({}) }, + Effect.fn(function* () { + // yield* agent("first", { project: "/path/to/project", brief: "What to do." }); + }), +); +`; + +/** + * The files that define this server's workflows: the list of them, or `file` in an editor. A + * `file` the folder does not have yet is a new one, which exists once it is saved. + */ +export default function WorkflowDefinitionEditor({ + environmentId, + file, + away, + onOpen, + actions, +}: { + readonly environmentId: EnvironmentId; + readonly file: string | null; + /** The environment's name while it is not connected. */ + readonly away: string | null; + readonly onOpen: (file: string | null) => void; + readonly actions: HTMLElement | null; +}) { + const query = useEnvironmentQuery( + serverEnvironment.workflowDefinition({ environmentId, input: {} }), + ); + const canChange = useAtomValue( + serverEnvironment.saveWorkflowDefinition.permissionAtom(environmentId), + ); + const remove = useAtomCommand(serverEnvironment.deleteWorkflowDefinition, { + label: "workflow definition delete", + }); + const gt = useGT(); + const [naming, setNaming] = useState(null); + // What the last delete said, on the page it belongs to: the file, or the list once it is gone. + const [refusal, setRefusal] = useState<{ + readonly at: string | null; + readonly problems: ReadonlyArray; + readonly deleted: boolean; + } | null>(null); + // Data already read stays on screen through a failed refresh or a dropped connection. + if (!query.data) { + if (away !== null) { + return ( + + ); + } + if (query.error) { + return ( + + ); + } + return ( +

    + Loading the workflow files… +

    + ); + } + const { directory, single, files, problems, revision } = query.data; + const open = (next: string | null) => { + setRefusal(null); + onOpen(next); + }; + const begin = () => { + const wanted = (naming ?? "").trim(); + if (wanted === "") return; + setNaming(null); + open(/\.(ts|mts|js|mjs)$/.test(wanted) ? wanted : `${wanted}.ts`); + }; + const removeFile = async (target: string) => { + const confirmed = await (requestConfirmDialog( + gt("Delete {file}? The workflows it defines can no longer be started.", { file: target }), + { variant: "destructive" }, + ) ?? Promise.resolve(false)); + if (!confirmed) return false; + const result = await remove({ environmentId, input: { name: target } }); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) { + setRefusal({ + at: target, + problems: [{ message: String(squashAtomCommandFailure(result)) }], + deleted: false, + }); + } + return false; + } + const { changed } = result.value; + setRefusal( + result.value.problems.length === 0 + ? null + : { at: changed ? null : target, problems: result.value.problems, deleted: changed }, + ); + return changed; + }; + const refused = refusal !== null && refusal.at === file ? refusal : null; + const between = ( + <> + {away === null ? null : ( +
    + {gt("{name} is not connected. What you write here stays, and saves once it is back.", { + name: away, + })} +
    + )} + {query.error === null || away !== null ? null : ( + + )} + {problems.length === 0 && refused === null ? null : ( + + )} + + ); + + if (file !== null) { + const shown = files.find((candidate) => candidate.name === file) ?? null; + return ( +
    + {between} + + removeFile(file)} + onClose={() => onOpen(null)} + actions={actions} + /> + +
    + ); + } + + return ( +
    + {between} +
    +
    +
    +

    + + Every file in{" "} + + {directory} + {" "} + defines workflows. A change to one is picked up without a restart. + +

    + {single || !canChange ? null : naming === null ? ( + + ) : ( + { + event.preventDefault(); + begin(); + }} + > + setNaming(event.target.value)} + onKeyDown={(event) => { + if (event.key === "Escape") setNaming(null); + }} + /> + + + )} +
    + {files.length === 0 ? ( +

    + + No workflows yet. Make the first file here, or ask an agent to write one in that + folder. + +

    + ) : ( +
      + {files.map((candidate) => ( +
    • + +
    • + ))} +
    + )} +
    +
    +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowPane.tsx b/apps/web/src/components/workflows/WorkflowPane.tsx new file mode 100644 index 0000000000000..e23d5de8a50c7 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowPane.tsx @@ -0,0 +1,179 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { workflowReferenceLabel } from "@t3tools/client-runtime/workflows"; +import { EnvironmentId, ThreadId, type WorkflowRunReference } from "@t3tools/contracts"; +import { useGT } from "gt-react"; +import { BotIcon, Maximize2Icon, XIcon } from "lucide-react"; + +import { cn } from "../../lib/utils"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { Button } from "../ui/button"; +import { + activeWorkflowPaneIndex, + closeWorkflowPaneTab, + openWorkflowPaneTab, + type WorkflowPaneState, + type WorkflowPaneTab, +} from "./workflowPane.logic"; +import { + useOpenReferencePage, + WorkflowReferenceMark, + WorkflowReferencePanel, +} from "./WorkflowReferences"; +import WorkflowThreadPane, { + useOpenThreadPage, + WorkflowThreadTabLabel, +} from "./WorkflowThreadPane"; + +/** + * The pane beside a run: a tab per transcript or reference opened from it. Only the tab that + * shows is mounted, so a pane with a chat and two pull requests renders one of them. + */ +export default function WorkflowPane({ + environmentId, + runId, + state, + onChange, +}: { + readonly environmentId: EnvironmentId; + readonly runId: string | null; + readonly state: WorkflowPaneState; + readonly onChange: (next: WorkflowPaneState) => void; +}) { + const gt = useGT(); + const detail = useEnvironmentQuery( + runId === null ? null : serverEnvironment.workflowRun({ environmentId, input: { runId } }), + ); + const openThreadPage = useOpenThreadPage(); + const openReferencePage = useOpenReferencePage(environmentId); + const tabs = state.pane ?? []; + const activeIndex = activeWorkflowPaneIndex(state); + const active = tabs[activeIndex]; + const threadOf = (tab: Extract) => + scopeThreadRef( + tab.env === undefined ? environmentId : EnvironmentId.make(tab.env), + ThreadId.make(tab.thread), + ); + const referenceOf = (tab: Extract) => + detail.data?.references.find( + (reference) => reference.kind === tab.kind && reference.key === tab.key, + ) ?? null; + const activeReference = active === undefined || "thread" in active ? null : referenceOf(active); + const openFull = + active === undefined + ? null + : "thread" in active + ? () => openThreadPage(threadOf(active)) + : activeReference === null + ? null + : openReferencePage(activeReference); + + return ( +
    +
    +
    + {tabs.map((tab, index) => ( +
    + + +
    + ))} +
    + {openFull === null ? null : ( + + )} + +
    +
    + {active === undefined ? null : "thread" in active ? ( + + ) : activeReference !== null ? ( + + ) : ( +

    + {detail.data === null ? gt("Loading…") : gt("This run no longer lists it.")} +

    + )} +
    +
    + ); +} + +function ReferenceTabLabel({ + reference, + fallback, +}: { + readonly reference: WorkflowRunReference | null; + readonly fallback: string; +}) { + if (reference === null) return {fallback}; + return ( + <> + + {workflowReferenceLabel(reference)} + + ); +} diff --git a/apps/web/src/components/workflows/WorkflowReferences.tsx b/apps/web/src/components/workflows/WorkflowReferences.tsx new file mode 100644 index 0000000000000..df89ecc7086cf --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowReferences.tsx @@ -0,0 +1,193 @@ +import { + workflowReferenceIssue, + workflowReferenceLabel, + workflowReferencePullRequest, +} from "@t3tools/client-runtime/workflows"; +import type { EnvironmentId, WorkflowRunReference } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { T } from "gt-react"; +import { CircleCheckIcon, CircleDotIcon, ExternalLinkIcon, LinkIcon } from "lucide-react"; + +import { isElectron } from "~/env"; +import { isTerminalFocused } from "../../lib/terminalFocus"; +import { cn } from "../../lib/utils"; +import { ISSUES_PANEL_REF, useRightPanelStore } from "../../rightPanelStore"; +import { IssueDetailPanel } from "../issue/IssueDetailPanel"; +import { readIssueListPreferences } from "../issue/issueListPreferences"; +import { PullRequestDetailPanel } from "../pullRequest/PullRequestDetailPanel"; +import { PULL_REQUEST_STATE_PRESENTATION } from "../pullRequest/pullRequestIcons"; +import { Button } from "../ui/button"; + +/** The mark a reference wears: its kind's icon, in the ink its state has on its own page. */ +function referenceGlyph(reference: WorkflowRunReference) { + if (workflowReferencePullRequest(reference) !== null) { + const state = + reference.state === "closed" || reference.state === "merged" ? reference.state : "open"; + return PULL_REQUEST_STATE_PRESENTATION[state]; + } + if (workflowReferenceIssue(reference) !== null) { + return reference.state === "closed" + ? { + Icon: CircleCheckIcon, + toneClassName: PULL_REQUEST_STATE_PRESENTATION.merged.toneClassName, + } + : { Icon: CircleDotIcon, toneClassName: PULL_REQUEST_STATE_PRESENTATION.open.toneClassName }; + } + return { Icon: LinkIcon, toneClassName: "text-muted-foreground" }; +} + +export function WorkflowReferenceMark({ reference }: { readonly reference: WorkflowRunReference }) { + const glyph = referenceGlyph(reference); + return ; +} + +/** A thing the run touched, as a chip that opens it beside the run. */ +export function WorkflowReferenceChip({ + reference, + open, + small = false, + onOpen, +}: { + readonly reference: WorkflowRunReference; + /** It shows in the pane now, so another click closes it. */ + readonly open: boolean; + /** On a step, where the label is enough. */ + readonly small?: boolean; + readonly onOpen: () => void; +}) { + const label = workflowReferenceLabel(reference); + const title = reference.title === label ? "" : reference.title; + const name = title === "" ? label : `${label} ${title}`; + return ( + + ); +} + +const shortcutContext = () => ({ + terminalFocus: isTerminalFocused(), + terminalOpen: false, + previewFocus: false, + previewOpen: false, + isWeb: !isElectron, + isDesktop: isElectron, +}); + +/** Opens the reference on its own page, where it has the whole window. Null for a kind with none. */ +export function useOpenReferencePage( + environmentId: EnvironmentId, +): (reference: WorkflowRunReference) => (() => void) | null { + const navigate = useNavigate(); + return (reference) => { + const issue = workflowReferenceIssue(reference); + if (issue !== null) { + return () => { + // The Issues page shows the issue its panel has open; the address keeps the list's place. + useRightPanelStore.getState().openIssue(ISSUES_PANEL_REF, { + environmentId, + projectId: issue.projectId, + tracker: issue.tracker, + ...(issue.host === undefined ? {} : { host: issue.host }), + scope: issue.scope, + key: issue.key, + ...(reference.url === null ? {} : { url: reference.url }), + }); + void navigate({ + to: "/issues", + search: { + ...readIssueListPreferences(), + selectedEnvironmentId: environmentId, + selectedProjectId: issue.projectId, + ...(issue.host === undefined ? {} : { selectedHost: issue.host }), + tracker: issue.tracker, + scope: issue.scope, + key: issue.key, + }, + }); + }; + } + const pullRequest = workflowReferencePullRequest(reference); + if (pullRequest !== null) { + return () => + void navigate({ + to: "/pull-requests", + search: { + involvement: "all", + state: "all", + repository: pullRequest.repository, + number: pullRequest.number, + ...(pullRequest.host === undefined ? {} : { selectedHost: pullRequest.host }), + selectedProjectId: pullRequest.projectId, + selectedEnvironmentId: environmentId, + }, + }); + } + return null; + }; +} + +/** A reference opened beside its run: the Issues or Pull requests page's own view of it. */ +export function WorkflowReferencePanel({ + environmentId, + reference, +}: { + readonly environmentId: EnvironmentId; + readonly reference: WorkflowRunReference; +}) { + const issue = workflowReferenceIssue(reference); + if (issue !== null) { + return ; + } + const pullRequest = workflowReferencePullRequest(reference); + if (pullRequest !== null) { + return ( + + ); + } + // A kind this client does not know yet: what the run knows of it, and where it lives. + return ( +
    +

    + {reference.title === "" ? workflowReferenceLabel(reference) : reference.title} +

    +

    + + {reference.kind} + {reference.state === null ? null : ( + <> + · + {reference.state} + + )} +

    + {reference.url === null ? null : ( + + )} +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowRunFeed.tsx b/apps/web/src/components/workflows/WorkflowRunFeed.tsx new file mode 100644 index 0000000000000..d77b54d8dcc11 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunFeed.tsx @@ -0,0 +1,1924 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, + type AtomCommandResult, +} from "@t3tools/client-runtime/state/runtime"; +import { + EnvironmentId, + ThreadId, + type WorkflowQuestion, + type WorkflowRun, + type WorkflowRunReference, +} from "@t3tools/contracts"; +import { formatModelSlugName } from "@t3tools/shared/model"; +import { formatDuration } from "@t3tools/shared/orchestrationTiming"; +import { msg, T, useGT, useMessages, Var } from "gt-react"; +import { + ArrowLeftIcon, + ArrowUpRightIcon, + ChevronRightIcon, + BotIcon, + CheckIcon, + CircleAlertIcon, + HourglassIcon, + MoonIcon, + SquareIcon, +} from "lucide-react"; +import { secondTick } from "@t3tools/client-runtime/clock"; +import { + createContext, + useContext, + useRef, + useState, + useSyncExternalStore, + type ReactNode, +} from "react"; + +import { requestConfirmDialog } from "../../confirmDialog"; +import { useNowMinute } from "../../hooks/useNowMinute"; +import { cn } from "../../lib/utils"; +import { useQuietThreadShell } from "../../state/entities"; +import { useEnvironment, useEnvironmentProviders } from "../../state/environments"; +import { type MessageResolver } from "../../i18n/messages"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { formatRelativeTimeLabel } from "../../timestampFormat"; +import ChatMarkdown from "../ChatMarkdown"; +import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; +import { stackedThreadToast, toastManager } from "../ui/toast"; +import { + buildWorkflowFeed, + buildWorkflowTimeline, + readWorkflowQuestion, + workflowAgentSummary, + workflowAnswer, + workflowChip, + workflowFlowFocus, + workflowPausedBeat, + workflowResultLines, + workflowRunNow, + workflowRunState, + workflowSaidStart, + workflowStepReferences, + workflowStepTime, + workflowOneLine, + type WorkflowBeat, + type WorkflowFeedRow, + type WorkflowQuickSteps, + type WorkflowRunNode, + type WorkflowRunTone, +} from "@t3tools/client-runtime/workflows"; +import type { WorkflowPaneTab } from "./workflowPane.logic"; +import { WorkflowReferenceChip } from "./WorkflowReferences"; + +/** An agent's thread, as a step names it: the linked environment it is in, or null for this one. */ +export interface WorkflowThreadTarget { + readonly threadId: string; + readonly environmentId: string | null; +} + +// An agent that wrote a page gets a few lines of it; the rest is a click away. +const SAID_SHOWN = 320; + +// What waits on a person is what they came for, so it is in view when the run opens. +const revealOnMount = (element: HTMLElement | null) => { + element?.scrollIntoView({ block: "nearest" }); +}; + +function reportFailure(title: string, result: AtomCommandResult) { + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; + toastManager.add( + stackedThreadToast({ + type: "error", + title, + description: String(squashAtomCommandFailure(result)), + }), + ); +} + +// Reads the minute tick because the compiler caches a render-time Date.now() on the timestamp. +function useNowMs(): number { + return Date.parse(`${useNowMinute()}:00.000Z`); +} + +// A time still counting is told to the second: its tenths would only flicker. +const wholeSeconds = (ms: number) => Math.max(1000, Math.round(ms / 1000) * 1000); +const elapsedOf = (beat: WorkflowBeat) => + beat.status === "running" ? wholeSeconds(beat.endMs - beat.startMs) : beat.endMs - beat.startMs; + +const never = () => () => {}; +const noTick = () => 0; + +/** The clock a run is told by: to the second while it is under way, to the minute after. */ +function useRunNowMs(live: boolean): number { + const minute = useNowMs(); + const second = useSyncExternalStore( + live ? secondTick.subscribe : never, + live ? secondTick.getSnapshot : noTick, + live ? secondTick.getSnapshot : noTick, + ); + return live ? second : minute; +} + +export function RelativeLabel({ value }: { readonly value: string }) { + return formatRelativeTimeLabel(value, useNowMs()); +} + +const CHIP_TONES = [ + "bg-sky-500/15 text-sky-700 dark:text-sky-300", + "bg-violet-500/15 text-violet-700 dark:text-violet-300", + "bg-amber-500/15 text-amber-700 dark:text-amber-300", + "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300", + "bg-rose-500/15 text-rose-700 dark:text-rose-300", +] as const; + +/** Which workflow a run is of, at a glance: the same letters and colour wherever it shows. */ +export function WorkflowChip({ name }: { readonly name: string }) { + const chip = workflowChip(name); + return ( + + {chip.letters} + + ); +} + +// The thread list's own colours for the same states, so a run reads like a thread does. +const WORKFLOW_TONE_CLASS: Record = { + input: "text-warning-foreground", + failed: "text-destructive", + working: "text-info-foreground", + quiet: "text-muted-foreground", + done: "text-success-foreground", +}; + +export function WorkflowStateWord({ node }: { readonly node: WorkflowRunNode }) { + const m = useMessages(); + const state = workflowRunState(node, m); + return ( + + {state.tone === "working" ? ( + + ) : state.tone === "done" ? ( + + ) : null} + {state.word} + + ); +} + +const nthTry = (count: number, resolve: MessageResolver) => + resolve( + msg("{count, plural, =1 {1st try} =2 {2nd try} =3 {3rd try} other {{count}th try}}", { + count, + }), + ); + +// The loading view and the timeline each draw a question's card, so a reason typed while the +// steps load is kept here rather than in the card that is about to be replaced. +const AnswerDrafts = createContext<{ + readonly get: (key: string) => string | null; + readonly set: (key: string, reason: string | null) => void; +} | null>(null); + +export function WorkflowRunFeed({ + environmentId, + node, + parent, + shownTab, + onSelect, + onOpenThread, + onOpenReference, +}: { + readonly environmentId: EnvironmentId; + readonly node: WorkflowRunNode; + readonly parent: WorkflowRun | null; + /** What shows beside the run, so the card or chip that opened it can say so. */ + readonly shownTab: WorkflowPaneTab | null; + readonly onSelect: (runId: string | null) => void; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; + readonly onOpenReference: (reference: WorkflowRunReference) => void; +}) { + const { run } = node; + const gt = useGT(); + const clockMs = useRunNowMs(node.run.endedAt === null); + // An ended run's last step can still read as running for a moment; it ran until the run ended. + const nowMs = node.run.endedAt === null ? clockMs : Date.parse(node.run.endedAt); + const panel = useRef(null); + const [picked, setPicked] = useState(null); + // Steps already there when the run opens are simply shown; only later ones arrive with motion. + const [openedAtMs] = useState(() => Date.now()); + const detail = useEnvironmentQuery( + serverEnvironment.workflowRun({ environmentId, input: { runId: run.runId } }), + ); + const canResume = useAtomValue(serverEnvironment.resumeWorkflowRun.permissionAtom(environmentId)); + const canCancel = useAtomValue(serverEnvironment.cancelWorkflowRun.permissionAtom(environmentId)); + const resume = useAtomCommand(serverEnvironment.resumeWorkflowRun, { label: "workflow resume" }); + const cancel = useAtomCommand(serverEnvironment.cancelWorkflowRun, { label: "workflow cancel" }); + const [busy, setBusy] = useState(false); + const target = { environmentId, input: { runId: run.runId } }; + const [drafts, setDrafts] = useState>(() => new Map()); + const answerDrafts = { + get: (key: string) => drafts.get(key) ?? null, + set: (key: string, reason: string | null) => + setDrafts((current) => { + const next = new Map(current); + if (reason === null) next.delete(key); + else next.set(key, reason); + return next; + }), + }; + const resumeRun = async () => { + if (busy) return; + setBusy(true); + const result = await resume(target); + setBusy(false); + reportFailure(gt("Could not resume the run"), result); + }; + const cancelRun = async () => { + if (busy) return; + // Busy while the dialog is up, so a second click does not open a second one. + setBusy(true); + const confirmed = await (requestConfirmDialog( + gt("Cancel {title}? Its agents stop and the run cannot be resumed.", { title: run.title }), + { variant: "destructive" }, + ) ?? Promise.resolve(false)); + if (!confirmed) return setBusy(false); + const result = await cancel(target); + setBusy(false); + reportFailure(gt("Could not cancel the run"), result); + }; + const ended = run.endedAt !== null; + const ranMs = ended + ? Date.parse(run.endedAt) - Date.parse(run.startedAt) + : wholeSeconds(nowMs - Date.parse(run.startedAt)); + const steps = detail.data?.steps; + const references = detail.data?.references ?? []; + // An open transcript is one thread in one environment; `env` is absent for the run's own. + const openThread = shownTab !== null && "thread" in shownTab ? shownTab : null; + const chip = (reference: WorkflowRunReference, small = false) => ( + onOpenReference(reference)} + /> + ); + const feed = + steps === undefined + ? null + : buildWorkflowFeed( + buildWorkflowTimeline({ + run, + steps, + children: node.children.map((child) => child.run), + nowMs, + }), + ); + const beats = (feed ?? []).flatMap((row) => + row.kind === "quick" ? [] : row.kind === "together" ? row.beats : [row], + ); + // A question is told where it was asked. One whose step is not in the list yet still shows. + const questionOf = (beat: WorkflowBeat) => + beat.kind === "ask" && beat.status === "running" + ? (node.questions.find((question) => question.name === beat.name) ?? null) + : null; + const loose = node.questions.filter( + (question) => !beats.some((beat) => questionOf(beat) === question), + ); + const pausedAt = feed === null ? null : workflowPausedBeat(feed, run.status); + const pause = (name: string | null, attempts: number, reason: string | null) => ( + void resumeRun()} + kept={(steps ?? []).some((step) => step.status === "completed")} + /> + ); + const beatCard = (beat: WorkflowBeat) => { + if (beat === pausedAt) { + // The step's own card stays, so its transcript can be read before resuming. + return ( +
    + {pause(beat.name, beat.attempts, beat.detail ?? run.detail)} + {stepCard(beat)} +
    + ); + } + return stepCard(beat); + }; + const stepCard = (beat: WorkflowBeat) => ( + child.run.runId === beat.childRun?.runId) ?? null} + nowMs={nowMs} + open={ + beat.thread !== null && + openThread !== null && + beat.thread.threadId === openThread.thread && + (beat.thread.environmentId ?? undefined) === openThread.env + } + onSelect={onSelect} + onOpenThread={onOpenThread} + /> + ); + const resultLines = workflowResultLines(run.result); + const pausedApart = run.status === "paused" && pausedAt === null; + const keys = new Set([ + ...(feed ?? []).flatMap((row) => (row.kind === "quick" ? [`quick:${row.steps[0]?.name}`] : [])), + ...beats.map((beat) => `step:${beat.name}`), + ...loose.map((question) => `question:${question.name}`), + ...(pausedApart ? ["pause"] : []), + ...(ended ? ["end"] : []), + ]); + // A run that finished opens on what it came to: its result when that says more than the last + // answer, else the last agent's reply. The header already says it is done. + const lastAnswer = beats.findLast((beat) => beat.kind === "ask" && beat.status === "completed"); + const answered = lastAnswer === undefined ? null : workflowAnswer(lastAnswer.result); + const resultSaysMore = + resultLines.length > 0 && + !(resultLines.length === 1 && answered !== null && resultLines[0]?.value === answered.choice); + const latest = (found: ReadonlyArray) => + found.reduce( + (best, beat) => (best === undefined || beat.endMs >= best.endMs ? beat : best), + undefined, + ); + const lastAgent = latest( + beats.filter((beat) => beat.kind === "agent" && beat.status === "completed"), + ); + const finishedFocus = + run.status !== "completed" || resultSaysMore || lastAgent === undefined + ? "end" + : `step:${lastAgent.name}`; + const focus = + picked !== null && keys.has(picked) + ? picked + : feed === null + ? null + : ended + ? finishedFocus + : workflowFlowFocus({ + rows: feed, + status: run.status, + ended, + questions: node.questions.map((question) => question.name), + }); + const pick = (key: string) => { + const asks = + key.startsWith("question:") || + beats.some((beat) => `step:${beat.name}` === key && questionOf(beat) !== null); + setPicked(asks ? null : key); + // Below the flow on a narrow page, so picking a step brings what it shows into view; a + // question is answered where it is, so the page stays put. + if (!asks) panel.current?.scrollIntoView({ block: "nearest" }); + }; + const endWord = + run.status === "completed" + ? gt("Finished", { $context: "how a workflow run ended" }) + : run.status === "stopped" + ? gt("Stopped", { $context: "how a workflow run ended" }) + : run.status === "skipped" + ? gt("Skipped", { $context: "how a workflow run ended" }) + : gt("Cancelled", { $context: "how a workflow run ended" }); + // A question is answered where it was asked, so beside it is what led up to it. + const asking = + focus !== null && + (focus.startsWith("question:") || + beats.some( + (beat) => + `step:${beat.name}` === focus && + // Answered, its question is gone a moment before the step itself says it is done. + (questionOf(beat) !== null || (beat.kind === "ask" && beat.status === "running")), + )); + // The latest agent's reply is what a person weighs before answering; failing that, the last + // step that left something behind. A sleep or a wait has nothing to say. + const before = asking + ? (latest(beats.filter((beat) => beat.kind === "agent" && beat.status !== "running")) ?? + beats.findLast( + (beat) => + beat.status !== "running" && + beat.kind !== "ask" && + beat.kind !== "sleep" && + beat.kind !== "wait", + ) ?? + null) + : null; + const shown = asking ? (before === null ? null : `step:${before.name}`) : focus; + const shownBeat = beats.find((beat) => `step:${beat.name}` === shown); + const shownQuick = (feed ?? []).find( + (row) => row.kind === "quick" && `quick:${row.steps[0]?.name}` === shown, + ); + + return ( + +
    +
    + + {parent === null ? null : ( + + )} +
    +

    {run.title}

    + + {ended ? null : ( + + )} +
    +

    + + {run.workflow} + · + + + started{" "} + + + + + + {run.status === "paused" ? null : ( + <> + · + + {ended + ? gt("took {duration}", { duration: formatDuration(ranMs) }) + : gt("{duration} so far", { duration: formatDuration(ranMs) })} + + + )} + {run.retired ? ( + <> + · + + its version is no longer registered + + + ) : null} +

    + {references.length === 0 ? null : ( +
      + {references.map((reference) => ( +
    • + {chip(reference, reference.title !== "" && run.title.includes(reference.title))} +
    • + ))} +
    + )} +
    + + {detail.error || + feed === null || + (feed.length === 0 && run.status === "paused" && loose.length === 0) ? ( + <> + {detail.error ? ( +

    {detail.error}

    + ) : feed === null ? ( +

    + Loading steps… +

    + ) : null} + {/* A question the run already asks is answerable without its step history. */} + {run.status === "paused" ? ( +
    +
    {pause(null, run.pauses, run.detail)}
    +
    + ) : null} + {node.questions.map((question) => ( +
    + +
    + ))} + + ) : ( +
    + +
    + {shownBeat !== undefined ? ( + // Keyed by the step: a reason typed for one question must not follow to the next. +
    + {beatCard(shownBeat)} + {(() => { + // With one reference, the header already says it. + const touched = + references.length > 1 + ? workflowStepReferences(references, shownBeat.name) + : []; + return touched.length === 0 ? null : ( +
    + {touched.map((reference) => chip(reference, true))} +
    + ); + })()} +
    + ) : shownQuick !== undefined && shownQuick.kind === "quick" ? ( + + ) : asking ? null : focus === "pause" ? ( + pause(null, run.pauses, run.detail) + ) : focus === "end" ? ( + + + ) : null + } + name={endWord} + sub={} + /> + {run.status !== "completed" && run.detail ? ( +

    {run.detail}

    + ) : null} + +
    + ) : ( +

    + Nothing yet. +

    + )} +
    +
    + )} +
    +
    + ); +} + +type StepTone = "working" | "input" | "quiet" | "done" | "failed" | "ended"; + +// Colour says what is live: blue for work under way, amber for a person's turn. Done is quiet. +const RING: Record = { + working: "stroke-info", + input: "stroke-warning", + quiet: "stroke-muted-foreground/60", + done: "stroke-muted-foreground/45", + failed: "stroke-destructive", + ended: "stroke-muted-foreground/60", +}; + +const VERB_TONE = { + working: "text-info-foreground", + input: "text-warning-foreground", + quiet: "text-muted-foreground", + failed: "text-destructive", +} as const; + +/** + * A step's place on the rail: a ring, filled while it works, ticked when it is done. `pulse` and + * `draw` never change for a step, so each plays once, when its part of the mark first appears. + */ +function StepMark({ + tone, + pulse, + draw, +}: { + readonly tone: StepTone; + /** It started while the run was open here. */ + readonly pulse: boolean; + /** It ended while the run was open here. */ + readonly draw: boolean; +}) { + const live = tone === "working" || tone === "input"; + return ( + + {live && pulse ? ( + + ) : null} + + + {live || tone === "quiet" ? ( + + ) : tone === "done" ? ( + + ) : tone === "failed" ? ( + + ) : ( + + )} + + + ); +} + +/** One line of the run: its mark on the rail, name, what it is doing, a word on how it went, its time. */ +function TimelineRow({ + tone, + enters, + draw, + lead, + name, + note, + verb, + verbTone = "working", + aside, + asideTone, + duration, + selected, + current = false, + onPick, + sub = false, +}: { + readonly tone: StepTone; + /** It started while the run was open here, so it arrives instead of just being there. */ + readonly enters: boolean; + /** It ended while the run was open here. */ + readonly draw: boolean; + /** A small mark before the name, such as the agent's provider. */ + readonly lead?: ReactNode; + readonly name: string; + /** A quieter word after the name, such as the agent's model. */ + readonly note?: string | null; + readonly verb?: string | null; + readonly verbTone?: keyof typeof VERB_TONE; + readonly aside?: string | null; + readonly asideTone?: "failed"; + readonly duration?: string | null; + readonly selected: boolean; + /** The pane beside the timeline shows it. */ + readonly current?: boolean; + readonly onPick: () => void; + /** A step of a fork, hanging off the branch rather than the rail. */ + readonly sub?: boolean; +}) { + const live = tone === "working" || tone === "input"; + return ( + + ); +} + +/** The rail beside a row: from the row above to this mark, and on to the next unless it is last. */ +function Rail({ first, last }: { readonly first: boolean; readonly last: boolean }) { + return ( + + ); +} + +// A fork leaves the rail under its mark, runs through each step's dot, and rejoins the rail. +// The rail's centre is 10px in and a step's dot 39px in; the mark ends 26px down, the first dot +// sits 46px down, and each dot is 14px below its own row's top. +function BranchOut() { + return ( + + + + ); +} + +function BranchBack() { + return ( + <> + + + + + + ); +} + +/** + * The run as it went, one line per step that took time or involved someone. Steps that ran at once + * hang off a branch. It never draws what comes next: a run can branch, so the rail just goes on. + */ +function WorkflowTimeline({ + environmentId, + rows, + node, + nowMs, + focus, + onPick, + loose, + paused, + end, + question, + onOpenThread, + openedAtMs, + current, +}: { + readonly environmentId: EnvironmentId; + readonly rows: ReadonlyArray; + readonly node: WorkflowRunNode; + readonly nowMs: number; + readonly focus: string | null; + readonly onPick: (key: string) => void; + /** Questions whose step is not in the list yet. */ + readonly loose: ReadonlyArray; + /** The run is paused, and not at a step that failed. */ + readonly paused: boolean; + /** How the run ended, once it has. */ + readonly end: string | null; + /** What it ended with, in a few words. */ + /** The question a step waits on a person for, answered right under it. */ + readonly question: (beat: WorkflowBeat) => WorkflowQuestion | null; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; + /** When this run was opened here: only what changes after that arrives with motion. */ + readonly openedAtMs: number; + /** What the pane beside the timeline shows. */ + readonly current: string | null; +}) { + const gt = useGT(); + const completed = node.run.status === "completed"; + const ask = (asked: WorkflowQuestion) => ( +
    + +
    + ); + const beatRow = (beat: WorkflowBeat, sub = false) => ( + child.run.runId === beat.childRun?.runId) ?? null} + asks={node.questions.some((asked) => asked.name === beat.name)} + nowMs={nowMs} + selected={focus === `step:${beat.name}`} + current={current === `step:${beat.name}`} + onPick={() => onPick(`step:${beat.name}`)} + sub={sub} + openedAtMs={openedAtMs} + /> + ); + const items: Array<{ + readonly key: string; + readonly body: ReactNode; + /** Its steps hang off a branch, which carries the rail past them. */ + readonly branch?: boolean; + }> = []; + for (const row of rows) { + if (row.kind === "quick") { + const key = `quick:${row.steps[0]?.name}`; + // Keyed by its first step, as that step's own row was, so regrouping does not remount it. + const itemKey = row.steps[0]?.name ?? key; + const names = row.steps.map((step) => step.name); + items.push({ + key: itemKey, + body: ( + openedAtMs} + name={ + names.length <= 2 + ? names.join(" · ") + : gt("{names} and {count} more", { + names: names.slice(0, 2).join(" · "), + count: names.length - 2, + }) + } + duration={workflowStepTime(Math.max(0, row.endMs - row.startMs))} + selected={focus === key} + current={current === key} + onPick={() => onPick(key)} + /> + ), + }); + continue; + } + if (row.kind === "together") { + const running = row.beats.filter((beat) => beat.status === "running").length; + // Steps that only sleep or wait are under way without working. + const working = row.beats.some( + (beat) => beat.status === "running" && beat.kind !== "sleep" && beat.kind !== "wait", + ); + const failed = row.beats.some((beat) => beat.status === "failed"); + const asks = row.beats.some( + (beat) => beat.status === "running" && node.questions.some((q) => q.name === beat.name), + ); + const startMs = Math.min(...row.beats.map((beat) => beat.startMs)); + const endMs = Math.max(...row.beats.map((beat) => beat.endMs)); + const first = row.beats[0]; + items.push({ + key: first?.name ?? "together", + branch: true, + body: ( + <> +
    + 0 + ? "quiet" + : failed + ? "failed" + : "done" + } + pulse={startMs > openedAtMs} + draw={running === 0 && endMs > openedAtMs} + /> + 0 ? "font-medium" : "text-muted-foreground", + )} + > + {gt("{count} in parallel", { count: row.beats.length })} + + {working ? ( + + {gt("{count} running", { count: running })} + + ) : null} + + {workflowStepTime(running > 0 ? wholeSeconds(endMs - startMs) : endMs - startMs)} + + +
    + +
      + {row.beats.map((beat, index) => { + const firstBeat = index === 0; + const lastBeat = index === row.beats.length - 1; + const asked = question(beat); + return ( +
    1. + + {lastBeat ? : null} + {beatRow(beat, true)} + {asked === null ? null : ask(asked)} +
    2. + ); + })} +
    + + ), + }); + continue; + } + const asked = question(row); + items.push({ + key: row.name, + body: ( + <> + {beatRow(row)} + {asked === null ? null : ask(asked)} + + ), + }); + } + for (const asked of loose) { + // Keyed like its step's row, which replaces it once the step arrives, so it does not arrive twice. + items.push({ + key: asked.name, + body: ( + <> + openedAtMs} + draw={false} + name={asked.name} + verb={gt("Asks you", { $context: "a workflow step waits on a person's answer" })} + verbTone="input" + selected={focus === `question:${asked.name}`} + current={current === `question:${asked.name}`} + onPick={() => onPick(`question:${asked.name}`)} + /> + {ask(asked)} + + ), + }); + } + if (paused) { + items.push({ + key: "pause", + body: ( + onPick("pause")} + /> + ), + }); + } + // A finished run needs no closing row: the header says so, and the last step is the end. + if (end !== null && !completed) { + const endedMs = Date.parse(node.run.endedAt ?? node.run.updatedAt); + items.push({ + key: "end", + body: ( + openedAtMs} + draw={false} + name={end} + aside={node.run.detail} + selected={focus === "end"} + current={current === "end"} + onPick={() => onPick("end")} + /> + ), + }); + } + const live = end === null; + return ( + + ); +} + +function WorkflowBeatRow({ + environmentId, + beat, + child, + asks, + nowMs, + selected, + onPick, + sub, + openedAtMs, + current, +}: { + readonly environmentId: EnvironmentId; + readonly beat: WorkflowBeat; + readonly child: WorkflowRunNode | null; + /** A person's answer is what it waits for. */ + readonly asks: boolean; + readonly nowMs: number; + readonly selected: boolean; + readonly onPick: () => void; + readonly sub: boolean; + readonly openedAtMs: number; + readonly current: boolean; +}) { + const gt = useGT(); + const m = useMessages(); + const threadEnvironmentId = + beat.thread?.environmentId == null + ? environmentId + : EnvironmentId.make(beat.thread.environmentId); + const shell = useQuietThreadShell( + beat.thread === null + ? null + : scopeThreadRef(threadEnvironmentId, ThreadId.make(beat.thread.threadId)), + ); + const provider = useEnvironmentProviders() + .get(threadEnvironmentId) + ?.find((candidate) => candidate.instanceId === shell?.modelSelection.instanceId); + const under = beat.status === "running"; + const failed = beat.status === "failed"; + const said = workflowAgentSummary(beat).said; + const answer = beat.kind === "ask" ? workflowAnswer(beat.result) : null; + const wakes = beat.detail === null ? Number.NaN : Date.parse(beat.detail); + // An agent's own approval or question needs a person as much as the workflow's does. + const agentAsks = + beat.kind === "agent" && under && shell !== null + ? shell.hasPendingUserInput + ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) + : shell.hasPendingApprovals + ? gt("waits for your approval") + : null + : null; + // A question waits on a person until its step ends, answered or not; the list of open + // questions drops it a moment before the step reports done. + const needsYou = (under && (asks || beat.kind === "ask")) || agentAsks !== null; + const model = shell === null ? null : formatModelSlugName(shell.modelSelection.model); + const verb = (() => { + if (!under) return null; + if (agentAsks !== null) return agentAsks; + switch (beat.kind) { + case "agent": + return shell?.runtime?.status === "preparing" || shell?.runtime?.status === "starting" + ? gt("starting") + : gt("working"); + case "ask": + // Without its question it was just answered, and the step is about to say so. + return asks + ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) + : null; + case "sleep": + return Number.isFinite(wakes) && wakes > nowMs + ? gt("wakes in {duration}", { duration: formatDuration(wholeSeconds(wakes - nowMs)) }) + : gt("about to wake"); + case "wait": + return gt("waiting"); + case "run": + return child === null ? gt("running") : workflowRunNow(child, m); + case "step": + return gt("running"); + } + })(); + const aside = (() => { + if (failed) return workflowOneLine(beat.detail ?? gt("failed")); + if (under) return null; + switch (beat.kind) { + case "agent": + return said === null ? null : workflowOneLine(said); + case "ask": + return answer === null + ? gt("nobody answered") + : gt("You said {choice}", { choice: answer.choice }); + case "sleep": + case "wait": + return null; + case "run": + return child === null ? null : workflowRunNow(child, m); + case "step": { + const first = workflowResultLines(beat.result)[0]; + return first === undefined + ? null + : first.label === null + ? first.value + : `${first.label}: ${first.value}`; + } + } + })(); + + return ( + openedAtMs} + draw={!under && beat.endMs > openedAtMs} + lead={ + beat.kind === "agent" && provider !== undefined ? ( + + ) : beat.kind === "run" ? ( + + ) : undefined + } + name={beat.childRun?.title ?? beat.name} + note={beat.kind === "agent" && (under || said === null) ? model : null} + verb={verb} + verbTone={ + needsYou ? "input" : beat.kind === "sleep" || beat.kind === "wait" ? "quiet" : "working" + } + aside={aside} + {...(failed ? { asideTone: "failed" as const } : {})} + duration={workflowStepTime(elapsedOf(beat))} + selected={selected} + current={current} + onPick={onPick} + sub={sub} + /> + ); +} + +// What happened reads as part of the page. A question, answered in the timeline, is the one box; +// a pause says so in its heading and its button. +const CARD_TONE = { + plain: "", + quiet: "", + ask: "rounded-xl border border-warning/30 bg-warning-surface px-3 py-2.5", + failed: "", + done: "", +} as const; + +function FeedCard({ + tone = "plain", + label, + reveal = false, + children, +}: { + readonly tone?: keyof typeof CARD_TONE; + readonly label?: string; + /** Scroll it into view when it first shows. */ + readonly reveal?: boolean; + readonly children: ReactNode; +}) { + return ( +
    + {children} +
    + ); +} + +function CardHead({ + mark, + name, + sub, + action, +}: { + readonly mark: ReactNode; + readonly name: ReactNode; + readonly sub?: ReactNode; + readonly action?: ReactNode; +}) { + return ( +
    +
    + {mark === null || mark === undefined ? null : ( + {mark} + )} +
    {name}
    + {action === undefined || action === null ? null :
    {action}
    } +
    + {sub === undefined || sub === null || sub === "" ? null : ( +
    {sub}
    + )} +
    + ); +} + +function ResultLines({ + lines, +}: { + readonly lines: ReadonlyArray<{ readonly label: string | null; readonly value: string }>; +}) { + if (lines.length === 0) return null; + if (lines.every((line) => line.label === null)) { + return ( +
    + {lines.map((line) => ( +

    + {line.value} +

    + ))} +
    + ); + } + return ({ label: line.label ?? "", value: line.value }))} />; +} + +/** What a step left behind, as a list of names and values. */ +function Facts({ + facts, +}: { + readonly facts: ReadonlyArray<{ readonly label: string; readonly value: string }>; +}) { + return ( +
    + {facts.map((fact) => ( +
    +
    {fact.label}
    +
    {fact.value}
    +
    + ))} +
    + ); +} + +/** A step with nothing to show but that it happened, and what it left behind. */ +function Note({ + label, + children, + detail, +}: { + readonly label: string; + readonly children: ReactNode; + readonly detail?: ReactNode; +}) { + return ( + + + {detail} + + ); +} + +function WorkflowQuickStepsCard({ row }: { readonly row: WorkflowQuickSteps }) { + const gt = useGT(); + return ( + +
      + {row.steps.map((step) => ( +
    • + {step.name} + +
    • + ))} +
    +
    + ); +} + +function WorkflowBeatCard({ + environmentId, + beat, + child, + nowMs, + open, + onSelect, + onOpenThread, +}: { + readonly environmentId: EnvironmentId; + readonly beat: WorkflowBeat; + readonly child: WorkflowRunNode | null; + readonly nowMs: number; + readonly open: boolean; + readonly onSelect: (runId: string | null) => void; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; +}) { + const gt = useGT(); + const m = useMessages(); + const under = beat.status === "running"; + const length = formatDuration(elapsedOf(beat)); + const tries = beat.attempts > 1 ? ` · ${nthTry(beat.attempts, m)}` : ""; + switch (beat.kind) { + case "agent": + return ( + + ); + case "ask": { + const answer = workflowAnswer(beat.result); + if (answer === null) + return {`${gt("nobody answered")} · ${length}`}; + return ( + + +

    + {answer.reason === null ? ( + + You said{" "} + + {answer.choice} + + . + + ) : ( + + You said{" "} + + {answer.choice} + + : {answer.reason} + + )} +

    +
    + ); + } + case "sleep": { + if (!under) return {`${gt("slept")} · ${length}`}; + const wakes = beat.detail === null ? Number.NaN : Date.parse(beat.detail); + return ( + + } + name={beat.name} + sub={ + Number.isFinite(wakes) && wakes > nowMs + ? gt("wakes in {duration}", { + duration: formatDuration(wholeSeconds(wakes - nowMs)), + }) + : gt("about to wake") + } + /> + + ); + } + case "wait": + if (!under) return {`${gt("waited")} · ${length}`}; + return ( + + } + name={beat.name} + sub={gt("{duration} so far", { duration: length })} + /> + + ); + case "run": { + const title = beat.childRun?.title ?? beat.name; + return ( + + } + name={title} + sub={ + child === null + ? `${beat.childRun?.workflow ?? ""} · ${length}` + : `${child.run.workflow} · ${workflowRunNow(child, m)}` + } + action={ + <> + {child === null ? null : } + + + } + /> + + ); + } + case "step": { + if (under) { + return ( + + } + name={beat.name} + sub={`${gt("running for {duration}", { duration: length })}${tries}`} + /> + + ); + } + const lines = workflowResultLines(beat.result); + return ( + }> + {beat.status === "failed" ? `${gt("failed")} · ${length}` : length} + {tries} + + ); + } + } +} + +function WorkflowAgentCard({ + environmentId, + beat, + open, + onOpenThread, +}: { + readonly environmentId: EnvironmentId; + readonly beat: WorkflowBeat; + readonly open: boolean; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; +}) { + const gt = useGT(); + const m = useMessages(); + const [all, setAll] = useState(false); + const elsewhere = beat.thread !== null && beat.thread.environmentId !== null; + const threadEnvironmentId = + beat.thread?.environmentId == null + ? environmentId + : EnvironmentId.make(beat.thread.environmentId); + // This client can only show a thread on an environment it is itself connected to. + const threadEnvironment = useEnvironment(threadEnvironmentId); + const shell = useQuietThreadShell( + beat.thread === null + ? null + : scopeThreadRef(threadEnvironmentId, ThreadId.make(beat.thread.threadId)), + ); + const provider = useEnvironmentProviders() + .get(threadEnvironmentId) + ?.find((candidate) => candidate.instanceId === shell?.modelSelection.instanceId); + const under = beat.status === "running"; + const length = formatDuration(elapsedOf(beat)); + const summary = workflowAgentSummary(beat); + const start = summary.said === null ? null : workflowSaidStart(summary.said, SAID_SHOWN); + const liveWord = !under + ? null + : shell?.hasPendingUserInput === true + ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) + : shell?.hasPendingApprovals === true + ? gt("waits for your approval") + : shell?.runtime?.status === "preparing" || shell?.runtime?.status === "starting" + ? gt("starting") + : gt("working"); + const sub = [ + shell === null ? null : formatModelSlugName(shell.modelSelection.model), + liveWord, + length, + beat.attempts > 1 ? nthTry(beat.attempts, m) : null, + elsewhere + ? gt("on {environment}", { environment: threadEnvironment?.label ?? threadEnvironmentId }) + : null, + ] + .filter((part) => part !== null) + .join(" · "); + return ( + + + ) : ( + + ) + } + name={beat.name} + sub={sub} + action={ + beat.thread === null ? null : threadEnvironment === null ? ( + + + Thread on {threadEnvironmentId} + + + ) : ( + + ) + } + /> + {beat.status === "failed" && beat.detail ? ( +

    + + {beat.detail} +

    + ) : null} + {summary.said === null ? null : ( + // Set off from the head, so headings in the reply read as the agent's, not the page's. +
    + + {start !== null ? ( + + ) : null} +
    + )} + {summary.facts.length === 0 ? null : } +
    + ); +} + +function WorkflowPauseCard({ + run, + name, + attempts, + reason, + nowMs, + disabled, + onResume, + kept, +}: { + readonly run: WorkflowRun; + /** The step it stopped at, when the steps say which. */ + readonly name: string | null; + readonly attempts: number; + readonly reason: string | null; + readonly nowMs: number; + readonly disabled: boolean; + readonly onResume: () => void; + /** Steps before it finished, and resuming keeps them. */ + readonly kept: boolean; +}) { + const gt = useGT(); + const m = useMessages(); + const resumes = run.resumesAt === null ? Number.NaN : Date.parse(run.resumesAt); + const next = run.retired + ? gt("cannot go on until its workflow version is registered again") + : !Number.isFinite(resumes) + ? gt("waits for you to resume it") + : resumes > nowMs + ? gt("tries again by itself in {duration}", { duration: formatDuration(resumes - nowMs) }) + : gt("about to try again by itself"); + return ( + + } + name={ + name === null + ? gt("Paused", { $context: "a workflow run is paused" }) + : gt("Paused at {step}", { step: name }) + } + sub={ + <> + {attempts > 0 ? `${nthTry(attempts, m)} · ` : null} + · {next} + + } + action={ + + } + /> + {reason ?

    {reason}

    : null} + {kept ? ( +

    + Only the failed step runs again; what finished before it is kept. +

    + ) : null} +
    + ); +} + +function WorkflowQuestionCard({ + environmentId, + question, + onOpenThread, + inline = false, +}: { + readonly environmentId: EnvironmentId; + readonly question: WorkflowQuestion; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; + /** Under its step in the run, which already says that it asks. */ + readonly inline?: boolean; +}) { + const gt = useGT(); + const view = readWorkflowQuestion(question); + const drafts = useContext(AnswerDrafts); + const [ownReason, setOwnReason] = useState(null); + const draftKey = `${question.runId}:${question.name}:${question.askedAt}`; + const reason = drafts === null ? ownReason : drafts.get(draftKey); + const setReason = (next: string | null) => + drafts === null ? setOwnReason(next) : drafts.set(draftKey, next); + const [busy, setBusy] = useState(false); + const canAnswer = useAtomValue( + serverEnvironment.answerWorkflowQuestion.permissionAtom(environmentId), + ); + const answer = useAtomCommand(serverEnvironment.answerWorkflowQuestion, { + label: "workflow answer", + }); + const threadEnvironmentId = + question.thread?.environmentId == null + ? environmentId + : EnvironmentId.make(question.thread.environmentId); + const reachable = useEnvironment(threadEnvironmentId) !== null; + const choose = async (choice: string) => { + if (busy) return; + setBusy(true); + const given = reason?.trim() ?? ""; + const result = await answer({ + environmentId, + input: { + runId: question.runId, + name: question.name, + choice, + ...(given === "" ? {} : { reason: given }), + }, + }); + setBusy(false); + reportFailure(gt("Could not answer the question"), result); + }; + return ( + + {inline ? null : ( +

    + + Needs you + + + + asked{" "} + + + {" "} + · the run waits for you + + +

    + )} +

    + {view.title} +

    + {view.body ? ( + + ) : null} +
    + {view.choices.map((choice, index) => ( + + ))} +
    + {reason === null || (question.thread !== null && reachable) ? ( +
    + {reason === null ? ( + + ) : null} + {question.thread === null || !reachable ? null : ( + + )} +
    + ) : null} + {reason === null ? null : ( +
    + setReason(event.currentTarget.value)} + /> +
    + )} +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowRunsView.browser.test.tsx b/apps/web/src/components/workflows/WorkflowRunsView.browser.test.tsx new file mode 100644 index 0000000000000..386ba513e0e5b --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunsView.browser.test.tsx @@ -0,0 +1,477 @@ +import { Atom } from "effect/reactivity"; +import { + EnvironmentId, + type WorkflowQuestion, + type WorkflowRun, + type WorkflowRunReference, + type WorkflowRunsSnapshot, + type WorkflowStep, +} from "@t3tools/contracts"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { page as browserPage, userEvent } from "vite-plus/test/browser"; + +import "~/index.css"; +import { render } from "../../../test/render"; +import type { WorkflowPaneTab } from "./workflowPane.logic"; +import { WorkflowRunsView } from "./WorkflowRunsView"; + +const environmentId = EnvironmentId.make("laptop"); +const at = (minute: number) => new Date(Date.UTC(2026, 10, 1, 0, minute)).toISOString(); +const run = (fields: Partial & Pick): WorkflowRun => ({ + workflow: "release", + version: 1, + status: "running", + detail: null, + result: null, + pauses: 0, + retired: false, + resumesAt: null, + parentRunId: null, + parentStep: null, + startedAt: at(0), + updatedAt: at(5), + endedAt: null, + ...fields, +}); +const step = ( + fields: Partial & Pick, +): WorkflowStep => ({ + status: "completed", + attempts: 1, + detail: null, + threadId: null, + environmentId: null, + result: null, + said: null, + startedAt: at(0), + endedAt: at(0), + ...fields, +}); + +const state = vi.hoisted(() => ({ + live: { query: "live" }, + snapshot: { workflows: [], runs: [], questions: [] } as { + workflows: ReadonlyArray; + runs: ReadonlyArray; + questions: ReadonlyArray; + }, + steps: {} as Record>, + references: {} as Record>, + commands: [] as Array, + permitted: true, + detailError: null as string | null, +})); +const canOperate = Atom.make(true); +const cannotOperate = Atom.make(false); + +function setup( + given: Omit & Partial>, + steps: Record> = {}, + references: Record> = {}, +) { + state.snapshot = { workflows: [], ...given }; + state.steps = steps; + state.references = references; + state.commands = []; + state.permitted = true; + state.detailError = null; +} + +const environment = { environmentId, label: "Laptop" }; + +vi.mock(import("../../state/server"), async (original) => { + const actual = await original(); + const permissionAtom = () => (state.permitted ? canOperate : cannotOperate); + return { + ...actual, + serverEnvironment: { + ...actual.serverEnvironment, + workflowsLive: (() => state.live) as never, + workflowRun: ((target: { readonly input: { readonly runId: string } }) => + target.input) as never, + answerWorkflowQuestion: { + ...actual.serverEnvironment.answerWorkflowQuestion, + permissionAtom, + }, + resumeWorkflowRun: { ...actual.serverEnvironment.resumeWorkflowRun, permissionAtom }, + cancelWorkflowRun: { ...actual.serverEnvironment.cancelWorkflowRun, permissionAtom }, + }, + }; +}); +// Stands in for the live list and for one run's detail, which the mocked atoms above name. +vi.mock(import("../../state/query"), async (original) => ({ + ...(await original()), + useEnvironmentQuery: ((request: { readonly runId?: string }) => ({ + data: + request === state.live + ? state.snapshot + : state.detailError !== null + ? null + : { + run: null, + steps: state.steps[request.runId ?? ""] ?? [], + references: state.references[request.runId ?? ""] ?? [], + }, + error: request === state.live ? null : state.detailError, + isPending: false, + refresh: vi.fn(), + })) as never, +})); +vi.mock(import("../../state/use-atom-command"), async (original) => ({ + ...(await original()), + useAtomCommand: ((_command: unknown, options: { readonly label: string }) => + (value: { readonly input: unknown }) => { + state.commands.push([options.label, value.input]); + return Promise.resolve({ _tag: "Success", value: undefined }); + }) as never, +})); +vi.mock(import("../../state/environments"), async (original) => ({ + ...(await original()), + useEnvironment: ((id: EnvironmentId | null) => + id === environmentId ? environment : null) as never, +})); +// The chat's renderer loads its highlighter; a question's body only has to reach the page. +vi.mock("../ChatMarkdown", () => ({ + default: ({ text }: { readonly text: string }) =>
    {text}
    , +})); + +const question: WorkflowQuestion = { + runId: "ship", + name: "approve", + request: { + title: "Ship release 1.2?", + choices: ["Ship", "Hold"], + data: { body: "The diff touches the installer." }, + }, + askedAt: at(4), + thread: { threadId: "thread-9", environmentId: null }, +}; + +const issue101: WorkflowRunReference = { + kind: "issue", + key: "i101", + address: { projectId: "p1", tracker: "github", scope: "me/app", key: "101" }, + title: "Wrong minutes", + url: "https://github.com/me/app/issues/101", + state: "open", + steps: ["triage"], + origin: "trigger", +}; + +/** Wide enough for the list and the run side by side; put back when the test ends. */ +async function desktop() { + const width = window.innerWidth; + const height = window.innerHeight; + await browserPage.viewport(1280, 800); + return { [Symbol.asyncDispose]: () => browserPage.viewport(width, height) }; +} + +const page = ( + selectedRunId: string | null = null, + on: { + readonly select?: (runId: string | null) => void; + readonly thread?: () => void; + readonly reference?: () => void; + } = {}, + shownTab: WorkflowPaneTab | null = null, +) => ( + +); + +describe("WorkflowRunsView", () => { + it("opens on the question that waits, and answers it with the reason given", async () => { + setup( + { + runs: [ + run({ runId: "busy", title: "Nightly sync" }), + run({ runId: "ship", title: "Release 1.2", status: "waiting", detail: "approve" }), + ], + questions: [question], + }, + { ship: [step({ name: "approve", kind: "ask", status: "running", endedAt: null })] }, + ); + const thread = vi.fn(); + await using _desktop = await desktop(); + await using screen = await render(page(null, { thread })); + + // The list opens on what waits on a person, and the run that asks is the one shown. + const runs = screen.getByRole("navigation", { name: "Workflow runs" }); + await expect.element(runs.getByRole("button", { name: /Release 1\.2/ })).toBeVisible(); + await expect + .element(runs.getByRole("button", { name: /Nightly sync/ })) + .not.toBeInTheDocument(); + await expect.element(runs).toMatchTextContent("Asks: Ship release 1.2?"); + await expect.element(screen.getByText("The diff touches the installer.")).toBeVisible(); + + await screen.getByRole("button", { name: "Ask the agent first" }).click(); + expect(thread).toHaveBeenCalledWith("ship", { threadId: "thread-9", environmentId: null }); + + await screen.getByRole("button", { name: "Add a reason" }).click(); + await userEvent.fill( + screen.getByRole("textbox", { name: "Reason for Ship release 1.2?" }), + " Too risky today ", + ); + await screen.getByRole("button", { name: "Hold", exact: true }).click(); + + await vi.waitFor(() => + expect(state.commands).toEqual([ + [ + "workflow answer", + { runId: "ship", name: "approve", choice: "Hold", reason: "Too risky today" }, + ], + ]), + ); + }); + + it("answers a question whose steps did not load, and says a linked run is not here", async () => { + setup({ + runs: [run({ runId: "ship", title: "Release 1.2", status: "waiting", detail: "approve" })], + questions: [question], + }); + state.detailError = "The server did not answer."; + await using _desktop = await desktop(); + { + await using screen = await render(page("ship")); + await expect.element(screen.getByText("The server did not answer.")).toBeVisible(); + await screen.getByRole("button", { name: "Ship", exact: true }).click(); + await vi.waitFor(() => + expect(state.commands).toEqual([ + ["workflow answer", { runId: "ship", name: "approve", choice: "Ship" }], + ]), + ); + } + + // A link to a run this environment does not have never shows another run in its place. + const select = vi.fn(); + await using screen = await render(page("gone", { select })); + await expect.element(screen.getByText("This run is not here")).toBeVisible(); + await expect + .element(screen.getByRole("button", { name: "Ship", exact: true })) + .not.toBeInTheDocument(); + await screen.getByRole("button", { name: "Back to the runs" }).click(); + expect(select).toHaveBeenCalledWith(null); + }); + + it("says a linked run is not here where nothing has run yet", async () => { + setup({ runs: [], questions: [] }); + const select = vi.fn(); + await using screen = await render(page("gone", { select })); + await expect.element(screen.getByText("This run is not here")).toBeVisible(); + await screen.getByRole("button", { name: "Back to the runs" }).click(); + expect(select).toHaveBeenCalledWith(null); + }); + + it("turns the answers off for a session that may not operate", async () => { + setup({ + runs: [run({ runId: "ship", title: "Release 1.2", status: "waiting" })], + questions: [question], + }); + state.permitted = false; + await using _desktop = await desktop(); + await using screen = await render(page()); + + await expect.element(screen.getByRole("button", { name: "Ship", exact: true })).toBeDisabled(); + await expect.element(screen.getByRole("button", { name: "Hold", exact: true })).toBeDisabled(); + }); + + it("says why a run paused at the step that failed, and resumes it", async () => { + setup( + { + runs: [ + run({ + runId: "sync", + title: "Sync labels", + status: "paused", + detail: "apply: 503", + pauses: 1, + }), + ], + questions: [], + }, + { + sync: [ + // A failure the workflow caught and went on from is not where it paused. + step({ name: "lint", kind: "step", status: "failed", endedAt: at(1), detail: "lint" }), + step({ name: "fetch", kind: "step", startedAt: at(1), endedAt: at(1) }), + step({ + name: "apply", + kind: "agent", + status: "failed", + attempts: 3, + detail: "503", + threadId: "thread-apply", + startedAt: at(2), + endedAt: at(3), + }), + ], + }, + ); + await using _desktop = await desktop(); + await using screen = await render(page()); + + const why = screen.getByRole("region", { name: "Why it paused" }); + await expect.element(why).toMatchTextContent(/Paused at apply.*3rd try.*waits for you/); + await expect.element(why).toMatchTextContent("503"); + // The failed agent's transcript is there to read before choosing. + await expect.element(screen.getByRole("button", { name: "Transcript" })).toBeVisible(); + await expect.element(screen.getByText("Paused at lint")).not.toBeInTheDocument(); + await why.getByRole("button", { name: "Resume" }).click(); + + await vi.waitFor(() => + expect(state.commands).toEqual([["workflow resume", { runId: "sync" }]]), + ); + }); + + it("draws a finished run as a flow, and shows the step that is picked", async () => { + setup( + { + runs: [ + run({ + runId: "fix", + title: "#101 Wrong minutes", + status: "completed", + result: "merged as ba6ac7", + endedAt: at(12), + }), + ], + questions: [], + }, + { + fix: [ + step({ name: "load", kind: "step" }), + step({ name: "existing-prs", kind: "step" }), + step({ + name: "triage", + kind: "agent", + endedAt: at(3), + threadId: "thread-1", + said: "Reproduced on main.", + result: { kind: "bug", reproduced: true }, + }), + step({ + name: "implement", + kind: "agent", + startedAt: at(3), + endedAt: at(10), + threadId: "thread-2", + environmentId: "build-box", + }), + step({ + name: "approve", + kind: "ask", + startedAt: at(10), + endedAt: at(11), + result: { choice: "Fix it", reason: "It hits everyone on Windows" }, + }), + ], + }, + { fix: [issue101] }, + ); + const thread = vi.fn(); + const reference = vi.fn(); + await using screen = await render(page("fix", { thread, reference }, { thread: "thread-1" })); + + // A finished run opens on how it ended; the flow has a node for each step that mattered. + const happened = screen.getByRole("region", { name: "What happened" }); + await expect.element(happened).toMatchTextContent(/Finished.*merged as ba6ac7/); + const flow = screen.getByRole("navigation", { name: "Steps so far" }); + await expect + .element(flow) + .toMatchTextContent(/load · existing-prs.*triage.*Reproduced on main\..*implement.*approve/); + + await flow.getByRole("button", { name: /triage/ }).click(); + const triage = screen.getByRole("region", { name: "triage" }); + await expect.element(triage).toMatchTextContent(/3m 0s.*Reproduced on main\..*kind.*bug/); + // Its thread is the one open beside the run, and the button says so. + const transcript = triage.getByRole("button", { name: "Transcript" }); + await expect.element(transcript).toHaveAttribute("aria-pressed", "true"); + await transcript.click(); + expect(thread).toHaveBeenCalledWith("fix", { threadId: "thread-1", environmentId: null }); + // What the run touched is under its title, by number alone when the title already says it. + // It opens beside the run. + const touched = screen.getByRole("list", { name: "What the run touched" }); + const onRun = touched.getByRole("button", { name: "#101 Wrong minutes" }); + await expect.element(onRun).toMatchTextContent(/^#101$/); + await onRun.click(); + expect(reference).toHaveBeenCalledWith("fix", issue101); + // This client is not connected to the linked environment, so there is nothing to open. + await flow.getByRole("button", { name: /implement/ }).click(); + await expect + .element(screen.getByRole("region", { name: "implement" })) + .toMatchTextContent("Thread on build-box"); + await flow.getByRole("button", { name: /approve/ }).click(); + await expect + .element(screen.getByRole("region", { name: "approve" })) + .toMatchTextContent("You said Fix it: It hits everyone on Windows"); + await flow.getByRole("button", { name: /load · existing-prs/ }).click(); + await expect + .element(screen.getByRole("region", { name: "Quick steps" })) + .toMatchTextContent("loadexisting-prs"); + await expect + .element(screen.getByRole("button", { name: "Cancel run" })) + .not.toBeInTheDocument(); + }); + + it("opens an invoked run from its parent's story", async () => { + setup( + { + runs: [ + run({ runId: "rel", title: "Release 1.3", status: "waiting", detail: "check" }), + run({ runId: "chk", title: "Check web", parentRunId: "rel", parentStep: "check" }), + ], + questions: [], + }, + { + rel: [ + step({ name: "check/start", kind: "step" }), + step({ name: "check", kind: "wait", status: "running", endedAt: null }), + ], + }, + ); + const select = vi.fn(); + await using screen = await render(page("rel", { select })); + + const invoked = screen.getByRole("region", { name: "Check web" }); + await invoked.getByRole("button", { name: "Open run" }).click(); + expect(select).toHaveBeenCalledWith("chk"); + }); + + it("switches between what is under way and everything, one workflow at a time", async () => { + setup({ + workflows: [ + { name: "release", version: 1, triggers: ["webhook tags"] }, + { name: "report", version: 1, triggers: ["daily at 09:00"] }, + ], + runs: [ + run({ runId: "rel", title: "Release 1.3" }), + run({ runId: "old", title: "Release 1.2", status: "completed", endedAt: at(3) }), + ], + questions: [], + }); + await using _desktop = await desktop(); + await using screen = await render(page()); + + const runs = screen.getByRole("navigation", { name: "Workflow runs" }); + await expect.element(runs.getByRole("button", { name: /Release 1\.3/ })).toBeVisible(); + await expect + .element(runs.getByRole("button", { name: /Release 1\.2/ })) + .not.toBeInTheDocument(); + await screen.getByRole("button", { name: "All", exact: true }).click(); + await expect.element(runs.getByRole("button", { name: /Release 1\.2/ })).toBeVisible(); + + // A workflow that has not run is still there to be picked, with what starts it. + await screen.getByRole("combobox", { name: "Workflow" }).click(); + await screen.getByRole("option", { name: "report" }).click(); + await expect.element(screen.getByText("Starts on daily at 09:00")).toBeVisible(); + await expect.element(runs).toMatchTextContent("Has not run yet."); + }); +}); diff --git a/apps/web/src/components/workflows/WorkflowRunsView.tsx b/apps/web/src/components/workflows/WorkflowRunsView.tsx new file mode 100644 index 0000000000000..4c43539b1e1e3 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunsView.tsx @@ -0,0 +1,384 @@ +import { type EnvironmentId, type WorkflowRunReference } from "@t3tools/contracts"; +import { msg, T, useGT, useMessages } from "gt-react"; +import { WorkflowIcon } from "lucide-react"; +import { useState, type ReactNode } from "react"; + +import { cn } from "../../lib/utils"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { Button } from "../ui/button"; +import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty"; +import { ScrollArea } from "../ui/scroll-area"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { + RelativeLabel, + WorkflowChip, + WorkflowRunFeed, + WorkflowStateWord, + type WorkflowThreadTarget, +} from "./WorkflowRunFeed"; +import type { WorkflowPaneTab } from "./workflowPane.logic"; +import { + allWorkflowRunNodes, + defaultWorkflowListTab, + defaultWorkflowRunId, + groupWorkflowRuns, + listedWorkflowRuns, + workflowRunLists, + workflowRunNow, + workflowTriggerLine, + type WorkflowListTab, + type WorkflowRunNode, + workflowRunInvolves, +} from "@t3tools/client-runtime/workflows"; + +const WORKFLOWS_GUIDE_URL = "https://github.com/pingdotgg/t3code/blob/main/docs/user/workflows.md"; +const EVERY_WORKFLOW = ""; +const TABS: ReadonlyArray<{ readonly value: WorkflowListTab; readonly label: string }> = [ + { + value: "needs-you", + label: msg("Needs you", { $context: "tab: workflow runs that wait on the user" }), + }, + { value: "running", label: msg("Running", { $context: "tab: workflow runs under way" }) }, + { value: "all", label: msg("All", { $context: "tab: every workflow run" }) }, +]; +const NOTHING: Record = { + "needs-you": msg("Nothing waits on you."), + running: msg("Nothing is running."), + all: msg("No runs yet."), +}; + +export function WorkflowsEmpty({ + title, + description, +}: { + readonly title: string; + readonly description: ReactNode; +}) { + return ( +
    + + + + + + {title} + {description} + + +
    + ); +} + +/** One environment's runs: the list to pick from, and the picked run told as a feed. */ +export function WorkflowRunsView({ + environmentId, + selectedRunId, + paneOpen, + shownTab, + onSelect, + onOpenThread, + onOpenReference, + onOpenDefinitions, +}: { + readonly environmentId: EnvironmentId; + readonly selectedRunId: string | null; + /** Something is open beside the run, so the list makes room below `xl`. */ + readonly paneOpen: boolean; + /** What shows beside the run, so what opened it can say so. */ + readonly shownTab: WorkflowPaneTab | null; + readonly onSelect: (runId: string | null) => void; + readonly onOpenThread: (runId: string, thread: WorkflowThreadTarget) => void; + readonly onOpenReference: (runId: string, reference: WorkflowRunReference) => void; + readonly onOpenDefinitions: () => void; +}) { + const live = useEnvironmentQuery(serverEnvironment.workflowsLive({ environmentId, input: {} })); + const [pickedTab, setPickedTab] = useState(null); + const [workflow, setWorkflow] = useState(EVERY_WORKFLOW); + const gt = useGT(); + const m = useMessages(); + const [showSkipped, setShowSkipped] = useState(false); + const snapshot = live.data; + if (live.error) { + return ; + } + if (!snapshot) { + return ( +

    + Loading workflow runs… +

    + ); + } + // A broken file is said even where nothing has run, or its workflows would just seem missing. + const problemAlert = + snapshot.definition?.problem == null ? null : ( +
    + + + + A workflow file has a problem. + {" "} + The last version that did keeps running. + + + +
    + ); + const withProblem = (empty: ReactNode) => + problemAlert === null ? ( + empty + ) : ( +
    + {problemAlert} + {empty} +
    + ); + const notHere = ( + + This environment has no run with that link.{" "} + + + } + /> + ); + // A link to a run says it is not here, even where nothing has run at all. + if (snapshot.runs.length === 0 && snapshot.workflows.length === 0 && selectedRunId !== null) { + return withProblem(notHere); + } + if (snapshot.runs.length === 0 && snapshot.workflows.length === 0) { + return withProblem( + + A workflow ties agents, code, schedules and questions to you into one run that survives + restarts. Write one under{" "} + + , or ask an agent to.{" "} +
    + Read the guide + + + } + />, + ); + } + // A skipped run opened by its link is shown all the same. + const openedSkipped = snapshot.runs.some( + (run) => run.runId === selectedRunId && run.status === "skipped", + ); + const visible = listedWorkflowRuns(snapshot.runs, showSkipped || openedSkipped); + const groups = groupWorkflowRuns(snapshot.workflows, visible.runs, snapshot.questions); + const lists = workflowRunLists(groups); + const all = allWorkflowRunNodes(groups); + const section = groups.workflows.find((candidate) => candidate.name === workflow) ?? null; + // A run the address names is that run or none: another one's buttons would act on the wrong run. + const shownRunId = + selectedRunId === null + ? defaultWorkflowRunId(groups) + : (all.find((node) => node.run.runId === selectedRunId)?.run.runId ?? null); + const shown = all.find((node) => node.run.runId === shownRunId) ?? null; + // A run that another invoked is not in the list itself; the one it is part of stands for it. + const listedFor = (node: WorkflowRunNode | null): string | null => { + if (node === null) return null; + const parent = all.find((candidate) => candidate.run.runId === node.run.parentRunId); + return parent === undefined ? node.run.runId : listedFor(parent); + }; + const currentRunId = listedFor(shown); + // A run opened by its link is shown in a list that has it, so the list never points at nothing. + const opening = defaultWorkflowListTab(groups); + const holds = (candidate: WorkflowListTab) => + lists[candidate].some((node) => node.run.runId === currentRunId); + const tab = + pickedTab ?? + (selectedRunId === null || holds(opening) ? opening : holds("running") ? "running" : "all"); + const listed = lists[tab].filter( + (node) => section === null || workflowRunInvolves(node, section.name), + ); + return ( +
    + {problemAlert} +
    + {/* Below md there is room for one of the two: the list, or the run picked from it. */} +
    +
    + { + const value = TABS.find((candidate) => candidate.value === next[0]); + if (value !== undefined) setPickedTab(value.value); + }} + > + {TABS.map(({ value, label }) => ( + + {m(label)} + + ))} + + {groups.workflows.length > 1 ? ( + + ) : null} + {section === null ? null : ( +

    + {workflowTriggerLine(section, m)} +

    + )} +
    + + + +
    + + {shown === null ? ( + selectedRunId === null ? null : ( + notHere + ) + ) : ( + node.run.runId === shown.run.parentRunId)?.run ?? null} + shownTab={shownTab} + onSelect={onSelect} + onOpenThread={(thread) => onOpenThread(shown.run.runId, thread)} + onOpenReference={(reference) => onOpenReference(shown.run.runId, reference)} + /> + )} + +
    +
    + ); +} + +/** A run in the thread list's own shape: which workflow, its state in a word, and what it is at. */ +function WorkflowRunListItem({ + node, + current, + onSelect, +}: { + readonly node: WorkflowRunNode; + readonly current: boolean; + readonly onSelect: (runId: string | null) => void; +}) { + const { run } = node; + const m = useMessages(); + return ( +
  • + +
  • + ); +} diff --git a/apps/web/src/components/workflows/WorkflowThreadPane.tsx b/apps/web/src/components/workflows/WorkflowThreadPane.tsx new file mode 100644 index 0000000000000..7e6432eaec393 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowThreadPane.tsx @@ -0,0 +1,65 @@ +import { type ScopedThreadRef } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { useGT } from "gt-react"; + +import { ComposerHandleContext } from "../../composerHandleContext"; +import type { SideChatParentPanel } from "../../lib/sideChatPane"; +import { useQuietThreadShell } from "../../state/entities"; +import { useEnvironmentShellHasSnapshot } from "../../state/shell"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import ChatView from "../ChatView"; +import { BackgroundThreadContext } from "../chat/backgroundThread"; + +/** Opens the thread as a full thread view. */ +export function useOpenThreadPage(): (threadRef: ScopedThreadRef) => void { + const navigate = useNavigate(); + return (threadRef) => + void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(threadRef) }); +} + +/** What a transcript's tab is called: the step its agent did, or the thread's own title. */ +export function WorkflowThreadTabLabel({ threadRef }: { readonly threadRef: ScopedThreadRef }) { + const gt = useGT(); + const shell = useQuietThreadShell(threadRef); + const step = shell?.workflowRun?.step; + return step === undefined + ? (shell?.title ?? gt("Agent", { $context: "fallback title of a coding agent's thread" })) + : gt("{step} · transcript", { step, $context: "tab: the agent thread of a workflow step" }); +} + +/** + * An agent step's thread beside its run: the same chat as anywhere, composer included, so a + * person can read what the agent did and talk to it without leaving the run. + */ +export default function WorkflowThreadPane({ threadRef }: { readonly threadRef: ScopedThreadRef }) { + const gt = useGT(); + const openThreadPage = useOpenThreadPage(); + const shell = useQuietThreadShell(threadRef); + const snapshotLoaded = useEnvironmentShellHasSnapshot(threadRef.environmentId); + const openFull = () => openThreadPage(threadRef); + // The diff panel and the terminal drawer belong to the full thread view, so both lead there. + const panel: SideChatParentPanel = { + hostRef: threadRef, + openToolDiff: openFull, + runShellCommand: openFull, + }; + return shell === null ? ( +

    + {snapshotLoaded ? gt("This thread is no longer there.") : gt("Loading the thread…")} +

    + ) : ( + // The attribute is how the embedded chat knows the keyboard is meant for it. +
    + + + + + +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowsPage.tsx b/apps/web/src/components/workflows/WorkflowsPage.tsx new file mode 100644 index 0000000000000..7c42a4d00080a --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowsPage.tsx @@ -0,0 +1,328 @@ +import { EnvironmentId, type WorkflowRunReference } from "@t3tools/contracts"; +import { Link, useNavigate, useSearch } from "@tanstack/react-router"; +import { T, useGT } from "gt-react"; +import { FileCode2Icon } from "lucide-react"; +import { lazy, Suspense, useState, type MouseEvent } from "react"; + +import { isElectron } from "~/env"; +import { type FileContextMenuAction, useFileContextMenu } from "../../fileContextMenu"; +import { cn } from "../../lib/utils"; +import { readLocalApi } from "../../localApi"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { + useConnectedEnvironmentIds, + useEnvironments, + usePrimaryEnvironmentId, +} from "../../state/environments"; +import { useWorkflowEnvironmentIds } from "./useWorkflowEnvironmentIds"; +import { Button } from "../ui/button"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { SidebarInset } from "../ui/sidebar"; +import { + WorkspaceBreadcrumb, + WorkspaceBreadcrumbItem, + WorkspaceBreadcrumbSeparator, + WorkspaceBreadcrumbText, +} from "../WorkspaceBreadcrumb"; +import { WorkspacePageHeader } from "../WorkspacePageHeader"; +import { WorkflowRunsView, WorkflowsEmpty } from "./WorkflowRunsView"; +import WorkflowPane from "./WorkflowPane"; +import { + activeWorkflowPaneTab, + toggleWorkflowPaneTab, + type WorkflowPaneState, +} from "./workflowPane.logic"; + +const COPY_PATH = "copy-path"; + +// The editor brings the code view's highlighter with it, which the run list has no use for. +const WorkflowDefinitionEditor = lazy(() => import("./WorkflowDefinitionEditor")); + +export interface WorkflowsSearch extends WorkflowPaneState { + readonly env?: string; + readonly run?: string; + /** Show the definition files instead of the runs: all of them, or `file` in the editor. */ + readonly definitions?: boolean; + readonly file?: string; +} + +export function WorkflowsPage() { + const search = useSearch({ from: "/_chat/workflows" }); + const navigate = useNavigate(); + const gt = useGT(); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const connectedIds = useConnectedEnvironmentIds(); + const { environments } = useEnvironments(); + const workflowIds = useWorkflowEnvironmentIds(); + // Only servers with workflows on in Labs can be picked; a connected one with them off says so. + const connected = environments.filter((environment) => + workflowIds.includes(environment.environmentId), + ); + const asked = search.env === undefined ? null : EnvironmentId.make(search.env); + const turnedOff = + asked === null + ? workflowIds.length === 0 && connectedIds.length > 0 + : connectedIds.includes(asked) && !workflowIds.includes(asked); + // An environment the address names is kept while it is away: its run and file mean nothing on + // another server. + const environmentId = + asked !== null + ? (connected.find((environment) => environment.environmentId === asked)?.environmentId ?? + null) + : (connected.find((environment) => environment.environmentId === primaryEnvironmentId) + ?.environmentId ?? + connected[0]?.environmentId ?? + null); + const select = (next: WorkflowsSearch) => + void navigate({ to: "/workflows", search: next, replace: true }); + // A level of the page, which the browser's Back should step out of again. + const go = (next: WorkflowsSearch) => void navigate({ to: "/workflows", search: next }); + // Opening a run or file pins the environment it is on, so the same address never means another. + const pinned = environmentId ?? search.env; + const env = pinned === undefined ? {} : { env: pinned }; + const away = + asked !== null && environmentId === null && !turnedOff + ? (environments.find((environment) => environment.environmentId === asked)?.label ?? asked) + : null; + const run = search.run === undefined ? {} : { run: search.run }; + const editing = search.definitions === true || search.file !== undefined; + // An open file stays open while its environment is away, so a draft in it is not lost. + const fileEnvironmentId = + environmentId ?? (search.file === undefined || turnedOff ? null : asked); + const [fileActions, setFileActions] = useState(null); + const definitions = useEnvironmentQuery( + fileEnvironmentId === null || search.file === undefined + ? null + : serverEnvironment.workflowDefinition({ environmentId: fileEnvironmentId, input: {} }), + ); + const fileMenu = useFileContextMenu(fileEnvironmentId); + /** What a right click on the open file's name offers: its path, and the editors on that machine. */ + const showFileMenu = (event: MouseEvent) => { + const api = readLocalApi(); + const directory = definitions.data?.directory; + if (api === undefined || directory === undefined || search.file === undefined) return; + event.preventDefault(); + const path = `${directory}/${search.file}`; + const target = { environmentId: fileEnvironmentId, filePath: path, workspaceRoot: undefined }; + void api.contextMenu + .show([{ id: COPY_PATH, label: gt("Copy path") }, ...fileMenu.buildItems(target)], { + x: event.clientX, + y: event.clientY, + }) + .then((picked) => { + if (picked === null) return; + if (picked === COPY_PATH) return void navigator.clipboard.writeText(path); + return fileMenu.activate(picked as FileContextMenuAction, target); + }); + }; + // The run stays in the address, so the breadcrumb back to the runs reopens it. + const openDefinitions = (file: string | null) => + go({ ...env, ...run, definitions: true, ...(file === null ? {} : { file }) }); + // What is open beside the run, which belongs to the run: picking another one closes it. + const pane: WorkflowPaneState = + environmentId === null || editing || search.pane === undefined + ? {} + : search.tab === undefined + ? { pane: search.pane } + : { pane: search.pane, tab: search.tab }; + const paneOpen = pane.pane !== undefined; + const shownTab = activeWorkflowPaneTab(pane); + // Opening something pins the run it is from, so the address keeps naming the run it belongs to. + const togglePane = (runId: string, tab: Parameters[1]) => + select({ ...env, run: runId, ...toggleWorkflowPaneTab(pane, tab) }); + + return ( + +
    + {/* Below md there is room for one thing, and an open pane is that thing. */} +
    + + + + {editing ? ( + + ) : ( +

    + Workflows +

    + )} +
    + {editing ? ( + <> + + / + + + {search.file === undefined ? ( +

    + Definitions +

    + ) : ( + + )} +
    + + ) : null} + {search.file === undefined ? null : ( + <> + + / + + +

    + + {search.file} + +

    +
    + + )} +
    + {(connected.length > 1 && environmentId !== null) || + ((away !== null || turnedOff) && connected.length > 0) ? ( + + ) : null} + {search.file === undefined ? null : ( +
    + )} + {environmentId === null || editing ? null : ( + + )} + + {editing && fileEnvironmentId !== null ? ( + + Loading the editor… +

    + } + > + +
    + ) : away !== null ? ( + + ) : turnedOff ? ( + + Turn them on for this server in{" "} + + Settings → Labs + + . + + } + /> + ) : environmentId === null ? ( + + ) : ( + openDefinitions(null)} + environmentId={environmentId} + selectedRunId={search.run ?? null} + paneOpen={paneOpen} + shownTab={shownTab} + onSelect={(runId) => select({ ...env, ...(runId === null ? {} : { run: runId }) })} + onOpenThread={(runId, thread) => + togglePane(runId, { + thread: thread.threadId, + ...(thread.environmentId === null ? {} : { env: thread.environmentId }), + }) + } + onOpenReference={(runId, reference: WorkflowRunReference) => + togglePane(runId, { kind: reference.kind, key: reference.key }) + } + /> + )} +
    + {environmentId === null || !paneOpen ? null : ( + + )} +
    + + ); +} diff --git a/apps/web/src/components/workflows/useWorkflowEnvironmentIds.ts b/apps/web/src/components/workflows/useWorkflowEnvironmentIds.ts new file mode 100644 index 0000000000000..9a8bd4a583b71 --- /dev/null +++ b/apps/web/src/components/workflows/useWorkflowEnvironmentIds.ts @@ -0,0 +1,11 @@ +import type { EnvironmentId } from "@t3tools/contracts"; + +import { useServerConfigs } from "../../state/entities"; +import { useConnectedEnvironmentIds } from "../../state/environments"; + +/** The connected environments whose server has workflows turned on in Labs. */ +export function useWorkflowEnvironmentIds(): ReadonlyArray { + const connectedIds = useConnectedEnvironmentIds(); + const configs = useServerConfigs(); + return connectedIds.filter((id) => configs.get(id)?.settings.workflowsEnabled === true); +} diff --git a/apps/web/src/components/workflows/workflowPane.logic.test.ts b/apps/web/src/components/workflows/workflowPane.logic.test.ts new file mode 100644 index 0000000000000..f9c9b54f926a2 --- /dev/null +++ b/apps/web/src/components/workflows/workflowPane.logic.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + activeWorkflowPaneTab, + closeWorkflowPaneTab, + openWorkflowPaneTab, + readWorkflowPane, + toggleWorkflowPaneTab, + type WorkflowPaneState, +} from "./workflowPane.logic"; + +const issue = { kind: "issue", key: "i412" }; +const pullRequest = { kind: "pullRequest", key: "p418" }; +const transcript = { thread: "workflow:ab", env: "env-2" }; + +describe("the pane beside a run", () => { + it("reads back from the address only what it can, once", () => { + expect( + readWorkflowPane( + [issue, { kind: "issue" }, issue, transcript, { thread: "t1", env: 3 }, "x"], + "0", + ), + ).toEqual({ pane: [issue, transcript, { thread: "t1" }], tab: 0 }); + // The last tab shows unless the address says another; one it cannot have shows the last. + expect(readWorkflowPane([issue, pullRequest], 7)).toEqual({ pane: [issue, pullRequest] }); + expect(readWorkflowPane("nope", 0)).toEqual({}); + }); + + it("opens a tab once, shows it, and closing one shows the tab beside it", () => { + let state: WorkflowPaneState = {}; + state = openWorkflowPaneTab(state, issue); + state = openWorkflowPaneTab(state, pullRequest); + state = openWorkflowPaneTab(state, transcript); + expect(state).toEqual({ pane: [issue, pullRequest, transcript] }); + state = openWorkflowPaneTab(state, { ...issue }); + expect(state).toEqual({ pane: [issue, pullRequest, transcript], tab: 0 }); + state = closeWorkflowPaneTab(state, 0); + expect(activeWorkflowPaneTab(state)).toEqual(pullRequest); + // Closing one that does not show leaves the one that does. + state = closeWorkflowPaneTab(state, 1); + expect(state).toEqual({ pane: [pullRequest] }); + expect(closeWorkflowPaneTab(state, 0)).toEqual({}); + }); + + it("asking for the tab that shows closes it, and any other shows it", () => { + const open = { pane: [issue, transcript] }; + expect(toggleWorkflowPaneTab(open, transcript)).toEqual({ pane: [issue] }); + expect(toggleWorkflowPaneTab(open, issue)).toEqual({ pane: [issue, transcript], tab: 0 }); + }); +}); diff --git a/apps/web/src/components/workflows/workflowPane.logic.ts b/apps/web/src/components/workflows/workflowPane.logic.ts new file mode 100644 index 0000000000000..9cdbc4963423d --- /dev/null +++ b/apps/web/src/components/workflows/workflowPane.logic.ts @@ -0,0 +1,103 @@ +/** + * What is open beside a run: agent transcripts and the things the run touched, one tab each. It + * lives in the address, so a reload or a shared link opens the same tabs. + */ +export type WorkflowPaneTab = + /** An agent's thread, and the linked environment it is in when not the run's own. */ + | { readonly thread: string; readonly env?: string } + /** One of the run's references, by its kind and key. */ + | { readonly kind: string; readonly key: string }; + +export interface WorkflowPaneState { + readonly pane?: ReadonlyArray; + /** Which tab shows; the last one when it names none. */ + readonly tab?: number; +} + +// A link is typed into an address bar: what it holds is capped like the rest of the address. +const MOST_TABS = 12; +const LONGEST = 400; + +const text = (value: unknown): value is string => + typeof value === "string" && value !== "" && value.length <= LONGEST; + +function readTab(raw: unknown): WorkflowPaneTab | null { + if (typeof raw !== "object" || raw === null) return null; + const fields = raw as Readonly>; + if (text(fields.thread)) { + return text(fields.env) + ? { thread: fields.thread, env: fields.env } + : { thread: fields.thread }; + } + return text(fields.kind) && text(fields.key) ? { kind: fields.kind, key: fields.key } : null; +} + +const sameWorkflowPaneTab = (left: WorkflowPaneTab, right: WorkflowPaneTab) => + "thread" in left + ? "thread" in right && left.thread === right.thread && left.env === right.env + : "kind" in right && left.kind === right.kind && left.key === right.key; + +/** The pane an address names, without what it cannot read or holds twice. */ +export function readWorkflowPane(rawPane: unknown, rawTab: unknown): WorkflowPaneState { + const tabs: Array = []; + for (const raw of Array.isArray(rawPane) ? rawPane : []) { + const tab = readTab(raw); + if (tab === null || tabs.some((open) => sameWorkflowPaneTab(open, tab))) continue; + tabs.push(tab); + if (tabs.length === MOST_TABS) break; + } + if (tabs.length === 0) return {}; + const tab = typeof rawTab === "number" ? rawTab : Number(rawTab); + return Number.isInteger(tab) && tab >= 0 && tab < tabs.length - 1 + ? { pane: tabs, tab } + : { pane: tabs }; +} + +/** The index of the tab that shows, or -1 when nothing is open. */ +export function activeWorkflowPaneIndex(state: WorkflowPaneState): number { + const count = state.pane?.length ?? 0; + return state.tab !== undefined && state.tab < count ? state.tab : count - 1; +} + +export function activeWorkflowPaneTab(state: WorkflowPaneState): WorkflowPaneTab | null { + return state.pane?.[activeWorkflowPaneIndex(state)] ?? null; +} + +const stateOf = (tabs: ReadonlyArray, active: number): WorkflowPaneState => + tabs.length === 0 + ? {} + : active === tabs.length - 1 + ? { pane: tabs } + : { pane: tabs, tab: active }; + +/** Shows `tab`, opening it after the others when it is not open yet. */ +export function openWorkflowPaneTab( + state: WorkflowPaneState, + tab: WorkflowPaneTab, +): WorkflowPaneState { + const tabs = state.pane ?? []; + const at = tabs.findIndex((open) => sameWorkflowPaneTab(open, tab)); + if (at !== -1) return stateOf(tabs, at); + const next = [...tabs, tab].slice(-MOST_TABS); + return stateOf(next, next.length - 1); +} + +/** Closes the tab at `index`. The one beside it shows if it was showing. */ +export function closeWorkflowPaneTab(state: WorkflowPaneState, index: number): WorkflowPaneState { + const tabs = state.pane ?? []; + if (index < 0 || index >= tabs.length) return state; + const active = activeWorkflowPaneIndex(state); + const rest = tabs.filter((_, at) => at !== index); + return stateOf(rest, active > index ? active - 1 : Math.min(active, rest.length - 1)); +} + +/** Asking for the tab that shows closes it, as the pressed control that asked says it will. */ +export function toggleWorkflowPaneTab( + state: WorkflowPaneState, + tab: WorkflowPaneTab, +): WorkflowPaneState { + const active = activeWorkflowPaneTab(state); + return active !== null && sameWorkflowPaneTab(active, tab) + ? closeWorkflowPaneTab(state, activeWorkflowPaneIndex(state)) + : openWorkflowPaneTab(state, tab); +} 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/hooks/useHandleNewThread.test.ts b/apps/web/src/hooks/useHandleNewThread.test.ts index 7c64d0077cc2b..07df36fe906a4 100644 --- a/apps/web/src/hooks/useHandleNewThread.test.ts +++ b/apps/web/src/hooks/useHandleNewThread.test.ts @@ -2,9 +2,15 @@ import { describe, expect, it, vi } from "vite-plus/test"; import type { EnvironmentId, ProjectId, RuntimeMode } from "@t3tools/contracts"; const testState = vi.hoisted(() => { - let completeProjectFileRead: (value: null) => void = () => undefined; - let projectFileRead = Promise.resolve(null); - let projectRemoved = false; + type ProjectFile = { readonly defaultThreadEnvMode?: "local" | "worktree" } | null; + let completeProjectFileRead: (value: ProjectFile) => void = () => undefined; + let projectFileRead = Promise.resolve(null); + let draftSession = { + envMode: "local", + worktreePath: null, + branch: null as string | null, + environmentSelection: undefined as "manual" | undefined, + }; let connectedEnvironmentIds = ["environment-primary", "environment-ssh"]; let targetSettings = { defaultThreadEnvMode: "local" as "local" | "worktree" | null, @@ -19,7 +25,6 @@ const testState = vi.hoisted(() => { readonly threadId: string; } | null = null; let openDraftRoute: { readonly kind: "draft"; readonly draftId: string } | null = null; - let draftsWithUserText = new Set(); const router = { state: { location: { href: "/" }, @@ -37,7 +42,7 @@ const testState = vi.hoisted(() => { getDraftSessionByLogicalProjectKey: vi.fn(() => storedDraft), getDraftSession: vi.fn(() => openDraftRoute === null - ? null + ? { ...draftSession, promotedTo: null, startFromOrigin: false } : { logicalProjectKey: "remote-project", promotedTo: null, @@ -56,34 +61,29 @@ const testState = vi.hoisted(() => { }; return { - completeProjectFileRead: (value: null) => completeProjectFileRead(value), + completeProjectFileRead: (value: ProjectFile) => completeProjectFileRead(value), + discoverBranch(branch: string) { + draftSession = { ...draftSession, branch }; + }, + keepEarlierManualChoice() { + draftSession = { ...draftSession, environmentSelection: "manual" }; + }, + pickBranch(branch: string) { + draftSession = { ...draftSession, branch, environmentSelection: "manual" }; + }, draftStore, get projectFileRead() { return projectFileRead; }, - get projectRemoved() { - return projectRemoved; - }, get connectedEnvironmentIds() { return connectedEnvironmentIds; }, disconnect(environmentId: string) { connectedEnvironmentIds = connectedEnvironmentIds.filter((id) => id !== environmentId); }, - removeProject() { - projectRemoved = true; - }, - hasUserText: (draft: { readonly draftId?: string } | null | undefined) => - draft?.draftId !== undefined && draftsWithUserText.has(draft.draftId), - giveUserText(draftId: string) { - draftsWithUserText = new Set([...draftsWithUserText, draftId]); - }, get openDraftRoute() { return openDraftRoute; }, - registerDraft(draft: NonNullable) { - storedDraft = draft; - }, openEmptyDraft(draftId: string) { openDraftRoute = { kind: "draft", draftId }; }, @@ -99,8 +99,12 @@ const testState = vi.hoisted(() => { ) { storedDraft = nextStoredDraft; openDraftRoute = null; - draftsWithUserText = new Set(); - projectRemoved = false; + draftSession = { + envMode: "local", + worktreePath: null, + branch: null, + environmentSelection: undefined, + }; connectedEnvironmentIds = ["environment-primary", "environment-ssh"]; targetSettings = { defaultThreadEnvMode: workspaceDefaults.envMode, @@ -113,7 +117,7 @@ const testState = vi.hoisted(() => { draftStore.setDraftThreadContext.mockClear(); draftStore.setLogicalProjectDraftThreadId.mockClear(); draftStore.setPrompt.mockClear(); - projectFileRead = new Promise((resolve) => { + projectFileRead = new Promise((resolve) => { completeProjectFileRead = resolve; }); }, @@ -186,6 +190,7 @@ vi.mock("@tanstack/react-router", () => ({ useParams: () => null, useRouter: () => testState.router, })); +vi.mock("react-dom", () => ({ flushSync: (update: () => void) => update() })); vi.mock("react", () => ({ useCallback: (callback: T) => callback, useMemo: (factory: () => T) => factory(), @@ -198,8 +203,7 @@ vi.mock("../composerDraftStore", () => { getState: () => testState.draftStore, }); return { - composerDraftHasUserContent: (draft: { readonly draftId?: string } | null | undefined) => - testState.hasUserText(draft), + composerDraftHasUserContent: () => false, markPromotedDraftThreadByRef: vi.fn(), useComposerDraftStore, }; @@ -212,6 +216,7 @@ vi.mock("../lib/chatThreadActions", async (importOriginal) => ({ vi.mock("../providerInstances", () => ({ resolveDefaultProviderModelSelection: () => null })); vi.mock("../lib/t3ProjectFileDefaults", () => ({ readT3ProjectFile: () => testState.projectFileRead, + peekT3ProjectFile: () => undefined, })); vi.mock("../lib/utils", () => ({ newDraftId: () => "draft-delayed", @@ -231,8 +236,7 @@ vi.mock("../state/entities", () => { defaultModelSelection: null, }; return { - readProject: () => (testState.projectRemoved ? null : project), - readProjects: () => (testState.projectRemoved ? [] : [project]), + readProjects: () => [project], readThreadShell: () => null, readThreadShells: () => [], useProjects: () => [], @@ -257,7 +261,11 @@ vi.mock("../uiStateStore", () => ({ })); vi.mock("./useSettings", () => ({ getClientSettings: () => ({}) })); -import { resolveDefaultProjectRef, useNewThreadHandler } from "./useHandleNewThread"; +import { + readPendingWorkspaceDefault, + resolveDefaultProjectRef, + useNewThreadHandler, +} from "./useHandleNewThread"; describe.each([ ["new", null], @@ -271,58 +279,79 @@ describe.each([ }, ], ])("useNewThreadHandler with a %s draft", (_, draft) => { - it("abandons a delayed draft open when the user navigates elsewhere", async () => { - testState.reset(draft); - const openThread = useNewThreadHandler(); - const pendingOpen = openThread( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { replace: true }, + it("opens the draft before the project file is read, then applies its workspace default", async () => { + testState.reset(draft, { envMode: null, startFromOrigin: false }); + const opened = await useNewThreadHandler()({ + environmentId: "environment-ssh", + projectId: "project-remote", + } as never); + + expect(testState.router.navigate).toHaveBeenCalledOnce(); + expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith( + "remote-project", + expect.anything(), + opened?.draftId, + expect.objectContaining({ envMode: "local" }), ); + testState.draftStore.setDraftThreadContext.mockClear(); - testState.router.state.location.href = "/usage"; - testState.completeProjectFileRead(null); - await pendingOpen; + testState.discoverBranch("main"); + const pendingDefault = readPendingWorkspaceDefault(opened!.draftId); + expect(pendingDefault).not.toBeNull(); + testState.completeProjectFileRead({ defaultThreadEnvMode: "worktree" }); + await pendingDefault; - expect(testState.router.state.location.href).toBe("/usage"); - expect(testState.router.navigate).not.toHaveBeenCalled(); - expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); - }); + expect(readPendingWorkspaceDefault(opened!.draftId)).toBeNull(); - it("resolves to the draft another opener showed for the same project meanwhile", async () => { - testState.reset(draft); - const pendingOpen = useNewThreadHandler()( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { replace: true }, - ); + expect(testState.draftStore.setDraftThreadContext).toHaveBeenCalledWith(opened?.draftId, { + envMode: "worktree", + startFromOrigin: false, + }); + }); - // The location moves before the route matches do. - testState.registerDraft({ - draftId: "draft-home", + it("applies the project file's default to a draft chosen manually before it opened", async () => { + testState.reset(draft, { envMode: null, startFromOrigin: false }); + testState.keepEarlierManualChoice(); + const opened = await useNewThreadHandler()({ environmentId: "environment-ssh", - promotedTo: null, - threadId: "thread-home", - }); - testState.router.state.location.href = "/draft/draft-home"; - testState.completeProjectFileRead(null); + projectId: "project-remote", + } as never); + testState.draftStore.setDraftThreadContext.mockClear(); - await expect(pendingOpen).resolves.toEqual({ - draftId: "draft-home", - threadId: "thread-home", + const pendingDefault = readPendingWorkspaceDefault(opened!.draftId); + expect(pendingDefault).not.toBeNull(); + testState.completeProjectFileRead({ defaultThreadEnvMode: "worktree" }); + await pendingDefault; + + expect(testState.draftStore.setDraftThreadContext).toHaveBeenCalledWith(opened?.draftId, { + envMode: "worktree", + startFromOrigin: false, }); - expect(testState.router.navigate).not.toHaveBeenCalled(); - expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); + }); + + it("keeps a branch the user picked while the project file loaded", async () => { + testState.reset(draft, { envMode: null, startFromOrigin: false }); + const opened = await useNewThreadHandler()({ + environmentId: "environment-ssh", + projectId: "project-remote", + } as never); + testState.draftStore.setDraftThreadContext.mockClear(); + + testState.pickBranch("feature"); + expect(readPendingWorkspaceDefault(opened!.draftId)).toBeNull(); + testState.completeProjectFileRead({ defaultThreadEnvMode: "worktree" }); + await testState.projectFileRead; + + expect(testState.draftStore.setDraftThreadContext).not.toHaveBeenCalled(); }); it("sets the prompt before the draft shows", async () => { testState.reset(draft); - const pendingOpen = useNewThreadHandler()( + const opened = await useNewThreadHandler()( { environmentId: "environment-ssh", projectId: "project-remote" } as never, { prompt: "Read the playbook. " }, ); - testState.completeProjectFileRead(null); - const opened = await pendingOpen; - expect(testState.draftStore.setPrompt).toHaveBeenCalledWith( opened?.draftId, "Read the playbook. ", @@ -331,46 +360,9 @@ describe.each([ testState.router.navigate.mock.invocationCallOrder[0] ?? 0, ); }); - - it("abandons a delayed draft open when the project is removed meanwhile", async () => { - testState.reset(draft); - const pendingOpen = useNewThreadHandler()( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { replace: true }, - ); - - testState.removeProject(); - testState.completeProjectFileRead(null); - - await expect(pendingOpen).resolves.toBeNull(); - expect(testState.router.navigate).not.toHaveBeenCalled(); - expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); - }); }); describe("useNewThreadHandler", () => { - it("keeps the text of a draft that gained some while it waited", async () => { - testState.reset(null); - const raced = { - draftId: "draft-raced", - environmentId: "environment-ssh", - promotedTo: null, - threadId: "thread-raced", - }; - testState.draftStore.getDraftSessionByLogicalProjectKey - .mockReturnValueOnce(null) - .mockReturnValueOnce(raced as never); - testState.giveUserText("draft-raced"); - - const opened = await useNewThreadHandler()( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { prompt: "Read the playbook. " }, - ); - - expect(opened?.draftId).toBe("draft-raced"); - expect(testState.draftStore.setPrompt).not.toHaveBeenCalled(); - }); - it("seeds the prompt into the empty draft that is already open", async () => { testState.reset(null); testState.openEmptyDraft("draft-open"); diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index f9926858bbb01..d4d1247c4578b 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -3,12 +3,19 @@ import { scopeProjectRef, scopeThreadRef, } from "@t3tools/client-runtime/environment"; -import { DEFAULT_SERVER_SETTINGS, type ScopedProjectRef, type ThreadId } from "@t3tools/contracts"; +import { + DEFAULT_SERVER_SETTINGS, + type ScopedProjectRef, + type T3ProjectFile, + type ThreadId, +} from "@t3tools/contracts"; import { type AnyRouter, useRouter } from "@tanstack/react-router"; +import { flushSync } from "react-dom"; import { composerDraftHasUserContent, markPromotedDraftThreadByRef, type DraftId, + type DraftSessionState, type DraftThreadEnvMode, type DraftThreadState, useComposerDraftStore, @@ -24,7 +31,6 @@ import { } from "@t3tools/client-runtime/state/project-grouping"; import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { - readProject, readProjects, readThreadShell, readThreadShells, @@ -39,7 +45,7 @@ import { threadHasStarted, } from "../lib/chatThreadActions"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; -import { readT3ProjectFile } from "../lib/t3ProjectFileDefaults"; +import { peekT3ProjectFile, readT3ProjectFile } from "../lib/t3ProjectFileDefaults"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentSummaries } from "../state/presentation"; import { environmentServerConfigsAtom } from "../state/server"; @@ -67,6 +73,39 @@ export function readLastUsedProjectKey(): string | null { } } +// Drafts that opened before their project's t3.json was read. A send waits for the file's +// workspace default unless the user has already chosen a workspace. +interface ProvisionalWorkspace { + readonly envMode: DraftThreadEnvMode; + // A reused draft keeps an earlier "manual" marker; only a switch to manual after opening is a choice. + readonly openedManual: boolean; +} + +const pendingWorkspaceDefaults = new Map< + DraftId, + ProvisionalWorkspace & { readonly settled: Promise } +>(); + +function keepsProvisionalWorkspace( + draft: DraftSessionState | null, + provisional: ProvisionalWorkspace, +): draft is DraftSessionState { + return ( + draft !== null && + draft.promotedTo == null && + draft.envMode === provisional.envMode && + draft.worktreePath === null && + (provisional.openedManual || draft.environmentSelection !== "manual") + ); +} + +export function readPendingWorkspaceDefault(draftId: DraftId): Promise | null { + const pending = pendingWorkspaceDefaults.get(draftId); + if (pending === undefined) return null; + const draft = useComposerDraftStore.getState().getDraftSession(draftId); + return keepsProvisionalWorkspace(draft, pending) ? pending.settled : null; +} + interface NewThreadWorkspaceOptions { branch?: string | null; worktreePath?: string | null; @@ -130,8 +169,6 @@ export function createNewThreadHandler(router: AnyRouter) { if (composerDraftHasUserContent(getComposerDraft(draftId))) return; setPrompt(draftId, options.prompt); }; - const requestingRouteHref = router.state.location.href; - const routeChangedSinceRequest = () => router.state.location.href !== requestingRouteHref; const currentRouteTarget = getCurrentRouteTarget(); // A draft gets a new pane instead of replacing the route thread in a split. const openDraft = async (draftId: DraftId) => { @@ -175,8 +212,6 @@ export function createNewThreadHandler(router: AnyRouter) { candidate.id === projectRef.projectId && candidate.environmentId === projectRef.environmentId, ); - const abandonedSinceRequest = () => - routeChangedSinceRequest() || (project !== undefined && readProject(projectRef) === null); const projectSettings = resolveProjectSettings( targetServerSettings, project?.id ?? null, @@ -211,19 +246,8 @@ export function createNewThreadHandler(router: AnyRouter) { currentRouteTarget?.kind === "draft" ? currentRouteTarget.draftId : null, destinationDraftId, }); - const resolveDefaultEnvMode = async (): Promise => { - // Environment queries wait for a connection, so reading the project file on an - // offline machine would never settle and the draft would never open. - const consultProjectFile = - project !== undefined && - projectSettings.settings.defaultThreadEnvMode === null && - appAtomRegistry - .get(environmentSummaries.connectedEnvironmentIdsAtom) - .includes(project.environmentId); - const projectFile = consultProjectFile - ? await readT3ProjectFile(project.environmentId, project.workspaceRoot) - : null; - return resolveNewThreadEnvMode({ + const envModeFor = (projectFile: T3ProjectFile | null): DraftThreadEnvMode => + resolveNewThreadEnvMode({ projectSettings: resolveProjectSettings( targetServerSettings, project?.id ?? null, @@ -243,25 +267,60 @@ export function createNewThreadHandler(router: AnyRouter) { [], ) > 0, }); + const startFromOriginFor = (envMode: DraftThreadEnvMode) => + resolveNewDraftStartFromOrigin({ + envMode, + newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, + }); + // The draft opens without waiting on t3.json: a cold read takes seconds on a loaded host. + // Its workspace default lands afterwards unless the user picked a workspace or sent first. + const resolveDefaultEnvMode = () => { + // Environment queries wait for a connection, so an offline machine's file is never read. + const consultProjectFile = + project !== undefined && + projectSettings.settings.defaultThreadEnvMode === null && + appAtomRegistry + .get(environmentSummaries.connectedEnvironmentIdsAtom) + .includes(project.environmentId); + if (!consultProjectFile) return { envMode: envModeFor(null), applyProjectFile: () => {} }; + const projectFileRead = readT3ProjectFile(project.environmentId, project.workspaceRoot); + const cachedProjectFile = peekT3ProjectFile(project.environmentId, project.workspaceRoot); + if (cachedProjectFile !== undefined) { + return { envMode: envModeFor(cachedProjectFile), applyProjectFile: () => {} }; + } + const envMode = envModeFor(null); + const applyProjectFile = (draftId: DraftId) => { + const provisional: ProvisionalWorkspace = { + envMode, + openedManual: getDraftSession(draftId)?.environmentSelection === "manual", + }; + const settled = projectFileRead + .then((projectFile) => { + const fileEnvMode = envModeFor(projectFile); + const draft = getDraftSession(draftId); + if (fileEnvMode === envMode || !keepsProvisionalWorkspace(draft, provisional)) return; + // Commit before a waiting send re-reads the composer's workspace. + flushSync(() => + setDraftThreadContext(draftId, { + envMode: fileEnvMode, + ...(draft.startFromOrigin === startFromOriginFor(envMode) + ? { startFromOrigin: startFromOriginFor(fileEnvMode) } + : {}), + }), + ); + }) + .finally(() => { + if (pendingWorkspaceDefaults.get(draftId)?.settled === settled) { + pendingWorkspaceDefaults.delete(draftId); + } + }); + pendingWorkspaceDefaults.set(draftId, { ...provisional, settled }); + }; + return { envMode, applyProjectFile }; }; const logicalProjectKey = project ? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings) : scopedProjectKey(projectRef); - // Another opener (home's own first-project draft) may have reached this project's draft first. - // Matches lag the location during a navigation, so compare against the location. - const resultIfAbandoned = () => { - const draft = getDraftSessionByLogicalProjectKey(logicalProjectKey); - if (draft === null || draft.promotedTo != null || readProject(projectRef) === null) { - return null; - } - const draftHref = router.buildLocation({ - to: "/draft/$draftId", - params: { draftId: draft.draftId }, - }).href; - return router.state.location.href === draftHref - ? { draftId: draft.draftId, threadId: draft.threadId } - : null; - }; const hasBranchOption = options?.branch !== undefined; const hasWorktreePathOption = options?.worktreePath !== undefined; const hasEnvModeOption = options?.envMode !== undefined; @@ -298,37 +357,17 @@ export function createNewThreadHandler(router: AnyRouter) { const hasExplicitWorkspaceOption = hasBranchOption || hasWorktreePathOption || hasEnvModeOption || hasStartFromOriginOption; let workspaceContext: NewThreadWorkspaceOptions | null = null; + let applyProjectFile: ((draftId: DraftId) => void) | null = null; if (hasExplicitWorkspaceOption) { workspaceContext = pickExplicitWorkspaceOptions(options); } else if (!isDraftAlreadyOpen) { - const defaultEnvMode = await resolveDefaultEnvMode(); - if (abandonedSinceRequest()) { - return resultIfAbandoned(); - } - // Concurrent calls may change the draft; stale resets, remaps, or navigation could clobber it. - const routeTargetNow = getCurrentRouteTarget(); - const openedMeanwhile = - routeTargetNow?.kind === "draft" && - routeTargetNow.draftId === emptyStoredDraftThread.draftId; - const promotedMeanwhile = - storedDraftThreadRef !== null && readThreadShell(storedDraftThreadRef) !== null; - const remappedMeanwhile = - getDraftSessionByLogicalProjectKey(logicalProjectKey)?.draftId !== - emptyStoredDraftThread.draftId; - const investedMeanwhile = composerDraftHasUserContent( - getComposerDraft(emptyStoredDraftThread.draftId), - ); - if (openedMeanwhile || promotedMeanwhile || remappedMeanwhile || investedMeanwhile) { - return null; - } + const defaultEnvMode = resolveDefaultEnvMode(); + applyProjectFile = defaultEnvMode.applyProjectFile; workspaceContext = { branch: null, worktreePath: null, - envMode: defaultEnvMode, - startFromOrigin: resolveNewDraftStartFromOrigin({ - envMode: defaultEnvMode, - newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, - }), + envMode: defaultEnvMode.envMode, + startFromOrigin: startFromOriginFor(defaultEnvMode.envMode), }; } if (workspaceContext) { @@ -368,6 +407,7 @@ export function createNewThreadHandler(router: AnyRouter) { threadId: emptyStoredDraftThread.threadId, }; seedPrompt(emptyStoredDraftThread.draftId); + applyProjectFile?.(emptyStoredDraftThread.draftId); const routeTargetAfterWrites = getCurrentRouteTarget(); if ( routeTargetAfterWrites?.kind === "draft" && @@ -413,40 +453,15 @@ export function createNewThreadHandler(router: AnyRouter) { const threadId = newThreadId(); const createdAt = new Date().toISOString(); return (async () => { - const initialEnvMode = options?.envMode ?? (await resolveDefaultEnvMode()); - if (abandonedSinceRequest()) { - return resultIfAbandoned(); - } - // Reuse drafts registered while awaiting so their pending navigation cannot lose them. - const racedDraft = getDraftSessionByLogicalProjectKey(logicalProjectKey); - if ( - racedDraft && - racedDraft.draftId !== storedDraftThread?.draftId && - readThreadShell(scopeThreadRef(racedDraft.environmentId, racedDraft.threadId)) === null - ) { - setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, racedDraft.draftId, { - threadId: racedDraft.threadId, - createdAt: racedDraft.createdAt, - runtimeMode: racedDraft.runtimeMode, - interactionMode: racedDraft.interactionMode, - ...pickExplicitWorkspaceOptions(options), - }); - seedPrompt(racedDraft.draftId); - await openDraft(racedDraft.draftId); - return { draftId: racedDraft.draftId, threadId: racedDraft.threadId }; - } + const defaultEnvMode = options?.envMode === undefined ? resolveDefaultEnvMode() : null; + const initialEnvMode = options?.envMode ?? defaultEnvMode?.envMode ?? "local"; setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, { threadId, createdAt, branch: options?.branch ?? null, worktreePath: options?.worktreePath ?? null, envMode: initialEnvMode, - startFromOrigin: - options?.startFromOrigin ?? - resolveNewDraftStartFromOrigin({ - envMode: initialEnvMode, - newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, - }), + startFromOrigin: options?.startFromOrigin ?? startFromOriginFor(initialEnvMode), runtimeMode: defaultRuntimeMode, ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}), }); @@ -456,6 +471,7 @@ export function createNewThreadHandler(router: AnyRouter) { setModelSelection(draftId, modelSelectionOverride, { replaceOptions: true }); } seedPrompt(draftId); + defaultEnvMode?.applyProjectFile(draftId); await openDraft(draftId); return { draftId, threadId }; })(); diff --git a/apps/web/src/i18n/I18nProvider.tsx b/apps/web/src/i18n/I18nProvider.tsx index d676e7f72b58e..5fbd532a86b48 100644 --- a/apps/web/src/i18n/I18nProvider.tsx +++ b/apps/web/src/i18n/I18nProvider.tsx @@ -1,10 +1,14 @@ import { GTProvider } from "gt-react"; import { useSyncExternalStore, type ReactNode } from "react"; -import { getI18nSnapshot, persistGTLocale, subscribeI18n } from "./runtime"; +import { getFormattingLocale, getI18nSnapshot, persistGTLocale, subscribeI18n } from "./runtime"; const reloadToSetting = (state: { readonly locale: string }) => persistGTLocale(state.locale); +export function useFormattingLocale(): string | undefined { + return useSyncExternalStore(subscribeI18n, getFormattingLocale); +} + export function I18nProvider({ children }: { readonly children: ReactNode }) { const { locale, translations } = useSyncExternalStore(subscribeI18n, getI18nSnapshot); return ( diff --git a/apps/web/src/i18n/locales.test.ts b/apps/web/src/i18n/locales.test.ts new file mode 100644 index 0000000000000..66d23e2170ba7 --- /dev/null +++ b/apps/web/src/i18n/locales.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveWebLocaleSelection } from "./locales"; + +describe("resolveWebLocaleSelection", () => { + it.each([ + ["system", ["en-GB"], "en", undefined], + ["system", ["zh-TW", "en-GB"], "en", undefined], + ["en", ["en-GB"], "en", undefined], + ["en", ["de-DE"], "en", "en"], + ["de", ["en-US"], "de", "de"], + ] as const)("%s with browser languages %j", (language, browserLocales, catalog, formatting) => { + expect(resolveWebLocaleSelection(language, browserLocales)).toEqual({ + catalogLocale: catalog, + formattingLocale: formatting, + }); + }); +}); diff --git a/apps/web/src/i18n/locales.ts b/apps/web/src/i18n/locales.ts index 26ac5721e4915..a9c6e20eddedd 100644 --- a/apps/web/src/i18n/locales.ts +++ b/apps/web/src/i18n/locales.ts @@ -1,4 +1,15 @@ +import { resolveLocale } from "@t3tools/client-runtime/locales"; + import gtConfig from "../../gt.config.json"; export const DEFAULT_LOCALE = gtConfig.defaultLocale; export const SUPPORTED_LOCALES: ReadonlyArray = [DEFAULT_LOCALE, ...gtConfig.locales]; + +export function resolveWebLocaleSelection(language: string, browserLocales: ReadonlyArray) { + const catalogLocale = resolveLocale(language, browserLocales, SUPPORTED_LOCALES, DEFAULT_LOCALE); + // Undefined formats with the host locale: "system", and English over a regional English browser. + const keepEnglishRegion = + language === DEFAULT_LOCALE && /^en(?:-|$)/i.test(browserLocales[0] ?? ""); + const formattingLocale = language === catalogLocale && !keepEnglishRegion ? language : undefined; + return { catalogLocale, formattingLocale }; +} diff --git a/apps/web/src/i18n/runtime.ts b/apps/web/src/i18n/runtime.ts index 188d296befd48..940a3a3f0b70c 100644 --- a/apps/web/src/i18n/runtime.ts +++ b/apps/web/src/i18n/runtime.ts @@ -1,4 +1,3 @@ -import { resolveLocale } from "@t3tools/client-runtime/locales"; import { getTranslationsSnapshot } from "gt-react"; import { @@ -7,21 +6,29 @@ import { updateClientSettings, } from "../hooks/useSettings"; import { initializeI18n } from "./initializeI18n"; -import { DEFAULT_LOCALE, SUPPORTED_LOCALES } from "./locales"; +import { DEFAULT_LOCALE, resolveWebLocaleSelection } from "./locales"; import { setActiveLocale } from "./messages"; type LocaleTranslations = Awaited>; export interface I18nSnapshot { readonly locale: string; + readonly formattingLocale: string | undefined; readonly translations: LocaleTranslations; } const loadedTranslations: LocaleTranslations = { [DEFAULT_LOCALE]: {} }; const pendingLoads = new Map>(); const listeners = new Set<() => void>(); -let snapshot: I18nSnapshot = { locale: DEFAULT_LOCALE, translations: { ...loadedTranslations } }; -let requestedLocale = DEFAULT_LOCALE; +let snapshot: I18nSnapshot = { + locale: DEFAULT_LOCALE, + formattingLocale: undefined, + translations: { ...loadedTranslations }, +}; +let requestedLocale: ReturnType = { + catalogLocale: DEFAULT_LOCALE, + formattingLocale: undefined, +}; function loadLocale(locale: string): Promise { if (locale in loadedTranslations) return Promise.resolve(); @@ -42,11 +49,16 @@ function loadLocale(locale: string): Promise { } function activateLocale(locale: string): void { - if (requestedLocale !== locale) return; - if (snapshot.locale === locale && snapshot.translations[locale] === loadedTranslations[locale]) { + if (requestedLocale.catalogLocale !== locale) return; + const { formattingLocale } = requestedLocale; + if ( + snapshot.locale === locale && + snapshot.formattingLocale === formattingLocale && + snapshot.translations[locale] === loadedTranslations[locale] + ) { return; } - snapshot = { locale, translations: { ...loadedTranslations } }; + snapshot = { locale, formattingLocale, translations: { ...loadedTranslations } }; setActiveLocale(locale); document.documentElement.lang = locale; for (const listener of listeners) listener(); @@ -54,12 +66,7 @@ function activateLocale(locale: string): void { function applyLanguageSetting(): void { // Not desktopBridge.getSystemLocale(): that is the regional/time locale, not the UI language. - requestedLocale = resolveLocale( - getClientSettings().language, - navigator.languages, - SUPPORTED_LOCALES, - DEFAULT_LOCALE, - ); + requestedLocale = resolveWebLocaleSelection(getClientSettings().language, navigator.languages); void whenLocaleReady(); } @@ -76,7 +83,7 @@ export function startI18n(): void { /** Resolves once the requested locale's translations are ready; immediate for English. */ export function whenLocaleReady(): Promise { - const locale = requestedLocale; + const locale = requestedLocale.catalogLocale; return loadLocale(locale).then(() => activateLocale(locale)); } @@ -90,3 +97,7 @@ export function subscribeI18n(listener: () => void): () => void { export function getI18nSnapshot(): I18nSnapshot { return snapshot; } + +export function getFormattingLocale(): string | undefined { + return snapshot.formattingLocale; +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 0e48b30d674da..bf4d2d77129c8 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -52,6 +52,27 @@ "eb0f60ef4f92ab7d": "Installiere {fj} 0.6 oder neuer von {fjUrl} und führe {fjLogin} aus, oder installiere {tea} 0.16 oder neuer von {teaUrl} und führe {teaLogin} für jeden Forgejo- oder Gitea-Server aus.", "d026a85e2e50e675": "Installiere die GitCafe CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", "22d3c0c48a34b5b3": "Installiere die TanStack Source CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", + "756c80ad262ef315": "Wartet im ursprünglichen Thread", + "d8df14f9905f38eb": "Gesendet", + "e7c59185f8ab3987": "Nicht gesendet", + "b54ddec9084fa955": "Ohne Senden geschlossen", + "fbaa7ab5da716e50": "Fehler", + "01bac997ea55272e": "Unverständlich", + "0f53bc8f74dfe56a": "Fehlende Funktion", + "055560f307e15e30": "Falsche Dokumentation", + "78344b60f407928e": "Sonstiges", + "f653846a95cd6e8f": "Art", + "f41ea186c275b56e": "Info", + "2f6e4f7cd364da73": "Erwartet", + "9d11c93d4035de3e": "Tatsächlich passiert", + "c87d0595693704f9": "Stattdessen getan", + "d7a4ea6ce5af44e0": "{speaker} · {count} Zeichen", + "f5114fb9c40fd929": "Du", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Runde {turn} · {what}", + "dfdaa6255a416140": "Übersicht über {turns, plural, one {{turns} letzte Runde} other {{turns} letzte Runden}}, {textTurns, plural, =0 {ohne Nachrichtentext} one {mit dem Nachrichtentext der letzten Runde} other {mit den Nachrichtentexten der letzten {textTurns} Runden}}{truncated, select, yes {, passend gekürzt} other {}}", + "260c6b45f52d2f27": "Fügt den Text deiner Nachrichten und der Antworten des Agenten aus {textTurns, plural, one {der letzten Runde} other {den letzten {textTurns} Runden}} hinzu.", + "afac52a5cc2dc801": "Deine Antwort konnte nicht gesendet werden. Versuche es erneut.", "79d776428f4d0650": "Die Datei konnte nicht geladen werden. Verbinde dich erneut und versuch es noch einmal.", "3ea34cbb1ca5ba9b": "Vorschau abgebrochen.", "7c0af279ecb3da3a": "Streamende Dateivorschauen sind in dieser Laufzeitumgebung nicht verfügbar.", @@ -118,9 +139,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.", @@ -246,6 +267,8 @@ "fec888c767b662d5": "Versucht, verknüpfte Issues zu prüfen", "bc31067af9c79d82": "{count, plural, one {Verknüpfte Issues {count}-mal geprüft} other {Verknüpfte Issues {count}-mal geprüft}}", "c712fec8d9dc6dd6": "{count, plural, one {{count}-mal versucht, verknüpfte Issues zu prüfen} other {{count}-mal versucht, verknüpfte Issues zu prüfen}}", + "81c2282590e549f5": "{count, plural, one {Read terminals {count} time} other {Read terminals {count} times}}", + "79cd7c5c29ffa938": "{count, plural, one {Tried to read terminals {count} time} other {Tried to read terminals {count} times}}", "537feee59d775e17": "{count, plural, one {Vorschau für {count} HTML-Seite angezeigt} other {Vorschau für {count} HTML-Seiten angezeigt}}", "4b45ac8cb8df04a4": "{count, plural, one {Versucht, eine Vorschau für {count} HTML-Seite anzuzeigen} other {Versucht, eine Vorschau für {count} HTML-Seiten anzuzeigen}}", "a6f62fca5dd25455": "{count, plural, one {{count} HTML-Seite gerendert} other {{count} HTML-Seiten gerendert}}", @@ -376,6 +399,31 @@ "476ca970255eaea4": "Verknüpfe diese Umgebung mit T3 Connect, um eine öffentliche URL zu erhalten.", "6b80f5b38a8f9950": "Nur dieser Computer kann diese Adresse aufrufen. Verknüpfe T3 Connect für eine öffentliche URL.", "c5a7b1d3891dd0b8": "Funktioniert überall, wo die Adresse dieser Umgebung erreichbar ist, zum Beispiel über Tailscale oder deinen eigenen Proxy. Verknüpfe T3 Connect für eine öffentliche URL.", + "3669395daf36fd33": "Auf diesem Server nicht mehr registriert", + "fe513cf316e796e3": "Läuft als Teil anderer Workflows", + "ccf00b97925efab3": "Wird von Hand gestartet", + "421e585eb092b07b": "Startet bei {triggers}", + "7bd7c58592671384": "Braucht dich", + "834ca879c14c167b": "Arbeitet", + "582d6df7dfab86fb": "Pausiert", + "ea6583ce92507ee3": "Schläft", + "7ea8cb8af281ce93": "Wartet", + "1347868f2523140e": "Fertig", + "57d76c4614054271": "Gestoppt", + "5c7344bd51d0b966": "Übersprungen", + "b2074e9bd23049a6": "Abgebrochen", + "5bb7401807ee2fb5": "Fragt: {question} und {more} weitere", + "9e4286183d5f9e34": "Fragt: {question}", + "474c18d001bd6717": "Ein Schritt ist fehlgeschlagen", + "d3890f4eb1508781": "Führt eigene Schritte aus", + "3e7ced10c9482af0": "{step} arbeitet", + "237e1bcb1cf1bdec": "Schläft bei {step}", + "3f7b17ac5a20c8d2": "Führt {run} aus", + "0306f5f324b8aaa5": "{count} Ausführungen laufen", + "e8fd779b84a202a2": "Wartet", + "b6d55657e1a027b8": "Wartet auf {step}", + "e942562a42aede34": "Abgeschlossen", + "26b2b9727fe11289": "Vorzeitig beendet", "1bb995dcec481554": "Genehmige dieses Gerät auf {host}. Dort wird der Code {verificationCode} angezeigt.", "8696a33219944832": "Der Autorisierungsnachweis für die WebSocket-Verbindung konnte nicht erstellt werden.", "5678f133a8631f7d": "Deine Cloud-Anmeldung hat sich geändert. Melde dich erneut an, um die Umgebung zu autorisieren.", @@ -637,6 +685,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", @@ -1720,6 +1771,8 @@ "2e995206e087c3fc": "Versuche zu antworten, sobald die Verbindung oder ausstehende Eingabe geklärt ist.", "604ec3067171a0d7": "Unterhaltung", "d6182a057ea12624": "Übergeordneter Thread", + "f2d8537c33cc55a5": "Schritt der Workflow-Ausführung", + "ba8337dca3232880": "Ausführung öffnen", "30fa4a764d11ae42": "{name} konnte nicht heruntergeladen werden", "4952f87dc98191a7": "Der Anhang ist nicht verfügbar.", "2fd6d178493fb407": "Die aktuelle Runde konnte nicht unterbrochen werden.", @@ -1784,6 +1837,8 @@ "181677cda4d3fd0a": "Keine verbundene Umgebung kann ein Projekt hinzufügen", "3a0bf3d17f31584e": "Neuer Thread in {project}", "4b4b64cc95acb8da": "Neuer Thread in...", + "2c45783ab9680fdb": "Open Git graph", + "e813386e62652710": "Open agent stage", "3f581e98c86df72a": "Neuer Thread ohne Projekt", "e510d9a7b684fbfe": "Ein Issue einordnen", "cce3d80a2ddf1125": "Ein Agent untersucht ein Problem mit T3 Code und hilft beim Erstellen eines Issues", @@ -1805,6 +1860,7 @@ "04fd71efaa2c3b92": "Pull Requests öffnen", "57e875b79b98ab82": "Issues öffnen", "f1db0a234c777a1d": "T3 Code in einer anderen App verwenden (MCP)", + "6050f22f63e2bcb5": "Workflows öffnen", "a0cc19e60dd99851": "Nutzung öffnen", "46694969044eee98": "Nächsten Arbeitsbereich fokussieren", "0a1011328ba42eef": "Vorherigen Arbeitsbereich fokussieren", @@ -2361,14 +2417,24 @@ "05037ca1666fd421": "Terminals sind nur aus einem Projekt-Thread verfügbar.", "a3aa1e49af278d41": "Dateien sind nur verfügbar, wenn ein Projekt geöffnet ist.", "87ea6995ea1e7aa4": "Diffs sind nur für Server-Threads in Git-Repositorys verfügbar.", + "80f10f5ea1804d8d": "The Git graph needs a Git repository on an up-to-date server.", "4a87cae01ccde544": "Der Branch dieses Threads hat noch keinen Pull Request.", "32535dba0b9af642": "Dieser Thread hat keine verknüpften Elemente.", + "d955eee48dece3c0": "Enable the agent stage in Settings > General.", + "d2f2f6d05148f8a3": "Threads a coordinator runs have no thread overview.", + "26c1c05b0d1d98fd": "Turn on coordinator decisions in Settings > General.", + "486d4369c4fbec9e": "Notes are only available from a thread.", + "50b5a57d3bd6f6ef": "Instructions are only available from a thread.", + "007ab76950f73521": "Media is only available from a thread.", "07080dead70f4cc5": "Geräte sind nur aus einem Thread verfügbar.", "a4bf49b31758ff7e": "Nur in der Desktop-App verfügbar.", "e917841cb66f9af1": "Verfügbar, wenn ein Projekt geöffnet ist.", "14c15fad0c2ee0c8": "Verfügbar für Git-Repositorys.", "9176276c78f3893f": "Noch kein Pull Request auf diesem Branch.", "52ce9db6fb62a59f": "Keine verknüpften Elemente verfügbar.", + "96c2ee76dd82d2cc": "Enable it in Settings > General.", + "2199013487151590": "Not for threads a coordinator runs.", + "f7a9300d9f9030d5": "Turn on coordinator decisions in Settings.", "e5d6f41e4fe4efd6": "Aus einem Thread verfügbar.", "0ebc2bb883a8e283": "Nach der ersten Nachricht verfügbar.", "84d0ff8fb9846057": "Tab-Ton einschalten", @@ -2377,8 +2443,15 @@ "5c78a8ae7b71af1d": "Terminal", "cba3e832ece50257": "Dateien", "83ac3423d6dfc4a7": "Diff", + "016750bdd5076287": "Git graph", "da16af47eff38ae9": "Pull Request", "ad3929f0103925d7": "Verknüpfte Elemente", + "70e7b208e032024a": "Stage", + "0caf7e5748f1d17b": "Threads this one started, and which need you.", + "96018894225bd4ff": "Inbox", + "0ed16d7723c04288": "Decisions the coordinator asks you for.", + "aec2b493d2b01445": "Notes", + "9e92f6aa6edae875": "Notes and todos for this thread, its project, or everywhere.", "ac0de2a59d9c8860": "Gerät", "1354df9fb7278843": "Einen iOS-Simulator oder Android-Emulator ansehen.", "fdcd9643e2e63b15": "Stelle eine Nebenfrage, während dieser Thread weiterarbeitet.", @@ -2497,8 +2570,7 @@ "2d1c111e1b4ae0b0": "Thread „{title}“ löschen?", "c568ab8dad798ec5": "Dadurch wird der Gesprächsverlauf dieses Threads dauerhaft gelöscht.", "0fd1c746a0e38003": "Thread konnte nicht gelöscht werden", - "0ecde875b0dd2f93": "Threads nach Projekt filtern: {projects}", - "1ef65b647231ff0b": "Threads nach Projekt filtern", + "1c8fc3c4a42949ab": "Projekte: {projects}", "165511761be2855c": "Projekte durchsuchen", "a46a6467883575a4": "Projekte durchsuchen...", "fdc0e086438a3045": "Projekteinstellungen für {project}", @@ -2561,10 +2633,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 +2645,7 @@ "a3178769f8308cbc": "Thread fehlgeschlagen", "89b5e8f3887812da": "Gastanfrage", "62e626804919b294": "Eingabe nötig", + "c6196d99000642b4": "Thread öffnen", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", @@ -2597,8 +2669,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", @@ -2687,8 +2757,6 @@ "78a04e0e625c0990": "Update fehlgeschlagen", "c24de5eb69373a55": "Dieser {build}-Build ignoriert {track}-Releases. Prüfe den Update-Kanal in den Einstellungen, um den Wechsel abzuschließen.", "b02ae45a6109c93b": "Auf dem neuesten Stand", - "edcda9e8ee4ccad8": "Update {version} installieren und T3 Code neu starten?\n\nLaufende Aufgaben werden unterbrochen. Stelle sicher, dass du bereit bist, bevor du fortfährst.", - "02eba0f7cc90f759": "Update installieren und T3 Code neu starten?\n\nLaufende Aufgaben werden unterbrochen. Stelle sicher, dass du bereit bist, bevor du fortfährst.", "9ed4d8a1531b9631": "Automatische Updates sind in diesem Build nicht verfügbar.", "c8c23435e780a60c": "Updates nicht verfügbar", "1af5f9767371ffd7": "Nach Updates suchen", @@ -3035,8 +3103,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 +3347,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 +3524,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", @@ -3578,6 +3650,13 @@ "c53bc5a4b0314342": "Nächstes Medium", "2950b1424a3cddf5": "Verbinde dich erneut mit dieser Umgebung und öffne das Medium noch einmal.", "ef638bf1479a5461": "Die Umgebung hat eine ungültige Medien-URL zurückgegeben.", + "3ccfbf7e86868c35": "Feedback für das T3-Team", + "4e0710d19dfc2e7e": "Diesen Bericht an das T3-Team senden?", + "87d0ae0723ba75d1": "Das ist alles, was deinen Rechner verlässt. Erst wenn du auf Senden klickst, wird etwas gesendet.", + "bf19826f81484328": "Unterhaltung mitsenden", + "ddb7e6f8ce99e657": "Nur wer auf diesem Rechner Agenten ausführen kann, kann den Bericht senden oder ablehnen.", + "03c1eb603c112f47": "Nicht senden", + "653405e4ed498d9f": "Senden", "262955d6eb632f9b": "Die Zwischenablage-API ist beim Kopieren des Gast-Links nicht verfügbar.", "f1a4f2b04cdbb4ef": "Der Gast-Link konnte nicht in die Zwischenablage kopiert werden.", "cf3490a604e44d31": "Gastlink konnte nicht erstellt werden.", @@ -3598,7 +3677,6 @@ "abd89e9eefedf11b": "Fertig", "18d166056c1ab6ff": "Freigabe beenden", "7a2d510eac9e4587": "Gastlink abgelaufen", - "653405e4ed498d9f": "Senden", "21888e302219891d": "Vergrößerte Vorschau von {title}", "419719298a7acaea": "Verkleinern", "ed8d5db95359cff4": "Zoom zurücksetzen", @@ -3694,7 +3772,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 +3783,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 +4061,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", @@ -5454,6 +5529,22 @@ "f0d79aa56f06663f": "Diese Datei ist zu groß für die vollständige Anzeige. Die Zahlen umfassen alle Änderungen.", "7fdde2b893ba1b9d": "Entfernt", "e58ce271d835b447": "Hinzugefügt", + "fb5c7ff5ea76e01a": "Added by esveo's fork. Click to list all of its settings.", + "352fa6aeb5d55665": "Trail the provider icon behind the thread title instead of giving it a line of its own. The line it saves also carried the branch, pull request badge and diff counts.", + "9d44fa03a230e0d8": "Reset two-line thread cards to default", + "7b216eedb1abe696": "Two-line thread cards", + "8d90fcd918e901c8": "Keep each project's threads together in the sidebar, under a header that folds the project away. Ordering stays by recency: the project with the newest thread leads.", + "d5dfd89c9a281386": "Projektgruppierung auf Standard zurücksetzen", + "aac9f889c7ec7ff5": "Group sidebar threads by project", + "da375a07c5309184": "Show how full the thread's context window is next to the composer controls.", + "33f6b88cba203990": "Reset context window usage to default", + "6496f57baeded3fa": "Context window usage", + "d9c146dc6b95714d": "Show how many minutes are left before the prompt cache expires. Claude only.", + "69609e27c2107da5": "Reset prompt cache timer to default", + "a4917d2b93c478f6": "Prompt cache timer", + "ea8ebcb77e657e9f": "Open the thread details card with workspace and version control in every thread. Off, it stays closed until you open it, and each thread remembers your choice.", + "662288b90e19635f": "Thread-Details auf Standard zurücksetzen", + "92729a403d37c575": "Open thread details by default", "07b9970b662ab70d": "Mermaid-Quelltext anzeigen", "5a422b7be35243f5": "Gerendertes Diagramm anzeigen", "c0628ad999cbbbf5": "Markdown-Quelltext anzeigen", @@ -5561,6 +5652,7 @@ "723d88a5fa7e2fdd": "Keine passenden Dateien.", "f8d6e9a1a2870a5c": "Datei-Explorer", "109edd252917113b": "Größe des Datei-Explorers ändern", + "7abd6af24fed7b60": "The file does not exist in the workspace or the home folder.", "37cbd2ecc659a007": "Datei", "b5188f172f59ca79": "Diese Verbindung kann keine Host-Dateien lesen.", "c3c5d36466ad2191": "Datei im Vorschaubrowser öffnen", @@ -5600,7 +5692,6 @@ }, ". Prüfe den Pfad des Links oder suche die Datei unter Dateien." ], - "b9b6bbd1e1ea189f": "Ganze Datei", "d715e9494fdbaaf6": "Die Schriftart konnte nicht geladen werden.", "ff17c777a72b4408": "Schriftvorschauen sind auf 10 MB begrenzt.", "6bd41ad699e22f10": "Die Schriftart ist nicht verfügbar.", @@ -5610,6 +5701,7 @@ "a9abaaa4220eae21": "{error} Speichere sie, um sie in einer anderen App zu öffnen.", "c508c9000d9656f8": "Schriftvorschau", "1c416d621d250be8": "Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich.", + "d7d08260f16b7828": "Die Datei wird noch geladen. Versuche es gleich noch einmal.", "76ebb03de52c92d6": "Der Textbetrachter wurde beendet.", "f48162e8e8c12af7": "Der Textbetrachter konnte nicht geladen werden. Schließe die Datei und versuche es erneut.", "bc4c5b13d38a5da7": "Vorschau geschlossen.", @@ -5617,8 +5709,6 @@ "9450d1827ef336a1": "Ein anderer Kopiervorgang läuft.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} Zeile} other {{formatted} Zeilen}}", "13b14784f8707ddd": "0 Byte", - "f6e9581cba3467fa": "Wird indiziert…", - "2d1f293ac12463fc": "Der Rest der Datei wird geladen…", "b75105bef8f564a4": "Die ersten 1.024 Spalten werden angezeigt. Quelltext und Speichern behalten alle Spalten.", "2a6e1b1f209c3888": "Diese Datei ist leer.", "192fc79eb3b5b2cb": "Dieses Diagramm enthält Ressourcen-URLs, Markup, Knotenmetadaten oder eine benutzerdefinierte Konfiguration. Zeige den Mermaid-Quelltext an, um es sicher zu prüfen.", @@ -5805,7 +5895,6 @@ "0061fff77e36bd4f": "Der Server ist nicht erreichbar.", "04dfdd46e3dd4a2e": "Etwas ist schiefgelaufen. Versuche es erneut.", "084bb2d8127a508d": "Gesendet", - "e7c59185f8ab3987": "Nicht gesendet", "77c01a15bd36d17c": "Dieser Link ist abgelaufen oder ungültig", "e0e736810f3cbef2": "Bitte den Besitzer um einen neuen Link. Jeder Link funktioniert in einem Browser.", "c3c53aa46f7330e5": "Dieser Link ist abgelaufen", @@ -5827,6 +5916,13 @@ "cbb2129c0dd4f40b": "Angehängte Dateien dürfen insgesamt bis zu 10 MB pro Nachricht groß sein.", "03b9cd79cfe0b435": "Diese Datei kann nicht angehängt werden. Bilder müssen PNG, JPEG, GIF oder WebP sein.", "8ff29c78798e6ac1": "Dieses Element konnte nicht geladen werden.", + "535923000a0f3e3b": "Send /compact to a large, idle Claude thread shortly before its 1-hour prompt cache expires, so the next message skips caching the whole conversation again. 5-minute caches are left alone.", + "bd8eb8f5f9843bc6": "Reset idle auto-compact to default", + "1db274eacf03c8de": "Auto-compact idle Claude threads", + "fb6643c75aafd996": "Between {min} and {max}; it has to fall inside the cache's hour.", + "48dee64ca7904281": "Minutes idle before auto-compact", + "8937fe924464eb70": "Smaller threads are cheap to cache again and keep their full history.", + "1981f1e1a753aabc": "Minimum context tokens for auto-compact", "94ab4591ce101233": "Der Kommentar konnte nicht gepostet werden", "92d0d4eab2596772": "Der Tracker hat es abgelehnt.", "33591d9596fb7cb7": "Kommentar hinzufügen", @@ -8695,12 +8791,16 @@ "58e0e226493150e7": "Issue-Tracker konnten nicht geladen werden", "77cfcbde543df32d": "Details zu {tracker} ein-/ausblenden", "0083f65885c60156": "{tracker} trennen", - "295392927d5c8a84": "Wähle für jedes Projekt ein oder mehrere {scope}s in {tracker}. Ihre Issues erscheinen neben denen des Repositorys, und Agenten legen neue Issues im ersten an.", + "ed83b25c71c98a20": "Wähle für jedes Projekt ein oder mehrere {scope}s in {tracker}. Ihre Issues erscheinen neben denen des Repositorys, und Agenten legen neue Issues im ersten an, sofern kein anderes verlangt wird.", "19c2d5e81ff8f89a": "{tracker} {scope} für {project}", "68e061510b765772": "Nicht zugeordnet", + "99d51127f573296b": "Weiteres Konto", + "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer.", + "99963c0142e17f00": "Für das neue {tracker}-Konto.", "a2d95d39d3398bda": "Anmeldedaten abgelehnt", "9eae463720500113": "Auf dem Server gespeichert.", "b6e27ab2537ef874": "Erstellen", + "6d8e4ebc889bace9": "Konto hinzufügen", "13ef526271b0f5d4": "Alle Bedingungen löschen", "d1938a629f039515": "Bedingung entfernen", "84a605b241ce65b7": "Gruppe und ihre Bedingungen entfernen", @@ -8830,6 +8930,12 @@ "d3866ead082d14e5": "Tastenkürzel hinzufügen", "d4345c90894a3220": "keybindings.json öffnen", "e56a8d51219efaa0": "Keine Tastenkürzel entsprechen deiner Suche.", + "90a258fff61fd77e": "Aus", + "4060244a7079a0d2": "Wenn ich darum bitte", + "e88c9d8769544731": "Automatisch", + "f29d1dade4dde8aa": "Agenten senden kein Feedback an das T3-Team.", + "93c4c53562d30a98": "Wenn du darum bittest, zeigen Agenten dir einen kurzen Bericht über T3 Code und senden ihn mit deiner Zustimmung an das T3-Team.", + "cd9ee803e8727017": "Agenten melden auch selbstständig Probleme mit T3 Code, auf die sie stoßen, etwa ein fehlgeschlagenes T3-Tool.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Threads in der Seitenleiste in Projektordnern gruppieren. Angeheftete Threads bleiben oben, Zurückgestellte und Erledigte bleiben unter den Ordnern.", "e4e91d155cb6a9b4": "Schlichte Seitenleiste (nach Projekt gruppieren)", @@ -8838,11 +8944,16 @@ "9ae293971d93c819": "Teile einen Thread mit einem Gast, der ihn live im Browser verfolgt und Nachrichten sendet, die du genehmigst. Melde dich bei T3 Connect an, um Gastlinks zu nutzen.", "0aa5406ac4d7f7c7": "Gastlinks", "f0e853acd2006d53": "Verknüpfte Umgebungen", + "ef10c2dff987f3ea": "Führe mehrstufige Workflows aus Dateien im Ordner workflows des T3-Home dieses Servers aus. Öffne sie über die Befehlspalette. Solange es aus ist, läuft nichts aus diesem Ordner; Läufe warten, bis es wieder an ist.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Nach einer Claude- oder Codex-Runde eine vorhergesagte nächste Nachricht im leeren Eingabefeld anzeigen. Tab übernimmt sie. Jede ist eine zusätzliche gecachte Anfrage in deinem Tarif. Erfordert Codex 0.165+. Claude-Threads werden nach einem Neustart aktualisiert.", "d4b2a2ec812aafb0": "Nächsten Prompt vorschlagen", "298c7150a7621c80": "Simlock-Geräte-Hosts", "67937aa49179285e": "Auf einem Mac neue Worktrees aus einem im T3-Home-Ordner zwischengespeicherten Checkout klonen, statt jede Datei zu schreiben. Verwendet den normalen Git-Checkout, wenn das nicht geht. Beim Ausschalten wird der Cache gelöscht.", "f9904f78d3003f58": "Schneller Worktree-Checkout", + "9c2f647882522302": "Die ausgewählten Rechner verwenden unterschiedliche Modi für Agenten-Feedback.", + "31bbf7bf8c0a5279": "Agenten-Feedback", + "d52b3d6bf9f2a013": "Gemischt", "ec7623deed751c05": [ "Teile einen Thread mit einem Gast, der ihn live im Browser verfolgt und Nachrichten sendet, die du genehmigst. Erfordert T3 Connect: Melde dich an und verknüpfe diesen Rechner unter", " ", @@ -8926,7 +9037,9 @@ "fb71127e5746a6bc": "Unter „Freigabe & Zugriff“ dort oder mit t3 pair", "1e3fee7084791773": "Auch {target} zurück mit {source} verknüpfen", "ea34a190b0bd804c": "Agenten auf {target} können dann auch auf {source} arbeiten.", - "ad5ed0ce61b966eb": "{label} vergessen? Agenten von hier arbeiten dort nicht mehr. Widerrufe „T3 Code · …“ unter „Freigabe & Zugriff“ auf {label}, um die Sitzung auch dort zu beenden.", + "974f8c65e8b5f492": "{label} vergessen? Agenten hier arbeiten dort nicht mehr, und ihre Sitzung auf {label} endet ebenfalls, wenn es antwortet.", + "6cf9e3083b15614f": "{label} hat nicht geantwortet", + "34ccbdf619b83be3": "Widerrufe „T3 Code · …“ unter „Freigabe & Zugriff“ auf {label}, um die Sitzung auch dort zu beenden.", "81c9796bf61b306a": "Verknüpfung konnte nicht vergessen werden", "130e51beb6cf5aad": "Umgebung verknüpfen", "122c3e355699e69d": "Agenten hier können dort dann Threads starten, ihnen Nachrichten senden und auf sie warten. Sie erscheint unter „Autorisierte Clients“ in „Freigabe & Zugriff“ dieser Umgebung und kann dort widerrufen werden.", @@ -9155,7 +9268,6 @@ "0b4779a1825c85bc": "Der gemeinsame Name dieser Projektgruppe in der Seitenleiste und in Thread-Listen.", "f68cbda4df83d739": "Projektname auf Standard zurücksetzen", "56e37b85027e8431": "Projektsymbol", - "e88c9d8769544731": "Automatisch", "c99736317da5b1fa": "Projektsymbol auf Standard zurücksetzen", "6afaa3e3739dc570": "Projektsymbol auswählen", "51651ce45d481a20": "Datei für Projektsymbol auswählen", @@ -10065,7 +10177,6 @@ "53de7aafe0afc10d": "Design-Einstellungen konnten nicht wiederhergestellt werden", "006bfa1846fe5dd2": "Tage der Inaktivität bis zum automatischen Erledigen", "d9b0fbd680d5f175": "Seitenleiste", - "d5dfd89c9a281386": "Projektgruppierung auf Standard zurücksetzen", "cd5452cc9e13c818": "Projektgruppierung", "cfb01b8a2a3361fb": "Projektreihenfolge auf Standard zurücksetzen", "26abcbe322049a8a": "Bereich „In Arbeit“ auf Standard zurücksetzen", @@ -10130,7 +10241,6 @@ "16bdc70b858c223f": "Proaktive Panels auf Standard zurücksetzen", "c5424f09d77138ff": "Wann ein inaktiver Claude-Thread über 200.000 Tokens komprimiert wird: nach deiner Rückkehr, kurz bevor sein Prompt-Cache abläuft, oder nie. Jeder Claude-Anbieter kann das überschreiben.", "3e99c5c14f4939c8": "Inaktive Threads komprimieren auf Standard zurücksetzen", - "d52b3d6bf9f2a013": "Gemischt", "cd72fe451ba0d6aa": "Neue Projekte", "394c3bd0a1782c8e": "Leer lassen, um „~/“ zu verwenden, wenn sich der Dialog „Projekt hinzufügen“ öffnet.", "f9b912a818bd869d": "Basisverzeichnis für neue Projekte auf Standard zurücksetzen", @@ -11032,7 +11142,6 @@ "4a237f41ce592b7f": "Die Worktrees dieses Projekts behalten, bis du sie manuell löschst.", "00b8ffd8ea6e6a93": "Diese Regeln für dieses Projekt verwenden.", "72c279824d15a999": "Die Worktree-Bereinigungseinstellungen jedes Rechners verwenden.", - "90a258fff61fd77e": "Aus", "b5702d0b64866b08": "Benutzerdefiniert", "c009c901f3eefe78": "Worktrees gelöschter Threads löschen", "431c7cd6d50102b7": "Ungenutzte Worktrees entfernen, wenn aktive oder archivierte Threads gelöscht werden. Worktrees mit lokalen Änderungen bleiben erhalten.", @@ -11388,7 +11497,6 @@ "f2043e87a10cb831": "Design bearbeiten", "595bdeefcdc9bf31": "Design-Datei exportieren", "b480281b3791b685": "Wähle, was die Karte mit Thread-Details anzeigt. Du kannst auch mit der rechten Maustaste auf die Karte klicken.", - "662288b90e19635f": "Thread-Details auf Standard zurücksetzen", "871d059d88548434": "Thread-Details: {enabled} von {total} an", "cec1fbb8b4c9180d": [ { @@ -11729,7 +11837,6 @@ "4c70e3e7b3e6c493": "Geheimnisse", "79b768229c9ef672": "Wartung", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Info", "af4b7734da1d5ce7": "Spracheingabe", "4ec62c39ca3192bf": "Versionskontrolle & Issues", "f2bf529f85e05494": "Freigabe & Zugriff", @@ -11758,11 +11865,17 @@ "8f5966eebd2b110f": "darstellung farben palette benutzerdefiniert import", "633ed64e952cca3b": "farben rahmen oberfläche", "9cf8308531b4ff31": "transparent transparenz deckend menüs dialoge eingabefeld", + "d99bfbc557fae743": "Notion", + "89df56091835b3a6": "notion integration secret pages links viewer connect token ntn", + "d699adcc04d4d4ab": "sidebar compact row height branch provider icon diff pull request", + "9b9df5ba41c4a8e2": "Group threads by project", + "0ed2eab2c1953531": "sidebar project folder runs grouping collapse header repository", "d8d6cfd630cff22d": "rot grün blau orange hinzufügungen löschungen änderungen anzahl palette farbenblind", "717e49895cfee1c7": "breit volle breite spalte layout nachrichten eingabefeld monitor", "88365077fd80787b": "anpassen anzeigen ausblenden panel karte umgebung editor skripte branch pull request git änderungen server automatisierungen herkunft nutzung limits 5 stunden wöchentlich kontingent tokens kontextfenster", "d561f74efa5f3920": "reasoning aufwand denken balken grafik wort bezeichnung stufe eingabefeld", "6113c17109ee0d57": "latex tex katex gleichungen formeln markdown", + "dfe7ead48efc3f5a": "thread details card panel workspace version control closed collapsed hide", "8c8364d44fa28d22": "dev nightly latest kanal artwork badge bezeichnung ausblenden keine", "2d90635156dfcb5a": "typografie schriftart größe system sans", "d32e93777e4819c8": "typografie schriftart größe eingabefeld eingabe", @@ -11784,6 +11897,7 @@ "d443390c4d2dcfd4": "barrierefreiheit a11y screenreader nvda jaws voiceover orca sprachausgabe fenstertitel tab-titel alt tab taskleiste thread status reihenfolge arbeitet genehmigung", "6826fa9579c22035": "beta teilen gast einladen link teammitglied zuschauen t3 connect tunnel", "f10c06cba0cdf7fe": "beta anderen rechner verknüpfen vps peer agenten dort arbeiten delegieren", + "bc0b409d89ce086e": "beta workflow dauerhafte läufe automatisierung schritte zeitplan webhook ordner", "4a21cf825a2045b0": "beta tab autovervollständigung nächste nachricht vorhersagen claude codex ghost text", "fea2dc36585c4a20": "Simlock-Geräte-Hosts (Alpha)", "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lease gateway", @@ -11825,7 +11939,29 @@ "34d74827c2a8b009": "enter return befehl strg ctrl mehrzeilig prompt neue zeile eingabefeld", "9d1013084c46ecce": "warteschlange einreihen umlenken laufende runde senden standardverhalten eingabefeld", "e5e7f5e1fb1f2e4c": "subagent nebenchat verknüpfter thread klick rechte leiste seitenleiste hauptansicht befehl strg mittelklick", + "5c59d7e2673267ea": "composer tokens usage meter percentage compaction", + "e0d6ec10218b714e": "composer claude cache ttl expire minutes warm cold tokens", + "ce0952668aba4140": "Agent stage", + "f637899f994b78c3": "sprites stations subagents thinking editing terminal right panel everything", + "9d9d3374ee961b91": "Easter eggs", + "571180dbfeddbfd5": "surprise fun rocket animation message send hidden", + "0716adb0d55ffa58": "Voice calls", + "027d8f5ea5555973": "voice call phone gpt live feature flag anruf telefon schalter", + "60d509bb55e2967c": "Voice call voice", + "0e5f5c5ebf026abd": "voice call phone gpt live speaker stimme anruf telefon", + "266f1e2b55e419b0": "Voice call follow-up", + "392226d9bed6fe21": "voice call queue steer follow-up warteschlange anruf", "5b8b854de7ee6f4d": "installierte cli versionen neuer verfügbar codex claude cursor grok fx kiro opencode", + "1ceaab7d898b689a": "Child threads in the sidebar", + "fa5a42a73d1c1ece": "coordinator subthreads nested group expand sidebar orchestration children", + "6a1072050d1ad19e": "Coordinator decisions", + "474ba8e025886f86": "inbox questions answers decide approve coordinator open items", + "8f5558f063214509": "Cross-project threads", + "b809e3ffa5178b88": "agents coordinator other projects read message start threads repositories", + "44207b47d209f601": "compact context prompt cache idle claude tokens cost expire", + "396a2cc5b442e359": "compact idle minutes prompt cache ttl", + "6d9520a9cbd70c2f": "Minimum context for auto-compact", + "2fe046cc1e0d0d4a": "compact context tokens threshold size", "64f12530d55d2ad1": "fortsetzen laufende aktive unterbrochene arbeit neustart rechner absturz desktop update automatisch", "214a98497c4ed05d": "caffeinate ruhezustand verhindern wach bleiben energie laptop deckel inhibit", "00469926c7027e2d": "ausgewogen leistung akku sparen erweitert git fetch anbieter zustand aktualisieren host energie überwachen inaktiv richtlinie", @@ -11855,6 +11991,7 @@ "901a823214edc8c4": "telemetrie analyse nutzungsdaten tracking rechtliches deaktivieren", "82136480255a5106": "OTel OTLP telemetrie export endpunkte logs traces metriken Grafana", "659d081051faf7ff": "logs traces prozesse ressourcenverlauf fehler spans cpu speicher", + "5eaeacfa9f82051a": "bericht fehler problem t3 team senden feedback agenten tools automatisch wenn ich darum bitte", "f537f91e1ee41d47": "tastenkürzel hotkeys befehle tastenzuweisungen json", "1ba01e7ceed64b95": "fenster aufnahme bildschirmfoto", "279b1cceb779ff38": "App-Text einbeziehen", @@ -12060,6 +12197,8 @@ "v": "v" } ], + "643c4b50feadc874": "Worktree: {path} ({branch})", + "fb7c44da0f0825ea": "Worktree: {path}", "e7f35f60e6229cf5": "Desktop-App", "77be1b7e2a1d3d31": "{count, plural, one {{count} Rechner aktualisieren?} other {{count} Rechner aktualisieren?}}", "e4892b21e88abb60": "{count, plural, one {{count} Anbieter-Update} other {{count} Anbieter-Updates}}", @@ -12123,6 +12262,25 @@ "ffaa75d2db1e7cc1": "Update wurde nicht angewendet", "626bcbe04dc55f93": "T3 Code ist noch auf {current}. Installiere {version} erneut über die Update-Schaltfläche.", "49214c047fbb1606": "Anbieter-Update unterbrochen", + "a135af0f1efda8de": "Cross-project", + "6e9798372b3fb922": "Coordinators put the questions they need you to decide into an Inbox tab beside the chat, instead of numbering them in their messages. Running sessions pick up a change.", + "7a5292a1705defec": "Reset coordinator decisions to default", + "9e3ff0f05f52b724": "Let agents read, message and start threads in other projects of this environment. Running sessions pick up a change.", + "384695cdd7ab6b54": "Reset cross-project threads to default", + "5a6c243a03eeca0c": "Choose a coordinator", + "f527bb5b4ad333da": "Coordinator for \"{title}\"…", + "6beb2db2a7b5edae": "Could not assign the thread", + "4ebb0c90c45690c0": "Could not detach the thread", + "73ac4f532306bea6": [ + "Assign \"", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "\" to a coordinator" + ], + "1871eb35b1ca5d41": "No thread can coordinate this one.", "52adbc863aeb5e59": "Kopieren fehlgeschlagen", "0944728904d886d2": "Sättigung und Helligkeit von {label}", "dded2cb4e4d26338": "Sättigung von {label}", @@ -12324,7 +12482,6 @@ "0bd41ff995d36a66": "Cache-Lesen", "3f0dfe0cb15a3272": "Cache-Schreiben", "1c9d860be42b1c02": "Ausgabe", - "78344b60f407928e": "Sonstiges", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Schnell", "66796576034c18ea": "Ultraschnell", @@ -12340,6 +12497,270 @@ "2cddd6095abc734a": "7 Tage", "53493056306708cf": "30 Tage", "c719359d18d37ad3": "90 Tage", + "a7ad3167ca62e7de": "Talk to your agents by voice with GPT-Live on your Codex ChatGPT login. Turning this off ends a running call.", + "9f0e45a1d67187cd": "Reset voice calls to default", + "da0ae8174ac2fc14": "Queue what you say in a voice call while the agent runs, or steer the current run. Saying otherwise overrides it for one message. A change applies from the next call.", + "fb0a2aa3b08a17c4": "Reset voice call follow-up to default", + "66936cae56d1d749": "Queue", + "89bf6f658c44cb1b": "Steer", + "930a28582d2c103f": "The voice that talks to you in a voice call. A change applies from the next call.", + "591a53f319b0d343": "Reset voice call voice to default", + "0bd950151ddc6407": "Ohne Speichern verlassen? Deine Änderungen an dieser Datei gehen verloren.", + "c0ba3f6756b09f30": "Ungespeicherte Änderungen", + "6914e22d357f0ad6": "Gespeichert und aktiv", + "aff389354a031d6f": "Die Datei auf der Festplatte lässt sich nicht laden. Die letzte funktionierende Version läuft weiter.", + "858effde748ab563": "Gespeichert, läuft aber noch nicht.", + "ddb37138df660942": "Nicht gespeichert. Auf dem Server hat sich nichts geändert.", + "6ef4db489e40e39e": "Speichern fehlgeschlagen", + "c89624a2e9af1793": "{name} ist nicht verbunden", + "b5a352a43adb4c17": "Ihre Workflows erscheinen wieder, sobald sie sich neu verbindet. Wähle eine andere Umgebung, um deren Läufe zu sehen.", + "3dcedb736d20aae5": "Die Workflow-Dateien konnten nicht gelesen werden", + "b09f4df8d76ae8ea": "{file} löschen? Die darin definierten Workflows können dann nicht mehr gestartet werden.", + "b4535f5a03689d27": "{name} ist nicht verbunden. Was du hier schreibst, bleibt erhalten und lässt sich speichern, sobald die Verbindung wieder da ist.", + "b54c78d85fd942ea": "Gelöscht, aber was läuft, ist noch nicht nachgezogen.", + "407c228d7da0b7df": "Nicht gelöscht. Auf dem Server hat sich nichts geändert.", + "1a6aa10f3cc14fff": "Diese Dateien passen nicht zusammen. Was bisher lief, läuft weiter.", + "259312516a1dbe6f": "Dateiname", + "2f48ab2aa0586853": "Definiert keine Workflows", + "ba5adfa37b55b8c5": [ + "Zeile ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Löschen", + "84c900d1ae72adc6": "Speichern", + "5912d817be03247a": "Die Datei wurde auf der Festplatte geändert, während du sie bearbeitet hast. Speichern ersetzt diese Änderung.", + "0b1e6f5608826387": "Datei laden und meine Änderungen verwerfen", + "f47b4c06aeb77c1c": "Workflow-Dateien werden geladen…", + "4353bfd401d58f87": [ + "Jede Datei in", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "definiert Workflows. Änderungen werden ohne Neustart übernommen." + ], + "0c165251a06f10f1": "Neue Datei", + "8e97cf734b4463e7": "Erstellen", + "2ec0d5108fd6cebe": "Noch keine Workflows. Erstelle hier die erste Datei oder bitte einen Agenten, eine in diesem Ordner zu schreiben.", + "5601350626e8cfe9": "Lässt sich nicht laden", + "21d778a1b9a0c234": "Neben der Ausführung geöffnet", + "62dc4d3a19ff7ca0": "Tab schließen", + "1e25265f2758fce3": "Als vollständigen Thread öffnen", + "672a3dae06b39402": "Auf eigener Seite öffnen", + "7755500a4cde5066": "Bereich schließen", + "b8dcbc93a2ca1861": "Diese Ausführung führt es nicht mehr auf.", + "115c69de3202f664": "Öffnen", + "644eafa9048b62df": "{count, plural, =1 {1. Versuch} =2 {2. Versuch} =3 {3. Versuch} other {{count}. Versuch}}", + "e39f89c909df4db0": "Die Ausführung konnte nicht fortgesetzt werden", + "865f034346b82f47": "{title} abbrechen? Die Agenten stoppen und die Ausführung kann nicht fortgesetzt werden.", + "6bc75632fd9c9136": "Die Ausführung konnte nicht abgebrochen werden", + "64e50329dcfdd5b0": "Abgeschlossen", + "350162e7cc1ebea4": "Gestoppt", + "0875cf506f4c6810": "Übersprungen", + "3cc43f1dbf3f8e0c": "Abgebrochen", + "ded70e75de6404ba": "Zurück zur Liste der Ausführungen", + "2f4ed7dbd22be30d": "Ausführung abbrechen", + "614e5ad58a795fb5": "Stoppen", + "04b050b0329f0ac8": "dauerte {duration}", + "aff78e1774818ff4": "bisher {duration}", + "38eddd466439afc9": "Was die Ausführung berührt hat", + "156ec271d49ddd70": "Was passiert ist", + "34f59bbbead0b97f": "{names} und {count} weitere", + "ac1556f6ce89a5ea": "{count} parallel", + "e197c4963bacc746": "{count} laufen", + "f5319ed9e18c0df1": "Fragt dich", + "882a25e9084ae1b2": "Pausiert", + "9a03d8a9afc60387": "Bisherige Schritte", + "2f2ae791afe01674": "wartet auf deine Freigabe", + "24f8060c4ccdf928": "startet", + "30a5be40eb956663": "arbeitet", + "dd7a1e58c2553933": "wacht in {duration} auf", + "95cc952724dd7310": "wacht gleich auf", + "3cc34921c0128593": "läuft", + "e777db2880f53a46": "niemand hat geantwortet", + "dc90739d391a5e67": "Du hast {choice} gesagt", + "389f2563b5b763fd": "Kurze Schritte", + "a41c8d758121ad81": "hat geschlafen", + "9db248b770096984": "hat gewartet", + "c76124517af28686": "läuft seit {duration}", + "89102905bf09b0e8": "Live ansehen", + "bdf338cdff4118f0": "Transkript", + "811e7e992f9ff820": "kann erst weitergehen, wenn ihre Workflow-Version wieder registriert ist", + "4d4cdf035e98dd57": "wartet darauf, dass du sie fortsetzt", + "eb5b21dd224a5941": "versucht es in {duration} von selbst erneut", + "6ab3dfa749fde477": "versucht es gleich von selbst erneut", + "44b6463aa70aa14c": "Grund der Pause", + "cf25e7169ab0eb7a": "Pausiert bei {step}", + "56c48c1f220f2754": "Die Frage konnte nicht beantwortet werden", + "a3c43735e1a81498": "Begründung für {title}", + "bfad234f016cfa3f": "Warum, in einem Satz. Gilt für die Antwort, die du wählst.", + "004c41aff9c97873": "Ausführungen", + "4dc0c244a2419f6c": [ + "Teil von ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "gestartet", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "ihre Version ist nicht mehr registriert", + "f92d9132f7b85d1a": "Schritte werden geladen…", + "6ebc59f64c761a49": "Noch nichts.", + "a759dccd157d7dae": [ + "Du hast", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " gesagt." + ], + "593b425188346781": [ + "Du hast", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " gesagt: ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Ausführung öffnen", + "c8eb9be36d4d51ad": [ + "Thread auf ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Fortsetzen", + "8cebd63fc4c967d5": "Nur der fehlgeschlagene Schritt läuft erneut; zuvor Abgeschlossenes bleibt erhalten.", + "bc1e0a2a0f1e9552": "Braucht dich", + "a812f51e970740f1": [ + "gefragt", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· die Ausführung wartet auf dich" + ], + "02dfe6c63fd0b8a1": "Begründung hinzufügen", + "19abd94828a3bdbc": "Erst den Agenten fragen", + "a18721fa8f328361": "Braucht dich", + "bbf24e7920c1e86b": "Läuft", + "8d6e18d2ad832db6": "Alle", + "f25af5332ffc3734": "Nichts wartet auf dich.", + "c3f0119b8d6231f8": "Es läuft nichts.", + "33028dfc1229eaa6": "Noch keine Ausführungen.", + "5459bf696a187c26": "Workflow-Ausführungen konnten nicht geladen werden", + "d57c35d43b0f163a": "Diesen Lauf gibt es hier nicht", + "b9aae2f7cdb1a379": "Noch keine Workflow-Ausführungen", + "8f15f66e545af7c0": "Welche Ausführungen", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "Alle {count} Workflows", + "46d614fa7b4bf1e5": "Workflow-Ausführungen", + "1c635faa2fb45b8b": "Noch nie gelaufen.", + "156ff7b625287a1e": "Übersprungene ausblenden", + "69b985b97ab45e6b": "{count} übersprungene anzeigen", + "2400254d362de84d": "Workflow-Ausführungen werden geladen…", + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Eine Workflow-Datei hat ein Problem." + }, + " ", + "Die letzte funktionierende Version läuft weiter." + ], + "ed8ce6ebc73dc12d": "Datei öffnen", + "145e1f7503ba3b2c": [ + "Diese Umgebung hat keinen Lauf mit diesem Link.", + " ", + { + "t": "button", + "i": 1, + "c": "Zurück zu den Läufen" + } + ], + "783e616cb0476c17": [ + "Ein Workflow verbindet Agenten, Code, Zeitpläne und Fragen an dich zu einer Ausführung, die Neustarts übersteht. Schreib einen unter", + " ", + { + "t": "button", + "i": 1, + "c": "Definitionen" + }, + ", oder bitte einen Agenten darum.", + " ", + { + "t": "a", + "i": 2, + "c": "Anleitung lesen" + } + ], + "5d8d278ff828102d": "Alle Workflows", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · Transkript", + "c512071143a5ba32": "Diesen Thread gibt es nicht mehr.", + "ed169d23683fb6ac": "Thread wird geladen…", + "290e0ab40b87dc17": "Workflows-Breadcrumb", + "683dd9831e54edc0": "Umgebung", + "34ad53646f06ed80": "Workflows sind aus", + "8f6589c9e0ac5d4e": "Keine Umgebung verbunden", + "744127f8dfad7d22": "Verbinde eine Umgebung, um ihre Workflow-Ausführungen zu sehen.", + "036182ec7e2ee4d4": "Neben der Ausführung", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Definitionen", + "f0a212aadfe1257b": "Editor wird geladen…", + "20f194e003885e95": [ + "Aktiviere sie für diesen Server in den", + " ", + { + "t": "Link", + "i": 1, + "c": "Einstellungen → Labs" + }, + "." + ], "8367779e149f723b": "Anfrage an die primäre Umgebung während {operation} fehlgeschlagen (HTTP {status}).", "c5cd027743a2b5a6": "Ungültiges Kopplungstoken. Prüfe das Token und versuch es erneut.", "0e4b49c8203aae81": "Zeitüberschreitung beim Warten auf eine authentifizierte Sitzung nach dem Bootstrap.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index e5d8d3dc2ed21..abbdbaeb84bf3 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -52,6 +52,27 @@ "eb0f60ef4f92ab7d": "Install {fj} 0.6 or later from {fjUrl} and run {fjLogin}, or install {tea} 0.16 or later from {teaUrl} and run {teaLogin} for each Forgejo or Gitea server.", "d026a85e2e50e675": "Install the GitCafe CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", "22d3c0c48a34b5b3": "Install the TanStack Source CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", + "756c80ad262ef315": "Waiting in the original thread", + "d8df14f9905f38eb": "Sent", + "e7c59185f8ab3987": "Not sent", + "b54ddec9084fa955": "Closed without sending", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Confusing", + "0f53bc8f74dfe56a": "Missing capability", + "055560f307e15e30": "Wrong docs", + "78344b60f407928e": "Other", + "f653846a95cd6e8f": "Kind", + "f41ea186c275b56e": "About", + "2f6e4f7cd364da73": "Expected", + "9d11c93d4035de3e": "Happened", + "c87d0595693704f9": "Did instead", + "d7a4ea6ce5af44e0": "{speaker} · {count} characters", + "f5114fb9c40fd929": "You", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Turn {turn} · {what}", + "dfdaa6255a416140": "Outline of {turns, plural, one {{turns} recent turn} other {{turns} recent turns}}, {textTurns, plural, =0 {no message text} one {message text of the last turn} other {message text of the last {textTurns} turns}}{truncated, select, yes {, shortened to fit} other {}}", + "260c6b45f52d2f27": "Adds the text of your messages and the agent's replies in the last {textTurns, plural, one {turn} other {{textTurns} turns}}.", + "afac52a5cc2dc801": "Could not send your answer. Try again.", "79d776428f4d0650": "The file could not be loaded. Reconnect and try again.", "3ea34cbb1ca5ba9b": "Preview cancelled.", "7c0af279ecb3da3a": "Streaming file previews are unavailable in this runtime.", @@ -118,9 +139,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.", @@ -246,6 +267,8 @@ "fec888c767b662d5": "Tried to check linked issues", "bc31067af9c79d82": "{count, plural, one {Checked linked issues {count} time} other {Checked linked issues {count} times}}", "c712fec8d9dc6dd6": "{count, plural, one {Tried to check linked issues {count} time} other {Tried to check linked issues {count} times}}", + "81c2282590e549f5": "{count, plural, one {Read terminals {count} time} other {Read terminals {count} times}}", + "79cd7c5c29ffa938": "{count, plural, one {Tried to read terminals {count} time} other {Tried to read terminals {count} times}}", "537feee59d775e17": "{count, plural, one {Previewed {count} HTML page} other {Previewed {count} HTML pages}}", "4b45ac8cb8df04a4": "{count, plural, one {Tried to preview {count} HTML page} other {Tried to preview {count} HTML pages}}", "a6f62fca5dd25455": "{count, plural, one {Rendered {count} HTML page} other {Rendered {count} HTML pages}}", @@ -376,6 +399,31 @@ "476ca970255eaea4": "Link this environment to T3 Connect for a public URL.", "6b80f5b38a8f9950": "Only this computer can call this address. Link T3 Connect for a public URL.", "c5a7b1d3891dd0b8": "Works wherever this environment's address is reachable, for example over Tailscale or your own proxy. Link T3 Connect for a public URL.", + "3669395daf36fd33": "No longer registered on this server", + "fe513cf316e796e3": "Runs as part of other workflows", + "ccf00b97925efab3": "Started by hand", + "421e585eb092b07b": "Starts on {triggers}", + "7bd7c58592671384": "Needs you", + "834ca879c14c167b": "Working", + "582d6df7dfab86fb": "Paused", + "ea6583ce92507ee3": "Sleeping", + "7ea8cb8af281ce93": "Waiting", + "1347868f2523140e": "Done", + "57d76c4614054271": "Stopped", + "5c7344bd51d0b966": "Skipped", + "b2074e9bd23049a6": "Cancelled", + "5bb7401807ee2fb5": "Asks: {question} and {more} more", + "9e4286183d5f9e34": "Asks: {question}", + "474c18d001bd6717": "A step failed", + "d3890f4eb1508781": "Running its own steps", + "3e7ced10c9482af0": "{step} is working", + "237e1bcb1cf1bdec": "Sleeping at {step}", + "3f7b17ac5a20c8d2": "Runs {run}", + "0306f5f324b8aaa5": "{count} runs under way", + "e8fd779b84a202a2": "Waiting", + "b6d55657e1a027b8": "Waiting for {step}", + "e942562a42aede34": "Finished", + "26b2b9727fe11289": "Ended early", "1bb995dcec481554": "Approve this device on {host}. It shows code {verificationCode}.", "8696a33219944832": "Could not create the websocket authorization proof.", "5678f133a8631f7d": "Your cloud sign-in changed. Sign in again to authorize the environment.", @@ -637,6 +685,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", @@ -1721,6 +1772,8 @@ "2e995206e087c3fc": "Try replying after the connection or pending input is resolved.", "604ec3067171a0d7": "Conversation", "d6182a057ea12624": "Parent thread", + "f2d8537c33cc55a5": "Step of the workflow run", + "ba8337dca3232880": "Open run", "30fa4a764d11ae42": "Could not download {name}", "4952f87dc98191a7": "The attachment is unavailable.", "2fd6d178493fb407": "Failed to interrupt the current turn.", @@ -1785,6 +1838,8 @@ "181677cda4d3fd0a": "No connected environment can add a project", "3a0bf3d17f31584e": "New thread in {project}", "4b4b64cc95acb8da": "New thread in...", + "2c45783ab9680fdb": "Open Git graph", + "e813386e62652710": "Open agent stage", "3f581e98c86df72a": "New thread without a project", "e510d9a7b684fbfe": "Triage an issue", "cce3d80a2ddf1125": "An agent investigates a T3 Code problem and helps file an issue", @@ -1806,6 +1861,7 @@ "04fd71efaa2c3b92": "Open pull requests", "57e875b79b98ab82": "Open issues", "f1db0a234c777a1d": "Use T3 Code in another app (MCP)", + "6050f22f63e2bcb5": "Open workflows", "a0cc19e60dd99851": "Open usage", "46694969044eee98": "Focus Next Workspace Area", "0a1011328ba42eef": "Focus Previous Workspace Area", @@ -2361,14 +2417,24 @@ "05037ca1666fd421": "Terminal surfaces are only available from a project thread.", "a3aa1e49af278d41": "Files are only available when a project is open.", "87ea6995ea1e7aa4": "Diff is only available for server threads in Git repositories.", + "80f10f5ea1804d8d": "The Git graph needs a Git repository on an up-to-date server.", "4a87cae01ccde544": "This thread's branch has no pull request yet.", "32535dba0b9af642": "This thread has no linked items.", + "d955eee48dece3c0": "Enable the agent stage in Settings > General.", + "d2f2f6d05148f8a3": "Threads a coordinator runs have no thread overview.", + "26c1c05b0d1d98fd": "Turn on coordinator decisions in Settings > General.", + "486d4369c4fbec9e": "Notes are only available from a thread.", + "50b5a57d3bd6f6ef": "Instructions are only available from a thread.", + "007ab76950f73521": "Media is only available from a thread.", "07080dead70f4cc5": "Devices are only available from a thread.", "a4bf49b31758ff7e": "Only available in the desktop app.", "e917841cb66f9af1": "Available when a project is open.", "14c15fad0c2ee0c8": "Available for Git repositories.", "9176276c78f3893f": "No pull request on this branch yet.", "52ce9db6fb62a59f": "No linked items available.", + "96c2ee76dd82d2cc": "Enable it in Settings > General.", + "2199013487151590": "Not for threads a coordinator runs.", + "f7a9300d9f9030d5": "Turn on coordinator decisions in Settings.", "e5d6f41e4fe4efd6": "Available from a thread.", "0ebc2bb883a8e283": "Available after the first message.", "84d0ff8fb9846057": "Unmute tab", @@ -2377,8 +2443,15 @@ "5c78a8ae7b71af1d": "Terminal", "cba3e832ece50257": "Files", "83ac3423d6dfc4a7": "Diff", + "016750bdd5076287": "Git graph", "da16af47eff38ae9": "Pull request", "ad3929f0103925d7": "Linked items", + "70e7b208e032024a": "Stage", + "0caf7e5748f1d17b": "Threads this one started, and which need you.", + "96018894225bd4ff": "Inbox", + "0ed16d7723c04288": "Decisions the coordinator asks you for.", + "aec2b493d2b01445": "Notes", + "9e92f6aa6edae875": "Notes and todos for this thread, its project, or everywhere.", "ac0de2a59d9c8860": "Device", "1354df9fb7278843": "Watch an iOS Simulator or Android Emulator.", "fdcd9643e2e63b15": "Ask a side question while this thread keeps working.", @@ -2497,8 +2570,7 @@ "2d1c111e1b4ae0b0": "Delete thread \"{title}\"?", "c568ab8dad798ec5": "This permanently clears conversation history for this thread.", "0fd1c746a0e38003": "Failed to delete thread", - "0ecde875b0dd2f93": "Filter threads by project: {projects}", - "1ef65b647231ff0b": "Filter threads by project", + "1c8fc3c4a42949ab": "Projects: {projects}", "165511761be2855c": "Search projects", "a46a6467883575a4": "Search projects...", "fdc0e086438a3045": "Project settings for {project}", @@ -2560,10 +2632,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 +2644,7 @@ "a3178769f8308cbc": "Thread failed", "89b5e8f3887812da": "Guest request", "62e626804919b294": "Input needed", + "c6196d99000642b4": "Open thread", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "You:", "a1fbf2422c588292": "Agent:", @@ -2596,8 +2668,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", @@ -2686,8 +2756,6 @@ "78a04e0e625c0990": "Update failed", "c24de5eb69373a55": "This {build} build ignores {track} releases. Review the update track in Settings to finish the switch.", "b02ae45a6109c93b": "Up to date", - "edcda9e8ee4ccad8": "Install update {version} and restart T3 Code?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.", - "02eba0f7cc90f759": "Install update and restart T3 Code?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.", "9ed4d8a1531b9631": "Automatic updates are not available in this build.", "c8c23435e780a60c": "Updates unavailable", "1af5f9767371ffd7": "Check for updates", @@ -3034,8 +3102,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 +3346,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 +3523,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", @@ -3577,6 +3649,13 @@ "c53bc5a4b0314342": "Next media", "2950b1424a3cddf5": "Reconnect to this environment and open the media again.", "ef638bf1479a5461": "The environment returned an invalid media URL.", + "3ccfbf7e86868c35": "Feedback for the T3 team", + "4e0710d19dfc2e7e": "Send this report to the T3 team?", + "87d0ae0723ba75d1": "This is everything that leaves your machine. Nothing is sent unless you press Send.", + "bf19826f81484328": "Include the conversation", + "ddb7e6f8ce99e657": "Only someone who can run agents on this machine can send or decline it.", + "03c1eb603c112f47": "Don't send", + "653405e4ed498d9f": "Send", "262955d6eb632f9b": "Clipboard API is unavailable while copying guest link.", "f1a4f2b04cdbb4ef": "Failed to copy guest link to the clipboard.", "cf3490a604e44d31": "Could not create a guest link.", @@ -3597,7 +3676,6 @@ "abd89e9eefedf11b": "Done", "18d166056c1ab6ff": "Stop sharing", "7a2d510eac9e4587": "Guest link expired", - "653405e4ed498d9f": "Send", "21888e302219891d": "Expanded {title} preview", "419719298a7acaea": "Zoom out", "ed8d5db95359cff4": "Reset zoom", @@ -3693,7 +3771,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 +3782,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 +4059,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", @@ -5455,6 +5530,22 @@ "f0d79aa56f06663f": "This file is too large to show in full. Counts include all changes.", "7fdde2b893ba1b9d": "Removed", "e58ce271d835b447": "Added", + "fb5c7ff5ea76e01a": "Added by esveo's fork. Click to list all of its settings.", + "352fa6aeb5d55665": "Trail the provider icon behind the thread title instead of giving it a line of its own. The line it saves also carried the branch, pull request badge and diff counts.", + "9d44fa03a230e0d8": "Reset two-line thread cards to default", + "7b216eedb1abe696": "Two-line thread cards", + "8d90fcd918e901c8": "Keep each project's threads together in the sidebar, under a header that folds the project away. Ordering stays by recency: the project with the newest thread leads.", + "d5dfd89c9a281386": "Reset project grouping to default", + "aac9f889c7ec7ff5": "Group sidebar threads by project", + "da375a07c5309184": "Show how full the thread's context window is next to the composer controls.", + "33f6b88cba203990": "Reset context window usage to default", + "6496f57baeded3fa": "Context window usage", + "d9c146dc6b95714d": "Show how many minutes are left before the prompt cache expires. Claude only.", + "69609e27c2107da5": "Reset prompt cache timer to default", + "a4917d2b93c478f6": "Prompt cache timer", + "ea8ebcb77e657e9f": "Open the thread details card with workspace and version control in every thread. Off, it stays closed until you open it, and each thread remembers your choice.", + "662288b90e19635f": "Reset thread details to default", + "92729a403d37c575": "Open thread details by default", "07b9970b662ab70d": "Show Mermaid source", "5a422b7be35243f5": "Show rendered diagram", "c0628ad999cbbbf5": "Show markdown source", @@ -5562,6 +5653,7 @@ "723d88a5fa7e2fdd": "No matching files.", "f8d6e9a1a2870a5c": "File explorer", "109edd252917113b": "Resize file explorer", + "7abd6af24fed7b60": "The file does not exist in the workspace or the home folder.", "37cbd2ecc659a007": "File", "b5188f172f59ca79": "This connection cannot read host files.", "c3c5d36466ad2191": "Open file in preview browser", @@ -5601,7 +5693,6 @@ }, ". Check the link's path or locate the file in Files." ], - "b9b6bbd1e1ea189f": "Full file", "d715e9494fdbaaf6": "The font could not be loaded.", "ff17c777a72b4408": "Font previews are limited to 10 MB.", "6bd41ad699e22f10": "The font is unavailable.", @@ -5611,6 +5702,7 @@ "a9abaaa4220eae21": "{error} Save it to open in another app.", "c508c9000d9656f8": "Font preview", "1c416d621d250be8": "The quick brown fox jumps over the lazy dog.", + "d7d08260f16b7828": "The file is still loading. Try again in a moment.", "76ebb03de52c92d6": "The text viewer stopped.", "f48162e8e8c12af7": "Could not load the text viewer. Close the file and try again.", "bc4c5b13d38a5da7": "Preview closed.", @@ -5618,8 +5710,6 @@ "9450d1827ef336a1": "Another copy is in progress.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} line} other {{formatted} lines}}", "13b14784f8707ddd": "0 bytes", - "f6e9581cba3467fa": "Indexing…", - "2d1f293ac12463fc": "Loading the rest of the file…", "b75105bef8f564a4": "Showing the first 1,024 columns. Source and Save retain every column.", "2a6e1b1f209c3888": "This file is empty.", "192fc79eb3b5b2cb": "This diagram contains resource URLs, markup, node metadata, or custom configuration. Show Mermaid source to inspect it safely.", @@ -5806,7 +5896,6 @@ "0061fff77e36bd4f": "Could not reach the server.", "04dfdd46e3dd4a2e": "Something went wrong. Try again.", "084bb2d8127a508d": "Sent", - "e7c59185f8ab3987": "Not sent", "77c01a15bd36d17c": "This link has ended or is not valid", "e0e736810f3cbef2": "Ask the owner for a new link. Each link works in one browser.", "c3c53aa46f7330e5": "This link has ended", @@ -5828,6 +5917,13 @@ "cbb2129c0dd4f40b": "Attached files can total up to 10 MB per message.", "03b9cd79cfe0b435": "This file cannot be attached. Images must be PNG, JPEG, GIF, or WebP.", "8ff29c78798e6ac1": "Could not load this item.", + "535923000a0f3e3b": "Send /compact to a large, idle Claude thread shortly before its 1-hour prompt cache expires, so the next message skips caching the whole conversation again. 5-minute caches are left alone.", + "bd8eb8f5f9843bc6": "Reset idle auto-compact to default", + "1db274eacf03c8de": "Auto-compact idle Claude threads", + "fb6643c75aafd996": "Between {min} and {max}; it has to fall inside the cache's hour.", + "48dee64ca7904281": "Minutes idle before auto-compact", + "8937fe924464eb70": "Smaller threads are cheap to cache again and keep their full history.", + "1981f1e1a753aabc": "Minimum context tokens for auto-compact", "94ab4591ce101233": "The comment could not be posted", "92d0d4eab2596772": "The tracker refused it.", "33591d9596fb7cb7": "Add a comment", @@ -8703,12 +8799,16 @@ "58e0e226493150e7": "Could not load issue trackers", "77cfcbde543df32d": "Toggle {tracker} details", "0083f65885c60156": "Disconnect {tracker}", - "295392927d5c8a84": "Pick one or more {tracker} {scope}s for each project. Their issues list beside the repository's own, and agents file new issues in the first one.", + "ed83b25c71c98a20": "Pick one or more {tracker} {scope}s for each project. Their issues list beside the repository's own, and agents file new issues in the first one unless asked for another.", "19c2d5e81ff8f89a": "{tracker} {scope} for {project}", "68e061510b765772": "Not bound", + "99d51127f573296b": "Another account", + "8ec2c57414669b79": "Connect a second {tracker} workspace or user.", + "99963c0142e17f00": "For the new {tracker} account.", "a2d95d39d3398bda": "Credential rejected", "9eae463720500113": "Stored on the server.", "b6e27ab2537ef874": "Create one", + "6d8e4ebc889bace9": "Add account", "13ef526271b0f5d4": "Clear all conditions", "d1938a629f039515": "Remove condition", "84a605b241ce65b7": "Remove group and its conditions", @@ -8838,6 +8938,12 @@ "d3866ead082d14e5": "Add keybinding", "d4345c90894a3220": "Open keybindings.json", "e56a8d51219efaa0": "No keybindings match your search.", + "90a258fff61fd77e": "Off", + "4060244a7079a0d2": "When I ask", + "e88c9d8769544731": "Automatic", + "f29d1dade4dde8aa": "Agents send no feedback to the T3 team.", + "93c4c53562d30a98": "When you ask, agents show you a short report about T3 Code and send it to the T3 team if you approve.", + "cd9ee803e8727017": "Agents also report T3 Code problems they hit on their own, such as a T3 tool that failed.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Group sidebar threads into project folders. Pinned threads stay on top, and Snoozed and Settled stay below the folders.", "e4e91d155cb6a9b4": "Boring sidebar (group by project)", @@ -8846,11 +8952,16 @@ "9ae293971d93c819": "Share a thread with a guest who watches it live in a browser and sends messages you approve. Sign in to T3 Connect to use guest links.", "0aa5406ac4d7f7c7": "Guest links", "f0e853acd2006d53": "Linked environments", + "ef10c2dff987f3ea": "Run multi-step workflows from files in the workflows folder of this server's T3 home. Open them from the command palette. While off, nothing in that folder runs; runs wait until it is on again.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Show a predicted next message in the empty composer after a Claude or Codex turn. Tab uses it. Each is an extra cached request on your plan. Needs Codex 0.165+. Claude threads update on restart.", "d4b2a2ec812aafb0": "Suggest next prompt", "298c7150a7621c80": "Simlock device hosts", "67937aa49179285e": "On a Mac, clone new worktrees from a checkout cached in the T3 home folder instead of writing every file. Uses Git’s normal checkout when it can’t. Turning it off deletes the cache.", "f9904f78d3003f58": "Fast worktree checkout", + "9c2f647882522302": "The selected machines use different agent feedback modes.", + "31bbf7bf8c0a5279": "Agent feedback", + "d52b3d6bf9f2a013": "Mixed", "ec7623deed751c05": [ "Share a thread with a guest who watches it live in a browser and sends messages you approve. Needs T3 Connect: sign in and link this machine in", " ", @@ -8934,7 +9045,9 @@ "fb71127e5746a6bc": "From Sharing & access there, or t3 pair", "1e3fee7084791773": "Also link {target} back to {source}", "ea34a190b0bd804c": "Agents on {target} can then work on {source} too.", - "ad5ed0ce61b966eb": "Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + "974f8c65e8b5f492": "Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.", + "6cf9e3083b15614f": "{label} did not answer", + "34ccbdf619b83be3": "Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", "81c9796bf61b306a": "Could not forget the link", "130e51beb6cf5aad": "Link an environment", "122c3e355699e69d": "Agents here can then launch, message and wait on threads there. It appears under Authorized clients in that environment's Sharing & access, where it can be revoked.", @@ -9163,7 +9276,6 @@ "0b4779a1825c85bc": "The shared name for this project group in the sidebar and thread lists.", "f68cbda4df83d739": "Reset project name to default", "56e37b85027e8431": "Project icon", - "e88c9d8769544731": "Automatic", "c99736317da5b1fa": "Reset project icon to default", "6afaa3e3739dc570": "Choose a project icon", "51651ce45d481a20": "Choose a project icon file", @@ -10074,7 +10186,6 @@ "53de7aafe0afc10d": "Couldn’t restore theme settings", "006bfa1846fe5dd2": "Days of inactivity before auto-settle", "d9b0fbd680d5f175": "Sidebar", - "d5dfd89c9a281386": "Reset project grouping to default", "cd5452cc9e13c818": "Project grouping", "cfb01b8a2a3361fb": "Reset project order to default", "26abcbe322049a8a": "Reset working section to default", @@ -10139,7 +10250,6 @@ "16bdc70b858c223f": "Reset proactive panels to default", "c5424f09d77138ff": "When to compact an idle Claude thread over 200,000 tokens: after you return, just before its prompt cache expires, or never. Each Claude provider can override this.", "3e99c5c14f4939c8": "Reset compact idle threads to default", - "d52b3d6bf9f2a013": "Mixed", "cd72fe451ba0d6aa": "New projects", "394c3bd0a1782c8e": "Leave empty to use \"~/\" when the Add Project browser opens.", "f9b912a818bd869d": "Reset add project base directory to default", @@ -11041,7 +11151,6 @@ "4a237f41ce592b7f": "Keep this project's worktrees until you delete them manually.", "00b8ffd8ea6e6a93": "Use these rules for this project.", "72c279824d15a999": "Use each machine's worktree cleanup settings.", - "90a258fff61fd77e": "Off", "b5702d0b64866b08": "Custom", "c009c901f3eefe78": "Delete worktrees with deleted threads", "431c7cd6d50102b7": "Remove unused worktrees when active or archived threads are deleted. Worktrees with local changes are kept.", @@ -11398,7 +11507,6 @@ "f2043e87a10cb831": "Edit theme", "595bdeefcdc9bf31": "Export theme file", "b480281b3791b685": "Choose what the thread details card shows. You can also right-click the card.", - "662288b90e19635f": "Reset thread details to default", "871d059d88548434": "Thread details: {enabled} of {total} on", "cec1fbb8b4c9180d": [ { @@ -11737,7 +11845,6 @@ "4c70e3e7b3e6c493": "Secrets", "79b768229c9ef672": "Maintenance", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "About", "af4b7734da1d5ce7": "Voice", "4ec62c39ca3192bf": "Source control & issues", "f2bf529f85e05494": "Sharing & access", @@ -11766,11 +11873,17 @@ "8f5966eebd2b110f": "appearance colors palette custom import", "633ed64e952cca3b": "colors borders interface", "9cf8308531b4ff31": "transparent transparency solid menus dialogs composer", + "d99bfbc557fae743": "Notion", + "89df56091835b3a6": "notion integration secret pages links viewer connect token ntn", + "d699adcc04d4d4ab": "sidebar compact row height branch provider icon diff pull request", + "9b9df5ba41c4a8e2": "Group threads by project", + "0ed2eab2c1953531": "sidebar project folder runs grouping collapse header repository", "d8d6cfd630cff22d": "red green blue orange additions deletions changes counts palette colorblind", "717e49895cfee1c7": "wide full width column layout messages composer monitor", "88365077fd80787b": "customize show hide panel card environment editor scripts branch pull request git changes servers automations lineage usage limits 5 hour weekly quota tokens context window", "d561f74efa5f3920": "reasoning effort thinking bars graph word label level composer", "6113c17109ee0d57": "latex tex katex equations formulas markdown", + "dfe7ead48efc3f5a": "thread details card panel workspace version control closed collapsed hide", "8c8364d44fa28d22": "dev nightly latest channel artwork pill label hide none", "2d90635156dfcb5a": "typography family size system sans", "d32e93777e4819c8": "typography family size composer input", @@ -11792,6 +11905,7 @@ "d443390c4d2dcfd4": "accessibility a11y screen reader nvda jaws voiceover orca narrator window title tab title alt tab taskbar thread status order working approval", "6826fa9579c22035": "beta share guest invite link teammate watch t3 connect tunnel", "f10c06cba0cdf7fe": "beta link another machine vps peer agents work there delegate", + "bc0b409d89ce086e": "beta workflow durable runs automation steps schedule webhook folder", "4a21cf825a2045b0": "beta tab autocomplete predict next message claude codex ghost text", "fea2dc36585c4a20": "Simlock device hosts (alpha)", "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lease gateway", @@ -11833,7 +11947,29 @@ "34d74827c2a8b009": "enter return command ctrl multiline prompt new line composer", "9d1013084c46ecce": "queue steer running turn send default behavior composer", "e5e7f5e1fb1f2e4c": "subagent side chat linked thread click right panel side panel main view command ctrl middle click", + "5c59d7e2673267ea": "composer tokens usage meter percentage compaction", + "e0d6ec10218b714e": "composer claude cache ttl expire minutes warm cold tokens", + "ce0952668aba4140": "Agent stage", + "f637899f994b78c3": "sprites stations subagents thinking editing terminal right panel everything", + "9d9d3374ee961b91": "Easter eggs", + "571180dbfeddbfd5": "surprise fun rocket animation message send hidden", + "0716adb0d55ffa58": "Voice calls", + "027d8f5ea5555973": "voice call phone gpt live feature flag anruf telefon schalter", + "60d509bb55e2967c": "Voice call voice", + "0e5f5c5ebf026abd": "voice call phone gpt live speaker stimme anruf telefon", + "266f1e2b55e419b0": "Voice call follow-up", + "392226d9bed6fe21": "voice call queue steer follow-up warteschlange anruf", "5b8b854de7ee6f4d": "installed cli versions newer available codex claude cursor grok fx kiro opencode", + "1ceaab7d898b689a": "Child threads in the sidebar", + "fa5a42a73d1c1ece": "coordinator subthreads nested group expand sidebar orchestration children", + "6a1072050d1ad19e": "Coordinator decisions", + "474ba8e025886f86": "inbox questions answers decide approve coordinator open items", + "8f5558f063214509": "Cross-project threads", + "b809e3ffa5178b88": "agents coordinator other projects read message start threads repositories", + "44207b47d209f601": "compact context prompt cache idle claude tokens cost expire", + "396a2cc5b442e359": "compact idle minutes prompt cache ttl", + "6d9520a9cbd70c2f": "Minimum context for auto-compact", + "2fe046cc1e0d0d4a": "compact context tokens threshold size", "64f12530d55d2ad1": "resume running active interrupted work restart reboot machine crash desktop update automatically", "214a98497c4ed05d": "caffeinate sleep prevent stay awake power laptop lid inhibit", "00469926c7027e2d": "balanced performance battery saver advanced git fetch provider health refresh host power monitor idle policy", @@ -11863,6 +11999,7 @@ "901a823214edc8c4": "telemetry analytics usage data tracking legal opt out", "82136480255a5106": "OTel OTLP telemetry export endpoints logs traces metrics Grafana", "659d081051faf7ff": "logs traces processes resource history failures spans cpu memory", + "5eaeacfa9f82051a": "report bug problem t3 team send feedback agents tools automatic when i ask", "f537f91e1ee41d47": "keyboard shortcuts hotkeys commands bindings json", "1ba01e7ceed64b95": "window capture screenshot", "279b1cceb779ff38": "Include app text", @@ -12068,6 +12205,8 @@ "v": "v" } ], + "643c4b50feadc874": "Worktree: {path} ({branch})", + "fb7c44da0f0825ea": "Worktree: {path}", "e7f35f60e6229cf5": "Desktop app", "77be1b7e2a1d3d31": "{count, plural, one {Update {count} machine?} other {Update {count} machines?}}", "e4892b21e88abb60": "{count, plural, one {{count} provider update} other {{count} provider updates}}", @@ -12131,6 +12270,25 @@ "ffaa75d2db1e7cc1": "Update did not apply", "626bcbe04dc55f93": "T3 Code is still on {current}. Install {version} again from the update button.", "49214c047fbb1606": "Provider update interrupted", + "a135af0f1efda8de": "Cross-project", + "6e9798372b3fb922": "Coordinators put the questions they need you to decide into an Inbox tab beside the chat, instead of numbering them in their messages. Running sessions pick up a change.", + "7a5292a1705defec": "Reset coordinator decisions to default", + "9e3ff0f05f52b724": "Let agents read, message and start threads in other projects of this environment. Running sessions pick up a change.", + "384695cdd7ab6b54": "Reset cross-project threads to default", + "5a6c243a03eeca0c": "Choose a coordinator", + "f527bb5b4ad333da": "Coordinator for \"{title}\"…", + "6beb2db2a7b5edae": "Could not assign the thread", + "4ebb0c90c45690c0": "Could not detach the thread", + "73ac4f532306bea6": [ + "Assign \"", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "\" to a coordinator" + ], + "1871eb35b1ca5d41": "No thread can coordinate this one.", "52adbc863aeb5e59": "Failed to copy", "0944728904d886d2": "{label} saturation and brightness", "dded2cb4e4d26338": "{label} saturation", @@ -12332,7 +12490,6 @@ "0bd41ff995d36a66": "Cache read", "3f0dfe0cb15a3272": "Cache write", "1c9d860be42b1c02": "Output", - "78344b60f407928e": "Other", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Fast", "66796576034c18ea": "Ultrafast", @@ -12348,6 +12505,270 @@ "2cddd6095abc734a": "7 days", "53493056306708cf": "30 days", "c719359d18d37ad3": "90 days", + "a7ad3167ca62e7de": "Talk to your agents by voice with GPT-Live on your Codex ChatGPT login. Turning this off ends a running call.", + "9f0e45a1d67187cd": "Reset voice calls to default", + "da0ae8174ac2fc14": "Queue what you say in a voice call while the agent runs, or steer the current run. Saying otherwise overrides it for one message. A change applies from the next call.", + "fb0a2aa3b08a17c4": "Reset voice call follow-up to default", + "66936cae56d1d749": "Queue", + "89bf6f658c44cb1b": "Steer", + "930a28582d2c103f": "The voice that talks to you in a voice call. A change applies from the next call.", + "591a53f319b0d343": "Reset voice call voice to default", + "0bd950151ddc6407": "Leave without saving? Your changes to this file are lost.", + "c0ba3f6756b09f30": "Unsaved changes", + "6914e22d357f0ad6": "Saved and running", + "aff389354a031d6f": "The file on disk does not load. The last version that did keeps running.", + "858effde748ab563": "Saved, but it does not run yet.", + "ddb37138df660942": "Not saved. Nothing changed on the server.", + "6ef4db489e40e39e": "Could not save", + "c89624a2e9af1793": "{name} is not connected", + "b5a352a43adb4c17": "Its workflows show again when it reconnects. Pick another environment to see its runs.", + "3dcedb736d20aae5": "Could not read the workflow files", + "b09f4df8d76ae8ea": "Delete {file}? The workflows it defines can no longer be started.", + "b4535f5a03689d27": "{name} is not connected. What you write here stays, and saves once it is back.", + "b54c78d85fd942ea": "Deleted, but what runs has not caught up yet.", + "407c228d7da0b7df": "Not deleted. Nothing changed on the server.", + "1a6aa10f3cc14fff": "These files do not fit together. What ran before keeps running.", + "259312516a1dbe6f": "File name", + "2f48ab2aa0586853": "Defines no workflows", + "ba5adfa37b55b8c5": [ + "Line ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Delete", + "84c900d1ae72adc6": "Save", + "5912d817be03247a": "The file changed on disk while you were editing. Saving replaces that change.", + "0b1e6f5608826387": "Load the file and drop my changes", + "f47b4c06aeb77c1c": "Loading the workflow files…", + "4353bfd401d58f87": [ + "Every file in", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "defines workflows. A change to one is picked up without a restart." + ], + "0c165251a06f10f1": "New file", + "8e97cf734b4463e7": "Create", + "2ec0d5108fd6cebe": "No workflows yet. Make the first file here, or ask an agent to write one in that folder.", + "5601350626e8cfe9": "Does not load", + "21d778a1b9a0c234": "Open beside the run", + "62dc4d3a19ff7ca0": "Close tab", + "1e25265f2758fce3": "Open as a full thread", + "672a3dae06b39402": "Open on its own page", + "7755500a4cde5066": "Close the pane", + "b8dcbc93a2ca1861": "This run no longer lists it.", + "115c69de3202f664": "Open", + "644eafa9048b62df": "{count, plural, =1 {1st try} =2 {2nd try} =3 {3rd try} other {{count}th try}}", + "e39f89c909df4db0": "Could not resume the run", + "865f034346b82f47": "Cancel {title}? Its agents stop and the run cannot be resumed.", + "6bc75632fd9c9136": "Could not cancel the run", + "64e50329dcfdd5b0": "Finished", + "350162e7cc1ebea4": "Stopped", + "0875cf506f4c6810": "Skipped", + "3cc43f1dbf3f8e0c": "Cancelled", + "ded70e75de6404ba": "Back to the list of runs", + "2f4ed7dbd22be30d": "Cancel run", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "took {duration}", + "aff78e1774818ff4": "{duration} so far", + "38eddd466439afc9": "What the run touched", + "156ec271d49ddd70": "What happened", + "34f59bbbead0b97f": "{names} and {count} more", + "ac1556f6ce89a5ea": "{count} in parallel", + "e197c4963bacc746": "{count} running", + "f5319ed9e18c0df1": "Asks you", + "882a25e9084ae1b2": "Paused", + "9a03d8a9afc60387": "Steps so far", + "2f2ae791afe01674": "waits for your approval", + "24f8060c4ccdf928": "starting", + "30a5be40eb956663": "working", + "dd7a1e58c2553933": "wakes in {duration}", + "95cc952724dd7310": "about to wake", + "3cc34921c0128593": "running", + "e777db2880f53a46": "nobody answered", + "dc90739d391a5e67": "You said {choice}", + "389f2563b5b763fd": "Quick steps", + "a41c8d758121ad81": "slept", + "9db248b770096984": "waited", + "c76124517af28686": "running for {duration}", + "89102905bf09b0e8": "Watch live", + "bdf338cdff4118f0": "Transcript", + "811e7e992f9ff820": "cannot go on until its workflow version is registered again", + "4d4cdf035e98dd57": "waits for you to resume it", + "eb5b21dd224a5941": "tries again by itself in {duration}", + "6ab3dfa749fde477": "about to try again by itself", + "44b6463aa70aa14c": "Why it paused", + "cf25e7169ab0eb7a": "Paused at {step}", + "56c48c1f220f2754": "Could not answer the question", + "a3c43735e1a81498": "Reason for {title}", + "bfad234f016cfa3f": "Why, in a sentence. It goes with whichever answer you pick.", + "004c41aff9c97873": "Runs", + "4dc0c244a2419f6c": [ + "Part of ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "started", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "its version is no longer registered", + "f92d9132f7b85d1a": "Loading steps…", + "6ebc59f64c761a49": "Nothing yet.", + "a759dccd157d7dae": [ + "You said", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "You said", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Open run", + "c8eb9be36d4d51ad": [ + "Thread on ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Resume", + "8cebd63fc4c967d5": "Only the failed step runs again; what finished before it is kept.", + "bc1e0a2a0f1e9552": "Needs you", + "a812f51e970740f1": [ + "asked", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· the run waits for you" + ], + "02dfe6c63fd0b8a1": "Add a reason", + "19abd94828a3bdbc": "Ask the agent first", + "a18721fa8f328361": "Needs you", + "bbf24e7920c1e86b": "Running", + "8d6e18d2ad832db6": "All", + "f25af5332ffc3734": "Nothing waits on you.", + "c3f0119b8d6231f8": "Nothing is running.", + "33028dfc1229eaa6": "No runs yet.", + "5459bf696a187c26": "Could not load workflow runs", + "d57c35d43b0f163a": "This run is not here", + "b9aae2f7cdb1a379": "No workflow runs yet", + "8f15f66e545af7c0": "Which runs", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "All {count} workflows", + "46d614fa7b4bf1e5": "Workflow runs", + "1c635faa2fb45b8b": "Has not run yet.", + "156ff7b625287a1e": "Hide skipped", + "69b985b97ab45e6b": "Show {count} skipped", + "2400254d362de84d": "Loading workflow runs…", + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "A workflow file has a problem." + }, + " ", + "The last version that did keeps running." + ], + "ed8ce6ebc73dc12d": "Open the file", + "145e1f7503ba3b2c": [ + "This environment has no run with that link.", + " ", + { + "t": "button", + "i": 1, + "c": "Back to the runs" + } + ], + "783e616cb0476c17": [ + "A workflow ties agents, code, schedules and questions to you into one run that survives restarts. Write one under", + " ", + { + "t": "button", + "i": 1, + "c": "Definitions" + }, + ", or ask an agent to.", + " ", + { + "t": "a", + "i": 2, + "c": "Read the guide" + } + ], + "5d8d278ff828102d": "All workflows", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · transcript", + "c512071143a5ba32": "This thread is no longer there.", + "ed169d23683fb6ac": "Loading the thread…", + "290e0ab40b87dc17": "Workflows breadcrumb", + "683dd9831e54edc0": "Environment", + "34ad53646f06ed80": "Workflows are off", + "8f6589c9e0ac5d4e": "No environment connected", + "744127f8dfad7d22": "Connect an environment to see its workflow runs.", + "036182ec7e2ee4d4": "Beside the run", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Definitions", + "f0a212aadfe1257b": "Loading the editor…", + "20f194e003885e95": [ + "Turn them on for this server in", + " ", + { + "t": "Link", + "i": 1, + "c": "Settings → Labs" + }, + "." + ], "8367779e149f723b": "Primary environment request failed during {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Invalid pairing token. Check the token and try again.", "0e4b49c8203aae81": "Timed out waiting for authenticated session after bootstrap.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 4a2868a7e97dc..c9761aacc1b3b 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -52,6 +52,27 @@ "eb0f60ef4f92ab7d": "Instala {fj} 0.6 o posterior desde {fjUrl} y ejecuta {fjLogin}, o instala {tea} 0.16 o posterior desde {teaUrl} y ejecuta {teaLogin} para cada servidor de Forgejo o Gitea.", "d026a85e2e50e675": "Instala la CLI de GitCafe con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", "22d3c0c48a34b5b3": "Instala la CLI de TanStack Source con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", + "756c80ad262ef315": "En espera en el hilo original", + "d8df14f9905f38eb": "Enviado", + "e7c59185f8ab3987": "No enviado", + "b54ddec9084fa955": "Cerrado sin enviar", + "fbaa7ab5da716e50": "Error", + "01bac997ea55272e": "Confuso", + "0f53bc8f74dfe56a": "Función ausente", + "055560f307e15e30": "Documentación incorrecta", + "78344b60f407928e": "Otros", + "f653846a95cd6e8f": "Tipo", + "f41ea186c275b56e": "Acerca de", + "2f6e4f7cd364da73": "Resultado esperado", + "9d11c93d4035de3e": "Lo que ocurrió", + "c87d0595693704f9": "Alternativa utilizada", + "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "f5114fb9c40fd929": "Tú", + "cd03eb1b84271c02": "Agente", + "bfe1a60f3f9c60fb": "Turno {turn} · {what}", + "dfdaa6255a416140": "Resumen de {turns, plural, one {{turns} turno reciente} other {{turns} turnos recientes}}, {textTurns, plural, =0 {sin texto de mensajes} one {con el texto de los mensajes del último turno} other {con el texto de los mensajes de los últimos {textTurns} turnos}}{truncated, select, yes {, acortado para ajustarse} other {}}", + "260c6b45f52d2f27": "Añade el texto de tus mensajes y de las respuestas del agente en {textTurns, plural, one {el último turno} other {los últimos {textTurns} turnos}}.", + "afac52a5cc2dc801": "No se pudo enviar tu respuesta. Inténtalo de nuevo.", "79d776428f4d0650": "No se pudo cargar el archivo. Vuelve a conectarte e inténtalo de nuevo.", "3ea34cbb1ca5ba9b": "Vista previa cancelada.", "7c0af279ecb3da3a": "Las vistas previas de archivos en streaming no están disponibles en este entorno de ejecución.", @@ -118,9 +139,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.", @@ -246,6 +267,8 @@ "fec888c767b662d5": "Intentó comprobar las issues vinculadas", "bc31067af9c79d82": "{count, plural, one {Comprobó las issues vinculadas {count} vez} other {Comprobó las issues vinculadas {count} veces}}", "c712fec8d9dc6dd6": "{count, plural, one {Intentó comprobar las issues vinculadas {count} vez} other {Intentó comprobar las issues vinculadas {count} veces}}", + "81c2282590e549f5": "{count, plural, one {Read terminals {count} time} other {Read terminals {count} times}}", + "79cd7c5c29ffa938": "{count, plural, one {Tried to read terminals {count} time} other {Tried to read terminals {count} times}}", "537feee59d775e17": "{count, plural, one {Previsualizó {count} página HTML} other {Previsualizó {count} páginas HTML}}", "4b45ac8cb8df04a4": "{count, plural, one {Intentó previsualizar {count} página HTML} other {Intentó previsualizar {count} páginas HTML}}", "a6f62fca5dd25455": "{count, plural, one {Renderizó {count} página HTML} other {Renderizó {count} páginas HTML}}", @@ -376,6 +399,31 @@ "476ca970255eaea4": "Vincula este entorno a T3 Connect para tener una URL pública.", "6b80f5b38a8f9950": "Solo este equipo puede llamar a esta dirección. Vincula T3 Connect para tener una URL pública.", "c5a7b1d3891dd0b8": "Funciona donde se pueda acceder a la dirección de este entorno, por ejemplo a través de Tailscale o de tu propio proxy. Vincula T3 Connect para tener una URL pública.", + "3669395daf36fd33": "Ya no está registrado en este servidor", + "fe513cf316e796e3": "Se ejecuta como parte de otros flujos de trabajo", + "ccf00b97925efab3": "Se inicia a mano", + "421e585eb092b07b": "Se inicia con {triggers}", + "7bd7c58592671384": "Te necesitan", + "834ca879c14c167b": "Trabajando", + "582d6df7dfab86fb": "En pausa", + "ea6583ce92507ee3": "Durmiendo", + "7ea8cb8af281ce93": "Esperando", + "1347868f2523140e": "Terminada", + "57d76c4614054271": "Detenida", + "5c7344bd51d0b966": "Omitida", + "b2074e9bd23049a6": "Cancelada", + "5bb7401807ee2fb5": "Pregunta: {question} y {more} más", + "9e4286183d5f9e34": "Pregunta: {question}", + "474c18d001bd6717": "Falló un paso", + "d3890f4eb1508781": "Ejecuta sus propios pasos", + "3e7ced10c9482af0": "{step} está trabajando", + "237e1bcb1cf1bdec": "Durmiendo en {step}", + "3f7b17ac5a20c8d2": "Ejecuta {run}", + "0306f5f324b8aaa5": "{count} ejecuciones en curso", + "e8fd779b84a202a2": "Esperando", + "b6d55657e1a027b8": "Esperando a {step}", + "e942562a42aede34": "Finalizada", + "26b2b9727fe11289": "Terminó antes de tiempo", "1bb995dcec481554": "Aprueba este dispositivo en {host}. Muestra el código {verificationCode}.", "8696a33219944832": "No se pudo crear la prueba de autorización del websocket.", "5678f133a8631f7d": "Tu inicio de sesión en la nube cambió. Vuelve a iniciar sesión para autorizar el entorno.", @@ -637,6 +685,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", @@ -1721,6 +1772,8 @@ "2e995206e087c3fc": "Prueba a responder cuando se resuelva la conexión o la entrada pendiente.", "604ec3067171a0d7": "Conversación", "d6182a057ea12624": "Hilo principal", + "f2d8537c33cc55a5": "Paso de la ejecución del flujo de trabajo", + "ba8337dca3232880": "Abrir ejecución", "30fa4a764d11ae42": "No se pudo descargar {name}", "4952f87dc98191a7": "El adjunto no está disponible.", "2fd6d178493fb407": "No se pudo interrumpir el turno actual.", @@ -1785,6 +1838,8 @@ "181677cda4d3fd0a": "Ningún entorno conectado puede añadir un proyecto", "3a0bf3d17f31584e": "Nuevo hilo en {project}", "4b4b64cc95acb8da": "Nuevo hilo en...", + "2c45783ab9680fdb": "Open Git graph", + "e813386e62652710": "Open agent stage", "3f581e98c86df72a": "Nuevo hilo sin proyecto", "e510d9a7b684fbfe": "Analizar un problema", "cce3d80a2ddf1125": "Un agente investiga un problema de T3 Code y te ayuda a abrir una issue", @@ -1806,6 +1861,7 @@ "04fd71efaa2c3b92": "Abrir pull requests", "57e875b79b98ab82": "Abrir issues", "f1db0a234c777a1d": "Usar T3 Code en otra app (MCP)", + "6050f22f63e2bcb5": "Abrir flujos de trabajo", "a0cc19e60dd99851": "Abrir uso", "46694969044eee98": "Enfocar la siguiente área de trabajo", "0a1011328ba42eef": "Enfocar el área de trabajo anterior", @@ -2361,14 +2417,24 @@ "05037ca1666fd421": "Las terminales solo están disponibles desde un hilo de proyecto.", "a3aa1e49af278d41": "Los archivos solo están disponibles cuando hay un proyecto abierto.", "87ea6995ea1e7aa4": "El diff solo está disponible para hilos del servidor en repositorios Git.", + "80f10f5ea1804d8d": "The Git graph needs a Git repository on an up-to-date server.", "4a87cae01ccde544": "La rama de este hilo aún no tiene ninguna pull request.", "32535dba0b9af642": "Este hilo no tiene elementos vinculados.", + "d955eee48dece3c0": "Enable the agent stage in Settings > General.", + "d2f2f6d05148f8a3": "Threads a coordinator runs have no thread overview.", + "26c1c05b0d1d98fd": "Turn on coordinator decisions in Settings > General.", + "486d4369c4fbec9e": "Notes are only available from a thread.", + "50b5a57d3bd6f6ef": "Instructions are only available from a thread.", + "007ab76950f73521": "Media is only available from a thread.", "07080dead70f4cc5": "Los dispositivos solo están disponibles desde un hilo.", "a4bf49b31758ff7e": "Solo disponible en la app de escritorio.", "e917841cb66f9af1": "Disponible cuando hay un proyecto abierto.", "14c15fad0c2ee0c8": "Disponible para repositorios Git.", "9176276c78f3893f": "Aún no hay ninguna pull request en esta rama.", "52ce9db6fb62a59f": "No hay elementos vinculados disponibles.", + "96c2ee76dd82d2cc": "Enable it in Settings > General.", + "2199013487151590": "Not for threads a coordinator runs.", + "f7a9300d9f9030d5": "Turn on coordinator decisions in Settings.", "e5d6f41e4fe4efd6": "Disponible desde un hilo.", "0ebc2bb883a8e283": "Disponible después del primer mensaje.", "84d0ff8fb9846057": "Activar sonido de la pestaña", @@ -2377,8 +2443,15 @@ "5c78a8ae7b71af1d": "Terminal", "cba3e832ece50257": "Archivos", "83ac3423d6dfc4a7": "Diff", + "016750bdd5076287": "Git graph", "da16af47eff38ae9": "Pull request", "ad3929f0103925d7": "Elementos vinculados", + "70e7b208e032024a": "Stage", + "0caf7e5748f1d17b": "Threads this one started, and which need you.", + "96018894225bd4ff": "Inbox", + "0ed16d7723c04288": "Decisions the coordinator asks you for.", + "aec2b493d2b01445": "Notes", + "9e92f6aa6edae875": "Notes and todos for this thread, its project, or everywhere.", "ac0de2a59d9c8860": "Dispositivo", "1354df9fb7278843": "Mira un simulador de iOS o un emulador de Android.", "fdcd9643e2e63b15": "Haz una pregunta aparte mientras este hilo sigue trabajando.", @@ -2497,8 +2570,7 @@ "2d1c111e1b4ae0b0": "¿Eliminar el hilo \"{title}\"?", "c568ab8dad798ec5": "Esto borra de forma permanente el historial de conversación de este hilo.", "0fd1c746a0e38003": "No se pudo eliminar el hilo", - "0ecde875b0dd2f93": "Filtrar hilos por proyecto: {projects}", - "1ef65b647231ff0b": "Filtrar hilos por proyecto", + "1c8fc3c4a42949ab": "Proyectos: {projects}", "165511761be2855c": "Buscar proyectos", "a46a6467883575a4": "Buscar proyectos...", "fdc0e086438a3045": "Ajustes del proyecto {project}", @@ -2560,10 +2632,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 +2644,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 +2668,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", @@ -2686,8 +2756,6 @@ "78a04e0e625c0990": "Falló la actualización", "c24de5eb69373a55": "Esta compilación {build} ignora las versiones {track}. Revisa el canal de actualizaciones en Ajustes para terminar el cambio.", "b02ae45a6109c93b": "Actualizado", - "edcda9e8ee4ccad8": "¿Instalar la actualización {version} y reiniciar T3 Code?\n\nSe interrumpirán las tareas en curso. Asegúrate de estar listo antes de continuar.", - "02eba0f7cc90f759": "¿Instalar la actualización y reiniciar T3 Code?\n\nSe interrumpirán las tareas en curso. Asegúrate de estar listo antes de continuar.", "9ed4d8a1531b9631": "Las actualizaciones automáticas no están disponibles en esta compilación.", "c8c23435e780a60c": "Actualizaciones no disponibles", "1af5f9767371ffd7": "Buscar actualizaciones", @@ -3034,8 +3102,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 +3346,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 +3523,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", @@ -3577,6 +3649,13 @@ "c53bc5a4b0314342": "Elemento siguiente", "2950b1424a3cddf5": "Vuelve a conectarte a este entorno y abre de nuevo el contenido.", "ef638bf1479a5461": "El entorno devolvió una URL de contenido no válida.", + "3ccfbf7e86868c35": "Comentarios para el equipo de T3", + "4e0710d19dfc2e7e": "¿Enviar este informe al equipo de T3?", + "87d0ae0723ba75d1": "Esto es todo lo que sale de tu máquina. No se envía nada hasta que pulses Enviar.", + "bf19826f81484328": "Incluir la conversación", + "ddb7e6f8ce99e657": "Solo quien pueda ejecutar agentes en esta máquina puede enviarlo o rechazarlo.", + "03c1eb603c112f47": "No enviar", + "653405e4ed498d9f": "Enviar", "262955d6eb632f9b": "La API del portapapeles no está disponible al copiar el enlace de invitado.", "f1a4f2b04cdbb4ef": "No se pudo copiar el enlace de invitado al portapapeles.", "cf3490a604e44d31": "No se pudo crear un enlace de invitado.", @@ -3597,7 +3676,6 @@ "abd89e9eefedf11b": "Listo", "18d166056c1ab6ff": "Dejar de compartir", "7a2d510eac9e4587": "El enlace de invitado caducó", - "653405e4ed498d9f": "Enviar", "21888e302219891d": "Vista previa ampliada de {title}", "419719298a7acaea": "Alejar", "ed8d5db95359cff4": "Restablecer zoom", @@ -3693,7 +3771,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 +3782,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 +4057,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", @@ -5453,6 +5528,22 @@ "f0d79aa56f06663f": "Este archivo es demasiado grande para mostrarlo completo. Los recuentos incluyen todos los cambios.", "7fdde2b893ba1b9d": "Eliminado", "e58ce271d835b447": "Añadido", + "fb5c7ff5ea76e01a": "Added by esveo's fork. Click to list all of its settings.", + "352fa6aeb5d55665": "Trail the provider icon behind the thread title instead of giving it a line of its own. The line it saves also carried the branch, pull request badge and diff counts.", + "9d44fa03a230e0d8": "Reset two-line thread cards to default", + "7b216eedb1abe696": "Two-line thread cards", + "8d90fcd918e901c8": "Keep each project's threads together in the sidebar, under a header that folds the project away. Ordering stays by recency: the project with the newest thread leads.", + "d5dfd89c9a281386": "Restablecer la agrupación de proyectos al valor predeterminado", + "aac9f889c7ec7ff5": "Group sidebar threads by project", + "da375a07c5309184": "Show how full the thread's context window is next to the composer controls.", + "33f6b88cba203990": "Reset context window usage to default", + "6496f57baeded3fa": "Context window usage", + "d9c146dc6b95714d": "Show how many minutes are left before the prompt cache expires. Claude only.", + "69609e27c2107da5": "Reset prompt cache timer to default", + "a4917d2b93c478f6": "Prompt cache timer", + "ea8ebcb77e657e9f": "Open the thread details card with workspace and version control in every thread. Off, it stays closed until you open it, and each thread remembers your choice.", + "662288b90e19635f": "Restablecer los detalles del hilo al valor predeterminado", + "92729a403d37c575": "Open thread details by default", "07b9970b662ab70d": "Mostrar el código fuente de Mermaid", "5a422b7be35243f5": "Mostrar el diagrama renderizado", "c0628ad999cbbbf5": "Mostrar el código fuente markdown", @@ -5560,6 +5651,7 @@ "723d88a5fa7e2fdd": "No hay archivos que coincidan.", "f8d6e9a1a2870a5c": "Explorador de archivos", "109edd252917113b": "Cambiar el tamaño del explorador de archivos", + "7abd6af24fed7b60": "The file does not exist in the workspace or the home folder.", "37cbd2ecc659a007": "Archivo", "b5188f172f59ca79": "Esta conexión no puede leer archivos del host.", "c3c5d36466ad2191": "Abrir el archivo en el navegador de vista previa", @@ -5599,7 +5691,6 @@ }, ". Revisa la ruta del enlace o busca el archivo en Archivos." ], - "b9b6bbd1e1ea189f": "Archivo completo", "d715e9494fdbaaf6": "No se pudo cargar la fuente.", "ff17c777a72b4408": "Las vistas previas de fuentes están limitadas a 10 MB.", "6bd41ad699e22f10": "La fuente no está disponible.", @@ -5609,6 +5700,7 @@ "a9abaaa4220eae21": "{error} Guárdala para abrirla en otra app.", "c508c9000d9656f8": "Vista previa de la fuente", "1c416d621d250be8": "El veloz murciélago hindú comía feliz cardillo y kiwi.", + "d7d08260f16b7828": "El archivo aún se está cargando. Inténtalo de nuevo en un momento.", "76ebb03de52c92d6": "El visor de texto se detuvo.", "f48162e8e8c12af7": "No se pudo cargar el visor de texto. Cierra el archivo y vuelve a intentarlo.", "bc4c5b13d38a5da7": "Vista previa cerrada.", @@ -5616,8 +5708,6 @@ "9450d1827ef336a1": "Ya hay otra copia en curso.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} línea} other {{formatted} líneas}}", "13b14784f8707ddd": "0 bytes", - "f6e9581cba3467fa": "Indexando…", - "2d1f293ac12463fc": "Cargando el resto del archivo…", "b75105bef8f564a4": "Se muestran las primeras 1024 columnas. El código fuente y Guardar conservan todas las columnas.", "2a6e1b1f209c3888": "Este archivo está vacío.", "192fc79eb3b5b2cb": "Este diagrama contiene URL de recursos, marcado, metadatos de nodos o configuración personalizada. Muestra el código fuente de Mermaid para inspeccionarlo de forma segura.", @@ -5804,7 +5894,6 @@ "0061fff77e36bd4f": "No se pudo acceder al servidor.", "04dfdd46e3dd4a2e": "Algo salió mal. Vuelve a intentarlo.", "084bb2d8127a508d": "Enviado", - "e7c59185f8ab3987": "No enviado", "77c01a15bd36d17c": "Este enlace terminó o no es válido", "e0e736810f3cbef2": "Pide un enlace nuevo al propietario. Cada enlace funciona en un navegador.", "c3c53aa46f7330e5": "Este enlace terminó", @@ -5826,6 +5915,13 @@ "cbb2129c0dd4f40b": "Los archivos adjuntos pueden sumar hasta 10 MB por mensaje.", "03b9cd79cfe0b435": "Este archivo no se puede adjuntar. Las imágenes deben ser PNG, JPEG, GIF o WebP.", "8ff29c78798e6ac1": "No se pudo cargar este elemento.", + "535923000a0f3e3b": "Send /compact to a large, idle Claude thread shortly before its 1-hour prompt cache expires, so the next message skips caching the whole conversation again. 5-minute caches are left alone.", + "bd8eb8f5f9843bc6": "Reset idle auto-compact to default", + "1db274eacf03c8de": "Auto-compact idle Claude threads", + "fb6643c75aafd996": "Between {min} and {max}; it has to fall inside the cache's hour.", + "48dee64ca7904281": "Minutes idle before auto-compact", + "8937fe924464eb70": "Smaller threads are cheap to cache again and keep their full history.", + "1981f1e1a753aabc": "Minimum context tokens for auto-compact", "94ab4591ce101233": "No se pudo publicar el comentario", "92d0d4eab2596772": "El gestor de issues lo rechazó.", "33591d9596fb7cb7": "Añadir un comentario", @@ -8693,12 +8789,16 @@ "58e0e226493150e7": "No se pudieron cargar los gestores de issues", "77cfcbde543df32d": "Mostrar u ocultar detalles de {tracker}", "0083f65885c60156": "Desconectar {tracker}", - "295392927d5c8a84": "Elige uno o más {scope}s de {tracker} para cada proyecto. Sus issues aparecen junto a las del repositorio, y los agentes crean issues nuevas en el primero.", + "ed83b25c71c98a20": "Elige uno o más {scope}s de {tracker} para cada proyecto. Sus issues aparecen junto a las del repositorio, y los agentes crean issues nuevas en el primero, salvo que se les pida otro.", "19c2d5e81ff8f89a": "{scope} de {tracker} para {project}", "68e061510b765772": "Sin vincular", + "99d51127f573296b": "Otra cuenta", + "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}.", + "99963c0142e17f00": "Para la nueva cuenta de {tracker}.", "a2d95d39d3398bda": "Credencial rechazada", "9eae463720500113": "Guardado en el servidor.", "b6e27ab2537ef874": "Crear uno", + "6d8e4ebc889bace9": "Añadir cuenta", "13ef526271b0f5d4": "Borrar todas las condiciones", "d1938a629f039515": "Quitar condición", "84a605b241ce65b7": "Quitar grupo y sus condiciones", @@ -8828,6 +8928,12 @@ "d3866ead082d14e5": "Añadir atajo de teclado", "d4345c90894a3220": "Abrir keybindings.json", "e56a8d51219efaa0": "Ningún atajo de teclado coincide con tu búsqueda.", + "90a258fff61fd77e": "Desactivado", + "4060244a7079a0d2": "Cuando lo pida", + "e88c9d8769544731": "Automático", + "f29d1dade4dde8aa": "Los agentes no envían comentarios al equipo de T3.", + "93c4c53562d30a98": "Cuando lo pides, los agentes te muestran un breve informe sobre T3 Code y lo envían al equipo de T3 si lo apruebas.", + "cd9ee803e8727017": "Los agentes también informan por su cuenta de los problemas que encuentran en T3 Code, como una herramienta de T3 que falla.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Agrupa los hilos de la barra lateral en carpetas de proyecto. Los hilos fijados quedan arriba, y Pospuestos y Resueltos quedan debajo de las carpetas.", "e4e91d155cb6a9b4": "Barra lateral simple (agrupar por proyecto)", @@ -8836,11 +8942,16 @@ "9ae293971d93c819": "Comparte un hilo con un invitado que lo ve en directo en un navegador y envía mensajes que tú apruebas. Inicia sesión en T3 Connect para usar enlaces de invitado.", "0aa5406ac4d7f7c7": "Enlaces de invitado", "f0e853acd2006d53": "Entornos vinculados", + "ef10c2dff987f3ea": "Ejecuta flujos de trabajo de varios pasos a partir de archivos en la carpeta workflows del directorio T3 de este servidor. Ábrelos desde la paleta de comandos. Mientras está desactivado, no se ejecuta nada de esa carpeta; las ejecuciones esperan hasta que se vuelva a activar.", + "2dadb2359422121c": "Flujos de trabajo", "13e86eb5d8287a71": "Muestra un mensaje siguiente previsto en el cuadro de mensaje vacío tras un turno de Claude o Codex. Tab lo usa. Cada uno es una solicitud extra en caché de tu plan. Requiere Codex 0.165+. Los hilos de Claude se actualizan al reiniciar.", "d4b2a2ec812aafb0": "Sugerir el siguiente prompt", "298c7150a7621c80": "Hosts de dispositivos Simlock", "67937aa49179285e": "En un Mac, clona los nuevos worktrees desde un checkout en caché en la carpeta de inicio de T3 en lugar de escribir cada archivo. Usa el checkout normal de Git cuando no puede. Al desactivarlo se elimina la caché.", "f9904f78d3003f58": "Checkout rápido de worktrees", + "9c2f647882522302": "Las máquinas seleccionadas usan distintos modos de comentarios de agentes.", + "31bbf7bf8c0a5279": "Comentarios de agentes", + "d52b3d6bf9f2a013": "Mixto", "ec7623deed751c05": [ "Comparte un hilo con un invitado que lo ve en directo en un navegador y envía mensajes que tú apruebas. Requiere T3 Connect: inicia sesión y vincula esta máquina en", " ", @@ -8924,7 +9035,9 @@ "fb71127e5746a6bc": "Desde Compartir y acceso allí, o t3 pair", "1e3fee7084791773": "Vincular también {target} de vuelta a {source}", "ea34a190b0bd804c": "Los agentes de {target} podrán trabajar también en {source}.", - "ad5ed0ce61b966eb": "¿Olvidar {label}? Los agentes de aquí dejarán de trabajar allí. Revoca \"T3 Code · …\" en Compartir y acceso de {label} para cerrar también la sesión allí.", + "974f8c65e8b5f492": "¿Olvidar {label}? Los agentes de aquí dejan de trabajar allí, y su sesión en {label} también termina si responde.", + "6cf9e3083b15614f": "{label} no respondió", + "34ccbdf619b83be3": "Revoca \"T3 Code · …\" en Compartir y acceso de {label} para cerrar también la sesión allí.", "81c9796bf61b306a": "No se pudo olvidar el vínculo", "130e51beb6cf5aad": "Vincular un entorno", "122c3e355699e69d": "Así los agentes de aquí podrán iniciar hilos allí, enviarles mensajes y esperarlos. Aparece en Clientes autorizados, en Compartir y acceso de ese entorno, donde se puede revocar.", @@ -9153,7 +9266,6 @@ "0b4779a1825c85bc": "El nombre compartido de este grupo de proyectos en la barra lateral y en las listas de hilos.", "f68cbda4df83d739": "Restablecer el nombre del proyecto al valor predeterminado", "56e37b85027e8431": "Icono del proyecto", - "e88c9d8769544731": "Automático", "c99736317da5b1fa": "Restablecer el icono del proyecto al valor predeterminado", "6afaa3e3739dc570": "Elige un icono para el proyecto", "51651ce45d481a20": "Elige un archivo de icono para el proyecto", @@ -10062,7 +10174,6 @@ "53de7aafe0afc10d": "No se pudieron restaurar los ajustes del tema", "006bfa1846fe5dd2": "Días de inactividad antes de resolver automáticamente", "d9b0fbd680d5f175": "Barra lateral", - "d5dfd89c9a281386": "Restablecer la agrupación de proyectos al valor predeterminado", "cd5452cc9e13c818": "Agrupación de proyectos", "cfb01b8a2a3361fb": "Restablecer el orden de proyectos al valor predeterminado", "26abcbe322049a8a": "Restablecer la sección En curso al valor predeterminado", @@ -10127,7 +10238,6 @@ "16bdc70b858c223f": "Restablecer los paneles proactivos al valor predeterminado", "c5424f09d77138ff": "Cuándo compactar un hilo inactivo de Claude con más de 200 000 tokens: al volver, justo antes de que caduque su caché de prompts o nunca. Cada proveedor de Claude puede anularlo.", "3e99c5c14f4939c8": "Restablecer la compactación de hilos inactivos al valor predeterminado", - "d52b3d6bf9f2a013": "Mixto", "cd72fe451ba0d6aa": "Proyectos nuevos", "394c3bd0a1782c8e": "Déjalo vacío para usar \"~/\" cuando se abra el explorador de Añadir proyecto.", "f9b912a818bd869d": "Restablecer el directorio base para añadir proyectos al valor predeterminado", @@ -11026,7 +11136,6 @@ "4a237f41ce592b7f": "Conserva los worktrees de este proyecto hasta que los elimines manualmente.", "00b8ffd8ea6e6a93": "Usa estas reglas para este proyecto.", "72c279824d15a999": "Usa los ajustes de limpieza de worktrees de cada máquina.", - "90a258fff61fd77e": "Desactivado", "b5702d0b64866b08": "Personalizado", "c009c901f3eefe78": "Eliminar los worktrees de hilos eliminados", "431c7cd6d50102b7": "Quita los worktrees sin uso cuando se eliminan hilos activos o archivados. Se conservan los worktrees con cambios locales.", @@ -11383,7 +11492,6 @@ "f2043e87a10cb831": "Editar tema", "595bdeefcdc9bf31": "Exportar archivo de tema", "b480281b3791b685": "Elige qué muestra la tarjeta de detalles del hilo. También puedes hacer clic derecho en la tarjeta.", - "662288b90e19635f": "Restablecer los detalles del hilo al valor predeterminado", "871d059d88548434": "Detalles del hilo: {enabled} de {total} activados", "cec1fbb8b4c9180d": [ { @@ -11722,7 +11830,6 @@ "4c70e3e7b3e6c493": "Secretos", "79b768229c9ef672": "Mantenimiento", "54b188d65247e42f": "Experimentos", - "f41ea186c275b56e": "Acerca de", "af4b7734da1d5ce7": "Voz", "4ec62c39ca3192bf": "Versiones e issues", "f2bf529f85e05494": "Compartir y acceso", @@ -11751,11 +11858,17 @@ "8f5966eebd2b110f": "apariencia colores paleta personalizada importar", "633ed64e952cca3b": "colores bordes interfaz", "9cf8308531b4ff31": "transparente transparencia sólido menús diálogos cuadro mensaje compositor", + "d99bfbc557fae743": "Notion", + "89df56091835b3a6": "notion integration secret pages links viewer connect token ntn", + "d699adcc04d4d4ab": "sidebar compact row height branch provider icon diff pull request", + "9b9df5ba41c4a8e2": "Group threads by project", + "0ed2eab2c1953531": "sidebar project folder runs grouping collapse header repository", "d8d6cfd630cff22d": "rojo verde azul naranja adiciones eliminaciones cambios recuentos paleta daltonismo", "717e49895cfee1c7": "ancho ancho completo columna diseño mensajes cuadro mensaje compositor monitor", "88365077fd80787b": "personalizar mostrar ocultar panel tarjeta entorno editor scripts rama pull request git cambios servidores automatizaciones linaje uso límites 5 horas semanal cuota tokens ventana de contexto", "d561f74efa5f3920": "esfuerzo de razonamiento pensamiento barras gráfico palabra etiqueta nivel cuadro mensaje compositor", "6113c17109ee0d57": "latex tex katex ecuaciones fórmulas markdown", + "dfe7ead48efc3f5a": "thread details card panel workspace version control closed collapsed hide", "8c8364d44fa28d22": "dev nightly latest canal ilustración píldora etiqueta ocultar ninguno", "2d90635156dfcb5a": "tipografía familia tamaño sistema sans", "d32e93777e4819c8": "tipografía familia tamaño cuadro mensaje compositor entrada", @@ -11777,6 +11890,7 @@ "d443390c4d2dcfd4": "accesibilidad a11y lector de pantalla nvda jaws voiceover orca narrador título de ventana título de pestaña alt tab barra de tareas estado del hilo orden en curso aprobación", "6826fa9579c22035": "beta compartir invitado invitar enlace compañero ver t3 connect túnel", "f10c06cba0cdf7fe": "beta vincular otra máquina vps agentes pares trabajar allí delegar", + "bc0b409d89ce086e": "beta flujo de trabajo workflow ejecuciones duraderas automatización pasos programación webhook carpeta", "4a21cf825a2045b0": "beta tab autocompletar predecir siguiente mensaje claude codex texto fantasma", "fea2dc36585c4a20": "Hosts de dispositivos Simlock (alfa)", "9d834d178130180e": "beta alfa simlock callstack simulador emulador ios android grupo préstamo gateway", @@ -11818,7 +11932,29 @@ "34d74827c2a8b009": "enter intro comando ctrl multilínea prompt nueva línea cuadro mensaje compositor", "9d1013084c46ecce": "cola redirigir turno en ejecución enviar comportamiento predeterminado cuadro mensaje compositor", "e5e7f5e1fb1f2e4c": "subagente chat lateral hilo vinculado clic panel derecho panel lateral vista principal comando ctrl clic central", + "5c59d7e2673267ea": "composer tokens usage meter percentage compaction", + "e0d6ec10218b714e": "composer claude cache ttl expire minutes warm cold tokens", + "ce0952668aba4140": "Agent stage", + "f637899f994b78c3": "sprites stations subagents thinking editing terminal right panel everything", + "9d9d3374ee961b91": "Easter eggs", + "571180dbfeddbfd5": "surprise fun rocket animation message send hidden", + "0716adb0d55ffa58": "Voice calls", + "027d8f5ea5555973": "voice call phone gpt live feature flag anruf telefon schalter", + "60d509bb55e2967c": "Voice call voice", + "0e5f5c5ebf026abd": "voice call phone gpt live speaker stimme anruf telefon", + "266f1e2b55e419b0": "Voice call follow-up", + "392226d9bed6fe21": "voice call queue steer follow-up warteschlange anruf", "5b8b854de7ee6f4d": "instalado cli versiones más recientes disponibles codex claude cursor grok fx kiro opencode", + "1ceaab7d898b689a": "Child threads in the sidebar", + "fa5a42a73d1c1ece": "coordinator subthreads nested group expand sidebar orchestration children", + "6a1072050d1ad19e": "Coordinator decisions", + "474ba8e025886f86": "inbox questions answers decide approve coordinator open items", + "8f5558f063214509": "Cross-project threads", + "b809e3ffa5178b88": "agents coordinator other projects read message start threads repositories", + "44207b47d209f601": "compact context prompt cache idle claude tokens cost expire", + "396a2cc5b442e359": "compact idle minutes prompt cache ttl", + "6d9520a9cbd70c2f": "Minimum context for auto-compact", + "2fe046cc1e0d0d4a": "compact context tokens threshold size", "64f12530d55d2ad1": "reanudar en ejecución activo interrumpido trabajo reiniciar máquina fallo actualización de escritorio automáticamente", "214a98497c4ed05d": "caffeinate reposo evitar mantener activo energía portátil tapa inhibir", "00469926c7027e2d": "equilibrado rendimiento ahorro de batería avanzado git fetch proveedor estado actualizar host energía monitor inactivo política", @@ -11848,6 +11984,7 @@ "901a823214edc8c4": "telemetría analítica datos de uso seguimiento legal desactivar", "82136480255a5106": "OTel OTLP telemetría exportar endpoints registros trazas métricas Grafana", "659d081051faf7ff": "registros trazas procesos historial de recursos fallos spans cpu memoria", + "5eaeacfa9f82051a": "informe error problema t3 equipo enviar comentarios agentes herramientas automático cuando lo pida", "f537f91e1ee41d47": "atajos de teclado teclas rápidas comandos combinaciones json", "1ba01e7ceed64b95": "ventana captura captura de pantalla", "279b1cceb779ff38": "Incluir el texto de la app", @@ -12053,6 +12190,8 @@ "v": "v" } ], + "643c4b50feadc874": "Worktree: {path} ({branch})", + "fb7c44da0f0825ea": "Worktree: {path}", "e7f35f60e6229cf5": "App de escritorio", "77be1b7e2a1d3d31": "{count, plural, one {¿Actualizar {count} máquina?} other {¿Actualizar {count} máquinas?}}", "e4892b21e88abb60": "{count, plural, one {{count} actualización de proveedor} other {{count} actualizaciones de proveedores}}", @@ -12116,6 +12255,25 @@ "ffaa75d2db1e7cc1": "No se aplicó la actualización", "626bcbe04dc55f93": "T3 Code sigue en {current}. Vuelve a instalar {version} desde el botón de actualizar.", "49214c047fbb1606": "Actualización del proveedor interrumpida", + "a135af0f1efda8de": "Cross-project", + "6e9798372b3fb922": "Coordinators put the questions they need you to decide into an Inbox tab beside the chat, instead of numbering them in their messages. Running sessions pick up a change.", + "7a5292a1705defec": "Reset coordinator decisions to default", + "9e3ff0f05f52b724": "Let agents read, message and start threads in other projects of this environment. Running sessions pick up a change.", + "384695cdd7ab6b54": "Reset cross-project threads to default", + "5a6c243a03eeca0c": "Choose a coordinator", + "f527bb5b4ad333da": "Coordinator for \"{title}\"…", + "6beb2db2a7b5edae": "Could not assign the thread", + "4ebb0c90c45690c0": "Could not detach the thread", + "73ac4f532306bea6": [ + "Assign \"", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "\" to a coordinator" + ], + "1871eb35b1ca5d41": "No thread can coordinate this one.", "52adbc863aeb5e59": "No se pudo copiar", "0944728904d886d2": "Saturación y brillo de {label}", "dded2cb4e4d26338": "Saturación de {label}", @@ -12317,7 +12475,6 @@ "0bd41ff995d36a66": "Lectura de caché", "3f0dfe0cb15a3272": "Escritura de caché", "1c9d860be42b1c02": "Salida", - "78344b60f407928e": "Otros", "684e516076de81fe": "Estándar", "3bbcc1b826fef537": "Rápida", "66796576034c18ea": "Ultrarrápida", @@ -12333,6 +12490,270 @@ "2cddd6095abc734a": "7 días", "53493056306708cf": "30 días", "c719359d18d37ad3": "90 días", + "a7ad3167ca62e7de": "Talk to your agents by voice with GPT-Live on your Codex ChatGPT login. Turning this off ends a running call.", + "9f0e45a1d67187cd": "Reset voice calls to default", + "da0ae8174ac2fc14": "Queue what you say in a voice call while the agent runs, or steer the current run. Saying otherwise overrides it for one message. A change applies from the next call.", + "fb0a2aa3b08a17c4": "Reset voice call follow-up to default", + "66936cae56d1d749": "Queue", + "89bf6f658c44cb1b": "Steer", + "930a28582d2c103f": "The voice that talks to you in a voice call. A change applies from the next call.", + "591a53f319b0d343": "Reset voice call voice to default", + "0bd950151ddc6407": "¿Salir sin guardar? Se perderán tus cambios en este archivo.", + "c0ba3f6756b09f30": "Cambios sin guardar", + "6914e22d357f0ad6": "Guardado y en ejecución", + "aff389354a031d6f": "El archivo en disco no se carga. Sigue en ejecución la última versión que sí cargó.", + "858effde748ab563": "Guardado, pero todavía no se ejecuta.", + "ddb37138df660942": "No se guardó. No cambió nada en el servidor.", + "6ef4db489e40e39e": "No se pudo guardar", + "c89624a2e9af1793": "{name} no está conectado", + "b5a352a43adb4c17": "Sus flujos de trabajo vuelven a mostrarse cuando se reconecta. Elige otro entorno para ver sus ejecuciones.", + "3dcedb736d20aae5": "No se pudieron leer los archivos de flujos de trabajo", + "b09f4df8d76ae8ea": "¿Eliminar {file}? Los flujos de trabajo que define ya no se podrán iniciar.", + "b4535f5a03689d27": "{name} no está conectado. Lo que escribas aquí se conserva y se puede guardar en cuanto vuelva.", + "b54c78d85fd942ea": "Eliminado, pero lo que se ejecuta aún no se ha actualizado.", + "407c228d7da0b7df": "No se eliminó. No cambió nada en el servidor.", + "1a6aa10f3cc14fff": "Estos archivos no encajan entre sí. Lo que se ejecutaba antes sigue en ejecución.", + "259312516a1dbe6f": "Nombre del archivo", + "2f48ab2aa0586853": "No define ningún flujo de trabajo", + "ba5adfa37b55b8c5": [ + "Línea ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Eliminar", + "84c900d1ae72adc6": "Guardar", + "5912d817be03247a": "El archivo cambió en disco mientras lo editabas. Al guardar se reemplaza ese cambio.", + "0b1e6f5608826387": "Cargar el archivo y descartar mis cambios", + "f47b4c06aeb77c1c": "Cargando los archivos de flujos de trabajo…", + "4353bfd401d58f87": [ + "Cada archivo de", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "define flujos de trabajo. Los cambios se aplican sin reiniciar." + ], + "0c165251a06f10f1": "Nuevo archivo", + "8e97cf734b4463e7": "Crear", + "2ec0d5108fd6cebe": "Aún no hay flujos de trabajo. Crea aquí el primer archivo o pide a un agente que escriba uno en esa carpeta.", + "5601350626e8cfe9": "No se carga", + "21d778a1b9a0c234": "Abierto junto a la ejecución", + "62dc4d3a19ff7ca0": "Cerrar pestaña", + "1e25265f2758fce3": "Abrir como hilo completo", + "672a3dae06b39402": "Abrir en su propia página", + "7755500a4cde5066": "Cerrar el panel", + "b8dcbc93a2ca1861": "Esta ejecución ya no lo incluye.", + "115c69de3202f664": "Abrir", + "644eafa9048b62df": "{count, plural, =1 {1.er intento} =2 {2.º intento} =3 {3.er intento} other {{count}.º intento}}", + "e39f89c909df4db0": "No se pudo reanudar la ejecución", + "865f034346b82f47": "¿Cancelar {title}? Sus agentes se detienen y la ejecución no se podrá reanudar.", + "6bc75632fd9c9136": "No se pudo cancelar la ejecución", + "64e50329dcfdd5b0": "Finalizada", + "350162e7cc1ebea4": "Detenida", + "0875cf506f4c6810": "Omitida", + "3cc43f1dbf3f8e0c": "Cancelada", + "ded70e75de6404ba": "Volver a la lista de ejecuciones", + "2f4ed7dbd22be30d": "Cancelar ejecución", + "614e5ad58a795fb5": "Detener", + "04b050b0329f0ac8": "tardó {duration}", + "aff78e1774818ff4": "{duration} hasta ahora", + "38eddd466439afc9": "Lo que tocó la ejecución", + "156ec271d49ddd70": "Qué ocurrió", + "34f59bbbead0b97f": "{names} y {count} más", + "ac1556f6ce89a5ea": "{count} en paralelo", + "e197c4963bacc746": "{count} en curso", + "f5319ed9e18c0df1": "Te pregunta", + "882a25e9084ae1b2": "En pausa", + "9a03d8a9afc60387": "Pasos hasta ahora", + "2f2ae791afe01674": "espera tu aprobación", + "24f8060c4ccdf928": "empezando", + "30a5be40eb956663": "trabajando", + "dd7a1e58c2553933": "despierta en {duration}", + "95cc952724dd7310": "a punto de despertar", + "3cc34921c0128593": "en curso", + "e777db2880f53a46": "nadie respondió", + "dc90739d391a5e67": "Dijiste {choice}", + "389f2563b5b763fd": "Pasos rápidos", + "a41c8d758121ad81": "en espera", + "9db248b770096984": "esperó", + "c76124517af28686": "en ejecución desde hace {duration}", + "89102905bf09b0e8": "Ver en directo", + "bdf338cdff4118f0": "Transcripción", + "811e7e992f9ff820": "no puede continuar hasta que su versión del flujo de trabajo vuelva a registrarse", + "4d4cdf035e98dd57": "espera a que la reanudes", + "eb5b21dd224a5941": "lo reintenta sola en {duration}", + "6ab3dfa749fde477": "a punto de reintentarlo sola", + "44b6463aa70aa14c": "Por qué se pausó", + "cf25e7169ab0eb7a": "En pausa en {step}", + "56c48c1f220f2754": "No se pudo responder a la pregunta", + "a3c43735e1a81498": "Motivo de {title}", + "bfad234f016cfa3f": "El porqué, en una frase. Acompaña a la respuesta que elijas.", + "004c41aff9c97873": "Ejecuciones", + "4dc0c244a2419f6c": [ + "Parte de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "iniciada", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "su versión ya no está registrada", + "f92d9132f7b85d1a": "Cargando pasos…", + "6ebc59f64c761a49": "Nada todavía.", + "a759dccd157d7dae": [ + "Dijiste", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Dijiste", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Abrir ejecución", + "c8eb9be36d4d51ad": [ + "Hilo en ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Reanudar", + "8cebd63fc4c967d5": "Solo se vuelve a ejecutar el paso que falló; lo que terminó antes se conserva.", + "bc1e0a2a0f1e9552": "Te necesitan", + "a812f51e970740f1": [ + "preguntó", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· la ejecución te espera" + ], + "02dfe6c63fd0b8a1": "Añadir un motivo", + "19abd94828a3bdbc": "Preguntar antes al agente", + "a18721fa8f328361": "Te necesitan", + "bbf24e7920c1e86b": "En ejecución", + "8d6e18d2ad832db6": "Todas", + "f25af5332ffc3734": "Nada espera tu respuesta.", + "c3f0119b8d6231f8": "No hay nada en ejecución.", + "33028dfc1229eaa6": "Aún no hay ejecuciones.", + "5459bf696a187c26": "No se pudieron cargar las ejecuciones de flujos de trabajo", + "d57c35d43b0f163a": "Esta ejecución no está aquí", + "b9aae2f7cdb1a379": "Aún no hay ejecuciones de flujos de trabajo", + "8f15f66e545af7c0": "Qué ejecuciones", + "b6409289e0c9a4dd": "Flujo de trabajo", + "035cb02ca1ae4952": "Los {count} flujos de trabajo", + "46d614fa7b4bf1e5": "Ejecuciones de flujos de trabajo", + "1c635faa2fb45b8b": "Aún no se ha ejecutado.", + "156ff7b625287a1e": "Ocultar omitidos", + "69b985b97ab45e6b": "Mostrar {count} omitidos", + "2400254d362de84d": "Cargando ejecuciones de flujos de trabajo…", + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Un archivo de flujo de trabajo tiene un problema." + }, + " ", + "Sigue en ejecución la última versión que sí cargó." + ], + "ed8ce6ebc73dc12d": "Abrir el archivo", + "145e1f7503ba3b2c": [ + "Este entorno no tiene ninguna ejecución con ese enlace.", + " ", + { + "t": "button", + "i": 1, + "c": "Volver a las ejecuciones" + } + ], + "783e616cb0476c17": [ + "Un flujo de trabajo une agentes, código, programaciones y preguntas para ti en una sola ejecución que sobrevive a los reinicios. Escribe uno en", + " ", + { + "t": "button", + "i": 1, + "c": "Definiciones" + }, + ", o pídeselo a un agente.", + " ", + { + "t": "a", + "i": 2, + "c": "Leer la guía" + } + ], + "5d8d278ff828102d": "Todos los flujos de trabajo", + "39459da07479f482": "Agente", + "7741243632056b81": "{step} · transcripción", + "c512071143a5ba32": "Este hilo ya no existe.", + "ed169d23683fb6ac": "Cargando el hilo…", + "290e0ab40b87dc17": "Ruta de navegación de flujos de trabajo", + "683dd9831e54edc0": "Entorno", + "34ad53646f06ed80": "Los flujos de trabajo están desactivados", + "8f6589c9e0ac5d4e": "Ningún entorno conectado", + "744127f8dfad7d22": "Conecta un entorno para ver sus ejecuciones de flujos de trabajo.", + "036182ec7e2ee4d4": "Junto a la ejecución", + "2d6107cb78382d08": "Flujos de trabajo", + "16f7df687349b399": "Definiciones", + "f0a212aadfe1257b": "Cargando el editor…", + "20f194e003885e95": [ + "Actívalos para este servidor en", + " ", + { + "t": "Link", + "i": 1, + "c": "Ajustes → Labs" + }, + "." + ], "8367779e149f723b": "Falló una solicitud al entorno principal durante {operation} (HTTP {status}).", "c5cd027743a2b5a6": "El token de emparejamiento no es válido. Revísalo e inténtalo de nuevo.", "0e4b49c8203aae81": "Se agotó el tiempo de espera de la sesión autenticada tras el arranque.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index a0962e52bed39..b4db7d74f6efd 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -52,6 +52,27 @@ "eb0f60ef4f92ab7d": "Installez {fj} 0.6 ou version ultérieure depuis {fjUrl} et exécutez {fjLogin}, ou installez {tea} 0.16 ou version ultérieure depuis {teaUrl} et exécutez {teaLogin} pour chaque serveur Forgejo ou Gitea.", "d026a85e2e50e675": "Installez la CLI GitCafe avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", "22d3c0c48a34b5b3": "Installez la CLI TanStack Source avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", + "756c80ad262ef315": "En attente dans le fil d'origine", + "d8df14f9905f38eb": "Envoyé", + "e7c59185f8ab3987": "Non envoyé", + "b54ddec9084fa955": "Fermé sans envoi", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Peu clair", + "0f53bc8f74dfe56a": "Fonctionnalité manquante", + "055560f307e15e30": "Documentation incorrecte", + "78344b60f407928e": "Autre", + "f653846a95cd6e8f": "Type", + "f41ea186c275b56e": "À propos", + "2f6e4f7cd364da73": "Résultat attendu", + "9d11c93d4035de3e": "Résultat obtenu", + "c87d0595693704f9": "Solution de repli", + "d7a4ea6ce5af44e0": "{speaker} · {count} caractères", + "f5114fb9c40fd929": "Vous", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Tour {turn} · {what}", + "dfdaa6255a416140": "Résumé de {turns, plural, one {{turns} tour récent} other {{turns} tours récents}}, {textTurns, plural, =0 {sans texte des messages} one {avec le texte des messages du dernier tour} other {avec le texte des messages des {textTurns} derniers tours}}{truncated, select, yes {, raccourci pour tenir dans la limite} other {}}", + "260c6b45f52d2f27": "Ajoute le texte de vos messages et des réponses de l'agent dans {textTurns, plural, one {le dernier tour} other {les {textTurns} derniers tours}}.", + "afac52a5cc2dc801": "Impossible d'envoyer votre réponse. Réessayez.", "79d776428f4d0650": "Le fichier n’a pas pu être chargé. Reconnectez-vous et réessayez.", "3ea34cbb1ca5ba9b": "Aperçu annulé.", "7c0af279ecb3da3a": "Les aperçus de fichiers en streaming ne sont pas disponibles dans cet environnement d’exécution.", @@ -118,9 +139,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}.", @@ -246,6 +267,8 @@ "fec888c767b662d5": "Tentative de vérification des tickets associés", "bc31067af9c79d82": "{count, plural, one {Tickets associés vérifiés {count} fois} other {Tickets associés vérifiés {count} fois}}", "c712fec8d9dc6dd6": "{count, plural, one {Tentative de vérifier les tickets associés {count} fois} other {Tentative de vérifier les tickets associés {count} fois}}", + "81c2282590e549f5": "{count, plural, one {Read terminals {count} time} other {Read terminals {count} times}}", + "79cd7c5c29ffa938": "{count, plural, one {Tried to read terminals {count} time} other {Tried to read terminals {count} times}}", "537feee59d775e17": "{count, plural, one {Aperçu de {count} page HTML} other {Aperçu de {count} pages HTML}}", "4b45ac8cb8df04a4": "{count, plural, one {Tentative d’aperçu de {count} page HTML} other {Tentative d’aperçu de {count} pages HTML}}", "a6f62fca5dd25455": "{count, plural, one {{count} page HTML rendue} other {{count} pages HTML rendues}}", @@ -376,6 +399,31 @@ "476ca970255eaea4": "Associez cet environnement à T3 Connect pour obtenir une URL publique.", "6b80f5b38a8f9950": "Seul cet ordinateur peut appeler cette adresse. Associez T3 Connect pour obtenir une URL publique.", "c5a7b1d3891dd0b8": "Fonctionne partout où l’adresse de cet environnement est joignable, par exemple via Tailscale ou votre propre proxy. Associez T3 Connect pour obtenir une URL publique.", + "3669395daf36fd33": "N’est plus enregistré sur ce serveur", + "fe513cf316e796e3": "S’exécute dans le cadre d’autres workflows", + "ccf00b97925efab3": "Démarré à la main", + "421e585eb092b07b": "Démarre sur {triggers}", + "7bd7c58592671384": "Vous attendent", + "834ca879c14c167b": "En cours", + "582d6df7dfab86fb": "En pause", + "ea6583ce92507ee3": "En veille", + "7ea8cb8af281ce93": "En attente", + "1347868f2523140e": "Terminée", + "57d76c4614054271": "Arrêtée", + "5c7344bd51d0b966": "Ignorée", + "b2074e9bd23049a6": "Annulée", + "5bb7401807ee2fb5": "Demande : {question} et {more} de plus", + "9e4286183d5f9e34": "Demande : {question}", + "474c18d001bd6717": "Une étape a échoué", + "d3890f4eb1508781": "Exécute ses propres étapes", + "3e7ced10c9482af0": "{step} est en cours", + "237e1bcb1cf1bdec": "En veille à {step}", + "3f7b17ac5a20c8d2": "Exécute {run}", + "0306f5f324b8aaa5": "{count} exécutions en cours", + "e8fd779b84a202a2": "En attente", + "b6d55657e1a027b8": "En attente de {step}", + "e942562a42aede34": "Terminée", + "26b2b9727fe11289": "Terminée prématurément", "1bb995dcec481554": "Approuvez cet appareil sur {host}. Il affiche le code {verificationCode}.", "8696a33219944832": "Impossible de créer la preuve d’autorisation WebSocket.", "5678f133a8631f7d": "Votre connexion cloud a changé. Reconnectez-vous pour autoriser l’environnement.", @@ -637,6 +685,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", @@ -1721,6 +1772,8 @@ "2e995206e087c3fc": "Réessayez de répondre une fois la connexion ou la saisie en attente résolue.", "604ec3067171a0d7": "Conversation", "d6182a057ea12624": "Fil parent", + "f2d8537c33cc55a5": "Étape de l’exécution du workflow", + "ba8337dca3232880": "Ouvrir l’exécution", "30fa4a764d11ae42": "Impossible de télécharger {name}", "4952f87dc98191a7": "La pièce jointe est indisponible.", "2fd6d178493fb407": "Échec de l’interruption du tour en cours.", @@ -1785,6 +1838,8 @@ "181677cda4d3fd0a": "Aucun environnement connecté ne peut ajouter de projet", "3a0bf3d17f31584e": "Nouveau fil dans {project}", "4b4b64cc95acb8da": "Nouveau fil dans...", + "2c45783ab9680fdb": "Open Git graph", + "e813386e62652710": "Open agent stage", "3f581e98c86df72a": "Nouveau fil sans projet", "e510d9a7b684fbfe": "Trier un ticket", "cce3d80a2ddf1125": "Un agent examine un problème de T3 Code et vous aide à ouvrir un ticket", @@ -1806,6 +1861,7 @@ "04fd71efaa2c3b92": "Ouvrir les pull requests", "57e875b79b98ab82": "Ouvrir les tickets", "f1db0a234c777a1d": "Utiliser T3 Code dans une autre app (MCP)", + "6050f22f63e2bcb5": "Ouvrir les workflows", "a0cc19e60dd99851": "Ouvrir l’utilisation", "46694969044eee98": "Activer la zone de travail suivante", "0a1011328ba42eef": "Activer la zone de travail précédente", @@ -2361,14 +2417,24 @@ "05037ca1666fd421": "Les terminaux ne sont disponibles que depuis un fil de projet.", "a3aa1e49af278d41": "Les fichiers ne sont disponibles que lorsqu’un projet est ouvert.", "87ea6995ea1e7aa4": "Le diff n’est disponible que pour les fils de serveur dans des dépôts Git.", + "80f10f5ea1804d8d": "The Git graph needs a Git repository on an up-to-date server.", "4a87cae01ccde544": "La branche de ce fil n’a pas encore de pull request.", "32535dba0b9af642": "Ce fil n’a aucun élément associé.", + "d955eee48dece3c0": "Enable the agent stage in Settings > General.", + "d2f2f6d05148f8a3": "Threads a coordinator runs have no thread overview.", + "26c1c05b0d1d98fd": "Turn on coordinator decisions in Settings > General.", + "486d4369c4fbec9e": "Notes are only available from a thread.", + "50b5a57d3bd6f6ef": "Instructions are only available from a thread.", + "007ab76950f73521": "Media is only available from a thread.", "07080dead70f4cc5": "Les appareils ne sont disponibles que depuis un fil.", "a4bf49b31758ff7e": "Disponible uniquement dans l’app desktop.", "e917841cb66f9af1": "Disponible lorsqu’un projet est ouvert.", "14c15fad0c2ee0c8": "Disponible pour les dépôts Git.", "9176276c78f3893f": "Pas encore de pull request sur cette branche.", "52ce9db6fb62a59f": "Aucun élément associé disponible.", + "96c2ee76dd82d2cc": "Enable it in Settings > General.", + "2199013487151590": "Not for threads a coordinator runs.", + "f7a9300d9f9030d5": "Turn on coordinator decisions in Settings.", "e5d6f41e4fe4efd6": "Disponible depuis un fil.", "0ebc2bb883a8e283": "Disponible après le premier message.", "84d0ff8fb9846057": "Réactiver le son de l’onglet", @@ -2377,8 +2443,15 @@ "5c78a8ae7b71af1d": "Terminal", "cba3e832ece50257": "Fichiers", "83ac3423d6dfc4a7": "Diff", + "016750bdd5076287": "Git graph", "da16af47eff38ae9": "Pull request", "ad3929f0103925d7": "Éléments associés", + "70e7b208e032024a": "Stage", + "0caf7e5748f1d17b": "Threads this one started, and which need you.", + "96018894225bd4ff": "Inbox", + "0ed16d7723c04288": "Decisions the coordinator asks you for.", + "aec2b493d2b01445": "Notes", + "9e92f6aa6edae875": "Notes and todos for this thread, its project, or everywhere.", "ac0de2a59d9c8860": "Appareil", "1354df9fb7278843": "Regardez un simulateur iOS ou un émulateur Android.", "fdcd9643e2e63b15": "Posez une question annexe pendant que ce fil continue de travailler.", @@ -2497,8 +2570,7 @@ "2d1c111e1b4ae0b0": "Supprimer le fil « {title} » ?", "c568ab8dad798ec5": "Cela efface définitivement l’historique de conversation de ce fil.", "0fd1c746a0e38003": "Échec de la suppression du fil", - "0ecde875b0dd2f93": "Filtrer les fils par projet : {projects}", - "1ef65b647231ff0b": "Filtrer les fils par projet", + "1c8fc3c4a42949ab": "Projets : {projects}", "165511761be2855c": "Rechercher des projets", "a46a6467883575a4": "Rechercher des projets...", "fdc0e086438a3045": "Paramètres du projet {project}", @@ -2560,10 +2632,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 +2644,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 +2668,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", @@ -2686,8 +2756,6 @@ "78a04e0e625c0990": "Échec de la mise à jour", "c24de5eb69373a55": "Cette version {build} ignore les versions {track}. Vérifiez le canal de mise à jour dans les Réglages pour terminer le changement.", "b02ae45a6109c93b": "À jour", - "edcda9e8ee4ccad8": "Installer la mise à jour {version} et redémarrer T3 Code ?\n\nToutes les tâches en cours seront interrompues. Assurez-vous d’être prêt avant de continuer.", - "02eba0f7cc90f759": "Installer la mise à jour et redémarrer T3 Code ?\n\nToutes les tâches en cours seront interrompues. Assurez-vous d’être prêt avant de continuer.", "9ed4d8a1531b9631": "Les mises à jour automatiques ne sont pas disponibles dans cette version.", "c8c23435e780a60c": "Mises à jour indisponibles", "1af5f9767371ffd7": "Rechercher des mises à jour", @@ -3034,8 +3102,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 +3346,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 +3523,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", @@ -3577,6 +3649,13 @@ "c53bc5a4b0314342": "Média suivant", "2950b1424a3cddf5": "Reconnectez-vous à cet environnement et ouvrez à nouveau le média.", "ef638bf1479a5461": "L’environnement a renvoyé une URL de média non valide.", + "3ccfbf7e86868c35": "Retour pour l'équipe T3", + "4e0710d19dfc2e7e": "Envoyer ce rapport à l'équipe T3 ?", + "87d0ae0723ba75d1": "Voici tout ce qui quitte votre machine. Rien n'est envoyé tant que vous ne cliquez pas sur Envoyer.", + "bf19826f81484328": "Inclure la conversation", + "ddb7e6f8ce99e657": "Seule une personne autorisée à exécuter des agents sur cette machine peut l'envoyer ou le refuser.", + "03c1eb603c112f47": "Ne pas envoyer", + "653405e4ed498d9f": "Envoyer", "262955d6eb632f9b": "L’API Presse-papiers n’est pas disponible pour copier le lien invité.", "f1a4f2b04cdbb4ef": "Impossible de copier le lien invité dans le presse-papiers.", "cf3490a604e44d31": "Impossible de créer un lien invité.", @@ -3597,7 +3676,6 @@ "abd89e9eefedf11b": "Terminé", "18d166056c1ab6ff": "Arrêter le partage", "7a2d510eac9e4587": "Lien invité expiré", - "653405e4ed498d9f": "Envoyer", "21888e302219891d": "Aperçu agrandi de {title}", "419719298a7acaea": "Zoom arrière", "ed8d5db95359cff4": "Réinitialiser le zoom", @@ -3693,7 +3771,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 +3782,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 +4058,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", @@ -5454,6 +5529,22 @@ "f0d79aa56f06663f": "Ce fichier est trop volumineux pour être affiché en entier. Les totaux incluent toutes les modifications.", "7fdde2b893ba1b9d": "Supprimé", "e58ce271d835b447": "Ajouté", + "fb5c7ff5ea76e01a": "Added by esveo's fork. Click to list all of its settings.", + "352fa6aeb5d55665": "Trail the provider icon behind the thread title instead of giving it a line of its own. The line it saves also carried the branch, pull request badge and diff counts.", + "9d44fa03a230e0d8": "Reset two-line thread cards to default", + "7b216eedb1abe696": "Two-line thread cards", + "8d90fcd918e901c8": "Keep each project's threads together in the sidebar, under a header that folds the project away. Ordering stays by recency: the project with the newest thread leads.", + "d5dfd89c9a281386": "Réinitialiser le regroupement des projets à la valeur par défaut", + "aac9f889c7ec7ff5": "Group sidebar threads by project", + "da375a07c5309184": "Show how full the thread's context window is next to the composer controls.", + "33f6b88cba203990": "Reset context window usage to default", + "6496f57baeded3fa": "Context window usage", + "d9c146dc6b95714d": "Show how many minutes are left before the prompt cache expires. Claude only.", + "69609e27c2107da5": "Reset prompt cache timer to default", + "a4917d2b93c478f6": "Prompt cache timer", + "ea8ebcb77e657e9f": "Open the thread details card with workspace and version control in every thread. Off, it stays closed until you open it, and each thread remembers your choice.", + "662288b90e19635f": "Réinitialiser les détails du fil à la valeur par défaut", + "92729a403d37c575": "Open thread details by default", "07b9970b662ab70d": "Afficher la source Mermaid", "5a422b7be35243f5": "Afficher le diagramme rendu", "c0628ad999cbbbf5": "Afficher la source Markdown", @@ -5561,6 +5652,7 @@ "723d88a5fa7e2fdd": "Aucun fichier correspondant.", "f8d6e9a1a2870a5c": "Explorateur de fichiers", "109edd252917113b": "Redimensionner l’explorateur de fichiers", + "7abd6af24fed7b60": "The file does not exist in the workspace or the home folder.", "37cbd2ecc659a007": "Fichier", "b5188f172f59ca79": "Cette connexion ne peut pas lire les fichiers de l’hôte.", "c3c5d36466ad2191": "Ouvrir le fichier dans le navigateur d’aperçu", @@ -5600,7 +5692,6 @@ }, ". Vérifiez le chemin du lien ou retrouvez le fichier dans Fichiers." ], - "b9b6bbd1e1ea189f": "Fichier complet", "d715e9494fdbaaf6": "Impossible de charger la police.", "ff17c777a72b4408": "Les aperçus de polices sont limités à 10 Mo.", "6bd41ad699e22f10": "La police est indisponible.", @@ -5610,6 +5701,7 @@ "a9abaaa4220eae21": "{error} Enregistrez-la pour l’ouvrir dans une autre app.", "c508c9000d9656f8": "Aperçu de la police", "1c416d621d250be8": "Portez ce vieux whisky au juge blond qui fume.", + "d7d08260f16b7828": "Le fichier est encore en cours de chargement. Réessaie dans un instant.", "76ebb03de52c92d6": "La visionneuse de texte s’est arrêtée.", "f48162e8e8c12af7": "Impossible de charger la visionneuse de texte. Fermez le fichier et réessayez.", "bc4c5b13d38a5da7": "Aperçu fermé.", @@ -5617,8 +5709,6 @@ "9450d1827ef336a1": "Une autre copie est en cours.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} ligne} other {{formatted} lignes}}", "13b14784f8707ddd": "0 octet", - "f6e9581cba3467fa": "Indexation…", - "2d1f293ac12463fc": "Chargement du reste du fichier…", "b75105bef8f564a4": "Affichage des 1 024 premières colonnes. Source et Enregistrer conservent toutes les colonnes.", "2a6e1b1f209c3888": "Ce fichier est vide.", "192fc79eb3b5b2cb": "Ce diagramme contient des URL de ressources, du balisage, des métadonnées de nœuds ou une configuration personnalisée. Affichez la source Mermaid pour l’examiner en toute sécurité.", @@ -5805,7 +5895,6 @@ "0061fff77e36bd4f": "Impossible de joindre le serveur.", "04dfdd46e3dd4a2e": "Une erreur s’est produite. Réessayez.", "084bb2d8127a508d": "Envoyé", - "e7c59185f8ab3987": "Non envoyé", "77c01a15bd36d17c": "Ce lien a expiré ou n’est pas valide", "e0e736810f3cbef2": "Demandez un nouveau lien au propriétaire. Chaque lien fonctionne dans un seul navigateur.", "c3c53aa46f7330e5": "Ce lien a expiré", @@ -5827,6 +5916,13 @@ "cbb2129c0dd4f40b": "Les fichiers joints peuvent totaliser jusqu’à 10 Mo par message.", "03b9cd79cfe0b435": "Ce fichier ne peut pas être joint. Les images doivent être au format PNG, JPEG, GIF ou WebP.", "8ff29c78798e6ac1": "Impossible de charger cet élément.", + "535923000a0f3e3b": "Send /compact to a large, idle Claude thread shortly before its 1-hour prompt cache expires, so the next message skips caching the whole conversation again. 5-minute caches are left alone.", + "bd8eb8f5f9843bc6": "Reset idle auto-compact to default", + "1db274eacf03c8de": "Auto-compact idle Claude threads", + "fb6643c75aafd996": "Between {min} and {max}; it has to fall inside the cache's hour.", + "48dee64ca7904281": "Minutes idle before auto-compact", + "8937fe924464eb70": "Smaller threads are cheap to cache again and keep their full history.", + "1981f1e1a753aabc": "Minimum context tokens for auto-compact", "94ab4591ce101233": "Le commentaire n’a pas pu être publié", "92d0d4eab2596772": "Le gestionnaire de tickets l’a refusé.", "33591d9596fb7cb7": "Ajouter un commentaire", @@ -8694,12 +8790,16 @@ "58e0e226493150e7": "Impossible de charger les gestionnaires de tickets", "77cfcbde543df32d": "Afficher ou masquer les détails de {tracker}", "0083f65885c60156": "Déconnecter {tracker}", - "295392927d5c8a84": "Choisissez un ou plusieurs {scope}s {tracker} pour chaque projet. Leurs tickets s'affichent à côté de ceux du dépôt, et les agents créent les nouveaux tickets dans le premier.", + "ed83b25c71c98a20": "Choisissez un ou plusieurs {scope}s {tracker} pour chaque projet. Leurs tickets s'affichent à côté de ceux du dépôt, et les agents créent les nouveaux tickets dans le premier, sauf si vous leur indiquez une autre destination.", "19c2d5e81ff8f89a": "{scope} {tracker} pour {project}", "68e061510b765772": "Non lié", + "99d51127f573296b": "Autre compte", + "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}.", + "99963c0142e17f00": "Pour le nouveau compte {tracker}.", "a2d95d39d3398bda": "Identifiant refusé", "9eae463720500113": "Stocké sur le serveur.", "b6e27ab2537ef874": "En créer un", + "6d8e4ebc889bace9": "Ajouter un compte", "13ef526271b0f5d4": "Effacer toutes les conditions", "d1938a629f039515": "Supprimer la condition", "84a605b241ce65b7": "Supprimer le groupe et ses conditions", @@ -8829,6 +8929,12 @@ "d3866ead082d14e5": "Ajouter un raccourci clavier", "d4345c90894a3220": "Ouvrir keybindings.json", "e56a8d51219efaa0": "Aucun raccourci clavier ne correspond à votre recherche.", + "90a258fff61fd77e": "Désactivé", + "4060244a7079a0d2": "À ma demande", + "e88c9d8769544731": "Automatique", + "f29d1dade4dde8aa": "Les agents n'envoient aucun retour à l'équipe T3.", + "93c4c53562d30a98": "À votre demande, les agents vous présentent un court rapport sur T3 Code et l'envoient à l'équipe T3 si vous l'approuvez.", + "cd9ee803e8727017": "Les agents signalent aussi spontanément les problèmes qu'ils rencontrent dans T3 Code, comme un outil T3 qui échoue.", "45fa271ea0e1ac8e": "Bêta", "3a678332fc7142f7": "Regroupe les fils de la barre latérale dans des dossiers de projet. Les fils épinglés restent en haut, les fils reportés et clos restent sous les dossiers.", "e4e91d155cb6a9b4": "Barre latérale classique (regrouper par projet)", @@ -8837,11 +8943,16 @@ "9ae293971d93c819": "Partagez un fil avec un invité qui le suit en direct dans un navigateur et envoie des messages que vous approuvez. Connectez-vous à T3 Connect pour utiliser les liens invités.", "0aa5406ac4d7f7c7": "Liens invités", "f0e853acd2006d53": "Environnements associés", + "ef10c2dff987f3ea": "Exécutez des workflows en plusieurs étapes à partir des fichiers du dossier workflows du répertoire T3 de ce serveur. Ouvrez-les depuis la palette de commandes. Tant que c'est désactivé, rien dans ce dossier ne s'exécute ; les exécutions attendent sa réactivation.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Affiche un prochain message suggéré dans la zone de saisie vide après un tour Claude ou Codex. Tab l’utilise. Chaque suggestion est une requête en cache supplémentaire sur votre forfait. Nécessite Codex 0.165+. Les fils Claude se mettent à jour au redémarrage.", "d4b2a2ec812aafb0": "Suggérer le prochain prompt", "298c7150a7621c80": "Hôtes d’appareils Simlock", "67937aa49179285e": "Sur Mac, clone les nouveaux worktrees depuis une copie en cache dans le dossier T3 home au lieu d’écrire chaque fichier. Utilise le checkout Git normal quand ce n’est pas possible. La désactivation supprime le cache.", "f9904f78d3003f58": "Checkout rapide des worktrees", + "9c2f647882522302": "Les machines sélectionnées utilisent des modes de retour des agents différents.", + "31bbf7bf8c0a5279": "Retours des agents", + "d52b3d6bf9f2a013": "Mixte", "ec7623deed751c05": [ "Partagez un fil avec un invité qui le suit en direct dans un navigateur et envoie des messages que vous approuvez. Nécessite T3 Connect : connectez-vous et associez cette machine dans", " ", @@ -8926,7 +9037,9 @@ "fb71127e5746a6bc": "Depuis Partage et accès sur cette machine, ou t3 pair", "1e3fee7084791773": "Associer aussi {target} en retour à {source}", "ea34a190b0bd804c": "Les agents de {target} pourront alors aussi travailler sur {source}.", - "ad5ed0ce61b966eb": "Oublier {label} ? Les agents d’ici cessent d’y travailler. Révoquez « T3 Code · … » dans Partage et accès sur {label} pour y fermer aussi la session.", + "974f8c65e8b5f492": "Oublier {label} ? Les agents d’ici cessent d’y travailler, et leur session sur {label} prend fin aussi s’il répond.", + "6cf9e3083b15614f": "{label} n’a pas répondu", + "34ccbdf619b83be3": "Révoquez « T3 Code · … » dans Partage et accès sur {label} pour y fermer aussi la session.", "81c9796bf61b306a": "Impossible d’oublier l’association", "130e51beb6cf5aad": "Associer un environnement", "122c3e355699e69d": "Les agents d’ici pourront alors lancer des fils là-bas, leur envoyer des messages et les attendre. L’association apparaît sous Clients autorisés dans Partage et accès de cet environnement, où elle peut être révoquée.", @@ -9155,7 +9268,6 @@ "0b4779a1825c85bc": "Le nom commun de ce groupe de projets dans la barre latérale et les listes de fils.", "f68cbda4df83d739": "Réinitialiser le nom du projet à la valeur par défaut", "56e37b85027e8431": "Icône du projet", - "e88c9d8769544731": "Automatique", "c99736317da5b1fa": "Réinitialiser l’icône du projet à la valeur par défaut", "6afaa3e3739dc570": "Choisir une icône de projet", "51651ce45d481a20": "Choisir un fichier d’icône de projet", @@ -10064,7 +10176,6 @@ "53de7aafe0afc10d": "Impossible de restaurer les paramètres du thème", "006bfa1846fe5dd2": "Jours d’inactivité avant la clôture automatique", "d9b0fbd680d5f175": "Barre latérale", - "d5dfd89c9a281386": "Réinitialiser le regroupement des projets à la valeur par défaut", "cd5452cc9e13c818": "Regroupement des projets", "cfb01b8a2a3361fb": "Réinitialiser l’ordre des projets à la valeur par défaut", "26abcbe322049a8a": "Réinitialiser la section En cours à la valeur par défaut", @@ -10129,7 +10240,6 @@ "16bdc70b858c223f": "Réinitialiser les panneaux proactifs à la valeur par défaut", "c5424f09d77138ff": "Quand compacter un fil Claude inactif de plus de 200 000 tokens : à votre retour, juste avant l’expiration de son cache de prompt, ou jamais. Chaque fournisseur Claude peut remplacer ce paramètre.", "3e99c5c14f4939c8": "Réinitialiser le compactage des fils inactifs à la valeur par défaut", - "d52b3d6bf9f2a013": "Mixte", "cd72fe451ba0d6aa": "Nouveaux projets", "394c3bd0a1782c8e": "Laissez vide pour utiliser « ~/ » à l’ouverture du navigateur Ajouter un projet.", "f9b912a818bd869d": "Réinitialiser le répertoire de base pour l’ajout de projets à la valeur par défaut", @@ -11031,7 +11141,6 @@ "4a237f41ce592b7f": "Conserve les worktrees de ce projet jusqu’à ce que vous les supprimiez manuellement.", "00b8ffd8ea6e6a93": "Utilise ces règles pour ce projet.", "72c279824d15a999": "Utilise les paramètres de nettoyage des worktrees de chaque machine.", - "90a258fff61fd77e": "Désactivé", "b5702d0b64866b08": "Personnalisé", "c009c901f3eefe78": "Supprimer les worktrees des fils supprimés", "431c7cd6d50102b7": "Supprime les worktrees inutilisés quand des fils actifs ou archivés sont supprimés. Les worktrees avec des modifications locales sont conservés.", @@ -11388,7 +11497,6 @@ "f2043e87a10cb831": "Modifier le thème", "595bdeefcdc9bf31": "Exporter le fichier de thème", "b480281b3791b685": "Choisissez ce qu’affiche la carte de détails du fil. Vous pouvez aussi faire un clic droit sur la carte.", - "662288b90e19635f": "Réinitialiser les détails du fil à la valeur par défaut", "871d059d88548434": "Détails du fil : {enabled} sur {total} activés", "cec1fbb8b4c9180d": [ { @@ -11727,7 +11835,6 @@ "4c70e3e7b3e6c493": "Secrets", "79b768229c9ef672": "Maintenance", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "À propos", "af4b7734da1d5ce7": "Voix", "4ec62c39ca3192bf": "Versions et tickets", "f2bf529f85e05494": "Partage et accès", @@ -11756,11 +11863,17 @@ "8f5966eebd2b110f": "apparence couleurs palette personnalisée importer", "633ed64e952cca3b": "couleurs bordures interface", "9cf8308531b4ff31": "transparent transparence opaque menus boîtes de dialogue zone de saisie", + "d99bfbc557fae743": "Notion", + "89df56091835b3a6": "notion integration secret pages links viewer connect token ntn", + "d699adcc04d4d4ab": "sidebar compact row height branch provider icon diff pull request", + "9b9df5ba41c4a8e2": "Group threads by project", + "0ed2eab2c1953531": "sidebar project folder runs grouping collapse header repository", "d8d6cfd630cff22d": "rouge vert bleu orange ajouts suppressions modifications compteurs palette daltonien", "717e49895cfee1c7": "large pleine largeur colonne mise en page messages zone de saisie écran", "88365077fd80787b": "personnaliser afficher masquer panneau carte environnement éditeur scripts branche pull request modifications git serveurs automatisations lignée utilisation limites 5 heures hebdomadaire quota jetons fenêtre de contexte", "d561f74efa5f3920": "effort de raisonnement réflexion barres graphique mot libellé niveau zone de saisie", "6113c17109ee0d57": "latex tex katex équations formules markdown", + "dfe7ead48efc3f5a": "thread details card panel workspace version control closed collapsed hide", "8c8364d44fa28d22": "dev nightly dernière canal illustration pastille libellé masquer aucun", "2d90635156dfcb5a": "typographie famille taille système sans", "d32e93777e4819c8": "typographie famille taille zone de saisie saisie", @@ -11782,6 +11895,7 @@ "d443390c4d2dcfd4": "accessibilité a11y lecteur d’écran nvda jaws voiceover orca narrateur titre de fenêtre titre d’onglet alt tab barre des tâches statut du fil ordre en cours approbation", "6826fa9579c22035": "bêta partager invité invitation lien coéquipier regarder t3 connect tunnel", "f10c06cba0cdf7fe": "bêta associer une autre machine vps pair agents y travaillent déléguer", + "bc0b409d89ce086e": "bêta workflow exécutions durables automatisation étapes planification webhook dossier", "4a21cf825a2045b0": "bêta tab autocomplétion prédire prochain message claude codex texte fantôme", "fea2dc36585c4a20": "Hôtes d’appareils Simlock (alpha)", "9d834d178130180e": "bêta alpha simlock callstack simulateur émulateur ios android pool bail passerelle", @@ -11823,7 +11937,29 @@ "34d74827c2a8b009": "entrée retour commande ctrl multiligne prompt nouvelle ligne zone de saisie", "9d1013084c46ecce": "file d’attente réorienter tour en cours envoyer comportement par défaut zone de saisie", "e5e7f5e1fb1f2e4c": "sous-agent discussion annexe fil associé clic panneau droit panneau latéral vue principale commande ctrl clic du milieu", + "5c59d7e2673267ea": "composer tokens usage meter percentage compaction", + "e0d6ec10218b714e": "composer claude cache ttl expire minutes warm cold tokens", + "ce0952668aba4140": "Agent stage", + "f637899f994b78c3": "sprites stations subagents thinking editing terminal right panel everything", + "9d9d3374ee961b91": "Easter eggs", + "571180dbfeddbfd5": "surprise fun rocket animation message send hidden", + "0716adb0d55ffa58": "Voice calls", + "027d8f5ea5555973": "voice call phone gpt live feature flag anruf telefon schalter", + "60d509bb55e2967c": "Voice call voice", + "0e5f5c5ebf026abd": "voice call phone gpt live speaker stimme anruf telefon", + "266f1e2b55e419b0": "Voice call follow-up", + "392226d9bed6fe21": "voice call queue steer follow-up warteschlange anruf", "5b8b854de7ee6f4d": "installé cli versions plus récentes disponibles codex claude cursor grok fx kiro opencode", + "1ceaab7d898b689a": "Child threads in the sidebar", + "fa5a42a73d1c1ece": "coordinator subthreads nested group expand sidebar orchestration children", + "6a1072050d1ad19e": "Coordinator decisions", + "474ba8e025886f86": "inbox questions answers decide approve coordinator open items", + "8f5558f063214509": "Cross-project threads", + "b809e3ffa5178b88": "agents coordinator other projects read message start threads repositories", + "44207b47d209f601": "compact context prompt cache idle claude tokens cost expire", + "396a2cc5b442e359": "compact idle minutes prompt cache ttl", + "6d9520a9cbd70c2f": "Minimum context for auto-compact", + "2fe046cc1e0d0d4a": "compact context tokens threshold size", "64f12530d55d2ad1": "reprendre en cours actif interrompu travail redémarrer redémarrage machine plantage mise à jour bureau automatiquement", "214a98497c4ed05d": "caffeinate veille empêcher rester éveillé alimentation portable capot inhiber", "00469926c7027e2d": "équilibré performances économie batterie avancé git fetch fournisseur état actualisation hôte énergie surveillance inactif politique", @@ -11853,6 +11989,7 @@ "901a823214edc8c4": "télémétrie analytique données d’utilisation suivi mentions légales refuser", "82136480255a5106": "OTel OTLP télémétrie export points de terminaison journaux traces métriques Grafana", "659d081051faf7ff": "journaux traces processus historique des ressources échecs spans cpu mémoire", + "5eaeacfa9f82051a": "rapport bug problème t3 équipe envoyer retour agents outils automatique à ma demande", "f537f91e1ee41d47": "raccourcis clavier touches commandes associations json", "1ba01e7ceed64b95": "fenêtre capture capture d’écran", "279b1cceb779ff38": "Inclure le texte de l’app", @@ -12058,6 +12195,8 @@ "v": "v" } ], + "643c4b50feadc874": "Worktree: {path} ({branch})", + "fb7c44da0f0825ea": "Worktree: {path}", "e7f35f60e6229cf5": "App de bureau", "77be1b7e2a1d3d31": "{count, plural, one {Mettre à jour {count} machine ?} other {Mettre à jour {count} machines ?}}", "e4892b21e88abb60": "{count, plural, one {{count} mise à jour de fournisseur} other {{count} mises à jour de fournisseurs}}", @@ -12121,6 +12260,25 @@ "ffaa75d2db1e7cc1": "La mise à jour ne s’est pas appliquée", "626bcbe04dc55f93": "T3 Code est toujours en {current}. Installez à nouveau {version} depuis le bouton de mise à jour.", "49214c047fbb1606": "Mise à jour du fournisseur interrompue", + "a135af0f1efda8de": "Cross-project", + "6e9798372b3fb922": "Coordinators put the questions they need you to decide into an Inbox tab beside the chat, instead of numbering them in their messages. Running sessions pick up a change.", + "7a5292a1705defec": "Reset coordinator decisions to default", + "9e3ff0f05f52b724": "Let agents read, message and start threads in other projects of this environment. Running sessions pick up a change.", + "384695cdd7ab6b54": "Reset cross-project threads to default", + "5a6c243a03eeca0c": "Choose a coordinator", + "f527bb5b4ad333da": "Coordinator for \"{title}\"…", + "6beb2db2a7b5edae": "Could not assign the thread", + "4ebb0c90c45690c0": "Could not detach the thread", + "73ac4f532306bea6": [ + "Assign \"", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "\" to a coordinator" + ], + "1871eb35b1ca5d41": "No thread can coordinate this one.", "52adbc863aeb5e59": "Échec de la copie", "0944728904d886d2": "Saturation et luminosité de {label}", "dded2cb4e4d26338": "Saturation de {label}", @@ -12322,7 +12480,6 @@ "0bd41ff995d36a66": "Lecture du cache", "3f0dfe0cb15a3272": "Écriture du cache", "1c9d860be42b1c02": "Sortie", - "78344b60f407928e": "Autre", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Rapide", "66796576034c18ea": "Ultrarapide", @@ -12338,6 +12495,270 @@ "2cddd6095abc734a": "7 jours", "53493056306708cf": "30 jours", "c719359d18d37ad3": "90 jours", + "a7ad3167ca62e7de": "Talk to your agents by voice with GPT-Live on your Codex ChatGPT login. Turning this off ends a running call.", + "9f0e45a1d67187cd": "Reset voice calls to default", + "da0ae8174ac2fc14": "Queue what you say in a voice call while the agent runs, or steer the current run. Saying otherwise overrides it for one message. A change applies from the next call.", + "fb0a2aa3b08a17c4": "Reset voice call follow-up to default", + "66936cae56d1d749": "Queue", + "89bf6f658c44cb1b": "Steer", + "930a28582d2c103f": "The voice that talks to you in a voice call. A change applies from the next call.", + "591a53f319b0d343": "Reset voice call voice to default", + "0bd950151ddc6407": "Quitter sans enregistrer ? Vos modifications de ce fichier seront perdues.", + "c0ba3f6756b09f30": "Modifications non enregistrées", + "6914e22d357f0ad6": "Enregistré et en service", + "aff389354a031d6f": "Le fichier sur le disque ne se charge pas. La dernière version valide continue de s’exécuter.", + "858effde748ab563": "Enregistré, mais il ne s’exécute pas encore.", + "ddb37138df660942": "Non enregistré. Rien n’a changé sur le serveur.", + "6ef4db489e40e39e": "Impossible d’enregistrer", + "c89624a2e9af1793": "{name} n’est pas connecté", + "b5a352a43adb4c17": "Ses workflows réapparaissent quand il se reconnecte. Choisis un autre environnement pour voir ses exécutions.", + "3dcedb736d20aae5": "Impossible de lire les fichiers de workflow", + "b09f4df8d76ae8ea": "Supprimer {file} ? Les workflows qu’il définit ne pourront plus être démarrés.", + "b4535f5a03689d27": "{name} n’est pas connecté. Ce que vous écrivez ici est conservé et pourra être enregistré dès son retour.", + "b54c78d85fd942ea": "Supprimé, mais ce qui s’exécute n’a pas encore suivi.", + "407c228d7da0b7df": "Non supprimé. Rien n’a changé sur le serveur.", + "1a6aa10f3cc14fff": "Ces fichiers ne sont pas cohérents entre eux. Ce qui s’exécutait avant continue de s’exécuter.", + "259312516a1dbe6f": "Nom du fichier", + "2f48ab2aa0586853": "Ne définit aucun workflow", + "ba5adfa37b55b8c5": [ + "Ligne ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " :" + ], + "d94eb9ab3201b641": "Supprimer", + "84c900d1ae72adc6": "Enregistrer", + "5912d817be03247a": "Le fichier a changé sur le disque pendant votre modification. L’enregistrement remplace ce changement.", + "0b1e6f5608826387": "Charger le fichier et abandonner mes modifications", + "f47b4c06aeb77c1c": "Chargement des fichiers de workflow…", + "4353bfd401d58f87": [ + "Chaque fichier de", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "définit des workflows. Toute modification est prise en compte sans redémarrage." + ], + "0c165251a06f10f1": "Nouveau fichier", + "8e97cf734b4463e7": "Créer", + "2ec0d5108fd6cebe": "Aucun workflow pour l’instant. Créez le premier fichier ici ou demandez à un agent d’en écrire un dans ce dossier.", + "5601350626e8cfe9": "Ne se charge pas", + "21d778a1b9a0c234": "Ouvert à côté de l’exécution", + "62dc4d3a19ff7ca0": "Fermer l’onglet", + "1e25265f2758fce3": "Ouvrir comme fil complet", + "672a3dae06b39402": "Ouvrir sur sa propre page", + "7755500a4cde5066": "Fermer le panneau", + "b8dcbc93a2ca1861": "Cette exécution ne le mentionne plus.", + "115c69de3202f664": "Ouvrir", + "644eafa9048b62df": "{count, plural, =1 {1er essai} =2 {2e essai} =3 {3e essai} other {{count}e essai}}", + "e39f89c909df4db0": "Impossible de reprendre l’exécution", + "865f034346b82f47": "Annuler {title} ? Ses agents s’arrêtent et l’exécution ne pourra pas être reprise.", + "6bc75632fd9c9136": "Impossible d’annuler l’exécution", + "64e50329dcfdd5b0": "Terminée", + "350162e7cc1ebea4": "Arrêtée", + "0875cf506f4c6810": "Ignorée", + "3cc43f1dbf3f8e0c": "Annulée", + "ded70e75de6404ba": "Retour à la liste des exécutions", + "2f4ed7dbd22be30d": "Annuler l’exécution", + "614e5ad58a795fb5": "Arrêter", + "04b050b0329f0ac8": "a duré {duration}", + "aff78e1774818ff4": "{duration} jusqu’ici", + "38eddd466439afc9": "Ce que l’exécution a touché", + "156ec271d49ddd70": "Ce qui s’est passé", + "34f59bbbead0b97f": "{names} et {count} de plus", + "ac1556f6ce89a5ea": "{count} en parallèle", + "e197c4963bacc746": "{count} en cours", + "f5319ed9e18c0df1": "Vous pose une question", + "882a25e9084ae1b2": "En pause", + "9a03d8a9afc60387": "Étapes jusqu’ici", + "2f2ae791afe01674": "attend ton approbation", + "24f8060c4ccdf928": "démarre", + "30a5be40eb956663": "en cours", + "dd7a1e58c2553933": "réveil dans {duration}", + "95cc952724dd7310": "réveil imminent", + "3cc34921c0128593": "en cours", + "e777db2880f53a46": "personne n’a répondu", + "dc90739d391a5e67": "Vous avez répondu {choice}", + "389f2563b5b763fd": "Étapes rapides", + "a41c8d758121ad81": "en veille", + "9db248b770096984": "a attendu", + "c76124517af28686": "en cours depuis {duration}", + "89102905bf09b0e8": "Suivre en direct", + "bdf338cdff4118f0": "Transcription", + "811e7e992f9ff820": "ne peut pas continuer tant que sa version du workflow n’est pas de nouveau enregistrée", + "4d4cdf035e98dd57": "attend que vous la repreniez", + "eb5b21dd224a5941": "réessaie d’elle-même dans {duration}", + "6ab3dfa749fde477": "va réessayer d’elle-même", + "44b6463aa70aa14c": "Raison de la pause", + "cf25e7169ab0eb7a": "En pause à {step}", + "56c48c1f220f2754": "Impossible de répondre à la question", + "a3c43735e1a81498": "Raison pour {title}", + "bfad234f016cfa3f": "Pourquoi, en une phrase. Elle accompagne la réponse que vous choisissez.", + "004c41aff9c97873": "Exécutions", + "4dc0c244a2419f6c": [ + "Fait partie de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "démarrée", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "sa version n’est plus enregistrée", + "f92d9132f7b85d1a": "Chargement des étapes…", + "6ebc59f64c761a49": "Rien pour l’instant.", + "a759dccd157d7dae": [ + "Vous avez répondu", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Vous avez répondu", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " : ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Ouvrir l’exécution", + "c8eb9be36d4d51ad": [ + "Fil sur ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Reprendre", + "8cebd63fc4c967d5": "Seule l’étape en échec est relancée ; ce qui s’est terminé avant est conservé.", + "bc1e0a2a0f1e9552": "Vous attendent", + "a812f51e970740f1": [ + "question posée", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· l’exécution vous attend" + ], + "02dfe6c63fd0b8a1": "Ajouter une raison", + "19abd94828a3bdbc": "Demander d’abord à l’agent", + "a18721fa8f328361": "Vous attendent", + "bbf24e7920c1e86b": "En cours", + "8d6e18d2ad832db6": "Toutes", + "f25af5332ffc3734": "Rien n’attend votre réponse.", + "c3f0119b8d6231f8": "Rien n’est en cours.", + "33028dfc1229eaa6": "Aucune exécution pour l’instant.", + "5459bf696a187c26": "Impossible de charger les exécutions de workflow", + "d57c35d43b0f163a": "Cette exécution n’est pas ici", + "b9aae2f7cdb1a379": "Aucune exécution de workflow pour l’instant", + "8f15f66e545af7c0": "Quelles exécutions", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "Les {count} workflows", + "46d614fa7b4bf1e5": "Exécutions de workflow", + "1c635faa2fb45b8b": "Pas encore exécuté.", + "156ff7b625287a1e": "Masquer les éléments ignorés", + "69b985b97ab45e6b": "Afficher {count} ignorés", + "2400254d362de84d": "Chargement des exécutions de workflow…", + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Un fichier de workflow présente un problème." + }, + " ", + "La dernière version valide continue de s’exécuter." + ], + "ed8ce6ebc73dc12d": "Ouvrir le fichier", + "145e1f7503ba3b2c": [ + "Cet environnement n’a aucune exécution avec ce lien.", + " ", + { + "t": "button", + "i": 1, + "c": "Retour aux exécutions" + } + ], + "783e616cb0476c17": [ + "Un workflow réunit agents, code, planifications et questions qui vous sont posées en une seule exécution qui survit aux redémarrages. Écrivez-en un dans", + " ", + { + "t": "button", + "i": 1, + "c": "Définitions" + }, + ", ou demandez-le à un agent.", + " ", + { + "t": "a", + "i": 2, + "c": "Lire le guide" + } + ], + "5d8d278ff828102d": "Tous les workflows", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · transcription", + "c512071143a5ba32": "Ce fil n’existe plus.", + "ed169d23683fb6ac": "Chargement du fil…", + "290e0ab40b87dc17": "Fil d’Ariane des workflows", + "683dd9831e54edc0": "Environnement", + "34ad53646f06ed80": "Les workflows sont désactivés", + "8f6589c9e0ac5d4e": "Aucun environnement connecté", + "744127f8dfad7d22": "Connectez un environnement pour voir ses exécutions de workflow.", + "036182ec7e2ee4d4": "À côté de l’exécution", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Définitions", + "f0a212aadfe1257b": "Chargement de l’éditeur…", + "20f194e003885e95": [ + "Activez-les pour ce serveur dans", + " ", + { + "t": "Link", + "i": 1, + "c": "Paramètres → Labs" + }, + "." + ], "8367779e149f723b": "La requête vers l’environnement principal a échoué pendant {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Jeton d’appairage non valide. Vérifiez le jeton et réessayez.", "0e4b49c8203aae81": "Délai dépassé en attendant la session authentifiée après l’amorçage.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 0c149c28fbe91..d95e55442ba73 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -52,6 +52,27 @@ "eb0f60ef4f92ab7d": "Forgejo または Gitea のサーバーごとに、{fjUrl} から {fj} 0.6 以降をインストールして {fjLogin} を実行するか、{teaUrl} から {tea} 0.16 以降をインストールして {teaLogin} を実行してください。", "d026a85e2e50e675": "{install} で GitCafe CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", "22d3c0c48a34b5b3": "{install} で TanStack Source CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", + "756c80ad262ef315": "元のスレッドで待機中", + "d8df14f9905f38eb": "送信済み", + "e7c59185f8ab3987": "未送信", + "b54ddec9084fa955": "送信せずに閉じました", + "fbaa7ab5da716e50": "不具合", + "01bac997ea55272e": "分かりにくい", + "0f53bc8f74dfe56a": "機能の不足", + "055560f307e15e30": "ドキュメントの誤り", + "78344b60f407928e": "その他", + "f653846a95cd6e8f": "種類", + "f41ea186c275b56e": "情報", + "2f6e4f7cd364da73": "期待した動作", + "9d11c93d4035de3e": "実際の動作", + "c87d0595693704f9": "代わりに行ったこと", + "d7a4ea6ce5af44e0": "{speaker} · {count} 文字", + "f5114fb9c40fd929": "あなた", + "cd03eb1b84271c02": "エージェント", + "bfe1a60f3f9c60fb": "ターン {turn} · {what}", + "dfdaa6255a416140": "{turns, plural, one {直近 {turns} ターン} other {直近 {turns} ターン}}の概要、{textTurns, plural, =0 {メッセージ本文なし} one {最後のターンのメッセージ本文} other {直近 {textTurns} ターンのメッセージ本文}}{truncated, select, yes {、収まる長さに短縮済み} other {}}", + "260c6b45f52d2f27": "直近 {textTurns} ターンでのあなたのメッセージとエージェントの返信の本文を追加します。", + "afac52a5cc2dc801": "回答を送信できませんでした。もう一度お試しください。", "79d776428f4d0650": "ファイルを読み込めませんでした。再接続してもう一度お試しください。", "3ea34cbb1ca5ba9b": "プレビューをキャンセルしました。", "7c0af279ecb3da3a": "このランタイムではファイルのストリーミングプレビューを利用できません。", @@ -118,9 +139,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 がありません。", @@ -246,6 +267,8 @@ "fec888c767b662d5": "リンクされた Issue を確認しようとしました", "bc31067af9c79d82": "{count, plural, other {リンクされた Issue を {count} 回確認しました}}", "c712fec8d9dc6dd6": "{count, plural, other {リンクされた Issue を {count} 回確認しようとしました}}", + "81c2282590e549f5": "{count, plural, one {Read terminals {count} time} other {Read terminals {count} times}}", + "79cd7c5c29ffa938": "{count, plural, one {Tried to read terminals {count} time} other {Tried to read terminals {count} times}}", "537feee59d775e17": "{count, plural, other {{count} 件の HTML ページをプレビューしました}}", "4b45ac8cb8df04a4": "{count, plural, other {{count} 件の HTML ページをプレビューしようとしました}}", "a6f62fca5dd25455": "{count, plural, other {{count} 件の HTML ページをレンダリングしました}}", @@ -376,6 +399,31 @@ "476ca970255eaea4": "公開 URL を使うには、この環境を T3 Connect にリンクしてください。", "6b80f5b38a8f9950": "このアドレスを呼び出せるのはこのコンピューターだけです。公開 URL を使うには T3 Connect をリンクしてください。", "c5a7b1d3891dd0b8": "この環境のアドレスに到達できる場所ならどこでも動作します (Tailscale や独自のプロキシ経由など)。公開 URL を使うには T3 Connect をリンクしてください。", + "3669395daf36fd33": "このサーバーにはもう登録されていません", + "fe513cf316e796e3": "他のワークフローの一部として実行", + "ccf00b97925efab3": "手動で開始", + "421e585eb092b07b": "{triggers} で開始", + "7bd7c58592671384": "要対応", + "834ca879c14c167b": "作業中", + "582d6df7dfab86fb": "一時停止中", + "ea6583ce92507ee3": "スリープ中", + "7ea8cb8af281ce93": "待機中", + "1347868f2523140e": "完了", + "57d76c4614054271": "停止", + "5c7344bd51d0b966": "スキップ", + "b2074e9bd23049a6": "キャンセル済み", + "5bb7401807ee2fb5": "質問: {question} ほか {more} 件", + "9e4286183d5f9e34": "質問: {question}", + "474c18d001bd6717": "ステップが失敗しました", + "d3890f4eb1508781": "自身のステップを実行中", + "3e7ced10c9482af0": "{step} が作業中", + "237e1bcb1cf1bdec": "{step} でスリープ中", + "3f7b17ac5a20c8d2": "{run} を実行", + "0306f5f324b8aaa5": "{count} 件の実行が進行中", + "e8fd779b84a202a2": "待機中", + "b6d55657e1a027b8": "{step} を待機中", + "e942562a42aede34": "完了", + "26b2b9727fe11289": "早期終了", "1bb995dcec481554": "{host} でこのデバイスを承認してください。コード {verificationCode} が表示されています。", "8696a33219944832": "WebSocket の認可証明を作成できませんでした。", "5678f133a8631f7d": "クラウドのサインインが変更されました。環境を認可するには、もう一度サインインしてください。", @@ -637,6 +685,9 @@ "fc2020db8a3804c0": "{host} は WebSocket 接続を確立できませんでした。", "d9ce6c142a485959": "{host} は {seconds} 秒間応答していません。", "d6bdce8f4e6101a4": "{host} の接続が切断されました。", + "8450a95e5214d199": "{host} から、このクライアントで読み取れないサーバー設定の更新が送信されました。", + "56b4ff3993c93eca": "{host} から互換性のないサーバー設定が送信されました。", + "368c4d4f99c66bfb": "クライアントとサーバーを互換性のあるバージョンに更新してください。", "e5fd422e445391fc": "アップロードに失敗しました。タップして再試行してください。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -1720,6 +1771,8 @@ "2e995206e087c3fc": "接続または保留中の入力が解決してから、返信してください。", "604ec3067171a0d7": "会話", "d6182a057ea12624": "親スレッド", + "f2d8537c33cc55a5": "ワークフロー実行のステップ", + "ba8337dca3232880": "実行を開く", "30fa4a764d11ae42": "{name} をダウンロードできませんでした", "4952f87dc98191a7": "添付ファイルを利用できません。", "2fd6d178493fb407": "現在のターンを中断できませんでした。", @@ -1784,6 +1837,8 @@ "181677cda4d3fd0a": "プロジェクトを追加できる接続済みの環境がありません", "3a0bf3d17f31584e": "{project} で新しいスレッド", "4b4b64cc95acb8da": "新しいスレッドの作成先...", + "2c45783ab9680fdb": "Open Git graph", + "e813386e62652710": "Open agent stage", "3f581e98c86df72a": "プロジェクトなしで新しいスレッド", "e510d9a7b684fbfe": "問題をトリアージ", "cce3d80a2ddf1125": "エージェントが T3 Code の問題を調査し、Issue の作成を手伝います", @@ -1805,6 +1860,7 @@ "04fd71efaa2c3b92": "プルリクエストを開く", "57e875b79b98ab82": "Issue を開く", "f1db0a234c777a1d": "他のアプリで T3 Code を使用 (MCP)", + "6050f22f63e2bcb5": "ワークフローを開く", "a0cc19e60dd99851": "使用量を開く", "46694969044eee98": "次のワークスペース領域にフォーカス", "0a1011328ba42eef": "前のワークスペース領域にフォーカス", @@ -2359,14 +2415,24 @@ "05037ca1666fd421": "ターミナルはプロジェクトのスレッドからのみ利用できます。", "a3aa1e49af278d41": "ファイルはプロジェクトが開いているときのみ利用できます。", "87ea6995ea1e7aa4": "差分は Git リポジトリ内のサーバースレッドでのみ利用できます。", + "80f10f5ea1804d8d": "The Git graph needs a Git repository on an up-to-date server.", "4a87cae01ccde544": "このスレッドのブランチにはまだプルリクエストがありません。", "32535dba0b9af642": "このスレッドにリンクされた項目はありません。", + "d955eee48dece3c0": "Enable the agent stage in Settings > General.", + "d2f2f6d05148f8a3": "Threads a coordinator runs have no thread overview.", + "26c1c05b0d1d98fd": "Turn on coordinator decisions in Settings > General.", + "486d4369c4fbec9e": "Notes are only available from a thread.", + "50b5a57d3bd6f6ef": "Instructions are only available from a thread.", + "007ab76950f73521": "Media is only available from a thread.", "07080dead70f4cc5": "デバイスはスレッドからのみ利用できます。", "a4bf49b31758ff7e": "デスクトップアプリでのみ利用できます。", "e917841cb66f9af1": "プロジェクトが開いているときに利用できます。", "14c15fad0c2ee0c8": "Git リポジトリで利用できます。", "9176276c78f3893f": "このブランチにはまだプルリクエストがありません。", "52ce9db6fb62a59f": "リンクされた項目はありません。", + "96c2ee76dd82d2cc": "Enable it in Settings > General.", + "2199013487151590": "Not for threads a coordinator runs.", + "f7a9300d9f9030d5": "Turn on coordinator decisions in Settings.", "e5d6f41e4fe4efd6": "スレッドから利用できます。", "0ebc2bb883a8e283": "最初のメッセージの後に利用できます。", "84d0ff8fb9846057": "タブのミュートを解除", @@ -2375,8 +2441,15 @@ "5c78a8ae7b71af1d": "ターミナル", "cba3e832ece50257": "ファイル", "83ac3423d6dfc4a7": "差分", + "016750bdd5076287": "Git graph", "da16af47eff38ae9": "プルリクエスト", "ad3929f0103925d7": "リンクされた項目", + "70e7b208e032024a": "Stage", + "0caf7e5748f1d17b": "Threads this one started, and which need you.", + "96018894225bd4ff": "Inbox", + "0ed16d7723c04288": "Decisions the coordinator asks you for.", + "aec2b493d2b01445": "Notes", + "9e92f6aa6edae875": "Notes and todos for this thread, its project, or everywhere.", "ac0de2a59d9c8860": "デバイス", "1354df9fb7278843": "iOS シミュレーターまたは Android エミュレーターを表示します。", "fdcd9643e2e63b15": "このスレッドの作業を続けたまま、別の質問をします。", @@ -2495,8 +2568,7 @@ "2d1c111e1b4ae0b0": "スレッド「{title}」を削除しますか?", "c568ab8dad798ec5": "このスレッドの会話履歴が完全に消去されます。", "0fd1c746a0e38003": "スレッドを削除できませんでした", - "0ecde875b0dd2f93": "プロジェクトでスレッドを絞り込み: {projects}", - "1ef65b647231ff0b": "プロジェクトでスレッドを絞り込み", + "1c8fc3c4a42949ab": "プロジェクト: {projects}", "165511761be2855c": "プロジェクトを検索", "a46a6467883575a4": "プロジェクトを検索...", "fdc0e086438a3045": "{project} のプロジェクト設定", @@ -2558,10 +2630,9 @@ }, " にインストール" ], + "b4b98a0287c282e2": "別のマシン上にあるため、このマシンのエージェントは読み取れません。削除するか、元に戻してから送信してください。", "5bbac0e5afeec779": "現在のスレッド", "33c7e68fca089036": "スレッド、{title}", - "b4b98a0287c282e2": "別のマシン上にあるため、このマシンのエージェントは読み取れません。削除するか、元に戻してから送信してください。", - "c6196d99000642b4": "スレッドを開く", "34cc63390ad793cc": "スレッドを選択", "8f12309ead62e38a": "スレッドまたはプロジェクトを検索...", "2f664754d005d9a7": "アクティブなスレッドが見つかりません。", @@ -2571,6 +2642,7 @@ "a3178769f8308cbc": "スレッドが失敗しました", "89b5e8f3887812da": "ゲストのリクエスト", "62e626804919b294": "入力が必要です", + "c6196d99000642b4": "スレッドを開く", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "あなた:", "a1fbf2422c588292": "エージェント:", @@ -2594,8 +2666,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "ターミナルのプロセスが実行中", "fc2c9a91f498ad6b": "{count, plural, other {{count} 個のターミナルプロセスが実行中。ターミナルを開く}}", - "643c4b50feadc874": "ワークツリー: {path} ({branch})", - "fb7c44da0f0825ea": "ワークツリー: {path}", "56f37ff8ca568059": "スタック", "6831e9a46cbd8939": "チェーン", "9aa9e74a3b7eee91": "チャットに追加", @@ -2684,8 +2754,6 @@ "78a04e0e625c0990": "更新に失敗しました", "c24de5eb69373a55": "この {build} ビルドは {track} のリリースを無視します。切り替えを完了するには、設定で更新トラックを確認してください。", "b02ae45a6109c93b": "最新の状態です", - "edcda9e8ee4ccad8": "更新 {version} をインストールして T3 Code を再起動しますか?\n\n実行中のタスクはすべて中断されます。準備ができていることを確認してから続行してください。", - "02eba0f7cc90f759": "更新をインストールして T3 Code を再起動しますか?\n\n実行中のタスクはすべて中断されます。準備ができていることを確認してから続行してください。", "9ed4d8a1531b9631": "このビルドでは自動更新を利用できません。", "c8c23435e780a60c": "更新を利用できません", "1af5f9767371ffd7": "更新を確認", @@ -3032,8 +3100,8 @@ "6f85f14f35b3f547": "{provider} ({environment} 経由)", "7c59a888a062a8bd": "音声入力を記録する下書きがありません。", "62450481c00d2ef3": "下書きの環境を利用できないため、文字起こしを整形できません。", - "c64cb58d9cecbcd2": "文字起こしの整形に失敗しました", "0674544195fcdc39": "元の文字起こしを追加しました。", + "c64cb58d9cecbcd2": "文字起こしの整形に失敗しました", "296496693cdac0db": "t3 コマンドを利用できません。", "efbcef7bc9bbda01": "t3 コマンドの状態を読み込めませんでした。", "1bf6910332426e62": "デスクトップのネットワークアクセスを利用できません。", @@ -3276,6 +3344,7 @@ "4d493d0bda4d403d": "中断されたファイルをもう一度添付するか、削除してください", "c9cad1d84d5f1a32": "中断されたファイルをもう一度添付するか、削除してください", "536a820f2ff726da": "モデルを少なくとも 1 つ選択してください。", + "48d6389202ad6754": "準備ができたら送信", "fbafbe78b5e37966": "スレッドを再開", "bcd7eb979dd38dae": "入力欄を開いて圧縮して送信", "95ee62a0d6968b89": "メッセージを送信", @@ -3450,6 +3519,9 @@ "e778e4f446fdf873": "次のメッセージで新しいセッションが始まります", "0e2f2da4f2d94785": "エージェントはこのスレッドの以前のメッセージを参照できません。", "e1189d2e582b008d": "現在のセッションを維持", + "2bb448d605877a22": "編集または Esc でキャンセル", + "1a1f128d70c62304": "{count, plural, other {画像の準備ができたら送信}}", + "5af3ab719a9725fb": "メッセージを送信中", "461c9f865f2e9b92": "{option} オン", "f2aa17b5c620f2a4": "{option} オフ", "f59314a884aae1ff": "デフォルト", @@ -3573,6 +3645,13 @@ "c53bc5a4b0314342": "次のメディア", "2950b1424a3cddf5": "この環境に再接続してから、もう一度メディアを開いてください。", "ef638bf1479a5461": "環境から無効なメディア URL が返されました。", + "3ccfbf7e86868c35": "T3 チームへのフィードバック", + "4e0710d19dfc2e7e": "このレポートを T3 チームに送信しますか?", + "87d0ae0723ba75d1": "この内容だけがこのマシンから送信されます。「送信」を押すまで何も送信されません。", + "bf19826f81484328": "会話を含める", + "ddb7e6f8ce99e657": "このマシンでエージェントを実行できる人だけが、送信または拒否できます。", + "03c1eb603c112f47": "送信しない", + "653405e4ed498d9f": "送信", "262955d6eb632f9b": "ゲストリンクをコピーする際にクリップボード API を利用できませんでした。", "f1a4f2b04cdbb4ef": "ゲストリンクをクリップボードにコピーできませんでした。", "cf3490a604e44d31": "ゲストリンクを作成できませんでした。", @@ -3593,7 +3672,6 @@ "abd89e9eefedf11b": "完了", "18d166056c1ab6ff": "共有を停止", "7a2d510eac9e4587": "ゲストリンクの期限が切れました", - "653405e4ed498d9f": "送信", "21888e302219891d": "拡大した {title} のプレビュー", "419719298a7acaea": "縮小", "ed8d5db95359cff4": "ズームをリセット", @@ -3688,7 +3766,6 @@ "7c1923203049d602": "コードをコピー", "637817e4ff79c90e": "コードブロックの操作", "ebf3a2b1e314aa5f": "ターミナルで実行", - "fe219642547fa0bf": "ターミナルで実行", "122a8512abc51180": "詳細", "58c38c65c2783c5d": "フルパス", "f37e7d36b51c5b28": "相対パスをコピー", @@ -3700,10 +3777,6 @@ "4967584e8d0fb1c2": "メディアをプレビュー", "67589dd912eacb7c": "統合ブラウザーで開く", "a3c98d4c4b24cecb": "{label} のファイルオプション", - "b4fe8a076e9fd2f8": "ディスプレイ数式", - "085d1407e8c92cce": "インライン数式", - "a2ef393fa7b48ae8": "ディスプレイ数式をスクロール", - "e94685ea5642e088": "インライン数式をスクロール", "3a04583c8500e23d": "図を表示", "16d64f650840fe06": "コードを表示", "6d329f7d3a50c7e7": "表をコピー", @@ -3975,9 +4048,11 @@ "973e99fa86d7f531": "キュー内のメッセージ {position}/{total}、未送信", "0f6087c4f53c7f17": "このメッセージでターンを開始 ({shortcut})", "adab89933af02669": "圧縮をスキップしてこのメッセージを送信 ({shortcut})", + "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", "3de4016452e8d2bd": "現在のターンに送信 ({shortcut})", "259cc9568148e8ad": "このメッセージでターンを開始", "bb7fddb812d5d29e": "圧縮をスキップしてこのメッセージを送信", + "425ab15036aec8a4": "このコマンドをキューの先頭に移動", "a5fe1ee609b29a9f": "現在のターンに送信", "2b7fd345e4f4fd6e": "キュー内のメッセージの編集をキャンセル", "47f1726bf106d2c8": "キュー内のメッセージを編集", @@ -5437,6 +5512,22 @@ "f0d79aa56f06663f": "このファイルは大きすぎて全体を表示できません。件数にはすべての変更が含まれます。", "7fdde2b893ba1b9d": "削除", "e58ce271d835b447": "追加", + "fb5c7ff5ea76e01a": "Added by esveo's fork. Click to list all of its settings.", + "352fa6aeb5d55665": "Trail the provider icon behind the thread title instead of giving it a line of its own. The line it saves also carried the branch, pull request badge and diff counts.", + "9d44fa03a230e0d8": "Reset two-line thread cards to default", + "7b216eedb1abe696": "Two-line thread cards", + "8d90fcd918e901c8": "Keep each project's threads together in the sidebar, under a header that folds the project away. Ordering stays by recency: the project with the newest thread leads.", + "d5dfd89c9a281386": "プロジェクトのグループ化をデフォルトにリセット", + "aac9f889c7ec7ff5": "Group sidebar threads by project", + "da375a07c5309184": "Show how full the thread's context window is next to the composer controls.", + "33f6b88cba203990": "Reset context window usage to default", + "6496f57baeded3fa": "Context window usage", + "d9c146dc6b95714d": "Show how many minutes are left before the prompt cache expires. Claude only.", + "69609e27c2107da5": "Reset prompt cache timer to default", + "a4917d2b93c478f6": "Prompt cache timer", + "ea8ebcb77e657e9f": "Open the thread details card with workspace and version control in every thread. Off, it stays closed until you open it, and each thread remembers your choice.", + "662288b90e19635f": "スレッドの詳細をデフォルトにリセット", + "92729a403d37c575": "Open thread details by default", "07b9970b662ab70d": "Mermaid のソースを表示", "5a422b7be35243f5": "レンダリングした図を表示", "c0628ad999cbbbf5": "Markdown のソースを表示", @@ -5543,6 +5634,7 @@ "723d88a5fa7e2fdd": "一致するファイルはありません。", "f8d6e9a1a2870a5c": "ファイルエクスプローラー", "109edd252917113b": "ファイルエクスプローラーのサイズを変更", + "7abd6af24fed7b60": "The file does not exist in the workspace or the home folder.", "37cbd2ecc659a007": "ファイル", "b5188f172f59ca79": "この接続ではホストのファイルを読み取れません。", "c3c5d36466ad2191": "プレビューブラウザーでファイルを開く", @@ -5582,7 +5674,6 @@ }, "。リンクのパスを確認するか、[ファイル] でファイルを探してください。" ], - "b9b6bbd1e1ea189f": "ファイル全体", "d715e9494fdbaaf6": "フォントを読み込めませんでした。", "ff17c777a72b4408": "フォントのプレビューは 10 MB までです。", "6bd41ad699e22f10": "フォントを利用できません。", @@ -5592,6 +5683,7 @@ "a9abaaa4220eae21": "{error} 別のアプリで開くには保存してください。", "c508c9000d9656f8": "フォントのプレビュー", "1c416d621d250be8": "いろはにほへと ちりぬるを わかよたれそ つねならむ", + "d7d08260f16b7828": "ファイルはまだ読み込み中です。少し待ってからもう一度お試しください。", "76ebb03de52c92d6": "テキストビューアーが停止しました。", "f48162e8e8c12af7": "テキストビューアーを読み込めませんでした。ファイルを閉じて、もう一度お試しください。", "bc4c5b13d38a5da7": "プレビューを閉じました。", @@ -5599,8 +5691,6 @@ "9450d1827ef336a1": "別のコピーが進行中です。", "8f48999eb6d9e2e3": "{count, plural, other {{formatted} 行}}", "13b14784f8707ddd": "0 バイト", - "f6e9581cba3467fa": "インデックスを作成しています…", - "2d1f293ac12463fc": "ファイルの残りを読み込んでいます…", "b75105bef8f564a4": "最初の 1,024 列を表示しています。ソースと保存ではすべての列が保持されます。", "2a6e1b1f209c3888": "このファイルは空です。", "192fc79eb3b5b2cb": "この図にはリソース URL、マークアップ、ノードのメタデータ、またはカスタム構成が含まれています。安全に確認するには Mermaid のソースを表示してください。", @@ -5787,7 +5877,6 @@ "0061fff77e36bd4f": "サーバーに接続できませんでした。", "04dfdd46e3dd4a2e": "問題が発生しました。もう一度お試しください。", "084bb2d8127a508d": "送信済み", - "e7c59185f8ab3987": "未送信", "77c01a15bd36d17c": "このリンクは終了したか、無効です", "e0e736810f3cbef2": "所有者に新しいリンクを依頼してください。各リンクは 1 つのブラウザーでのみ使用できます。", "c3c53aa46f7330e5": "このリンクは終了しました", @@ -5809,6 +5898,13 @@ "cbb2129c0dd4f40b": "添付ファイルの合計はメッセージあたり 10 MB までです。", "03b9cd79cfe0b435": "このファイルは添付できません。画像は PNG、JPEG、GIF、WebP のいずれかである必要があります。", "8ff29c78798e6ac1": "この項目を読み込めませんでした。", + "535923000a0f3e3b": "Send /compact to a large, idle Claude thread shortly before its 1-hour prompt cache expires, so the next message skips caching the whole conversation again. 5-minute caches are left alone.", + "bd8eb8f5f9843bc6": "Reset idle auto-compact to default", + "1db274eacf03c8de": "Auto-compact idle Claude threads", + "fb6643c75aafd996": "Between {min} and {max}; it has to fall inside the cache's hour.", + "48dee64ca7904281": "Minutes idle before auto-compact", + "8937fe924464eb70": "Smaller threads are cheap to cache again and keep their full history.", + "1981f1e1a753aabc": "Minimum context tokens for auto-compact", "94ab4591ce101233": "コメントを投稿できませんでした", "92d0d4eab2596772": "トラッカーが拒否しました。", "33591d9596fb7cb7": "コメントを追加", @@ -8651,12 +8747,16 @@ "58e0e226493150e7": "Issue トラッカーを読み込めませんでした", "77cfcbde543df32d": "{tracker} の詳細を切り替え", "0083f65885c60156": "{tracker} を切断", - "295392927d5c8a84": "各プロジェクトに {tracker} の {scope} を1つ以上選択します。その Issue はリポジトリ自身の Issue と並べて表示され、エージェントは最初の {scope} に新しい Issue を作成します。", + "ed83b25c71c98a20": "各プロジェクトに {tracker} の {scope} を1つ以上選択します。その Issue はリポジトリ自身の Issue と並べて表示され、エージェントは別の {scope} を指定されない限り、最初の {scope} に新しい Issue を作成します。", "19c2d5e81ff8f89a": "{project} の {tracker} {scope}", "68e061510b765772": "未バインド", + "99d51127f573296b": "別のアカウント", + "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。", + "99963c0142e17f00": "新しい {tracker} アカウント用です。", "a2d95d39d3398bda": "資格情報が拒否されました", "9eae463720500113": "サーバーに保存されています。", "b6e27ab2537ef874": "作成する", + "6d8e4ebc889bace9": "アカウントを追加", "13ef526271b0f5d4": "すべての条件をクリア", "d1938a629f039515": "条件を削除", "84a605b241ce65b7": "グループとその条件を削除", @@ -8786,6 +8886,12 @@ "d3866ead082d14e5": "キーボードショートカットを追加", "d4345c90894a3220": "keybindings.json を開く", "e56a8d51219efaa0": "検索に一致するキーボードショートカットはありません。", + "90a258fff61fd77e": "オフ", + "4060244a7079a0d2": "依頼したとき", + "e88c9d8769544731": "自動", + "f29d1dade4dde8aa": "エージェントは T3 チームにフィードバックを送信しません。", + "93c4c53562d30a98": "依頼すると、エージェントが T3 Code についての短いレポートを表示し、承認した場合に T3 チームへ送信します。", + "cd9ee803e8727017": "エージェントが自ら遭遇した T3 Code の問題も報告します。たとえば、T3 ツールの失敗などです。", "45fa271ea0e1ac8e": "ベータ", "3a678332fc7142f7": "サイドバーのスレッドをプロジェクトフォルダーにまとめます。ピン留めしたスレッドは上部に残り、スヌーズ中と対応済みはフォルダーの下に表示されます。", "e4e91d155cb6a9b4": "シンプルなサイドバー(プロジェクトでグループ化)", @@ -8794,11 +8900,16 @@ "9ae293971d93c819": "スレッドをゲストと共有します。ゲストはブラウザーでライブで閲覧し、あなたが承認したメッセージを送信できます。ゲストリンクを使うには T3 Connect にサインインしてください。", "0aa5406ac4d7f7c7": "ゲストリンク", "f0e853acd2006d53": "リンクされた環境", + "ef10c2dff987f3ea": "このサーバーの T3 ホームにある workflows フォルダーのファイルから、複数ステップのワークフローを実行します。コマンドパレットから開けます。オフの間はそのフォルダーの内容は実行されず、実行はオンに戻るまで待機します。", + "2dadb2359422121c": "ワークフロー", "13e86eb5d8287a71": "Claude または Codex のターンの後、空の入力欄に次のメッセージの予測を表示します。Tab で使用します。毎回、プランでキャッシュされたリクエストが 1 つ追加されます。Codex 0.165 以降が必要です。Claude のスレッドは再起動時に更新されます。", "d4b2a2ec812aafb0": "次のプロンプトを提案", "298c7150a7621c80": "Simlock デバイスホスト", "67937aa49179285e": "Mac では、すべてのファイルを書き込む代わりに、T3 ホームフォルダーにキャッシュしたチェックアウトから新しいワークツリーを複製します。できない場合は Git の通常のチェックアウトを使います。オフにするとキャッシュは削除されます。", "f9904f78d3003f58": "高速ワークツリーチェックアウト", + "9c2f647882522302": "選択したマシンでは、エージェントのフィードバックモードが異なります。", + "31bbf7bf8c0a5279": "エージェントのフィードバック", + "d52b3d6bf9f2a013": "混在", "ec7623deed751c05": [ "スレッドをゲストと共有します。ゲストはブラウザーでライブで閲覧し、あなたが承認したメッセージを送信できます。T3 Connect が必要です。サインインして、", " ", @@ -8882,7 +8993,9 @@ "fb71127e5746a6bc": "リンク先の「共有とアクセス」、または t3 pair から", "1e3fee7084791773": "{target} から {source} へも逆方向にリンクする", "ea34a190b0bd804c": "{target} のエージェントも {source} で作業できるようになります。", - "ad5ed0ce61b966eb": "{label} を削除しますか?ここのエージェントはそこで作業できなくなります。そこでのセッションも終了するには、{label} の「共有とアクセス」で \"T3 Code · …\" を取り消してください。", + "974f8c65e8b5f492": "{label} を削除しますか?ここのエージェントはそこで作業できなくなり、{label} が応答すればそこでのセッションも終了します。", + "6cf9e3083b15614f": "{label} が応答しませんでした", + "34ccbdf619b83be3": "そこでのセッションも終了するには、{label} の「共有とアクセス」で \"T3 Code · …\" を取り消してください。", "81c9796bf61b306a": "リンクを削除できませんでした", "130e51beb6cf5aad": "環境をリンク", "122c3e355699e69d": "これで、ここのエージェントがそこでスレッドを起動し、メッセージを送り、完了を待てるようになります。リンクはその環境の「共有とアクセス」の「承認済みクライアント」に表示され、そこで取り消せます。", @@ -9112,7 +9225,6 @@ "0b4779a1825c85bc": "サイドバーとスレッド一覧に表示される、このプロジェクトグループの共通の名前です。", "f68cbda4df83d739": "プロジェクト名をデフォルトにリセット", "56e37b85027e8431": "プロジェクトのアイコン", - "e88c9d8769544731": "自動", "c99736317da5b1fa": "プロジェクトのアイコンをデフォルトにリセット", "6afaa3e3739dc570": "プロジェクトのアイコンを選択", "51651ce45d481a20": "プロジェクトのアイコンファイルを選択", @@ -10017,7 +10129,6 @@ "53de7aafe0afc10d": "テーマの設定を元に戻せませんでした", "006bfa1846fe5dd2": "自動的に対応済みにするまでの非アクティブ日数", "d9b0fbd680d5f175": "サイドバー", - "d5dfd89c9a281386": "プロジェクトのグループ化をデフォルトにリセット", "cd5452cc9e13c818": "プロジェクトのグループ化", "cfb01b8a2a3361fb": "プロジェクトの並び順をデフォルトにリセット", "26abcbe322049a8a": "「作業中」セクションをデフォルトにリセット", @@ -10082,7 +10193,6 @@ "16bdc70b858c223f": "自動で開くパネルをデフォルトにリセット", "c5424f09d77138ff": "200,000 トークンを超えるアイドル状態の Claude スレッドを圧縮するタイミングです。戻ってきた後、プロンプトキャッシュの有効期限の直前、またはしない、から選びます。Claude プロバイダーごとに上書きできます。", "3e99c5c14f4939c8": "「アイドル状態のスレッドを圧縮」をデフォルトにリセット", - "d52b3d6bf9f2a013": "混在", "cd72fe451ba0d6aa": "新しいプロジェクト", "394c3bd0a1782c8e": "空のままにすると、「プロジェクトを追加」のブラウザーを開いたときに \"~/\" を使用します。", "f9b912a818bd869d": "プロジェクト追加のベースディレクトリをデフォルトにリセット", @@ -10982,7 +11092,6 @@ "4a237f41ce592b7f": "このプロジェクトのワークツリーは、手動で削除するまで保持します。", "00b8ffd8ea6e6a93": "このプロジェクトでこれらのルールを使用します。", "72c279824d15a999": "各マシンのワークツリーのクリーンアップ設定を使用します。", - "90a258fff61fd77e": "オフ", "b5702d0b64866b08": "カスタム", "c009c901f3eefe78": "削除したスレッドのワークツリーを削除", "431c7cd6d50102b7": "アクティブまたはアーカイブ済みのスレッドを削除したときに、使われていないワークツリーを削除します。ローカルの変更があるワークツリーは保持されます。", @@ -11339,7 +11448,6 @@ "f2043e87a10cb831": "テーマを編集", "595bdeefcdc9bf31": "テーマファイルをエクスポート", "b480281b3791b685": "スレッドの詳細カードに表示する項目を選択します。カードを右クリックしても選択できます。", - "662288b90e19635f": "スレッドの詳細をデフォルトにリセット", "871d059d88548434": "スレッドの詳細: {total} 個中 {enabled} 個がオン", "cec1fbb8b4c9180d": [ { @@ -11678,7 +11786,6 @@ "4c70e3e7b3e6c493": "シークレット", "79b768229c9ef672": "メンテナンス", "54b188d65247e42f": "試験的機能", - "f41ea186c275b56e": "情報", "af4b7734da1d5ce7": "音声", "4ec62c39ca3192bf": "ソース管理と Issue", "f2bf529f85e05494": "共有とアクセス", @@ -11707,11 +11814,17 @@ "8f5966eebd2b110f": "外観 色 パレット カスタム インポート appearance colors theme", "633ed64e952cca3b": "色 境界線 インターフェイス colors borders", "9cf8308531b4ff31": "透明 透過 不透明 メニュー ダイアログ 入力欄 transparency", + "d99bfbc557fae743": "Notion", + "89df56091835b3a6": "notion integration secret pages links viewer connect token ntn", + "d699adcc04d4d4ab": "sidebar compact row height branch provider icon diff pull request", + "9b9df5ba41c4a8e2": "Group threads by project", + "0ed2eab2c1953531": "sidebar project folder runs grouping collapse header repository", "d8d6cfd630cff22d": "赤 緑 青 オレンジ 追加 削除 変更 件数 パレット 色覚 colorblind", "717e49895cfee1c7": "幅 全幅 列 レイアウト メッセージ 入力欄 モニター wide width", "88365077fd80787b": "カスタマイズ 表示 非表示 パネル カード 環境 エディター スクリプト ブランチ プルリクエスト Git 変更 サーバー オートメーション 系譜 使用量 上限 5 時間 週間 クォータ トークン コンテキストウィンドウ panel card", "d561f74efa5f3920": "推論レベル 思考 バー グラフ 単語 ラベル レベル 入力欄 reasoning effort", "6113c17109ee0d57": "LaTeX TeX KaTeX 数式 方程式 Markdown latex math", + "dfe7ead48efc3f5a": "thread details card panel workspace version control closed collapsed hide", "8c8364d44fa28d22": "dev nightly latest チャンネル アートワーク ピル ラベル 非表示 なし channel", "2d90635156dfcb5a": "タイポグラフィ フォント ファミリー サイズ システム サンセリフ font", "d32e93777e4819c8": "タイポグラフィ フォント ファミリー サイズ 入力欄 入力 font", @@ -11733,6 +11846,7 @@ "d443390c4d2dcfd4": "アクセシビリティ a11y スクリーンリーダー NVDA JAWS VoiceOver Orca ナレーター ウィンドウタイトル タブタイトル Alt+Tab タスクバー スレッド ステータス 順序 作業中 承認 accessibility", "6826fa9579c22035": "ベータ 共有 ゲスト 招待 リンク チームメイト 閲覧 T3 Connect トンネル beta share guest", "f10c06cba0cdf7fe": "ベータ リンク 別のマシン VPS ピア エージェント そこで作業 委任 beta link machine", + "bc0b409d89ce086e": "ベータ ワークフロー 永続 実行 自動化 ステップ スケジュール webhook フォルダー beta workflow", "4a21cf825a2045b0": "ベータ Tab 補完 次のメッセージを予測 Claude Codex ゴーストテキスト autocomplete", "fea2dc36585c4a20": "Simlock デバイスホスト (アルファ版)", "9d834d178130180e": "ベータ アルファ simlock callstack シミュレーター エミュレーター iOS Android プール リース ゲートウェイ simulator", @@ -11774,7 +11888,29 @@ "34d74827c2a8b009": "Enter Return Command Ctrl 複数行 プロンプト 改行 入力欄 shortcut", "9d1013084c46ecce": "キュー 軌道修正 実行中 ターン 送信 デフォルト 動作 入力欄 queue steer", "e5e7f5e1fb1f2e4c": "サブエージェント サイドチャット リンクされたスレッド クリック 右パネル サイドパネル メインビュー コマンド ctrl 中クリック", + "5c59d7e2673267ea": "composer tokens usage meter percentage compaction", + "e0d6ec10218b714e": "composer claude cache ttl expire minutes warm cold tokens", + "ce0952668aba4140": "Agent stage", + "f637899f994b78c3": "sprites stations subagents thinking editing terminal right panel everything", + "9d9d3374ee961b91": "Easter eggs", + "571180dbfeddbfd5": "surprise fun rocket animation message send hidden", + "0716adb0d55ffa58": "Voice calls", + "027d8f5ea5555973": "voice call phone gpt live feature flag anruf telefon schalter", + "60d509bb55e2967c": "Voice call voice", + "0e5f5c5ebf026abd": "voice call phone gpt live speaker stimme anruf telefon", + "266f1e2b55e419b0": "Voice call follow-up", + "392226d9bed6fe21": "voice call queue steer follow-up warteschlange anruf", "5b8b854de7ee6f4d": "インストール済み CLI バージョン 新しい 利用可能 Codex Claude Cursor Grok fx Kiro OpenCode update", + "1ceaab7d898b689a": "Child threads in the sidebar", + "fa5a42a73d1c1ece": "coordinator subthreads nested group expand sidebar orchestration children", + "6a1072050d1ad19e": "Coordinator decisions", + "474ba8e025886f86": "inbox questions answers decide approve coordinator open items", + "8f5558f063214509": "Cross-project threads", + "b809e3ffa5178b88": "agents coordinator other projects read message start threads repositories", + "44207b47d209f601": "compact context prompt cache idle claude tokens cost expire", + "396a2cc5b442e359": "compact idle minutes prompt cache ttl", + "6d9520a9cbd70c2f": "Minimum context for auto-compact", + "2fe046cc1e0d0d4a": "compact context tokens threshold size", "64f12530d55d2ad1": "再開 実行中 アクティブ 中断 作業 再起動 マシン クラッシュ デスクトップ 更新 自動 resume", "214a98497c4ed05d": "caffeinate スリープ 防止 スリープしない 電源 ノートパソコン 蓋 inhibit sleep", "00469926c7027e2d": "バランス パフォーマンス バッテリー節約 詳細 Git フェッチ プロバイダー ヘルス 更新 ホスト 電源 モニター アイドル ポリシー battery", @@ -11804,6 +11940,7 @@ "901a823214edc8c4": "テレメトリー 分析 使用状況データ トラッキング 法的事項 オプトアウト telemetry", "82136480255a5106": "OTel OTLP テレメトリー エクスポート エンドポイント ログ トレース メトリクス Grafana", "659d081051faf7ff": "ログ トレース プロセス リソース履歴 失敗 スパン CPU メモリ diagnostics", + "5eaeacfa9f82051a": "報告 不具合 問題 t3 チーム 送信 フィードバック エージェント ツール 自動 依頼したとき", "f537f91e1ee41d47": "キーボードショートカット ホットキー コマンド キーバインド JSON keybindings", "1ba01e7ceed64b95": "ウィンドウ キャプチャ スクリーンショット window capture", "279b1cceb779ff38": "アプリのテキストを含める", @@ -12009,6 +12146,8 @@ }, " の変更内容" ], + "643c4b50feadc874": "Worktree: {path} ({branch})", + "fb7c44da0f0825ea": "Worktree: {path}", "e7f35f60e6229cf5": "デスクトップアプリ", "77be1b7e2a1d3d31": "{count, plural, other {{count} 台のマシンを更新しますか?}}", "e4892b21e88abb60": "{count, plural, other {{count} 件のプロバイダーの更新}}", @@ -12072,6 +12211,25 @@ "ffaa75d2db1e7cc1": "更新は適用されませんでした", "626bcbe04dc55f93": "T3 Code はまだ {current} です。更新ボタンからもう一度 {version} をインストールしてください。", "49214c047fbb1606": "プロバイダーの更新が中断されました", + "a135af0f1efda8de": "Cross-project", + "6e9798372b3fb922": "Coordinators put the questions they need you to decide into an Inbox tab beside the chat, instead of numbering them in their messages. Running sessions pick up a change.", + "7a5292a1705defec": "Reset coordinator decisions to default", + "9e3ff0f05f52b724": "Let agents read, message and start threads in other projects of this environment. Running sessions pick up a change.", + "384695cdd7ab6b54": "Reset cross-project threads to default", + "5a6c243a03eeca0c": "Choose a coordinator", + "f527bb5b4ad333da": "Coordinator for \"{title}\"…", + "6beb2db2a7b5edae": "Could not assign the thread", + "4ebb0c90c45690c0": "Could not detach the thread", + "73ac4f532306bea6": [ + "Assign \"", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "\" to a coordinator" + ], + "1871eb35b1ca5d41": "No thread can coordinate this one.", "52adbc863aeb5e59": "コピーできませんでした", "0944728904d886d2": "{label} の彩度と明度", "dded2cb4e4d26338": "{label} の彩度", @@ -12273,7 +12431,6 @@ "0bd41ff995d36a66": "キャッシュの読み取り", "3f0dfe0cb15a3272": "キャッシュの書き込み", "1c9d860be42b1c02": "出力", - "78344b60f407928e": "その他", "684e516076de81fe": "標準", "3bbcc1b826fef537": "高速", "66796576034c18ea": "超高速", @@ -12289,6 +12446,262 @@ "2cddd6095abc734a": "7 日間", "53493056306708cf": "30 日間", "c719359d18d37ad3": "90 日間", + "a7ad3167ca62e7de": "Talk to your agents by voice with GPT-Live on your Codex ChatGPT login. Turning this off ends a running call.", + "9f0e45a1d67187cd": "Reset voice calls to default", + "da0ae8174ac2fc14": "Queue what you say in a voice call while the agent runs, or steer the current run. Saying otherwise overrides it for one message. A change applies from the next call.", + "fb0a2aa3b08a17c4": "Reset voice call follow-up to default", + "66936cae56d1d749": "Queue", + "89bf6f658c44cb1b": "Steer", + "930a28582d2c103f": "The voice that talks to you in a voice call. A change applies from the next call.", + "591a53f319b0d343": "Reset voice call voice to default", + "0bd950151ddc6407": "保存せずに移動しますか?このファイルへの変更は失われます。", + "c0ba3f6756b09f30": "未保存の変更", + "6914e22d357f0ad6": "保存済み、実行中", + "aff389354a031d6f": "ディスク上のファイルを読み込めません。正常に読み込めた最後のバージョンが引き続き実行されます。", + "858effde748ab563": "保存しましたが、まだ実行されていません。", + "ddb37138df660942": "保存されませんでした。サーバー上では何も変更されていません。", + "6ef4db489e40e39e": "保存できませんでした", + "c89624a2e9af1793": "{name} は接続されていません", + "b5a352a43adb4c17": "再接続するとワークフローがまた表示されます。別の環境を選ぶと、その実行を確認できます。", + "3dcedb736d20aae5": "ワークフローファイルを読み取れませんでした", + "b09f4df8d76ae8ea": "{file} を削除しますか?このファイルで定義されたワークフローは開始できなくなります。", + "b4535f5a03689d27": "{name} は接続されていません。ここに書いた内容は残り、再接続後に保存できます。", + "b54c78d85fd942ea": "削除しましたが、実行中の内容はまだ反映されていません。", + "407c228d7da0b7df": "削除されませんでした。サーバー上では何も変更されていません。", + "1a6aa10f3cc14fff": "これらのファイルは互いに整合しません。以前のものが引き続き実行されます。", + "259312516a1dbe6f": "ファイル名", + "2f48ab2aa0586853": "ワークフローの定義なし", + "ba5adfa37b55b8c5": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 行目:" + ], + "d94eb9ab3201b641": "削除", + "84c900d1ae72adc6": "保存", + "5912d817be03247a": "編集中にディスク上のファイルが変更されました。保存するとその変更が上書きされます。", + "0b1e6f5608826387": "ファイルを読み込んで自分の変更を破棄", + "f47b4c06aeb77c1c": "ワークフローファイルを読み込んでいます…", + "4353bfd401d58f87": [ + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "内のすべてのファイルがワークフローを定義します。変更は再起動なしで反映されます。" + ], + "0c165251a06f10f1": "新しいファイル", + "8e97cf734b4463e7": "作成", + "2ec0d5108fd6cebe": "ワークフローはまだありません。ここで最初のファイルを作成するか、エージェントにそのフォルダーへ作成するよう依頼してください。", + "5601350626e8cfe9": "読み込めません", + "21d778a1b9a0c234": "実行の横で開いているもの", + "62dc4d3a19ff7ca0": "タブを閉じる", + "1e25265f2758fce3": "通常のスレッドとして開く", + "672a3dae06b39402": "専用のページで開く", + "7755500a4cde5066": "ペインを閉じる", + "b8dcbc93a2ca1861": "この実行には含まれなくなりました。", + "115c69de3202f664": "開く", + "644eafa9048b62df": "{count, plural, =1 {1 回目の試行} =2 {2 回目の試行} =3 {3 回目の試行} other {{count} 回目の試行}}", + "e39f89c909df4db0": "実行を再開できませんでした", + "865f034346b82f47": "{title} をキャンセルしますか?エージェントは停止し、この実行は再開できなくなります。", + "6bc75632fd9c9136": "実行をキャンセルできませんでした", + "64e50329dcfdd5b0": "完了", + "350162e7cc1ebea4": "停止", + "0875cf506f4c6810": "スキップ", + "3cc43f1dbf3f8e0c": "キャンセル済み", + "ded70e75de6404ba": "実行一覧に戻る", + "2f4ed7dbd22be30d": "実行をキャンセル", + "614e5ad58a795fb5": "停止", + "04b050b0329f0ac8": "所要時間 {duration}", + "aff78e1774818ff4": "{duration} 経過", + "38eddd466439afc9": "この実行が扱ったもの", + "156ec271d49ddd70": "経過", + "34f59bbbead0b97f": "{names} ほか {count} 件", + "ac1556f6ce89a5ea": "{count} 件を並行", + "e197c4963bacc746": "{count} 件実行中", + "f5319ed9e18c0df1": "あなたへの質問", + "882a25e9084ae1b2": "一時停止中", + "9a03d8a9afc60387": "これまでのステップ", + "2f2ae791afe01674": "承認待ち", + "24f8060c4ccdf928": "開始中", + "30a5be40eb956663": "作業中", + "dd7a1e58c2553933": "{duration} 後にスリープ解除", + "95cc952724dd7310": "まもなくスリープ解除", + "3cc34921c0128593": "実行中", + "e777db2880f53a46": "回答なし", + "dc90739d391a5e67": "あなたの回答: {choice}", + "389f2563b5b763fd": "短いステップ", + "a41c8d758121ad81": "スリープ", + "9db248b770096984": "待機", + "c76124517af28686": "{duration} 実行中", + "89102905bf09b0e8": "ライブで見る", + "bdf338cdff4118f0": "トランスクリプト", + "811e7e992f9ff820": "ワークフローのバージョンが再登録されるまで続行できません", + "4d4cdf035e98dd57": "手動での再開待ち", + "eb5b21dd224a5941": "{duration} 後に自動で再試行", + "6ab3dfa749fde477": "まもなく自動で再試行", + "44b6463aa70aa14c": "一時停止の理由", + "cf25e7169ab0eb7a": "{step} で一時停止中", + "56c48c1f220f2754": "質問に回答できませんでした", + "a3c43735e1a81498": "{title} の理由", + "bfad234f016cfa3f": "理由を一文で。どの回答を選んでも一緒に送信されます。", + "004c41aff9c97873": "実行", + "4dc0c244a2419f6c": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " の一部" + ], + "8c303e8335acb135": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "に開始" + ], + "8bffb377e2a6a7de": "そのバージョンはもう登録されていません", + "f92d9132f7b85d1a": "ステップを読み込んでいます…", + "6ebc59f64c761a49": "まだ何もありません。", + "a759dccd157d7dae": [ + "あなたの回答: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + } + ], + "593b425188346781": [ + "あなたの回答: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "実行を開く", + "c8eb9be36d4d51ad": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 上のスレッド" + ], + "3d9761e81798fcd8": "再開", + "8cebd63fc4c967d5": "失敗したステップだけが再実行されます。それより前に完了したものは保持されます。", + "bc1e0a2a0f1e9552": "要対応", + "a812f51e970740f1": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "に質問", + " ", + "· 実行はあなたの回答を待っています" + ], + "02dfe6c63fd0b8a1": "理由を追加", + "19abd94828a3bdbc": "先にエージェントに質問", + "a18721fa8f328361": "要対応", + "bbf24e7920c1e86b": "実行中", + "8d6e18d2ad832db6": "すべて", + "f25af5332ffc3734": "対応待ちのものはありません。", + "c3f0119b8d6231f8": "実行中のものはありません。", + "33028dfc1229eaa6": "実行はまだありません。", + "5459bf696a187c26": "ワークフローの実行を読み込めませんでした", + "d57c35d43b0f163a": "この実行はここにありません", + "b9aae2f7cdb1a379": "ワークフローの実行はまだありません", + "8f15f66e545af7c0": "表示する実行", + "b6409289e0c9a4dd": "ワークフロー", + "035cb02ca1ae4952": "すべてのワークフロー ({count} 件)", + "46d614fa7b4bf1e5": "ワークフローの実行", + "1c635faa2fb45b8b": "まだ実行されていません。", + "156ff7b625287a1e": "スキップ済みを非表示", + "69b985b97ab45e6b": "スキップ済み {count} 件を表示", + "2400254d362de84d": "ワークフローの実行を読み込んでいます…", + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "ワークフローファイルに問題があります。" + }, + " ", + "正常に読み込めた最後のバージョンが引き続き実行されます。" + ], + "ed8ce6ebc73dc12d": "ファイルを開く", + "145e1f7503ba3b2c": [ + "この環境には、そのリンクの実行はありません。", + " ", + { + "t": "button", + "i": 1, + "c": "実行一覧に戻る" + } + ], + "783e616cb0476c17": [ + "ワークフローは、エージェント、コード、スケジュール、あなたへの質問を、再起動後も継続する 1 つの実行にまとめます。", + { + "t": "button", + "i": 1, + "c": "定義" + }, + " ", + "で作成するか、エージェントに依頼してください。", + " ", + { + "t": "a", + "i": 2, + "c": "ガイドを読む" + } + ], + "5d8d278ff828102d": "すべてのワークフロー", + "39459da07479f482": "エージェント", + "7741243632056b81": "{step} · トランスクリプト", + "c512071143a5ba32": "このスレッドはもう存在しません。", + "ed169d23683fb6ac": "スレッドを読み込んでいます…", + "290e0ab40b87dc17": "ワークフローのパンくずリスト", + "683dd9831e54edc0": "環境", + "34ad53646f06ed80": "ワークフローはオフです", + "8f6589c9e0ac5d4e": "接続されている環境がありません", + "744127f8dfad7d22": "環境を接続すると、そのワークフローの実行が表示されます。", + "036182ec7e2ee4d4": "実行の横", + "2d6107cb78382d08": "ワークフロー", + "16f7df687349b399": "定義", + "f0a212aadfe1257b": "エディターを読み込んでいます…", + "20f194e003885e95": [ + "このサーバーの", + " ", + { + "t": "Link", + "i": 1, + "c": "設定 → Labs" + }, + " でオンにしてください。" + ], "8367779e149f723b": "プライマリ環境へのリクエストが {operation} 中に失敗しました (HTTP {status})。", "c5cd027743a2b5a6": "ペアリングトークンが無効です。トークンを確認して、もう一度お試しください。", "0e4b49c8203aae81": "ブートストラップ後、認証済みセッションの待機がタイムアウトしました。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c01191b387b4f..a0ca579192907 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -52,6 +52,27 @@ "eb0f60ef4f92ab7d": "{fjUrl}에서 {fj} 0.6 이상을 설치하고 {fjLogin}을(를) 실행하거나, {teaUrl}에서 {tea} 0.16 이상을 설치하고 Forgejo 또는 Gitea 서버마다 {teaLogin}을(를) 실행하세요.", "d026a85e2e50e675": "{install}로 GitCafe CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", "22d3c0c48a34b5b3": "{install}로 TanStack Source CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", + "756c80ad262ef315": "원래 스레드에서 대기 중", + "d8df14f9905f38eb": "보냄", + "e7c59185f8ab3987": "보내지 않음", + "b54ddec9084fa955": "보내지 않고 닫음", + "fbaa7ab5da716e50": "버그", + "01bac997ea55272e": "이해하기 어려움", + "0f53bc8f74dfe56a": "기능 부족", + "055560f307e15e30": "잘못된 문서", + "78344b60f407928e": "기타", + "f653846a95cd6e8f": "유형", + "f41ea186c275b56e": "정보", + "2f6e4f7cd364da73": "기대한 동작", + "9d11c93d4035de3e": "실제 동작", + "c87d0595693704f9": "대신 한 일", + "d7a4ea6ce5af44e0": "{speaker} · {count}자", + "f5114fb9c40fd929": "나", + "cd03eb1b84271c02": "에이전트", + "bfe1a60f3f9c60fb": "턴 {turn} · {what}", + "dfdaa6255a416140": "{turns, plural, one {최근 {turns}개 턴} other {최근 {turns}개 턴}}의 개요, {textTurns, plural, =0 {메시지 본문 없음} one {마지막 턴의 메시지 본문} other {최근 {textTurns}개 턴의 메시지 본문}}{truncated, select, yes {, 길이에 맞게 줄임} other {}}", + "260c6b45f52d2f27": "최근 {textTurns}개 턴에서 내 메시지와 에이전트 답변의 본문을 추가합니다.", + "afac52a5cc2dc801": "답변을 보내지 못했습니다. 다시 시도하세요.", "79d776428f4d0650": "파일을 불러올 수 없습니다. 다시 연결한 뒤 시도하세요.", "3ea34cbb1ca5ba9b": "미리 보기가 취소되었습니다.", "7c0af279ecb3da3a": "이 런타임에서는 스트리밍 파일 미리 보기를 사용할 수 없습니다.", @@ -118,9 +139,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이 없습니다.", @@ -246,6 +267,8 @@ "fec888c767b662d5": "연결된 이슈 확인 시도함", "bc31067af9c79d82": "{count, plural, other {연결된 이슈 {count}회 확인함}}", "c712fec8d9dc6dd6": "{count, plural, other {연결된 이슈 {count}회 확인 시도함}}", + "81c2282590e549f5": "{count, plural, one {Read terminals {count} time} other {Read terminals {count} times}}", + "79cd7c5c29ffa938": "{count, plural, one {Tried to read terminals {count} time} other {Tried to read terminals {count} times}}", "537feee59d775e17": "{count, plural, other {HTML 페이지 {count}개를 미리 봄}}", "4b45ac8cb8df04a4": "{count, plural, other {HTML 페이지 {count}개 미리 보기 시도함}}", "a6f62fca5dd25455": "{count, plural, other {HTML 페이지 {count}개를 렌더링함}}", @@ -376,6 +399,31 @@ "476ca970255eaea4": "공개 URL을 사용하려면 이 환경을 T3 Connect에 연결하세요.", "6b80f5b38a8f9950": "이 컴퓨터에서만 이 주소를 호출할 수 있습니다. 공개 URL을 사용하려면 T3 Connect를 연결하세요.", "c5a7b1d3891dd0b8": "Tailscale이나 자체 프록시처럼 이 환경의 주소에 접근할 수 있는 곳이면 어디서든 작동합니다. 공개 URL을 사용하려면 T3 Connect를 연결하세요.", + "3669395daf36fd33": "이 서버에 더 이상 등록되어 있지 않음", + "fe513cf316e796e3": "다른 워크플로의 일부로 실행", + "ccf00b97925efab3": "수동으로 시작", + "421e585eb092b07b": "{triggers}에서 시작", + "7bd7c58592671384": "확인 필요", + "834ca879c14c167b": "작업 중", + "582d6df7dfab86fb": "일시 중지됨", + "ea6583ce92507ee3": "슬립 중", + "7ea8cb8af281ce93": "대기 중", + "1347868f2523140e": "완료", + "57d76c4614054271": "중지됨", + "5c7344bd51d0b966": "건너뜀", + "b2074e9bd23049a6": "취소됨", + "5bb7401807ee2fb5": "질문: {question} 외 {more}개", + "9e4286183d5f9e34": "질문: {question}", + "474c18d001bd6717": "단계 실패", + "d3890f4eb1508781": "자체 단계 실행 중", + "3e7ced10c9482af0": "{step} 작업 중", + "237e1bcb1cf1bdec": "{step}에서 슬립 중", + "3f7b17ac5a20c8d2": "{run} 실행", + "0306f5f324b8aaa5": "실행 {count}개 진행 중", + "e8fd779b84a202a2": "대기 중", + "b6d55657e1a027b8": "{step} 대기 중", + "e942562a42aede34": "완료", + "26b2b9727fe11289": "조기 종료", "1bb995dcec481554": "{host}에서 이 기기를 승인하세요. 코드 {verificationCode}이(가) 표시됩니다.", "8696a33219944832": "WebSocket 인증 증명을 만들 수 없습니다.", "5678f133a8631f7d": "클라우드 로그인이 변경되었습니다. 환경을 인증하려면 다시 로그인하세요.", @@ -637,6 +685,9 @@ "fc2020db8a3804c0": "{host}에서 WebSocket 연결을 설정할 수 없습니다.", "d9ce6c142a485959": "{host}이(가) {seconds}초 동안 응답하지 않습니다.", "d6bdce8f4e6101a4": "{host} 연결이 끊어졌습니다.", + "8450a95e5214d199": "{host}에서 이 클라이언트가 읽을 수 없는 서버 구성 업데이트를 보냈습니다.", + "56b4ff3993c93eca": "{host}에서 호환되지 않는 서버 구성을 보냈습니다.", + "368c4d4f99c66bfb": "클라이언트와 서버를 호환되는 버전으로 업데이트하세요.", "e5fd422e445391fc": "업로드에 실패했습니다. 탭하여 다시 시도하세요.", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", @@ -1720,6 +1771,8 @@ "2e995206e087c3fc": "연결 또는 대기 중인 입력이 해결된 후 답장해 보세요.", "604ec3067171a0d7": "대화", "d6182a057ea12624": "상위 스레드", + "f2d8537c33cc55a5": "워크플로 실행의 단계", + "ba8337dca3232880": "실행 열기", "30fa4a764d11ae42": "{name}을(를) 다운로드할 수 없습니다", "4952f87dc98191a7": "첨부 파일을 사용할 수 없습니다.", "2fd6d178493fb407": "현재 턴을 중단하지 못했습니다.", @@ -1784,6 +1837,8 @@ "181677cda4d3fd0a": "프로젝트를 추가할 수 있는 연결된 환경이 없습니다", "3a0bf3d17f31584e": "{project}에서 새 스레드", "4b4b64cc95acb8da": "다음에서 새 스레드...", + "2c45783ab9680fdb": "Open Git graph", + "e813386e62652710": "Open agent stage", "3f581e98c86df72a": "프로젝트 없이 새 스레드", "e510d9a7b684fbfe": "이슈 분류", "cce3d80a2ddf1125": "에이전트가 T3 Code 문제를 조사하고 이슈 작성을 돕습니다", @@ -1805,6 +1860,7 @@ "04fd71efaa2c3b92": "풀 리퀘스트 열기", "57e875b79b98ab82": "이슈 열기", "f1db0a234c777a1d": "다른 앱에서 T3 Code 사용(MCP)", + "6050f22f63e2bcb5": "워크플로 열기", "a0cc19e60dd99851": "사용량 열기", "46694969044eee98": "다음 작업 영역으로 포커스 이동", "0a1011328ba42eef": "이전 작업 영역으로 포커스 이동", @@ -2360,14 +2416,24 @@ "05037ca1666fd421": "터미널은 프로젝트 스레드에서만 사용할 수 있습니다.", "a3aa1e49af278d41": "파일은 프로젝트가 열려 있을 때만 사용할 수 있습니다.", "87ea6995ea1e7aa4": "변경 사항은 Git 저장소의 서버 스레드에서만 사용할 수 있습니다.", + "80f10f5ea1804d8d": "The Git graph needs a Git repository on an up-to-date server.", "4a87cae01ccde544": "이 스레드의 브랜치에 아직 풀 리퀘스트가 없습니다.", "32535dba0b9af642": "이 스레드에 연결된 항목이 없습니다.", + "d955eee48dece3c0": "Enable the agent stage in Settings > General.", + "d2f2f6d05148f8a3": "Threads a coordinator runs have no thread overview.", + "26c1c05b0d1d98fd": "Turn on coordinator decisions in Settings > General.", + "486d4369c4fbec9e": "Notes are only available from a thread.", + "50b5a57d3bd6f6ef": "Instructions are only available from a thread.", + "007ab76950f73521": "Media is only available from a thread.", "07080dead70f4cc5": "기기는 스레드에서만 사용할 수 있습니다.", "a4bf49b31758ff7e": "데스크톱 앱에서만 사용할 수 있습니다.", "e917841cb66f9af1": "프로젝트가 열려 있을 때 사용할 수 있습니다.", "14c15fad0c2ee0c8": "Git 저장소에서 사용할 수 있습니다.", "9176276c78f3893f": "이 브랜치에 아직 풀 리퀘스트가 없습니다.", "52ce9db6fb62a59f": "연결된 항목이 없습니다.", + "96c2ee76dd82d2cc": "Enable it in Settings > General.", + "2199013487151590": "Not for threads a coordinator runs.", + "f7a9300d9f9030d5": "Turn on coordinator decisions in Settings.", "e5d6f41e4fe4efd6": "스레드에서 사용할 수 있습니다.", "0ebc2bb883a8e283": "첫 메시지 후에 사용할 수 있습니다.", "84d0ff8fb9846057": "탭 음소거 해제", @@ -2376,8 +2442,15 @@ "5c78a8ae7b71af1d": "터미널", "cba3e832ece50257": "파일", "83ac3423d6dfc4a7": "변경 사항", + "016750bdd5076287": "Git graph", "da16af47eff38ae9": "풀 리퀘스트", "ad3929f0103925d7": "연결된 항목", + "70e7b208e032024a": "Stage", + "0caf7e5748f1d17b": "Threads this one started, and which need you.", + "96018894225bd4ff": "Inbox", + "0ed16d7723c04288": "Decisions the coordinator asks you for.", + "aec2b493d2b01445": "Notes", + "9e92f6aa6edae875": "Notes and todos for this thread, its project, or everywhere.", "ac0de2a59d9c8860": "기기", "1354df9fb7278843": "iOS 시뮬레이터나 Android 에뮬레이터를 봅니다.", "fdcd9643e2e63b15": "이 스레드가 계속 작업하는 동안 곁가지 질문을 하세요.", @@ -2496,8 +2569,7 @@ "2d1c111e1b4ae0b0": "스레드 \"{title}\"을(를) 삭제할까요?", "c568ab8dad798ec5": "이 스레드의 대화 기록이 영구적으로 삭제됩니다.", "0fd1c746a0e38003": "스레드를 삭제하지 못했습니다", - "0ecde875b0dd2f93": "프로젝트별 스레드 필터: {projects}", - "1ef65b647231ff0b": "프로젝트별 스레드 필터", + "1c8fc3c4a42949ab": "프로젝트: {projects}", "165511761be2855c": "프로젝트 검색", "a46a6467883575a4": "프로젝트 검색...", "fdc0e086438a3045": "{project} 프로젝트 설정", @@ -2559,10 +2631,9 @@ }, "에 설치" ], + "b4b98a0287c282e2": "다른 머신에 있어 이 머신의 에이전트가 읽을 수 없습니다. 제거하거나 원래대로 전환한 후 보내세요.", "5bbac0e5afeec779": "현재 스레드", "33c7e68fca089036": "스레드, {title}", - "b4b98a0287c282e2": "다른 머신에 있어 이 머신의 에이전트가 읽을 수 없습니다. 제거하거나 원래대로 전환한 후 보내세요.", - "c6196d99000642b4": "스레드 열기", "34cc63390ad793cc": "스레드 선택", "8f12309ead62e38a": "스레드 또는 프로젝트 검색...", "2f664754d005d9a7": "활성 스레드를 찾을 수 없습니다.", @@ -2572,6 +2643,7 @@ "a3178769f8308cbc": "스레드 실패", "89b5e8f3887812da": "게스트 요청", "62e626804919b294": "입력 필요", + "c6196d99000642b4": "스레드 열기", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "나:", "a1fbf2422c588292": "에이전트:", @@ -2595,8 +2667,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "터미널 프로세스 실행 중", "fc2c9a91f498ad6b": "{count, plural, other {터미널 프로세스 {count}개 실행 중. 터미널 열기}}", - "643c4b50feadc874": "워크트리: {path}({branch})", - "fb7c44da0f0825ea": "워크트리: {path}", "56f37ff8ca568059": "스택", "6831e9a46cbd8939": "체인", "9aa9e74a3b7eee91": "채팅에 추가", @@ -2685,8 +2755,6 @@ "78a04e0e625c0990": "업데이트 실패", "c24de5eb69373a55": "이 {build} 빌드는 {track} 릴리스를 무시합니다. 전환을 완료하려면 설정에서 업데이트 트랙을 확인하세요.", "b02ae45a6109c93b": "최신 상태", - "edcda9e8ee4ccad8": "업데이트 {version}을(를) 설치하고 T3 Code를 다시 시작할까요?\n\n실행 중인 작업은 모두 중단됩니다. 계속하기 전에 준비가 되었는지 확인하세요.", - "02eba0f7cc90f759": "업데이트를 설치하고 T3 Code를 다시 시작할까요?\n\n실행 중인 작업은 모두 중단됩니다. 계속하기 전에 준비가 되었는지 확인하세요.", "9ed4d8a1531b9631": "이 빌드에서는 자동 업데이트를 사용할 수 없습니다.", "c8c23435e780a60c": "업데이트를 사용할 수 없음", "1af5f9767371ffd7": "업데이트 확인", @@ -3033,8 +3101,8 @@ "6f85f14f35b3f547": "{environment}을(를) 통한 {provider}", "7c59a888a062a8bd": "음성 입력을 기록할 초안이 없습니다.", "62450481c00d2ef3": "초안의 환경을 사용할 수 없어 받아쓴 내용을 정리할 수 없습니다.", - "c64cb58d9cecbcd2": "받아쓴 내용 정리 실패", "0674544195fcdc39": "원본 받아쓰기 내용이 추가되었습니다.", + "c64cb58d9cecbcd2": "받아쓴 내용 정리 실패", "296496693cdac0db": "t3 명령을 사용할 수 없습니다.", "efbcef7bc9bbda01": "t3 명령 상태를 불러오지 못했습니다.", "1bf6910332426e62": "데스크톱 네트워크 액세스를 사용할 수 없습니다.", @@ -3277,6 +3345,7 @@ "4d493d0bda4d403d": "중단된 파일을 다시 첨부하거나 제거하세요", "c9cad1d84d5f1a32": "중단된 파일을 다시 첨부하거나 제거하세요", "536a820f2ff726da": "모델을 하나 이상 선택하세요.", + "48d6389202ad6754": "준비되면 전송", "fbafbe78b5e37966": "스레드 재개", "bcd7eb979dd38dae": "압축하고 보내려면 입력창을 여세요", "95ee62a0d6968b89": "메시지 보내기", @@ -3450,6 +3519,9 @@ "e778e4f446fdf873": "다음 메시지부터 새 세션이 시작됩니다", "0e2f2da4f2d94785": "에이전트는 이 스레드의 이전 메시지를 볼 수 없습니다.", "e1189d2e582b008d": "현재 세션 유지", + "2bb448d605877a22": "편집하거나 Esc를 눌러 취소", + "1a1f128d70c62304": "{count, plural, other {이미지가 준비되면 전송}}", + "5af3ab719a9725fb": "메시지 전송 중", "461c9f865f2e9b92": "{option} 켜짐", "f2aa17b5c620f2a4": "{option} 꺼짐", "f59314a884aae1ff": "기본값", @@ -3573,6 +3645,13 @@ "c53bc5a4b0314342": "다음 미디어", "2950b1424a3cddf5": "이 환경에 다시 연결한 후 미디어를 다시 여세요.", "ef638bf1479a5461": "환경에서 잘못된 미디어 URL을 반환했습니다.", + "3ccfbf7e86868c35": "T3 팀에 보내는 피드백", + "4e0710d19dfc2e7e": "이 보고서를 T3 팀에 보낼까요?", + "87d0ae0723ba75d1": "이 내용만 이 컴퓨터에서 전송됩니다. 보내기를 누르기 전에는 아무것도 전송되지 않습니다.", + "bf19826f81484328": "대화 포함", + "ddb7e6f8ce99e657": "이 컴퓨터에서 에이전트를 실행할 수 있는 사람만 보고서를 보내거나 거절할 수 있습니다.", + "03c1eb603c112f47": "보내지 않기", + "653405e4ed498d9f": "보내기", "262955d6eb632f9b": "게스트 링크를 복사하는 중 클립보드 API를 사용할 수 없습니다.", "f1a4f2b04cdbb4ef": "게스트 링크를 클립보드에 복사하지 못했습니다.", "cf3490a604e44d31": "게스트 링크를 만들 수 없습니다.", @@ -3593,7 +3672,6 @@ "abd89e9eefedf11b": "완료", "18d166056c1ab6ff": "공유 중지", "7a2d510eac9e4587": "게스트 링크 만료됨", - "653405e4ed498d9f": "보내기", "21888e302219891d": "확대된 {title} 미리 보기", "419719298a7acaea": "축소", "ed8d5db95359cff4": "확대/축소 초기화", @@ -3688,7 +3766,6 @@ "7c1923203049d602": "코드 복사", "637817e4ff79c90e": "코드 블록 작업", "ebf3a2b1e314aa5f": "터미널에서 실행", - "fe219642547fa0bf": "터미널에서 실행", "122a8512abc51180": "세부 정보", "58c38c65c2783c5d": "전체 경로", "f37e7d36b51c5b28": "상대 경로 복사", @@ -3700,10 +3777,6 @@ "4967584e8d0fb1c2": "미디어 미리 보기", "67589dd912eacb7c": "통합 브라우저에서 열기", "a3c98d4c4b24cecb": "{label} 파일 옵션", - "b4fe8a076e9fd2f8": "블록 수식", - "085d1407e8c92cce": "인라인 수식", - "a2ef393fa7b48ae8": "블록 수식 스크롤", - "e94685ea5642e088": "인라인 수식 스크롤", "3a04583c8500e23d": "다이어그램 표시", "16d64f650840fe06": "코드 표시", "6d329f7d3a50c7e7": "표 복사", @@ -3973,9 +4046,11 @@ "973e99fa86d7f531": "대기열 메시지 {total}개 중 {position}번째, 보내지 않음", "0f6087c4f53c7f17": "이 메시지로 턴 시작({shortcut})", "adab89933af02669": "압축을 건너뛰고 이 메시지 보내기({shortcut})", + "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", "3de4016452e8d2bd": "현재 턴에 보내기({shortcut})", "259cc9568148e8ad": "이 메시지로 턴 시작", "bb7fddb812d5d29e": "압축을 건너뛰고 이 메시지 보내기", + "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동", "a5fe1ee609b29a9f": "현재 턴에 보내기", "2b7fd345e4f4fd6e": "대기열 메시지 편집 취소", "47f1726bf106d2c8": "대기열 메시지 편집", @@ -5434,6 +5509,22 @@ "f0d79aa56f06663f": "이 파일은 너무 커서 전체를 표시할 수 없습니다. 개수에는 모든 변경 사항이 포함됩니다.", "7fdde2b893ba1b9d": "삭제됨", "e58ce271d835b447": "추가됨", + "fb5c7ff5ea76e01a": "Added by esveo's fork. Click to list all of its settings.", + "352fa6aeb5d55665": "Trail the provider icon behind the thread title instead of giving it a line of its own. The line it saves also carried the branch, pull request badge and diff counts.", + "9d44fa03a230e0d8": "Reset two-line thread cards to default", + "7b216eedb1abe696": "Two-line thread cards", + "8d90fcd918e901c8": "Keep each project's threads together in the sidebar, under a header that folds the project away. Ordering stays by recency: the project with the newest thread leads.", + "d5dfd89c9a281386": "프로젝트 그룹화 기본값으로 재설정", + "aac9f889c7ec7ff5": "Group sidebar threads by project", + "da375a07c5309184": "Show how full the thread's context window is next to the composer controls.", + "33f6b88cba203990": "Reset context window usage to default", + "6496f57baeded3fa": "Context window usage", + "d9c146dc6b95714d": "Show how many minutes are left before the prompt cache expires. Claude only.", + "69609e27c2107da5": "Reset prompt cache timer to default", + "a4917d2b93c478f6": "Prompt cache timer", + "ea8ebcb77e657e9f": "Open the thread details card with workspace and version control in every thread. Off, it stays closed until you open it, and each thread remembers your choice.", + "662288b90e19635f": "스레드 세부 정보 기본값으로 재설정", + "92729a403d37c575": "Open thread details by default", "07b9970b662ab70d": "Mermaid 소스 표시", "5a422b7be35243f5": "렌더링된 다이어그램 표시", "c0628ad999cbbbf5": "Markdown 소스 표시", @@ -5541,6 +5632,7 @@ "723d88a5fa7e2fdd": "일치하는 파일이 없습니다.", "f8d6e9a1a2870a5c": "파일 탐색기", "109edd252917113b": "파일 탐색기 크기 조정", + "7abd6af24fed7b60": "The file does not exist in the workspace or the home folder.", "37cbd2ecc659a007": "파일", "b5188f172f59ca79": "이 연결로는 호스트 파일을 읽을 수 없습니다.", "c3c5d36466ad2191": "미리 보기 브라우저에서 파일 열기", @@ -5580,7 +5672,6 @@ }, ". 링크의 경로를 확인하거나 파일에서 해당 파일을 찾으세요." ], - "b9b6bbd1e1ea189f": "전체 파일", "d715e9494fdbaaf6": "글꼴을 불러올 수 없습니다.", "ff17c777a72b4408": "글꼴 미리 보기는 10MB로 제한됩니다.", "6bd41ad699e22f10": "글꼴을 사용할 수 없습니다.", @@ -5590,6 +5681,7 @@ "a9abaaa4220eae21": "{error} 저장한 후 다른 앱에서 여세요.", "c508c9000d9656f8": "글꼴 미리 보기", "1c416d621d250be8": "다람쥐 헌 쳇바퀴에 타고파.", + "d7d08260f16b7828": "파일을 아직 불러오는 중입니다. 잠시 후 다시 시도하세요.", "76ebb03de52c92d6": "텍스트 뷰어가 중지되었습니다.", "f48162e8e8c12af7": "텍스트 뷰어를 불러올 수 없습니다. 파일을 닫고 다시 시도하세요.", "bc4c5b13d38a5da7": "미리 보기가 닫혔습니다.", @@ -5597,8 +5689,6 @@ "9450d1827ef336a1": "다른 복사가 진행 중입니다.", "8f48999eb6d9e2e3": "{count, plural, other {{formatted}줄}}", "13b14784f8707ddd": "0바이트", - "f6e9581cba3467fa": "색인하는 중…", - "2d1f293ac12463fc": "파일의 나머지를 불러오는 중…", "b75105bef8f564a4": "처음 1,024열을 표시합니다. 소스와 저장에는 모든 열이 유지됩니다.", "2a6e1b1f209c3888": "이 파일은 비어 있습니다.", "192fc79eb3b5b2cb": "이 다이어그램에는 리소스 URL, 마크업, 노드 메타데이터 또는 사용자 지정 구성이 포함되어 있습니다. 안전하게 확인하려면 Mermaid 소스를 표시하세요.", @@ -5785,7 +5875,6 @@ "0061fff77e36bd4f": "서버에 연결할 수 없습니다.", "04dfdd46e3dd4a2e": "문제가 발생했습니다. 다시 시도하세요.", "084bb2d8127a508d": "보냄", - "e7c59185f8ab3987": "보내지 않음", "77c01a15bd36d17c": "이 링크는 종료되었거나 유효하지 않습니다", "e0e736810f3cbef2": "소유자에게 새 링크를 요청하세요. 각 링크는 한 브라우저에서만 작동합니다.", "c3c53aa46f7330e5": "이 링크는 종료되었습니다", @@ -5807,6 +5896,13 @@ "cbb2129c0dd4f40b": "첨부 파일은 메시지당 합계 10MB까지 가능합니다.", "03b9cd79cfe0b435": "이 파일은 첨부할 수 없습니다. 이미지는 PNG, JPEG, GIF 또는 WebP여야 합니다.", "8ff29c78798e6ac1": "이 항목을 불러올 수 없습니다.", + "535923000a0f3e3b": "Send /compact to a large, idle Claude thread shortly before its 1-hour prompt cache expires, so the next message skips caching the whole conversation again. 5-minute caches are left alone.", + "bd8eb8f5f9843bc6": "Reset idle auto-compact to default", + "1db274eacf03c8de": "Auto-compact idle Claude threads", + "fb6643c75aafd996": "Between {min} and {max}; it has to fall inside the cache's hour.", + "48dee64ca7904281": "Minutes idle before auto-compact", + "8937fe924464eb70": "Smaller threads are cheap to cache again and keep their full history.", + "1981f1e1a753aabc": "Minimum context tokens for auto-compact", "94ab4591ce101233": "댓글을 게시할 수 없습니다", "92d0d4eab2596772": "트래커가 거부했습니다.", "33591d9596fb7cb7": "댓글 추가", @@ -8654,12 +8750,16 @@ "58e0e226493150e7": "이슈 트래커를 불러올 수 없습니다", "77cfcbde543df32d": "{tracker} 세부 정보 전환", "0083f65885c60156": "{tracker} 연결 끊기", - "295392927d5c8a84": "각 프로젝트에 {tracker} {scope}을(를) 하나 이상 선택하세요. 해당 이슈는 저장소 자체 이슈와 함께 표시되며, 에이전트는 첫 번째 {scope}에 새 이슈를 만듭니다.", + "ed83b25c71c98a20": "각 프로젝트에 {tracker} {scope}을(를) 하나 이상 선택하세요. 해당 이슈는 저장소 자체 이슈와 함께 표시되며, 에이전트는 다른 {scope}을(를) 지정받지 않으면 첫 번째 {scope}에 새 이슈를 만듭니다.", "19c2d5e81ff8f89a": "{project}의 {tracker} {scope}", "68e061510b765772": "바인딩되지 않음", + "99d51127f573296b": "다른 계정", + "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다.", + "99963c0142e17f00": "새 {tracker} 계정용입니다.", "a2d95d39d3398bda": "자격 증명 거부됨", "9eae463720500113": "서버에 저장됩니다.", "b6e27ab2537ef874": "새로 만들기", + "6d8e4ebc889bace9": "계정 추가", "13ef526271b0f5d4": "모든 조건 지우기", "d1938a629f039515": "조건 제거", "84a605b241ce65b7": "그룹과 조건 제거", @@ -8789,6 +8889,12 @@ "d3866ead082d14e5": "단축키 추가", "d4345c90894a3220": "keybindings.json 열기", "e56a8d51219efaa0": "검색과 일치하는 단축키가 없습니다.", + "90a258fff61fd77e": "끔", + "4060244a7079a0d2": "내가 요청할 때", + "e88c9d8769544731": "자동", + "f29d1dade4dde8aa": "에이전트가 T3 팀에 피드백을 보내지 않습니다.", + "93c4c53562d30a98": "요청하면 에이전트가 T3 Code에 관한 짧은 보고서를 보여주고, 승인하면 T3 팀에 보냅니다.", + "cd9ee803e8727017": "에이전트가 직접 겪은 T3 Code 문제도 보고합니다. 예를 들어 T3 도구가 실패한 경우입니다.", "45fa271ea0e1ac8e": "베타", "3a678332fc7142f7": "사이드바 스레드를 프로젝트 폴더로 묶습니다. 고정된 스레드는 맨 위에, 다시 알림과 정리됨은 폴더 아래에 유지됩니다.", "e4e91d155cb6a9b4": "단순 사이드바(프로젝트별 그룹화)", @@ -8797,11 +8903,16 @@ "9ae293971d93c819": "브라우저에서 실시간으로 지켜보고 승인한 메시지를 보낼 수 있는 게스트와 스레드를 공유합니다. 게스트 링크를 사용하려면 T3 Connect에 로그인하세요.", "0aa5406ac4d7f7c7": "게스트 링크", "f0e853acd2006d53": "연결된 환경", + "ef10c2dff987f3ea": "이 서버 T3 홈의 workflows 폴더에 있는 파일로 여러 단계의 워크플로를 실행합니다. 명령 팔레트에서 엽니다. 꺼져 있는 동안에는 그 폴더의 어떤 것도 실행되지 않으며, 실행은 다시 켤 때까지 기다립니다.", + "2dadb2359422121c": "워크플로", "13e86eb5d8287a71": "Claude 또는 Codex 턴이 끝난 뒤 빈 입력창에 예상되는 다음 메시지를 표시합니다. Tab을 누르면 사용합니다. 제안마다 요금제에서 캐시된 요청이 하나 더 발생합니다. Codex 0.165 이상이 필요합니다. Claude 스레드는 다시 시작하면 업데이트됩니다.", "d4b2a2ec812aafb0": "다음 프롬프트 제안", "298c7150a7621c80": "Simlock 기기 호스트", "67937aa49179285e": "Mac에서 모든 파일을 쓰는 대신 T3 홈 폴더에 캐시된 체크아웃에서 새 워크트리를 복제합니다. 불가능하면 Git의 일반 체크아웃을 사용합니다. 끄면 캐시가 삭제됩니다.", "f9904f78d3003f58": "빠른 워크트리 체크아웃", + "9c2f647882522302": "선택한 컴퓨터의 에이전트 피드백 모드가 서로 다릅니다.", + "31bbf7bf8c0a5279": "에이전트 피드백", + "d52b3d6bf9f2a013": "혼합", "ec7623deed751c05": [ "브라우저에서 실시간으로 지켜보고 승인한 메시지를 보낼 수 있는 게스트와 스레드를 공유합니다. T3 Connect가 필요합니다. 로그인한 뒤", " ", @@ -8885,7 +8996,9 @@ "fb71127e5746a6bc": "그곳의 공유 및 액세스 또는 t3 pair에서", "1e3fee7084791773": "{target}에서 {source}(으)로도 반대 방향 연결", "ea34a190b0bd804c": "그러면 {target}의 에이전트도 {source}에서 작업할 수 있습니다.", - "ad5ed0ce61b966eb": "{label}을(를) 삭제할까요? 이곳의 에이전트가 그곳에서 더 이상 작업하지 않습니다. 그곳의 세션도 끝내려면 {label}의 공유 및 액세스에서 \"T3 Code · …\"를 취소하세요.", + "974f8c65e8b5f492": "{label}을(를) 잊을까요? 여기의 에이전트는 그곳에서 더 이상 작업하지 않으며, {label}이(가) 응답하면 그곳의 세션도 종료됩니다.", + "6cf9e3083b15614f": "{label}이(가) 응답하지 않았습니다", + "34ccbdf619b83be3": "그곳의 세션도 끝내려면 {label}의 공유 및 액세스에서 \"T3 Code · …\"를 취소하세요.", "81c9796bf61b306a": "링크를 삭제할 수 없습니다", "130e51beb6cf5aad": "환경 연결", "122c3e355699e69d": "그러면 이곳의 에이전트가 그곳에서 스레드를 시작하고, 메시지를 보내고, 기다릴 수 있습니다. 해당 환경의 공유 및 액세스에서 승인된 클라이언트에 표시되며 그곳에서 취소할 수 있습니다.", @@ -9114,7 +9227,6 @@ "0b4779a1825c85bc": "사이드바와 스레드 목록에 표시되는 이 프로젝트 그룹의 공유 이름입니다.", "f68cbda4df83d739": "프로젝트 이름 기본값으로 재설정", "56e37b85027e8431": "프로젝트 아이콘", - "e88c9d8769544731": "자동", "c99736317da5b1fa": "프로젝트 아이콘 기본값으로 재설정", "6afaa3e3739dc570": "프로젝트 아이콘 선택", "51651ce45d481a20": "프로젝트 아이콘 파일 선택", @@ -10019,7 +10131,6 @@ "53de7aafe0afc10d": "테마 설정을 복원할 수 없습니다", "006bfa1846fe5dd2": "자동 정리까지의 비활성 일수", "d9b0fbd680d5f175": "사이드바", - "d5dfd89c9a281386": "프로젝트 그룹화 기본값으로 재설정", "cd5452cc9e13c818": "프로젝트 그룹화", "cfb01b8a2a3361fb": "프로젝트 순서 기본값으로 재설정", "26abcbe322049a8a": "작업 중 섹션 기본값으로 재설정", @@ -10084,7 +10195,6 @@ "16bdc70b858c223f": "패널 미리 열기 기본값으로 재설정", "c5424f09d77138ff": "200,000 토큰이 넘는 유휴 Claude 스레드를 압축할 시점입니다. 돌아온 뒤, 프롬프트 캐시가 만료되기 직전, 또는 압축 안 함 중에서 선택합니다. 각 Claude 제공자에서 재정의할 수 있습니다.", "3e99c5c14f4939c8": "유휴 스레드 압축 기본값으로 재설정", - "d52b3d6bf9f2a013": "혼합", "cd72fe451ba0d6aa": "새 프로젝트", "394c3bd0a1782c8e": "프로젝트 추가 탐색기가 열릴 때 \"~/\"를 사용하려면 비워 두세요.", "f9b912a818bd869d": "프로젝트 추가 기본 디렉터리 기본값으로 재설정", @@ -10982,7 +11092,6 @@ "4a237f41ce592b7f": "직접 삭제할 때까지 이 프로젝트의 워크트리를 유지합니다.", "00b8ffd8ea6e6a93": "이 프로젝트에 이 규칙을 사용합니다.", "72c279824d15a999": "각 머신의 워크트리 정리 설정을 사용합니다.", - "90a258fff61fd77e": "끔", "b5702d0b64866b08": "사용자 지정", "c009c901f3eefe78": "삭제된 스레드의 워크트리 삭제", "431c7cd6d50102b7": "활성 또는 보관된 스레드가 삭제되면 사용하지 않는 워크트리를 제거합니다. 로컬 변경 사항이 있는 워크트리는 유지됩니다.", @@ -11335,7 +11444,6 @@ "f2043e87a10cb831": "테마 편집", "595bdeefcdc9bf31": "테마 파일 내보내기", "b480281b3791b685": "스레드 세부 정보 카드에 표시할 항목을 선택합니다. 카드를 마우스 오른쪽 버튼으로 클릭해도 됩니다.", - "662288b90e19635f": "스레드 세부 정보 기본값으로 재설정", "871d059d88548434": "스레드 세부 정보: {total}개 중 {enabled}개 켜짐", "cec1fbb8b4c9180d": [ { @@ -11674,7 +11782,6 @@ "4c70e3e7b3e6c493": "시크릿", "79b768229c9ef672": "유지 관리", "54b188d65247e42f": "실험 기능", - "f41ea186c275b56e": "정보", "af4b7734da1d5ce7": "음성", "4ec62c39ca3192bf": "소스 제어 및 이슈", "f2bf529f85e05494": "공유 및 액세스", @@ -11703,11 +11810,17 @@ "8f5966eebd2b110f": "모양 색상 팔레트 사용자 지정 가져오기", "633ed64e952cca3b": "색상 테두리 인터페이스", "9cf8308531b4ff31": "투명 투명도 불투명 메뉴 대화 상자 입력창", + "d99bfbc557fae743": "Notion", + "89df56091835b3a6": "notion integration secret pages links viewer connect token ntn", + "d699adcc04d4d4ab": "sidebar compact row height branch provider icon diff pull request", + "9b9df5ba41c4a8e2": "Group threads by project", + "0ed2eab2c1953531": "sidebar project folder runs grouping collapse header repository", "d8d6cfd630cff22d": "빨간색 녹색 파란색 주황색 추가 삭제 변경 개수 팔레트 색맹", "717e49895cfee1c7": "넓게 전체 너비 열 레이아웃 메시지 입력창 모니터", "88365077fd80787b": "사용자 지정 표시 숨기기 패널 카드 환경 편집기 스크립트 브랜치 풀 리퀘스트 git 변경 사항 서버 자동화 계보 사용량 한도 5시간 주간 할당량 토큰 컨텍스트 창", "d561f74efa5f3920": "추론 수준 생각 막대 그래프 단어 레이블 수준 입력창", "6113c17109ee0d57": "latex tex katex 수식 공식 마크다운", + "dfe7ead48efc3f5a": "thread details card panel workspace version control closed collapsed hide", "8c8364d44fa28d22": "dev nightly latest 채널 아트워크 알약 레이블 숨기기 없음", "2d90635156dfcb5a": "타이포그래피 글꼴 크기 시스템 산세리프", "d32e93777e4819c8": "타이포그래피 글꼴 크기 입력창 입력", @@ -11729,6 +11842,7 @@ "d443390c4d2dcfd4": "접근성 a11y 화면 낭독기 nvda jaws voiceover orca 내레이터 창 제목 탭 제목 alt tab 작업 표시줄 스레드 상태 순서 작업 중 승인", "6826fa9579c22035": "베타 공유 게스트 초대 링크 팀원 지켜보기 T3 Connect 터널", "f10c06cba0cdf7fe": "베타 다른 머신 연결 vps 피어 에이전트 원격 작업 위임", + "bc0b409d89ce086e": "베타 워크플로 workflow 지속 실행 자동화 단계 일정 webhook 폴더", "4a21cf825a2045b0": "베타 탭 자동 완성 다음 메시지 예측 Claude Codex 고스트 텍스트", "fea2dc36585c4a20": "Simlock 기기 호스트(알파)", "9d834d178130180e": "베타 알파 simlock callstack 시뮬레이터 에뮬레이터 iOS Android 풀 임대 게이트웨이", @@ -11770,7 +11884,29 @@ "34d74827c2a8b009": "enter return command ctrl 여러 줄 프롬프트 새 줄 입력창", "9d1013084c46ecce": "대기열 방향 조정 실행 중 턴 보내기 기본 동작 입력창", "e5e7f5e1fb1f2e4c": "서브에이전트 사이드 채팅 연결된 스레드 클릭 오른쪽 패널 사이드 패널 메인 보기 커맨드 ctrl 가운데 클릭", + "5c59d7e2673267ea": "composer tokens usage meter percentage compaction", + "e0d6ec10218b714e": "composer claude cache ttl expire minutes warm cold tokens", + "ce0952668aba4140": "Agent stage", + "f637899f994b78c3": "sprites stations subagents thinking editing terminal right panel everything", + "9d9d3374ee961b91": "Easter eggs", + "571180dbfeddbfd5": "surprise fun rocket animation message send hidden", + "0716adb0d55ffa58": "Voice calls", + "027d8f5ea5555973": "voice call phone gpt live feature flag anruf telefon schalter", + "60d509bb55e2967c": "Voice call voice", + "0e5f5c5ebf026abd": "voice call phone gpt live speaker stimme anruf telefon", + "266f1e2b55e419b0": "Voice call follow-up", + "392226d9bed6fe21": "voice call queue steer follow-up warteschlange anruf", "5b8b854de7ee6f4d": "설치된 CLI 버전 최신 사용 가능 Codex Claude Cursor Grok fx Kiro OpenCode", + "1ceaab7d898b689a": "Child threads in the sidebar", + "fa5a42a73d1c1ece": "coordinator subthreads nested group expand sidebar orchestration children", + "6a1072050d1ad19e": "Coordinator decisions", + "474ba8e025886f86": "inbox questions answers decide approve coordinator open items", + "8f5558f063214509": "Cross-project threads", + "b809e3ffa5178b88": "agents coordinator other projects read message start threads repositories", + "44207b47d209f601": "compact context prompt cache idle claude tokens cost expire", + "396a2cc5b442e359": "compact idle minutes prompt cache ttl", + "6d9520a9cbd70c2f": "Minimum context for auto-compact", + "2fe046cc1e0d0d4a": "compact context tokens threshold size", "64f12530d55d2ad1": "재개 실행 중 활성 중단된 작업 다시 시작 재부팅 머신 충돌 데스크톱 업데이트 자동", "214a98497c4ed05d": "caffeinate 절전 방지 깨어 있기 전원 노트북 덮개 inhibit", "00469926c7027e2d": "균형 성능 배터리 절약 고급 git 가져오기 제공자 상태 새로 고침 호스트 전원 모니터 유휴 정책", @@ -11800,6 +11936,7 @@ "901a823214edc8c4": "원격 분석 분석 사용 데이터 추적 법적 옵트아웃", "82136480255a5106": "OTel OTLP 원격 분석 내보내기 엔드포인트 로그 추적 메트릭 Grafana", "659d081051faf7ff": "로그 추적 프로세스 리소스 기록 실패 스팬 cpu 메모리", + "5eaeacfa9f82051a": "보고 버그 문제 t3 팀 보내기 피드백 에이전트 도구 자동 내가 요청할 때", "f537f91e1ee41d47": "키보드 단축키 핫키 명령 바인딩 json", "1ba01e7ceed64b95": "창 캡처 스크린샷", "279b1cceb779ff38": "앱 텍스트 포함", @@ -12005,6 +12142,8 @@ }, "의 변경 사항" ], + "643c4b50feadc874": "Worktree: {path} ({branch})", + "fb7c44da0f0825ea": "Worktree: {path}", "e7f35f60e6229cf5": "데스크톱 앱", "77be1b7e2a1d3d31": "{count, plural, other {머신 {count}대를 업데이트할까요?}}", "e4892b21e88abb60": "{count, plural, other {제공자 업데이트 {count}개}}", @@ -12068,6 +12207,25 @@ "ffaa75d2db1e7cc1": "업데이트가 적용되지 않았습니다", "626bcbe04dc55f93": "T3 Code가 아직 {current}입니다. 업데이트 버튼에서 {version}을(를) 다시 설치하세요.", "49214c047fbb1606": "제공자 업데이트가 중단되었습니다", + "a135af0f1efda8de": "Cross-project", + "6e9798372b3fb922": "Coordinators put the questions they need you to decide into an Inbox tab beside the chat, instead of numbering them in their messages. Running sessions pick up a change.", + "7a5292a1705defec": "Reset coordinator decisions to default", + "9e3ff0f05f52b724": "Let agents read, message and start threads in other projects of this environment. Running sessions pick up a change.", + "384695cdd7ab6b54": "Reset cross-project threads to default", + "5a6c243a03eeca0c": "Choose a coordinator", + "f527bb5b4ad333da": "Coordinator for \"{title}\"…", + "6beb2db2a7b5edae": "Could not assign the thread", + "4ebb0c90c45690c0": "Could not detach the thread", + "73ac4f532306bea6": [ + "Assign \"", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "\" to a coordinator" + ], + "1871eb35b1ca5d41": "No thread can coordinate this one.", "52adbc863aeb5e59": "복사하지 못했습니다", "0944728904d886d2": "{label} 채도 및 밝기", "dded2cb4e4d26338": "{label} 채도", @@ -12269,7 +12427,6 @@ "0bd41ff995d36a66": "캐시 읽기", "3f0dfe0cb15a3272": "캐시 쓰기", "1c9d860be42b1c02": "출력", - "78344b60f407928e": "기타", "684e516076de81fe": "표준", "3bbcc1b826fef537": "빠름", "66796576034c18ea": "초고속", @@ -12285,6 +12442,263 @@ "2cddd6095abc734a": "7일", "53493056306708cf": "30일", "c719359d18d37ad3": "90일", + "a7ad3167ca62e7de": "Talk to your agents by voice with GPT-Live on your Codex ChatGPT login. Turning this off ends a running call.", + "9f0e45a1d67187cd": "Reset voice calls to default", + "da0ae8174ac2fc14": "Queue what you say in a voice call while the agent runs, or steer the current run. Saying otherwise overrides it for one message. A change applies from the next call.", + "fb0a2aa3b08a17c4": "Reset voice call follow-up to default", + "66936cae56d1d749": "Queue", + "89bf6f658c44cb1b": "Steer", + "930a28582d2c103f": "The voice that talks to you in a voice call. A change applies from the next call.", + "591a53f319b0d343": "Reset voice call voice to default", + "0bd950151ddc6407": "저장하지 않고 나갈까요? 이 파일의 변경 사항이 사라집니다.", + "c0ba3f6756b09f30": "저장되지 않은 변경 사항", + "6914e22d357f0ad6": "저장되어 실행 중", + "aff389354a031d6f": "디스크의 파일을 불러올 수 없습니다. 마지막으로 불러온 버전이 계속 실행됩니다.", + "858effde748ab563": "저장했지만 아직 실행되지 않습니다.", + "ddb37138df660942": "저장되지 않았습니다. 서버에서 변경된 것은 없습니다.", + "6ef4db489e40e39e": "저장할 수 없습니다", + "c89624a2e9af1793": "{name}이(가) 연결되어 있지 않습니다", + "b5a352a43adb4c17": "다시 연결되면 워크플로가 다시 표시됩니다. 다른 환경을 선택하면 그 환경의 실행을 볼 수 있습니다.", + "3dcedb736d20aae5": "워크플로 파일을 읽을 수 없습니다", + "b09f4df8d76ae8ea": "{file}을(를) 삭제할까요? 이 파일에 정의된 워크플로는 더 이상 시작할 수 없습니다.", + "b4535f5a03689d27": "{name}이(가) 연결되어 있지 않습니다. 여기에 작성한 내용은 유지되며, 다시 연결되면 저장할 수 있습니다.", + "b54c78d85fd942ea": "삭제했지만 실행 중인 내용에 아직 반영되지 않았습니다.", + "407c228d7da0b7df": "삭제되지 않았습니다. 서버에서 변경된 것은 없습니다.", + "1a6aa10f3cc14fff": "이 파일들은 서로 맞지 않습니다. 이전에 실행되던 것이 계속 실행됩니다.", + "259312516a1dbe6f": "파일 이름", + "2f48ab2aa0586853": "정의된 워크플로 없음", + "ba5adfa37b55b8c5": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "번째 줄:" + ], + "d94eb9ab3201b641": "삭제", + "84c900d1ae72adc6": "저장", + "5912d817be03247a": "편집하는 동안 디스크의 파일이 변경되었습니다. 저장하면 해당 변경 사항을 덮어씁니다.", + "0b1e6f5608826387": "파일을 불러오고 내 변경 사항 버리기", + "f47b4c06aeb77c1c": "워크플로 파일을 불러오는 중…", + "4353bfd401d58f87": [ + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "의 모든 파일이 워크플로를 정의합니다. 파일을 변경하면 다시 시작하지 않아도 반영됩니다." + ], + "0c165251a06f10f1": "새 파일", + "8e97cf734b4463e7": "만들기", + "2ec0d5108fd6cebe": "아직 워크플로가 없습니다. 여기에서 첫 파일을 만들거나 에이전트에게 해당 폴더에 작성해 달라고 요청하세요.", + "5601350626e8cfe9": "불러올 수 없음", + "21d778a1b9a0c234": "실행 옆에 열린 항목", + "62dc4d3a19ff7ca0": "탭 닫기", + "1e25265f2758fce3": "전체 스레드로 열기", + "672a3dae06b39402": "전용 페이지에서 열기", + "7755500a4cde5066": "창 닫기", + "b8dcbc93a2ca1861": "이 실행에 더 이상 포함되지 않습니다.", + "115c69de3202f664": "열기", + "644eafa9048b62df": "{count, plural, =1 {1번째 시도} =2 {2번째 시도} =3 {3번째 시도} other {{count}번째 시도}}", + "e39f89c909df4db0": "실행을 재개할 수 없습니다", + "865f034346b82f47": "{title}을(를) 취소할까요? 에이전트가 중지되며 이 실행은 재개할 수 없습니다.", + "6bc75632fd9c9136": "실행을 취소할 수 없습니다", + "64e50329dcfdd5b0": "완료", + "350162e7cc1ebea4": "중지됨", + "0875cf506f4c6810": "건너뜀", + "3cc43f1dbf3f8e0c": "취소됨", + "ded70e75de6404ba": "실행 목록으로 돌아가기", + "2f4ed7dbd22be30d": "실행 취소", + "614e5ad58a795fb5": "중지", + "04b050b0329f0ac8": "{duration} 소요", + "aff78e1774818ff4": "현재까지 {duration}", + "38eddd466439afc9": "이 실행이 다룬 항목", + "156ec271d49ddd70": "진행 내역", + "34f59bbbead0b97f": "{names} 외 {count}개", + "ac1556f6ce89a5ea": "{count}개 병렬", + "e197c4963bacc746": "{count}개 실행 중", + "f5319ed9e18c0df1": "사용자에게 질문", + "882a25e9084ae1b2": "일시 중지됨", + "9a03d8a9afc60387": "지금까지의 단계", + "2f2ae791afe01674": "승인을 기다리는 중", + "24f8060c4ccdf928": "시작하는 중", + "30a5be40eb956663": "작업 중", + "dd7a1e58c2553933": "{duration} 후 깨어남", + "95cc952724dd7310": "곧 깨어남", + "3cc34921c0128593": "실행 중", + "e777db2880f53a46": "응답 없음", + "dc90739d391a5e67": "내 답변: {choice}", + "389f2563b5b763fd": "빠른 단계", + "a41c8d758121ad81": "슬립", + "9db248b770096984": "대기", + "c76124517af28686": "{duration}째 실행 중", + "89102905bf09b0e8": "실시간 보기", + "bdf338cdff4118f0": "대화 기록", + "811e7e992f9ff820": "워크플로 버전이 다시 등록될 때까지 계속할 수 없음", + "4d4cdf035e98dd57": "사용자가 재개하기를 기다리는 중", + "eb5b21dd224a5941": "{duration} 후 자동으로 다시 시도", + "6ab3dfa749fde477": "곧 자동으로 다시 시도", + "44b6463aa70aa14c": "일시 중지된 이유", + "cf25e7169ab0eb7a": "{step}에서 일시 중지됨", + "56c48c1f220f2754": "질문에 답변할 수 없습니다", + "a3c43735e1a81498": "{title}의 이유", + "bfad234f016cfa3f": "이유를 한 문장으로 적어 주세요. 어떤 답변을 고르든 함께 전달됩니다.", + "004c41aff9c97873": "실행", + "4dc0c244a2419f6c": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "의 일부" + ], + "8c303e8335acb135": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "시작" + ], + "8bffb377e2a6a7de": "해당 버전이 더 이상 등록되어 있지 않음", + "f92d9132f7b85d1a": "단계를 불러오는 중…", + "6ebc59f64c761a49": "아직 아무것도 없습니다.", + "a759dccd157d7dae": [ + "내 답변: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + } + ], + "593b425188346781": [ + "내 답변: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "실행 열기", + "c8eb9be36d4d51ad": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "의 스레드" + ], + "3d9761e81798fcd8": "재개", + "8cebd63fc4c967d5": "실패한 단계만 다시 실행되며, 그 전에 완료된 내용은 유지됩니다.", + "bc1e0a2a0f1e9552": "확인 필요", + "a812f51e970740f1": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "질문", + " ", + "· 실행이 답변을 기다리는 중" + ], + "02dfe6c63fd0b8a1": "이유 추가", + "19abd94828a3bdbc": "먼저 에이전트에게 묻기", + "a18721fa8f328361": "확인 필요", + "bbf24e7920c1e86b": "실행 중", + "8d6e18d2ad832db6": "전체", + "f25af5332ffc3734": "확인이 필요한 항목이 없습니다.", + "c3f0119b8d6231f8": "실행 중인 항목이 없습니다.", + "33028dfc1229eaa6": "아직 실행이 없습니다.", + "5459bf696a187c26": "워크플로 실행을 불러올 수 없습니다", + "d57c35d43b0f163a": "이 실행은 여기에 없습니다", + "b9aae2f7cdb1a379": "아직 워크플로 실행이 없습니다", + "8f15f66e545af7c0": "표시할 실행", + "b6409289e0c9a4dd": "워크플로", + "035cb02ca1ae4952": "워크플로 {count}개 전체", + "46d614fa7b4bf1e5": "워크플로 실행", + "1c635faa2fb45b8b": "아직 실행된 적이 없습니다.", + "156ff7b625287a1e": "건너뛴 항목 숨기기", + "69b985b97ab45e6b": "건너뛴 항목 {count}개 표시", + "2400254d362de84d": "워크플로 실행을 불러오는 중…", + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "워크플로 파일에 문제가 있습니다." + }, + " ", + "마지막으로 불러온 버전이 계속 실행됩니다." + ], + "ed8ce6ebc73dc12d": "파일 열기", + "145e1f7503ba3b2c": [ + "이 환경에는 해당 링크의 실행이 없습니다.", + " ", + { + "t": "button", + "i": 1, + "c": "실행 목록으로 돌아가기" + } + ], + "783e616cb0476c17": [ + "워크플로는 에이전트, 코드, 일정, 사용자에게 묻는 질문을 다시 시작해도 유지되는 하나의 실행으로 묶습니다.", + " ", + { + "t": "button", + "i": 1, + "c": "정의" + }, + "에서 직접 작성하거나 에이전트에게 요청하세요.", + " ", + { + "t": "a", + "i": 2, + "c": "가이드 읽기" + } + ], + "5d8d278ff828102d": "모든 워크플로", + "39459da07479f482": "에이전트", + "7741243632056b81": "{step} · 기록", + "c512071143a5ba32": "이 스레드는 더 이상 존재하지 않습니다.", + "ed169d23683fb6ac": "스레드를 불러오는 중…", + "290e0ab40b87dc17": "워크플로 탐색 경로", + "683dd9831e54edc0": "환경", + "34ad53646f06ed80": "워크플로가 꺼져 있습니다", + "8f6589c9e0ac5d4e": "연결된 환경 없음", + "744127f8dfad7d22": "환경을 연결하면 해당 환경의 워크플로 실행을 볼 수 있습니다.", + "036182ec7e2ee4d4": "실행 옆", + "2d6107cb78382d08": "워크플로", + "16f7df687349b399": "정의", + "f0a212aadfe1257b": "편집기를 불러오는 중…", + "20f194e003885e95": [ + "이 서버의", + " ", + { + "t": "Link", + "i": 1, + "c": "설정 → Labs" + }, + "에서 켜세요." + ], "8367779e149f723b": "{operation} 중 기본 환경 요청에 실패했습니다(HTTP {status}).", "c5cd027743a2b5a6": "잘못된 페어링 토큰입니다. 토큰을 확인하고 다시 시도하세요.", "0e4b49c8203aae81": "부트스트랩 후 인증된 세션을 기다리다 시간이 초과되었습니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5feb95d75c3da..80b685316a325 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -52,6 +52,27 @@ "eb0f60ef4f92ab7d": "Instale o {fj} 0.6 ou posterior em {fjUrl} e execute {fjLogin}, ou instale o {tea} 0.16 ou posterior em {teaUrl} e execute {teaLogin} para cada servidor Forgejo ou Gitea.", "d026a85e2e50e675": "Instale a CLI do GitCafe com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", "22d3c0c48a34b5b3": "Instale a CLI do TanStack Source com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", + "756c80ad262ef315": "Aguardando na thread original", + "d8df14f9905f38eb": "Enviado", + "e7c59185f8ab3987": "Não enviada", + "b54ddec9084fa955": "Fechado sem enviar", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Confuso", + "0f53bc8f74dfe56a": "Funcionalidade ausente", + "055560f307e15e30": "Documentação incorreta", + "78344b60f407928e": "Outros", + "f653846a95cd6e8f": "Tipo", + "f41ea186c275b56e": "Sobre", + "2f6e4f7cd364da73": "Resultado esperado", + "9d11c93d4035de3e": "O que aconteceu", + "c87d0595693704f9": "Alternativa utilizada", + "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "f5114fb9c40fd929": "Você", + "cd03eb1b84271c02": "Agente", + "bfe1a60f3f9c60fb": "Turno {turn} · {what}", + "dfdaa6255a416140": "Resumo de {turns, plural, one {{turns} turno recente} other {{turns} turnos recentes}}, {textTurns, plural, =0 {sem texto das mensagens} one {com o texto das mensagens do último turno} other {com o texto das mensagens dos últimos {textTurns} turnos}}{truncated, select, yes {, encurtado para caber} other {}}", + "260c6b45f52d2f27": "Adiciona o texto das suas mensagens e das respostas do agente {textTurns, plural, one {no último turno} other {nos últimos {textTurns} turnos}}.", + "afac52a5cc2dc801": "Não foi possível enviar sua resposta. Tente novamente.", "79d776428f4d0650": "Não foi possível carregar o arquivo. Reconecte e tente novamente.", "3ea34cbb1ca5ba9b": "Pré-visualização cancelada.", "7c0af279ecb3da3a": "As pré-visualizações de arquivos por streaming não estão disponíveis neste runtime.", @@ -118,9 +139,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.", @@ -246,6 +267,8 @@ "fec888c767b662d5": "Tentou verificar as issues vinculadas", "bc31067af9c79d82": "{count, plural, one {Verificou as issues vinculadas {count} vez} other {Verificou as issues vinculadas {count} vezes}}", "c712fec8d9dc6dd6": "{count, plural, one {Tentou verificar as issues vinculadas {count} vez} other {Tentou verificar as issues vinculadas {count} vezes}}", + "81c2282590e549f5": "{count, plural, one {Read terminals {count} time} other {Read terminals {count} times}}", + "79cd7c5c29ffa938": "{count, plural, one {Tried to read terminals {count} time} other {Tried to read terminals {count} times}}", "537feee59d775e17": "{count, plural, one {Pré-visualizou {count} página HTML} other {Pré-visualizou {count} páginas HTML}}", "4b45ac8cb8df04a4": "{count, plural, one {Tentou pré-visualizar {count} página HTML} other {Tentou pré-visualizar {count} páginas HTML}}", "a6f62fca5dd25455": "{count, plural, one {Renderizou {count} página HTML} other {Renderizou {count} páginas HTML}}", @@ -376,6 +399,31 @@ "476ca970255eaea4": "Vincule este ambiente ao T3 Connect para ter uma URL pública.", "6b80f5b38a8f9950": "Só este computador pode acessar este endereço. Vincule o T3 Connect para ter uma URL pública.", "c5a7b1d3891dd0b8": "Funciona onde o endereço deste ambiente for acessível, por exemplo pelo Tailscale ou pelo seu próprio proxy. Vincule o T3 Connect para ter uma URL pública.", + "3669395daf36fd33": "Não está mais registrado neste servidor", + "fe513cf316e796e3": "Executa como parte de outros workflows", + "ccf00b97925efab3": "Iniciado manualmente", + "421e585eb092b07b": "Inicia com {triggers}", + "7bd7c58592671384": "Precisam de você", + "834ca879c14c167b": "Trabalhando", + "582d6df7dfab86fb": "Pausada", + "ea6583ce92507ee3": "Dormindo", + "7ea8cb8af281ce93": "Aguardando", + "1347868f2523140e": "Concluída", + "57d76c4614054271": "Parada", + "5c7344bd51d0b966": "Pulada", + "b2074e9bd23049a6": "Cancelada", + "5bb7401807ee2fb5": "Pergunta: {question} e mais {more}", + "9e4286183d5f9e34": "Pergunta: {question}", + "474c18d001bd6717": "Uma etapa falhou", + "d3890f4eb1508781": "Executando as próprias etapas", + "3e7ced10c9482af0": "{step} está trabalhando", + "237e1bcb1cf1bdec": "Dormindo em {step}", + "3f7b17ac5a20c8d2": "Executa {run}", + "0306f5f324b8aaa5": "{count} execuções em andamento", + "e8fd779b84a202a2": "Aguardando", + "b6d55657e1a027b8": "Aguardando {step}", + "e942562a42aede34": "Concluída", + "26b2b9727fe11289": "Encerrada antes do fim", "1bb995dcec481554": "Aprove este dispositivo em {host}. Ele mostra o código {verificationCode}.", "8696a33219944832": "Não foi possível criar a prova de autorização do websocket.", "5678f133a8631f7d": "Seu login na nuvem mudou. Entre novamente para autorizar o ambiente.", @@ -637,6 +685,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", @@ -1721,6 +1772,8 @@ "2e995206e087c3fc": "Tente responder depois que a conexão ou a resposta pendente for resolvida.", "604ec3067171a0d7": "Conversa", "d6182a057ea12624": "Thread principal", + "f2d8537c33cc55a5": "Etapa da execução do workflow", + "ba8337dca3232880": "Abrir execução", "30fa4a764d11ae42": "Não foi possível baixar {name}", "4952f87dc98191a7": "O anexo não está disponível.", "2fd6d178493fb407": "Falha ao interromper o turno atual.", @@ -1785,6 +1838,8 @@ "181677cda4d3fd0a": "Nenhum ambiente conectado pode adicionar um projeto", "3a0bf3d17f31584e": "Nova thread em {project}", "4b4b64cc95acb8da": "Nova thread em...", + "2c45783ab9680fdb": "Open Git graph", + "e813386e62652710": "Open agent stage", "3f581e98c86df72a": "Nova thread sem projeto", "e510d9a7b684fbfe": "Fazer a triagem de um problema", "cce3d80a2ddf1125": "Um agente investiga um problema do T3 Code e ajuda a abrir uma issue", @@ -1806,6 +1861,7 @@ "04fd71efaa2c3b92": "Abrir pull requests", "57e875b79b98ab82": "Abrir issues", "f1db0a234c777a1d": "Usar o T3 Code em outro app (MCP)", + "6050f22f63e2bcb5": "Abrir workflows", "a0cc19e60dd99851": "Abrir uso", "46694969044eee98": "Focar a próxima área do workspace", "0a1011328ba42eef": "Focar a área anterior do workspace", @@ -2071,7 +2127,7 @@ "cd80122422577239": "Publicar repositório", "c85db9ac99efa605": "Push e criar {term, select, mr {MR} cr {solicitação de alteração} other {PR}}", "dbccf81ad4a03f48": "Sincronizar ref", - "4350ab8128b18105": "Pull", + "4350ab8128b18105": "Fazer pull", "dca2ca8303bfc14e": "Fazer commit e push na ref padrão?", "e196fda632e279d0": "Esta ação vai fazer commit e push das alterações em \"{branch}\". Você pode continuar nesta ref ou criar uma ref de feature e executar a mesma ação nela.", "87e714255e8be7f2": "Fazer push na ref padrão?", @@ -2361,14 +2417,24 @@ "05037ca1666fd421": "Os terminais só estão disponíveis a partir de uma thread de projeto.", "a3aa1e49af278d41": "Os arquivos só estão disponíveis com um projeto aberto.", "87ea6995ea1e7aa4": "O diff só está disponível para threads do servidor em repositórios Git.", + "80f10f5ea1804d8d": "The Git graph needs a Git repository on an up-to-date server.", "4a87cae01ccde544": "O branch desta thread ainda não tem pull request.", "32535dba0b9af642": "Esta thread não tem itens vinculados.", + "d955eee48dece3c0": "Enable the agent stage in Settings > General.", + "d2f2f6d05148f8a3": "Threads a coordinator runs have no thread overview.", + "26c1c05b0d1d98fd": "Turn on coordinator decisions in Settings > General.", + "486d4369c4fbec9e": "Notes are only available from a thread.", + "50b5a57d3bd6f6ef": "Instructions are only available from a thread.", + "007ab76950f73521": "Media is only available from a thread.", "07080dead70f4cc5": "Os dispositivos só estão disponíveis a partir de uma thread.", "a4bf49b31758ff7e": "Disponível só no app para desktop.", "e917841cb66f9af1": "Disponível com um projeto aberto.", "14c15fad0c2ee0c8": "Disponível para repositórios Git.", "9176276c78f3893f": "Ainda não há pull request neste branch.", "52ce9db6fb62a59f": "Nenhum item vinculado disponível.", + "96c2ee76dd82d2cc": "Enable it in Settings > General.", + "2199013487151590": "Not for threads a coordinator runs.", + "f7a9300d9f9030d5": "Turn on coordinator decisions in Settings.", "e5d6f41e4fe4efd6": "Disponível a partir de uma thread.", "0ebc2bb883a8e283": "Disponível após a primeira mensagem.", "84d0ff8fb9846057": "Ativar som da aba", @@ -2377,8 +2443,15 @@ "5c78a8ae7b71af1d": "Terminal", "cba3e832ece50257": "Arquivos", "83ac3423d6dfc4a7": "Diff", + "016750bdd5076287": "Git graph", "da16af47eff38ae9": "Pull request", "ad3929f0103925d7": "Itens vinculados", + "70e7b208e032024a": "Stage", + "0caf7e5748f1d17b": "Threads this one started, and which need you.", + "96018894225bd4ff": "Inbox", + "0ed16d7723c04288": "Decisions the coordinator asks you for.", + "aec2b493d2b01445": "Notes", + "9e92f6aa6edae875": "Notes and todos for this thread, its project, or everywhere.", "ac0de2a59d9c8860": "Dispositivo", "1354df9fb7278843": "Acompanhe um iOS Simulator ou Android Emulator.", "fdcd9643e2e63b15": "Faça uma pergunta paralela enquanto esta thread continua trabalhando.", @@ -2497,8 +2570,7 @@ "2d1c111e1b4ae0b0": "Excluir a thread \"{title}\"?", "c568ab8dad798ec5": "Isso apaga permanentemente o histórico de conversa desta thread.", "0fd1c746a0e38003": "Falha ao excluir a thread", - "0ecde875b0dd2f93": "Filtrar threads por projeto: {projects}", - "1ef65b647231ff0b": "Filtrar threads por projeto", + "1c8fc3c4a42949ab": "Projetos: {projects}", "165511761be2855c": "Pesquisar projetos", "a46a6467883575a4": "Pesquisar projetos...", "fdc0e086438a3045": "Configurações do projeto {project}", @@ -2560,10 +2632,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 +2644,7 @@ "a3178769f8308cbc": "A thread falhou", "89b5e8f3887812da": "Pedido de convidado", "62e626804919b294": "Resposta necessária", + "c6196d99000642b4": "Abrir thread", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Você:", "a1fbf2422c588292": "Agente:", @@ -2596,8 +2668,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", @@ -2686,8 +2756,6 @@ "78a04e0e625c0990": "Falha na atualização", "c24de5eb69373a55": "Esta build {build} ignora as versões {track}. Revise o canal de atualização em Configurações para concluir a troca.", "b02ae45a6109c93b": "Atualizado", - "edcda9e8ee4ccad8": "Instalar a atualização {version} e reiniciar o T3 Code?\n\nAs tarefas em execução serão interrompidas. Verifique se está tudo pronto antes de continuar.", - "02eba0f7cc90f759": "Instalar a atualização e reiniciar o T3 Code?\n\nAs tarefas em execução serão interrompidas. Verifique se está tudo pronto antes de continuar.", "9ed4d8a1531b9631": "Atualizações automáticas não estão disponíveis nesta versão.", "c8c23435e780a60c": "Atualizações indisponíveis", "1af5f9767371ffd7": "Verificar atualizações", @@ -3034,8 +3102,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 +3346,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 +3523,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", @@ -3577,6 +3649,13 @@ "c53bc5a4b0314342": "Próxima mídia", "2950b1424a3cddf5": "Reconecte-se a este ambiente e abra a mídia novamente.", "ef638bf1479a5461": "O ambiente retornou uma URL de mídia inválida.", + "3ccfbf7e86868c35": "Feedback para a equipe do T3", + "4e0710d19dfc2e7e": "Enviar este relatório para a equipe do T3?", + "87d0ae0723ba75d1": "Isto é tudo o que sai da sua máquina. Nada é enviado até você clicar em Enviar.", + "bf19826f81484328": "Incluir a conversa", + "ddb7e6f8ce99e657": "Somente quem pode executar agentes nesta máquina pode enviar ou recusar o relatório.", + "03c1eb603c112f47": "Não enviar", + "653405e4ed498d9f": "Enviar", "262955d6eb632f9b": "A API da área de transferência não está disponível ao copiar o link de convidado.", "f1a4f2b04cdbb4ef": "Falha ao copiar o link de convidado para a área de transferência.", "cf3490a604e44d31": "Não foi possível criar um link de convidado.", @@ -3597,7 +3676,6 @@ "abd89e9eefedf11b": "Concluído", "18d166056c1ab6ff": "Parar de compartilhar", "7a2d510eac9e4587": "Link de convidado expirado", - "653405e4ed498d9f": "Enviar", "21888e302219891d": "Pré-visualização expandida de {title}", "419719298a7acaea": "Diminuir zoom", "ed8d5db95359cff4": "Redefinir zoom", @@ -3693,7 +3771,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 +3782,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 +4058,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", @@ -5453,6 +5528,22 @@ "f0d79aa56f06663f": "Este arquivo é grande demais para ser mostrado por inteiro. As contagens incluem todas as alterações.", "7fdde2b893ba1b9d": "Removido", "e58ce271d835b447": "Adicionado", + "fb5c7ff5ea76e01a": "Added by esveo's fork. Click to list all of its settings.", + "352fa6aeb5d55665": "Trail the provider icon behind the thread title instead of giving it a line of its own. The line it saves also carried the branch, pull request badge and diff counts.", + "9d44fa03a230e0d8": "Reset two-line thread cards to default", + "7b216eedb1abe696": "Two-line thread cards", + "8d90fcd918e901c8": "Keep each project's threads together in the sidebar, under a header that folds the project away. Ordering stays by recency: the project with the newest thread leads.", + "d5dfd89c9a281386": "Redefinir o agrupamento de projetos para o padrão", + "aac9f889c7ec7ff5": "Group sidebar threads by project", + "da375a07c5309184": "Show how full the thread's context window is next to the composer controls.", + "33f6b88cba203990": "Reset context window usage to default", + "6496f57baeded3fa": "Context window usage", + "d9c146dc6b95714d": "Show how many minutes are left before the prompt cache expires. Claude only.", + "69609e27c2107da5": "Reset prompt cache timer to default", + "a4917d2b93c478f6": "Prompt cache timer", + "ea8ebcb77e657e9f": "Open the thread details card with workspace and version control in every thread. Off, it stays closed until you open it, and each thread remembers your choice.", + "662288b90e19635f": "Redefinir os detalhes da thread para o padrão", + "92729a403d37c575": "Open thread details by default", "07b9970b662ab70d": "Mostrar o código Mermaid", "5a422b7be35243f5": "Mostrar o diagrama renderizado", "c0628ad999cbbbf5": "Mostrar o código Markdown", @@ -5560,6 +5651,7 @@ "723d88a5fa7e2fdd": "Nenhum arquivo correspondente.", "f8d6e9a1a2870a5c": "Explorador de arquivos", "109edd252917113b": "Redimensionar o explorador de arquivos", + "7abd6af24fed7b60": "The file does not exist in the workspace or the home folder.", "37cbd2ecc659a007": "Arquivo", "b5188f172f59ca79": "Esta conexão não pode ler arquivos do host.", "c3c5d36466ad2191": "Abrir o arquivo no navegador de pré-visualização", @@ -5599,7 +5691,6 @@ }, ". Verifique o caminho do link ou localize o arquivo em Arquivos." ], - "b9b6bbd1e1ea189f": "Arquivo completo", "d715e9494fdbaaf6": "Não foi possível carregar a fonte.", "ff17c777a72b4408": "As pré-visualizações de fontes são limitadas a 10 MB.", "6bd41ad699e22f10": "A fonte não está disponível.", @@ -5609,6 +5700,7 @@ "a9abaaa4220eae21": "{error} Salve-a para abrir em outro app.", "c508c9000d9656f8": "Pré-visualização da fonte", "1c416d621d250be8": "Um pequeno jabuti xereta viu dez cegonhas felizes.", + "d7d08260f16b7828": "O arquivo ainda está carregando. Tente novamente em instantes.", "76ebb03de52c92d6": "O visualizador de texto parou.", "f48162e8e8c12af7": "Não foi possível carregar o visualizador de texto. Feche o arquivo e tente novamente.", "bc4c5b13d38a5da7": "Pré-visualização fechada.", @@ -5616,8 +5708,6 @@ "9450d1827ef336a1": "Outra cópia está em andamento.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} linha} other {{formatted} linhas}}", "13b14784f8707ddd": "0 bytes", - "f6e9581cba3467fa": "Indexando…", - "2d1f293ac12463fc": "Carregando o restante do arquivo…", "b75105bef8f564a4": "Mostrando as primeiras 1.024 colunas. O código-fonte e o arquivo salvo mantêm todas as colunas.", "2a6e1b1f209c3888": "Este arquivo está vazio.", "192fc79eb3b5b2cb": "Este diagrama contém URLs de recursos, markup, metadados de nós ou configuração personalizada. Mostre o código Mermaid para inspecioná-lo com segurança.", @@ -5804,7 +5894,6 @@ "0061fff77e36bd4f": "Não foi possível acessar o servidor.", "04dfdd46e3dd4a2e": "Algo deu errado. Tente novamente.", "084bb2d8127a508d": "Enviada", - "e7c59185f8ab3987": "Não enviada", "77c01a15bd36d17c": "Este link expirou ou não é válido", "e0e736810f3cbef2": "Peça um novo link ao proprietário. Cada link funciona em um navegador.", "c3c53aa46f7330e5": "Este link expirou", @@ -5826,6 +5915,13 @@ "cbb2129c0dd4f40b": "Os arquivos anexados podem somar até 10 MB por mensagem.", "03b9cd79cfe0b435": "Este arquivo não pode ser anexado. As imagens precisam ser PNG, JPEG, GIF ou WebP.", "8ff29c78798e6ac1": "Não foi possível carregar este item.", + "535923000a0f3e3b": "Send /compact to a large, idle Claude thread shortly before its 1-hour prompt cache expires, so the next message skips caching the whole conversation again. 5-minute caches are left alone.", + "bd8eb8f5f9843bc6": "Reset idle auto-compact to default", + "1db274eacf03c8de": "Auto-compact idle Claude threads", + "fb6643c75aafd996": "Between {min} and {max}; it has to fall inside the cache's hour.", + "48dee64ca7904281": "Minutes idle before auto-compact", + "8937fe924464eb70": "Smaller threads are cheap to cache again and keep their full history.", + "1981f1e1a753aabc": "Minimum context tokens for auto-compact", "94ab4591ce101233": "Não foi possível publicar o comentário", "92d0d4eab2596772": "O rastreador recusou.", "33591d9596fb7cb7": "Adicionar um comentário", @@ -8693,12 +8789,16 @@ "58e0e226493150e7": "Não foi possível carregar os rastreadores de issues", "77cfcbde543df32d": "Mostrar ou ocultar detalhes de {tracker}", "0083f65885c60156": "Desconectar {tracker}", - "295392927d5c8a84": "Escolha um ou mais {scope}s do {tracker} para cada projeto. As issues deles aparecem ao lado das do repositório, e os agentes criam novas issues no primeiro.", + "ed83b25c71c98a20": "Escolha um ou mais {scope}s do {tracker} para cada projeto. As issues deles aparecem ao lado das do repositório, e os agentes criam novas issues no primeiro, a menos que outro seja pedido.", "19c2d5e81ff8f89a": "{scope} do {tracker} para {project}", "68e061510b765772": "Não vinculado", + "99d51127f573296b": "Outra conta", + "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}.", + "99963c0142e17f00": "Para a nova conta do {tracker}.", "a2d95d39d3398bda": "Credencial recusada", "9eae463720500113": "Armazenado no servidor.", "b6e27ab2537ef874": "Criar um", + "6d8e4ebc889bace9": "Adicionar conta", "13ef526271b0f5d4": "Limpar todas as condições", "d1938a629f039515": "Remover condição", "84a605b241ce65b7": "Remover grupo e as condições dele", @@ -8828,6 +8928,12 @@ "d3866ead082d14e5": "Adicionar atalho de teclado", "d4345c90894a3220": "Abrir keybindings.json", "e56a8d51219efaa0": "Nenhum atalho de teclado corresponde à sua pesquisa.", + "90a258fff61fd77e": "Desativado", + "4060244a7079a0d2": "Quando eu pedir", + "e88c9d8769544731": "Automático", + "f29d1dade4dde8aa": "Os agentes não enviam feedback para a equipe do T3.", + "93c4c53562d30a98": "Quando você pede, os agentes mostram um breve relatório sobre o T3 Code e o enviam para a equipe do T3 se você aprovar.", + "cd9ee803e8727017": "Os agentes também relatam por conta própria os problemas que encontram no T3 Code, como uma ferramenta do T3 que falhou.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Agrupa as threads da barra lateral em pastas de projeto. As threads fixadas ficam no topo, e Adiadas e Concluídas ficam abaixo das pastas.", "e4e91d155cb6a9b4": "Barra lateral sem graça (agrupar por projeto)", @@ -8836,11 +8942,16 @@ "9ae293971d93c819": "Compartilhe uma thread com um convidado que a acompanha ao vivo no navegador e envia mensagens que você aprova. Entre no T3 Connect para usar links de convidado.", "0aa5406ac4d7f7c7": "Links de convidado", "f0e853acd2006d53": "Ambientes vinculados", + "ef10c2dff987f3ea": "Execute workflows de várias etapas a partir de arquivos na pasta workflows da pasta T3 deste servidor. Abra-os pela paleta de comandos. Enquanto estiver desativado, nada dessa pasta é executado; as execuções aguardam até que seja ativado novamente.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Mostra uma próxima mensagem prevista no editor vazio após um turno do Claude ou do Codex. Tab a usa. Cada uma é uma requisição extra em cache no seu plano. Requer Codex 0.165+. As threads do Claude são atualizadas ao reiniciar.", "d4b2a2ec812aafb0": "Sugerir próximo prompt", "298c7150a7621c80": "Hosts de dispositivos Simlock", "67937aa49179285e": "No Mac, clona novos worktrees a partir de um checkout em cache na pasta T3 home em vez de gravar cada arquivo. Usa o checkout normal do Git quando não consegue. Desativar exclui o cache.", "f9904f78d3003f58": "Checkout rápido de worktree", + "9c2f647882522302": "As máquinas selecionadas usam modos diferentes de feedback dos agentes.", + "31bbf7bf8c0a5279": "Feedback dos agentes", + "d52b3d6bf9f2a013": "Misto", "ec7623deed751c05": [ "Compartilhe uma thread com um convidado que a acompanha ao vivo no navegador e envia mensagens que você aprova. Requer T3 Connect: entre e vincule esta máquina em", " ", @@ -8925,7 +9036,9 @@ "fb71127e5746a6bc": "Em Compartilhamento e acesso de lá, ou t3 pair", "1e3fee7084791773": "Vincular também {target} de volta a {source}", "ea34a190b0bd804c": "Os agentes de {target} poderão trabalhar também em {source}.", - "ad5ed0ce61b966eb": "Esquecer {label}? Os agentes daqui deixam de funcionar lá. Revogue \"T3 Code · …\" em Compartilhamento e acesso de {label} para encerrar a sessão lá também.", + "974f8c65e8b5f492": "Esquecer {label}? Os agentes daqui param de trabalhar lá, e a sessão deles em {label} também termina se ele responder.", + "6cf9e3083b15614f": "{label} não respondeu", + "34ccbdf619b83be3": "Revogue \"T3 Code · …\" em Compartilhamento e acesso de {label} para encerrar a sessão lá também.", "81c9796bf61b306a": "Não foi possível esquecer o vínculo", "130e51beb6cf5aad": "Vincular um ambiente", "122c3e355699e69d": "Os agentes daqui poderão então iniciar threads lá, enviar mensagens e aguardá-las. Ele aparece em Clientes autorizados em Compartilhamento e acesso daquele ambiente, onde pode ser revogado.", @@ -9155,7 +9268,6 @@ "0b4779a1825c85bc": "O nome compartilhado deste grupo de projetos na barra lateral e nas listas de threads.", "f68cbda4df83d739": "Redefinir o nome do projeto para o padrão", "56e37b85027e8431": "Ícone do projeto", - "e88c9d8769544731": "Automático", "c99736317da5b1fa": "Redefinir o ícone do projeto para o padrão", "6afaa3e3739dc570": "Escolha um ícone para o projeto", "51651ce45d481a20": "Escolha um arquivo de ícone para o projeto", @@ -10064,7 +10176,6 @@ "53de7aafe0afc10d": "Não foi possível restaurar as configurações de tema", "006bfa1846fe5dd2": "Dias de inatividade antes de concluir automaticamente", "d9b0fbd680d5f175": "Barra lateral", - "d5dfd89c9a281386": "Redefinir o agrupamento de projetos para o padrão", "cd5452cc9e13c818": "Agrupamento de projetos", "cfb01b8a2a3361fb": "Redefinir a ordem dos projetos para o padrão", "26abcbe322049a8a": "Redefinir a seção Trabalhando para o padrão", @@ -10129,7 +10240,6 @@ "16bdc70b858c223f": "Redefinir os painéis proativos para o padrão", "c5424f09d77138ff": "Quando compactar uma thread do Claude ociosa com mais de 200.000 tokens: depois que você voltar, logo antes de o cache do prompt expirar ou nunca. Cada provedor Claude pode substituir isso.", "3e99c5c14f4939c8": "Redefinir a compactação de threads ociosas para o padrão", - "d52b3d6bf9f2a013": "Misto", "cd72fe451ba0d6aa": "Novos projetos", "394c3bd0a1782c8e": "Deixe vazio para usar \"~/\" quando o navegador de Adicionar projeto abrir.", "f9b912a818bd869d": "Redefinir o diretório base para adicionar projetos para o padrão", @@ -11031,7 +11141,6 @@ "4a237f41ce592b7f": "Mantém os worktrees deste projeto até você excluí-los manualmente.", "00b8ffd8ea6e6a93": "Usa estas regras neste projeto.", "72c279824d15a999": "Usa as configurações de limpeza de worktrees de cada máquina.", - "90a258fff61fd77e": "Desativado", "b5702d0b64866b08": "Personalizado", "c009c901f3eefe78": "Excluir worktrees de threads excluídas", "431c7cd6d50102b7": "Remove worktrees sem uso quando threads ativas ou arquivadas são excluídas. Worktrees com alterações locais são mantidos.", @@ -11388,7 +11497,6 @@ "f2043e87a10cb831": "Editar tema", "595bdeefcdc9bf31": "Exportar arquivo de tema", "b480281b3791b685": "Escolha o que o cartão de detalhes da thread mostra. Você também pode clicar com o botão direito no cartão.", - "662288b90e19635f": "Redefinir os detalhes da thread para o padrão", "871d059d88548434": "Detalhes da thread: {enabled} de {total} ativados", "cec1fbb8b4c9180d": [ { @@ -11727,7 +11835,6 @@ "4c70e3e7b3e6c493": "Segredos", "79b768229c9ef672": "Manutenção", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Sobre", "af4b7734da1d5ce7": "Voz", "4ec62c39ca3192bf": "Versões e issues", "f2bf529f85e05494": "Compartilhamento", @@ -11756,11 +11863,17 @@ "8f5966eebd2b110f": "aparência cores paleta personalizada importar", "633ed64e952cca3b": "cores bordas interface", "9cf8308531b4ff31": "transparente transparência sólido menus caixas de diálogo editor de mensagens", + "d99bfbc557fae743": "Notion", + "89df56091835b3a6": "notion integration secret pages links viewer connect token ntn", + "d699adcc04d4d4ab": "sidebar compact row height branch provider icon diff pull request", + "9b9df5ba41c4a8e2": "Group threads by project", + "0ed2eab2c1953531": "sidebar project folder runs grouping collapse header repository", "d8d6cfd630cff22d": "vermelho verde azul laranja adições exclusões alterações contagens paleta daltonismo", "717e49895cfee1c7": "largo largura total coluna layout mensagens editor de mensagens monitor", "88365077fd80787b": "personalizar mostrar ocultar painel cartão ambiente editor scripts branch pull request git alterações servidores automações linhagem uso limites 5 horas semanal cota tokens janela de contexto", "d561f74efa5f3920": "esforço de raciocínio pensamento barras gráfico palavra rótulo nível editor de mensagens", "6113c17109ee0d57": "latex tex katex equações fórmulas markdown", + "dfe7ead48efc3f5a": "thread details card panel workspace version control closed collapsed hide", "8c8364d44fa28d22": "dev nightly latest canal arte pílula rótulo ocultar nenhum", "2d90635156dfcb5a": "tipografia família tamanho sistema sans", "d32e93777e4819c8": "tipografia família tamanho editor de mensagens entrada", @@ -11782,6 +11895,7 @@ "d443390c4d2dcfd4": "acessibilidade a11y leitor de tela nvda jaws voiceover orca narrador título da janela título da aba alt tab barra de tarefas status da thread ordem trabalhando aprovação", "6826fa9579c22035": "beta compartilhar convidado convite link colega acompanhar t3 connect túnel", "f10c06cba0cdf7fe": "beta vincular outra máquina vps par agentes trabalham lá delegar", + "bc0b409d89ce086e": "beta workflow execuções duráveis automação etapas agendamento webhook pasta", "4a21cf825a2045b0": "beta tab autocompletar prever próxima mensagem claude codex texto fantasma", "fea2dc36585c4a20": "Hosts de dispositivos Simlock (alfa)", "9d834d178130180e": "beta alpha simlock callstack simulador emulador ios android pool lease gateway", @@ -11823,7 +11937,29 @@ "34d74827c2a8b009": "enter return command ctrl várias linhas prompt nova linha editor de mensagens", "9d1013084c46ecce": "fila enfileirar direcionar turno em execução enviar comportamento padrão editor de mensagens", "e5e7f5e1fb1f2e4c": "subagente chat paralelo thread vinculada clique painel direito painel lateral visualização principal comando ctrl clique do meio", + "5c59d7e2673267ea": "composer tokens usage meter percentage compaction", + "e0d6ec10218b714e": "composer claude cache ttl expire minutes warm cold tokens", + "ce0952668aba4140": "Agent stage", + "f637899f994b78c3": "sprites stations subagents thinking editing terminal right panel everything", + "9d9d3374ee961b91": "Easter eggs", + "571180dbfeddbfd5": "surprise fun rocket animation message send hidden", + "0716adb0d55ffa58": "Voice calls", + "027d8f5ea5555973": "voice call phone gpt live feature flag anruf telefon schalter", + "60d509bb55e2967c": "Voice call voice", + "0e5f5c5ebf026abd": "voice call phone gpt live speaker stimme anruf telefon", + "266f1e2b55e419b0": "Voice call follow-up", + "392226d9bed6fe21": "voice call queue steer follow-up warteschlange anruf", "5b8b854de7ee6f4d": "cli instaladas versões mais novas disponíveis codex claude cursor grok fx kiro opencode", + "1ceaab7d898b689a": "Child threads in the sidebar", + "fa5a42a73d1c1ece": "coordinator subthreads nested group expand sidebar orchestration children", + "6a1072050d1ad19e": "Coordinator decisions", + "474ba8e025886f86": "inbox questions answers decide approve coordinator open items", + "8f5558f063214509": "Cross-project threads", + "b809e3ffa5178b88": "agents coordinator other projects read message start threads repositories", + "44207b47d209f601": "compact context prompt cache idle claude tokens cost expire", + "396a2cc5b442e359": "compact idle minutes prompt cache ttl", + "6d9520a9cbd70c2f": "Minimum context for auto-compact", + "2fe046cc1e0d0d4a": "compact context tokens threshold size", "64f12530d55d2ad1": "retomar em execução ativo interrompido trabalho reiniciar reboot máquina falha atualização do desktop automaticamente", "214a98497c4ed05d": "caffeinate repouso impedir manter acordado energia notebook tampa inibir", "00469926c7027e2d": "equilibrado desempenho economia de bateria avançado git fetch verificação de provedores atualizar host energia monitor política de ociosidade", @@ -11853,6 +11989,7 @@ "901a823214edc8c4": "telemetria analytics dados de uso rastreamento legal desativar", "82136480255a5106": "OTel OTLP telemetria exportar endpoints logs traces métricas Grafana", "659d081051faf7ff": "logs traces processos histórico de recursos falhas spans cpu memória", + "5eaeacfa9f82051a": "relatório bug problema t3 equipe enviar feedback agentes ferramentas automático quando eu pedir", "f537f91e1ee41d47": "atalhos de teclado teclas de atalho comandos bindings json", "1ba01e7ceed64b95": "janela captura captura de tela", "279b1cceb779ff38": "Incluir texto do app", @@ -12058,6 +12195,8 @@ "v": "v" } ], + "643c4b50feadc874": "Worktree: {path} ({branch})", + "fb7c44da0f0825ea": "Worktree: {path}", "e7f35f60e6229cf5": "App desktop", "77be1b7e2a1d3d31": "{count, plural, one {Atualizar {count} máquina?} other {Atualizar {count} máquinas?}}", "e4892b21e88abb60": "{count, plural, one {{count} atualização de provedor} other {{count} atualizações de provedores}}", @@ -12121,6 +12260,25 @@ "ffaa75d2db1e7cc1": "A atualização não foi aplicada", "626bcbe04dc55f93": "O T3 Code ainda está na {current}. Instale a {version} novamente pelo botão de atualização.", "49214c047fbb1606": "Atualização do provedor interrompida", + "a135af0f1efda8de": "Cross-project", + "6e9798372b3fb922": "Coordinators put the questions they need you to decide into an Inbox tab beside the chat, instead of numbering them in their messages. Running sessions pick up a change.", + "7a5292a1705defec": "Reset coordinator decisions to default", + "9e3ff0f05f52b724": "Let agents read, message and start threads in other projects of this environment. Running sessions pick up a change.", + "384695cdd7ab6b54": "Reset cross-project threads to default", + "5a6c243a03eeca0c": "Choose a coordinator", + "f527bb5b4ad333da": "Coordinator for \"{title}\"…", + "6beb2db2a7b5edae": "Could not assign the thread", + "4ebb0c90c45690c0": "Could not detach the thread", + "73ac4f532306bea6": [ + "Assign \"", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "\" to a coordinator" + ], + "1871eb35b1ca5d41": "No thread can coordinate this one.", "52adbc863aeb5e59": "Falha ao copiar", "0944728904d886d2": "Saturação e brilho de {label}", "dded2cb4e4d26338": "Saturação de {label}", @@ -12322,7 +12480,6 @@ "0bd41ff995d36a66": "Leitura de cache", "3f0dfe0cb15a3272": "Gravação de cache", "1c9d860be42b1c02": "Saída", - "78344b60f407928e": "Outros", "684e516076de81fe": "Padrão", "3bbcc1b826fef537": "Rápido", "66796576034c18ea": "Ultrarrápido", @@ -12338,6 +12495,270 @@ "2cddd6095abc734a": "7 dias", "53493056306708cf": "30 dias", "c719359d18d37ad3": "90 dias", + "a7ad3167ca62e7de": "Talk to your agents by voice with GPT-Live on your Codex ChatGPT login. Turning this off ends a running call.", + "9f0e45a1d67187cd": "Reset voice calls to default", + "da0ae8174ac2fc14": "Queue what you say in a voice call while the agent runs, or steer the current run. Saying otherwise overrides it for one message. A change applies from the next call.", + "fb0a2aa3b08a17c4": "Reset voice call follow-up to default", + "66936cae56d1d749": "Queue", + "89bf6f658c44cb1b": "Steer", + "930a28582d2c103f": "The voice that talks to you in a voice call. A change applies from the next call.", + "591a53f319b0d343": "Reset voice call voice to default", + "0bd950151ddc6407": "Sair sem salvar? Suas alterações neste arquivo serão perdidas.", + "c0ba3f6756b09f30": "Alterações não salvas", + "6914e22d357f0ad6": "Salvo e em execução", + "aff389354a031d6f": "O arquivo no disco não carrega. A última versão que carregou continua em execução.", + "858effde748ab563": "Salvo, mas ainda não está em execução.", + "ddb37138df660942": "Não salvo. Nada mudou no servidor.", + "6ef4db489e40e39e": "Não foi possível salvar", + "c89624a2e9af1793": "{name} não está conectado", + "b5a352a43adb4c17": "Os fluxos de trabalho dele voltam a aparecer quando ele se reconectar. Escolha outro ambiente para ver as execuções dele.", + "3dcedb736d20aae5": "Não foi possível ler os arquivos de workflow", + "b09f4df8d76ae8ea": "Excluir {file}? Os workflows que ele define não poderão mais ser iniciados.", + "b4535f5a03689d27": "{name} não está conectado. O que você escrever aqui fica guardado e pode ser salvo assim que ele voltar.", + "b54c78d85fd942ea": "Excluído, mas o que está em execução ainda não foi atualizado.", + "407c228d7da0b7df": "Não excluído. Nada mudou no servidor.", + "1a6aa10f3cc14fff": "Estes arquivos não são compatíveis entre si. O que rodava antes continua em execução.", + "259312516a1dbe6f": "Nome do arquivo", + "2f48ab2aa0586853": "Não define nenhum workflow", + "ba5adfa37b55b8c5": [ + "Linha ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Excluir", + "84c900d1ae72adc6": "Salvar", + "5912d817be03247a": "O arquivo mudou no disco enquanto você editava. Salvar substitui essa alteração.", + "0b1e6f5608826387": "Carregar o arquivo e descartar minhas alterações", + "f47b4c06aeb77c1c": "Carregando os arquivos de workflow…", + "4353bfd401d58f87": [ + "Cada arquivo em", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "define workflows. Uma alteração em qualquer um deles é aplicada sem reiniciar." + ], + "0c165251a06f10f1": "Novo arquivo", + "8e97cf734b4463e7": "Criar", + "2ec0d5108fd6cebe": "Nenhum workflow ainda. Crie o primeiro arquivo aqui ou peça a um agente para escrever um nessa pasta.", + "5601350626e8cfe9": "Não carrega", + "21d778a1b9a0c234": "Aberto ao lado da execução", + "62dc4d3a19ff7ca0": "Fechar aba", + "1e25265f2758fce3": "Abrir como thread completa", + "672a3dae06b39402": "Abrir na própria página", + "7755500a4cde5066": "Fechar o painel", + "b8dcbc93a2ca1861": "Esta execução não o lista mais.", + "115c69de3202f664": "Abrir", + "644eafa9048b62df": "{count, plural, =1 {1ª tentativa} =2 {2ª tentativa} =3 {3ª tentativa} other {{count}ª tentativa}}", + "e39f89c909df4db0": "Não foi possível retomar a execução", + "865f034346b82f47": "Cancelar {title}? Os agentes param e a execução não pode ser retomada.", + "6bc75632fd9c9136": "Não foi possível cancelar a execução", + "64e50329dcfdd5b0": "Concluída", + "350162e7cc1ebea4": "Parada", + "0875cf506f4c6810": "Pulada", + "3cc43f1dbf3f8e0c": "Cancelada", + "ded70e75de6404ba": "Voltar à lista de execuções", + "2f4ed7dbd22be30d": "Cancelar execução", + "614e5ad58a795fb5": "Parar", + "04b050b0329f0ac8": "levou {duration}", + "aff78e1774818ff4": "{duration} até agora", + "38eddd466439afc9": "O que a execução tocou", + "156ec271d49ddd70": "O que aconteceu", + "34f59bbbead0b97f": "{names} e mais {count}", + "ac1556f6ce89a5ea": "{count} em paralelo", + "e197c4963bacc746": "{count} em execução", + "f5319ed9e18c0df1": "Pergunta a você", + "882a25e9084ae1b2": "Pausada", + "9a03d8a9afc60387": "Etapas até agora", + "2f2ae791afe01674": "aguarda sua aprovação", + "24f8060c4ccdf928": "iniciando", + "30a5be40eb956663": "trabalhando", + "dd7a1e58c2553933": "acorda em {duration}", + "95cc952724dd7310": "prestes a acordar", + "3cc34921c0128593": "em execução", + "e777db2880f53a46": "ninguém respondeu", + "dc90739d391a5e67": "Você disse {choice}", + "389f2563b5b763fd": "Etapas rápidas", + "a41c8d758121ad81": "em espera", + "9db248b770096984": "aguardou", + "c76124517af28686": "em execução há {duration}", + "89102905bf09b0e8": "Assistir ao vivo", + "bdf338cdff4118f0": "Transcrição", + "811e7e992f9ff820": "não pode continuar até que a versão do workflow seja registrada novamente", + "4d4cdf035e98dd57": "aguarda você retomá-la", + "eb5b21dd224a5941": "tenta de novo sozinha em {duration}", + "6ab3dfa749fde477": "prestes a tentar de novo sozinha", + "44b6463aa70aa14c": "Por que pausou", + "cf25e7169ab0eb7a": "Pausada em {step}", + "56c48c1f220f2754": "Não foi possível responder à pergunta", + "a3c43735e1a81498": "Motivo para {title}", + "bfad234f016cfa3f": "O motivo, em uma frase. Ele acompanha a resposta que você escolher.", + "004c41aff9c97873": "Execuções", + "4dc0c244a2419f6c": [ + "Parte de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "iniciada", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "sua versão não está mais registrada", + "f92d9132f7b85d1a": "Carregando etapas…", + "6ebc59f64c761a49": "Nada ainda.", + "a759dccd157d7dae": [ + "Você disse", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Você disse", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Abrir execução", + "c8eb9be36d4d51ad": [ + "Thread em ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Retomar", + "8cebd63fc4c967d5": "Só a etapa que falhou é executada de novo; o que terminou antes dela é mantido.", + "bc1e0a2a0f1e9552": "Precisam de você", + "a812f51e970740f1": [ + "perguntou", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· a execução aguarda você" + ], + "02dfe6c63fd0b8a1": "Adicionar um motivo", + "19abd94828a3bdbc": "Perguntar ao agente primeiro", + "a18721fa8f328361": "Precisam de você", + "bbf24e7920c1e86b": "Em execução", + "8d6e18d2ad832db6": "Todas", + "f25af5332ffc3734": "Nada aguarda você.", + "c3f0119b8d6231f8": "Nada em execução.", + "33028dfc1229eaa6": "Nenhuma execução ainda.", + "5459bf696a187c26": "Não foi possível carregar as execuções de workflow", + "d57c35d43b0f163a": "Esta execução não está aqui", + "b9aae2f7cdb1a379": "Nenhuma execução de workflow ainda", + "8f15f66e545af7c0": "Quais execuções", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "Todos os workflows ({count})", + "46d614fa7b4bf1e5": "Execuções de workflow", + "1c635faa2fb45b8b": "Ainda não foi executado.", + "156ff7b625287a1e": "Ocultar puladas", + "69b985b97ab45e6b": "Mostrar puladas ({count})", + "2400254d362de84d": "Carregando execuções de workflow…", + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Um arquivo de workflow tem um problema." + }, + " ", + "A última versão que carregou continua em execução." + ], + "ed8ce6ebc73dc12d": "Abrir o arquivo", + "145e1f7503ba3b2c": [ + "Este ambiente não tem nenhuma execução com esse link.", + " ", + { + "t": "button", + "i": 1, + "c": "Voltar às execuções" + } + ], + "783e616cb0476c17": [ + "Um workflow reúne agentes, código, agendamentos e perguntas para você em uma única execução que sobrevive a reinicializações. Escreva um em", + " ", + { + "t": "button", + "i": 1, + "c": "Definições" + }, + ", ou peça a um agente.", + " ", + { + "t": "a", + "i": 2, + "c": "Leia o guia" + } + ], + "5d8d278ff828102d": "Todos os workflows", + "39459da07479f482": "Agente", + "7741243632056b81": "{step} · transcrição", + "c512071143a5ba32": "Esta thread não existe mais.", + "ed169d23683fb6ac": "Carregando a thread…", + "290e0ab40b87dc17": "Trilha de navegação de workflows", + "683dd9831e54edc0": "Ambiente", + "34ad53646f06ed80": "Os workflows estão desativados", + "8f6589c9e0ac5d4e": "Nenhum ambiente conectado", + "744127f8dfad7d22": "Conecte um ambiente para ver as execuções de workflow dele.", + "036182ec7e2ee4d4": "Ao lado da execução", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Definições", + "f0a212aadfe1257b": "Carregando o editor…", + "20f194e003885e95": [ + "Ative-os para este servidor em", + " ", + { + "t": "Link", + "i": 1, + "c": "Configurações → Labs" + }, + "." + ], "8367779e149f723b": "A requisição ao ambiente principal falhou durante {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Token de pareamento inválido. Verifique o token e tente novamente.", "0e4b49c8203aae81": "Tempo esgotado aguardando a sessão autenticada após a inicialização.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 65a8eede879fa..a83ae3f8cb74e 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -52,6 +52,27 @@ "eb0f60ef4f92ab7d": "Установите {fj} 0.6 или новее с {fjUrl} и выполните {fjLogin} либо установите {tea} 0.16 или новее с {teaUrl} и выполните {teaLogin} для каждого сервера Forgejo или Gitea.", "d026a85e2e50e675": "Установите GitCafe CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", "22d3c0c48a34b5b3": "Установите TanStack Source CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", + "756c80ad262ef315": "Ожидание в исходном треде", + "d8df14f9905f38eb": "Отправлено", + "e7c59185f8ab3987": "Не отправлено", + "b54ddec9084fa955": "Закрыто без отправки", + "fbaa7ab5da716e50": "Ошибка", + "01bac997ea55272e": "Непонятное поведение", + "0f53bc8f74dfe56a": "Не хватает возможности", + "055560f307e15e30": "Ошибка в документации", + "78344b60f407928e": "Другое", + "f653846a95cd6e8f": "Тип", + "f41ea186c275b56e": "О приложении", + "2f6e4f7cd364da73": "Ожидалось", + "9d11c93d4035de3e": "Произошло", + "c87d0595693704f9": "Что сделано вместо этого", + "d7a4ea6ce5af44e0": "{speaker} · {count} симв.", + "f5114fb9c40fd929": "Вы", + "cd03eb1b84271c02": "Агент", + "bfe1a60f3f9c60fb": "Ход {turn} · {what}", + "dfdaa6255a416140": "Обзор {turns, plural, one {{turns} последнего хода} other {{turns} последних ходов}}, {textTurns, plural, =0 {без текста сообщений} =1 {с текстом сообщений последнего хода} one {с текстом сообщений последнего {textTurns} хода} other {с текстом сообщений последних {textTurns} ходов}}{truncated, select, yes {, сокращено до допустимого размера} other {}}", + "260c6b45f52d2f27": "Добавляет текст ваших сообщений и ответов агента за {textTurns, plural, =1 {последний ход} one {последний {textTurns} ход} few {последние {textTurns} хода} many {последние {textTurns} ходов} other {последние {textTurns} хода}}.", + "afac52a5cc2dc801": "Не удалось отправить ваш ответ. Попробуйте ещё раз.", "79d776428f4d0650": "Не удалось загрузить файл. Переподключитесь и попробуйте ещё раз.", "3ea34cbb1ca5ba9b": "Предпросмотр отменён.", "7c0af279ecb3da3a": "Потоковый предпросмотр файлов недоступен в этой среде выполнения.", @@ -118,9 +139,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}.", @@ -246,6 +267,8 @@ "fec888c767b662d5": "Попытка проверить привязанные issue", "bc31067af9c79d82": "{count, plural, one {Привязанные issue проверены {count} раз} few {Привязанные issue проверены {count} раза} many {Привязанные issue проверены {count} раз} other {Привязанные issue проверены {count} раза}}", "c712fec8d9dc6dd6": "{count, plural, one {Попытка проверить привязанные issue: {count} раз} few {Попытка проверить привязанные issue: {count} раза} many {Попытка проверить привязанные issue: {count} раз} other {Попытка проверить привязанные issue: {count} раза}}", + "81c2282590e549f5": "{count, plural, one {Read terminals {count} time} other {Read terminals {count} times}}", + "79cd7c5c29ffa938": "{count, plural, one {Tried to read terminals {count} time} other {Tried to read terminals {count} times}}", "537feee59d775e17": "{count, plural, one {Показан предпросмотр {count} HTML-страницы} few {Показан предпросмотр {count} HTML-страниц} many {Показан предпросмотр {count} HTML-страниц} other {Показан предпросмотр {count} HTML-страницы}}", "4b45ac8cb8df04a4": "{count, plural, one {Попытка показать предпросмотр {count} HTML-страницы} few {Попытка показать предпросмотр {count} HTML-страниц} many {Попытка показать предпросмотр {count} HTML-страниц} other {Попытка показать предпросмотр {count} HTML-страницы}}", "a6f62fca5dd25455": "{count, plural, one {Отрисована {count} HTML-страница} few {Отрисовано {count} HTML-страницы} many {Отрисовано {count} HTML-страниц} other {Отрисовано {count} HTML-страницы}}", @@ -376,6 +399,31 @@ "476ca970255eaea4": "Привяжите это окружение к T3 Connect, чтобы получить публичный URL.", "6b80f5b38a8f9950": "Обращаться к этому адресу может только этот компьютер. Привяжите T3 Connect, чтобы получить публичный URL.", "c5a7b1d3891dd0b8": "Работает везде, где доступен адрес этого окружения, например через Tailscale или ваш прокси. Привяжите T3 Connect, чтобы получить публичный URL.", + "3669395daf36fd33": "Больше не зарегистрирован на этом сервере", + "fe513cf316e796e3": "Запускается в составе других воркфлоу", + "ccf00b97925efab3": "Запускается вручную", + "421e585eb092b07b": "Запускается по: {triggers}", + "7bd7c58592671384": "Ждут вас", + "834ca879c14c167b": "Работает", + "582d6df7dfab86fb": "Приостановлен", + "ea6583ce92507ee3": "Спит", + "7ea8cb8af281ce93": "Ожидает", + "1347868f2523140e": "Готово", + "57d76c4614054271": "Остановлен", + "5c7344bd51d0b966": "Пропущен", + "b2074e9bd23049a6": "Отменён", + "5bb7401807ee2fb5": "Спрашивает: {question} и ещё {more}", + "9e4286183d5f9e34": "Спрашивает: {question}", + "474c18d001bd6717": "Шаг завершился ошибкой", + "d3890f4eb1508781": "Выполняет свои шаги", + "3e7ced10c9482af0": "{step} работает", + "237e1bcb1cf1bdec": "Спит на шаге {step}", + "3f7b17ac5a20c8d2": "Запускает {run}", + "0306f5f324b8aaa5": "Запусков в работе: {count}", + "e8fd779b84a202a2": "Ожидает", + "b6d55657e1a027b8": "Ожидает шага {step}", + "e942562a42aede34": "Завершён", + "26b2b9727fe11289": "Завершён досрочно", "1bb995dcec481554": "Подтвердите это устройство на {host}. Там отображается код {verificationCode}.", "8696a33219944832": "Не удалось создать подтверждение авторизации WebSocket.", "5678f133a8631f7d": "Ваш облачный вход изменился. Войдите снова, чтобы авторизовать окружение.", @@ -637,6 +685,9 @@ "fc2020db8a3804c0": "{host} не удалось установить WebSocket-соединение.", "d9ce6c142a485959": "{host} не отвечает уже {seconds} с.", "d6bdce8f4e6101a4": "{host} отключён.", + "8450a95e5214d199": "{host} отправил обновление конфигурации сервера, которое этот клиент не смог прочитать.", + "56b4ff3993c93eca": "{host} отправил несовместимую конфигурацию сервера.", + "368c4d4f99c66bfb": "Обновите клиент и сервер до совместимых версий.", "e5fd422e445391fc": "Ошибка загрузки. Нажмите, чтобы повторить.", "b2bc6bd92ea24e5c": "{size} МБ", "88f84178edbb7f57": "{size} КБ", @@ -1721,6 +1772,8 @@ "2e995206e087c3fc": "Попробуйте ответить после восстановления подключения или завершения ожидающего ввода.", "604ec3067171a0d7": "Беседа", "d6182a057ea12624": "Родительский тред", + "f2d8537c33cc55a5": "Шаг запуска воркфлоу", + "ba8337dca3232880": "Открыть запуск", "30fa4a764d11ae42": "Не удалось скачать {name}", "4952f87dc98191a7": "Вложение недоступно.", "2fd6d178493fb407": "Не удалось прервать текущий ход.", @@ -1785,6 +1838,8 @@ "181677cda4d3fd0a": "Нет подключённого окружения, в которое можно добавить проект", "3a0bf3d17f31584e": "Новый тред в {project}", "4b4b64cc95acb8da": "Новый тред в...", + "2c45783ab9680fdb": "Open Git graph", + "e813386e62652710": "Open agent stage", "3f581e98c86df72a": "Новый тред без проекта", "e510d9a7b684fbfe": "Разобрать проблему", "cce3d80a2ddf1125": "Агент изучит проблему с T3 Code и поможет создать issue", @@ -1806,6 +1861,7 @@ "04fd71efaa2c3b92": "Открыть пул-реквесты", "57e875b79b98ab82": "Открыть issue", "f1db0a234c777a1d": "Использовать T3 Code в другом приложении (MCP)", + "6050f22f63e2bcb5": "Открыть воркфлоу", "a0cc19e60dd99851": "Открыть использование", "46694969044eee98": "Фокус на следующую панель рабочей области", "0a1011328ba42eef": "Фокус на предыдущую панель рабочей области", @@ -2361,14 +2417,24 @@ "05037ca1666fd421": "Терминалы доступны только из треда проекта.", "a3aa1e49af278d41": "Файлы доступны, только когда открыт проект.", "87ea6995ea1e7aa4": "Дифф доступен только для серверных тредов в Git-репозиториях.", + "80f10f5ea1804d8d": "The Git graph needs a Git repository on an up-to-date server.", "4a87cae01ccde544": "У ветки этого треда пока нет пул-реквеста.", "32535dba0b9af642": "У этого треда нет привязанных элементов.", + "d955eee48dece3c0": "Enable the agent stage in Settings > General.", + "d2f2f6d05148f8a3": "Threads a coordinator runs have no thread overview.", + "26c1c05b0d1d98fd": "Turn on coordinator decisions in Settings > General.", + "486d4369c4fbec9e": "Notes are only available from a thread.", + "50b5a57d3bd6f6ef": "Instructions are only available from a thread.", + "007ab76950f73521": "Media is only available from a thread.", "07080dead70f4cc5": "Устройства доступны только из треда.", "a4bf49b31758ff7e": "Доступно только в десктопном приложении.", "e917841cb66f9af1": "Доступно, когда открыт проект.", "14c15fad0c2ee0c8": "Доступно для Git-репозиториев.", "9176276c78f3893f": "В этой ветке пока нет пул-реквеста.", "52ce9db6fb62a59f": "Нет привязанных элементов.", + "96c2ee76dd82d2cc": "Enable it in Settings > General.", + "2199013487151590": "Not for threads a coordinator runs.", + "f7a9300d9f9030d5": "Turn on coordinator decisions in Settings.", "e5d6f41e4fe4efd6": "Доступно из треда.", "0ebc2bb883a8e283": "Доступно после первого сообщения.", "84d0ff8fb9846057": "Включить звук вкладки", @@ -2377,8 +2443,15 @@ "5c78a8ae7b71af1d": "Терминал", "cba3e832ece50257": "Файлы", "83ac3423d6dfc4a7": "Дифф", + "016750bdd5076287": "Git graph", "da16af47eff38ae9": "Пул-реквест", "ad3929f0103925d7": "Привязанные элементы", + "70e7b208e032024a": "Stage", + "0caf7e5748f1d17b": "Threads this one started, and which need you.", + "96018894225bd4ff": "Inbox", + "0ed16d7723c04288": "Decisions the coordinator asks you for.", + "aec2b493d2b01445": "Notes", + "9e92f6aa6edae875": "Notes and todos for this thread, its project, or everywhere.", "ac0de2a59d9c8860": "Устройство", "1354df9fb7278843": "Смотрите на iOS Simulator или Android Emulator.", "fdcd9643e2e63b15": "Задайте побочный вопрос, пока тред продолжает работу.", @@ -2497,8 +2570,7 @@ "2d1c111e1b4ae0b0": "Удалить тред «{title}»?", "c568ab8dad798ec5": "История беседы этого треда будет удалена безвозвратно.", "0fd1c746a0e38003": "Не удалось удалить тред", - "0ecde875b0dd2f93": "Фильтр тредов по проекту: {projects}", - "1ef65b647231ff0b": "Фильтр тредов по проекту", + "1c8fc3c4a42949ab": "Проекты: {projects}", "165511761be2855c": "Поиск проектов", "a46a6467883575a4": "Поиск проектов...", "fdc0e086438a3045": "Настройки проекта {project}", @@ -2560,10 +2632,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Находится на другой машине, поэтому агент этой машины не может его прочитать. Удалите его или переключитесь обратно, чтобы отправить.", "5bbac0e5afeec779": "Текущий тред", "33c7e68fca089036": "Тред, {title}", - "b4b98a0287c282e2": "Находится на другой машине, поэтому агент этой машины не может его прочитать. Удалите его или переключитесь обратно, чтобы отправить.", - "c6196d99000642b4": "Открыть тред", "34cc63390ad793cc": "Выберите тред", "8f12309ead62e38a": "Поиск тредов или проектов...", "2f664754d005d9a7": "Активные треды не найдены.", @@ -2573,6 +2644,7 @@ "a3178769f8308cbc": "Ошибка в треде", "89b5e8f3887812da": "Запрос гостя", "62e626804919b294": "Нужен ввод", + "c6196d99000642b4": "Открыть тред", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Вы:", "a1fbf2422c588292": "Агент:", @@ -2596,8 +2668,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Процесс в терминале запущен", "fc2c9a91f498ad6b": "{count, plural, one {Запущен {count} процесс в терминале. Открыть терминал} few {Запущено {count} процесса в терминале. Открыть терминал} many {Запущено {count} процессов в терминале. Открыть терминал} other {Запущено {count} процесса в терминале. Открыть терминал}}", - "643c4b50feadc874": "Рабочее дерево: {path} ({branch})", - "fb7c44da0f0825ea": "Рабочее дерево: {path}", "56f37ff8ca568059": "стек", "6831e9a46cbd8939": "цепочка", "9aa9e74a3b7eee91": "Добавить в чат", @@ -2686,8 +2756,6 @@ "78a04e0e625c0990": "Ошибка обновления", "c24de5eb69373a55": "Эта сборка {build} игнорирует выпуски {track}. Проверьте канал обновлений в настройках, чтобы завершить переключение.", "b02ae45a6109c93b": "Последняя версия", - "edcda9e8ee4ccad8": "Установить обновление {version} и перезапустить T3 Code?\n\nВсе выполняющиеся задачи будут прерваны. Убедитесь, что вы готовы.", - "02eba0f7cc90f759": "Установить обновление и перезапустить T3 Code?\n\nВсе выполняющиеся задачи будут прерваны. Убедитесь, что вы готовы.", "9ed4d8a1531b9631": "Автоматические обновления недоступны в этой сборке.", "c8c23435e780a60c": "Обновления недоступны", "1af5f9767371ffd7": "Проверить обновления", @@ -3034,8 +3102,8 @@ "6f85f14f35b3f547": "{provider} через {environment}", "7c59a888a062a8bd": "Нет черновика для записи голосового ввода.", "62450481c00d2ef3": "Окружение черновика недоступно для очистки расшифровки.", - "c64cb58d9cecbcd2": "Не удалось очистить расшифровку", "0674544195fcdc39": "Добавлена исходная расшифровка.", + "c64cb58d9cecbcd2": "Не удалось очистить расшифровку", "296496693cdac0db": "Команда t3 недоступна.", "efbcef7bc9bbda01": "Не удалось загрузить состояние команды t3.", "1bf6910332426e62": "Сетевой доступ десктопа недоступен.", @@ -3278,6 +3346,7 @@ "4d493d0bda4d403d": "Прикрепите прерванный файл снова или удалите его", "c9cad1d84d5f1a32": "Прикрепите прерванные файлы снова или удалите их", "536a820f2ff726da": "Выберите хотя бы одну модель.", + "48d6389202ad6754": "Отправка по готовности", "fbafbe78b5e37966": "Возобновить тред", "bcd7eb979dd38dae": "Откройте поле ввода, чтобы сжать и отправить", "95ee62a0d6968b89": "Отправить сообщение", @@ -3454,6 +3523,9 @@ "e778e4f446fdf873": "Следующее сообщение начнёт новый сеанс", "0e2f2da4f2d94785": "Агент не увидит предыдущие сообщения этого треда.", "e1189d2e582b008d": "Оставить текущий сеанс", + "2bb448d605877a22": "Отредактируйте или нажмите Esc для отмены", + "1a1f128d70c62304": "{count, plural, one {Отправится, когда изображение будет готово} few {Отправится, когда {count} изображения будут готовы} many {Отправится, когда {count} изображений будут готовы} other {Отправится, когда {count} изображения будут готовы}}", + "5af3ab719a9725fb": "Отправка сообщения", "461c9f865f2e9b92": "{option}: вкл.", "f2aa17b5c620f2a4": "{option}: выкл.", "f59314a884aae1ff": "По умолчанию", @@ -3577,6 +3649,13 @@ "c53bc5a4b0314342": "Следующее медиа", "2950b1424a3cddf5": "Переподключитесь к этому окружению и откройте медиа снова.", "ef638bf1479a5461": "Окружение вернуло некорректный URL медиа.", + "3ccfbf7e86868c35": "Обратная связь для команды T3", + "4e0710d19dfc2e7e": "Отправить этот отчёт команде T3?", + "87d0ae0723ba75d1": "С этого компьютера отправится только это содержимое. Ничего не будет отправлено, пока вы не нажмёте «Отправить».", + "bf19826f81484328": "Включить переписку", + "ddb7e6f8ce99e657": "Отправить отчёт или отклонить его может только тот, кто может запускать агентов на этом компьютере.", + "03c1eb603c112f47": "Не отправлять", + "653405e4ed498d9f": "Отправить", "262955d6eb632f9b": "API буфера обмена недоступен при копировании гостевой ссылки.", "f1a4f2b04cdbb4ef": "Не удалось скопировать гостевую ссылку в буфер обмена.", "cf3490a604e44d31": "Не удалось создать гостевую ссылку.", @@ -3597,7 +3676,6 @@ "abd89e9eefedf11b": "Готово", "18d166056c1ab6ff": "Прекратить общий доступ", "7a2d510eac9e4587": "Срок гостевой ссылки истёк", - "653405e4ed498d9f": "Отправить", "21888e302219891d": "Развёрнутый предпросмотр: {title}", "419719298a7acaea": "Уменьшить", "ed8d5db95359cff4": "Сбросить масштаб", @@ -3693,7 +3771,6 @@ "7c1923203049d602": "Копировать код", "637817e4ff79c90e": "Действия с блоком кода", "ebf3a2b1e314aa5f": "Выполнить в терминале", - "fe219642547fa0bf": "Выполнить в терминале", "122a8512abc51180": "Подробности", "58c38c65c2783c5d": "Полный путь", "f37e7d36b51c5b28": "Копировать относительный путь", @@ -3705,10 +3782,6 @@ "4967584e8d0fb1c2": "Предпросмотр медиа", "67589dd912eacb7c": "Открыть во встроенном браузере", "a3c98d4c4b24cecb": "Параметры файла {label}", - "b4fe8a076e9fd2f8": "Формула в отдельной строке", - "085d1407e8c92cce": "Формула в строке", - "a2ef393fa7b48ae8": "Прокрутить формулу", - "e94685ea5642e088": "Прокрутить формулу в строке", "3a04583c8500e23d": "Показать диаграмму", "16d64f650840fe06": "Показать код", "6d329f7d3a50c7e7": "Копировать таблицу", @@ -3985,9 +4058,11 @@ "973e99fa86d7f531": "Сообщение в очереди {position} из {total}, не отправлено", "0f6087c4f53c7f17": "Начать ход с этим сообщением ({shortcut})", "adab89933af02669": "Пропустить сжатие и отправить сообщение ({shortcut})", + "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", "3de4016452e8d2bd": "Отправить в текущий ход ({shortcut})", "259cc9568148e8ad": "Начать ход с этим сообщением", "bb7fddb812d5d29e": "Пропустить сжатие и отправить сообщение", + "425ab15036aec8a4": "Переместить эту команду в начало очереди", "a5fe1ee609b29a9f": "Отправить в текущий ход", "2b7fd345e4f4fd6e": "Отменить редактирование сообщения в очереди", "47f1726bf106d2c8": "Редактировать сообщение в очереди", @@ -5453,6 +5528,22 @@ "f0d79aa56f06663f": "Файл слишком большой, чтобы показать его полностью. Счётчики учитывают все изменения.", "7fdde2b893ba1b9d": "Удалено", "e58ce271d835b447": "Добавлено", + "fb5c7ff5ea76e01a": "Added by esveo's fork. Click to list all of its settings.", + "352fa6aeb5d55665": "Trail the provider icon behind the thread title instead of giving it a line of its own. The line it saves also carried the branch, pull request badge and diff counts.", + "9d44fa03a230e0d8": "Reset two-line thread cards to default", + "7b216eedb1abe696": "Two-line thread cards", + "8d90fcd918e901c8": "Keep each project's threads together in the sidebar, under a header that folds the project away. Ordering stays by recency: the project with the newest thread leads.", + "d5dfd89c9a281386": "Сбросить группировку проектов к значению по умолчанию", + "aac9f889c7ec7ff5": "Group sidebar threads by project", + "da375a07c5309184": "Show how full the thread's context window is next to the composer controls.", + "33f6b88cba203990": "Reset context window usage to default", + "6496f57baeded3fa": "Context window usage", + "d9c146dc6b95714d": "Show how many minutes are left before the prompt cache expires. Claude only.", + "69609e27c2107da5": "Reset prompt cache timer to default", + "a4917d2b93c478f6": "Prompt cache timer", + "ea8ebcb77e657e9f": "Open the thread details card with workspace and version control in every thread. Off, it stays closed until you open it, and each thread remembers your choice.", + "662288b90e19635f": "Сбросить сведения о треде к значению по умолчанию", + "92729a403d37c575": "Open thread details by default", "07b9970b662ab70d": "Показать исходник Mermaid", "5a422b7be35243f5": "Показать диаграмму", "c0628ad999cbbbf5": "Показать исходник Markdown", @@ -5560,6 +5651,7 @@ "723d88a5fa7e2fdd": "Нет подходящих файлов.", "f8d6e9a1a2870a5c": "Обозреватель файлов", "109edd252917113b": "Изменить размер обозревателя файлов", + "7abd6af24fed7b60": "The file does not exist in the workspace or the home folder.", "37cbd2ecc659a007": "Файл", "b5188f172f59ca79": "Это подключение не может читать файлы на хосте.", "c3c5d36466ad2191": "Открыть файл в браузере предпросмотра", @@ -5599,7 +5691,6 @@ }, ". Проверьте путь в ссылке или найдите файл в «Файлах»." ], - "b9b6bbd1e1ea189f": "Файл целиком", "d715e9494fdbaaf6": "Не удалось загрузить шрифт.", "ff17c777a72b4408": "Предпросмотр шрифтов ограничен 10 МБ.", "6bd41ad699e22f10": "Шрифт недоступен.", @@ -5609,6 +5700,7 @@ "a9abaaa4220eae21": "{error} Сохраните его, чтобы открыть в другом приложении.", "c508c9000d9656f8": "Предпросмотр шрифта", "1c416d621d250be8": "Съешь же ещё этих мягких французских булок, да выпей чаю.", + "d7d08260f16b7828": "Файл ещё загружается. Повторите попытку через мгновение.", "76ebb03de52c92d6": "Просмотрщик текста остановился.", "f48162e8e8c12af7": "Не удалось загрузить просмотрщик текста. Закройте файл и повторите попытку.", "bc4c5b13d38a5da7": "Предпросмотр закрыт.", @@ -5616,8 +5708,6 @@ "9450d1827ef336a1": "Уже идёт другое копирование.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} строка} few {{formatted} строки} many {{formatted} строк} other {{formatted} строки}}", "13b14784f8707ddd": "0 байт", - "f6e9581cba3467fa": "Индексация…", - "2d1f293ac12463fc": "Загрузка остальной части файла…", "b75105bef8f564a4": "Показаны первые 1 024 столбца. «Исходник» и «Сохранить» сохраняют все столбцы.", "2a6e1b1f209c3888": "Этот файл пуст.", "192fc79eb3b5b2cb": "Эта диаграмма содержит URL ресурсов, разметку, метаданные узлов или собственную конфигурацию. Откройте исходник Mermaid, чтобы безопасно её изучить.", @@ -5804,7 +5894,6 @@ "0061fff77e36bd4f": "Не удалось связаться с сервером.", "04dfdd46e3dd4a2e": "Что-то пошло не так. Повторите попытку.", "084bb2d8127a508d": "Отправлено", - "e7c59185f8ab3987": "Не отправлено", "77c01a15bd36d17c": "Срок действия ссылки истёк или она недействительна", "e0e736810f3cbef2": "Попросите владельца прислать новую ссылку. Каждая ссылка работает в одном браузере.", "c3c53aa46f7330e5": "Срок действия ссылки истёк", @@ -5826,6 +5915,13 @@ "cbb2129c0dd4f40b": "Общий размер вложений в сообщении — не более 10 МБ.", "03b9cd79cfe0b435": "Этот файл нельзя прикрепить. Изображения должны быть в формате PNG, JPEG, GIF или WebP.", "8ff29c78798e6ac1": "Не удалось загрузить этот элемент.", + "535923000a0f3e3b": "Send /compact to a large, idle Claude thread shortly before its 1-hour prompt cache expires, so the next message skips caching the whole conversation again. 5-minute caches are left alone.", + "bd8eb8f5f9843bc6": "Reset idle auto-compact to default", + "1db274eacf03c8de": "Auto-compact idle Claude threads", + "fb6643c75aafd996": "Between {min} and {max}; it has to fall inside the cache's hour.", + "48dee64ca7904281": "Minutes idle before auto-compact", + "8937fe924464eb70": "Smaller threads are cheap to cache again and keep their full history.", + "1981f1e1a753aabc": "Minimum context tokens for auto-compact", "94ab4591ce101233": "Не удалось опубликовать комментарий", "92d0d4eab2596772": "Трекер отклонил запрос.", "33591d9596fb7cb7": "Добавить комментарий", @@ -8695,12 +8791,16 @@ "58e0e226493150e7": "Не удалось загрузить issue-трекеры", "77cfcbde543df32d": "Показать или скрыть подробности {tracker}", "0083f65885c60156": "Отключить {tracker}", - "295392927d5c8a84": "Выберите один или несколько {scope} в {tracker} для каждого проекта. Их issue показываются рядом с issue репозитория, а агенты создают новые issue в первом.", + "ed83b25c71c98a20": "Выберите один или несколько {scope} в {tracker} для каждого проекта. Их issue показываются рядом с issue репозитория, а агенты создают новые issue в первом, если вы не укажете, где их создать.", "19c2d5e81ff8f89a": "{tracker} {scope} для {project}", "68e061510b765772": "Не привязано", + "99d51127f573296b": "Другой аккаунт", + "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}.", + "99963c0142e17f00": "Для нового аккаунта {tracker}.", "a2d95d39d3398bda": "Учётные данные отклонены", "9eae463720500113": "Хранится на сервере.", "b6e27ab2537ef874": "Создать", + "6d8e4ebc889bace9": "Добавить аккаунт", "13ef526271b0f5d4": "Очистить все условия", "d1938a629f039515": "Удалить условие", "84a605b241ce65b7": "Удалить группу и её условия", @@ -8830,6 +8930,12 @@ "d3866ead082d14e5": "Добавить сочетание клавиш", "d4345c90894a3220": "Открыть keybindings.json", "e56a8d51219efaa0": "Нет сочетаний клавиш по вашему запросу.", + "90a258fff61fd77e": "Выкл.", + "4060244a7079a0d2": "По моему запросу", + "e88c9d8769544731": "Автоматически", + "f29d1dade4dde8aa": "Агенты не отправляют обратную связь команде T3.", + "93c4c53562d30a98": "По вашему запросу агенты показывают краткий отчёт о T3 Code и с вашего одобрения отправляют его команде T3.", + "cd9ee803e8727017": "Агенты также сообщают о проблемах T3 Code, с которыми сталкиваются самостоятельно, например о сбое инструмента T3.", "45fa271ea0e1ac8e": "Бета", "3a678332fc7142f7": "Группирует треды боковой панели по папкам проектов. Закреплённые треды остаются наверху, а отложенные и разобранные — под папками.", "e4e91d155cb6a9b4": "Простая боковая панель (группировка по проектам)", @@ -8838,11 +8944,16 @@ "9ae293971d93c819": "Поделитесь тредом с гостем: он смотрит его в браузере в реальном времени и отправляет сообщения, которые вы одобряете. Войдите в T3 Connect, чтобы использовать гостевые ссылки.", "0aa5406ac4d7f7c7": "Гостевые ссылки", "f0e853acd2006d53": "Привязанные окружения", + "ef10c2dff987f3ea": "Запускайте многошаговые воркфлоу из файлов в папке workflows домашней папки T3 этого сервера. Открывайте их из палитры команд. Пока функция выключена, ничего из этой папки не выполняется; запуски ждут, пока её снова не включат.", + "2dadb2359422121c": "Воркфлоу", "13e86eb5d8287a71": "Показывать предполагаемое следующее сообщение в пустом поле ввода после хода Claude или Codex. Tab вставляет его. Каждое — дополнительный кешированный запрос в рамках вашего плана. Нужен Codex 0.165+. Треды Claude обновятся после перезапуска.", "d4b2a2ec812aafb0": "Предлагать следующий промпт", "298c7150a7621c80": "Хосты устройств Simlock", "67937aa49179285e": "На Mac клонировать новые рабочие деревья из копии, закешированной в домашней папке T3, вместо записи каждого файла. Если это невозможно, используется обычный checkout Git. При выключении кеш удаляется.", "f9904f78d3003f58": "Быстрый checkout рабочих деревьев", + "9c2f647882522302": "На выбранных компьютерах используются разные режимы обратной связи от агентов.", + "31bbf7bf8c0a5279": "Обратная связь от агентов", + "d52b3d6bf9f2a013": "Разные", "ec7623deed751c05": [ "Поделитесь тредом с гостем: он смотрит его в браузере в реальном времени и отправляет сообщения, которые вы одобряете. Нужен T3 Connect: войдите и привяжите эту машину в разделе", " ", @@ -8926,7 +9037,9 @@ "fb71127e5746a6bc": "Из раздела «Общий доступ» там или через t3 pair", "1e3fee7084791773": "Также привязать {target} в ответ к {source}", "ea34a190b0bd804c": "Тогда агенты на {target} смогут работать и на {source}.", - "ad5ed0ce61b966eb": "Забыть {label}? Агенты отсюда перестанут там работать. Чтобы завершить сеанс и там, отзовите «T3 Code · …» в разделе «Общий доступ» на {label}.", + "974f8c65e8b5f492": "Забыть {label}? Агенты отсюда перестанут там работать, а их сеанс на {label} тоже завершится, если он ответит.", + "6cf9e3083b15614f": "{label} не ответил", + "34ccbdf619b83be3": "Чтобы завершить сеанс и там, отзовите «T3 Code · …» в разделе «Общий доступ» на {label}.", "81c9796bf61b306a": "Не удалось забыть привязку", "130e51beb6cf5aad": "Привязать окружение", "122c3e355699e69d": "После этого агенты отсюда смогут запускать треды там, писать в них и ждать их. Связь появится в разделе «Авторизованные клиенты» в «Общем доступе» того окружения, где её можно отозвать.", @@ -9156,7 +9269,6 @@ "0b4779a1825c85bc": "Общее название этой группы проектов на боковой панели и в списках тредов.", "f68cbda4df83d739": "Сбросить название проекта к значению по умолчанию", "56e37b85027e8431": "Значок проекта", - "e88c9d8769544731": "Автоматически", "c99736317da5b1fa": "Сбросить значок проекта к значению по умолчанию", "6afaa3e3739dc570": "Выберите значок проекта", "51651ce45d481a20": "Выберите файл значка проекта", @@ -10067,7 +10179,6 @@ "53de7aafe0afc10d": "Не удалось восстановить настройки темы", "006bfa1846fe5dd2": "Дней бездействия до авторазбора", "d9b0fbd680d5f175": "Боковая панель", - "d5dfd89c9a281386": "Сбросить группировку проектов к значению по умолчанию", "cd5452cc9e13c818": "Группировка проектов", "cfb01b8a2a3361fb": "Сбросить порядок проектов к значению по умолчанию", "26abcbe322049a8a": "Сбросить раздел «В работе» к значению по умолчанию", @@ -10132,7 +10243,6 @@ "16bdc70b858c223f": "Сбросить заблаговременные панели к значению по умолчанию", "c5424f09d77138ff": "Когда сжимать неактивный тред Claude больше 200 000 токенов: после вашего возвращения, перед самым истечением его кеша промптов или никогда. Каждый провайдер Claude может это переопределить.", "3e99c5c14f4939c8": "Сбросить сжатие простаивающих тредов к значению по умолчанию", - "d52b3d6bf9f2a013": "Разные", "cd72fe451ba0d6aa": "Новые проекты", "394c3bd0a1782c8e": "Оставьте пустым, чтобы при открытии «Добавить проект» использовался «~/».", "f9b912a818bd869d": "Сбросить базовый каталог для добавления проектов к значению по умолчанию", @@ -11032,7 +11142,6 @@ "4a237f41ce592b7f": "Хранить рабочие деревья этого проекта, пока вы не удалите их вручную.", "00b8ffd8ea6e6a93": "Использовать эти правила для этого проекта.", "72c279824d15a999": "Использовать настройки очистки рабочих деревьев каждой машины.", - "90a258fff61fd77e": "Выкл.", "b5702d0b64866b08": "Свои", "c009c901f3eefe78": "Удалять рабочие деревья вместе с удалёнными тредами", "431c7cd6d50102b7": "Удалять неиспользуемые рабочие деревья при удалении активных или архивных тредов. Рабочие деревья с локальными изменениями сохраняются.", @@ -11389,7 +11498,6 @@ "f2043e87a10cb831": "Изменить тему", "595bdeefcdc9bf31": "Экспортировать файл темы", "b480281b3791b685": "Выберите, что показывает карточка сведений о треде. Можно также нажать на карточку правой кнопкой.", - "662288b90e19635f": "Сбросить сведения о треде к значению по умолчанию", "871d059d88548434": "Сведения о треде: включено {enabled} из {total}", "cec1fbb8b4c9180d": [ "Включено ", @@ -11728,7 +11836,6 @@ "4c70e3e7b3e6c493": "Секреты", "79b768229c9ef672": "Обслуживание", "54b188d65247e42f": "Эксперименты", - "f41ea186c275b56e": "О приложении", "af4b7734da1d5ce7": "Голос", "4ec62c39ca3192bf": "Контроль версий и issue", "f2bf529f85e05494": "Общий доступ", @@ -11757,11 +11864,17 @@ "8f5966eebd2b110f": "оформление цвета палитра своя импорт", "633ed64e952cca3b": "цвета границы интерфейс", "9cf8308531b4ff31": "прозрачный прозрачность сплошной меню диалоги поле ввода", + "d99bfbc557fae743": "Notion", + "89df56091835b3a6": "notion integration secret pages links viewer connect token ntn", + "d699adcc04d4d4ab": "sidebar compact row height branch provider icon diff pull request", + "9b9df5ba41c4a8e2": "Group threads by project", + "0ed2eab2c1953531": "sidebar project folder runs grouping collapse header repository", "d8d6cfd630cff22d": "красный зелёный синий оранжевый добавления удаления изменения счётчики палитра дальтонизм", "717e49895cfee1c7": "широкий полная ширина колонка раскладка сообщения поле ввода монитор", "88365077fd80787b": "настроить показать скрыть панель карточка окружение редактор скрипты ветка пул-реквест git изменения серверы автоматизации происхождение использование лимиты 5 часов неделя квота токены контекстное окно", "d561f74efa5f3920": "усилие рассуждений размышление полосы график слово метка уровень поле ввода", "6113c17109ee0d57": "latex tex katex уравнения формулы markdown", + "dfe7ead48efc3f5a": "thread details card panel workspace version control closed collapsed hide", "8c8364d44fa28d22": "dev nightly latest канал оформление метка скрыть нет", "2d90635156dfcb5a": "типографика семейство размер системный sans", "d32e93777e4819c8": "типографика семейство размер поле ввода ввод", @@ -11783,6 +11896,7 @@ "d443390c4d2dcfd4": "доступность a11y экранный диктор nvda jaws voiceover orca экранный диктор заголовок окна заголовок вкладки alt tab панель задач статус треда порядок в работе подтверждение", "6826fa9579c22035": "бета поделиться гость приглашение ссылка коллега наблюдать t3 connect туннель", "f10c06cba0cdf7fe": "бета привязать другой компьютер vps агенты работают там делегировать", + "bc0b409d89ce086e": "бета воркфлоу workflow надёжные запуски автоматизация шаги расписание webhook папка", "4a21cf825a2045b0": "бета tab автодополнение предсказать следующее сообщение claude codex подсказка", "fea2dc36585c4a20": "Хосты устройств Simlock (альфа)", "9d834d178130180e": "бета альфа simlock callstack симулятор эмулятор ios android пул аренда шлюз", @@ -11824,7 +11938,29 @@ "34d74827c2a8b009": "enter return command ctrl многострочный промпт новая строка поле ввода", "9d1013084c46ecce": "очередь корректировка выполняющийся ход отправить поведение по умолчанию поле ввода", "e5e7f5e1fb1f2e4c": "субагент боковой чат привязанный тред щелчок правая панель боковая панель основное окно command ctrl средняя кнопка", + "5c59d7e2673267ea": "composer tokens usage meter percentage compaction", + "e0d6ec10218b714e": "composer claude cache ttl expire minutes warm cold tokens", + "ce0952668aba4140": "Agent stage", + "f637899f994b78c3": "sprites stations subagents thinking editing terminal right panel everything", + "9d9d3374ee961b91": "Easter eggs", + "571180dbfeddbfd5": "surprise fun rocket animation message send hidden", + "0716adb0d55ffa58": "Voice calls", + "027d8f5ea5555973": "voice call phone gpt live feature flag anruf telefon schalter", + "60d509bb55e2967c": "Voice call voice", + "0e5f5c5ebf026abd": "voice call phone gpt live speaker stimme anruf telefon", + "266f1e2b55e419b0": "Voice call follow-up", + "392226d9bed6fe21": "voice call queue steer follow-up warteschlange anruf", "5b8b854de7ee6f4d": "установленные cli версии новее доступно codex claude cursor grok fx kiro opencode", + "1ceaab7d898b689a": "Child threads in the sidebar", + "fa5a42a73d1c1ece": "coordinator subthreads nested group expand sidebar orchestration children", + "6a1072050d1ad19e": "Coordinator decisions", + "474ba8e025886f86": "inbox questions answers decide approve coordinator open items", + "8f5558f063214509": "Cross-project threads", + "b809e3ffa5178b88": "agents coordinator other projects read message start threads repositories", + "44207b47d209f601": "compact context prompt cache idle claude tokens cost expire", + "396a2cc5b442e359": "compact idle minutes prompt cache ttl", + "6d9520a9cbd70c2f": "Minimum context for auto-compact", + "2fe046cc1e0d0d4a": "compact context tokens threshold size", "64f12530d55d2ad1": "возобновить выполняющаяся активная прерванная работа перезапуск перезагрузка компьютер сбой обновление десктоп автоматически", "214a98497c4ed05d": "caffeinate сон не давать уснуть бодрствование питание ноутбук крышка блокировать", "00469926c7027e2d": "сбалансированный производительность экономия батареи дополнительно git fetch проверка провайдеров обновление питание хоста монитор простой политика", @@ -11854,6 +11990,7 @@ "901a823214edc8c4": "телеметрия аналитика данные об использовании отслеживание юридическое отказ", "82136480255a5106": "OTel OTLP телеметрия экспорт конечные точки логи трассировки метрики Grafana", "659d081051faf7ff": "логи трассировки процессы история ресурсов сбои спаны cpu память", + "5eaeacfa9f82051a": "отчёт ошибка проблема t3 команда отправить обратная связь агенты инструменты автоматически по моему запросу", "f537f91e1ee41d47": "сочетания клавиш горячие клавиши команды привязки json", "1ba01e7ceed64b95": "окно захват снимок экрана", "279b1cceb779ff38": "Включать текст приложения", @@ -12059,6 +12196,8 @@ "v": "v" } ], + "643c4b50feadc874": "Worktree: {path} ({branch})", + "fb7c44da0f0825ea": "Worktree: {path}", "e7f35f60e6229cf5": "Десктопное приложение", "77be1b7e2a1d3d31": "{count, plural, one {Обновить {count} машину?} few {Обновить {count} машины?} many {Обновить {count} машин?} other {Обновить {count} машины?}}", "e4892b21e88abb60": "{count, plural, one {{count} обновление провайдера} few {{count} обновления провайдеров} many {{count} обновлений провайдеров} other {{count} обновления провайдеров}}", @@ -12122,6 +12261,25 @@ "ffaa75d2db1e7cc1": "Обновление не применилось", "626bcbe04dc55f93": "T3 Code всё ещё на {current}. Установите {version} снова с помощью кнопки обновления.", "49214c047fbb1606": "Обновление провайдера прервано", + "a135af0f1efda8de": "Cross-project", + "6e9798372b3fb922": "Coordinators put the questions they need you to decide into an Inbox tab beside the chat, instead of numbering them in their messages. Running sessions pick up a change.", + "7a5292a1705defec": "Reset coordinator decisions to default", + "9e3ff0f05f52b724": "Let agents read, message and start threads in other projects of this environment. Running sessions pick up a change.", + "384695cdd7ab6b54": "Reset cross-project threads to default", + "5a6c243a03eeca0c": "Choose a coordinator", + "f527bb5b4ad333da": "Coordinator for \"{title}\"…", + "6beb2db2a7b5edae": "Could not assign the thread", + "4ebb0c90c45690c0": "Could not detach the thread", + "73ac4f532306bea6": [ + "Assign \"", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "\" to a coordinator" + ], + "1871eb35b1ca5d41": "No thread can coordinate this one.", "52adbc863aeb5e59": "Не удалось скопировать", "0944728904d886d2": "Насыщенность и яркость {label}", "dded2cb4e4d26338": "Насыщенность {label}", @@ -12323,7 +12481,6 @@ "0bd41ff995d36a66": "Чтение кеша", "3f0dfe0cb15a3272": "Запись кеша", "1c9d860be42b1c02": "Вывод", - "78344b60f407928e": "Другое", "684e516076de81fe": "Стандартная", "3bbcc1b826fef537": "Быстрая", "66796576034c18ea": "Сверхбыстрая", @@ -12339,6 +12496,270 @@ "2cddd6095abc734a": "7 дней", "53493056306708cf": "30 дней", "c719359d18d37ad3": "90 дней", + "a7ad3167ca62e7de": "Talk to your agents by voice with GPT-Live on your Codex ChatGPT login. Turning this off ends a running call.", + "9f0e45a1d67187cd": "Reset voice calls to default", + "da0ae8174ac2fc14": "Queue what you say in a voice call while the agent runs, or steer the current run. Saying otherwise overrides it for one message. A change applies from the next call.", + "fb0a2aa3b08a17c4": "Reset voice call follow-up to default", + "66936cae56d1d749": "Queue", + "89bf6f658c44cb1b": "Steer", + "930a28582d2c103f": "The voice that talks to you in a voice call. A change applies from the next call.", + "591a53f319b0d343": "Reset voice call voice to default", + "0bd950151ddc6407": "Уйти без сохранения? Изменения в этом файле будут потеряны.", + "c0ba3f6756b09f30": "Несохранённые изменения", + "6914e22d357f0ad6": "Сохранено и работает", + "aff389354a031d6f": "Файл на диске не загружается. Продолжает работать последняя версия, которая загрузилась.", + "858effde748ab563": "Сохранено, но пока не запускается.", + "ddb37138df660942": "Не сохранено. На сервере ничего не изменилось.", + "6ef4db489e40e39e": "Не удалось сохранить", + "c89624a2e9af1793": "{name} не подключено", + "b5a352a43adb4c17": "Его рабочие процессы снова появятся после переподключения. Выберите другое окружение, чтобы увидеть его запуски.", + "3dcedb736d20aae5": "Не удалось прочитать файлы воркфлоу", + "b09f4df8d76ae8ea": "Удалить {file}? Воркфлоу, которые он определяет, больше нельзя будет запустить.", + "b4535f5a03689d27": "{name} не подключено. Написанное здесь сохранится, и его можно будет сохранить, когда подключение вернётся.", + "b54c78d85fd942ea": "Удалено, но то, что запущено, ещё не обновилось.", + "407c228d7da0b7df": "Не удалено. На сервере ничего не изменилось.", + "1a6aa10f3cc14fff": "Эти файлы не согласуются между собой. Продолжает работать то, что работало раньше.", + "259312516a1dbe6f": "Имя файла", + "2f48ab2aa0586853": "Не определяет ни одного воркфлоу", + "ba5adfa37b55b8c5": [ + "Строка ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Удалить", + "84c900d1ae72adc6": "Сохранить", + "5912d817be03247a": "Файл изменился на диске, пока вы его редактировали. Сохранение заменит это изменение.", + "0b1e6f5608826387": "Загрузить файл и сбросить мои изменения", + "f47b4c06aeb77c1c": "Загрузка файлов воркфлоу…", + "4353bfd401d58f87": [ + "Каждый файл в", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "определяет воркфлоу. Изменения в любом из них подхватываются без перезапуска." + ], + "0c165251a06f10f1": "Новый файл", + "8e97cf734b4463e7": "Создать", + "2ec0d5108fd6cebe": "Воркфлоу пока нет. Создайте первый файл здесь или попросите агента написать его в этой папке.", + "5601350626e8cfe9": "Не загружается", + "21d778a1b9a0c234": "Открыто рядом с запуском", + "62dc4d3a19ff7ca0": "Закрыть вкладку", + "1e25265f2758fce3": "Открыть как полноценный тред", + "672a3dae06b39402": "Открыть на отдельной странице", + "7755500a4cde5066": "Закрыть панель", + "b8dcbc93a2ca1861": "Этого больше нет в запуске.", + "115c69de3202f664": "Открыть", + "644eafa9048b62df": "{count, plural, =1 {1-я попытка} =2 {2-я попытка} =3 {3-я попытка} one {{count}-я попытка} few {{count}-я попытка} many {{count}-я попытка} other {{count}-я попытка}}", + "e39f89c909df4db0": "Не удалось возобновить запуск", + "865f034346b82f47": "Отменить {title}? Его агенты остановятся, и запуск нельзя будет возобновить.", + "6bc75632fd9c9136": "Не удалось отменить запуск", + "64e50329dcfdd5b0": "Завершён", + "350162e7cc1ebea4": "Остановлен", + "0875cf506f4c6810": "Пропущен", + "3cc43f1dbf3f8e0c": "Отменён", + "ded70e75de6404ba": "Назад к списку запусков", + "2f4ed7dbd22be30d": "Отменить запуск", + "614e5ad58a795fb5": "Остановить", + "04b050b0329f0ac8": "занял {duration}", + "aff78e1774818ff4": "пока {duration}", + "38eddd466439afc9": "Что затронул запуск", + "156ec271d49ddd70": "Что произошло", + "34f59bbbead0b97f": "{names} и ещё {count}", + "ac1556f6ce89a5ea": "параллельно: {count}", + "e197c4963bacc746": "выполняется: {count}", + "f5319ed9e18c0df1": "Спрашивает вас", + "882a25e9084ae1b2": "Приостановлен", + "9a03d8a9afc60387": "Шаги на данный момент", + "2f2ae791afe01674": "ждёт вашего одобрения", + "24f8060c4ccdf928": "запускается", + "30a5be40eb956663": "работает", + "dd7a1e58c2553933": "проснётся через {duration}", + "95cc952724dd7310": "вот-вот проснётся", + "3cc34921c0128593": "выполняется", + "e777db2880f53a46": "никто не ответил", + "dc90739d391a5e67": "Вы ответили: {choice}", + "389f2563b5b763fd": "Быстрые шаги", + "a41c8d758121ad81": "спал", + "9db248b770096984": "ждал", + "c76124517af28686": "выполняется {duration}", + "89102905bf09b0e8": "Смотреть вживую", + "bdf338cdff4118f0": "Транскрипт", + "811e7e992f9ff820": "не может продолжиться, пока версия его воркфлоу не будет снова зарегистрирована", + "4d4cdf035e98dd57": "ждёт, пока вы его возобновите", + "eb5b21dd224a5941": "повторит попытку сам через {duration}", + "6ab3dfa749fde477": "вот-вот повторит попытку сам", + "44b6463aa70aa14c": "Почему приостановлен", + "cf25e7169ab0eb7a": "Приостановлен на шаге {step}", + "56c48c1f220f2754": "Не удалось ответить на вопрос", + "a3c43735e1a81498": "Причина: {title}", + "bfad234f016cfa3f": "Причина в одном предложении. Она прикладывается к любому выбранному ответу.", + "004c41aff9c97873": "Запуски", + "4dc0c244a2419f6c": [ + "В составе: ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "запущен", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "его версия больше не зарегистрирована", + "f92d9132f7b85d1a": "Загрузка шагов…", + "6ebc59f64c761a49": "Пока ничего.", + "a759dccd157d7dae": [ + "Вы ответили:", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Вы ответили:", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " — ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Открыть запуск", + "c8eb9be36d4d51ad": [ + "Тред на ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Возобновить", + "8cebd63fc4c967d5": "Заново выполняется только упавший шаг; всё, что завершилось до него, сохраняется.", + "bc1e0a2a0f1e9552": "Ждут вас", + "a812f51e970740f1": [ + "спросил", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· запуск ждёт вас" + ], + "02dfe6c63fd0b8a1": "Добавить причину", + "19abd94828a3bdbc": "Сначала спросить агента", + "a18721fa8f328361": "Ждут вас", + "bbf24e7920c1e86b": "Выполняются", + "8d6e18d2ad832db6": "Все", + "f25af5332ffc3734": "Вас ничего не ждёт.", + "c3f0119b8d6231f8": "Ничего не выполняется.", + "33028dfc1229eaa6": "Запусков пока нет.", + "5459bf696a187c26": "Не удалось загрузить запуски воркфлоу", + "d57c35d43b0f163a": "Этого запуска здесь нет", + "b9aae2f7cdb1a379": "Запусков воркфлоу пока нет", + "8f15f66e545af7c0": "Какие запуски", + "b6409289e0c9a4dd": "Воркфлоу", + "035cb02ca1ae4952": "Все воркфлоу ({count})", + "46d614fa7b4bf1e5": "Запуски воркфлоу", + "1c635faa2fb45b8b": "Ещё не запускался.", + "156ff7b625287a1e": "Скрыть пропущенные", + "69b985b97ab45e6b": "Показать пропущенные ({count})", + "2400254d362de84d": "Загрузка запусков воркфлоу…", + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "В файле воркфлоу есть ошибка." + }, + " ", + "Продолжает работать последняя версия, которая загрузилась." + ], + "ed8ce6ebc73dc12d": "Открыть файл", + "145e1f7503ba3b2c": [ + "В этом окружении нет запуска по этой ссылке.", + " ", + { + "t": "button", + "i": 1, + "c": "Вернуться к запускам" + } + ], + "783e616cb0476c17": [ + "Воркфлоу объединяет агентов, код, расписания и вопросы к вам в один запуск, который переживает перезапуски. Напишите его в разделе", + " ", + { + "t": "button", + "i": 1, + "c": "Определения" + }, + " или попросите об этом агента.", + " ", + { + "t": "a", + "i": 2, + "c": "Читать руководство" + } + ], + "5d8d278ff828102d": "Все воркфлоу", + "39459da07479f482": "Агент", + "7741243632056b81": "{step} · расшифровка", + "c512071143a5ba32": "Этого треда больше нет.", + "ed169d23683fb6ac": "Загрузка треда…", + "290e0ab40b87dc17": "Навигационная цепочка воркфлоу", + "683dd9831e54edc0": "Окружение", + "34ad53646f06ed80": "Воркфлоу выключены", + "8f6589c9e0ac5d4e": "Нет подключённых окружений", + "744127f8dfad7d22": "Подключите окружение, чтобы увидеть его запуски воркфлоу.", + "036182ec7e2ee4d4": "Рядом с запуском", + "2d6107cb78382d08": "Воркфлоу", + "16f7df687349b399": "Определения", + "f0a212aadfe1257b": "Загрузка редактора…", + "20f194e003885e95": [ + "Включите их для этого сервера в разделе", + " ", + { + "t": "Link", + "i": 1, + "c": "«Настройки → Labs»" + }, + "." + ], "8367779e149f723b": "Запрос к основному окружению не удался во время {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Недействительный токен сопряжения. Проверьте токен и попробуйте ещё раз.", "0e4b49c8203aae81": "Истекло время ожидания аутентифицированного сеанса после начальной загрузки.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 081857c5dae81..4266390af26ae 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -52,6 +52,27 @@ "eb0f60ef4f92ab7d": "Installera {fj} 0.6 eller senare från {fjUrl} och kör {fjLogin}, eller installera {tea} 0.16 eller senare från {teaUrl} och kör {teaLogin} för varje Forgejo- eller Gitea-server.", "d026a85e2e50e675": "Installera GitCafe CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", "22d3c0c48a34b5b3": "Installera TanStack Source CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", + "756c80ad262ef315": "Väntar i den ursprungliga tråden", + "d8df14f9905f38eb": "Skickat", + "e7c59185f8ab3987": "Inte skickat", + "b54ddec9084fa955": "Stängd utan att skickas", + "fbaa7ab5da716e50": "Bugg", + "01bac997ea55272e": "Otydligt", + "0f53bc8f74dfe56a": "Funktion saknas", + "055560f307e15e30": "Fel i dokumentationen", + "78344b60f407928e": "Övrigt", + "f653846a95cd6e8f": "Typ", + "f41ea186c275b56e": "Om", + "2f6e4f7cd364da73": "Förväntat", + "9d11c93d4035de3e": "Vad som hände", + "c87d0595693704f9": "Gjorde i stället", + "d7a4ea6ce5af44e0": "{speaker} · {count} tecken", + "f5114fb9c40fd929": "Du", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Omgång {turn} · {what}", + "dfdaa6255a416140": "Översikt över {turns, plural, one {{turns} senaste omgång} other {{turns} senaste omgångar}}, {textTurns, plural, =0 {ingen meddelandetext} one {meddelandetext från den senaste omgången} other {meddelandetext från de senaste {textTurns} omgångarna}}{truncated, select, yes {, förkortad för att få plats} other {}}", + "260c6b45f52d2f27": "Lägger till texten i dina meddelanden och agentens svar under {textTurns, plural, one {den senaste omgången} other {de senaste {textTurns} omgångarna}}.", + "afac52a5cc2dc801": "Det gick inte att skicka ditt svar. Försök igen.", "79d776428f4d0650": "Filen kunde inte läsas in. Återanslut och försök igen.", "3ea34cbb1ca5ba9b": "Förhandsvisningen avbröts.", "7c0af279ecb3da3a": "Strömmande förhandsvisning av filer är inte tillgänglig i den här körmiljön.", @@ -118,9 +139,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}.", @@ -246,6 +267,8 @@ "fec888c767b662d5": "Försökte kontrollera länkade ärenden", "bc31067af9c79d82": "{count, plural, one {Kontrollerade länkade ärenden {count} gång} other {Kontrollerade länkade ärenden {count} gånger}}", "c712fec8d9dc6dd6": "{count, plural, one {Försökte kontrollera länkade ärenden {count} gång} other {Försökte kontrollera länkade ärenden {count} gånger}}", + "81c2282590e549f5": "{count, plural, one {Read terminals {count} time} other {Read terminals {count} times}}", + "79cd7c5c29ffa938": "{count, plural, one {Tried to read terminals {count} time} other {Tried to read terminals {count} times}}", "537feee59d775e17": "{count, plural, one {Förhandsvisade {count} HTML-sida} other {Förhandsvisade {count} HTML-sidor}}", "4b45ac8cb8df04a4": "{count, plural, one {Försökte förhandsvisa {count} HTML-sida} other {Försökte förhandsvisa {count} HTML-sidor}}", "a6f62fca5dd25455": "{count, plural, one {Renderade {count} HTML-sida} other {Renderade {count} HTML-sidor}}", @@ -376,6 +399,31 @@ "476ca970255eaea4": "Länka den här miljön till T3 Connect för en publik URL.", "6b80f5b38a8f9950": "Bara den här datorn kan anropa den här adressen. Länka T3 Connect för en publik URL.", "c5a7b1d3891dd0b8": "Fungerar där den här miljöns adress kan nås, till exempel via Tailscale eller din egen proxy. Länka T3 Connect för en publik URL.", + "3669395daf36fd33": "Inte längre registrerat på den här servern", + "fe513cf316e796e3": "Körs som en del av andra arbetsflöden", + "ccf00b97925efab3": "Startas manuellt", + "421e585eb092b07b": "Startar vid {triggers}", + "7bd7c58592671384": "Behöver dig", + "834ca879c14c167b": "Arbetar", + "582d6df7dfab86fb": "Pausad", + "ea6583ce92507ee3": "Sover", + "7ea8cb8af281ce93": "Väntar", + "1347868f2523140e": "Klar", + "57d76c4614054271": "Stoppad", + "5c7344bd51d0b966": "Överhoppad", + "b2074e9bd23049a6": "Avbruten", + "5bb7401807ee2fb5": "Frågar: {question} och {more} till", + "9e4286183d5f9e34": "Frågar: {question}", + "474c18d001bd6717": "Ett steg misslyckades", + "d3890f4eb1508781": "Kör sina egna steg", + "3e7ced10c9482af0": "{step} arbetar", + "237e1bcb1cf1bdec": "Sover vid {step}", + "3f7b17ac5a20c8d2": "Kör {run}", + "0306f5f324b8aaa5": "{count} körningar pågår", + "e8fd779b84a202a2": "Väntar", + "b6d55657e1a027b8": "Väntar på {step}", + "e942562a42aede34": "Klar", + "26b2b9727fe11289": "Avslutad i förtid", "1bb995dcec481554": "Godkänn den här enheten på {host}. Den visar koden {verificationCode}.", "8696a33219944832": "Kunde inte skapa auktoriseringsbeviset för websocket.", "5678f133a8631f7d": "Din molninloggning har ändrats. Logga in igen för att auktorisera miljön.", @@ -637,6 +685,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", @@ -1721,6 +1772,8 @@ "2e995206e087c3fc": "Försök svara när anslutningen eller den väntande inmatningen är löst.", "604ec3067171a0d7": "Konversation", "d6182a057ea12624": "Överordnad tråd", + "f2d8537c33cc55a5": "Steg i arbetsflödeskörningen", + "ba8337dca3232880": "Öppna körning", "30fa4a764d11ae42": "Kunde inte ladda ned {name}", "4952f87dc98191a7": "Bilagan är inte tillgänglig.", "2fd6d178493fb407": "Det gick inte att avbryta den aktuella omgången.", @@ -1785,6 +1838,8 @@ "181677cda4d3fd0a": "Ingen ansluten miljö kan lägga till ett projekt", "3a0bf3d17f31584e": "Ny tråd i {project}", "4b4b64cc95acb8da": "Ny tråd i...", + "2c45783ab9680fdb": "Open Git graph", + "e813386e62652710": "Open agent stage", "3f581e98c86df72a": "Ny tråd utan projekt", "e510d9a7b684fbfe": "Triagera ett ärende", "cce3d80a2ddf1125": "En agent undersöker ett problem i T3 Code och hjälper till att skapa ett ärende", @@ -1806,6 +1861,7 @@ "04fd71efaa2c3b92": "Öppna pull requests", "57e875b79b98ab82": "Öppna ärenden", "f1db0a234c777a1d": "Använd T3 Code i en annan app (MCP)", + "6050f22f63e2bcb5": "Öppna arbetsflöden", "a0cc19e60dd99851": "Öppna användning", "46694969044eee98": "Fokusera nästa område i arbetsytan", "0a1011328ba42eef": "Fokusera föregående område i arbetsytan", @@ -2361,14 +2417,24 @@ "05037ca1666fd421": "Terminalytor finns bara i en projekttråd.", "a3aa1e49af278d41": "Filer är bara tillgängliga när ett projekt är öppet.", "87ea6995ea1e7aa4": "Diff är bara tillgänglig för servertrådar i Git-repon.", + "80f10f5ea1804d8d": "The Git graph needs a Git repository on an up-to-date server.", "4a87cae01ccde544": "Den här trådens gren har ingen pull request än.", "32535dba0b9af642": "Den här tråden har inga länkade objekt.", + "d955eee48dece3c0": "Enable the agent stage in Settings > General.", + "d2f2f6d05148f8a3": "Threads a coordinator runs have no thread overview.", + "26c1c05b0d1d98fd": "Turn on coordinator decisions in Settings > General.", + "486d4369c4fbec9e": "Notes are only available from a thread.", + "50b5a57d3bd6f6ef": "Instructions are only available from a thread.", + "007ab76950f73521": "Media is only available from a thread.", "07080dead70f4cc5": "Enheter är bara tillgängliga från en tråd.", "a4bf49b31758ff7e": "Finns bara i skrivbordsappen.", "e917841cb66f9af1": "Tillgängligt när ett projekt är öppet.", "14c15fad0c2ee0c8": "Tillgängligt för Git-repon.", "9176276c78f3893f": "Ingen pull request på den här grenen än.", "52ce9db6fb62a59f": "Inga länkade objekt tillgängliga.", + "96c2ee76dd82d2cc": "Enable it in Settings > General.", + "2199013487151590": "Not for threads a coordinator runs.", + "f7a9300d9f9030d5": "Turn on coordinator decisions in Settings.", "e5d6f41e4fe4efd6": "Tillgängligt från en tråd.", "0ebc2bb883a8e283": "Tillgängligt efter det första meddelandet.", "84d0ff8fb9846057": "Slå på ljudet för fliken", @@ -2377,8 +2443,15 @@ "5c78a8ae7b71af1d": "Terminal", "cba3e832ece50257": "Filer", "83ac3423d6dfc4a7": "Diff", + "016750bdd5076287": "Git graph", "da16af47eff38ae9": "Pull request", "ad3929f0103925d7": "Länkade objekt", + "70e7b208e032024a": "Stage", + "0caf7e5748f1d17b": "Threads this one started, and which need you.", + "96018894225bd4ff": "Inbox", + "0ed16d7723c04288": "Decisions the coordinator asks you for.", + "aec2b493d2b01445": "Notes", + "9e92f6aa6edae875": "Notes and todos for this thread, its project, or everywhere.", "ac0de2a59d9c8860": "Enhet", "1354df9fb7278843": "Titta på en iOS-simulator eller Android-emulator.", "fdcd9643e2e63b15": "Ställ en sidofråga medan tråden fortsätter arbeta.", @@ -2497,8 +2570,7 @@ "2d1c111e1b4ae0b0": "Ta bort tråden ”{title}”?", "c568ab8dad798ec5": "Det här rensar konversationshistoriken för den här tråden permanent.", "0fd1c746a0e38003": "Det gick inte att ta bort tråden", - "0ecde875b0dd2f93": "Filtrera trådar efter projekt: {projects}", - "1ef65b647231ff0b": "Filtrera trådar efter projekt", + "1c8fc3c4a42949ab": "Projekt: {projects}", "165511761be2855c": "Sök projekt", "a46a6467883575a4": "Sök projekt...", "fdc0e086438a3045": "Projektinställningar för {project}", @@ -2560,10 +2632,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 +2644,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 +2668,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", @@ -2686,8 +2756,6 @@ "78a04e0e625c0990": "Uppdateringen misslyckades", "c24de5eb69373a55": "Den här {build}-versionen ignorerar {track}-versioner. Granska uppdateringsspåret i Inställningar för att slutföra bytet.", "b02ae45a6109c93b": "Uppdaterad", - "edcda9e8ee4ccad8": "Installera uppdateringen {version} och starta om T3 Code?\n\nPågående uppgifter avbryts. Se till att du är redo innan du fortsätter.", - "02eba0f7cc90f759": "Installera uppdateringen och starta om T3 Code?\n\nPågående uppgifter avbryts. Se till att du är redo innan du fortsätter.", "9ed4d8a1531b9631": "Automatiska uppdateringar är inte tillgängliga i den här versionen.", "c8c23435e780a60c": "Uppdateringar är inte tillgängliga", "1af5f9767371ffd7": "Sök efter uppdateringar", @@ -3034,8 +3102,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 +3346,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 +3523,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", @@ -3577,6 +3649,13 @@ "c53bc5a4b0314342": "Nästa media", "2950b1424a3cddf5": "Återanslut till den här miljön och öppna mediet igen.", "ef638bf1479a5461": "Miljön returnerade en ogiltig media-URL.", + "3ccfbf7e86868c35": "Återkoppling till T3-teamet", + "4e0710d19dfc2e7e": "Skicka den här rapporten till T3-teamet?", + "87d0ae0723ba75d1": "Det här är allt som lämnar din dator. Inget skickas förrän du trycker på Skicka.", + "bf19826f81484328": "Ta med konversationen", + "ddb7e6f8ce99e657": "Bara den som kan köra agenter på den här datorn kan skicka eller avböja rapporten.", + "03c1eb603c112f47": "Skicka inte", + "653405e4ed498d9f": "Skicka", "262955d6eb632f9b": "Urklipps-API:t är inte tillgängligt vid kopiering av gästlänken.", "f1a4f2b04cdbb4ef": "Kunde inte kopiera gästlänken till urklipp.", "cf3490a604e44d31": "Kunde inte skapa en gästlänk.", @@ -3597,7 +3676,6 @@ "abd89e9eefedf11b": "Klar", "18d166056c1ab6ff": "Sluta dela", "7a2d510eac9e4587": "Gästlänken har gått ut", - "653405e4ed498d9f": "Skicka", "21888e302219891d": "Expanderad förhandsvisning av {title}", "419719298a7acaea": "Zooma ut", "ed8d5db95359cff4": "Återställ zoom", @@ -3693,7 +3771,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 +3782,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 +4058,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", @@ -5454,6 +5529,22 @@ "f0d79aa56f06663f": "Den här filen är för stor för att visas i sin helhet. Antalen inkluderar alla ändringar.", "7fdde2b893ba1b9d": "Borttagen", "e58ce271d835b447": "Tillagd", + "fb5c7ff5ea76e01a": "Added by esveo's fork. Click to list all of its settings.", + "352fa6aeb5d55665": "Trail the provider icon behind the thread title instead of giving it a line of its own. The line it saves also carried the branch, pull request badge and diff counts.", + "9d44fa03a230e0d8": "Reset two-line thread cards to default", + "7b216eedb1abe696": "Two-line thread cards", + "8d90fcd918e901c8": "Keep each project's threads together in the sidebar, under a header that folds the project away. Ordering stays by recency: the project with the newest thread leads.", + "d5dfd89c9a281386": "Återställ projektgruppering till standard", + "aac9f889c7ec7ff5": "Group sidebar threads by project", + "da375a07c5309184": "Show how full the thread's context window is next to the composer controls.", + "33f6b88cba203990": "Reset context window usage to default", + "6496f57baeded3fa": "Context window usage", + "d9c146dc6b95714d": "Show how many minutes are left before the prompt cache expires. Claude only.", + "69609e27c2107da5": "Reset prompt cache timer to default", + "a4917d2b93c478f6": "Prompt cache timer", + "ea8ebcb77e657e9f": "Open the thread details card with workspace and version control in every thread. Off, it stays closed until you open it, and each thread remembers your choice.", + "662288b90e19635f": "Återställ tråddetaljer till standard", + "92729a403d37c575": "Open thread details by default", "07b9970b662ab70d": "Visa Mermaid-källa", "5a422b7be35243f5": "Visa renderat diagram", "c0628ad999cbbbf5": "Visa Markdown-källa", @@ -5561,6 +5652,7 @@ "723d88a5fa7e2fdd": "Inga matchande filer.", "f8d6e9a1a2870a5c": "Filutforskare", "109edd252917113b": "Ändra storlek på filutforskaren", + "7abd6af24fed7b60": "The file does not exist in the workspace or the home folder.", "37cbd2ecc659a007": "Fil", "b5188f172f59ca79": "Den här anslutningen kan inte läsa värdens filer.", "c3c5d36466ad2191": "Öppna filen i förhandsvisningens webbläsare", @@ -5600,7 +5692,6 @@ }, ". Kontrollera länkens sökväg eller leta upp filen i Filer." ], - "b9b6bbd1e1ea189f": "Hela filen", "d715e9494fdbaaf6": "Teckensnittet kunde inte läsas in.", "ff17c777a72b4408": "Förhandsvisningar av teckensnitt är begränsade till 10 MB.", "6bd41ad699e22f10": "Teckensnittet är inte tillgängligt.", @@ -5610,6 +5701,7 @@ "a9abaaa4220eae21": "{error} Spara det för att öppna det i en annan app.", "c508c9000d9656f8": "Förhandsvisning av teckensnitt", "1c416d621d250be8": "Flygande bäckasiner söka hwila på mjuka tuvor.", + "d7d08260f16b7828": "Filen läses fortfarande in. Försök igen om en stund.", "76ebb03de52c92d6": "Textvisaren stoppades.", "f48162e8e8c12af7": "Kunde inte läsa in textvisaren. Stäng filen och försök igen.", "bc4c5b13d38a5da7": "Förhandsvisningen stängdes.", @@ -5617,8 +5709,6 @@ "9450d1827ef336a1": "En annan kopiering pågår.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} rad} other {{formatted} rader}}", "13b14784f8707ddd": "0 byte", - "f6e9581cba3467fa": "Indexerar…", - "2d1f293ac12463fc": "Läser in resten av filen…", "b75105bef8f564a4": "Visar de första 1 024 kolumnerna. Källa och Spara behåller alla kolumner.", "2a6e1b1f209c3888": "Den här filen är tom.", "192fc79eb3b5b2cb": "Det här diagrammet innehåller resurs-URL:er, markup, nodmetadata eller anpassad konfiguration. Visa Mermaid-källan för att granska det säkert.", @@ -5805,7 +5895,6 @@ "0061fff77e36bd4f": "Kunde inte nå servern.", "04dfdd46e3dd4a2e": "Något gick fel. Försök igen.", "084bb2d8127a508d": "Skickat", - "e7c59185f8ab3987": "Inte skickat", "77c01a15bd36d17c": "Den här länken har upphört eller är ogiltig", "e0e736810f3cbef2": "Be ägaren om en ny länk. Varje länk fungerar i en webbläsare.", "c3c53aa46f7330e5": "Den här länken har upphört", @@ -5827,6 +5916,13 @@ "cbb2129c0dd4f40b": "Bifogade filer får vara högst 10 MB totalt per meddelande.", "03b9cd79cfe0b435": "Den här filen kan inte bifogas. Bilder måste vara PNG, JPEG, GIF eller WebP.", "8ff29c78798e6ac1": "Kunde inte läsa in det här objektet.", + "535923000a0f3e3b": "Send /compact to a large, idle Claude thread shortly before its 1-hour prompt cache expires, so the next message skips caching the whole conversation again. 5-minute caches are left alone.", + "bd8eb8f5f9843bc6": "Reset idle auto-compact to default", + "1db274eacf03c8de": "Auto-compact idle Claude threads", + "fb6643c75aafd996": "Between {min} and {max}; it has to fall inside the cache's hour.", + "48dee64ca7904281": "Minutes idle before auto-compact", + "8937fe924464eb70": "Smaller threads are cheap to cache again and keep their full history.", + "1981f1e1a753aabc": "Minimum context tokens for auto-compact", "94ab4591ce101233": "Kommentaren kunde inte publiceras", "92d0d4eab2596772": "Ärendehanteraren nekade.", "33591d9596fb7cb7": "Lägg till en kommentar", @@ -8701,12 +8797,16 @@ "58e0e226493150e7": "Kunde inte läsa in ärendehanterare", "77cfcbde543df32d": "Visa/dölj detaljer för {tracker}", "0083f65885c60156": "Koppla från {tracker}", - "295392927d5c8a84": "Välj en eller flera {scope} i {tracker} för varje projekt. Deras ärenden listas bredvid repots egna, och agenter skapar nya ärenden i den första.", + "ed83b25c71c98a20": "Välj en eller flera {scope} i {tracker} för varje projekt. Deras ärenden listas bredvid repots egna, och agenter skapar nya ärenden i det första om de inte ombeds välja ett annat.", "19c2d5e81ff8f89a": "{scope} i {tracker} för {project}", "68e061510b765772": "Inte kopplad", + "99d51127f573296b": "Ett konto till", + "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare.", + "99963c0142e17f00": "För det nya {tracker}-kontot.", "a2d95d39d3398bda": "Autentiseringsuppgiften avvisades", "9eae463720500113": "Lagras på servern.", "b6e27ab2537ef874": "Skapa en", + "6d8e4ebc889bace9": "Lägg till konto", "13ef526271b0f5d4": "Rensa alla villkor", "d1938a629f039515": "Ta bort villkor", "84a605b241ce65b7": "Ta bort gruppen och dess villkor", @@ -8836,6 +8936,12 @@ "d3866ead082d14e5": "Lägg till kortkommando", "d4345c90894a3220": "Öppna keybindings.json", "e56a8d51219efaa0": "Inga kortkommandon matchar sökningen.", + "90a258fff61fd77e": "Av", + "4060244a7079a0d2": "När jag ber om det", + "e88c9d8769544731": "Automatisk", + "f29d1dade4dde8aa": "Agenter skickar ingen återkoppling till T3-teamet.", + "93c4c53562d30a98": "När du ber om det visar agenter en kort rapport om T3 Code och skickar den till T3-teamet om du godkänner den.", + "cd9ee803e8727017": "Agenter rapporterar även problem med T3 Code som de själva stöter på, till exempel ett T3-verktyg som misslyckats.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Gruppera trådar i sidofältet i projektmappar. Fästa trådar ligger överst, och Snoozade och Klara ligger under mapparna.", "e4e91d155cb6a9b4": "Enkelt sidofält (gruppera per projekt)", @@ -8844,11 +8950,16 @@ "9ae293971d93c819": "Dela en tråd med en gäst som följer den live i en webbläsare och skickar meddelanden som du godkänner. Logga in på T3 Connect för att använda gästlänkar.", "0aa5406ac4d7f7c7": "Gästlänkar", "f0e853acd2006d53": "Länkade miljöer", + "ef10c2dff987f3ea": "Kör arbetsflöden i flera steg från filer i mappen workflows i serverns T3-hemkatalog. Öppna dem från kommandopaletten. När det är av körs inget i mappen; körningar väntar tills det slås på igen.", + "2dadb2359422121c": "Arbetsflöden", "13e86eb5d8287a71": "Visa ett förutsagt nästa meddelande i det tomma inmatningsfältet efter en omgång med Claude eller Codex. Tab använder det. Varje förslag är en extra cachad begäran i ditt abonnemang. Kräver Codex 0.165+. Claude-trådar uppdateras vid omstart.", "d4b2a2ec812aafb0": "Föreslå nästa prompt", "298c7150a7621c80": "Simlock-enhetsvärdar", "67937aa49179285e": "På en Mac klonas nya worktrees från en utcheckning som cachas i T3-hemmappen i stället för att varje fil skrivs. Använder Gits vanliga utcheckning när det inte går. Om du stänger av det tas cachen bort.", "f9904f78d3003f58": "Snabb utcheckning av worktree", + "9c2f647882522302": "De valda datorerna använder olika lägen för återkoppling från agenter.", + "31bbf7bf8c0a5279": "Återkoppling från agenter", + "d52b3d6bf9f2a013": "Blandat", "ec7623deed751c05": [ "Dela en tråd med en gäst som följer den live i en webbläsare och skickar meddelanden som du godkänner. Kräver T3 Connect: logga in och länka den här datorn under", " ", @@ -8932,7 +9043,9 @@ "fb71127e5746a6bc": "Från Delning och åtkomst där, eller t3 pair", "1e3fee7084791773": "Länka även {target} tillbaka till {source}", "ea34a190b0bd804c": "Agenter på {target} kan då också arbeta på {source}.", - "ad5ed0ce61b966eb": "Glöm {label}? Agenter här slutar arbeta där. Återkalla ”T3 Code · …” under Delning och åtkomst på {label} för att avsluta sessionen där också.", + "974f8c65e8b5f492": "Glöm {label}? Agenter här slutar arbeta där, och deras session på {label} avslutas också om den svarar.", + "6cf9e3083b15614f": "{label} svarade inte", + "34ccbdf619b83be3": "Återkalla ”T3 Code · …” under Delning och åtkomst på {label} för att avsluta sessionen där också.", "81c9796bf61b306a": "Kunde inte glömma länken", "130e51beb6cf5aad": "Länka en miljö", "122c3e355699e69d": "Agenter här kan sedan starta, skicka meddelanden till och vänta på trådar där. Den visas under Auktoriserade klienter i miljöns Delning och åtkomst, där den kan återkallas.", @@ -9161,7 +9274,6 @@ "0b4779a1825c85bc": "Det gemensamma namnet för projektgruppen i sidofältet och trådlistorna.", "f68cbda4df83d739": "Återställ projektnamn till standard", "56e37b85027e8431": "Projektikon", - "e88c9d8769544731": "Automatisk", "c99736317da5b1fa": "Återställ projektikon till standard", "6afaa3e3739dc570": "Välj en projektikon", "51651ce45d481a20": "Välj en fil för projektikonen", @@ -9511,9 +9623,9 @@ "d2b0987f8c907e13": "Samplar var {ms} ms", "4a3d538e12caed70": "{count, plural, one {Samplar var {seconds} sekund} other {Samplar var {seconds}:e sekund}}", "32c787e014d8f2ec": "Underprocess i backend", - "ca84041dbbfb9e45": "Electron main", + "ca84041dbbfb9e45": "Electrons huvudprocess", "0693ca29c961e19b": "Renderare", - "fb4e08f7e0f78d3b": "Electron utility", + "fb4e08f7e0f78d3b": "Electrons hjälpprocess", "7f206abc2cb38ab2": "Övervakare", "7cdfa8c2f4106d6a": "T3-process", "9bc60e1d0ef816cf": "Lagringsbyte", @@ -10072,7 +10184,6 @@ "53de7aafe0afc10d": "Kunde inte återställa temainställningarna", "006bfa1846fe5dd2": "Dagar av inaktivitet innan automatisk markering som klar", "d9b0fbd680d5f175": "Sidofält", - "d5dfd89c9a281386": "Återställ projektgruppering till standard", "cd5452cc9e13c818": "Projektgruppering", "cfb01b8a2a3361fb": "Återställ projektordning till standard", "26abcbe322049a8a": "Återställ avsnittet Arbetar till standard", @@ -10137,7 +10248,6 @@ "16bdc70b858c223f": "Återställ proaktiva paneler till standard", "c5424f09d77138ff": "När en inaktiv Claude-tråd på över 200 000 token ska komprimeras: när du kommer tillbaka, precis innan dess promptcache går ut, eller aldrig. Varje Claude-leverantör kan åsidosätta detta.", "3e99c5c14f4939c8": "Återställ komprimering av inaktiva trådar till standard", - "d52b3d6bf9f2a013": "Blandat", "cd72fe451ba0d6aa": "Nya projekt", "394c3bd0a1782c8e": "Lämna tomt för att använda ”~/” när bläddraren Lägg till projekt öppnas.", "f9b912a818bd869d": "Återställ baskatalog för nya projekt till standard", @@ -11039,7 +11149,6 @@ "4a237f41ce592b7f": "Behåll projektets worktrees tills du tar bort dem manuellt.", "00b8ffd8ea6e6a93": "Använd de här reglerna för projektet.", "72c279824d15a999": "Använd varje dators inställningar för rensning av worktrees.", - "90a258fff61fd77e": "Av", "b5702d0b64866b08": "Anpassat", "c009c901f3eefe78": "Ta bort worktrees med borttagna trådar", "431c7cd6d50102b7": "Ta bort oanvända worktrees när aktiva eller arkiverade trådar tas bort. Worktrees med lokala ändringar behålls.", @@ -11396,7 +11505,6 @@ "f2043e87a10cb831": "Redigera tema", "595bdeefcdc9bf31": "Exportera temafil", "b480281b3791b685": "Välj vad kortet med tråddetaljer visar. Du kan också högerklicka på kortet.", - "662288b90e19635f": "Återställ tråddetaljer till standard", "871d059d88548434": "Tråddetaljer: {enabled} av {total} på", "cec1fbb8b4c9180d": [ { @@ -11735,7 +11843,6 @@ "4c70e3e7b3e6c493": "Hemligheter", "79b768229c9ef672": "Underhåll", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Om", "af4b7734da1d5ce7": "Röst", "4ec62c39ca3192bf": "Versioner och ärenden", "f2bf529f85e05494": "Delning och åtkomst", @@ -11764,11 +11871,17 @@ "8f5966eebd2b110f": "utseende färger palett anpassad import", "633ed64e952cca3b": "färger kanter gränssnitt", "9cf8308531b4ff31": "transparent genomskinlighet solid menyer dialoger inmatningsfält", + "d99bfbc557fae743": "Notion", + "89df56091835b3a6": "notion integration secret pages links viewer connect token ntn", + "d699adcc04d4d4ab": "sidebar compact row height branch provider icon diff pull request", + "9b9df5ba41c4a8e2": "Group threads by project", + "0ed2eab2c1953531": "sidebar project folder runs grouping collapse header repository", "d8d6cfd630cff22d": "röd grön blå orange tillägg borttagningar ändringar antal palett färgblind", "717e49895cfee1c7": "bred full bredd kolumn layout meddelanden inmatningsfält skärm", "88365077fd80787b": "anpassa visa dölj panel kort miljö redigerare skript gren pull request git ändringar servrar automatiseringar härkomst användning gränser 5 timmar vecka kvot token kontextfönster", "d561f74efa5f3920": "resonemang ansträngning tänkande staplar diagram ord etikett nivå inmatningsfält", "6113c17109ee0d57": "latex tex katex ekvationer formler markdown", + "dfe7ead48efc3f5a": "thread details card panel workspace version control closed collapsed hide", "8c8364d44fa28d22": "dev nightly latest kanal grafik pill etikett dölj ingen", "2d90635156dfcb5a": "typografi typsnitt familj storlek system sans", "d32e93777e4819c8": "typografi typsnitt familj storlek inmatningsfält inmatning", @@ -11790,6 +11903,7 @@ "d443390c4d2dcfd4": "tillgänglighet a11y skärmläsare nvda jaws voiceover orca skärmläsaren fönstertitel fliktitel alt tab aktivitetsfält trådstatus ordning arbetar godkännande", "6826fa9579c22035": "beta dela gäst bjud in länk kollega titta t3 connect tunnel", "f10c06cba0cdf7fe": "beta länka en annan dator vps peer agenter arbetar där delegera", + "bc0b409d89ce086e": "beta arbetsflöde workflow beständiga körningar automatisering steg schema webhook mapp", "4a21cf825a2045b0": "beta tabb autokomplettering förutsäg nästa meddelande claude codex spöktext", "fea2dc36585c4a20": "Simlock-enhetsvärdar (alfa)", "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lån gateway", @@ -11831,7 +11945,29 @@ "34d74827c2a8b009": "enter retur command ctrl flera rader prompt ny rad inmatningsfält", "9d1013084c46ecce": "kö styr om pågående omgång skicka standardbeteende inmatningsfält", "e5e7f5e1fb1f2e4c": "subagent sidochatt länkad tråd klick högerpanel sidopanel huvudvy kommando ctrl mittenklick", + "5c59d7e2673267ea": "composer tokens usage meter percentage compaction", + "e0d6ec10218b714e": "composer claude cache ttl expire minutes warm cold tokens", + "ce0952668aba4140": "Agent stage", + "f637899f994b78c3": "sprites stations subagents thinking editing terminal right panel everything", + "9d9d3374ee961b91": "Easter eggs", + "571180dbfeddbfd5": "surprise fun rocket animation message send hidden", + "0716adb0d55ffa58": "Voice calls", + "027d8f5ea5555973": "voice call phone gpt live feature flag anruf telefon schalter", + "60d509bb55e2967c": "Voice call voice", + "0e5f5c5ebf026abd": "voice call phone gpt live speaker stimme anruf telefon", + "266f1e2b55e419b0": "Voice call follow-up", + "392226d9bed6fe21": "voice call queue steer follow-up warteschlange anruf", "5b8b854de7ee6f4d": "installerade cli versioner nyare tillgänglig codex claude cursor grok fx kiro opencode", + "1ceaab7d898b689a": "Child threads in the sidebar", + "fa5a42a73d1c1ece": "coordinator subthreads nested group expand sidebar orchestration children", + "6a1072050d1ad19e": "Coordinator decisions", + "474ba8e025886f86": "inbox questions answers decide approve coordinator open items", + "8f5558f063214509": "Cross-project threads", + "b809e3ffa5178b88": "agents coordinator other projects read message start threads repositories", + "44207b47d209f601": "compact context prompt cache idle claude tokens cost expire", + "396a2cc5b442e359": "compact idle minutes prompt cache ttl", + "6d9520a9cbd70c2f": "Minimum context for auto-compact", + "2fe046cc1e0d0d4a": "compact context tokens threshold size", "64f12530d55d2ad1": "återuppta pågående aktiv avbrutet arbete omstart starta om dator krasch skrivbord uppdatering automatiskt", "214a98497c4ed05d": "caffeinate viloläge förhindra håll vaken ström laptop lock förhindra", "00469926c7027e2d": "balanserad prestanda batterisparläge avancerat git fetch leverantör hälsa uppdatera värd ström övervakning inaktiv policy", @@ -11861,6 +11997,7 @@ "901a823214edc8c4": "telemetri analys användningsdata spårning juridiskt avböj", "82136480255a5106": "OTel OTLP telemetri export slutpunkter loggar spår mätvärden Grafana", "659d081051faf7ff": "loggar spår processer resurshistorik fel spans cpu minne", + "5eaeacfa9f82051a": "rapport bugg problem t3 team skicka återkoppling agenter verktyg automatiskt när jag ber om det", "f537f91e1ee41d47": "kortkommandon snabbtangenter kommandon tangentbindningar json", "1ba01e7ceed64b95": "fönster fånga skärmbild", "279b1cceb779ff38": "Ta med apptext", @@ -12066,6 +12203,8 @@ "v": "v" } ], + "643c4b50feadc874": "Worktree: {path} ({branch})", + "fb7c44da0f0825ea": "Worktree: {path}", "e7f35f60e6229cf5": "Skrivbordsapp", "77be1b7e2a1d3d31": "{count, plural, one {Uppdatera {count} dator?} other {Uppdatera {count} datorer?}}", "e4892b21e88abb60": "{count, plural, one {{count} leverantörsuppdatering} other {{count} leverantörsuppdateringar}}", @@ -12129,6 +12268,25 @@ "ffaa75d2db1e7cc1": "Uppdateringen tillämpades inte", "626bcbe04dc55f93": "T3 Code har fortfarande {current}. Installera {version} igen med uppdateringsknappen.", "49214c047fbb1606": "Leverantörsuppdateringen avbröts", + "a135af0f1efda8de": "Cross-project", + "6e9798372b3fb922": "Coordinators put the questions they need you to decide into an Inbox tab beside the chat, instead of numbering them in their messages. Running sessions pick up a change.", + "7a5292a1705defec": "Reset coordinator decisions to default", + "9e3ff0f05f52b724": "Let agents read, message and start threads in other projects of this environment. Running sessions pick up a change.", + "384695cdd7ab6b54": "Reset cross-project threads to default", + "5a6c243a03eeca0c": "Choose a coordinator", + "f527bb5b4ad333da": "Coordinator for \"{title}\"…", + "6beb2db2a7b5edae": "Could not assign the thread", + "4ebb0c90c45690c0": "Could not detach the thread", + "73ac4f532306bea6": [ + "Assign \"", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "\" to a coordinator" + ], + "1871eb35b1ca5d41": "No thread can coordinate this one.", "52adbc863aeb5e59": "Kunde inte kopiera", "0944728904d886d2": "Mättnad och ljusstyrka för {label}", "dded2cb4e4d26338": "Mättnad för {label}", @@ -12330,7 +12488,6 @@ "0bd41ff995d36a66": "Cacheläsning", "3f0dfe0cb15a3272": "Cacheskrivning", "1c9d860be42b1c02": "Utdata", - "78344b60f407928e": "Övrigt", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Snabb", "66796576034c18ea": "Ultrasnabb", @@ -12346,6 +12503,270 @@ "2cddd6095abc734a": "7 dagar", "53493056306708cf": "30 dagar", "c719359d18d37ad3": "90 dagar", + "a7ad3167ca62e7de": "Talk to your agents by voice with GPT-Live on your Codex ChatGPT login. Turning this off ends a running call.", + "9f0e45a1d67187cd": "Reset voice calls to default", + "da0ae8174ac2fc14": "Queue what you say in a voice call while the agent runs, or steer the current run. Saying otherwise overrides it for one message. A change applies from the next call.", + "fb0a2aa3b08a17c4": "Reset voice call follow-up to default", + "66936cae56d1d749": "Queue", + "89bf6f658c44cb1b": "Steer", + "930a28582d2c103f": "The voice that talks to you in a voice call. A change applies from the next call.", + "591a53f319b0d343": "Reset voice call voice to default", + "0bd950151ddc6407": "Lämna utan att spara? Dina ändringar i filen går förlorade.", + "c0ba3f6756b09f30": "Osparade ändringar", + "6914e22d357f0ad6": "Sparad och körs", + "aff389354a031d6f": "Filen på disken går inte att läsa in. Den senaste versionen som gick att läsa in körs vidare.", + "858effde748ab563": "Sparad, men den körs inte än.", + "ddb37138df660942": "Inte sparad. Inget ändrades på servern.", + "6ef4db489e40e39e": "Kunde inte spara", + "c89624a2e9af1793": "{name} är inte ansluten", + "b5a352a43adb4c17": "Dess arbetsflöden visas igen när den ansluter igen. Välj en annan miljö för att se dess körningar.", + "3dcedb736d20aae5": "Kunde inte läsa arbetsflödesfilerna", + "b09f4df8d76ae8ea": "Ta bort {file}? Arbetsflödena som den definierar kan inte längre startas.", + "b4535f5a03689d27": "{name} är inte ansluten. Det du skriver här finns kvar och kan sparas när den är tillbaka.", + "b54c78d85fd942ea": "Borttagen, men det som körs har inte hunnit ikapp än.", + "407c228d7da0b7df": "Inte borttagen. Inget ändrades på servern.", + "1a6aa10f3cc14fff": "De här filerna passar inte ihop. Det som kördes förut körs vidare.", + "259312516a1dbe6f": "Filnamn", + "2f48ab2aa0586853": "Definierar inga arbetsflöden", + "ba5adfa37b55b8c5": [ + "Rad ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Ta bort", + "84c900d1ae72adc6": "Spara", + "5912d817be03247a": "Filen ändrades på disken medan du redigerade. Om du sparar ersätts den ändringen.", + "0b1e6f5608826387": "Läs in filen och släng mina ändringar", + "f47b4c06aeb77c1c": "Läser in arbetsflödesfilerna…", + "4353bfd401d58f87": [ + "Varje fil i", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "definierar arbetsflöden. En ändring i någon av dem plockas upp utan omstart." + ], + "0c165251a06f10f1": "Ny fil", + "8e97cf734b4463e7": "Skapa", + "2ec0d5108fd6cebe": "Inga arbetsflöden än. Skapa den första filen här, eller be en agent skriva en i den mappen.", + "5601350626e8cfe9": "Går inte att läsa in", + "21d778a1b9a0c234": "Öppet bredvid körningen", + "62dc4d3a19ff7ca0": "Stäng flik", + "1e25265f2758fce3": "Öppna som en hel tråd", + "672a3dae06b39402": "Öppna på en egen sida", + "7755500a4cde5066": "Stäng panelen", + "b8dcbc93a2ca1861": "Körningen listar det inte längre.", + "115c69de3202f664": "Öppna", + "644eafa9048b62df": "{count, plural, =1 {1:a försöket} =2 {2:a försöket} =3 {3:e försöket} other {försök {count}}}", + "e39f89c909df4db0": "Kunde inte återuppta körningen", + "865f034346b82f47": "Avbryta {title}? Dess agenter stoppas och körningen kan inte återupptas.", + "6bc75632fd9c9136": "Kunde inte avbryta körningen", + "64e50329dcfdd5b0": "Klar", + "350162e7cc1ebea4": "Stoppad", + "0875cf506f4c6810": "Överhoppad", + "3cc43f1dbf3f8e0c": "Avbruten", + "ded70e75de6404ba": "Tillbaka till listan över körningar", + "2f4ed7dbd22be30d": "Avbryt körningen", + "614e5ad58a795fb5": "Stoppa", + "04b050b0329f0ac8": "tog {duration}", + "aff78e1774818ff4": "{duration} hittills", + "38eddd466439afc9": "Vad körningen rörde", + "156ec271d49ddd70": "Vad som hände", + "34f59bbbead0b97f": "{names} och {count} till", + "ac1556f6ce89a5ea": "{count} parallellt", + "e197c4963bacc746": "{count} körs", + "f5319ed9e18c0df1": "Frågar dig", + "882a25e9084ae1b2": "Pausad", + "9a03d8a9afc60387": "Steg hittills", + "2f2ae791afe01674": "väntar på ditt godkännande", + "24f8060c4ccdf928": "startar", + "30a5be40eb956663": "arbetar", + "dd7a1e58c2553933": "vaknar om {duration}", + "95cc952724dd7310": "vaknar strax", + "3cc34921c0128593": "körs", + "e777db2880f53a46": "ingen svarade", + "dc90739d391a5e67": "Du svarade {choice}", + "389f2563b5b763fd": "Snabba steg", + "a41c8d758121ad81": "sov", + "9db248b770096984": "väntade", + "c76124517af28686": "har körts i {duration}", + "89102905bf09b0e8": "Följ live", + "bdf338cdff4118f0": "Transkript", + "811e7e992f9ff820": "kan inte fortsätta förrän dess arbetsflödesversion registreras igen", + "4d4cdf035e98dd57": "väntar på att du återupptar den", + "eb5b21dd224a5941": "försöker igen själv om {duration}", + "6ab3dfa749fde477": "försöker strax igen själv", + "44b6463aa70aa14c": "Varför den pausades", + "cf25e7169ab0eb7a": "Pausad vid {step}", + "56c48c1f220f2754": "Kunde inte svara på frågan", + "a3c43735e1a81498": "Skäl för {title}", + "bfad234f016cfa3f": "Varför, i en mening. Det följer med vilket svar du än väljer.", + "004c41aff9c97873": "Körningar", + "4dc0c244a2419f6c": [ + "Del av ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "startade", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "dess version är inte längre registrerad", + "f92d9132f7b85d1a": "Läser in steg…", + "6ebc59f64c761a49": "Inget än.", + "a759dccd157d7dae": [ + "Du svarade", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Du svarade", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Öppna körning", + "c8eb9be36d4d51ad": [ + "Tråd på ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Återuppta", + "8cebd63fc4c967d5": "Bara det misslyckade steget körs igen; det som blev klart före det behålls.", + "bc1e0a2a0f1e9552": "Behöver dig", + "a812f51e970740f1": [ + "frågade", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· körningen väntar på dig" + ], + "02dfe6c63fd0b8a1": "Lägg till ett skäl", + "19abd94828a3bdbc": "Fråga agenten först", + "a18721fa8f328361": "Behöver dig", + "bbf24e7920c1e86b": "Körs", + "8d6e18d2ad832db6": "Alla", + "f25af5332ffc3734": "Inget väntar på dig.", + "c3f0119b8d6231f8": "Inget körs.", + "33028dfc1229eaa6": "Inga körningar än.", + "5459bf696a187c26": "Kunde inte läsa in arbetsflödeskörningarna", + "d57c35d43b0f163a": "Den här körningen finns inte här", + "b9aae2f7cdb1a379": "Inga arbetsflödeskörningar än", + "8f15f66e545af7c0": "Vilka körningar", + "b6409289e0c9a4dd": "Arbetsflöde", + "035cb02ca1ae4952": "Alla arbetsflöden ({count})", + "46d614fa7b4bf1e5": "Arbetsflödeskörningar", + "1c635faa2fb45b8b": "Har inte körts än.", + "156ff7b625287a1e": "Dölj överhoppade", + "69b985b97ab45e6b": "Visa överhoppade ({count})", + "2400254d362de84d": "Läser in arbetsflödeskörningar…", + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "En arbetsflödesfil har ett problem." + }, + " ", + "Den senaste versionen som gick att läsa in körs vidare." + ], + "ed8ce6ebc73dc12d": "Öppna filen", + "145e1f7503ba3b2c": [ + "Den här miljön har ingen körning med den länken.", + " ", + { + "t": "button", + "i": 1, + "c": "Tillbaka till körningarna" + } + ], + "783e616cb0476c17": [ + "Ett arbetsflöde knyter ihop agenter, kod, scheman och frågor till dig i en enda körning som överlever omstarter. Skriv ett under", + " ", + { + "t": "button", + "i": 1, + "c": "Definitioner" + }, + ", eller be en agent göra det.", + " ", + { + "t": "a", + "i": 2, + "c": "Läs guiden" + } + ], + "5d8d278ff828102d": "Alla arbetsflöden", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · transkript", + "c512071143a5ba32": "Den här tråden finns inte längre.", + "ed169d23683fb6ac": "Läser in tråden…", + "290e0ab40b87dc17": "Brödsmulor för arbetsflöden", + "683dd9831e54edc0": "Miljö", + "34ad53646f06ed80": "Arbetsflöden är avstängda", + "8f6589c9e0ac5d4e": "Ingen miljö ansluten", + "744127f8dfad7d22": "Anslut en miljö för att se dess arbetsflödeskörningar.", + "036182ec7e2ee4d4": "Bredvid körningen", + "2d6107cb78382d08": "Arbetsflöden", + "16f7df687349b399": "Definitioner", + "f0a212aadfe1257b": "Läser in redigeraren…", + "20f194e003885e95": [ + "Slå på dem för den här servern i", + " ", + { + "t": "Link", + "i": 1, + "c": "Inställningar → Labs" + }, + "." + ], "8367779e149f723b": "Begäran till den primära miljön misslyckades under {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Ogiltig parkopplingstoken. Kontrollera token och försök igen.", "0e4b49c8203aae81": "Tidsgränsen överskreds i väntan på en autentiserad session efter uppstart.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 17d0dd6a93303..62927eefcc82a 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -52,6 +52,27 @@ "eb0f60ef4f92ab7d": "请从 {fjUrl} 安装 {fj} 0.6 或更高版本并运行 {fjLogin},或从 {teaUrl} 安装 {tea} 0.16 或更高版本,并为每个 Forgejo 或 Gitea 服务器运行 {teaLogin}。", "d026a85e2e50e675": "请使用 {install} 安装 GitCafe CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", "22d3c0c48a34b5b3": "请使用 {install} 安装 TanStack Source CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", + "756c80ad262ef315": "正在原始对话中等待", + "d8df14f9905f38eb": "已发送", + "e7c59185f8ab3987": "未发送", + "b54ddec9084fa955": "已关闭,未发送", + "fbaa7ab5da716e50": "错误", + "01bac997ea55272e": "难以理解", + "0f53bc8f74dfe56a": "缺少功能", + "055560f307e15e30": "文档有误", + "78344b60f407928e": "其他", + "f653846a95cd6e8f": "类型", + "f41ea186c275b56e": "关于", + "2f6e4f7cd364da73": "预期行为", + "9d11c93d4035de3e": "实际情况", + "c87d0595693704f9": "替代做法", + "d7a4ea6ce5af44e0": "{speaker} · {count} 个字符", + "f5114fb9c40fd929": "你", + "cd03eb1b84271c02": "智能体", + "bfe1a60f3f9c60fb": "第 {turn} 轮 · {what}", + "dfdaa6255a416140": "{turns, plural, one {最近 {turns} 轮的概要} other {最近 {turns} 轮的概要}},{textTurns, plural, =0 {不含消息文本} one {包含最后一轮的消息文本} other {包含最近 {textTurns} 轮的消息文本}}{truncated, select, yes {,已缩短以符合长度限制} other {}}", + "260c6b45f52d2f27": "添加你在最近 {textTurns} 轮中的消息和智能体回复的文本。", + "afac52a5cc2dc801": "无法发送你的回答。请重试。", "79d776428f4d0650": "无法加载文件。请重新连接后重试。", "3ea34cbb1ca5ba9b": "预览已取消。", "7c0af279ecb3da3a": "此运行时不支持流式文件预览。", @@ -118,9 +139,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。", @@ -246,6 +267,8 @@ "fec888c767b662d5": "尝试检查关联的 issue", "bc31067af9c79d82": "{count, plural, other {已检查关联的 issue {count} 次}}", "c712fec8d9dc6dd6": "{count, plural, other {尝试检查关联的 issue {count} 次}}", + "81c2282590e549f5": "{count, plural, one {Read terminals {count} time} other {Read terminals {count} times}}", + "79cd7c5c29ffa938": "{count, plural, one {Tried to read terminals {count} time} other {Tried to read terminals {count} times}}", "537feee59d775e17": "{count, plural, other {已预览 {count} 个 HTML 页面}}", "4b45ac8cb8df04a4": "{count, plural, other {尝试预览 {count} 个 HTML 页面}}", "a6f62fca5dd25455": "{count, plural, other {已渲染 {count} 个 HTML 页面}}", @@ -376,6 +399,31 @@ "476ca970255eaea4": "将此环境关联到 T3 Connect,获取公网 URL。", "6b80f5b38a8f9950": "只有本机可以访问此地址。关联 T3 Connect 可获取公网 URL。", "c5a7b1d3891dd0b8": "只要能连接此环境的地址(例如通过 Tailscale 或你自己的代理)即可使用。关联 T3 Connect 可获取公网 URL。", + "3669395daf36fd33": "已不再注册到此服务器", + "fe513cf316e796e3": "作为其他工作流的一部分运行", + "ccf00b97925efab3": "手动启动", + "421e585eb092b07b": "由 {triggers} 触发启动", + "7bd7c58592671384": "等你处理", + "834ca879c14c167b": "运行中", + "582d6df7dfab86fb": "已暂停", + "ea6583ce92507ee3": "休眠中", + "7ea8cb8af281ce93": "等待中", + "1347868f2523140e": "完成", + "57d76c4614054271": "已停止", + "5c7344bd51d0b966": "已跳过", + "b2074e9bd23049a6": "已取消", + "5bb7401807ee2fb5": "提问:{question},另有 {more} 个", + "9e4286183d5f9e34": "提问:{question}", + "474c18d001bd6717": "有步骤失败", + "d3890f4eb1508781": "正在运行自身的步骤", + "3e7ced10c9482af0": "{step} 正在运行", + "237e1bcb1cf1bdec": "在 {step} 休眠中", + "3f7b17ac5a20c8d2": "运行 {run}", + "0306f5f324b8aaa5": "{count} 个运行进行中", + "e8fd779b84a202a2": "等待中", + "b6d55657e1a027b8": "正在等待 {step}", + "e942562a42aede34": "已完成", + "26b2b9727fe11289": "提前结束", "1bb995dcec481554": "请在 {host} 上批准此设备。它会显示代码 {verificationCode}。", "8696a33219944832": "无法创建 WebSocket 授权证明。", "5678f133a8631f7d": "你的云端登录已变化。请重新登录以授权环境。", @@ -637,6 +685,9 @@ "fc2020db8a3804c0": "{host} 无法建立 WebSocket 连接。", "d9ce6c142a485959": "{host} 已 {seconds} 秒无响应。", "d6bdce8f4e6101a4": "{host} 已断开连接。", + "8450a95e5214d199": "{host} 发送了此客户端无法读取的服务器配置更新。", + "56b4ff3993c93eca": "{host} 发送了不兼容的服务器配置。", + "368c4d4f99c66bfb": "请将客户端和服务器更新到兼容的版本。", "e5fd422e445391fc": "上传失败。点按以重试。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -1721,6 +1772,8 @@ "2e995206e087c3fc": "请在连接恢复或待处理的输入完成后重试回复。", "604ec3067171a0d7": "对话", "d6182a057ea12624": "父会话", + "f2d8537c33cc55a5": "工作流运行的步骤", + "ba8337dca3232880": "打开运行", "30fa4a764d11ae42": "无法下载 {name}", "4952f87dc98191a7": "附件不可用。", "2fd6d178493fb407": "无法中断当前这一轮。", @@ -1785,6 +1838,8 @@ "181677cda4d3fd0a": "没有可添加项目的已连接环境", "3a0bf3d17f31584e": "在 {project} 中新建会话", "4b4b64cc95acb8da": "在以下位置新建会话…", + "2c45783ab9680fdb": "Open Git graph", + "e813386e62652710": "Open agent stage", "3f581e98c86df72a": "不关联项目新建会话", "e510d9a7b684fbfe": "排查 issue", "cce3d80a2ddf1125": "由智能体排查 T3 Code 的问题并协助提交 issue", @@ -1806,6 +1861,7 @@ "04fd71efaa2c3b92": "打开 PR", "57e875b79b98ab82": "打开 issue", "f1db0a234c777a1d": "在其他应用中使用 T3 Code(MCP)", + "6050f22f63e2bcb5": "打开工作流", "a0cc19e60dd99851": "打开用量", "46694969044eee98": "聚焦下一个工作区区域", "0a1011328ba42eef": "聚焦上一个工作区区域", @@ -2365,14 +2421,24 @@ "05037ca1666fd421": "终端面板仅在项目会话中可用。", "a3aa1e49af278d41": "打开项目后才能使用文件面板。", "87ea6995ea1e7aa4": "差异仅在 Git 仓库的服务器会话中可用。", + "80f10f5ea1804d8d": "The Git graph needs a Git repository on an up-to-date server.", "4a87cae01ccde544": "此会话的分支尚无 pull request。", "32535dba0b9af642": "此会话没有已关联项。", + "d955eee48dece3c0": "Enable the agent stage in Settings > General.", + "d2f2f6d05148f8a3": "Threads a coordinator runs have no thread overview.", + "26c1c05b0d1d98fd": "Turn on coordinator decisions in Settings > General.", + "486d4369c4fbec9e": "Notes are only available from a thread.", + "50b5a57d3bd6f6ef": "Instructions are only available from a thread.", + "007ab76950f73521": "Media is only available from a thread.", "07080dead70f4cc5": "设备仅在会话中可用。", "a4bf49b31758ff7e": "仅桌面应用可用。", "e917841cb66f9af1": "打开项目后可用。", "14c15fad0c2ee0c8": "仅适用于 Git 仓库。", "9176276c78f3893f": "此分支尚无 pull request。", "52ce9db6fb62a59f": "没有可用的已关联项。", + "96c2ee76dd82d2cc": "Enable it in Settings > General.", + "2199013487151590": "Not for threads a coordinator runs.", + "f7a9300d9f9030d5": "Turn on coordinator decisions in Settings.", "e5d6f41e4fe4efd6": "在会话中可用。", "0ebc2bb883a8e283": "发送第一条消息后可用。", "84d0ff8fb9846057": "取消标签静音", @@ -2381,8 +2447,15 @@ "5c78a8ae7b71af1d": "终端", "cba3e832ece50257": "文件", "83ac3423d6dfc4a7": "差异", + "016750bdd5076287": "Git graph", "da16af47eff38ae9": "PR", "ad3929f0103925d7": "已关联项", + "70e7b208e032024a": "Stage", + "0caf7e5748f1d17b": "Threads this one started, and which need you.", + "96018894225bd4ff": "Inbox", + "0ed16d7723c04288": "Decisions the coordinator asks you for.", + "aec2b493d2b01445": "Notes", + "9e92f6aa6edae875": "Notes and todos for this thread, its project, or everywhere.", "ac0de2a59d9c8860": "设备", "1354df9fb7278843": "查看 iOS 模拟器或 Android 模拟器。", "fdcd9643e2e63b15": "在会话继续运行的同时追问一个旁支问题。", @@ -2501,8 +2574,7 @@ "2d1c111e1b4ae0b0": "删除会话“{title}”?", "c568ab8dad798ec5": "这将永久清除此会话的对话历史。", "0fd1c746a0e38003": "删除会话失败", - "0ecde875b0dd2f93": "按项目筛选会话:{projects}", - "1ef65b647231ff0b": "按项目筛选会话", + "1c8fc3c4a42949ab": "项目:{projects}", "165511761be2855c": "搜索项目", "a46a6467883575a4": "搜索项目…", "fdc0e086438a3045": "{project} 的项目设置", @@ -2564,10 +2636,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "它在另一台机器上,本机的智能体读不到它。请移除它,或切回那台机器再发送。", "5bbac0e5afeec779": "当前会话", "33c7e68fca089036": "会话,{title}", - "b4b98a0287c282e2": "它在另一台机器上,本机的智能体读不到它。请移除它,或切回那台机器再发送。", - "c6196d99000642b4": "打开会话", "34cc63390ad793cc": "选择会话", "8f12309ead62e38a": "搜索会话或项目…", "2f664754d005d9a7": "未找到活动会话。", @@ -2577,6 +2648,7 @@ "a3178769f8308cbc": "会话失败", "89b5e8f3887812da": "访客请求", "62e626804919b294": "需要输入", + "c6196d99000642b4": "打开会话", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "你:", "a1fbf2422c588292": "智能体:", @@ -2600,8 +2672,6 @@ "3260b22f72f7effb": "{tooltipLead}:{title}", "feac8e54b30c5a03": "终端进程正在运行", "fc2c9a91f498ad6b": "{count, plural, other {{count} 个终端进程正在运行。打开终端}}", - "643c4b50feadc874": "工作树:{path}({branch})", - "fb7c44da0f0825ea": "工作树:{path}", "56f37ff8ca568059": "堆叠", "6831e9a46cbd8939": "链", "9aa9e74a3b7eee91": "添加到对话", @@ -2690,8 +2760,6 @@ "78a04e0e625c0990": "更新失败", "c24de5eb69373a55": "此 {build} 版本会忽略 {track} 版本。请在设置中检查更新通道以完成切换。", "b02ae45a6109c93b": "已是最新版本", - "edcda9e8ee4ccad8": "安装更新 {version} 并重启 T3 Code?\n\n正在运行的任务会被中断。请确认已准备好再继续。", - "02eba0f7cc90f759": "安装更新并重启 T3 Code?\n\n正在运行的任务会被中断。请确认已准备好再继续。", "9ed4d8a1531b9631": "此版本不支持自动更新。", "c8c23435e780a60c": "更新不可用", "1af5f9767371ffd7": "检查更新", @@ -3038,8 +3106,8 @@ "6f85f14f35b3f547": "{provider}(经由 {environment})", "7c59a888a062a8bd": "语音输入没有可录入的草稿。", "62450481c00d2ef3": "草稿所在环境不可用,无法整理转写内容。", - "c64cb58d9cecbcd2": "转写文本整理失败", "0674544195fcdc39": "已添加原始转写文本。", + "c64cb58d9cecbcd2": "转写文本整理失败", "296496693cdac0db": "t3 命令不可用。", "efbcef7bc9bbda01": "无法加载 t3 命令状态。", "1bf6910332426e62": "桌面网络访问不可用。", @@ -3282,6 +3350,7 @@ "4d493d0bda4d403d": "请重新添加中断的文件,或将其移除", "c9cad1d84d5f1a32": "请重新添加中断的文件,或将它们移除", "536a820f2ff726da": "请至少选择一个模型。", + "48d6389202ad6754": "就绪后发送", "fbafbe78b5e37966": "继续会话", "bcd7eb979dd38dae": "打开输入框以压缩并发送", "95ee62a0d6968b89": "发送消息", @@ -3459,6 +3528,9 @@ "e778e4f446fdf873": "你的下一条消息将以全新上下文开始", "0e2f2da4f2d94785": "智能体将看不到这个会话里之前的消息。", "e1189d2e582b008d": "保留当前上下文", + "2bb448d605877a22": "编辑或按 Esc 取消", + "1a1f128d70c62304": "{count, plural, other {图片就绪后发送}}", + "5af3ab719a9725fb": "正在发送消息", "461c9f865f2e9b92": "{option} 开启", "f2aa17b5c620f2a4": "{option} 关闭", "f59314a884aae1ff": "默认", @@ -3582,6 +3654,13 @@ "c53bc5a4b0314342": "下一个媒体", "2950b1424a3cddf5": "请重新连接这个环境,然后再打开媒体。", "ef638bf1479a5461": "环境返回了无效的媒体 URL。", + "3ccfbf7e86868c35": "给 T3 团队的反馈", + "4e0710d19dfc2e7e": "将这份报告发送给 T3 团队?", + "87d0ae0723ba75d1": "只有这些内容会从你的机器发送出去。点击“发送”前,不会发送任何内容。", + "bf19826f81484328": "包含对话", + "ddb7e6f8ce99e657": "只有能在这台机器上运行智能体的人,才能发送或拒绝这份报告。", + "03c1eb603c112f47": "不发送", + "653405e4ed498d9f": "发送", "262955d6eb632f9b": "复制访客链接时剪贴板 API 不可用。", "f1a4f2b04cdbb4ef": "无法将访客链接复制到剪贴板。", "cf3490a604e44d31": "无法创建访客链接。", @@ -3602,7 +3681,6 @@ "abd89e9eefedf11b": "完成", "18d166056c1ab6ff": "停止分享", "7a2d510eac9e4587": "访客链接已过期", - "653405e4ed498d9f": "发送", "21888e302219891d": "展开的 {title} 预览", "419719298a7acaea": "缩小", "ed8d5db95359cff4": "重置缩放", @@ -3698,7 +3776,6 @@ "7c1923203049d602": "复制代码", "637817e4ff79c90e": "代码块操作", "ebf3a2b1e314aa5f": "在终端中运行", - "fe219642547fa0bf": "在终端中运行", "122a8512abc51180": "详情", "58c38c65c2783c5d": "完整路径", "f37e7d36b51c5b28": "复制相对路径", @@ -3710,10 +3787,6 @@ "4967584e8d0fb1c2": "预览媒体", "67589dd912eacb7c": "在内置浏览器中打开", "a3c98d4c4b24cecb": "{label} 的文件选项", - "b4fe8a076e9fd2f8": "独立公式", - "085d1407e8c92cce": "行内公式", - "a2ef393fa7b48ae8": "滚动查看独立公式", - "e94685ea5642e088": "滚动查看行内公式", "3a04583c8500e23d": "显示图表", "16d64f650840fe06": "显示代码", "6d329f7d3a50c7e7": "复制表格", @@ -3990,9 +4063,11 @@ "973e99fa86d7f531": "排队消息 {position}/{total},尚未发送", "0f6087c4f53c7f17": "用此消息开始一个轮次 ({shortcut})", "adab89933af02669": "跳过压缩并发送此消息 ({shortcut})", + "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", "3de4016452e8d2bd": "发送到当前轮次 ({shortcut})", "259cc9568148e8ad": "用这条消息开始新一轮", "bb7fddb812d5d29e": "跳过压缩并发送这条消息", + "425ab15036aec8a4": "将此命令移到队列最前面", "a5fe1ee609b29a9f": "发送到当前这一轮", "2b7fd345e4f4fd6e": "取消编辑排队消息", "47f1726bf106d2c8": "编辑排队消息", @@ -5460,6 +5535,22 @@ "f0d79aa56f06663f": "此文件过大,无法完整显示。统计包含全部改动。", "7fdde2b893ba1b9d": "已删除", "e58ce271d835b447": "已添加", + "fb5c7ff5ea76e01a": "Added by esveo's fork. Click to list all of its settings.", + "352fa6aeb5d55665": "Trail the provider icon behind the thread title instead of giving it a line of its own. The line it saves also carried the branch, pull request badge and diff counts.", + "9d44fa03a230e0d8": "Reset two-line thread cards to default", + "7b216eedb1abe696": "Two-line thread cards", + "8d90fcd918e901c8": "Keep each project's threads together in the sidebar, under a header that folds the project away. Ordering stays by recency: the project with the newest thread leads.", + "d5dfd89c9a281386": "重置项目分组为默认值", + "aac9f889c7ec7ff5": "Group sidebar threads by project", + "da375a07c5309184": "Show how full the thread's context window is next to the composer controls.", + "33f6b88cba203990": "Reset context window usage to default", + "6496f57baeded3fa": "Context window usage", + "d9c146dc6b95714d": "Show how many minutes are left before the prompt cache expires. Claude only.", + "69609e27c2107da5": "Reset prompt cache timer to default", + "a4917d2b93c478f6": "Prompt cache timer", + "ea8ebcb77e657e9f": "Open the thread details card with workspace and version control in every thread. Off, it stays closed until you open it, and each thread remembers your choice.", + "662288b90e19635f": "重置会话详情为默认值", + "92729a403d37c575": "Open thread details by default", "07b9970b662ab70d": "显示 Mermaid 源码", "5a422b7be35243f5": "显示渲染后的图表", "c0628ad999cbbbf5": "显示 Markdown 源码", @@ -5567,6 +5658,7 @@ "723d88a5fa7e2fdd": "没有匹配的文件。", "f8d6e9a1a2870a5c": "文件浏览器", "109edd252917113b": "调整文件浏览器宽度", + "7abd6af24fed7b60": "The file does not exist in the workspace or the home folder.", "37cbd2ecc659a007": "文件", "b5188f172f59ca79": "此连接无法读取主机文件。", "c3c5d36466ad2191": "在预览浏览器中打开文件", @@ -5606,7 +5698,6 @@ }, "。请检查链接的路径,或在“文件”中找到该文件。" ], - "b9b6bbd1e1ea189f": "完整文件", "d715e9494fdbaaf6": "无法加载该字体。", "ff17c777a72b4408": "字体预览限制为 10 MB。", "6bd41ad699e22f10": "该字体不可用。", @@ -5616,6 +5707,7 @@ "a9abaaa4220eae21": "{error} 保存后可在其他应用中打开。", "c508c9000d9656f8": "字体预览", "1c416d621d250be8": "敏捷的棕色狐狸跳过了那只懒狗。", + "d7d08260f16b7828": "文件仍在加载中。请稍后重试。", "76ebb03de52c92d6": "文本查看器已停止。", "f48162e8e8c12af7": "无法加载文本查看器。请关闭文件后重试。", "bc4c5b13d38a5da7": "预览已关闭。", @@ -5623,8 +5715,6 @@ "9450d1827ef336a1": "另一个复制操作正在进行。", "8f48999eb6d9e2e3": "{count, plural, other {{formatted} 行}}", "13b14784f8707ddd": "0 字节", - "f6e9581cba3467fa": "正在建立索引…", - "2d1f293ac12463fc": "正在加载文件的其余部分…", "b75105bef8f564a4": "仅显示前 1,024 列。查看源码或保存文件时会保留所有列。", "2a6e1b1f209c3888": "此文件为空。", "192fc79eb3b5b2cb": "此图表包含资源 URL、标记、节点元数据或自定义配置。请显示 Mermaid 源码以安全查看。", @@ -5811,7 +5901,6 @@ "0061fff77e36bd4f": "无法连接到服务器。", "04dfdd46e3dd4a2e": "出了点问题。请重试。", "084bb2d8127a508d": "已发送", - "e7c59185f8ab3987": "未发送", "77c01a15bd36d17c": "此链接已结束或无效", "e0e736810f3cbef2": "请向所有者索取新链接。每个链接只能在一个浏览器中使用。", "c3c53aa46f7330e5": "此链接已结束", @@ -5833,6 +5922,13 @@ "cbb2129c0dd4f40b": "每条消息的附件总大小不能超过 10 MB。", "03b9cd79cfe0b435": "无法附加此文件。图片必须是 PNG、JPEG、GIF 或 WebP 格式。", "8ff29c78798e6ac1": "无法加载此项。", + "535923000a0f3e3b": "Send /compact to a large, idle Claude thread shortly before its 1-hour prompt cache expires, so the next message skips caching the whole conversation again. 5-minute caches are left alone.", + "bd8eb8f5f9843bc6": "Reset idle auto-compact to default", + "1db274eacf03c8de": "Auto-compact idle Claude threads", + "fb6643c75aafd996": "Between {min} and {max}; it has to fall inside the cache's hour.", + "48dee64ca7904281": "Minutes idle before auto-compact", + "8937fe924464eb70": "Smaller threads are cheap to cache again and keep their full history.", + "1981f1e1a753aabc": "Minimum context tokens for auto-compact", "94ab4591ce101233": "无法发布评论", "92d0d4eab2596772": "跟踪器拒绝了操作。", "33591d9596fb7cb7": "添加评论", @@ -8711,12 +8807,16 @@ "58e0e226493150e7": "无法加载 issue 跟踪器", "77cfcbde543df32d": "切换 {tracker} 详情", "0083f65885c60156": "断开 {tracker} 连接", - "295392927d5c8a84": "为每个项目选择一个或多个 {tracker} {scope}。它们的 issue 会列在仓库自身的 issue 旁,智能体会在第一个中创建新 issue。", + "ed83b25c71c98a20": "为每个项目选择一个或多个 {tracker} {scope}。它们的 issue 会列在仓库自身的 issue 旁;除非另有指定,智能体会在第一个中创建新 issue。", "19c2d5e81ff8f89a": "{project} 的 {tracker} {scope}", "68e061510b765772": "未绑定", + "99d51127f573296b": "其他账号", + "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。", + "99963c0142e17f00": "用于新的 {tracker} 账号。", "a2d95d39d3398bda": "凭据被拒绝", "9eae463720500113": "存储在服务器上。", "b6e27ab2537ef874": "创建一个", + "6d8e4ebc889bace9": "添加账号", "13ef526271b0f5d4": "清除所有条件", "d1938a629f039515": "移除条件", "84a605b241ce65b7": "移除条件组及其条件", @@ -8846,6 +8946,12 @@ "d3866ead082d14e5": "添加快捷键", "d4345c90894a3220": "打开 keybindings.json", "e56a8d51219efaa0": "没有匹配的快捷键。", + "90a258fff61fd77e": "关闭", + "4060244a7079a0d2": "当我要求时", + "e88c9d8769544731": "自动", + "f29d1dade4dde8aa": "智能体不会向 T3 团队发送反馈。", + "93c4c53562d30a98": "当你要求时,智能体会向你展示一份关于 T3 Code 的简短报告,经你批准后发送给 T3 团队。", + "cd9ee803e8727017": "智能体还会主动报告自己遇到的 T3 Code 问题,例如 T3 工具运行失败。", "45fa271ea0e1ac8e": "测试版", "3a678332fc7142f7": "将侧边栏会话按项目文件夹分组。置顶会话保留在顶部,已暂缓和已收尾会话显示在文件夹下方。", "e4e91d155cb6a9b4": "简洁侧边栏(按项目分组)", @@ -8854,11 +8960,16 @@ "9ae293971d93c819": "与访客共享会话,访客可在浏览器中实时查看,并发送需要你批准的消息。登录 T3 Connect 后即可使用访客链接。", "0aa5406ac4d7f7c7": "访客链接", "f0e853acd2006d53": "关联环境", + "ef10c2dff987f3ea": "从此服务器 T3 主目录下 workflows 文件夹中的文件运行多步骤工作流。可从命令面板打开。关闭期间,该文件夹中的内容都不会运行;运行会等到重新开启后继续。", + "2dadb2359422121c": "工作流", "13e86eb5d8287a71": "Claude 或 Codex 完成一轮回复后,在空输入框中预测下一条消息。按 Tab 使用它。每次预测都会在你的套餐上产生一次额外的缓存请求。需要 Codex 0.165+。Claude 会话在重启后更新。", "d4b2a2ec812aafb0": "建议下一条提示词", "298c7150a7621c80": "Simlock 设备主机", "67937aa49179285e": "在 Mac 上,从缓存在 T3 主目录中的工作副本克隆新的工作树,无需逐个写入每个文件。无法使用时改为 Git 的常规检出。关闭后会删除缓存。", "f9904f78d3003f58": "快速创建工作树", + "9c2f647882522302": "所选机器使用的智能体反馈模式不同。", + "31bbf7bf8c0a5279": "智能体反馈", + "d52b3d6bf9f2a013": "各不相同", "ec7623deed751c05": [ "与访客共享会话,访客可在浏览器中实时观看并发送需经你批准的消息。需要 T3 Connect:请登录并在", " ", @@ -8942,7 +9053,9 @@ "fb71127e5746a6bc": "从远端“共享与访问”页面或 t3 pair 获取", "1e3fee7084791773": "同时将 {target} 反向关联到 {source}", "ea34a190b0bd804c": "之后 {target} 上的智能体也能在 {source} 上工作。", - "ad5ed0ce61b966eb": "忘记 {label}?此处的智能体将停止在那里工作。在 {label} 的“共享与访问”中撤销“T3 Code · …”,以同时结束那里的连接。", + "974f8c65e8b5f492": "忘记 {label}?此处的代理将不再在那里工作;如果 {label} 有响应,它们在那里的会话也会结束。", + "6cf9e3083b15614f": "{label} 没有响应", + "34ccbdf619b83be3": "在 {label} 的“共享与访问”中撤销“T3 Code · …”,以同时结束那里的连接。", "81c9796bf61b306a": "无法移除关联", "130e51beb6cf5aad": "关联环境", "122c3e355699e69d": "这里的智能体随后就能在该环境中启动会话、发送消息并等待结果。此连接将显示在该环境“共享与访问”的“已授权客户端”中,可在那里撤销。", @@ -9172,7 +9285,6 @@ "0b4779a1825c85bc": "此项目组在侧边栏和会话列表中共用的名称。", "f68cbda4df83d739": "重置项目名称为默认值", "56e37b85027e8431": "项目图标", - "e88c9d8769544731": "自动", "c99736317da5b1fa": "重置项目图标为默认值", "6afaa3e3739dc570": "选择项目图标", "51651ce45d481a20": "选择项目图标文件", @@ -10080,7 +10192,6 @@ "53de7aafe0afc10d": "无法恢复主题设置", "006bfa1846fe5dd2": "自动收尾前的闲置天数", "d9b0fbd680d5f175": "侧边栏", - "d5dfd89c9a281386": "重置项目分组为默认值", "cd5452cc9e13c818": "项目分组", "cfb01b8a2a3361fb": "重置项目排序为默认值", "26abcbe322049a8a": "重置“运行中”分区为默认值", @@ -10145,7 +10256,6 @@ "16bdc70b858c223f": "重置主动面板为默认值", "c5424f09d77138ff": "空闲且超过 200,000 token 的 Claude 会话何时压缩:在你回来后、提示缓存即将过期前,或从不压缩。每个 Claude 提供方都可以单独覆盖此设置。", "3e99c5c14f4939c8": "重置压缩空闲会话为默认值", - "d52b3d6bf9f2a013": "各不相同", "cd72fe451ba0d6aa": "新项目", "394c3bd0a1782c8e": "留空时,“添加项目”浏览器从“~/”打开。", "f9b912a818bd869d": "重置添加项目基础目录为默认值", @@ -11053,7 +11163,6 @@ "4a237f41ce592b7f": "保留此项目的工作树,直到你手动删除。", "00b8ffd8ea6e6a93": "此项目使用以下规则。", "72c279824d15a999": "使用各机器的工作树清理设置。", - "90a258fff61fd77e": "关闭", "b5702d0b64866b08": "自定义", "c009c901f3eefe78": "删除会话时删除工作树", "431c7cd6d50102b7": "删除活跃或已归档会话时,移除不再使用的工作树。保留有本地改动的工作树。", @@ -11410,7 +11519,6 @@ "f2043e87a10cb831": "编辑主题", "595bdeefcdc9bf31": "导出主题文件", "b480281b3791b685": "选择会话详情卡片显示的内容,也可以右键点击卡片来设置。", - "662288b90e19635f": "重置会话详情为默认值", "871d059d88548434": "会话详情:已启用 {enabled}/{total} 项", "cec1fbb8b4c9180d": [ "已开启 ", @@ -11752,7 +11860,6 @@ "4c70e3e7b3e6c493": "凭据", "79b768229c9ef672": "维护", "54b188d65247e42f": "实验功能", - "f41ea186c275b56e": "关于", "af4b7734da1d5ce7": "语音", "4ec62c39ca3192bf": "版本控制与 issue", "f2bf529f85e05494": "共享与访问", @@ -11781,11 +11888,17 @@ "8f5966eebd2b110f": "外观 颜色 调色板 自定义 导入", "633ed64e952cca3b": "颜色 边框 界面", "9cf8308531b4ff31": "透明 透明度 实色 菜单 对话框 输入框", + "d99bfbc557fae743": "Notion", + "89df56091835b3a6": "notion integration secret pages links viewer connect token ntn", + "d699adcc04d4d4ab": "sidebar compact row height branch provider icon diff pull request", + "9b9df5ba41c4a8e2": "Group threads by project", + "0ed2eab2c1953531": "sidebar project folder runs grouping collapse header repository", "d8d6cfd630cff22d": "红 绿 蓝 橙 新增 删除 更改 计数 调色板 色盲", "717e49895cfee1c7": "宽 全宽 列 布局 消息 输入框 显示器", "88365077fd80787b": "自定义 显示 隐藏 面板 卡片 环境 编辑器 脚本 分支 PR git 更改 服务器 自动化 谱系 用量 限制 5 小时 每周 配额 token 上下文窗口", "d561f74efa5f3920": "推理强度 思考 条形 图表 文字 标签 级别 输入框", "6113c17109ee0d57": "latex tex katex 方程 公式 markdown", + "dfe7ead48efc3f5a": "thread details card panel workspace version control closed collapsed hide", "8c8364d44fa28d22": "dev nightly latest 渠道 插图 胶囊 标签 隐藏 无", "2d90635156dfcb5a": "排版 字体 字号 系统 无衬线", "d32e93777e4819c8": "排版 字体 字号 输入框 输入", @@ -11807,6 +11920,7 @@ "d443390c4d2dcfd4": "无障碍 a11y 屏幕阅读器 nvda jaws voiceover orca 讲述人 窗口标题 标签页标题 alt tab 任务栏 会话状态 顺序 运行中 批准", "6826fa9579c22035": "测试版 共享 访客 邀请 链接 队友 观看 t3 connect 隧道", "f10c06cba0cdf7fe": "测试版 关联 另一台机器 vps 对等 智能体 在那里工作 委派", + "bc0b409d89ce086e": "测试版 工作流 workflow 持久 运行 自动化 步骤 计划 webhook 文件夹", "4a21cf825a2045b0": "测试版 tab 自动补全 预测 下一条消息 claude codex 幽灵文本", "fea2dc36585c4a20": "Simlock 设备主机(早期测试)", "9d834d178130180e": "测试版 alpha simlock callstack 模拟器 ios android 池 租用 网关", @@ -11848,7 +11962,29 @@ "34d74827c2a8b009": "enter 回车 command ctrl 多行 提示词 换行 输入框", "9d1013084c46ecce": "排队 引导 运行中 轮次 发送 默认行为 输入框", "e5e7f5e1fb1f2e4c": "子智能体 侧聊 关联会话 单击 右侧面板 侧边面板 主视图 command ctrl 中键单击", + "5c59d7e2673267ea": "composer tokens usage meter percentage compaction", + "e0d6ec10218b714e": "composer claude cache ttl expire minutes warm cold tokens", + "ce0952668aba4140": "Agent stage", + "f637899f994b78c3": "sprites stations subagents thinking editing terminal right panel everything", + "9d9d3374ee961b91": "Easter eggs", + "571180dbfeddbfd5": "surprise fun rocket animation message send hidden", + "0716adb0d55ffa58": "Voice calls", + "027d8f5ea5555973": "voice call phone gpt live feature flag anruf telefon schalter", + "60d509bb55e2967c": "Voice call voice", + "0e5f5c5ebf026abd": "voice call phone gpt live speaker stimme anruf telefon", + "266f1e2b55e419b0": "Voice call follow-up", + "392226d9bed6fe21": "voice call queue steer follow-up warteschlange anruf", "5b8b854de7ee6f4d": "已安装 cli 版本 更新 可用 codex claude cursor grok fx kiro opencode", + "1ceaab7d898b689a": "Child threads in the sidebar", + "fa5a42a73d1c1ece": "coordinator subthreads nested group expand sidebar orchestration children", + "6a1072050d1ad19e": "Coordinator decisions", + "474ba8e025886f86": "inbox questions answers decide approve coordinator open items", + "8f5558f063214509": "Cross-project threads", + "b809e3ffa5178b88": "agents coordinator other projects read message start threads repositories", + "44207b47d209f601": "compact context prompt cache idle claude tokens cost expire", + "396a2cc5b442e359": "compact idle minutes prompt cache ttl", + "6d9520a9cbd70c2f": "Minimum context for auto-compact", + "2fe046cc1e0d0d4a": "compact context tokens threshold size", "64f12530d55d2ad1": "恢复 运行中 活跃 中断 工作 重启 重新启动 机器 崩溃 桌面 更新 自动", "214a98497c4ed05d": "caffeinate 睡眠 阻止 保持唤醒 电源 笔记本 盖子 抑制", "00469926c7027e2d": "平衡 性能 省电 高级 git 获取 提供方 健康 刷新 主机 电源 监控 空闲 策略", @@ -11878,6 +12014,7 @@ "901a823214edc8c4": "遥测 分析 用量数据 跟踪 法律 退出", "82136480255a5106": "OTel OTLP 遥测 导出 端点 日志 追踪 指标 Grafana", "659d081051faf7ff": "日志 追踪 进程 资源历史 失败 span cpu 内存", + "5eaeacfa9f82051a": "报告 错误 问题 t3 团队 发送 反馈 智能体 工具 自动 当我要求时", "f537f91e1ee41d47": "键盘 快捷键 热键 命令 绑定 json", "1ba01e7ceed64b95": "窗口 捕获 截图", "279b1cceb779ff38": "包含应用文本", @@ -12084,6 +12221,8 @@ }, " 中的更改" ], + "643c4b50feadc874": "Worktree: {path} ({branch})", + "fb7c44da0f0825ea": "Worktree: {path}", "e7f35f60e6229cf5": "桌面应用", "77be1b7e2a1d3d31": "{count, plural, other {更新 {count} 台机器?}}", "e4892b21e88abb60": "{count, plural, other {{count} 个提供方更新}}", @@ -12147,6 +12286,25 @@ "ffaa75d2db1e7cc1": "更新未生效", "626bcbe04dc55f93": "T3 Code 仍为 {current}。请通过更新按钮重新安装 {version}。", "49214c047fbb1606": "提供方更新已中断", + "a135af0f1efda8de": "Cross-project", + "6e9798372b3fb922": "Coordinators put the questions they need you to decide into an Inbox tab beside the chat, instead of numbering them in their messages. Running sessions pick up a change.", + "7a5292a1705defec": "Reset coordinator decisions to default", + "9e3ff0f05f52b724": "Let agents read, message and start threads in other projects of this environment. Running sessions pick up a change.", + "384695cdd7ab6b54": "Reset cross-project threads to default", + "5a6c243a03eeca0c": "Choose a coordinator", + "f527bb5b4ad333da": "Coordinator for \"{title}\"…", + "6beb2db2a7b5edae": "Could not assign the thread", + "4ebb0c90c45690c0": "Could not detach the thread", + "73ac4f532306bea6": [ + "Assign \"", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "\" to a coordinator" + ], + "1871eb35b1ca5d41": "No thread can coordinate this one.", "52adbc863aeb5e59": "复制失败", "0944728904d886d2": "{label} 饱和度与亮度", "dded2cb4e4d26338": "{label} 饱和度", @@ -12348,7 +12506,6 @@ "0bd41ff995d36a66": "缓存读取", "3f0dfe0cb15a3272": "缓存写入", "1c9d860be42b1c02": "输出", - "78344b60f407928e": "其他", "684e516076de81fe": "标准", "3bbcc1b826fef537": "快速", "66796576034c18ea": "极速", @@ -12364,6 +12521,263 @@ "2cddd6095abc734a": "7 天", "53493056306708cf": "30 天", "c719359d18d37ad3": "90 天", + "a7ad3167ca62e7de": "Talk to your agents by voice with GPT-Live on your Codex ChatGPT login. Turning this off ends a running call.", + "9f0e45a1d67187cd": "Reset voice calls to default", + "da0ae8174ac2fc14": "Queue what you say in a voice call while the agent runs, or steer the current run. Saying otherwise overrides it for one message. A change applies from the next call.", + "fb0a2aa3b08a17c4": "Reset voice call follow-up to default", + "66936cae56d1d749": "Queue", + "89bf6f658c44cb1b": "Steer", + "930a28582d2c103f": "The voice that talks to you in a voice call. A change applies from the next call.", + "591a53f319b0d343": "Reset voice call voice to default", + "0bd950151ddc6407": "不保存就离开?对此文件的更改将丢失。", + "c0ba3f6756b09f30": "未保存的更改", + "6914e22d357f0ad6": "已保存并生效", + "aff389354a031d6f": "磁盘上的文件无法加载。上一个可加载的版本会继续运行。", + "858effde748ab563": "已保存,但尚未运行。", + "ddb37138df660942": "未保存。服务器上没有任何更改。", + "6ef4db489e40e39e": "无法保存", + "c89624a2e9af1793": "{name} 未连接", + "b5a352a43adb4c17": "重新连接后,它的工作流会再次显示。选择其他环境可查看其运行。", + "3dcedb736d20aae5": "无法读取工作流文件", + "b09f4df8d76ae8ea": "要删除 {file} 吗?它定义的工作流将无法再启动。", + "b4535f5a03689d27": "{name} 未连接。你在这里写的内容会保留,重新连接后即可保存。", + "b54c78d85fd942ea": "已删除,但正在运行的内容尚未更新。", + "407c228d7da0b7df": "未删除。服务器上没有任何更改。", + "1a6aa10f3cc14fff": "这些文件彼此不匹配。之前的版本会继续运行。", + "259312516a1dbe6f": "文件名", + "2f48ab2aa0586853": "未定义任何工作流", + "ba5adfa37b55b8c5": [ + "第 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 行:" + ], + "d94eb9ab3201b641": "删除", + "84c900d1ae72adc6": "保存", + "5912d817be03247a": "编辑期间磁盘上的文件发生了变化。保存会覆盖该变化。", + "0b1e6f5608826387": "加载该文件并放弃我的更改", + "f47b4c06aeb77c1c": "正在加载工作流文件…", + "4353bfd401d58f87": [ + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "中的每个文件都定义工作流。修改后无需重启即可生效。" + ], + "0c165251a06f10f1": "新建文件", + "8e97cf734b4463e7": "创建", + "2ec0d5108fd6cebe": "还没有工作流。在这里创建第一个文件,或让智能体在该文件夹中编写一个。", + "5601350626e8cfe9": "无法加载", + "21d778a1b9a0c234": "在运行旁打开的内容", + "62dc4d3a19ff7ca0": "关闭标签页", + "1e25265f2758fce3": "作为完整会话打开", + "672a3dae06b39402": "在单独的页面打开", + "7755500a4cde5066": "关闭面板", + "b8dcbc93a2ca1861": "此运行不再列出它。", + "115c69de3202f664": "打开", + "644eafa9048b62df": "{count, plural, =1 {第 1 次尝试} =2 {第 2 次尝试} =3 {第 3 次尝试} other {第 {count} 次尝试}}", + "e39f89c909df4db0": "无法继续此运行", + "865f034346b82f47": "要取消 {title} 吗?其智能体将停止,且此运行无法再继续。", + "6bc75632fd9c9136": "无法取消此运行", + "64e50329dcfdd5b0": "已完成", + "350162e7cc1ebea4": "已停止", + "0875cf506f4c6810": "已跳过", + "3cc43f1dbf3f8e0c": "已取消", + "ded70e75de6404ba": "返回运行列表", + "2f4ed7dbd22be30d": "取消运行", + "614e5ad58a795fb5": "停止", + "04b050b0329f0ac8": "用时 {duration}", + "aff78e1774818ff4": "已用时 {duration}", + "38eddd466439afc9": "此运行涉及的内容", + "156ec271d49ddd70": "经过", + "34f59bbbead0b97f": "{names} 等另外 {count} 个", + "ac1556f6ce89a5ea": "{count} 个并行", + "e197c4963bacc746": "{count} 个运行中", + "f5319ed9e18c0df1": "向你提问", + "882a25e9084ae1b2": "已暂停", + "9a03d8a9afc60387": "目前的步骤", + "2f2ae791afe01674": "等待你的批准", + "24f8060c4ccdf928": "正在启动", + "30a5be40eb956663": "工作中", + "dd7a1e58c2553933": "{duration} 后唤醒", + "95cc952724dd7310": "即将唤醒", + "3cc34921c0128593": "运行中", + "e777db2880f53a46": "无人回答", + "dc90739d391a5e67": "你的回答:{choice}", + "389f2563b5b763fd": "快速步骤", + "a41c8d758121ad81": "已休眠", + "9db248b770096984": "已等待", + "c76124517af28686": "已运行 {duration}", + "89102905bf09b0e8": "实时查看", + "bdf338cdff4118f0": "对话记录", + "811e7e992f9ff820": "需重新注册其工作流版本后才能继续", + "4d4cdf035e98dd57": "等你手动继续", + "eb5b21dd224a5941": "{duration} 后自动重试", + "6ab3dfa749fde477": "即将自动重试", + "44b6463aa70aa14c": "暂停原因", + "cf25e7169ab0eb7a": "暂停于 {step}", + "56c48c1f220f2754": "无法回答此问题", + "a3c43735e1a81498": "{title} 的理由", + "bfad234f016cfa3f": "用一句话说明理由。无论你选哪个回答,它都会一并附上。", + "004c41aff9c97873": "运行", + "4dc0c244a2419f6c": [ + "属于 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "开始" + ], + "8bffb377e2a6a7de": "其版本已不再注册", + "f92d9132f7b85d1a": "正在加载步骤…", + "6ebc59f64c761a49": "暂无内容。", + "a759dccd157d7dae": [ + "你的回答:", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + } + ], + "593b425188346781": [ + "你的回答:", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ":", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "打开运行", + "c8eb9be36d4d51ad": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 上的会话" + ], + "3d9761e81798fcd8": "继续", + "8cebd63fc4c967d5": "只会重新运行失败的步骤;此前已完成的内容会保留。", + "bc1e0a2a0f1e9552": "等你处理", + "a812f51e970740f1": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "提问", + " ", + "· 运行正在等你回答" + ], + "02dfe6c63fd0b8a1": "添加理由", + "19abd94828a3bdbc": "先问问智能体", + "a18721fa8f328361": "等你处理", + "bbf24e7920c1e86b": "运行中", + "8d6e18d2ad832db6": "全部", + "f25af5332ffc3734": "没有等你处理的内容。", + "c3f0119b8d6231f8": "没有正在运行的内容。", + "33028dfc1229eaa6": "还没有运行。", + "5459bf696a187c26": "无法加载工作流运行", + "d57c35d43b0f163a": "此运行不在这里", + "b9aae2f7cdb1a379": "还没有工作流运行", + "8f15f66e545af7c0": "显示哪些运行", + "b6409289e0c9a4dd": "工作流", + "035cb02ca1ae4952": "全部 {count} 个工作流", + "46d614fa7b4bf1e5": "工作流运行", + "1c635faa2fb45b8b": "尚未运行过。", + "156ff7b625287a1e": "隐藏已跳过", + "69b985b97ab45e6b": "显示 {count} 个已跳过", + "2400254d362de84d": "正在加载工作流运行…", + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "有工作流文件存在问题。" + }, + "上一个可加载的版本会继续运行。" + ], + "ed8ce6ebc73dc12d": "打开文件", + "145e1f7503ba3b2c": [ + "此环境中没有该链接对应的运行。", + " ", + { + "t": "button", + "i": 1, + "c": "返回运行列表" + } + ], + "783e616cb0476c17": [ + "工作流将智能体、代码、定时计划和向你提出的问题串联成一次重启后仍会继续的运行。可在", + " ", + { + "t": "button", + "i": 1, + "c": "定义" + }, + " ", + "中编写,或让智能体代写。", + " ", + { + "t": "a", + "i": 2, + "c": "阅读指南" + } + ], + "5d8d278ff828102d": "全部工作流", + "39459da07479f482": "智能体", + "7741243632056b81": "{step} · 记录", + "c512071143a5ba32": "此会话已不存在。", + "ed169d23683fb6ac": "正在加载会话…", + "290e0ab40b87dc17": "工作流面包屑导航", + "683dd9831e54edc0": "环境", + "34ad53646f06ed80": "工作流已关闭", + "8f6589c9e0ac5d4e": "未连接任何环境", + "744127f8dfad7d22": "连接一个环境以查看其工作流运行。", + "036182ec7e2ee4d4": "运行旁", + "2d6107cb78382d08": "工作流", + "16f7df687349b399": "定义", + "f0a212aadfe1257b": "正在加载编辑器…", + "20f194e003885e95": [ + "在此服务器的", + " ", + { + "t": "Link", + "i": 1, + "c": "设置 → Labs" + }, + " 中开启。" + ], "8367779e149f723b": "主环境请求在 {operation} 期间失败(HTTP {status})。", "c5cd027743a2b5a6": "配对 token 无效。请检查后重试。", "0e4b49c8203aae81": "引导完成后等待登录状态超时。", diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 4ba107059f2b7..15380512f4060 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -231,6 +231,10 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil --animate-stash-pulse-row: stash-pulse-row 1400ms; --animate-stash-pulse-row-alt: stash-pulse-row-alt 1400ms; --animate-stash-pulse-count: stash-pulse-count 1400ms step-start; + /* One-off arrivals in a workflow run's timeline; nothing here loops. */ + --animate-step-in: step-in 180ms ease-out; + --animate-step-ping: step-ping 520ms ease-out; + --animate-check-draw: check-draw 200ms ease-out; --color-warning-foreground: var(--warning-foreground); --color-warning: var(--warning); --color-warning-surface: var(--warning-surface); @@ -345,6 +349,27 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil opacity: 1; } } + @keyframes step-in { + from { + opacity: 0; + translate: 0 4px; + } + } + @keyframes step-ping { + from { + opacity: 0.55; + scale: 0.7; + } + to { + opacity: 0; + scale: 1.45; + } + } + @keyframes check-draw { + from { + stroke-dashoffset: 12; + } + } @keyframes status-ping { /* Burst first (immediate feedback for click ripples), then hold invisible for the rest of the cycle. Mirrors animate-ping's @@ -1887,10 +1912,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 +2333,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/composerContextRecords.ts b/apps/web/src/lib/composerContextRecords.ts index 31b7239719f1a..6f1c9d3bb8227 100644 --- a/apps/web/src/lib/composerContextRecords.ts +++ b/apps/web/src/lib/composerContextRecords.ts @@ -9,6 +9,8 @@ import { COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS, } from "@t3tools/contracts"; import type { + ChatFileAttachment, + ChatImageAttachment, ComposerContextId, ComposerContextRecord, EnvironmentContextRecord, @@ -488,39 +490,59 @@ export function fileContextReference(file: ComposerFileAttachment): ComposerCont }; } +export type ComposerContextAttachment = + | ComposerImageAttachment + | ComposerFileAttachment + | (Omit & { + readonly file: File | null; + readonly uploadedAttachmentId?: string | undefined; + }) + | ChatImageAttachment + | ChatFileAttachment; + export interface BoundComposerAttachment { - attachment: ComposerImageAttachment | ComposerFileAttachment; + attachment: ComposerContextAttachment; attachmentId: string; + contextId?: ComposerContextId | undefined; } /** Returns null until the attachment has a server id. */ export function uploadedAttachmentContextRecord( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: ComposerContextAttachment, upload: AttachmentUploadState | undefined, + contextId?: ComposerContextId, ): ImageContextRecord | FileContextRecord | null { const attachmentId = - attachment.type === "file" && attachment.uploadedAttachmentId !== undefined + "uploadedAttachmentId" in attachment && attachment.uploadedAttachmentId !== undefined ? attachment.uploadedAttachmentId : upload?.status === "ready" ? upload.attachmentId : undefined; - return attachmentId === undefined ? null : attachmentContextRecord({ attachment, attachmentId }); + return attachmentId === undefined + ? null + : attachmentContextRecord({ attachment, attachmentId, contextId }); } export function attachmentContextRecord( bound: BoundComposerAttachment, ): ImageContextRecord | FileContextRecord { - const { attachment, attachmentId } = bound; + const { attachment, attachmentId, contextId } = bound; const base = { version: 1 as const, - contextId: toKindScopedComposerContextId(attachment.type, attachment.id), + contextId: contextId ?? toKindScopedComposerContextId(attachment.type, attachment.id), label: sanitizeComposerContextLabel(attachment.name, attachment.type), attachmentId, name: attachment.name, mimeType: attachment.mimeType, sizeBytes: attachment.sizeBytes, }; - return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" }; + return attachment.type === "image" + ? { + ...base, + kind: "image", + ...(attachment.source !== undefined ? { source: attachment.source } : {}), + } + : { ...base, kind: "file" }; } export function buildMessageContext(input: { 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/preserveReadingPosition.ts b/apps/web/src/lib/preserveReadingPosition.ts new file mode 100644 index 0000000000000..2c6f576519911 --- /dev/null +++ b/apps/web/src/lib/preserveReadingPosition.ts @@ -0,0 +1,115 @@ +import { observeResize } from "./observeResize"; + +/** Native anchoring keeps a paragraph's start fixed, losing the visible line in a long paragraph. */ +export function preserveReadingPosition( + scroller: HTMLElement, + enabled: () => boolean = () => true, +): () => void { + let width = scroller.clientWidth; + let anchor: { range: Range; top: number } | null = null; + let frame: number | null = null; + + const capture = () => { + if (frame !== null || scroller.clientWidth !== width) return; + anchor = null; + if (!enabled() || scroller.scrollTop === 0) return; + const box = scroller.getBoundingClientRect(); + const selection = + scroller.isContentEditable && document.activeElement === scroller + ? document.getSelection() + : null; + if (selection?.isCollapsed && selection.rangeCount > 0) { + const range = selection.getRangeAt(0).cloneRange(); + const rect = range.getBoundingClientRect(); + if ( + scroller.contains(range.startContainer) && + rect.top >= box.top && + rect.bottom <= box.bottom + ) { + anchor = { range, top: rect.top - box.top }; + return; + } + } + // A point near the top captures text rather than the paragraph's bounding box. + const x = box.left + box.width / 2; + // The first point can land in paragraph spacing. Look only within the first few lines. + for (let inset = Math.min(24, box.height / 2); inset < Math.min(64, box.height); inset += 8) { + const y = box.top + inset; + const position = document.caretPositionFromPoint?.(x, y); + const range = document.createRange(); + if (position) { + range.setStart(position.offsetNode, position.offset); + } else { + const fallback = document.caretRangeFromPoint?.(x, y); + if (!fallback) continue; + range.setStart(fallback.startContainer, fallback.startOffset); + } + range.collapse(true); + if ( + !scroller.contains(range.startContainer) || + range.startContainer.nodeType !== Node.TEXT_NODE + ) + continue; + const top = range.getBoundingClientRect().top - box.top; + if (top >= 0 && top < scroller.clientHeight) { + anchor = { range, top }; + break; + } + } + }; + const restore = () => { + if ( + !enabled() || + !anchor || + anchor.range.startContainer.nodeType !== Node.TEXT_NODE || + !scroller.contains(anchor.range.startContainer) + ) + return; + const delta = + anchor.range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - anchor.top; + if (Math.abs(delta) > 0.5) scroller.scrollTop += delta; + }; + const stop = observeResize(scroller, () => { + const nextWidth = scroller.clientWidth; + if (nextWidth === width) { + capture(); + return; + } + width = nextWidth; + restore(); + if (frame !== null) cancelAnimationFrame(frame); + // Virtualized rows can finish measuring in the next frame. Keep the same text anchor then. + frame = requestAnimationFrame(() => { + restore(); + frame = null; + capture(); + }); + }); + scroller.addEventListener("scroll", capture, { passive: true }); + scroller.addEventListener("input", capture); + const captureSelection = () => { + if (document.activeElement === scroller) capture(); + }; + if (scroller.isContentEditable) document.addEventListener("selectionchange", captureSelection); + const interrupt = () => { + if (frame !== null) cancelAnimationFrame(frame); + anchor = null; + // Scrolling wins over a pending resize correction; the next frame captures the reader's new place. + frame = requestAnimationFrame(() => { + frame = null; + width = scroller.clientWidth; + capture(); + }); + }; + scroller.addEventListener("wheel", interrupt, { passive: true }); + scroller.addEventListener("touchmove", interrupt, { passive: true }); + return () => { + stop(); + if (frame !== null) cancelAnimationFrame(frame); + scroller.removeEventListener("scroll", capture); + scroller.removeEventListener("input", capture); + document.removeEventListener("selectionchange", captureSelection); + scroller.removeEventListener("wheel", interrupt); + scroller.removeEventListener("touchmove", interrupt); + }; +} diff --git a/apps/web/src/lib/resourceTelemetryState.browser.test.tsx b/apps/web/src/lib/resourceTelemetryState.browser.test.tsx index 981beeafdfd38..f93c53aff89fd 100644 --- a/apps/web/src/lib/resourceTelemetryState.browser.test.tsx +++ b/apps/web/src/lib/resourceTelemetryState.browser.test.tsx @@ -173,6 +173,7 @@ function setup({ retryFails = false, holdRetry = false } = {}) { const registry = AtomRegistry.make(); return { registry, + snapshot, historyQueries, historyReads, releaseRetry, @@ -265,4 +266,48 @@ describe("resource monitor retry", () => { await expect.element(screen.getByText(startError, { exact: true })).toBeVisible(); await expect.element(screen.getByText(historyError, { exact: true })).toBeVisible(); }); + + it("stops showing refresh as pending after the first live snapshot arrives", async () => { + using fixture = setup(); + const liveTelemetry = Atom.make< + AsyncResult.AsyncResult + >(AsyncResult.initial(true)).pipe(Atom.keepAlive); + monitor.telemetry.mockImplementation(() => liveTelemetry); + + await using screen = await render( + + + , + ); + const refreshButton = screen.getByRole("button", { name: "Refresh resource telemetry" }); + await expect.element(refreshButton).toBeDisabled(); + + await act(() => { + fixture.registry.set( + liveTelemetry, + AsyncResult.waiting(AsyncResult.success(fixture.snapshot)), + ); + }); + await expect.element(refreshButton).toBeEnabled(); + }); + + it("stops showing refresh as pending after a live subscription error", async () => { + using fixture = setup(); + const liveTelemetry = Atom.make< + AsyncResult.AsyncResult + >(AsyncResult.waiting(AsyncResult.fail(new MonitorError({ message: startError })))).pipe( + Atom.keepAlive, + ); + monitor.telemetry.mockImplementation(() => liveTelemetry); + + await using screen = await render( + + + , + ); + await expect.element(screen.getByText(startError, { exact: true })).toBeVisible(); + await expect + .element(screen.getByRole("button", { name: "Refresh resource telemetry" })) + .toBeEnabled(); + }); }); diff --git a/apps/web/src/lib/resourceTelemetryState.ts b/apps/web/src/lib/resourceTelemetryState.ts index 5105195d41e28..1fe63398c95b7 100644 --- a/apps/web/src/lib/resourceTelemetryState.ts +++ b/apps/web/src/lib/resourceTelemetryState.ts @@ -60,7 +60,9 @@ export function useResourceTelemetry( return result.value.snapshot; }; - return { ...query, retry }; + // The live subscription keeps waiting for updates after its first snapshot. + const isPending = query.isPending && query.data === null && query.error === null; + return { ...query, isPending, retry }; } export function useResourceTelemetryHistory( 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/lib/t3ProjectFileDefaults.ts b/apps/web/src/lib/t3ProjectFileDefaults.ts index b5000b4ddd92f..a780a1d906cdb 100644 --- a/apps/web/src/lib/t3ProjectFileDefaults.ts +++ b/apps/web/src/lib/t3ProjectFileDefaults.ts @@ -1,6 +1,12 @@ -import { T3_PROJECT_FILE_NAME, type EnvironmentId, type T3ProjectFile } from "@t3tools/contracts"; +import { + T3_PROJECT_FILE_NAME, + type EnvironmentId, + type ProjectReadFileResult, + type T3ProjectFile, +} from "@t3tools/contracts"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime"; +import { AsyncResult } from "effect/reactivity"; import { getProjectFileQueryAtom, @@ -8,6 +14,21 @@ import { } from "~/components/files/projectFilesQueryState"; import { appAtomRegistry } from "~/rpc/atomRegistry"; +function toT3ProjectFile( + environmentId: EnvironmentId, + workspaceRoot: string, + result: ProjectReadFileResult | null, +): T3ProjectFile | null { + const data = resolveProjectFileQueryData( + environmentId, + workspaceRoot, + T3_PROJECT_FILE_NAME, + result, + ); + if (data === null || data.exists === false || data.truncated) return null; + return parseT3ProjectFile(data.contents); +} + export async function readT3ProjectFile( environmentId: EnvironmentId, workspaceRoot: string, @@ -17,12 +38,22 @@ export async function readT3ProjectFile( getProjectFileQueryAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME), { reportDefect: false, reportFailure: false }, ); - const data = resolveProjectFileQueryData( + return toT3ProjectFile( environmentId, workspaceRoot, - T3_PROJECT_FILE_NAME, result._tag === "Success" ? result.value : null, ); - if (data === null || data.exists === false || data.truncated) return null; - return parseT3ProjectFile(data.contents); +} + +/** The project's t3.json from an earlier read, or `undefined` when none has loaded yet. */ +export function peekT3ProjectFile( + environmentId: EnvironmentId, + workspaceRoot: string, +): T3ProjectFile | null | undefined { + const result = appAtomRegistry.get( + getProjectFileQueryAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME), + ); + return AsyncResult.isSuccess(result) + ? toT3ProjectFile(environmentId, workspaceRoot, result.value) + : undefined; } 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 fc26b06902925..70ee2c13a29a7 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -9,21 +9,13 @@ 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"; import { esveoReactRootErrorOptions } from "./components/esveoErrorReport/reactErrorInfo"; 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. @@ -41,7 +33,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, esveoReactRootErrorOptions, @@ -56,6 +48,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/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index d3ff25c4ee629..7b09d7a837779 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -18,6 +18,7 @@ import { Route as ApproveAgentRouteImport } from './routes/approve-agent' import { Route as ChatRouteImport } from './routes/_chat' import { Route as ChatIndexRouteImport } from './routes/_chat.index' import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey' +import { Route as ChatWorkflowsRouteImport } from './routes/_chat.workflows' import { Route as ChatUsageRouteImport } from './routes/_chat.usage' import { Route as ChatSettingsRouteImport } from './routes/_chat.settings' import { Route as ChatPullRequestsRouteImport } from './routes/_chat.pull-requests' @@ -101,6 +102,11 @@ const ProjectsProjectKeyRoute = ProjectsProjectKeyRouteImport.update({ path: '/projects/$projectKey', getParentRoute: () => rootRouteImport, } as any) +const ChatWorkflowsRoute = ChatWorkflowsRouteImport.update({ + id: '/workflows', + path: '/workflows', + getParentRoute: () => ChatRoute, +} as any) const ChatUsageRoute = ChatUsageRouteImport.update({ id: '/usage', path: '/usage', @@ -316,6 +322,7 @@ export interface FileRoutesByFullPath { '/pull-requests': typeof ChatPullRequestsRoute '/settings': typeof ChatSettingsRouteWithChildren '/usage': typeof ChatUsageRoute + '/workflows': typeof ChatWorkflowsRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute '/draft/$draftId': typeof ChatDraftDraftIdRoute @@ -363,6 +370,7 @@ export interface FileRoutesByTo { '/pull-requests': typeof ChatPullRequestsRoute '/settings': typeof ChatSettingsRouteWithChildren '/usage': typeof ChatUsageRoute + '/workflows': typeof ChatWorkflowsRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/': typeof ChatIndexRoute '/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute @@ -413,6 +421,7 @@ export interface FileRoutesById { '/_chat/pull-requests': typeof ChatPullRequestsRoute '/_chat/settings': typeof ChatSettingsRouteWithChildren '/_chat/usage': typeof ChatUsageRoute + '/_chat/workflows': typeof ChatWorkflowsRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/_chat/': typeof ChatIndexRoute '/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute @@ -464,6 +473,7 @@ export interface FileRouteTypes { | '/pull-requests' | '/settings' | '/usage' + | '/workflows' | '/projects/$projectKey' | '/$environmentId/$threadId' | '/draft/$draftId' @@ -511,6 +521,7 @@ export interface FileRouteTypes { | '/pull-requests' | '/settings' | '/usage' + | '/workflows' | '/projects/$projectKey' | '/' | '/$environmentId/$threadId' @@ -560,6 +571,7 @@ export interface FileRouteTypes { | '/_chat/pull-requests' | '/_chat/settings' | '/_chat/usage' + | '/_chat/workflows' | '/projects/$projectKey' | '/_chat/' | '/_chat/$environmentId/$threadId' @@ -674,6 +686,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ProjectsProjectKeyRouteImport parentRoute: typeof rootRouteImport } + '/_chat/workflows': { + id: '/_chat/workflows' + path: '/workflows' + fullPath: '/workflows' + preLoaderRoute: typeof ChatWorkflowsRouteImport + parentRoute: typeof ChatRoute + } '/_chat/usage': { id: '/_chat/usage' path: '/usage' @@ -1014,6 +1033,7 @@ interface ChatRouteChildren { ChatPullRequestsRoute: typeof ChatPullRequestsRoute ChatSettingsRoute: typeof ChatSettingsRouteWithChildren ChatUsageRoute: typeof ChatUsageRoute + ChatWorkflowsRoute: typeof ChatWorkflowsRoute ChatIndexRoute: typeof ChatIndexRoute ChatEnvironmentIdThreadIdRoute: typeof ChatEnvironmentIdThreadIdRoute ChatDraftDraftIdRoute: typeof ChatDraftDraftIdRoute @@ -1027,6 +1047,7 @@ const ChatRouteChildren: ChatRouteChildren = { ChatPullRequestsRoute: ChatPullRequestsRoute, ChatSettingsRoute: ChatSettingsRouteWithChildren, ChatUsageRoute: ChatUsageRoute, + ChatWorkflowsRoute: ChatWorkflowsRoute, ChatIndexRoute: ChatIndexRoute, ChatEnvironmentIdThreadIdRoute: ChatEnvironmentIdThreadIdRoute, ChatDraftDraftIdRoute: ChatDraftDraftIdRoute, 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/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsx index c97534939f743..637bf8f9a2236 100644 --- a/apps/web/src/routes/_chat.settings.tsx +++ b/apps/web/src/routes/_chat.settings.tsx @@ -52,22 +52,41 @@ function SettingsScopeBoundary({ pathname, children }: { pathname: string; child const m = useMessages(); const hash = useLocation({ select: (location) => location.hash }); const searchTarget = getSettingsSearchTargetScope(hash); - const autoSettlementAvailability = searchTarget?.requiresThreadAutoSettlement - ? getThreadAutoSettlementSearchAvailability(environments, scope) + const agentFeedbackAvailability = searchTarget?.agentFeedbackOnly + ? { + eligibleEnvironmentIds: environments + .filter( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ) + .map((environment) => environment.environmentId), + isTargetAvailable: + connectedEnvironments.length > 0 && + connectedEnvironments.every( + (environment) => + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ), + } : null; + const targetAvailability = + agentFeedbackAvailability ?? + (searchTarget?.requiresThreadAutoSettlement + ? getThreadAutoSettlementSearchAvailability(environments, scope) + : null); if ( scope.kind !== "unavailable" && searchTarget && - autoSettlementAvailability && - !autoSettlementAvailability.isTargetAvailable + targetAvailability && + !targetAvailability.isTargetAvailable ) { return ( - {autoSettlementAvailability.eligibleEnvironmentIds.length > 0 + {targetAvailability.eligibleEnvironmentIds.length > 0 ? gt("{title} requires a supporting environment. Choose one to continue.", { title: m(searchTarget.title), }) diff --git a/apps/web/src/routes/_chat.workflows.tsx b/apps/web/src/routes/_chat.workflows.tsx new file mode 100644 index 0000000000000..c755da76d5b38 --- /dev/null +++ b/apps/web/src/routes/_chat.workflows.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from "@tanstack/react-router"; + +import { readWorkflowPane } from "../components/workflows/workflowPane.logic"; +import { WorkflowsPage, type WorkflowsSearch } from "../components/workflows/WorkflowsPage"; + +export const Route = createFileRoute("/_chat/workflows")({ + validateSearch: (raw: Record): WorkflowsSearch => ({ + ...(typeof raw.env === "string" && raw.env ? { env: raw.env.slice(0, 200) } : {}), + ...(typeof raw.run === "string" && raw.run ? { run: raw.run.slice(0, 200) } : {}), + ...readWorkflowPane(raw.pane, raw.tab), + ...(raw.definitions === true || raw.definitions === "true" ? { definitions: true } : {}), + ...(typeof raw.file === "string" && raw.file ? { file: raw.file.slice(0, 200) } : {}), + }), + component: WorkflowsPage, +}); 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..99a1fc62a0bc3 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -245,6 +245,7 @@ const STANDALONE_V2_ITEM_TYPES = new Set) { - 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/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index adeb858c23cab..4194e07834811 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -11,7 +11,7 @@ import { useNavigate, useRouter } from "@tanstack/react-router"; import { AsyncResult, Atom } from "effect/reactivity"; import type { TurnItemSource } from "../components/chat/timelineRowContext"; -import { useRightPanelStore } from "../rightPanelStore"; +import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore"; import { connectPairing, reachesEnvironment } from "../connection/onboarding"; import { openLinkedThreadRead } from "../lib/sideChatPane"; import type { LinkedThreadSurface } from "../linkedThreadSurface"; @@ -107,14 +107,17 @@ const tabViewAtom = Atom.family((key: string) => { const view = peerLinkEnvironment.threadView( targetOf({ viaEnvironmentId, environmentId, threadId }), ); - return Atom.make((get) => { - const live = get(view); - const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; - if (title && panelRef !== null) { - useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); - } - return live; - }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); + return Atom.readable( + (get) => { + const live = get(view); + const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; + if (title && panelRef !== null) { + useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); + } + return live; + }, + (refresh) => refresh(view), + ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); }); /** @@ -203,8 +206,17 @@ export function useConnectLinkedEnvironment( const connect = async () => { setState({ phase: "connecting" }); const startedOn = router.state.location.href; + let tabClosed = false; + // A tab can close and reopen with the same ID while pairing is in flight. + const stopWatchingTab = + panelRef === null + ? undefined + : useRightPanelStore.subscribe((state) => { + const { surfaces } = selectThreadRightPanelState(state.byThreadKey, panelRef); + if (!surfaces.some((tab) => tab.id === surface.id)) tabClosed = true; + }); // Pairing takes a moment; a user who has gone elsewhere since is not moved again. - const stayed = () => router.state.location.href === startedOn; + const stayed = () => !tabClosed && router.state.location.href === startedOn; const outcome = await connectLinkedEnvironment({ label: surface.label, requestPairing: async () => { @@ -228,13 +240,14 @@ export function useConnectLinkedEnvironment( }); return result._tag === "Success"; }, - }); + }).finally(stopWatchingTab); if (outcome.type === "unreachable") { setState({ phase: "unreachable", label: outcome.label }); return outcome; } if (outcome.type === "connected") { setState({ phase: "idle" }); + if (tabClosed) return outcome; // The thread opens where every thread on a connected environment does, so its tab is done. if (panelRef !== null) useRightPanelStore.getState().closeSurface(panelRef, surface.id); if (!stayed()) return outcome; 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.test.ts b/apps/web/src/timestampFormat.test.ts index 5f6513ab69623..e94bffea49fbe 100644 --- a/apps/web/src/timestampFormat.test.ts +++ b/apps/web/src/timestampFormat.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; import { formatChatTimestampTooltip, @@ -18,6 +18,20 @@ function useTimeZone(timeZone: string): Disposable { }; } +it("localizes the day period while honoring the system clock and explicit 24-hour mode", async () => { + using _zone = useTimeZone("UTC"); + vi.stubGlobal("window", { desktopBridge: { getSystemLocale: () => "en-US" } }); + vi.resetModules(); + try { + const { formatShortTimestamp } = await import("./timestampFormat"); + const date = "2026-11-19T18:05:00.000Z"; + expect(formatShortTimestamp(date, "locale", "zh")).toBe("下午6:05"); + expect(formatShortTimestamp(date, "24-hour", "zh")).toBe("18:05"); + } finally { + vi.unstubAllGlobals(); + } +}); + describe("timestamps in an explicit time zone", () => { // 23:00 UTC on July 1 is 7 PM on July 1 in New York, whatever the host zone. const now = Date.parse("2026-07-01T23:00:00.000Z"); diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index ac99534a5ca2f..273b5989366f2 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -84,15 +84,21 @@ function getTimestampFormatter( timestampFormat: TimestampFormat, includeSeconds: boolean, timeZone = "UTC", + locale = timestampLocale, ): Intl.DateTimeFormat { - const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}:${timeZone}`; + const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}:${timeZone}:${locale ?? ""}`; const cachedFormatter = timestampFormatterCache.get(cacheKey); if (cachedFormatter) { return cachedFormatter; } - const formatter = new Intl.DateTimeFormat(timestampLocale, { + const hourCycle = + timestampFormat === "locale" && locale !== timestampLocale + ? getTimestampFormatter(timestampFormat, includeSeconds).resolvedOptions().hourCycle + : undefined; + const formatter = new Intl.DateTimeFormat(locale, { ...getTimestampFormatOptions(timestampFormat, includeSeconds), + ...(hourCycle === undefined ? {} : { hourCycle }), timeZone, }); timestampFormatterCache.set(cacheKey, formatter); @@ -175,10 +181,41 @@ export function formatFullTimestamp(isoDate: string, timestampFormat: TimestampF ); } -export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string { +export function formatShortTimestamp( + isoDate: string, + timestampFormat: TimestampFormat, + locale?: string, +): string { + const date = parseTimestampDate(isoDate); + if (!date) return ""; + return getTimestampFormatter(timestampFormat, false, "UTC", locale).format(wallClockAsUtc(date)); +} + +const dateTimeFormatterCache = new Map(); + +export function formatDateTimeTimestamp(isoDate: string, timestampFormat: TimestampFormat): string { const date = parseTimestampDate(isoDate); if (!date) return ""; - return formatTime(date, timestampFormat); + 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" }; diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts index 5fda79ec7846f..97540f4985def 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; readonly VITE_ESVEO_COMMIT_HASH: string; } diff --git a/apps/web/src/workspaceBasenameLookup.test.ts b/apps/web/src/workspaceBasenameLookup.test.ts index 4e11917a0aeff..7c1d17587813e 100644 --- a/apps/web/src/workspaceBasenameLookup.test.ts +++ b/apps/web/src/workspaceBasenameLookup.test.ts @@ -129,6 +129,21 @@ describe("chat file links into another project", () => { ).toBeNull(); }); + it("opens nothing when a project left ambiguous by case also has the name", () => { + expect( + pickProjectLinkMatch("handoff.txt", [ + { root: "/reports", entries: [{ path: "notes/HANDOFF.txt", kind: "file" }] }, + { + root: "/support", + entries: [ + { path: "current/Handoff.txt", kind: "file" }, + { path: "archive/HANDOFF.txt", kind: "file" }, + ], + }, + ]), + ).toBeNull(); + }); + it("opens nothing when overlapping projects also list a second suffix match", () => { expect( pickProjectLinkMatch("docs/handoff.txt", [ diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index 71e8875bb56db..85a857b33329a 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -67,7 +67,12 @@ const descriptor = { // A matching version, since a mismatch adds an update banner a typical user never sees. serverVersion: APP_VERSION, orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, - capabilities: { repositoryIdentity: true, sideChats: true, freshContext: true }, + capabilities: { + repositoryIdentity: true, + sideChats: true, + freshContext: true, + fileAttachments: { maxUploadBytes: 10_000_000 }, + }, }; const auth = { policy: "loopback-browser", @@ -338,9 +343,9 @@ function shellOf(thread: FakeThread): OrchestrationV2ThreadShell { createdBy: thread.providerSubagentOf ? "agent" : "user", creationSource: thread.providerSubagentOf ? "provider" : "web", latestRunId: latest?.id ?? null, - activeRunId: null, + activeRunId: latest?.status === "running" ? latest.id : null, // Idle reads as waiting on the user, which shows a per-second duration in the sidebar. - status: latest ? "completed" : "idle", + status: latest?.status === "running" ? "running" : latest ? "completed" : "idle", pendingRuntimeRequest: null, latestVisibleMessage: null, latestUserMessageAt: AT, diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 3b92e74f12c57..dc3a3f4c2e7ab 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), "import.meta.env.VITE_ESVEO_COMMIT_HASH": JSON.stringify( diff --git a/docs/internals/product-analytics.md b/docs/internals/product-analytics.md index b6dc3f245390a..2b8685ecf2281 100644 --- a/docs/internals/product-analytics.md +++ b/docs/internals/product-analytics.md @@ -144,10 +144,22 @@ batch was sent every second for days. ## Collection boundary -Keep analytics payloads to product metadata and normalized measurements. Do not -send prompts, authentication material, raw provider payloads, user-assigned device -names, or conversation identifiers. Client metadata is best effort; invalid values -must not reject a connection. PostHog person profiles remain disabled. +Keep analytics payloads to product metadata and normalized measurements. The one +exception is `agent.feedback`, sent only while the user has turned on agent +feedback: its `expected`, `actual`, and `workaround` fields are agent-written text, +which [FeedbackService](../../apps/server/src/feedback/FeedbackService.ts) scrubs of +file paths, values the server knows are private to the caller, and secret-shaped +strings, and caps at 300 characters each. `userRequested: true` means the user saw the +report in its preview card and pressed Send; only such a report carries +`trace`, which the server builds from the thread when the card is shown: an outline of +at least the last 5 turns with no text, plus the scrubbed message text of the turns the +agent said the problem spans only when the user turned on the card's conversation switch, capped at 1,000 characters per message and 16 KB per +trace so a telemetry batch stays small. Both traces live on the card's turn item until +it is answered, so the server sends what the card showed and never text from a client. Tool inputs and outputs never go in it, and tools from other MCP servers go +by one generic name. The server attaches no other prompts, authentication material, +raw provider payloads, user-assigned device names, or conversation identifiers to +any event. Client metadata is best effort; invalid values must not reject a +connection. PostHog person profiles remain disabled. Dev-runner servers and the CI archive smoke test turn telemetry off, which also stops relay tracing, because each would count as a new install. Set diff --git a/docs/internals/workflows.md b/docs/internals/workflows.md new file mode 100644 index 0000000000000..5f9b965c082b5 --- /dev/null +++ b/docs/internals/workflows.md @@ -0,0 +1,178 @@ +# Workflows + +A workflow run is a journaled function: a step's result is stored once it succeeds, a restart +replays the run to where it was, and a run sleeps on a wait until something outside signals it. A +step's body can run more than once, after a failure it retries or a crash mid-step, so what it does +outside the run must be safe to repeat. The code is in +[`apps/server/src/workflows`](../../apps/server/src/workflows). This page holds what is not +obvious from it. + +## Why it is shaped this way + +**The engine is Effect's, in the server's database.** `effect/workflow` on one runner journals +runs in tables it creates itself. Runs, steps, waits and kept signals are rows of ours beside them, +not orchestration events: the event store knows projects and threads, a run is neither, and its +journal is the engine's to read. Clients follow runs the way they follow scheduled tasks, by a +list that is sent again when something changes. + +**Off until turned on, then until something is defined.** Workflows are a Labs setting, +`workflowsEnabled`, and the runtime's lifetime follows it: while it is off no file is loaded, no +engine runs, and every request is refused with how to turn it on; turning it off closes the +runtime the way a restart does, so runs wait in the database for it to come back. Once on, the +server registers what the files in the home's `workflows` folder define. While they define +nothing and no runs are kept, the `Workflows` service is the disabled one and the engine's modules +are never imported ([`WorkflowRuntime.ts`](../../apps/server/src/workflows/WorkflowRuntime.ts)). +Keep it that way: anything a light module imports from `effect/workflow` or `effect/cluster` is +paid for by every server and CLI start. + +**A step failure pauses the run.** The alternative, ending the run, loses everything done so far to +a dependency that is back in a minute. Resuming runs the failed step again and nothing before it. +Effect's engine suspends the body when a step fails, so no handler in the body ever sees the +error: the primitives type their error as `never`, and `step.try` and `agent.try` return a failure +as data instead. A step runs once unless it asks for retries, since a lost reply to a post or a +merge would otherwise do it again. A run paused by an agent that gave up waits for a person rather +than `resumeAfter`: resuming starts the agent's whole job again. `stop` is the workflow's own +decision to end, and is not a failure. + +**An agent step is a thread.** It completes when the agent submits a result the server checked +against the step's schema, not when a turn ends, and a person can open the thread and talk to it. +See [typed results](../orchestration-v2/orchestrator-mcp-server.md#t3_submit_output). + +**A run stays where it started; its agents need not.** An agent step that names a linked +environment runs its thread there through that environment's own thread tools, with the step's key +as the request id, so a replay finds the thread it already started. The run is no agent and has no +modes to pass on, so the link's access is the only ceiling on what it starts there. Making and +linking machines is the workflow author's own code in a `step`; nothing here knows how. + +**An agent step's thread says which run it belongs to.** The thread is created with the run, the +workflow and the step it is, and its lineage marks it as a workflow step, so the default lists +of threads leave it out the way they leave out subagents (a list that asks for subagents gets +them too): a run can have dozens, and they are read +through the run. Only the server may set this, as with a link's origin; over a link the launch +tool carries it and it is kept only for a link session. + +**An invoked run is a run of its own.** `invoke` starts it from a step with this run as its +parent and then waits like any `wait`; the engine signals that wait when the child ends, however +it ends, so a child that finished before the parent got to its wait is not missed. A key names +one run with one parent, so invoking under a key something else started is refused instead of +waiting for a signal that would never come. + +**The store is for inside a step.** Its values change between replays, so the body must not read +it; `step` and `onEnd` hand their code the store, a way to signal, and a way to start, find and +cancel runs, and nothing else may use them. A step's signals are numbered from the step's name +and where each goes, so a retried step that sends the same signal again sends no new one, and +one that sends somewhere new is not taken for what an earlier try sent. + +**A run keeps what it touched.** A reference is a `kind`, a `key` naming the thing within its +kind, and an `address` that only that kind's client reads, so a new kind is a new caller of +[`noteReference`](../../apps/server/src/workflows/runReferences.ts) and nothing more. It is called +from inside a step: by the forge helpers, by an agent step's thread for its `issue` and the pull +requests linked to it while the step ran, and by the engine's look at a pull request a wait is +on. An issue or pull request trigger notes its item with no step. There is one row per run, kind +and key, so a retry or replay that touches the same thing adds nothing. It is only for a person +to read: a failure to keep it is logged and never fails a step. Only a run's detail carries +references, not the list that is sent again on every change. + +**A thread owes its result across turns.** An agent that waits for something ends its turn and is +woken later, in a turn nobody asked a result of. A submission from such a turn goes to the newest +turn that was asked and has not answered, so the result lands on the turn the step started, and a +wait with `untilOutput` holds past that turn's end for it. The `quiet` option of an agent step is +that wait with a limit: quiet is counted from the thread's last turn, and when it passes the +step asks for the result as it would have at once without the option. + +**A failed agent is an answer only when the workflow asks for that.** `agent.try` journals the same +turns as `agent` and differs at the end: it marks the step failed and returns, where `agent` +fails the step and pauses the run. A start that failed is journaled as a turn without ids, so a +replay does not try the start again. + +**`onEnd` gets the payload and the run's id, not the body's values.** A cancelled run's body is +gone, so its cleanup runs outside the engine and has only what the run was started with. Inside +the engine `onEnd` is an ordinary last step. + +**Definitions reload by replacing the engine.** The engine is built from a fixed set of +definitions, so a changed folder closes it and builds a new one on the same database, which is +what a restart does; runs come through it as they come through a restart. The service the rest +of the server holds forwards to whichever engine is current, and callers during the swap wait +for the new one. With nothing defined but runs kept, an engine with nothing registered and no +cluster runner serves their history. + +**Each file keeps its last good version.** A file that stops loading does not take its workflows +down, and does not hold back the other files. A change that fails a check across files, a +workflow defined twice or a version dropped under unfinished runs, is held back the same way: +the changed file keeps its last good version (a new one stays out, and of two new files the +first by name wins), and the rest of the change is taken. A held change is tried again on every +reload, since the runs that held it may have ended. + +**The API is globals, so files load one at a time.** `T3.workflow` registers with the load in +progress, and the globals are the process's. A file is loaded under a new address each time, +because Node keeps a module by its address; modules a file imports keep theirs, so they are not +reloaded, and a workflow one of them defines registers only the first time. That is why shared +code belongs in a subfolder and definitions in the files themselves. Saving from a client +verifies a copy beside the real file first, so its imports resolve the same way. + +## Traps + +**A workflow body is replayed.** After a restart or a wait, the body runs again from the top and +each journaled action returns what it stored. Anything that touches the world goes through +a durable activity: `journaled` for `step` and `agent`, and a pair of open and close activities +around a `DurableDeferred` for `wait`, so a fix to one is not a fix to the other. Code between steps must give the same +answer on every pass: no clock, no randomness, no reads. + +**Names are the journal's keys.** A step's result and its row in the step list are both kept by +name, so two steps with one name would share a result. `claim` rejects that, across kinds. A change +to the order of steps, or to the shape a step returns, is a new `version` of the workflow; keep the +old one registered until its runs have ended. A run whose version is gone shows as `retired`. + +**The engine reads integers as BigInt, and nothing else may.** It stores 64-bit ids, which +`node:sqlite` only reads when asked for BigInts, so the engine's fibers and every call into it run +with `SqlClient.SafeIntegers` on. That setting is inherited by whatever those fibers call. +`journaled` turns it off again around a step's own code, and the sweep turns it off around the +turn stops and the `onEnd` it runs for a cancelled run; without that, a step that reads a project +gets rows it cannot decode. + +**The pause is recorded in two places, a moment apart.** A failing step marks its run paused from +inside the engine, just before the engine records the failure. `resume` waits for the engine's +record, or it would resume a run the engine does not yet consider stopped and do nothing. The sweep +puts back a run that still says it goes on while the engine holds it as failed, held for a person if +it was, and leaves alone one a resume is under way for. + +**A paused run is not woken.** The engine replays a run for any wake, and the replay runs the failed +step again as a resume would, though nobody resumed it. A signal, timeout or child's end for a +paused run's other wait is only claimed; the resume sends the wakes its run has claimed. + +**A step in flight cannot be interrupted.** The engine runs a step's body to its end. `cancel` +therefore ends the run's row first, so nothing the step still does is recorded as the outcome, and +stops the step's own turn, which is what makes a long agent step return. Only that turn: someone +else's turn on the same thread is left alone. The cancelled run's `onEnd` waits for the steps still +running in this process, or a cleanup would take away what a step is still making. A version stays +required while a cancelled run's cleanup still has tries left, since only that version can run it; +one that has used them up stays failed on the run for a person to see. + +**A key is one run whatever the version.** The engine's own run id hashes `name@version` with the +key, so after a version bump the same key would be a new run: a trigger that sees its newest issue +again, or a webhook retry, would start the work twice. The key is unique per workflow, so the row +that takes it is the run; a start that finds a row the engine never got executes it. + +**An ended run's journal is deleted.** The engine keeps every request and reply of a run, which +grew one large deployment's database by gigabytes in two weeks, so the sweep clears a run's engine +messages (its sleeps included) an hour after it ends with no step still going. Our rows stay, and +they are all that shows a run. Nothing may hand an ended run to the engine again: with no journal +it would run the body from the start, so a start for an ended run's key returns that run as it is. + +**One signal wakes one wait.** A wait is taken by the first signal for it; a second signal on the +same channel is for the next run that waits on that channel, and is kept until one does or its `ttl` runs +out (seven days by default), after which it is gone. A signal's id is remembered for seven days +once delivered, or until its `ttl` if that is later, so a sender's retry within that time is not a +second signal. + +**A wait checks a signal twice.** The engine checks a value against the wait's JSON Schema before +it wakes the wait, but only the run has the wait's codec, and a codec can refuse what its JSON +Schema allows (a number read from text). A value the codec refuses was not for the wait: the wait +opens again under a fresh wake and says why, rather than failing on every replay. Kept mail on a +channel that a wait cannot read is left for another wait there; mail addressed to that wait is +dropped. + +**`signalAll` keeps nothing.** It wakes the waits open on a channel now and is not kept for one that +opens later: a kept broadcast would wake whichever single run waited next, days on. A run that +holds for a condition therefore reads the condition in a step and waits with a timeout, so one +that began to wait just after the broadcast looks again. diff --git a/docs/operations/scenarios.md b/docs/operations/scenarios.md index 798d066371684..abfccf45a9673 100644 --- a/docs/operations/scenarios.md +++ b/docs/operations/scenarios.md @@ -23,7 +23,8 @@ test( await t3.project("demo"); await t3.open(); - await screen.getByRole("button", "Add project").tap(); + await screen.getByRole("combobox", "Projects").tap(); + await screen.getByRole("option", "Add project").tap(); await screen.getByText("Git URL").tap(); await screen.getByRole("combobox").fill("https://github.com/pingdotgg/t3code.git"); const submit = screen.getByRole("button", "Continue (Enter)"); diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 71d8845e74c75..8167049a87817 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -479,6 +479,13 @@ status and does not cancel work. `output` carries what the run submitted against its `outputSchema`; with `untilOutput`, a completed run that has not submitted yet is waited on until it has. +### `t3_workflow` + +Starts, lists, reads, signals, resumes and cancels [workflow runs](../internals/workflows.md), and +lists the questions runs ask a person. It is advertised to clients outside a thread only, such as +the `t3 workflow` CLI, so it costs no thread any context; an agent in a thread drives workflows +through that CLI. `start` is idempotent on `idempotencyKey` and `signal` on `signalId`. + ### `t3_thread_interrupt` Interrupts a selected active run through the normal V2 `run.interrupt` command. diff --git a/docs/user/composer.md b/docs/user/composer.md index 94b0219e5ab5a..53017052a2a01 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -69,6 +69,10 @@ are saved on the server and can be edited or removed before they send. When Enter sends, `Cmd+Enter` on macOS or `Ctrl+Enter` on Windows and Linux uses the opposite action: it steers when your default is Queue and queues when your default is Steer. +A slash command such as `/compact` or `/context` waits for the current turn to +finish, because a command steered into a turn would replace the agent's task. +Sending a queued command now moves it to the front of the queue. [Goal](#goals) +commands are the exception: some can stop the current turn. If your **Send shortcut** requires `Cmd+Enter` or `Ctrl+Enter`, that shortcut uses your default follow-up behavior; add **Shift** to use the opposite action. This applies only to multiline messages when you choose the multiline send option. @@ -271,8 +275,9 @@ shortcut described above. On web and desktop, queued messages appear at the end of the thread as dashed messages that have not been sent yet. On mobile they appear above the composer. Each shows its text and any attached -images. **Send now** sends a message right away, into the running turn if there is one. You can -also edit or remove it. +images. **Send now** sends a message right away, into the running turn if there is one. While a +turn runs, a slash command moves to the front of the queue instead. You can also edit or +remove it. If you stop the agent or the server restarts, queued messages keep their order and are held. Press **Resume** in an empty composer to continue. For stopped runs and usage limits, 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/managed-policy.md b/docs/user/managed-policy.md index 32e6f47da4693..a8583b923f3c1 100644 --- a/docs/user/managed-policy.md +++ b/docs/user/managed-policy.md @@ -249,6 +249,7 @@ so restart T3 Code after that. - `webhookTasks: false`: scheduled tasks cannot use webhook triggers. Existing webhook tasks stay but do not run, and cannot be turned back on. Users can still edit or delete them. + Workflow webhooks are refused too. - `browserCookieImport: false`: users cannot import cookies from another browser into T3 Code's browser. - `previewTunnel: false`: other devices cannot load this machine's `localhost` pages themselves. diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 9c164f91c9962..30c8aba13ffb1 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -135,6 +135,23 @@ Any agent that supports remote MCP servers over HTTP with OAuth can connect. Giv it the MCP URL and choose OAuth, and the agent finds the sign-in settings itself. Agents without OAuth support cannot connect. +A bot that supports MCP Events (`io.modelcontextprotocol/events`) can learn +when something happens without reading threads over and over: a turn ended, an +agent waits on a person, a guest asked something, a watched pull request woke +its thread. [Workflow runs](workflows.md) are events too: a run started, paused, +resumed or ended, or waits on a person. A bot can poll, stream, or receive each +event type by webhook, narrowed to projects and threads or to workflows and +runs; runs another run started are left out unless asked for, as subagent +threads are, and narrowing thread events to a run picks out its agent steps. +The environment keeps its latest 1,000 milestones in memory, so a bot that was +away longer, or reconnects after a restart, is told some may be missing and +should reread what it cares about. Webhooks go only to public `https` addresses, +a subscription lasts at most an hour before the bot must renew it, and signing +the bot out ends its subscriptions. To test with a receiver on your own machine +or network, start the environment with `T3CODE_MCP_WEBHOOK_ALLOWED_HOSTS` set to +its host names, for example `localhost,127.0.0.1`; those hosts may also use +plain `http`. + ## Scripts on the host On the machine that runs the environment, `t3 thread` uses the same tools diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md index a8f1cf8391221..60c403e31979b 100644 --- a/docs/user/permission-modes.md +++ b/docs/user/permission-modes.md @@ -48,6 +48,10 @@ session-wide choice, because Grok would remember that command for the whole proj ACP Registry agents run their own tools in their own mode; T3 Code answers their approval requests by the permission mode. See [ACP Registry permissions](./providers-acp.md#permissions-and-terminals). +In **Full access**, commands that Codex's dangerous-command check would ask about run without +asking. Codex still asks before network access its managed network settings don't allow, unless +you already allowed commands for the session. + Claude can still ask in **Full access** when its settings disable bypass permissions or require approval for an action. Dangerous-removal safety checks in bypass mode reject the command with the original warning. Claude can use a safe rewrite when the warning supplies one; otherwise it diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 84c13d30c4c84..00b27e02ae23d 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -63,8 +63,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/remote-access.md b/docs/user/remote-access.md index 99255db9ac8cb..051445f03eb07 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -468,8 +468,10 @@ an address you trust: the code is sent there. machine's own threads, projects or settings, and they skip its project setup scripts. - The link shows up in that machine's **Settings → Sharing & access** like any - outside agent. Revoke it there to end it. **Forget** on this machine only - removes it here. + outside agent, and can be revoked there. **Forget** on this machine also ends + it there when that machine confirms it. If it can't, such as when it is + offline or on an older T3 Code, Forget says so; revoke it in that machine's + Sharing & access. - A link stays valid while agents use it. One unused for 30 days expires, as does one to a machine on an older T3 Code after 30 days; link again with a new pairing code. diff --git a/docs/user/source-control.md b/docs/user/source-control.md index c04060ba831a3..ba951c3fe9bda 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -146,8 +146,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 @@ -158,7 +160,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. @@ -412,7 +416,9 @@ To list Linear issues beside a project's, connect Linear with an API key under Settings → Source control & issues, then pick one or more teams for that project there. Pick another team at any time to add it; uncheck every team to unbind the project. Each team's issues appear in the Linear group of the issue list, sorted with the rest by last update, and -each can be loaded further on its own. Agents file new issues in the first team picked. +each can be loaded further on its own. Agents file new issues in the first team picked unless you name another bound team. To +connect another Linear workspace or user, add another account in the same place; each project +reads its teams through the account you picked them under. Select an issue to open it beside the list: description, comments, state changes, linked pull requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md index 2f2ccc8932769..4c6b3f20eaad5 100644 --- a/docs/user/telemetry.md +++ b/docs/user/telemetry.md @@ -10,7 +10,56 @@ available. Child-agent token counts are reported separately from the main agent' are sent only when they appear in a provider's public model list. Product events do not include prompts, responses, file contents, authentication tokens, conversation IDs, -raw provider events, or child-agent output. +raw provider events, or child-agent output. The one exception is [agent feedback](#agent-feedback), +which is off unless you turn it on. + +## Agent feedback + +Agent feedback lets agents tell the T3 team about T3 Code: a T3 tool or `t3` command that did not +do what they expected, a confusing instruction, or a missing capability. Choose a mode in +**Agent feedback** in **Settings > Labs**: + +- **Off**, the default: agents do not see the feedback tools, and `t3 feedback` stops with a + message pointing to Labs. +- **When I ask**: agents send a report only when you ask them to, about anything in T3 Code. +- **Automatic**: agents also report T3 Code problems they hit on their own, such as a T3 tool that + failed and made them find another way. These reports carry no outline and no message text, and + go out without asking you. `t3 feedback --kind bug --subject "t3 thread send" --expected "…" --actual "…"` + sends one the same way, so it works only in this mode. + +When you ask your agent for a report, in either mode, T3 Code shows it in the thread as a card +with exactly what would leave your machine, and sends it only if you press **Send**. The agent +carries on without waiting and never learns your answer. The card stays open until you answer it, +even after the turn ends or the server restarts; **Don't send** sends nothing, and the agent is +told not to send it another way. Only someone who can run agents on that machine can answer the +card; people on a guest link cannot. + +Each report has the kind of problem, the T3 tool or command it concerns (or `general`), and up to +300 characters each of expected behavior, actual behavior, and workaround, written by the agent, +which is told not to quote your messages or code. The agent also says how many recent turns the +problem spans. A report you approved carries an outline of those turns, and of at least the last 5, +from when the agent asked: who spoke, how long each message was, and which tools ran, whether they +worked, and how long they took. The outline has no text. Tools from your other MCP servers appear +only as `mcp`. Turn on **Include the conversation** in the card to attach the text of your +messages and the agent's replies in the turns the problem spans, up to 1,000 characters per +message and 16 KB in all, oldest text dropped first; the card shows that text before you send it. +To change a report, such as the turns it covers, ask the agent in the chat: it shows a new card, +and you can decline the old one. Tool inputs and outputs, files, and attachments are never sent. An agent can +show you at most 3 report cards and send 3 reports on its own per turn, and `t3 feedback` can +send at most 10 an hour. + +Before anything is saved, T3 Code removes file paths (when text mentions one, the rest of that line +goes with it), your user name, machine name, project title, branch, and git remote, and anything +that looks like a key, token, email address, or URL with a password. It cannot recognise your code +or a name written in a sentence, so only include the conversation when it holds nothing you would +not send. Reports from agents also name the provider, and the model when it is from the provider's +public model list. No thread IDs or project IDs are sent. + +Reports are saved on your machine first, and a declined one is not saved at all; its card keeps +only what you would have sent without the conversation. When product usage +data is turned off, saved reports stay there and are not sent. `t3 feedback list` shows recent +reports, the thread each came from, and a line for each outline; `t3 feedback list --json` shows +exactly what each one holds. ## Relay connection diagnostics diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index c2045a3e45da8..c798f4a55a800 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/docs/user/workflows.md b/docs/user/workflows.md new file mode 100644 index 0000000000000..3327d28062bf9 --- /dev/null +++ b/docs/user/workflows.md @@ -0,0 +1,92 @@ +# Workflows + +A workflow is a TypeScript script that chains agents, plain code, schedules, webhooks, issue and pull request events, and questions to you into one durable run that survives server restarts. Each step's result is saved when it succeeds, so restarts pick up where the run left off and failures do not lose earlier work. Workflows are an early feature: start runs from the `t3` CLI or a trigger, and follow them in the app. + +For one prompt on a timer or webhook, use a scheduled task. Use a workflow when work has stages — such as triage, a fix, your approval, and a release. + +## Turn on workflows + +Workflows are a Labs feature, off by default. Turn on **Settings → Labs → Workflows** for the server that runs them. On a server without a desktop, set `"workflowsEnabled": true` in `userdata/settings.json` in its T3 home (`~/.t3` by default). While off, nothing in the workflows folder runs and `t3 workflow` says how to turn it on; runs are kept and continue once it is on again. + +## Create a workflow + +Workflow files live in `~/.t3/workflows/` (or wherever `T3CODE_WORKFLOWS` points — a folder or a single file). The server watches the folder and reloads changes without a restart. + +- **Ask an agent (recommended):** copy the [`t3-workflows` skill](https://github.com/pingdotgg/t3code/blob/main/skills/t3-workflows/SKILL.md) into your agent's skills folder (such as `~/.claude/skills/` or `~/.agents/skills/`) and describe what you want. +- **Edit directly:** edit files in `~/.t3/workflows/`, or use **Definitions** on the Workflows page (saving and deleting in the app require terminal access). Before anything has run, open the page with **Open workflows** in the command palette. + +A small workflow, saved as `~/.t3/workflows/release.ts`: + +```ts +const { workflow, step, ask, stop, title } = T3; + +export default workflow( + "release", + { version: 1, payload: Schema.Struct({ name: Schema.String }) }, + Effect.fn(function* (payload) { + yield* title(`Release ${payload.name}`); + const notes = yield* step("notes", { returns: Schema.String }, Effect.succeed("3 fixes")); + const answer = yield* ask("ship", { + title: `Ship ${payload.name}? ${notes}`, + choices: ["Ship", "Hold"], + }); + if (Option.isNone(answer) || answer.value.choice !== "Ship") return yield* stop("held back"); + return { shipped: payload.name }; + }), +); +``` + +Start it with `t3 workflow start release --input '{"name":"v1.4"}' --key v1.4`, then answer its question in the app. `T3`, `Effect`, `Schema` and `Option` are provided; a workflow file imports nothing from T3 or Effect. Name files with letters, digits, `-`, `_` and `.`; other names are skipped with a warning. + +Saving checks that the file loads, does not duplicate a workflow name and version, and does not remove a version with unfinished runs. A file that fails these checks keeps its last working version while the Workflows page (and the server log) shows why; other files are not affected. A change held back by unfinished runs goes in by itself once those runs end or are cancelled. Mistakes inside a workflow body surface when a run hits them and pauses. To change steps while runs are unfinished, add the new body under a higher `version` and keep the old one until those runs end. + +Dot-files and subfolders are ignored. Keep shared helpers in a subfolder and restart the server after editing an imported file. + +## Start and steer + +```sh +t3 workflow start --input '' --key +t3 workflow list [--status paused] +t3 workflow show +t3 workflow resume +t3 workflow cancel [--reason ''] +t3 workflow questions +t3 workflow signal '{"choice":"yes"}' --run --wait +t3 workflow signal '' --workflow --channel +t3 workflow hooks +t3 workflow store list +t3 workflow store set '' +``` + +Every start needs a `--key`: starting twice with the same key returns the same run — even after a version bump — so retries do not duplicate work. Use `signal` with `--run` and `--wait` to answer a question or wake a run, or with `--workflow` and `--channel` to wake whichever run waits on that channel. A signal for a question that is no longer open is kept for a later wait rather than refused, so check `t3 workflow questions` first. Use `store` to read or change state kept between runs. + +## Triggers + +- **Schedules:** `every` runs on an interval, starting one interval after the workflow loads; `daily` runs at a local time of day (a time missed by more than 10 minutes while the server is down is skipped). +- **Webhooks:** `t3 workflow hooks` prints each hook's path; prepend your server's address. The path contains the hook's secret, so share it only with the sender. A sender's retry that repeats its delivery header (such as GitHub's `X-GitHub-Delivery`) starts no second run, and bodies over 1 MiB are refused. Organization policies blocking webhook tasks block workflow webhooks too. +- **Issues and pull requests:** workflows can start on new issues or pull requests and read, comment on, or update them via **Settings → Source control & issues** — no webhook needed. T3 Code checks roughly once a minute, and only items opened after the workflow was first loaded start runs. + +## Follow runs in the app + +Open the Workflows page with **Open workflows** in the command palette of the web or desktop app; the entry shows once a connected server has workflows on. Filter by **Needs you**, **Running**, or **All** (skipped runs stay hidden unless toggled on), open child runs from their parent, and answer questions, resume paused runs, or cancel active runs (requires permission to operate threads). The issues and pull requests a run touched show as chips under its title and on the steps that touched them; a chip opens the item beside the run, in a tab next to any agent transcripts you opened. + +### Agent threads + +Each `agent` step runs in an ordinary thread, left out of thread lists (including `t3 thread list`). Open it from the run to watch it live, read its transcript, or send follow-up messages; the thread links back to the run. + +An `agent` step can launch a new thread with its own `workspace` (such as a worktree), `runtimeMode`, `interactionMode`, `title`, and typed `returns`, or continue an earlier step's thread. Runs can set their display name with `title(text)`. An `agent` step can also target a project on a [linked environment](remote-access.md#link-another-environment) (requires **Settings → Labs → Linked environments**); the run itself stays on the server that started it. + +### Failures, pause, and cancel + +A plain code step runs once unless it asks for retries. When a step fails, the run pauses there instead of losing earlier work: + +- **Code step failures** retry automatically after 5, 20, and 80 minutes by default, or immediately when you resume; only that step runs again. +- **Agent failures** — when an agent ran and gave up or timed out — pause and wait for you to resume rather than retrying automatically. An agent that could not be started at all, for example because its environment was offline, retries on its own like a failed step. + +Cancelling a run stops its active agent turns and cancels child runs it invoked. A cancelled run cannot be resumed. + +## Limits + +- Runs live on the server that started them and only advance while it is running; use an always-on machine for schedules or webhooks you cannot miss. +- Keep older workflow versions defined until their unfinished runs end or are cancelled. +- Signals sent to a `channel` before a run waits on it are kept for 7 days by default. diff --git a/evals/README.md b/evals/README.md index 8cfb697373c31..d2ecb73dd71be 100644 --- a/evals/README.md +++ b/evals/README.md @@ -4,13 +4,14 @@ An eval runs a real model against T3 Code's real text or code and scores what th Write or run an eval when a change affects what a model sees or does: agent instructions, MCP tool descriptions and schemas, tool results, generated titles, or the guidance an agent gets for a feature such as Device Manager. -| Eval | Measures | -| ------------------------------- | ---------------------------------------------------------------------------------------------------- | -| [mcp-tool-use](mcp-tool-use/) | Whether agents use T3's MCP tools correctly, including device routing and recovery, in fake threads. | -| [thread-titles](thread-titles/) | Whether generated thread titles name the right subject. | -| [pr-content](pr-content/) | Whether PR generation describes the diff when project instructions try to redirect it. | -| [voice-cleanup](voice-cleanup/) | Whether optional dictation cleanup edits only the spoken text and preserves its meaning. | -| [test-signal](test-signal/) | Whether a cheap model running the test-signal check flags low-signal tests. | +| Eval | Measures | +| ----------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| [mcp-tool-use](mcp-tool-use/) | Whether agents use T3's MCP tools correctly, including device routing and recovery, in fake threads. | +| [thread-titles](thread-titles/) | Whether generated thread titles name the right subject. | +| [pr-content](pr-content/) | Whether PR generation describes the diff when project instructions try to redirect it. | +| [voice-cleanup](voice-cleanup/) | Whether optional dictation cleanup edits only the spoken text and preserves its meaning. | +| [test-signal](test-signal/) | Whether a cheap model running the test-signal check flags low-signal tests. | +| [workflow-authoring](workflow-authoring/) | Whether a model writes a working workflow file from the `t3-workflows` skill alone. | ## Run an eval diff --git a/evals/mcp-tool-use/cases/agent-feedback.ndjson b/evals/mcp-tool-use/cases/agent-feedback.ndjson new file mode 100644 index 0000000000000..df85866b2ed91 --- /dev/null +++ b/evals/mcp-tool-use/cases/agent-feedback.ndjson @@ -0,0 +1,18 @@ +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-12"}, "id": "feedback-on-reports-workaround", "kind": "bad", "pattern": "works around a failing T3 tool without reporting it", "experience": "With agent feedback on, t3_thread_read returned no items for a completed thread, the agent fell back to `t3 thread show`, and nobody heard about it.", "rule": "Agent feedback is on and a T3 tool failed, so the agent falls back and reports it with t3_feedback.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "priorTurns": [{"role": "user", "text": "What did the docs audit thread conclude? Its id is 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30. Summarize it for me."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "view": "activity", "limit": 20}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "Bash", "input": {"command": "t3 thread show 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": "Docs audit (completed)\n\nassistant: Audit done. docs/user/remote.md has 3 broken links (lines 12, 40, 88). docs/user/mobile.md still shows the old pairing command. I opened no PR."}]}], "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}}, "prompt": "", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_read"}, "success": true}], "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "Resumes right after the workaround succeeded."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-12"}, "id": "feedback-on-project-failure-guard", "kind": "guard", "pattern": "reports problems outside T3 Code", "experience": "With agent feedback on, a project test failure and a gh auth error are the user's own problems, not T3 Code's.", "rule": "Only T3 Code problems are reported: never the user's code or other tools.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "docs/fix-links", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Fix the failing link test and open a PR for this branch."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm test"}, "result": "FAIL src/links.test.ts > resolves relative links\nAssertionError: expected '/docs/a' to be '/docs/a/'\nExit code 1"}, {"tool": "Edit", "input": {"file_path": "/home/user/acme/app/src/links.ts", "old_string": "return path;", "new_string": "return path.endsWith('/') ? path : `${path}/`;"}, "result": "The file /home/user/acme/app/src/links.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "pnpm test"}, "result": "Test Files 12 passed (12)\n Tests 148 passed (148)"}, {"tool": "Bash", "input": {"command": "git commit -am 'fix: keep trailing slash on relative links' && gh pr create --fill"}, "result": "[docs/fix-links 3e1f0a2] fix: keep trailing slash on relative links\n 1 file changed, 1 insertion(+), 1 deletion(-)\nHTTP 401: Bad credentials (https://api.github.com/graphql)\nTry authenticating with: gh auth login\nExit code 1"}, {"tool": "Bash", "input": {"command": "git push -u origin docs/fix-links"}, "result": "remote: Create a pull request for 'docs/fix-links' on GitHub by visiting:\nremote: https://github.com/acme/app/pull/new/docs/fix-links\nbranch 'docs/fix-links' set up to track 'origin/docs/fix-links'."}]}]}, "prompt": "", "maxSteps": 6, "expect": {"callsMustNot": [{"tool": "t3_feedback"}, {"tool": "t3_environment_preferences_update"}]}, "notes": "Resumes after the push. The gh failure and the test failure are not T3 Code's."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Two of five agents asked to send T3 feedback declined it in real threads."}, "id": "feedback-on-user-asks-tool-gap", "kind": "bad", "pattern": "declines to send feedback the user asked for", "experience": "Mid-task, the user asked the agent to tell the T3 team about a T3 tool gap, and the agent said it could only report T3 tool failures.", "rule": "When the user asks to send feedback to the T3 team, the agent sends one report marked userRequested.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Find the thread that worked on the docs/fix-links branch."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_list", "input": {"titleContains": "links"}, "result": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}], "text": "t3_thread_list has no branch filter, so I searched titles for \"links\". The thread on docs/fix-links is \"Fix relative links\" (5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30)."}], "mocks": {"t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "link": "", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Thanks. t3_thread_list really should let you filter by branch. Please tell the T3 team about that, then summarize what that thread changed.", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_list", "userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}}, "notes": "The user asks in the same message as more work. The thread tools are mocked so the follow-up finds the thread it expects."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Two of five agents asked to send T3 feedback declined it in real threads."}, "id": "feedback-on-user-asks-conversation", "kind": "bad", "pattern": "declines feedback about how the conversation went", "experience": "The user asked the agent to send the T3 team feedback that the session went badly, and the agent said agent feedback only covers T3 tool problems.", "rule": "Feedback the user asks for can be about anything in T3 Code; it uses subject general and leaves out the user's code and paths.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "docs/fix-links", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Fix the trailing slash bug in src/links.ts. Don't ask me anything, just make the fix and run the tests."}, {"role": "assistant", "text": "I found the bug in /home/user/acme/app/src/links.ts: relative links drop their trailing slash. Should I change `return path;` to keep it?"}, {"role": "user", "text": "Yes. I said just do it."}, {"role": "assistant", "toolCalls": [{"tool": "Edit", "input": {"file_path": "/home/user/acme/app/src/links.ts", "old_string": "return path;", "new_string": "return path.endsWith('/') ? path : `${path}/`;"}, "result": "The file /home/user/acme/app/src/links.ts has been updated successfully."}], "text": "Edited src/links.ts. Do you want me to run the tests now?"}, {"role": "user", "text": "Yes, run them."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm test"}, "result": "Test Files 12 passed (12)\n Tests 148 passed (148)"}], "text": "All 148 tests pass. Should I commit this?"}]}, "prompt": "Honestly this went badly. I told you up front not to ask me anything and you stopped for confirmation three times. Please send that to the T3 team as feedback.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "general", "userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"expected": "~/home/user"}}, {"tool": "t3_feedback", "args": {"expected": "~links.ts"}}, {"tool": "t3_feedback", "args": {"expected": "~endsWith"}}, {"tool": "t3_feedback", "args": {"actual": "~/home/user"}}, {"tool": "t3_feedback", "args": {"actual": "~links.ts"}}, {"tool": "t3_feedback", "args": {"actual": "~endsWith"}}, {"tool": "t3_feedback", "args": {"workaround": "~/home/user"}}, {"tool": "t3_feedback", "args": {"workaround": "~links.ts"}}, {"tool": "t3_feedback", "args": {"workaround": "~endsWith"}}]}, "notes": "About the agent's conduct in T3 Code, not one tool. The report must not carry the file path or code."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-midtask-search", "kind": "bad", "pattern": "a T3 tool fails mid-task and the agent moves on without reporting", "experience": "t3_thread_search failed with an internal error while the agent was gathering context for a refactor; it found the thread another way and went straight on with the refactor.", "rule": "In automatic mode, a T3 tool failure the agent worked around is reported once, even when more work follows.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Check what the auth refactor thread decided about session tokens, then rename getSession to readSession across src/, run the tests, and commit."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_search", "input": {"query": "session tokens"}, "result": {"code": "orchestration_error", "message": "Thread search failed: SQLITE_ERROR: no such column: rank"}}, {"tool": "t3_thread_list", "input": {"titleContains": "auth"}, "result": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed", "branch": "refactor/auth"}], "nextCursor": null}}, {"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "How should we store session tokens?"}, {"position": 2, "createdBy": "assistant", "text": "Decision: session tokens live in an httpOnly cookie, never localStorage. getSession reads the cookie."}], "nextPosition": null, "hasMore": false}}, {"tool": "Bash", "input": {"command": "grep -rn getSession src/"}, "result": "src/auth/session.ts:4:export function getSession(req: Request) {\nsrc/routes/me.ts:2:import { getSession } from '../auth/session';\nsrc/routes/me.ts:7: const session = getSession(req);"}]}], "mocks": {"t3_thread_search": {"code": "orchestration_error", "message": "Thread search failed: SQLITE_ERROR: no such column: rank"}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed", "branch": "refactor/auth"}], "nextCursor": null}, "t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "How should we store session tokens?"}, {"position": 2, "createdBy": "assistant", "text": "Decision: session tokens live in an httpOnly cookie, never localStorage. getSession reads the cookie."}], "nextPosition": null, "hasMore": false}}}, "prompt": "", "maxSteps": 12, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_search"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "Resumes after the workaround, with the rename, tests and commit still to do. T3's thread tools answer as they did."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-wrong-result", "kind": "bad", "pattern": "a T3 tool returns a wrong result and the agent trusts git instead without reporting", "experience": "t3_worktree_status said the thread had no worktree while git showed the agent working in one; the agent used git's answer and said nothing.", "rule": "In automatic mode, a T3 tool that returns a wrong result, not only an error, is reported once.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "feat/search", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Hand this work off to the main checkout so I can test it there."}, {"role": "assistant", "toolCalls": [{"tool": "t3_worktree_status", "input": {}, "result": {"attached": false, "path": null, "branch": null, "projectRoot": "/home/user/acme/app", "startFromOrigin": true}}, {"tool": "Bash", "input": {"command": "pwd && git rev-parse --show-toplevel && git worktree list"}, "result": "/home/user/.t3/worktrees/app/feat-search\n/home/user/.t3/worktrees/app/feat-search\n/home/user/acme/app 3e1f0a2 [main]\n/home/user/.t3/worktrees/app/feat-search 9c4d2b1 [feat/search]"}], "text": "t3_worktree_status says this thread has no worktree, but git shows I'm in /home/user/.t3/worktrees/app/feat-search on feat/search. I'll go by git."}], "mocks": {"t3_worktree_handoff": {"ok": true, "from": "worktree", "to": "local", "branch": "feat/search"}, "t3_worktree_status": {"attached": false, "path": null, "branch": null, "projectRoot": "/home/user/acme/app", "startFromOrigin": true}}}, "prompt": "Ok, go ahead with the handoff.", "maxSteps": 12, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_worktree_status"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "The user's message is about the handoff, not about feedback."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-user-corrects", "kind": "bad", "pattern": "the user corrects the agent about T3 Code and nothing is reported", "experience": "The agent told the user it could not message another thread; the user pointed it at t3_thread_send.", "rule": "In automatic mode, when the user corrects the agent about how T3 Code works, the agent reports it once, without marking it user-requested.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Send this summary to the Release notes thread: search now ranks exact title matches first."}, {"role": "assistant", "text": "I can't post into another T3 thread from here. Here is the text so you can paste it there: \"Search now ranks exact title matches first.\""}], "mocks": {"t3_thread_send": {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "delivery": "started", "link": ""}, "t3_thread_read": {"thread": {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Release notes", "status": "idle"}, "items": [{"position": 1, "createdBy": "user", "text": "Collect release notes for 1.9 here."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Release notes", "status": "idle"}], "nextCursor": null}, "t3_thread_search": {"matches": [{"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Release notes", "status": "idle"}]}}}, "prompt": "You can, T3 Code has t3_thread_send for that. The Release notes thread id is 8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b. Send it.", "maxSteps": 10, "expect": {"calls": [{"tool": "t3_thread_send", "success": true}, {"tool": "t3_feedback", "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "The user corrects the agent but does not ask for feedback."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-missing-capability", "kind": "bad", "pattern": "the agent finds a T3 capability missing and only tells the user", "experience": "Asked for the thread's token usage, the agent found no T3 tool that reports it and told the user so.", "rule": "In automatic mode, a capability the agent looked for in T3 Code and could not find is reported once as missing_capability.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "How many tokens has this thread used so far?"}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_read", "input": {}, "result": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Search ranking", "status": "running"}, "items": [{"position": 1, "createdBy": "user", "text": "How many tokens has this thread used so far?"}], "nextPosition": null, "hasMore": false}}, {"tool": "t3_environment_read", "input": {}, "result": {"environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "label": "Workstation", "version": "1.9.0", "providers": [{"driver": "codex", "status": "ready"}]}}]}], "mocks": {"t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Search ranking", "status": "running"}, "items": [{"position": 1, "createdBy": "user", "text": "How many tokens has this thread used so far?"}], "nextPosition": null, "hasMore": false}, "t3_environment_read": {"environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "label": "Workstation", "version": "1.9.0", "providers": [{"driver": "codex", "status": "ready"}]}}}, "prompt": "", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"kind": "missing_capability"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "Resumes after both reads came back without usage."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-other-mcp-guard", "kind": "guard", "pattern": "reports another MCP server's failure as T3 feedback", "experience": "A Linear MCP tool failed and the agent used the GitHub CLI instead. That is not a T3 Code problem.", "rule": "Only T3 Code problems are reported: never other tools or MCP servers.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "fix/search-ranking", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Read issue ENG-142 and open a branch for it."}, {"role": "assistant", "toolCalls": [{"tool": "mcp__linear__get_issue", "input": {"id": "ENG-142"}, "result": {"error": "Linear API error: 502 Bad Gateway"}}, {"tool": "Bash", "input": {"command": "gh issue view 142 --repo acme/app"}, "result": "Search results show stale titles #142\nopen acme/app\nExact title matches should rank above partial ones."}, {"tool": "Bash", "input": {"command": "git switch -c fix/search-ranking"}, "result": "Switched to a new branch 'fix/search-ranking'"}]}], "mocks": {"read_issue": {"url": "https://linear.app/acme/issue/ENG-142/search-results-show-stale-titles", "displayKey": "ENG-142", "title": "Search results show stale titles", "state": "open", "body": "Exact title matches should rank above partial ones."}, "list_issues": {"issues": [{"url": "https://linear.app/acme/issue/ENG-142/search-results-show-stale-titles", "displayKey": "ENG-142", "title": "Search results show stale titles", "state": "open"}], "nextCursors": {}, "errors": []}}}, "prompt": "", "maxSteps": 6, "expect": {"callsMustNot": [{"tool": "t3_feedback"}]}, "notes": "Resumes after the fallback. The Linear failure belongs to another MCP server; T3's own issue tools answer normally."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Gabriel: agent feedback gets Off, When I ask, and Automatic modes, and requested reports can carry the conversation."}, "id": "feedback-on-request-no-unprompted", "kind": "guard", "pattern": "reports unprompted while agent feedback only allows requested reports", "experience": "With agent feedback set to When I ask, a T3 tool failed and the agent fell back; nobody asked for a report.", "rule": "In When I ask mode, the agent sends no report the user did not ask for.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "priorTurns": [{"role": "user", "text": "What did the docs audit thread conclude? Its id is 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30. Summarize it for me."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "view": "activity", "limit": 20}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "Bash", "input": {"command": "t3 thread show 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": "Docs audit (completed)\n\nassistant: Audit done. docs/user/remote.md has 3 broken links (lines 12, 40, 88). docs/user/mobile.md still shows the old pairing command. I opened no PR."}]}], "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "on-request"}}, "prompt": "", "maxSteps": 8, "expect": {"callsMustNot": [{"tool": "t3_feedback"}]}, "notes": "The workaround case in When I ask mode."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Gabriel: agent feedback gets Off, When I ask, and Automatic modes, and requested reports can carry the conversation."}, "id": "feedback-on-request-user-asks", "kind": "bad", "pattern": "declines to send feedback the user asked for", "experience": "Mid-task, the user asked the agent to tell the T3 team about a T3 tool gap, and the agent said it could only report T3 tool failures.", "rule": "In When I ask mode, the agent still sends the report the user asks for, marked userRequested.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "on-request"}, "priorTurns": [{"role": "user", "text": "Find the thread that worked on the docs/fix-links branch."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_list", "input": {"titleContains": "links"}, "result": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}], "text": "t3_thread_list has no branch filter, so I searched titles for \"links\". The thread on docs/fix-links is \"Fix relative links\" (5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30)."}], "mocks": {"t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "link": "", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Thanks. t3_thread_list really should let you filter by branch. Please tell the T3 team about that, then summarize what that thread changed.", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_list", "userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}}, "notes": "The tool-gap request in When I ask mode."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-19", "finding": "Julius: the card no longer blocks the turn, and the user, not the agent, chooses in the card whether to include the conversation."}, "id": "feedback-user-asks-include-conversation", "kind": "bad", "pattern": "pastes the conversation into the report, or claims it was included", "experience": "The user asked the agent to send feedback about the session and to include the conversation so the T3 team could see it.", "rule": "When the user asks to include the conversation, the agent sends one report with userRequested, leaves the conversation out of its fields, and leaves the choice to the card.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "docs/fix-links", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Fix the trailing slash bug in src/links.ts. Don't ask me anything, just make the fix and run the tests."}, {"role": "assistant", "text": "I found the bug in /home/user/acme/app/src/links.ts: relative links drop their trailing slash. Should I change `return path;` to keep it?"}, {"role": "user", "text": "Yes. I said just do it."}, {"role": "assistant", "toolCalls": [{"tool": "Edit", "input": {"file_path": "/home/user/acme/app/src/links.ts", "old_string": "return path;", "new_string": "return path.endsWith('/') ? path : `${path}/`;"}, "result": "The file /home/user/acme/app/src/links.ts has been updated successfully."}], "text": "Edited src/links.ts. Do you want me to run the tests now?"}, {"role": "user", "text": "Yes, run them."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm test"}, "result": "Test Files 12 passed (12)\n Tests 148 passed (148)"}], "text": "All 148 tests pass. Should I commit this?"}]}, "prompt": "This went badly: I told you not to ask me anything and you stopped for confirmation three times. Send that to the T3 team, and include our conversation so they can see what happened.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"expected": "~/home/user"}}, {"tool": "t3_feedback", "args": {"expected": "~links.ts"}}, {"tool": "t3_feedback", "args": {"expected": "~endsWith"}}, {"tool": "t3_feedback", "args": {"actual": "~/home/user"}}, {"tool": "t3_feedback", "args": {"actual": "~links.ts"}}, {"tool": "t3_feedback", "args": {"actual": "~endsWith"}}, {"tool": "t3_feedback", "args": {"workaround": "~/home/user"}}, {"tool": "t3_feedback", "args": {"workaround": "~links.ts"}}, {"tool": "t3_feedback", "args": {"workaround": "~endsWith"}}, {"tool": "t3_feedback", "args": {"expected": "~don't ask me anything"}}, {"tool": "t3_feedback", "args": {"expected": "~I said just do it"}}, {"tool": "t3_feedback", "args": {"actual": "~don't ask me anything"}}, {"tool": "t3_feedback", "args": {"actual": "~I said just do it"}}, {"tool": "t3_feedback", "args": {"workaround": "~don't ask me anything"}}, {"tool": "t3_feedback", "args": {"workaround": "~I said just do it"}}], "textMustNot": ["\\b(?:included|attached|added) (?:the |our |your )?(?:conversation|chat|transcript)\\b", "\\b(?:[Cc]onversation|[Tt]ranscript) (?:is|was|has been) (?:included|attached)\\b", "\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "t3_thread_list really should let you filter by branch. Please tell the T3 team about that.", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}, "shellMustNot": ["\\bt3\\s+feedback\\b"], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Did the T3 team get it?", "maxSteps": 8, "expect": {"callsMustNot": [{"tool": "t3_feedback"}], "shellMustNot": ["\\bt3\\s+feedback\\b"], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "About finding that thread two turns ago: t3_thread_list made you guess from titles. Report that to the T3 team.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true, "turns": ">=3"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"turns": ">=5"}}], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Send the T3 team a feature request: thread search should be able to filter by branch.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true, "turns": 1}, "success": true}], "maxCalls": {"t3_feedback": 1}, "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Make it cover the last four turns instead, so they see the work before it too.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true, "turns": ">=4"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"turns": ">=6"}}], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(? 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/mcp-tool-use/cases/issues.ndjson b/evals/mcp-tool-use/cases/issues.ndjson index b3c33cef640e9..16967ba5e17db 100644 --- a/evals/mcp-tool-use/cases/issues.ndjson +++ b/evals/mcp-tool-use/cases/issues.ndjson @@ -1,2 +1,4 @@ {"id":"work-on-issue-links-thread","area":"issues","kind":"bad","pattern":"Agent takes on a tracked issue without linking it to the thread","experience":"Agents linked pull requests but often left the issues they were working on unlinked.","privacy":"commit-safe","setup":{"role":"top","mocks":{"link_issue":{"projectId":"app","tracker":"github","host":"github.com","scope":"acme/app","key":"42","url":"https://github.com/acme/app/issues/42","alreadyLinked":false}},"world":{"repo":"acme/app","files":{"src/label.ts":"export const label = 'Setings';"},"issues":[{"url":"https://github.com/acme/app/issues/42","number":42,"title":"Typo in Settings label","body":"The Settings label says Setings.","state":"open"}],"pages":{"https://github.com/acme/app/issues/42":"Typo in Settings label\nThe Settings label says Setings."}},"context":"The current thread ID is issue-work-thread. Its project ID is app, configured for the GitHub repository acme/app."},"prompt":"Take on https://github.com/acme/app/issues/42. Investigate the Settings label typo, which says Setings, and propose the smallest fix.","expect":{"calls":[{"tool":"link_issue","argsAnyOf":[{"url":"https://github.com/acme/app/issues/42","threadId":null},{"url":"https://github.com/acme/app/issues/42","threadId":"issue-work-thread"},{"key":"42","url":null,"projectId":null,"threadId":null},{"key":"42","url":null,"projectId":null,"threadId":"issue-work-thread"},{"key":"42","url":null,"projectId":"app","threadId":null},{"key":"42","url":null,"projectId":"app","threadId":"issue-work-thread"},{"url":"https://github.com/acme/app/issues/42/","threadId":null},{"url":"https://github.com/acme/app/issues/42/","threadId":"issue-work-thread"}],"success":true}],"finalTextMust":["Setings","Settings"]},"source":{"pr":"https://github.com/pingdotgg/t3code/pull/38356"}} {"id":"read-only-issue-stays-unlinked","area":"issues","kind":"control","pattern":"Read-only issue lookup leaves thread links alone","experience":"An issue used for reference does not belong in the thread's work links.","privacy":"commit-safe","setup":{"role":"top","mocks":{"read_issue":{"url":"https://github.com/acme/app/issues/42","title":"Typo in Settings label","body":"The Settings label says Setings."}},"world":{"repo":"acme/app","issues":[{"url":"https://github.com/acme/app/issues/42","number":42,"title":"Typo in Settings label","body":"The Settings label says Setings.","state":"open"}],"pages":{"https://github.com/acme/app/issues/42":"Typo in Settings label\nThe Settings label says Setings."}}},"prompt":"Summarize https://github.com/acme/app/issues/42 so I can decide whether to take it on.","expect":{"notCalls":["link_issue","unlink_issue","create_issue","comment_on_issue","set_issue_state"],"finalTextMust":["Setings","Settings"]},"source":{"pr":"https://github.com/pingdotgg/t3code/pull/38356"}} +{"id":"create-issue-in-named-team","area":"issues","kind":"bad","pattern":"Agent asked to file in a bound team that is not the project's default","experience":"A project bound to several Linear teams filed every agent-created issue in its default team, even when the user named another bound team.","privacy":"commit-safe","setup":{"role":"top","mocks":{"create_issue":{"projectId":"app","tracker":"linear","host":"linear.app","scope":"OPS","key":"OPS-12","url":"https://linear.app/acme/issue/OPS-12","displayKey":"OPS-12"}},"world":{"repo":"acme/app","files":{"scripts/backup.sh":"#!/bin/sh\n# nightly backup\n"}},"context":"The current thread ID is issue-thread. Its project ID is app, for the GitHub repository acme/app. The project is also bound to the Linear teams ENG (its default) and OPS."},"prompt":"File an issue in our OPS Linear team: the nightly backup job ran twice on Nov 20. No need to investigate, just file it.","expect":{"calls":[{"tool":"create_issue","args":{"scope":"re:^\\s*[Oo][Pp][Ss]\\s*$"},"success":true}],"maxCalls":{"create_issue":1}},"source":{"pr":"https://github.com/pingdotgg/t3code/pull/40023"}} +{"id":"create-issue-default-team","area":"issues","kind":"control","pattern":"Agent files an issue without a team named","experience":"With no team named, an issue belongs in the project's default team.","privacy":"commit-safe","setup":{"role":"top","mocks":{"create_issue":{"projectId":"app","tracker":"linear","host":"linear.app","scope":"ENG","key":"ENG-31","url":"https://linear.app/acme/issue/ENG-31","displayKey":"ENG-31"}},"world":{"repo":"acme/app","files":{"src/label.ts":"export const label = 'Setings';"}},"context":"The current thread ID is issue-thread. Its project ID is app, for the GitHub repository acme/app. The project is also bound to the Linear teams ENG (its default) and OPS."},"prompt":"File an issue: the Settings label in the app says Setings. No need to fix it, just file it.","expect":{"calls":[{"tool":"create_issue","argsAnyOf":[{"scope":null},{"scope":"re:^\\s*[Ee][Nn][Gg]\\s*$"}],"success":true}],"maxCalls":{"create_issue":1}},"source":{"pr":"https://github.com/pingdotgg/t3code/pull/40023"}} diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index f29e9117a8690..817b916ebe1a6 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -31,6 +31,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schedule from "effect/Schedule"; +import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import { Tool } from "effect/ai"; @@ -56,6 +57,15 @@ import { makeSideChatContext } from "../../apps/server/src/orchestration-v2/Cont import { withInlineContext } from "../../apps/server/src/orchestration-v2/ContextHandoffDelivery.ts"; import { AttachmentToolkit } from "../../apps/server/src/mcp/toolkits/attachment/tools.ts"; import { DeviceToolkit } from "../../apps/server/src/mcp/toolkits/device/tools.ts"; +import { FeedbackToolkit } from "../../apps/server/src/mcp/toolkits/feedback/tools.ts"; +import { + FEEDBACK_AWAITING_APPROVAL_NOTE, + FEEDBACK_SUBJECT_MESSAGE, + FeedbackInput, + FeedbackNotRequestedError, + resolveFeedbackSubject, +} from "../../apps/server/src/feedback/FeedbackReport.ts"; +import { scrubFeedback } from "../../apps/server/src/feedback/scrubFeedback.ts"; import { EnvironmentToolkit } from "../../apps/server/src/mcp/toolkits/environment/tools.ts"; import { HtmlToolkit } from "../../apps/server/src/mcp/toolkits/html/tools.ts"; import { IssuesToolkit } from "../../apps/server/src/mcp/toolkits/issues/tools.ts"; @@ -304,6 +314,8 @@ const McpToolUseWorld = Schema.StructWithRest( deviceAgentAccess: Schema.optional(Schema.Boolean), /** false: agent browser access is off. T3 denies every preview call and drops its browser text. */ browserAgentAccess: Schema.optional(Schema.Boolean), + /** The Agent feedback mode; absent is off. On, T3 lists its tools and its text has the mode's line. */ + agentFeedback: Schema.optional(Contracts.AgentFeedbackMode), /** Every capture reaches T3 with adb screencap's warning ahead of the PNG: T3 reports 0×0. */ deviceInvalidCapture: Schema.optional(Schema.Boolean), /** Devices another thread's agent-device session holds, by device id: that thread's id. */ @@ -491,6 +503,7 @@ const t3SourceTools: ReadonlyArray = [ ProjectToolkit, EnvironmentToolkit, ThemeToolkit, + FeedbackToolkit, PreviewControlsToolkit, WorktreeToolkit, PullRequestsToolkit, @@ -554,6 +567,8 @@ const pastedSecret = (name: string, input: Readonly>) => const hiddenFromSubagents = enabledWhen(McpInvocationContext.hiddenFromSubagents); // The Linked environments beta starts off, and T3 lists its tools only while it is on. const hiddenWhileLinksOff = enabledWhen(McpInvocationContext.hiddenWhileLinksOff); +// Agent feedback starts off, and T3 lists its tools only while it is on. +const hiddenWhileFeedbackOff = enabledWhen(McpInvocationContext.hiddenWhileFeedbackOff); // T3 lists PR and CI tools only to a thread whose project is on a forge it reads. const hiddenWithoutForge = enabledWhen(McpInvocationContext.hiddenWithoutForge); /** @@ -574,12 +589,14 @@ const visibleT3Tools = (options: { readonly subagent?: boolean; readonly links?: boolean; readonly forge?: boolean; + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }) => t3Tools.filter( (tool) => !(options.arm === "raw" && forgeToolNames.has(tool.name)) && (options.links === true || !hiddenWhileLinksOff.has(tool.name)) && + ((options.agentFeedback ?? "off") !== "off" || !hiddenWhileFeedbackOff.has(tool.name)) && (options.forge !== false || !hiddenWithoutForge.has(tool.name)) && !(options.subagent === true && hiddenFromSubagents.has(tool.name)), ); @@ -589,7 +606,12 @@ const visibleT3Tools = (options: { * `browser` say whether the thread holds the `device` and `preview` capabilities, as agent device * and browser access decide. */ -const claudeQueryOptions = (model: Model, device = true, browser = true) => { +const claudeQueryOptions = ( + model: Model, + device = true, + browser = true, + agentFeedback: Contracts.AgentFeedbackMode = "off", +) => { // Refs whose text follows a capability read its flag; older ones ignore it. const input: Parameters[0] & { readonly deviceToolsAvailable?: boolean; @@ -600,6 +622,7 @@ const claudeQueryOptions = (model: Model, device = true, browser = true) => { resume: false, cwd: null, mcpServers: { "t3-code": { type: "http", url: "http://127.0.0.1/mcp" } }, + agentFeedback, deviceToolsAvailable: device, browserToolsAvailable: browser, }; @@ -607,8 +630,13 @@ const claudeQueryOptions = (model: Model, device = true, browser = true) => { }; /** Text T3 appends to Claude Code's system prompt. Delegated children get the same text. */ -export const t3SystemAppend = (model: Model, device = true, browser = true) => { - const { systemPrompt } = claudeQueryOptions(model, device, browser); +export const t3SystemAppend = ( + model: Model, + device = true, + browser = true, + agentFeedback: Contracts.AgentFeedbackMode = "off", +) => { + const { systemPrompt } = claudeQueryOptions(model, device, browser, agentFeedback); if (isRecord(systemPrompt) && systemPrompt.type === "preset" && systemPrompt.append) { return systemPrompt.append; } @@ -698,6 +726,8 @@ export const buildBase = ( readonly deviceAccess?: boolean; /** false: the thread has no agent browser access, so T3's text leaves the browser out. */ readonly browserAccess?: boolean; + /** The Agent feedback mode: on, T3 lists its tools and its text includes the mode's line. */ + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }, ) => { @@ -724,7 +754,10 @@ export const buildBase = ( const { model } = options; const append = options.nativeSubagent ? "" - : forArm(t3SystemAppend(model, options.deviceAccess, options.browserAccess), options.arm); + : forArm( + t3SystemAppend(model, options.deviceAccess, options.browserAccess, options.agentFeedback), + options.arm, + ); const modelLine = `You are powered by the model named ${MODELS[model]}. The exact model ID is ${model}.`; const joined = systemTexts.join("\n"); // The capture's home directory names its user. Cases use `/home/user` paths instead. @@ -794,6 +827,8 @@ const buildCodexBase = ( readonly deviceAccess?: boolean; /** false: the thread has no agent browser access, so T3's text leaves the browser out. */ readonly browserAccess?: boolean; + /** The Agent feedback mode: on, T3 lists its tools and its text includes the mode's line. */ + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }, ): Base => { @@ -829,7 +864,11 @@ const buildCodexBase = ( return [JSON.parse(clean(JSON.stringify(item))) as Block]; }); const context = buildCodexAdditionalContext( - { model: options.model, reasoningEffort: effort }, + { + model: options.model, + reasoningEffort: effort, + agentFeedback: options.agentFeedback ?? "off", + }, { browser: options.browserAccess ?? true, device: options.deviceAccess ?? true }, ); input.push( @@ -2101,6 +2140,8 @@ const savedSecretFile = ( } }; +const decodeFeedbackInput = Schema.decodeUnknownResult(FeedbackInput); + /** The result for one tool call. */ const FORGE_WRITE_TOOLS = new Set([ "pull_request_create", @@ -2257,6 +2298,39 @@ export const answerToolCall = Effect.fn("evaluateMcpToolUse.answerToolCall")(fun const refused = productRefusal(sample, name, input); if (refused !== undefined) return failed(refused); } + if (isT3Name(call.name) && name === "t3_feedback" && (mock === undefined || mock === "default")) { + const decoded = decodeFeedbackInput(input); + if (Result.isFailure(decoded)) return failed(decoded.failure.message); + const report = decoded.success; + // The same refusals as FeedbackService, in its order. + if (sample.testCase.setup.world?.agentFeedback === "on-request" && !report.userRequested) + return failed(new FeedbackNotRequestedError({ source: "mcp" }).message); + const subject = resolveFeedbackSubject( + report.subject, + t3SourceTools.map((tool) => tool.name), + ); + if (subject === undefined) return failed(FEEDBACK_SUBJECT_MESSAGE); + // T3 shows a requested report to the user in a card and answers at once. + if (report.userRequested) { + return toolResult(call.id, { + status: "awaiting_approval", + note: FEEDBACK_AWAITING_APPROVAL_NOTE, + }); + } + return toolResult(call.id, { + ...report, + subject, + trace: null, + expected: scrubFeedback(report.expected, []), + actual: scrubFeedback(report.actual, []), + workaround: scrubFeedback(report.workaround, []), + id: "019a7b3c-0000-7000-8000-000000000001", + threadId: "thread-1", + createdAt: `${base.environment.date ?? "2026-01-01"}T12:00:00.000Z`, + source: "mcp", + sent: true, + }); + } // A pasted secret is saved without a card, so a mocked card outcome does not apply. if (mock !== undefined && mock !== "default" && !pastedSecret(name, input)) { if (name === "request_secret") savedSecretFile(sample, input, mock); @@ -3217,6 +3291,7 @@ const main = Effect.gen(function* () { browserAccess: boolean, links: boolean, forge: boolean, + agentFeedback: Contracts.AgentFeedbackMode = "off", ): Effect.Effect => codex ? decodeCodexCapture(template).pipe( @@ -3230,6 +3305,7 @@ const main = Effect.gen(function* () { forge, deviceAccess, browserAccess, + agentFeedback, arm: flags.arm, }), ), @@ -3245,6 +3321,7 @@ const main = Effect.gen(function* () { forge, deviceAccess, browserAccess, + agentFeedback, arm: flags.arm, }); return role === "native-subagent" @@ -3256,18 +3333,19 @@ const main = Effect.gen(function* () { ); // Codex has no native subagents; its cases with that role run as top-level threads. const baseKey = ({ setup }: McpToolUseCase) => - `${codex && setup.role === "native-subagent" ? "top" : setup.role}:${setup.world?.deviceAgentAccess !== false}:${setup.world?.browserAgentAccess !== false}:${setup.linkedEnvironments === true}:${setup.forge !== false}`; + `${codex && setup.role === "native-subagent" ? "top" : setup.role}:${setup.world?.deviceAgentAccess !== false}:${setup.world?.browserAgentAccess !== false}:${setup.linkedEnvironments === true}:${setup.forge !== false}:${setup.world?.agentFeedback ?? "off"}`; const base = yield* buildFor("top", true, true, false, true); - const bases = new Map([["top:true:true:false:true", base]]); + const bases = new Map([["top:true:true:false:true:off", base]]); for (const testCase of selected) { const key = baseKey(testCase); if (bases.has(key)) continue; - const [role = "top", device, browser, links, forge] = key.split(":") as [ + const [role = "top", device, browser, links, forge, feedback] = key.split(":") as [ McpToolUseCase["setup"]["role"], string, string, string, string, + string, ]; bases.set( key, @@ -3277,6 +3355,7 @@ const main = Effect.gen(function* () { browser === "true", links === "true", forge === "true", + feedback as Contracts.AgentFeedbackMode, ), ); } diff --git a/evals/package.json b/evals/package.json index 245448ac4021c..21f022a680466 100644 --- a/evals/package.json +++ b/evals/package.json @@ -11,6 +11,7 @@ "pr-content": "node --env-file-if-exists=../.env pr-content/run.ts", "voice-cleanup": "node --env-file-if-exists=../.env voice-cleanup/run.ts", "test-signal": "node --env-file-if-exists=../.env test-signal/run.ts", + "workflow-authoring": "node --env-file-if-exists=../.env workflow-authoring/run.ts", "typecheck": "effect-tsgo tsrs --noEmit", "test": "vp test run --config ../vite.config.ts --dir ." }, 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/evals/workflow-authoring/README.md b/evals/workflow-authoring/README.md new file mode 100644 index 0000000000000..f93fb582e6933 --- /dev/null +++ b/evals/workflow-authoring/README.md @@ -0,0 +1,36 @@ +# Workflow authoring + +Checks that a model can write a working workflow definitions file from the +[`t3-workflows` skill](../../skills/t3-workflows/SKILL.md) alone. Run it when the skill, the author +API, or the way the server loads a definitions file changes. + +The model gets the skill's body and one task, and replies with a file. The grader loads that file +with the server's loader, registers it in the real engine on a throwaway database, and drives it +with a stand-in for agents: it starts runs, delivers webhooks, answers questions, restarts the +engine, and checks how each run ends. Nothing is judged by reading the code. + +## Run + +```sh +cd evals +pnpm workflow-authoring --out runs/baseline +pnpm workflow-authoring --out runs/shorter --skill /path/to/variant.md --baseline runs/baseline/results.ndjson +``` + +- Models go through the `vibeproxy` CLIProxyAPI provider in `~/.codex/config.toml`. Default models: + `gpt-6.1-terra` and `gpt-6-luna`. Pass `--model` once per model to change them. +- Flags: `--skill ` (a variant of the skill), `--case ` (repeatable), `--samples ` + (default 3), `--reasoning ` (default `low`), `--baseline `. +- Each answer is saved next to the results as `...ts`, and `summary.md` lists + every problem the grader found. +- Cost: proxy quota only, about 5,000 tokens per sample. + +The answers are code the grader runs. They come from a model that saw only the skill and the task, +but run this on a machine where that is acceptable. + +## Add a case + +Add an entry to `cases.ts`: the task as a person would give it, and one or more scenarios. A +scenario says what the stand-in agent answers and returns the problems it finds after driving the +file's workflows; none is a pass. Put a reference answer in `fixtures/.ts`, which +`run.test.ts` requires to pass, and a wrong answer when the case exists to catch one mistake. diff --git a/evals/workflow-authoring/cases.ts b/evals/workflow-authoring/cases.ts new file mode 100644 index 0000000000000..9353dd4d7c12d --- /dev/null +++ b/evals/workflow-authoring/cases.ts @@ -0,0 +1,270 @@ +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import type { Case, World } from "./grade.ts"; + +const defined = (world: World, name: string) => + world.definitions.find((definition) => definition.name === name); +const missing = (name: string) => [`No workflow named ${name} is defined.`]; + +const todos = [ + { file: "src/a.ts", line: 3, text: "handle the empty list" }, + { file: "src/b.ts", line: 9, text: "remove after the migration" }, +]; + +const SUCCEEDED = JSON.stringify({ status: "succeeded", service: "billing" }); +const FAILED = JSON.stringify({ status: "failed", service: "checkout-api" }); + +export const cases: ReadonlyArray = [ + { + id: "scheduled-agent-then-approval", + source: + "The dependency report in the skill: a schedule, typed agent data, a question, a continued thread.", + task: [ + "Write a workflow named `todo-sweep` that runs every weekday (Monday to Friday) at 09:00.", + "An agent in the project with id `proj-1` lists the TODO comments in the repository as data shaped `{ todos: [{ file: string, line: number, text: string }] }`, without changing files.", + "If there are none, the run ends there; that is not a failure.", + "Otherwise a person is asked whether to fix them, with the choices `fix` and `skip`, and the run waits at most one day for the answer.", + "On `fix`, the same agent thread fixes them. On `skip` or no answer, the run ends.", + ].join("\n"), + scenarios: [ + { + name: "nothing to do", + agent: () => ({ output: { todos: [] } }), + check: (world) => + world.server( + Effect.fn(function* (workflows) { + const definition = defined(world, "todo-sweep"); + if (definition === undefined) return missing("todo-sweep"); + const problems: Array = []; + const schedule = definition.triggers.flatMap((trigger) => + trigger.kind === "schedule" && trigger.schedule.type === "fixed_time" + ? [trigger.schedule] + : [], + )[0]; + if (schedule === undefined) { + problems.push("It has no time-of-day trigger."); + } else { + if (!/^0?9:00$/.test(schedule.timeOfDay)) { + problems.push(`It runs at ${schedule.timeOfDay}, not 09:00.`); + } + if ([...(schedule.weekdays ?? [])].toSorted().join() !== "1,2,3,4,5") { + problems.push("It does not run on exactly Monday to Friday."); + } + } + const { runId } = yield* workflows.start( + "todo-sweep", + { scheduledAt: "2026-01-05T09:00:00.000Z" }, + { idempotencyKey: "a" }, + ); + const ended = yield* world.reaches( + workflows, + runId, + "stopped", + "completed", + "paused", + ); + if (Option.isNone(ended)) return [...problems, "The run never ended."]; + if (ended.value.status === "paused") { + problems.push(`The run paused: ${ended.value.detail}`); + } + if (world.turns.length !== 1) { + problems.push(`It asked for ${world.turns.length} agent turns, not 1.`); + } + if (world.turns[0]?.project !== "proj-1") { + problems.push("The agent did not start in proj-1."); + } + if ((yield* workflows.questions).length > 0) { + problems.push("It asked a person although there was nothing to fix."); + } + return problems; + }), + ), + }, + { + name: "approved", + agent: (turn) => + turn.outputSchema === undefined ? { reply: "Fixed." } : { output: { todos } }, + check: (world) => + world.server( + Effect.fn(function* (workflows) { + if (defined(world, "todo-sweep") === undefined) return missing("todo-sweep"); + const { runId } = yield* workflows.start( + "todo-sweep", + { scheduledAt: "2026-01-05T09:00:00.000Z" }, + { idempotencyKey: "b" }, + ); + const question = yield* world.asks(workflows, runId); + if (Option.isNone(question)) return ["It did not ask a person whether to fix them."]; + yield* workflows.signal( + { runId, wait: question.value }, + { choice: "fix" }, + { id: "answer-1" }, + ); + const ended = yield* world.reaches( + workflows, + runId, + "completed", + "paused", + "stopped", + ); + if (Option.isNone(ended) || ended.value.status !== "completed") { + return [ + `After "fix" the run did not complete: ${Option.getOrUndefined(ended)?.status ?? "never ended"}`, + ]; + } + const [first, second] = world.turns; + if (world.turns.length !== 2) { + return [`It asked for ${world.turns.length} agent turns, not 2.`]; + } + return second?.thread === `thread-${first?.key}` + ? [] + : ["The fix did not continue the first agent's thread."]; + }), + ), + }, + ], + }, + { + id: "webhook-filter-and-dedupe", + source: + "Scheduled-task webhooks keep filters and replay keys as settings; a workflow has to write both.", + task: [ + "Write a workflow named `deploy-watch` started by a webhook named `deploys`.", + 'The request body is JSON shaped `{ "status": string, "service": string }`.', + "A sender may deliver the same event more than once; the header `x-delivery-id` identifies an event, and one event must be one run.", + "Anything whose status is not `failed` is ignored: the run ends there, which is not a failure.", + "For a failed deploy, an agent in the project with id `proj-1` investigates. Its brief must name the service.", + ].join("\n"), + scenarios: [ + { + name: "deliveries", + agent: () => ({ reply: "The migration timed out." }), + check: (world) => + world.server( + Effect.fn(function* (workflows) { + if (defined(world, "deploy-watch") === undefined) return missing("deploy-watch"); + const hook = (yield* workflows.hooks).find((entry) => entry.name === "deploys"); + if (hook === undefined) return ["It has no webhook named deploys."]; + const [hookId, token] = hook.path.split("/").slice(-2).map(decodeURIComponent); + const deliver = (delivery: string, body: string) => + workflows + .deliver({ + hookId: hookId!, + token: token!, + request: { + method: "POST", + headers: { "content-type": "application/json", "x-delivery-id": delivery }, + query: "", + body, + }, + }) + .pipe(Effect.map(Option.getOrThrow)); + const problems: Array = []; + + const fine = yield* deliver("d1", SUCCEEDED); + const ignored = yield* world.reaches( + workflows, + fine.runId, + "skipped", + "stopped", + "completed", + "paused", + ); + if (Option.isNone(ignored) || ignored.value.status === "paused") { + problems.push("A deploy that did not fail left its run paused or unfinished."); + } + if (world.turns.length > 0) + problems.push("It started an agent for a deploy that did not fail."); + + const failed = yield* deliver("d2", FAILED); + const again = yield* deliver("d2", FAILED); + if (again.runId !== failed.runId) + problems.push("A redelivered event started a second run."); + const done = yield* world.reaches( + workflows, + failed.runId, + "completed", + "paused", + "stopped", + ); + if (Option.isNone(done) || done.value.status !== "completed") { + problems.push( + `A failed deploy's run did not complete: ${Option.getOrUndefined(done)?.detail ?? "never ended"}`, + ); + } + const turn = world.turns[0]; + if (turn === undefined) + return [...problems, "It started no agent for a failed deploy."]; + if (turn.project !== "proj-1") problems.push("The agent did not start in proj-1."); + if (!turn.prompt.includes("checkout-api")) + problems.push("The brief does not name the service."); + return problems; + }), + ), + }, + ], + }, + { + id: "replay-keeps-what-it-read", + source: + "The replay rule: the body runs again after a wait, so a value read from the world outside a step changes under the run.", + task: [ + "Write a workflow named `stamp`, started by hand with the payload `{ label: string }`, that returns a string.", + "It reads the current time in milliseconds since the epoch, then waits for a signal named `go` whose value is a string.", + "When the signal arrives it returns `( + use: (workflows: Workflows.Workflows["Service"]) => Effect.Effect, + ) => Effect.Effect; + /** The run once it is in one of these states, or nothing after ten seconds. */ + readonly reaches: ( + workflows: Workflows.Workflows["Service"], + runId: string, + ...statuses: ReadonlyArray + ) => Effect.Effect>; + /** The name of the question the run asks a person, or nothing after ten seconds. */ + readonly asks: ( + workflows: Workflows.Workflows["Service"], + runId: string, + ) => Effect.Effect>; +} + +export interface Case { + readonly id: string; + readonly source: string; + /** What the model is asked to write. */ + readonly task: string; + /** What a fake agent answers. Each scenario of the case sets its own. */ + readonly scenarios: ReadonlyArray<{ + readonly name: string; + readonly agent: (turn: AgentTurnInput) => Partial; + /** The problems found. None is a pass. */ + readonly check: (world: World) => Effect.Effect, Workflows.WorkflowError>; + }>; +} + +// Across every grade in the process: a load under an address used before would get that module. +let lifetimes = 0; + +const world = Effect.fn("gradeWorkflow.world")(function* ( + file: string, + definitions: ReadonlyArray, + agent: (turn: AgentTurnInput) => Partial, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-eval-" }); + const database = NodeSqliteClient.layer({ filename: path.join(directory, "state.sqlite") }); + yield* Effect.provide(WorkflowsMigration, database); + const turns: Array = []; + const asked = new Map(); + const agents = WorkflowAgents.of({ + start: Effect.fn("gradeWorkflow.agents.start")(function* (input) { + if (!asked.has(input.key)) { + asked.set(input.key, input); + turns.push(input); + } + return yield* Effect.succeed({ + threadId: input.thread ?? `thread-${input.key}`, + turnId: input.key, + }); + }), + result: Effect.fn("gradeWorkflow.agents.result")(function* (turn) { + return yield* Effect.succeed({ + ending: "completed" as const, + detail: "", + reply: "", + ...agent(asked.get(turn.turnId)!), + }); + }), + // Every turn here has already completed, so there is nothing to stop. + interrupt: Effect.fn("gradeWorkflow.agents.interrupt")(function* () { + return yield* Effect.succeed("ended" as const); + }), + }); + const engine = (loaded: ReadonlyArray) => + WorkflowEngine.layer(loaded).pipe( + Layer.provide(Layer.succeed(WorkflowAgents, agents)), + Layer.provide(database), + Layer.provide(NodeCrypto.layer), + Layer.orDie, + ); + return { + definitions, + turns, + server: (use) => + loadDefinitions(file, ++lifetimes).pipe( + Effect.orDie, + Effect.provideService(Path.Path, path), + Effect.flatMap((loaded) => + Effect.scoped(Effect.provide(Effect.flatMap(Workflows.Workflows, use), engine(loaded))), + ), + ), + reaches: (workflows, runId, ...statuses) => + workflows + .waitFor(runId, (run) => statuses.includes(run.status)) + .pipe(Effect.timeoutOption("10 seconds")), + asks: (workflows, runId) => + workflows.watch.pipe( + Stream.filterMap((snapshot) => { + const question = snapshot.questions.find((asked) => asked.runId === runId); + return question === undefined ? Result.failVoid : Result.succeed(question.name); + }), + Stream.runHead, + Effect.timeoutOption("10 seconds"), + Effect.map(Option.flatten), + ), + } satisfies World; +}); + +const problemsWith = Effect.fn("gradeWorkflow.problemsWith")(function* (file: string, entry: Case) { + const loaded = yield* Effect.result(loadDefinitions(file)); + if (loaded._tag === "Failure") { + return [`The file does not load: ${String(loaded.failure.cause)}`]; + } + const problems: Array = []; + for (const scenario of entry.scenarios) { + const found = yield* world(file, loaded.success, scenario.agent).pipe( + Effect.flatMap(scenario.check), + Effect.scoped, + Effect.catch((error) => Effect.succeed([error.message])), + Effect.catchDefect((defect) => Effect.succeed([`It crashed: ${String(defect)}`])), + ); + problems.push(...found.map((problem) => `${scenario.name}: ${problem}`)); + } + return problems; +}); + +/** The problems with the workflow file at `file` as an answer to `entry`. None is a pass. */ +export const grade = (file: string, entry: Case): Promise> => + Effect.runPromise(Effect.provide(problemsWith(file, entry), NodeServices.layer)); diff --git a/evals/workflow-authoring/run.test.ts b/evals/workflow-authoring/run.test.ts new file mode 100644 index 0000000000000..104d56d38d77b --- /dev/null +++ b/evals/workflow-authoring/run.test.ts @@ -0,0 +1,37 @@ +// A test of an eval script, which works on plain file paths. +// @effect-diagnostics nodeBuiltinImport:off +import * as NodePath from "node:path"; + +import { expect, it } from "vite-plus/test"; + +import { cases } from "./cases.ts"; +import { grade } from "./grade.ts"; + +const fixture = (name: string) => NodePath.join(import.meta.dirname, "fixtures", `${name}.ts`); +const entry = (id: string) => cases.find((candidate) => candidate.id === id)!; + +it.each(cases.map((candidate) => candidate.id))("a correct answer to %s passes", async (id) => { + expect(await grade(fixture(id), entry(id))).toEqual([]); +}); + +it("a body that reads the clock outside a step fails the replay case", async () => { + expect( + await grade(fixture("replay-reads-outside-a-step"), entry("replay-keeps-what-it-read")), + ).toEqual([ + "restart while waiting: The time it returned was read again after the restart, not kept from the start.", + ]); +}); + +it("a body that keeps the time in a module variable fails the replay case", async () => { + expect( + await grade(fixture("replay-keeps-in-a-module"), entry("replay-keeps-what-it-read")), + ).toEqual([ + "restart while waiting: The time it returned was read again after the restart, not kept from the start.", + ]); +}); + +it("an answer to another task fails with the reason", async () => { + expect( + await grade(fixture("webhook-filter-and-dedupe"), entry("replay-keeps-what-it-read")), + ).toEqual(["restart while waiting: No workflow named stamp is defined."]); +}); diff --git a/evals/workflow-authoring/run.ts b/evals/workflow-authoring/run.ts new file mode 100644 index 0000000000000..2e2c66f7a5fff --- /dev/null +++ b/evals/workflow-authoring/run.ts @@ -0,0 +1,179 @@ +#!/usr/bin/env node +// An eval script, not server code: it reads and writes files directly. +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; +import * as NodeUtil from "node:util"; +import * as Effect from "effect/Effect"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; + +import { proxyConfig } from "../shared/proxy.ts"; +import { cases } from "./cases.ts"; +import { type Case, grade } from "./grade.ts"; + +const { values } = NodeUtil.parseArgs({ + options: { + out: { type: "string" }, + model: { type: "string", multiple: true }, + skill: { type: "string" }, + case: { type: "string", multiple: true }, + samples: { type: "string", default: "3" }, + reasoning: { type: "string", default: "low" }, + baseline: { type: "string" }, + }, +}); +if (!values.out) throw new Error("Use --out [--model ] [--skill ]."); +const outDirectory = values.out; +const models = values.model ?? ["gpt-6.1-terra", "gpt-6-luna"]; +const skillFile = + values.skill ?? NodePath.resolve(import.meta.dirname, "../../skills/t3-workflows/SKILL.md"); +// An agent is given the skill's body; the front matter only decides when it loads. +const skill = NodeFS.readFileSync(skillFile, "utf8") + .replace(/^---\n[\s\S]*?\n---\n/, "") + .trim(); +const selected = values.case ? cases.filter((entry) => values.case!.includes(entry.id)) : cases; +const proxy = proxyConfig(); + +const Row = Schema.Struct({ + model: Schema.String, + case: Schema.String, + sample: Schema.Number, + problems: Schema.Array(Schema.String), + tokens: Schema.Number, +}); +const encodeRow = Schema.encodeSync(Schema.fromJsonString(Row)); +const decodeRow = Schema.decodeUnknownSync(Schema.fromJsonString(Row)); +const decodeResponse = Schema.decodeUnknownSync( + Schema.fromJsonString( + Schema.Struct({ + output: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), + usage: Schema.optional(Schema.Struct({ total_tokens: Schema.optional(Schema.Number) })), + }), + ), +); + +const instructions = [ + "You write workflow definitions files for T3 Code. This is everything you know about them:", + "", + "", + skill, + "", + "", + "Reply with the complete definitions file in one ```ts code block and nothing else.", +].join("\n"); + +const sample = Effect.fn("evaluateWorkflowAuthoring.sample")(function* ( + entry: Case, + model: string, + index: number, +) { + const client = (yield* HttpClient.HttpClient).pipe( + HttpClient.retryTransient({ + retryOn: "errors-and-responses", + schedule: Schedule.exponential("2 seconds"), + times: 4, + }), + ); + const response = yield* HttpClientRequest.post(`${proxy.url}/responses`).pipe( + HttpClientRequest.setHeaders(proxy.headers), + HttpClientRequest.bodyJson({ + model, + instructions, + input: [{ role: "user", content: entry.task }], + reasoning: { effort: values.reasoning }, + store: false, + }), + Effect.flatMap(client.execute), + ); + const body = yield* response.text; + if (response.status !== 200) { + return yield* Effect.die(new Error(`Model API ${response.status}: ${body}`)); + } + const decoded = decodeResponse(body); + const reply = decoded.output + .filter((item) => item.type === "message") + .flatMap((item) => (item.content as Array<{ text?: string }>).map((part) => part.text ?? "")) + .join(""); + const code = /```(?:ts|typescript)?\n([\s\S]*?)```/.exec(reply)?.[1] ?? reply; + const file = NodePath.join(outDirectory, `${entry.id}.${model}.${index}.ts`); + NodeFS.writeFileSync(file, code); + const problems = yield* Effect.promise(() => grade(file, entry)); + return { + model, + case: entry.id, + sample: index, + problems, + tokens: decoded.usage?.total_tokens ?? 0, + }; +}); + +/** Half or more of a case's samples failing is the case failing. */ +const passes = (rows: ReadonlyArray, model: string, id: string) => { + const own = rows.filter((row) => row.model === model && row.case === id); + return own.length > 0 && own.filter((row) => row.problems.length > 0).length < own.length / 2; +}; + +NodeFS.mkdirSync(outDirectory, { recursive: true }); +const summary = await Effect.runPromise( + Effect.gen(function* () { + const count = Number(values.samples); + const rows = yield* Effect.forEach( + models.flatMap((model) => + selected.flatMap((entry) => + Array.from({ length: count }, (_, index) => ({ model, entry, index })), + ), + ), + ({ model, entry, index }) => + sample(entry, model, index).pipe( + Effect.catchDefect((defect) => + Effect.succeed({ + model, + case: entry.id, + sample: index, + problems: [`The sample did not run: ${String(defect)}`], + tokens: 0, + }), + ), + ), + // The grader starts an engine per scenario; a few at a time keeps their timings honest. + { concurrency: 3 }, + ); + NodeFS.writeFileSync( + NodePath.join(outDirectory, "results.ndjson"), + rows.map((row) => encodeRow(row)).join("\n") + "\n", + ); + const baseline = values.baseline + ? NodeFS.readFileSync(values.baseline, "utf8") + .trim() + .split("\n") + .map((line) => decodeRow(line)) + : undefined; + const words = skill.split(/\s+/).length; + const lines = [`skill ${skillFile}, ${words} words, ${count} samples per case`, ""]; + lines.push("| model | case | samples passed | verdict | baseline |", "|---|---|---|---|---|"); + for (const model of models) { + for (const entry of selected) { + const own = rows.filter((row) => row.model === model && row.case === entry.id); + const good = own.filter((row) => row.problems.length === 0).length; + const before = + baseline === undefined ? "" : passes(baseline, model, entry.id) ? "pass" : "fail"; + lines.push( + `| ${model} | ${entry.id} | ${good}/${own.length} | ${passes(rows, model, entry.id) ? "pass" : "FAIL"} | ${before} |`, + ); + } + } + const tokens = rows.reduce((sum, row) => sum + row.tokens, 0); + lines.push("", `${tokens} tokens`, "", "## Problems", ""); + for (const row of rows) { + for (const problem of row.problems) { + lines.push(`- ${row.model} ${row.case} #${row.sample}: ${problem}`); + } + } + const report = lines.join("\n") + "\n"; + NodeFS.writeFileSync(NodePath.join(outDirectory, "summary.md"), report); + return report; + }).pipe(Effect.provide(FetchHttpClient.layer)), +); +process.stdout.write(summary); 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/knip.jsonc b/knip.jsonc index 6382c0237f5e4..9f421f04522dd 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -17,6 +17,10 @@ "vite": { "entry": [".github/**/*.test.cjs"] }, "vitest": { "entry": [".github/**/*.test.cjs"] }, }, + "evals": { + // The grader loads these answers by path, as the server loads a definitions file. + "entry": ["workflow-authoring/fixtures/*.ts"], + }, "scripts": { // Knip loads its preprocessor through a CLI option; native verification and // worktree setup (from t3.json) run directly. release-desktop.yml bundles the diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 111ff15592952..1fb69467f7e1e 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -47,6 +47,10 @@ "types": "./src/contractLabels.ts", "default": "./src/contractLabels.ts" }, + "./workflows": { + "types": "./src/workflows.ts", + "default": "./src/workflows.ts" + }, "./locales": { "types": "./src/locales.ts", "default": "./src/locales.ts" @@ -107,6 +111,10 @@ "types": "./src/secretRequest.ts", "default": "./src/secretRequest.ts" }, + "./feedback-request": { + "types": "./src/feedbackRequest.ts", + "default": "./src/feedbackRequest.ts" + }, "./link-batch": { "types": "./src/linkBatch.ts", "default": "./src/linkBatch.ts" @@ -658,6 +666,10 @@ "./provider-instance-ids": { "types": "./src/providerInstanceIds.ts", "default": "./src/providerInstanceIds.ts" + }, + "./pull-request-references": { + "types": "./src/pullRequestReferences.ts", + "default": "./src/pullRequestReferences.ts" } }, "scripts": { @@ -684,16 +696,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/clock.test.ts b/packages/client-runtime/src/clock.test.ts index 1f45860addf7c..f26f830d5b88c 100644 --- a/packages/client-runtime/src/clock.test.ts +++ b/packages/client-runtime/src/clock.test.ts @@ -1,6 +1,12 @@ import { EnvironmentId } from "@t3tools/contracts"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { deadlineStore, recordServerClock, secondTick, toServerClock } from "./clock.ts"; +import { + deadlineStore, + observeServerTime, + recordServerClock, + secondTick, + toServerClock, +} from "./clock.ts"; describe("deadlineStore", () => { afterEach(() => { @@ -172,4 +178,24 @@ describe("server clock", () => { }); expect(toServerClock(environmentId, 12_345)).toBe(12_345); }); + + it("raises a stale negative offset when a host timestamp arrives ahead of it", () => { + const environmentId = EnvironmentId.make("caught-up"); + recordServerClock(environmentId, { + serverTimeMs: 1_000, + requestedAtMs: 2 * HOUR + 900, + receivedAtMs: 2 * HOUR + 1_050, + }); + expect(toServerClock(environmentId, 2 * HOUR + 10_050)).toBe(10_150); + + observeServerTime(environmentId, 2 * HOUR + 10_000, 2 * HOUR + 10_050); + expect(toServerClock(environmentId, 2 * HOUR + 20_050)).toBe(2 * HOUR + 20_000); + + observeServerTime(environmentId, 5_000, 2 * HOUR + 20_100); + expect(toServerClock(environmentId, 2 * HOUR + 20_050)).toBe(2 * HOUR + 20_000); + + const unrecorded = EnvironmentId.make("unrecorded"); + observeServerTime(unrecorded, HOUR, 1_000); + expect(toServerClock(unrecorded, 1_000)).toBe(1_000); + }); }); diff --git a/packages/client-runtime/src/clock.ts b/packages/client-runtime/src/clock.ts index f8f1290730084..67693220883b8 100644 --- a/packages/client-runtime/src/clock.ts +++ b/packages/client-runtime/src/clock.ts @@ -104,6 +104,29 @@ export function recordServerClock( ); } +/** + * A timestamp stamped by the host is never in its own future, so it gives a + * lower bound on the host's clock. Raises a stale negative offset (for example + * when a VM or WSL clock catches up after host sleep) without shifting a clock + * that already agrees. + */ +export function observeServerTime( + environmentId: EnvironmentId, + serverTimeMs: number, + receivedAtMs: number, +): void { + const currentOffset = serverClockOffsets.get(environmentId); + if ( + currentOffset === undefined || + !Number.isFinite(serverTimeMs) || + !Number.isFinite(receivedAtMs) + ) { + return; + } + if (receivedAtMs + currentOffset >= serverTimeMs) return; + serverClockOffsets.set(environmentId, serverTimeMs - receivedAtMs); +} + /** Converts client epoch milliseconds to the environment's clock. */ export function toServerClock(environmentId: EnvironmentId, clientMs: number): number { return clientMs + (serverClockOffsets.get(environmentId) ?? 0); diff --git a/packages/client-runtime/src/device/stream.test.ts b/packages/client-runtime/src/device/stream.test.ts index ad930680fbeb5..9050e6c18504f 100644 --- a/packages/client-runtime/src/device/stream.test.ts +++ b/packages/client-runtime/src/device/stream.test.ts @@ -140,6 +140,35 @@ describe("native device stream transport", () => { }, ); + it.each([ + ["ios", { button: "home" }, { button: "app_switcher" }], + ["android", { type: "home" }, { type: "recents" }], + ] as const)( + "opens the %s app switcher on a double-tapped home button", + async (platform, home, switcher) => { + const { client, opened } = setup(platform); + client.start(); + const socket = await opened; + socket.onopen?.(); + if (platform === "ios") socket.onmessage?.({ data: Uint8Array.of(0x83).buffer }); + socket.send.mockClear(); + + client.pressButton("home"); + client.pressButton("home"); + client.pressButton("home"); + vi.advanceTimersByTime(1000); + client.pressButton("home"); + + const sent = socket.send.mock.calls.map(([payload]) => + JSON.parse( + typeof payload === "string" ? payload : new TextDecoder().decode(payload.subarray(1)), + ), + ); + expect(sent).toEqual([home, switcher, home, home]); + client.stop(); + }, + ); + it.each(["ios", "android"] as const)( "does not renew credentials or reconnect a stopped %s stream", async (platform) => { diff --git a/packages/client-runtime/src/device/stream.ts b/packages/client-runtime/src/device/stream.ts index c570ee107ad55..45824149a8c66 100644 --- a/packages/client-runtime/src/device/stream.ts +++ b/packages/client-runtime/src/device/stream.ts @@ -1,4 +1,4 @@ -// @effect-diagnostics globalFetch:off globalTimers:off - This browser and WebView transport runs without an Effect runtime. +// @effect-diagnostics globalFetch:off globalTimers:off globalDate:off - This browser and WebView transport runs without an Effect runtime. import { createDuoControl, @@ -157,6 +157,7 @@ const SOFT_DECODE_QUEUE = 8; const ANDROID_MAX_TEXT_BYTES = 300; // The pinned hub queue depth is 128; the client does not read queue rejections. const ANDROID_MAX_TEXT_CHUNKS = 64; +const HOME_DOUBLE_TAP_MS = 400; const IOS_MSG_TOUCH = 0x03; const IOS_MSG_BUTTON = 0x04; @@ -428,6 +429,7 @@ export function createDeviceStreamClient( isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg && !serveSimOnly); let stopped = true; + let lastHomePress = -Infinity; let socket: WebSocket | null = null; let controller: AbortController | null = null; const retryTimers = new Map<"video" | "input", ReturnType>(); @@ -1460,7 +1462,11 @@ export function createDeviceStreamClient( } if (chunk.length > 0) send(JSON.stringify({ type: "text", text: chunk })); }, - pressButton: (button) => { + pressButton: (pressed) => { + const now = Date.now(); + const doubleHome = pressed === "home" && now - lastHomePress < HOME_DOUBLE_TAP_MS; + lastHomePress = pressed === "home" && !doubleHome ? now : -Infinity; + const button = doubleHome ? "appSwitcher" : pressed; if (avcc) { const name = button === "home" diff --git a/packages/client-runtime/src/feedbackRequest.test.ts b/packages/client-runtime/src/feedbackRequest.test.ts new file mode 100644 index 0000000000000..8c1d5b6cae4bd --- /dev/null +++ b/packages/client-runtime/src/feedbackRequest.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + feedbackConversationHint, + feedbackPreviewFields, + feedbackRequestDisplay, + feedbackTraceLines, + feedbackTraceSummary, +} from "./feedbackRequest.ts"; + +describe("feedbackRequestDisplay", () => { + it("lets only the thread that asked answer, and names how each card ended", () => { + expect(feedbackRequestDisplay({ feedbackStatus: "pending" }, "local")).toEqual({ + kind: "pending", + }); + expect(feedbackRequestDisplay({ feedbackStatus: "pending" }, "inherited").kind).toBe( + "pending-elsewhere", + ); + expect( + (["sent", "declined", "cancelled"] as const).map((feedbackStatus) => + feedbackRequestDisplay({ feedbackStatus }, "local"), + ), + ).toEqual([ + { kind: "answered", outcome: "sent", label: "Sent" }, + { kind: "answered", outcome: "not-sent", label: "Not sent" }, + { kind: "answered", outcome: "not-sent", label: "Closed without sending" }, + ]); + }); +}); + +describe("feedback preview", () => { + it("shows every field that is sent, and each outline entry with its text", () => { + const trace = { + turns: 1, + textTurns: 1, + truncated: false, + entries: [ + { turn: 1, type: "user" as const, length: 5, text: "Hello" }, + { + turn: 1, + type: "tool" as const, + tool: "t3_thread_read", + outcome: "error" as const, + durationMs: 1_500, + }, + ], + }; + expect( + feedbackPreviewFields({ + kind: "bug", + subject: "t3_thread_read", + expected: "Items.", + actual: "None.", + workaround: "", + trace, + }).map((field) => field.label), + ).toEqual(["Kind", "About", "Expected", "Happened"]); + expect(feedbackTraceLines(trace)).toEqual([ + { key: "0", line: "Turn 1 · You · 5 characters", text: "Hello" }, + { key: "1", line: "Turn 1 · t3_thread_read · error · 1.5 s" }, + ]); + // Text only in turn 4 of 5: the wording reaches back to it, not "the last turn". + const older = { + turns: 5, + textTurns: 1, + truncated: false, + entries: [ + { turn: 4, type: "user" as const, length: 5, text: "Hello" }, + { turn: 5, type: "tool" as const, tool: "shell", outcome: "ok" as const }, + ], + }; + expect(feedbackTraceSummary(older)).toBe( + "Outline of 5 recent turns, message text of the last 2 turns", + ); + expect(feedbackConversationHint(older)).toBe( + "Adds the text of your messages and the agent's replies in the last 2 turns.", + ); + }); +}); diff --git a/packages/client-runtime/src/feedbackRequest.ts b/packages/client-runtime/src/feedbackRequest.ts new file mode 100644 index 0000000000000..f6b0079213ebc --- /dev/null +++ b/packages/client-runtime/src/feedbackRequest.ts @@ -0,0 +1,145 @@ +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; +import type { AgentFeedbackPreview, OrchestrationV2TurnItem } from "@t3tools/contracts"; + +export type FeedbackRequestItem = Extract< + OrchestrationV2TurnItem, + { readonly type: "feedback_request" } +>; + +export type FeedbackRequestDisplay = + | { readonly kind: "pending" } + /** Inherited by a fork: only the thread that asked can answer it. */ + | { readonly kind: "pending-elsewhere"; readonly label: string } + | { readonly kind: "answered"; readonly outcome: "sent" | "not-sent"; readonly label: string }; + +export function feedbackRequestDisplay( + item: Pick, + visibility: "local" | "inherited" | "synthetic", + resolve: MFunctionType = mFallback, +): FeedbackRequestDisplay { + switch (item.feedbackStatus) { + case "pending": + return visibility === "local" + ? { kind: "pending" } + : { kind: "pending-elsewhere", label: resolve(msg("Waiting in the original thread")) }; + case "sent": + return { kind: "answered", outcome: "sent", label: resolve(msg("Sent")) }; + case "declined": + return { kind: "answered", outcome: "not-sent", label: resolve(msg("Not sent")) }; + case "cancelled": + return { + kind: "answered", + outcome: "not-sent", + label: resolve(msg("Closed without sending")), + }; + } +} + +/** Exactly what Send sends: the outline, or with the conversation included, its text too. */ +export function feedbackCardPreview( + item: Pick, + includeConversation: boolean, +): AgentFeedbackPreview { + return includeConversation && item.conversationTrace !== undefined + ? { ...item.preview, trace: item.conversationTrace } + : item.preview; +} + +const KIND_LABELS: Record = { + bug: msg("Bug"), + confusing: msg("Confusing"), + missing_capability: msg("Missing capability"), + wrong_docs: msg("Wrong docs"), + other: msg("Other"), +}; + +/** The report's fields in reading order, the empty workaround left out. */ +export function feedbackPreviewFields( + preview: AgentFeedbackPreview, + resolve: MFunctionType = mFallback, +): ReadonlyArray<{ readonly label: string; readonly value: string }> { + return [ + { label: resolve(msg("Kind")), value: resolve(KIND_LABELS[preview.kind]) }, + { label: resolve(msg("About")), value: preview.subject }, + { label: resolve(msg("Expected")), value: preview.expected }, + { label: resolve(msg("Happened")), value: preview.actual }, + { label: resolve(msg("Did instead")), value: preview.workaround }, + ].filter((field) => field.value !== ""); +} + +const seconds = (ms: number) => `${(ms / 1_000).toFixed(ms < 10_000 ? 1 : 0)} s`; + +/** One line per outline entry, plus the message text that goes with it. */ +export function feedbackTraceLines( + trace: NonNullable, + resolve: MFunctionType = mFallback, +): ReadonlyArray<{ readonly key: string; readonly line: string; readonly text?: string }> { + return trace.entries.map((entry, index) => { + const what = + entry.type === "tool" + ? [ + entry.tool ?? "tool", + entry.outcome, + entry.durationMs === undefined ? undefined : seconds(entry.durationMs), + ] + .filter((part) => part !== undefined) + .join(" · ") + : resolve( + msg("{speaker} · {count} characters", { + speaker: resolve(entry.type === "user" ? msg("You") : msg("Agent")), + count: entry.length ?? 0, + }), + ); + return { + key: `${index}`, + line: resolve(msg("Turn {turn} · {what}", { turn: entry.turn, what })), + ...(entry.text === undefined ? {} : { text: entry.text }), + }; + }); +} + +type Trace = NonNullable; + +// Counted back to the oldest turn with text, so a newer turn without any is still inside it. +const textSpan = (trace: Trace) => { + const withText = trace.entries.filter((entry) => entry.text !== undefined); + return withText.length === 0 + ? 0 + : trace.turns - Math.min(...withText.map((entry) => entry.turn)) + 1; +}; + +/** What the outline holds, in one line. */ +export function feedbackTraceSummary(trace: Trace, resolve: MFunctionType = mFallback): string { + return resolve( + msg( + "Outline of {turns, plural, one {{turns} recent turn} other {{turns} recent turns}}, {textTurns, plural, =0 {no message text} one {message text of the last turn} other {message text of the last {textTurns} turns}}{truncated, select, yes {, shortened to fit} other {}}", + { turns: trace.turns, textTurns: textSpan(trace), truncated: trace.truncated ? "yes" : "no" }, + ), + ); +} + +/** What the conversation switch adds: the text of the turns the agent said the problem spans. */ +export function feedbackConversationHint(trace: Trace, resolve: MFunctionType = mFallback): string { + return resolve( + msg( + "Adds the text of your messages and the agent's replies in the last {textTurns, plural, one {turn} other {{textTurns} turns}}.", + { textTurns: textSpan(trace) }, + ), + ); +} + +/** The server's own message for a failed answer, else a generic one. */ +export function feedbackRequestFailureMessage( + failure: unknown, + resolve: MFunctionType = mFallback, +): string { + return typeof failure === "object" && + failure !== null && + "_tag" in failure && + failure._tag === "AgentFeedbackRequestError" && + "message" in failure && + typeof failure.message === "string" + ? failure.message + : resolve(msg("Could not send your answer. Try again.")); +} diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index 66909fad1f054..1f2683f92cd59 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + IssueTrackerAccountId, IssueTrackerKind, ProjectId, SourceControlProviderKind, @@ -49,6 +50,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) => ({ @@ -127,6 +139,25 @@ describe("resolveIssueLinkTarget", () => { expect( resolveIssueLinkTarget({ url: "https://linear.app/acme/issue/WEB-17", projects }), ).toBeNull(); + + // A second account reaches its own workspace, through only the projects bound with it. + const accountId = IssueTrackerAccountId.make("second"); + const [p1, p2] = [ProjectId.make("p1"), ProjectId.make("p2")]; + const both = (url: string) => + resolveIssueLinkTarget({ + url, + projects, + trackers: { + ...trackers, + accounts: [{ ...trackers.trackers[0]!, accountId, workspace: "othercorp" }], + bindings: { [p1]: trackers.bindings[p1]! }, + accountBindings: { [p2]: { ...trackers.bindings[p2]!, accountId } }, + }, + })?.ref.projectId; + expect([ + both("https://linear.app/othercorp/issue/WEB-17"), + both("https://linear.app/acme/issue/WEB-17"), + ]).toEqual(["p2", "p1"]); }); it.each([ diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index 0b442d18c92b5..a81ac7831396d 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 { @@ -70,8 +82,8 @@ export function mayContainStandaloneIssueLink(text: string): boolean { /** * A standalone tracker link resolves through the project bound to its scope, else any bound to - * the tracker, and only when it names the workspace the credential reaches: team keys repeat - * across workspaces, so a link elsewhere stays an ordinary link. + * the tracker, and only through an account whose credential reaches the workspace it names: team + * keys repeat across workspaces, so a link elsewhere stays an ordinary link. */ function resolveStandaloneIssueLink( url: string, @@ -82,14 +94,23 @@ function resolveStandaloneIssueLink( const parsed = trackers === undefined ? null : parseStandaloneIssueLink(url); if (parsed === null || trackers === undefined) return null; const { tracker, link } = parsed; - const workspace = trackers.trackers.find( - (connection) => connection.tracker === tracker && connection.account !== null, - )?.workspace; - if (workspace?.toLowerCase() !== link.workspace.toLowerCase()) return null; - const { bindings } = trackers; + const accounts = new Set( + [...trackers.trackers, ...(trackers.accounts ?? [])] + .filter( + (connection) => + connection.tracker === tracker && + connection.account !== null && + connection.workspace?.toLowerCase() === link.workspace.toLowerCase(), + ) + .map((connection) => connection.accountId ?? null), + ); + if (accounts.size === 0) return null; + const bindings = { ...trackers.bindings, ...trackers.accountBindings }; const onTracker = projects.flatMap((project) => { const binding = bindings[project.id]; - return binding?.tracker === tracker ? [{ project, binding }] : []; + return binding?.tracker === tracker && accounts.has(binding.accountId ?? null) + ? [{ project, binding }] + : []; }); const preferFirst = (candidates: typeof onTracker) => candidates.find((candidate) => candidate.project.id === preferredProjectId) ?? candidates[0]; diff --git a/packages/client-runtime/src/issueList.test.ts b/packages/client-runtime/src/issueList.test.ts index 5085c10e51887..49bab599b4f51 100644 --- a/packages/client-runtime/src/issueList.test.ts +++ b/packages/client-runtime/src/issueList.test.ts @@ -144,6 +144,35 @@ describe("issueFilterScopes", () => { expect(issueFilterScopes(held, [])).toEqual([{ environmentId, input: scope }]); }); + it("offers the same team key of two Linear accounts as two scopes", () => { + const first = { + projectId: api, + tracker: "linear" as IssueTrackerKind, + host: "linear.app", + scope: "ENG", + }; + const second = hold( + answer({ + trackers: [tracker({})], + scopes: [first, { ...first, projectId: "home" as ProjectId }], + }), + ); + const other = hold( + answer({ trackers: [tracker({})], scopes: [{ ...first, projectId: "o" as ProjectId }] }), + ); + // Older servers name no scopes; their rows stand in, once per team on that server. + const older = hold( + answer({ trackers: [tracker({})], entries: [linearRow, { ...linearRow, key: "ENG-2" }] }), + ); + const count = (...pages: ReadonlyArray>) => + issueFilterScopes( + new Map(pages.map((page, index) => [`env-${index}` as EnvironmentId, page])), + [], + ).length; + expect([count(second), count(second, other), count(other, second)]).toEqual([2, 3, 3]); + expect([count(older), count(older, second), count(second, older)]).toEqual([1, 3, 3]); + }); + it("skips a tracker that cannot be read", () => { const held = new Map([ [ diff --git a/packages/client-runtime/src/issueList.ts b/packages/client-runtime/src/issueList.ts index 5e01c4683830d..1a99f54e0f580 100644 --- a/packages/client-runtime/src/issueList.ts +++ b/packages/client-runtime/src/issueList.ts @@ -170,6 +170,9 @@ export function issueFilterScopes( ) { const scopes: Array<{ readonly environmentId: EnvironmentId; readonly input: IssueScopeRef }> = []; + // A repository's scope is the same scope on every server. A bound tracker's scope is not: two + // accounts, or two servers, may both have an ENG team, so those are deduplicated per server only. + const fromRepository = new Set(); for (const [environmentId, page] of held) { for (const project of projects) { if (project.environmentId !== environmentId) continue; @@ -186,10 +189,9 @@ export function issueFilterScopes( ) ) continue; - scopes.push({ - environmentId, - input: { projectId: project.id, tracker: tracker.tracker, host, scope }, - }); + const input = { projectId: project.id, tracker: tracker.tracker, host, scope }; + fromRepository.add(input); + scopes.push({ environmentId, input }); } } // A tracker bound in settings (a Linear team) is no repository's; the answer names its scope, @@ -209,9 +211,12 @@ export function issueFilterScopes( ); if (!tracker?.configured) continue; if (!tracker.capabilities?.labels && !tracker.capabilities?.assignees) continue; + // An answer names each scope once per account; rows standing in for one repeat. if ( scopes.some( (s) => + (fromRepository.has(s.input) || + (page.answer.scopes === undefined && s.environmentId === environmentId)) && s.input.scope.toLowerCase() === input.scope.toLowerCase() && s.input.host?.toLowerCase() === host, ) diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 8b2d4e105e5b1..dc98322c225da 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - The probe fixture uses a Node macrotask boundary. +import * as NodeTimersPromises from "node:timers/promises"; import { EnvironmentId, EventId, @@ -20,7 +22,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 +165,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"; @@ -177,16 +256,22 @@ describe("connectLinkedEnvironment", () => { credential: "ONE-TIME", expiresAt: DateTime.makeUnsafe(0), }; + const unsupported: PeerLinkClientPairingResult = { + type: "unsupported", + reason: "link_access", + ...target, + }; const connect = ( pairing: PeerLinkClientPairingResult | null, - reachable: ReadonlyArray, + reachable: ReadonlyArray | ((host: string) => Promise), paired = true, ) => { const pairs: Array<{ host: string; pairingCode: string }> = []; return connectLinkedEnvironment({ label: "vm (saved name)", requestPairing: async () => pairing, - reaches: async (host) => reachable.includes(host), + reaches: + typeof reachable === "function" ? reachable : async (host) => reachable.includes(host), pair: async (input) => { pairs.push(input); return paired; @@ -202,6 +287,42 @@ describe("connectLinkedEnvironment", () => { expect((await connect(credential, [tailnet, lan])).pairs[0]?.host).toBe(lan); }); + it.each([ + { + name: "redeems at an alternate after the preferred probe fails", + pairing: credential, + preferredReachable: false, + expected: { + outcome: { type: "connected" }, + pairs: [{ host: tailnet, pairingCode: "ONE-TIME" }], + }, + }, + { + name: "prefills the preferred address even when an alternate answers first", + pairing: unsupported, + preferredReachable: true, + expected: { outcome: { type: "manual", label: "VM", host: lan }, pairs: [] }, + }, + ])("$name without waiting for a silent last address", async (row) => { + const last = "https://other.example.test"; + const preferred = Promise.withResolvers(); + const silent = Promise.withResolvers(); + const connecting = connect({ ...row.pairing, urls: [lan, tailnet, last] }, (host) => { + if (host === lan) return preferred.promise; + if (host === last) return silent.promise; + queueMicrotask(() => preferred.resolve(row.preferredReachable)); + return Promise.resolve(true); + }); + try { + // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Let the already runnable probe continuations finish while the last probe stays pending. + const pending = NodeTimersPromises.setImmediate("still waiting for an address"); + expect(await Promise.race([connecting, pending])).toEqual(row.expected); + } finally { + silent.resolve(false); + preferred.resolve(false); + } + }); + it("says the machine is out of reach, and spends nothing, when no address answers", async () => { expect(await connect(credential, [])).toEqual({ outcome: { type: "unreachable", label: "VM" }, @@ -210,11 +331,6 @@ describe("connectLinkedEnvironment", () => { }); it("leaves pairing to the user when the link cannot do it, with an address filled in", async () => { - const unsupported: PeerLinkClientPairingResult = { - type: "unsupported", - reason: "link_access", - ...target, - }; const manual = (host: string | null) => ({ outcome: { type: "manual", label: "VM", host }, pairs: [], diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 15364cddf54ea..9e2b4487f59b4 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"; @@ -86,8 +89,17 @@ export async function connectLinkedEnvironment(options: { if (pairing === null) return { type: "manual", label: options.label, host: null }; const { label, urls } = pairing; // Asked together, taken in the linking environment's order of preference. - const answers = await Promise.all(urls.map((url) => options.reaches(url))); - const host = urls.find((_, index) => answers[index]) ?? null; + const probes = urls.map((url) => + options.reaches(url).then( + (reached) => (reached ? url : null), + () => null, + ), + ); + let host: string | null = null; + for (const probe of probes) { + host = await probe; + if (host !== null) break; + } if (pairing.type === "unsupported") { return { type: "manual", label, host: host ?? urls[0] ?? null }; } @@ -212,12 +224,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 +271,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 +286,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 +387,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/operations/threadTitle.ts b/packages/client-runtime/src/operations/threadTitle.ts index 0f57de34036a5..bb1fcd7648dbf 100644 --- a/packages/client-runtime/src/operations/threadTitle.ts +++ b/packages/client-runtime/src/operations/threadTitle.ts @@ -3,6 +3,7 @@ import type { MFunctionType } from "gt-i18n/types"; import type { ChatAttachment } from "@t3tools/contracts"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { truncate } from "@t3tools/shared/String"; import { collectComposerModelMentions } from "../composerModelMentions.ts"; @@ -45,7 +46,7 @@ export function threadTitleTextFromPrompt( return reference.label; }); return ( - normalizeTitleSeed(modelMentionsAsSlugs(prose)) || + normalizeTitleSeed(modelMentionsAsSlugs(composerFileLinksToPlainText(prose))) || (imageIds.size > 0 ? attachedImagesTitle(imageIds.size, resolve) : "") ); } 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 cf7bb6c0f92fd..d4af4aa10ddd5 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -87,6 +87,7 @@ import { mergeToolCallState, parsePermissionRequest, parseSessionUpdateEvent, + sessionUpdateIsReplay, toolCallVisibleOutputChanged, withTrackedPermissionToolCall, type AcpPlanUpdate, @@ -388,15 +389,17 @@ export interface AcpAdapterV2Flavor { /** The flavor's runtime refuses a version the policy rates broken when it starts. */ readonly checksVersionAtHandshake?: boolean; /** - * Runs before `session/prompt`. The returned check sees a prompt the agent ended - * without an error or cancel, and reports a failure its stop reason hid. A reported - * failure restarts the runtime before the next turn. A `broken` thread's native - * history is unusable, so the next turn falls back to a fresh session. + * Runs before `session/prompt`. The check reports a failure hidden by a clean stop, or + * by silence when the inactivity watchdog retires the prompt (`retired`). A failure + * restarts the runtime; a `broken` thread's next turn starts a fresh session. */ readonly watchPromptOutcome?: ( sessionId: string, ) => Effect.Effect< - (result: EffectAcpSchema.PromptResponse) => Effect.Effect + ( + result: EffectAcpSchema.PromptResponse, + options?: { readonly retired?: boolean }, + ) => Effect.Effect >; readonly requiresSignIn?: (cause: unknown) => boolean; /** @@ -636,6 +639,15 @@ export interface AcpAdapterV2Flavor { * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then. */ readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean; + /** + * Finalize a settled turn held only by running commands once the session has been silent for + * `timeout`, so a command that never reports back cannot leave the thread in Working forever. + * Other holds (questions, schedules, subagents) keep the turn open as before. + */ + readonly postSettleCommandHold?: { + readonly timeout: Duration.Input; + readonly isCommand: (toolCall: AcpToolCallState) => boolean; + }; readonly isProviderWakeNotification?: ( notification: EffectAcpSchema.SessionNotification, ) => boolean; @@ -1736,6 +1748,12 @@ interface ActiveAcpTurn { inactivityWatchdog: Fiber.Fiber | undefined; } +const PROMPT_OUTCOME_CHECK_TIMEOUT = Duration.seconds(5); + +type PromptOutcomeCheck = Effect.Success< + ReturnType> +>; + type AcpRuntimeTeardownState = | { readonly _tag: "Idle" } | { @@ -2304,6 +2322,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); @@ -2723,7 +2759,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const notePromptProgress = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (notification?: EffectAcpSchema.SessionNotification) { - if (promptInactivityTimeoutMillis === undefined) return; + if ( + promptInactivityTimeoutMillis === undefined && + flavor.postSettleCommandHold === undefined + ) { + return; + } if ( notification !== undefined && !ACP_PROMPT_ACTIVITY_UPDATES.has(notification.update.sessionUpdate) @@ -4255,11 +4296,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const isMonitorEndNoticeText = (text: string): boolean => /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); - const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { + const hasDeferredBackgroundWork = ( + context: ActiveAcpTurn, + ignoreTool?: (tool: AcpToolCallState) => boolean, + ): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. for (const tool of context.tools.values()) { + if (ignoreTool?.(tool) === true) continue; if (toolStatus(tool.status) === "running" && flavor.toolOutlivesPrompt(tool)) return true; } @@ -5650,6 +5695,80 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), ); + const recordLoadedHistory = Effect.fnUntraced(function* ( + notification: EffectAcpSchema.SessionNotification, + live: boolean, + ) { + const update = notification.update; + if ( + notification.sessionId !== + ((yield* Ref.get(loadingSessionId)) ?? (yield* Ref.get(activeSessionId))) + ) + return; + if ( + update.sessionUpdate === "user_message_chunk" || + update.sessionUpdate === "agent_message_chunk" || + update.sessionUpdate === "agent_thought_chunk" + ) { + const text = acpContentBlockDisplayText(update.content); + if (text === undefined) return; + const lateBackgroundMutations = + update.content.type === "text" + ? (flavor.extractBackgroundToolMutation?.(text) ?? []) + : []; + if (live) { + for (const lateBackgroundMutation of lateBackgroundMutations) { + yield* applyLateBackgroundMutation(notification.sessionId, lateBackgroundMutation); + } + } + if (lateBackgroundMutations.length === 0 && !acpIsMonitorChatter(text)) { + yield* appendLoadedHistory( + notification, + update.sessionUpdate === "user_message_chunk" + ? "user" + : update.sessionUpdate === "agent_thought_chunk" + ? "thought" + : "assistant", + text, + ); + } + } else if ( + update.sessionUpdate === "user_message" || + update.sessionUpdate === "agent_message" || + update.sessionUpdate === "agent_thought" + ) { + if (update.content === undefined) return; + const text = (update.content ?? []) + .flatMap((content) => { + const display = acpContentBlockDisplayText(content); + return display === undefined ? [] : [display]; + }) + .join("\n"); + yield* appendLoadedHistory( + notification, + update.sessionUpdate === "user_message" + ? "user" + : update.sessionUpdate === "agent_thought" + ? "thought" + : "assistant", + text, + true, + ); + } else if ( + update.sessionUpdate === "tool_call" || + update.sessionUpdate === "tool_call_update" || + update.sessionUpdate === "plan" || + update.sessionUpdate === "plan_update" || + update.sessionUpdate === "plan_removed" + ) { + yield* Ref.update(snapshot, (current) => ({ + ...current, + loadingRole: null, + loadingMessageId: null, + })); + } + }); + const handleSessionUpdate = Effect.fnUntraced(function* ( notification: EffectAcpSchema.SessionNotification, ) { @@ -5717,6 +5836,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 ?? @@ -5898,71 +6021,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (wakeOutcome.stopProcessing) { return; } - if ( - notification.sessionId !== - ((yield* Ref.get(loadingSessionId)) ?? (yield* Ref.get(activeSessionId))) - ) - return; - if ( - update.sessionUpdate === "user_message_chunk" || - update.sessionUpdate === "agent_message_chunk" || - update.sessionUpdate === "agent_thought_chunk" - ) { - const text = acpContentBlockDisplayText(update.content); - if (text === undefined) return; - const lateBackgroundMutations = - update.content.type === "text" - ? (flavor.extractBackgroundToolMutation?.(text) ?? []) - : []; - for (const lateBackgroundMutation of lateBackgroundMutations) { - yield* applyLateBackgroundMutation(notification.sessionId, lateBackgroundMutation); - } - if (lateBackgroundMutations.length === 0 && !acpIsMonitorChatter(text)) { - yield* appendLoadedHistory( - notification, - update.sessionUpdate === "user_message_chunk" - ? "user" - : update.sessionUpdate === "agent_thought_chunk" - ? "thought" - : "assistant", - text, - ); - } - } else if ( - update.sessionUpdate === "user_message" || - update.sessionUpdate === "agent_message" || - update.sessionUpdate === "agent_thought" - ) { - if (update.content === undefined) return; - const text = (update.content ?? []) - .flatMap((content) => { - const display = acpContentBlockDisplayText(content); - return display === undefined ? [] : [display]; - }) - .join("\n"); - yield* appendLoadedHistory( - notification, - update.sessionUpdate === "user_message" - ? "user" - : update.sessionUpdate === "agent_thought" - ? "thought" - : "assistant", - text, - true, - ); - } else if ( - update.sessionUpdate === "tool_call" || - update.sessionUpdate === "tool_call_update" || - update.sessionUpdate === "plan" || - update.sessionUpdate === "plan_update" || - update.sessionUpdate === "plan_removed" - ) { - yield* Ref.update(snapshot, (current) => ({ - ...current, - loadingRole: null, - loadingMessageId: null, - })); - } + yield* recordLoadedHistory(notification, true); return; } if (context.finalized) return; @@ -7016,6 +7075,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.fnUntraced( function* (rawNotification: EffectAcpSchema.SessionNotification) { if (flavor.ignoreSessionUpdate?.(rawNotification) === true) return; + // Replayed history feeds snapshots only; it must not drive live turn or wake state. + if (sessionUpdateIsReplay(rawNotification)) { + yield* recordLoadedHistory( + flavor.normalizeSessionUpdate?.(rawNotification) ?? rawNotification, + false, + ); + return; + } yield* notePromptProgress(rawNotification); const nativePromptId = flavor.forkFromTurn?.nativeTurnId(rawNotification); if (nativePromptId !== undefined) { @@ -8334,6 +8401,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?.( @@ -8522,6 +8590,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", @@ -8617,6 +8718,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); @@ -8759,6 +8861,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* options.testHooks?.onDeferredFinalizeScheduled?.(debounce) ?? Effect.void; }); + const schedulePostSettleHoldExpiry = Effect.fn("AcpAdapterV2.schedulePostSettleHoldExpiry")( + function* (context: ActiveAcpTurn) { + const hold = flavor.postSettleCommandHold; + if (hold === undefined) return; + if (!context.promptSettled || context.finalized) return; + const timeoutMillis = Duration.toMillis(hold.timeout); + const isRunningCommand = (tool: AcpToolCallState) => + toolStatus(tool.status) === "running" && hold.isCommand(tool); + let quietSince = yield* Clock.currentTimeMillis; + // Armed even without a command yet: a pending reply can still start one. + yield* Effect.gen(function* () { + while (!context.finalized) { + quietSince = Math.max(quietSince, context.lastProgressAt); + const now = yield* Clock.currentTimeMillis; + const remaining = quietSince + timeoutMillis - now; + if (remaining > 0) { + yield* Effect.sleep(Duration.millis(remaining)); + continue; + } + if ( + context.tools.values().some(isRunningCommand) && + !hasDeferredBackgroundWork(context, isRunningCommand) + ) { + yield* finalizeTurn(context, context.promptSettledStatus ?? "completed"); + return; + } + // Something else still holds the turn; count silence again once it clears. + quietSince = now; + } + }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); + }, + ); + const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { @@ -8782,6 +8917,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context: ActiveAcpTurn, generation: number, timeoutMillis: number, + checkPromptOutcome: PromptOutcomeCheck | undefined, ) { const retired = yield* runRuntimeCallbackAtGeneration( generation, @@ -8802,14 +8938,31 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(runtimeRestartRequired, true); yield* cancelPendingRuntimeRequests(); yield* terminalizeOpenForegroundTools(context, "failed"); + // Bounded: it runs under the transition permit that Stop and the next turn wait on. + const recorded = + checkPromptOutcome === undefined + ? undefined + : yield* checkPromptOutcome({ stopReason: "end_turn" }, { retired: true }).pipe( + Effect.timeout(PROMPT_OUTCOME_CHECK_TIMEOUT), + Effect.catchCause((cause) => + Effect.logError("failed to check a silent ACP prompt's outcome", { + driver, + cause, + }).pipe(Effect.as(undefined)), + ), + ); const minutes = Math.max(1, Math.round(timeoutMillis / 60_000)); yield* finalizeTurn( context, "failed", - makeProviderFailure({ - class: "provider_error", - message: `${flavor.runtimeHarness ?? driver} sent nothing for ${minutes} ${minutes === 1 ? "minute" : "minutes"}, so T3 Code stopped the turn and restarted the agent. Send a message to continue.`, - }), + recorded?.failure ?? + makeProviderFailure({ + class: "provider_error", + message: `${flavor.runtimeHarness ?? driver} sent nothing for ${minutes} ${minutes === 1 ? "minute" : "minutes"}, so T3 Code stopped the turn and restarted the agent. Send a message to continue.`, + }), + recorded === undefined + ? undefined + : { threadDisposition: recorded.threadDisposition }, ); return "retired" as const; }), @@ -8833,6 +8986,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context: ActiveAcpTurn, generation: number, timeoutMillis: number, + checkPromptOutcome: PromptOutcomeCheck | undefined, ) { yield* Deferred.await(context.promptDispatched); context.lastProgressAt = yield* Clock.currentTimeMillis; @@ -8851,7 +9005,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( continue; } const outcome = yield* runtimeTransitionPermit.withPermit( - retireInactivePrompt(context, generation, timeoutMillis), + retireInactivePrompt(context, generation, timeoutMillis, checkPromptOutcome), ); if (outcome !== "rearm") return; } @@ -8965,6 +9119,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const sessionSetup = yield* Ref.get(activeSessionSetup); const runtimeInstructions = buildRuntimeInstructions({ + agentFeedback: instructionState.hasT3Mcp ? (turnInput.agentFeedback ?? "off") : "off", harness: flavor.runtimeHarness ?? driver, model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy, @@ -9189,6 +9344,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (context.finalized) return; if (deferredBackgroundWork || pendingReply) { yield* closeTextStreams(context); + yield* schedulePostSettleHoldExpiry(context); if (pendingReply) { context.replyOpen = true; yield* scheduleDeferredFinalize(context); @@ -9589,6 +9745,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } if (!context.finalized) { + yield* schedulePostSettleHoldExpiry(context); if (hasDeferredBackgroundWork(context)) { yield* rearmDeferredFinalize(context); } else { @@ -9612,6 +9769,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context, promptGeneration, promptInactivityTimeoutMillis, + checkPromptOutcome, ).pipe(Effect.forkIn(sessionScope)); } const compactSession = isCompactionMessage(turnInput.message) @@ -9714,6 +9872,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context, generation, promptInactivityTimeoutMillis, + checkPromptOutcome, ).pipe(Effect.forkIn(sessionScope)); } const releasedForSteer = context.foregroundIdle; 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 98fe2fe626683..ba237aea81e37 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -1,5 +1,6 @@ import type { OrchestrationV2HistoricalMessage } from "@t3tools/contracts"; import { + type AgentFeedbackMode, ChatAttachment, CheckpointId, MessageId, @@ -8,6 +9,7 @@ import { OrchestrationV2AppThread, OrchestrationV2ConversationMessage, OrchestrationV2ExecutionNode, + OrchestrationV2PendingBackgroundTask, OrchestrationV2ProviderSession, OrchestrationV2PlanArtifact, OrchestrationV2ProviderCapabilities, @@ -118,6 +120,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 +178,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 +223,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 +239,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)), @@ -558,6 +583,7 @@ export interface ProviderAdapterV2EnsureThreadInput { } export interface ProviderAdapterV2TurnInput { + readonly agentFeedback?: AgentFeedbackMode; readonly appThread: OrchestrationV2AppThread; readonly threadId: ThreadId; readonly runId: RunId; 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-core/src/server/runtimeInstructions.test.ts b/packages/provider-core/src/server/runtimeInstructions.test.ts index 2564bedaa9216..5aa9259c49d91 100644 --- a/packages/provider-core/src/server/runtimeInstructions.test.ts +++ b/packages/provider-core/src/server/runtimeInstructions.test.ts @@ -1,6 +1,7 @@ import { assert, describe, it } from "@effect/vitest"; import { + AGENT_FEEDBACK_INSTRUCTIONS, buildRuntimeInstructions, PULL_REQUEST_LINKING_INSTRUCTIONS, } from "./runtimeInstructions.ts"; @@ -57,6 +58,22 @@ describe("buildRuntimeInstructions", () => { assert.include(instructions, "call unwatch_pull_request"); }); + it("carries the feedback line of the agent feedback mode, and none while it is off", () => { + assert.notInclude(buildRuntimeInstructions({ harness: "Codex" }), "t3_feedback"); + assert.notInclude( + buildRuntimeInstructions({ harness: "Codex", agentFeedback: "off" }), + "t3_feedback", + ); + for (const agentFeedback of ["on-request", "auto"] as const) { + for (const pullRequestLinking of [true, false]) { + assert.include( + buildRuntimeInstructions({ harness: "Codex", agentFeedback, pullRequestLinking }), + AGENT_FEEDBACK_INSTRUCTIONS[agentFeedback], + ); + } + } + }); + it("lists a multi-folder thread's folders and leaves single-folder text unchanged", () => { const base = { runtimeMode: "full-access", interactionMode: "default" } as const; const single = buildRuntimeInstructions({ harness: "Codex" }); @@ -86,6 +103,21 @@ describe("buildRuntimeInstructions", () => { }, }); assert.isTrue(listed.startsWith(`${single}\n\n\n`)); + const withFeedback = buildRuntimeInstructions({ harness: "Codex", agentFeedback: "auto" }); + assert.isTrue( + buildRuntimeInstructions({ + harness: "Codex", + agentFeedback: "auto", + runtimePolicy: { + ...base, + cwd: "/work/app", + workspace: { + folders: [{ name: "api", path: "/work/api", isGitRepository: true }], + extraRoots: [], + }, + }, + }).startsWith(`${withFeedback}\n\n\n`), + ); assert.deepEqual( listed .slice(single.length + 2) diff --git a/packages/provider-core/src/server/runtimeInstructions.ts b/packages/provider-core/src/server/runtimeInstructions.ts index bf532bbfeec57..0aec771e67660 100644 --- a/packages/provider-core/src/server/runtimeInstructions.ts +++ b/packages/provider-core/src/server/runtimeInstructions.ts @@ -1,5 +1,14 @@ +import type { AgentFeedbackMode } from "@t3tools/contracts"; + import type { ProviderAdapterV2RuntimePolicy } from "./ProviderAdapter.ts"; +/** None while agent feedback is off, so users who never opt in pay no context for it. */ +export const AGENT_FEEDBACK_INSTRUCTIONS = { + off: "", + "on-request": "Use `t3_feedback` only when the user asks you to send T3 feedback.", + auto: "`t3_feedback` reports are wanted and cheap. Send one, then continue, when a T3 tool or `t3` command fails or gives a wrong result, the user corrects how you use T3 Code, or a T3 capability you looked for is missing. Once per problem; also when the user asks. Only about T3 Code, never the user's code or other tools.", +} satisfies Record; + /** Session-invariant; harnesses with a native system-prompt append can carry it once per session. */ export const PULL_REQUEST_LINKING_INSTRUCTIONS = ` Link each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch. When pull_request_* tools are listed, use them, not gh or cafe, to read, list, open, edit, review, reply on, close, or merge PRs, and ci_logs and ci_rerun for their checks. pull_request_create links for you. @@ -16,6 +25,7 @@ When you need the user to decide or approve something, record each question with */ export function buildRuntimeInstructions(runtime: { readonly harness: string; + readonly agentFeedback?: AgentFeedbackMode; readonly model?: string | undefined; readonly modelName?: string | undefined; readonly reasoningEffort?: string | undefined; @@ -36,11 +46,16 @@ export function buildRuntimeInstructions(runtime: { const effortInfo = effort ? ` with ${effort} reasoning effort` : ""; // Fork: agents name the app esveo code, e.g. in PR attributions. const runtimeInfo = `In case you're asked: you are running in esveo code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in esveo code's files viewer.`; + const feedbackLine = AGENT_FEEDBACK_INSTRUCTIONS[runtime.agentFeedback ?? "off"]; + const feedback = feedbackLine ? `\n${feedbackLine}` : ""; const workspace = runtime.runtimePolicy === undefined ? "" : buildWorkspaceInstructions(runtime.runtimePolicy); + const linked = + runtime.pullRequestLinking === false + ? runtimeInfo + : `${runtimeInfo}\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`; return [ - runtimeInfo, - ...(runtime.pullRequestLinking === false ? [] : [PULL_REQUEST_LINKING_INSTRUCTIONS]), + linked + feedback, ...(workspace === "" ? [] : [workspace]), ...(runtime.threadDecisions ? [THREAD_DECISIONS_INSTRUCTIONS] : []), ].join("\n\n"); diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index d1638b8022029..df5ea84c4b440 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -395,7 +395,7 @@ export function subagentHoldsCompletion( export function delegatedTaskProgress(projection: { readonly runs: OrchestrationV2ThreadProjection["runs"]; readonly messages: ReadonlyArray< - Pick + Pick >; readonly subagents: ReadonlyArray< Pick @@ -410,9 +410,17 @@ export function delegatedTaskProgress(projection: { const workRuns = projection.runs.filter( (run) => !monitorRuns.has(run.id) && run.status !== "rolled_back", ); - const active = workRuns.some( - (run) => !terminal(run.status) && !(run.status === "queued" && run.queueHeld === true), + const held = (run: OrchestrationV2Run) => run.status === "queued" && run.queueHeld === true; + const active = workRuns.some((run) => !terminal(run.status) && !held(run)); + // Held wakes wait on nobody, but a held message the user wrote is the child's next work. + const userRunIds = new Set( + projection.messages.flatMap((message) => + message.createdBy === "user" && message.notification === undefined && message.runId !== null + ? [message.runId] + : [], + ), ); + const awaitsUserRun = workRuns.some((run) => held(run) && userRunIds.has(run.id)); const children = projection.subagents.some(subagentHoldsCompletion) || projection.providerThreads.some((thread) => @@ -423,12 +431,14 @@ export function delegatedTaskProgress(projection: { .toSorted((a, b) => (runRanAfter(a, b) ? -1 : runRanAfter(b, a) ? 1 : 0))[0]; return { state: - active || resultRun === undefined + active || awaitsUserRun || resultRun === undefined ? ("working" as const) : children ? ("waiting_for_children" as const) : ("result_available" as const), resultRun, + /** Working only because of a held message the user wrote, which a cancel does not wait for. */ + onlyAwaitsUserRun: awaitsUserRun && !active && resultRun !== undefined, }; } diff --git a/packages/provider-core/src/server/usage.ts b/packages/provider-core/src/server/usage.ts index ff4c14dfefe00..260f160421f33 100644 --- a/packages/provider-core/src/server/usage.ts +++ b/packages/provider-core/src/server/usage.ts @@ -62,8 +62,8 @@ export interface TranscriptUsageFormat { readonly usageMarkers: readonly [string, ...string[]]; parseLine(line: string, state: State): readonly UsageRecord[]; parseProjected(projected: unknown, state: State): readonly UsageRecord[]; - /** Cumulative malformed or inconsistent usage records, including skipped records. */ - readMalformedRecords?(state: State): number; + /** Timestamps of malformed or inconsistent usage records, including skipped records. */ + readMalformedRecords?(state: State): readonly number[]; /** * Present for formats whose records depend on earlier lines. The state at a * resume point is persisted in the scan cache through `schema`, so a grown diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index a426ba0b518ce..73be7b7081e1a 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -445,6 +445,54 @@ describe("CursorAdapterV2", () => { failure: null, answers: [], }, + { + reason: "no failure when the connection fails after the turn ended", + updates: [ + { type: "text-delta", text: "Done." }, + { type: "turn-ended" }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + requestId: "native-request", + status: "error" as const, + error: { message: "Connection failed repeatedly" }, + model: { id: "claude-fable-5" }, + durationMs: 1, + }), + failure: null, + }, + { + reason: "a connection failure before the turn ends", + updates: [ + { type: "text-delta", text: "Working." }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + requestId: "native-request", + status: "error" as const, + error: { message: "Connection failed repeatedly" }, + model: { id: "claude-fable-5" }, + durationMs: 1, + }), + failure: { class: "provider_error", message: "Connection failed repeatedly" }, + }, + { + reason: "a connection failure during a continuation after the turn ended", + updates: [ + { type: "text-delta", text: "Done." }, + { type: "turn-ended" }, + { type: "step-started", stepId: 2 }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + requestId: "native-request", + status: "error" as const, + error: { message: "Connection failed repeatedly" }, + model: { id: "claude-fable-5" }, + durationMs: 1, + }), + failure: { class: "provider_error", message: "Connection failed repeatedly" }, + }, { reason: "the token usage Cursor reported", // Cursor's inputTokens already include cache reads and writes. @@ -756,6 +804,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 241263052de4b..85653c250fce7 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -928,9 +928,11 @@ interface CursorProjectionTarget { const MAX_CURSOR_STREAMED_OUTPUT_CHARS = 256 * 1024; // After a turn ends, a retryable stream error can make Cursor's SDK resume from // an older checkpoint inside the same run. When those resumes save nothing, it -// ends the run with this error even though the answer was already delivered. -const CURSOR_RESUME_NO_PROGRESS_MESSAGE = - "Agent turn stopped after repeated resume attempts made no progress"; +// ends with either retry limit even though the answer was already delivered. +const CURSOR_POST_TURN_RETRY_ERRORS = new Set([ + "Agent turn stopped after repeated resume attempts made no progress", + "Connection failed repeatedly", +]); interface ActiveCursorToolCall { readonly callId: string; @@ -2510,6 +2512,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 +2528,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 +2594,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 +2610,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( context: input.context, status: input.status, completedAt, + ...(promptDropped ? { promptDropped: true as const } : {}), ...(contextUsage === undefined ? {} : { @@ -2633,6 +2647,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 +2658,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: null, threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), }, ); if (input.context.runtimeInstructions !== undefined) { @@ -2676,7 +2692,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( const isResumeFailureAfterTurnEnded = (context: ActiveCursorTurn, result: RunResult) => context.turnEnded && result.status === "error" && - result.error?.message === CURSOR_RESUME_NO_PROGRESS_MESSAGE; + CURSOR_POST_TURN_RETRY_ERRORS.has(result.error?.message ?? ""); const terminalStatus = ( context: ActiveCursorTurn, @@ -2889,11 +2905,12 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }); } const runtimeInstructions = buildRuntimeInstructions({ + agentFeedback: mcpServers === undefined ? "off" : (turnInput.agentFeedback ?? "off"), harness: "Cursor", model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy, }); - // Resend only on a new/compacted/rewound conversation or when the model changes. + // Resend only on a new/compacted/rewound conversation or when the instructions change. const sendRuntimeInstructions = delivered.runtime !== runtimeInstructions; const text = sendRuntimeInstructions ? userText.length === 0 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/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index f23f7ca84d7ea..7e0375e99a3ec 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -388,7 +388,8 @@ vi.mock("node:fs/promises", { spy: true }); describe("MuseAdapterV2", () => { it.effect("connects the thread's MCP credential on native start and resume", () => Effect.gen(function* () { - yield* (yield* McpProviderSessions.McpProviderSessions).set({ + const sessions = yield* McpProviderSessions.McpProviderSessions; + const config = { environmentId: EnvironmentId.make("test-environment"), threadId: THREAD_ID, providerSessionId: "test-session", @@ -396,11 +397,12 @@ describe("MuseAdapterV2", () => { endpoint: "http://127.0.0.1:43210/mcp", authorizationHeader: "Bearer thread-scoped-test-token", browserToolsAvailable: true, - }); + }; for (const nativeId of [undefined, "saved-native-session"]) { + yield* sessions.set(config); const fake = yield* makeFakeMuse(); fake.host.initializeResult.grantedCapabilities.push("sessionMcp"); - yield* makeHarness(fake, INSTANCE_ID, nativeId); + const harness = yield* makeHarness(fake, INSTANCE_ID, nativeId); const call = yield* fake.takeCall(nativeId ? "session/resume" : "session/start"); assert.deepStrictEqual(call.params.config, { mcpServers: { @@ -412,6 +414,13 @@ describe("MuseAdapterV2", () => { }, }, }); + yield* sessions.clear(THREAD_ID); + yield* harness.runtime.startTurn({ + ...(yield* turnInput(harness.providerThread, 1, harness.policy)), + agentFeedback: "auto", + }); + const turn = yield* fake.takeCall("turn/start"); + assert.match(JSON.stringify(turn.params.input), /t3_feedback/); } }).pipe(Effect.scoped, Effect.provide(testLayer)), ); diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 0b5835e0bad12..66c1fd1a505ff 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -356,6 +356,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( let relaunchable = false; let nativeSessionId: string | undefined; let thread: OrchestrationV2ProviderThread | undefined; + let hasT3Mcp = false; let active: ActiveTurn | undefined; let lastProviderTurn: OrchestrationV2ProviderTurn | undefined; let latestSubscriptionUsage: MuseSubscriptionUsage | undefined; @@ -2013,6 +2014,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( createdAt, updatedAt: createdAt, }; + hasT3Mcp = mcpSession !== undefined; session = { ...session, model: result.session.modelId ?? args.modelSelection.model, @@ -2191,6 +2193,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( { type: "text", text: buildRuntimeInstructions({ + agentFeedback: hasT3Mcp ? (turnInput.agentFeedback ?? "off") : "off", harness: "Muse Code", model: session.model ?? undefined, reasoningEffort: effort, 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/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index d0e1d27cc2a7b..6398e8ec74800 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -13,6 +13,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import { causeErrorTag } from "@t3tools/shared/observability"; import { + type AgentFeedbackMode, defaultInstanceIdForDriver, type ModelSelection, type OrchestrationV2AppThread, @@ -296,6 +297,7 @@ interface ActiveOpenCodeTurn { readonly appThread: OrchestrationV2AppThread; readonly modelSelection: ModelSelection; readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; + readonly agentFeedback: AgentFeedbackMode; readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; readonly providerThreadId: OrchestrationV2ProviderTurn["providerThreadId"]; readonly runOrdinal: number; @@ -2513,6 +2515,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function appThread: state.appThread, modelSelection: state.appThread.modelSelection, runtimePolicy: state.parentSubagent.parentTurn.runtimePolicy, + agentFeedback: state.parentSubagent.parentTurn.agentFeedback, providerTurnId, providerThreadId: providerTurn.providerThreadId, runOrdinal: state.parentSubagent.parentTurn.runOrdinal, @@ -3515,6 +3518,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function buildRuntimeInstructions({ harness: "OpenCode", model: turn.modelSelection.model, + agentFeedback: hasT3Mcp ? turn.agentFeedback : "off", runtimePolicy: turn.runtimePolicy, }), ] @@ -3788,6 +3792,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function appThread: turnInput.appThread, modelSelection: turnInput.modelSelection, runtimePolicy: turnInput.runtimePolicy, + agentFeedback: turnInput.agentFeedback ?? "off", providerTurnId, providerThreadId: turnInput.providerThread.id, runOrdinal: turnInput.runOrdinal, diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts index ff77d8ef72a2f..701ad57fe488a 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts @@ -467,6 +467,16 @@ describe("OpenCode2Client usage limits", () => { "unsupported", ], [503, {}, "probeFailed"], + [ + 503, + { + _tag: "ServiceUnavailableError", + message: + "OpenCode Console budgets are unavailable: StatusCode: non 2xx status code (401 GET https://opencode.ai/console/api/policies/current-budgets)", + service: "opencode", + }, + "probeFailed", + ], [401, {}, "probeFailed"], [200, { data: { workspace: {} } }, "probeFailed"], ] as const) { @@ -487,6 +497,8 @@ describe("OpenCode2Client usage limits", () => { else assert.strictEqual(result?.unavailable?.reason, reason); if ("data" in body && body.data === null) assert.include(result?.unavailable?.message ?? "", "signed in"); + if ("message" in body) + assert.include(result?.unavailable?.message ?? "", "OpenCode Console budgets"); } }), ); diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 9e14f8c4ef36b..9cee26a3fb20d 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -4430,6 +4430,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } const instructions = [ buildRuntimeInstructions({ + agentFeedback: mcpAvailable ? (turnInput.agentFeedback ?? "off") : "off", harness: "OpenCode", model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy, @@ -4726,7 +4727,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 +4741,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-opencode/src/server/v2/usageLimits.ts b/packages/provider-opencode/src/server/v2/usageLimits.ts index dd28770b9c5c4..bdf678e424692 100644 --- a/packages/provider-opencode/src/server/v2/usageLimits.ts +++ b/packages/provider-opencode/src/server/v2/usageLimits.ts @@ -61,6 +61,9 @@ const Providers = Schema.Struct({ ), }); +const ErrorBody = Schema.Struct({ message: Schema.String }); +const probeFailedMessage = "OpenCode could not read workspace usage."; + const resetTime = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); const budgetPercent = (spent: number, limit: number) => limit <= 0 ? 100 : clampPercent((spent / limit) * 100); @@ -81,9 +84,17 @@ export const readServerUsageLimits = Effect.fn("OpenCode2Client.usageLimits")(fu response.headers["content-type"]?.split(";")[0]?.trim() === "text/html") ) return undefined; - const body = yield* HttpClientResponse.filterStatusOk(response).pipe( - Effect.flatMap(HttpClientResponse.schemaBodyJson(ResponseBody)), - ); + // OpenCode names the upstream cause, such as an expired Console login, in its error body. + if (response.status < 200 || response.status >= 300) + return makeUnavailableUsageLimits({ + checkedAt, + reason: "probeFailed", + message: yield* HttpClientResponse.schemaBodyJson(ErrorBody)(response).pipe( + Effect.map((error) => error.message.trim() || probeFailedMessage), + Effect.orElseSucceed(() => probeFailedMessage), + ), + }); + const body = yield* HttpClientResponse.schemaBodyJson(ResponseBody)(response); if (body.data === null) return makeUnavailableUsageLimits({ checkedAt, @@ -186,7 +197,7 @@ export const readServerUsageLimits = Effect.fn("OpenCode2Client.usageLimits")(fu makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed", - message: "OpenCode could not read workspace usage.", + message: probeFailedMessage, }), ), ); 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 735265212c18f..eeccf605e6e46 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -171,6 +171,10 @@ "types": "./src/toolOutput.ts", "import": "./src/toolOutput.ts" }, + "./appLinks": { + "types": "./src/appLinks.ts", + "import": "./src/appLinks.ts" + }, "./htmlRender": { "types": "./src/htmlRender.ts", "import": "./src/htmlRender.ts" @@ -391,6 +395,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" @@ -535,6 +543,14 @@ "types": "./src/markdownGithubAlerts.ts", "import": "./src/markdownGithubAlerts.ts" }, + "./markdownChunks": { + "types": "./src/markdownChunks.ts", + "import": "./src/markdownChunks.ts" + }, + "./markdownHast": { + "types": "./src/markdownHast.ts", + "import": "./src/markdownHast.ts" + }, "./markdownFrontmatter": { "types": "./src/markdownFrontmatter.ts", "import": "./src/markdownFrontmatter.ts" @@ -662,6 +678,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": { @@ -676,6 +704,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:", @@ -695,8 +724,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/appLinks.test.ts b/packages/shared/src/appLinks.test.ts new file mode 100644 index 0000000000000..2e3556803208f --- /dev/null +++ b/packages/shared/src/appLinks.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { appLinkUrl } from "./appLinks.ts"; + +describe("appLinkUrl", () => { + it("accepts schemes another app opens", () => { + expect(appLinkUrl("obsidian://open?vault=vault&file=Note")).toBe( + "obsidian://open?vault=vault&file=Note", + ); + expect(appLinkUrl("t3-thread://v2/env/thread")).toBe("t3-thread://v2/env/thread"); + expect(appLinkUrl("mailto:a@example.com")).toBe("mailto:a@example.com"); + }); + + it("rejects schemes the browser loads itself, and non-URLs", () => { + for (const url of [ + "https://example.com", + "http://example.com", + "javascript:alert(1)", + "JavaScript:alert(1)", + "data:text/html,x", + "file:///etc/passwd", + "blob:https://example.com/id", + "about:blank", + "view-source:https://example.com", + "chrome://settings", + "filesystem:https://example.com/temporary/a", + "not a url", + ]) { + expect(appLinkUrl(url), url).toBeNull(); + } + }); +}); diff --git a/packages/shared/src/appLinks.ts b/packages/shared/src/appLinks.ts new file mode 100644 index 0000000000000..85ebe6a6922f7 --- /dev/null +++ b/packages/shared/src/appLinks.ts @@ -0,0 +1,22 @@ +/** Schemes the browser engine loads itself; every other scheme names an app the OS opens. */ +const BROWSER_PROTOCOLS = [ + "about:", + "blob:", + "chrome:", + "data:", + "devtools:", + "file:", + "filesystem:", + "http:", + "https:", + "javascript:", + "view-source:", +]; + +const browserProtocols: ReadonlySet = new Set(BROWSER_PROTOCOLS); + +/** The normalized URL when it is an app link, such as `obsidian:` or `mailto:`, otherwise null. */ +export function appLinkUrl(rawUrl: string): string | null { + const url = URL.parse(rawUrl); + return url === null || browserProtocols.has(url.protocol) ? null : url.href; +} 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..c8c17b84a9b7b 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -1,8 +1,19 @@ import { describe, expect, it } from "vite-plus/test"; -import { collectComposerInlineTokens, composerMathRanges } from "./composerInlineTokens.ts"; +import { + collectComposerInlineTokens as collectWithoutMath, + type CollectComposerInlineTokensOptions, + composerFileLinksToPlainText, + 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 +226,21 @@ 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$"]); + }); +}); + +describe("composerFileLinksToPlainText", () => { + it("shows file mentions by name and leaves other links as written", () => { + const mentions = ["src/foo.ts", ".gitignore", "pkg/__init__.py", "docs/My File (draft).md"] + .map(serializeComposerFileLink) + .join(" "); + expect(composerFileLinksToPlainText(`Review ${mentions}`)).toBe( + "Review foo.ts .gitignore __init__.py My File (draft).md", + ); + const links = "See [docs](https://example.com) and [the config](src/config.ts)"; + expect(composerFileLinksToPlainText(links)).toBe(links); }); }); diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index 992a9d08e4774..80a1b4d6916ae 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -1,4 +1,9 @@ -import { markdownMathRanges } from "./markdownMath.ts"; +import { fileBasename } from "./path.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 +23,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 +107,7 @@ function collectMentionTokens(text: string): ComposerInlineToken[] { */ export function composerMathRanges( text: string, + findMath: FindMathRanges, mentions: ReadonlyArray = collectMentionTokens(text), ) { let masked = text; @@ -110,7 +118,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,10 +165,26 @@ 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), ) .sort((left, right) => left.start - right.start); } + +/** Shows each `@`-file link by its file name, as its composer chip does, for one-line previews. */ +export function composerFileLinksToPlainText(text: string): string { + let result = ""; + let cursor = 0; + // The composer reads a link as a mention only before whitespace, so one may end the text. + for (const token of collectMentionTokens(`${text} `)) { + if (!token.source.startsWith("[")) continue; + result += text.slice(cursor, token.start) + fileBasename(token.value); + cursor = token.end; + } + return result + text.slice(cursor); +} diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts index 96a0a877d14df..2a95d6b34cd0a 100644 --- a/packages/shared/src/composerTrigger.ts +++ b/packages/shared/src/composerTrigger.ts @@ -137,6 +137,14 @@ export function replaceTextRange( return { text: nextText, cursor: safeStart + replacement.length }; } +/** A message that only invokes a slash command, such as `/context all`, not a path like `/src/a.ts`. */ +export function isSlashCommand(message: { + readonly text: string; + readonly attachments: ReadonlyArray; +}): boolean { + return message.attachments.length === 0 && /^\/[\w:-]+(?:\s|$)/u.test(message.text.trim()); +} + /** `/clear` as the whole message arms a fresh session instead of sending. */ export function isClearComposerCommand(text: string): boolean { return /^\/clear\s*$/i.test(text.trim()); diff --git a/packages/shared/src/markdownChunks.test.ts b/packages/shared/src/markdownChunks.test.ts new file mode 100644 index 0000000000000..a5cf2a8017b35 --- /dev/null +++ b/packages/shared/src/markdownChunks.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { splitMarkdown } from "./markdownChunks.ts"; + +const splitLargeMarkdown = (text: string, targetChars?: number) => + splitMarkdown(text, targetChars).chunks; + +const starts = (text: string) => + splitLargeMarkdown(text, 1).map((chunk) => chunk.text.split("\n")[0]); + +describe("splitMarkdown", () => { + it("cuts only where a new top-level block starts, and keeps every byte", () => { + const text = [ + "# Title", + "Intro paragraph", + "", + "- item one", + "", + " continued item", + "- item two", + "", + "2. ordered", + "", + "```md", + "# not a heading", + "", + "Not a paragraph", + "```", + "", + "> quote", + "", + "Closing paragraph", + "## Next", + "---", + "", + "| a | b |", + ].join("\n"); + const chunks = splitLargeMarkdown(text, 1); + expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text); + expect(chunks.reduce((sum, chunk) => sum + chunk.lines, 0)).toBe(text.split("\n").length); + expect(starts(text)).toEqual([ + "# Title", + "```md", + "> quote", + "Closing paragraph", + "## Next", + "| a | b |", + ]); + }); + + it("keeps a fence open until a matching closer", () => { + const text = ["````", "```", "", "# inside", "````", "", "after"].join("\n"); + expect(starts(text)).toEqual(["````", "after"]); + }); + + it("keeps HTML blocks and display math open across blank lines", () => { + const text = [ + "", + "", + "$$", + "", + "Inside math", + "$$", + "", + "
    ",
    +      "",
    +      "Preformatted",
    +      "
    ", + "", + "", + "", + "
    ", + "# literal", + "
    ", + "", + "after", + ].join("\n"); + expect(starts(text)).toEqual(["/], + [/^ {0,3}<\?/, /\?>/], + [/^ {0,3}/], + [/^ {0,3}/], + [/^ {0,3}\$\$/, /\$\$/], +]; + +// A tag name, not an autolink such as . +const HTML_BLOCK_START = /^ {0,3}<\/?[A-Za-z][A-Za-z0-9-]*(?=[\s/>]|$)/; + +/** Returns how to recognize the end of a block that `line` opens, or null for none. */ +function blockCloser(line: string): ((line: string) => boolean) | null { + const fence = FENCE_OPEN.exec(line)?.[1]; + if (fence) { + return (next) => { + const closer = FENCE_OPEN.exec(next)?.[1]; + return ( + closer !== undefined && + closer[0] === fence[0] && + closer.length >= fence.length && + !next.trim().slice(closer.length) + ); + }; + } + for (const [open, close] of SPANNING_BLOCKS) { + const opener = open.exec(line)?.[0]; + if (opener === undefined) continue; + return close.test(line.slice(opener.length)) ? null : (next) => close.test(next); + } + // Other HTML blocks (CommonMark types 6 and 7) run until a blank line. + return HTML_BLOCK_START.test(line) ? (next) => next.trim() === "" : null; +} + +export interface MarkdownChunk { + readonly text: string; + readonly lines: number; +} + +const FRONTMATTER_OPEN = /^\uFEFF?---[ \t]*\r?$/; +const FRONTMATTER_CLOSE = /^(?:---|\.\.\.)[ \t]*\r?$/; +// An opening rule with no closer is a thematic break, not frontmatter; stop waiting for one. +const FRONTMATTER_MAX_LINES = 1000; + +// A one-line link reference definition; footnotes are left alone so each piece does not grow +// a footnote section. +const LINK_DEFINITION = + /^ {0,3}\[(?!\^)(?:[^\]\\]|\\.)+\]:[ \t]*(?:<[^<>\n]*>|[^\s<]\S*)(?:[ \t]+(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^()\\]|\\.)*\)))?[ \t]*\r?$/; +// Definitions past this are not repeated into every piece; their parse cost would outweigh links. +const SHARED_DEFINITIONS_MAX_CHARS = 16 * 1024; + +export interface SplitMarkdown { + readonly chunks: readonly MarkdownChunk[]; + readonly definitions: string; +} + +/** + * Cuts Markdown into pieces of roughly `targetChars`, only at column-0 headings or paragraphs + * that start a new top-level block. Leading frontmatter stays in the first piece. Link + * definitions are collected so every piece can resolve them; footnotes resolve only inside their + * own piece, and duplicate heading slugs restart per piece. + */ +export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): SplitMarkdown { + const chunks: MarkdownChunk[] = []; + const definitions: string[] = []; + let lines: string[] = []; + let first = true; + let chars = 0; + let closes: ((line: string) => boolean) | null = null; + let afterBlankLine = false; + let afterDefinition = false; + let afterHeading = false; + let definitionChars = 0; + const flush = () => { + chunks.push({ text: lines.join("\n"), lines: lines.length }); + lines = []; + chars = 0; + }; + for (const line of text.split("\n")) { + if (closes !== null) { + if (closes(line)) closes = null; + } else if (first && FRONTMATTER_OPEN.test(line)) { + let seen = 0; + closes = (next) => FRONTMATTER_CLOSE.test(next) || ++seen >= FRONTMATTER_MAX_LINES; + } else { + const cut = + chars >= targetChars && + (ATX_HEADING.test(line) || + (afterBlankLine && BLOCK_START.test(line) && !ORDERED_ITEM.test(line))); + if (cut) flush(); + closes = blockCloser(line); + // A definition cannot interrupt a paragraph, so it follows a blank line, a heading or + // another definition. + const definition: boolean = + (first || afterBlankLine || afterDefinition || afterHeading) && LINK_DEFINITION.test(line); + afterDefinition = definition; + if (definition && definitionChars + line.length < SHARED_DEFINITIONS_MAX_CHARS) { + definitions.push(line.trim()); + definitionChars += line.length + 1; + } + } + first = false; + lines.push(line); + chars += line.length + 1; + afterBlankLine = line.trim() === ""; + afterHeading = closes === null && (ATX_HEADING.test(line) || THEMATIC_BREAK.test(line)); + } + flush(); + return { chunks, definitions: definitions.join("\n") }; +} + +/** Appends shared link definitions after a piece, leaving its own offsets unchanged. */ +export function withMarkdownDefinitions(text: string, definitions: string): string { + return definitions ? `${text}\n\n${definitions}` : text; +} 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 38bf4b59ad492..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); - }; -} - -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"], - 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/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts index 24910bc0bf9cf..71a9897b841f3 100644 --- a/packages/shared/src/nodeSqliteClient.test.ts +++ b/packages/shared/src/nodeSqliteClient.test.ts @@ -148,6 +148,23 @@ layer("NodeSqliteClient", (it) => { const largeText = "x".repeat(64 * 1024 + 1); +it.effect("a rowid above 2^53 does not leave a transaction open", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE big (id INTEGER PRIMARY KEY, name TEXT)`; + yield* sql`INSERT INTO big (id, name) VALUES (246166233861328896, 'first')`; + // BEGIN reports the connection's last insert rowid; a failure to convert it must not + // read as a failed BEGIN, or the open transaction is never rolled back. + yield* sql.withTransaction(sql`INSERT INTO big (name) VALUES ('second')`); + yield* sql.withTransaction(sql`UPDATE big SET name = 'third' WHERE name = 'second'`); + const rows = yield* sql<{ name: string }>`SELECT name FROM big ORDER BY id`; + assert.deepStrictEqual( + rows.map((row) => row.name), + ["first", "third"], + ); + }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))), +); + it.effect("reads integers on the values path as the caller asked, cached or not", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index da521a7c6036d..bb00de7459816 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -286,6 +286,8 @@ parentPort.on("message", (request) => { if (pendingBatch) Atomics.wait(received, 0, 0); parentPort.postMessage({ id, rows }); } else { + // A discarded result is read as BigInt: see the same line in the in-process client. + if (!raw) statement.setReadBigInts(true); const result = statement.run(...params); parentPort.postMessage({ id, rows: raw ? result : [] }); } @@ -854,6 +856,10 @@ const make = Effect.fn("makeWithDatabase")(function* ( if (arrays) statement.setReturnArrays(true); result = Exit.succeed(statement.all(...(params as any))); } else { + // `run` reports the connection's last insert rowid even for BEGIN. One above 2^53 + // throws on conversion after the statement already took effect, so a discarded + // result is read as BigInt. + if (mode !== "raw") statement.setReadBigInts(true); const value = statement.run(...(params as any)); result = Exit.succeed( mode === "raw" ? (value as unknown as ReadonlyArray) : [], 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/orchestrationV2ThreadError.ts b/packages/shared/src/orchestrationV2ThreadError.ts index 8987593a0b0a5..1e011eb1c64fd 100644 --- a/packages/shared/src/orchestrationV2ThreadError.ts +++ b/packages/shared/src/orchestrationV2ThreadError.ts @@ -86,6 +86,7 @@ export function orchestrationV2WorktreePending( (latest?.status === "preparing" || latest?.status === "failed" || latest?.status === "interrupted") && + latest.startedAt === null && latest.workspacePreparation?.type === "worktree" ); } 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/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index cad89fe0eb39a..fe7096230c398 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -364,6 +364,7 @@ const T3_MCP_TOOLS: Readonly> = { ["Handle", "Handling", "Handled", "pending questions"], "question-respond", ), + t3_workflow: tool(["Use", "Using", "Used", "workflow runs"], "thread-send"), t3_submit_output: tool(["Submit", "Submitting", "Submitted", "the result"], "thread-send"), t3_queue_list: tool(["List", "Listing", "Listed", "queued messages"], "queue-list"), t3_queue_read: tool(["Read", "Reading", "Read", "a queued message"], "queue-read"), 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 6e4600fe5a338..c71f1f36df2fb 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts @@ -414,7 +414,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 6cffe9ab0b3ab..f289e7406950f 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts @@ -495,7 +495,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/IssueTrackerHost.ts b/packages/source-control-core/src/server/IssueTrackerHost.ts index efc51b5046de2..eb85a2f711a5e 100644 --- a/packages/source-control-core/src/server/IssueTrackerHost.ts +++ b/packages/source-control-core/src/server/IssueTrackerHost.ts @@ -2,12 +2,12 @@ * What a standalone tracker package may ask of the server it runs in: the credential the user * saved in Settings. Git-host trackers never need it; their CLIs carry their own credentials. */ -import type { IssueTrackerKind } from "@t3tools/contracts"; +import type { IssueTrackerAccountId, IssueTrackerKind } from "@t3tools/contracts"; import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; +import * as Effect from "effect/Effect"; import type * as Option from "effect/Option"; -import type { IssueTrackerError } from "./IssueTracker.ts"; +import type { IssueTrackerApi, IssueTrackerError } from "./IssueTracker.ts"; export class IssueTrackerHost extends Context.Service< IssueTrackerHost, @@ -20,3 +20,53 @@ export class IssueTrackerHost extends Context.Service< }; } >()("@t3tools/source-control-core/server/IssueTrackerHost") {} + +/** + * The account a standalone tracker call is made as, set by the server around each call; null is + * the tracker's first account. A tracker never reads it: `credentials.get` does. + */ +export const IssueTrackerAccount = Context.Reference( + "@t3tools/source-control-core/server/IssueTrackerHost/IssueTrackerAccount", + { defaultValue: () => null }, +); + +/** The tracker with every call made as one account, so no call site can forget to name it. */ +export function asIssueTrackerAccount( + api: IssueTrackerApi, + accountId: IssueTrackerAccountId | null, +): IssueTrackerApi { + if (accountId === null) return api; + const as = (effect: Effect.Effect) => + Effect.provideService(effect, IssueTrackerAccount, accountId); + const { + getIssueLink, + create, + comment, + update, + setState, + setReaction, + listTemplates, + listCandidates, + } = api; + // Every key is required here, so a method added to IssueTrackerApi fails to compile until it + // is wrapped instead of silently running as the first account. + const wrapped: { readonly [K in keyof IssueTrackerApi]-?: IssueTrackerApi[K] | undefined } = { + kind: api.kind, + capabilities: api.capabilities, + getViewer: (input) => as(api.getViewer(input)), + listIssues: (input) => as(api.listIssues(input)), + getIssue: (input) => as(api.getIssue(input)), + getComments: (input) => as(api.getComments(input)), + getIssueLink: getIssueLink && ((input) => as(getIssueLink(input))), + create: create && ((input) => as(create(input))), + comment: comment && ((input) => as(comment(input))), + update: update && ((input) => as(update(input))), + setState: setState && ((input) => as(setState(input))), + setReaction: setReaction && ((input) => as(setReaction(input))), + listTemplates: listTemplates && ((input) => as(listTemplates(input))), + listCandidates: listCandidates && ((input) => as(listCandidates(input))), + }; + return Object.fromEntries( + Object.entries(wrapped).filter(([, value]) => value !== undefined), + ) as unknown as IssueTrackerApi; +} 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 62ec94d7d67fe..0cc6654adf021 100644 --- a/packages/source-control-core/src/server/discovery.ts +++ b/packages/source-control-core/src/server/discovery.ts @@ -357,7 +357,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-forgejo/src/server/ForgejoSourceControlProvider.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts index 7b6e475f99152..1c088a58e8876 100644 --- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts +++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts @@ -24,6 +24,7 @@ import { unknownRemoteProvider, } from "@t3tools/source-control-core/shared/definition"; import { ForgejoPullRequestSchema, toForgejoChangeRequest } from "./forgejoPullRequests.ts"; +import * as ForgejoChangeRequestTemplate from "./forgejoChangeRequestTemplate.ts"; const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError); @@ -303,7 +304,7 @@ interface UnfilteredPulls { export const make = Effect.gen(function* () { const cli = yield* ForgejoCli.ForgejoCli; const fs = yield* FileSystem.FileSystem; - const { process } = yield* SourceControlHost.SourceControlHost; + const { git, process } = yield* SourceControlHost.SourceControlHost; const request = >( input: ForgejoCli.ForgejoApiInput, schema: S, @@ -488,6 +489,11 @@ export const make = Effect.gen(function* () { }, (effect, input) => effect.pipe(mapError("listChangeRequests", input.cwd)), ), + readChangeRequestTemplate: Effect.fn("ForgejoSourceControlProvider.readChangeRequestTemplate")( + function ({ cwd, treeish }) { + return ForgejoChangeRequestTemplate.detect(cwd, treeish, git.execute); + }, + ), getChangeRequest: Effect.fn("ForgejoSourceControlProvider.getChangeRequest")(function (input) { return getPull(input).pipe( Effect.map(toForgejoChangeRequest), diff --git a/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts new file mode 100644 index 0000000000000..87f27e315406c --- /dev/null +++ b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts @@ -0,0 +1,100 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; + +import * as ForgejoCli from "./ForgejoCli.ts"; +import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts"; + +const templateRepository = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { git } = yield* SourceControlHost.SourceControlHost; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-forgejo-pr-template-" }); + const runGit = (args: ReadonlyArray) => + git.execute({ operation: "forgejoChangeRequestTemplate.test.git", cwd, args }); + yield* runGit(["init", "--initial-branch=main", "--template="]); + yield* runGit(["config", "user.email", "test@example.com"]); + yield* runGit(["config", "user.name", "Test User"]); + const provider = yield* ForgejoSourceControlProvider.make; + + return { + runGit, + writeTemplate: (relativePath: string, body: string) => + Effect.gen(function* () { + const file = path.join(cwd, relativePath); + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, body); + }), + commit: Effect.gen(function* () { + yield* runGit(["add", "-A"]); + yield* runGit(["commit", "--allow-empty", "-m", "Set pull request template"]); + }), + read: (treeish: string) => + provider.readChangeRequestTemplate?.({ cwd, treeish }) ?? Effect.succeedNone, + }; +}); + +const testLayer = Layer.mergeAll( + TestSourceControlHost.layerWithRealGit(), + Layer.mock(ForgejoCli.ForgejoCli)({}), + NodeServices.layer, +); + +it.live("reads the Gitea template committed to the target branch", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + yield* repo.commit; + yield* repo.runGit(["branch", "feature"]); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Expected on the PR"); + yield* repo.commit; + yield* repo.runGit(["checkout", "feature"]); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Working tree only"); + + assert.deepStrictEqual(yield* repo.read("main"), Option.some("## Expected on the PR")); + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.none()); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + +it.live("uses the first non-empty Markdown template in Forgejo's lookup order", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + yield* repo.writeTemplate("pull_request_template.md", " \n"); + yield* repo.writeTemplate(".forgejo/PULL_REQUEST_TEMPLATE.md", "## Forgejo"); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Gitea"); + yield* repo.commit; + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.some("## Forgejo")); + + yield* repo.writeTemplate("pull_request_template.md", "## Root"); + yield* repo.commit; + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.some("## Root")); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + +it.live("rejects a committed template symlink and caps the fallback blob", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + const fallback = "x".repeat(9_000); + yield* repo.writeTemplate(".github/pull_request_template.md", fallback); + yield* repo.writeTemplate("link-target", "README.md"); + yield* repo.commit; + const linkBlob = yield* repo.runGit(["rev-parse", "HEAD:link-target"]); + yield* repo.runGit([ + "update-index", + "--add", + "--cacheinfo", + `120000,${linkBlob.stdout.trim()},pull_request_template.md`, + ]); + yield* repo.runGit(["commit", "-m", "Record a template symlink"]); + + assert.deepStrictEqual( + yield* repo.read("HEAD"), + Option.some(`${fallback.slice(0, 8_000)}\n\n[truncated]`), + ); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); diff --git a/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts new file mode 100644 index 0000000000000..0ffbc33956b7d --- /dev/null +++ b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts @@ -0,0 +1,63 @@ +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; + +// Forgejo's Markdown lookup order also preserves Gitea's root, .gitea, .github order. +const TEMPLATE_PATHS = ["", ".forgejo/", ".gitea/", ".github/", "docs/"].flatMap((directory) => [ + `${directory}PULL_REQUEST_TEMPLATE.md`, + `${directory}pull_request_template.md`, +]); +const TEMPLATE_MAX_BYTES = 8_000; +const TREE_LIST_MAX_BYTES = 100_000; +const TRUNCATION_MARKER = "[truncated]"; + +type ExecuteGit = SourceControlHost.SourceControlHost["Service"]["git"]["execute"]; + +export const detect = Effect.fn("forgejoChangeRequestTemplate.detect")( + function* (cwd: string, treeish: string, executeGit: ExecuteGit) { + const listing = yield* executeGit({ + operation: "forgejoChangeRequestTemplate.listTemplates", + cwd, + args: ["ls-tree", "-z", "--full-tree", treeish, "--", ...TEMPLATE_PATHS], + maxOutputBytes: TREE_LIST_MAX_BYTES, + appendTruncationMarker: true, + }); + if (listing.stdoutTruncated) { + return Option.none(); + } + + // Read only regular blobs from the target tree, including when the worktree has a symlink. + const objectsByPath = new Map(); + for (const record of listing.stdout.split("\0")) { + const entry = /^100(?:644|755) blob ([0-9a-f]{40,64})\t(.+)$/.exec(record); + if (entry?.[1] && entry[2]) { + objectsByPath.set(entry[2], entry[1]); + } + } + + for (const path of TEMPLATE_PATHS) { + const objectId = objectsByPath.get(path); + if (!objectId) { + continue; + } + const blob = yield* executeGit({ + operation: "forgejoChangeRequestTemplate.readTemplate", + cwd, + args: ["cat-file", "blob", objectId], + maxOutputBytes: TEMPLATE_MAX_BYTES, + appendTruncationMarker: true, + }); + const template = blob.stdout.trim(); + if (template.length > 0) { + return Option.some( + blob.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER) + ? `${template}\n\n${TRUNCATION_MARKER}` + : template, + ); + } + } + return Option.none(); + }, + Effect.orElseSucceed(() => Option.none()), +); 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/patches/effect@4.1.5.patch b/patches/effect@4.1.5.patch new file mode 100644 index 0000000000000..91026f0d15bd7 --- /dev/null +++ b/patches/effect@4.1.5.patch @@ -0,0 +1,4086 @@ +diff --git a/dist/ai/McpSchema.d.ts b/dist/ai/McpSchema.d.ts +index 8f86c27..aed42ae 100644 +--- a/dist/ai/McpSchema.d.ts ++++ b/dist/ai/McpSchema.d.ts +@@ -941,6 +941,52 @@ export declare const HEADER_MISMATCH_ERROR_CODE: -32020; + * @since 4.0.6 + */ + export declare const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE: -32022; ++/** ++ * Represents the MCP error code for a referenced entity that does not exist, ++ * such as an unknown event name. `data.kind` may say which. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const NOT_FOUND_ERROR_CODE: -32023; ++/** ++ * Represents the MCP error code for a principal that is not permitted, or ++ * whose access was revoked. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const FORBIDDEN_ERROR_CODE: -32024; ++/** ++ * Represents the MCP error code for a server-imposed limit or quota. ++ * `data.limit` names it. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const RESOURCE_EXHAUSTED_ERROR_CODE: -32025; ++/** ++ * Represents the MCP error code for a well-formed request that asks for a ++ * capability or option not supported here. `data` identifies it, for example ++ * `{ feature: "deliveryMode", value: "push" }`. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const UNSUPPORTED_ERROR_CODE: -32026; ++/** ++ * Represents the MCP error code for a client-supplied callback endpoint that ++ * failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const CALLBACK_ENDPOINT_ERROR_CODE: -32027; + declare const ParseError_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"NotFound">; ++ readonly code: Schema.tag<-32023>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a referenced entity that does not exist. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class NotFound extends NotFound_base { ++} ++declare const Forbidden_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"Forbidden">; ++ readonly code: Schema.tag<-32024>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a principal that is not permitted. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class Forbidden extends Forbidden_base { ++} ++declare const ResourceExhausted_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"ResourceExhausted">; ++ readonly code: Schema.tag<-32025>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a server-imposed limit or quota. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class ResourceExhausted extends ResourceExhausted_base { ++} ++declare const Unsupported_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"Unsupported">; ++ readonly code: Schema.tag<-32026>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a capability or option not supported here. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class Unsupported extends Unsupported_base { ++} ++declare const CallbackEndpointError_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"CallbackEndpointError">; ++ readonly code: Schema.tag<-32027>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a callback endpoint that failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class CallbackEndpointError extends CallbackEndpointError_base { ++} + /** + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. +@@ -1880,6 +2001,66 @@ declare const Skill_base: Schema.Class; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDelivery = typeof EventDelivery.Type; ++/** ++ * An event type listed by `events/list`: its subscription arguments, its ++ * payload, and the delivery modes it supports. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const EventDescriptor: Schema.Struct<{ ++ readonly name: Schema.String; ++ readonly description: Schema.decodeTo>, Schema.optionalKey, never, never>; ++ readonly delivery: Schema.$Array>; ++ readonly inputSchema: Schema.$Record; ++ readonly payloadSchema: Schema.$Record; ++ readonly _meta: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++}>; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDescriptor = typeof EventDescriptor.Type; ++/** ++ * One delivered event. `cursor` is the subscription's position after it, on ++ * push and webhook delivery; poll carries the cursor on the result. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const EventOccurrence: Schema.Struct<{ ++ readonly eventId: Schema.String; ++ readonly name: Schema.String; ++ readonly timestamp: Schema.String; ++ readonly data: Schema.$Record; ++ readonly cursor: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++ readonly _meta: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++}>; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventOccurrence = typeof EventOccurrence.Type; + declare const PromptArgument_base: Schema.Opaque Effect.Effect Layer.Layer; ++ ++/** ++ * A failure an event handler reports to the client: a JSON-RPC error on a ++ * poll or when a push stream opens, and `notifications/events/terminated` ++ * once it is open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventError = ++ | InvalidParams ++ | InternalError ++ | McpSchema.NotFound ++ | McpSchema.Forbidden ++ | McpSchema.ResourceExhausted ++ | McpSchema.Unsupported ++ ++/** ++ * Where a poll starts. `cursor` is `null` to start from now, which replays ++ * nothing. With a cursor, replay starts at whichever is later: the cursor, or ++ * `maxAgeMs` before now. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * Where a push stream starts, read as for {@link EventPollRequest}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventStreamRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * One occurrence, with its payload as the event's `payload` schema types it. ++ * `eventId` stays the same however often the occurrence is delivered. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOccurrence
    { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: A ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * A poll's answer. `truncated` says delivery started later than the cursor, ++ * and `hasMore` that `maxEvents` cut the batch short. `nextPollMs` defaults ++ * to 30 seconds. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollResult { ++ readonly events: ReadonlyArray> ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly hasMore?: boolean | undefined ++ readonly nextPollMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries: an occurrence and the cursor after it; a ++ * position checked without a match, which the next heartbeat reports; a gap, ++ * sent as a fresh `notifications/events/active` with `truncated`; or an error ++ * that leaves the stream open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EventOccurrence) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventError } ++ ++/** ++ * An accepted push subscription: where it starts, and its items. A failure ++ * of `items` ends it. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly items: Stream.Stream, EventError, R> ++} ++ ++/** ++ * Options for {@link registerEvent} and {@link event}. ++ * ++ * **Details** ++ * ++ * `parameters` types the subscription arguments, an empty object by default, ++ * and `payload` the occurrences' `data`; both are advertised as JSON Schema ++ * by `events/list`. `poll` offers poll delivery and `stream` push delivery, ++ * and at least one is required. With {@link EventWebhooks} provided where the ++ * event is registered, `stream` also backs webhook delivery. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOptions, Payload extends Schema.Codec, R> { ++ readonly name: string ++ readonly description?: string | undefined ++ readonly parameters?: Params | undefined ++ readonly payload: Payload ++ readonly _meta?: Readonly> | undefined ++ readonly annotations?: Context.Context | undefined ++ readonly poll?: ++ | (( ++ args: Params["Type"], ++ request: EventPollRequest ++ ) => Effect.Effect, EventError, R>) ++ | undefined ++ readonly stream?: ++ | (( ++ args: Params["Type"], ++ request: EventStreamRequest ++ ) => Effect.Effect, EventError, R | Scope.Scope>) ++ | undefined ++} ++ ++/** ++ * Registers an event type under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * The server declares `io.modelcontextprotocol/events` on revision ++ * `2026-07-28` once any event type is registered, and answers `events/list`, ++ * `events/poll` and `events/stream`. A push stream runs `stream` for its ++ * lifetime inside the request's middleware, sends heartbeats carrying the ++ * last cursor, and ends when the client goes away. Services read by `poll` ++ * and `stream` are request-level, as for tools. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const registerEvent: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Effect.Effect>; ++/** ++ * Creates a layer that registers an event type under the MCP Events ++ * extension (SEP-3415). ++ * ++ * @see {@link registerEvent} for the Effect-level event registration API ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const event: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Layer.Layer>; ++declare const CallbackRejected_base: new = {}>(args: import("../Types.ts").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("../Cause.ts").YieldableError & { ++ readonly _tag: "CallbackRejected"; ++} & Readonly; ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare class CallbackRejected extends CallbackRejected_base<{ ++ readonly message: string; ++}> { ++} ++/** ++ * Decides which webhook callback URLs may be reached. ++ * ++ * **Details** ++ * ++ * `check` runs when a subscription is created and again before every POST. ++ * Resolving a host name needs the platform, so the default refuses every URL: ++ * a server that offers webhooks provides a guard that resolves the host and ++ * refuses addresses that are not globally routable. That check alone cannot ++ * stop DNS rebinding, so the `HttpClient` given to {@link layerEventWebhooks} ++ * must connect only to the address it validated, sending the original host ++ * name in `Host` and TLS SNI, and must not follow redirects. `allowsPlaintext` ++ * admits an `http:` URL, which only a local test setup should do. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const CallbackGuard: Context.Reference<{ ++ readonly check: (url: URL) => Effect.Effect; ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined; ++}>; ++declare const EventWebhooks_base: Context.ServiceClass; ++}>; ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * Event types registered with a `stream` where this service is present also ++ * offer webhook delivery. `events/subscribe` validates the callback, verifies ++ * the endpoint with a challenge, and runs the event's `stream` for the ++ * subscription's lifetime, POSTing each occurrence with Standard Webhooks ++ * signatures, one at a time, retrying with backoff. Subscriptions live in ++ * memory: every grant is finite, between a minute and an hour, so a client ++ * refreshing from its cursor recreates what a restart lost. A failure of the ++ * stream, such as `Forbidden` when access is revoked, ends the subscription ++ * with a `terminated` envelope. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare class EventWebhooks extends EventWebhooks_base { ++} ++/** ++ * Options for {@link layerEventWebhooks}. ++ * ++ * **Details** ++ * ++ * `principal` names the authenticated subject of an `events/subscribe` or ++ * `events/unsubscribe` request, read from the request's services. It fails ++ * with `Forbidden` for a caller that may not subscribe; webhook delivery ++ * requires an authenticated principal. A subscription's identity is its ++ * principal, callback URL, event name and arguments, so the principal must ++ * stay the same across token refreshes. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventWebhooksOptions { ++ readonly principal: Effect.Effect; ++} ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const layerEventWebhooks: (options: EventWebhooksOptions) => Layer.Layer; + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/dist/ai/McpServer.js b/dist/ai/McpServer.js +index 4bf6bca..5ad258e 100644 +--- a/dist/ai/McpServer.js ++++ b/dist/ai/McpServer.js +@@ -16,6 +16,8 @@ import * as Cause from "../Cause.js"; + import * as Clock from "../Clock.js"; + import * as Context from "../Context.js"; + import * as Digest from "../crypto/Digest.js"; ++import * as Mac from "../crypto/Mac.js"; ++import * as SecureRandom from "../crypto/SecureRandom.js"; + import * as Data from "../Data.js"; + import * as Deferred from "../Deferred.js"; + import * as Duration from "../Duration.js"; +@@ -26,6 +28,7 @@ import * as Exit from "../Exit.js"; + import * as Fiber from "../Fiber.js"; + import * as FindMyWay from "../http/FindMyWay.js"; + import * as Headers from "../http/Headers.js"; ++import * as HttpClient from "../http/HttpClient.js"; + import { appendPreResponseHandlerUnsafe } from "../http/HttpEffect.js"; + import * as HttpRouter from "../http/HttpRouter.js"; + import * as HttpServerRequest from "../http/HttpServerRequest.js"; +@@ -55,6 +58,7 @@ import * as McpCore from "./internal/mcpCore.js"; + import * as McpProtocolInternal from "./internal/mcpProtocol.js"; + import * as McpRuntime from "./internal/mcpRuntime.js"; + import * as McpSkills from "./internal/mcpSkills.js"; ++import * as McpWebhooks from "./internal/mcpWebhooks.js"; + import * as InternalStructuredOutput from "./internal/structured-output.js"; + import * as McpSchema from "./McpSchema.js"; + import { CallToolResult, ElicitationDeclined, EnabledWhen, GetPromptResult, InternalError, InvalidParams, InvalidRequest, isParam, McpRequestContext, McpServerClient, McpServerClientMiddleware, MethodNotFound, Prompt, Resource, ResourceTemplate, ServerNotificationRpcs, TextContent, Tool as McpTool, ToolJson } from "./McpSchema.js"; +@@ -413,6 +417,9 @@ const notFound = (method, target) => { + return new McpCore.SkillNotFound({ + uri: target + }); ++ case "events/poll": ++ case "events/stream": ++ return McpCore.eventNotFound(target); + } + }; + const isHidden = error => error instanceof Hidden; +@@ -2637,6 +2644,155 @@ export const registerSkill = /*#__PURE__*/Effect.fnUntraced(function* (options) + * @since 4.1.1 + */ + export const skill = options => Layer.effectDiscard(registerSkill(options)); ++// ============================================================================= ++// Events ++// ============================================================================= ++const DEFAULT_NEXT_POLL_MS = 30_000; ++/** ++* Registers an event type under the MCP Events extension (SEP-3415). ++* ++* **Details** ++* ++* The server declares `io.modelcontextprotocol/events` on revision ++* `2026-07-28` once any event type is registered, and answers `events/list`, ++* `events/poll`, `events/stream`, and with {@link EventWebhooks} ++* `events/subscribe` and `events/unsubscribe`. A push stream runs `stream` for its ++* lifetime inside the request's middleware, sends heartbeats carrying the ++* last cursor, and ends when the client goes away. Services read by `poll` ++* and `stream` are request-level, as for tools. ++* ++* @stability unstable ++* @category events ++* @since 4.1.4 ++*/ ++export const registerEvent = Effect.fnUntraced(function* (options) { ++ const { name, poll, stream } = options; ++ if (poll === undefined && stream === undefined) { ++ return yield* Effect.die(new Cause.IllegalArgumentError(`Event ${name}: give it poll, stream or both`)); ++ } ++ const registry = yield* McpServer; ++ const { core, globalMiddleware } = internalState.get(registry); ++ const services = yield* Effect.context(); ++ const annotations = options.annotations ?? Context.empty(); ++ const { invoke, visible } = makeInvoke(services, globalMiddleware); ++ const webhooks = stream === undefined ++ ? undefined ++ : Option.getOrUndefined(Option.map(Context.getOption(services, EventWebhooks), (service) => webhooksState.get(service))); ++ const parameters = options.parameters ?? Schema.Struct({}); ++ const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)); ++ const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)); ++ const argumentsOf = (args) => decodeArguments(args).pipe(Effect.mapError((error) => new InvalidParams({ message: error.message }))); ++ const encodeEvent = (event) => encodePayload(event.data).pipe(Effect.flatMap((data) => Predicate.isReadonlyObject(data) ? Effect.succeed(data) : Effect.fail(data)), Effect.map((data) => ({ ++ eventId: event.eventId, ++ timestamp: event.timestamp, ++ data, ++ ...(event._meta === undefined ? {} : { _meta: event._meta }) ++ })), Effect.mapError(() => new InternalError({ message: `Event '${name}' payload failed to encode` }))); ++ yield* core.events.register({ ++ descriptor: { ++ name, ++ ...(options.description === undefined ? {} : { description: options.description }), ++ delivery: [ ++ ...(poll === undefined ? [] : ["poll"]), ++ ...(stream === undefined ? [] : ["push"]), ++ ...(webhooks === undefined ? [] : ["webhook"]) ++ ], ++ inputSchema: toolJsonSchema(parameters, false), ++ payloadSchema: toolJsonSchema(options.payload, false), ++ ...(options._meta === undefined ? {} : { _meta: options._meta }) ++ }, ++ isVisible: isEnabled(annotations), ++ visible: visible("events/list", name), ++ webhooks, ++ decodeArguments: argumentsOf, ++ poll: poll === undefined ? undefined : (request, invocation) => invoke(Effect.gen(function* () { ++ const result = yield* poll(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }); ++ return { ++ events: yield* Effect.forEach(result.events, encodeEvent), ++ cursor: result.cursor, ++ truncated: result.truncated ?? false, ++ hasMore: result.hasMore ?? false, ++ nextPollMs: result.nextPollMs ?? DEFAULT_NEXT_POLL_MS ++ }; ++ }), invocation, { method: "events/poll", target: name, payload: request }), ++ stream: stream === undefined ? undefined : (request, invocation, deliver) => invoke(Effect.scoped(Effect.gen(function* () { ++ const args = request.decoded !== undefined ? request.decoded.value : yield* argumentsOf(request.arguments); ++ const subscription = yield* stream(args, { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs ++ }); ++ // The items run on the delivery fiber, so they keep this request's services. ++ const context = yield* Effect.context(); ++ const items = subscription.items.pipe(Stream.mapEffect((item) => item._tag === "Event" ++ ? encodeEvent(item).pipe(Effect.map((event) => ({ ...event, _tag: "Event", cursor: item.cursor })), Effect.catch((error) => Effect.succeed({ _tag: "Error", error }))) ++ : Effect.succeed(item)), Stream.provideContext(context)); ++ yield* deliver({ cursor: subscription.cursor, truncated: subscription.truncated ?? false, items }); ++ })), invocation, { method: "events/stream", target: name, payload: request }) ++ }); ++}); ++/** ++* Creates a layer that registers an event type under the MCP Events ++* extension (SEP-3415). ++* ++* @see {@link registerEvent} for the Effect-level event registration API ++* ++* @stability unstable ++* @category events ++* @since 4.1.4 ++*/ ++export const event = (options) => Layer.effectDiscard(registerEvent(options)); ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class CallbackRejected extends /*#__PURE__*/Data.TaggedError("CallbackRejected") {} ++/** ++ * Decides which webhook callback URLs may be reached. The default refuses ++ * every URL; see the source for the contract a platform guard keeps. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const CallbackGuard = /*#__PURE__*/Context.Reference("effect/ai/McpServer/CallbackGuard", { ++ defaultValue: () => ({ ++ check: (url) => Effect.fail(new CallbackRejected({ message: `No callback guard admits ${url.host}` })) ++ }) ++}); ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class EventWebhooks extends /*#__PURE__*/Context.Service()("effect/ai/McpServer/EventWebhooks") {} ++const webhooksState = /*#__PURE__*/new WeakMap(); ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const layerEventWebhooks = (options) => Layer.effect(EventWebhooks, Effect.gen(function* () { ++ const webhooks = yield* McpWebhooks.make({ ++ principal: options.principal, ++ guard: yield* CallbackGuard, ++ client: yield* HttpClient.HttpClient ++ }); ++ const service = EventWebhooks.of({ size: webhooks.size }); ++ webhooksState.set(service, webhooks); ++ return service; ++}).pipe(Effect.provide(Layer.mergeAll(Mac.layerWebCrypto, Digest.layerWebCrypto).pipe(Layer.provideMerge(SecureRandom.layerWebCrypto))))); + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/dist/ai/internal/mcpCore.js b/dist/ai/internal/mcpCore.js +index 4c416a8..50d2d34 100644 +--- a/dist/ai/internal/mcpCore.js ++++ b/dist/ai/internal/mcpCore.js +@@ -75,6 +75,15 @@ export const ClientNotification = /*#__PURE__*/Data.taggedEnum(); + * @internal + */ + export const ServerNotification = /*#__PURE__*/Data.taggedEnum(); ++/** ++ * @internal ++ */ ++export const eventNotFound = name => new McpSchema.NotFound({ ++ message: `Event '${name}' not found`, ++ data: { ++ kind: "event" ++ } ++}); + // Whether one skill directory contains the other, or both are the same. + const skillsOverlap = (a, b) => { + const rootA = a.slice(0, -"/SKILL.md".length); +@@ -90,6 +99,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + const resourceTemplateRegistrations = []; + const promptRegistrations = new Map(); + const skillRegistrations = new Map(); ++ const eventRegistrations = new Map(); + const skillFiles = new Set(); + const completionRegistrations = new Map(); + const filterList = (registrations, invocation) => Effect.map(Effect.filter(Arr.filter(registrations, entry => entry.isVisible(invocation.protocol)), entry => entry.visible === undefined ? Effect.succeed(true) : entry.visible(invocation)), entries => entries.map(entry => entry.descriptor)); +@@ -234,11 +244,22 @@ export const make = /*#__PURE__*/Effect.sync(() => { + return Array.from(children.values()).sort((a, b) => a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : 0); + }) + }; ++ const events = { ++ register: registration => Effect.sync(() => { ++ eventRegistrations.set(registration.descriptor.name, registration); ++ }), ++ list: invocation => filterList(eventRegistrations.values(), invocation), ++ get: (name, invocation) => Effect.suspend(() => { ++ const registration = eventRegistrations.get(name); ++ return registration !== undefined && registration.isVisible(invocation.protocol) ? Effect.succeed(registration) : Effect.fail(eventNotFound(name)); ++ }) ++ }; + const registrationPresence = Effect.sync(() => ({ + tools: registrations.size > 0, + resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, + prompts: promptRegistrations.size > 0, +- skills: skillRegistrations.size > 0 ++ skills: skillRegistrations.size > 0, ++ events: eventRegistrations.size > 0 + })); + return { + tools, +@@ -246,6 +267,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + prompts, + completions, + skills, ++ events, + registrationPresence + }; + }); +diff --git a/dist/ai/internal/mcpEvents.d.ts b/dist/ai/internal/mcpEvents.d.ts +new file mode 100644 +index 0000000..cb0ff5c +--- /dev/null ++++ b/dist/ai/internal/mcpEvents.d.ts +@@ -0,0 +1 @@ ++export {}; +diff --git a/dist/ai/internal/mcpEvents.js b/dist/ai/internal/mcpEvents.js +new file mode 100644 +index 0000000..d875046 +--- /dev/null ++++ b/dist/ai/internal/mcpEvents.js +@@ -0,0 +1,265 @@ ++/** ++ * The Events extension (SEP-3415): wire schemas on revision 2026-07-28 and ++ * the delivery loop behind a push stream. ++ */ ++import * as Cause from "../../Cause.js"; ++import * as Clock from "../../Clock.js"; ++import * as Duration from "../../Duration.js"; ++import * as Effect from "../../Effect.js"; ++import * as Option from "../../Option.js"; ++import * as Queue from "../../Queue.js"; ++import * as Result from "../../Result.js"; ++import * as Rpc from "../../rpc/Rpc.js"; ++import * as RpcGroup from "../../rpc/RpcGroup.js"; ++import * as Schema from "../../Schema.js"; ++import * as Stream from "../../Stream.js"; ++import * as PublicMcpSchema from "../McpSchema.js"; ++import * as McpProtocol from "./mcpProtocol.js"; ++import * as Stateless from "./mcpSchema/v2026_07_28.js"; ++/** ++ * @internal ++ */ ++export const EXTENSION_ID = "io.modelcontextprotocol/events"; ++/** ++ * Adds the extension declaration while any event type is registered. The ++ * server sends no `notifications/events/list_changed`, so its settings object ++ * is empty. ++ * ++ * @internal ++ */ ++export const declareExtension = (extensions, servesEvents) => servesEvents ? { ...extensions, [EXTENSION_ID]: {} } : extensions; ++const methodNotFound = (method) => new McpProtocol.ProtocolError({ ++ code: PublicMcpSchema.METHOD_NOT_FOUND_ERROR_CODE, ++ message: `Method not found: ${method}` ++}); ++/** ++ * Fails with `Method not found` while no event type is registered, as a ++ * server that does not declare the extension. ++ * ++ * @internal ++ */ ++export const requireEvents = (core, method) => Effect.flatMap(core.registrationPresence, (presence) => presence.events ? Effect.void : Effect.fail(methodNotFound(method))); ++/** ++ * @internal ++ */ ++export const unsupportedDelivery = (value) => new PublicMcpSchema.Unsupported({ ++ message: `Delivery mode '${value}' is not supported for this event`, ++ data: { feature: "deliveryMode", value } ++}); ++// ============================================================================= ++// Wire schemas ++// ============================================================================= ++const optional = Stateless.optional; ++const Cursor = Schema.NullOr(Schema.String); ++const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); ++/** ++ * @internal ++ */ ++export const ListEventsResult = Schema.StructWithRest(Schema.Struct({ ...Stateless.PaginatedResult, events: Schema.Array(PublicMcpSchema.EventDescriptor) }), [Stateless.UnknownObject]); ++/** ++ * @internal ++ */ ++export class ListEvents extends Rpc.make("events/list", { ++ success: ListEventsResult, ++ error: Stateless.McpError, ++ payload: Stateless.PaginatedRequestParams ++}) { ++} ++const SubscriptionParams = { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ cursor: optional(Cursor), ++ maxAgeMs: optional(NonNegativeInt) ++}; ++/** ++ * @internal ++ */ ++export const PollEventsResult = Schema.StructWithRest(Schema.Struct({ ++ ...Stateless.ResultMeta, ++ events: Schema.Array(PublicMcpSchema.EventOccurrence), ++ cursor: Cursor, ++ truncated: Schema.Boolean, ++ hasMore: Schema.Boolean, ++ nextPollMs: NonNegativeInt ++}), [Stateless.UnknownObject]); ++/** ++ * @internal ++ */ ++export class PollEvents extends Rpc.make("events/poll", { ++ success: PollEventsResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, maxEvents: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))) } ++}) { ++} ++/** ++ * @internal ++ */ ++export class StreamEvents extends Rpc.make("events/stream", { ++ success: Stateless.SubscriptionsListenResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, heartbeatMs: optional(NonNegativeInt) } ++}) { ++} ++/** ++ * @internal ++ */ ++export class SubscribeEvents extends Rpc.make("events/subscribe", { ++ success: Schema.StructWithRest(Schema.Struct({ ++ ...Stateless.ResultMeta, ++ id: Schema.String, ++ refreshBefore: Schema.NullOr(Schema.String), ++ cursor: Cursor, ++ truncated: Schema.Boolean ++ }), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...SubscriptionParams, ++ delivery: Stateless.UnknownObject, ++ ttlMs: optional(Schema.NullOr(NonNegativeInt)) ++ } ++}) { ++} ++/** ++ * @internal ++ */ ++export class UnsubscribeEvents extends Rpc.make("events/unsubscribe", { ++ success: Schema.StructWithRest(Schema.Struct(Stateless.ResultMeta), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ delivery: Stateless.UnknownObject ++ } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsActiveNotification extends Rpc.make("notifications/events/active", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor, truncated: Schema.Boolean, heartbeatMs: NonNegativeInt } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsEventNotification extends Rpc.make("notifications/events/event", { ++ payload: { ...PublicMcpSchema.EventOccurrence.fields, ...Stateless.NotificationParams.fields } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsHeartbeatNotification extends Rpc.make("notifications/events/heartbeat", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsErrorNotification extends Rpc.make("notifications/events/error", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsTerminatedNotification extends Rpc.make("notifications/events/terminated", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) { ++} ++/** ++ * The extension's requests on revision 2026-07-28. ++ * ++ * @internal ++ */ ++export class StatelessRpcs extends RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents) { ++} ++/** ++ * The notifications a push stream carries. ++ * ++ * @internal ++ */ ++export class ServerNotificationRpcs extends RpcGroup.make(EventsActiveNotification, EventsEventNotification, EventsHeartbeatNotification, EventsErrorNotification, EventsTerminatedNotification) { ++} ++// ============================================================================= ++// Push delivery ++// ============================================================================= ++const DEFAULT_HEARTBEAT_MS = 30_000; ++const MIN_HEARTBEAT_MS = 1_000; ++const MAX_HEARTBEAT_MS = 300_000; ++// Occurrences the handler may run ahead of a slow client before it waits. ++const PENDING_ITEMS = 16; ++/** ++ * The heartbeat interval granted for a suggested one. ++ * ++ * @internal ++ */ ++export const grantHeartbeat = (suggested) => Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, suggested ?? DEFAULT_HEARTBEAT_MS)); ++const isJson = Schema.is(Schema.Json); ++/** ++ * @internal ++ */ ++export const wireError = (failure) => ({ ++ code: failure.code, ++ message: failure.message, ++ ...(failure.data !== undefined && isJson(failure.data) ? { data: failure.data } : {}) ++}); ++/** ++ * Sends `notifications/events/active`, then each occurrence, and a heartbeat ++ * with the position checked so far whenever `heartbeatMs` passes without ++ * another message. A failure of the subscription's items ends it with ++ * `notifications/events/terminated`. `send` adds the subscription id. ++ * ++ * @internal ++ */ ++export const deliver = Effect.fnUntraced(function* (options) { ++ const { heartbeatMs, name, subscription } = options; ++ let cursor = subscription.cursor; ++ // Measured from the last message sent: a Position changes the cursor but sends nothing. ++ let sentAt = 0; ++ const send = (tag, payload) => ++ options.send(tag, payload).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((at) => { ++ sentAt = at; ++ })); ++ const active = (truncated) => send(EventsActiveNotification._tag, { cursor, truncated, heartbeatMs }); ++ yield* active(subscription.truncated); ++ const items = yield* Stream.toQueue(subscription.items, { capacity: PENDING_ITEMS }); ++ while (true) { ++ const wait = Math.max(0, sentAt + heartbeatMs - (yield* Clock.currentTimeMillis)); ++ const next = yield* Queue.take(items).pipe(Effect.timeoutOption(Duration.millis(wait)), Effect.result); ++ if (Result.isFailure(next)) { ++ if (!Cause.isDone(next.failure)) { ++ yield* send(EventsTerminatedNotification._tag, { error: wireError(next.failure) }); ++ } ++ return; ++ } ++ if (Option.isNone(next.success)) { ++ yield* send(EventsHeartbeatNotification._tag, { cursor }); ++ continue; ++ } ++ const item = next.success.value; ++ switch (item._tag) { ++ case "Event": { ++ cursor = item.cursor; ++ const { _meta, _tag, ...occurrence } = item; ++ yield* send(EventsEventNotification._tag, { ...occurrence, name, ...(_meta === undefined ? {} : { _meta }) }); ++ break; ++ } ++ case "Position": { ++ cursor = item.cursor; ++ break; ++ } ++ case "Gap": { ++ cursor = item.cursor; ++ yield* active(true); ++ break; ++ } ++ case "Error": { ++ yield* send(EventsErrorNotification._tag, { error: wireError(item.error) }); ++ break; ++ } ++ } ++ } ++}, Effect.scoped); +diff --git a/dist/ai/internal/mcpProtocol/v2026_07_28.js b/dist/ai/internal/mcpProtocol/v2026_07_28.js +index af1ceed..ea29279 100644 +--- a/dist/ai/internal/mcpProtocol/v2026_07_28.js ++++ b/dist/ai/internal/mcpProtocol/v2026_07_28.js +@@ -17,6 +17,7 @@ import * as Schema from "../../../Schema.js"; + import * as Scope from "../../../Scope.js"; + import * as PublicMcpSchema from "../../McpSchema.js"; + import * as McpCore from "../mcpCore.js"; ++import * as McpEvents from "../mcpEvents.js"; + import * as McpProtocol from "../mcpProtocol.js"; + import * as McpSchema from "../mcpSchema/v2026_07_28.js"; + import * as McpSkills from "../mcpSkills.js"; +@@ -242,7 +243,7 @@ const unsupported = operation => new PublicMcpSchema.McpReverseOperationUnsuppor + /** + * @internal + */ +-export const handlerRpcs = /*#__PURE__*/McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs); ++export const handlerRpcs = /*#__PURE__*/McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs, McpEvents.StatelessRpcs); + /** + * @internal + */ +@@ -260,6 +261,10 @@ export const makeHandlers = (core, _lifecycle, context) => { + const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult); + const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult); + const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult); ++ const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult); ++ const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult); ++ const decodeSubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.SubscribeEvents.successSchema); ++ const decodeUnsubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.UnsubscribeEvents.successSchema); + const sendNotification = context.sendNotification; + const supportsSubscriptions = sendNotification !== undefined; + // Older adapters accept arbitrary JSON; this binding requires extension settings objects. +@@ -277,8 +282,11 @@ export const makeHandlers = (core, _lifecycle, context) => { + completions: {}, + logging: {} + }; +- const declared = McpSkills.declareExtension(extensions, presence.skills); ++ const declared = McpEvents.declareExtension(McpSkills.declareExtension(extensions, presence.skills), presence.events); + if (declared !== undefined) capabilities.extensions = declared; ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They look for a top-level `events` capability instead of the extension. ++ if (presence.events) capabilities.events = {}; + if (presence.tools) capabilities.tools = { + listChanged: supportsSubscriptions + }; +@@ -297,6 +305,26 @@ export const makeHandlers = (core, _lifecycle, context) => { + serverInfo: context.serverInfo + }; + }); ++ const requireEvents = (method) => McpEvents.requireEvents(core, method).pipe(Effect.catch((error) => failWithHttpStatus(404, error))); ++ // The event type's `x-mcp-header` arguments must match their headers, as a tool's do. ++ const validateEventHeaders = Effect.fnUntraced(function* (registration, args) { ++ const httpRequest = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest); ++ if (Option.isSome(httpRequest)) { ++ yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers); ++ } ++ }); ++ // Webhook delivery runs the event's push stream, so it needs both. ++ const webhookRegistration = Effect.fnUntraced(function* (method, name, args) { ++ yield* requireEvents(method); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(name, invocation); ++ const { stream, webhooks } = registration; ++ if (webhooks === undefined || stream === undefined) { ++ return yield* McpEvents.unsupportedDelivery("webhook"); ++ } ++ yield* validateEventHeaders(registration, args); ++ return { invocation, stream, webhooks, decodeArguments: registration.decodeArguments }; ++ }); + const requireSkills = method => McpSkills.requireSkills(core, method).pipe(Effect.catch(error => failWithHttpStatus(404, error))); + const getInvocation = PublicMcpSchema.McpRequestContext.useSync(McpProtocol.invocationFromRequestContext); + const getInputInvocation = Effect.fnUntraced(function* (request) { +@@ -592,6 +620,97 @@ export const makeHandlers = (core, _lifecycle, context) => { + }, context.serverInfo); + return yield* decodeReadResourceDirectoryResult(result); + }, Effect.mapError(projectError)), ++ "events/list": Effect.fnUntraced(function* (request) { ++ yield* requireEvents("events/list"); ++ yield* McpProtocol.rejectCursor(request.cursor); ++ const events = yield* core.events.list(yield* getInvocation); ++ // Without a notification channel nothing can be pushed. ++ const offered = supportsSubscriptions ? events : events.flatMap((event) => { ++ const delivery = event.delivery.filter((mode) => mode !== "push"); ++ return delivery.length === 0 ? [] : [{ ...event, delivery }]; ++ }); ++ const result = yield* projectCompleteResult({ events: offered }, context.serverInfo); ++ return yield* decodeListEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/poll": Effect.fnUntraced(function* (request) { ++ yield* requireEvents("events/poll"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(request.name, invocation); ++ if (registration.poll === undefined) { ++ return yield* McpEvents.unsupportedDelivery("poll"); ++ } ++ yield* validateEventHeaders(registration, request.arguments); ++ const outcome = yield* registration.poll({ ++ arguments: request.arguments ?? {}, ++ cursor: request.cursor ?? null, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }, invocation); ++ const result = yield* projectCompleteResult({ ++ events: outcome.events.map((event) => omitUndefined({ ++ eventId: event.eventId, ++ name: request.name, ++ timestamp: event.timestamp, ++ data: event.data, ++ _meta: event._meta ++ })), ++ cursor: outcome.cursor, ++ truncated: outcome.truncated, ++ hasMore: outcome.hasMore, ++ nextPollMs: outcome.nextPollMs ++ }, context.serverInfo); ++ return yield* decodePollEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/stream": Effect.fnUntraced(function* (request, { client, requestId }) { ++ yield* requireEvents("events/stream"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(request.name, invocation); ++ if (registration.stream === undefined || sendNotification === undefined) { ++ return yield* McpEvents.unsupportedDelivery("push"); ++ } ++ yield* validateEventHeaders(registration, request.arguments); ++ const subscriptionMetadata = { "io.modelcontextprotocol/subscriptionId": requestId }; ++ const send = (tag, payload) => sendNotification(McpSchema.protocolVersion, client.id, { ++ tag, ++ payload: { ++ ...payload, ++ _meta: { ...(Predicate.isReadonlyObject(payload._meta) ? payload._meta : {}), ...subscriptionMetadata } ++ } ++ }); ++ const heartbeatMs = McpEvents.grantHeartbeat(request.heartbeatMs); ++ yield* Effect.raceFirst(registration.stream({ arguments: request.arguments ?? {}, cursor: request.cursor ?? null, maxAgeMs: request.maxAgeMs }, invocation, (subscription) => McpEvents.deliver({ name: request.name, subscription, heartbeatMs, send })), context.awaitClientEnd ?? Effect.never); ++ const encodedServerInfo = yield* encodeImplementation(context.serverInfo); ++ return McpSchema.SubscriptionsListenResult.make({ ++ _meta: { ...subscriptionMetadata, "io.modelcontextprotocol/serverInfo": encodedServerInfo }, ++ resultType: "complete" ++ }); ++ }, Effect.mapError(projectError)), ++ "events/subscribe": Effect.fnUntraced(function* (request) { ++ const { decodeArguments, invocation, stream, webhooks } = yield* webhookRegistration("events/subscribe", request.name, request.arguments); ++ const args = request.arguments ?? {}; ++ const cursor = request.cursor ?? null; ++ const subscribed = yield* webhooks.subscribe({ ++ name: request.name, ++ arguments: args, ++ delivery: request.delivery, ++ cursor, ++ ttlMs: request.ttlMs, ++ decode: decodeArguments(args), ++ open: (decoded, deliver) => stream({ arguments: args, decoded: { value: decoded }, cursor, maxAgeMs: request.maxAgeMs }, invocation, deliver) ++ }); ++ const result = yield* projectCompleteResult(omitUndefined({ ...subscribed }), context.serverInfo); ++ return yield* decodeSubscribeEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/unsubscribe": Effect.fnUntraced(function* (request) { ++ const { webhooks } = yield* webhookRegistration("events/unsubscribe", request.name, request.arguments); ++ yield* webhooks.unsubscribe({ ++ name: request.name, ++ arguments: request.arguments ?? {}, ++ delivery: request.delivery ++ }); ++ const result = yield* projectCompleteResult({}, context.serverInfo); ++ return yield* decodeUnsubscribeEventsResult(result); ++ }, Effect.mapError(projectError)), + "notifications/cancelled": Effect.fnUntraced(function* (_request) { + return yield* Effect.void; + }) +@@ -613,10 +732,10 @@ const runtime = { + export const protocol = /*#__PURE__*/McpProtocol.make({ + protocolVersion: McpSchema.protocolVersion, + runtime, +- clientRpcs: /*#__PURE__*/McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs), ++ clientRpcs: /*#__PURE__*/McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs, McpEvents.StatelessRpcs), + clientNotificationRpcs: McpSchema.ClientNotificationRpcs, + serverRequestRpcs: McpSchema.ServerRequestRpcs, +- serverNotificationRpcs: McpSchema.ServerNotificationRpcs, ++ serverNotificationRpcs: /*#__PURE__*/McpSchema.ServerNotificationRpcs.merge(McpEvents.ServerNotificationRpcs), + handlerRpcs, + makeHandlers, + toReverseClient: () => ({ +diff --git a/dist/ai/internal/mcpRuntime.js b/dist/ai/internal/mcpRuntime.js +index 88238ff..721ff28 100644 +--- a/dist/ai/internal/mcpRuntime.js ++++ b/dist/ai/internal/mcpRuntime.js +@@ -39,6 +39,10 @@ const routingNameKey = method => { + switch (method) { + case "tools/call": + case "prompts/get": ++ case "events/poll": ++ case "events/stream": ++ case "events/subscribe": ++ case "events/unsubscribe": + return "name"; + case "resources/read": + return "uri"; +@@ -178,7 +182,10 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { + if (nameKey !== undefined) { + const name = asRecord(inputRecord?.params)?.[nameKey]; + const header = headers[MCP_NAME_HEADER]; +- if (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) { ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They send no Mcp-Name on these; one they do send must still match. ++ const optional = header === undefined && (method === "events/subscribe" || method === "events/unsubscribe"); ++ if (!optional && (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name)) { + return headerMismatch("Mcp-Name header does not match request parameters"); + } + } +@@ -340,7 +347,8 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { + return { + _tag: "Accepted", + acknowledge: !isRequest || !hasId, +- isSubscription: Predicate.hasProperty(input, "method") && input.method === "subscriptions/listen" ++ // A push subscription stays open until cancelled, so it is never a plain response. ++ isSubscription: Predicate.hasProperty(input, "method") && (input.method === "subscriptions/listen" || input.method === "events/stream") + }; + }, + effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/dist/ai/internal/mcpWebhooks.d.ts b/dist/ai/internal/mcpWebhooks.d.ts +new file mode 100644 +index 0000000..cb0ff5c +--- /dev/null ++++ b/dist/ai/internal/mcpWebhooks.d.ts +@@ -0,0 +1 @@ ++export {}; +diff --git a/dist/ai/internal/mcpWebhooks.js b/dist/ai/internal/mcpWebhooks.js +new file mode 100644 +index 0000000..4e2871a +--- /dev/null ++++ b/dist/ai/internal/mcpWebhooks.js +@@ -0,0 +1,456 @@ ++import * as Clock from "../../Clock.js"; ++import * as Digest from "../../crypto/Digest.js"; ++import * as Mac from "../../crypto/Mac.js"; ++import * as SecureRandom from "../../crypto/SecureRandom.js"; ++import * as Deferred from "../../Deferred.js"; ++import * as Duration from "../../Duration.js"; ++import * as Effect from "../../Effect.js"; ++import * as Base64 from "../../encoding/Base64.js"; ++import * as Base64Url from "../../encoding/Base64Url.js"; ++import * as Fiber from "../../Fiber.js"; ++import * as FetchHttpClient from "../../http/FetchHttpClient.js"; ++import * as HttpClient from "../../http/HttpClient.js"; ++import * as HttpClientRequest from "../../http/HttpClientRequest.js"; ++import * as Option from "../../Option.js"; ++import * as Result from "../../Result.js"; ++import * as Stream from "../../Stream.js"; ++import * as PublicMcpSchema from "../McpSchema.js"; ++import { wireError } from "./mcpEvents.js"; ++const MINUTE_MS = 6e4; ++const MIN_TTL_MS = MINUTE_MS; ++const MAX_TTL_MS = 60 * MINUTE_MS; ++const DEFAULT_TTL_MS = 15 * MINUTE_MS; ++const MAX_ATTEMPTS = 5; ++const FIRST_RETRY_MS = 3e4; ++const REQUEST_TIMEOUT_MS = 1e4; ++const ROTATION_GRACE_MS = 5 * MINUTE_MS; ++const VERIFIED_FOR_MS = MAX_TTL_MS; ++const FAILED_FOR_MS = 5 * MINUTE_MS; ++const VERIFICATIONS_PER_HOST_PER_MINUTE = 10; ++const MAX_SUBSCRIPTIONS_PER_PRINCIPAL = 100; ++const MAX_CHALLENGE_RESPONSE_BYTES = 8192; ++const SECRET_PREFIX = "whsec_"; ++const invalid = (message) => new PublicMcpSchema.InvalidParams({ message }); ++const grantTtl = (suggested) => suggested === void 0 ? DEFAULT_TTL_MS : suggested === null ? MAX_TTL_MS : Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, suggested)); ++const canonicalJson = (value) => { ++ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; ++ if (typeof value === "object" && value !== null) { ++ const entries = Object.entries(value).filter(([, entry]) => entry !== void 0); ++ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); ++ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`; ++ } ++ return JSON.stringify(value) ?? "null"; ++}; ++const encoder = new TextEncoder(); ++const parseUrl = (value, guard) => { ++ if (typeof value !== "string") return Effect.fail(invalid("delivery.url is required")); ++ let url; ++ try { ++ url = new URL(value); ++ } catch { ++ return Effect.fail(invalid("delivery.url is not a valid URL")); ++ } ++ if (url.protocol !== "https:" && !(url.protocol === "http:" && guard.allowsPlaintext?.(url) === true)) { ++ return Effect.fail(invalid("delivery.url must use https")); ++ } ++ if (url.username !== "" || url.password !== "") { ++ return Effect.fail(invalid("delivery.url must not carry credentials")); ++ } ++ url.hash = ""; ++ return Effect.succeed(url); ++}; ++const parseSecret = (value) => { ++ const fail = Effect.fail(invalid("delivery.secret must be whsec_ and the base64 of 24 to 64 random bytes")); ++ if (typeof value !== "string" || !value.startsWith(SECRET_PREFIX)) return fail; ++ const bytes = Base64.decode(value.slice(SECRET_PREFIX.length)); ++ if (Result.isFailure(bytes) || bytes.success.length < 24 || bytes.success.length > 64) return fail; ++ return Mac.key(Mac.hmacSha256, bytes.success).pipe(Effect.orDie, Effect.map((key) => ({ text: value, key }))); ++}; ++const statusCategory = (status) => status >= 500 ? "http_5xx" : "http_4xx"; ++const transportCategory = (error) => { ++ let current = error; ++ for (let depth = 0; depth < 8 && typeof current === "object" && current !== null; depth++) { ++ const code = current.code; ++ if (typeof code === "string" && /CERT|TLS|SSL/.test(code)) return "tls_error"; ++ current = current.cause ?? current.reason; ++ } ++ return "connection_refused"; ++}; ++const readCapped = (response) => Effect.suspend(() => { ++ const chunks = []; ++ let total = 0; ++ let oversized = false; ++ return response.stream.pipe( ++ Stream.takeWhile((chunk) => { ++ if (total + chunk.length > MAX_CHALLENGE_RESPONSE_BYTES) { ++ oversized = true; ++ return false; ++ } ++ total += chunk.length; ++ chunks.push(chunk); ++ return true; ++ }), ++ Stream.runDrain, ++ Effect.map(() => { ++ if (oversized) return void 0; ++ const bytes = new Uint8Array(total); ++ let offset = 0; ++ for (const chunk of chunks) { ++ bytes.set(chunk, offset); ++ offset += chunk.length; ++ } ++ return new TextDecoder().decode(bytes); ++ }) ++ ); ++}); ++const echoedChallenge = (body) => { ++ try { ++ const parsed = JSON.parse(body); ++ const challenge = typeof parsed === "object" && parsed !== null ? parsed.challenge : void 0; ++ return typeof challenge === "string" ? challenge : void 0; ++ } catch { ++ return void 0; ++ } ++}; ++const callbackError = (category) => new PublicMcpSchema.CallbackEndpointError({ ++ message: `The callback endpoint failed verification: ${category}`, ++ data: { reason: category } ++}); ++const iso = (millis) => new Date(millis).toISOString(); ++const make = Effect.fnUntraced(function* (options) { ++ const scope = yield* Effect.scope; ++ const mac = yield* Mac.Mac; ++ const digest = yield* Digest.Digest; ++ const random = yield* SecureRandom.SecureRandom; ++ const { guard } = options; ++ const client = HttpClient.withScope(options.client); ++ const subscriptions = /* @__PURE__ */ new Map(); ++ const pending = /* @__PURE__ */ new Map(); ++ const verified = /* @__PURE__ */ new Map(); ++ const failedVerifications = /* @__PURE__ */ new Map(); ++ const verifying = /* @__PURE__ */ new Map(); ++ const verificationsByHost = /* @__PURE__ */ new Map(); ++ const forget = (subscription) => { ++ if (subscriptions.get(subscription.id) === subscription) subscriptions.delete(subscription.id); ++ }; ++ const subscriptionId = (principal, url, name, args) => digest.digestHex(Digest.sha256, encoder.encode(canonicalJson([principal, url.href, name, args]))).pipe( ++ Effect.map((hex) => `sub_${hex.slice(0, 32)}`) ++ ); ++ const messageId = (prefix) => Effect.map(random.randomBytes(18), (bytes) => `${prefix}_${Base64Url.encode(bytes)}`); ++ const deliveryId = (subscription, eventId) => Effect.map( ++ digest.digest(Digest.sha256, encoder.encode(`${subscription.id}\0${eventId}`)), ++ (hash) => `evt_${Base64Url.encode(hash).slice(0, 22)}` ++ ); ++ const MAX_CURSORS_SINCE_GAP = 1024; ++ const advance = (subscription, cursor) => { ++ subscription.watermark = cursor; ++ const since = subscription.cursorsSinceGap; ++ if (since === void 0) return; ++ since.add(cursor); ++ if (since.size > MAX_CURSORS_SINCE_GAP) since.delete(since.values().next().value); ++ }; ++ const sign = (keys, webhookId, timestamp, body) => Effect.forEach(keys, (key) => mac.sign(key, encoder.encode(`${webhookId}.${timestamp}.${body}`))).pipe( ++ Effect.orDie, ++ Effect.map((tags) => tags.map((tag) => `v1,${Base64.encode(tag)}`).join(" ")) ++ ); ++ const send = Effect.fnUntraced(function* (subscription, body, webhookId, readBody) { ++ const admitted = yield* Effect.result(guard.check(subscription.url)); ++ if (Result.isFailure(admitted)) { ++ return { _tag: "Failed", category: "connection_refused", retryable: true }; ++ } ++ const now = yield* Clock.currentTimeMillis; ++ const timestamp = Math.floor(now / 1e3); ++ const previous = subscription.previous; ++ const keys = previous !== void 0 && now < previous.until ? [subscription.key, previous.key] : [subscription.key]; ++ const request = HttpClientRequest.post(subscription.url).pipe( ++ HttpClientRequest.setHeaders({ ++ "webhook-id": webhookId, ++ "webhook-timestamp": String(timestamp), ++ "webhook-signature": yield* sign(keys, webhookId, timestamp, body), ++ "x-mcp-subscription-id": subscription.id ++ }), ++ HttpClientRequest.bodyText(body, "application/json") ++ ); ++ const outcome = yield* client.execute(request).pipe( ++ Effect.flatMap((response) => { ++ if (response.status < 200 || response.status >= 300) { ++ return Effect.succeed({ ++ _tag: "Failed", ++ category: statusCategory(response.status), ++ retryable: response.status !== 410 && response.status !== 413 ++ }); ++ } ++ return readBody ? Effect.map(readCapped(response), (text) => ({ _tag: "Delivered", body: text })) : Effect.succeed({ _tag: "Delivered", body: void 0 }); ++ }), ++ Effect.timeoutOption(Duration.millis(REQUEST_TIMEOUT_MS)), ++ Effect.scoped, ++ // `fetch` would follow a redirect itself; webhook delivery never does. ++ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), ++ // Trace ids stay inside: the endpoint belongs to someone else. ++ Effect.provideService(HttpClient.TracerPropagationEnabled, false), ++ Effect.catch( ++ (error) => Effect.succeed(Option.some({ _tag: "Failed", category: transportCategory(error), retryable: true })) ++ ) ++ ); ++ return Option.getOrElse(outcome, () => ({ _tag: "Failed", category: "timeout", retryable: true })); ++ }); ++ const deliver = Effect.fnUntraced(function* (subscription, body, webhookId) { ++ for (let attempt = 1; ; attempt++) { ++ const current = subscriptions.get(subscription.id); ++ if (current !== void 0 && current !== subscription) return false; ++ const startedAt = yield* Clock.currentTimeMillis; ++ const outcome = yield* send(subscription, body, webhookId, false); ++ if (outcome._tag === "Delivered") { ++ subscription.lastDeliveryAt = yield* Clock.currentTimeMillis; ++ subscription.lastError = void 0; ++ return true; ++ } ++ subscription.lastError = outcome.category; ++ if (!outcome.retryable || attempt >= MAX_ATTEMPTS) return false; ++ const wait = startedAt + FIRST_RETRY_MS * 2 ** (attempt - 1) - (yield* Clock.currentTimeMillis); ++ if (wait > 0) yield* Effect.sleep(Duration.millis(wait)); ++ } ++ }); ++ const control = (subscription, type, fields) => Effect.flatMap( ++ messageId(`msg_${type}`), ++ (webhookId) => deliver(subscription, JSON.stringify({ type, ...fields }), webhookId) ++ ); ++ const run = (subscription, name, events) => events.items.pipe( ++ Stream.runForEach((item) => { ++ switch (item._tag) { ++ case "Event": ++ return Effect.flatMap(deliveryId(subscription, item.eventId), (webhookId) => { ++ const body = JSON.stringify({ ++ eventId: webhookId, ++ name, ++ timestamp: item.timestamp, ++ data: item.data, ++ cursor: item.cursor, ++ ...item._meta === void 0 ? {} : { _meta: item._meta } ++ }); ++ return deliver(subscription, body, webhookId); ++ }).pipe(Effect.andThen(Effect.sync(() => advance(subscription, item.cursor)))); ++ case "Position": ++ return Effect.sync(() => advance(subscription, item.cursor)); ++ case "Gap": ++ return control(subscription, "gap", { cursor: item.cursor }).pipe( ++ Effect.map((delivered) => { ++ if (!delivered) subscription.cursorsSinceGap = /* @__PURE__ */ new Set(); ++ advance(subscription, item.cursor); ++ }) ++ ); ++ case "Error": ++ return Effect.void; ++ } ++ }), ++ // Ended before it says so, so a refresh meanwhile starts afresh instead of reporting it live. ++ Effect.catch( ++ (failure) => Effect.suspend(() => { ++ forget(subscription); ++ return control(subscription, "terminated", { error: wireError(failure) }); ++ }) ++ ) ++ ); ++ const expiry = (subscription) => Effect.gen(function* () { ++ while (true) { ++ const left = subscription.expiresAt - (yield* Clock.currentTimeMillis); ++ if (left <= 0) return forget(subscription); ++ yield* Effect.raceFirst(Effect.sleep(Duration.millis(left)), Deferred.await(subscription.deadlineMoved)); ++ } ++ }); ++ const handshake = Effect.fnUntraced(function* (subscription) { ++ const challenge = Base64Url.encode(yield* random.randomBytes(32)); ++ const outcome = yield* send( ++ subscription, ++ JSON.stringify({ type: "verification", challenge }), ++ yield* messageId("msg_verification"), ++ true ++ ); ++ if (outcome._tag === "Failed") return yield* Effect.fail(outcome.category); ++ const echoed = outcome.body === void 0 ? void 0 : echoedChallenge(outcome.body); ++ if (echoed === void 0 || !Mac.timingSafeEqual(encoder.encode(echoed), encoder.encode(challenge))) { ++ return yield* Effect.fail("challenge_failed"); ++ } ++ }); ++ const verify = Effect.fnUntraced(function* (subscription) { ++ const key = JSON.stringify([subscription.principal, subscription.url.href]); ++ const now = yield* Clock.currentTimeMillis; ++ for (const [entry, until] of verified) if (until <= now) verified.delete(entry); ++ for (const [entry, failure2] of failedVerifications) if (failure2.until <= now) failedVerifications.delete(entry); ++ if (verified.has(key)) return; ++ const failure = failedVerifications.get(key); ++ if (failure !== void 0) return yield* callbackError(failure.category); ++ const inFlight = verifying.get(key); ++ if (inFlight !== void 0) return yield* Deferred.await(inFlight); ++ const host = subscription.url.hostname; ++ const recent = (verificationsByHost.get(host) ?? []).filter((at) => at > now - MINUTE_MS); ++ if (recent.length >= VERIFICATIONS_PER_HOST_PER_MINUTE) { ++ verificationsByHost.set(host, recent); ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many callback verifications for this host", ++ data: { limit: "verifications", max: VERIFICATIONS_PER_HOST_PER_MINUTE } ++ }); ++ } ++ for (const [entry, times] of verificationsByHost) { ++ if (times.every((at) => at <= now - MINUTE_MS)) verificationsByHost.delete(entry); ++ } ++ verificationsByHost.set(host, [...recent, now]); ++ const done = Deferred.makeUnsafe(); ++ verifying.set(key, done); ++ return yield* handshake(subscription).pipe( ++ Effect.tap( ++ () => Effect.map(Clock.currentTimeMillis, (at) => { ++ verified.set(key, at + VERIFIED_FOR_MS); ++ }) ++ ), ++ Effect.tapError( ++ (category) => Effect.map(Clock.currentTimeMillis, (at) => { ++ failedVerifications.set(key, { until: at + FAILED_FOR_MS, category }); ++ }) ++ ), ++ Effect.mapError(callbackError), ++ Effect.onExit( ++ (exit) => Effect.sync(() => { ++ verifying.delete(key); ++ Deferred.doneUnsafe(done, exit); ++ }) ++ ) ++ ); ++ }); ++ const refresh = Effect.fnUntraced(function* (request, subscription, secret, expiresAt, now) { ++ const opening = !Deferred.isDoneUnsafe(subscription.accepted); ++ const start = yield* Deferred.await(subscription.accepted); ++ if (subscriptions.get(subscription.id) !== subscription) return yield* subscribe(request); ++ if (subscription.secret !== secret.text) { ++ subscription.previous = { key: subscription.key, until: now + ROTATION_GRACE_MS }; ++ subscription.secret = secret.text; ++ subscription.key = secret.key; ++ } ++ subscription.expiresAt = expiresAt; ++ const moved = subscription.deadlineMoved; ++ subscription.deadlineMoved = Deferred.makeUnsafe(); ++ Deferred.doneUnsafe(moved, Effect.void); ++ if (opening) return { id: subscription.id, refreshBefore: iso(expiresAt), ...start }; ++ const since = subscription.cursorsSinceGap; ++ if (since !== void 0 && since.has(request.cursor)) subscription.cursorsSinceGap = void 0; ++ const truncated = subscription.cursorsSinceGap !== void 0; ++ return { ++ id: subscription.id, ++ refreshBefore: iso(expiresAt), ++ cursor: subscription.watermark, ++ truncated, ++ deliveryStatus: { ++ active: true, ++ lastDeliveryAt: subscription.lastDeliveryAt === void 0 ? null : iso(subscription.lastDeliveryAt), ++ lastError: subscription.lastError ?? null ++ } ++ }; ++ }); ++ const subscribe = Effect.fnUntraced(function* (request) { ++ const principal = yield* options.principal; ++ const mode = request.delivery.mode; ++ if (mode !== void 0 && mode !== "webhook") return yield* invalid("delivery.mode must be 'webhook'"); ++ const url = yield* parseUrl(request.delivery.url, guard); ++ const secret = yield* parseSecret(request.delivery.secret); ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments); ++ const now = yield* Clock.currentTimeMillis; ++ const expiresAt = now + grantTtl(request.ttlMs); ++ const live = subscriptions.get(id); ++ if (live !== void 0) return yield* refresh(request, live, secret, expiresAt, now); ++ let held = pending.get(principal) ?? 0; ++ for (const subscription of subscriptions.values()) if (subscription.principal === principal) held++; ++ if (held >= MAX_SUBSCRIPTIONS_PER_PRINCIPAL) { ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many webhook subscriptions", ++ data: { limit: "subscriptions", max: MAX_SUBSCRIPTIONS_PER_PRINCIPAL } ++ }); ++ } ++ pending.set(principal, (pending.get(principal) ?? 0) + 1); ++ let reserved = true; ++ const release = () => { ++ if (!reserved) return; ++ reserved = false; ++ const left = (pending.get(principal) ?? 1) - 1; ++ if (left === 0) pending.delete(principal); ++ else pending.set(principal, left); ++ }; ++ return yield* create(request, { principal, url, secret, id, expiresAt, now, release }).pipe( ++ Effect.ensuring(Effect.sync(release)) ++ ); ++ }); ++ const create = Effect.fnUntraced(function* (request, { expiresAt, id, now, principal, release, secret, url }) { ++ yield* Effect.mapError(guard.check(url), () => invalid("delivery.url is not allowed")); ++ const subscription = { ++ id, ++ principal, ++ url, ++ secret: secret.text, ++ key: secret.key, ++ previous: void 0, ++ expiresAt, ++ watermark: request.cursor, ++ lastDeliveryAt: void 0, ++ lastError: void 0, ++ fiber: void 0, ++ deadlineMoved: Deferred.makeUnsafe(), ++ accepted: Deferred.makeUnsafe(), ++ cursorsSinceGap: void 0 ++ }; ++ const decoded = yield* request.decode; ++ yield* verify(subscription); ++ const raced = subscriptions.get(id); ++ if (raced !== void 0) { ++ release(); ++ return yield* refresh(request, raced, secret, expiresAt, now); ++ } ++ release(); ++ subscriptions.set(id, subscription); ++ const { accepted } = subscription; ++ const lifetime = request.open( ++ decoded, ++ (events) => Effect.suspend(() => { ++ subscription.watermark = events.cursor; ++ return Deferred.succeed(accepted, { cursor: events.cursor, truncated: events.truncated }); ++ }).pipe(Effect.andThen(run(subscription, request.name, events))) ++ ).pipe( ++ Effect.tapError((failure) => Deferred.fail(accepted, failure)), ++ Effect.raceFirst(expiry(subscription)), ++ Effect.ignore, ++ Effect.ensuring(Effect.suspend(() => { ++ forget(subscription); ++ return Deferred.fail(accepted, new PublicMcpSchema.InternalError({ message: "The subscription ended" })); ++ })) ++ ); ++ subscription.fiber = yield* Effect.forkIn(lifetime, scope); ++ const start = yield* Deferred.await(accepted); ++ return { id, refreshBefore: iso(expiresAt), cursor: start.cursor, truncated: start.truncated }; ++ }); ++ const unsubscribe = Effect.fnUntraced(function* (request) { ++ const principal = yield* options.principal; ++ const url = yield* parseUrl(request.delivery.url, guard); ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments); ++ const subscription = subscriptions.get(id); ++ if (subscription === void 0) { ++ return yield* new PublicMcpSchema.NotFound({ ++ message: "No webhook subscription matches", ++ data: { kind: "subscription" } ++ }); ++ } ++ subscriptions.delete(id); ++ if (subscription.fiber !== void 0) yield* Fiber.interrupt(subscription.fiber); ++ }); ++ return { ++ subscribe, ++ unsubscribe, ++ size: Effect.sync(() => subscriptions.size) ++ }; ++}); ++export { ++ DEFAULT_TTL_MS, ++ MAX_ATTEMPTS, ++ MAX_TTL_MS, ++ MIN_TTL_MS, ++ canonicalJson, ++ grantTtl, ++ make ++}; +diff --git a/src/ai/McpSchema.ts b/src/ai/McpSchema.ts +index ba6c830..1e58fb9 100644 +--- a/src/ai/McpSchema.ts ++++ b/src/ai/McpSchema.ts +@@ -740,6 +740,57 @@ export const HEADER_MISMATCH_ERROR_CODE = -32020 as const + */ + export const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE = -32022 as const + ++/** ++ * Represents the MCP error code for a referenced entity that does not exist, ++ * such as an unknown event name. `data.kind` may say which. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const NOT_FOUND_ERROR_CODE = -32023 as const ++ ++/** ++ * Represents the MCP error code for a principal that is not permitted, or ++ * whose access was revoked. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const FORBIDDEN_ERROR_CODE = -32024 as const ++ ++/** ++ * Represents the MCP error code for a server-imposed limit or quota. ++ * `data.limit` names it. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const RESOURCE_EXHAUSTED_ERROR_CODE = -32025 as const ++ ++/** ++ * Represents the MCP error code for a well-formed request that asks for a ++ * capability or option not supported here. `data` identifies it, for example ++ * `{ feature: "deliveryMode", value: "push" }`. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const UNSUPPORTED_ERROR_CODE = -32026 as const ++ ++/** ++ * Represents the MCP error code for a client-supplied callback endpoint that ++ * failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const CALLBACK_ENDPOINT_ERROR_CODE = -32027 as const ++ + /** + * Represents an MCP/JSON-RPC error for invalid JSON that could not be parsed. + * +@@ -852,6 +903,74 @@ export class InternalError extends Schema.Error("effect/ai/McpSch + static readonly notImplemented = new InternalError({ message: "Not implemented" }) + } + ++/** ++ * Represents an MCP error for a referenced entity that does not exist. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class NotFound extends Schema.Error("effect/ai/McpSchema/NotFound")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("NotFound"), ++ code: Schema.tag(NOT_FOUND_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a principal that is not permitted. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class Forbidden extends Schema.Error("effect/ai/McpSchema/Forbidden")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("Forbidden"), ++ code: Schema.tag(FORBIDDEN_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a server-imposed limit or quota. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class ResourceExhausted extends Schema.Error("effect/ai/McpSchema/ResourceExhausted")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("ResourceExhausted"), ++ code: Schema.tag(RESOURCE_EXHAUSTED_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a capability or option not supported here. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class Unsupported extends Schema.Error("effect/ai/McpSchema/Unsupported")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("Unsupported"), ++ code: Schema.tag(UNSUPPORTED_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a callback endpoint that failed verification or ++ * could not be reached. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class CallbackEndpointError ++ extends Schema.Error("effect/ai/McpSchema/CallbackEndpointError")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("CallbackEndpointError"), ++ code: Schema.tag(CALLBACK_ENDPOINT_ERROR_CODE) ++ }) ++{} ++ + /** + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. +@@ -1501,6 +1620,76 @@ export class Skill extends Schema.Class( + _meta: optional(UnknownObject) + }) {} + ++// ============================================================================= ++// Events ++// ============================================================================= ++ ++/** ++ * How a client receives an event type's occurrences under the MCP Events ++ * extension (SEP-3415): by `events/poll`, an `events/stream` push stream, or ++ * a webhook registered with `events/subscribe`. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventDelivery = Schema.Literals(["poll", "push", "webhook"]) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDelivery = typeof EventDelivery.Type ++ ++/** ++ * An event type listed by `events/list`: its subscription arguments, its ++ * payload, and the delivery modes it supports. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventDescriptor = Schema.Struct({ ++ name: Schema.String, ++ description: optional(Schema.String), ++ delivery: Schema.Array(EventDelivery), ++ inputSchema: UnknownObject, ++ payloadSchema: UnknownObject, ++ _meta: optional(UnknownObject) ++}) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDescriptor = typeof EventDescriptor.Type ++ ++/** ++ * One delivered event. `cursor` is the subscription's position after it, on ++ * push and webhook delivery; poll carries the cursor on the result. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventOccurrence = Schema.Struct({ ++ eventId: Schema.String, ++ name: Schema.String, ++ timestamp: Schema.String, ++ data: UnknownObject, ++ cursor: optional(Schema.NullOr(Schema.String)), ++ _meta: optional(UnknownObject) ++}) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventOccurrence = typeof EventOccurrence.Type ++ + // ============================================================================= + // Prompts + // ============================================================================= +diff --git a/src/ai/McpServer.ts b/src/ai/McpServer.ts +index 4c2e191..bedd064 100644 +--- a/src/ai/McpServer.ts ++++ b/src/ai/McpServer.ts +@@ -16,6 +16,8 @@ import * as Cause from "../Cause.ts" + import * as Clock from "../Clock.ts" + import * as Context from "../Context.ts" + import * as Digest from "../crypto/Digest.ts" ++import * as Mac from "../crypto/Mac.ts" ++import * as SecureRandom from "../crypto/SecureRandom.ts" + import * as Data from "../Data.ts" + import * as Deferred from "../Deferred.ts" + import * as Duration from "../Duration.ts" +@@ -26,6 +28,7 @@ import * as Exit from "../Exit.ts" + import * as Fiber from "../Fiber.ts" + import * as FindMyWay from "../http/FindMyWay.ts" + import * as Headers from "../http/Headers.ts" ++import * as HttpClient from "../http/HttpClient.ts" + import { appendPreResponseHandlerUnsafe } from "../http/HttpEffect.ts" + import * as HttpRouter from "../http/HttpRouter.ts" + import * as HttpServerRequest from "../http/HttpServerRequest.ts" +@@ -59,6 +62,7 @@ import * as McpCore from "./internal/mcpCore.ts" + import * as McpProtocolInternal from "./internal/mcpProtocol.ts" + import * as McpRuntime from "./internal/mcpRuntime.ts" + import * as McpSkills from "./internal/mcpSkills.ts" ++import * as McpWebhooks from "./internal/mcpWebhooks.ts" + import * as InternalStructuredOutput from "./internal/structured-output.ts" + import type * as McpProtocol from "./McpProtocol.ts" + import * as McpSchema from "./McpSchema.ts" +@@ -344,6 +348,9 @@ export type MiddlewareMethod = + | "skills/list" + | "skills/get" + | "resources/directory/read" ++ | "events/list" ++ | "events/poll" ++ | "events/stream" + + /** + * Request metadata passed to MCP middleware. +@@ -819,7 +826,14 @@ const internalError = new InternalError({ message: "Internal error" }) + const rejectWith = (error: McpErrorBase) => + Effect.fail(new McpCore.RequestRejected({ code: error.code, message: error.message, data: error.data, error })) + +-type CallMethod = "tools/call" | "resources/read" | "prompts/get" | "completion/complete" | "skills/get" ++type CallMethod = ++ | "tools/call" ++ | "resources/read" ++ | "prompts/get" ++ | "completion/complete" ++ | "skills/get" ++ | "events/poll" ++ | "events/stream" + + type ListMethod = Exclude + +@@ -829,6 +843,8 @@ interface NotFoundErrors { + readonly "prompts/get": McpCore.PromptNotFound + readonly "completion/complete": InvalidParams + readonly "skills/get": McpCore.SkillNotFound ++ readonly "events/poll": McpSchema.NotFound ++ readonly "events/stream": McpSchema.NotFound + } + + const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod] => { +@@ -843,6 +859,9 @@ const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod + return new InvalidParams({ message: "Unknown completion reference or argument" }) + case "skills/get": + return new McpCore.SkillNotFound({ uri: target }) ++ case "events/poll": ++ case "events/stream": ++ return McpCore.eventNotFound(target) + } + } + +@@ -4134,6 +4153,404 @@ export const registerSkill: (options: SkillOptions) => Effect.Effect => + Layer.effectDiscard(registerSkill(options)) + ++// ============================================================================= ++// Events ++// ============================================================================= ++ ++/** ++ * A failure an event handler reports to the client: a JSON-RPC error on a ++ * poll or when a push stream opens, and `notifications/events/terminated` ++ * once it is open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventError = ++ | InvalidParams ++ | InternalError ++ | McpSchema.NotFound ++ | McpSchema.Forbidden ++ | McpSchema.ResourceExhausted ++ | McpSchema.Unsupported ++ ++/** ++ * Where a poll starts. `cursor` is `null` to start from now, which replays ++ * nothing. With a cursor, replay starts at whichever is later: the cursor, or ++ * `maxAgeMs` before now. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * Where a push stream starts, read as for {@link EventPollRequest}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventStreamRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * One occurrence, with its payload as the event's `payload` schema types it. ++ * `eventId` stays the same however often the occurrence is delivered. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOccurrence { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: A ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * A poll's answer. `truncated` says delivery started later than the cursor, ++ * and `hasMore` that `maxEvents` cut the batch short. `nextPollMs` defaults ++ * to 30 seconds. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollResult { ++ readonly events: ReadonlyArray> ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly hasMore?: boolean | undefined ++ readonly nextPollMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries: an occurrence and the cursor after it; a ++ * position checked without a match, which the next heartbeat reports; a gap, ++ * sent as a fresh `notifications/events/active` with `truncated`; or an error ++ * that leaves the stream open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EventOccurrence) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventError } ++ ++/** ++ * An accepted push subscription: where it starts, and its items. A failure ++ * of `items` ends it. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly items: Stream.Stream, EventError, R> ++} ++ ++/** ++ * Options for {@link registerEvent} and {@link event}. ++ * ++ * **Details** ++ * ++ * `parameters` types the subscription arguments, an empty object by default, ++ * and `payload` the occurrences' `data`; both are advertised as JSON Schema ++ * by `events/list`. `poll` offers poll delivery and `stream` push delivery, ++ * and at least one is required. With {@link EventWebhooks} provided where the ++ * event is registered, `stream` also backs webhook delivery. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOptions, Payload extends Schema.Codec, R> { ++ readonly name: string ++ readonly description?: string | undefined ++ readonly parameters?: Params | undefined ++ readonly payload: Payload ++ readonly _meta?: Readonly> | undefined ++ readonly annotations?: Context.Context | undefined ++ readonly poll?: ++ | (( ++ args: Params["Type"], ++ request: EventPollRequest ++ ) => Effect.Effect, EventError, R>) ++ | undefined ++ readonly stream?: ++ | (( ++ args: Params["Type"], ++ request: EventStreamRequest ++ ) => Effect.Effect, EventError, R | Scope.Scope>) ++ | undefined ++} ++ ++const DEFAULT_NEXT_POLL_MS = 30_000 ++ ++/** ++ * Registers an event type under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * The server declares `io.modelcontextprotocol/events` on revision ++ * `2026-07-28` once any event type is registered, and answers `events/list`, ++ * `events/poll`, `events/stream`, and with {@link EventWebhooks} ++ * `events/subscribe` and `events/unsubscribe`. A push stream runs `stream` for its ++ * lifetime inside the request's middleware, sends heartbeats carrying the ++ * last cursor, and ends when the client goes away. Services read by `poll` ++ * and `stream` are request-level, as for tools. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const registerEvent: < ++ Params extends Schema.Codec = Schema.Struct<{}>, ++ Payload extends Schema.Codec = Schema.Codec, ++ R = never ++>(options: EventOptions) => Effect.Effect> = ++ Effect.fnUntraced(function*(options: EventOptions, Schema.Codec, any>) { ++ const { name, poll, stream } = options ++ if (poll === undefined && stream === undefined) { ++ return yield* Effect.die(new Cause.IllegalArgumentError(`Event ${name}: give it poll, stream or both`)) ++ } ++ const registry = yield* McpServer ++ const { core, globalMiddleware } = internalState.get(registry)! ++ const services = yield* Effect.context() ++ const annotations = options.annotations ?? Context.empty() ++ const { invoke, visible } = makeInvoke(services, globalMiddleware) ++ const webhooks = stream === undefined ++ ? undefined ++ : Option.getOrUndefined(Option.map(Context.getOption(services, EventWebhooks), (service) => webhooksState.get(service))) ++ const parameters = options.parameters ?? Schema.Struct({}) ++ const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)) ++ const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)) ++ const argumentsOf = (args: unknown) => ++ decodeArguments(args).pipe(Effect.mapError((error) => new InvalidParams({ message: error.message }))) ++ const encodeEvent = (event: EventOccurrence) => ++ encodePayload(event.data).pipe( ++ Effect.flatMap((data) => Predicate.isReadonlyObject(data) ? Effect.succeed(data) : Effect.fail(data)), ++ Effect.map((data): McpCore.EncodedEvent => ({ ++ eventId: event.eventId, ++ timestamp: event.timestamp, ++ data, ++ ...(event._meta === undefined ? {} : { _meta: event._meta }) ++ })), ++ Effect.mapError(() => new InternalError({ message: `Event '${name}' payload failed to encode` })) ++ ) ++ yield* core.events.register({ ++ descriptor: { ++ name, ++ ...(options.description === undefined ? {} : { description: options.description }), ++ delivery: [ ++ ...(poll === undefined ? [] : ["poll" as const]), ++ ...(stream === undefined ? [] : ["push" as const]), ++ ...(webhooks === undefined ? [] : ["webhook" as const]) ++ ], ++ inputSchema: toolJsonSchema(parameters, false) as Record, ++ payloadSchema: toolJsonSchema(options.payload, false) as Record, ++ ...(options._meta === undefined ? {} : { _meta: options._meta }) ++ }, ++ isVisible: isEnabled(annotations), ++ visible: visible("events/list", name), ++ webhooks, ++ decodeArguments: argumentsOf, ++ poll: poll === undefined ? undefined : (request, invocation) => ++ invoke( ++ Effect.gen(function*() { ++ const result = yield* poll(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }) ++ return { ++ events: yield* Effect.forEach(result.events, encodeEvent), ++ cursor: result.cursor, ++ truncated: result.truncated ?? false, ++ hasMore: result.hasMore ?? false, ++ nextPollMs: result.nextPollMs ?? DEFAULT_NEXT_POLL_MS ++ } ++ }), ++ invocation, ++ { method: "events/poll", target: name, payload: request } ++ ), ++ stream: stream === undefined ? undefined : (request, invocation, deliver) => ++ invoke( ++ Effect.scoped(Effect.gen(function*() { ++ const args = request.decoded !== undefined ++ ? request.decoded.value ++ : yield* argumentsOf(request.arguments) ++ const subscription = yield* stream(args, { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs ++ }) ++ // The items run on the delivery fiber, so they keep this request's services. ++ const context = yield* Effect.context() ++ const items = subscription.items.pipe( ++ Stream.mapEffect((item): Effect.Effect => ++ item._tag === "Event" ++ ? encodeEvent(item).pipe( ++ Effect.map((event) => ({ ...event, _tag: "Event" as const, cursor: item.cursor })), ++ Effect.catch((error) => Effect.succeed({ _tag: "Error" as const, error })) ++ ) ++ : Effect.succeed(item) ++ ), ++ Stream.provideContext(context) ++ ) ++ yield* deliver({ cursor: subscription.cursor, truncated: subscription.truncated ?? false, items }) ++ })), ++ invocation, ++ { method: "events/stream", target: name, payload: request } ++ ) ++ }) ++ }) as any ++ ++/** ++ * Creates a layer that registers an event type under the MCP Events ++ * extension (SEP-3415). ++ * ++ * @see {@link registerEvent} for the Effect-level event registration API ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const event = < ++ Params extends Schema.Codec = Schema.Struct<{}>, ++ Payload extends Schema.Codec = Schema.Codec, ++ R = never ++>(options: EventOptions): Layer.Layer> => ++ Layer.effectDiscard(registerEvent(options)) ++ ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class CallbackRejected extends Data.TaggedError("CallbackRejected")<{ ++ readonly message: string ++}> {} ++ ++/** ++ * Decides which webhook callback URLs may be reached. ++ * ++ * **Details** ++ * ++ * `check` runs when a subscription is created and again before every POST. ++ * Resolving a host name needs the platform, so the default refuses every URL: ++ * a server that offers webhooks provides a guard that resolves the host and ++ * refuses addresses that are not globally routable. That check alone cannot ++ * stop DNS rebinding, so the `HttpClient` given to {@link layerEventWebhooks} ++ * must connect only to the address it validated, sending the original host ++ * name in `Host` and TLS SNI, and must not follow redirects. `allowsPlaintext` ++ * admits an `http:` URL, which only a local test setup should do. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const CallbackGuard = Context.Reference<{ ++ readonly check: (url: URL) => Effect.Effect ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined ++}>("effect/ai/McpServer/CallbackGuard", { ++ defaultValue: () => ({ ++ check: (url) => Effect.fail(new CallbackRejected({ message: `No callback guard admits ${url.host}` })) ++ }) ++}) ++ ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * Event types registered with a `stream` where this service is present also ++ * offer webhook delivery. `events/subscribe` validates the callback, verifies ++ * the endpoint with a challenge, and runs the event's `stream` for the ++ * subscription's lifetime, POSTing each occurrence with Standard Webhooks ++ * signatures, one at a time, retrying with backoff. Subscriptions live in ++ * memory: every grant is finite, between a minute and an hour, so a client ++ * refreshing from its cursor recreates what a restart lost. A failure of the ++ * stream, such as `Forbidden` when access is revoked, ends the subscription ++ * with a `terminated` envelope. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class EventWebhooks extends Context.Service ++}>()("effect/ai/McpServer/EventWebhooks") {} ++ ++const webhooksState = new WeakMap() ++ ++/** ++ * Options for {@link layerEventWebhooks}. ++ * ++ * **Details** ++ * ++ * `principal` names the authenticated subject of an `events/subscribe` or ++ * `events/unsubscribe` request, read from the request's services. It fails ++ * with `Forbidden` for a caller that may not subscribe; webhook delivery ++ * requires an authenticated principal. A subscription's identity is its ++ * principal, callback URL, event name and arguments, so the principal must ++ * stay the same across token refreshes. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventWebhooksOptions { ++ readonly principal: Effect.Effect ++} ++ ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const layerEventWebhooks = ( ++ options: EventWebhooksOptions ++): Layer.Layer => ++ Layer.effect( ++ EventWebhooks, ++ Effect.gen(function*() { ++ const webhooks = yield* McpWebhooks.make({ ++ principal: options.principal, ++ guard: yield* CallbackGuard, ++ client: yield* HttpClient.HttpClient ++ }) ++ const service = EventWebhooks.of({ size: webhooks.size }) ++ webhooksState.set(service, webhooks) ++ return service ++ }).pipe( ++ Effect.provide( ++ Layer.mergeAll(Mac.layerWebCrypto, Digest.layerWebCrypto).pipe( ++ Layer.provideMerge(SecureRandom.layerWebCrypto) ++ ) ++ ) ++ ) ++ ) ++ + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/src/ai/internal/mcpCore.ts b/src/ai/internal/mcpCore.ts +index 643982d..d705160 100644 +--- a/src/ai/internal/mcpCore.ts ++++ b/src/ai/internal/mcpCore.ts +@@ -8,6 +8,8 @@ import * as Data from "../../Data.ts" + import * as Effect from "../../Effect.ts" + import type * as McpProtocol from "../McpProtocol.ts" + import * as McpSchema from "../McpSchema.ts" ++import type * as Stream from "../../Stream.ts" ++import type * as McpWebhooks from "./mcpWebhooks.ts" + + /** + * @internal +@@ -330,6 +332,123 @@ export interface SkillRegistration { + readonly directory: (uri: string) => ReadonlyArray | undefined + } + ++/** ++ * A failure an event handler reports to the client as a JSON-RPC error, such ++ * as `McpSchema.Forbidden` or `McpSchema.InvalidParams`. ++ * ++ * @internal ++ */ ++export interface EventFailure { ++ readonly code: number ++ readonly message: string ++ readonly data?: unknown ++} ++ ++/** ++ * @internal ++ */ ++export interface EventPollRequest { ++ readonly arguments: Readonly> ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * An occurrence with its payload already encoded for the wire. ++ * ++ * @internal ++ */ ++export interface EncodedEvent { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: Readonly> ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface EventPollOutcome { ++ readonly events: ReadonlyArray ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly hasMore: boolean ++ readonly nextPollMs: number ++} ++ ++/** ++ * @internal ++ */ ++export interface EventStreamRequest { ++ readonly arguments: Readonly> ++ // Set when the arguments were already decoded, as a webhook subscribe does first. ++ readonly decoded?: { readonly value: unknown } | undefined ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries after `notifications/events/active`: occurrences, ++ * a position checked without a match (carried by the next heartbeat), a gap ++ * (a fresh `active` with `truncated`), or a recoverable error. ++ * ++ * @internal ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EncodedEvent) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventFailure } ++ ++/** ++ * A push subscription the handler accepted. A failure of `items` ends it with ++ * `notifications/events/terminated`. ++ * ++ * @internal ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly items: Stream.Stream ++} ++ ++/** ++ * @internal ++ */ ++export interface EventRegistration { ++ readonly descriptor: McpSchema.EventDescriptor ++ readonly isVisible: (profile: NegotiatedProtocolProfile) => boolean ++ readonly visible?: Visible | undefined ++ // Set when webhook delivery is offered, which runs `stream`. ++ readonly webhooks?: McpWebhooks.Webhooks | undefined ++ readonly decodeArguments: (args: unknown) => Effect.Effect ++ readonly poll?: ++ | (( ++ request: EventPollRequest, ++ invocation: McpInvocation ++ ) => Effect.Effect) ++ | undefined ++ // Runs for the subscription's lifetime: `deliver` takes over once the ++ // handler accepts it, so a failure before that is the request's error. ++ readonly stream?: ++ | (( ++ request: EventStreamRequest, ++ invocation: McpInvocation, ++ deliver: (subscription: EventSubscription) => Effect.Effect ++ ) => Effect.Effect) ++ | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface Events { ++ readonly register: (registration: EventRegistration) => Effect.Effect ++ readonly list: (invocation: McpInvocation) => Effect.Effect, RequestRejected> ++ readonly get: (name: string, invocation: McpInvocation) => Effect.Effect ++} ++ + /** + * @internal + */ +@@ -507,11 +626,13 @@ export interface McpCore { + readonly prompts: Prompts + readonly completions: Completions + readonly skills: Skills ++ readonly events: Events + readonly registrationPresence: Effect.Effect<{ + readonly tools: boolean + readonly resources: boolean + readonly prompts: boolean + readonly skills: boolean ++ readonly events: boolean + }> + } + +@@ -523,6 +644,12 @@ export interface McpCore { + */ + export type Visible = (invocation: McpInvocation) => Effect.Effect + ++/** ++ * @internal ++ */ ++export const eventNotFound = (name: string): McpSchema.NotFound => ++ new McpSchema.NotFound({ message: `Event '${name}' not found`, data: { kind: "event" } }) ++ + // Whether one skill directory contains the other, or both are the same. + const skillsOverlap = (a: string, b: string): boolean => { + const rootA = a.slice(0, -"/SKILL.md".length) +@@ -539,6 +666,7 @@ export const make: Effect.Effect = Effect.sync(() => { + const resourceTemplateRegistrations: Array = [] + const promptRegistrations = new Map() + const skillRegistrations = new Map() ++ const eventRegistrations = new Map() + const skillFiles = new Set() + const completionRegistrations = new Map< + string, +@@ -717,12 +845,28 @@ export const make: Effect.Effect = Effect.sync(() => { + }) + } + ++ const events: Events = { ++ register: (registration) => ++ Effect.sync(() => { ++ eventRegistrations.set(registration.descriptor.name, registration) ++ }), ++ list: (invocation) => filterList(eventRegistrations.values(), invocation), ++ get: (name, invocation) => ++ Effect.suspend(() => { ++ const registration = eventRegistrations.get(name) ++ return registration !== undefined && registration.isVisible(invocation.protocol) ++ ? Effect.succeed(registration) ++ : Effect.fail(eventNotFound(name)) ++ }) ++ } ++ + const registrationPresence = Effect.sync(() => ({ + tools: registrations.size > 0, + resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, + prompts: promptRegistrations.size > 0, +- skills: skillRegistrations.size > 0 ++ skills: skillRegistrations.size > 0, ++ events: eventRegistrations.size > 0 + })) + +- return { tools, resources, prompts, completions, skills, registrationPresence } ++ return { tools, resources, prompts, completions, skills, events, registrationPresence } + }) +diff --git a/src/ai/internal/mcpEvents.ts b/src/ai/internal/mcpEvents.ts +new file mode 100644 +index 0000000..54b2ca8 +--- /dev/null ++++ b/src/ai/internal/mcpEvents.ts +@@ -0,0 +1,315 @@ ++/** ++ * The Events extension (SEP-3415): wire schemas on revision 2026-07-28 and ++ * the delivery loop behind a push stream. ++ */ ++import * as Cause from "../../Cause.ts" ++import * as Clock from "../../Clock.ts" ++import * as Duration from "../../Duration.ts" ++import * as Effect from "../../Effect.ts" ++import * as Option from "../../Option.ts" ++import * as Queue from "../../Queue.ts" ++import * as Result from "../../Result.ts" ++import * as Rpc from "../../rpc/Rpc.ts" ++import * as RpcGroup from "../../rpc/RpcGroup.ts" ++import * as Schema from "../../Schema.ts" ++import * as Stream from "../../Stream.ts" ++import * as PublicMcpSchema from "../McpSchema.ts" ++import type * as McpCore from "./mcpCore.ts" ++import * as McpProtocol from "./mcpProtocol.ts" ++import * as Stateless from "./mcpSchema/v2026_07_28.ts" ++ ++/** ++ * @internal ++ */ ++export const EXTENSION_ID = "io.modelcontextprotocol/events" ++ ++/** ++ * Adds the extension declaration while any event type is registered. The ++ * server sends no `notifications/events/list_changed`, so its settings object ++ * is empty. ++ * ++ * @internal ++ */ ++export const declareExtension = ( ++ extensions: Readonly> | undefined, ++ servesEvents: boolean ++): Readonly> | undefined => ++ servesEvents ? { ...extensions, [EXTENSION_ID]: {} } : extensions ++ ++const methodNotFound = (method: string) => ++ new McpProtocol.ProtocolError({ ++ code: PublicMcpSchema.METHOD_NOT_FOUND_ERROR_CODE, ++ message: `Method not found: ${method}` ++ }) ++ ++/** ++ * Fails with `Method not found` while no event type is registered, as a ++ * server that does not declare the extension. ++ * ++ * @internal ++ */ ++export const requireEvents = (core: McpCore.McpCore, method: string) => ++ Effect.flatMap( ++ core.registrationPresence, ++ (presence) => presence.events ? Effect.void : Effect.fail(methodNotFound(method)) ++ ) ++ ++/** ++ * @internal ++ */ ++export const unsupportedDelivery = (value: PublicMcpSchema.EventDelivery) => ++ new PublicMcpSchema.Unsupported({ ++ message: `Delivery mode '${value}' is not supported for this event`, ++ data: { feature: "deliveryMode", value } ++ }) ++ ++// ============================================================================= ++// Wire schemas ++// ============================================================================= ++ ++const optional = Stateless.optional ++const Cursor = Schema.NullOr(Schema.String) ++const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) ++ ++/** ++ * @internal ++ */ ++export const ListEventsResult = Schema.StructWithRest( ++ Schema.Struct({ ...Stateless.PaginatedResult, events: Schema.Array(PublicMcpSchema.EventDescriptor) }), ++ [Stateless.UnknownObject] ++) ++ ++/** ++ * @internal ++ */ ++export class ListEvents extends Rpc.make("events/list", { ++ success: ListEventsResult, ++ error: Stateless.McpError, ++ payload: Stateless.PaginatedRequestParams ++}) {} ++ ++const SubscriptionParams = { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ cursor: optional(Cursor), ++ maxAgeMs: optional(NonNegativeInt) ++} ++ ++/** ++ * @internal ++ */ ++export const PollEventsResult = Schema.StructWithRest( ++ Schema.Struct({ ++ ...Stateless.ResultMeta, ++ events: Schema.Array(PublicMcpSchema.EventOccurrence), ++ cursor: Cursor, ++ truncated: Schema.Boolean, ++ hasMore: Schema.Boolean, ++ nextPollMs: NonNegativeInt ++ }), ++ [Stateless.UnknownObject] ++) ++ ++/** ++ * @internal ++ */ ++export class PollEvents extends Rpc.make("events/poll", { ++ success: PollEventsResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, maxEvents: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))) } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class StreamEvents extends Rpc.make("events/stream", { ++ success: Stateless.SubscriptionsListenResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, heartbeatMs: optional(NonNegativeInt) } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class SubscribeEvents extends Rpc.make("events/subscribe", { ++ success: Schema.StructWithRest( ++ Schema.Struct({ ++ ...Stateless.ResultMeta, ++ id: Schema.String, ++ refreshBefore: Schema.NullOr(Schema.String), ++ cursor: Cursor, ++ truncated: Schema.Boolean ++ }), ++ [Stateless.UnknownObject] ++ ), ++ error: Stateless.McpError, ++ payload: { ++ ...SubscriptionParams, ++ delivery: Stateless.UnknownObject, ++ ttlMs: optional(Schema.NullOr(NonNegativeInt)) ++ } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class UnsubscribeEvents extends Rpc.make("events/unsubscribe", { ++ success: Schema.StructWithRest(Schema.Struct(Stateless.ResultMeta), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ delivery: Stateless.UnknownObject ++ } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsActiveNotification extends Rpc.make("notifications/events/active", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor, truncated: Schema.Boolean, heartbeatMs: NonNegativeInt } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsEventNotification extends Rpc.make("notifications/events/event", { ++ payload: { ...PublicMcpSchema.EventOccurrence.fields, ...Stateless.NotificationParams.fields } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsHeartbeatNotification extends Rpc.make("notifications/events/heartbeat", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsErrorNotification extends Rpc.make("notifications/events/error", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsTerminatedNotification extends Rpc.make("notifications/events/terminated", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) {} ++ ++/** ++ * The extension's requests on revision 2026-07-28. ++ * ++ * @internal ++ */ ++export class StatelessRpcs ++ extends RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents) ++{} ++ ++/** ++ * The notifications a push stream carries. ++ * ++ * @internal ++ */ ++export class ServerNotificationRpcs extends RpcGroup.make( ++ EventsActiveNotification, ++ EventsEventNotification, ++ EventsHeartbeatNotification, ++ EventsErrorNotification, ++ EventsTerminatedNotification ++) {} ++ ++// ============================================================================= ++// Push delivery ++// ============================================================================= ++ ++const DEFAULT_HEARTBEAT_MS = 30_000 ++const MIN_HEARTBEAT_MS = 1_000 ++const MAX_HEARTBEAT_MS = 300_000 ++// Occurrences the handler may run ahead of a slow client before it waits. ++const PENDING_ITEMS = 16 ++ ++/** ++ * The heartbeat interval granted for a suggested one. ++ * ++ * @internal ++ */ ++export const grantHeartbeat = (suggested: number | undefined): number => ++ Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, suggested ?? DEFAULT_HEARTBEAT_MS)) ++ ++const isJson = Schema.is(Schema.Json) ++ ++/** ++ * @internal ++ */ ++export const wireError = (failure: McpCore.EventFailure): Stateless.McpError => ({ ++ code: failure.code, ++ message: failure.message, ++ ...(failure.data !== undefined && isJson(failure.data) ? { data: failure.data } : {}) ++}) ++ ++/** ++ * Sends `notifications/events/active`, then each occurrence, and a heartbeat ++ * with the position checked so far whenever `heartbeatMs` passes without ++ * another message. A failure of the subscription's items ends it with ++ * `notifications/events/terminated`. `send` adds the subscription id. ++ * ++ * @internal ++ */ ++export const deliver = Effect.fnUntraced(function*(options: { ++ readonly name: string ++ readonly subscription: McpCore.EventSubscription ++ readonly heartbeatMs: number ++ readonly send: (tag: string, payload: Readonly>) => Effect.Effect ++}) { ++ const { heartbeatMs, name, subscription } = options ++ let cursor = subscription.cursor ++ // Measured from the last message sent: a Position changes the cursor but sends nothing. ++ let sentAt = 0 ++ const send = (tag: string, payload: Readonly>) => ++ options.send(tag, payload).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((at) => { ++ sentAt = at ++ })) ++ const active = (truncated: boolean) => send(EventsActiveNotification._tag, { cursor, truncated, heartbeatMs }) ++ yield* active(subscription.truncated) ++ const items = yield* Stream.toQueue(subscription.items, { capacity: PENDING_ITEMS }) ++ while (true) { ++ const wait = Math.max(0, sentAt + heartbeatMs - (yield* Clock.currentTimeMillis)) ++ const next = yield* Queue.take(items).pipe(Effect.timeoutOption(Duration.millis(wait)), Effect.result) ++ if (Result.isFailure(next)) { ++ if (!Cause.isDone(next.failure)) { ++ yield* send(EventsTerminatedNotification._tag, { error: wireError(next.failure) }) ++ } ++ return ++ } ++ if (Option.isNone(next.success)) { ++ yield* send(EventsHeartbeatNotification._tag, { cursor }) ++ continue ++ } ++ const item = next.success.value ++ switch (item._tag) { ++ case "Event": { ++ cursor = item.cursor ++ const { _meta, _tag, ...occurrence } = item ++ yield* send(EventsEventNotification._tag, { ...occurrence, name, ...(_meta === undefined ? {} : { _meta }) }) ++ break ++ } ++ case "Position": { ++ cursor = item.cursor ++ break ++ } ++ case "Gap": { ++ cursor = item.cursor ++ yield* active(true) ++ break ++ } ++ case "Error": { ++ yield* send(EventsErrorNotification._tag, { error: wireError(item.error) }) ++ break ++ } ++ } ++ } ++}, Effect.scoped) +diff --git a/src/ai/internal/mcpProtocol.ts b/src/ai/internal/mcpProtocol.ts +index 5393651..f40915b 100644 +--- a/src/ai/internal/mcpProtocol.ts ++++ b/src/ai/internal/mcpProtocol.ts +@@ -484,6 +484,7 @@ export interface HandlerInstallationContext { + readonly resources: boolean + readonly prompts: boolean + readonly skills: boolean ++ readonly events: boolean + }> + } + +diff --git a/src/ai/internal/mcpProtocol/v2026_07_28.ts b/src/ai/internal/mcpProtocol/v2026_07_28.ts +index a701ec8..8e4b36a 100644 +--- a/src/ai/internal/mcpProtocol/v2026_07_28.ts ++++ b/src/ai/internal/mcpProtocol/v2026_07_28.ts +@@ -22,6 +22,7 @@ import type * as Types from "../../../Types.ts" + import type * as PublicMcpProtocol from "../../McpProtocol.ts" + import * as PublicMcpSchema from "../../McpSchema.ts" + import * as McpCore from "../mcpCore.ts" ++import * as McpEvents from "../mcpEvents.ts" + import * as McpProtocol from "../mcpProtocol.ts" + import * as McpSchema from "../mcpSchema/v2026_07_28.ts" + import * as McpSkills from "../mcpSkills.ts" +@@ -344,7 +345,11 @@ const unsupported = ( + /** + * @internal + */ +-export const handlerRpcs = McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs) ++export const handlerRpcs = McpSchema.ClientRequestRpcs.merge( ++ McpSchema.ClientNotificationRpcs, ++ McpSkills.StatelessRpcs, ++ McpEvents.StatelessRpcs ++) + + /** + * @internal +@@ -370,6 +375,10 @@ export const makeHandlers = ( + const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult) + const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult) + const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult) ++ const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult) ++ const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult) ++ const decodeSubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.SubscribeEvents.successSchema) ++ const decodeUnsubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.UnsubscribeEvents.successSchema) + const sendNotification = context.sendNotification + const supportsSubscriptions = sendNotification !== undefined + // Older adapters accept arbitrary JSON; this binding requires extension settings objects. +@@ -384,8 +393,14 @@ export const makeHandlers = ( + } + const getDiscovery = Effect.map(context.registrationPresence, (presence) => { + const capabilities: Types.Mutable = { completions: {}, logging: {} } +- const declared = McpSkills.declareExtension(extensions, presence.skills) ++ const declared = McpEvents.declareExtension( ++ McpSkills.declareExtension(extensions, presence.skills), ++ presence.events ++ ) + if (declared !== undefined) capabilities.extensions = declared ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They look for a top-level `events` capability instead of the extension. ++ if (presence.events) capabilities.events = {} + if (presence.tools) capabilities.tools = { listChanged: supportsSubscriptions } + if (presence.resources) { + capabilities.resources = { listChanged: supportsSubscriptions, subscribe: supportsSubscriptions } +@@ -393,6 +408,30 @@ export const makeHandlers = ( + if (presence.prompts) capabilities.prompts = { listChanged: supportsSubscriptions } + return { supportedVersions: context.supportedVersions, capabilities, serverInfo: context.serverInfo } + }) ++ const requireEvents = (method: string) => ++ McpEvents.requireEvents(core, method).pipe(Effect.catch((error) => failWithHttpStatus(404, error))) ++ // The event type's `x-mcp-header` arguments must match their headers, as a tool's do. ++ const validateEventHeaders = Effect.fnUntraced(function*( ++ registration: McpCore.EventRegistration, ++ args: unknown ++ ) { ++ const httpRequest = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest) ++ if (Option.isSome(httpRequest)) { ++ yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers) ++ } ++ }) ++ // Webhook delivery runs the event's push stream, so it needs both. ++ const webhookRegistration = Effect.fnUntraced(function*(method: string, name: string, args: unknown) { ++ yield* requireEvents(method) ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(name, invocation) ++ const { stream, webhooks } = registration ++ if (webhooks === undefined || stream === undefined) { ++ return yield* McpEvents.unsupportedDelivery("webhook") ++ } ++ yield* validateEventHeaders(registration, args) ++ return { invocation, stream, webhooks, decodeArguments: registration.decodeArguments } ++ }) + const requireSkills = (method: string) => + McpSkills.requireSkills(core, method).pipe( + Effect.catch((error) => failWithHttpStatus(404, error)) +@@ -728,6 +767,121 @@ export const makeHandlers = ( + const result = yield* projectCompleteResult({ ...cacheHint("skills"), resources }, context.serverInfo) + return yield* decodeReadResourceDirectoryResult(result) + }, Effect.mapError(projectError)), ++ "events/list": Effect.fnUntraced(function*(request: typeof McpEvents.ListEvents.payloadSchema.Type) { ++ yield* requireEvents("events/list") ++ yield* McpProtocol.rejectCursor(request.cursor) ++ const events = yield* core.events.list(yield* getInvocation) ++ // Without a notification channel nothing can be pushed. ++ const offered = supportsSubscriptions ? events : events.flatMap((event) => { ++ const delivery = event.delivery.filter((mode) => mode !== "push") ++ return delivery.length === 0 ? [] : [{ ...event, delivery }] ++ }) ++ const result = yield* projectCompleteResult({ events: offered }, context.serverInfo) ++ return yield* decodeListEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/poll": Effect.fnUntraced(function*(request: typeof McpEvents.PollEvents.payloadSchema.Type) { ++ yield* requireEvents("events/poll") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(request.name, invocation) ++ if (registration.poll === undefined) { ++ return yield* McpEvents.unsupportedDelivery("poll") ++ } ++ yield* validateEventHeaders(registration, request.arguments) ++ const outcome = yield* registration.poll({ ++ arguments: request.arguments ?? {}, ++ cursor: request.cursor ?? null, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }, invocation) ++ const result = yield* projectCompleteResult({ ++ events: outcome.events.map((event) => ++ omitUndefined({ ++ eventId: event.eventId, ++ name: request.name, ++ timestamp: event.timestamp, ++ data: event.data, ++ _meta: event._meta ++ }) ++ ), ++ cursor: outcome.cursor, ++ truncated: outcome.truncated, ++ hasMore: outcome.hasMore, ++ nextPollMs: outcome.nextPollMs ++ }, context.serverInfo) ++ return yield* decodePollEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/stream": Effect.fnUntraced(function*( ++ request: typeof McpEvents.StreamEvents.payloadSchema.Type, ++ { client, requestId }: { readonly client: Rpc.ServerClient; readonly requestId: RpcMessage.RequestId } ++ ) { ++ yield* requireEvents("events/stream") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(request.name, invocation) ++ if (registration.stream === undefined || sendNotification === undefined) { ++ return yield* McpEvents.unsupportedDelivery("push") ++ } ++ yield* validateEventHeaders(registration, request.arguments) ++ const subscriptionMetadata = { "io.modelcontextprotocol/subscriptionId": requestId } ++ const send = (tag: string, payload: Readonly>) => ++ sendNotification(McpSchema.protocolVersion, client.id, { ++ tag, ++ payload: { ++ ...payload, ++ _meta: { ...(Predicate.isReadonlyObject(payload._meta) ? payload._meta : {}), ...subscriptionMetadata } ++ } ++ }) ++ const heartbeatMs = McpEvents.grantHeartbeat(request.heartbeatMs) ++ yield* Effect.raceFirst( ++ registration.stream( ++ { arguments: request.arguments ?? {}, cursor: request.cursor ?? null, maxAgeMs: request.maxAgeMs }, ++ invocation, ++ (subscription) => McpEvents.deliver({ name: request.name, subscription, heartbeatMs, send }) ++ ), ++ context.awaitClientEnd ?? Effect.never ++ ) ++ const encodedServerInfo = yield* encodeImplementation(context.serverInfo) ++ return McpSchema.SubscriptionsListenResult.make({ ++ _meta: { ...subscriptionMetadata, "io.modelcontextprotocol/serverInfo": encodedServerInfo }, ++ resultType: "complete" ++ }) ++ }, Effect.mapError(projectError)), ++ "events/subscribe": Effect.fnUntraced(function*(request: typeof McpEvents.SubscribeEvents.payloadSchema.Type) { ++ const { decodeArguments, invocation, stream, webhooks } = yield* webhookRegistration( ++ "events/subscribe", ++ request.name, ++ request.arguments ++ ) ++ const args = request.arguments ?? {} ++ const cursor = request.cursor ?? null ++ const subscribed = yield* webhooks.subscribe({ ++ name: request.name, ++ arguments: args, ++ delivery: request.delivery, ++ cursor, ++ ttlMs: request.ttlMs, ++ decode: decodeArguments(args), ++ open: (decoded, deliver) => ++ stream( ++ { arguments: args, decoded: { value: decoded }, cursor, maxAgeMs: request.maxAgeMs }, ++ invocation, ++ deliver ++ ) ++ }) ++ const result = yield* projectCompleteResult(omitUndefined({ ...subscribed }), context.serverInfo) ++ return yield* decodeSubscribeEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/unsubscribe": Effect.fnUntraced(function*( ++ request: typeof McpEvents.UnsubscribeEvents.payloadSchema.Type ++ ) { ++ const { webhooks } = yield* webhookRegistration("events/unsubscribe", request.name, request.arguments) ++ yield* webhooks.unsubscribe({ ++ name: request.name, ++ arguments: request.arguments ?? {}, ++ delivery: request.delivery ++ }) ++ const result = yield* projectCompleteResult({}, context.serverInfo) ++ return yield* decodeUnsubscribeEventsResult(result) ++ }, Effect.mapError(projectError)), + "notifications/cancelled": Effect.fnUntraced(function*( + _request: typeof McpSchema.CancelledNotification.payloadSchema.Type + ) { +@@ -751,10 +905,10 @@ const runtime = { + export const protocol = McpProtocol.make({ + protocolVersion: McpSchema.protocolVersion, + runtime, +- clientRpcs: McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs), ++ clientRpcs: McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs, McpEvents.StatelessRpcs), + clientNotificationRpcs: McpSchema.ClientNotificationRpcs, + serverRequestRpcs: McpSchema.ServerRequestRpcs, +- serverNotificationRpcs: McpSchema.ServerNotificationRpcs, ++ serverNotificationRpcs: McpSchema.ServerNotificationRpcs.merge(McpEvents.ServerNotificationRpcs), + handlerRpcs, + makeHandlers, + toReverseClient: () => ({ +diff --git a/src/ai/internal/mcpRuntime.ts b/src/ai/internal/mcpRuntime.ts +index 9d4c96e..0afe3ed 100644 +--- a/src/ai/internal/mcpRuntime.ts ++++ b/src/ai/internal/mcpRuntime.ts +@@ -53,6 +53,10 @@ const routingNameKey = (method: string): "name" | "uri" | undefined => { + switch (method) { + case "tools/call": + case "prompts/get": ++ case "events/poll": ++ case "events/stream": ++ case "events/subscribe": ++ case "events/unsubscribe": + return "name" + case "resources/read": + return "uri" +@@ -319,7 +323,13 @@ export const make = Effect.fnUntraced(function*( + if (nameKey !== undefined) { + const name = asRecord(inputRecord?.params)?.[nameKey] + const header = headers[MCP_NAME_HEADER] +- if (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) { ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They send no Mcp-Name on these; one they do send must still match. ++ const optional = header === undefined && (method === "events/subscribe" || method === "events/unsubscribe") ++ if ( ++ !optional && ++ (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) ++ ) { + return headerMismatch("Mcp-Name header does not match request parameters") + } + } +@@ -479,7 +489,9 @@ export const make = Effect.fnUntraced(function*( + return { + _tag: "Accepted", + acknowledge: !isRequest || !hasId, +- isSubscription: Predicate.hasProperty(input, "method") && input.method === "subscriptions/listen" ++ // A push subscription stays open until cancelled, so it is never a plain response. ++ isSubscription: Predicate.hasProperty(input, "method") && ++ (input.method === "subscriptions/listen" || input.method === "events/stream") + } + }, + effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/src/ai/internal/mcpWebhooks.ts b/src/ai/internal/mcpWebhooks.ts +new file mode 100644 +index 0000000..5b53d08 +--- /dev/null ++++ b/src/ai/internal/mcpWebhooks.ts +@@ -0,0 +1,692 @@ ++/** ++ * Webhook delivery for the Events extension (SEP-3415): `events/subscribe` ++ * validation, subscription identity, Standard Webhooks signing, the endpoint ++ * verification handshake and the delivery loop. ++ * ++ * Subscriptions live in memory. Every grant is finite, so a subscription lost ++ * in a restart comes back on the client's next refresh, from its cursor. ++ */ ++import * as Clock from "../../Clock.ts" ++import * as Digest from "../../crypto/Digest.ts" ++import * as Mac from "../../crypto/Mac.ts" ++import * as SecureRandom from "../../crypto/SecureRandom.ts" ++import * as Deferred from "../../Deferred.ts" ++import * as Duration from "../../Duration.ts" ++import * as Effect from "../../Effect.ts" ++import * as Base64 from "../../encoding/Base64.ts" ++import * as Base64Url from "../../encoding/Base64Url.ts" ++import * as Fiber from "../../Fiber.ts" ++import * as FetchHttpClient from "../../http/FetchHttpClient.ts" ++import * as HttpClient from "../../http/HttpClient.ts" ++import * as HttpClientRequest from "../../http/HttpClientRequest.ts" ++import type * as HttpClientResponse from "../../http/HttpClientResponse.ts" ++import * as Option from "../../Option.ts" ++import * as Result from "../../Result.ts" ++import * as Stream from "../../Stream.ts" ++import * as PublicMcpSchema from "../McpSchema.ts" ++import type * as McpCore from "./mcpCore.ts" ++import { wireError } from "./mcpEvents.ts" ++ ++const MINUTE_MS = 60_000 ++/** @internal */ ++export const MIN_TTL_MS = MINUTE_MS ++// Short grants because subscriptions live in memory: a restart loses them until the next refresh. ++/** @internal */ ++export const MAX_TTL_MS = 60 * MINUTE_MS ++/** @internal */ ++export const DEFAULT_TTL_MS = 15 * MINUTE_MS ++/** @internal */ ++export const MAX_ATTEMPTS = 5 ++// Retries wait 30 s, 1, 2 and 4 minutes: about 7.5 minutes in all. ++const FIRST_RETRY_MS = 30_000 ++const REQUEST_TIMEOUT_MS = 10_000 ++// Deliveries signed with the old secret before a rotation still verify for this long. ++const ROTATION_GRACE_MS = 5 * MINUTE_MS ++const VERIFIED_FOR_MS = MAX_TTL_MS ++// A failed challenge is answered from here, so repeated subscribes cannot flood the endpoint. ++const FAILED_FOR_MS = 5 * MINUTE_MS ++// Verification POSTs one destination host receives per minute, across all principals. ++const VERIFICATIONS_PER_HOST_PER_MINUTE = 10 ++const MAX_SUBSCRIPTIONS_PER_PRINCIPAL = 100 ++// A verification reads this many bytes of the response at most; a delivery reads none. ++const MAX_CHALLENGE_RESPONSE_BYTES = 8_192 ++const SECRET_PREFIX = "whsec_" ++ ++/** ++ * The fixed categories `deliveryStatus.lastError` and `CallbackEndpointError` ++ * report; never the endpoint's own response. ++ * ++ * @internal ++ */ ++export type FailureCategory = ++ | "connection_refused" ++ | "timeout" ++ | "tls_error" ++ | "http_4xx" ++ | "http_5xx" ++ | "challenge_failed" ++ ++/** ++ * @internal ++ */ ++export interface Guard { ++ readonly check: (url: URL) => Effect.Effect ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface Options { ++ readonly principal: Effect.Effect ++ readonly guard: Guard ++ readonly client: HttpClient.HttpClient ++} ++ ++/** ++ * @internal ++ */ ++export interface SubscribeRequest { ++ readonly name: string ++ readonly arguments: Readonly> ++ readonly delivery: Readonly> ++ readonly cursor: string | null ++ readonly ttlMs?: number | null | undefined ++ // The event's argument decoder, run before the endpoint is contacted. ++ readonly decode: Effect.Effect ++ // Runs the event's stream for the subscription's lifetime, as push delivery does. ++ readonly open: ( ++ decoded: unknown, ++ deliver: (subscription: McpCore.EventSubscription) => Effect.Effect ++ ) => Effect.Effect ++} ++ ++/** ++ * @internal ++ */ ++export interface SubscribeResult { ++ readonly id: string ++ readonly refreshBefore: string ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly deliveryStatus?: { ++ readonly active: boolean ++ readonly lastDeliveryAt: string | null ++ readonly lastError: FailureCategory | null ++ } | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface UnsubscribeRequest { ++ readonly name: string ++ readonly arguments: Readonly> ++ readonly delivery: Readonly> ++} ++ ++/** ++ * @internal ++ */ ++export interface Webhooks { ++ readonly subscribe: ( ++ request: SubscribeRequest ++ ) => Effect.Effect ++ readonly unsubscribe: (request: UnsubscribeRequest) => Effect.Effect ++ readonly size: Effect.Effect ++} ++ ++interface Subscription { ++ readonly id: string ++ readonly principal: string ++ readonly url: URL ++ secret: string ++ key: Mac.Key ++ previous: { readonly key: Mac.Key; readonly until: number } | undefined ++ expiresAt: number ++ // Everything at or before it was acknowledged or given up on. ++ watermark: string | null ++ lastDeliveryAt: number | undefined ++ lastError: FailureCategory | undefined ++ fiber: Fiber.Fiber | undefined ++ // Completed when a refresh moves the deadline, so the expiry recomputes it. ++ deadlineMoved: Deferred.Deferred ++ // Where the event's stream started, or why it could not; a same-key refresh waits for it. ++ readonly accepted: Deferred.Deferred< ++ { readonly cursor: string | null; readonly truncated: boolean }, ++ McpCore.EventFailure | McpCore.RequestRejected ++ > ++ // After a gap whose envelope the endpoint never took: the cursors handed out since, any of ++ // which a refresh presents to say it saw past the gap. Until then every refresh is truncated. ++ cursorsSinceGap: Set | undefined ++} ++ ++type Outcome = ++ // `body` is read only for a verification, and is undefined when it was too long. ++ | { readonly _tag: "Delivered"; readonly body: string | undefined } ++ | { readonly _tag: "Failed"; readonly category: FailureCategory; readonly retryable: boolean } ++ ++const invalid = (message: string) => new PublicMcpSchema.InvalidParams({ message }) ++ ++/** ++ * The TTL granted for a suggested one: the default when none is suggested, and ++ * never unbounded, since subscriptions are not kept across restarts. ++ * ++ * @internal ++ */ ++export const grantTtl = (suggested: number | null | undefined): number => ++ suggested === undefined ++ ? DEFAULT_TTL_MS ++ : suggested === null ++ ? MAX_TTL_MS ++ : Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, suggested)) ++ ++/** ++ * JSON with object keys sorted, so equal arguments serialize equally. ++ * ++ * @internal ++ */ ++export const canonicalJson = (value: unknown): string => { ++ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]` ++ if (typeof value === "object" && value !== null) { ++ const entries = Object.entries(value).filter(([, entry]) => entry !== undefined) ++ entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) ++ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}` ++ } ++ return JSON.stringify(value) ?? "null" ++} ++ ++const encoder = new TextEncoder() ++ ++const parseUrl = (value: unknown, guard: Guard) => { ++ if (typeof value !== "string") return Effect.fail(invalid("delivery.url is required")) ++ let url: URL ++ try { ++ url = new URL(value) ++ } catch { ++ return Effect.fail(invalid("delivery.url is not a valid URL")) ++ } ++ if (url.protocol !== "https:" && !(url.protocol === "http:" && guard.allowsPlaintext?.(url) === true)) { ++ return Effect.fail(invalid("delivery.url must use https")) ++ } ++ if (url.username !== "" || url.password !== "") { ++ return Effect.fail(invalid("delivery.url must not carry credentials")) ++ } ++ url.hash = "" ++ return Effect.succeed(url) ++} ++ ++const parseSecret = (value: unknown) => { ++ const fail = Effect.fail(invalid("delivery.secret must be whsec_ and the base64 of 24 to 64 random bytes")) ++ if (typeof value !== "string" || !value.startsWith(SECRET_PREFIX)) return fail ++ const bytes = Base64.decode(value.slice(SECRET_PREFIX.length)) ++ if (Result.isFailure(bytes) || bytes.success.length < 24 || bytes.success.length > 64) return fail ++ return Mac.key(Mac.hmacSha256, bytes.success).pipe(Effect.orDie, Effect.map((key) => ({ text: value, key }))) ++} ++ ++const statusCategory = (status: number): FailureCategory => (status >= 500 ? "http_5xx" : "http_4xx") ++ ++// Only codes and names are read, never what the endpoint sent. ++const transportCategory = (error: unknown): FailureCategory => { ++ let current: unknown = error ++ for (let depth = 0; depth < 8 && typeof current === "object" && current !== null; depth++) { ++ const code = (current as { readonly code?: unknown }).code ++ if (typeof code === "string" && /CERT|TLS|SSL/.test(code)) return "tls_error" ++ current = (current as { readonly cause?: unknown }).cause ?? ++ (current as { readonly reason?: unknown }).reason ++ } ++ return "connection_refused" ++} ++ ++// Stops pulling past the cap; closing the request's scope then aborts the rest. ++const readCapped = (response: HttpClientResponse.HttpClientResponse) => ++ Effect.suspend(() => { ++ const chunks: Array = [] ++ let total = 0 ++ let oversized = false ++ return response.stream.pipe( ++ Stream.takeWhile((chunk) => { ++ if (total + chunk.length > MAX_CHALLENGE_RESPONSE_BYTES) { ++ oversized = true ++ return false ++ } ++ total += chunk.length ++ chunks.push(chunk) ++ return true ++ }), ++ Stream.runDrain, ++ Effect.map(() => { ++ if (oversized) return undefined ++ const bytes = new Uint8Array(total) ++ let offset = 0 ++ for (const chunk of chunks) { ++ bytes.set(chunk, offset) ++ offset += chunk.length ++ } ++ return new TextDecoder().decode(bytes) ++ }) ++ ) ++ }) ++ ++const echoedChallenge = (body: string): string | undefined => { ++ try { ++ const parsed: unknown = JSON.parse(body) ++ const challenge = typeof parsed === "object" && parsed !== null ++ ? (parsed as { readonly challenge?: unknown }).challenge ++ : undefined ++ return typeof challenge === "string" ? challenge : undefined ++ } catch { ++ return undefined ++ } ++} ++ ++const callbackError = (category: FailureCategory) => ++ new PublicMcpSchema.CallbackEndpointError({ ++ message: `The callback endpoint failed verification: ${category}`, ++ data: { reason: category } ++ }) ++ ++const iso = (millis: number) => new Date(millis).toISOString() ++ ++/** ++ * @internal ++ */ ++export const make = Effect.fnUntraced(function*(options: Options) { ++ const scope = yield* Effect.scope ++ const mac = yield* Mac.Mac ++ const digest = yield* Digest.Digest ++ const random = yield* SecureRandom.SecureRandom ++ const { guard } = options ++ // Closing a request's scope aborts its body, so a delivery never downloads what the endpoint sends. ++ const client = HttpClient.withScope(options.client) ++ const subscriptions = new Map() ++ // Subscribes past the principal check that have not created their subscription yet. ++ const pending = new Map() ++ const verified = new Map() ++ const failedVerifications = new Map() ++ const verifying = new Map>() ++ const verificationsByHost = new Map>() ++ ++ const forget = (subscription: Subscription) => { ++ if (subscriptions.get(subscription.id) === subscription) subscriptions.delete(subscription.id) ++ } ++ ++ const subscriptionId = (principal: string, url: URL, name: string, args: unknown) => ++ digest.digestHex(Digest.sha256, encoder.encode(canonicalJson([principal, url.href, name, args]))).pipe( ++ Effect.map((hex) => `sub_${hex.slice(0, 32)}`) ++ ) ++ ++ // High entropy and unrelated to the eventId; a retry reuses it. ++ const messageId = (prefix: string) => ++ Effect.map(random.randomBytes(18), (bytes) => `${prefix}_${Base64Url.encode(bytes)}`) ++ ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They require an event's webhook-id to equal its eventId. Both become this id, derived per ++ // subscription so two subscriptions to one URL never share it; poll and push keep the eventId. ++ const deliveryId = (subscription: Subscription, eventId: string) => ++ Effect.map( ++ digest.digest(Digest.sha256, encoder.encode(`${subscription.id}\0${eventId}`)), ++ (hash) => `evt_${Base64Url.encode(hash).slice(0, 22)}` ++ ) ++ ++ const MAX_CURSORS_SINCE_GAP = 1_024 ++ const advance = (subscription: Subscription, cursor: string | null) => { ++ subscription.watermark = cursor ++ const since = subscription.cursorsSinceGap ++ if (since === undefined) return ++ since.add(cursor) ++ if (since.size > MAX_CURSORS_SINCE_GAP) since.delete(since.values().next().value!) ++ } ++ ++ const sign = (keys: ReadonlyArray, webhookId: string, timestamp: number, body: string) => ++ Effect.forEach(keys, (key) => mac.sign(key, encoder.encode(`${webhookId}.${timestamp}.${body}`))).pipe( ++ Effect.orDie, ++ Effect.map((tags) => tags.map((tag) => `v1,${Base64.encode(tag)}`).join(" ")) ++ ) ++ ++ // One POST. The timestamp and signature are fresh on every attempt. ++ const send = Effect.fnUntraced(function*( ++ subscription: Subscription, ++ body: string, ++ webhookId: string, ++ readBody: boolean ++ ) { ++ const admitted = yield* Effect.result(guard.check(subscription.url)) ++ if (Result.isFailure(admitted)) { ++ return { _tag: "Failed", category: "connection_refused", retryable: true } satisfies Outcome ++ } ++ const now = yield* Clock.currentTimeMillis ++ const timestamp = Math.floor(now / 1000) ++ const previous = subscription.previous ++ const keys = previous !== undefined && now < previous.until ++ ? [subscription.key, previous.key] ++ : [subscription.key] ++ const request = HttpClientRequest.post(subscription.url).pipe( ++ HttpClientRequest.setHeaders({ ++ "webhook-id": webhookId, ++ "webhook-timestamp": String(timestamp), ++ "webhook-signature": yield* sign(keys, webhookId, timestamp, body), ++ "x-mcp-subscription-id": subscription.id ++ }), ++ HttpClientRequest.bodyText(body, "application/json") ++ ) ++ const outcome = yield* client.execute(request).pipe( ++ Effect.flatMap((response): Effect.Effect => { ++ if (response.status < 200 || response.status >= 300) { ++ return Effect.succeed({ ++ _tag: "Failed", ++ category: statusCategory(response.status), ++ retryable: response.status !== 410 && response.status !== 413 ++ }) ++ } ++ return readBody ++ ? Effect.map(readCapped(response), (text) => ({ _tag: "Delivered", body: text })) ++ : Effect.succeed({ _tag: "Delivered", body: undefined }) ++ }), ++ Effect.timeoutOption(Duration.millis(REQUEST_TIMEOUT_MS)), ++ Effect.scoped, ++ // `fetch` would follow a redirect itself; webhook delivery never does. ++ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), ++ // Trace ids stay inside: the endpoint belongs to someone else. ++ Effect.provideService(HttpClient.TracerPropagationEnabled, false), ++ Effect.catch((error) => ++ Effect.succeed(Option.some({ _tag: "Failed", category: transportCategory(error), retryable: true })) ++ ) ++ ) ++ return Option.getOrElse(outcome, (): Outcome => ({ _tag: "Failed", category: "timeout", retryable: true })) ++ }) ++ ++ // Retries with backoff; gives up after a 410, a 413 or the last attempt. True once delivered. ++ const deliver = Effect.fnUntraced(function*(subscription: Subscription, body: string, webhookId: string) { ++ for (let attempt = 1;; attempt++) { ++ // A subscription that ended may have been replaced under its id; this one speaks no longer. ++ const current = subscriptions.get(subscription.id) ++ if (current !== undefined && current !== subscription) return false ++ const startedAt = yield* Clock.currentTimeMillis ++ const outcome = yield* send(subscription, body, webhookId, false) ++ if (outcome._tag === "Delivered") { ++ subscription.lastDeliveryAt = yield* Clock.currentTimeMillis ++ subscription.lastError = undefined ++ return true ++ } ++ subscription.lastError = outcome.category ++ if (!outcome.retryable || attempt >= MAX_ATTEMPTS) return false ++ // Counted from the attempt's start, so a slow endpoint does not stretch the window. ++ const wait = startedAt + FIRST_RETRY_MS * 2 ** (attempt - 1) - (yield* Clock.currentTimeMillis) ++ if (wait > 0) yield* Effect.sleep(Duration.millis(wait)) ++ } ++ }) ++ ++ const control = (subscription: Subscription, type: string, fields: Readonly>) => ++ Effect.flatMap( ++ messageId(`msg_${type}`), ++ (webhookId) => deliver(subscription, JSON.stringify({ type, ...fields }), webhookId) ++ ) ++ ++ // One delivery in flight per subscription, so the watermark only moves forward ++ // once everything before it is resolved. ++ const run = (subscription: Subscription, name: string, events: McpCore.EventSubscription) => ++ events.items.pipe( ++ Stream.runForEach((item): Effect.Effect => { ++ switch (item._tag) { ++ case "Event": ++ return Effect.flatMap(deliveryId(subscription, item.eventId), (webhookId) => { ++ const body = JSON.stringify({ ++ eventId: webhookId, ++ name, ++ timestamp: item.timestamp, ++ data: item.data, ++ cursor: item.cursor, ++ ...(item._meta === undefined ? {} : { _meta: item._meta }) ++ }) ++ return deliver(subscription, body, webhookId) ++ }).pipe(Effect.andThen(Effect.sync(() => advance(subscription, item.cursor)))) ++ case "Position": ++ return Effect.sync(() => advance(subscription, item.cursor)) ++ case "Gap": ++ return control(subscription, "gap", { cursor: item.cursor }).pipe( ++ Effect.map((delivered) => { ++ if (!delivered) subscription.cursorsSinceGap = new Set() ++ advance(subscription, item.cursor) ++ }) ++ ) ++ case "Error": ++ // A webhook has no envelope for an error that leaves the subscription open. ++ return Effect.void ++ } ++ }), ++ // Ended before it says so, so a refresh meanwhile starts afresh instead of reporting it live. ++ Effect.catch((failure) => ++ Effect.suspend(() => { ++ forget(subscription) ++ return control(subscription, "terminated", { error: wireError(failure) }) ++ }) ++ ) ++ ) ++ ++ const expiry = (subscription: Subscription) => ++ Effect.gen(function*() { ++ while (true) { ++ const left = subscription.expiresAt - (yield* Clock.currentTimeMillis) ++ if (left <= 0) return forget(subscription) ++ yield* Effect.raceFirst(Effect.sleep(Duration.millis(left)), Deferred.await(subscription.deadlineMoved)) ++ } ++ }) ++ ++ const handshake = Effect.fnUntraced(function*(subscription: Subscription) { ++ const challenge = Base64Url.encode(yield* random.randomBytes(32)) ++ const outcome = yield* send( ++ subscription, ++ JSON.stringify({ type: "verification", challenge }), ++ yield* messageId("msg_verification"), ++ true ++ ) ++ if (outcome._tag === "Failed") return yield* Effect.fail(outcome.category) ++ const echoed = outcome.body === undefined ? undefined : echoedChallenge(outcome.body) ++ if (echoed === undefined || !Mac.timingSafeEqual(encoder.encode(echoed), encoder.encode(challenge))) { ++ return yield* Effect.fail("challenge_failed") ++ } ++ }) ++ ++ // Cached per (principal, url) either way; concurrent subscribes share one handshake. ++ const verify = Effect.fnUntraced(function*(subscription: Subscription) { ++ const key = JSON.stringify([subscription.principal, subscription.url.href]) ++ const now = yield* Clock.currentTimeMillis ++ for (const [entry, until] of verified) if (until <= now) verified.delete(entry) ++ for (const [entry, failure] of failedVerifications) if (failure.until <= now) failedVerifications.delete(entry) ++ if (verified.has(key)) return ++ const failure = failedVerifications.get(key) ++ if (failure !== undefined) return yield* callbackError(failure.category) ++ const inFlight = verifying.get(key) ++ if (inFlight !== undefined) return yield* Deferred.await(inFlight) ++ const host = subscription.url.hostname ++ const recent = (verificationsByHost.get(host) ?? []).filter((at) => at > now - MINUTE_MS) ++ if (recent.length >= VERIFICATIONS_PER_HOST_PER_MINUTE) { ++ verificationsByHost.set(host, recent) ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many callback verifications for this host", ++ data: { limit: "verifications", max: VERIFICATIONS_PER_HOST_PER_MINUTE } ++ }) ++ } ++ for (const [entry, times] of verificationsByHost) { ++ if (times.every((at) => at <= now - MINUTE_MS)) verificationsByHost.delete(entry) ++ } ++ verificationsByHost.set(host, [...recent, now]) ++ const done = Deferred.makeUnsafe() ++ verifying.set(key, done) ++ return yield* handshake(subscription).pipe( ++ Effect.tap(() => ++ Effect.map(Clock.currentTimeMillis, (at) => { ++ verified.set(key, at + VERIFIED_FOR_MS) ++ }) ++ ), ++ Effect.tapError((category) => ++ Effect.map(Clock.currentTimeMillis, (at) => { ++ failedVerifications.set(key, { until: at + FAILED_FOR_MS, category }) ++ }) ++ ), ++ Effect.mapError(callbackError), ++ Effect.onExit((exit) => ++ Effect.sync(() => { ++ verifying.delete(key) ++ Deferred.doneUnsafe(done, exit) ++ }) ++ ) ++ ) ++ }) ++ ++ // A caller that joins while the first subscribe's stream is opening waits for it and gets ++ // where it started; one whose subscription went away meanwhile subscribes afresh. ++ const refresh = Effect.fnUntraced(function*( ++ request: SubscribeRequest, ++ subscription: Subscription, ++ secret: { readonly text: string; readonly key: Mac.Key }, ++ expiresAt: number, ++ now: number ++ ): Effect.fn.Return { ++ const opening = !Deferred.isDoneUnsafe(subscription.accepted) ++ const start = yield* Deferred.await(subscription.accepted) ++ if (subscriptions.get(subscription.id) !== subscription) return yield* subscribe(request) ++ if (subscription.secret !== secret.text) { ++ subscription.previous = { key: subscription.key, until: now + ROTATION_GRACE_MS } ++ subscription.secret = secret.text ++ subscription.key = secret.key ++ } ++ subscription.expiresAt = expiresAt ++ const moved = subscription.deadlineMoved ++ subscription.deadlineMoved = Deferred.makeUnsafe() ++ Deferred.doneUnsafe(moved, Effect.void) ++ if (opening) return { id: subscription.id, refreshBefore: iso(expiresAt), ...start } ++ // Kept until the client shows a cursor from past the gap, so a lost response hides nothing. ++ const since = subscription.cursorsSinceGap ++ if (since !== undefined && since.has(request.cursor)) subscription.cursorsSinceGap = undefined ++ const truncated = subscription.cursorsSinceGap !== undefined ++ return { ++ id: subscription.id, ++ refreshBefore: iso(expiresAt), ++ cursor: subscription.watermark, ++ truncated, ++ deliveryStatus: { ++ active: true, ++ lastDeliveryAt: subscription.lastDeliveryAt === undefined ? null : iso(subscription.lastDeliveryAt), ++ lastError: subscription.lastError ?? null ++ } ++ } satisfies SubscribeResult ++ }) ++ ++ const subscribe: Webhooks["subscribe"] = Effect.fnUntraced(function*(request) { ++ const principal = yield* options.principal ++ const mode = request.delivery.mode ++ if (mode !== undefined && mode !== "webhook") return yield* invalid("delivery.mode must be 'webhook'") ++ const url = yield* parseUrl(request.delivery.url, guard) ++ const secret = yield* parseSecret(request.delivery.secret) ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments) ++ const now = yield* Clock.currentTimeMillis ++ const expiresAt = now + grantTtl(request.ttlMs) ++ const live = subscriptions.get(id) ++ if (live !== undefined) return yield* refresh(request, live, secret, expiresAt, now) ++ // The slot is taken before anything asynchronous, so concurrent subscribes cannot pass the cap. ++ let held = pending.get(principal) ?? 0 ++ for (const subscription of subscriptions.values()) if (subscription.principal === principal) held++ ++ if (held >= MAX_SUBSCRIPTIONS_PER_PRINCIPAL) { ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many webhook subscriptions", ++ data: { limit: "subscriptions", max: MAX_SUBSCRIPTIONS_PER_PRINCIPAL } ++ }) ++ } ++ pending.set(principal, (pending.get(principal) ?? 0) + 1) ++ let reserved = true ++ const release = () => { ++ if (!reserved) return ++ reserved = false ++ const left = (pending.get(principal) ?? 1) - 1 ++ if (left === 0) pending.delete(principal) ++ else pending.set(principal, left) ++ } ++ return yield* create(request, { principal, url, secret, id, expiresAt, now, release }).pipe( ++ Effect.ensuring(Effect.sync(release)) ++ ) ++ }) ++ ++ const create = Effect.fnUntraced(function*( ++ request: SubscribeRequest, ++ { expiresAt, id, now, principal, release, secret, url }: { ++ readonly principal: string ++ readonly url: URL ++ readonly secret: { readonly text: string; readonly key: Mac.Key } ++ readonly id: string ++ readonly expiresAt: number ++ readonly now: number ++ readonly release: () => void ++ } ++ ) { ++ // One answer whether the host is private or does not resolve, so it reveals neither. ++ yield* Effect.mapError(guard.check(url), () => invalid("delivery.url is not allowed")) ++ const subscription: Subscription = { ++ id, ++ principal, ++ url, ++ secret: secret.text, ++ key: secret.key, ++ previous: undefined, ++ expiresAt, ++ watermark: request.cursor, ++ lastDeliveryAt: undefined, ++ lastError: undefined, ++ fiber: undefined, ++ deadlineMoved: Deferred.makeUnsafe(), ++ accepted: Deferred.makeUnsafe(), ++ cursorsSinceGap: undefined ++ } ++ const decoded = yield* request.decode ++ yield* verify(subscription) ++ // A concurrent subscribe for the same key may have finished while this one verified. ++ const raced = subscriptions.get(id) ++ if (raced !== undefined) { ++ release() ++ return yield* refresh(request, raced, secret, expiresAt, now) ++ } ++ release() ++ subscriptions.set(id, subscription) ++ const { accepted } = subscription ++ const lifetime = request.open(decoded, (events) => ++ Effect.suspend(() => { ++ subscription.watermark = events.cursor ++ return Deferred.succeed(accepted, { cursor: events.cursor, truncated: events.truncated }) ++ }).pipe(Effect.andThen(run(subscription, request.name, events))) ++ ).pipe( ++ Effect.tapError((failure) => Deferred.fail(accepted, failure)), ++ Effect.raceFirst(expiry(subscription)), ++ Effect.ignore, ++ Effect.ensuring(Effect.suspend(() => { ++ forget(subscription) ++ return Deferred.fail(accepted, new PublicMcpSchema.InternalError({ message: "The subscription ended" })) ++ })) ++ ) ++ // Forked from the request, so the event's stream keeps the request's services. ++ subscription.fiber = yield* Effect.forkIn(lifetime, scope) ++ const start = yield* Deferred.await(accepted) ++ return { id, refreshBefore: iso(expiresAt), cursor: start.cursor, truncated: start.truncated } ++ }) ++ ++ const unsubscribe: Webhooks["unsubscribe"] = Effect.fnUntraced(function*(request) { ++ const principal = yield* options.principal ++ const url = yield* parseUrl(request.delivery.url, guard) ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments) ++ const subscription = subscriptions.get(id) ++ if (subscription === undefined) { ++ return yield* new PublicMcpSchema.NotFound({ ++ message: "No webhook subscription matches", ++ data: { kind: "subscription" } ++ }) ++ } ++ subscriptions.delete(id) ++ if (subscription.fiber !== undefined) yield* Fiber.interrupt(subscription.fiber) ++ }) ++ ++ return { ++ subscribe, ++ unsubscribe, ++ size: Effect.sync(() => subscriptions.size) ++ } satisfies Webhooks ++}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e117b0248c953..df15375cc09f8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -384,7 +384,7 @@ overrides: packageExtensionsChecksum: sha256-18pwcgTDbqYFYAzCw8OfBYuC2btyq6aJSLhE/gjTJb4= -pnpmfileChecksum: sha256-h8NLkl2dhhbQKbAHnoo4rQ3tYV96igLQxJ7la6dsbSc= +pnpmfileChecksum: sha256-G0L7+qfid3Wo9BlLIlMyF/+fqBnAnqHKSe0HlWAtlg8= patchedDependencies: '@alchemy.run/test@2.0.0-beta.85': 29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e @@ -394,6 +394,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 @@ -401,6 +402,7 @@ patchedDependencies: alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 + effect@4.1.5: 24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28 electron-updater@6.8.9: 91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155 expo-audio@58.0.11: 92414572bf24ffd0c45de44c45f11f6c48bc0af13b8b9a56f77a67bc0e915c1e expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 @@ -458,7 +460,7 @@ importers: version: 0.15.4 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 @@ -482,7 +484,7 @@ importers: version: 0.10.2(patch_hash=cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4) effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) electron: specifier: 44.10.1 version: 44.10.1(supports-color@8.1.1) @@ -513,7 +515,7 @@ importers: devDependencies: '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -574,7 +576,7 @@ importers: version: 0.4.4(patch_hash=127b95167fa0738004d2e9b8b5b6beaee34f1b0e2b3d2684ee606d19b5041e4a)(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)(supports-color@8.1.1)(typescript@6.0.3) '@effect/atom-react': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5)(react@19.3.0)(scheduler@0.28.0) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react@19.3.0)(scheduler@0.28.0) '@expo-google-fonts/dm-sans': specifier: ^0.4.2 version: 0.4.2 @@ -598,7 +600,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 @@ -652,7 +654,7 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) expo: specifier: 58.0.23 version: 58.0.23(d226faf1ca90e630d8c56a2108dee32d) @@ -839,10 +841,10 @@ importers: version: 7.29.7(supports-color@8.1.1) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@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) @@ -884,10 +886,10 @@ importers: version: 1.4.2(patch_hash=d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a)(zod@4.6.7) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/platform-node-shared': specifier: 4.1.5 - version: 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) + version: 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) '@ff-labs/fff-node': specifier: 0.11.0 version: 0.11.0(patch_hash=93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252) @@ -968,7 +970,7 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -1008,10 +1010,10 @@ importers: devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@handy-computer/models': specifier: 0.2.3 version: 0.2.3 @@ -1119,13 +1121,13 @@ importers: version: 3.2.2(react@19.3.0) '@effect/atom-react': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5)(react@19.3.0)(scheduler@0.28.0) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react@19.3.0)(scheduler@0.28.0) '@fontsource-variable/inter': specifier: ^5.3.0 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 @@ -1135,6 +1137,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 @@ -1186,6 +1191,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)) @@ -1218,7 +1226,7 @@ importers: version: 3.4.17 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) entities: specifier: 8.1.0 version: 8.1.0 @@ -1252,42 +1260,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) - mermaid: - specifier: ^12.0.0 - version: 12.3.0 - 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 @@ -1300,25 +1287,19 @@ 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)) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@tailwindcss/vite': specifier: 4.3.3 version: 4.3.3(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)) @@ -1337,9 +1318,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 @@ -1370,9 +1348,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 @@ -1396,7 +1371,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../packages/contracts @@ -1408,11 +1383,11 @@ importers: version: link:../packages/shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -1424,28 +1399,28 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1) + version: 2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e) '@alchemy.run/drizzle': specifier: 'catalog:' - version: 2.0.0-beta.85(aaf71186a61e3f73fb98ecfca2947754) + version: 2.0.0-beta.85(5cde798e96ab6d44cdc28240628f10b1) '@alchemy.run/planetscale': specifier: 'catalog:' - version: 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) + version: 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) '@clerk/backend': specifier: 3.27.0 version: 3.27.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@distilled.cloud/cloudflare': specifier: 'catalog:' - version: 1.0.0-rc.18(effect@4.1.5) + version: 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/sql-pg': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/sql-sqlite-do': specifier: 'catalog:' - version: 4.1.5(effect@4.1.5) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@noble/curves': specifier: 'catalog:' version: 1.9.1 @@ -1463,26 +1438,26 @@ importers: version: link:../../packages/shared alchemy: specifier: 2.0.0-beta.85 - version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) drizzle-orm: specifier: 1.0.0-rc.5 - version: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + version: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@alchemy.run/test': specifier: 'catalog:' - version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(adf93af6036c4c597e35df2cca6d42d0) + version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(a619c060a1b8ed45ad4914f1f8e44c19) '@cloudflare/workers-types': specifier: ^4.20260601.1 version: 4.20260604.1 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@electric-sql/pglite': specifier: 0.3.15 version: 0.3.15 @@ -1491,7 +1466,7 @@ importers: version: 24.12.4 drizzle-kit: specifier: 1.0.0-rc.5 - version: 1.0.0-rc.5(drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7)) + version: 1.0.0-rc.5(73cc0b8bb5cef1afe1d24404a4fb8809) vite: specifier: npm:@voidzero-dev/vite-plus-core@1.4.0 version: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' @@ -1503,16 +1478,16 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1) + version: 2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e) alchemy: specifier: 2.0.0-beta.85 - version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) jose: specifier: 'catalog:' version: 6.2.2 @@ -1522,10 +1497,10 @@ importers: version: 4.20260604.1 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -1540,14 +1515,14 @@ importers: version: 1.89.0 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) 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) @@ -1604,38 +1579,38 @@ importers: version: link:../source-control-definitions effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) gt-i18n: specifier: 1.0.40 version: 1.0.40 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 - 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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/mdast': specifier: ^4.0.4 version: 4.0.4 '@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) @@ -1644,11 +1619,11 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) 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) @@ -1657,17 +1632,17 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)(encoding@0.1.13) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(encoding@0.1.13) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -1679,17 +1654,17 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)(encoding@0.1.13) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(encoding@0.1.13) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -1707,14 +1682,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -1738,14 +1713,14 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -1775,14 +1750,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1806,14 +1781,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -1837,7 +1812,7 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) jsonc-parser: specifier: 3.3.1 version: 3.3.1 @@ -1847,10 +1822,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1877,14 +1852,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1914,14 +1889,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1951,14 +1926,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1988,14 +1963,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2013,7 +1988,7 @@ importers: version: 1.15.13 '@opencode/client': specifier: 2.0.28 - version: 2.0.28(effect@4.1.5) + version: 2.0.28(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@opencode/protocol': specifier: 2.0.28 version: 2.0.28 @@ -2031,14 +2006,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2062,14 +2037,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2084,7 +2059,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2096,11 +2071,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -2115,14 +2090,14 @@ importers: version: link:../contracts effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -2155,14 +2130,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -2183,7 +2158,7 @@ importers: version: link:../contracts effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -2193,6 +2168,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) @@ -2241,16 +2219,22 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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 @@ -2274,14 +2258,14 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2308,14 +2292,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2336,11 +2320,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -2352,7 +2336,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2367,11 +2351,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -2425,14 +2409,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2459,11 +2443,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2478,7 +2462,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2493,17 +2477,17 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) yaml: specifier: ^2.9.0 version: 2.9.0 devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2527,14 +2511,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2558,11 +2542,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2577,7 +2561,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2589,7 +2573,7 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@types/node': specifier: 24.12.4 @@ -2605,14 +2589,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -2630,11 +2614,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/node': specifier: 24.12.4 version: 24.12.4 @@ -2652,7 +2636,7 @@ importers: version: 0.15.5(e2e@0.23.0) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@electron/asar': specifier: ^4.3.0 version: 4.3.0 @@ -2676,7 +2660,7 @@ importers: version: 0.23.0 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) playwright-core: specifier: 1.64.1 version: 1.64.1 @@ -2692,7 +2676,7 @@ importers: devDependencies: '@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) + 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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/plist': specifier: 'catalog:' version: 3.0.5 @@ -2886,9 +2870,6 @@ packages: vitest: optional: true - '@antfu/install-pkg@2.1.0': - resolution: {integrity: sha512-sdg9NxU3zR4Mnawfbc/x6GB5Wf17WYud5qOuEuxXjaKpYpMkISSJEjItGebXJ2bQ4DIcly4NYH23mtkGJjvKUw==} - '@anthropic-ai/claude-agent-sdk@0.3.321': resolution: {integrity: sha512-Smer/h/jQLTtT+l4sxaAUwZq7wif/9RzzuqltS5Gy+kAFo/iP89H7JHa8avhVT0xGkPBvBD/1Bbdg3pcArhQcw==} engines: {node: '>=18.14.0'} @@ -3463,9 +3444,6 @@ packages: '@blazediff/core@1.10.0': resolution: {integrity: sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==} - '@braintree/sanitize-url@7.1.2': - resolution: {integrity: sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==} - '@bramus/specificity@2.4.2': resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==} hasBin: true @@ -3526,21 +3504,6 @@ packages: resolution: {integrity: sha512-CuNiSqg7+e1cO/GjffyMOm5Tt2jUF9CWHHnvQ/UkqvtkGfHdgwEC0wpmq7fkN3gxwpRnrAN0WzO3vREKmNolMQ==} engines: {node: '>=18'} - '@chevrotain/cst-dts-gen@13.2.0': - resolution: {integrity: sha512-bA9dvWlhAUcHkNwU+8w9yiUxJPlj/Lm3VqS7MD+NbIR/7LmpNLuK/AWNFdCo/T3SK5ND0/UHf3IJvl/Jn/i6yg==} - - '@chevrotain/gast@13.2.0': - resolution: {integrity: sha512-bCARdAsG+eEbOveSXcOAC7pVxA04I1ionzeMOwIYf5NX7SaS7zgn4Dgug2BSqoL+iyKeMNSorQjsFSHJHsCNwg==} - - '@chevrotain/regexp-to-ast@13.2.0': - resolution: {integrity: sha512-kxpUkLtiaK09ph+dib+Yvm+3sWSnuwlo25gqfKRgTPNmF6H7uW4gVkMjaRdtnN783S9sM6vUNWh9CsxYX4QwKw==} - - '@chevrotain/types@13.2.0': - resolution: {integrity: sha512-7qrYHRlKfWf2AvBfJi5eVOrKAkbxvMFsy/iIHTGIiApNcEecCaVIdR+mIQhyCBsTDJxBz4JWXHMo6krbhR9hVg==} - - '@chevrotain/utils@13.2.0': - resolution: {integrity: sha512-SzKYY68rseOrb9KILVzPsl6SjkQtdWw01SRGB5aCVI5kFcHltQsOYV3JB0Ffst72DgkvHCyDQ0NLwxtmCCf97Q==} - '@clack/core@1.0.0-alpha.6': resolution: {integrity: sha512-eG5P45+oShFG17u9I1DJzLkXYB1hpUgTLi32EfsMjSHLEqJUR8BOBCVFkdbUX2g08eh/HCi6UxNGpPhaac1LAA==} @@ -4740,12 +4703,6 @@ packages: '@iarna/toml@2.2.5': resolution: {integrity: sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==} - '@iconify/types@2.0.0': - resolution: {integrity: sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==} - - '@iconify/utils@3.1.7': - resolution: {integrity: sha512-JZHlwdID+dy+lTgbYC8NEC4zeugqeYsc6jewvzb4c58kHauJn+X7rNwQjxz5p2qSjqaEeQoLkCIQ9v/H4PK0/w==} - '@img/colour@1.1.0': resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} @@ -5138,10 +5095,6 @@ packages: '@material/material-color-utilities@0.3.0': resolution: {integrity: sha512-ztmtTd6xwnuh2/xu+Vb01btgV8SQWYCaK56CkRK8gEkWe5TuDyBcYJ0wgkMRn+2VcE9KUmhvkz+N9GHrqw/C0g==} - '@mermaid-js/parser@2.0.1': - resolution: {integrity: sha512-j37dj/h6p6pots1L7pLPPNuABEEu9WP4OYg9pW1g+nYG331j0+3canE9OagtYdytYvdSAMG+2fKU5cxep6LgjA==} - engines: {node: '>=22.12.0'} - '@modelcontextprotocol/core@2.4.0': resolution: {integrity: sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==} engines: {node: '>=20'} @@ -6552,6 +6505,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==} @@ -7439,99 +7404,6 @@ packages: '@types/culori@4.0.1': resolution: {integrity: sha512-43M51r/22CjhbOXyGT361GZ9vncSVQ39u62x5eJdBQFviI8zWp2X5jzqg7k4M6PVgDQAClpy2bUe2dtwEgEDVQ==} - '@types/d3-array@3.2.2': - resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==} - - '@types/d3-axis@3.0.6': - resolution: {integrity: sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==} - - '@types/d3-brush@3.0.6': - resolution: {integrity: sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==} - - '@types/d3-chord@3.0.6': - resolution: {integrity: sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==} - - '@types/d3-color@3.1.3': - resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==} - - '@types/d3-contour@3.0.6': - resolution: {integrity: sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==} - - '@types/d3-delaunay@6.0.4': - resolution: {integrity: sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==} - - '@types/d3-dispatch@3.0.7': - resolution: {integrity: sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==} - - '@types/d3-drag@3.0.7': - resolution: {integrity: sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==} - - '@types/d3-dsv@3.0.7': - resolution: {integrity: sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==} - - '@types/d3-ease@3.0.2': - resolution: {integrity: sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==} - - '@types/d3-fetch@3.0.7': - resolution: {integrity: sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==} - - '@types/d3-force@3.0.10': - resolution: {integrity: sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==} - - '@types/d3-format@3.0.4': - resolution: {integrity: sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==} - - '@types/d3-geo@3.1.1': - resolution: {integrity: sha512-65Emv9fQiQQqphLlRkuQ5ypPsOmWPhtBGCMv61JDPEPMvsx+gzhGf74yw1a78xFKPj6zw4AgQICJoQv0vK9M2w==} - - '@types/d3-hierarchy@3.1.7': - resolution: {integrity: sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==} - - '@types/d3-interpolate@3.0.4': - resolution: {integrity: sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==} - - '@types/d3-path@3.1.1': - resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==} - - '@types/d3-polygon@3.0.2': - resolution: {integrity: sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==} - - '@types/d3-quadtree@3.0.6': - resolution: {integrity: sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==} - - '@types/d3-random@3.0.4': - resolution: {integrity: sha512-UHYId5WTCx4L4YNel7NU00XUXXgvgpgZOvp10PuvsQENjMDXhh2RyFc0KBjO7B45ne4Ha1yVH7ii0vnzKkuzWA==} - - '@types/d3-scale-chromatic@3.1.0': - resolution: {integrity: sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==} - - '@types/d3-scale@4.0.9': - resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==} - - '@types/d3-selection@3.0.12': - resolution: {integrity: sha512-Qe/KWYhEiIIxGs7HrAAjMfShxKldx19SJtr5zu53f3afPsdZNz7HHtdTLXo/kqeiWNXVycI24kSnfzBYkTzpgw==} - - '@types/d3-shape@3.2.0': - resolution: {integrity: sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==} - - '@types/d3-time-format@4.0.3': - resolution: {integrity: sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==} - - '@types/d3-time@3.0.4': - resolution: {integrity: sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==} - - '@types/d3-timer@3.0.2': - resolution: {integrity: sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==} - - '@types/d3-transition@3.0.9': - resolution: {integrity: sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==} - - '@types/d3-zoom@3.0.9': - resolution: {integrity: sha512-0sE1406XBYJGiqD3AusTl9ZqC//2mIXix51tbom25gDCA8ri4xnSZg28CaSE8Srl6FClqABUKfsn0qghgdepMA==} - - '@types/d3@7.4.3': - resolution: {integrity: sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==} - '@types/debug@4.1.13': resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==} @@ -7556,9 +7428,6 @@ packages: '@types/fs-extra@9.0.13': resolution: {integrity: sha512-nEnwB++1u5lVDM2UI4c1+5R+FYaKfaAzS4OococimjVm3nQw3TuzH5UNsocrcTBbhnerblyHj4A49qXbIiZdpA==} - '@types/geojson@7946.0.16': - resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==} - '@types/hast@3.0.5': resolution: {integrity: sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==} @@ -7678,9 +7547,6 @@ packages: '@ungap/structured-clone@1.3.1': resolution: {integrity: sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==} - '@upsetjs/venn.js@2.0.0': - resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==} - '@vercel/config@0.3.0': resolution: {integrity: sha512-Tf5k5y2F478oTiQcU5R8Ntix1UejE6NdduZnI7aa1XXxjCtifX1XdRS/D2uTjiQAwIL3pLa1LSAN80ABbba+TQ==} hasBin: true @@ -8552,10 +8418,6 @@ packages: character-reference-invalid@2.0.1: resolution: {integrity: sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==} - chevrotain@13.2.0: - resolution: {integrity: sha512-GTouk5YzgBxlTPCaDn5q0q2EJKkrYmnPF+HmF8v0Qo4r3iyPG7HJivkN1wthCXZcm3sIcZFpGTRovLPNdJNRCA==} - engines: {node: '>=22.0.0'} - chokidar@4.0.3: resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} engines: {node: '>= 14.16.0'} @@ -8779,12 +8641,6 @@ packages: resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==} engines: {node: '>= 0.10'} - cose-base@1.0.3: - resolution: {integrity: sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==} - - cose-base@2.2.0: - resolution: {integrity: sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==} - cross-dirname@0.1.0: resolution: {integrity: sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==} @@ -8841,162 +8697,6 @@ packages: resolution: {integrity: sha512-1+BhOB8ahCn4O0cep0Sh2l9KCOfOdY+BXJnKMHFFzDEouSr/el18QwXEMRlOj9UY5nCeA8UN3a/82rUWRBeyBw==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - cytoscape-cose-bilkent@4.1.0: - resolution: {integrity: sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==} - peerDependencies: - cytoscape: ^3.2.0 - - cytoscape-fcose@2.2.0: - resolution: {integrity: sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==} - peerDependencies: - cytoscape: ^3.2.0 - - cytoscape@3.35.0: - resolution: {integrity: sha512-sMvBIXiGMnhkCaWz2R06FwF/27MNlS+Tqvi17foO9UhnUg3XGZccKjxsvEqQFAQYMSSZmN5SxYzUYlQ0DOJJ3g==} - engines: {node: '>=0.10'} - - d3-array@2.12.1: - resolution: {integrity: sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==} - - d3-array@3.2.5: - resolution: {integrity: sha512-Th8qGXoBalmWsstpkuhmBuTsBQIFqYOJtjlBvNVvBfJ8E3uYusBUwUR8HU20U0qKKQkgCvKyR1YjiozWadk5QA==} - engines: {node: '>=12'} - - d3-axis@3.0.1: - resolution: {integrity: sha512-E5QCXfaf/uJZEHHiqoWRq+bQEm2PzoVFv2rDC7CZ3wwI0MjfMW3w83J3ubobG4IJj3lShAI5eiPJhOu/8wHofA==} - engines: {node: '>=12'} - - d3-brush@3.0.1: - resolution: {integrity: sha512-L5Glqa/Gb7LU3ndIOMtA5mDzlJ0aXKp5ELP2X09ctWF23jO7+faIUVDbmaIi+D6k3EemXFWn1F3lkfguExoVhA==} - engines: {node: '>=12'} - - d3-chord@3.0.2: - resolution: {integrity: sha512-cGmADo5M2PTi3ewJZ2lcE32eURd4JmHtQ5JwRIUcas5L1SXqufG9yPyjWp8fW0gRi7aZi9bgbZPFZO1eyZ+1CQ==} - engines: {node: '>=12'} - - d3-color@3.1.1: - resolution: {integrity: sha512-lfab8x0Bj0UO7SNsY8dZSbNIA6ipbkE3X0NG9nqjCu6CfCHZseuDnOSJY7hidKrjpP++i1M2qT+FlAdPKYRilA==} - engines: {node: '>=12'} - - d3-contour@4.0.3: - resolution: {integrity: sha512-5DYURc8KwXPOhSUBblU0P9rVcArsSPxPOxsfO0Eud0s28oU0sB2e80aRHRL9AZW3usT8ikFKyIHpHHLNWLdRVA==} - engines: {node: '>=12'} - - d3-delaunay@6.0.6: - resolution: {integrity: sha512-DMQIEvSJhZCB6pwedcXaAlQ+MeKU5LlM2XakKtc73b/VM+RBiI1SRXycOEOKg2jsKj4zZ9F0KGYG6nCGwwWu/g==} - engines: {node: '>=12'} - - d3-dispatch@3.0.2: - resolution: {integrity: sha512-sAzH4Y4nsLo8eSqw5jKiZt+LU2wZmL/qS+OkxQGjhwazB/D7TY34R/QK1eshfGr7cZEKymKZ/Haem7m+lu98Sg==} - engines: {node: '>=12'} - - d3-drag@3.0.1: - resolution: {integrity: sha512-OWeoayCq8J69hUIjvL+Mb6Q6Oaj/fyHV5XaXByEUAG+JUjIfTGDnk3qGpcXrD3VmQ3BSV96fcbM6fqq7C0tbPA==} - engines: {node: '>=12'} - - d3-dsv@3.0.2: - resolution: {integrity: sha512-FUnXhX7I4/AXyRCZzwfZTDGSq8PGZ4oR0tiCBqNGOZMsDrQ+6sIWNQnBzcCGhzJKZ6uCvCezTwflUqI209RRiQ==} - engines: {node: '>=12'} - hasBin: true - - d3-ease@3.0.2: - resolution: {integrity: sha512-B5znKqRmKROAN4oHWQ50W/qisVjA9GXh2WMsVKdFVp4DxWmcrOsweqgUOUVsv5th96kwaZlokU6SlV4J3gak1w==} - engines: {node: '>=12'} - - d3-fetch@3.0.2: - resolution: {integrity: sha512-1wGF62bgjMRbF6mqbD+6rRWBL2hwWVYQjFO2UP3Wm1nIAvJZKaQxXM5caVY7athoCa8wIq9lCf7g44lPWFk50g==} - engines: {node: '>=12'} - - d3-force@3.0.1: - resolution: {integrity: sha512-kAaaHLFebBYwgi5cYBXAI8vKrQFMCD2MEswj2QuPKKbdU1wYLc8WXtS7O8F/b6POCIe3gJjY6hkDstHi1yMETQ==} - engines: {node: '>=12'} - - d3-format@3.1.3: - resolution: {integrity: sha512-+F+/49swqmGuQJmSKnVMIDH/QkEFV5li9QRj0xm/KhyAUBv099O5PrvpQFxBp24PYph17Mnvt9mjKQV0ii0nMA==} - engines: {node: '>=12'} - - d3-geo@3.1.2: - resolution: {integrity: sha512-5R8ZgDQorIxmauv7R6gpE/ndz+Z0qAZssigq0aXFdvPHdY41RqtW02jrRUQAL724NdPABYXo1+gQEGBBr7uKNg==} - engines: {node: '>=12'} - - d3-hierarchy@3.1.3: - resolution: {integrity: sha512-GRajN5ZcnEwYFWqqdzhG1qJ3+fDg6WWzk47TJg7ePY7yvYAgRfD2r1mUx+wviBOWuCwamCUzjwMSdato43jbGA==} - engines: {node: '>=12'} - - d3-interpolate@3.0.2: - resolution: {integrity: sha512-IRzGU62DtxhvsnSTWMQIdnoZ6gA+BCWwBon1EJI6SjoN595799b6z/QRBzXfFhE8iupUPp3042yBNo0STPqnzQ==} - engines: {node: '>=12'} - - d3-path@1.0.9: - resolution: {integrity: sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==} - - d3-path@3.1.1: - resolution: {integrity: sha512-jsbgV8zIT38ReB9O7X7gcLndTQRONSqNNd+oGIaTBdUug4r5jFmp0N6RY9R5GWbdUDucn0qoTGyfjapT4tDhcg==} - engines: {node: '>=12'} - - d3-polygon@3.0.2: - resolution: {integrity: sha512-WAUvPudGU1Dn4mDPfb6+JnnbeVEV53hG/BoT+bxts6AkZsOpTEiV1jHYX+2vtwCICNFG9Wxv8QS+eW1zE/Dwfg==} - engines: {node: '>=12'} - - d3-quadtree@3.0.2: - resolution: {integrity: sha512-9Lu9mqJKRbIk0d6mKDjpvPURaPdwHVK5CYbcdd0/4vBgz4ldz/7TIOse3kNERsByGNfld58KEco507AztJWyTQ==} - engines: {node: '>=12'} - - d3-random@3.0.2: - resolution: {integrity: sha512-PxJi9LNV+7mulaYO77nd+oGurXGL1fhedXjHnB3pWLUcqDnQtF4VASoqnQGHgoXLByVdv5QJ/2kfwkGn5HTS8g==} - engines: {node: '>=12'} - - d3-sankey@0.12.3: - resolution: {integrity: sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==} - - d3-scale-chromatic@3.1.1: - resolution: {integrity: sha512-lA5gfN2yMvmChubmptnDiBfeGpHD7Yb1EbvCz0TZE0WHXhyR6W2allPuhKtzV5ILQRqeOdefF0qYtERReLUBDg==} - engines: {node: '>=12'} - - d3-scale@4.0.3: - resolution: {integrity: sha512-66cWobCNzcMvlfoaDHCxuIv9TBUWG1BLOWdv9kHHFuCr1JdqAWPvTmsaEYDD5NRMyWZ5+7u0GqiCDfMXMqh3hg==} - engines: {node: '>=12'} - - d3-selection@3.0.1: - resolution: {integrity: sha512-ODSf35vqCrlCfp7hrm0eZjvOosSXSYLjqvIlhMBV9q9VOx7EBJG6pc+uXBswEZNJgCGJ+qnKYcWutbZDIxe/Xg==} - engines: {node: '>=12'} - - d3-shape@1.3.7: - resolution: {integrity: sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==} - - d3-shape@3.2.1: - resolution: {integrity: sha512-dm2o+lbKdzg9tY7GEag/dB9hcbodLfwkE/DkvqbELJXaMz0yKzWWhZqhbI7CKubukA7HnRyz0avdtvi7EPxPvw==} - engines: {node: '>=12'} - - d3-time-format@4.1.1: - resolution: {integrity: sha512-22XaqjyCjpqgda20erhsOjGmC3vvYwTNYniKAd45W5UWLDF43moeOuV9qYpRqobIlsnK0UhnKZjUUJm3VgORUA==} - engines: {node: '>=12'} - - d3-time@3.1.1: - resolution: {integrity: sha512-Ze7rjrhMzdeulh0/hjcfFj7XLAHOfowtEMfsoG6DU866HPynQNW7Wfen6hzXcqKTv8XzxvF6Hzr5XD6bMHr2ug==} - engines: {node: '>=12'} - - d3-timer@3.0.2: - resolution: {integrity: sha512-1Il1aliroVSErrv5aulRBxAY+7+DnaoLIWGd1C6SsBTWDeobWiP/V69vwb8vT6abR1kKwaNe1196pmaQ1fK90A==} - engines: {node: '>=12'} - - d3-transition@3.0.2: - resolution: {integrity: sha512-RcjCsdFgyFoDB+QXLC5m60ZkTN0k9zH+ovoLlTdJnDS1AbfbcuowiM4pCKSTOclNibS4f4J4cbv2m7O7y8NTOQ==} - engines: {node: '>=12'} - peerDependencies: - d3-selection: 2 - 3 - - d3-zoom@3.0.1: - resolution: {integrity: sha512-kfjD3BDQu/FOatpZ6JdMSyIoDwTxIpI29ySTI2J5ZlDaH1WbuJGQJ2Q9oJkWTEZEW98j6idezoomSD3Cn2zwiw==} - engines: {node: '>=12'} - - d3@7.9.2: - resolution: {integrity: sha512-ZKb/mONPVKzaO5UlcWcwN8bS4ezvQaYu+bsou+XgNABdGC800kwH651ADTbbTxMPHW13UlvbQafdmJQDk1w7Mg==} - engines: {node: '>=12'} - - dagre-d3-es@7.0.14: - resolution: {integrity: sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg==} - data-urls@7.0.0: resolution: {integrity: sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==} engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} @@ -9007,9 +8707,6 @@ packages: dateformat@4.6.3: resolution: {integrity: sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==} - dayjs@1.11.23: - resolution: {integrity: sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==} - dbus-next@0.10.2: resolution: {integrity: sha512-kLNQoadPstLgKKGIXKrnRsMgtAK/o+ix3ZmcfTfvBHzghiO9yHXpoKImGnB50EXwnfSFaSAullW/7UrSkAISSQ==} @@ -9086,9 +8783,6 @@ packages: defu@6.1.7: resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} - delaunator@5.1.0: - resolution: {integrity: sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==} - delayed-stream@1.0.0: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} @@ -9425,9 +9119,6 @@ packages: engines: {node: '>= 22.12.0'} hasBin: true - elkjs@0.12.1: - resolution: {integrity: sha512-IhMYKHE4S2vtx0QrhBP3lYOIKDeIiJXBrdq9MGYkuB8ZHqhrBnHNfSUndjXFewrX1CPK8chwq+2NA0K0hliYuw==} - emmet@2.4.11: resolution: {integrity: sha512-23QPJB3moh/U9sT4rQzGgeyyGIrcM+GH5uVYg2C6wZIxAIJq7Ng3QLT79tl8FUwDXhyq9SusfknOrofAKqvgyQ==} @@ -9504,9 +9195,6 @@ packages: resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} engines: {node: '>= 0.4'} - es-toolkit@1.53.2: - resolution: {integrity: sha512-iUqZ+NlwH4jUgRmXZUxFBsV/9762TQEa1O4IXLFBmDEjVHScBytKuseX23I0+v9ShZ5MYxEx6WKNzm6IPnex8g==} - es6-error@4.1.1: resolution: {integrity: sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==} @@ -10258,9 +9946,6 @@ packages: h3@1.15.11: resolution: {integrity: sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg==} - hachure-fill@0.5.2: - resolution: {integrity: sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==} - has-flag@3.0.0: resolution: {integrity: sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==} engines: {node: '>=4'} @@ -10402,9 +10087,6 @@ packages: immediate@3.0.6: resolution: {integrity: sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==} - import-meta-resolve@4.2.0: - resolution: {integrity: sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==} - inflight@1.0.6: resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful. @@ -10415,13 +10097,6 @@ packages: inline-style-parser@0.2.7: resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==} - internmap@1.0.1: - resolution: {integrity: sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==} - - internmap@2.0.3: - resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==} - engines: {node: '>=12'} - invariant@2.2.4: resolution: {integrity: sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==} @@ -10697,9 +10372,6 @@ packages: keyv@4.5.4: resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} - khroma@2.1.0: - resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==} - kleur@3.0.3: resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} engines: {node: '>=6'} @@ -10720,12 +10392,6 @@ packages: resolution: {integrity: sha512-ONPnazC96VKDntab9j9JKwIWhZ4ZUceB4A9Epu4Ssg0hYFmtHZSeQ+n15nIwTFmcBUKtExOer8WTJ4GF9MO64A==} hasBin: true - layout-base@1.0.2: - resolution: {integrity: sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==} - - layout-base@2.0.1: - resolution: {integrity: sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==} - lazy-val@1.0.5: resolution: {integrity: sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==} @@ -10822,9 +10488,6 @@ packages: resolution: {integrity: sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==} engines: {node: '>=6'} - lodash-es@4.18.1: - resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==} - lodash.debounce@4.0.8: resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==} @@ -10907,11 +10570,6 @@ packages: markdown-table@3.0.4: resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==} - marked@16.4.2: - resolution: {integrity: sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==} - engines: {node: '>= 20'} - hasBin: true - matcher@3.0.0: resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==} engines: {node: '>=10'} @@ -11007,10 +10665,6 @@ packages: resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} engines: {node: '>= 8'} - mermaid@12.3.0: - resolution: {integrity: sha512-4113TdXeLAsMruJ79OpFL5O8+LTFXhQqZ260rF3tgUmiNAtRm4Uume04I+65PRN6yZ69J4f8rVYWW8zRk65UYw==} - engines: {node: '>=22.12.0'} - meshoptimizer@0.22.0: resolution: {integrity: sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==} @@ -11634,9 +11288,6 @@ packages: path-browserify@1.0.1: resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==} - path-data-parser@0.1.0: - resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==} - path-exists@3.0.0: resolution: {integrity: sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==} engines: {node: '>=4'} @@ -11791,12 +11442,6 @@ packages: resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==} engines: {node: '>=14.19.0'} - points-on-curve@0.2.0: - resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==} - - points-on-path@0.2.1: - resolution: {integrity: sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==} - postcss@8.5.30: resolution: {integrity: sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==} engines: {node: ^10 || ^12 || >=14} @@ -12020,12 +11665,6 @@ packages: react-is@19.3.1: resolution: {integrity: sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==} - 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 @@ -12311,9 +11950,6 @@ packages: resolution: {integrity: sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==} engines: {node: '>=8.0'} - robust-predicates@3.0.3: - resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==} - rolldown@1.0.0-rc.17: resolution: {integrity: sha512-ZrT53oAKrtA4+YtBWPQbtPOxIbVDbxT0orcYERKd63VJTF13zPcgXTvD4843L8pcsI7M6MErt8QtON6lrB9tyA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -12327,9 +11963,6 @@ packages: rope-sequence@1.3.4: resolution: {integrity: sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==} - roughjs@4.6.6: - resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==} - router@2.2.0: resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==} engines: {node: '>= 18'} @@ -12341,9 +11974,6 @@ packages: run-parallel@1.2.0: resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} - rw@1.3.3: - resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==} - safe-buffer@5.1.2: resolution: {integrity: sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==} @@ -12680,9 +12310,6 @@ packages: style-to-object@1.0.14: resolution: {integrity: sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==} - stylis@4.4.0: - resolution: {integrity: sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==} - sumchecker@3.0.1: resolution: {integrity: sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==} engines: {node: '>= 8.0'} @@ -12862,10 +12489,6 @@ packages: ts-algebra@2.0.0: resolution: {integrity: sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==} - ts-dedent@2.3.0: - resolution: {integrity: sha512-JfJeIHke7y2egdGGgRAvpCwYFUsHlM2gPcrVOxFkznt/4uzQ7HFmvE63iFHVLBJNDuyDOQgijDK/tXH/f6Msjg==} - engines: {node: '>=6.10'} - ts-morph@28.0.0: resolution: {integrity: sha512-Wp3tnZ2bzwxyTZMtgWVzXDfm7lB1Drz+y9DmmYH/L702PQhPyVrp3pkou3yIz4qjS14GY9kcpmLiOOMvl8oG1g==} @@ -13541,10 +13164,12 @@ packages: yuku-core@0.19.0: resolution: {integrity: sha512-kYK9e1XdfirNhkipzW0wmMcSWcVF/CWnuugodfVYRCUwvoBefweL9HzB96OiKEhsx78V5WbUxbJqlizMX869Qg==} engines: {node: '>=14.18.0'} + deprecated: 'Yuku is now one package with one core. Use "yuku" instead: https://yuku.fyi/javascript/. Existing installs keep working but get no more fixes.' yuku-parser@0.19.0: resolution: {integrity: sha512-XrBh9ZiQK5mJVRxZBAvD6LwRyAYrK3MFtH3+onyuxFL5hFD44EC3QOmIC1FjTj6H2MMwq46/NAI+NZxLZPZgxg==} engines: {node: '>=14.18.0'} + deprecated: 'Yuku is now one package with one core. Use "yuku" instead: https://yuku.fyi/javascript/. Existing installs keep working but get no more fixes.' zod-to-json-schema@3.25.2: resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==} @@ -13590,27 +13215,27 @@ snapshots: dependencies: json-schema: 0.4.0 - '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)': + '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)': + '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(rolldown@1.2.13)(typescript@6.0.3)': + '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(rolldown@1.2.13)(typescript@6.0.3)': dependencies: '@alchemy.run/node-utils': 2.0.0-beta.85 '@cloudflare/unenv-preset': 2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261026.1) - '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@puppeteer/browsers': 3.2.6(yauzl@3.4.0) capnp-es: 0.0.16(typescript@6.0.3) - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) magic-string: 0.30.21 mime: 4.1.1 sharp: 0.35.5(@types/node@24.12.4) @@ -13618,8 +13243,8 @@ snapshots: workerd: 1.20261026.1 yauzl: 3.4.0 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) rolldown: 1.2.13 vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: @@ -13627,27 +13252,27 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/cloudflare@2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1)': - dependencies: - '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) - '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(rolldown@1.2.13)(typescript@6.0.3) - '@alchemy.run/docker': 2.0.0-beta.85(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) - '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) - '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.5) - '@effect/sql-d1': 4.1.1(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@alchemy.run/cloudflare@2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e)': + dependencies: + '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(rolldown@1.2.13)(typescript@6.0.3) + '@alchemy.run/docker': 2.0.0-beta.85(b7b9d9a38fe35faf72b0a492112f9365) + '@alchemy.run/sql': 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) + '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) pathe: 2.0.3 picomatch: 4.0.7 rolldown: 1.2.13 tinyglobby: 0.2.17 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: - '@effect/sql-libsql' @@ -13659,26 +13284,26 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/docker@2.0.0-beta.85(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)': + '@alchemy.run/docker@2.0.0-beta.85(b7b9d9a38fe35faf72b0a492112f9365)': dependencies: - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) rolldown: 1.2.13 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) - '@alchemy.run/drizzle@2.0.0-beta.85(aaf71186a61e3f73fb98ecfca2947754)': + '@alchemy.run/drizzle@2.0.0-beta.85(5cde798e96ab6d44cdc28240628f10b1)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) - '@effect/sql-d1': 4.1.1(effect@4.1.5) - '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) - effect: 4.1.5 + '@alchemy.run/sql': 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: - '@alchemy.run/cloudflare': 2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1) - '@effect/sql-pg': 4.1.5(effect@4.1.5) - drizzle-kit: 1.0.0-rc.5(drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7)) + '@alchemy.run/cloudflare': 2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + drizzle-kit: 1.0.0-rc.5(73cc0b8bb5cef1afe1d24404a4fb8809) transitivePeerDependencies: - mysql2 - pg @@ -13688,13 +13313,13 @@ snapshots: chokidar: 5.0.0 rolldown: 1.2.13 - '@alchemy.run/planetscale@2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0)': + '@alchemy.run/planetscale@2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@alchemy.run/sql': 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: pg: 8.23.0 transitivePeerDependencies: @@ -13707,31 +13332,26 @@ snapshots: '@types/react': 19.3.0 react-devtools-core: 6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@alchemy.run/sql@2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0)': + '@alchemy.run/sql@2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5)': dependencies: - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: - '@effect/sql-pg': 4.1.5(effect@4.1.5) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) pg: 8.23.0 - '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(adf93af6036c4c597e35df2cca6d42d0)': + '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(a619c060a1b8ed45ad4914f1f8e44c19)': dependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: - '@effect/vitest': 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) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@effect/vitest': 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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) vitest: 5.0.5(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/browser-preview@5.0.5)(@vitest/ui@5.0.5)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0) transitivePeerDependencies: - bufferutil - utf-8-validate - '@antfu/install-pkg@2.1.0': - dependencies: - package-manager-detector: 1.8.0 - tinyexec: 1.3.1 - '@anthropic-ai/claude-agent-sdk@0.3.321(@anthropic-ai/sdk@0.93.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.29.0(supports-color@8.1.1)(zod@4.6.7))(zod@4.6.7)': dependencies: '@anthropic-ai/sdk': 0.93.0(zod@4.6.7) @@ -14406,8 +14026,6 @@ snapshots: '@blazediff/core@1.10.0': {} - '@braintree/sanitize-url@7.1.2': {} - '@bramus/specificity@2.4.2': dependencies: css-tree: 3.2.1 @@ -14449,21 +14067,6 @@ snapshots: dependencies: fontkitten: 1.0.3 - '@chevrotain/cst-dts-gen@13.2.0': - dependencies: - '@chevrotain/gast': 13.2.0 - '@chevrotain/types': 13.2.0 - - '@chevrotain/gast@13.2.0': - dependencies: - '@chevrotain/types': 13.2.0 - - '@chevrotain/regexp-to-ast@13.2.0': {} - - '@chevrotain/types@13.2.0': {} - - '@chevrotain/utils@13.2.0': {} - '@clack/core@1.0.0-alpha.6': dependencies: picocolors: 1.1.1 @@ -14722,45 +14325,45 @@ snapshots: '@dimforge/rapier3d-compat@0.12.0': {} - '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@dnd-kit/accessibility@3.1.1(react@19.3.0)': dependencies: @@ -14806,64 +14409,64 @@ snapshots: e2e: 0.23.0 playwright-core: 1.64.1 - '@effect/atom-react@4.1.5(effect@4.1.5)(react@19.3.0)(scheduler@0.28.0)': + '@effect/atom-react@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react@19.3.0)(scheduler@0.28.0)': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) react: 19.3.0 scheduler: 0.28.0 - '@effect/graphql-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)': + '@effect/graphql-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@effect/openapi-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)(encoding@0.1.13)': + '@effect/openapi-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(encoding@0.1.13)': dependencies: - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) swagger2openapi: 7.0.8(encoding@0.1.13) transitivePeerDependencies: - encoding - '@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6)': + '@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node-shared@4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6)': + '@effect/platform-node-shared@4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6)': dependencies: '@types/ws': 8.18.2 - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6)': + '@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) redis: 6.2.1 undici: 8.12.4 transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/sql-d1@4.1.1(effect@4.1.5)': + '@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: '@cloudflare/workers-types': 5.20261026.1 - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@effect/sql-pg@4.1.5(effect@4.1.5)': + '@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@effect/sql-sqlite-do@4.1.5(effect@4.1.5)': + '@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@effect/tsgo-darwin-arm64@0.67.1': optional: true @@ -14896,9 +14499,9 @@ snapshots: '@effect/tsgo-win32-arm64': 0.67.1 '@effect/tsgo-win32-x64': 0.67.1 - '@effect/vitest@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)': + '@effect/vitest@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(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(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)': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) vite-plus: 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) transitivePeerDependencies: - '@arethetypeswrong/core' @@ -15850,14 +15453,6 @@ snapshots: '@iarna/toml@2.2.5': {} - '@iconify/types@2.0.0': {} - - '@iconify/utils@3.1.7': - dependencies: - '@antfu/install-pkg': 2.1.0 - '@iconify/types': 2.0.0 - import-meta-resolve: 4.2.0 - '@img/colour@1.1.0': {} '@img/sharp-darwin-arm64@0.35.5': @@ -16078,7 +15673,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) @@ -16163,10 +15758,6 @@ snapshots: '@material/material-color-utilities@0.3.0': {} - '@mermaid-js/parser@2.0.1': - dependencies: - '@chevrotain/types': 13.2.0 - '@modelcontextprotocol/core@2.4.0': dependencies: zod: 4.6.7 @@ -16386,22 +15977,22 @@ snapshots: dependencies: cross-spawn: 7.0.6 - '@opencode/client@2.0.28(effect@4.1.5)': + '@opencode/client@2.0.28(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: '@opencode/protocol': 2.0.28 '@opencode/schema': 2.0.28 optionalDependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@opencode/protocol@2.0.28': dependencies: '@opencode/schema': 2.0.28 - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@opencode/schema@2.0.28': dependencies: '@standard-schema/spec': 1.1.0 - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@oslojs/asn1@1.0.0': dependencies: @@ -17002,6 +16593,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': {} @@ -17860,123 +17456,6 @@ snapshots: '@types/culori@4.0.1': {} - '@types/d3-array@3.2.2': {} - - '@types/d3-axis@3.0.6': - dependencies: - '@types/d3-selection': 3.0.12 - - '@types/d3-brush@3.0.6': - dependencies: - '@types/d3-selection': 3.0.12 - - '@types/d3-chord@3.0.6': {} - - '@types/d3-color@3.1.3': {} - - '@types/d3-contour@3.0.6': - dependencies: - '@types/d3-array': 3.2.2 - '@types/geojson': 7946.0.16 - - '@types/d3-delaunay@6.0.4': {} - - '@types/d3-dispatch@3.0.7': {} - - '@types/d3-drag@3.0.7': - dependencies: - '@types/d3-selection': 3.0.12 - - '@types/d3-dsv@3.0.7': {} - - '@types/d3-ease@3.0.2': {} - - '@types/d3-fetch@3.0.7': - dependencies: - '@types/d3-dsv': 3.0.7 - - '@types/d3-force@3.0.10': {} - - '@types/d3-format@3.0.4': {} - - '@types/d3-geo@3.1.1': - dependencies: - '@types/geojson': 7946.0.16 - - '@types/d3-hierarchy@3.1.7': {} - - '@types/d3-interpolate@3.0.4': - dependencies: - '@types/d3-color': 3.1.3 - - '@types/d3-path@3.1.1': {} - - '@types/d3-polygon@3.0.2': {} - - '@types/d3-quadtree@3.0.6': {} - - '@types/d3-random@3.0.4': {} - - '@types/d3-scale-chromatic@3.1.0': {} - - '@types/d3-scale@4.0.9': - dependencies: - '@types/d3-time': 3.0.4 - - '@types/d3-selection@3.0.12': {} - - '@types/d3-shape@3.2.0': - dependencies: - '@types/d3-path': 3.1.1 - - '@types/d3-time-format@4.0.3': {} - - '@types/d3-time@3.0.4': {} - - '@types/d3-timer@3.0.2': {} - - '@types/d3-transition@3.0.9': - dependencies: - '@types/d3-selection': 3.0.12 - - '@types/d3-zoom@3.0.9': - dependencies: - '@types/d3-interpolate': 3.0.4 - '@types/d3-selection': 3.0.12 - - '@types/d3@7.4.3': - dependencies: - '@types/d3-array': 3.2.2 - '@types/d3-axis': 3.0.6 - '@types/d3-brush': 3.0.6 - '@types/d3-chord': 3.0.6 - '@types/d3-color': 3.1.3 - '@types/d3-contour': 3.0.6 - '@types/d3-delaunay': 6.0.4 - '@types/d3-dispatch': 3.0.7 - '@types/d3-drag': 3.0.7 - '@types/d3-dsv': 3.0.7 - '@types/d3-ease': 3.0.2 - '@types/d3-fetch': 3.0.7 - '@types/d3-force': 3.0.10 - '@types/d3-format': 3.0.4 - '@types/d3-geo': 3.1.1 - '@types/d3-hierarchy': 3.1.7 - '@types/d3-interpolate': 3.0.4 - '@types/d3-path': 3.1.1 - '@types/d3-polygon': 3.0.2 - '@types/d3-quadtree': 3.0.6 - '@types/d3-random': 3.0.4 - '@types/d3-scale': 4.0.9 - '@types/d3-scale-chromatic': 3.1.0 - '@types/d3-selection': 3.0.12 - '@types/d3-shape': 3.2.0 - '@types/d3-time': 3.0.4 - '@types/d3-time-format': 4.0.3 - '@types/d3-timer': 3.0.2 - '@types/d3-transition': 3.0.9 - '@types/d3-zoom': 3.0.9 - '@types/debug@4.1.13': dependencies: '@types/ms': 2.1.0 @@ -18008,8 +17487,6 @@ snapshots: dependencies: '@types/node': 24.12.4 - '@types/geojson@7946.0.16': {} - '@types/hast@3.0.5': dependencies: '@types/unist': 3.0.3 @@ -18142,11 +17619,6 @@ snapshots: '@ungap/structured-clone@1.3.1': {} - '@upsetjs/venn.js@2.0.0': - optionalDependencies: - d3-selection: 3.0.1 - d3-transition: 3.0.2(d3-selection@3.0.1) - '@vercel/config@0.3.0': dependencies: '@vercel/routing-utils': 6.2.0 @@ -18613,12 +18085,12 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 - alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): + alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): dependencies: '@alchemy.run/node-utils': 2.0.0-beta.85 '@alchemy.run/sigil': 0.1.0-alpha.1(@types/react@19.3.0)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6)) capnweb: 0.12.0 - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) fflate: 0.8.3 pathe: 2.0.3 picomatch: 4.0.7 @@ -18626,8 +18098,8 @@ snapshots: tinyglobby: 0.2.17 yaml: 2.9.0 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: @@ -19166,14 +18638,6 @@ snapshots: character-reference-invalid@2.0.1: {} - chevrotain@13.2.0: - dependencies: - '@chevrotain/cst-dts-gen': 13.2.0 - '@chevrotain/gast': 13.2.0 - '@chevrotain/regexp-to-ast': 13.2.0 - '@chevrotain/types': 13.2.0 - '@chevrotain/utils': 13.2.0 - chokidar@4.0.3: dependencies: readdirp: 4.1.2 @@ -19363,14 +18827,6 @@ snapshots: object-assign: 4.1.1 vary: 1.1.2 - cose-base@1.0.3: - dependencies: - layout-base: 1.0.2 - - cose-base@2.2.0: - dependencies: - layout-base: 2.0.1 - cross-dirname@0.1.0: optional: true @@ -19434,191 +18890,6 @@ snapshots: culori@4.0.2: {} - cytoscape-cose-bilkent@4.1.0(cytoscape@3.35.0): - dependencies: - cose-base: 1.0.3 - cytoscape: 3.35.0 - - cytoscape-fcose@2.2.0(cytoscape@3.35.0): - dependencies: - cose-base: 2.2.0 - cytoscape: 3.35.0 - - cytoscape@3.35.0: {} - - d3-array@2.12.1: - dependencies: - internmap: 1.0.1 - - d3-array@3.2.5: - dependencies: - internmap: 2.0.3 - - d3-axis@3.0.1: {} - - d3-brush@3.0.1: - dependencies: - d3-dispatch: 3.0.2 - d3-drag: 3.0.1 - d3-interpolate: 3.0.2 - d3-selection: 3.0.1 - d3-transition: 3.0.2(d3-selection@3.0.1) - - d3-chord@3.0.2: - dependencies: - d3-path: 3.1.1 - - d3-color@3.1.1: {} - - d3-contour@4.0.3: - dependencies: - d3-array: 3.2.5 - - d3-delaunay@6.0.6: - dependencies: - delaunator: 5.1.0 - - d3-dispatch@3.0.2: {} - - d3-drag@3.0.1: - dependencies: - d3-dispatch: 3.0.2 - d3-selection: 3.0.1 - - d3-dsv@3.0.2: - dependencies: - commander: 7.2.0 - iconv-lite: 0.6.3 - rw: 1.3.3 - - d3-ease@3.0.2: {} - - d3-fetch@3.0.2: - dependencies: - d3-dsv: 3.0.2 - - d3-force@3.0.1: - dependencies: - d3-dispatch: 3.0.2 - d3-quadtree: 3.0.2 - d3-timer: 3.0.2 - - d3-format@3.1.3: {} - - d3-geo@3.1.2: - dependencies: - d3-array: 3.2.5 - - d3-hierarchy@3.1.3: {} - - d3-interpolate@3.0.2: - dependencies: - d3-color: 3.1.1 - - d3-path@1.0.9: {} - - d3-path@3.1.1: {} - - d3-polygon@3.0.2: {} - - d3-quadtree@3.0.2: {} - - d3-random@3.0.2: {} - - d3-sankey@0.12.3: - dependencies: - d3-array: 2.12.1 - d3-shape: 1.3.7 - - d3-scale-chromatic@3.1.1: - dependencies: - d3-color: 3.1.1 - d3-interpolate: 3.0.2 - d3-scale: 4.0.3 - - d3-scale@4.0.3: - dependencies: - d3-array: 3.2.5 - d3-format: 3.1.3 - d3-interpolate: 3.0.2 - d3-time: 3.1.1 - d3-time-format: 4.1.1 - - d3-selection@3.0.1: {} - - d3-shape@1.3.7: - dependencies: - d3-path: 1.0.9 - - d3-shape@3.2.1: - dependencies: - d3-path: 3.1.1 - - d3-time-format@4.1.1: - dependencies: - d3-time: 3.1.1 - - d3-time@3.1.1: - dependencies: - d3-array: 3.2.5 - - d3-timer@3.0.2: {} - - d3-transition@3.0.2(d3-selection@3.0.1): - dependencies: - d3-color: 3.1.1 - d3-dispatch: 3.0.2 - d3-ease: 3.0.2 - d3-interpolate: 3.0.2 - d3-selection: 3.0.1 - d3-timer: 3.0.2 - - d3-zoom@3.0.1: - dependencies: - d3-dispatch: 3.0.2 - d3-drag: 3.0.1 - d3-interpolate: 3.0.2 - d3-selection: 3.0.1 - d3-transition: 3.0.2(d3-selection@3.0.1) - - d3@7.9.2: - dependencies: - d3-array: 3.2.5 - d3-axis: 3.0.1 - d3-brush: 3.0.1 - d3-chord: 3.0.2 - d3-color: 3.1.1 - d3-contour: 4.0.3 - d3-delaunay: 6.0.6 - d3-dispatch: 3.0.2 - d3-drag: 3.0.1 - d3-dsv: 3.0.2 - d3-ease: 3.0.2 - d3-fetch: 3.0.2 - d3-force: 3.0.1 - d3-format: 3.1.3 - d3-geo: 3.1.2 - d3-hierarchy: 3.1.3 - d3-interpolate: 3.0.2 - d3-path: 3.1.1 - d3-polygon: 3.0.2 - d3-quadtree: 3.0.2 - d3-random: 3.0.2 - d3-scale: 4.0.3 - d3-scale-chromatic: 3.1.1 - d3-selection: 3.0.1 - d3-shape: 3.2.1 - d3-time: 3.1.1 - d3-time-format: 4.1.1 - d3-timer: 3.0.2 - d3-transition: 3.0.2(d3-selection@3.0.1) - d3-zoom: 3.0.1 - - dagre-d3-es@7.0.14: - dependencies: - d3: 7.9.2 - lodash-es: 4.18.1 - data-urls@7.0.0(@noble/hashes@1.8.0): dependencies: whatwg-mimetype: 5.0.0 @@ -19630,8 +18901,6 @@ snapshots: dateformat@4.6.3: {} - dayjs@1.11.23: {} - dbus-next@0.10.2(patch_hash=cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4): dependencies: '@nornagon/put': 0.0.8 @@ -19707,10 +18976,6 @@ snapshots: defu@6.1.7: {} - delaunator@5.1.0: - dependencies: - robust-predicates: 3.0.3 - delayed-stream@1.0.0: {} denque@2.1.0: @@ -19793,21 +19058,21 @@ snapshots: dotenv@16.6.1: {} - drizzle-kit@1.0.0-rc.5(drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7)): + drizzle-kit@1.0.0-rc.5(73cc0b8bb5cef1afe1d24404a4fb8809): optionalDependencies: - drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) - drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7): + drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7): optionalDependencies: '@cloudflare/workers-types': 4.20260604.1 - '@effect/sql-d1': 4.1.1(effect@4.1.5) - '@effect/sql-pg': 4.1.5(effect@4.1.5) - '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@electric-sql/pglite': 0.3.15 '@libsql/client': 0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@types/sql.js': 1.4.11 bun-types: 1.3.14 - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) expo-sqlite: 58.0.15(expo@58.0.23)(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) pg: 8.23.0 sql.js: 1.15.0 @@ -19846,7 +19111,7 @@ snapshots: ee-first@1.1.1: {} - effect@4.1.5: {} + effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28): {} ejs@3.1.10: dependencies: @@ -19938,8 +19203,6 @@ snapshots: transitivePeerDependencies: - supports-color - elkjs@0.12.1: {} - emmet@2.4.11: dependencies: '@emmetio/abbreviation': 2.3.3 @@ -20002,8 +19265,6 @@ snapshots: has-tostringtag: 1.0.2 hasown: 2.0.4 - es-toolkit@1.53.2: {} - es6-error@4.1.1: optional: true @@ -20989,8 +20250,6 @@ snapshots: ufo: 1.6.4 uncrypto: 0.1.3 - hachure-fill@0.5.2: {} - has-flag@3.0.0: {} has-flag@4.0.0: {} @@ -21175,6 +20434,7 @@ snapshots: iconv-lite@0.6.3: dependencies: safer-buffer: 2.1.2 + optional: true iconv-lite@0.7.3: dependencies: @@ -21189,8 +20449,6 @@ snapshots: immediate@3.0.6: {} - import-meta-resolve@4.2.0: {} - inflight@1.0.6: dependencies: once: 1.4.0 @@ -21200,10 +20458,6 @@ snapshots: inline-style-parser@0.2.7: {} - internmap@1.0.1: {} - - internmap@2.0.3: {} - invariant@2.2.4: dependencies: loose-envify: 1.4.0 @@ -21455,8 +20709,6 @@ snapshots: dependencies: json-buffer: 3.0.1 - khroma@2.1.0: {} - kleur@3.0.3: {} kleur@4.1.5: {} @@ -21502,10 +20754,6 @@ snapshots: lan-network@0.2.1: {} - layout-base@1.0.2: {} - - layout-base@2.0.1: {} - lazy-val@1.0.5: {} leven@3.1.0: {} @@ -21586,8 +20834,6 @@ snapshots: p-locate: 3.0.0 path-exists: 3.0.0 - lodash-es@4.18.1: {} - lodash.debounce@4.0.8: {} lodash.escaperegexp@4.1.2: {} @@ -21659,8 +20905,6 @@ snapshots: markdown-table@3.0.4: {} - marked@16.4.2: {} - matcher@3.0.0: dependencies: escape-string-regexp: 4.0.0 @@ -21889,31 +21133,6 @@ snapshots: merge2@1.4.1: {} - mermaid@12.3.0: - dependencies: - '@braintree/sanitize-url': 7.1.2 - '@iconify/utils': 3.1.7 - '@mermaid-js/parser': 2.0.1 - '@types/d3': 7.4.3 - '@upsetjs/venn.js': 2.0.0 - chevrotain: 13.2.0 - cytoscape: 3.35.0 - cytoscape-cose-bilkent: 4.1.0(cytoscape@3.35.0) - cytoscape-fcose: 2.2.0(cytoscape@3.35.0) - d3: 7.9.2 - d3-sankey: 0.12.3 - dagre-d3-es: 7.0.14 - dayjs: 1.11.23 - dompurify: 3.4.17 - elkjs: 0.12.1 - es-toolkit: 1.53.2 - katex: 0.18.10 - khroma: 2.1.0 - marked: 16.4.2 - roughjs: 4.6.6 - stylis: 4.4.0 - ts-dedent: 2.3.0 - meshoptimizer@0.22.0: {} metro-babel-transformer@0.87.1(supports-color@8.1.1): @@ -22957,8 +22176,6 @@ snapshots: path-browserify@1.0.1: {} - path-data-parser@0.1.0: {} - path-exists@3.0.0: {} path-expression-matcher@1.6.2: {} @@ -23121,13 +22338,6 @@ snapshots: pngjs@7.0.0: {} - points-on-curve@0.2.0: {} - - points-on-path@0.2.1: - dependencies: - path-data-parser: 0.1.0 - points-on-curve: 0.2.0 - postcss@8.5.30: dependencies: nanoid: 3.3.20 @@ -23369,24 +22579,6 @@ snapshots: react-is@19.3.1: {} - 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 @@ -23766,8 +22958,6 @@ snapshots: sprintf-js: 1.1.3 optional: true - robust-predicates@3.0.3: {} - rolldown@1.0.0-rc.17: dependencies: '@oxc-project/types': 0.127.0 @@ -23813,13 +23003,6 @@ snapshots: rope-sequence@1.3.4: {} - roughjs@4.6.6: - dependencies: - hachure-fill: 0.5.2 - path-data-parser: 0.1.0 - points-on-curve: 0.2.0 - points-on-path: 0.2.1 - router@2.2.0(supports-color@8.1.1): dependencies: debug: 4.4.3(supports-color@8.1.1) @@ -23836,8 +23019,6 @@ snapshots: dependencies: queue-microtask: 1.2.3 - rw@1.3.3: {} - safe-buffer@5.1.2: {} safe-buffer@5.2.1: {} @@ -24232,8 +23413,6 @@ snapshots: dependencies: inline-style-parser: 0.2.7 - stylis@4.4.0: {} - sumchecker@3.0.1(supports-color@8.1.1): dependencies: debug: 4.4.3(supports-color@8.1.1) @@ -24417,8 +23596,6 @@ snapshots: ts-algebra@2.0.0: {} - ts-dedent@2.3.0: {} - ts-morph@28.0.0: dependencies: '@ts-morph/common': 0.29.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index d8fd4bc07cb15..fdaafa748a67e 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -232,6 +232,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 @@ -284,6 +285,8 @@ patchedDependencies: react-native-svg@15.16.1: patches/react-native-svg@15.16.1.patch # Android: double-tap zoom no longer cancels itself, and taps near a link open it. react-native-pdf-jsi@6.1.0: patches/react-native-pdf-jsi@6.1.0.patch + # The MCP Events extension (SEP-3415) on effect/ai, until Effect ships it. + effect@4.1.5: patches/effect@4.1.5.patch # Unmet peers fail resolution, so a pin outside a dependency's peer range is # caught when the lockfile changes instead of scrolling past as a warning. 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/add-project-tab-reaches-submit.e2e.ts b/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts index b6afb9358cd2b..66c69347e4aa4 100644 --- a/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts +++ b/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts @@ -9,7 +9,8 @@ test( await t3.project("demo"); await t3.open(); - await screen.getByRole("button", "Add project").tap(); + await screen.getByRole("combobox", "Projects").tap(); + await screen.getByRole("option", "Add project").tap(); await screen.getByText("Git URL").tap(); await screen.getByRole("combobox").fill("https://github.com/pingdotgg/t3code.git"); const submit = screen.getByRole("button", "Continue (Enter)"); 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/citation-skips-ambiguous-project-files.e2e.ts b/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts new file mode 100644 index 0000000000000..6cfbafc6c49b2 --- /dev/null +++ b/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const FILE = "handoff.txt"; + +test( + "A bare citation leaves the file unresolved when other projects contain several matches", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("planning"); + await t3.project("reports", { "notes/HANDOFF.txt": "Report handoff" }); + await t3.project("support", { + "current/Handoff.txt": "Current support handoff", + "archive/HANDOFF.txt": "Archived support handoff", + }); + const thread = await t3.thread({ + project, + title: "Find the handoff", + messages: [`See :codex-file-citation{path="${FILE}" line_range_start="1"}`], + }); + + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await screen.getByRole("link", /^handoff\.txt/).tap(); + + try { + await expect( + browser + .locator("[data-right-panel-surface-content]") + .getByText("The file could not be accessed or read. It may be missing or inaccessible."), + ).toBeVisible(); + } finally { + await app.screenshot("ambiguous-handoff-citation"); + } + }, +); diff --git a/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts b/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts new file mode 100644 index 0000000000000..22458e6223fbb --- /dev/null +++ b/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts @@ -0,0 +1,34 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A bare citation leaves the file unresolved when the thread project has ambiguous matches", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("support", { + "current/Handoff.txt": "Current support handoff", + "archive/HANDOFF.txt": "Archived support handoff", + }); + await t3.project("reports", { "notes/HANDOFF.txt": "Report handoff" }); + const thread = await t3.thread({ + project, + title: "Find the handoff", + messages: ['See :codex-file-citation{path="handoff.txt" line_range_start="1"}'], + }); + + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await screen.getByRole("link", /^handoff\.txt/).tap(); + + try { + await expect( + browser + .locator("[data-right-panel-surface-content]") + .getByText("The file could not be accessed or read. It may be missing or inaccessible."), + ).toBeVisible(); + } finally { + await app.screenshot("ambiguous-local-handoff-citation"); + } + }, +); 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/clone-failure-after-dismissing-progress.e2e.ts b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts new file mode 100644 index 0000000000000..739497a827757 --- /dev/null +++ b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts @@ -0,0 +1,113 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The fixture holds Git's HTTP request open. +import * as NodeHttp from "node:http"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { ProjectId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Stream from "effect/Stream"; + +import { T3_HOME } from "../e2e.config.ts"; +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; + +test( + "Dismissing clone progress leaves the later failure notification visible", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Other work", messages: ["Start"] }); + const gitRequest = Promise.withResolvers(); + const remote = NodeHttp.createServer((_request, response) => { + gitRequest.resolve(response); + }); + + try { + await new Promise((resolve) => remote.listen(0, "127.0.0.1", resolve)); + const address = remote.address(); + if (!address || typeof address === "string") throw new Error("No Git fixture port"); + const projectId = ProjectId.make( + await runPromise( + SecureRandom.SecureRandom.pipe( + Effect.flatMap((random) => random.uuidV4()), + Effect.provide(NodeCrypto.layer), + ), + ), + ); + const name = "pending-clone"; + const origin = app.baseUrl ?? ""; + await t3.open(thread); + await screen.getByText("Start", { exact: true }).waitFor(); + + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + const createdAt = DateTime.formatIso(yield* DateTime.now); + yield* client["projectClone.start"]({ + projectId, + title: name, + createdAt, + remoteUrl: `http://127.0.0.1:${address.port}/${name}.git`, + destinationPath: `${project}/../${name}`, + }); + }).pipe(Effect.scoped), + ); + const response = await gitRequest.promise; + + const toastTitle = (title: string) => + browser.locator(`[data-slot="toast-title"]:text-is("${title}")`); + const dismiss = async (title: string) => { + await browser + .locator( + `[data-position]:has(> div > [data-slot="toast-close"]):has([data-slot="toast-title"]:text-is("${title}"))`, + ) + .getByRole("button", "Dismiss notification", { exact: true }) + .tap(); + await toastTitle(title).waitFor({ state: "detached" }); + }; + const progress = toastTitle(`Cloning ${name}`); + const failure = toastTitle(`Failed to clone ${name}`); + + await progress.waitFor(); + await dismiss(`Cloning ${name}`); + + response.writeHead(404).end(); + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + yield* client.subscribeProjectClones({}).pipe( + Stream.filter((clones) => + clones.some((clone) => clone.projectId === projectId && clone.phase === "failed"), + ), + Stream.runHead, + ); + }).pipe(Effect.scoped, Effect.timeout("10 seconds")), + ); + + try { + await expect(failure).toBeVisible(); + } finally { + await app.screenshot("after-background-clone-fails"); + } + + await dismiss(`Failed to clone ${name}`); + + const retryRequest = Promise.withResolvers(); + remote.once("request", (_request, response) => retryRequest.resolve(response)); + const retry = await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + return yield* client["projectClone.retry"]({ projectId }); + }).pipe(Effect.scoped), + ); + await expect(retry.applied).toBe(true); + const retryResponse = await retryRequest.promise; + await expect(progress).toBeVisible(); + retryResponse.writeHead(404).end(); + await expect(failure).toBeVisible(); + } finally { + remote.close(); + remote.closeAllConnections(); + } + }, +); diff --git a/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts b/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts new file mode 100644 index 0000000000000..dbd90361cfe45 --- /dev/null +++ b/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts @@ -0,0 +1,139 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodeCredential = Schema.decodeUnknownSync(Schema.Struct({ credential: Schema.String })); + +test( + "A closed linked-thread tab does not take over the conversation when pairing finishes", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("primary"); + const parent = await t3.thread({ + project, + title: "Current work", + messages: ["Keep this conversation open"], + }); + const origin = app.baseUrl ?? ""; + const server = startSecondServer(origin); + try { + const { host } = await server.ready; + const second = makeState(SECOND_HOME); + const issued = await runPromise(second.cli(["auth", "session", "issue", "--token-only"])); + // @effect-diagnostics-next-line globalFetch:off -- Seeds the real peer link from the scenario's Node fixture. + const pairing = await fetch(`${host}/api/auth/pairing-token`, { + method: "POST", + headers: { + authorization: `Bearer ${issued.stdout.trim()}`, + "content-type": "application/json", + }, + body: JSON.stringify({ purpose: "peer-link", access: "full-access" }), + }); + if (!pairing.ok) throw new Error(`Could not mint a peer-link code: ${pairing.status}`); + const { credential } = decodeCredential(await pairing.json()); + await runPromise( + Effect.gen(function* () { + const primary = yield* rpcClient(T3_HOME, origin); + const remote = yield* rpcClient(SECOND_HOME, host); + for (const client of [primary, remote]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + yield* primary["peerLinks.link"]({ + url: host, + pairingCode: credential, + access: "full-access", + }); + }).pipe(Effect.scoped), + ); + + const linkedProject = await second.state.project("linked"); + const linkedTitle = "Remote design notes"; + const linkedPrompt = "Read the remote design notes"; + const remoteThread = await second.state.thread({ + project: linkedProject, + title: linkedTitle, + messages: [linkedPrompt], + }); + const via = await runPromise(environmentId(origin)); + const linked = await runPromise(environmentId(host)); + await browser.setViewport({ width: 1440, height: 900 }); + + // Restore the same saved tab that opening the delegated thread in the panel would leave. + await browser.addInitScript( + ({ via, linked, parentId, childId, title }) => { + if (location.pathname !== `/${via}/${parentId}`) return; + const id = `linked-thread:${encodeURIComponent(via)}:${encodeURIComponent(linked)}:${encodeURIComponent(childId)}`; + localStorage.setItem( + "t3code:right-panel-state:v2", + JSON.stringify({ + version: 16, + state: { + byThreadKey: { + [`${via}:${parentId}`]: { + isOpen: true, + activeSurfaceId: id, + surfaces: [ + { + kind: "linked-thread", + id, + viaEnvironmentId: via, + environmentId: linked, + threadId: childId, + label: "Scenario", + title, + }, + ], + }, + }, + threadPanelVisibilityByThreadKey: {}, + }, + }), + ); + }, + { + via, + linked, + parentId: parent.threadId, + childId: remoteThread.threadId, + title: linkedTitle, + }, + ); + + const tokenUrl = `${host}/oauth/token`; + const requested = Promise.withResolvers(); + const release = Promise.withResolvers(); + await browser.route(tokenUrl, async (route) => { + if (route.request.method !== "POST") return route.fallback(); + requested.resolve(); + await release.promise; + await route.continue(); + }); + try { + await t3.open(parent); + await screen.getByText(linkedPrompt, { exact: true }).waitFor(); + const originalUrl = await browser.url(); + await screen.getByRole("button", "Connect to interact", { exact: true }).tap(); + await requested.promise; + await screen.getByRole("button", `Close ${linkedTitle}`, { exact: true }).tap(); + + release.resolve(); + await screen + .getByText("This device is paired with it and can use its threads.", { exact: true }) + .waitFor(); + + await app.screenshot("after-pairing-finishes"); + await expect(browser).toHaveURL(originalUrl); + } finally { + release.resolve(); + await browser.unroute(tokenUrl); + } + } finally { + await server.stop(); + } + }, +); 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/linear-settings-name-another-team.e2e.ts b/scripts/scenarios/linear-settings-name-another-team.e2e.ts new file mode 100644 index 0000000000000..32f18c883ab84 --- /dev/null +++ b/scripts/scenarios/linear-settings-name-another-team.e2e.ts @@ -0,0 +1,59 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - a fake Linear API for the server to call +import * as NodeHttp from "node:http"; + +import { expect } from "e2e"; + +import { SCENARIO_LINEAR_PORT } from "./start-app.ts"; +import { test, WEB } from "./t3.ts"; + +// Connecting reads only the viewer, the workspace and its teams. +const VIEWER = { + data: { + viewer: { + id: "user-1", + name: "Scenario User", + displayName: "scenario", + email: "user@example.com", + avatarUrl: null, + }, + organization: { urlKey: "acme" }, + teams: { + nodes: [ + { id: "team-eng", key: "ENG", name: "Engineering" }, + { id: "team-ops", key: "OPS", name: "Operations" }, + ], + }, + }, +}; + +test( + "Linear settings say agents can file new issues in another bound team", + WEB, + async ({ t3, app, browser, screen }) => { + const linear = NodeHttp.createServer((_request, response) => { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify(VIEWER)); + }); + await new Promise((resolve) => linear.listen(SCENARIO_LINEAR_PORT, "127.0.0.1", resolve)); + try { + await t3.project("demo"); + await t3.open("/settings/source-control"); + + await screen.getByRole("button", "Toggle Linear details").tap(); + await browser.locator('input[id^="issue-tracker-linear-"]').fill("lin_api_scenario"); + await browser.keyboard.press("Enter"); + await expect( + screen.getByText("Pick one or more Linear teams for each project", { exact: false }), + ).toBeVisible(); + await app.screenshot("linear-projects"); + + await expect( + screen.getByText("agents file new issues in the first one unless asked for another", { + exact: false, + }), + ).toBeVisible(); + } finally { + await new Promise((resolve) => linear.close(resolve)); + } + }, +); diff --git a/scripts/scenarios/linked-thread-connects-before-fallback-timeout.e2e.ts b/scripts/scenarios/linked-thread-connects-before-fallback-timeout.e2e.ts new file mode 100644 index 0000000000000..42c5c57b1ea4c --- /dev/null +++ b/scripts/scenarios/linked-thread-connects-before-fallback-timeout.e2e.ts @@ -0,0 +1,88 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodePairing = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), +); + +const linkEnvironments = Effect.fn("scenario.linkEnvironments")(function* ( + primaryOrigin: string, + secondOrigin: string, + fallback: string, +) { + const primary = yield* rpcClient(T3_HOME, primaryOrigin); + const second = yield* rpcClient(SECOND_HOME, secondOrigin); + for (const client of [primary, second]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + const pairing = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]); + const { credential } = yield* decodePairing(pairing.stdout); + yield* primary["peerLinks.link"]({ + url: secondOrigin, + alternateUrls: [fallback], + pairingCode: credential, + access: "full-access", + }); +}, Effect.scoped); + +test( + "Connect to interact opens the editable thread before a silent fallback times out", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("primary"); + const primary = app.baseUrl ?? ""; + const secondServer = startSecondServer(primary); + try { + const { host } = await secondServer.ready; + const alternate = new URL(host); + alternate.hostname = "127.0.0.2"; + await runPromise(linkEnvironments(primary, host, alternate.origin)); + + const second = makeState(SECOND_HOME).state; + const project = await second.project("linked"); + const thread = await second.thread({ + project, + title: "Linked handoff", + messages: ["first"], + }); + const via = await runPromise(environmentId(primary)); + const target = await runPromise(environmentId(host)); + + await browser.addInitScript((fallback) => { + const fetchActual = globalThis.fetch; + globalThis.fetch = (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input), location.href); + if (url.origin !== fallback || url.pathname !== "/.well-known/t3/environment") { + // @effect-diagnostics-next-line globalFetch:off - This interception runs inside the browser. + return fetchActual(input, init); + } + // The browser's network silently drops this route. The preferred address is still real. + return new Promise((_, reject) => { + const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined); + signal?.addEventListener("abort", () => reject(signal.reason), { once: true }); + }); + }; + }, alternate.origin); + + await t3.open(`/linked/${via}/${target}/${thread.threadId}`); + await screen.getByRole("heading", "Linked handoff").waitFor(); + await screen.getByRole("button", "Connect to interact").tap(); + + try { + await expect + .poll(() => browser.evaluate(() => location.pathname), { timeout: 4_000 }) + .toBe(`/${target}/${encodeURIComponent(thread.threadId)}`); + } finally { + await app.screenshot("linked-thread-after-connect"); + } + } finally { + await secondServer.stop(); + } + }, +); diff --git a/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts b/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts new file mode 100644 index 0000000000000..fd24c39b74dea --- /dev/null +++ b/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts @@ -0,0 +1,105 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodePairing = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), +); + +test( + "Try again immediately reads a linked thread once it is reachable", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("primary"); + const origin = app.baseUrl ?? ""; + const server = startSecondServer(origin); + try { + const { host } = await server.ready; + await runPromise( + Effect.gen(function* () { + const primary = yield* rpcClient(T3_HOME, origin); + const remote = yield* rpcClient(SECOND_HOME, host); + for (const client of [primary, remote]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + const pairing = yield* makeState(SECOND_HOME).cli([ + "auth", + "pairing", + "create", + "--json", + ]); + const { credential } = yield* decodePairing(pairing.stdout); + yield* primary["peerLinks.link"]({ + url: host, + pairingCode: credential, + access: "approval-required", + }); + }).pipe(Effect.scoped), + ); + + const remote = makeState(SECOND_HOME).state; + const project = await remote.project("linked"); + const prompt = "Read the linked design notes"; + const thread = await remote.thread({ project, title: "Design notes", messages: [prompt] }); + const via = await runPromise(environmentId(origin)); + const linked = await runPromise(environmentId(host)); + + // Drop only the first subscription, as if the linked machine were briefly unreachable. + // Every later request goes to the real server and reads the seeded thread. + await browser.addInitScript(() => { + let failed = false; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (failed || typeof data !== "string") return send.call(this, data); + const parsed = JSON.parse(data); + const messages = Array.isArray(parsed) ? parsed : [parsed]; + const request = messages.find( + (message) => message?._tag === "Request" && message.tag === "peerLinks.subscribeThread", + ); + if (!request) return send.call(this, data); + failed = true; + const others = messages.filter((message) => message !== request); + if (others.length > 0) send.call(this, JSON.stringify(others)); + // @effect-diagnostics-next-line globalTimers:off - This callback is injected into the browser. + setTimeout(() => { + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ + _tag: "Exit", + requestId: request.id, + exit: { + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "PeerLinkThreadReadError", + reason: "unreachable", + label: "Scenario", + message: "The linked machine is temporarily unreachable.", + }, + }, + ], + }, + }), + }), + ); + }, 0); + }; + }); + + await t3.open(`/linked/${via}/${linked}/${thread.threadId}`); + await screen.getByRole("button", "Try again", { exact: true }).tap(); + await app.screenshot("after-trying-again"); + // The automatic retry waits 15 seconds. This checks the user's explicit retry. + await expect(screen.getByText(prompt, { exact: true })).toBeVisible({ timeout: 4_000 }); + } finally { + await server.stop(); + } + }, +); diff --git a/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts b/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts new file mode 100644 index 0000000000000..c944cf1ec9d42 --- /dev/null +++ b/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts @@ -0,0 +1,80 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const savedResults = Array.from({ length: 17 }, (_, index) => `Saved result ${index + 1}`); +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { language_info: { name: "python" } }, + cells: [ + { + id: "results", + cell_type: "code", + source: [], + metadata: {}, + execution_count: 1, + outputs: [ + { output_type: "stream", name: "stdout", text: Array(12).fill("Processing").join("\n") }, + ...savedResults.map((result) => ({ + output_type: "display_data", + metadata: {}, + data: { "text/html": `${result}` }, + })), + ], + }, + ], +}; +const lastOutput = '[data-notebook-output="0-17"]'; + +test( + "All saved notebook outputs render when they fit in a tall preview", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) }); + const thread = await t3.thread({ project, title: "Review results", messages: ["Start"] }); + await browser.setViewport({ width: 1440, height: 1080 }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("results.ipynb"); + await screen.getByRole("option", "results.ipynb", { exact: false }).tap(); + await browser.locator(lastOutput).waitFor({ state: "attached", timeout: 120_000 }); + + // The stream puts the final result below the fold until the user scrolls. + const height = await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + return window.innerHeight - viewport.clientHeight + 1070; + }, lastOutput); + await browser.setViewport({ width: 1440, height }); + await browser.locator('[data-notebook-output="0-15"] iframe').waitFor({ timeout: 30_000 }); + await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + viewport.scrollTop = viewport.scrollHeight; + return null; + }, lastOutput); + + try { + await expect + .poll(() => + browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + const bounds = viewport.getBoundingClientRect(); + return Array.from(viewport.querySelectorAll("[data-notebook-output]"), (output) => { + const row = output.getBoundingClientRect(); + if (row.top < bounds.top || row.bottom > bounds.bottom) return "Output is offscreen"; + return ( + output.querySelector("iframe")?.contentDocument?.body?.textContent?.trim() || + "Output is in view but blank" + ); + }); + }, lastOutput), + ) + .toEqual(savedResults); + } finally { + await app.screenshot("last-saved-output-in-tall-preview"); + } + }, +); diff --git a/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts b/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts new file mode 100644 index 0000000000000..2897ecc0df7eb --- /dev/null +++ b/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts @@ -0,0 +1,77 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { language_info: { name: "python" } }, + cells: [ + { + id: "results", + cell_type: "code", + source: [], + metadata: {}, + execution_count: 1, + outputs: Array.from({ length: 17 }, (_, index) => ({ + output_type: "display_data", + metadata: {}, + data: { "text/html": `Saved result ${index + 1}` }, + })), + }, + ], +}; +const fifteenthOutputFrame = '[data-notebook-output="0-14"] iframe'; +const lastOutput = '[data-notebook-output="0-16"]'; + +test( + "A visible saved notebook output renders when earlier outputs have scrolled above it", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) }); + const thread = await t3.thread({ project, title: "Review results", messages: ["Start"] }); + await browser.setViewport({ width: 1440, height: 1080 }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("results.ipynb"); + await screen.getByRole("option", "results.ipynb", { exact: false }).tap(); + await browser.locator(lastOutput).waitFor({ state: "attached", timeout: 120_000 }); + + // Leave room for the final output and fewer than sixteen preceding outputs. + const height = await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + return window.innerHeight - viewport.clientHeight + 940; + }, lastOutput); + await browser.setViewport({ width: 1440, height }); + await browser.locator(fifteenthOutputFrame).waitFor({ timeout: 30_000 }); + await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + viewport.scrollTop = 170; + return null; + }, lastOutput); + + try { + await expect + .poll(() => + browser.evaluate((selector) => { + const output = document.querySelector(selector); + const viewport = output?.closest(".scrollbar-gutter-both"); + if (!output || !viewport) return null; + const bounds = viewport.getBoundingClientRect(); + const row = output.getBoundingClientRect(); + if (row.top < bounds.top || row.bottom > bounds.bottom) return null; + return ( + output.querySelector("iframe")?.contentDocument?.body?.textContent?.trim() || + "Output is in view but blank" + ); + }, lastOutput), + ) + .toBe("Saved result 17"); + } finally { + await app.screenshot("last-saved-output"); + } + }, +); diff --git a/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts new file mode 100644 index 0000000000000..8ee5453bbba20 --- /dev/null +++ b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A queued message shows its @-file mention by name, not as a raw link", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "src/foo.ts": "export {};\n" }); + const thread = await t3.thread({ + project, + title: "Long work", + messages: ["Show me around"], + model: "showcase", + }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.pressSequentially("Review @foo"); + await screen.getByRole("option", "foo.ts", { exact: false }).tap(); + await expect(composer).toContainText("foo.ts"); + + // The showcase recording streams for several seconds, long enough to queue behind its turn. + await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Show me again"])); + await screen.getByText("Working for", { exact: false }).waitFor(); + // Enter steers by default; the alternate send queues. + await browser.keyboard.press("ControlOrMeta+Enter"); + + const queued = screen.getByRole("listitem", "Queued message 1 of 1, not sent"); + await queued.waitFor(); + // Read the row once: the queued message sends, and its row goes, when the turn ends. + const text = await queued.textContent(); + await app.screenshot("queued-row"); + expect(text).toContain("Review foo.ts"); + }, +); diff --git a/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts new file mode 100644 index 0000000000000..49186eaa4429a --- /dev/null +++ b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts @@ -0,0 +1,64 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +declare global { + interface Window { + releaseOldThemeRead: () => void; + } +} + +test( + "An earlier theme file cannot become the draft after its replacement is rejected", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await t3.open("/settings/appearance"); + await screen.getByRole("button", "Add theme", { exact: true }).tap(); + const dialog = screen.getByRole("dialog", "Add a theme"); + + await browser.evaluate(() => { + const target = document.querySelector('input[type="file"]')?.parentElement; + if (!target) throw new Error("No theme file drop target"); + + const gate = Promise.withResolvers(); + const theme = JSON.stringify({ + version: 1, + name: "Earlier theme", + appearance: "dark", + colors: { accent: "#734ee4" }, + }); + const first = new File([theme], "earlier.json", { type: "application/json" }); + const text = File.prototype.text; + File.prototype.text = function () { + if (this.name === first.name) return gate.promise.then(() => theme); + return text.call(this); + }; + window.releaseOldThemeRead = gate.resolve; + + const drop = (file: File) => { + const files = new DataTransfer(); + files.items.add(file); + target.dispatchEvent( + new DragEvent("drop", { dataTransfer: files, bubbles: true, cancelable: true }), + ); + }; + drop(first); + drop(new File([" ".repeat(300_000)], "replacement.json", { type: "application/json" })); + return null; + }); + + await dialog.getByText(/That file is/).waitFor(); + await browser.evaluate(async () => { + window.releaseOldThemeRead(); + // Let the earlier file response and its React update reach the dialog. + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + return null; + }); + await app.screenshot("dialog-after-earlier-theme-read-finishes"); + await expect(dialog.getByRole("button", "Add theme", { exact: true })).toBeDisabled(); + }, +); 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/server-preview-app-link-stops-loading.e2e.ts b/scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts new file mode 100644 index 0000000000000..2aa4c70a1fa12 --- /dev/null +++ b/scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts @@ -0,0 +1,53 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - one fixture page for the server's browser to load +import * as NodeHttp from "node:http"; + +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +// One app link that fills the page. Its click renames the page a moment later, after the server +// has seen the link's request. +const PAGE = ` +Note link +
    Open the note`; + +test( + "An app link clicked in the Browser leaves the page shown and loaded", + WEB, + async ({ t3, app, browser, screen }) => { + const server = NodeHttp.createServer((_request, response) => { + response.writeHead(200, { "content-type": "text/html" }); + response.end(PAGE); + }); + 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 url = `http://127.0.0.1:${address.port}/`; + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Note check", messages: ["first"] }); + await t3.open(thread); + + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + const addressBar = screen.getByRole("textbox", "Search or enter URL"); + await addressBar.fill(url); + await browser.keyboard.press("Enter"); + await expect(screen.getByText("Note link")).toBeVisible(); + + // The page draws on the canvas beside its input proxy. + await browser.locator('canvas:has(~ textarea[aria-label="Browser page"])').tap(); + try { + // Chromium hands the link to the OS and keeps the page, which goes on renaming itself. + await expect(screen.getByText("Link clicked")).toBeVisible({ timeout: 2_000 }); + await expect(addressBar).toHaveValue(url); + await expect(screen.getByRole("button", "Refresh", { exact: true })).toBeVisible(); + } finally { + await app.screenshot("after-click"); + } + } finally { + await new Promise((resolve) => server.close(resolve)); + } + }, +); diff --git a/scripts/scenarios/side-panel-preserves-reading-position.e2e.ts b/scripts/scenarios/side-panel-preserves-reading-position.e2e.ts new file mode 100644 index 0000000000000..5a86da06aae41 --- /dev/null +++ b/scripts/scenarios/side-panel-preserves-reading-position.e2e.ts @@ -0,0 +1,124 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const text = Array.from( + { length: 70 }, + (_, index) => + `Sentence ${index + 1}. Opening a side panel should keep the sentence being read visible while the text wraps to the available width. `, +).join(""); + +test( + "Opening a side panel preserves the visible text in the conversation and draft", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ + project, + title: "Reading position", + messages: ["Start"], + model: "multi-turn", + }); + await browser.setViewport({ width: 1440, height: 1000 }); + await t3.open(thread); + await screen.getByRole("button", "Toggle thread details panel").tap(); + await screen.getByRole("textbox").fill(text); + await screen.getByRole("textbox").press("Enter"); + await screen.getByText("second fixture turn complete", { exact: false }).waitFor(); + await screen.getByRole("button", "Show full message").tap(); + + const position = (draft: boolean, place: boolean) => + browser.evaluate( + async ({ draft, place }) => { + const scroller = document.querySelector( + draft ? ".composer-tiptap" : ".messages-timeline-scroll", + )!; + const content = draft + ? scroller + : Array.from(scroller.querySelectorAll("[data-user-message-body]")).find( + (body) => (body.textContent?.length ?? 0) >= 3000, + ); + if (!content) throw new Error("The long message is not rendered"); + const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT); + let node = walker.nextNode(); + while (node && (node.textContent?.length ?? 0) < 3000) node = walker.nextNode(); + if (!node) throw new Error("The long paragraph is not rendered"); + const range = document.createRange(); + range.setStart(node, 2500); + range.collapse(true); + if (place) { + scroller.blur(); + scroller.scrollTop += + range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - 48; + } + await new Promise((resolve) => + requestAnimationFrame(() => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ), + ); + return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top; + }, + { draft, place }, + ); + + const point = await browser.evaluate(() => { + const box = document.querySelector(".messages-timeline-scroll")!.getBoundingClientRect(); + return { x: box.left + box.width / 2, y: box.top + 150 }; + }); + await browser.mouse.move(point.x, point.y); + await browser.mouse.wheel(0, -800); + // The wheel's native scroll completes asynchronously before positioning the fixture text. + await browser.evaluate( + () => + new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve(null))), + ), + ); + let timelineBefore = await position(false, true); + if (Math.abs(timelineBefore - 48) > 2) timelineBefore = await position(false, true); + if (Math.abs(timelineBefore - 48) > 2) + throw new Error(`The conversation did not settle at the reading position: ${timelineBefore}`); + await app.screenshot("conversation-panel-closed"); + await screen.getByRole("button", "Toggle right panel").tap(); + const timelineAfter = await position(false, false); + await app.screenshot("conversation-panel-open"); + await screen.getByRole("button", "Toggle right panel").tap(); + + await screen.getByRole("textbox").fill(text); + const draftBefore = await position(true, true); + if (Math.abs(draftBefore - 48) > 2) + throw new Error("The draft did not settle at the reading position"); + await app.screenshot("draft-panel-closed"); + await screen.getByRole("button", "Toggle right panel").tap(); + const draftAfter = await position(true, false); + await app.screenshot("draft-panel-open"); + + // The panel shortcut is pressed inside the focused draft, with a caret and then a selection. + const shortcutShifts: number[] = []; + for (const length of [0, 20]) { + const shortcutBefore = await browser.evaluate((length) => { + const scroller = document.querySelector(".composer-tiptap")!; + scroller.focus(); + const node = document.createTreeWalker(scroller, NodeFilter.SHOW_TEXT).nextNode()!; + document.getSelection()!.setBaseAndExtent(node, 2500, node, 2500 + length); + const range = document.createRange(); + range.setStart(node, 2500); + scroller.scrollTop += + range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - 48; + return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top; + }, length); + await browser.keyboard.press("Control+Alt+B"); + shortcutShifts.push(Math.abs((await position(true, false)) - shortcutBefore)); + await app.screenshot(length === 0 ? "draft-caret-shortcut" : "draft-selection-shortcut"); + } + + expect( + Math.max( + Math.abs(timelineAfter - timelineBefore), + Math.abs(draftAfter - draftBefore), + ...shortcutShifts, + ), + ).toBeLessThan(30); + }, +); diff --git a/scripts/scenarios/start-app.ts b/scripts/scenarios/start-app.ts index 5dc7de2460996..d635f1ba0fd64 100644 --- a/scripts/scenarios/start-app.ts +++ b/scripts/scenarios/start-app.ts @@ -39,9 +39,13 @@ const REAL_PROVIDERS = [ ]; /** Captures must not depend on, or show, the machine that made them. */ +/** Where a scenario serves a fake Linear API; nothing listens there unless one does. */ +export const SCENARIO_LINEAR_PORT = 13_997; + export const SCENARIO_MACHINE_ENV = { T3CODE_ENVIRONMENT_LABEL: "Scenario", T3CODE_ENVIRONMENT_MACHINE_KIND: "laptop", + T3CODE_LINEAR_API_URL: `http://127.0.0.1:${SCENARIO_LINEAR_PORT}/graphql`, }; const encodeSettings = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); diff --git a/scripts/scenarios/steered-compact-waits-for-turn.e2e.ts b/scripts/scenarios/steered-compact-waits-for-turn.e2e.ts new file mode 100644 index 0000000000000..7ed990805fd22 --- /dev/null +++ b/scripts/scenarios/steered-compact-waits-for-turn.e2e.ts @@ -0,0 +1,71 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +const SettingsJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)); +const decodeSettings = Schema.decodeEffect(SettingsJson); +const encodeSettings = Schema.encodeEffect(SettingsJson); + +const threadRuntimeSettings = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const settingsPath = (yield* Path.Path).join(T3_HOME, "userdata/settings.json"); + const original = yield* fs.readFileString(settingsPath); + const settings = yield* decodeSettings(original); + return { + supervise: fs.writeFileString( + settingsPath, + yield* encodeSettings({ ...settings, defaultRuntimeMode: "approval-required" }), + ), + restore: fs.writeFileString(settingsPath, original), + }; +}); + +test("/compact sent while the agent works waits for the turn", WEB, async ({ t3, app, screen }) => { + const project = await t3.project("demo"); + // The showcase recording streams for several seconds, long enough to send into its turn. + const thread = await t3.thread({ + project, + title: "Long work", + messages: ["Show me around"], + model: "showcase", + }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.tap(); + await composer.pressSequentially("Show me again"); + await composer.press("Enter"); + await expect(screen.getByRole("button", "Stop generation")).toBeVisible(); + + // The trailing space closes the slash menu so Enter sends instead of picking a command. + await composer.pressSequentially("/compact "); + await composer.press("Enter"); + await app.screenshot("compact-sent"); + await expect(screen.getByRole("button", "Edit queued message")).toBeVisible(); + + const settings = await runPromise(threadRuntimeSettings); + try { + // An approval holds this turn open, so the queued command stays put while Send now is hovered. + await runPromise(settings.supervise); + const waiting = await t3.thread({ + project, + title: "Waiting work", + messages: ["Change the file"], + model: "approval", + }); + await runPromise(makeState(T3_HOME).cli(["thread", "send", waiting.threadId, "/compact"])); + await t3.open(waiting); + await screen.getByRole("button", "Send now").hover(); + await expect( + screen.getByText("Move this command to the front of the queue", { exact: false }), + ).toBeVisible(); + await app.screenshot("send-now-tooltip"); + } finally { + await runPromise(settings.restore); + } +}); diff --git a/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts b/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts new file mode 100644 index 0000000000000..1f93e154b89e2 --- /dev/null +++ b/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts @@ -0,0 +1,51 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A worktree thread stopped mid-turn and moved to the project checkout runs its next message", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + // The question recording waits for an answer, so the turn is running in its new worktree. + const started = await runPromise( + makeState(T3_HOME).cli( + [ + "thread", + "start", + project, + "Ask me something", + "--worktree", + "main", + "--provider", + "devReplay", + "--model", + "question", + "--wait", + "--json", + ], + [2], + ), + ); + await t3.open(JSON.parse(started.stdout) as { threadId: string }); + + const stop = screen.getByRole("button", "Stop generation"); + await stop.waitFor({ timeout: 60_000 }); + await stop.tap(); + await stop.waitFor({ state: "hidden" }); + + await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').click(); + await screen.getByRole("option", /^main\b/).tap(); + // The server has moved the thread to the project checkout before the send. + await browser + .locator('[aria-label^="Run context:"][aria-label$="Local checkout"]') + .waitFor({ timeout: 60_000 }); + + await screen.getByRole("textbox").fill("Once more"); + await screen.getByRole("textbox").press("Enter"); + await screen.getByText("Once more").first().waitFor(); + await expect(stop).toBeVisible({ timeout: 60_000 }); + await app.screenshot("running-in-checkout"); + }, +); diff --git a/scripts/scenarios/terminal-latched-modifier-reads-selected.e2e.ts b/scripts/scenarios/terminal-latched-modifier-reads-selected.e2e.ts new file mode 100644 index 0000000000000..5ee593a409190 --- /dev/null +++ b/scripts/scenarios/terminal-latched-modifier-reads-selected.e2e.ts @@ -0,0 +1,41 @@ +import { expect } from "e2e"; + +import { MOBILE } from "../e2e.config.ts"; +import { environmentId, runPromise } from "./t3.ts"; +import { IOS, test } from "./t3-mobile.ts"; + +test( + "A latched terminal ctrl key reads as selected to iOS accessibility", + IOS, + async ({ t3, app, screen, device }) => { + const project = await t3.project("demo"); + const { threadId } = await t3.thread({ project, title: "Latched keys", messages: ["hello"] }); + await t3.open(); + await screen.getByText("Latched keys", { exact: false }).first().waitFor({ timeout: 120_000 }); + + const environment = await runPromise( + environmentId(`http://${MOBILE.host}:${MOBILE.serverPort}`), + ); + await device.openLink(`t3code-dev://threads/${environment}/${threadId}/terminal`, { + app: "com.t3tools.t3code.dev", + }); + await device.alert("accept").catch(() => {}); + + // The keyboard toolbar shows with the software keyboard; ctrl starts past its right edge. + const esc = screen.getByRole("button", "esc"); + await esc.waitFor({ timeout: 60_000 }); + const box = await esc.boundingBox(); + const x = (box?.x ?? 0) + (box?.width ?? 0); + const y = (box?.y ?? 0) + (box?.height ?? 0) / 2; + // A slow drag, so the scroller stops with ctrl in view instead of flinging to its end. + await screen.swipe({ from: { x, y }, to: { x: x - 150, y }, duration: 1_500 }); + const ctrl = screen.getByRole("button", "ctrl"); + await ctrl.waitFor(); + await ctrl.tap(); + await app.screenshot("ctrl-latched"); + await expect(ctrl).toBeSelected(); + + await ctrl.tap(); + await expect(ctrl).not.toBeSelected(); + }, +); 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(" +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import JSZip from "jszip"; + +import { test, WEB } from "./t3.ts"; + +const SHEETS = ["Overview", "Actuals", "Forecast"]; +const RELATIONSHIPS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + +async function workbook() { + const archive = new JSZip(); + const sheets = SHEETS.map( + (name, index) => ``, + ).join(""); + archive.file( + "xl/workbook.xml", + `${sheets}`, + ); + const relationships = SHEETS.map( + (_, index) => + ``, + ).join(""); + archive.file("xl/_rels/workbook.xml.rels", `${relationships}`); + for (const [index] of SHEETS.entries()) + archive.file( + `xl/worksheets/sheet${index + 1}.xml`, + `${index + 1}`, + ); + return archive.generateAsync({ type: "uint8array" }); +} + +test( + "Two rapid right arrows advance two tabs in an Excel preview", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "budget.xlsx": await workbook() }); + const archive = await JSZip.loadAsync(await workbook()); + const manifest = (await archive.file("xl/workbook.xml")!.async("string")).replace( + ' { + const first = document.querySelector( + '[role="tablist"] [role="tab"][aria-selected="true"]', + )!; + first.focus(); + for (let press = 0; press < 2; press++) + document.activeElement?.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }), + ); + return null; + }); + await screen.getByRole("grid", /Actuals|Forecast/).waitFor(); + await app.screenshot("after-two-right-arrows"); + await expect + .poll(() => + browser.evaluate( + () => + document + .querySelector('[role="tablist"]') + ?.parentElement?.querySelector('[role="grid"]') + ?.getAttribute("aria-label") ?? null, + ), + ) + .toBe("Forecast"); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("wraparound.xlsx"); + await screen.getByRole("option", "wraparound.xlsx", { exact: false }).tap(); + await browser + .locator('[data-active-tab="true"]') + .getByText("wraparound.xlsx", { exact: true }) + .waitFor(); + const overview = screen.getByRole("tab", "Overview"); + await overview.waitFor(); + + const { ok: showSucceeded, selectedAtSecondPress } = await browser.evaluate(async () => { + const first = document.querySelector( + '[role="tablist"] [role="tab"][aria-selected="true"]', + )!; + const pressRight = () => + document.activeElement?.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }), + ); + const postMessage = Worker.prototype.postMessage; + return await new Promise<{ ok: boolean; selectedAtSecondPress: string | null }>((resolve) => { + Worker.prototype.postMessage = function ( + this: Worker, + message: { method?: string; id?: number }, + options?: Transferable[] | StructuredSerializeOptions, + ) { + if (message.method === "show") { + Worker.prototype.postMessage = postMessage; + const onReply = (event: MessageEvent<{ id: number; ok: boolean }>) => { + if (event.data.id !== message.id) return; + this.removeEventListener("message", onReply); + if (event.data.ok !== true) { + resolve({ ok: false, selectedAtSecondPress: null }); + return; + } + // The worker client has queued the first layout, and React has yet to commit it. + queueMicrotask(() => { + const selected = first.getAttribute("aria-selected"); + pressRight(); + resolve({ ok: true, selectedAtSecondPress: selected }); + }); + }; + this.addEventListener("message", onReply); + } + Reflect.apply(postMessage, this, [message, options]); + }; + first.focus(); + pressRight(); + }); + }); + expect(showSucceeded).toBe(true); + expect(selectedAtSecondPress).toBe("true"); + await expect(overview).toBeFocused(); + await app.screenshot("after-wrapping-to-overview"); + await expect(overview).toHaveAttribute("aria-selected", "true"); + await expect(screen.getByRole("grid", "Overview")).toBeVisible(); + }, +); diff --git a/skills/t3-workflows/SKILL.md b/skills/t3-workflows/SKILL.md new file mode 100644 index 0000000000000..7f600e0b4cee5 --- /dev/null +++ b/skills/t3-workflows/SKILL.md @@ -0,0 +1,353 @@ +--- +name: t3-workflows +description: Author, edit, run, and debug durable T3 Code workflows (`~/.t3/workflows/*.ts`). Use when asked to build or change a multi-step T3 Code automation tying together agent threads, code steps, schedules, webhooks, issue/PR trackers, or human approvals, or to inspect, resume, signal, or cancel workflow runs. +--- + +# T3 Code workflows + +A workflow is a TypeScript function the T3 Code server runs durably on Effect v4 (`effect/workflow`). Every step's result is stored, so restarts replay to where the run left off and a failing step pauses the run instead of losing it. Runs can sleep for days, wait on signals or pull requests, ask a person a question, and launch agents in ordinary threads. + +Use a workflow for multi-stage work that must not be lost or repeated (triage → fix → verify, nightly reports, webhook reactions). For a single prompt on a timer, use a scheduled task instead. + +## Quick start + +Workflows are a Labs feature, off by default. If `t3 workflow` says workflows are off, ask the user to turn them on in Settings → Labs → Workflows; do not edit their settings yourself. + +Put a `.ts` file in `~/.t3/workflows/` (the `workflows` folder of T3 home, or the path in `T3CODE_WORKFLOWS`). Once workflows are on, the server watches the folder and reloads files automatically—nothing to restart. A file name with a space or other unusual character (`fix issue.ts`) is skipped with a warning in the server log: use letters, digits, `-`, `_` and `.`. Files run with Node's type stripping, so only erasable TypeScript works: no `enum`, `namespace` or parameter properties. + +Workflow files import nothing from T3 or Effect. `T3`, `Effect`, `Schema`, `Option`, `Duration`, and `Schedule` are injected as globals. Never `import` from `effect` (that loads a second runtime copy the engine cannot run). Node built-ins (`node:fs`, `node:crypto`) can be imported normally. + +```ts +const { workflow, agent, ask, stop, title, every, Tick } = T3; + +workflow( + "dependency-report", + { version: 1, payload: Tick, triggers: [every("1 day")] }, + Effect.fn(function* (tick) { + yield* title(`Dependencies ${tick.scheduledAt.slice(0, 10)}`); + + const audit = yield* agent("audit", { + project: "/home/me/app", // the project's folder, or its id + brief: "List this repository's outdated dependencies. Do not change any file.", + returns: Schema.Struct({ + outdated: Schema.Array(Schema.Struct({ name: Schema.String, latest: Schema.String })), + }), + }); + if (audit.value.outdated.length === 0) return yield* stop("nothing is outdated"); + + const answer = yield* ask("approve-upgrade", { + title: `Upgrade ${audit.value.outdated.length} dependencies?`, + choices: ["upgrade", "skip"], + data: audit.value, + timeout: "2 days", + }); + if (Option.isNone(answer) || answer.value.choice === "skip") { + return yield* stop("not approved"); + } + + yield* agent("upgrade", { + thread: audit.thread, + brief: "Upgrade the dependencies you listed, run the tests, and say what changed.", + }); + }), +); +``` + +### What `T3` holds + +Only `T3`, `Effect`, `Schema`, `Option`, `Duration` and `Schedule` are globals. Everything below is a +property of `T3`: take what you use at the top of the file, as the quick start does +(`const { workflow, step, daily } = T3;`), or write `T3.step(…)` in full. A bare `daily(…)` or +`step(…)` without that line is a `ReferenceError`. + +- **Definitions & body**: `workflow`, `step`, `agent`, `ask`, `wait`, `sleep`, `title`, `stop`, `skip`, `invoke` +- **Inside `step` / `onEnd` only**: `store`, `signal`, `signalAll`, `start`, `runs`, `cancel` +- **Trackers & hosts**: `issues`, `pullRequests` (triggers, step calls, and `pullRequests.wait` in the body) +- **Triggers**: `every`, `daily`, `webhook` +- **Schemas**: `Tick`, `WebhookRequest`, `Issue`, `IssueDetail`, `PullRequest`, `PullRequestStanding` + +### Effect v4 `Schema` cheatsheet + +```ts +Schema.String; +Schema.Number; +Schema.Boolean; +Schema.Void; +Schema.Null; +Schema.Struct({ name: Schema.String, count: Schema.optional(Schema.Number) }); +Schema.Array(Schema.String); +Schema.Literals(["open", "closed"]); +Schema.NullOr(Schema.String); +Schema.Record(Schema.String, Schema.Number); // two arguments, not an object +``` + +## Defining a workflow + +`workflow(name, options, body)` registers a workflow and returns a handle you can pass to `invoke`, `start`, `runs`, or `signal`. Each `(name, version)` pair must be unique across all files. + +| Option | Required | Meaning | +| ------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `version` | Yes | Integer version. Raise it whenever the body changes (see rules below). | +| `payload` | Yes | `Schema` of the run's input. | +| `returns` | No | `Schema` of the body's return value. If omitted, any JSON value (or `undefined`) is accepted. | +| `triggers` | No | Array of triggers that start runs automatically. | +| `resumeAfter` | No | Durations to wait before auto-resuming a paused run. Defaults to `["5 minutes", "20 minutes", "80 minutes"]`. The server checks about every 15 seconds, so shorter waits act as 15 seconds. | +| `onEnd` | No | `(payload, { id, outcome, reason }) => Effect`: cleanup hook run once when the run ends. | + +The body is `Effect.fn(function* (payload, run) { … })`, where `run.id` is the run's id. Use `yield*` on every primitive. + +### Cleanup with `onEnd` + +`onEnd` runs once when a run completes, stops, is skipped, or is cancelled—not when it pauses. It runs with step services (`store`, `signal`, `issues`, etc.), receives `(payload, { id, outcome, reason })`, and cannot see local variables from the body. Name external resources after `run.id`, and make `onEnd` safe if the run was cancelled before acquiring anything. + +```ts +const { workflow, step, agent, Issue } = T3; + +workflow( + "fix", + { + version: 1, + payload: Issue, + onEnd: (issue, end) => exec("machines.sh", ["delete", `fix-${end.id}`]), + }, + Effect.fn(function* (issue, run) { + const environment = yield* step( + "machine", + { returns: Schema.String }, + exec("machines.sh", ["create-and-link", `fix-${run.id}`]), + ); + yield* agent("fix", { environment, project: "/home/user/app", brief: issue.title }); + }), +); +``` + +(`exec` above is your own Effect helper, not part of `T3`.) On normal end, `onEnd` retries 3 times before pausing at the `onEnd` step; on cancel, it waits for any in-flight step to finish, then tries up to 5 times, 5 minutes, 20 minutes, 80 minutes and 5 hours apart. The workflow version stays required until one try succeeds; after the last failed try the `onEnd` step stays `failed` on the run and nothing retries it, so make cleanup something a person can redo by hand. + +## Body primitives + +Call these directly in the workflow body with `yield*`. Every named primitive stores its result under `name`, which must be unique across all primitives in the run (an `ask("fix", …)` and `agent("fix", …)` collide). + +| Call | Behavior | Returns | +| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- | +| `step(name, { returns, retry? }, effect)` | Runs code once per run and journals the result. Failure pauses the run. | `A` | +| `step.try(name, { returns, retry? }, effect)` | Same as `step`, but returns failure as data instead of pausing. | `{ outcome: "done", value }` or `{ outcome: "failed", reason }` | +| `agent(name, { brief, project? \| thread?, returns?, … })` | Runs an agent in a thread. Failure pauses the run for a person. | `{ value, thread }` (`value` matches `returns`, or last reply string) | +| `agent.try(name, { brief, project? \| thread?, returns?, … })` | Same as `agent`, but returns failure as data instead of pausing. | `{ outcome: "done", value, thread }` or `{ outcome: "failed", reason, thread? }` | +| `ask(name, { title, choices, data?, timeout? })` | Puts a multiple-choice question to a person. | `Option<{ choice, reason? }>` (`None` on timeout) | +| `wait(name, { returns, timeout?, channel? })` | Sleeps until signalled by `{ runId, wait }` or `{ workflow, channel }`. | `Option` (`None` on timeout) | +| `pullRequests.wait(name, pr, { until, timeout? })` | Sleeps until PR checks settle, or the PR merges or closes. | `Option` (`None` on timeout) | +| `sleep(name, duration)` | Durable sleep across restarts (e.g. `"1 hour"`, `"2 days"`). | `void` | +| `invoke(name, workflow, payload, { key? })` | Runs another workflow as a child run and waits for it to end. | `{ outcome: "completed", value }` or `{ outcome: "stopped" \| "skipped" \| "cancelled", reason }` | +| `title(text)` | Sets the run's display title in lists (cut to 200 characters). Takes no step name. | `void` | +| `stop(reason)` | Ends the run on purpose as `stopped` (not a failure). Body only: inside a `step` it fails the step and pauses the run, and so does `skip`. | `never` | +| `skip(reason)` | Ends the run as `skipped`, which run lists leave out unless asked (`runs()` includes them). | `never` | + +- **Retries and failures:** A `step` runs once by default. For idempotent work, pass `retry: { times: 3, schedule: Schedule.exponential("2 seconds") }`. Nothing in the body can catch a failed `step` or `agent` because the engine pauses the run—use `step.try` or `agent.try` whenever the workflow should branch on failure. +- **Timeouts are checked about every 15 seconds:** a `wait` or `ask` timeout can end up to 15 seconds late, and a signal that arrives before the check still wins. +- **`Option` results:** `wait`, `ask` and `pullRequests.wait` always give an `Option`, with or without a `timeout`. Check `Option.isNone(result)` first, then read `result.value`. Never put the `Option` itself into a string or a return value. +- **Concurrency:** Run steps or agents in parallel with `Effect.all([agent("a", …), agent("b", …)], { concurrency: 2 })`. +- **Strict options:** Every call refuses an option it does not take, naming the ones it does, since workflow files are not type-checked. So does `every` under a minute and a `daily` time it cannot read. + +## Agents (`agent` and `agent.try`) + +| Option | Applies to | Meaning | +| ----------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `brief` | All | Full task instructions. The agent sees only this brief and its project. | +| `project` | New thread | Project id (from `t3_project_list`) or absolute folder path. | +| `thread` | Continue | `thread` returned by an earlier `agent` step. Continues it as it started, so the New thread options are refused alongside it. | +| `returns` | All | Optional `Schema`. Completes only when the agent submits valid data (up to 2 correction prompts). | +| `model` | New thread | `{ instanceId, model, options? }`; `options` is `[{ id, value }]` (e.g. `[{ id: "reasoningEffort", value: "high" }]`). Defaults to project default. | +| `workspace` | New thread | `{ type: "root" }` (default) or `{ type: "worktree", baseRef: "origin/main", startFromOrigin: true }`. | +| `runtimeMode` | New thread | `"full-access" \| "auto" \| "auto-accept-edits" \| "approval-required"` (waits on thread approvals). Project default if omitted. | +| `interactionMode` | New thread | `"default" \| "plan"`. | +| `title` | New thread | Thread title. Defaults to `: `. | +| `environment` | New thread | Linked environment id (`t3 environment list`). Folder paths not yet registered there are registered automatically. | +| `issue` | Local only | `Issue` or `{ project, url }`. Links the thread to that issue (not applied in linked environments). | +| `timeout` | All | Time limit for each attempt (e.g. `"2 hours"`); an automatic retry or a resume starts a new one. Past it, the turn is stopped and the step fails. | +| `quiet` | All | Idle grace period (e.g. `"45 minutes"`) for agents that wait across turns before submitting `returns`. | + +- **Worktrees:** Use a `worktree` workspace whenever two agents can edit the same repo at once (concurrent runs or parallel `agent` calls). +- **Waiting across turns (`quiet`):** If an agent watches PR checks or background work and ends its turn while waiting to be woken, set `quiet: "45 minutes"` and tell it in `brief` to end waiting turns without submitting. The step prompts for the result only after the thread has been idle for `quiet`. Without `quiet`, it prompts as soon as a turn ends without output. Always set a `timeout` alongside `quiet`. +- **Retries and pauses:** If a turn dies (crashes or is cut off), `agent` automatically tries once more (on a fresh thread, or the same thread if continuing `thread`). An agent that finishes its turn without valid `returns` is asked to correct it twice in the same thread, and then gives up without starting the job again. A timeout or manual stop does not auto-retry. A run paused by an agent that ran and gave up or timed out waits for a person—`resumeAfter` does not auto-resume it (`t3 workflow resume` starts a fresh attempt). An agent that could not be started at all (no project at that folder, linked environment unreachable) pauses like a failed `step` and resumes on its own; `agent.try` returns that failure as data instead. +- **Fallback with `agent.try`:** + +```ts +Effect.fn(function* () { + let fix = yield* agent.try("fix", { project, brief, returns: Fix, timeout: "2 hours" }); + if (fix.outcome === "failed") { + fix = yield* agent.try("fix-again", { project, brief, returns: Fix, model: stronger }); + } + if (fix.outcome === "failed") return yield* stop(`no fix: ${fix.reason}`); +}); +``` + +- **Linked environments:** Enable Settings → Labs → Linked environments. The run stays on this server; only the thread runs remotely, bounded by the link's paired access. For a machine per run, create and link it in a `step` (`t3 auth pairing create --json` on the remote, `t3 environment link --pairing-code --access ` here), return its id, and delete it in `onEnd`. + +## Other workflows + +Define caller and callee in the same file and keep the callee in a variable so its payload and return type flow through: + +```ts +const { workflow, invoke, stop } = T3; + +const review = workflow("review", { version: 1, payload: Change, returns: Verdict }, reviewBody); + +workflow( + "fix", + { version: 1, payload: Issue }, + Effect.fn(function* (issue) { + const ended = yield* invoke("review", review, { branch: `fix/${issue.key}` }); + if (ended.outcome !== "completed") { + return yield* stop(`review ${ended.outcome}: ${ended.reason}`); + } + return ended.value; // Verdict + }), +); +``` + +| Call | Where | Behavior | +| ------------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `invoke(name, workflow, payload, { key? })` | Body | Starts a child run and waits for it (including while it is paused). Listed and resumed independently; cancelling the parent cancels the child. Pass the definition `workflow(…)` returned, not its name. `key` names the child run; one already started under that key by something else is refused. | +| `start(workflow, payload, { key })` | `step` / `onEnd` | Fire-and-forget. Returns `{ runId }`. Same `key` returns the same run. Use for fan-out. | +| `runs({ workflow?, status?, keyPrefix? })` | `step` / `onEnd` | Lists up to 500 matching runs (skipped runs included), newest first: `{ id, workflow, key, title, status, detail, startedAt, endedAt }`. `workflow` is a definition or its name. | +| `cancel(runId, reason)` | `step` / `onEnd` | Cancels another run (stops agents, withdraws questions, cancels invoked children, runs `onEnd`). Cannot cancel self—use `stop`. | + +End subject keys with a separator (e.g. `issue/412/`), so `runs({ workflow: fix, keyPrefix: "issue/412/" })` does not match `issue/4120`. + +## Store and signals + +`store` holds durable key-value state shared across all workflows on the server (cursors, switches, counters, queues). Call `store`, `signal`, and `signalAll` **only inside `step` or `onEnd`**—never directly in the body. + +| Call | Behavior | +| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `store.entry(key, Schema)` | Handle for one key: `.get` (`Option`), `.set(value)`, `.delete`. | +| `entry.update((current) => next)` | Atomic read-modify-write; `current` is `Option`. Return `undefined` to delete. Returns `Option`. | +| `store.entries(prefix, Schema)` | Every `{ key, value }` starting with `prefix`, in key order. Fails if any matching row does not fit `Schema`. | +| `store.transaction(effect)` | Runs all store reads and writes in `effect` atomically (all or nothing). | +| `signal(address, value, { id?, ttl? })` | Wakes one `wait` at `{ runId, wait }` or `{ workflow, channel }`. Buffered until a wait opens or `ttl` (default 7 days) expires. Returns `"delivered" \| "buffered"`. `"buffered"` checks neither the address nor the shape: a wrong workflow or wait name, or a run that has ended, also buffers. A value that does not fit an open wait fails the sending step. | +| `signalAll({ channel, workflow? }, value)` | Wakes every run currently waiting on `channel` (one workflow or all). Returns count woken. Buffers nothing. | + +```ts +const { step, store, Issue } = T3; +const seen = store.entry("issues/seen", Schema.String); + +Effect.fn(function* () { + const fresh = yield* step( + "fetch", + { returns: Schema.Array(Issue) }, + Effect.gen(function* () { + const since = yield* seen.get; + const batch = yield* fetchIssuesAfter(Option.getOrUndefined(since)); + if (batch[0]) yield* seen.set(batch[0].createdAt); + return batch; + }), + ); +}); +``` + +- **Shared gate pattern (`signalAll`):** Because `signalAll` keeps nothing for late arrivals, check the switch in a `step`, then while it is on call `wait` with `{ channel: "main-green", timeout: "10 minutes", returns: Schema.Null }` and re-check in a loop. Number step names per iteration (`switch/1`, `released/1`, `switch/2`, `released/2`). Whoever clears the switch calls `signalAll({ channel: "main-green" }, null)`. +- **Transactions:** Use `entry.update` or `store.transaction` whenever a write depends on a read, or when a step might fail after writing. +- **CLI access:** Inspect or flip keys with `t3 workflow store list [prefix]`, `store set ''`, and `store delete `. + +## Issues and pull requests + +Reads and writes the project's configured tracker (GitHub, GitLab, Linear, etc.) and git host using the project's credentials. Pass an issue/PR object from a trigger or `list`, or `{ project, url }` (useful when an agent returns a URL). + +| Call | Where | Returns | +| ----------------------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------- | +| `issues.list({ project, state?, labels?, query?, assignee?, sort?, limit? })` | `step` / `onEnd` | `Issue[]` (`state` defaults to `"open"`) | +| `issues.read(issue)` | `step` / `onEnd` | `IssueDetail` (body, comments, valid `states`) | +| `issues.comment(issue, body)` | `step` / `onEnd` | `void` | +| `issues.setState(issue, name)` | `step` / `onEnd` | `void` (`name` from `issues.read(issue).states`) | +| `issues.create({ project, title, body?, labels?, assignees? })` | `step` / `onEnd` | `{ key, displayKey, url }` | +| `pullRequests.list({ project, state?, query?, limit? })` | `step` / `onEnd` | `PullRequest[]` (`state` defaults to `"open"`) | +| `pullRequests.read(pr)` | `step` / `onEnd` | State, checks, reviews, mergeability | +| `pullRequests.comment(pr, body)` | `step` / `onEnd` | `void` | +| `pullRequests.act(pr, action, { mergeMethod? })` | `step` / `onEnd` | `void` (`merge`, `close`, `ready`, `update-branch`, etc.) | +| `pullRequests.wait(name, pr, { until, timeout? })` | **Body** | `Option` (`{ state, checks, mergeability, url }`) | + +Keep one comment or mutation per `step` so a retry does not post twice. + +```ts +const { workflow, title, agent, step, issues, Issue } = T3; + +workflow( + "triage", + { version: 1, payload: Issue, triggers: [issues.opened({ project: "/home/me/app" })] }, + Effect.fn(function* (issue) { + yield* title(`${issue.displayKey} ${issue.title}`); + const found = yield* agent("reproduce", { + project: "/home/me/app", + issue, + brief: `Reproduce this on main. Change nothing.\n\n${issue.url}`, + returns: Schema.Struct({ reproduced: Schema.Boolean, summary: Schema.String }), + }); + yield* step("report", { returns: Schema.Void }, issues.comment(issue, found.value.summary)); + }), +); +``` + +`pullRequests.wait` polls about once a minute. `until` is `"checks"` (no checks still pending), `"merged"`, or `"closed"`. Merging or closing ends any wait, so always check `state` before `checks` (`"passing" | "failing" | "pending" | "none"`): + +```ts +Effect.fn(function* () { + const at = yield* pullRequests.wait( + "checks", + { project, url }, + { until: "checks", timeout: "2 hours" }, + ); + if (Option.isNone(at) || at.value.state !== "open" || at.value.checks !== "passing") { + return yield* stop("not ready to merge"); + } + yield* step("merge", { returns: Schema.Void }, pullRequests.act({ project, url }, "merge")); +}); +``` + +## Triggers + +A workflow's `payload` schema must match what its `triggers` emit. + +| Trigger | Payload | Notes | +| ------------------------------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `every("1 hour")` | `Tick` | `{ scheduledAt }`. Minimum 1 minute. The first run comes one interval after the file loads, not at load. Downtime collapses into one run, not one per missed interval. | +| `daily("09:00", { weekdays?: [1, 2, 3, 4, 5] })` | `Tick` | Server local time; `0` is Sunday. Missed by more than 10 minutes is skipped. | +| `webhook("name", { key? })` | `WebhookRequest` | `{ method, headers, query, body }` (lowercase header names, text `query`/`body`). Set `payload: WebhookRequest`, taken from `T3`; never write its shape out yourself. `t3 workflow hooks` prints URL paths (includes secret). A retry that repeats a delivery header (`X-GitHub-Delivery`, `Idempotency-Key`, `webhook-id`, and the Gitea, GitLab and Linear ones) starts no second run; for other senders, `key: (r) => …` names the run from the request. Bodies over 1 MiB are refused. | +| `issues.opened({ project, labels?, query? })` | `Issue` | Polls ~once a minute. Only issues opened after the workflow first loaded. Issue must carry all `labels`. | +| `pullRequests.opened({ project, query? })` | `PullRequest` | Polls ~once a minute. Only pull requests opened after the workflow first loaded. | + +Filter unwanted deliveries in the body with `skip("not a push to main")` so they stay out of run lists. Verify webhook signatures inside a `step`. + +Start any workflow manually with `t3 workflow start --input '' --key `. A `key` identifies one run of that workflow across all versions. + +## Rules you must not break + +1. **The body is replayed from the top.** After every wait or restart, the body runs again and completed primitives return their stored values. Put all side effects, I/O, clock reads, randomness, and `store`/API reads inside `step` or `agent`. Code between calls must be deterministic given `payload` and earlier results. +2. **Names are journal keys.** Every named primitive (`step`, `agent`, `ask`, `wait`, `sleep`, `invoke`, `pullRequests.wait`) must have a unique name within the run, across all kinds. Loops need distinct names (``step(`check-${i}`, …)``). Never name a body step `"onEnd"` (reserved for cleanup). `invoke("x", …)` also takes `x/start`, and `title(…)` takes `title/0`, `title/1`, …. +3. **Bump `version` when changing a live workflow.** Do not reorder, rename, or change the stored schema of steps in a version that still has unfinished runs. Register the updated body under a higher `version` and keep the old version in the file until its runs finish. Runs started by the CLI, a trigger or a webhook use the highest version; `start` and `invoke` run the version of the definition you pass them, so point callers at the new definition when you bump. Keys still deduplicate across versions. +4. **Never import `effect`, and take every `T3` name you use.** The globals are `T3`, `Effect`, `Schema`, `Option`, `Duration` and `Schedule`; `step`, `daily`, `WebhookRequest` and the rest come from `const { … } = T3;` at the top of the file, and one left out of that line is a `ReferenceError`. Shared helpers go in a subfolder (dotfiles and folders are ignored by the loader), and changing an imported helper requires a server restart. +5. **Payloads and step results must fit their `Schema`.** Everything journaled is serialized as JSON; a value that fails encoding fails the step. +6. **Steps can run more than once.** A crash mid-step, a retry, or a manual resume re-runs the step. Make external side effects idempotent (derive idempotency keys from `payload` or `run.id`, keep one comment/post per step, wrap dependent store writes in `store.transaction`). + +## Files, reloading, and CLI + +If an edited file fails to load, its last good version keeps running and the server logs `A workflow definitions file was not loaded` with the reason. A change that defines the same `(name, version)` twice or removes a version with unfinished runs is rejected. The Workflows page shows these errors, and its Definitions view validates files on save. + +```sh +t3 workflow start --input '' --key +t3 workflow list [--status paused] +t3 workflow show [--json] +t3 workflow resume +t3 workflow cancel [--reason ''] +t3 workflow questions +t3 workflow signal '{"choice":"upgrade"}' --run --wait approve-upgrade +t3 workflow signal '' --workflow --channel +t3 workflow hooks +t3 workflow store list [prefix] +t3 workflow store set '' +t3 workflow store delete +``` + +- **Run states:** `running`, `waiting` (agent, signal, question, PR wait, or sleep), `paused` (step failed), `completed`, `stopped`, `skipped`, `cancelled`. +- **Resuming:** Check the failing step and error with `show`, fix the cause, then `resume` (only the failed step re-runs). A paused run also resumes by itself on `resumeAfter` (default 5, 20, 80 minutes), unless it paused because its agent gave up. +- **Retired runs:** A run whose version was removed shows `"retired": true` in `show --json` and cannot continue until that version is restored. +- **Stuck agents:** An agent step's thread is an ordinary thread—open it to inspect or steer the agent. The step finishes as soon as the agent submits its result.