diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 92fd3d2b49b3a..658c4315a0ef8 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -310,11 +310,9 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool } const primaryBackend = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary; - // WSL-only fallback can change the primary endpoint before readiness. const config = yield* primaryBackend.currentConfig; if ( !environment.isDevelopment && - !settings.wslOnly && Option.isSome(config) && Option.isNone(config.value.preflightFailure) ) { diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts index 5dfde9103f152..b58b583fd6cd5 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts @@ -300,4 +300,66 @@ describe("DesktopConnectionCatalogStore", () => { assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}')); }).pipe(Effect.provide(NodeServices.layer)), ); + + const emptyCatalog = + '{"schemaVersion":1,"targets":[],"profiles":[],"credentials":[],"remoteDpopTokens":[],"disabledEnvironmentIds":[]}'; + const savedFilesHolding = Effect.fn(function* (stateDir: string, contents: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const kept: string[] = []; + for (const name of yield* fileSystem.readDirectory(stateDir)) { + const file = path.join(stateDir, name); + if ((yield* fileSystem.stat(file)).type !== "File") continue; + if ((yield* fileSystem.readFileString(file)) === contents) kept.push(name); + } + return kept; + }); + + it.effect("keeps a catalog this build cannot decode when the next save replaces it", () => + withStore( + Effect.gen(function* () { + const path = yield* Path.Path; + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore; + const catalogPath = path.join(environment.stateDir, "connection-catalog.json"); + assert.isTrue( + yield* store.set( + '{"schemaVersion":1,"targets":[{"_tag":"FutureConnectionTarget","environmentId":"remote"}],"profiles":[],"credentials":[],"remoteDpopTokens":[],"disabledEnvironmentIds":[]}', + ), + ); + const original = yield* fileSystem.readFileString(catalogPath); + + yield* store.get; + assert.isTrue(yield* store.set(emptyCatalog)); + + assert.isNotEmpty(yield* savedFilesHolding(environment.stateDir, original)); + }), + ), + ); + + it.effect("keeps a catalog that no longer decrypts when the next save replaces it", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-connection-catalog-test-", + }); + const failDecrypt = yield* Ref.make(false); + const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( + Effect.provide(layerFor(baseDir, true, failDecrypt)), + ); + const stateDir = path.join(baseDir, "userdata"); + assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}')); + const original = yield* fileSystem.readFileString( + path.join(stateDir, "connection-catalog.json"), + ); + + yield* Ref.set(failDecrypt, true); + yield* store.get.pipe(Effect.flip); + assert.isTrue(yield* store.set(emptyCatalog)); + + assert.isNotEmpty(yield* savedFilesHolding(stateDir, original)); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + ); }); diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts index 3240df3636e38..5db49e5f9504c 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts @@ -15,6 +15,7 @@ import { fromLenientJson } from "@t3tools/shared/schemaJson"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; +import * as Clock from "effect/Clock"; import * as Base64 from "effect/encoding/Base64"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -45,6 +46,9 @@ const RuntimeConnectionCatalogDocumentJson = Schema.fromJsonString( const encodeRuntimeConnectionCatalogDocumentJson = Schema.encodeEffect( RuntimeConnectionCatalogDocumentJson, ); +const decodeRuntimeConnectionCatalogDocumentJson = Schema.decodeEffect( + RuntimeConnectionCatalogDocumentJson, +); const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([ "create-temporary-file-name", @@ -52,6 +56,7 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([ "create-directory", "write-temporary-file", "replace-catalog-file", + "keep-unreadable-catalog", ]); const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([ @@ -395,6 +400,57 @@ export const make = Effect.gen(function* () { ), ); + const decryptDocument = (document: EncryptedConnectionCatalogDocument) => + decodeSecretBytes(catalogPath, document.encryptedCatalog).pipe( + Effect.flatMap((encryptedCatalog) => + safeStorage.decryptString(encryptedCatalog).pipe( + Effect.mapError( + (cause) => + new DesktopConnectionCatalogStoreProtectionError({ + operation: "decrypt-catalog", + catalogPath, + cause, + }), + ), + ), + ), + ); + + // A catalog this build cannot decrypt or decode may still hold another build's saved + // environments and credentials, so a save copies it aside instead of destroying it. + const keepUnreadableCatalog = Effect.gen(function* () { + const readable = yield* readDocument(fileSystem, catalogPath).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed(true), + onSome: (document) => + decryptDocument(document).pipe( + Effect.flatMap(decodeRuntimeConnectionCatalogDocumentJson), + Effect.as(true), + ), + }), + ), + Effect.orElseSucceed(() => false), + ); + if (readable) { + return; + } + const keptPath = `${catalogPath}.unreadable-${yield* Clock.currentTimeMillis}`; + yield* fileSystem.copyFile(catalogPath, keptPath).pipe( + Effect.mapError( + (cause) => + new DesktopConnectionCatalogStoreWriteError({ + operation: "keep-unreadable-catalog", + path: keptPath, + cause, + }), + ), + ); + yield* Effect.logWarning("Kept an unreadable connection catalog before replacing it.", { + keptPath, + }); + }); + const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* ( catalog: string, ) { @@ -470,26 +526,13 @@ export const make = Effect.gen(function* () { if (!(yield* encryptionAvailable)) { return Option.none(); } - const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe( - Effect.flatMap((encryptedCatalog) => - safeStorage.decryptString(encryptedCatalog).pipe( - Effect.mapError( - (cause) => - new DesktopConnectionCatalogStoreProtectionError({ - operation: "decrypt-catalog", - catalogPath, - cause, - }), - ), - ), - ), - ); - return Option.some(decrypted); + return Option.some(yield* decryptDocument(document.value)); }).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")), set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) { if (!(yield* encryptionAvailable)) { return false; } + yield* keepUnreadableCatalog; yield* writeCatalog(catalog); return true; }), diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index be4784dcba51b..f80f601473280 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -398,7 +398,7 @@ describe("DesktopBackendConfiguration", () => { runtimeId: string; sha256: string; }> = []; - const observedProbeRoots: string[] = []; + let probeCount = 0; let legacyCleanupCount = 0; const linuxAppRoot = "/home/test/.t3/wsl-runtime/1.2.3-x64"; const resolvedPath = "/home/test/.local/bin:/usr/bin:/bin"; @@ -419,8 +419,8 @@ describe("DesktopBackendConfiguration", () => { }); return { ok: true, linuxAppRoot }; }, - probeRuntime: (_distro, root) => { - observedProbeRoots.push(root); + probeRuntime: () => { + probeCount += 1; return { ok: true, resolvedPath }; }, ensureNodePty: () => { @@ -441,7 +441,7 @@ describe("DesktopBackendConfiguration", () => { sha256: archiveHash, }, ]); - assert.deepEqual(observedProbeRoots, [linuxAppRoot]); + assert.equal(probeCount, 1); assert.equal( config.entryPath, path.join(baseDir, "server.asar/apps/server/dist/bin.mjs"), @@ -536,10 +536,10 @@ describe("DesktopBackendConfiguration", () => { ); }); - it.effect("resolveWsl retires a staged runtime whose executable does not start", () => { + it.effect("resolveWsl retires a staged runtime whose launch probe fails", () => { const archiveHash = "c".repeat(64); const stagedAppRoot = `/home/test/.t3/wsl-runtime/sha256-${archiveHash}`; - const observedProbeRoots: string[] = []; + let probeCount = 0; const observedNodePtyRoots: string[] = []; const invalidatedRuntimeIds: string[] = []; return withPackagedWslHarness( @@ -551,9 +551,9 @@ describe("DesktopBackendConfiguration", () => { Effect.sync(() => { invalidatedRuntimeIds.push(runtimeId); }), - probeRuntime: (_distro, root) => { - observedProbeRoots.push(root); - return { ok: false, reason: `${root}/t3 --version failed (exit 127)` }; + probeRuntime: () => { + probeCount += 1; + return { ok: false, reason: "WSL login-shell PATH could not be resolved" }; }, ensureNodePty: (_distro, root) => { observedNodePtyRoots.push(root); @@ -566,7 +566,7 @@ describe("DesktopBackendConfiguration", () => { const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" }); - assert.deepEqual(observedProbeRoots, [stagedAppRoot]); + assert.equal(probeCount, 1); assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]); assert.include(config.args, "/usr/bin/node"); assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`); @@ -591,7 +591,7 @@ describe("DesktopBackendConfiguration", () => { Effect.sync(() => { invalidatedRuntimeIds.push(runtimeId); }), - probeRuntime: () => ({ ok: false, reason: "t3 --version failed (exit 1)" }), + probeRuntime: () => ({ ok: false, reason: "WSL login-shell PATH could not be resolved" }), ensureNodePty: () => ({ ok: false, reason: "WSL backend preflight timed out while probing for Node.js.", diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 26037f5a4a076..70b7dc3b87e29 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -435,7 +435,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive); if (runtime.ok) { // Staged runtimes bundle Node and node-pty; provider PATH discovery must not require them. - const stagedProbe = yield* wslEnv.probeRuntime(runningDistro, runtime.linuxAppRoot); + const stagedProbe = yield* wslEnv.probeRuntime(runningDistro); if (stagedProbe.ok) { yield* wslServerTree.cleanupLegacy; return { @@ -448,7 +448,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f } as const; } yield* Effect.logWarning( - "The staged WSL runtime did not start; retrying from the mounted server tree.", + "The staged WSL runtime probe failed; retrying from the mounted server tree.", { reason: stagedProbe.reason }, ); stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason }; diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index 06a1f768f4bd4..ff5b7b8c08e4b 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -11,6 +11,7 @@ import { DATABASE_MIGRATIONS_STARTED_MESSAGE, } from "@t3tools/shared/databaseMigrationLog"; import { assert, describe, it } from "@effect/vitest"; +import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -239,6 +240,43 @@ describe("DesktopBackendManager", () => { }), ); + it.effect("notices a WSL backend soon after it listens despite slow refused connects", () => + Effect.gen(function* () { + const ready = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const instance = yield* makeTestInstance({ + config: { ...baseConfig, httpBaseUrl: new URL("http://172.20.84.98:3773") }, + onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid), + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.acquireRelease( + Effect.succeed(makeProcess({ exitCode: Deferred.await(exit) })), + () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)), + ), + ), + ), + // Before the server listens at 300 ms, each refused connect takes a second to fail. + httpClientLayer: layerHttpClient((request) => + Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => + now < 300 + ? Effect.sleep(Duration.seconds(1)).pipe( + Effect.as(responseForRequest(request, 503)), + ) + : Effect.succeed(responseForRequest(request, 200)), + ), + ), + ), + }); + yield* instance.start; + yield* TestClock.adjust(Duration.millis(600)); + + assert.isTrue(yield* Deferred.isDone(ready)); + yield* instance.stop(); + }), + ); + it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () => Effect.gen(function* () { let spawnedCommand: ChildProcess.Command | undefined; diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index dd33910ae98fe..098b0b57cd5b3 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -350,8 +350,26 @@ const closeRun = ( ); }; +const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]); +// Windows takes about a second to fail a refused connection to a non-loopback address such as a +// WSL distro IP, so one sequential poller notices readiness up to a second late. +const STAGGERED_READINESS_POLLERS = 4; +const READINESS_POLLER_STAGGER = Duration.millis(250); + const waitForHttpReady = ( options: BackendProcessContext & { readonly timeout: Duration.Duration }, +): Effect.Effect => { + const poll = pollHttpReady(options); + if (LOOPBACK_HOSTNAMES.has(options.httpBaseUrl.hostname)) return poll; + return Effect.raceAll( + Array.from({ length: STAGGERED_READINESS_POLLERS }, (_, index) => + Effect.sleep(Duration.times(READINESS_POLLER_STAGGER, index)).pipe(Effect.andThen(poll)), + ), + ); +}; + +const pollHttpReady = ( + options: BackendProcessContext & { readonly timeout: Duration.Duration }, ): Effect.Effect => { const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl); return waitForHttpReadyShared({ diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts index 401785183f1a1..6aab916a7a104 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.test.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts @@ -114,6 +114,10 @@ function layerPool( labelRef: Ref.Ref, options: { readonly config?: DesktopBackendStartConfig; + readonly resolvePrimary?: Effect.Effect; + readonly onMainContentsCommand?: ( + command: DesktopWindow.MainWindowContentsCommand, + ) => Effect.Effect; readonly fileSystem?: Partial; readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly httpClient?: HttpClient.HttpClient; @@ -188,9 +192,11 @@ function layerPool( }), DesktopBrowserHost.layer, Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, { - resolvePrimary: options.config - ? Effect.succeed(options.config) - : Effect.die("unexpected primary config resolve"), + resolvePrimary: + options.resolvePrimary ?? + (options.config + ? Effect.succeed(options.config) + : Effect.die("unexpected primary config resolve")), resolvePrimaryLabel: Ref.get(labelRef), resolveWsl: () => Effect.die("unexpected WSL config resolve"), currentBootstrapToken: Effect.die("unexpected bootstrap token read"), @@ -200,8 +206,11 @@ function layerPool( DesktopWslEnvironment.layerTest(), Layer.succeed(ElectronDialog.ElectronDialog, { ...ElectronDialog.make, - ...(options.showErrorBox ? { showErrorBox: options.showErrorBox } : {}), - }), + pickFolder: () => Effect.die("unexpected folder picker"), + pickFiles: () => Effect.die("unexpected file picker"), + showMessageBox: () => Effect.die("unexpected message box"), + showErrorBox: options.showErrorBox ?? (() => Effect.void), + } satisfies ElectronDialog.ElectronDialog["Service"]), Layer.succeed(ElectronApp.ElectronApp, { ...ElectronApp.make, ...(options.quit ? { quit: options.quit } : {}), @@ -220,7 +229,8 @@ function layerPool( dispatchMenuAction: () => Effect.die("unexpected menu action"), dispatchSnapShotEvent: () => Effect.void, zoomMain: () => Effect.die("unexpected zoom"), - runMainContentsCommand: () => Effect.die("unexpected main contents command"), + runMainContentsCommand: + options.onMainContentsCommand ?? (() => Effect.die("unexpected main contents command")), syncAppearance: Effect.void, } satisfies DesktopWindow.DesktopWindow["Service"]), ), @@ -556,4 +566,70 @@ describe("DesktopBackendPool", () => { }), ), ); + + it.effect("reloads a main window that read the WSL endpoint before the Windows fallback", () => + Effect.gen(function* () { + const events: string[] = []; + let resolves = 0; + const resolvePrimary = Effect.sync(() => + resolves++ === 0 + ? { + ...runningConfig, + preflightFailure: Option.some({ + reason: "WSL still unavailable", + fatal: false, + retryLimit: 1, + }), + } + : runningConfig, + ); + const ready = yield* Deferred.make(); + yield* Effect.gen(function* () { + const primary = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary; + yield* primary.start; + yield* TestClock.adjust(Duration.seconds(1)); + yield* Deferred.await(ready); + + assert.deepEqual(events, ["reload", "ready"]); + }).pipe( + Effect.provide( + layerPool(Ref.makeUnsafe("WSL"), { + resolvePrimary, + spawner: ChildProcessSpawner.make(() => + Effect.gen(function* () { + const exited = yield* Deferred.make(); + const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe( + Effect.asVoid, + ); + yield* Effect.addFinalizer(() => exit); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(123), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Deferred.await(exited), + isRunning: Effect.succeed(true), + kill: () => exit, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }); + }), + ), + httpClient: HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })), + ), + ), + onMainContentsCommand: (command) => Effect.sync(() => void events.push(command)), + onReady: Effect.sync(() => void events.push("ready")).pipe( + Effect.andThen(Deferred.succeed(ready, undefined)), + Effect.asVoid, + ), + }), + ), + ); + }), + ); }); diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts index 9c31e79db5f77..2033ceaeac8f0 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.ts @@ -167,6 +167,17 @@ export const layer = Layer.effect( // One wait at a time: each run's shutdown or readiness ends the previous run's wait. const updateMarkerWait = yield* FiberHandle.make(); + // The main window loads during startup and reads the primary endpoint once; a Windows fallback + // before the first readiness replaces the WSL endpoint it read. + let primaryWasReady = false; + let reloadMainOnReady = false; + const reloadStaleMain = Effect.suspend(() => { + primaryWasReady = true; + if (!reloadMainOnReady) return Effect.void; + reloadMainOnReady = false; + return desktopWindow.runMainContentsCommand("reload"); + }); + // Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference. const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")( function* (failure: DesktopBackendManager.PreflightFailure) { @@ -182,6 +193,7 @@ export const layer = Layer.effect( }); return false; } + if (!primaryWasReady) reloadMainOnReady = true; if (!fatal) { yield* logBackendPoolWarning( "primary WSL preflight retry window exhausted; using Windows for this launch", @@ -226,6 +238,7 @@ export const layer = Layer.effect( // Absorb window errors so readiness can reset restartAttempt. onReady: (httpBaseUrl, pid) => FiberHandle.run(updateMarkerWait, releaseUpdateMarker(httpBaseUrl, pid)).pipe( + Effect.andThen(reloadStaleMain), Effect.andThen(desktopWindow.handleBackendReady(httpBaseUrl)), // Only once the main window exists, so the recovery window never closes into nothing. Effect.andThen(SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" })), diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts index 81f48c6a783ad..a90da0f225ec2 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts @@ -1,11 +1,13 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { assert, describe, it } from "@effect/vitest"; +import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; 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 Ref from "effect/Ref"; +import * as Result from "effect/Result"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientRequest from "effect/http/HttpClientRequest"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; @@ -246,4 +248,34 @@ describe("DesktopLocalEnvironmentAuth", () => { assert.strictEqual(yield* Ref.get(requestCount), 1); }).pipe(Effect.provide(TestClock.layer())), ); + + it.effect("waits through a backend that stalls for 30 seconds after it is ready", () => + Effect.gen(function* () { + const requestCount = yield* Ref.make(0); + const layerHttpClient = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.gen(function* () { + yield* Ref.update(requestCount, (count) => count + 1); + const now = yield* Clock.currentTimeMillis; + return now < 30_000 ? yield* Effect.never : tokenResponse(request); + }), + ), + ); + const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe( + Effect.provide( + DesktopLocalEnvironmentAuth.layer.pipe( + Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)), + ), + ), + ); + + const fiber = yield* auth.getBearerToken.pipe(Effect.result, Effect.forkChild); + yield* TestClock.adjust(Duration.seconds(45)); + const result = yield* Fiber.join(fiber); + + assert.isTrue(Result.isSuccess(result)); + assert.strictEqual(yield* Ref.get(requestCount), 4); + }).pipe(Effect.provide(TestClock.layer())), + ); }); diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts index e36ae5a2efa19..63c6e623aa78d 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts @@ -17,7 +17,8 @@ import * as HttpClient from "effect/http/HttpClient"; import * as DesktopBackendPool from "./DesktopBackendPool.ts"; -const BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT = Duration.seconds(15); +// Each /oauth/token attempt may take 10 s, so a backend busy after ready needs several attempts. +const BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT = Duration.seconds(60); const BOOTSTRAP_TRANSIENT_RETRY_INTERVAL = Duration.millis(500); const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]); diff --git a/apps/desktop/src/electron/ElectronAudio.test.ts b/apps/desktop/src/electron/ElectronAudio.test.ts new file mode 100644 index 0000000000000..b38d7bbb3ae47 --- /dev/null +++ b/apps/desktop/src/electron/ElectronAudio.test.ts @@ -0,0 +1,60 @@ +import * as Effect from "effect/Effect"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { app } from "electron"; +import { expect, vi } from "vite-plus/test"; +import { it } from "@effect/vitest"; +import * as Fiber from "effect/Fiber"; + +const { getAppMetrics, kill } = vi.hoisted(() => ({ getAppMetrics: vi.fn(), kill: vi.fn() })); +vi.mock("node:process", () => ({ kill })); +vi.mock("electron", async () => { + const { EventEmitter } = await import("node:events"); + return { app: Object.assign(new EventEmitter(), { getAppMetrics }) }; +}); + +import { restart } from "./ElectronAudio.ts"; + +const audio = { pid: 42, type: "Utility", serviceName: "audio.mojom.AudioService" }; + +it.effect("coalesces recovery and waits for its own audio utility to exit", () => + Effect.gen(function* () { + getAppMetrics.mockReturnValue([ + { pid: 1, type: "Utility", serviceName: "network.mojom.NetworkService" }, + { pid: 2, type: "Browser", serviceName: audio.serviceName }, + audio, + ]); + const started = Promise.withResolvers(); + kill.mockReset().mockImplementation(() => { + started.resolve(); + }); + const pending = yield* Effect.forkChild( + Effect.all([restart(), restart()], { concurrency: "unbounded" }), + ); + yield* Effect.promise(() => started.promise); + app.emit( + "child-process-gone", + {}, + { type: "Utility", serviceName: "network.mojom.NetworkService" }, + ); + expect(app.listenerCount("child-process-gone")).toBe(1); + app.emit("child-process-gone", {}, audio); + expect(yield* Fiber.join(pending)).toEqual([true, true]); + expect(kill.mock.calls).toEqual([[42, "SIGTERM"]]); + expect(app.listenerCount("child-process-gone")).toBe(0); + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), +); + +it.effect.each(["linux", "darwin", "win32"] as const)( + "leaves other processes alone on %s", + (platform) => + Effect.gen(function* () { + getAppMetrics.mockReturnValue([ + { pid: 1, type: "Utility", serviceName: "network.mojom.NetworkService" }, + ]); + kill.mockReset(); + expect(yield* restart().pipe(Effect.provideService(HostProcess.Platform, platform))).toBe( + false, + ); + expect(kill).not.toHaveBeenCalled(); + }), +); diff --git a/apps/desktop/src/electron/ElectronAudio.ts b/apps/desktop/src/electron/ElectronAudio.ts new file mode 100644 index 0000000000000..6a7f290d6fd83 --- /dev/null +++ b/apps/desktop/src/electron/ElectronAudio.ts @@ -0,0 +1,62 @@ +// @effect-diagnostics globalTimers:off -- The shared native restart deadline must outlive individual IPC callers. +// @effect-diagnostics nodeBuiltinImport:off -- Only Electron's main process can restart its Chromium audio utility. +import * as NodeProcess from "node:process"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { app, type Details, type Event } from "electron"; + +class AudioServiceRestartError extends Schema.TaggedError()( + "AudioServiceRestartError", + { cause: Schema.Defect() }, +) {} + +let pendingRestart: Promise | undefined; + +export const restart = Effect.fn("ElectronAudio.restart")(function* () { + if ((yield* HostProcess.Platform) !== "linux") return false; + return yield* Effect.tryPromise({ + try: () => { + if (pendingRestart) return pendingRestart; + const audio = app + .getAppMetrics() + .find( + (metric) => + metric.type === "Utility" && metric.serviceName === "audio.mojom.AudioService", + ); + if (!audio) return Promise.resolve(false); + // A failed PulseAudio context survives new getUserMedia calls; Chromium reconnects when its utility exits. + pendingRestart = new Promise((resolve, reject) => { + const cleanup = () => { + clearTimeout(timer); + app.removeListener("child-process-gone", onGone); + }; + const onGone = (_event: Event, details: Details) => { + if (details.type === "Utility" && details.serviceName === audio.serviceName) { + cleanup(); + resolve(true); + } + }; + const timer = setTimeout(() => { + cleanup(); + resolve(false); + }, 5_000); + app.on("child-process-gone", onGone); + try { + NodeProcess.kill(audio.pid, "SIGTERM"); + } catch (cause) { + cleanup(); + reject(cause); + } + }).finally(() => { + pendingRestart = undefined; + }); + return pendingRestart; + }, + catch: (cause) => new AudioServiceRestartError({ cause }), + }).pipe( + Effect.catch((cause) => + Effect.logWarning("Could not restart the audio service", cause).pipe(Effect.as(false)), + ), + ); +}); diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 57d7101cf9ec7..60b72deb293a5 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -44,6 +44,7 @@ import { getWindowFullscreenState, openExternal, readMedia, + restartAudioService, openSystemSettings, checkSystemPermission, pasteAsText, @@ -109,6 +110,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(getHostEnvironmentId); yield* ipc.handle(getLocalEnvironmentBearerToken); + yield* ipc.handle(restartAudioService); yield* ipc.handle(getClientSettings); yield* ipc.handle(setClientSettings); yield* ipc.handle(getConnectionCatalog); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 4de0a23af35b3..9e5c7296a3a03 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -140,3 +140,5 @@ export const RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:receive-provider- export const CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:cancel-provider-auth-callback"; export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-storage"; export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-local-storage"; + +export const RESTART_AUDIO_SERVICE_CHANNEL = "desktop:restart-audio-service"; diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 8674c0ae65dfb..623b7e991dcf7 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -38,6 +38,7 @@ import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronApp from "../../electron/ElectronApp.ts"; +import * as ElectronAudio from "../../electron/ElectronAudio.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts"; import * as ElectronMenu from "../../electron/ElectronMenu.ts"; import * as ElectronShell from "../../electron/ElectronShell.ts"; @@ -600,3 +601,10 @@ export const checkSystemPermission = DesktopIpc.makeIpcMethod({ return yield* Effect.promise(check); }), }); + +export const restartAudioService = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL, + payload: Schema.Void, + result: Schema.Boolean, + handler: ElectronAudio.restart, +}); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index f0f9648173dc8..ba9c17aae2695 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -115,6 +115,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL) === true, getPathForFile: (file: File) => webUtils.getPathForFile(file), getClientPlatform: () => clientPlatform, + restartAudioService: () => ipcRenderer.invoke(IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL), setNotificationBadge: (badge) => ipcRenderer.invoke(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, badge), onNotificationBadgeClear: (listener) => { diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index dc85f6a7e3cdc..4b6b171569771 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -1,7 +1,7 @@ import * as NodeModule from "node:module"; import { assert, describe, it } from "@effect/vitest"; -import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts"; +import { DESKTOP_UPDATE_RESTART_MARKER_FILE, DesktopUpdateStateSchema } from "@t3tools/contracts"; import { computeReleaseNotes } from "electron-updater/out/providers/GitHubProvider.js"; import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; @@ -13,6 +13,7 @@ import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as References from "effect/References"; import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; @@ -25,6 +26,8 @@ import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts"; import * as DesktopUpdates from "./DesktopUpdates.ts"; import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts"; +const encodeUpdateState = Schema.encodeEffect(DesktopUpdateStateSchema); + type ReleaseFeed = Parameters[2]; type RunningVersion = Parameters[0]; @@ -1198,6 +1201,7 @@ describe("DesktopUpdates under a managed policy", () => { assert.include(held.message ?? "", message); assert.include(held.message ?? "", "Install the stable channel separately"); assert.isTrue(held.channelBlockedByPolicy); + assert.isTrue((yield* encodeUpdateState(held)).channelBlockedByPolicy); assert.isFalse((yield* updates.check("menu")).checked); assert.equal(harness.checkCount(), 0); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index 03c40bb189022..7811b147cc286 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -189,7 +189,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed " }", ' eval "$2"', "); }", - buildWslRuntimeProbeScript(fixture.runtimeRoot), + buildWslRuntimeProbeScript(), ].join("\n"), ); @@ -224,7 +224,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed [ "bash() { return 127; }", 'export PATH="/fixture/bin:/usr/bin:/bin"', - buildWslRuntimeProbeScript(fixture.runtimeRoot), + buildWslRuntimeProbeScript(), ].join("\n"), ); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index 810c03d200919..537091b24afd2 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -115,10 +115,7 @@ export class DesktopWslEnvironment extends Context.Service< ) => Effect.Effect; readonly pruneRuntimes: (distro: string | null, runtimeId: string) => Effect.Effect; readonly invalidateRuntime: (distro: string | null, runtimeId: string) => Effect.Effect; - readonly probeRuntime: ( - distro: string | null, - linuxAppRoot: string, - ) => Effect.Effect; + readonly probeRuntime: (distro: string | null) => Effect.Effect; readonly ensureNodePty: ( distro: string | null, linuxAppRoot: string, @@ -535,11 +532,9 @@ require("node-pty"); NODE`; // Resolve version-managed Node for providers without making runtime readiness depend on it. -export const buildWslRuntimeProbeScript = (linuxAppRoot: string) => - [ - `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`, - `${shellQuote(`${linuxAppRoot}/t3`)} --version >/dev/null 2>&1`, - ].join("\n"); +// The install script already ran the staged t3, so running it again here only adds a second startup. +export const buildWslRuntimeProbeScript = () => + `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`; const TOOLCHAIN_CHECK_SCRIPT = [ "for tool in node make g++ python3; do", @@ -653,30 +648,17 @@ const formatMissingToolsReason = ( const probeWslRuntimeImpl = Effect.fn("DesktopWslEnvironment.probeWslRuntimeImpl")(function* ( distro: string | null, - linuxAppRoot: string, ): Effect.fn.Return { - const probe = yield* runWslShell( - distro, - buildWslRuntimeProbeScript(linuxAppRoot), - PROBE_TIMEOUT, - { - resolveNode: false, - }, - ); + const probe = yield* runWslShell(distro, buildWslRuntimeProbeScript(), PROBE_TIMEOUT, { + resolveNode: false, + }); const transportFailureReason = formatWslShellTransportFailureReason( probe.transportFailure, - "the staged runtime", + "the login-shell PATH", ); if (transportFailureReason !== null) { return { ok: false, reason: transportFailureReason } as const; } - if (probe.exitCode !== 0) { - const trimmedTail = probe.stderr.trim().slice(-500); - return { - ok: false, - reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`, - } as const; - } const resolvedPath = parseResolvedPath(probe.stdout); if (resolvedPath === null) { return { @@ -1233,7 +1215,7 @@ export interface DesktopWslEnvironmentTestStub { ) => PrepareWslRuntimeResult; readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect; readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect; - readonly probeRuntime?: (distro: string | null, linuxAppRoot: string) => ProbeWslRuntimeResult; + readonly probeRuntime?: (distro: string | null) => ProbeWslRuntimeResult; readonly ensureNodePty?: ( distro: string | null, linuxAppRoot: string, @@ -1280,16 +1262,14 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => { return stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void; }, ), - probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")( - function (distro, linuxAppRoot) { - return Effect.succeed( - stub.probeRuntime?.(distro, linuxAppRoot) ?? { - ok: true, - resolvedPath: "/usr/bin:/bin", - }, - ); - }, - ), + probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(function (distro) { + return Effect.succeed( + stub.probeRuntime?.(distro) ?? { + ok: true, + resolvedPath: "/usr/bin:/bin", + }, + ); + }), ensureNodePty: Effect.fn("DesktopWslEnvironment.ensureNodePty")( function (distro, linuxAppRoot, options) { return Effect.succeed( @@ -1379,8 +1359,8 @@ export const layer = Layer.effect( invalidateRuntime: Effect.fn("desktop.wsl.invalidateRuntime")(function (distro, runtimeId) { return provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId, environment.appVersion)); }), - probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro, linuxAppRoot) { - return provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot)); + probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro) { + return provideSpawner(probeWslRuntimeImpl(distro)); }), ensureNodePty: Effect.fn("desktop.wsl.ensureNodePty")( function (distro, linuxAppRoot, options) { 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 7a1225cd392bf..2f1e4d9fd4a43 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 @@ -402,7 +402,7 @@ internal class ReviewDiffCanvasDrawing(context: Context) { @Suppress("LongParameterList") fun drawCode( canvas: Canvas, - content: String, + row: DiffRow, tokens: List?, codeX: Float, baseline: Float, @@ -417,12 +417,16 @@ internal class ReviewDiffCanvasDrawing(context: Context) { canvas.restore() return } - val runs = if (tokens.isNullOrEmpty()) listOf(DiffToken(content, null, 0)) else tokens + val runs = if (tokens.isNullOrEmpty()) listOf(DiffToken(row.content, null, 0)) else tokens var line = 0 var x = codeX var column = 0 - runs.forEach { run -> - configureCodePaint(run.color ?: theme.text, run.fontStyle, style) + splitAtNote(runs, row.noteStart).forEach { (run, note) -> + configureCodePaint( + if (note) theme.warningText else run.color ?: theme.text, + run.fontStyle, + style, + ) var start = 0 while (start < run.content.length) { while (line + 1 < lines.starts.size && lines.starts[line + 1] <= column + start) { @@ -434,8 +438,10 @@ internal class ReviewDiffCanvasDrawing(context: Context) { if (lineBaseline + textPaint.fontMetrics.descent >= canvas.clipBounds.top && lineBaseline + textPaint.fontMetrics.ascent <= canvas.clipBounds.bottom ) { + val segmentWidth = textPaint.measureText(run.content, start, end) + fillNote(canvas, note, x, x + segmentWidth, lineBaseline) canvas.drawText(run.content, start, end, x, lineBaseline, textPaint) - x += textPaint.measureText(run.content, start, end) + x += segmentWidth } start = end } @@ -443,6 +449,21 @@ internal class ReviewDiffCanvasDrawing(context: Context) { } } + fun noticeColor(row: DiffRow): Int = + if (row.tone == "warning") theme.warningText else theme.mutedText + + fun noticeFill(row: DiffRow): Int = + if (row.tone == "warning") theme.warningBackground else theme.background + + /** Fills behind a segment of a cut line's note; other segments are left alone. */ + private fun fillNote(canvas: Canvas, note: Boolean, left: Float, right: Float, baseline: Float) { + if (!note) return + backgroundPaint.color = theme.warningBackground + val metrics = textPaint.fontMetrics + val top = baseline + metrics.ascent + canvas.drawRect(left, top, right, baseline + metrics.descent, backgroundPaint) + } + fun drawFileHeaderPathScrollFades( canvas: Canvas, pathRect: RectF, @@ -532,3 +553,24 @@ private object ReviewDiffTypefaces { else -> regular } } + +/** Splits color runs where a cut line's note starts; the flag marks the note's runs. */ +private fun splitAtNote(runs: List, noteStart: Int?): List> { + if (noteStart == null) return runs.map { it to false } + return buildList { + var offset = 0 + for (run in runs) { + val end = offset + run.content.length + when { + end <= noteStart -> add(run to false) + offset >= noteStart -> add(run to true) + else -> { + val cut = noteStart - offset + add(run.copy(content = run.content.substring(0, cut)) to false) + add(run.copy(content = run.content.substring(cut)) to true) + } + } + offset = end + } + } +} diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt index 770bc656de569..83f32788e8ab8 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCodeLayout.kt @@ -182,6 +182,20 @@ internal class CodeLayoutCache { } } } + row.noteStart?.takeIf { it in 0 until text.length }?.let { start -> + text.setSpan( + ForegroundColorSpan(theme.warningText), + start, + text.length, + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE, + ) + text.setSpan( + BackgroundColorSpan(theme.warningBackground), + start, + text.length, + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE, + ) + } return text } } diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt index 63ab13dde3d12..03609e3658e84 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffModule.kt @@ -4,6 +4,16 @@ import expo.modules.kotlin.Promise import expo.modules.kotlin.modules.Module import expo.modules.kotlin.modules.ModuleDefinition +private val REVIEW_DIFF_EVENTS = arrayOf( + "onDebug", + "onVisibleFileChange", + "onToggleFile", + "onToggleViewedFile", + "onPressLine", + "onToggleComment", + "onPressNotice", +) + class T3ReviewDiffModule : Module() { override fun definition() = ModuleDefinition { Name("T3ReviewDiffSurface") @@ -54,14 +64,7 @@ class T3ReviewDiffModule : Module() { view.setInitialFileId(fileId) } - Events( - "onDebug", - "onVisibleFileChange", - "onToggleFile", - "onToggleViewedFile", - "onPressLine", - "onToggleComment", - ) + Events(REVIEW_DIFF_EVENTS) AsyncFunction("scrollToFile") { view: T3ReviewDiffView, fileId: String, animated: Boolean -> view.scrollToFile(fileId, animated) 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 54ff86c611a8e..91bb6719ed8fa 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 @@ -31,6 +31,7 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont private val onToggleViewedFile by EventDispatcher() private val onPressLine by EventDispatcher() private val onToggleComment by EventDispatcher() + private val onPressNotice by EventDispatcher() private var rows: List = emptyList() private var visibleRows: List = emptyList() private var visibleRowIndices = IntArray(0) @@ -432,6 +433,9 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont } } "comment" -> onToggleComment(mapOf("commentId" to row.id)) + "notice" -> if (gesture == "tap" && row.actionable) { + onPressNotice(mapOf("rowId" to row.id, "fileId" to row.resolvedFileId)) + } "line" -> { val payload = mutableMapOf( "rowId" to row.id, @@ -534,7 +538,13 @@ internal data class DiffRow( val wordDiffRanges: List, val commentText: String, val commentRangeLabel: String, - val commentSectionTitle: String + val commentSectionTitle: String, + /** A notice drawn in the warning colors. */ + val tone: String = "", + /** A notice that reports taps through `onPressNotice`. */ + val actionable: Boolean = false, + /** Where a cut line's note starts in `content`. */ + val noteStart: Int? = null ) { val resolvedFileId: String get() = fileId.ifEmpty { id } val isPlainAscii: Boolean = content.all { it in ' '..'~' } @@ -564,7 +574,9 @@ internal data class DiffTheme( val addBar: Int, val deleteBar: Int, val addText: Int, - val deleteText: Int + val deleteText: Int, + val warningText: Int, + val warningBackground: Int ) { companion object { fun fallback(scheme: String): DiffTheme = if (scheme == "dark") { @@ -582,6 +594,8 @@ internal data class DiffTheme( deleteBar = Color.rgb(255, 46, 63), addText = Color.rgb(94, 204, 113), deleteText = Color.rgb(255, 103, 98), + warningText = Color.rgb(250, 204, 102), + warningBackground = Color.rgb(51, 38, 13), ) } else { DiffTheme( @@ -598,6 +612,8 @@ internal data class DiffTheme( deleteBar = Color.rgb(213, 44, 54), addText = Color.rgb(25, 130, 67), deleteText = Color.rgb(190, 38, 48), + warningText = Color.rgb(140, 92, 0), + warningBackground = Color.rgb(255, 245, 214), ) } @@ -617,6 +633,8 @@ internal data class DiffTheme( deleteBar = color(json, "deleteBar", fallback.deleteBar), addText = color(json, "addText", fallback.addText), deleteText = color(json, "deleteText", fallback.deleteText), + warningText = color(json, "warningText", fallback.warningText), + warningBackground = color(json, "warningBackground", fallback.warningBackground), ) } catch (_: Exception) { fallback @@ -1189,7 +1207,7 @@ private class DiffCanvasView(context: Context) : View(context) { } private fun drawNoticeRow(canvas: Canvas, row: DiffRow, top: Int, bottom: Int) { - fill(canvas, theme.background, 0f, top.toFloat(), width.toFloat(), bottom.toFloat()) + fill(canvas, drawing.noticeFill(row), 0f, top.toFloat(), width.toFloat(), bottom.toFloat()) val iconSize = 16f * density val iconRect = RectF( style.fileHeaderHorizontalPaddingPx + 2f * density, @@ -1197,10 +1215,10 @@ private class DiffCanvasView(context: Context) : View(context) { style.fileHeaderHorizontalPaddingPx + 2f * density + iconSize, (top + bottom + iconSize) / 2f, ) - drawing.drawNoticeIcon(canvas, iconRect, theme.mutedText) + drawing.drawNoticeIcon(canvas, iconRect, drawing.noticeColor(row)) drawing.configureUiPaint( paint = textPaint, - color = theme.mutedText, + color = drawing.noticeColor(row), size = style.fileHeaderSubtextFontSizePx, weight = style.fileHeaderSubtextFontWeight, ) @@ -1313,7 +1331,7 @@ private class DiffCanvasView(context: Context) : View(context) { drawing.configureCodePaint(theme.text, 0, style) drawing.drawWordDiffRanges(canvas, row, codeX, top, firstLineBottom, lines) val baseline = lines.baseline(top, firstLineBottom, textPaint) - drawing.drawCode(canvas, row.content, tokensByRowId[row.id], codeX, baseline, style, lines) + drawing.drawCode(canvas, row, tokensByRowId[row.id], codeX, baseline, style, lines) } drawLineNumber(canvas, row, top, firstLineBottom) @@ -1488,6 +1506,9 @@ private fun parseRows(value: String, isCancelled: () -> Boolean): List commentText = row.optString("commentText"), commentRangeLabel = row.optString("commentRangeLabel"), commentSectionTitle = row.optString("commentSectionTitle"), + tone = row.optString("tone"), + actionable = row.optBoolean("actionable"), + noteStart = row.optNullableInt("noteStart"), ) } } catch (_: Exception) { diff --git a/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift b/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift index 7f96dc17a25e6..4c60b20c1add5 100644 --- a/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift +++ b/apps/mobile/modules/t3-review-diff/ios/ReviewDiffCodeLayout.swift @@ -16,6 +16,13 @@ struct ReviewDiffCodeLineStarts: RandomAccessCollection { /// ASCII uses fixed-pitch columns. TextKit handles shaping, tabs, and Unicode highlights. /// Pass `unboundedWidth` to lay a row out on one line for horizontal scrolling. +/** A cut line's note, drawn in its own colors. */ +struct ReviewDiffCodeNote { + let range: NSRange + let color: UIColor + let background: UIColor +} + final class ReviewDiffCodeLayout: NSObject { static let unboundedWidth = CGFloat.greatestFiniteMagnitude @@ -84,7 +91,14 @@ final class ReviewDiffCodeLayout: NSObject { return layout } - func decorate(text: NSAttributedString, highlights: [NSRange], color: UIColor, version: Int) { + // A cut line's note is not code, so it takes the warning colors over any token color. + func decorate( + text: NSAttributedString, + highlights: [NSRange], + color: UIColor, + note: ReviewDiffCodeNote? = nil, + version: Int + ) { guard usesNativeLayout else { return } let layout = nativeLayout() guard layout.decorationVersion != version else { return } @@ -105,6 +119,13 @@ final class ReviewDiffCodeLayout: NSObject { storage.addAttribute(.backgroundColor, value: color, range: intersection) } } + if let note { + let intersection = NSIntersectionRange(note.range, fullRange) + if intersection.length > 0 { + storage.addAttribute(.foregroundColor, value: note.color, range: intersection) + storage.addAttribute(.backgroundColor, value: note.background, range: intersection) + } + } storage.endEditing() layout.decorationVersion = version } diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift index 2fcb8a4801809..d1be707b0d9d6 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffModule.swift @@ -88,6 +88,7 @@ public class T3ReviewDiffModule: Module { "onToggleViewedFile", "onPressLine", "onToggleComment", + "onPressNotice", "onPullToRefresh" ) diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index a80a391380750..7fe4a068f9bbb 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -19,6 +19,12 @@ private struct ReviewDiffNativeRow: Decodable, Sendable { let commentText: String? let commentRangeLabel: String? let commentSectionTitle: String? + /** A notice drawn in the warning colors. */ + let tone: String? + /** A notice that reports taps through `onPressNotice`. */ + let actionable: Bool? + /** Where a cut line's note starts in `content`, in UTF-16 units. */ + let noteStart: Int? } private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable { @@ -52,6 +58,8 @@ private struct ReviewDiffNativeThemePayload: Decodable { let deleteBar: String? let addText: String? let deleteText: String? + let warningText: String? + let warningBackground: String? } private struct ReviewDiffNativeTheme { @@ -68,6 +76,8 @@ private struct ReviewDiffNativeTheme { let deleteBar: UIColor let addText: UIColor let deleteText: UIColor + let warningText: UIColor + let warningBackground: UIColor static func resolve(_ scheme: String) -> ReviewDiffNativeTheme { resolve(scheme, payload: nil) @@ -95,7 +105,10 @@ private struct ReviewDiffNativeTheme { addBar: UIColor(reviewDiffHex: payload.addBar) ?? fallback.addBar, deleteBar: UIColor(reviewDiffHex: payload.deleteBar) ?? fallback.deleteBar, addText: UIColor(reviewDiffHex: payload.addText) ?? fallback.addText, - deleteText: UIColor(reviewDiffHex: payload.deleteText) ?? fallback.deleteText + deleteText: UIColor(reviewDiffHex: payload.deleteText) ?? fallback.deleteText, + warningText: UIColor(reviewDiffHex: payload.warningText) ?? fallback.warningText, + warningBackground: UIColor(reviewDiffHex: payload.warningBackground) + ?? fallback.warningBackground ) } @@ -114,7 +127,9 @@ private struct ReviewDiffNativeTheme { addBar: UIColor(red: 0.02, green: 0.82, blue: 0.54, alpha: 1), deleteBar: UIColor(red: 1.00, green: 0.36, blue: 0.50, alpha: 1), addText: UIColor(red: 0.10, green: 0.84, blue: 0.56, alpha: 1), - deleteText: UIColor(red: 1.00, green: 0.38, blue: 0.52, alpha: 1) + deleteText: UIColor(red: 1.00, green: 0.38, blue: 0.52, alpha: 1), + warningText: UIColor(red: 0.98, green: 0.80, blue: 0.40, alpha: 1), + warningBackground: UIColor(red: 0.20, green: 0.15, blue: 0.05, alpha: 1) ) } @@ -131,7 +146,9 @@ private struct ReviewDiffNativeTheme { addBar: UIColor(red: 0.02, green: 0.80, blue: 0.52, alpha: 1), deleteBar: UIColor(red: 1.00, green: 0.34, blue: 0.48, alpha: 1), addText: UIColor(red: 0.00, green: 0.56, blue: 0.34, alpha: 1), - deleteText: UIColor(red: 0.90, green: 0.10, blue: 0.24, alpha: 1) + deleteText: UIColor(red: 0.90, green: 0.10, blue: 0.24, alpha: 1), + warningText: UIColor(red: 0.55, green: 0.36, blue: 0.00, alpha: 1), + warningBackground: UIColor(red: 1.00, green: 0.96, blue: 0.84, alpha: 1) ) } } @@ -350,6 +367,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { let onToggleViewedFile = EventDispatcher() let onPressLine = EventDispatcher() let onToggleComment = EventDispatcher() + let onPressNotice = EventDispatcher() let onPullToRefresh = EventDispatcher() private let pullRefreshControl = UIRefreshControl() @@ -383,6 +401,9 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate { contentView.onToggleComment = { [weak self] commentId in self?.onToggleComment(["commentId": commentId]) } + contentView.onPressNotice = { [weak self] payload in + self?.onPressNotice(payload) + } contentView.onDrawMetrics = { [weak self] metrics in self?.emitDebug("draw-metrics", metrics) } @@ -1214,6 +1235,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { var onToggleViewedFile: ((String) -> Void)? var onPressLine: (([String: Any]) -> Void)? var onToggleComment: ((String) -> Void)? + var onPressNotice: (([String: Any]) -> Void)? var onDrawMetrics: (([String: Any]) -> Void)? private var stickyWidth: CGFloat { @@ -1555,6 +1577,11 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { return } + if row.kind == "notice", row.actionable == true { + onPressNotice?(["rowId": row.id, "fileId": resolvedFileId(for: row)]) + return + } + if row.kind == "line" { onPressLine?(linePressPayload(for: row, gesture: "tap")) return @@ -2200,7 +2227,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { return } - theme.background.setFill() + let warning = row.tone == "warning" + (warning ? theme.warningBackground : theme.background).setFill() context.fill(rect) let hairline = 1 / traitCollection.displayScale @@ -2214,7 +2242,8 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { width: iconSize, height: iconSize ) - drawNoticeIcon(rect: iconRect, color: theme.mutedText) + let noticeColor = warning ? theme.warningText : theme.mutedText + drawNoticeIcon(rect: iconRect, color: noticeColor) drawSingleLineText( row.text ?? "", @@ -2224,7 +2253,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { width: max(24, viewportWidth - iconRect.maxX - 10 - style.fileHeaderHorizontalPadding), height: fileHeaderSubtextFont.lineHeight ), - color: theme.mutedText, + color: noticeColor, font: fileHeaderSubtextFont ) } @@ -2554,6 +2583,13 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { NSRange(location: $0.start, length: $0.end - $0.start) }, color: (change == "add" ? theme.addBar : theme.deleteBar).withAlphaComponent(0.28), + note: row.noteStart.map { + ReviewDiffCodeNote( + range: NSRange(location: $0, length: max(0, text.length - $0)), + color: theme.warningText, + background: theme.warningBackground + ) + }, version: codeDecorationVersion ) layout.draw( diff --git a/apps/mobile/src/components/VideoThumbnailImage.tsx b/apps/mobile/src/components/VideoThumbnailImage.tsx index 6f6fea83063ca..f4ddb25a276fb 100644 --- a/apps/mobile/src/components/VideoThumbnailImage.tsx +++ b/apps/mobile/src/components/VideoThumbnailImage.tsx @@ -41,7 +41,7 @@ export function VideoThumbnailImage(props: { readonly contentFit?: "cover" | "contain"; }) { const { cacheKey, source } = props; - // Extraction runs only while the screen is focused; leaving it interrupts the load. + // Extraction starts only while the screen is focused; leaving it skips queued loads. const isFocused = useIsFocused(); const loaded = useAtomValue( source && isFocused ? videoThumbnailAtom({ cacheKey, source }) : noVideoThumbnail, diff --git a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx index 528a18541eb46..448fd929e42e8 100644 --- a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx +++ b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx @@ -96,10 +96,10 @@ export function SettingsDiagnosticsRouteScreen() { {crashReportingAvailable ? : null} diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts index bf8c6e8e311ca..2699bb995406c 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.ts @@ -47,6 +47,12 @@ export interface NativeReviewDiffRow { readonly commentText?: string; readonly commentRangeLabel?: string; readonly commentSectionTitle?: string; + /** A notice drawn in the warning colors. */ + readonly tone?: "warning"; + /** A notice that reports taps through `onPressNotice`. */ + readonly actionable?: boolean; + /** Where a cut line's note starts in `content`. */ + readonly noteStart?: number; } export interface NativeReviewDiffWordDiffRange { @@ -74,6 +80,8 @@ export interface NativeReviewDiffTheme { readonly deleteBar: string; readonly addText: string; readonly deleteText: string; + readonly warningText: string; + readonly warningBackground: string; } export interface NativeReviewDiffStyle { @@ -151,6 +159,9 @@ export interface NativeReviewDiffViewProps extends ViewProps { }>, ) => void; readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void; + readonly onPressNotice?: ( + event: NativeSyntheticEvent<{ readonly rowId?: string; readonly fileId?: string }>, + ) => void; } export interface NativeReviewDiffViewHandle { diff --git a/apps/mobile/src/features/home/ThreadUndoNotice.tsx b/apps/mobile/src/features/home/ThreadUndoNotice.tsx index caeb47a3c2195..544a2909124ea 100644 --- a/apps/mobile/src/features/home/ThreadUndoNotice.tsx +++ b/apps/mobile/src/features/home/ThreadUndoNotice.tsx @@ -51,7 +51,11 @@ export function ThreadUndoNotice(props: { readonly visible: boolean }) { const bottom = Platform.OS === "ios" ? foldedResting - ? Math.max(rootMetrics.safeArea.bottom, keyboardHeight) + 8 + ? // Sit level with the rail's tab pill, which floats inside the bottom safe area. + Math.max( + rootMetrics.bottomBarInset ?? rootMetrics.safeArea.bottom + 8, + keyboardHeight + 8, + ) : rootMetrics?.hasHinge && rootMetrics.verticalBarEdge !== "none" ? // The column's safe area already includes UIKit's search toolbar in this posture. workspaceSearchBottomClearance({ diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx index af33c7bec3a2a..c94267a68f5ad 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx @@ -100,8 +100,8 @@ function WorkspaceRootContent() { layout.variant === "medium" && state.selectedTab === "usage" ? workspaceDockBottomClearance({ bottomInset: insets.bottom, keyboardHeight }) : isDuoDevice(deviceType) - ? // The column's safe area already holds the Duo's search toolbar and keyboard. - Math.max(insets.bottom, keyboardHeight) + 16 + ? // The column's safe area holds the Duo's search toolbar, but not the sidebar's own tab bar. + Math.max(insets.bottom + (sidebarPicker ? 64 : 0), keyboardHeight) + 16 : compactTabs || deviceType === "pad" ? workspaceDockBottomClearance({ bottomInset: insets.bottom, keyboardHeight }) : Math.max(insets.bottom, keyboardHeight) + diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx index 1bcab04eb3eea..d72cbe743f23e 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx @@ -12,12 +12,9 @@ import { pullRequestTabOffset } from "./pullRequestTabScroll"; import { guideFocusedRows, type GuideDiffFocus } from "./guide/guideDiffFocus"; import { PullRequestGuideContent } from "./guide/PullRequestGuideScreen"; import { useReviewGuidesEnabled } from "./guide/useReviewGuide"; -import { - filterPullRequestActivity, - DEFAULT_ACTIVITY_FILTER, - type ActivityFilter, -} from "./pullRequestActivityFilter"; +import { filterPullRequestActivity, type ActivityFilter } from "./pullRequestActivityFilter"; import { PullRequestActivityFilters } from "./PullRequestActivityFilters"; +import { usePullRequestActivityFilter } from "./usePullRequestActivityFilter"; import type { LegendListRef } from "@legendapp/list/react-native"; import { AnimatedLegendList } from "@legendapp/list/reanimated"; import Animated from "react-native-reanimated"; @@ -383,14 +380,8 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps !guidesEnabled && tab === "guide" ? "overview" : tab; const section = shown(chosenSection); - const [activityFilter, setActivityFilter] = useState(() => { - const kind = parsePullRequestAnchor(params.navigationUrl)?.kind; - return kind === "timeline" - ? { ...DEFAULT_ACTIVITY_FILTER, bots: true, resolved: true } - : kind === "commits" - ? { ...DEFAULT_ACTIVITY_FILTER, kind: "commits" } - : DEFAULT_ACTIVITY_FILTER; - }); + const activity = usePullRequestActivityFilter(parsePullRequestAnchor(params.navigationUrl)?.kind); + const activityFilter = activity.filter; const activityContent = usePullRequestActivityRows(params, activityFilter); const scrollOffsets = useRef>({}); // The offset of the tab last shown, and which tab that was: a tab standing in for a hidden guide @@ -442,10 +433,10 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps ({ ...filter, kind: "all", bots: true, resolved: true })); + activity.showTimeline(); } else if (target?.kind === "commits") { selectSection("activity"); - setActivityFilter((filter) => ({ ...filter, kind: "commits" })); + activity.showCommits(); } else if (target?.kind === "checks") { selectSection("overview"); // Checks head Overview, which a reused screen may have scrolled past. @@ -831,7 +822,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps ) : null} @@ -1011,6 +1002,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { !staleDiff && !detail.isPending && !result.isPending && + !result.withheldRefetching && !result.error; const activity = useEnvironmentQuery(composerPullRequests.activity(requestTarget(route.params))); const baseData = useMemo(() => getCachedNativeReviewDiffData({ parsedDiff: parsed }), [parsed]); @@ -1338,6 +1330,10 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { }); else void viewed.toggle(file.path); }} + onPressNotice={(event) => { + const file = data.files.find((file) => file.id === event.nativeEvent.fileId); + if (file) result.loadWithheldFile(file.path); + }} onToggleComment={(event) => { const id = event.nativeEvent.commentId; if (id?.startsWith("discussion:")) diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts index 82027addc72cc..b0c91ab3ada9e 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.test.ts @@ -7,6 +7,8 @@ import { combinePullRequestDiffPages, getCachedPullRequestDiffPages, retainPullRequestDiffPage, + withWithheldFiles, + type WithheldFileLoad, } from "./pullRequestDiffPages"; const GITHUB = sourceControlClients.get("github").changeRequest; @@ -156,4 +158,41 @@ describe("paged mobile pull request diffs", () => { expect(refreshed).toHaveLength(1); expect(refreshed[0]?.result.patch).toContain("changed.ts"); }); + + it("swaps a loaded withheld file in under its id and says what a tap does for the rest", () => { + const pages = [{ cursor: null, result: withheldDiff() }]; + const parsed = combinePullRequestDiffPages(pages, new WeakMap(), "pr", GITHUB); + if (parsed.kind !== "files") throw new Error("Expected structured diff"); + const placeholder = parsed.files[0]; + let merged: ReviewParsedDiff = parsed; + const fileWith = (load: WithheldFileLoad | undefined, canLoad = true) => { + merged = withWithheldFiles( + parsed, + new Map(load === undefined ? [] : [["large.ts", load]]), + canLoad, + "pr", + ); + return merged.kind === "files" ? merged.files[0] : undefined; + }; + expect(fileWith(undefined)).toMatchObject({ + notice: "Diff too large to display. Tap to load it.", + noticeTone: "warning", + noticeActionable: true, + }); + expect(fileWith(undefined, false)).toMatchObject({ + notice: "Diff too large to display here.", + noticeActionable: false, + }); + expect(fileWith({ status: "loading" })).toMatchObject({ noticeActionable: false }); + expect(fileWith({ status: "error" })).toMatchObject({ + notice: "Couldn't load this diff. Tap to try again.", + noticeActionable: true, + }); + const loaded = fileWith({ status: "loaded", result: diff("large.ts") }); + expect(loaded).toMatchObject({ id: placeholder?.id, path: "large.ts" }); + expect(loaded?.notice).toBeUndefined(); + expect(loaded?.rows.length).toBeGreaterThan(0); + // The totals follow the loaded file, which may have changed since the page was read. + expect(merged).toMatchObject({ additions: 1, deletions: 1 }); + }); }); diff --git a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts index 9abf7cfc0c074..8ec7cea70bf32 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDiffPages.ts @@ -1,6 +1,10 @@ import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients"; import type { PullRequestDiffResult } from "@t3tools/contracts"; -import { buildReviewParsedDiff, type ReviewParsedDiff } from "../review/reviewModel"; +import { + buildReviewParsedDiff, + type ReviewParsedDiff, + type ReviewRenderableFile, +} from "../review/reviewModel"; export interface PullRequestDiffPage { readonly cursor: string | null; @@ -61,6 +65,7 @@ export function retainPullRequestDiffPage( (previous?.patch === result.patch && previous.truncated === result.truncated && previous.nextCursor === result.nextCursor && + previous.withheldFilesReadable === result.withheldFilesReadable && JSON.stringify(previous.omittedFileStats ?? []) === JSON.stringify(result.omittedFileStats ?? [])) ) @@ -84,7 +89,13 @@ export function combinePullRequestDiffPages( ); const files = value.files.map((file) => { const stat = omittedFileStats.get(file.path); - return stat ? { ...file, additions: stat.additions, deletions: stat.deletions } : file; + if (!stat) return file; + return { + ...file, + additions: stat.additions, + deletions: stat.deletions, + ...(file.rows.length === 0 ? { withheld: true } : {}), + }; }); value = { ...value, @@ -111,3 +122,63 @@ export function combinePullRequestDiffPages( : null, }; } + +export type WithheldFileLoad = + | { readonly status: "loading" | "error" } + | { readonly status: "loaded"; readonly result: PullRequestDiffResult }; + +const withheldFileParses = new WeakMap(); + +function parseWithheldFile(result: PullRequestDiffResult, scope: string) { + if (withheldFileParses.has(result)) return withheldFileParses.get(result) ?? null; + const parsed = buildReviewParsedDiff(result.patch, scope); + const file = + parsed.kind === "files" ? (parsed.files.find((entry) => entry.rows.length > 0) ?? null) : null; + withheldFileParses.set(result, file); + return file; +} + +function withheldFileNotice(load: WithheldFileLoad | undefined, canLoad: boolean): string { + if (load === undefined) { + return canLoad + ? "Diff too large to display. Tap to load it." + : "Diff too large to display here."; + } + if (load.status === "loading") return "Loading diff…"; + if (load.status === "error") return "Couldn't load this diff. Tap to try again."; + return "No text diff for this file."; +} + +/** + * Puts each loaded withheld file in place of its empty one, under the same id so folds and + * targets hold, and gives the rest a notice saying what a tap does. + */ +export function withWithheldFiles( + parsed: ReviewParsedDiff, + loads: ReadonlyMap, + canLoad: boolean, + scope: string, +): ReviewParsedDiff { + if (parsed.kind !== "files" || !parsed.files.some((file) => file.withheld)) return parsed; + const files = parsed.files.map((file): ReviewRenderableFile => { + if (!file.withheld) return file; + const load = loads.get(file.path); + const loaded = + load?.status === "loaded" + ? parseWithheldFile(load.result, `${scope}:withheld:${file.path}`) + : null; + if (loaded !== null) return { ...loaded, id: file.id }; + return { + ...file, + notice: withheldFileNotice(load, canLoad), + noticeTone: "warning", + noticeActionable: canLoad && (load === undefined || load.status === "error"), + }; + }); + return { + ...parsed, + files, + additions: files.reduce((total, file) => total + file.additions, 0), + deletions: files.reduce((total, file) => total + file.deletions, 0), + }; +} diff --git a/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts b/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts new file mode 100644 index 0000000000000..1f2d0d8582de1 --- /dev/null +++ b/apps/mobile/src/features/pull-requests/usePullRequestActivityFilter.ts @@ -0,0 +1,52 @@ +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { AsyncResult } from "effect/reactivity"; +import { useState } from "react"; +import type { PullRequestActivityVisibility } from "../../persistence/mobile-preferences"; +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { DEFAULT_ACTIVITY_FILTER, type ActivityFilter } from "./pullRequestActivityFilter"; + +const SHOW_EVERYTHING: PullRequestActivityVisibility = { bots: true, resolved: true }; + +/** + * Bot and resolved visibility is a saved preference. A timeline link shows everything for this + * screen only, until the user picks visibility themselves. + */ +export function usePullRequestActivityFilter(link: string | undefined) { + const preferences = useAtomValue(mobilePreferencesAtom); + const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const [view, setView] = useState(() => ({ + kind: link === "commits" ? ("commits" as const) : DEFAULT_ACTIVITY_FILTER.kind, + newestFirst: DEFAULT_ACTIVITY_FILTER.newestFirst, + linkVisibility: link === "timeline" ? SHOW_EVERYTHING : null, + })); + const saved = AsyncResult.isSuccess(preferences) + ? preferences.value.pullRequestActivityVisibility + : undefined; + const visibility = view.linkVisibility ?? saved ?? DEFAULT_ACTIVITY_FILTER; + const filter: ActivityFilter = { + kind: view.kind, + newestFirst: view.newestFirst, + bots: visibility.bots, + resolved: visibility.resolved, + }; + const visibilityChanged = (next: ActivityFilter) => + next.bots !== filter.bots || next.resolved !== filter.resolved; + return { + filter, + setFilter: (next: ActivityFilter) => { + if (visibilityChanged(next)) { + savePreferences({ + pullRequestActivityVisibility: { bots: next.bots, resolved: next.resolved }, + }); + } + setView((current) => ({ + kind: next.kind, + newestFirst: next.newestFirst, + linkVisibility: visibilityChanged(next) ? null : current.linkVisibility, + })); + }, + showTimeline: () => + setView((current) => ({ ...current, kind: "all", linkVisibility: SHOW_EVERYTHING })), + showCommits: () => setView((current) => ({ ...current, kind: "commits" })), + }; +} diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts index 6e49993a137f3..f091e5b6847d6 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts @@ -5,8 +5,9 @@ import { type PullRequestListEntry, type PullRequestSummary, } from "@t3tools/contracts"; -import { useAtomRefresh } from "@effect/atom-react"; -import { useLayoutEffect, useMemo, useState } from "react"; +import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react"; +import { Atom } from "effect/reactivity"; +import { useContext, useLayoutEffect, useMemo, useState } from "react"; import { composerPullRequests } from "../../state/pull-requests"; import { useEnvironmentQuery } from "../../state/query"; @@ -14,7 +15,9 @@ import { usePullToRefresh } from "../../state/use-pull-to-refresh"; import { getCachedPullRequestDiffPages, retainPullRequestDiffPage, + withWithheldFiles, type PullRequestDiffPage, + type WithheldFileLoad, } from "./pullRequestDiffPages"; export type PullRequestParams = { @@ -43,6 +46,26 @@ export function pullRequestTarget(params: PullRequestParams) { } const NO_PAGES: readonly PullRequestDiffPage[] = []; +const NO_PATHS: readonly string[] = []; + +type PullRequestDiffTarget = Parameters[0]; + +// Keyed by the diff's serialized target, which the hook already holds as its scope. +const withheldFileDiff = (targetKey: string, path: string) => { + const target = JSON.parse(targetKey) as PullRequestDiffTarget; + return composerPullRequests.diff({ ...target, input: { ...target.input, path } }); +}; + +// One read per withheld file the reader asked for, so only that file's diff crosses the wire. +const withheldFileDiffsAtom = Atom.family((key: string) => { + const { targetKey, paths } = JSON.parse(key) as { + readonly targetKey: string; + readonly paths: readonly string[]; + }; + return Atom.make((get) => paths.map((path) => get(withheldFileDiff(targetKey, path)))).pipe( + Atom.withLabel(`mobile:pull-request-withheld-file-diffs:${key}`), + ); +}); export function usePullRequestDiffEntry(navigation: { readonly addListener: ( @@ -116,10 +139,46 @@ export function usePullRequestDiff( }, [cursor, key, query.data, state.key, state.pages]); if (state.key !== key || state.pages !== pages) setState({ key, cursor, pages }); - const parsed = useMemo( + const [withheldLoads, setWithheldLoads] = useState<{ + readonly key: string; + readonly paths: readonly string[]; + }>({ key: "", paths: NO_PATHS }); + const withheldPaths = withheldLoads.key === key ? withheldLoads.paths : NO_PATHS; + const withheldResults = useAtomValue( + withheldFileDiffsAtom(JSON.stringify({ targetKey: key, paths: withheldPaths })), + ); + const registry = useContext(RegistryContext); + const refreshWithheldFiles = () => { + for (const path of withheldPaths) registry.refresh(withheldFileDiff(key, path)); + }; + const loadWithheldFile = (path: string) => { + // The read is keyed without the head, so even a first load must not reuse an older one. + registry.refresh(withheldFileDiff(key, path)); + if (!withheldPaths.includes(path)) setWithheldLoads({ key, paths: [...withheldPaths, path] }); + }; + // A refetch keeps showing the last patch, whose lines may not exist at the new head. + const withheldRefetching = withheldResults.some((result) => result.waiting); + const loads = new Map(); + withheldPaths.forEach((path, index) => { + const result = withheldResults[index]; + if (result === undefined) return; + // A failed refetch still carries the last patch; show the failure instead. + loads.set( + path, + result._tag === "Failure" + ? { status: "error" } + : result._tag === "Success" + ? { status: "loaded", result: result.value } + : { status: "loading" }, + ); + }); + const pagesParsed = useMemo( () => getCachedPullRequestDiffPages(pages, key, terminology), [key, pages, terminology], ); + // The server says whether a withheld file can be read alone; GitHub may refuse the whole diff. + const withheldFilesReadable = pages[0]?.result.withheldFilesReadable === true; + const parsed = withWithheldFiles(pagesParsed, loads, withheldFilesReadable, key); const patch = useMemo(() => pages.map((page) => page.result.patch).join("\n"), [pages]); const nextCursor = pages.at(-1)?.result.nextCursor ?? null; const canLoadMore = @@ -136,15 +195,19 @@ export function usePullRequestDiff( } setState({ key, cursor: null, pages: NO_PAGES }); refreshFirstPage(); + refreshWithheldFiles(); }; const onPullRefresh = () => { setState({ key, cursor: null, pages: NO_PAGES }); onRefresh(); + refreshWithheldFiles(); }; return { ...query, refresh, parsed, + loadWithheldFile, + withheldRefetching, patch, nextCursor, canLoadMore, diff --git a/apps/mobile/src/features/pull-requests/usePullRequestList.ts b/apps/mobile/src/features/pull-requests/usePullRequestList.ts index d4fe1ab3461bd..8ba0721fd7fb5 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestList.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestList.ts @@ -1,3 +1,8 @@ +import { + editHeldPullRequestListEntries, + pullRequestHostAnswer, + pullRequestPendingEditsFor, +} from "@t3tools/client-runtime/state/pull-requests"; import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react"; import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts"; @@ -31,7 +36,10 @@ type Read = (atom: Atom.Atom) => A; /** The head the list query holds now, cached or answered. */ function currentHead(read: Read, target: ListTarget) { - return AsyncResult.getOrElse(read(composerPullRequests.list(target)), () => null); + return AsyncResult.getOrElse( + read(pullRequestHostAnswer(composerPullRequests.list(target))), + () => null, + ); } function currentPages(read: Read, target: ListTarget): PullRequestListPages | null { @@ -44,12 +52,23 @@ function currentPages(read: Read, target: ListTarget): PullRequestListPages | nu const sourcesFamily = Atom.family((key: string) => { const targets: readonly ListTarget[] = JSON.parse(key); return Atom.make((get) => - targets.map((target) => ({ - target, - result: get(composerPullRequests.list(target)), - pages: currentPages(get, target), - stats: get(pullRequestListStatsFamily(target.environmentId)), - })), + targets.map((target) => { + const pages = currentPages(get, target); + return { + target, + result: get(composerPullRequests.list(target)), + pages: + pages === null + ? null + : { + ...pages, + entries: editHeldPullRequestListEntries(target.input, pages.entries, (entry) => + get(pullRequestPendingEditsFor(target.environmentId, entry)), + ), + }, + stats: get(pullRequestListStatsFamily(target.environmentId)), + }; + }), ); }); @@ -71,7 +90,7 @@ async function loadNextPages( continuations(registry, targets).map(async ({ target, pages, input }) => { const response = await executeAtomQuery( registry, - composerPullRequests.list({ ...target, input }), + pullRequestHostAnswer(composerPullRequests.list({ ...target, input })), { signal, refresh: retry, @@ -113,11 +132,15 @@ async function refreshHeads( input: {}, }); if (signal.aborted) return; - const response = await executeAtomQuery(registry, composerPullRequests.list(target), { - refresh: true, - signal, - reportFailure: false, - }); + const response = await executeAtomQuery( + registry, + pullRequestHostAnswer(composerPullRequests.list(target)), + { + refresh: true, + signal, + reportFailure: false, + }, + ); if (signal.aborted) return; if (response._tag === "Failure") throw squashAtomCommandFailure(response); registry.set( diff --git a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts index e943fd5c57928..63372efb661bc 100644 --- a/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts +++ b/apps/mobile/src/features/review/nativeReviewDiffAdapter.ts @@ -1,3 +1,4 @@ +import { cutLineNoteStart } from "@t3tools/shared/diffCutLines"; import type { NativeReviewDiffRow, NativeReviewDiffTheme } from "../diffs/nativeReviewDiffSurface"; import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes"; import * as Arr from "effect/Array"; @@ -226,6 +227,8 @@ export function createNativeReviewDiffTheme( deleteBar: terminalRed ?? "#ff2e3f", addText: "#5ECC71", deleteText: "#FF6762", + warningText: nativeColor(appTheme["--color-warning-foreground"]), + warningBackground: nativeColor(appTheme["--color-warning"]), }; } @@ -243,6 +246,8 @@ export function createNativeReviewDiffTheme( deleteBar: terminalRed ?? "#ff2e3f", addText: "#199F43", deleteText: "#D52C36", + warningText: nativeColor(appTheme["--color-warning-foreground"]), + warningBackground: nativeColor(appTheme["--color-warning"]), }; } @@ -270,7 +275,15 @@ function createNoticeRow(fileId: string, suffix: string, text: string): NativeRe } function noticeRowsForFile(file: ReviewRenderableFile): ReadonlyArray { - if (file.notice) return [createNoticeRow(file.id, "loading", file.notice)]; + if (file.notice) { + return [ + { + ...createNoticeRow(file.id, "loading", file.notice), + ...(file.noticeTone === undefined ? {} : { tone: file.noticeTone }), + ...(file.noticeActionable ? { actionable: true } : {}), + }, + ]; + } if (file.rows.length > 0) { return []; } @@ -388,6 +401,7 @@ function mapLineRow( row: ReviewRenderableLineRow, rowIndex: number, ): NativeReviewDiffRow { + const noteStart = cutLineNoteStart(row.content); return { kind: "line", id: `${file.id}:line:${rowIndex}:${row.id}`, @@ -396,6 +410,7 @@ function mapLineRow( change: row.change, oldLineNumber: row.oldLineNumber, newLineNumber: row.newLineNumber, + ...(noteStart === null ? {} : { noteStart }), }; } diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts index df3c7c51324b4..3a1028dbb1730 100644 --- a/apps/mobile/src/features/review/reviewModel.ts +++ b/apps/mobile/src/features/review/reviewModel.ts @@ -56,6 +56,11 @@ export interface ReviewRenderableFile { readonly id: string; readonly cacheKey: string; readonly notice?: string; + readonly noticeTone?: "warning"; + /** The notice row reports taps, as for loading a withheld file's diff. */ + readonly noticeActionable?: boolean; + /** The host left out this file's hunks as too large; it can be loaded on its own. */ + readonly withheld?: boolean; readonly path: string; readonly previousPath: string | null; readonly changeType: ChangeTypes; diff --git a/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx index c0f93d2ee324d..1b34022d4cae5 100644 --- a/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsClientStorageRouteScreen.tsx @@ -72,10 +72,10 @@ export function SettingsClientStorageRouteScreen() { {AsyncResult.isFailure(summaryResult) ? ( diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx index 173e0cb62c624..82dc526d3de0c 100644 --- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx +++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx @@ -893,7 +893,7 @@ function ThreadTerminal(props: { title="No terminal sessions" detail="Existing terminals will appear here when another client opens one." /> - ) : !canOperateTerminal && terminal.error !== null ? ( + ) : terminal.error !== null && (!canOperateTerminal || terminal.status === "error") ? ( ) : ( <> diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 73b985fc20144..3e905bd2209c1 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -31,7 +31,6 @@ import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-e import { childThreadInputsTitle, type CodexFeedbackSubmission, - type EnvironmentThreadStatus, } from "@t3tools/client-runtime/state/threads"; import { useKeyboardScrollToEnd } from "@legendapp/list/keyboard"; import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills"; @@ -269,7 +268,6 @@ export interface ThreadDetailScreenProps { readonly respondingUserInputId: RuntimeRequestId | null; readonly connectionStateLabel: EnvironmentConnectionPhase; readonly connectionAwaitingApproval?: boolean; - readonly threadSyncStatus?: EnvironmentThreadStatus; readonly historyControls?: ThreadFeedHistoryControls; readonly activeThreadBusy: boolean; readonly canStopThread: boolean; @@ -568,20 +566,6 @@ function ThreadDetailBody( ); const composerKeyboardOffset = composerBottomInset; const contentPresentationKind = props.contentPresentation.kind; - const realThreadSyncLabel = (() => { - switch (props.threadSyncStatus) { - case "empty": - case "cached": - case "synchronizing": - if (contentPresentationKind === "ready") { - return "Syncing messages..."; - } - return contentPresentationKind === "loading" ? "Loading messages..." : null; - default: - return null; - } - })(); - const threadSyncLabel = useDelayedStatus(selectedThreadKey, realThreadSyncLabel); const connectionRetrying = props.connectionStateLabel === "connecting" || props.connectionStateLabel === "reconnecting"; const retryError = connectionRetrying ? props.connectionError : null; @@ -804,18 +788,13 @@ function ThreadDetailBody( return null; } if (props.creationState?.kind === "preparing") { - if (props.worktreeSetup) return null; - return { - kind: "preparing", - label: props.creationState.preparingWorktree ? "Setting up worktree…" : "Starting…", - }; + // The feed shows worktree setup in place, so only a plain start needs the pill. + if (props.worktreeSetup || props.creationState.preparingWorktree) return null; + return { kind: "preparing", label: "Starting…" }; } if (props.creationState?.kind === "failed") { return null; } - if (threadSyncLabel !== null) { - return { kind: "syncing", label: threadSyncLabel }; - } const childInput = childThreadInputs[0]; if (childInput && contentPresentationKind === "ready") { return { @@ -1493,6 +1472,11 @@ function ThreadDetailBody( pendingHandoff={props.pendingHandoff} worktreeSetup={props.worktreeSetup} setupWorkingStartedAt={props.setupWorkingStartedAt} + preparingWorktree={ + props.creationState?.kind === "preparing" && + props.creationState.preparingWorktree && + !props.worktreeSetup + } queuedMessages={props.queuedMessages} dispatchingMessageId={props.dispatchingMessageId} // A native subagent has no composer to edit a pending message in; diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index f1a9c93f77db3..b85825fef89bc 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -26,6 +26,7 @@ import { LinkRequestCard } from "./LinkRequestCard"; import { SecretRequestCard } from "./SecretRequestCard"; import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { + WorktreePreparingHeader, WorktreeWorkingHeader, WorktreeSetupCard, type WorktreeSetupCardProps, @@ -288,7 +289,7 @@ import { import { ZoomableImagePressable } from "./ZoomableImagePressable"; import { openSettings } from "../settings/settings-navigation"; import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; -import { formatMessageTimestamp } from "./messageTimestamp"; +import { useMessageTimeFormatter } from "./useMessageTimeFormatter"; const WIDE_MARKDOWN_BLOCK_OPTIONS = { // iOS blockquotes and selectable text measure separately; definite bubble width matches UIKit's drawing width. @@ -321,6 +322,7 @@ export interface ThreadFeedProps { readonly toolCallVisibility?: ToolCallVisibility; readonly worktreeSetup?: WorktreeSetupCardProps | null; readonly setupWorkingStartedAt?: string | null; + readonly preparingWorktree?: boolean; readonly queuedMessages: ReadonlyArray; readonly dispatchingMessageId: MessageId | null; readonly onEditPendingMessage: ((message: QueuedThreadMessage) => void) | null; @@ -1667,6 +1669,7 @@ function renderFeedEntry( | "threadId" | "workspaceRoot" > & { + readonly formatMessageTime: (input: string) => string; readonly copiedRowId: string | null; readonly expandedWorkRows: Record; readonly workRowSizing: ReturnType; @@ -1912,7 +1915,7 @@ function renderFeedEntry( const presentation = resolveUserMessagePresentation(message); const renderedText = renderAssistantCitationsAsText(presentation.text); const styles = isUser ? markdownStyles.user : markdownStyles.assistant; - const timestampLabel = formatMessageTimestamp(isUser ? message.createdAt : message.updatedAt); + const timestampLabel = props.formatMessageTime(isUser ? message.createdAt : message.updatedAt); const attachments = message.attachments ?? []; const hasReviewCommentContext = presentation.text.includes(" { @@ -3751,6 +3759,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ) : null} {renderFeedEntry(info, { userMessageGrouping: info.item.userMessageGrouping, + formatMessageTime, environmentId: props.environmentId, dispatchingMessageId: props.dispatchingMessageId, onEditPendingMessage: props.onEditPendingMessage, @@ -3796,6 +3805,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ) : props.setupWorkingStartedAt && info.index === setupAnchorIndex ? ( + ) : props.preparingWorktree && info.index === setupAnchorIndex ? ( + ) : null} @@ -3892,6 +3903,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { {usesNativeAutomaticInsets ? null : } {setupAnchorIndex < 0 && props.worktreeSetup ? ( + ) : setupAnchorIndex < 0 && props.preparingWorktree ? ( + ) : null} {props.historyControls ? ( diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 51e1e7182ae5a..b60991731e0d7 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -51,6 +51,7 @@ import { vcsEnvironment } from "../../state/vcs"; import { EmptyState } from "../../components/ui/EmptyState"; import { LoadingScreen } from "../../components/LoadingScreen"; import { scopedThreadKey } from "../../lib/scopedEntities"; +import { useDelayedStatus } from "../../lib/useDelayedStatus"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { useThreadShell } from "../../state/entities"; import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; @@ -95,7 +96,10 @@ import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread- import { threadEnvironment } from "../../state/threads"; import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/threads"; import { useProjects } from "../../state/entities"; -import { projectThreadContentPresentation } from "./threadContentPresentation"; +import { + projectThreadContentPresentation, + threadSyncStatusLabel, +} from "./threadContentPresentation"; import { Inspector, useAdaptiveWorkspaceLayout, @@ -290,8 +294,11 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) { } if (selectedThread !== null && selectedThreadKey === routeThreadKey) { - return withInspectorHeader( - , + // ThreadRouteContent draws its own inspector header so it can show the sync status. + return ( + + + ); } @@ -944,14 +951,6 @@ function ThreadRouteContent( serverOwned: false, }; })(); - if (!environmentId || !threadId) { - return ; - } - - if (!selectedThread) { - return ; - } - // Queued creation displays its prompt before server creation; temporary not-found is expected. const contentPresentation = creationState !== null @@ -962,6 +961,27 @@ function ThreadRouteContent( detailDeleted: selectedThreadDetailState.status === "deleted", connectionState: routeConnectionState, }); + // Shown in the header subtitle so the composer's status slot doesn't jump while history syncs. + const threadSyncLabel = useDelayedStatus( + selectedThread === null ? "" : scopedThreadKey(selectedThread.environmentId, selectedThread.id), + threadSyncStatusLabel(selectedThreadDetailState.status, contentPresentation.kind), + ); + const inspectorHeader = props.inspectorPresentation ? ( + + ) : null; + if (!environmentId || !threadId || !selectedThread) { + return ( + <> + {inspectorHeader} + + + ); + } + const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null; const renderThreadRouteBody = () => ( <> @@ -977,7 +997,7 @@ function ThreadRouteContent( props.inspectorPresentation ? null : ( + {inspectorHeader} {!props.inspectorPresentation && inspectorContent ? ( setComposerDraftText(draftKey, text)} reportedModelSelection={reportedModelSelection} - onSelectModel={(option) => updateModelSelection(withRememberedModelOptions(option.selection))} + onSelectModel={(option) => + updateModelSelection( + withStoredThreadModelOptions( + withRememberedModelOptions(option.selection), + selectedThread.modelSelection, + ), + ) + } restoreSelection={withRememberedModelOptions} optionDescriptors={resolveProviderOptionDescriptors({ capabilities: currentModelOption?.capabilities, diff --git a/apps/mobile/src/features/threads/floating-working-control.tsx b/apps/mobile/src/features/threads/floating-working-control.tsx index 55028a58b7df2..0f83743f99d31 100644 --- a/apps/mobile/src/features/threads/floating-working-control.tsx +++ b/apps/mobile/src/features/threads/floating-working-control.tsx @@ -427,21 +427,6 @@ function FloatingStatusLabel(props: { ); } - if (props.status.kind === "syncing") { - return ( - - - - {props.status.label} - - - ); - } if (props.status.kind === "compacting") { return ; } diff --git a/apps/mobile/src/features/threads/floating-working-status.ts b/apps/mobile/src/features/threads/floating-working-status.ts index 6beb9cb6cb01a..941a875c9500c 100644 --- a/apps/mobile/src/features/threads/floating-working-status.ts +++ b/apps/mobile/src/features/threads/floating-working-status.ts @@ -10,7 +10,6 @@ export interface FloatingStatusAction { export type FloatingWorkingStatus = | { readonly kind: "working"; readonly environmentId: EnvironmentId; readonly startedAt: string } - | { readonly kind: "syncing"; readonly label: string } | { readonly kind: "compacting" } | { readonly kind: "child-input"; diff --git a/apps/mobile/src/features/threads/messageTimestamp.test.ts b/apps/mobile/src/features/threads/messageTimestamp.test.ts index 94f6010acd4a1..fa1ab4be779b3 100644 --- a/apps/mobile/src/features/threads/messageTimestamp.test.ts +++ b/apps/mobile/src/features/threads/messageTimestamp.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { formatMessageTimestamp } from "./messageTimestamp"; +import { createMessageTimeFormatter, formatMessageTimestamp } from "./messageTimestamp"; describe("formatMessageTimestamp", () => { const now = new Date(2026, 10, 8, 20, 0).getTime(); @@ -20,3 +20,15 @@ describe("formatMessageTimestamp", () => { ); }); }); + +describe("createMessageTimeFormatter", () => { + const now = new Date(2026, 0, 1, 20, 0).getTime(); + + it("follows the system clock preference over the locale's hour cycle", () => { + const format24 = createMessageTimeFormatter(true, "en-US"); + expect(format24(new Date(2026, 0, 1, 15, 7).toISOString(), now)).toBe("15:07"); + expect(format24(new Date(2026, 0, 1, 0, 7).toISOString(), now)).toBe("00:07"); + const format12 = createMessageTimeFormatter(false, "en-GB"); + expect(format12(new Date(2026, 0, 1, 15, 7).toISOString(), now)).toMatch(/^3:07\spm$/i); + }); +}); diff --git a/apps/mobile/src/features/threads/messageTimestamp.ts b/apps/mobile/src/features/threads/messageTimestamp.ts index 5624b71c0c917..cfae85e092666 100644 --- a/apps/mobile/src/features/threads/messageTimestamp.ts +++ b/apps/mobile/src/features/threads/messageTimestamp.ts @@ -7,13 +7,28 @@ const DATE_WITH_YEAR_FORMATTER = new Intl.DateTimeFormat(undefined, { }); /** Time only for today's messages; older ones lead with the day and month. */ -export function formatMessageTimestamp(input: string, nowMs: number = Date.now()): string { +export function formatMessageTimestamp( + input: string, + nowMs: number = Date.now(), + timeFormatter: Intl.DateTimeFormat = TIME_FORMATTER, +): string { const timestamp = Date.parse(input); if (Number.isNaN(timestamp)) return ""; const date = new Date(timestamp); const now = new Date(nowMs); - const time = TIME_FORMATTER.format(date); + const time = timeFormatter.format(date); if (date.toDateString() === now.toDateString()) return time; const sameYear = date.getFullYear() === now.getFullYear(); return `${(sameYear ? DATE_FORMATTER : DATE_WITH_YEAR_FORMATTER).format(date)} ${time}`; } + +/** `is24Hour` overrides the locale's hour cycle with the system clock preference when known. */ +export function createMessageTimeFormatter(is24Hour: boolean | undefined, locale?: string) { + const timeFormatter = new Intl.DateTimeFormat(locale, { + hour: "numeric", + minute: "2-digit", + ...(is24Hour === undefined ? {} : { hourCycle: is24Hour ? "h23" : "h12" }), + }); + return (input: string, nowMs?: number): string => + formatMessageTimestamp(input, nowMs, timeFormatter); +} diff --git a/apps/mobile/src/features/threads/thread-inspector-preview.tsx b/apps/mobile/src/features/threads/thread-inspector-preview.tsx index d41d1f0c7e9b1..c2d3a96c34ec7 100644 --- a/apps/mobile/src/features/threads/thread-inspector-preview.tsx +++ b/apps/mobile/src/features/threads/thread-inspector-preview.tsx @@ -22,12 +22,13 @@ export type ThreadInspectorPresentation = | { readonly onClose: () => void }; export function ThreadInspectorHeader( - props: ThreadInspectorPresentation & { readonly title: string }, + props: ThreadInspectorPresentation & { readonly title: string; readonly subtitle?: string }, ) { if ("onMaximize" in props) { return ( + ); } diff --git a/apps/mobile/src/features/threads/threadContentPresentation.ts b/apps/mobile/src/features/threads/threadContentPresentation.ts index a180ed7594db0..46cc5a6d43f72 100644 --- a/apps/mobile/src/features/threads/threadContentPresentation.ts +++ b/apps/mobile/src/features/threads/threadContentPresentation.ts @@ -1,4 +1,5 @@ import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; +import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads"; export type ThreadContentPresentation = | { readonly kind: "ready" } @@ -45,3 +46,12 @@ export function projectThreadContentPresentation(input: { detail: "Reconnect this environment to load the conversation.", }; } + +export function threadSyncStatusLabel( + status: EnvironmentThreadStatus, + presentation: ThreadContentPresentation["kind"], +): string | null { + if (status !== "empty" && status !== "cached" && status !== "synchronizing") return null; + if (presentation === "ready") return "Syncing messages…"; + return presentation === "loading" ? "Loading messages…" : null; +} diff --git a/apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts b/apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts index c29ef5eea7aa5..ea03de50e4de7 100644 --- a/apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts +++ b/apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts @@ -1,4 +1,6 @@ +import { ComposerContextId } from "@t3tools/contracts"; import { formatAssistantCitationHref } from "@t3tools/shared/assistantCitations"; +import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences"; import { describe, expect, it } from "vite-plus/test"; import { resolveThreadQueueRowControls } from "./threadQueueControlPresentation"; @@ -47,6 +49,33 @@ describe("threadQueueControlPresentation", () => { ); }); + it("shows context chips by their labels", () => { + const environment = formatComposerContextReference({ + kind: "environment", + contextId: ComposerContextId.make("environment_mac"), + label: "MacBook", + }); + const file = formatComposerContextReference({ + kind: "file", + contextId: ComposerContextId.make("report"), + label: "report.pdf", + }); + const image = formatComposerContextReference({ + kind: "image", + contextId: ComposerContextId.make("screenshot"), + label: "screenshot.png", + }); + + expect( + resolveThreadQueueRowControls({ + busy: false, + canPromoteToSteer: true, + canSendNow: false, + text: `Check ${environment} for ${file} ${image} `, + }).displayText, + ).toBe("Check MacBook for report.pdf screenshot.png"); + }); + it("keeps the row already open in the composer from being reopened or steered", () => { const editing = resolveThreadQueueRowControls({ busy: false, diff --git a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts index a62e29e14795d..ed5482b830d82 100644 --- a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts +++ b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts @@ -1,6 +1,9 @@ import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; -import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences"; +import { + isAttachmentOnlyBootstrapPrompt, + replaceComposerContextReferences, +} from "@t3tools/shared/composerContextReferences"; export const REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL = "Remove queued message"; @@ -38,7 +41,9 @@ export function resolveThreadQueueRowControls(input: { // Editing and sending keep the original text so quoted citations stay linked. displayText: isAttachmentOnlyBootstrapPrompt(input.text) ? "" - : assistantCitationsToPlainText(input.text), + : assistantCitationsToPlainText( + replaceComposerContextReferences(input.text, (reference) => reference.label), + ).trim(), isEditing, }; } diff --git a/apps/mobile/src/features/threads/useMessageTimeFormatter.ts b/apps/mobile/src/features/threads/useMessageTimeFormatter.ts new file mode 100644 index 0000000000000..2320d369762ca --- /dev/null +++ b/apps/mobile/src/features/threads/useMessageTimeFormatter.ts @@ -0,0 +1,22 @@ +import { requireNativeModule } from "expo"; +import { useEffect, useMemo, useState } from "react"; +import { AppState, Platform } from "react-native"; +import { createMessageTimeFormatter } from "./messageTimestamp"; + +function systemUses24HourClock() { + if (Platform.OS !== "android") return undefined; + return requireNativeModule<{ is24HourFormat(): boolean }>("T3NativeControls").is24HourFormat(); +} + +export function useMessageTimeFormatter() { + const [is24Hour, setIs24Hour] = useState(systemUses24HourClock); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Refresh the native clock preference when Android returns to the foreground. + useEffect(() => { + if (Platform.OS !== "android") return; + const subscription = AppState.addEventListener("change", (state) => { + if (state === "active") setIs24Hour(systemUses24HourClock()); + }); + return () => subscription.remove(); + }, []); + return useMemo(() => createMessageTimeFormatter(is24Hour), [is24Hour]); +} diff --git a/apps/mobile/src/features/threads/worktree-setup-card.tsx b/apps/mobile/src/features/threads/worktree-setup-card.tsx index ce2fd4abc0b0e..b5ce9d10de107 100644 --- a/apps/mobile/src/features/threads/worktree-setup-card.tsx +++ b/apps/mobile/src/features/threads/worktree-setup-card.tsx @@ -147,6 +147,17 @@ export function WorktreeSetupCard(props: WorktreeSetupCardProps) { ); } +/** Holds the card's place until the server publishes the first setup snapshot. */ +export function WorktreePreparingHeader() { + return ( + + + + + + ); +} + export function WorktreeWorkingHeader({ startedAt }: { startedAt: string }) { const now = useVisibleSecondClock(true); return ( diff --git a/apps/mobile/src/lib/enrichedLinkPresentation.test.ts b/apps/mobile/src/lib/enrichedLinkPresentation.test.ts index 4dd5ecbd08317..771674cc4eff6 100644 --- a/apps/mobile/src/lib/enrichedLinkPresentation.test.ts +++ b/apps/mobile/src/lib/enrichedLinkPresentation.test.ts @@ -34,6 +34,8 @@ describe("Enriched link presentation", () => { "https://example.com/app.tsx", "x + y", "README.md", + "Dockerfile", + "docker/Dockerfiles", "/app/settings", ]) { expect(ENRICHED_INLINE_FILE_LINK_REGEX.test(text), text).toBe(false); diff --git a/apps/mobile/src/lib/enrichedLinkPresentation.ts b/apps/mobile/src/lib/enrichedLinkPresentation.ts index 5d2e9431339d1..f31d8659b6614 100644 --- a/apps/mobile/src/lib/enrichedLinkPresentation.ts +++ b/apps/mobile/src/lib/enrichedLinkPresentation.ts @@ -17,6 +17,7 @@ import { parseComposerContextHref, } from "@t3tools/shared/composerContextReferences"; import { hasThreadLinks, parseThreadLinkHref } from "@t3tools/shared/threadLinks"; +import { EXTENSIONLESS_FILE_NAMES } from "@t3tools/shared/markdownLinks"; export function enrichedContextLinkPresentation( href: string, @@ -91,8 +92,14 @@ export function enrichedLinkVariantPattern(url: string) { return `^${url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`; } -export const ENRICHED_INLINE_FILE_LINK_REGEX = - /^(?!\S*:\/\/)(?:(?:\.{1,2}[\\/]|~[\\/]|\/(?:Users|home|tmp|var|etc|opt|mnt|Volumes|private|root|usr|bin|sbin|lib|lib64|srv|dev|proc|sys|run|boot|media|workspace|workspaces)\/|[A-Za-z]:[\\/])[^\s`]+|(?:[\p{L}\p{M}\p{N}._-]+[\\/])+[\p{L}\p{M}\p{N}._-]+\.[A-Za-z0-9_-]+(?::\d+(?::\d+|-\d+)?)?|[\p{L}\p{M}\p{N}._-]+\.[A-Za-z0-9_-]+:\d+(?::\d+|-\d+)?)$/u; +const EXTENSIONLESS_FILE_NAME_PATTERN = [...EXTENSIONLESS_FILE_NAMES] + .map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) + .join("|"); + +export const ENRICHED_INLINE_FILE_LINK_REGEX = new RegExp( + String.raw`^(?!\S*:\/\/)(?:(?:\.{1,2}[\\/]|~[\\/]|\/(?:Users|home|tmp|var|etc|opt|mnt|Volumes|private|root|usr|bin|sbin|lib|lib64|srv|dev|proc|sys|run|boot|media|workspace|workspaces)\/|[A-Za-z]:[\\/])[^\s\x60]+|(?:[\p{L}\p{M}\p{N}._-]+[\\/])+(?:[\p{L}\p{M}\p{N}._-]+\.[A-Za-z0-9_-]+|(?:${EXTENSIONLESS_FILE_NAME_PATTERN}))(?::\d+(?::\d+|-\d+)?)?|[\p{L}\p{M}\p{N}._-]+\.[A-Za-z0-9_-]+:\d+(?::\d+|-\d+)?)$`, + "u", +); export function enrichedSkillLinkRegex(skills?: ReadonlyArray) { const names = [...new Set(skills?.map((skill) => skill.name) ?? [])].filter(Boolean); diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index 8363b0ba5c958..2c7a7313e47e9 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -113,6 +113,7 @@ vi.mock("../components/ui/Button", () => ({ createElement("button", { onClick: props.onPress, disabled: props.disabled }, props.label), })); vi.mock("expo", () => ({ + requireNativeModule: () => ({ is24HourFormat: () => true }), useEvent: (_player: unknown, _event: unknown, initial: unknown) => initial, useReleasingSharedObjectWithLifecycle: ( lifecycle: { diff --git a/apps/mobile/src/lib/markdownInlineFileLinks.test.ts b/apps/mobile/src/lib/markdownInlineFileLinks.test.ts index e2d81cf869561..3de6590dc7a4b 100644 --- a/apps/mobile/src/lib/markdownInlineFileLinks.test.ts +++ b/apps/mobile/src/lib/markdownInlineFileLinks.test.ts @@ -93,7 +93,13 @@ describe("inline code that names a file", () => { expect(rewrite("See `src/math.ts:2` and `./README.md`.")).toBe( "See [src/math.ts:2]() and [./README.md](<./README.md>).", ); - for (const path of ["src/數學.ts:2", "數學/math.ts:2", "數學.ts:2", "src/數學.ts:2-4"]) { + for (const path of [ + "src/數學.ts:2", + "數學/math.ts:2", + "數學.ts:2", + "src/數學.ts:2-4", + "docker/Dockerfile", + ]) { expect(rewrite(`See \`${path}\`.`), path).toBe(`See [${path}](<${path}>).`); } }); diff --git a/apps/mobile/src/lib/modelOptions.test.ts b/apps/mobile/src/lib/modelOptions.test.ts index c7d9cd6beebb6..5bf37c345b45c 100644 --- a/apps/mobile/src/lib/modelOptions.test.ts +++ b/apps/mobile/src/lib/modelOptions.test.ts @@ -22,6 +22,7 @@ import { resolvePendingHandoffTarget, resolveSelectableModelSelection, resolveUsageLimitPoolSelection, + withStoredThreadModelOptions, type ModelOption, } from "./modelOptions"; @@ -195,6 +196,27 @@ describe("mobile model options", () => { expect(explicitOption?.selection.options).toEqual([{ id: "serviceTier", value: "priority" }]); }); + it("carries a thread's stored options onto an optionless pick of its own model", () => { + const claude = ProviderInstanceId.make("claudeAgent"); + const stored: ModelSelection = { + instanceId: claude, + model: "claude-opus-5-5", + options: [{ id: "effort", value: "high" }], + }; + expect( + withStoredThreadModelOptions({ instanceId: claude, model: stored.model }, stored), + ).toEqual(stored); + const remembered: ModelSelection = { ...stored, options: [{ id: "effort", value: "low" }] }; + expect(withStoredThreadModelOptions(remembered, stored)).toBe(remembered); + const otherInstance: ModelSelection = { + instanceId: ProviderInstanceId.make("claude_work"), + model: stored.model, + }; + expect(withStoredThreadModelOptions(otherInstance, stored)).toBe(otherInstance); + const otherModel: ModelSelection = { instanceId: claude, model: "claude-sonnet-5-5" }; + expect(withStoredThreadModelOptions(otherModel, stored)).toBe(otherModel); + }); + it("limits existing threads to their provider while new tasks keep every provider", () => { const providers = ["codex", "claudeAgent"].map((instanceId) => ({ instanceId, diff --git a/apps/mobile/src/lib/modelOptions.ts b/apps/mobile/src/lib/modelOptions.ts index c9c3d7cee853a..8f784b6c57727 100644 --- a/apps/mobile/src/lib/modelOptions.ts +++ b/apps/mobile/src/lib/modelOptions.ts @@ -351,6 +351,22 @@ export function resolveNewTaskModelSelection(input: { ); } +// Rows built after a pick on another instance carry no options for the thread's own model. +export function withStoredThreadModelOptions( + selection: ModelSelection, + stored: ModelSelection, +): ModelSelection { + if ( + (selection.options?.length ?? 0) > 0 || + !stored.options?.length || + selection.instanceId !== stored.instanceId || + selection.model !== stored.model + ) { + return selection; + } + return { ...selection, options: stored.options }; +} + export function buildModelOptions( config: T3ServerConfig | null | undefined, fallbackModelSelection: ModelSelection | null, diff --git a/apps/mobile/src/lib/videoThumbnails.test.ts b/apps/mobile/src/lib/videoThumbnails.test.ts index 155a906143a26..a35e62b98ae71 100644 --- a/apps/mobile/src/lib/videoThumbnails.test.ts +++ b/apps/mobile/src/lib/videoThumbnails.test.ts @@ -5,11 +5,20 @@ vi.mock("expo-video", () => ({ createVideoPlayer: mocks.createPlayer })); let thumbnails: typeof import("./videoThumbnails"); const frame = { width: 480, height: 270 }; -const player = () => ({ - replaceAsync: vi.fn(async (): Promise => {}), - generateThumbnailsAsync: vi.fn(async () => [frame]), - release: vi.fn(), -}); +const player = () => { + const listeners = new Set<(event: { source: unknown }) => void>(); + const attach = () => listeners.forEach((listener) => listener({ source: {} })); + return { + attach, + addListener: vi.fn((_event: string, listener: (event: { source: unknown }) => void) => { + listeners.add(listener); + return { remove: () => listeners.delete(listener) }; + }), + replaceAsync: vi.fn(async (): Promise => queueMicrotask(attach)), + generateThumbnailsAsync: vi.fn(async () => [frame]), + release: vi.fn(), + }; +}; const source = () => ({ uri: "file:///clip.mp4", dispose: vi.fn() }); beforeEach(async () => { @@ -51,7 +60,7 @@ describe("video thumbnails", () => { expect(first.release).toHaveBeenCalledTimes(1); }); - it("releases an active canceled player and ignores late source loading", async () => { + it("finishes a started extraction after its reader leaves so a re-signed URL reuses it", async () => { const started = Promise.withResolvers(); const replaced = Promise.withResolvers(); const first = player(); @@ -62,21 +71,71 @@ describe("video thumbnails", () => { mocks.createPlayer.mockReturnValueOnce(first); const file = source(); const controller = new AbortController(); - const request = thumbnails.loadVideoThumbnail("canceled", async () => file, controller.signal); + const request = thumbnails.loadVideoThumbnail("video", async () => file, controller.signal); await started.promise; controller.abort(); - expect(await request).toBeNull(); + const resigned = thumbnails.loadVideoThumbnail( + "video", + async () => source(), + new AbortController().signal, + ); + replaced.resolve(); + first.attach(); + expect(await request).toBe(frame); + expect(await resigned).toBe(frame); + expect(mocks.createPlayer).toHaveBeenCalledTimes(1); expect(first.release).toHaveBeenCalledTimes(1); expect(file.dispose).toHaveBeenCalledTimes(1); - replaced.resolve(); - expect( - await thumbnails.loadVideoThumbnail( - "next", - async () => source(), - new AbortController().signal, - ), - ).toBe(frame); + }); + + it("asks for a frame only once the player has attached the item", async () => { + const first = player(); + let attached = false; + // Like iOS: replaceAsync resolves before the item attaches, and until then + // generateThumbnailsAsync finds no asset. + first.replaceAsync.mockImplementation(async () => {}); + first.generateThumbnailsAsync.mockImplementation(async () => (attached ? [frame] : [])); + mocks.createPlayer.mockReturnValueOnce(first); + const request = thumbnails.loadVideoThumbnail( + "attach", + async () => source(), + new AbortController().signal, + ); + await vi.waitFor(() => expect(first.replaceAsync).toHaveBeenCalled()); + await first.replaceAsync.mock.results[0]!.value; + attached = true; + first.attach(); + expect(await request).toBe(frame); + }); + + it("gives up on an item that never attaches without holding up the next request", async () => { + vi.useFakeTimers(); + const first = player(); + const subscriptions: Array<{ remove: ReturnType }> = []; + first.addListener.mockImplementation(() => { + const subscription = { remove: vi.fn() }; + subscriptions.push(subscription); + return subscription; + }); + first.replaceAsync.mockImplementation(async () => {}); + mocks.createPlayer.mockReturnValueOnce(first); + const file = source(); + const stuck = thumbnails.loadVideoThumbnail( + "never-attached", + async () => file, + new AbortController().signal, + ); + const next = thumbnails.loadVideoThumbnail( + "next", + async () => source(), + new AbortController().signal, + ); + await vi.advanceTimersByTimeAsync(15_000); + expect(await stuck).toBeNull(); expect(first.generateThumbnailsAsync).not.toHaveBeenCalled(); - expect(thumbnails.cachedVideoThumbnail("canceled")).toBeNull(); + expect(subscriptions[0]!.remove).toHaveBeenCalledTimes(1); + expect(first.release).toHaveBeenCalledTimes(1); + expect(file.dispose).toHaveBeenCalledTimes(1); + expect(await next).toBe(frame); }); }); diff --git a/apps/mobile/src/lib/videoThumbnails.ts b/apps/mobile/src/lib/videoThumbnails.ts index 7606a71457dba..33e4f74e42f63 100644 --- a/apps/mobile/src/lib/videoThumbnails.ts +++ b/apps/mobile/src/lib/videoThumbnails.ts @@ -10,35 +10,40 @@ export function cachedVideoThumbnail(key: string): VideoThumbnail | null { return thumbnails.get(key) ?? null; } -async function extractFrame(uri: string, signal: AbortSignal) { +async function extractFrame(uri: string) { const { createVideoPlayer } = await import("expo-video"); - if (signal.aborted) return null; const player = createVideoPlayer(null); let disposed = false; - let cancel = () => {}; let timeout: ReturnType | undefined; + let attachedSubscription: { remove(): void } | undefined; try { // Never play or change audio settings: thumbnails must leave the shared audio session alone. player.bufferOptions = { preferredForwardBufferDuration: 1 }; - const canceled = new Promise((resolve) => { - cancel = () => resolve(null); + const timedOut = new Promise((resolve) => { + timeout = setTimeout(() => resolve(null), 15_000); + }); + // iOS resolves replaceAsync before the main thread attaches the item, and until then + // generateThumbnailsAsync finds no asset and returns no frames. + const attached = new Promise((resolve) => { + attachedSubscription = player.addListener("sourceChange", ({ source }) => { + if (source) resolve(); + }); }); - signal.addEventListener("abort", cancel, { once: true }); - timeout = setTimeout(cancel, 15_000); const frame = (async () => { await player.replaceAsync({ uri, contentType: "progressive" }); - if (disposed || signal.aborted) return null; + await attached; + if (disposed) return null; const [thumbnail] = await player.generateThumbnailsAsync([0], { maxWidth: 480, maxHeight: 480, }); return thumbnail ?? null; })(); - return await Promise.race([frame, canceled]); + return await Promise.race([frame, timedOut]); } finally { disposed = true; clearTimeout(timeout); - signal.removeEventListener("abort", cancel); + attachedSubscription?.remove(); player.release(); } } @@ -62,8 +67,11 @@ export function loadVideoThumbnail( const source = await resolveSource(signal); if (!source) return null; try { - const thumbnail = await extractFrame(source.uri, signal); - if (!thumbnail || signal.aborted) return null; + if (signal.aborted) return null; + // A started extraction finishes even if its reader leaves: its requests are already in + // flight, and a re-signed URL for the same video replaces the reader, not the frame. + const thumbnail = await extractFrame(source.uri); + if (!thumbnail) return null; thumbnails.set(key, thumbnail); if (thumbnails.size > MAX_CACHED_THUMBNAILS) { thumbnails.delete(thumbnails.keys().next().value!); diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts index f29fbc8c119b4..7a26fc2b8d694 100644 --- a/apps/mobile/src/persistence/mobile-preferences.ts +++ b/apps/mobile/src/persistence/mobile-preferences.ts @@ -79,7 +79,14 @@ const WorkspaceSelections = Schema.Struct({ }); export type WorkspaceSelections = typeof WorkspaceSelections.Type; +const PullRequestActivityVisibility = Schema.Struct({ + bots: Schema.Boolean, + resolved: Schema.Boolean, +}); +export type PullRequestActivityVisibility = typeof PullRequestActivityVisibility.Type; + const isThreadListFilters = Schema.is(ThreadListFilters); +const isPullRequestActivityVisibility = Schema.is(PullRequestActivityVisibility); const isWorkspaceSelections = Schema.is(WorkspaceSelections); const isPullRequestListPreferences = Schema.is(PullRequestListPreferences); const ThreadProject = Schema.Struct({ @@ -92,6 +99,8 @@ export interface Preferences { readonly navigationTabOrder?: readonly string[]; readonly hiddenNavigationTabs?: readonly string[]; readonly pullRequestHideTestFiles?: boolean; + /** Which hidden-by-default PR activity is shown: bot comments and resolved or dismissed ones. */ + readonly pullRequestActivityVisibility?: PullRequestActivityVisibility; readonly pullRequestMergeMethod?: PullRequestMergeMethod; readonly liveActivitiesEnabled?: boolean; readonly themeId?: MobileThemeId; @@ -181,6 +190,7 @@ function sanitizePreferences(parsed: Preferences): Preferences { navigationTabOrder?: readonly string[]; hiddenNavigationTabs?: readonly string[]; pullRequestHideTestFiles?: boolean; + pullRequestActivityVisibility?: PullRequestActivityVisibility; pullRequestMergeMethod?: PullRequestMergeMethod; liveActivitiesEnabled?: boolean; themeId?: MobileThemeId; @@ -233,6 +243,10 @@ function sanitizePreferences(parsed: Preferences): Preferences { preferences.pullRequestHideTestFiles = parsed.pullRequestHideTestFiles; } + if (isPullRequestActivityVisibility(parsed.pullRequestActivityVisibility)) { + preferences.pullRequestActivityVisibility = parsed.pullRequestActivityVisibility; + } + if (isPullRequestMergeMethod(parsed.pullRequestMergeMethod)) { preferences.pullRequestMergeMethod = parsed.pullRequestMergeMethod; } diff --git a/apps/mobile/src/state/pull-requests.ts b/apps/mobile/src/state/pull-requests.ts index 8ca65760e5913..cb8606b96b5f9 100644 --- a/apps/mobile/src/state/pull-requests.ts +++ b/apps/mobile/src/state/pull-requests.ts @@ -1,7 +1,9 @@ import { createPullRequestEnvironmentAtoms, + editHeldPullRequestListEntries, createPullRequestStackAtomFamily, patchPullRequestListEntries, + pullRequestPendingEditsAtom, } from "@t3tools/client-runtime/state/pull-requests"; import type { EnvironmentId, PullRequestListInput, PullRequestRef } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; @@ -66,11 +68,30 @@ export const composerPullRequests = createPullRequestEnvironmentAtoms(connection pages.entries, target.input, reply, + registry.get(pullRequestPendingEditsAtom(target.environmentId)), ); return entries === "refresh" || entries === pages.entries ? pages : { ...pages, entries }; }); } }), + acceptedEdit: (target, edit, registry) => + Effect.sync(() => { + for (const atom of registry.getNodes().keys()) { + const listing = + typeof atom === "string" ? undefined : pullRequestListPagesTargets.get(atom); + if (listing === undefined || listing[0] !== target.environmentId) continue; + registry.update(atom as Atom.Writable, (pages) => { + if (pages === null) return pages; + const entries = editHeldPullRequestListEntries( + listing[1], + pages.entries, + () => [edit], + registry.get(pullRequestPendingEditsAtom(target.environmentId)), + ); + return entries === pages.entries ? pages : { ...pages, entries }; + }); + } + }), // A new head can change which files GitHub still counts as viewed, so the viewed-files read is // refreshed where the new head lands. The detail atom still holds the previous answer here. detail: (target, value, registry) => diff --git a/apps/mobile/src/state/queries.test.ts b/apps/mobile/src/state/queries.test.ts deleted file mode 100644 index dba11b2e56ea7..0000000000000 --- a/apps/mobile/src/state/queries.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { threadPullRequestKeyOf } from "@t3tools/client-runtime/thread-pull-requests"; -import { filterComposerPullRequestMatches } from "@t3tools/shared/composerPullRequestMatches"; -import { expect, it } from "@effect/vitest"; - -it("keeps an older exact PR in the mobile menu ahead of twenty newer substring matches", () => { - const exact = { - host: "github.com", - number: 42, - projectId: "project", - repository: "example/repo", - updatedAt: "2025-01-01", - }; - const recent = Array.from({ length: 25 }, (_, index) => ({ - ...exact, - number: 4200 + index, - updatedAt: "2026-01-01", - })); - const matches = filterComposerPullRequestMatches({ - keyOf: threadPullRequestKeyOf, - entries: [exact, ...recent, exact], - projectId: exact.projectId, - repository: exact.repository, - query: "42", - limit: 20, - }); - expect(matches).toHaveLength(20); - expect(matches[0]).toEqual(exact); - expect(matches.filter((entry) => entry.number === 42)).toHaveLength(1); -}); diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 8f050c3748c56..d137305317327 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -1012,6 +1012,15 @@ describe("AssetAccess", () => { kind: "file", path: canonicalCssPath, }); + yield* fileSystem.makeDirectory(path.join(root, "clips")); + for (const mediaName of ["clips/clip.mp4", "clips/clip.webm", "clips/clip.mp3"]) { + const mediaPath = path.join(root, mediaName); + yield* fileSystem.writeFileString(mediaPath, "media bytes"); + expect(yield* resolveAsset(token, mediaName)).toMatchObject({ + kind: "file", + path: yield* fileSystem.realPath(mediaPath), + }); + } for (const extension of ["otf", "ttf", "woff", "woff2"]) { const fontName = `preview.${extension}`; const fontPath = path.join(root, fontName); diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index b1c1b28b626cd..5674372bee1a9 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -94,6 +94,18 @@ const PREVIEW_ASSET_EXTENSIONS = new Set([ ".png", ".svg", ".webp", + ".m4v", + ".mp4", + ".ogv", + ".webm", + ".aac", + ".flac", + ".m4a", + ".mp3", + ".oga", + ".ogg", + ".opus", + ".wav", ".css", ".js", ".mjs", diff --git a/apps/server/src/assets/NativeAppIconResolver.test.ts b/apps/server/src/assets/NativeAppIconResolver.test.ts index ecfe08788af3b..66a1171c9053c 100644 --- a/apps/server/src/assets/NativeAppIconResolver.test.ts +++ b/apps/server/src/assets/NativeAppIconResolver.test.ts @@ -1,6 +1,8 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; +import * as Digest from "effect/crypto/Digest"; +import * as Hex from "effect/encoding/Hex"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -28,18 +30,34 @@ it.effect("resolves the exact bundle path without Spotlight and caches the conve commands.push(command.command); if (command.command === "/usr/bin/plutil") return "AppIcon"; if (command.command === "/usr/bin/sips") { + expect(command.args.slice(0, 3)).toEqual(["-z", "128", "128"]); yield* fs.writeFileString(String(command.args.at(-1)), "converted icon"); } return ""; }), }); yield* Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const canonicalBundle = yield* fs.realPath(bundle); + const sourceIcon = path.join(canonicalBundle, "Contents", "Resources", "AppIcon.icns"); + const digest = yield* Digest.Digest; + const legacyKey = yield* digest + .digest( + Digest.sha256, + new TextEncoder().encode(`${canonicalBundle}\0AppIcon\0${sourceIcon}`), + ) + .pipe(Effect.map(Hex.encode), Effect.orDie); + const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons"); + yield* fs.makeDirectory(cacheDirectory, { recursive: true }); + const legacyIcon = path.join(cacheDirectory, `${legacyKey}.png`); + yield* fs.writeFileString(legacyIcon, "legacy 64px icon"); const resolver = yield* NativeAppIconResolver.make; const reference = { _tag: "app-path" as const, path: bundle }; const icon = yield* resolver.resolve(reference); expect(icon).not.toBeNull(); if (icon === null) return; expect(yield* fs.readFileString(icon)).toBe("converted icon"); + expect(icon).not.toBe(legacyIcon); expect(yield* resolver.resolve(reference)).toBe(icon); expect(yield* resolver.resolve({ _tag: "app-path", path: "~/Build Output/My App.app" })).toBe( icon, diff --git a/apps/server/src/assets/NativeAppIconResolver.ts b/apps/server/src/assets/NativeAppIconResolver.ts index 0d238effee4cc..e31d7a1d8c30d 100644 --- a/apps/server/src/assets/NativeAppIconResolver.ts +++ b/apps/server/src/assets/NativeAppIconResolver.ts @@ -21,7 +21,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ServerConfig from "../config.ts"; -const ICON_SIZE = 64; +const ICON_SIZE = 128; const COMMAND_TIMEOUT = "5 seconds"; const RESOLUTION_CACHE_TTL = Duration.hours(1); const RESOLUTION_CACHE_MAX_ENTRIES = 256; @@ -189,7 +189,7 @@ const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUnc ) .pipe(Effect.map(Hex.encode), Effect.orDie); const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons"); - const cachePath = path.join(cacheDirectory, `${cacheKey}.png`); + const cachePath = path.join(cacheDirectory, `${cacheKey}-${ICON_SIZE}.png`); if (yield* existingFile(cachePath)) return cachePath; yield* fileSystem.makeDirectory(cacheDirectory, { recursive: true }); diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index 22742cecea795..2b462f9ed95b8 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -241,6 +241,46 @@ it.effect("registers loopback and https clients and never redirects for an unver expect(response.status).toBe(400); expect(yield* json(response)).toMatchObject({ error: "invalid_redirect_uri" }); } + // JSON escaping can inflate the signed client_id past what an authorize URL can carry. + const oversized = yield* handler( + at("/oauth/mcp/register", { + method: "POST", + headers: { "content-type": "application/json" }, + body: encodeJson({ + redirect_uris: Array.from( + { length: 10 }, + (_, index) => `https://bot.example/${index}/${'"'.repeat(480)}`, + ), + }), + }), + ); + expect(oversized.status).toBe(400); + const fiveLongCallbacks = yield* handler( + at("/oauth/mcp/register", { + method: "POST", + headers: { "content-type": "application/json" }, + body: encodeJson({ + client_name: "A".repeat(100), + redirect_uris: Array.from( + { length: 5 }, + (_, index) => `https://a.co/${index}/${"界".repeat(497)}`, + ), + }), + }), + ); + expect(fiveLongCallbacks.status).toBe(201); + + for (const malformed of [ + { client_name: 42, redirect_uris: [REDIRECT] }, + { redirect_uris: REDIRECT }, + ]) { + const response = yield* handler(postJson("/oauth/mcp/register", malformed)); + expect(response.status).toBe(400); + expect(response.headers.get("content-type")).toMatch(/^application\/json/); + expect(yield* json<{ error: string }>(response)).toMatchObject({ + error: expect.stringMatching(/^invalid_(client_metadata|redirect_uri)$/), + }); + } const registered = yield* register(handler); expect(registered.status).toBe(201); @@ -264,6 +304,17 @@ it.effect("registers loopback and https clients and never redirects for an unver expect(unregistered.status).toBe(400); expect(unregistered.headers.get("location")).toBeNull(); + for (const resource of [`${ORIGIN}/mcp#section`, `${ORIGIN}/mcp#`]) { + const wrongTarget = yield* handler( + at( + `/oauth/mcp/authorize?${new URLSearchParams({ ...authorizeParams(clientId), resource })}`, + ), + ); + expect(wrongTarget.status).toBe(302); + const location = new URL(wrongTarget.headers.get("location")!, ORIGIN); + expect(location.searchParams.get("error"), resource).toBe("invalid_target"); + } + const query = new URLSearchParams(authorizeParams(clientId)).toString(); const handoff = yield* handler(at(`/oauth/mcp/authorize?${query}`)); expect(handoff.status).toBe(302); @@ -423,6 +474,43 @@ it.live("signs in a hosted agent with an https callback that asked for a client ), ); +it.live("signs in Gemini, which registers six user-bound redirect URIs for one client", () => + withRoutes((handler, auth) => + Effect.gen(function* () { + const redirectUris = Array.from( + { length: 6 }, + (_, index) => + `https://oauth-redirect.googleusercontent.com/r/user_bound_custom-mcp-test${index}`, + ); + const registered = yield* handler( + at("/oauth/mcp/register", { + method: "POST", + headers: { "content-type": "application/json" }, + body: encodeJson({ + client_name: "Google", + redirect_uris: redirectUris, + token_endpoint_auth_method: "client_secret_basic", + }), + }), + ); + const client = (yield* json(registered)) as { client_id: string }; + expect(client).toMatchObject({ redirect_uris: redirectUris }); + expect(registered.status).toBe(201); + + const callbackUrl = redirectUris[5]!; + const params = authorizeParams(client.client_id, callbackUrl); + const pairing = yield* auth.issuePairingCredential(); + const approved = yield* decide(handler, params, { + _tag: "pairing-code", + access: "approval-required", + code: pairing.credential, + }); + const callback = new URL(approved.redirectTo!); + expect(`${callback.origin}${callback.pathname}`).toBe(callbackUrl); + }), + ), +); + it.live("rejects a wrong PKCE verifier and spends the code", () => withRoutes((handler, auth) => Effect.gen(function* () { diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index fd118e49cdbd5..3270d802df801 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -54,8 +54,12 @@ import { requestUrl } from "../requestUrl.ts"; const SIGNING_SECRET_NAME = "mcp-oauth-signing-key"; const AUTHORIZATION_CODE_TTL_MS = 60_000; const MAX_CLIENT_NAME_LENGTH = 100; -const MAX_REDIRECT_URIS = 5; +const MAX_REDIRECT_URIS = 10; const MAX_REDIRECT_URI_LENGTH = 512; +// The client_id rides in the authorize URL. Past the original five-URI limit, cap it to leave room +// under Node's 16 KB header cap for an encoded redirect_uri and state. +const MAX_UNBOUNDED_CLIENT_ID_REDIRECT_URIS = 5; +const MAX_CLIENT_ID_LENGTH = 10_240; const DEFAULT_CLIENT_NAME = "MCP client"; const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]); const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/; @@ -130,9 +134,11 @@ export const redirectMatches = (registered: string, presented: string): boolean const sameResource = (urls: McpOAuthUrls, presented: string | undefined): boolean => { if (presented === undefined) return true; + // URL.hash misses empty fragments, which RFC 8707 §2 also forbids. + if (presented.includes("#")) return false; try { const url = new URL(presented); - return url.hash === "" && `${url.origin}${url.pathname.replace(/\/+$/u, "")}` === urls.resource; + return `${url.origin}${url.pathname.replace(/\/+$/u, "")}` === urls.resource; } catch { return false; } @@ -348,8 +354,18 @@ const make = Effect.gen(function* () { "Linked environments is off on that machine. Turn it on in its Settings → Labs.", }); } + const clientId = yield* signClientId(name, redirectUris, peerLink); + if ( + redirectUris.length > MAX_UNBOUNDED_CLIENT_ID_REDIRECT_URIS && + clientId.length > MAX_CLIENT_ID_LENGTH + ) { + return yield* new AuthMcpRegistrationError({ + error: "invalid_redirect_uri", + error_description: "Redirect URIs are too long to fit in an authorization request.", + }); + } return { - clientId: yield* signClientId(name, redirectUris, peerLink), + clientId, name, redirectUris, peerLink, diff --git a/apps/server/src/auth/PairingGrantStore.test.ts b/apps/server/src/auth/PairingGrantStore.test.ts index 5184beb096807..3f95ce46ec695 100644 --- a/apps/server/src/auth/PairingGrantStore.test.ts +++ b/apps/server/src/auth/PairingGrantStore.test.ts @@ -70,6 +70,22 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PairingGrantStor ), ); + it.effect("accepts a one-time token typed in hyphen- or space-separated groups", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore; + const issued = yield* bootstrapCredentials.issueOneTimeToken(); + const formatted = issued.credential.match(/.{1,4}/g)!.join("-"); + const consumed = yield* bootstrapCredentials.consume(formatted.toLowerCase()); + const second = yield* bootstrapCredentials.issueOneTimeToken(); + const spaced = yield* bootstrapCredentials.consume( + second.credential.match(/.{1,4}/g)!.join(" "), + ); + + expect(consumed.method).toBe("one-time-token"); + expect(spaced.method).toBe("one-time-token"); + }).pipe(Effect.provide(layerPairingGrantStore())), + ); + it.effect("atomically consumes a one-time token when multiple requests race", () => Effect.gen(function* () { const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore; diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.ts index 69e0ded648eed..883ca58375790 100644 --- a/apps/server/src/auth/PairingGrantStore.ts +++ b/apps/server/src/auth/PairingGrantStore.ts @@ -685,8 +685,10 @@ const make = Effect.gen(function* () { } // Only credentials in the issued pairing-code formats are case-insensitive. - const pairingCredential = PAIRING_TOKEN_PATTERN.test(credential) - ? credential.toUpperCase() + // People type codes in groups such as XXXX-XXXX-XXXX. + const compactCredential = credential.replace(/[\s-]/g, ""); + const pairingCredential = PAIRING_TOKEN_PATTERN.test(compactCredential) + ? compactCredential.toUpperCase() : (parseMcpApprovalCode(credential)?.code ?? credential); // Check scopes in the UPDATE so rejected requests cannot spend one-time links. diff --git a/apps/server/src/auth/ServerSecretStore.test.ts b/apps/server/src/auth/ServerSecretStore.test.ts index 08a33e2fde3c5..fa216177f494a 100644 --- a/apps/server/src/auth/ServerSecretStore.test.ts +++ b/apps/server/src/auth/ServerSecretStore.test.ts @@ -113,6 +113,55 @@ const layerConcurrentCreateSecretStore = () => Layer.provideMerge(layerConcurrentReadMissFileSystem), ); +// Both callers read the empty secret before either repairs it, and the second removal of the +// secret file waits until the first caller has returned its key. +const layerConcurrentEmptyRepairFileSystem = (firstReturned: Deferred.Deferred) => + Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const readCountRef = yield* Ref.make(0); + const removeCountRef = yield* Ref.make(0); + const readBarrier = yield* Deferred.make(); + const isSecretPath = (path: string) => /[\\/]session-signing-key\.bin$/.test(path); + + return { + ...fileSystem, + readFile: (path) => + isSecretPath(path) + ? Ref.updateAndGet(readCountRef, (count) => count + 1).pipe( + Effect.flatMap((count) => + count > 2 + ? fileSystem.readFile(path) + : Effect.gen(function* () { + if (count === 2) { + yield* Deferred.succeed(readBarrier, void 0); + } + yield* Deferred.await(readBarrier); + return yield* fileSystem.readFile(path); + }), + ), + ) + : fileSystem.readFile(path), + remove: (path, options) => + isSecretPath(path) + ? Ref.updateAndGet(removeCountRef, (count) => count + 1).pipe( + Effect.flatMap((count) => + count > 1 ? Deferred.await(firstReturned) : Effect.void, + ), + Effect.flatMap(() => fileSystem.remove(path, options)), + ) + : fileSystem.remove(path, options), + } satisfies FileSystem.FileSystem; + }), + ).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); + +const layerConcurrentEmptyRepairSecretStore = (firstReturned: Deferred.Deferred) => + ServerSecretStore.layer.pipe( + Layer.provide(layerServerConfig()), + Layer.provideMerge(layerConcurrentEmptyRepairFileSystem(firstReturned)), + ); + it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerSecretStore.layer", (it) => { it.effect("reuses an existing secret instead of regenerating it", () => Effect.gen(function* () { @@ -125,6 +174,40 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerSecretStor }).pipe(Effect.provide(layerServerSecretStore())), ); + it.effect("replaces an empty persisted secret with a fresh random one", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore.ServerSecretStore; + yield* secretStore.set("session-signing-key", new Uint8Array()); + + const secret = yield* secretStore.getOrCreateRandom("session-signing-key", 32); + const persisted = yield* secretStore.get("session-signing-key"); + + assert.equal(secret.byteLength, 32); + assert.deepEqual(Array.from(Option.getOrThrow(persisted)), Array.from(secret)); + }).pipe(Effect.provide(layerServerSecretStore())), + ); + + it.effect("keeps the repaired secret when concurrent callers find it empty", () => + Effect.gen(function* () { + const firstReturned = yield* Deferred.make(); + yield* Effect.gen(function* () { + const secretStore = yield* ServerSecretStore.ServerSecretStore; + yield* secretStore.set("session-signing-key", new Uint8Array()); + const getOrCreate = secretStore + .getOrCreateRandom("session-signing-key", 32) + .pipe(Effect.tap(() => Deferred.succeed(firstReturned, void 0))); + + const [first, second] = yield* Effect.all([getOrCreate, getOrCreate], { + concurrency: "unbounded", + }); + const persisted = Option.getOrThrow(yield* secretStore.get("session-signing-key")); + + assert.deepEqual(Array.from(first), Array.from(persisted)); + assert.deepEqual(Array.from(second), Array.from(persisted)); + }).pipe(Effect.provide(layerConcurrentEmptyRepairSecretStore(firstReturned))); + }), + ); + it.effect("returns the persisted secret when concurrent creators race", () => Effect.gen(function* () { const secretStore = yield* ServerSecretStore.ServerSecretStore; diff --git a/apps/server/src/auth/ServerSecretStore.ts b/apps/server/src/auth/ServerSecretStore.ts index e950acb38a71d..cabded3d0c7b0 100644 --- a/apps/server/src/auth/ServerSecretStore.ts +++ b/apps/server/src/auth/ServerSecretStore.ts @@ -8,6 +8,7 @@ import * as Path from "effect/Path"; import * as Predicate from "effect/Predicate"; import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; @@ -169,6 +170,9 @@ export const make = Effect.gen(function* () { ); const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`); + const emptySecretRepair = yield* Semaphore.make(1); + const isMissingOrNonEmpty = (secret: Option.Option) => + Option.isNone(secret) || secret.value.byteLength > 0; const get: ServerSecretStore["Service"]["get"] = (name) => fileSystem.readFile(resolveSecretPath(name)).pipe( @@ -263,6 +267,19 @@ export const make = Effect.gen(function* () { const getOrCreateRandom: ServerSecretStore["Service"]["getOrCreateRandom"] = (name, bytes) => get(name).pipe( + // Older builds could persist a 0-byte secret, which is never a usable key. Re-read under + // the permit, and keep it until an interrupted removal settles, so a caller that saw the + // empty file cannot remove a key another caller created. + Effect.filterOrElse(isMissingOrNonEmpty, () => + emptySecretRepair.withPermits(1)( + get(name).pipe( + Effect.filterOrElse(isMissingOrNonEmpty, () => + remove(name).pipe(Effect.as(Option.none())), + ), + Effect.uninterruptible, + ), + ), + ), Effect.flatMap( Option.match({ onSome: Effect.succeed, diff --git a/apps/server/src/auth/mcpOAuthHttp.ts b/apps/server/src/auth/mcpOAuthHttp.ts index 3226432bc304d..0158a5e35931a 100644 --- a/apps/server/src/auth/mcpOAuthHttp.ts +++ b/apps/server/src/auth/mcpOAuthHttp.ts @@ -2,6 +2,8 @@ import { AuthMcpApprovalError, AuthMcpAuthorizationRequest, AuthMcpClientAccess, + AuthMcpClientRegistration, + AuthMcpRegistrationError, EnvironmentHttpApi, mcpClientScopes, } from "@t3tools/contracts"; @@ -42,6 +44,10 @@ const noStore = HttpEffect.appendPreResponseHandler((_request, response) => const requestUrls = Effect.map(HttpServerRequest.HttpServerRequest, McpOAuth.requestUrls); const decodeAuthorizationRequest = Schema.decodeEffect(AuthMcpAuthorizationRequest); +// Decoded by the handler so malformed metadata gets the RFC 7591 error, not HttpApi's empty 400. +const decodeClientRegistration = Schema.decodeUnknownEffect( + Schema.fromJsonString(AuthMcpClientRegistration), +); /** * An unverified client or redirect is reported, never redirected; any other problem goes back to @@ -103,8 +109,18 @@ export const layer = HttpApiBuilder.group( .handle("authorizationServer", () => requestUrls.pipe(Effect.map(McpOAuth.authorizationServerMetadata)), ) - .handle("register", ({ payload }) => - oauth.register(payload).pipe( + .handleRaw("register", ({ request }) => + request.text.pipe( + Effect.orDie, + Effect.flatMap(decodeClientRegistration), + Effect.mapError( + (cause) => + new AuthMcpRegistrationError({ + error: "invalid_client_metadata", + error_description: `Invalid client metadata: ${cause.message}`, + }), + ), + Effect.flatMap(oauth.register), Effect.map((client) => ({ client_id: client.clientId, client_name: client.name, diff --git a/apps/server/src/auth/utils.test.ts b/apps/server/src/auth/utils.test.ts index 30784ab33ceb0..f9c228aeb418b 100644 --- a/apps/server/src/auth/utils.test.ts +++ b/apps/server/src/auth/utils.test.ts @@ -24,6 +24,29 @@ describe("deriveAuthClientMetadata", () => { }); }); + it("records the forwarded client address of a request proxied by Tailscale Serve", () => { + const metadata = deriveAuthClientMetadata({ + request: { + headers: { + "x-forwarded-for": "100.64.0.2", + "x-forwarded-host": "host-a.tailnet-name.ts.net", + "x-forwarded-proto": "https", + }, + source: { remoteAddress: "127.0.0.1" }, + } as never, + }); + + expect(metadata.ipAddress).toBe("100.64.0.2"); + + const direct = deriveAuthClientMetadata({ + request: { + headers: { "x-forwarded-for": "100.64.0.2" }, + source: { remoteAddress: "192.168.1.20" }, + } as never, + }); + expect(direct.ipAddress).toBe("192.168.1.20"); + }); + it.each([ [ "Edge on Android", diff --git a/apps/server/src/auth/utils.ts b/apps/server/src/auth/utils.ts index c1b8dc92fbe00..12c27cc1fdf57 100644 --- a/apps/server/src/auth/utils.ts +++ b/apps/server/src/auth/utils.ts @@ -166,12 +166,25 @@ function readRemoteAddressFromSource(source: unknown): string | undefined { return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress); } +const isLoopbackIpAddress = (address: string): boolean => + (NodeNet.isIPv4(address) && address.startsWith("127.")) || address === "::1"; + +// A loopback peer is a local reverse proxy (Tailscale Serve); trust only the entry it appended. +function resolveClientIpAddress(request: HttpServerRequest.HttpServerRequest): string | undefined { + const peer = readRemoteAddressFromSource(request.source); + if (!peer || !isLoopbackIpAddress(peer)) { + return peer; + } + const forwarded = normalizeIpAddress(request.headers["x-forwarded-for"]?.split(",").at(-1)); + return forwarded && NodeNet.isIP(forwarded) !== 0 ? forwarded : peer; +} + export function deriveAuthClientMetadata(input: { readonly request: HttpServerRequest.HttpServerRequest; readonly presented?: AuthClientPresentationMetadata; }): AuthClientMetadata { const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]); - const ipAddress = readRemoteAddressFromSource(input.request.source); + const ipAddress = resolveClientIpAddress(input.request); const os = input.presented?.os ?? inferOs(userAgent); const browser = inferBrowser(userAgent); return { diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index 8cc560db63733..f5015abf84518 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -21,6 +21,11 @@ import { } from "@t3tools/contracts"; import * as NetService from "@t3tools/shared/Net"; import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability"; +import { + DEFAULT_HOME_DIRECTORY, + PRODUCT_HOME_MARKER, + PRODUCT_ID, +} from "@t3tools/shared/productIdentity"; import * as OtelEnvironment from "@t3tools/shared/otelEnvironment"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -222,6 +227,61 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { }), ); + it.effect("names the pair command for the refused server's home", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const child = yield* liveProcess; + assert(child.pid !== undefined); + for (const source of ["flag", "T3CODE_HOME", "default"] as const) { + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-pair-" }); + const baseDir = source === "default" ? path.join(home, DEFAULT_HOME_DIRECTORY) : home; + const stateDir = path.join(baseDir, "userdata"); + yield* fs.makeDirectory(stateDir, { recursive: true }); + // This fork claims a nonempty home only after its product marker is there. + yield* fs.writeFileString(path.join(baseDir, PRODUCT_HOME_MARKER), `${PRODUCT_ID}\n`); + yield* fs.writeFileString( + path.join(stateDir, "server-runtime.json"), + yield* encodeUnknownJson({ + version: 1, + pid: child.pid, + port: 3773, + origin: "http://127.0.0.1:3773", + startedAt: "2026-10-01T00:00:00.000Z", + }), + ); + const error = yield* resolveServerConfig( + { + ...minimalWebFlags(baseDir), + baseDir: source === "flag" ? Option.some(baseDir) : Option.none(), + cwd: Option.some(path.join(home, "project")), + }, + Option.none(), + { rejectRunningServer: true }, + ).pipe( + Effect.provide( + Layer.merge( + NetService.layer, + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: source === "T3CODE_HOME" ? { T3CODE_HOME: baseDir } : {}, + }), + ), + ), + ), + Effect.provideService(HostProcess.HomeDirectory, home), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.flip, + ); + // A temp dir with spaces or backslashes is single-quoted for the shell. + const homePattern = baseDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + expect(String(error)).toMatch( + new RegExp(`pair --base-dir (${homePattern}|'${homePattern}')`), + ); + } + }), + ); + it.effect("enables a trimmed reusable auth token only for web dev mode", () => Effect.gen(function* () { const baseDir = yield* FileSystem.FileSystem.pipe( diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index 5d7b19a6e52e3..fcda92a97836e 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -27,6 +27,7 @@ import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts"; import * as ServerConfig from "../config.ts"; import { expandHomePath, resolveBaseDir } from "../os-jank.ts"; import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { resolveHostCliCommand } from "./invocation.ts"; const modeFlag = Flag.Literals("mode", ServerConfig.RuntimeMode.literals).pipe( Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."), @@ -358,8 +359,13 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct runtime.value.pid !== process.pid && isProcessAlive(runtime.value.pid) ) { + // Bare `t3 pair` prefers a linked worktree's `.t3`, so always name this home. + const { command: pairCommand } = yield* resolveHostCliCommand("pair", [ + "--base-dir", + baseDir, + ]); return yield* new CliError.UserError({ - cause: `A T3 Code server is already running for ${baseDir} (pid ${runtime.value.pid}, ${runtime.value.origin}). Connect to that server, stop it before starting another, or use a different --base-dir.`, + cause: `A T3 Code server is already running for ${baseDir} (pid ${runtime.value.pid}, ${runtime.value.origin}). To open it, run \`${pairCommand}\` and open the pairing URL it prints. To start another server, stop this one first or use a different --base-dir.`, }); } } diff --git a/apps/server/src/cli/invocation.ts b/apps/server/src/cli/invocation.ts index 3f8181bf666b7..9d82a2bfe87eb 100644 --- a/apps/server/src/cli/invocation.ts +++ b/apps/server/src/cli/invocation.ts @@ -366,7 +366,8 @@ export const resolveHostCliCommand = Effect.fnUntraced(function* ( // PowerShell runs a quoted path only through the call operator. const call = platform === "win32" && invocation.pathCommand ? "& " : ""; return { - command: [`${call}${invocation.command}`, ...args.map(quote)].join(" "), + // An empty subcommand names the root command. + command: [`${call}${invocation.command}`.trimEnd(), ...args.map(quote)].join(" "), launcher: invocation.launcher, }; }); diff --git a/apps/server/src/cli/up.test.ts b/apps/server/src/cli/up.test.ts index 9c9e7c0c0fb80..4cfb8aafef2ac 100644 --- a/apps/server/src/cli/up.test.ts +++ b/apps/server/src/cli/up.test.ts @@ -168,7 +168,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) readonly reportStatus?: boolean; /** Runs as if in a terminal, answering each question with this text. */ readonly answer?: string; - readonly prints?: string; + /** Lines the run prints, with `` standing for the test's home. */ + readonly prints?: ReadonlyArray; readonly omits?: string; readonly json?: object; readonly env: string; @@ -188,7 +189,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) }, { label: "the local network opens", - prints: " pair --base-dir `. Use the code on your other device.", + prints: [" pair --base-dir `. Use the code on your other device."], installed: true, env: "S2CODE_LAN=false\n", args: ["--lan"], @@ -207,6 +208,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) }, { label: "a route turns off with no service to run", + prints: [" --base-dir ` to use S2Code here."], installed: false, env: "S2CODE_LAN=true\n", args: ["--no-lan"], @@ -227,7 +229,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) { label: "a failed update keeps service.env matching the old service", // The old service still runs, so no foreground server is offered. - prints: " up --base-dir ` again.", + prints: [" up --base-dir ` again."], installed: true, status: { current: false }, installFails: true, @@ -285,12 +287,27 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) restarts: 0, envAfter: "", }, + { + label: "status hints keep the caller's --base-dir", + installed: true, + reportStatus: true, + prints: [ + " up --base-dir --no-lan`.", + "Change access: `", + " up --base-dir `.", + ], + env: "", + args: [], + installs: 0, + restarts: 0, + envAfter: "", + }, { label: "a host override gets no --no-lan hint it would ignore", installed: true, reportStatus: true, - prints: "overridden · S2CODE_HOST=0.0.0.0", - omits: "s2code up --no-lan", + prints: ["overridden · S2CODE_HOST=0.0.0.0"], + omits: "--no-lan", env: "S2CODE_HOST=0.0.0.0\n", args: [], installs: 0, @@ -422,8 +439,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) ), ), ); - if (input.prints !== undefined) { - expect(lines.join("\n")).toContain(input.prints.replace("", baseDir)); + for (const line of input.prints ?? []) { + expect(lines.join("\n")).toContain(line.replace("", baseDir)); } if (input.omits !== undefined) { expect(lines.join("\n")).not.toContain(input.omits); diff --git a/apps/server/src/cli/up.ts b/apps/server/src/cli/up.ts index e28187038be00..c65ffc0c6e4d3 100644 --- a/apps/server/src/cli/up.ts +++ b/apps/server/src/cli/up.ts @@ -128,7 +128,25 @@ const CHOICES = { lan: { title: "Local network", description: "LAN and tailnet. Pairing code required." }, } satisfies Record; -const formatSetup = (setup: Setup) => { +/** The commands hints name, run with the caller's --base-dir and launcher. */ +const resolveHints = Effect.fn("cli.up.resolve_hints")(function* (baseDir: Option.Option) { + const baseDirArgs = Option.match(baseDir, { + onNone: () => [], + onSome: (dir) => ["--base-dir", dir], + }); + const command = (subcommand: string, args: ReadonlyArray = []) => + Effect.map(resolveHostCliCommand(subcommand, [...baseDirArgs, ...args]), (r) => r.command); + return { + run: yield* command(""), + pair: yield* command("pair"), + up: yield* command("up"), + upNoLan: yield* command("up", ["--no-lan"]), + connect: yield* command("connect"), + }; +}); +type Hints = Effect.Success>; + +const formatSetup = (setup: Setup, hints: Hints) => { const { service } = setup; // This home's access settings reach no service, so only the service is shown. if (service.otherBaseDir !== undefined) { @@ -155,7 +173,7 @@ const formatSetup = (setup: Setup) => { setup.connect ? "on · your T3 account" : setup.connectRevoked - ? `off · link revoked. Run \`${forkCliCommand("connect")}\`.` + ? `off · link revoked. Run \`${hints.connect}\`.` : "off", ] as const, ]), @@ -175,7 +193,7 @@ const formatSetup = (setup: Setup) => { ? ["Anyone on your LAN or tailnet can reach the port. A pairing code is the only lock."] : []), ...(setup.lanFromOldDefault - ? [`Older installs keep LAN access on. Turn it off: \`${forkCliCommand("up --no-lan")}\`.`] + ? [`Older installs keep LAN access on. Turn it off: \`${hints.upNoLan}\`.`] : []), ]; return [ @@ -184,18 +202,18 @@ const formatSetup = (setup: Setup) => { ].join("\n"); }; -const formatNextSteps = (routes: Routes, serviceInstalled: boolean, pairCommand: string) => +const formatNextSteps = (routes: Routes, serviceInstalled: boolean, hints: Hints) => [ ...(routes.connect ? ["On your other device, sign in to T3 Connect with the same account."] : []), - ...(routes.lan ? [`Run \`${pairCommand}\`. Use the code on your other device.`] : []), + ...(routes.lan ? [`Run \`${hints.pair}\`. Use the code on your other device.`] : []), ...(routes.connect || routes.lan ? [] : [ serviceInstalled ? "Remote access is off. S2Code still runs here in the background." - : `Remote access is off. Run \`${forkCliCommand("").trimEnd()}\` to use S2Code here.`, + : `Remote access is off. Run \`${hints.run}\` to use S2Code here.`, ]), ].join("\n"); @@ -214,7 +232,7 @@ const setUp = Effect.fn("cli.up")(function* (flags: { onNone: () => [], onSome: (dir) => ["--base-dir", dir], }); - const { command: pairCommand } = yield* resolveHostCliCommand("pair", baseDirArgs); + const hints = yield* resolveHints(flags.baseDir); const before = yield* readSetup(); // Before any question or write: install would refuse only after both. if (before.service.otherBaseDir !== undefined) { @@ -240,7 +258,8 @@ const setUp = Effect.fn("cli.up")(function* (flags: { const interactive = !flags.yes && interactiveTerminal(); let routes = plan.routes; if (plan.ask.length > 0 && interactive) { - if (before.service.installed) yield* Console.log(`Current setup\n${formatSetup(before)}\n`); + if (before.service.installed) + yield* Console.log(`Current setup\n${formatSetup(before, hints)}\n`); const picked = yield* Prompt.run( Prompt.MultiSelect({ message: "Allow connections through:", @@ -277,7 +296,7 @@ const setUp = Effect.fn("cli.up")(function* (flags: { yield* disconnectCloud({ clearAuthorization: false }); } if (current.lan) yield* CliService.writeServiceEnv(baseDir, { S2CODE_LAN: "false" }); - return yield* Console.log(formatNextSteps(routes, false, pairCommand)); + return yield* Console.log(formatNextSteps(routes, false, hints)); } const { installedVersion } = before.service; const newer = @@ -387,9 +406,8 @@ const setUp = Effect.fn("cli.up")(function* (flags: { if ("failed" in result && before.service.installed) { // The old service still runs, so a foreground server would clash with it. yield* restoreServiceEnv; - const { command } = yield* resolveHostCliCommand("up", baseDirArgs); yield* Console.log( - `Service setup failed: ${result.failed} Fix that, then run \`${command}\` again.`, + `Service setup failed: ${result.failed} Fix that, then run \`${hints.up}\` again.`, ); } else if ("failed" in result) { yield* printServeCommand(`Service setup failed: ${result.failed}`); @@ -432,10 +450,10 @@ const setUp = Effect.fn("cli.up")(function* (flags: { const after = yield* readSetup(); yield* Console.log( // From what took effect: a failed service step can undo a choice. - `\nThis machine\n${formatSetup(after)}\n\n${formatNextSteps( + `\nThis machine\n${formatSetup(after, hints)}\n\n${formatNextSteps( { connect: after.connect === true, lan: after.lan }, after.service.installed, - pairCommand, + hints, )}`, ); }); @@ -544,12 +562,12 @@ export const statusCommand = Command.make("status", { ), ), ); + if (flags.json) return yield* Console.log(setupJson(setup)); + const hints = yield* resolveHints(flags.baseDir); yield* Console.log( - flags.json - ? setupJson(setup) - : setup.service.otherBaseDir !== undefined - ? `This machine\n${formatSetup(setup)}` - : `This machine\n${formatSetup(setup)}\n\nChange access: \`${forkCliCommand("up")}\`.`, + setup.service.otherBaseDir !== undefined + ? `This machine\n${formatSetup(setup, hints)}` + : `This machine\n${formatSetup(setup, hints)}\n\nChange access: \`${hints.up}\`.`, ); }), ), diff --git a/apps/server/src/environment/DirectEndpoints.test.ts b/apps/server/src/environment/DirectEndpoints.test.ts index 5e1459b3dc2ab..09ecc1ee8c8c9 100644 --- a/apps/server/src/environment/DirectEndpoints.test.ts +++ b/apps/server/src/environment/DirectEndpoints.test.ts @@ -246,6 +246,17 @@ describe("resolveBoundEndpoints", () => { ).toEqual([{ kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" }]); }); + it("reports an explicit bind to Tailscale's IPv6 address as the tailnet route", () => { + expect( + resolveBoundEndpoints({ + platform: "linux", + host: "fd7a:115c:a1e0::1", + port: 3773, + interfaces: INTERFACES, + }), + ).toEqual([{ kind: "tailnet", httpBaseUrl: "http://[fd7a:115c:a1e0::1]:3773/" }]); + }); + it("never reports an IPv4-mapped host, which can name the client's own loopback", () => { expect( resolveBoundEndpoints({ diff --git a/apps/server/src/environment/DirectEndpoints.ts b/apps/server/src/environment/DirectEndpoints.ts index e883766e070c4..4508d208e75e6 100644 --- a/apps/server/src/environment/DirectEndpoints.ts +++ b/apps/server/src/environment/DirectEndpoints.ts @@ -40,6 +40,7 @@ export class DirectEndpoints extends Context.Service< >()("t3/environment/DirectEndpoints") {} // Credentials travel over HTTP; public IPs leak them and hostnames can resolve differently per client. +// Wildcard binds stay IPv4: the private-network listener check accepts only IPv4 peers. const isAdvertisableAddress = (address: string): boolean => NodeNet.isIPv4(address) && !address.startsWith("127.") && isPrivateNetworkAddress(address); @@ -81,7 +82,10 @@ export function resolveBoundEndpoints(input: { !(input.platform === "win32" && WINDOWS_HOST_ADAPTER_MAC.test(entry.mac)), ) .map((entry) => entry.address) - : [input.host!].filter(isAdvertisableAddress); + : [input.host!].filter( + (address) => + isAdvertisableAddress(address) || (NodeNet.isIPv6(address) && isTailnetHost(address)), + ); return [...new Set(addresses)] .filter((address) => !input.onCloudVm || tailscaleAddresses.has(address)) .map((address) => ({ diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index d6a6adb2d91d2..9db9bca7b53e1 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -465,9 +465,9 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { : { headBranchProbe: scenario.headBranchProbe ?? - (({ headSelectors, defaultBranchHeadSelector }) => ({ - headSelectors: defaultBranchHeadSelector - ? [defaultBranchHeadSelector] + (({ headSelectors, ownerHeadSelector }) => ({ + headSelectors: ownerHeadSelector + ? [ownerHeadSelector] : headSelectors.filter((selector) => !selector.includes(":")), limit: 100, })), @@ -2280,6 +2280,72 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("finds a fork branch's open PR past a full page of other forks' PRs", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["remote", "add", "fork", forkDir]); + yield* runGit(repoDir, ["checkout", "-b", "feature"]); + yield* runGit(repoDir, ["push", "-u", "fork", "feature"]); + yield* configureVisibleRemoteUrlWithLocalRewrite( + repoDir, + "origin", + "git@github.com:team/repository.git", + originDir, + ); + yield* configureVisibleRemoteUrlWithLocalRewrite( + repoDir, + "fork", + "git@github.com:alice/repository.git", + forkDir, + ); + const otherForks: FakeChangeRequest[] = Array.from({ length: 100 }, (_, index) => ({ + number: 200 - index, + title: "Update docs", + url: `https://github.com/team/repository/pull/${200 - index}`, + baseRefName: "main", + headRefName: "feature", + state: "open", + isCrossRepository: true, + headRepositoryNameWithOwner: `fork-${index + 1}/repository`, + headRepositoryOwnerLogin: `fork-${index + 1}`, + })); + const { manager, providerCalls } = yield* makeManager({ + providerScenario: { + prListSequenceByHeadSelector: { feature: [otherForks, otherForks] }, + prListByHeadSelector: { + "alice:feature": [ + { + number: 1, + title: "This fork", + url: "https://github.com/team/repository/pull/1", + baseRefName: "main", + headRefName: "feature", + state: "open", + isCrossRepository: true, + headRepositoryNameWithOwner: "alice/repository", + headRepositoryOwnerLogin: "alice", + }, + ], + }, + }, + }); + + expect(yield* manager.branchPullRequest({ cwd: repoDir, branch: "feature" })).toMatchObject({ + number: 1, + state: "open", + }); + expect(listed(providerCalls).map((call) => [call.headSelector, call.state])).toEqual([ + ["feature", "all"], + ["alice:feature", "open"], + ]); + }), + ); + it.effect.each([ { remoteUrl: "git@gitlab.com:Group/Subgroup/Fork.git", setUpstream: true }, { remoteUrl: "git@gitlab.com:Group/Subgroup/Fork.git", setUpstream: false }, @@ -3658,6 +3724,56 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("finishes a pushed commit when the final status read fails", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-after-push"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + NodeFS.writeFileSync(NodePath.join(repoDir, "change.txt"), "change\n"); + const gate = { + matches: (args: ReadonlyArray) => args[0] === "push", + reached: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + const events: GitActionProgressEvent[] = []; + const { manager } = yield* makeManager({ gitSpawnGate: gate }); + + const action = yield* Effect.forkChild( + runStackedAction( + manager, + { cwd: repoDir, action: "commit_push", commitMessage: "Status after push" }, + { + progressReporter: { + publish: (event) => + Effect.sync(() => { + events.push(event); + }), + }, + }, + ), + ); + yield* Deferred.await(gate.reached); + NodeFS.writeFileSync(NodePath.join(repoDir, ".git", "index.lock"), ""); + yield* Deferred.succeed(gate.release, undefined); + const result = yield* Fiber.join(action); + + expect(result.push.status).toBe("pushed"); + expect(result.toast.cta).toEqual({ kind: "none" }); + expect(events.at(-1)?.kind).toBe("action_finished"); + expect( + (yield* runGit(remoteDir, [ + "--git-dir=.", + "log", + "-1", + "--pretty=%s", + "feature/status-after-push", + ])).stdout.trim(), + ).toBe("Status after push"); + }), + ); + it.effect("hands the branch base to the host when a failed first push is retried", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 8cb8584dcb552..c3fc87f9d13c5 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -101,6 +101,11 @@ export interface GitRunStackedActionOptions { readonly progressReporter?: GitActionProgressReporter; } +export interface GitLocalStatusOptions { + /** Defaults to true. The branch-wide totals cost about half of a local status read. */ + readonly includeBranchChanges?: boolean; +} + export interface GitRemoteStatusOptions extends GitVcsDriver.GitRemoteStatusOptions { readonly refreshMissingPullRequest?: boolean; } @@ -131,6 +136,7 @@ export class GitManager extends Context.Service< ) => Effect.Effect; readonly localStatus: ( input: VcsStatusInput, + options?: GitLocalStatusOptions, ) => Effect.Effect; readonly remoteStatus: ( input: VcsStatusInput, @@ -622,10 +628,10 @@ function headBranchProbe( provider: SourceControlProvider.SourceControlProvider["Service"], headSelectors: ReadonlyArray, state: "open" | "all", - defaultBranchHeadSelector?: string, + ownerHeadSelector?: string, ) { return ( - provider.headBranchProbe?.({ headSelectors, state, defaultBranchHeadSelector }) ?? { + provider.headBranchProbe?.({ headSelectors, state, ownerHeadSelector }) ?? { headSelectors, limit: state === "open" ? 1 : 20, } @@ -1201,9 +1207,12 @@ export const make = Effect.gen(function* () { behindCount: 0, aheadOfDefaultCount: 0, }; - const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) { + const readLocalStatus = Effect.fn("readLocalStatus")(function* ( + cwd: string, + includeBranchChanges: boolean, + ) { const details = yield* gitCore - .statusDetailsLocal(cwd, { includeDivergence: false, includeBranchChanges: true }) + .statusDetailsLocal(cwd, { includeDivergence: false, includeBranchChanges }) .pipe( Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)), ); @@ -1222,13 +1231,22 @@ export const make = Effect.gen(function* () { ...(details.branchChanges ? { branchChanges: details.branchChanges } : {}), } satisfies VcsStatusLocalResult; }); - const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, { - capacity: STATUS_RESULT_CACHE_CAPACITY, - timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero), - }); + const makeLocalStatusResultCache = (includeBranchChanges: boolean) => + Cache.makeWith((cwd: string) => readLocalStatus(cwd, includeBranchChanges), { + capacity: STATUS_RESULT_CACHE_CAPACITY, + timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero), + }); + // Separate entries, so a read without totals is never served to a caller that shows them. + const localStatusResultCache = yield* makeLocalStatusResultCache(true); + const localStatusWithoutBranchChangesCache = yield* makeLocalStatusResultCache(false); const invalidateLocalStatusResultCache = (cwd: string) => normalizeStatusCacheKey(cwd).pipe( - Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)), + Effect.flatMap((cacheKey) => + Effect.all([ + Cache.invalidate(localStatusResultCache, cacheKey), + Cache.invalidate(localStatusWithoutBranchChangesCache, cacheKey), + ]), + ), ); const prLookupEpochByCwd = new Map(); const prLookupEpoch = (cwd: string) => prLookupEpochByCwd.get(cwd) ?? 0; @@ -1961,9 +1979,10 @@ export const make = Effect.gen(function* () { | "headRepositoryOwnerLogin" | "isCrossRepository" >, + ownerHeadSelector?: string, ) { const provider = yield* sourceControlProvider(cwd); - const probe = headBranchProbe(provider, headContext.headSelectors, "open"); + const probe = headBranchProbe(provider, headContext.headSelectors, "open", ownerHeadSelector); for (const headSelector of probe.headSelectors) { const pullRequests = yield* provider.listChangeRequests({ cwd, @@ -2004,6 +2023,7 @@ export const make = Effect.gen(function* () { ? `${headContext.headRepositoryOwnerLogin}:${defaultBranch}` : undefined, ); + let pageWasFull = false; for (const headSelector of probe.headSelectors) { const pullRequests = yield* provider.listChangeRequests({ cwd, @@ -2011,6 +2031,7 @@ export const make = Effect.gen(function* () { state: "all", limit: probe.limit, }); + pageWasFull ||= pullRequests.length >= probe.limit; for (const pr of pullRequests.map(toPullRequestInfo)) { if (!matchesBranchHeadContext(pr, headContext)) { @@ -2026,6 +2047,17 @@ export const make = Effect.gen(function* () { if (latestOpenPr) { return latestOpenPr; } + // Forks reusing the head name can fill the page before the branch's own open PR. + if (pageWasFull) { + const openPr = yield* findOpenPr( + cwd, + headContext, + headContext.headRepositoryOwnerLogin + ? `${headContext.headRepositoryOwnerLogin}:${headContext.headBranch}` + : undefined, + ); + if (openPr) return openPr; + } return parsed[0] ?? null; }); const buildCompletionToast = Effect.fn("buildCompletionToast")(function* ( @@ -2042,16 +2074,17 @@ export const make = Effect.gen(function* () { hasUpstream: boolean; } | null = null; - if (result.action !== "commit") { - const finalStatus = yield* gitCore.statusDetails(cwd); - if (finalStatus.branch) { - finalBranchContext = { - branch: finalStatus.branch, - upstreamRef: finalStatus.upstreamRef, - hasUpstream: finalStatus.hasUpstream, - }; - currentBranchIsDefault = finalStatus.isDefaultBranch; - } + const finalStatus = + result.action === "commit" + ? null + : yield* gitCore.statusDetails(cwd).pipe(Effect.orElseSucceed(() => null)); + if (finalStatus?.branch) { + finalBranchContext = { + branch: finalStatus.branch, + upstreamRef: finalStatus.upstreamRef, + hasUpstream: finalStatus.hasUpstream, + }; + currentBranchIsDefault = finalStatus.isDefaultBranch; } const explicitResultPr = @@ -2103,6 +2136,7 @@ export const make = Effect.gen(function* () { } : (result.action === "push" || result.action === "commit_push") && result.push.status === "pushed" && + finalStatus !== null && !currentBranchIsDefault ? { kind: "run_action" as const, @@ -2553,9 +2587,14 @@ export const make = Effect.gen(function* () { }); const localStatus: GitManager["Service"]["localStatus"] = Effect.fn("localStatus")( - function* (input) { + function* (input, options) { const cacheKey = yield* normalizeStatusCacheKey(input.cwd); - return yield* Cache.get(localStatusResultCache, cacheKey); + return yield* Cache.get( + options?.includeBranchChanges === false + ? localStatusWithoutBranchChangesCache + : localStatusResultCache, + cacheKey, + ); }, ); const remoteStatus: GitManager["Service"]["remoteStatus"] = Effect.fn("remoteStatus")( diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index 3cffe66441365..287207840ad6a 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -51,6 +51,7 @@ export class GitWorkflowService extends Context.Service< ) => Effect.Effect; readonly localStatus: ( input: VcsStatusInput, + options?: GitManager.GitLocalStatusOptions, ) => Effect.Effect; readonly currentBranch: (cwd: string) => Effect.Effect; readonly upstreamDivergence: (cwd: string) => Effect.Effect< @@ -341,11 +342,11 @@ export const make = Effect.gen(function* () { ), ); }), - localStatus: Effect.fn("GitWorkflowService.localStatus")(function (input) { + localStatus: Effect.fn("GitWorkflowService.localStatus")(function (input, options) { return detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe( Effect.flatMap((isGitRepository) => isGitRepository - ? gitManager.localStatus(input) + ? gitManager.localStatus(input, options) : Effect.succeed(nonRepositoryLocalStatus()), ), ); diff --git a/apps/server/src/guest/GuestShareService.test.ts b/apps/server/src/guest/GuestShareService.test.ts index 5a873eeb23952..b377cd1ce00b0 100644 --- a/apps/server/src/guest/GuestShareService.test.ts +++ b/apps/server/src/guest/GuestShareService.test.ts @@ -37,6 +37,7 @@ import { resolveAttachmentPathById, sweepStalePendingAttachments, } from "../attachmentStore.ts"; +import { resolveAttachmentRelativePath } from "../attachmentPaths.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import { CloudManagedEndpointRuntime } from "../cloud/ManagedEndpointRuntime.ts"; import * as ServerConfig from "../config.ts"; @@ -449,6 +450,10 @@ const writeItem = ( | Pick< Extract, "type" | "status" | "fileName" | "diffStr" | "oldStr" | "newStr" + > + | Pick< + Extract, + "type" | "status" | "toolName" | "input" | "output" >, ) => Effect.gen(function* () { @@ -539,6 +544,80 @@ it.effect("gives the guest a command's detail and output, but no file diffs", () }).pipe(Effect.provide(layerTest)), ); +it.effect("gives a fork's guest the commands the fork shows from its source thread", () => + Effect.gen(function* () { + const { orchestrator, guestShares } = yield* shareThread; + const command = yield* writeItem("item:command", { + type: "command_execution", + status: "completed", + input: "ls /work/src", + output: "/work/src/auth.ts\n", + }); + const { attachmentsDir } = yield* ServerConfig.ServerConfig; + const page = createAttachmentId(threadId, "html")!; + yield* (yield* FileSystem.FileSystem).writeFileString( + resolveAttachmentRelativePath({ attachmentsDir, relativePath: `${page}.html` })!, + "

Plan

", + ); + const render = yield* writeItem("item:render", { + type: "dynamic_tool", + status: "completed", + toolName: "mcp__t3-code__html_render", + input: {}, + output: [ + { + type: "text", + text: JSON.stringify({ htmlRender: { attachmentId: page, title: "Plan", height: 300 } }), + }, + ], + }); + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const run = (yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs[0]!; + yield* eventSink.write({ + events: [ + { + id: EventId.make("event:run-done"), + type: "run.updated", + threadId, + runId: run.id, + providerInstanceId: instanceId, + occurredAt: now, + payload: { ...run, status: "completed", completedAt: now }, + }, + ], + }); + const forkId = ThreadId.make("thread:guest-share-fork"); + yield* orchestrator.dispatch({ + type: "thread.fork", + commandId: CommandId.make("fork"), + sourceThreadId: threadId, + targetThreadId: forkId, + sourcePoint: { type: "run", runId: run.id }, + createdBy: "user", + creationSource: "web", + }); + const { url } = yield* guestShares.create({ threadId: forkId }); + const { token: session } = yield* guestShares.redeem({ + credential: url.slice(url.indexOf("#") + 1), + name: "Sam", + }); + + const detail = (yield* guestShares.item(session, command)).item; + assert.deepInclude(detail, { input: "ls /work/src", output: "/work/src/auth.ts\n" }); + const frames = Array.from( + yield* Stream.runCollect(yield* guestShares.commandOutput(session, command)), + ); + assert.deepEqual(frames, [ + { kind: "replace", text: "/work/src/auth.ts\n", truncated: false, running: false }, + ]); + assert.deepEqual(yield* guestShares.render(session, render), { + path: resolveAttachmentPathById({ attachmentsDir, attachmentId: page })!, + title: "Plan", + }); + }).pipe(Effect.provide(layerTest)), +); + it.effect("pages the guest back through turns older than the stream's snapshot", () => Effect.gen(function* () { const { guestShares, credential } = yield* shareThread; diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.ts index 71550d622358d..b5b21a7af2ae7 100644 --- a/apps/server/src/guest/GuestShareService.ts +++ b/apps/server/src/guest/GuestShareService.ts @@ -639,17 +639,26 @@ const make = Effect.gen(function* () { itemId: string, ) { const { thread } = yield* authorize(session, "session"); - const item = yield* orchestrator - .getTurnItem({ threadId: thread.id, itemId: TurnItemId.make(itemId) }) - .pipe(Effect.mapError(() => unavailable)); + const id = TurnItemId.make(itemId); + const item = + (yield* orchestrator + .getTurnItem({ threadId: thread.id, itemId: id }) + .pipe(Effect.mapError(() => unavailable))) ?? + // A fork shows its source's earlier items, which stay in the source thread. + (thread.forkedFrom === null + ? null + : yield* orchestrator.getTimelinePage(thread.id, { itemId: id, limit: 1 }).pipe( + Effect.map((page) => page.items[0]?.item ?? null), + Effect.mapError(() => unavailable), + )); return item === null ? yield* unavailable : { thread, item }; }); const render = Effect.fn("GuestShareService.render")(function* (session: string, itemId: string) { - const { thread, item } = yield* threadItem(session, itemId); + const { item } = yield* threadItem(session, itemId); if (item.type !== "dynamic_tool") return yield* unavailable; const reference = htmlRenderFromToolItem(item); - const [attachmentId] = threadHtmlRenderAttachmentIds(thread.id, [item]); + const [attachmentId] = threadHtmlRenderAttachmentIds(item.threadId, [item]); const path = attachmentId === undefined ? null @@ -685,9 +694,9 @@ const make = Effect.gen(function* () { session: string, itemId: string, ) { - const { thread, item } = yield* threadItem(session, itemId); + const { item } = yield* threadItem(session, itemId); if (item.type !== "command_execution") return yield* unavailable; - return commandOutputs.subscribe({ threadId: thread.id, itemId: item.id }).pipe( + return commandOutputs.subscribe({ threadId: item.threadId, itemId: item.id }).pipe( // A lost hub stream ends the output; the row reloads it when reopened. Stream.catchCause(() => Stream.empty), Stream.interruptWhen(untilRevoked(session)), diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index d0b232315213f..2cf33ea62cf05 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -55,6 +55,7 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods, DESKTOP_RENDERER_ORIGINS, + MCP_HTTP_PATH, } from "./httpCors.ts"; import { requestUrl } from "./requestUrl.ts"; @@ -261,7 +262,7 @@ export const layerBrowserApiCors = Layer.unwrap( const config = yield* ServerConfig.ServerConfig; const devOrigin = config.devUrl?.origin; // Credentialed dev requests need explicit Vite/Electron origins; packaged desktop uses the default wildcard. - return HttpRouter.cors({ + const cors = HttpMiddleware.cors({ ...(devOrigin ? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins], @@ -272,6 +273,15 @@ export const layerBrowserApiCors = Layer.unwrap( allowedHeaders: browserApiCorsAllowedHeaders, maxAge: 600, }); + return HttpRouter.middleware( + (httpEffect) => { + const withCors = cors(httpEffect); + return Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => + request.url.split("?", 1)[0] === MCP_HTTP_PATH ? httpEffect : withCors, + ); + }, + { global: true }, + ); }), ); diff --git a/apps/server/src/httpCors.ts b/apps/server/src/httpCors.ts index 655e7fee79f71..3e0af83b5c3ad 100644 --- a/apps/server/src/httpCors.ts +++ b/apps/server/src/httpCors.ts @@ -23,3 +23,6 @@ export const DESKTOP_RENDERER_ORIGINS = [ "shuv2code-nightly://app", "shuv2code-preview://app", ] as const; + +/** MCP refuses every browser Origin with 403, so the browser CORS layer must not answer for it. */ +export const MCP_HTTP_PATH = "/mcp"; diff --git a/apps/server/src/imageMime.test.ts b/apps/server/src/imageMime.test.ts index 5d427b957265a..87fb46d912939 100644 --- a/apps/server/src/imageMime.test.ts +++ b/apps/server/src/imageMime.test.ts @@ -10,16 +10,22 @@ describe("imageMime", () => { }); }); - it("parses base64 data URL with spaces in payload", () => { - expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({ - mimeType: "image/png", - base64: "SGVsbG8=", - }); - }); + it.each(["\t", "\n", "\f", "\r", " "])( + "parses base64 data URL with ASCII whitespace %j", + (space) => { + expect(parseBase64DataUrl(`data:image/png;base64,SGVs${space}bG8=\n`)).toEqual({ + mimeType: "image/png", + base64: "SGVsbG8=", + }); + }, + ); it("rejects payload with characters outside the base64 alphabet", () => { expect(parseBase64DataUrl("data:image/png;base64,SGVs!bG8=")).toBeNull(); expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull(); + for (const space of ["\v", "\u00a0", "\u2003"]) { + expect(parseBase64DataUrl(`data:image/png;base64,SGVs${space}bG8=`)).toBeNull(); + } }); // regression: #3952 image upload crashed dispatchCommand with a stack overflow @@ -43,7 +49,7 @@ describe("imageMime", () => { it("rejects empty and whitespace-only payloads", () => { expect(parseBase64DataUrl("data:image/png;base64,")).toBeNull(); - expect(parseBase64DataUrl("data:image/png;base64, \r\n")).toBeNull(); + expect(parseBase64DataUrl("data:image/png;base64, \t\r\n\f")).toBeNull(); }); it("parses a case-insensitive scheme and mime type", () => { diff --git a/apps/server/src/imageMime.ts b/apps/server/src/imageMime.ts index 338bbd62ce592..4c985dccb8235 100644 --- a/apps/server/src/imageMime.ts +++ b/apps/server/src/imageMime.ts @@ -42,7 +42,7 @@ function isBase64Char(code: number): boolean { } function isBase64Whitespace(code: number): boolean { - return code === 0x0d || code === 0x0a || code === 0x20; + return code === 0x09 || code === 0x0a || code === 0x0c || code === 0x0d || code === 0x20; } // V8 regexes use the JS stack; scanning image payloads can overflow a deep fiber stack. diff --git a/apps/server/src/mcp/McpDeviceToolkit.test.ts b/apps/server/src/mcp/McpDeviceToolkit.test.ts index 91c33029be305..11a4e9ca589e5 100644 --- a/apps/server/src/mcp/McpDeviceToolkit.test.ts +++ b/apps/server/src/mcp/McpDeviceToolkit.test.ts @@ -235,7 +235,7 @@ it.effect("registers the device tools and returns the screenshot as image conten expect(denied.content).toEqual([ { type: "text", - text: "Agent device access is turned off for this environment. Ask the user to turn on Agent device access in Settings > Integrations > Devices; it applies when the agent session next starts, such as in a new thread.", + text: "Agent device access is turned off for this environment. Ask the user to turn on the Device hub and Agent device access in Settings > Integrations > Devices; it applies when the agent session next starts, such as in a new thread.", }, ]); }), diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 53c4d44e5e680..8d5f9f9439383 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -53,6 +53,7 @@ import * as DeviceService from "../device/DeviceService.ts"; import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts"; import * as PullRequestService from "../pullRequest/PullRequestService.ts"; import * as ServerConfig from "../config.ts"; +import * as ServerHttp from "../http.ts"; import * as ServerSettings from "../serverSettings.ts"; import { advertisedJsonSchema } from "./advertisedJsonSchema.ts"; import * as McpHttpServer from "./McpHttpServer.ts"; @@ -1261,6 +1262,12 @@ it.effect("admits provider and OAuth client credentials and points only clients ), }), ), + Layer.provide(ServerHttp.layerBrowserApiCors), + Layer.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-origin-test-" }).pipe( + Layer.provide(NodeServices.layer), + ), + ), ); const traced = recordSpans(); yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe( @@ -1343,6 +1350,30 @@ it.effect("admits provider and OAuth client credentials and points only clients (span) => span.name.startsWith("mcp.tool.") || span.name.startsWith("McpServer."), ), ).toEqual([]); + + // A present, disallowed Origin is refused with 403 before credentials or CORS answer. + const foreignOrigin = (method: "POST" | "OPTIONS", token: string | undefined) => + httpClient.execute( + HttpClientRequest.make(method)("/mcp", { + headers: { + origin: "https://untrusted.invalid", + accept: "application/json, text/event-stream", + "access-control-request-method": "POST", + ...(token === undefined ? {} : { authorization: `Bearer ${token}` }), + }, + ...(method === "POST" + ? { + body: HttpBody.text( + `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`, + "application/json", + ), + } + : {}), + }), + ); + expect((yield* foreignOrigin("POST", providerToken)).status).toBe(403); + expect((yield* foreignOrigin("POST", undefined)).status).toBe(403); + expect((yield* foreignOrigin("OPTIONS", undefined)).status).toBe(403); }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index a13c4e70fd056..62144a3dbc204 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -96,6 +96,7 @@ import * as HtmlHandlers from "./toolkits/html/handlers.ts"; import { MessageToolkit } from "./toolkits/message/tools.ts"; import * as MessageHandlers from "./toolkits/message/handlers.ts"; import { HtmlPreviewTool, HtmlPreviewToolkit, HtmlRenderToolkit } from "./toolkits/html/tools.ts"; +import { MCP_HTTP_PATH } from "../httpCors.ts"; import { requestUrl } from "../requestUrl.ts"; const mcpResourceMetadataUrl = (request: HttpServerRequest.HttpServerRequest) => @@ -286,7 +287,10 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { }); // Untraced: a span here would wrap the tool call; the HTTP server span already covers it. return Effect.fnUntraced(function* (httpEffect) { - const admitted = yield* authenticateRequest(yield* HttpServerRequest.HttpServerRequest); + const request = yield* HttpServerRequest.HttpServerRequest; + // The transport allows no browser Origin; refuse it before credentials, as the MCP spec requires. + if (request.headers.origin !== undefined) return HttpServerResponse.empty({ status: 403 }); + const admitted = yield* authenticateRequest(request); if (HttpServerResponse.isHttpServerResponse(admitted)) return admitted; return yield* httpEffect.pipe( Effect.provideService(McpInvocationContext.McpInvocationContext, admitted), @@ -1350,7 +1354,7 @@ export const layerMcpTransport = (registrations: Layer.Layer { const parentThreadId = ThreadId.make("thread:mcp-restart-parent"); const childThreadId = ThreadId.make("thread:mcp-restart-child"); const taskId = NodeId.make("node:mcp-restart-task"); + const cutRunId = RunId.make("run:mcp-restart-child"); + const continuationRunId = RunId.make("run:mcp-restart-continuation"); const dispatched = yield* Ref.make(0); let awaitsRestart = true; let readFails = true; @@ -284,10 +286,12 @@ describe("OrchestratorMcpService", () => { thread: { id: childThreadId, title: "Child" }, runs: [ { - id: RunId.make("run:mcp-restart-child"), + id: cutRunId, ordinal: 1, status: "cancelled", delegatedTaskId: taskId, + startedAt: DateTime.makeUnsafe("2026-10-03T10:00:00Z"), + completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00Z"), }, { id: RunId.make("run:mcp-restart-later"), ordinal: 2, status: "running" }, ], @@ -299,12 +303,17 @@ describe("OrchestratorMcpService", () => { runtimeRequests: [], turnItems: [], } as unknown as OrchestrationV2ThreadProjection; + let childRuns = childProjection.runs; const layerDependencies = Layer.mergeAll( NodeServices.layer, NodeCrypto.layer, Layer.mock(ThreadManagementService.ThreadManagementService)({ getThreadRecords: (threadId) => - Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection), + Effect.succeed( + threadId === parentThreadId + ? parentProjection + : { ...childProjection, runs: childRuns }, + ), delegatedTaskResultPending: () => readFails ? Effect.fail(new OrchestratorProjectionError({ threadId: childThreadId })) @@ -344,11 +353,63 @@ describe("OrchestratorMcpService", () => { assert.equal(held.status, "running"); assert.equal(held.workState, "working"); assert.isNull(held.summary); + assert.isNull(held.latestTerminalRunId); + assert.isNull(held.latestTerminalStatus); assert.equal(yield* Ref.get(dispatched), 0); + + const continuationRun = { + id: continuationRunId, + ordinal: 3, + status: "running", + delegatedTaskId: taskId, + startedAt: DateTime.makeUnsafe("2026-10-03T10:06:00Z"), + restartContinuationOfRunId: cutRunId, + } as unknown as (typeof childRuns)[number]; + childRuns = [...childProjection.runs, continuationRun]; + const continuing = yield* service.taskStatus(scope, taskId); + assert.equal(continuing.status, "running"); + assert.isNull(continuing.latestTerminalRunId); + assert.isNull(continuing.latestTerminalStatus); + + // A second restart cut the continuation, and its own continuation declined. + childRuns = [ + ...childProjection.runs, + { + ...continuationRun, + status: "cancelled", + completedAt: DateTime.makeUnsafe("2026-10-03T10:10:00Z"), + }, + ]; awaitsRestart = false; const settled = yield* service.taskStatus(scope, taskId); assert.equal(settled.status, "cancelled"); + assert.equal(settled.latestTerminalRunId, continuationRunId); + assert.equal(settled.latestTerminalStatus, "cancelled"); assert.equal(yield* Ref.get(dispatched), 1); + + // A continuation cancelled before it started leaves the cut run as the result. + childRuns = [ + ...childProjection.runs, + { ...continuationRun, status: "cancelled", startedAt: null }, + ]; + const unstarted = yield* service.taskStatus(scope, taskId); + assert.equal(unstarted.latestTerminalRunId, cutRunId); + assert.equal(unstarted.latestTerminalStatus, "cancelled"); + + // That unstarted continuation was itself continued, so the whole chain is still live. + childRuns = [ + ...childProjection.runs, + { ...continuationRun, status: "cancelled", startedAt: null }, + { + ...continuationRun, + id: RunId.make("run:mcp-restart-continuation-2"), + ordinal: 4, + restartContinuationOfRunId: continuationRunId, + }, + ]; + const chained = yield* service.taskStatus(scope, taskId); + assert.isNull(chained.latestTerminalRunId); + assert.isNull(chained.latestTerminalStatus); }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); }), ); @@ -5005,11 +5066,18 @@ describe("OrchestratorMcpService thread list", () => { capabilities: new Set(["orchestration"]), issuedAt: 1, }; - const shell = (id: string, projectId: string, snoozed: boolean, waiting = false) => ({ + const shell = ( + id: string, + projectId: string, + snoozed: boolean, + waiting = false, + pinned = false, + ) => ({ ...liveThreadShell(ThreadId.make(id)), projectId: ProjectId.make(projectId), status: "completed" as const, snoozedUntil: snoozed ? DateTime.makeUnsafe("2099-01-01T00:00:00Z") : null, + pinnedAt: pinned ? DateTime.makeUnsafe("2026-01-01T00:00:00Z") : null, blockedOnThreadWait: waiting, pendingBackgroundTasks: waiting ? [ @@ -5028,7 +5096,7 @@ describe("OrchestratorMcpService thread list", () => { const shells = [ shell("thread:a-snoozed", "project:a", true), shell("thread:a-awake", "project:a", false), - shell("thread:b-snoozed", "project:b", true, true), + shell("thread:b-snoozed", "project:b", true, true, true), { ...shell("thread:a-awaiting-command", "project:a", false), activityRunStatus: null, @@ -5101,6 +5169,10 @@ describe("OrchestratorMcpService thread list", () => { ["thread:b-snoozed", "project:b"], ], ); + assert.deepStrictEqual( + listed.threads.map((thread) => thread.pinned), + [false, true], + ); assert.deepStrictEqual( listed.threads.map((thread) => [thread.blockedOnThreadWait, thread.pendingBackgroundTasks]), [ diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index e69f3274c2af8..8ce06f9f1e5be 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -138,7 +138,7 @@ import { runtimeModeRank, taskPrompt, } from "./delegatedTaskModes.ts"; -import { isLiveCallerShell, threadNotFound } from "./threadAccess.ts"; +import { assertTargetWithinLimits, isLiveCallerShell, threadNotFound } from "./threadAccess.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as PeerForwarding from "../peer/PeerForwarding.ts"; import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; @@ -736,17 +736,38 @@ function pageIncludesTerminalTaskResult(input: { function latestTerminalResultRun( projection: Pick, delegatedRun: OrchestrationV2Run | undefined, + awaitingContinuationRun: OrchestrationV2Run | undefined, ): OrchestrationV2Run | undefined { const monitorRunIds = new Set( projection.messages .filter((message) => message.notification?.source.kind === "monitor") .map((message) => message.runId), ); + // A restart-cut run, and each cut run before it in the chain, has no outcome while a + // continuation is pending, live, or ran to a result. + const runsById = new Map(projection.runs.map((run) => [run.id, run])); + const supersededRunIds = new Set(); + const supersede = (runId: RunId | undefined) => { + let id = runId; + while (id !== undefined && !supersededRunIds.has(id)) { + supersededRunIds.add(id); + id = runsById.get(id)?.restartContinuationOfRunId; + } + }; + supersede(awaitingContinuationRun?.id); + for (const run of projection.runs) { + if ( + !ThreadManagementService.isTerminalRunStatus(run.status) || + (run.status !== "rolled_back" && run.startedAt !== null) + ) + supersede(run.restartContinuationOfRunId); + } return projection.runs .filter( (run) => ThreadManagementService.isTerminalRunStatus(run.status) && !monitorRunIds.has(run.id) && + !supersededRunIds.has(run.id) && run.status !== "rolled_back" && (run.id === delegatedRun?.id || run.startedAt !== null), ) @@ -963,6 +984,7 @@ function listItemFromShell( ...threadPullRequests(shell.pullRequests), ...threadSettlement(shell), ...threadSnooze(shell, nowMs), + pinned: shell.pinnedAt != null, ...threadBackgroundWork(shell), parentThreadId: shell.lineage.parentThreadId, relationshipToParent: shell.lineage.relationshipToParent, @@ -1030,6 +1052,7 @@ function threadDetail( archived: projection.thread.archivedAt !== null, ...threadSettlement(projection.thread), ...threadSnooze(shell, nowMs), + pinned: shell.pinnedAt != null, ...threadBackgroundWork(shell), createdAt: DateTime.formatIso(projection.thread.createdAt), updatedAt: DateTime.formatIso(projection.thread.updatedAt), @@ -1750,7 +1773,6 @@ const make = Effect.gen(function* () { ) .pipe(Effect.mapError(threadManagementFailure)); const childRun = delegatedTaskRun(childControls, task); - const terminalRun = latestTerminalResultRun(childControls, childRun); const progress = delegatedTaskProgress(childControls); const followupRuns = childRun?.delegatedTaskId === task.id ? delegatedTaskRuns(childControls, task.id) : undefined; @@ -1764,6 +1786,17 @@ const make = Effect.gen(function* () { : delegatedTaskAwaitsWork(followupRuns, childControls) ? "waiting_for_children" : "result_available"; + const heldForRestart = + task.result === null && + taskWorkState === "result_available" && + (yield* threadManagement + .delegatedTaskResultPending(task.childThreadId, childRun?.delegatedTaskId) + .pipe(Effect.mapError(threadManagementFailure))); + const terminalRun = latestTerminalResultRun( + childControls, + childRun, + heldForRestart ? taskResultRun : undefined, + ); const resultRunIds = [ ...new Set( [taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined), @@ -1782,12 +1815,6 @@ const make = Effect.gen(function* () { messages: [...childControls.messages, ...resultRecords.messages], turnItems: resultRecords.turnItems, }; - const heldForRestart = - task.result === null && - taskWorkState === "result_available" && - (yield* threadManagement - .delegatedTaskResultPending(task.childThreadId, childRun?.delegatedTaskId) - .pipe(Effect.mapError(threadManagementFailure))); const workState = task.result !== null ? "result_available" : heldForRestart ? "working" : taskWorkState; const runStatus = taskStatusForRun(taskResultRun ?? childRun); @@ -3776,8 +3803,7 @@ const make = Effect.gen(function* () { sendToThread: Effect.fn("OrchestratorMcpService.sendToThread")(function* (scope, input) { const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId, ["runs"]); yield* assertLiveCallerForOtherThread(scope, parent, target); - yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode); - yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode); + yield* assertTargetWithinLimits(limits, target.thread); const mode = input.mode ?? "auto"; const key = yield* requestKey(input.clientRequestId); @@ -3881,8 +3907,7 @@ const make = Effect.gen(function* () { interruptThread: Effect.fn("OrchestratorMcpService.interruptThread")(function* (scope, input) { const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId, ["runs"]); yield* assertLiveCallerForOtherThread(scope, parent, target); - yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode); - yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode); + yield* assertTargetWithinLimits(limits, target.thread); const key = yield* requestKey(input.clientRequestId); // A peer from before `stop` drops it when decoding, so it interrupts // the run instead, as this call did then. diff --git a/apps/server/src/mcp/threadAccess.test.ts b/apps/server/src/mcp/threadAccess.test.ts index 3b4683871dcc7..914b42426540b 100644 --- a/apps/server/src/mcp/threadAccess.test.ts +++ b/apps/server/src/mcp/threadAccess.test.ts @@ -11,7 +11,7 @@ import * as Layer from "effect/Layer"; import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import { liveThreadShell } from "./McpToolAccess.testkit.ts"; -import { readThread } from "./threadAccess.ts"; +import { assertTargetWithinLimits, readThread } from "./threadAccess.ts"; const bareId = ThreadId.make("5d0b4a3e-8c1f-4a52-9d37-2f6c7e1b9a04"); const claudeCode: McpInvocationContext.McpClientCaller = { @@ -117,3 +117,24 @@ it.effect("points an unencoded delegated-task id at the encoded thread it belong expect(error.message).toContain(`\`${encoded}\``); }), ); + +it.effect("identifies the target and effective caller ceiling when a thread write is refused", () => + Effect.gen(function* () { + for (const [runtimeMode, interactionMode, code] of [ + ["approval-required", "default", "runtime_mode_escalation_denied"], + ["full-access", "plan", "interaction_mode_escalation_denied"], + ["approval-required", "plan", "runtime_mode_escalation_denied"], + ] as const) { + const target = liveThreadShell(bareId, { runtimeMode: "full-access" }); + const error = yield* assertTargetWithinLimits({ runtimeMode, interactionMode }, target).pipe( + Effect.flip, + ); + + expect(error.code).toBe(code); + expect(error.message).toContain(bareId); + expect(error.message).toContain("full-access/default"); + expect(error.message).toContain(`${runtimeMode}/${interactionMode}`); + expect(error.message).not.toMatch(/child|parent mode/i); + } + }), +); diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts index cc5a4651a5de7..8cce38949cdd0 100644 --- a/apps/server/src/mcp/threadAccess.ts +++ b/apps/server/src/mcp/threadAccess.ts @@ -144,11 +144,18 @@ export const loadCaller = Effect.fn("mcp.loadCaller")(function* () { export const assertTargetWithinLimits = ( limits: CallerLimits, - target: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode }, + target: Pick, ) => resolveRuntimeMode(limits.runtimeMode, target.runtimeMode).pipe( Effect.andThen(resolveInteractionMode(limits.interactionMode, target.interactionMode)), Effect.asVoid, + Effect.mapError( + (error) => + new OrchestratorMcpFailure({ + code: error.code, + message: `Thread "${target.id}" runs in ${target.runtimeMode}/${target.interactionMode}, above this caller's ${limits.runtimeMode}/${limits.interactionMode} limit. For linked calls, this limit is also capped by the link's approved access. This call does not create an approval request. Have the user act directly in the target thread through an authorized client.`, + }), + ), ); /** Background subagents retain credentials until provider exit; archived threads and other instances cannot act. */ diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 35a18f5f0b460..d95e44de9e691 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -19,9 +19,12 @@ import { RuntimeRequestId, ThreadId, TurnItemId, + type OrchestrationV2ServerCommand, type OrchestrationV2ProjectedTurnItem, type OrchestrationV2ThreadShell, } from "@t3tools/contracts"; +import { pinOrderKeyBetween } from "@t3tools/shared/pinOrderKey"; +import * as DateTime from "effect/DateTime"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -447,6 +450,7 @@ it.effect("records only failed calls of tools that hand off no work", () => { Effect.succeed( McpToolAccessTestkit.idleThreadProjection(McpToolAccessTestkit.liveThreadShell(id)), ), + listActiveShellIndex: () => Effect.succeed([]), dispatch: () => Effect.succeed({ sequence: 1 } as never), }), ), @@ -756,6 +760,7 @@ it.effect("a client caller targets any thread within its ceiling and cannot act deletedAt: null, }, } as never), + listActiveShellIndex: () => Effect.succeed([]), dispatch: () => Effect.succeed({ sequence: 7, storedEvents: [] }), }), ), @@ -764,6 +769,78 @@ it.effect("a client caller targets any thread within its ceiling and cannot act ), ); +it.effect("an MCP pin lands above every existing pin, as a client pin does", () => { + const dispatched: Array = []; + let targetPinnedAt: DateTime.Utc | null = null; + const pinnedAt = DateTime.makeUnsafe("2026-11-10T00:00:00.000Z"); + const indexEntry = (id: string, pinned: boolean, pinOrderKey: string | null) => ({ + ...McpToolAccessTestkit.liveThreadShell(ThreadId.make(id)), + pinnedAt: pinned ? pinnedAt : null, + pinOrderKey, + mayBeLive: false, + hasRemoteTasks: false, + }); + return Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const pin = server + .callTool({ + name: "t3_thread_organize", + arguments: { action: "pin", threadId: "pin-target" }, + }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, clientScope("auto")), + Effect.provideService(McpSchema.McpServerClient, client), + ); + + const first = yield* pin; + expect(first.isError).toBe(false); + const orderKey = (dispatched[0] as { readonly orderKey?: string }).orderKey; + expect(dispatched[0]).toMatchObject({ type: "thread.pin", threadId: "pin-target" }); + // The smallest key among pinned threads is "g"; the unpinned "b" and keyless pin are ignored. + expect(orderKey).toBe(pinOrderKeyBetween(null, "g")); + + // A thread the handler last saw pinned still gets a key: an unpin can commit + // before this command, and the reducer ignores the key if the pin holds. + targetPinnedAt = pinnedAt; + const again = yield* pin; + expect(again.isError).toBe(false); + expect(dispatched[1]).toMatchObject({ type: "thread.pin", orderKey }); + }).pipe( + Effect.provide( + layerThreadToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(NodeCrypto.layer), + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => + Effect.succeed(McpToolAccessTestkit.liveThreadShell(id, { runtimeMode: "auto" })), + getProjectThreadRecords: ({ threadId: id }) => { + const projection = McpToolAccessTestkit.idleThreadProjection( + McpToolAccessTestkit.liveThreadShell(id, { runtimeMode: "auto" }), + ); + return Effect.succeed({ + ...projection, + thread: { ...projection.thread, pinnedAt: targetPinnedAt }, + }); + }, + listActiveShellIndex: () => + Effect.succeed([ + indexEntry("pinned-late", true, "t"), + indexEntry("pinned-top", true, "g"), + indexEntry("pinned-keyless", true, null), + indexEntry("unpinned-stale-key", false, "b"), + ]), + dispatch: (command) => { + dispatched.push(command); + return Effect.succeed({ sequence: dispatched.length, storedEvents: [] }); + }, + }), + ), + ), + ), + ); +}); + it.effect("search names the calling thread, so an agent can tell its own match apart", () => Effect.gen(function* () { const server = yield* McpServer.McpServer; diff --git a/apps/server/src/mcp/toolkits/device/handlers.ts b/apps/server/src/mcp/toolkits/device/handlers.ts index 382beed7284ac..099a9bae9e2d3 100644 --- a/apps/server/src/mcp/toolkits/device/handlers.ts +++ b/apps/server/src/mcp/toolkits/device/handlers.ts @@ -89,7 +89,7 @@ const requireDeviceAccess = McpInvocationContext.requireThreadMcpCapability("dev () => new DeviceToolUnavailableError({ reason: - "Agent device access is turned off for this environment. Ask the user to turn on Agent device access in Settings > Integrations > Devices; it applies when the agent session next starts, such as in a new thread.", + "Agent device access is turned off for this environment. Ask the user to turn on the Device hub and Agent device access in Settings > Integrations > Devices; it applies when the agent session next starts, such as in a new thread.", }), ), ); diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index cce07e5e9291d..dedea139364a1 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -176,7 +176,10 @@ const clientLaunchHarness = (input: { ), }), Layer.mock(PeerForwarding.PeerForwarding)({}), - Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/projects" }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer)), ).pipe( Layer.provideMerge(GitVcsDriver.layer), @@ -1014,6 +1017,22 @@ it.effect("an agent's clone is not cut off while git is still transferring", () }).pipe(Effect.provide(NodeServices.layer)), ); +const deletedProject = (id: ProjectId) => ({ + id, + title: "client-target", + workspaceRoot: "/projects/client-target", + repositoryIdentity: null, + faviconPath: null, + defaultModelSelection: null, + defaultThreadEnvMode: null, + autoPull: false, + projectIcon: null, + scripts: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + deletedAt: "2026-01-01T00:00:00.000Z", +}); + it.effect("deleting a project through MCP also discards its clone record", () => Effect.gen(function* () { const discarded: Array = []; @@ -1022,22 +1041,7 @@ it.effect("deleting a project through MCP also discards its clone record", () => harness.dependencies, Layer.mergeAll( Layer.mock(Project.ProjectService)({ - delete: (input) => - Effect.succeed({ - id: input.projectId, - title: "client-target", - workspaceRoot: "/projects/client-target", - repositoryIdentity: null, - faviconPath: null, - defaultModelSelection: null, - defaultThreadEnvMode: null, - autoPull: false, - projectIcon: null, - scripts: [], - createdAt: "2026-01-01T00:00:00.000Z", - updatedAt: "2026-01-01T00:00:00.000Z", - deletedAt: "2026-01-01T00:00:00.000Z", - }), + delete: (input) => Effect.succeed(deletedProject(input.projectId)), }), Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({ discard: (projectId) => Effect.sync(() => void discarded.push(projectId)), @@ -1058,6 +1062,45 @@ it.effect("deleting a project through MCP also discards its clone record", () => }), ); +it.effect("an agent cannot delete the built-in scratch project, even with force", () => + Effect.gen(function* () { + const deleted: Array = []; + const harness = clientLaunchHarness({ runtimeModeCeiling: "full-access", launched: [] }); + const dependencies = Layer.merge( + harness.dependencies, + Layer.mergeAll( + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: (projectId) => Effect.succeed(projectId === harness.projectId), + }), + Layer.mock(Project.ProjectService)({ + delete: (input) => + Effect.sync(() => { + deleted.push(input.projectId); + return deletedProject(input.projectId); + }), + }), + Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({ discard: () => Effect.void }), + ), + ); + const toolkit = yield* ProjectToolkit.pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)), + ), + ); + + const refused = yield* toolkit + .handle("t3_project_delete", { projectId: harness.projectId, force: true }) + .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies)); + + expect(deleted).toEqual([]); + expect(refused.at(-1)?.result).toMatchObject({ + code: "invalid_request", + message: expect.stringMatching(/scratch|no project/i), + }); + }), +); + it.effect("an update the project refuses tells the agent why", () => Effect.gen(function* () { const harness = clientLaunchHarness({ runtimeModeCeiling: "full-access", launched: [] }); diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index c0fbea9b27898..6c9f5e0b6b8b3 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -463,6 +463,13 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { ), t3_project_delete: McpToolAccess.writesEnvironment((input) => Effect.gen(function* () { + const folders = yield* ManagedProjectFolders.ManagedProjectFolders; + if (yield* folders.isScratchProject(input.projectId)) + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: + '"No project" is the built-in scratch project and cannot be deleted through MCP. The user can remove it in Settings.', + }); const projects = yield* Project.ProjectService; const clones = yield* ProjectCloneTracker.ProjectCloneTracker; return yield* mutateProjectWithClone(projects, clones, { diff --git a/apps/server/src/mcp/toolkits/project/tools.ts b/apps/server/src/mcp/toolkits/project/tools.ts index c1698e50751ae..fa7997c8ca3a2 100644 --- a/apps/server/src/mcp/toolkits/project/tools.ts +++ b/apps/server/src/mcp/toolkits/project/tools.ts @@ -107,7 +107,11 @@ const ProjectDeleteTool = Tool.make("t3_project_delete", { projectId: ProjectId, force: Schema.optionalKey(Schema.Boolean), }), - dependencies: [...shared.dependencies, ProjectCloneTracker.ProjectCloneTracker], + dependencies: [ + ...shared.dependencies, + ProjectCloneTracker.ProjectCloneTracker, + ManagedProjectFolders.ManagedProjectFolders, + ], }).annotate(Tool.Destructive, true); const ProjectCloneTool = Tool.make("t3_project_clone", { ...shared, diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index db13197ea6ffb..3c454cbe6e48c 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -726,6 +726,36 @@ describe("pull request guide tools", () => { }), ); + it.effect( + "reads a guide on a host readable without a checkout through the caller's project", + () => + Effect.gen(function* () { + const api = makeProject({ + canonicalKey: "bitbucket.org/acme/api", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "git@bitbucket.org:acme/api.git", + }, + provider: SourceControlProviderKind.make("bitbucket"), + displayName: "acme/api", + owner: "acme", + name: "api", + }); + const harness = yield* makeHarness({ project: api }); + const result = yield* harness.call("read_pull_request_guide", { + url: "https://bitbucket.org/acme/web/pull-requests/123", + }); + expect(result).toMatchObject({ + host: "bitbucket.org", + repository: "acme/web", + number: 123, + guide: null, + currentHeadSha: "head-1", + }); + }), + ); + it.effect("finds an Azure DevOps checkout for a pull request named by its full path", () => Effect.gen(function* () { const azure = { diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 954e33e85c3e2..b738b2d8b4359 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -244,10 +244,17 @@ const make = Effect.gen(function* () { input, target, project: projectForPullRequest(known, target, callerProject), + callerProject, failure: null, })), Effect.catch((error) => - Effect.succeed({ input, target: null, project: undefined, failure: error.message }), + Effect.succeed({ + input, + target: null, + project: undefined, + callerProject, + failure: error.message, + }), ), ), ); @@ -492,18 +499,25 @@ const make = Effect.gen(function* () { if (entry !== undefined && entry.target === null) { return yield* new PullRequestGuideFailedError({ detail: entry.failure ?? "" }); } - if (entry === undefined || entry.target === null || entry.project === undefined) { + // Hosts readable without a checkout (GitHub, Bitbucket, Forgejo) are read through the + // caller's project; PullRequestService decides whether the host allows that. + const project = entry?.project ?? entry?.callerProject; + if (entry === undefined || entry.target === null || project === undefined) { return yield* new PullRequestProjectNotFoundError({ repository: entry?.target.repository ?? input.repository ?? "", }); } - const result = yield* reviewGuides.get(guideReference(entry.project, entry.target)).pipe( - Effect.mapError( - (error) => - new PullRequestGuideFailedError({ - detail: guideFailureDetail(error), - cause: error, - }), + const target = entry.target; + const result = yield* reviewGuides.get(guideReference(project, target)).pipe( + Effect.mapError((error) => + entry.project === undefined && + error._tag === "PullRequestUnavailableError" && + error.reason === "provider-unsupported" + ? new PullRequestProjectNotFoundError({ repository: target.repository }) + : new PullRequestGuideFailedError({ + detail: guideFailureDetail(error), + cause: error, + }), ), ); return { diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 21a435d922c8a..6374018260702 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -8,7 +8,7 @@ import { type OrchestrationV2Command, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; -import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts"; +import { topOfPinnedRunOrderKey } from "@t3tools/shared/pinOrderKey"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; @@ -19,6 +19,8 @@ import { readThread, unavailable, } from "../../threadAccess.ts"; +import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts"; +import type * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts"; import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts"; import * as ScheduledTasks from "../../../scheduledTasks/ScheduledTaskService.ts"; import { queuedRunsInDeliveryOrder } from "../../../orchestration-v2/QueuedRunOrder.ts"; @@ -50,6 +52,20 @@ const dispatch = Effect.fn("mcp.dispatchThreadCommand")(function* ( return { sequence: result.sequence }; }); +/** + * Places an agent pin at the top of the Pinned section, as a client pin is placed. + * Without a key the sidebar sorts the pin below every keyed pin. Ordering is + * best effort: if the index cannot be read, the pin still lands, keyless. + */ +const topOfPinnedRunKey = Effect.fn("mcp.topOfPinnedRunKey")(function* ( + threads: Pick, +) { + const index = yield* threads.listActiveShellIndex().pipe(Effect.orElseSucceed(() => null)); + if (index === null) return undefined; + const pinnedKeys = index.flatMap((entry) => (entry.pinnedAt == null ? [] : [entry.pinOrderKey])); + return topOfPinnedRunOrderKey(pinnedKeys) ?? undefined; +}); + const readQuestion = Effect.fn("mcp.readQuestion")(function* (input: { threadId?: ThreadId | undefined; requestId: RuntimeRequestId; @@ -363,6 +379,14 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { case "mark_unread": command = { ...common, type: "thread.mark-unread" }; break; + case "pin": { + // Always send a key, as the client does: the reducer ignores it for a + // thread that is already pinned, and a projection read before this + // command can be stale if an unpin commits in between. + const orderKey = yield* topOfPinnedRunKey(threads); + command = { ...common, type: "thread.pin", ...(orderKey ? { orderKey } : {}) }; + break; + } default: command = { ...common, type: `thread.${input.action}` }; } diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index eec7da369445d..1fde851cb07c0 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -1961,7 +1961,15 @@ describe("AcpAdapterV2", () => { scenario: "OMP unrelated form uses generic mapping", settings: OMP_SETTINGS, schema: { type: "object", properties: { name: { type: "string" } } }, - questions: [{ id: "name", header: "Question 1", question: "Your answer?", options: [] }], + questions: [ + { + id: "name", + header: "Question 1", + question: "Your answer?", + options: [], + required: false, + }, + ], answers: { name: "Ada" }, result: { action: "accept", content: { name: "Ada" } }, }, @@ -2004,7 +2012,15 @@ describe("AcpAdapterV2", () => { { scenario: "falls back for an unrelated form", schema: { type: "object", properties: { name: { type: "string" } } }, - questions: [{ id: "name", header: "Question 1", question: "Your answer?", options: [] }], + questions: [ + { + id: "name", + header: "Question 1", + question: "Your answer?", + options: [], + required: false, + }, + ], answers: { name: "Ada" }, result: { action: "accept", content: { name: "Ada" } }, }, @@ -5913,6 +5929,22 @@ describe("AcpAdapterV2", () => { ], optionId: "allow-once", }, + { + label: "answers Always allow with the agent's option id unchanged when it has spaces", + options: [ + { optionId: " opaque-choice ", name: "Allow once", kind: "allow_once" }, + { optionId: "reject-once", name: "Reject", kind: "reject_once" }, + ], + optionId: " opaque-choice ", + }, + { + label: "answers Always allow with a whitespace-only option id instead of cancelling", + options: [ + { optionId: " ", name: "Allow once", kind: "allow_once" }, + { optionId: "reject-once", name: "Reject", kind: "reject_once" }, + ], + optionId: " ", + }, ] as const)("$label", ({ options, optionId }) => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index fd009041fd93f..97fb6e636054f 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -234,6 +234,7 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* ( }).pipe(Effect.andThen(Queue.offer(offered, undefined)), Effect.asVoid), }; const instanceId = ProviderInstanceId.make("claude-lifecycle"); + const outgoing = yield* Queue.unbounded(); let onTermination: NonNullable< AcpSessionRuntime.AcpSessionRuntimeOptions["onTermination"] > = () => Effect.die("Runtime has not started"); @@ -255,7 +256,17 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* ( ...(continuationEnabled ? { continuationRequests } : {}), makeRuntime: (runtimeInput: Parameters[0]) => { onTermination = runtimeInput.onTermination; - return replayRuntime(runtimeInput); + return replayRuntime({ + ...runtimeInput, + protocolLogging: { + logIncoming: false, + logOutgoing: true, + logger: (event) => + event.stage === "raw" && typeof event.payload === "string" + ? Queue.offer(outgoing, JSON.parse(event.payload)).pipe(Effect.asVoid) + : Effect.void, + }, + }); }, }; const adapter = yield* makeAcpRegistryAdapterV2(adapterOptions).pipe( @@ -365,6 +376,7 @@ const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* ( terminal, offers, offered, + outgoing, terminate: () => onTermination( new EffectAcpErrors.AcpTransportError({ @@ -2274,6 +2286,103 @@ describe("AcpRegistryAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("approves Devin's plan without choosing a bypass option it lists first", () => + Effect.gen(function* () { + const session = yield* openClaudeReplaySession( + [ + ...claudeFrames.open.map((entry) => + entry.frame.method === "initialize" && entry.type === "emit_inbound" + ? { + ...entry, + frame: { + ...entry.frame, + result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] }, + }, + } + : entry, + ), + { + type: "expect_outbound", + frame: { kind: "request", method: "session/prompt", params: "" }, + }, + claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call", + toolCallId: "exit-plan", + title: "Exit plan mode", + kind: "switch_mode", + status: "pending", + }), + { + type: "emit_inbound", + frame: { + kind: "request", + method: "session/request_permission", + params: { + sessionId: CLAUDE_ROOT_SESSION, + toolCall: { toolCallId: "exit-plan" }, + // Devin gives both plan approvals allow_once and does not promise their order. + options: [ + { + optionId: "plan_bypass", + name: "Yes, implement plan and bypass permissions", + kind: "allow_once", + }, + { + optionId: "plan_accept_edits", + name: "Yes, implement plan and accept edits", + kind: "allow_once", + }, + { optionId: "reject_once", name: "No, plan needs changes", kind: "reject_once" }, + ], + }, + }, + }, + { + type: "expect_outbound", + frame: { + kind: "response", + method: "session/request_permission", + result: { outcome: { outcome: "selected", optionId: "" } }, + }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/prompt", + result: { stopReason: "end_turn" }, + }, + }, + claudeFrames.closeRequest, + claudeFrames.closed, + ], + undefined, + false, + "devin", + ); + yield* session.runtime.startTurn(session.turnInput(1)).pipe(Effect.forkScoped); + const seen = yield* session.until( + (event) => + event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", + ); + const request = seen.at(-1)!; + if (request.type !== "runtime_request.updated") throw new Error("Missing request"); + yield* session.runtime.respondToRuntimeRequest({ + requestId: request.runtimeRequest.id, + decision: "accept", + }); + let answer: unknown; + while (answer === undefined) { + const frame = (yield* Queue.take(session.outgoing)) as { + readonly result?: { readonly outcome?: { readonly optionId?: string } }; + }; + answer = frame.result?.outcome; + } + assert.deepEqual(answer, { outcome: "selected", optionId: "plan_accept_edits" }); + assert.equal((yield* session.terminal).status, "completed"); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.effect("keeps stopped child tools interrupted when a late output chunk arrives", () => Effect.gen(function* () { const { update } = claudeFrames; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 137212a695787..e89fb34ddf89e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -803,6 +803,39 @@ describe("ClaudeAdapterV2 MCP query overrides", () => { }); }); +describe("ClaudeAdapterV2 SDK warnings", () => { + it("drops only the SDK's canUseTool shadowing warning while opening a query", async () => { + using emitWarning = vi.spyOn(process, "emitWarning").mockImplementation(() => {}); + for (const options of [ + { permissionMode: "default", allowedTools: [ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD] }, + { permissionMode: "bypassPermissions", allowDangerouslySkipPermissions: true }, + ] satisfies ReadonlyArray) { + const query = ClaudeAdapterV2.withoutClaudeCanUseToolShadowedWarning(() => + ClaudeSdk.query({ + prompt: "", + options: { + ...options, + canUseTool: async (_toolName, input) => ({ behavior: "allow", updatedInput: input }), + pathToClaudeCodeExecutable: "/nonexistent/claude", + }, + }), + ); + await query.next().catch(() => undefined); + } + ClaudeAdapterV2.withoutClaudeCanUseToolShadowedWarning(() => + process.emitWarning("unrelated", { code: "UNRELATED_WARNING" }), + ); + + assert.deepEqual( + emitWarning.mock.calls.map(([, options]) => + typeof options === "object" ? options.code : options, + ), + ["UNRELATED_WARNING"], + ); + assert.strictEqual(process.emitWarning, emitWarning); + }); +}); + describe("ClaudeAdapterV2 native protocol logging", () => { it("injects thread-scoped MCP configuration without logging the credential", () => { const threadId = ThreadId.make("thread-claude-mcp"); @@ -1016,6 +1049,22 @@ describe("ClaudeAdapterV2 session permissions", () => { assert.equal(result.decisionClassification, "user_reject"); assert.equal(result.message, "User declined tool execution."); assert.equal(result.interrupt, undefined); + + // regression: #27854 bare feedback read to Claude as a tool error, not the user's words + const withFeedback = ClaudeAdapterV2.permissionResultFromDecision({ + toolName: "Bash", + decision: "decline", + toolInput: { command: "make" }, + toolUseID: "denied-build", + feedback: " Use the dry-run flag first. ", + }); + assert.equal(withFeedback.behavior, "deny"); + if (withFeedback.behavior !== "deny") return; + assert.equal(withFeedback.decisionClassification, "user_reject"); + assert.equal( + withFeedback.message, + "The user declined this tool call and said:\nUse the dry-run flag first.", + ); }); it("forces suggested permission updates to session scope", () => { @@ -1302,6 +1351,36 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => { const appendSystemPrompt = (options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined) => (options?.systemPrompt as { readonly append?: string } | undefined)?.append; + // regression: #35594 append text starting with "--" was read as a missing value + it.effect("sends append launch text that starts with two hyphens to Claude", () => + Effect.scoped( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" }); + const plain = yield* startTurnWithLaunchArgs("", cwd); + const { exit, opened } = yield* startTurnWithLaunchArgs( + '--append-system-prompt "-- Always answer in English"', + cwd, + ); + assert.isTrue(Exit.isSuccess(exit)); + assert.lengthOf(opened, 1); + assert.equal( + appendSystemPrompt(opened[0]), + `${appendSystemPrompt(plain.opened[0])}\n\n-- Always answer in English`, + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + it.effect("sends append launch arguments to Claude after the T3 instructions", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -12493,6 +12572,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { { taskId: longRunning.taskId, kind: "monitor", + awaited: true, description: "Monitor 0", nativeItemId: "toolu_monitor_0", command: "sleep 8 && echo MONITOR_DONE", @@ -12500,6 +12580,29 @@ describe("ClaudeAdapterV2 background wake turns", () => { sourceThreadId: harness.threadId, }, ]); + assert.isDefined(harness.runtime.awaitBackgroundTasks); + const released = yield* harness.runtime.awaitBackgroundTasks!({ + providerThread: harness.providerThread, + taskIds: [longRunning.taskId], + awaited: false, + }); + assert.deepEqual(released.matched, [longRunning.taskId]); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [ + { task_id: longRunning.taskId, task_type: "local_bash", description: "Monitor 0" }, + ], + uuid: nextUuid(), + session_id: WAKE_NATIVE_SESSION, + }), + ); + assert.equal( + providerThreadRosterEvents(harness.events).at(-1)?.providerThread + .pendingBackgroundTasks?.[0]?.awaited, + undefined, + ); }).pipe( Effect.provide( Layer.mergeAll( @@ -12695,6 +12798,11 @@ describe("ClaudeAdapterV2 background wake turns", () => { assert.equal(harness.terminalEvents()[settled + 1]?.status, "completed"); assert.include(assistantTexts(), "Scheduled answer."); assert.lengthOf(harness.continuationRequests, 2); + assert.deepInclude( + providerThreadRosterEvents(harness.events).at(-1)?.providerThread + .pendingBackgroundTasks?.[0], + { taskId, kind: "monitor", awaited: true }, + ); }).pipe( Effect.provide( Layer.mergeAll( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 60dd2265c91ee..1e028a1ee6a73 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -355,6 +355,9 @@ function mergeClaudeStreamUsage( }; } export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_PROVIDER); +// The Claude CLI takes the next token as this flag's value even when it starts with `--`. +const claudeLaunchArgParseOptions = { valueFlags: ["append-system-prompt"] }; + const CLAUDE_SCRIPT_EXTENSIONS = [".js", ".mjs", ".tsx", ".ts", ".jsx"]; // The SDK has no control-request deadline; the CLI waits up to 30 s per MCP server. const CLAUDE_MCP_REGISTRATION_TIMEOUT = "90 seconds"; @@ -1352,6 +1355,26 @@ const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(functio ); }); +const CLAUDE_CAN_USE_TOOL_SHADOWED_WARNING = "CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"; + +// query() warns when canUseTool meets bypassPermissions or bare allowedTools. T3 installs +// canUseTool in every mode on purpose (AskUserQuestion, ask rules), so it is per-session noise. +export function withoutClaudeCanUseToolShadowedWarning
(run: () => A): A { + const emitWarning = process.emitWarning; + process.emitWarning = function (this: NodeJS.Process, ...args: Parameters) { + const [, options] = args; + if (typeof options === "object" && options.code === CLAUDE_CAN_USE_TOOL_SHADOWED_WARNING) { + return; + } + return Reflect.apply(emitWarning, this, args); + } as typeof emitWarning; + try { + return run(); + } finally { + process.emitWarning = emitWarning; + } +} + export const layerQueryRunner: Layer.Layer< ClaudeAgentSdkQueryRunner, never, @@ -1560,10 +1583,12 @@ export const layerQueryRunner: Layer.Layer< const queryRuntime = yield* Effect.uninterruptibleMask((restore) => Effect.try({ try: () => - query({ - prompt, - options: { ...options, spawnClaudeCodeProcess }, - }), + withoutClaudeCanUseToolShadowedWarning(() => + query({ + prompt, + options: { ...options, spawnClaudeCodeProcess }, + }), + ), catch: (cause) => queryRunnerError(cause, "query"), }).pipe( Effect.tap((queryRuntime) => @@ -2150,7 +2175,9 @@ export function makeClaudeQueryOptions(input: { // The SDK replaces this flag with options.settings, so it arrives read as sdkSettings. settings: _launchArgSettings, ...extraArgs - } = input.settings === undefined ? {} : parseCliArgs(input.settings.launchArgs).flags; + } = input.settings === undefined + ? {} + : parseCliArgs(input.settings.launchArgs, claudeLaunchArgParseOptions).flags; // Claude Code overwrites its CLI append text with the SDK's initialize // appendSystemPrompt, so launch-argument text has to travel in that value. // The CLI puts file text before inline text and trims one trailing newline. @@ -2320,7 +2347,7 @@ const readClaudeAppendSystemPromptFile = Effect.fnUntraced(function* (input: { readonly path: Path.Path; }) { if (input.settings === undefined) return undefined; - const flags = parseCliArgs(input.settings.launchArgs).flags; + const flags = parseCliArgs(input.settings.launchArgs, claudeLaunchArgParseOptions).flags; // parseCliArgs gives null for a flag with no following value. An explicit // `--append-system-prompt ""` is a value the CLI accepts, so it stays. if (flags["append-system-prompt"] === null) { @@ -2357,7 +2384,7 @@ const decodeClaudeLaunchArgSettings = Schema.decodeUnknownEffect( * relative to the thread's cwd (the project or its worktree). * makeClaudeQueryOptions merges the result beneath T3's own settings. */ -const readClaudeLaunchArgSettings = Effect.fn("ClaudeAdapterV2.readLaunchArgSettings")( +export const readClaudeLaunchArgSettings = Effect.fn("ClaudeAdapterV2.readLaunchArgSettings")( function* (input: { readonly settings: ClaudeSettings | undefined; readonly cwd: string | null; @@ -2365,7 +2392,8 @@ const readClaudeLaunchArgSettings = Effect.fn("ClaudeAdapterV2.readLaunchArgSett readonly path: Path.Path; }) { if (input.settings === undefined) return undefined; - const value = parseCliArgs(input.settings.launchArgs).flags.settings; + const value = parseCliArgs(input.settings.launchArgs, claudeLaunchArgParseOptions).flags + .settings; if (value === undefined) return undefined; const trimmed = value?.trim() ?? ""; if (trimmed.length === 0) return yield* new ClaudeSettingsLaunchArgError({}); @@ -4279,13 +4307,14 @@ export function permissionResultFromDecision(input: { }; } + const feedback = input.feedback?.trim(); return { behavior: "deny", - message: - input.feedback?.trim() || - (input.decision === "cancel" + message: feedback + ? `The user declined this tool call and said:\n${feedback}` + : input.decision === "cancel" ? "User cancelled tool execution." - : "User declined tool execution."), + : "User declined tool execution.", toolUseID: input.toolUseID, decisionClassification: "user_reject", ...(input.decision === "cancel" ? { interrupt: true } : {}), @@ -6647,11 +6676,23 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId: string, task: OrchestrationV2PendingBackgroundTask, ) { - yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => { - const roster = new Map(rosterForNativeThread(current, nativeThreadId)); - roster.set(task.taskId, task); - return new Map(current).set(nativeThreadId, roster); - }); + const startedMonitor = yield* Ref.modify( + pendingBackgroundTasksByNativeThread, + (current) => { + const roster = new Map(rosterForNativeThread(current, nativeThreadId)); + const startedMonitor = + task.kind === "monitor" && roster.get(task.taskId)?.kind !== "monitor"; + roster.set(task.taskId, task); + return [startedMonitor, new Map(current).set(nativeThreadId, roster)] as const; + }, + ); + if (startedMonitor) { + yield* addTaskIdsToNativeThreadSet( + awaitedBackgroundTasksByNativeThread, + nativeThreadId, + [task.taskId], + ); + } yield* rememberOpaqueTasks([task]); yield* markWakeEligibleOpaqueBackgroundTasks(nativeThreadId, [task.taskId]); }); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 3bdf26e86df00..8abcffba681cd 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -2028,13 +2028,13 @@ describe("CodexAdapterV2 post-settle continuation", () => { url: "http://127.0.0.1:43123/mcp", tool_timeout_sec: 3_900, http_headers: { Authorization: "Bearer secret-codex-token" }, - disabled_tools: ["t3_thread_wait"], + disabled_tools: ["t3_thread_wait", "delegate_task"], }, "mcp_servers.t3-code-direct": { url: "http://127.0.0.1:43123/mcp", tool_timeout_sec: 3_900, http_headers: { Authorization: "Bearer secret-codex-token" }, - enabled_tools: ["t3_thread_wait"], + enabled_tools: ["t3_thread_wait", "delegate_task"], omit_tools_from: ["code_mode", "deferred"], }, ...sharedConfig, @@ -8011,6 +8011,124 @@ describe("CodexAdapterV2 post-settle continuation", () => { ], }); + it.effect("resumes an unloaded native thread and retries an MCP resource read", () => + Effect.scoped( + Effect.gen(function* () { + const scenario = "mcp-resource-thread-recovery"; + const nativeThreadId = `native-${scenario}`; + const preamble = codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "unused-turn", + prompt: "unused-prompt", + }).slice(0, 5); + + const resourceResult = { + contents: [ + { + uri: MCP_APP_RESOURCE, + mimeType: "text/html;profile=mcp-app", + text: MCP_APP_HTML, + _meta: { ui: { csp: { connectDomains: ["https://api.weather.test"] } } }, + }, + ], + }; + + const transcript = makeCodexReplayTranscript({ + scenario, + entries: [ + ...preamble, + { + type: "expect_outbound", + label: "initial MCP resource read", + frame: { + id: 3, + method: "mcpServer/resource/read", + params: { + threadId: nativeThreadId, + server: "weather", + uri: MCP_APP_RESOURCE, + }, + }, + }, + { + type: "emit_inbound", + label: "native thread is unloaded", + frame: { + id: 3, + error: { + code: -32600, + message: `thread not found: ${nativeThreadId}`, + }, + }, + }, + { + type: "expect_outbound", + label: "resume unloaded native thread", + frame: { + id: 4, + method: "thread/resume", + params: { + threadId: nativeThreadId, + excludeTurns: true, + config: CodexAdapterV2.CODEX_THREAD_CONFIG, + }, + }, + }, + { + type: "emit_inbound", + label: "native thread resumed", + frame: { + id: 4, + result: { + thread: { id: nativeThreadId, updatedAt: 1782622450 }, + }, + }, + }, + { + type: "expect_outbound", + label: "retry MCP resource read", + frame: { + id: 5, + method: "mcpServer/resource/read", + params: { + threadId: nativeThreadId, + server: "weather", + uri: MCP_APP_RESOURCE, + }, + }, + }, + { + type: "emit_inbound", + label: "MCP resource read succeeds", + frame: { id: 5, result: resourceResult }, + }, + ], + }); + + const harness = yield* makeCodexReplayHarness(transcript); + const mcpApps = harness.runtime.mcpApps; + assert.ok(mcpApps, "Codex runtime should expose MCP apps"); + + const result = yield* mcpApps.readResource({ + providerThread: harness.providerThread, + server: "weather", + uri: MCP_APP_RESOURCE, + }); + + assert.deepEqual(result, resourceResult); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + it.effect("captures an MCP app's resource and holds the turn open until it lands", () => Effect.gen(function* () { const appCaptured = yield* Deferred.make(); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 462d7d10cd168..d57533806c105 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -379,6 +379,14 @@ function isCodexActiveWriterError(error: unknown): boolean { ); } +function isCodexThreadNotFoundError(error: unknown): boolean { + return ( + isCodexAppServerRequestError(error) && + error.code === -32600 && + error.errorMessage.startsWith("thread not found:") + ); +} + function codexTimestamp(seconds: number | null | undefined): DateTime.Utc { return seconds === null || seconds === undefined ? DateTime.nowUnsafe() @@ -1484,7 +1492,7 @@ const CODEX_T3_MCP_TOOL_TIMEOUT_SEC = 65 * 60; // Holds T3 tools Codex must call directly, never from Code Mode. Calls arrive as // `t3-code-direct.`; t3McpToolPresentation.ts must keep resolving that form. const CODEX_T3_DIRECT_MCP_SERVER = "t3-code-direct"; -const CODEX_DIRECT_ONLY_T3_TOOL = "t3_thread_wait"; +const CODEX_DIRECT_ONLY_T3_TOOLS = ["t3_thread_wait", "delegate_task"]; function codexThreadRuntimeParams(input: { readonly threadId: ThreadId | null; @@ -1518,12 +1526,12 @@ function codexThreadRuntimeParams(input: { ? {} : { // Override only T3's servers so launch-argument MCP servers survive. - "mcp_servers.t3-code": { ...t3Server, disabled_tools: [CODEX_DIRECT_ONLY_T3_TOOL] }, - // Code Mode runs a blocking wait as a nested call, and the model keeps working - // around it. A second, direct-only registration makes it a plain tool call. + "mcp_servers.t3-code": { ...t3Server, disabled_tools: CODEX_DIRECT_ONLY_T3_TOOLS }, + // Code Mode runs a blocking wait or delegate wait as a nested call, and the model + // keeps polling it. A second, direct-only registration makes it a plain tool call. [`mcp_servers.${CODEX_T3_DIRECT_MCP_SERVER}`]: { ...t3Server, - enabled_tools: [CODEX_DIRECT_ONLY_T3_TOOL], + enabled_tools: CODEX_DIRECT_ONLY_T3_TOOLS, omit_tools_from: ["code_mode", "deferred"], }, ...Object.fromEntries( @@ -2779,7 +2787,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( CodexAppServerInputStreamEndedError: () => Effect.succeed({ terminated: true }), // Unloading kills terminals, so "thread not found" means nothing remains to stop. CodexAppServerRequestError: (error) => - error.code === -32600 && error.errorMessage.startsWith("thread not found:") + isCodexThreadNotFoundError(error) ? Effect.succeed({ terminated: true }) : Effect.fail(error), }), @@ -7726,17 +7734,45 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( detail, payload: cause, }); + // Codex unloads idle threads; MCP requests against one fail until it is resumed. + const withLoadedThread = ( + providerThread: OrchestrationV2ProviderThread, + threadId: string, + request: Effect.Effect, + ) => + request.pipe( + Effect.catchIf(isCodexThreadNotFoundError, () => + readMcpSession(providerThread.appThreadId).pipe( + Effect.flatMap((mcpSession) => + resumeNativeThread(threadId, { + excludeTurns: true, + ...codexThreadRuntimeParams({ + threadId: providerThread.appThreadId, + mcpSession, + modelSelection: input.modelSelection, + runtimePolicy: input.runtimePolicy, + }), + }), + ), + Effect.andThen(request), + ), + ), + ); const mcpApps: ProviderAdapter.ProviderAdapterV2McpApps = { listTools: Effect.fn("CodexAdapterV2.listTools")( function* (toolsInput) { const threadId = yield* getNativeThreadId(toolsInput.providerThread); - const response = yield* ensureInitialized.pipe( - Effect.andThen( - client.request("mcpServerStatus/list", { - threadId, - serverName: toolsInput.server, - detail: "toolsAndAuthOnly", - }), + const response = yield* withLoadedThread( + toolsInput.providerThread, + threadId, + ensureInitialized.pipe( + Effect.andThen( + client.request("mcpServerStatus/list", { + threadId, + serverName: toolsInput.server, + detail: "toolsAndAuthOnly", + }), + ), ), ); const server = response.data.find((entry) => entry.name === toolsInput.server); @@ -7747,14 +7783,18 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( callTool: Effect.fn("CodexAdapterV2.callTool")( function* (callInput) { const threadId = yield* getNativeThreadId(callInput.providerThread); - const response = yield* ensureInitialized.pipe( - Effect.andThen( - client.request("mcpServer/tool/call", { - threadId, - server: callInput.server, - tool: callInput.tool, - arguments: callInput.arguments as Schema.Json, - }), + const response = yield* withLoadedThread( + callInput.providerThread, + threadId, + ensureInitialized.pipe( + Effect.andThen( + client.request("mcpServer/tool/call", { + threadId, + server: callInput.server, + tool: callInput.tool, + arguments: callInput.arguments as Schema.Json, + }), + ), ), ); return { @@ -7771,13 +7811,17 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( readResource: Effect.fn("CodexAdapterV2.readResource")( function* (readInput) { const threadId = yield* getNativeThreadId(readInput.providerThread); - const response = yield* ensureInitialized.pipe( - Effect.andThen( - client.request("mcpServer/resource/read", { - threadId, - server: readInput.server, - uri: readInput.uri, - }), + const response = yield* withLoadedThread( + readInput.providerThread, + threadId, + ensureInitialized.pipe( + Effect.andThen( + client.request("mcpServer/resource/read", { + threadId, + server: readInput.server, + uri: readInput.uri, + }), + ), ), ); return { contents: response.contents }; diff --git a/apps/server/src/orchestration-v2/Adapters/FxAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/FxAdapterV2.test.ts index 7a39e5468cfb6..6e21a3f4428e1 100644 --- a/apps/server/src/orchestration-v2/Adapters/FxAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/FxAdapterV2.test.ts @@ -277,7 +277,11 @@ describe("FxAdapterV2", () => { runtimeMode: "auto", frames: [ ...initialize, - outbound("session/new", { cwd: "", mcpServers: "" }), + outbound("session/new", { + cwd: "", + mcpServers: "", + _meta: { fx: { profileMcpServers: true } }, + }), answer("session/new", fxSession({ model: FX_DEFAULT_MODEL, modes })), ...setConfig( "mode", @@ -298,7 +302,12 @@ describe("FxAdapterV2", () => { loadSessionId: SESSION_ID, frames: [ ...initialize, - outbound("session/load"), + outbound("session/load", { + sessionId: SESSION_ID, + cwd: "", + mcpServers: "", + _meta: { fx: { profileMcpServers: true } }, + }), answer("session/load", fxSession({ model: NAMED_MODEL, modes: FX_0_0_13_MODES })), // Config id `model`, never fx's `provider`, and never T3's "default". ...setConfig( diff --git a/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts b/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts index 227fc531602fc..6a7b75528ef9d 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts @@ -280,6 +280,17 @@ describe("handoff budget", () => { ); } assert.equal(handoffBudget({ ...base, tokenCap: 2_000 }), 2_000); + // The work reserve never takes more than half of a small local window. + for (const [modelContextWindow, nativeContextEstimate, expected] of [ + [8_192, 0, 4_086], + [32_768, 0, 16_758], + [131_072, 50_000, 48_294], + ] as const) { + assert.equal( + handoffBudget({ ...base, tokenCap: 64_000, modelContextWindow, nativeContextEstimate }), + expected, + ); + } }); it("keeps measured occupancy across a model change", () => { @@ -408,13 +419,15 @@ describe("handoff budget", () => { assert.isAtMost(historyCost(selected.messages, selected.context), budget); } assert.equal(handoffBudget({ ...input, modelContextWindow: 2_000_000 }), 16_000); - assert.equal(handoffBudget({ ...input, modelContextWindow: 20_000 }), 0); + // 20k window: half is reserved for work, then 27 prompt bytes and 8,192 per image. + const smallWindowBudget = count === 1 ? 1_781 : 0; + assert.equal(handoffBudget({ ...input, modelContextWindow: 20_000 }), smallWindowBudget); assert.equal( handoffBudget({ ...input, providerThread: { ...providerThread, contextUsage: { usedTokens: 0, maxTokens: 20_000 } }, }), - 0, + smallWindowBudget, ); assert.equal( handoffBudget({ @@ -425,7 +438,7 @@ describe("handoff budget", () => { contextUsage: { usedTokens: 0, maxTokens: 1_000_000, autoCompactThreshold: 20_000 }, }, }), - 0, + smallWindowBudget, ); } }); diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index 896957fc69065..e28d7a4424056 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -25,6 +25,7 @@ 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 Result from "effect/Result"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; @@ -578,13 +579,31 @@ export const layer: Layer.Layer = La ) RETURNING * `; - const rows = yield* claimStatement.pipe(Effect.withTracerEnabled(false)); - const row = rows[0]; - if (row === undefined) return Option.none(); - cancellationSignals.set(row.effect_id, Deferred.makeUnsafe()); - return Option.some(yield* rowToEffect(row)); + while (true) { + const rows = yield* claimStatement.pipe(Effect.withTracerEnabled(false)); + const row = rows[0]; + if (row === undefined) return Option.none(); + const decoded = yield* Effect.result(rowToEffect(row)); + if (Result.isSuccess(decoded)) { + cancellationSignals.set(row.effect_id, Deferred.makeUnsafe()); + return Option.some(decoded.success); + } + // Left running, an unreadable row would block every later effect on its thread. + yield* Effect.logWarning("Failing an orchestration effect this build cannot decode", { + effectId: row.effect_id, + effectType: row.effect_type, + cause: decoded.failure, + }); + yield* service.fail({ + effectId: row.effect_id, + workerId, + error: `This server build cannot decode the ${row.effect_type} effect.`, + }); + } }, - Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause })), + Effect.mapError((cause) => + isEffectOutboxError(cause) ? cause : new EffectOutboxError({ operation: "claim", cause }), + ), ), nextClaimableAt: Effect.fnUntraced( function* ({ diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 3f00941c8daa3..14f443aa8cb62 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -2752,6 +2752,66 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { }).pipe(Effect.provide(layerIsolatedOutbox)), ); + it.effect("fails an effect this build cannot decode and claims the thread's next effect", () => + Effect.gen(function* () { + const outbox = yield* EffectOutbox.EffectOutboxV2; + const sql = yield* SqlClient.SqlClient; + const nowIso = DateTime.formatIso(yield* DateTime.now); + const workerId = "undecodable-worker"; + const commandId = CommandId.make("command:foundation-undecodable"); + const threadId = ThreadId.make("thread:foundation-undecodable"); + yield* sql` + INSERT INTO orchestration_v2_effect_outbox ( + effect_id, command_id, thread_id, effect_type, payload_json, status, + available_at, created_at, updated_at + ) + VALUES ( + 'effect:foundation-undecodable:a', ${commandId}, ${threadId}, 'future-effect.kind', + '{"type":"future-effect.kind"}', 'pending', ${nowIso}, ${nowIso}, ${nowIso} + ) + `; + yield* outbox.enqueue([ + { + id: "effect:foundation-undecodable:b", + commandId, + threadId, + request: { type: "provider-turn.start", runId: RunId.make("run:foundation-undecodable") }, + }, + ]); + + const claimed = yield* Effect.exit(outbox.claimNext({ workerId })); + + const rows = yield* sql<{ + readonly effect_id: string; + readonly status: string; + readonly lease_owner: string | null; + readonly last_error: string | null; + }>` + SELECT effect_id, status, lease_owner, last_error + FROM orchestration_v2_effect_outbox + ORDER BY effect_id + `; + assert.deepEqual(rows, [ + { + effect_id: "effect:foundation-undecodable:a", + status: "failed", + lease_owner: null, + last_error: "This server build cannot decode the future-effect.kind effect.", + }, + { + effect_id: "effect:foundation-undecodable:b", + status: "running", + lease_owner: workerId, + last_error: null, + }, + ]); + assert.equal( + Exit.isSuccess(claimed) ? Option.getOrUndefined(claimed.value)?.id : undefined, + "effect:foundation-undecodable:b", + ); + }).pipe(Effect.provide(layerIsolatedOutbox)), + ); + it.effect.each(["queued", "waiting"])( "keeps a %s continuation's crash budget past outbox retention", (status) => diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6ca1121b192d5..113a26b033e00 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -5719,9 +5719,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), ), ); - // Only side chat forks lock the source; validate the modes copied here, not an earlier read. + // Read under the source's lock; validate the modes copied here, not an earlier read. yield* refuseAboveDispatchModeLimit(command, command.sourceThreadId, sourceProjection.thread); - if (command.sideChat === true && sourceProjection.thread.deletedAt !== null) { + if (sourceProjection.thread.deletedAt !== null) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, @@ -15317,6 +15317,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: "Continue the limited thread before resuming its queue.", }); } + if (worktreeSetupPending(projection)) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "Retry worktree setup or choose a workspace before resuming the queue.", + }); + } const now = yield* DateTime.now; const queued = projection.runs.filter((run) => run.status === "queued"); for (const run of queued) { @@ -15842,28 +15849,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio commandThreadId(command), dispatchWithReceiptEffect(command), ); - // A parent's lock comes before its side chats' locks, so a delete cascade and a side chat - // fork or command never interleave. A fork from a side chat or onto an existing thread would - // invert that order; dispatch rejects both, so they skip the source lock. - if ( - command.type === "thread.fork" && - command.sideChat === true && - command.sourceThreadId !== command.targetThreadId - ) { + // A fork holds its source's lock, so a source deletion and its fork never interleave. A + // parent's lock comes before its side chats' locks. A side chat fork from a side chat or a + // fork onto an existing thread would invert that order; dispatch rejects both, so they skip it. + if (command.type === "thread.fork" && command.sourceThreadId !== command.targetThreadId) { const source = yield* findThread(command.sourceThreadId); const target = yield* findThread(command.targetThreadId); - return yield* source === null || source.lineage.sideChat === true || target !== null + const skipsSourceLock = + source === null || + target !== null || + (command.sideChat === true && source.lineage.sideChat === true); + return yield* skipsSourceLock ? dispatch : threadDispatch.withLock(command.sourceThreadId, dispatch); } if (command.type === "thread.delete") - return yield* threadDispatch.withLock( - command.threadId, - liveSideChatIds(command.threadId).pipe( - Effect.flatMap((sideChatIds) => - sideChatIds.reduce( - (locked, sideChatId) => threadDispatch.withLock(sideChatId, locked), - dispatchWithReceiptEffect(command, sideChatIds), + return yield* threadDispatch.withDeletionLock( + threadDispatch.withLock( + command.threadId, + liveSideChatIds(command.threadId).pipe( + Effect.flatMap((sideChatIds) => + sideChatIds.reduce( + (locked, sideChatId) => threadDispatch.withLock(sideChatId, locked), + dispatchWithReceiptEffect(command, sideChatIds), + ), ), ), ), diff --git a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts index 8563448071548..d8b7dae693632 100644 --- a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts @@ -13,6 +13,7 @@ import { ProviderSessionId, ProviderThreadId, ProviderTurnId, + RunAttemptId, RunId, RuntimeRequestId, ThreadId, @@ -1239,7 +1240,13 @@ it.effect("reads the run that owns a background roster, not a queued or resumed }).pipe(Effect.provide(layerTest)), ); -it.effect("wakes the run whose subagent lost its shell, past a wake cut before it started", () => +it.effect.each([ + ["a wake cut before it started", { status: "starting", startedAt: null }], + [ + "a prompt the provider never accepted", + { status: "running", activeAttemptId: RunAttemptId.make("attempt:unaccepted") }, + ], +] as const)("wakes the run whose subagent lost its shell, past %s", ([, later]) => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; @@ -1269,11 +1276,11 @@ it.effect("wakes the run whose subagent lost its shell, past a wake cut before i }, }); const settledRun = yield* createRun(threadId, "completed", { providerThreadId }); - yield* createRun(threadId, "starting", { + yield* createRun(threadId, later.status, { ordinal: 2, providerThreadId, - startedAt: null, completedAt: null, + ...later, }); yield* projections.apply({ id: EventId.make(`event:${threadId}:roster`), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index c8cab5e8cfc72..1209f44244e28 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -44,6 +44,7 @@ import * as Tracer from "effect/Tracer"; import * as SqlClient from "effect/sql/SqlClient"; import * as Statement from "effect/sql/Statement"; import { projectThreadAwarenessV2 } from "@t3tools/shared/agentAwareness"; +import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; @@ -148,7 +149,14 @@ const assertShellIndexCoversShells = Effect.fnUntraced(function* () { const trimmed = ( row: Pick< ProjectionStore.ActiveShellIndexEntry, - "id" | "projectId" | "lineage" | "settledOverride" | "settledAt" | "pinnedAt" | "snoozedUntil" + | "id" + | "projectId" + | "lineage" + | "settledOverride" + | "settledAt" + | "pinnedAt" + | "pinOrderKey" + | "snoozedUntil" >, ) => ({ id: row.id, @@ -157,6 +165,7 @@ const assertShellIndexCoversShells = Effect.fnUntraced(function* () { settledOverride: row.settledOverride, settledAt: iso(row.settledAt), pinnedAt: iso(row.pinnedAt), + pinOrderKey: row.pinOrderKey ?? null, snoozedUntil: iso(row.snoozedUntil), }); assert.deepEqual(index.map(trimmed), shells.map(trimmed)); @@ -2517,13 +2526,28 @@ const backgroundThreadUpdatesKeepTimestamp = Effect.gen(function* () { assert.deepEqual(reordered.updatedAt, createdAt); assert.equal(reordered.thread.activeOrderKey, "a"); + // MCP pins read the stored pin key from the active shell index. + yield* store.apply({ + id: EventId.make("event:background-updates:pinned"), + type: "thread.pinned", + threadId, + occurredAt: DateTime.add(createdAt, { minutes: 52 }), + payload: { + ...reordered.thread, + pinnedAt: DateTime.add(createdAt, { minutes: 52 }), + pinOrderKey: "m", + }, + }); + const pinned = yield* readActivity; + yield* assertShellIndexCoversShells(); + // An already-unpinned thread keeps its activity time even when replay's envelope advances. yield* store.apply({ id: EventId.make("event:background-updates:already-unpinned"), type: "thread.unpinned", threadId, occurredAt: DateTime.add(createdAt, { minutes: 55 }), - payload: { ...reordered.thread, pinnedAt: null, pinOrderKey: null }, + payload: { ...pinned.thread, pinnedAt: null, pinOrderKey: null }, }); yield* readActivity; }); @@ -4322,13 +4346,13 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { ordinalsFrom(915, 75), ); assert.strictEqual(decodeThreadHistoryCursor(page.nextCursor!).p, 914); - // A jump to an entry reads the full index and leaves it cached. With work, it scans - // payloads for inline output only in its page's runs, not in a run after its cursor. + // A jump to an entry reads the full index and leaves it cached. With work, it looks for + // inline output only in its page's runs, not in a run after its cursor. const scannedRuns: Array = []; yield* read("turn-item:bounded-sql-history:950").pipe( Effect.provideService(Statement.CurrentTransformer, (statement) => { const [query, params] = statement.compile(); - if (query.includes("LIKE '%htmlRender%'")) scannedRuns.push(String(params[0])); + if (query.includes("item.inline_work_output = 1")) scannedRuns.push(String(params[0])); return Effect.succeed(statement); }), ); @@ -4553,17 +4577,49 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { workCursor = page.nextCursor; } assert.strictEqual(workIds.size, 999); - for (const [toolName, output] of [ - ["t3-code.delegate_task", null], - ["mcp__t3_code__delegate_task", null], - ["mcp__t3-code__send_to_user", null], + const secondItemId = TurnItemId.make("turn-item:bounded-sql-history:2"); + const secondItem = { + id: secondItemId, + threadId, + runId: (yield* projectionStore.getTurnItem({ threadId, itemId: secondItemId }))!.runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "completed" as const, + title: "command 2", + startedAt: now, + completedAt: now, + updatedAt: now, + }; + const writeSecondItem = (item: OrchestrationV2TurnItem) => + projectionStore.apply({ + id: EventId.make(`event:bounded-sql-history:item-2:${item.type}`), + type: "turn-item.updated", + threadId, + runId: secondItem.runId ?? undefined, + driver, + occurredAt: now, + payload: item, + }); + for (const inline of [ + { toolName: "t3-code.delegate_task" }, + { toolName: "mcp__t3_code__delegate_task" }, + { toolName: "mcp__docs__search", output: { next: "Delegate-Task" } }, + { toolName: "view_image", viewedImagePath: "/repo/screenshot.png" }, + { toolName: "mcp__docs__chart", output: { [MCP_APP_OUTPUT_KEY]: { uri: "ui://chart" } } }, + { toolName: "mcp__t3-code__send_to_user" }, // OpenCode Code Mode reports a nested send_to_user call as one `execute` item. - ["execute", JSON.stringify({ sentMessage: "Draft" })], - ] as const) { - yield* sql`UPDATE orchestration_v2_projection_turn_items SET type = 'dynamic_tool', - payload_json = json_set(payload_json, '$.type', 'dynamic_tool', '$.toolName', ${toolName}, - '$.output', ${output}) - WHERE thread_id = ${threadId} AND ordinal = 2`; + { toolName: "execute", output: JSON.stringify({ sentMessage: "Draft" }) }, + ]) { + yield* writeSecondItem({ + ...secondItem, + type: "dynamic_tool", + input: {}, + ...inline, + }); const window = yield* projectionStore.getThreadSnapshotWindow(threadId, { rowLimit: sqlPageLimit, userTurnLimit: 10, @@ -4585,8 +4641,8 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { }); const page = yield* historyPage(threadId, newestCursor, undefined, false, "deferred"); assert.isUndefined(page.items.find((row) => row.item.ordinal === 2)?.item.deferredWork); - // Tool payloads hold megabytes, so a page that reads the full index, as a jump to an - // entry does, looks for inline output only in its own runs. + // A page that reads the full index, as a jump to an entry does, looks for inline output + // only in its own runs. const pageRead = traceSqlStatements(); yield* historyPage( threadId, @@ -4596,15 +4652,15 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { "deferred", ).pipe(Effect.withTracer(pageRead.tracer)); const payloadScans = pageRead.statements.filter((statement) => - statement.includes("LIKE '%htmlRender%'"), + statement.includes("item.inline_work_output = 1"), ); assert.lengthOf(payloadScans, 1); assert.include(payloadScans[0], "item.run_id IS json_extract(wanted.value, '$.id')"); } // Until its run is scanned, a cursor on inline output is hidden inside a work group. yield* sql`UPDATE orchestration_v2_projection_turn_items SET type = 'dynamic_tool', - payload_json = json_set(payload_json, '$.type', 'dynamic_tool', '$.toolName', 't3-code.delegate_task') - WHERE thread_id = ${threadId} AND ordinal = 4`; + payload_json = json_set(payload_json, '$.type', 'dynamic_tool', '$.toolName', 't3-code.delegate_task'), + inline_work_output = 1 WHERE thread_id = ${threadId} AND ordinal = 4`; const sharedRunId = "run:bounded-sql-history:1"; // A work page of rows that have no run leaves their inline output out too. yield* sql`UPDATE orchestration_v2_projection_turn_items SET run_id = NULL @@ -4665,8 +4721,8 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { '$.runId', CASE WHEN ordinal <= 700 THEN 'run:bounded-sql-history:300' ELSE ${sharedRunId} END) WHERE thread_id = ${threadId} AND ordinal >= 100`; yield* sql`UPDATE orchestration_v2_projection_turn_items SET type = 'dynamic_tool', - payload_json = json_set(payload_json, '$.type', 'dynamic_tool', '$.toolName', 't3-code.delegate_task') - WHERE thread_id = ${threadId} AND ordinal = 720`; + payload_json = json_set(payload_json, '$.type', 'dynamic_tool', '$.toolName', 't3-code.delegate_task'), + inline_work_output = 1 WHERE thread_id = ${threadId} AND ordinal = 720`; const beforeMissingCursor = yield* historyPage( threadId, encodeThreadHistoryCursor({ @@ -4685,7 +4741,15 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { payload_json = json_set(payload_json, '$.status', 'completed', '$.runId', ${sharedRunId}) WHERE thread_id = ${threadId} AND ordinal >= 100`; yield* sql`UPDATE orchestration_v2_projection_turn_items SET type = 'command_execution', - payload_json = json_set(payload_json, '$.type', 'command_execution') WHERE thread_id = ${threadId} AND ordinal IN (2, 4, 720)`; + payload_json = json_set(payload_json, '$.type', 'command_execution'), inline_work_output = 0 + WHERE thread_id = ${threadId} AND ordinal IN (4, 720)`; + yield* writeSecondItem({ + ...secondItem, + type: "command_execution", + input: "echo 2", + output: "ok", + exitCode: 0, + }); for (const [ordinal, status] of [ [0, "completed"], [1, "superseded"], @@ -4722,6 +4786,23 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { }); const oldWork = window.projection.visibleTurnItems.find((row) => row.item.deferredWork); assert.strictEqual(oldWork?.item.deferredWork?.itemCount, 987); + // A jump to an entry reads the full index, which folds the same group. + const jump = yield* historyPage( + threadId, + encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId: "turn-item:bounded-sql-history:1000", + position: 1000, + }), + oldWork!.sourceItemId, + false, + "deferred", + ); + assert.strictEqual( + jump.items.find((row) => row.item.deferredWork)?.item.deferredWork?.itemCount, + 987, + ); let cursor: string | null = oldWork!.item.deferredWork!.cursor; const loaded = new Set(); for (let pages = 0; cursor !== null; pages += 1) { @@ -8466,21 +8547,32 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { const [originalRow] = yield* sql<{ payload_json: string; }>`SELECT payload_json FROM orchestration_v2_projection_threads WHERE thread_id = ${threadId}`; - for (const [field, value] of [ - ["archivedAt", DateTime.formatIso(now)], - ["settledOverride", "settled"], - ]) { - yield* sql`UPDATE orchestration_v2_projection_threads - SET payload_json = json_set(payload_json, ${`$.${field}`}, ${value}) - WHERE thread_id = ${threadId}`; - assert.isUndefined( - (yield* store.getLimitRecoveryCandidates({ now, autoResume: true, snooze: false })).find( + const limitThread = (yield* store.getThreadProjection(threadId)).thread; + for (const archivedAt of [now, null]) { + yield* store.apply({ + id: EventId.make(`event:limit-shell:archived:${archivedAt !== null}`), + type: archivedAt === null ? "thread.unarchived" : "thread.archived", + threadId, + occurredAt: now, + payload: { ...limitThread, archivedAt }, + }); + assert.strictEqual( + (yield* store.getLimitRecoveryCandidates({ now, autoResume: true, snooze: false })).some( (row) => row.id === threadId, ), + archivedAt === null, ); - yield* sql`UPDATE orchestration_v2_projection_threads - SET payload_json = ${originalRow!.payload_json} WHERE thread_id = ${threadId}`; } + yield* sql`UPDATE orchestration_v2_projection_threads + SET payload_json = json_set(payload_json, '$.settledOverride', 'settled') + WHERE thread_id = ${threadId}`; + assert.isUndefined( + (yield* store.getLimitRecoveryCandidates({ now, autoResume: true, snooze: false })).find( + (row) => row.id === threadId, + ), + ); + yield* sql`UPDATE orchestration_v2_projection_threads + SET payload_json = ${originalRow!.payload_json} WHERE thread_id = ${threadId}`; yield* sql`UPDATE orchestration_v2_projection_threads SET deleted_at = ${DateTime.formatIso(now)} WHERE thread_id = ${threadId}`; assert.isUndefined( (yield* store.getLimitRecoveryCandidates({ now, autoResume: true, snooze: false })).find( diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index a04989da8d401..9dc14d2e47bf2 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -466,7 +466,14 @@ export interface ShellSnapshotOptions { /** What a shell subscriber's trims read from an active thread, without building its shell. */ export interface ActiveShellIndexEntry extends Pick< OrchestrationV2ThreadShell, - "id" | "projectId" | "lineage" | "settledOverride" | "settledAt" | "pinnedAt" | "snoozedUntil" + | "id" + | "projectId" + | "lineage" + | "settledOverride" + | "settledAt" + | "pinnedAt" + | "pinOrderKey" + | "snoozedUntil" > { /** False only when no run, request, work item, or watch can make the shell live. */ readonly mayBeLive: boolean; @@ -2173,18 +2180,31 @@ function shellFromState(input: { }; } +// Dynamic tool output the client renders inline (HTML, MCP apps, viewed images, delegated +// tasks, messages sent to the user), so its work group never defers. Mirrors the LIKE backfill +// in migration 095, where a tool name counts anywhere after the first toolName. Searching from +// that first one once avoids rescanning the payload for every nested toolName. +const INLINE_WORK_OUTPUT = new RegExp( + `htmlRender|${MCP_APP_OUTPUT_KEY}|"viewedImagePath"|sentMessage`, + "i", +); +const TOOL_NAME_PREFIX = /"toolName":"/i; +const INLINE_TOOL_NAME = /(?:delegate.task|send.to.user)"/is; + +const isInlineWorkOutput = (payloadJson: string) => { + if (INLINE_WORK_OUTPUT.test(payloadJson)) return true; + const toolName = TOOL_NAME_PREFIX.exec(payloadJson); + return ( + toolName !== null && + INLINE_TOOL_NAME.test(payloadJson.slice(toolName.index + toolName[0].length)) + ); +}; + export const layer: Layer.Layer = Layer.effect( ProjectionStoreV2, Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; - const inlineWorkOutput = sql`item.type = 'dynamic_tool' AND ( - item.payload_json LIKE '%htmlRender%' OR item.payload_json LIKE ${`%${MCP_APP_OUTPUT_KEY}%`} - OR item.payload_json LIKE '%"viewedImagePath"%' - OR item.payload_json LIKE '%"toolName":"%delegate_task"%' - OR item.payload_json LIKE '%"toolName":"%send_to_user"%' - OR item.payload_json LIKE '%sentMessage%')`; - // SQLite uses the partial conversation index of migration 082 only for this exact predicate. const CONVERSATION_INDEX_EXCLUDED_TYPES = sql.literal( `(${DEFERRED_WORK_ITEM_TYPES.map((type) => `'${type}'`).join(", ")})`, @@ -2934,7 +2954,8 @@ export const layer: Layer.Layer = type, status, updated_at, - payload_json + payload_json, + inline_work_output ) VALUES ( ${event.payload.id}, @@ -2948,7 +2969,8 @@ export const layer: Layer.Layer = ${event.payload.type}, ${event.payload.status}, ${updatedAt}, - ${payloadJson} + ${payloadJson}, + ${event.payload.type === "dynamic_tool" && isInlineWorkOutput(payloadJson) ? 1 : 0} ) ON CONFLICT(turn_item_id) DO UPDATE SET @@ -2962,7 +2984,8 @@ export const layer: Layer.Layer = type = excluded.type, status = excluded.status, updated_at = excluded.updated_at, - payload_json = excluded.payload_json + payload_json = excluded.payload_json, + inline_work_output = excluded.inline_work_output `; break; } @@ -3184,7 +3207,8 @@ export const layer: Layer.Layer = const eligible = sql` WITH eligible AS NOT MATERIALIZED ( SELECT item.rowid AS item_rowid, item.payload_json, item.ordinal, item.turn_item_id, - item.run_id, item.node_id, item.type, item.status, run.status AS run_status, + item.run_id, item.node_id, item.type, item.status, item.inline_work_output, + run.status AS run_status, attempt.attempt_id, attempt.status AS attempt_status FROM orchestration_v2_projection_turn_items AS item LEFT JOIN orchestration_v2_projection_runs AS run @@ -3475,7 +3499,7 @@ export const layer: Layer.Layer = OVER (PARTITION BY run_id ORDER BY ordinal) AS segment, CASE WHEN status = 'completed' AND (run_status = 'completed' OR attempt_status = 'superseded') AND type IN ${sql.in(DEFERRED_WORK_ITEM_TYPES)} - AND NOT (${inlineWorkOutput}) + AND inline_work_output = 0 AND run_id NOT IN (SELECT run_id FROM blocked_runs) THEN 1 ELSE 0 END AS can_defer FROM eligible AS item @@ -4661,7 +4685,7 @@ export const layer: Layer.Layer = WHERE failure.type = 'error' AND failure.status = 'failed' AND json_extract(failure.payload_json, '$.failure.class') = 'usage_limit' ) - AND json_extract(t.payload_json, '$.archivedAt') IS NULL + AND t.archived_at IS NULL AND json_extract(t.payload_json, '$.settledOverride') IS NOT 'settled' AND json_extract(item.payload_json, '$.failure.class') = 'usage_limit' AND json_extract(item.payload_json, '$.failure.resetAt') IS NOT NULL @@ -5268,14 +5292,17 @@ export const layer: Layer.Layer = WHERE latest.thread_id = ${threadId} ORDER BY latest.ordinal DESC LIMIT 1 ) - -- Retain the latest run for each provider thread with lost - -- background work, including owners used before a handoff. + -- Retain the latest ended run for each provider thread with lost + -- background work, including owners used before a handoff. An + -- unfinished run is read above and may prove never started. OR run.run_id IN ( SELECT ( SELECT ended.run_id FROM orchestration_v2_projection_runs AS ended WHERE ended.thread_id = ${threadId} AND ended.provider_thread_id = roster.provider_thread_id - AND ended.status NOT IN ('queued', 'rolled_back') + AND ended.status NOT IN ( + 'queued', 'preparing', 'starting', 'running', 'waiting', 'rolled_back' + ) -- A run that never started (see neverStarted) owns no work. AND NOT ( json_type(ended.payload_json, '$.startedAt') = 'null' @@ -6297,45 +6324,62 @@ export const layer: Layer.Layer = Effect.mapError(controlReadError(threadId)), ); - // A live run fork shows its source's history through the fork run without copying it. - const shownByLiveFork = (threadId: ThreadId, runIdColumn: string) => sql` - EXISTS ( - SELECT 1 - FROM orchestration_v2_projection_threads AS fork - JOIN orchestration_v2_projection_runs AS fork_run - ON fork_run.run_id = json_extract(fork.payload_json, '$.forkedFrom.runId') - LEFT JOIN orchestration_v2_projection_runs AS item_run - ON item_run.run_id = ${sql.literal(runIdColumn)} - WHERE fork_run.thread_id = ${threadId} - AND fork.deleted_at IS NULL - AND json_extract(fork.payload_json, '$.forkedFrom.type') = 'run' - AND json_extract(fork.payload_json, '$.forkedFrom.threadId') = ${threadId} - AND json_extract(fork.payload_json, '$.lineage.sideChat') IS NOT 1 - AND (${sql.literal(runIdColumn)} IS NULL OR item_run.ordinal <= fork_run.ordinal) - ) + // A run fork shows its source's history through the fork run without copying it, and every + // run fork below it shows that history too. Returns the last source run live forks show, with + // and without `leavingForkId`. + const lastRunsShownByLiveForks = (threadId: ThreadId, leavingForkId: ThreadId) => + sql<{ with_fork: number | null; without_fork: number | null }>` + WITH RECURSIVE showing(thread_id, deleted_at, through) AS ( + SELECT fork.thread_id, fork.deleted_at, fork_run.ordinal + FROM orchestration_v2_projection_context_transfers AS transfer + JOIN orchestration_v2_projection_threads AS fork + ON fork.thread_id = transfer.target_thread_id + JOIN orchestration_v2_projection_runs AS fork_run + ON fork_run.run_id = json_extract(fork.payload_json, '$.forkedFrom.runId') + WHERE transfer.source_thread_id = ${threadId} + AND transfer.type = 'fork' + AND fork_run.thread_id = ${threadId} + AND json_extract(fork.payload_json, '$.forkedFrom.type') = 'run' + AND json_extract(fork.payload_json, '$.forkedFrom.threadId') = ${threadId} + AND json_extract(fork.payload_json, '$.lineage.sideChat') IS NOT 1 + UNION + SELECT child.thread_id, child.deleted_at, showing.through + FROM showing + JOIN orchestration_v2_projection_context_transfers AS transfer + ON transfer.source_thread_id = showing.thread_id AND transfer.type = 'fork' + JOIN orchestration_v2_projection_threads AS child + ON child.thread_id = transfer.target_thread_id + WHERE json_extract(child.payload_json, '$.forkedFrom.type') = 'run' + AND json_extract(child.payload_json, '$.forkedFrom.threadId') = showing.thread_id + AND json_extract(child.payload_json, '$.lineage.sideChat') IS NOT 1 + ) + SELECT + MAX(through) AS with_fork, + MAX(CASE WHEN thread_id <> ${leavingForkId} THEN through END) AS without_fork + FROM showing + WHERE deleted_at IS NULL + `.pipe(Effect.map((rows) => rows[0] ?? { with_fork: null, without_fork: null })); + + // A row with no run predates every run (-1), so any live fork shows it. + const runOrdinalBetween = (runIdColumn: string, from: number, through: number) => sql` + COALESCE(( + SELECT run.ordinal FROM orchestration_v2_projection_runs AS run + WHERE run.run_id = ${sql.literal(runIdColumn)} + ), -1) BETWEEN ${from} AND ${through} `; - // Thread deletion keeps what a live fork still shows; a reference check must count it. - const exceptShownByLiveFork = ( + const runAttachmentIds = Effect.fn("ProjectionStore.runAttachmentIds")(function* ( threadId: ThreadId, - runIdColumn: string, - options: { readonly includeShownByLiveFork?: boolean } | undefined, - ) => - options?.includeShownByLiveFork === true - ? sql`` - : sql`AND NOT ${shownByLiveFork(threadId, runIdColumn)}`; - - const getThreadAttachmentIds: ProjectionStoreV2Shape["getThreadAttachmentIds"] = ( - threadId, - options, - ) => - Effect.all([ + from: number, + through: number, + ) { + const [messages, renders, answerFiles] = yield* Effect.all([ sql<{ id: string }>` SELECT DISTINCT json_extract(attachment.value, '$.id') AS id FROM orchestration_v2_projection_messages AS message, json_each(message.payload_json, '$.attachments') AS attachment WHERE message.thread_id = ${threadId} - ${exceptShownByLiveFork(threadId, "message.run_id", options)} + AND ${runOrdinalBetween("message.run_id", from, through)} `, sql<{ payload_json: string }>` SELECT item.payload_json @@ -6345,7 +6389,7 @@ export const layer: Layer.Layer = AND (item.payload_json LIKE '%htmlRender%' OR item.payload_json LIKE ${`%${MCP_APP_OUTPUT_KEY}%`} OR item.payload_json LIKE '%preview_recording_stop%') - ${exceptShownByLiveFork(threadId, "item.run_id", options)} + AND ${runOrdinalBetween("item.run_id", from, through)} `, sql<{ id: string }>` SELECT DISTINCT json_extract(attachment.value, '$.id') AS id @@ -6354,37 +6398,98 @@ export const layer: Layer.Layer = json_each(question.value) AS attachment WHERE item.thread_id = ${threadId} AND item.type = 'user_input_request' - ${exceptShownByLiveFork(threadId, "item.run_id", options)} + AND ${runOrdinalBetween("item.run_id", from, through)} `, + ]); + return [ + ...messages.map((row) => row.id), + ...answerFiles.map((row) => row.id), + ...threadHtmlRenderAttachmentIds( + threadId, + renders.map((row) => { + const item = parseEncodedPayload(row.payload_json); + return { + toolName: typeof item.toolName === "string" ? item.toolName : null, + output: item.output, + }; + }), + ), + ]; + }); + + const unshownRunAttachmentIds = Effect.fn("ProjectionStore.unshownRunAttachmentIds")(function* ( + threadId: ThreadId, + from: number, + through: number, + ) { + const candidates = yield* runAttachmentIds(threadId, from, through); + if (from <= -1 || candidates.length === 0) return candidates; + const retained = new Set(yield* runAttachmentIds(threadId, -1, from - 1)); + return candidates.filter((id) => !retained.has(id)); + }); + + // Deleting a fork also frees what its deleted sources kept only for it. + const getThreadAttachmentIds: ProjectionStoreV2Shape["getThreadAttachmentIds"] = Effect.fn( + "ProjectionStore.getThreadAttachmentIds", + )( + function* (threadId, options) { + const deletedSources = yield* sql<{ thread_id: ThreadId }>` + WITH RECURSIVE source(thread_id) AS ( + SELECT json_extract(thread.payload_json, '$.forkedFrom.threadId') + FROM orchestration_v2_projection_threads AS thread + WHERE thread.thread_id = ${threadId} + AND json_extract(thread.payload_json, '$.forkedFrom.type') = 'run' + AND json_extract(thread.payload_json, '$.lineage.sideChat') IS NOT 1 + UNION + SELECT json_extract(thread.payload_json, '$.forkedFrom.threadId') + FROM orchestration_v2_projection_threads AS thread + JOIN source USING (thread_id) + WHERE thread.deleted_at IS NOT NULL + AND json_extract(thread.payload_json, '$.forkedFrom.type') = 'run' + AND json_extract(thread.payload_json, '$.lineage.sideChat') IS NOT 1 + ) + SELECT thread.thread_id + FROM source + JOIN orchestration_v2_projection_threads AS thread USING (thread_id) + WHERE thread.deleted_at IS NOT NULL + `; + const afterRun = (ordinal: number | null) => (ordinal === null ? -1 : ordinal + 1); + const own = yield* lastRunsShownByLiveForks(threadId, threadId); + const released = yield* Effect.forEach( + options?.includeShownByLiveFork ? [] : deletedSources, + ({ thread_id: source }) => + lastRunsShownByLiveForks(source, threadId).pipe( + Effect.flatMap((shown) => + shown.with_fork === null + ? Effect.succeed([]) + : unshownRunAttachmentIds(source, afterRun(shown.without_fork), shown.with_fork), + ), + ), + ); // A guest's waiting files are pending uploads that no message row holds yet. - sql<{ id: string }>` - SELECT DISTINCT json_extract(attachment.value, '$.id') AS id - FROM orchestration_v2_projection_threads AS thread, - json_each(thread.payload_json, '$.guestShare.messages') AS message, - json_each(message.value, '$.attachments') AS attachment - WHERE thread.thread_id = ${threadId} - AND json_extract(message.value, '$.status') = 'pending' - `, - ]).pipe( - Effect.map(([messages, renders, answerFiles, guestFiles]) => [ + const guestFiles = yield* sql<{ id: string }>` + SELECT DISTINCT json_extract(attachment.value, '$.id') AS id + FROM orchestration_v2_projection_threads AS thread, + json_each(thread.payload_json, '$.guestShare.messages') AS message, + json_each(message.value, '$.attachments') AS attachment + WHERE thread.thread_id = ${threadId} + AND json_extract(message.value, '$.status') = 'pending' + `; + return [ ...new Set([ - ...messages.map((row) => row.id), - ...guestFiles.map((row) => row.id), - ...answerFiles.map((row) => row.id), - ...threadHtmlRenderAttachmentIds( + ...(yield* unshownRunAttachmentIds( threadId, - renders.map((row) => { - const item = parseEncodedPayload(row.payload_json); - return { - toolName: typeof item.toolName === "string" ? item.toolName : null, - output: item.output, - }; - }), - ), + options?.includeShownByLiveFork ? -1 : afterRun(own.with_fork), + Number.MAX_SAFE_INTEGER, + )), + ...guestFiles.map((row) => row.id), + ...released.flat(), ]), - ]), - Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })), - ); + ]; + }, + (effect, threadId) => + effect.pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause }))), + ); const getMessagesById = Effect.fn("ProjectionStore.getMessagesById")( function* (threadId: ThreadId, messageIds: ReadonlyArray) { @@ -6678,9 +6783,7 @@ export const layer: Layer.Layer = }>`SELECT item.turn_item_id, item.run_id, item.node_id, item.parent_item_id, item.type, item.status, item.ordinal, ${includePersistentOutput ? sql`attempt.attempt_id` : sql`NULL`} AS attempt_id, ${includePersistentOutput ? sql`attempt.status` : sql`NULL`} AS attempt_status, - ${ - includePersistentOutput ? sql`CASE WHEN ${inlineWorkOutput} THEN 1 ELSE 0 END` : sql`0` - } AS persistent_output, + ${includePersistentOutput ? sql`item.inline_work_output` : sql`0`} AS persistent_output, CASE WHEN item.type = 'user_message' THEN json_extract(item.payload_json, '$.inputIntent') END AS input_intent, CASE WHEN item.type = 'user_message' THEN json_extract(item.payload_json, '$.createdBy') END AS created_by, CASE WHEN item.type IN ('user_message', 'assistant_message') THEN json_extract(item.payload_json, '$.messageId') END AS message_id @@ -7234,7 +7337,7 @@ export const layer: Layer.Layer = CROSS JOIN orchestration_v2_projection_turn_items AS item ON item.thread_id = json_extract(wanted.value, '$.threadId') AND item.run_id IS json_extract(wanted.value, '$.id') - WHERE item.status = 'completed' AND ${inlineWorkOutput}`; + WHERE item.status = 'completed' AND item.inline_work_output = 1`; if (found.length === 0) break; for (const row of found) persistentOutputs.add(`${row.thread_id}:${row.turn_item_id}`); @@ -8380,7 +8483,7 @@ export const layer: Layer.Layer = SELECT thread_id, json_extract(payload_json, '$.worktreePath') AS worktree_path FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL - ${options?.includeArchived === true ? sql`` : sql`AND json_extract(payload_json, '$.archivedAt') IS NULL`} + ${options?.includeArchived === true ? sql`` : sql`AND archived_at IS NULL`} AND json_extract(payload_json, '$.worktreePath') IS NOT NULL `.pipe( Effect.map((rows) => @@ -8832,7 +8935,7 @@ export const layer: Layer.Layer = SELECT thread_id FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL - AND json_extract(payload_json, '$.archivedAt') IS NULL + AND archived_at IS NULL AND json_extract(payload_json, '$.lineage.relationshipToParent') = 'subagent' `; return rows.map((row) => ThreadId.make(row.thread_id)); @@ -8858,6 +8961,7 @@ export const layer: Layer.Layer = readonly settled_override: string | null; readonly settled_at: string | null; readonly pinned_at: string | null; + readonly pin_order_key: string | null; readonly snoozed_until: string | null; readonly may_be_live: number; readonly has_remote_tasks: number; @@ -8872,6 +8976,7 @@ export const layer: Layer.Layer = json_extract(t.payload_json, '$.settledOverride') AS settled_override, json_extract(t.payload_json, '$.settledAt') AS settled_at, json_extract(t.payload_json, '$.pinnedAt') AS pinned_at, + json_extract(t.payload_json, '$.pinOrderKey') AS pin_order_key, json_extract(t.payload_json, '$.snoozedUntil') AS snoozed_until, -- A superset of isLiveSubagentShell: the sources of its run status, pending request, -- and pending background work. @@ -8930,6 +9035,7 @@ export const layer: Layer.Layer = : null, settledAt: row.settled_at === null ? null : DateTime.makeUnsafe(row.settled_at), pinnedAt: row.pinned_at === null ? null : DateTime.makeUnsafe(row.pinned_at), + pinOrderKey: row.pin_order_key, snoozedUntil: row.snoozed_until === null ? null : DateTime.makeUnsafe(row.snoozed_until), mayBeLive: row.may_be_live === 1, hasRemoteTasks: row.has_remote_tasks === 1, @@ -9049,7 +9155,7 @@ export const layer: Layer.Layer = json_extract(t.payload_json, '$.settledAt') AS settled_at FROM orchestration_v2_projection_threads t WHERE t.deleted_at IS NULL - AND json_extract(t.payload_json, '$.archivedAt') IS NULL + AND t.archived_at IS NULL AND json_extract(t.payload_json, '$.lineage.relationshipToParent') IS NOT 'subagent' AND json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1 AND json_extract(t.payload_json, '$.settledOverride') = 'settled' diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts index 0197a10fae2e2..f08a3a038be6f 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts @@ -14,6 +14,7 @@ import { TurnItemId, type OrchestrationV2ThreadProjection, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -428,8 +429,17 @@ it.effect("recovery closes a secret card's form but leaves a link card open", () runtimeRequests: [], providerSessions: [], providerThreads: [], - providerTurns: [], - runs: [{ id: runId, status: "running", providerInstanceId: ProviderInstanceId.make("codex") }], + providerTurns: [ + { runAttemptId: RunAttemptId.make("attempt_secret_recovery"), status: "running" }, + ], + runs: [ + { + id: runId, + status: "running", + activeAttemptId: RunAttemptId.make("attempt_secret_recovery"), + providerInstanceId: ProviderInstanceId.make("codex"), + }, + ], attempts: [], nodes: [], subagents: [], @@ -508,20 +518,62 @@ it.effect.each([ "starting-other-request", "starting-own-request", "starting-scheduled", + "starting-steered", + "running", + "running-delegated", + "running-delegated-capped", + "running-delegated-snoozed", + "running-delegated-stopped", + "running-resume", ] as const)("recovers $0 work after restart", (scenario) => { - const status = scenario.startsWith("starting") ? "starting" : scenario; + const status = scenario.startsWith("starting") + ? "starting" + : scenario.startsWith("running") + ? "running" + : scenario; + const resent = scenario === "starting-scheduled" || scenario === "running-delegated"; const terminalized = status === "preparing" || scenario === "starting-own-request" || - scenario === "starting-scheduled"; + scenario === "starting-steered" || + scenario === "running-delegated-capped" || + scenario === "running-delegated-snoozed" || + scenario === "running-delegated-stopped" || + scenario === "running-resume"; + const startedAt = + status === "running" || scenario === "starting-steered" + ? DateTime.makeUnsafe("2026-11-01T19:34:40.403Z") + : null; const threadId = ThreadId.make("thread_queued_restart"); const runId = RunId.make("run_queued_restart"); const attemptId = RunAttemptId.make("attempt_queued_restart"); + const steeredAttemptId = RunAttemptId.make("attempt_queued_restart_steered"); const rootNodeId = NodeId.make("node_queued_restart"); let committedInput: Parameters[0] | null = null; + const written: Array = []; const projection = { - thread: { id: threadId }, + thread: { + id: threadId, + archivedAt: null, + deletedAt: null, + settledOverride: null, + snoozedUntil: + scenario === "running-delegated-snoozed" + ? DateTime.makeUnsafe("2099-07-25T09:00:00.000Z") + : null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + ...(scenario === "running-resume" + ? { + limitRecovery: { + runId: RunId.make("run_queued_restart_limited"), + resetAt: "2026-11-01T19:34:00.000Z", + autoResume: true, + }, + } + : {}), + }, runtimeRequests: scenario.endsWith("request") ? [ { @@ -536,16 +588,29 @@ it.effect.each([ : [], providerSessions: [], providerThreads: [], - providerTurns: [], + providerTurns: + scenario === "starting-steered" + ? [ + { + id: ProviderTurnId.make("provider_turn_queued_restart_steered"), + runAttemptId: steeredAttemptId, + status: "interrupted", + }, + ] + : [], runs: [ { id: runId, status, - startedAt: null, + startedAt, + rootNodeId, activeAttemptId: attemptId, userMessageId: MessageId.make("message_queued_restart"), queuePosition: 1, providerInstanceId: ProviderInstanceId.make("codex"), + ...(scenario === "running-resume" + ? { usageLimitContinuationOfRunId: RunId.make("run_queued_restart_limited") } + : {}), ...(status === "preparing" ? { workspacePreparation: { @@ -558,11 +623,15 @@ it.effect.each([ }, ], attempts: [ + ...(scenario === "starting-steered" + ? [{ id: steeredAttemptId, runId, rootNodeId, status: "interrupted" }] + : []), { id: attemptId, runId, rootNodeId, - status: "pending", + status: status === "running" ? "running" : "pending", + startedAt: status === "running" ? startedAt : null, }, ], nodes: [ @@ -578,21 +647,37 @@ it.effect.each([ { id: rootNodeId, runId, - status: "pending", + status: status === "running" ? "running" : "pending", + startedAt: status === "running" ? startedAt : null, }, ], subagents: [], messages: - status === "starting" + status === "starting" || status === "running" ? [ { id: MessageId.make("message_queued_restart"), - createdBy: "user", + ...(scenario.startsWith("running-delegated") + ? { createdBy: "agent", creationSource: "mcp" } + : scenario === "running-resume" + ? { createdBy: "agent", creationSource: "server" } + : { createdBy: "user" }), ...(scenario === "starting-scheduled" ? { scheduledTaskId: "scheduled-task" } : {}), }, ] : [], - turnItems: [], + turnItems: + scenario === "running-delegated-stopped" + ? [ + { + id: TurnItemId.make("turn_item_queued_restart_stop"), + type: "run_interrupt_request", + runId, + nodeId: rootNodeId, + status: "completed", + }, + ] + : [], } as unknown as OrchestrationV2ThreadProjection; const layer = ProviderRuntimeRecovery.layer.pipe( Layer.provide(ServerSettings.layerTest()), @@ -600,7 +685,12 @@ it.effect.each([ Layer.mergeAll( Layer.mock(ProjectionStore.ProjectionStoreV2)({ getRecoveryThreadIds: () => Effect.succeed([threadId]), - getRuntimeRecoveryProjection: () => Effect.succeed(projection), + // Like the store, recovery state carries only provider turns that have not ended. + getRuntimeRecoveryProjection: () => + Effect.succeed({ + ...projection, + providerTurns: projection.providerTurns.filter((turn) => turn.status === "running"), + }), getMessagesById: (requestedThreadId, messageIds) => Effect.succeed( new Map( @@ -618,12 +708,23 @@ it.effect.each([ committedInput = input; return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never); }, + writeWithEffects: (input) => { + written.push(...input.effects); + return Effect.succeed([]); + }, }), IdAllocator.layer, Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runRecoveryOnce: Effect.succeed(false), }), Layer.mock(EffectOutbox.EffectOutboxV2)({ + // Three earlier restarts each cut a resend the worker had claimed. + listByCommandId: () => + Effect.succeed( + scenario === "running-delegated-capped" + ? ([1, 1, 1].map((attemptCount) => ({ attemptCount })) as never) + : [], + ), reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }), }), ), @@ -640,11 +741,15 @@ it.effect.each([ const runEvent = command.events.find((event) => event.type === "run.updated"); const attemptEvent = command.events.find((event) => event.type === "run-attempt.updated"); const nodeEvent = command.events.find((event) => event.type === "node.updated"); - assert.equal( - runEvent?.type === "run.updated" ? runEvent.payload.status : null, - terminalized ? "cancelled" : "queued", - ); + assert.deepInclude(runEvent?.type === "run.updated" ? runEvent.payload : null, { + status: terminalized ? "cancelled" : resent ? "starting" : "queued", + startedAt: scenario === "starting-steered" ? startedAt : null, + }); assert.isEmpty(command.effects); + assert.deepEqual( + written.map((effect) => effect.request), + resent ? [{ type: "provider-turn.start", runId }] : [], + ); if (terminalized) { assert.equal( attemptEvent?.type === "run-attempt.updated" ? attemptEvent.payload.status : null, @@ -655,10 +760,33 @@ it.effect.each([ scenario === "starting-own-request" ? null : "cancelled", ); } else { - assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queuePosition : null, 1); - assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queueHeld : false, true); - assert.isUndefined(attemptEvent); - assert.isUndefined(nodeEvent); + if (!resent) { + assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queuePosition : null, 1); + assert.equal(runEvent?.type === "run.updated" ? runEvent.payload.queueHeld : false, true); + } + if (status === "running") { + assert.deepInclude( + attemptEvent?.type === "run-attempt.updated" ? attemptEvent.payload : null, + { status: "pending", startedAt: null }, + ); + assert.deepInclude(nodeEvent?.type === "node.updated" ? nodeEvent.payload : null, { + status: "pending", + startedAt: null, + }); + } else { + assert.isUndefined(attemptEvent); + assert.isUndefined(nodeEvent); + } + } + // The unsent auto-resume gets a fresh request id so the limit worker sends it again. + if (scenario === "running-resume") { + const rearmed = command.events.find((event) => event.type === "thread.metadata-updated"); + assert.equal( + rearmed?.type === "thread.metadata-updated" + ? rearmed.payload.limitRecovery?.requestId + : null, + command.commandId, + ); } }).pipe(Effect.provide(layer)); }); @@ -707,6 +835,7 @@ it.effect( { id: runId, status: "starting", + activeAttemptId: attemptId, providerThreadId, providerInstanceId: ProviderInstanceId.make("codex"), }, @@ -975,7 +1104,7 @@ it.effect( pendingBackgroundTasks: [], }, ], - providerTurns: [], + providerTurns: [{ runAttemptId: activeAttemptId, status: "running" }], runs: [ { id: settledRunId, @@ -985,6 +1114,7 @@ it.effect( { id: activeRunId, status: "running", + activeAttemptId, providerInstanceId: claudeInstanceId, }, ], @@ -1440,7 +1570,9 @@ it.effect("leaves delegated tasks to their own child threads after process loss" pendingBackgroundTasks: [], }, ], - providerTurns: [], + providerTurns: [ + { runAttemptId: RunAttemptId.make("attempt_recovery_delegation"), status: "running" }, + ], runs: [ { id: settledRunId, @@ -1453,6 +1585,7 @@ it.effect("leaves delegated tasks to their own child threads after process loss" id: runningRunId, ordinal: 2, status: "running", + activeAttemptId: RunAttemptId.make("attempt_recovery_delegation"), providerThreadId, providerInstanceId: claudeInstanceId, }, diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index 979c5a0fc3ae7..0cd4377a23b3d 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -5,6 +5,7 @@ import { isProviderNativeSubagentThread, type OrchestrationV2DomainEvent, type ProviderThreadId, + type RunAttemptId, type OrchestrationV2RestartCancelledBackgroundWork, type OrchestrationV2Subagent, type OrchestrationV2ThreadProjection, @@ -24,7 +25,11 @@ import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ServerSettings from "../serverSettings.ts"; -import { restartContinuationRun } from "./RestartContinuation.ts"; +import { + restartContinuationBlocked, + restartContinuationRun, + restartStopRequested, +} from "./RestartContinuation.ts"; import { isBufferedProviderNotification } from "./NotificationMailbox.ts"; import { queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts"; import { @@ -54,6 +59,8 @@ export class ProviderRuntimeRecoveryError extends Schema.TaggedError + (run.status === "running" || (run.status === "starting" && run.startedAt !== null)) && + run.activeAttemptId !== null + ? [[run.activeAttemptId, run.id] as const] + : [], + ), + ); + if (runIdByAttempt.size === 0) return projection; + const unaccepted = new Set(runIdByAttempt.values()); + const accept = (turns: ReadonlyArray<{ readonly runAttemptId: RunAttemptId | null }>) => { + for (const turn of turns) { + const runId = + turn.runAttemptId === null ? undefined : runIdByAttempt.get(turn.runAttemptId); + if (runId !== undefined) unaccepted.delete(runId); + } + }; + accept(projection.providerTurns); + if (unaccepted.size === 0) return projection; + for (const attempt of projection.attempts) { + if (unaccepted.has(attempt.runId)) runIdByAttempt.set(attempt.id, attempt.runId); + } + // The recovery projection omits ended provider turns, such as one a steer replaced. + accept( + (yield* projections + .getThreadRecords(projection.thread.id, ["providerTurns"], { + providerTurnAttemptIds: [...runIdByAttempt].flatMap(([attemptId, runId]) => + unaccepted.has(runId) ? [attemptId] : [], + ), + }) + .pipe( + Effect.mapError( + (cause) => + new ProviderRuntimeRecoveryError({ + operation: "read-projections", + threadId: projection.thread.id, + cause, + }), + ), + )).providerTurns, + ); + return { + ...projection, + runs: projection.runs.map((run) => + unaccepted.has(run.id) ? { ...run, status: "starting" as const, startedAt: null } : run, + ), + }; + }, + ); + const reconcileProjection = Effect.fn("ProviderRuntimeRecoveryService.reconcileProjection")( function* ( - projection: ProjectionStore.ProjectionRuntimeRecoveryState, + stored: ProjectionStore.ProjectionRuntimeRecoveryState, trigger: "startup" | "shutdown", continueAfterRestart: boolean, stoppedThisPass: ReadonlyMap = new Map(), ) { const now = yield* DateTime.now; + const projection = yield* rewindUnacceptedRuns(stored); let runs = [] as Array; for (const run of nonterminalRuns(projection)) { if (run.status === "waiting") { @@ -380,7 +444,105 @@ export const make = Effect.gen(function* () { const retryableRuns = unstartedRuns.filter((run) => retryableMessageIds.has(run.userMessageId), ); - const retryableRunIds = new Set(retryableRuns.map((run) => run.id)); + // Nobody reviews a delegated, agent-sent or scheduled prompt, so it is sent again instead. + const unattendedRuns = continueAfterRestart + ? unstartedRuns.filter((run) => + queuedMessages.some( + (message) => + message.id === run.userMessageId && + !retryableMessageIds.has(message.id) && + message.notification === undefined && + message.delegatedCompletion === undefined && + (message.scheduledTaskId !== undefined || message.creationSource === "mcp"), + ), + ) + : []; + const resentRuns: Array = []; + const resends: Array = []; + for (const run of unattendedRuns) { + if ( + restartContinuationBlocked(projection, run, now, false) || + (yield* restartStopRequested(projections.getThreadRecords, projection.thread, run).pipe( + Effect.mapError( + (cause) => + new ProviderRuntimeRecoveryError({ + operation: "read-projections", + threadId: projection.thread.id, + cause, + }), + ), + )) + ) + continue; + const resendCommandId = CommandId.make(`command:restart-resend:${run.id}`); + const earlierResends = yield* outbox.listByCommandId(resendCommandId).pipe( + Effect.mapError( + (cause) => + new ProviderRuntimeRecoveryError({ + operation: "reconcile", + threadId: projection.thread.id, + cause, + }), + ), + ); + // A prompt whose start keeps crashing the server would otherwise be sent forever. + if (earlierResends.filter((effect) => effect.attemptCount > 0).length >= MAX_RESENDS) { + yield* Effect.logWarning("Not resending a prompt that restarts cut too many times", { + threadId: projection.thread.id, + runId: run.id, + }); + continue; + } + resentRuns.push(run); + resends.push({ + id: `effect:restart-resend:${run.id}:${commandId}`, + commandId: resendCommandId, + threadId: projection.thread.id, + request: { type: "provider-turn.start", runId: run.id }, + }); + } + for (const run of resentRuns) { + events.push({ + id: yield* allocateEventId(), + type: "run.updated", + threadId: projection.thread.id, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: run, + }); + } + const keptRuns = [...retryableRuns, ...resentRuns]; + for (const run of keptRuns) { + for (const attempt of projection.attempts.filter( + (candidate) => candidate.id === run.activeAttemptId && candidate.status === "running", + )) { + events.push({ + id: yield* allocateEventId(), + type: "run-attempt.updated", + threadId: projection.thread.id, + runId: run.id, + nodeId: attempt.rootNodeId, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...attempt, status: "pending", startedAt: null }, + }); + } + for (const node of projection.nodes.filter( + (candidate) => candidate.id === run.rootNodeId && candidate.status === "running", + )) { + events.push({ + id: yield* allocateEventId(), + type: "node.updated", + threadId: projection.thread.id, + runId: run.id, + nodeId: node.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...node, status: "pending", startedAt: null }, + }); + } + } const retryableItems = retryableRuns.length === 0 ? [] @@ -417,7 +579,7 @@ export const make = Effect.gen(function* () { }, }); } - runs = runs.filter((run) => !retryableRunIds.has(run.id)); + runs = runs.filter((run) => !keptRuns.some((kept) => kept.id === run.id)); const heldRuns = [ ...retryableRuns, ...queuedRunsInDeliveryOrder({ runs: queuedRuns, messages: queuedMessages }), @@ -932,6 +1094,7 @@ export const make = Effect.gen(function* () { closedRequests: requests.length, retiredEffects, cancelledEffectIds, + resends, }; }, ); @@ -951,6 +1114,7 @@ export const make = Effect.gen(function* () { let stoppedSessions = 0; let closedRequests = 0; let retiredEffects = 0; + const resends: Array = []; const stoppedThisPass = new Map(); const grouped = trigger === "shutdown" && threadIds.length > 1; const groupSize = grouped ? 32 : 1; @@ -980,6 +1144,7 @@ export const make = Effect.gen(function* () { } } cancelledEffectIds.push(...result.cancelledEffectIds); + resends.push(...result.resends); terminalizedRuns += result.terminalizedRuns; stoppedSessions += result.stoppedSessions; closedRequests += result.closedRequests; @@ -1001,6 +1166,17 @@ export const make = Effect.gen(function* () { (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }), ), ); + // After the drain, which cancels every unsettled provider start. A crash before this write + // leaves the run unstarted, so the next recovery sends it again. + if (resends.length > 0) { + yield* eventSink + .writeWithEffects({ events: [], effects: resends }) + .pipe( + Effect.mapError( + (cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause }), + ), + ); + } return { terminalizedRuns, stoppedSessions, @@ -1036,7 +1212,10 @@ export const make = Effect.gen(function* () { .continueThreadsAfterServerUpdate ) return; - const run = restartContinuationRun(projection, yield* DateTime.now); + const run = restartContinuationRun( + yield* rewindUnacceptedRuns(projection), + yield* DateTime.now, + ); if (!run) return; const commandId = CommandId.make(`command:restart-prepare:${run.id}`); yield* eventSink.writeWithEffects({ diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index c03890ee44501..50bc8e4139b80 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -816,6 +816,8 @@ function runBrowserAccessScenario(input: { readonly enableAgentBrowserAccess: boolean; readonly projectOverride: boolean; readonly deviceOverride?: boolean; + readonly enableAgentDeviceAccess?: boolean; + readonly enableDeviceSupport?: boolean; readonly createThread?: boolean; readonly projectExists?: boolean; readonly delegatedBy?: ThreadId; @@ -870,6 +872,12 @@ function runBrowserAccessScenario(input: { projectServiceLayer: layerProjectService, serverSettingsLayer: ServerSettings.layerTest({ enableAgentBrowserAccess: input.enableAgentBrowserAccess, + ...(input.enableAgentDeviceAccess === undefined + ? {} + : { enableAgentDeviceAccess: input.enableAgentDeviceAccess }), + ...(input.enableDeviceSupport === undefined + ? {} + : { enableDeviceSupport: input.enableDeviceSupport }), projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: input.projectOverride, @@ -5662,6 +5670,7 @@ it.effect( enableAgentBrowserAccess: false, projectOverride: false, deviceOverride: true, + enableDeviceSupport: true, }); assert.isTrue(enabled?.capabilities?.has("device")); assert.isFalse(enabled?.browserToolsAvailable); @@ -5669,12 +5678,49 @@ it.effect( enableAgentBrowserAccess: false, projectOverride: false, deviceOverride: true, + enableDeviceSupport: true, projectExists: false, }); assert.isFalse(denied?.capabilities?.has("device")); }), ); +it.effect("ProviderSessionManagerV2 withholds device tools while device support is off", () => + Effect.gen(function* () { + const global = yield* runBrowserAccessScenario({ + enableAgentBrowserAccess: false, + projectOverride: false, + enableAgentDeviceAccess: true, + enableDeviceSupport: false, + }); + assert.isFalse( + global?.capabilities?.has("device"), + "global agent device access granted device tools with device support off", + ); + const project = yield* runBrowserAccessScenario({ + enableAgentBrowserAccess: false, + projectOverride: false, + deviceOverride: true, + enableDeviceSupport: false, + }); + assert.isFalse( + project?.capabilities?.has("device"), + "project agent device access granted device tools with device support off", + ); + const missingProject = yield* runBrowserAccessScenario({ + enableAgentBrowserAccess: false, + projectOverride: false, + enableAgentDeviceAccess: true, + enableDeviceSupport: false, + projectExists: false, + }); + assert.isFalse( + missingProject?.capabilities?.has("device"), + "agent device access granted device tools with device support off for a missing project", + ); + }), +); + // Device instructions reach delegated children only because their own sessions hold `device`. it.effect("ProviderSessionManagerV2 gives a delegated child its project's device access", () => Effect.gen(function* () { @@ -5682,6 +5728,7 @@ it.effect("ProviderSessionManagerV2 gives a delegated child its project's device enableAgentBrowserAccess: false, projectOverride: false, deviceOverride: true, + enableDeviceSupport: true, delegatedBy: ThreadId.make("thread-provider-session-manager-parent"), }); assert.isTrue(child?.capabilities?.has("device")); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 0868f3a871893..2d2038472a0cb 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -470,13 +470,16 @@ export const layerWithOptions = ( if (Option.isNone(project)) return { browser: browserOverridden ? false : settings.enableAgentBrowserAccess, - device: deviceOverridden ? false : settings.enableAgentDeviceAccess, + device: + settings.enableDeviceSupport && + !deviceOverridden && + settings.enableAgentDeviceAccess, }; } const effective = resolveProjectSettings(settings, thread.projectId).settings; return { browser: effective.enableAgentBrowserAccess, - device: effective.enableAgentDeviceAccess, + device: settings.enableDeviceSupport && effective.enableAgentDeviceAccess, }; }).pipe( Effect.catch((cause) => diff --git a/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts b/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts index cde112bb74b09..a1442b82e10cd 100644 --- a/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts @@ -314,3 +314,31 @@ it.effect("distinguishes compatible and incompatible instances of the same drive ), ), ); + +it.effect( + "applies a next-turn selection change when a shared session's cwd is another thread's", + () => + Effect.gen(function* () { + const service = yield* ProviderSwitch.ProviderSwitchServiceV2; + const thread = projection(); + const result = yield* service.plan({ + projection: { + ...thread, + providerSessions: [{ ...thread.providerSessions[0]!, cwd: "/other-thread-worktree" }], + }, + targetModelSelection: { + instanceId: currentInstanceId, + model: "gpt-5.1-codex", + options: [{ id: "fastMode", value: true }], + }, + }); + assert.equal(result.transition.type, "switch_model_in_session"); + assert.deepEqual(result.releaseProviderSessionIds, []); + }).pipe( + Effect.provide( + layerTest({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }, () => + Effect.succeed({ type: "apply_on_next_turn" }), + ), + ), + ), +); diff --git a/apps/server/src/orchestration-v2/ProviderSwitchService.ts b/apps/server/src/orchestration-v2/ProviderSwitchService.ts index a31b5120964ed..69c3f351602b5 100644 --- a/apps/server/src/orchestration-v2/ProviderSwitchService.ts +++ b/apps/server/src/orchestration-v2/ProviderSwitchService.ts @@ -113,6 +113,10 @@ export const layer: Layer.Layer< sessionCapabilities: negotiatedCapabilities, }) : undefined; + // A selection change keeps the thread where it is. A shared session's cwd is the + // workspace of whichever thread opened it, not a move of this thread. + const workspace = + projection.thread.worktreePath ?? currentSession?.cwd ?? ""; const transition = Option.isNone(targetInstance) || Option.isNone(targetAdapter) ? ({ @@ -133,10 +137,7 @@ export const layer: Layer.Layer< modelSelection: current, runtimeMode: projection.thread.runtimeMode, interactionMode: projection.thread.interactionMode, - workspace: - currentSession?.cwd ?? - projection.thread.worktreePath ?? - "", + workspace, }, target: { driver: targetInstance.value.driver, @@ -147,10 +148,7 @@ export const layer: Layer.Layer< modelSelection: targetModelSelection, runtimeMode: projection.thread.runtimeMode, interactionMode: projection.thread.interactionMode, - workspace: - projection.thread.worktreePath ?? - currentSession?.cwd ?? - "", + workspace, available: targetInstance.value.enabled, }, ...(selectionTransition === undefined ? {} : { selectionTransition }), diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts index d333aad6626bd..77af7d2680e05 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts @@ -149,23 +149,65 @@ it("continues a live turn whose session the adapter never marked running", () => assert.isUndefined(restartContinuationRun(withSessionStatus(status), now), status); }); -it("recovers an admitted continuation after another crash before provider start", () => { - const projection = makeProjection(); - const starting = { - ...projection, - runs: [ - { - ...projection.runs[0]!, - status: "starting" as const, - restartContinuationOfRunId: RunId.make("run:previous-crash"), - }, - ], - providerThreads: [{ ...projection.providerThreads[0]!, status: "idle" as const }], - providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" as const }], - providerTurns: [], - }; - assert.equal(restartContinuationRun(starting, now)?.id, runId); -}); +it.effect("recovers an admitted continuation after another crash before provider start", () => + Effect.gen(function* () { + const projection = makeProjection(); + const starting = { + ...projection, + runs: [ + { + ...projection.runs[0]!, + status: "starting" as const, + restartContinuationOfRunId: RunId.make("run:previous-crash"), + }, + ], + providerThreads: [{ ...projection.providerThreads[0]!, status: "idle" as const }], + providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" as const }], + providerTurns: [], + }; + assert.equal(restartContinuationRun(starting, now)?.id, runId); + + // Marked running, but the provider never accepted its prompt. + const running = { + ...projection, + runs: [ + { ...projection.runs[0]!, restartContinuationOfRunId: RunId.make("run:previous-crash") }, + ], + providerTurns: [], + } as unknown as OrchestrationV2ThreadProjection; + const commits: Parameters[0][] = []; + const recovery = yield* ProviderRuntimeRecovery.make.pipe( + Effect.provide( + Layer.mergeAll( + ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getRecoveryThreadIds: () => Effect.succeed([threadId]), + getRuntimeRecoveryProjection: () => Effect.succeed(running), + getThreadRecords: () => Effect.succeed(running), + }), + Layer.mock(EventSink.EventSinkV2)({ + commitCommand: (input) => + Effect.sync(() => { + commits.push(input); + return { committed: true, cancelledEffectCount: 0 } as never; + }), + }), + IdAllocator.layer, + Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}), + Layer.mock(EffectOutbox.EffectOutboxV2)({ + get: () => Effect.succeedNone, + reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }), + }), + ), + ), + ); + yield* recovery.reconcile("startup"); + assert.deepEqual( + commits.flatMap((commit) => commit.effects.map((effect) => effect.request)), + [{ type: "provider-runtime.continue", sourceRunId: runId, processLossCount: 1 }], + ); + }), +); it("does not continue settled root runs with restart-cancelled background work", () => { const projection = makeProjection(); @@ -602,20 +644,39 @@ const devServer = { work: { kind: "shell" as const, label: "vp run dev", id: "turn-item:dev-server" }, }; +const unacceptedFollowUp = { + id: RunId.make("run:follow-up"), + ordinal: 2, + activeAttemptId: RunAttemptId.make("attempt:follow-up"), + userMessageId: MessageId.make("message:follow-up"), + status: "running", + startedAt: now, +}; + it.effect.each([ - ["completed", scratchProjectId, backgroundSubagent, true], - ["waiting", ProjectId.make("restart-project"), backgroundSubagent, true], - ["completed", ProjectId.make("restart-project"), devServer, false], - ["waiting", scratchProjectId, devServer, false], + ["completed", scratchProjectId, backgroundSubagent, true, ""], + ["waiting", ProjectId.make("restart-project"), backgroundSubagent, true, ""], + ["completed", ProjectId.make("restart-project"), devServer, false, ""], + ["waiting", scratchProjectId, devServer, false, ""], + [ + "completed", + ProjectId.make("restart-project"), + backgroundSubagent, + true, + ", past a later prompt the provider never accepted", + ], ] as const)( - "cleans up background work of a %s run in project %s and wakes it only for awaited work", - ([status, projectId, background, wakes]) => + "cleans up background work of a $0 run in project $1 and wakes it only for awaited work$4", + ([status, projectId, background, wakes, followUp]) => Effect.gen(function* () { const base = makeProjection(); const projection = { ...base, thread: { ...base.thread, projectId }, - runs: [{ ...base.runs[0]!, status }], + runs: [ + { ...base.runs[0]!, status }, + ...(followUp === "" ? [] : [{ ...base.runs[0]!, ...unacceptedFollowUp }]), + ], providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }], turnItems: [background.turnItem], subagents: @@ -642,6 +703,16 @@ it.effect.each([ Layer.mock(ProjectionStore.ProjectionStoreV2)({ getRecoveryThreadIds: () => Effect.succeed([threadId]), getRuntimeRecoveryProjection: () => Effect.succeed(projection), + getThreadRecords: () => Effect.succeed(projection), + getMessagesById: () => + Effect.succeed( + new Map([ + [ + unacceptedFollowUp.userMessageId, + { id: unacceptedFollowUp.userMessageId, createdBy: "user" } as never, + ], + ]), + ), }), Layer.mock(EventSink.EventSinkV2)({ writeWithEffects: (input) => @@ -692,7 +763,9 @@ it.effect.each([ assert.equal(note?.runId, runId); assert.deepEqual(note?.payload.restartCancelledBackgroundWork, [background.work]); if (status === "completed") - assert.isFalse(events.some((event) => event.type === "run.updated")); + assert.isFalse( + events.some((event) => event.type === "run.updated" && event.runId === runId), + ); } }), ); diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index 7454c2154461b..e8db8055ab69a 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -11,7 +11,12 @@ import { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; -import type { ProjectionRuntimeRecoveryState } from "./ProjectionStore.ts"; +import type { + ProjectionRecordField, + ProjectionRecordFilter, + ProjectionRecords, + ProjectionRuntimeRecoveryState, +} from "./ProjectionStore.ts"; import * as ServerSettings from "../serverSettings.ts"; import { isNativeMaintenanceCommand } from "./CommandPolicy.ts"; @@ -36,7 +41,7 @@ const CONTINUE_PROMPT = const MAX_CONTINUATION_CHAIN = 3; const CONTINUATION_LOOP_WINDOW_MS = 5 * 60 * 1_000; -function restartContinuationBlocked( +export function restartContinuationBlocked( projection: Pick< ProjectionRuntimeRecoveryState, "thread" | "runtimeRequests" | "providerTurns" | "turnItems" @@ -84,6 +89,52 @@ function restartContinuationBlocked( ); } +/** A Stop from the user, or from the parent that delegated the task, that a restart cut short. */ +export const restartStopRequested = Effect.fn("RestartContinuation.restartStopRequested")( + function* ( + getThreadRecords: ( + threadId: ThreadId, + fields: ReadonlyArray, + filter: ProjectionRecordFilter, + ) => Effect.Effect, E>, + thread: Pick, + source: Pick, + ) { + const { turnItems } = yield* getThreadRecords(thread.id, ["turnItems"], { + turnItemRunIds: [source.id], + turnItemTypes: ["run_interrupt_request"], + }); + if (turnItems.some((item) => item.runId === source.id && item.type === "run_interrupt_request")) + return true; + const { lineage, forkedFrom } = thread; + const taskId = + source.delegatedTaskId ?? (forkedFrom?.type === "node" ? forkedFrom.nodeId : undefined); + if ( + lineage.relationshipToParent !== "subagent" || + lineage.parentThreadId === null || + taskId === undefined + ) + return false; + const task = (yield* getThreadRecords(lineage.parentThreadId, ["subagents"], { + subagentIds: [taskId], + })).subagents.find((candidate) => candidate.id === taskId); + // A settled task no longer owns later work in its thread. + if ( + task === undefined || + task.runId === null || + task.result !== null || + !isOrchestrationV2WorkActive(task.status) + ) + return false; + return ( + (yield* getThreadRecords(lineage.parentThreadId, ["turnItems"], { + turnItemTypes: ["run_interrupt_request"], + turnItemRunIds: [task.runId], + })).turnItems.length > 0 + ); + }, +); + /** App-owned delegations continue in their own threads and report back. */ function hasOpenAwaitedWork( projection: Pick, @@ -254,50 +305,10 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta }); return; } - const sourceRecords = yield* threads.getThreadRecords( - input.threadId, - ["messages", "turnItems"], - { - messageIds: [source.userMessageId], - turnItemRunIds: [source.id], - turnItemTypes: ["run_interrupt_request"], - }, - ); - if ( - sourceRecords.turnItems.some( - (item) => item.runId === source.id && item.type === "run_interrupt_request", - ) - ) - return; - // A parent's Stop reaches its open delegated tasks through an effect a restart can cut short. - const { lineage, forkedFrom } = projection.thread; - const taskId = - source.delegatedTaskId ?? (forkedFrom?.type === "node" ? forkedFrom.nodeId : undefined); - if ( - lineage.relationshipToParent === "subagent" && - lineage.parentThreadId !== null && - taskId !== undefined - ) { - const task = (yield* threads.getThreadRecords(lineage.parentThreadId, ["subagents"], { - subagentIds: [taskId], - })).subagents.find((candidate) => candidate.id === taskId); - // A settled task no longer owns later work in its thread. - const parentRunId = - task !== undefined && task.result === null && isOrchestrationV2WorkActive(task.status) - ? task.runId - : null; - if ( - parentRunId !== null && - (yield* threads.getThreadRecords(lineage.parentThreadId, ["turnItems"], { - turnItemTypes: ["run_interrupt_request"], - turnItemRunIds: [parentRunId], - })).turnItems.length > 0 - ) - return; - } - const sourceMessage = sourceRecords.messages.find( - (message) => message.id === source.userMessageId, - ); + if (yield* restartStopRequested(threads.getThreadRecords, projection.thread, source)) return; + const sourceMessage = (yield* threads.getThreadRecords(input.threadId, ["messages"], { + messageIds: [source.userMessageId], + })).messages.find((message) => message.id === source.userMessageId); if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return; const note = restartContinuationNote( source, diff --git a/apps/server/src/orchestration-v2/ThreadCommandExecutor.ts b/apps/server/src/orchestration-v2/ThreadCommandExecutor.ts index 8bd1cc38d2de2..aa9a1f1ca7ab3 100644 --- a/apps/server/src/orchestration-v2/ThreadCommandExecutor.ts +++ b/apps/server/src/orchestration-v2/ThreadCommandExecutor.ts @@ -1,11 +1,31 @@ import type { ThreadId } from "@t3tools/contracts"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Semaphore from "effect/Semaphore"; export class ThreadCommandExecutor extends Context.Service< ThreadCommandExecutor, - KeyedLock.KeyedLock + KeyedLock.KeyedLock & { + /** + * One thread deletion plans and commits at a time: each decides what its deleted fork + * sources keep for the forks still alive. Take it before any thread lock. + */ + readonly withDeletionLock: (effect: Effect.Effect) => Effect.Effect; + } >()("t3/orchestration-v2/ThreadCommandExecutor") {} -export const layer = Layer.effect(ThreadCommandExecutor, KeyedLock.make()); +export const make = Effect.gen(function* () { + const deletion = yield* Semaphore.make(1); + return ThreadCommandExecutor.of({ + ...(yield* KeyedLock.make()), + withDeletionLock: Effect.fn("ThreadCommandExecutor.withDeletionLock")(function* ( + effect: Effect.Effect, + ) { + return yield* deletion.withPermit(effect); + }), + }); +}); + +export const layer = Layer.effect(ThreadCommandExecutor, make); diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.ts index 7518705f5a5ac..399224533089d 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts @@ -1149,12 +1149,22 @@ it.layer(layerTest)("ThreadSearch.searchOlderSettled", (it) => { thread(id("elsewhere"), other, { title: "Kestrel nest", settledAt: old }), thread(id("note"), project, { title: "Unrelated", settledAt: old }), thread(id("new-note"), project, { title: "Unrelated", settledAt: at(50) }), + thread(id("archived"), project, { + title: "Kestrel nest", + settledAt: old, + archivedAt: old, + }), + thread(id("archived-note"), project, { + title: "Unrelated", + settledAt: old, + archivedAt: old, + }), ], projections.apply, { discard: true }, ); const before = DateTime.formatIso(at(30)); - const messageThreadIds = [id("new-note"), id("note"), id("old")]; + const messageThreadIds = [id("new-note"), id("note"), id("archived-note"), id("old")]; assert.sameMembers( [...(yield* search.searchOlderSettled({ query: "kestrel", before, messageThreadIds }))], [id("old"), id("elsewhere"), id("note")], diff --git a/apps/server/src/orchestration-v2/ThreadSearch.ts b/apps/server/src/orchestration-v2/ThreadSearch.ts index f01fb6b0f35eb..3ad48b26f172d 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.ts @@ -450,7 +450,7 @@ export const make = Effect.gen(function* () { INNER JOIN projection_projects AS projects ON projects.project_id = threads.project_id WHERE threads.deleted_at IS NULL - AND json_extract(threads.payload_json, '$.archivedAt') IS NULL + AND threads.archived_at IS NULL AND projects.deleted_at IS NULL AND json_extract(threads.payload_json, '$.lineage.relationshipToParent') IS NOT 'subagent' @@ -474,7 +474,7 @@ export const make = Effect.gen(function* () { FROM orchestration_v2_projection_threads AS threads WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds})) AND threads.deleted_at IS NULL - AND json_extract(threads.payload_json, '$.archivedAt') IS NULL + AND threads.archived_at IS NULL AND json_extract(threads.payload_json, '$.lineage.relationshipToParent') IS NOT 'subagent' AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1 diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index efdfe5882087c..29d58568c8d94 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -47,6 +47,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as SqlClient from "effect/sql/SqlClient"; @@ -462,6 +463,7 @@ const layerProjectDeletionTest = Layer.mergeAll( RuntimeLayer.layer.pipe(Layer.provide(RuntimeLayer.layerProjectService)), RuntimeLayer.layerProjectService, RuntimeLayer.layerEventSink, + ProjectionStore.layer, ThreadCommandExecutor.layer, ).pipe( Layer.provide( @@ -496,7 +498,7 @@ const layerProjectDeletionTest = Layer.mergeAll( Layer.provide(ServerSettings.layerTest()), Layer.provide(layerTestProviderInstanceRegistry), Layer.provide(layerGitWorkflowTest), - Layer.provide(layerPlatformTest), + Layer.provideMerge(layerPlatformTest), ); it.layer(layerProjectDeletionTest)("project deletion during thread commands", (it) => { @@ -819,6 +821,41 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i assert.isFalse(yield* fileSystem.exists(filePath(dropped))); assert.equal(yield* fileSystem.readFileString(filePath(shared)), "bytes"); + + if (fork !== "no fork") { + const laterRunId = yield* writeRun({ + name: "later", + ordinal: 3, + status: "completed", + attachments: [shared], + }); + const laterForkId = ThreadId.make(`${key}:later-fork`); + yield* orchestrator.dispatch({ + type: "thread.fork", + commandId: CommandId.make(`${key}:later-fork`), + sourceThreadId: threadId, + targetThreadId: laterForkId, + sourcePoint: { type: "run", runId: laterRunId }, + createdBy: "user", + creationSource: "web", + }); + for (const id of [threadId, laterForkId]) { + yield* orchestrator.dispatch({ + type: "thread.delete", + commandId: CommandId.make(`${key}:delete:${id}`), + threadId: id, + }); + yield* worker.drain(); + assert.equal(yield* fileSystem.readFileString(filePath(shared)), "bytes"); + } + yield* orchestrator.dispatch({ + type: "thread.delete", + commandId: CommandId.make(`${key}:delete-first-fork`), + threadId: ThreadId.make(`${key}:fork`), + }); + yield* worker.drain(); + assert.isFalse(yield* fileSystem.exists(filePath(shared))); + } }).pipe(Effect.provide(NodeServices.layer)), ); @@ -1137,6 +1174,167 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i }).pipe(Effect.ensuring(Effect.sync(() => lockSpy.mockRestore()))); }), ); + + it.effect("deleted sources keep the html_render pages any live fork shows", () => + Effect.gen(function* () { + const projects = yield* ProjectService.ProjectService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const fileSystem = yield* FileSystem.FileSystem; + const projectId = ProjectId.make("html-fork-project"); + const sourceThreadId = ThreadId.make("html-fork-source"); + const forkThreadId = ThreadId.make("html-fork-target"); + yield* projects.create({ + commandId: CommandId.make("html-fork-project"), + projectId, + title: "Page family", + workspaceRoot: "/work/html-fork", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("html-fork-create"), + threadId: sourceThreadId, + projectId, + title: "Page source", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + const inherited = yield* writeHtmlRenderRun({ + threadId: sourceThreadId, + key: "inherited", + ordinal: 1, + }); + const fork = (sourceThreadId: ThreadId, runId: RunId, targetThreadId: ThreadId) => + orchestrator.dispatch({ + type: "thread.fork", + commandId: CommandId.make(`html-fork:${targetThreadId}`), + sourceThreadId, + targetThreadId, + sourcePoint: { type: "run", runId }, + createdBy: "user", + creationSource: "web", + }); + yield* fork(sourceThreadId, inherited.runId, forkThreadId); + const forkPage = yield* writeHtmlRenderRun({ + threadId: forkThreadId, + key: "fork", + ordinal: 1, + }); + const [first, second] = [ThreadId.make("html-fork-first"), ThreadId.make("html-fork-second")]; + yield* fork(forkThreadId, forkPage.runId, first); + // Project deletion goes newest first, so it reaches `second` before `first`. + yield* TestClock.adjust("1 second"); + yield* fork(forkThreadId, forkPage.runId, second); + const firstRun = yield* writeHtmlRenderRun({ threadId: first, key: "first", ordinal: 1 }); + const later = yield* writeHtmlRenderRun({ + threadId: sourceThreadId, + key: "later", + ordinal: 2, + }); + const deleteThread = (threadId: ThreadId) => + orchestrator.dispatch({ + type: "thread.delete", + commandId: CommandId.make(`html-fork-delete:${threadId}`), + threadId, + }); + const pagesOnDisk = Effect.gen(function* () { + yield* worker.drain(); + return yield* Effect.forEach([inherited, forkPage, later], (page) => + fileSystem.exists(page.pagePath), + ); + }); + yield* deleteThread(forkThreadId); + yield* deleteThread(sourceThreadId); + assert.deepEqual(yield* pagesOnDisk, [true, true, false]); + + // `first`'s delete pauses after reading what to free. A fork of it and the project delete, + // which reaches `second`, must each wait on a lock it holds rather than decide on the same + // state; `blocked` hears each request for one. + const firstPlanned = yield* Deferred.make(); + const releaseFirst = yield* Deferred.make(); + const blocked = yield* Queue.unbounded(); + const readAttachmentIds = projections.getThreadAttachmentIds; + const attachmentSpy = vi + .spyOn(projections, "getThreadAttachmentIds") + .mockImplementation((threadId) => + threadId === first + ? readAttachmentIds(threadId).pipe( + Effect.tap(() => Deferred.succeed(firstPlanned, undefined)), + Effect.tap(() => Deferred.await(releaseFirst)), + ) + : readAttachmentIds(threadId), + ); + const deletionHeld = yield* Ref.make(false); + const requestsHeld = (held: Effect.Effect) => + Effect.all([Deferred.isDone(firstPlanned), held]).pipe( + Effect.flatMap(([planned, isHeld]) => + planned && isHeld ? Queue.offer(blocked, undefined) : Effect.void, + ), + ); + const { withLock, withDeletionLock } = executor; + const observeLock: ThreadCommandExecutor.ThreadCommandExecutor["Service"]["withLock"] = ( + key, + effect, + ) => requestsHeld(Effect.succeed(key === first)).pipe(Effect.andThen(withLock(key, effect))); + const observeDeletion: ThreadCommandExecutor.ThreadCommandExecutor["Service"]["withDeletionLock"] = + (effect) => + requestsHeld(Ref.get(deletionHeld)).pipe( + Effect.andThen( + withDeletionLock( + Ref.set(deletionHeld, true).pipe( + Effect.andThen(effect), + Effect.ensuring(Ref.set(deletionHeld, false)), + ), + ), + ), + ); + const lockSpy = vi.spyOn(executor, "withLock").mockImplementation(observeLock); + const deletionSpy = vi + .spyOn(executor, "withDeletionLock") + .mockImplementation(observeDeletion); + const forkOfDeleted = yield* Effect.gen(function* () { + const firstFiber = yield* deleteThread(first).pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.await(firstPlanned); + const forkFiber = yield* fork(first, firstRun.runId, ThreadId.make("html-fork-late")).pipe( + Effect.match({ + onSuccess: () => "created", + onFailure: (error) => ("cause" in error ? String(error.cause) : error._tag), + }), + Effect.forkChild({ startImmediately: true }), + ); + yield* Effect.raceFirst(Queue.take(blocked), Fiber.await(forkFiber)); + const projectFiber = yield* projects + .delete({ commandId: CommandId.make("html-fork-project-delete"), projectId, force: true }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.raceFirst(Queue.take(blocked), Fiber.await(projectFiber)); + yield* Deferred.succeed(releaseFirst, undefined); + yield* Fiber.join(firstFiber); + yield* Fiber.join(projectFiber); + return yield* Fiber.join(forkFiber); + }).pipe( + Effect.ensuring( + Effect.sync(() => { + lockSpy.mockRestore(); + deletionSpy.mockRestore(); + attachmentSpy.mockRestore(); + }), + ), + ); + assert.deepEqual( + { afterLastForks: yield* pagesOnDisk, forkOfDeleted }, + { afterLastForks: [false, false, false], forkOfDeleted: `Thread ${first} was deleted.` }, + ); + }), + ); }); const layerSharedApplicationDataPlaneTest = Layer.mergeAll( @@ -3017,6 +3215,11 @@ const writeHtmlRenderRun = Effect.fn("test.writeHtmlRenderRun")(function* (input const runId = RunId.make(`html-fork-run:${input.key}`); const messageId = MessageId.make(`html-fork-message:${input.key}`); const attachmentId = createAttachmentId(input.threadId, "html")!; + const fileSystem = yield* FileSystem.FileSystem; + const { attachmentsDir } = yield* ServerConfig.ServerConfig; + const pagePath = (yield* Path.Path).join(attachmentsDir, `${attachmentId}.html`); + yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true }); + yield* fileSystem.writeFileString(pagePath, "

Page

"); yield* eventSink.write({ events: [ { @@ -3098,67 +3301,10 @@ const writeHtmlRenderRun = Effect.fn("test.writeHtmlRenderRun")(function* (input }, ], }); - return { runId, attachmentId }; + return { runId, pagePath }; }); it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { - it.effect("deleting a source keeps the html_render page its live fork shows", () => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const outbox = yield* EffectOutbox.EffectOutboxV2; - const sourceThreadId = ThreadId.make("html-fork-source"); - const forkThreadId = ThreadId.make("html-fork-target"); - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make("html-fork-create"), - threadId: sourceThreadId, - projectId: ProjectId.make("html-fork-project"), - title: "Page source", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - createdBy: "user", - creationSource: "web", - }); - const inherited = yield* writeHtmlRenderRun({ - threadId: sourceThreadId, - key: "inherited", - ordinal: 1, - }); - yield* orchestrator.dispatch({ - type: "thread.fork", - commandId: CommandId.make("html-fork-fork"), - sourceThreadId, - targetThreadId: forkThreadId, - sourcePoint: { type: "run", runId: inherited.runId }, - createdBy: "user", - creationSource: "web", - }); - const later = yield* writeHtmlRenderRun({ - threadId: sourceThreadId, - key: "later", - ordinal: 2, - }); - const deleteCommandId = CommandId.make("html-fork-delete-source"); - yield* orchestrator.dispatch({ - type: "thread.delete", - commandId: deleteCommandId, - threadId: sourceThreadId, - }); - const cleaned = (yield* outbox.listByCommandId(deleteCommandId)).flatMap((effect) => - effect.request.type === "attachment.cleanup" ? effect.request.attachmentIds : [], - ); - assert.include(cleaned, later.attachmentId); - assert.notInclude( - cleaned, - inherited.attachmentId, - "deleted a page its live fork still shows", - ); - }), - ); - it.effect("applies lifecycle commands idempotently and emits archive/removal shell deltas", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -7997,6 +8143,15 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { yield* witness.end("active", "completed"); assert.equal(yield* Queue.take(witness.startedRunIds), (yield* witness.runFor("queued")).id); assert.isTrue((yield* dispatcher.runFor("issue")).queueHeld); + const resume = yield* orchestrator + .dispatch({ + type: "queue.resume", + commandId: CommandId.make(`${dispatcherId}:resume`), + threadId: dispatcherId, + }) + .pipe(Effect.flip); + assert.include(String(resume.cause), "Retry worktree setup"); + assert.isTrue((yield* dispatcher.runFor("issue")).queueHeld); }), ); @@ -9584,6 +9739,24 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { occurredAt: yield* DateTime.now, payload: { ...source, status: "running", startedAt: yield* DateTime.now }, }, + { + id: EventId.make(`${threadId}:accepted`), + type: "provider-turn.updated", + threadId, + runId: source.id, + occurredAt: yield* DateTime.now, + payload: { + id: ProviderTurnId.make(`${threadId}:turn`), + providerThreadId: source.providerThreadId!, + nodeId: source.rootNodeId!, + runAttemptId: source.activeAttemptId, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt: yield* DateTime.now, + completedAt: null, + }, + }, ], }); } @@ -9705,6 +9878,122 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect.each(["startup", "shutdown"] as const)( + "sends a delegated task's prompt again after a %s cut it before the provider accepted it", + (trigger) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const recovery = yield* ProviderRuntimeRecoveryService.ProviderRuntimeRecoveryService; + const outbox = yield* EffectOutbox.EffectOutboxV2; + const parentThreadId = ThreadId.make(`delegate-resend-${trigger}`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${parentThreadId}:create`), + threadId: parentThreadId, + projectId: ProjectId.make(`${parentThreadId}:project`), + title: "Delegating parent", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${parentThreadId}:message`), + threadId: parentThreadId, + messageId: MessageId.make(`${parentThreadId}:message`), + text: "Delegate a review", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!; + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make(`${parentThreadId}:delegate`), + parentThreadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Review the diff", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + completionWake: "always", + createdBy: "agent", + creationSource: "mcp", + }); + const threadId = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]! + .childThreadId!; + const before = yield* orchestrator.getThreadProjection(threadId); + const run = before.runs[0]!; + const attempt = before.attempts.find((row) => row.id === run.activeAttemptId)!; + const rootNode = before.nodes.find((row) => row.id === run.rootNodeId)!; + // What a provider turn start commits before the provider accepts the prompt. + const startedAt = yield* DateTime.now; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make(`${threadId}:running:run`), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: startedAt, + payload: { ...run, status: "running", startedAt }, + }, + { + id: EventId.make(`${threadId}:running:attempt`), + type: "run-attempt.updated", + threadId, + runId: run.id, + nodeId: rootNode.id, + occurredAt: startedAt, + payload: { ...attempt, status: "running", startedAt }, + }, + { + id: EventId.make(`${threadId}:running:node`), + type: "node.updated", + threadId, + runId: run.id, + nodeId: rootNode.id, + occurredAt: startedAt, + payload: { ...rootNode, status: "running", startedAt }, + }, + ], + }); + const expectResent = Effect.gen(function* () { + const child = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + child.runs.map((row) => [row.id, row.status, row.startedAt]), + [[run.id, "starting", null]], + ); + assert.deepEqual(child.messages, before.messages); + const starts = yield* outbox.listByCommandId( + CommandId.make(`command:restart-resend:${run.id}`), + ); + assert.deepEqual( + starts.filter((effect) => effect.status === "pending").map((effect) => effect.request), + [{ type: "provider-turn.start", runId: run.id }], + ); + }); + yield* recovery.reconcile(trigger); + yield* expectResent; + // The server stops again before the worker sent the prompt. + yield* TestClock.adjust("1 second"); + yield* recovery.reconcile("startup"); + yield* orchestrator.recoverDelegatedTasks; + yield* expectResent; + assert.deepInclude((yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0], { + status: "running", + result: null, + }); + }), + ); + it.effect("starts a provider wake queued beside a held queue", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -11853,6 +12142,24 @@ it.layer(layerTest)("usage-limit recovery", (it) => { occurredAt: startedAt, payload: { ...continuation, status: "running", startedAt }, }, + { + id: EventId.make("recovery:continuation-accepted:resume-started"), + type: "provider-turn.updated", + threadId, + runId: continuation.id, + occurredAt: startedAt, + payload: { + id: ProviderTurnId.make("recovery:continuation-turn:resume-started"), + providerThreadId: continuation.providerThreadId!, + nodeId: continuation.rootNodeId!, + runAttemptId: continuation.activeAttemptId, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt, + completedAt: null, + }, + }, ], }); } diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index f07d942cbac2f..edc12dcd98840 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -603,7 +603,7 @@ describe("orchestration v2 provider switching", () => { : scenario === "large-current-input" || priorImages || exhaustedTarget ? { getModelContextWindow: () => - scenario.includes("target-tight") ? 25_121 : 32_000, + scenario.includes("target-tight") ? 18_241 : 32_000, } : {}), ...(scenario.endsWith("-native") || scenario === "large-current-input" diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_monitor_wake/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_monitor_wake/output.ts index dc8a8c5b4ee25..6c11f179dd4e0 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_monitor_wake/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_monitor_wake/output.ts @@ -44,6 +44,7 @@ export function assertClaudeBackgroundMonitorWakeOutput( taskId: MONITOR_TASK_ID, description: "Background monitor test", kind: "monitor", + awaited: true, nativeItemId: "toolu_019b4EUbhEcYP4TS7vZn27N1", command: "sleep 8 && echo MONITOR_DONE", itemId: monitorItem?.id, diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/fx_early_stop/fx_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/fx_early_stop/fx_transcript.ndjson index 443a33b13ca30..f1d868c622672 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/fx_early_stop/fx_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/fx_early_stop/fx_transcript.ndjson @@ -1,7 +1,7 @@ {"type":"transcript_start","provider":"fx","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"fx_early_stop","metadata":{"generatedBy":"live-fx-recorder","fxVersion":"0.0.13","normalization":"Session ids are fx-session-NN, the workspace is , HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are . User skill names, emails and token-shaped strings are removed. Timestamps are kept as recorded.","droppedFrames":0}} {"type":"expect_outbound","label":"request:initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"","capabilities":"","clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"session":{"notices":{},"compaction":{}},"elicitation":{"form":{}}},"clientInfo":""}}} {"type":"emit_inbound","label":"response:initialize","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":true,"audio":false,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":true,"acp":true},"sessionCapabilities":{"list":{},"resume":{},"close":{},"systemPrompt":{}},"_meta":{"fx":{"steering":true}}},"agentInfo":{"name":"fx","title":"fx","version":"0.0.13"},"authMethods":[]}}} -{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","_meta":{"fx":{"profileMcpServers":true}},"mcpServers":""}}} {"type":"emit_inbound","label":"response:session/new","frame":{"kind":"response","method":"session/new","result":{"sessionId":"fx-session-01","configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"gateway","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"anthropic/claude-opus-5.5","options":[{"value":"anthropic/claude-sonnet-5.5","name":"anthropic/claude-sonnet-5.5"},{"value":"anthropic/claude-opus-5.5","name":"anthropic/claude-opus-5.5"},{"value":"anthropic/claude-opus-5.5-fast","name":"anthropic/claude-opus-5.5-fast"},{"value":"anthropic/claude-opus-5","name":"anthropic/claude-opus-5"},{"value":"anthropic/claude-opus-5-fast","name":"anthropic/claude-opus-5-fast"},{"value":"anthropic/claude-sonnet-5","name":"anthropic/claude-sonnet-5"},{"value":"anthropic/claude-opus-4.8","name":"anthropic/claude-opus-4.8"},{"value":"anthropic/claude-opus-4.8-fast","name":"anthropic/claude-opus-4.8-fast"},{"value":"anthropic/claude-opus-4.7","name":"anthropic/claude-opus-4.7"},{"value":"anthropic/claude-sonnet-4.6","name":"anthropic/claude-sonnet-4.6"},{"value":"anthropic/claude-opus-4.6","name":"anthropic/claude-opus-4.6"},{"value":"anthropic/claude-opus-4.5","name":"anthropic/claude-opus-4.5"},{"value":"anthropic/claude-sonnet-4.5","name":"anthropic/claude-sonnet-4.5"},{"value":"anthropic/claude-opus-4","name":"anthropic/claude-opus-4"},{"value":"anthropic/claude-sonnet-4","name":"anthropic/claude-sonnet-4"},{"value":"openai/gpt-5.6-luna","name":"openai/gpt-5.6-luna"},{"value":"openai/gpt-5.6-luna-fast","name":"openai/gpt-5.6-luna-fast"},{"value":"openai/gpt-5.6-sol","name":"openai/gpt-5.6-sol"},{"value":"openai/gpt-5.6-sol-fast","name":"openai/gpt-5.6-sol-fast"},{"value":"openai/gpt-5.6-terra","name":"openai/gpt-5.6-terra"},{"value":"openai/gpt-5.6-terra-fast","name":"openai/gpt-5.6-terra-fast"},{"value":"openai/gpt-5.5","name":"openai/gpt-5.5"},{"value":"openai/gpt-5.5-fast","name":"openai/gpt-5.5-fast"},{"value":"openai/gpt-5.5-pro","name":"openai/gpt-5.5-pro"},{"value":"openai/gpt-5.4-nano","name":"openai/gpt-5.4-nano"},{"value":"openai/gpt-5.4","name":"openai/gpt-5.4"},{"value":"openai/gpt-5.4-fast","name":"openai/gpt-5.4-fast"},{"value":"openai/gpt-5.4-pro","name":"openai/gpt-5.4-pro"},{"value":"openai/gpt-5.3-codex","name":"openai/gpt-5.3-codex"},{"value":"openai/gpt-5.3-codex-fast","name":"openai/gpt-5.3-codex-fast"},{"value":"openai/gpt-5.2","name":"openai/gpt-5.2"},{"value":"openai/gpt-5.2-fast","name":"openai/gpt-5.2-fast"},{"value":"openai/gpt-5.2-pro","name":"openai/gpt-5.2-pro"},{"value":"openai/gpt-5.1-thinking","name":"openai/gpt-5.1-thinking"},{"value":"openai/gpt-5.1-thinking-fast","name":"openai/gpt-5.1-thinking-fast"},{"value":"openai/gpt-5-pro","name":"openai/gpt-5-pro"},{"value":"openai/gpt-5","name":"openai/gpt-5"},{"value":"openai/gpt-5-fast","name":"openai/gpt-5-fast"},{"value":"openai/gpt-5-nano","name":"openai/gpt-5-nano"},{"value":"openai/o3-pro","name":"openai/o3-pro"},{"value":"openai/o3","name":"openai/o3"},{"value":"openai/o3-fast","name":"openai/o3-fast"},{"value":"openai/o1","name":"openai/o1"},{"value":"deepseek/deepseek-v4-pro-0813","name":"deepseek/deepseek-v4-pro-0813"},{"value":"deepseek/deepseek-v4-pro","name":"deepseek/deepseek-v4-pro"},{"value":"spacexai/grok-4.7","name":"spacexai/grok-4.7"},{"value":"spacexai/grok-4.6","name":"spacexai/grok-4.6"},{"value":"spacexai/grok-4.5","name":"spacexai/grok-4.5"},{"value":"spacexai/grok-4.3","name":"spacexai/grok-4.3"},{"value":"spacexai/grok-4.20-multi-agent","name":"spacexai/grok-4.20-multi-agent"},{"value":"spacexai/grok-4.20-non-reasoning","name":"spacexai/grok-4.20-non-reasoning"},{"value":"spacexai/grok-4.20-reasoning","name":"spacexai/grok-4.20-reasoning"},{"value":"spacexai/grok-4.1-fast-non-reasoning","name":"spacexai/grok-4.1-fast-non-reasoning"},{"value":"spacexai/grok-4.1-fast-reasoning","name":"spacexai/grok-4.1-fast-reasoning"},{"value":"amazon/nova-pro","name":"amazon/nova-pro"},{"value":"anthropic/claude-fable-5.1","name":"anthropic/claude-fable-5.1"},{"value":"anthropic/claude-fable-5","name":"anthropic/claude-fable-5"},{"value":"openai/gpt-6.1-sol","name":"openai/gpt-6.1-sol"},{"value":"openai/gpt-6.1-sol-fast","name":"openai/gpt-6.1-sol-fast"},{"value":"openai/gpt-6-luna","name":"openai/gpt-6-luna"},{"value":"openai/gpt-6-luna-fast","name":"openai/gpt-6-luna-fast"},{"value":"openai/gpt-6-sol","name":"openai/gpt-6-sol"},{"value":"openai/gpt-6-sol-fast","name":"openai/gpt-6-sol-fast"},{"value":"openai/gpt-6-astra","name":"openai/gpt-6-astra"},{"value":"openai/gpt-6-astra-fast","name":"openai/gpt-6-astra-fast"},{"value":"openai/gpt-oss-safeguard-120b","name":"openai/gpt-oss-safeguard-120b"},{"value":"openai/gpt-oss-safeguard-20b","name":"openai/gpt-oss-safeguard-20b"},{"value":"openai/gpt-oss-120b","name":"openai/gpt-oss-120b"},{"value":"openai/gpt-oss-20b","name":"openai/gpt-oss-20b"},{"value":"openai/gpt-4.1","name":"openai/gpt-4.1"},{"value":"openai/gpt-4.1-fast","name":"openai/gpt-4.1-fast"},{"value":"openai/gpt-4.1-nano","name":"openai/gpt-4.1-nano"},{"value":"openai/gpt-4.1-nano-fast","name":"openai/gpt-4.1-nano-fast"},{"value":"openai/gpt-4o","name":"openai/gpt-4o"},{"value":"openai/gpt-4o-fast","name":"openai/gpt-4o-fast"},{"value":"openai/gpt-4-turbo","name":"openai/gpt-4-turbo"},{"value":"openai/gpt-3.5-turbo","name":"openai/gpt-3.5-turbo"},{"value":"google/gemma-4-26b-a4b-it","name":"google/gemma-4-26b-a4b-it"},{"value":"deepseek/deepseek-v3.2","name":"deepseek/deepseek-v3.2"},{"value":"deepseek/deepseek-v3.2-thinking","name":"deepseek/deepseek-v3.2-thinking"},{"value":"deepseek/deepseek-r1","name":"deepseek/deepseek-r1"},{"value":"meta/llama-4-maverick","name":"meta/llama-4-maverick"},{"value":"meta/llama-4-scout","name":"meta/llama-4-scout"},{"value":"meta/llama-3.3-70b","name":"meta/llama-3.3-70b"},{"value":"meta/llama-3.1-70b","name":"meta/llama-3.1-70b"},{"value":"meta/llama-3.1-8b","name":"meta/llama-3.1-8b"},{"value":"alibaba/qwen3.8-2.4t-a95b","name":"alibaba/qwen3.8-2.4t-a95b"},{"value":"alibaba/qwen3.8-max","name":"alibaba/qwen3.8-max"},{"value":"alibaba/qwen3-next-80b-a3b-instruct","name":"alibaba/qwen3-next-80b-a3b-instruct"},{"value":"alibaba/qwen3-next-80b-a3b-thinking","name":"alibaba/qwen3-next-80b-a3b-thinking"},{"value":"alibaba/qwen3-coder-30b-a3b","name":"alibaba/qwen3-coder-30b-a3b"},{"value":"alibaba/qwen3-coder","name":"alibaba/qwen3-coder"},{"value":"alibaba/qwen3-coder-next","name":"alibaba/qwen3-coder-next"},{"value":"alibaba/qwen-3-235b","name":"alibaba/qwen-3-235b"},{"value":"alibaba/qwen-3-32b","name":"alibaba/qwen-3-32b"},{"value":"fireworks/ember-1","name":"fireworks/ember-1"},{"value":"zai/glm-5.3-fast","name":"zai/glm-5.3-fast"},{"value":"zai/glm-5.3","name":"zai/glm-5.3"},{"value":"nvidia/nemotron-3.5-lightning","name":"nvidia/nemotron-3.5-lightning"},{"value":"moonshotai/kimi-k3-fast","name":"moonshotai/kimi-k3-fast"},{"value":"moonshotai/kimi-k3","name":"moonshotai/kimi-k3"},{"value":"zai/glm-5.2-fast","name":"zai/glm-5.2-fast"},{"value":"zai/glm-5.2","name":"zai/glm-5.2"},{"value":"nvidia/nemotron-3-ultra-550b-a55b","name":"nvidia/nemotron-3-ultra-550b-a55b"},{"value":"spacexai/grok-build-0.1","name":"spacexai/grok-build-0.1"},{"value":"nvidia/nemotron-3-super-120b-a12b","name":"nvidia/nemotron-3-super-120b-a12b"},{"value":"zai/glm-5","name":"zai/glm-5"},{"value":"moonshotai/kimi-k2.5","name":"moonshotai/kimi-k2.5"},{"value":"zai/glm-4.7","name":"zai/glm-4.7"},{"value":"nvidia/nemotron-nano-12b-v2-vl","name":"nvidia/nemotron-nano-12b-v2-vl"},{"value":"nvidia/nemotron-nano-9b-v2","name":"nvidia/nemotron-nano-9b-v2"},{"value":"amazon/nova-micro","name":"amazon/nova-micro"},{"value":"deepseek/deepseek-v4.1-flash","name":"deepseek/deepseek-v4.1-flash"},{"value":"deepseek/deepseek-v4-flash","name":"deepseek/deepseek-v4-flash"},{"value":"deepseek/deepseek-v4-flash-0731","name":"deepseek/deepseek-v4-flash-0731"},{"value":"zai/glm-5.3-flash","name":"zai/glm-5.3-flash"},{"value":"zai/glm-4.7-flash","name":"zai/glm-4.7-flash"},{"value":"anthropic/claude-haiku-5.5","name":"anthropic/claude-haiku-5.5"},{"value":"anthropic/claude-haiku-4.5","name":"anthropic/claude-haiku-4.5"},{"value":"anthropic/claude-3-haiku","name":"anthropic/claude-3-haiku"},{"value":"openai/gpt-5.4-mini","name":"openai/gpt-5.4-mini"},{"value":"openai/gpt-5.4-mini-fast","name":"openai/gpt-5.4-mini-fast"},{"value":"openai/gpt-5-mini","name":"openai/gpt-5-mini"},{"value":"openai/gpt-5-mini-fast","name":"openai/gpt-5-mini-fast"},{"value":"openai/gpt-4.1-mini","name":"openai/gpt-4.1-mini"},{"value":"openai/gpt-4.1-mini-fast","name":"openai/gpt-4.1-mini-fast"},{"value":"openai/o4-mini","name":"openai/o4-mini"},{"value":"openai/o4-mini-fast","name":"openai/o4-mini-fast"},{"value":"openai/o3-mini","name":"openai/o3-mini"},{"value":"openai/gpt-4o-mini","name":"openai/gpt-4o-mini"},{"value":"openai/gpt-4o-mini-fast","name":"openai/gpt-4o-mini-fast"},{"value":"google/gemini-3.8-flash","name":"google/gemini-3.8-flash"},{"value":"google/gemini-3.7-flash","name":"google/gemini-3.7-flash"},{"value":"google/gemini-3.5-flash-lite","name":"google/gemini-3.5-flash-lite"},{"value":"google/gemini-3.6-flash","name":"google/gemini-3.6-flash"},{"value":"google/gemini-3.5-flash","name":"google/gemini-3.5-flash"},{"value":"google/gemini-3.1-flash-lite","name":"google/gemini-3.1-flash-lite"},{"value":"google/gemini-3-flash","name":"google/gemini-3-flash"},{"value":"google/gemini-2.5-flash-lite","name":"google/gemini-2.5-flash-lite"},{"value":"google/gemini-2.5-flash","name":"google/gemini-2.5-flash"},{"value":"google/gemini-2.5-pro","name":"google/gemini-2.5-pro"},{"value":"minimax/minimax-m3","name":"minimax/minimax-m3"},{"value":"minimax/minimax-m2.5","name":"minimax/minimax-m2.5"},{"value":"minimax/minimax-m2.1","name":"minimax/minimax-m2.1"},{"value":"amazon/nova-2-lite","name":"amazon/nova-2-lite"},{"value":"amazon/nova-lite","name":"amazon/nova-lite"},{"value":"google/gemini-3.1-pro-preview","name":"google/gemini-3.1-pro-preview"},{"value":"spacexai/grok-4.20-multi-agent-beta","name":"spacexai/grok-4.20-multi-agent-beta"},{"value":"spacexai/grok-4.20-non-reasoning-beta","name":"spacexai/grok-4.20-non-reasoning-beta"},{"value":"spacexai/grok-4.20-reasoning-beta","name":"spacexai/grok-4.20-reasoning-beta"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"code","name":"Code","description":"Write and modify code with full tool access","permissionMode":"auto"},{"value":"ask","name":"Ask","description":"Request permission before making any changes","permissionMode":"ask"}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"xhigh","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"code","name":"Code","description":"Write and modify code with full tool access"},{"id":"ask","name":"Ask","description":"Request permission before making any changes"}]}}}} {"type":"emit_inbound","label":"notification:session/update:available_commands_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}} {"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"effort","value":"medium"}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/fx_subagent/fx_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/fx_subagent/fx_transcript.ndjson index 99ce6d8a0b7ba..964a666072aca 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/fx_subagent/fx_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/fx_subagent/fx_transcript.ndjson @@ -1,7 +1,7 @@ {"type":"transcript_start","provider":"fx","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"fx_subagent","metadata":{"generatedBy":"live-fx-recorder","fxVersion":"0.0.14","normalization":"Session ids are fx-session-NN, the workspace is , HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are . User skill names, emails and token-shaped strings are removed. Timestamps are kept as recorded.","droppedFrames":0}} {"type":"expect_outbound","label":"request:initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"","capabilities":"","clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"session":{"notices":{},"compaction":{}},"elicitation":{"form":{}}},"clientInfo":""}}} {"type":"emit_inbound","label":"response:initialize","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":true,"audio":false,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":true,"acp":true},"sessionCapabilities":{"list":{},"resume":{},"close":{},"systemPrompt":{}},"_meta":{"fx":{"steering":true}}},"agentInfo":{"name":"fx","title":"fx","version":"0.0.14"},"authMethods":[]}}} -{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","_meta":{"fx":{"profileMcpServers":true}},"mcpServers":""}}} {"type":"emit_inbound","label":"response:session/new","frame":{"kind":"response","method":"session/new","result":{"sessionId":"fx-session-01","configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"gateway","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"openai/gpt-5.2","options":[{"value":"anthropic/claude-sonnet-5.5","name":"anthropic/claude-sonnet-5.5"},{"value":"anthropic/claude-opus-5.5","name":"anthropic/claude-opus-5.5"},{"value":"anthropic/claude-opus-5.5-fast","name":"anthropic/claude-opus-5.5-fast"},{"value":"anthropic/claude-opus-5","name":"anthropic/claude-opus-5"},{"value":"anthropic/claude-opus-5-fast","name":"anthropic/claude-opus-5-fast"},{"value":"anthropic/claude-sonnet-5","name":"anthropic/claude-sonnet-5"},{"value":"anthropic/claude-opus-4.8","name":"anthropic/claude-opus-4.8"},{"value":"anthropic/claude-opus-4.8-fast","name":"anthropic/claude-opus-4.8-fast"},{"value":"anthropic/claude-opus-4.7","name":"anthropic/claude-opus-4.7"},{"value":"anthropic/claude-sonnet-4.6","name":"anthropic/claude-sonnet-4.6"},{"value":"anthropic/claude-opus-4.6","name":"anthropic/claude-opus-4.6"},{"value":"anthropic/claude-opus-4.5","name":"anthropic/claude-opus-4.5"},{"value":"anthropic/claude-sonnet-4.5","name":"anthropic/claude-sonnet-4.5"},{"value":"openai/gpt-5.6-luna","name":"openai/gpt-5.6-luna"},{"value":"openai/gpt-5.6-luna-fast","name":"openai/gpt-5.6-luna-fast"},{"value":"openai/gpt-5.6-sol","name":"openai/gpt-5.6-sol"},{"value":"openai/gpt-5.6-sol-fast","name":"openai/gpt-5.6-sol-fast"},{"value":"openai/gpt-5.6-terra","name":"openai/gpt-5.6-terra"},{"value":"openai/gpt-5.6-terra-fast","name":"openai/gpt-5.6-terra-fast"},{"value":"openai/gpt-5.5","name":"openai/gpt-5.5"},{"value":"openai/gpt-5.5-fast","name":"openai/gpt-5.5-fast"},{"value":"openai/gpt-5.5-pro","name":"openai/gpt-5.5-pro"},{"value":"openai/gpt-5.4-nano","name":"openai/gpt-5.4-nano"},{"value":"openai/gpt-5.4","name":"openai/gpt-5.4"},{"value":"openai/gpt-5.4-fast","name":"openai/gpt-5.4-fast"},{"value":"openai/gpt-5.4-pro","name":"openai/gpt-5.4-pro"},{"value":"openai/gpt-5.3-codex","name":"openai/gpt-5.3-codex"},{"value":"openai/gpt-5.3-codex-fast","name":"openai/gpt-5.3-codex-fast"},{"value":"openai/gpt-5.2-codex","name":"openai/gpt-5.2-codex"},{"value":"openai/gpt-5.2","name":"openai/gpt-5.2"},{"value":"openai/gpt-5.2-fast","name":"openai/gpt-5.2-fast"},{"value":"openai/gpt-5.2-pro","name":"openai/gpt-5.2-pro"},{"value":"openai/gpt-5.1-codex-max","name":"openai/gpt-5.1-codex-max"},{"value":"openai/gpt-5.1-codex","name":"openai/gpt-5.1-codex"},{"value":"openai/gpt-5.1-thinking","name":"openai/gpt-5.1-thinking"},{"value":"openai/gpt-5.1-thinking-fast","name":"openai/gpt-5.1-thinking-fast"},{"value":"openai/gpt-5-pro","name":"openai/gpt-5-pro"},{"value":"openai/gpt-5-codex","name":"openai/gpt-5-codex"},{"value":"openai/gpt-5","name":"openai/gpt-5"},{"value":"openai/gpt-5-fast","name":"openai/gpt-5-fast"},{"value":"openai/gpt-5-nano","name":"openai/gpt-5-nano"},{"value":"openai/o3-pro","name":"openai/o3-pro"},{"value":"openai/o3","name":"openai/o3"},{"value":"openai/o3-fast","name":"openai/o3-fast"},{"value":"openai/o1","name":"openai/o1"},{"value":"deepseek/deepseek-v4-pro-0813","name":"deepseek/deepseek-v4-pro-0813"},{"value":"deepseek/deepseek-v4-pro","name":"deepseek/deepseek-v4-pro"},{"value":"moonshotai/kimi-k3.1-pro","name":"moonshotai/kimi-k3.1-pro"},{"value":"moonshotai/kimi-k3.1-pro-highspeed","name":"moonshotai/kimi-k3.1-pro-highspeed"},{"value":"spacexai/grok-4.7","name":"spacexai/grok-4.7"},{"value":"xiaomi/mimo-v2.6-pro","name":"xiaomi/mimo-v2.6-pro"},{"value":"xiaomi/mimo-v2.6-pro-ultraspeed","name":"xiaomi/mimo-v2.6-pro-ultraspeed"},{"value":"spacexai/grok-4.6","name":"spacexai/grok-4.6"},{"value":"spacexai/grok-4.5","name":"spacexai/grok-4.5"},{"value":"spacexai/grok-4.3","name":"spacexai/grok-4.3"},{"value":"xiaomi/mimo-v2.5-pro","name":"xiaomi/mimo-v2.5-pro"},{"value":"spacexai/grok-4.20-multi-agent","name":"spacexai/grok-4.20-multi-agent"},{"value":"spacexai/grok-4.20-non-reasoning","name":"spacexai/grok-4.20-non-reasoning"},{"value":"spacexai/grok-4.20-reasoning","name":"spacexai/grok-4.20-reasoning"},{"value":"amazon/nova-pro","name":"amazon/nova-pro"},{"value":"anthropic/claude-fable-5.1","name":"anthropic/claude-fable-5.1"},{"value":"anthropic/claude-fable-5","name":"anthropic/claude-fable-5"},{"value":"openai/gpt-6.1-terra","name":"openai/gpt-6.1-terra"},{"value":"openai/gpt-6.1-terra-fast","name":"openai/gpt-6.1-terra-fast"},{"value":"openai/gpt-6.1-sol","name":"openai/gpt-6.1-sol"},{"value":"openai/gpt-6.1-sol-fast","name":"openai/gpt-6.1-sol-fast"},{"value":"openai/gpt-6-luna","name":"openai/gpt-6-luna"},{"value":"openai/gpt-6-luna-fast","name":"openai/gpt-6-luna-fast"},{"value":"openai/gpt-6-sol","name":"openai/gpt-6-sol"},{"value":"openai/gpt-6-sol-fast","name":"openai/gpt-6-sol-fast"},{"value":"openai/gpt-6-astra","name":"openai/gpt-6-astra"},{"value":"openai/gpt-6-astra-fast","name":"openai/gpt-6-astra-fast"},{"value":"openai/gpt-oss-safeguard-120b","name":"openai/gpt-oss-safeguard-120b"},{"value":"openai/gpt-oss-safeguard-20b","name":"openai/gpt-oss-safeguard-20b"},{"value":"openai/gpt-oss-120b","name":"openai/gpt-oss-120b"},{"value":"openai/gpt-oss-20b","name":"openai/gpt-oss-20b"},{"value":"openai/gpt-4.1","name":"openai/gpt-4.1"},{"value":"openai/gpt-4.1-fast","name":"openai/gpt-4.1-fast"},{"value":"openai/gpt-4.1-nano","name":"openai/gpt-4.1-nano"},{"value":"openai/gpt-4o","name":"openai/gpt-4o"},{"value":"openai/gpt-4o-fast","name":"openai/gpt-4o-fast"},{"value":"google/gemma-4-26b-a4b-it","name":"google/gemma-4-26b-a4b-it"},{"value":"google/gemma-4-31b-it","name":"google/gemma-4-31b-it"},{"value":"deepseek/deepseek-v3.2","name":"deepseek/deepseek-v3.2"},{"value":"deepseek/deepseek-v3.2-thinking","name":"deepseek/deepseek-v3.2-thinking"},{"value":"deepseek/deepseek-v3.1","name":"deepseek/deepseek-v3.1"},{"value":"deepseek/deepseek-r1","name":"deepseek/deepseek-r1"},{"value":"meta/muse-spark-open","name":"meta/muse-spark-open"},{"value":"meta/muse-wonder-1.0","name":"meta/muse-wonder-1.0"},{"value":"meta/muse-spark-1.3","name":"meta/muse-spark-1.3"},{"value":"meta/muse-spark-1.3-contributor","name":"meta/muse-spark-1.3-contributor"},{"value":"meta/muse-glimmer-30b","name":"meta/muse-glimmer-30b"},{"value":"meta/muse-spark-1.2","name":"meta/muse-spark-1.2"},{"value":"meta/muse-spark-1.2-contributor","name":"meta/muse-spark-1.2-contributor"},{"value":"meta/muse-spark-1.1","name":"meta/muse-spark-1.1"},{"value":"meta/llama-4-maverick","name":"meta/llama-4-maverick"},{"value":"meta/llama-4-scout","name":"meta/llama-4-scout"},{"value":"meta/llama-3.3-70b","name":"meta/llama-3.3-70b"},{"value":"meta/llama-3.1-70b","name":"meta/llama-3.1-70b"},{"value":"meta/llama-3.1-8b","name":"meta/llama-3.1-8b"},{"value":"mistral/mistral-large-4","name":"mistral/mistral-large-4"},{"value":"mistral/mistral-medium-3.5","name":"mistral/mistral-medium-3.5"},{"value":"mistral/mistral-large-3","name":"mistral/mistral-large-3"},{"value":"mistral/mistral-small","name":"mistral/mistral-small"},{"value":"mistral/mistral-nemo","name":"mistral/mistral-nemo"},{"value":"mistral/codestral","name":"mistral/codestral"},{"value":"alibaba/qwen3.8-max-prime","name":"alibaba/qwen3.8-max-prime"},{"value":"alibaba/qwen3.8-max-0902","name":"alibaba/qwen3.8-max-0902"},{"value":"alibaba/qwen3.8-27b","name":"alibaba/qwen3.8-27b"},{"value":"alibaba/qwen3.8-2.4t-a95b","name":"alibaba/qwen3.8-2.4t-a95b"},{"value":"alibaba/qwen3.8-max","name":"alibaba/qwen3.8-max"},{"value":"alibaba/qwen3.7-plus","name":"alibaba/qwen3.7-plus"},{"value":"alibaba/qwen3.7-max","name":"alibaba/qwen3.7-max"},{"value":"alibaba/qwen3.6-27b","name":"alibaba/qwen3.6-27b"},{"value":"alibaba/qwen3.6-plus","name":"alibaba/qwen3.6-plus"},{"value":"alibaba/qwen3.5-plus","name":"alibaba/qwen3.5-plus"},{"value":"alibaba/qwen3-max-thinking","name":"alibaba/qwen3-max-thinking"},{"value":"alibaba/qwen3-vl-instruct","name":"alibaba/qwen3-vl-instruct"},{"value":"alibaba/qwen3-next-80b-a3b-instruct","name":"alibaba/qwen3-next-80b-a3b-instruct"},{"value":"alibaba/qwen3-next-80b-a3b-thinking","name":"alibaba/qwen3-next-80b-a3b-thinking"},{"value":"alibaba/qwen3-coder-30b-a3b","name":"alibaba/qwen3-coder-30b-a3b"},{"value":"alibaba/qwen3-coder","name":"alibaba/qwen3-coder"},{"value":"alibaba/qwen3-coder-next","name":"alibaba/qwen3-coder-next"},{"value":"alibaba/qwen-3-14b","name":"alibaba/qwen-3-14b"},{"value":"alibaba/qwen-3-235b","name":"alibaba/qwen-3-235b"},{"value":"alibaba/qwen-3-30b","name":"alibaba/qwen-3-30b"},{"value":"alibaba/qwen-3-32b","name":"alibaba/qwen-3-32b"},{"value":"inception/mercury-3","name":"inception/mercury-3"},{"value":"reflection/beam","name":"reflection/beam"},{"value":"reflection/beam-free","name":"reflection/beam-free"},{"value":"nvidia/nemotron-3.5-super-vl","name":"nvidia/nemotron-3.5-super-vl"},{"value":"nvidia/nemotron-3.5-lightning-free","name":"nvidia/nemotron-3.5-lightning-free"},{"value":"liquid/lfm2.5-24b-a2b","name":"liquid/lfm2.5-24b-a2b"},{"value":"callstack/apex","name":"callstack/apex"},{"value":"stealth/glyph-cluster","name":"stealth/glyph-cluster"},{"value":"fireworks/ember-1","name":"fireworks/ember-1"},{"value":"sakana/fugu-max","name":"sakana/fugu-max"},{"value":"sakana/fugu-ultra-v2","name":"sakana/fugu-ultra-v2"},{"value":"inception/mercury-2.5","name":"inception/mercury-2.5"},{"value":"zai/glm-5.3-fast","name":"zai/glm-5.3-fast"},{"value":"zai/glm-5.3","name":"zai/glm-5.3"},{"value":"mixedbread/toast-1","name":"mixedbread/toast-1"},{"value":"nvidia/nemotron-3.5-lightning","name":"nvidia/nemotron-3.5-lightning"},{"value":"sakana/namazu","name":"sakana/namazu"},{"value":"thinkingmachines/inkling-small","name":"thinkingmachines/inkling-small"},{"value":"moonshotai/kimi-k3-fast","name":"moonshotai/kimi-k3-fast"},{"value":"poolside/laguna-s-2.1-free","name":"poolside/laguna-s-2.1-free"},{"value":"poolside/laguna-s-2.1","name":"poolside/laguna-s-2.1"},{"value":"moonshotai/kimi-k3","name":"moonshotai/kimi-k3"},{"value":"thinkingmachines/inkling","name":"thinkingmachines/inkling"},{"value":"tencent/hy3","name":"tencent/hy3"},{"value":"bytedance/seed-2.1-turbo","name":"bytedance/seed-2.1-turbo"},{"value":"zai/glm-5.2-fast","name":"zai/glm-5.2-fast"},{"value":"sakana/fugu-ultra","name":"sakana/fugu-ultra"},{"value":"zai/glm-5.2","name":"zai/glm-5.2"},{"value":"moonshotai/kimi-k2.7-code-highspeed","name":"moonshotai/kimi-k2.7-code-highspeed"},{"value":"moonshotai/kimi-k2.7-code","name":"moonshotai/kimi-k2.7-code"},{"value":"nvidia/nemotron-3-ultra-550b-a55b","name":"nvidia/nemotron-3-ultra-550b-a55b"},{"value":"spacexai/grok-build-0.1","name":"spacexai/grok-build-0.1"},{"value":"xiaomi/mimo-v2.5","name":"xiaomi/mimo-v2.5"},{"value":"moonshotai/kimi-k2.6","name":"moonshotai/kimi-k2.6"},{"value":"zai/glm-5.1","name":"zai/glm-5.1"},{"value":"arcee-ai/trinity-large-thinking","name":"arcee-ai/trinity-large-thinking"},{"value":"zai/glm-5v-turbo","name":"zai/glm-5v-turbo"},{"value":"zai/glm-5-turbo","name":"zai/glm-5-turbo"},{"value":"nvidia/nemotron-3-super-120b-a12b","name":"nvidia/nemotron-3-super-120b-a12b"},{"value":"inception/mercury-2","name":"inception/mercury-2"},{"value":"zai/glm-5","name":"zai/glm-5"},{"value":"moonshotai/kimi-k2.5","name":"moonshotai/kimi-k2.5"},{"value":"zai/glm-4.7","name":"zai/glm-4.7"},{"value":"nvidia/nemotron-3-nano-30b-a3b","name":"nvidia/nemotron-3-nano-30b-a3b"},{"value":"nvidia/nemotron-nano-12b-v2-vl","name":"nvidia/nemotron-nano-12b-v2-vl"},{"value":"zai/glm-4.6","name":"zai/glm-4.6"},{"value":"bytedance/seed-1.6","name":"bytedance/seed-1.6"},{"value":"bytedance/seed-1.8","name":"bytedance/seed-1.8"},{"value":"nvidia/nemotron-nano-9b-v2","name":"nvidia/nemotron-nano-9b-v2"},{"value":"zai/glm-4.5v","name":"zai/glm-4.5v"},{"value":"zai/glm-4.5","name":"zai/glm-4.5"},{"value":"zai/glm-4.5-air","name":"zai/glm-4.5-air"},{"value":"moonshotai/kimi-k2","name":"moonshotai/kimi-k2"},{"value":"cohere/command-a","name":"cohere/command-a"},{"value":"inception/mercury-coder-small","name":"inception/mercury-coder-small"},{"value":"amazon/nova-micro","name":"amazon/nova-micro"},{"value":"deepseek/deepseek-v4.1-flash-1017","name":"deepseek/deepseek-v4.1-flash-1017"},{"value":"deepseek/deepseek-v4.1-flash-1017-fast","name":"deepseek/deepseek-v4.1-flash-1017-fast"},{"value":"deepseek/deepseek-v4.1-flash-fast","name":"deepseek/deepseek-v4.1-flash-fast"},{"value":"deepseek/deepseek-v4.1-flash","name":"deepseek/deepseek-v4.1-flash"},{"value":"deepseek/deepseek-v4-flash-vision-exp","name":"deepseek/deepseek-v4-flash-vision-exp"},{"value":"deepseek/deepseek-v4-flash","name":"deepseek/deepseek-v4-flash"},{"value":"deepseek/deepseek-v4-flash-0731","name":"deepseek/deepseek-v4-flash-0731"},{"value":"alibaba/qwen3.8-omni-flash","name":"alibaba/qwen3.8-omni-flash"},{"value":"alibaba/qwen3.8-flash","name":"alibaba/qwen3.8-flash"},{"value":"alibaba/qwen3.7-flash","name":"alibaba/qwen3.7-flash"},{"value":"alibaba/qwen3.5-flash","name":"alibaba/qwen3.5-flash"},{"value":"inclusionai/ling-3.1-flash","name":"inclusionai/ling-3.1-flash"},{"value":"xiaomi/mimo-v2.6-flash","name":"xiaomi/mimo-v2.6-flash"},{"value":"zai/glm-5.3-flashx","name":"zai/glm-5.3-flashx"},{"value":"inclusionai/ling-3.0-flash-vl","name":"inclusionai/ling-3.0-flash-vl"},{"value":"inclusionai/ling-3.0-flash-sante","name":"inclusionai/ling-3.0-flash-sante"},{"value":"inclusionai/ling-3.0-flash-fin","name":"inclusionai/ling-3.0-flash-fin"},{"value":"zai/glm-5.3-flash","name":"zai/glm-5.3-flash"},{"value":"inclusionai/ling-3.0-flash","name":"inclusionai/ling-3.0-flash"},{"value":"stepfun/step-3.7-flash","name":"stepfun/step-3.7-flash"},{"value":"zai/glm-4.7-flash","name":"zai/glm-4.7-flash"},{"value":"zai/glm-4.7-flashx","name":"zai/glm-4.7-flashx"},{"value":"anthropic/claude-haiku-5.5","name":"anthropic/claude-haiku-5.5"},{"value":"anthropic/claude-haiku-4.5","name":"anthropic/claude-haiku-4.5"},{"value":"openai/gpt-5.4-mini","name":"openai/gpt-5.4-mini"},{"value":"openai/gpt-5.4-mini-fast","name":"openai/gpt-5.4-mini-fast"},{"value":"openai/gpt-5.1-codex-mini","name":"openai/gpt-5.1-codex-mini"},{"value":"openai/gpt-5-mini","name":"openai/gpt-5-mini"},{"value":"openai/gpt-5-mini-fast","name":"openai/gpt-5-mini-fast"},{"value":"openai/gpt-4.1-mini","name":"openai/gpt-4.1-mini"},{"value":"openai/gpt-4.1-mini-fast","name":"openai/gpt-4.1-mini-fast"},{"value":"openai/o4-mini","name":"openai/o4-mini"},{"value":"openai/o3-mini","name":"openai/o3-mini"},{"value":"openai/gpt-4o-mini","name":"openai/gpt-4o-mini"},{"value":"openai/gpt-4o-mini-fast","name":"openai/gpt-4o-mini-fast"},{"value":"google/gemini-4-argon","name":"google/gemini-4-argon"},{"value":"google/gemini-3.8-flash","name":"google/gemini-3.8-flash"},{"value":"google/gemini-3.7-flash","name":"google/gemini-3.7-flash"},{"value":"google/gemini-3.5-flash-lite","name":"google/gemini-3.5-flash-lite"},{"value":"google/gemini-3.6-flash","name":"google/gemini-3.6-flash"},{"value":"google/gemini-3.5-flash","name":"google/gemini-3.5-flash"},{"value":"google/gemini-3.1-flash-lite","name":"google/gemini-3.1-flash-lite"},{"value":"google/gemini-3-flash","name":"google/gemini-3-flash"},{"value":"google/gemini-2.5-flash-lite","name":"google/gemini-2.5-flash-lite"},{"value":"google/gemini-2.5-flash","name":"google/gemini-2.5-flash"},{"value":"google/gemini-2.5-pro","name":"google/gemini-2.5-pro"},{"value":"mistral/ministral-14b","name":"mistral/ministral-14b"},{"value":"mistral/ministral-3b","name":"mistral/ministral-3b"},{"value":"mistral/ministral-8b","name":"mistral/ministral-8b"},{"value":"minimax/minimax-m3.1-flash","name":"minimax/minimax-m3.1-flash"},{"value":"minimax/minimax-m3","name":"minimax/minimax-m3"},{"value":"minimax/minimax-m2.7","name":"minimax/minimax-m2.7"},{"value":"minimax/minimax-m2.7-highspeed","name":"minimax/minimax-m2.7-highspeed"},{"value":"minimax/minimax-m2.5","name":"minimax/minimax-m2.5"},{"value":"minimax/minimax-m2.5-highspeed","name":"minimax/minimax-m2.5-highspeed"},{"value":"minimax/minimax-m2.1","name":"minimax/minimax-m2.1"},{"value":"minimax/minimax-m2.1-lightning","name":"minimax/minimax-m2.1-lightning"},{"value":"amazon/nova-2-lite","name":"amazon/nova-2-lite"},{"value":"minimax/minimax-m2","name":"minimax/minimax-m2"},{"value":"amazon/nova-lite","name":"amazon/nova-lite"},{"value":"google/gemini-3.1-pro-preview","name":"google/gemini-3.1-pro-preview"},{"value":"meituan/longcat-2.5-preview","name":"meituan/longcat-2.5-preview"},{"value":"stepfun/step-5-preview","name":"stepfun/step-5-preview"},{"value":"tencent/hy4-preview","name":"tencent/hy4-preview"},{"value":"spacexai/grok-4.20-multi-agent-beta","name":"spacexai/grok-4.20-multi-agent-beta"},{"value":"spacexai/grok-4.20-non-reasoning-beta","name":"spacexai/grok-4.20-non-reasoning-beta"},{"value":"spacexai/grok-4.20-reasoning-beta","name":"spacexai/grok-4.20-reasoning-beta"},{"value":"interfaze/interfaze-beta","name":"interfaze/interfaze-beta"},{"value":"tencent/hy-mt2-pro","name":"tencent/hy-mt2-pro"},{"value":"scaledown/scaledown-extract-1","name":"scaledown/scaledown-extract-1"},{"value":"scaledown/scaledown-summarize-1","name":"scaledown/scaledown-summarize-1"},{"value":"elorian/glimpse","name":"elorian/glimpse"},{"value":"tencent/hy-mt2-plus","name":"tencent/hy-mt2-plus"},{"value":"inference-net/schematron-v2-small","name":"inference-net/schematron-v2-small"},{"value":"inference-net/schematron-v2-turbo","name":"inference-net/schematron-v2-turbo"},{"value":"morph/morph-v3-fast","name":"morph/morph-v3-fast"},{"value":"morph/morph-v3-large","name":"morph/morph-v3-large"},{"value":"perplexity/sonar","name":"perplexity/sonar"},{"value":"tencent/hy-mt2-lite","name":"tencent/hy-mt2-lite"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"auto","name":"Auto","description":"Check actions with an automatic safety review instead of asking","_meta":{"fx":{"permissionMode":"auto"}}},{"value":"ask","name":"Ask","description":"Request permission before making any changes","_meta":{"fx":{"permissionMode":"ask"}}},{"value":"full-access","name":"Full access","description":"Run every action without asking, outside the sandbox","_meta":{"fx":{"permissionMode":"yolo"}}}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"auto","options":[{"value":"auto","name":"default"},{"value":"none","name":"none"},{"value":"minimal","name":"minimal"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"}]},{"id":"fast","name":"Fast Mode","description":"Uses the model's fast lane","category":"model","type":"select","currentValue":"false","options":[{"value":"false","name":"off"},{"value":"true","name":"on"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"auto","name":"Auto","description":"Check actions with an automatic safety review instead of asking"},{"id":"ask","name":"Ask","description":"Request permission before making any changes"},{"id":"full-access","name":"Full access","description":"Run every action without asking, outside the sandbox"}]}}}} {"type":"emit_inbound","label":"notification:session/update:available_commands_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}} {"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"effort","value":"medium"}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/fx_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/fx_transcript.ndjson index 86c9b5d36e00e..18eed3d4670bb 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/fx_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/fx_transcript.ndjson @@ -1,7 +1,7 @@ {"type":"transcript_start","provider":"fx","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"message_steering","metadata":{"generatedBy":"live-fx-recorder","fxVersion":"0.0.13","normalization":"Session ids are fx-session-NN, the workspace is , HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are . User skill names, emails and token-shaped strings are removed. Timestamps are kept as recorded.","droppedFrames":0}} {"type":"expect_outbound","label":"request:initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"","capabilities":"","clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"session":{"notices":{},"compaction":{}},"elicitation":{"form":{}}},"clientInfo":""}}} {"type":"emit_inbound","label":"response:initialize","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":true,"audio":false,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":true,"acp":true},"sessionCapabilities":{"list":{},"resume":{},"close":{},"systemPrompt":{}},"_meta":{"fx":{"steering":true}}},"agentInfo":{"name":"fx","title":"fx","version":"0.0.13"},"authMethods":[]}}} -{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","_meta":{"fx":{"profileMcpServers":true}},"mcpServers":""}}} {"type":"emit_inbound","label":"response:session/new","frame":{"kind":"response","method":"session/new","result":{"sessionId":"fx-session-01","configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"gateway","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"anthropic/claude-opus-5.5","options":[{"value":"anthropic/claude-sonnet-5.5","name":"anthropic/claude-sonnet-5.5"},{"value":"anthropic/claude-opus-5.5","name":"anthropic/claude-opus-5.5"},{"value":"anthropic/claude-opus-5.5-fast","name":"anthropic/claude-opus-5.5-fast"},{"value":"anthropic/claude-opus-5","name":"anthropic/claude-opus-5"},{"value":"anthropic/claude-opus-5-fast","name":"anthropic/claude-opus-5-fast"},{"value":"anthropic/claude-sonnet-5","name":"anthropic/claude-sonnet-5"},{"value":"anthropic/claude-opus-4.8","name":"anthropic/claude-opus-4.8"},{"value":"anthropic/claude-opus-4.8-fast","name":"anthropic/claude-opus-4.8-fast"},{"value":"anthropic/claude-opus-4.7","name":"anthropic/claude-opus-4.7"},{"value":"anthropic/claude-sonnet-4.6","name":"anthropic/claude-sonnet-4.6"},{"value":"anthropic/claude-opus-4.6","name":"anthropic/claude-opus-4.6"},{"value":"anthropic/claude-opus-4.5","name":"anthropic/claude-opus-4.5"},{"value":"anthropic/claude-sonnet-4.5","name":"anthropic/claude-sonnet-4.5"},{"value":"anthropic/claude-opus-4","name":"anthropic/claude-opus-4"},{"value":"anthropic/claude-sonnet-4","name":"anthropic/claude-sonnet-4"},{"value":"openai/gpt-5.6-luna","name":"openai/gpt-5.6-luna"},{"value":"openai/gpt-5.6-luna-fast","name":"openai/gpt-5.6-luna-fast"},{"value":"openai/gpt-5.6-sol","name":"openai/gpt-5.6-sol"},{"value":"openai/gpt-5.6-sol-fast","name":"openai/gpt-5.6-sol-fast"},{"value":"openai/gpt-5.6-terra","name":"openai/gpt-5.6-terra"},{"value":"openai/gpt-5.6-terra-fast","name":"openai/gpt-5.6-terra-fast"},{"value":"openai/gpt-5.5","name":"openai/gpt-5.5"},{"value":"openai/gpt-5.5-fast","name":"openai/gpt-5.5-fast"},{"value":"openai/gpt-5.5-pro","name":"openai/gpt-5.5-pro"},{"value":"openai/gpt-5.4-nano","name":"openai/gpt-5.4-nano"},{"value":"openai/gpt-5.4","name":"openai/gpt-5.4"},{"value":"openai/gpt-5.4-fast","name":"openai/gpt-5.4-fast"},{"value":"openai/gpt-5.4-pro","name":"openai/gpt-5.4-pro"},{"value":"openai/gpt-5.3-codex","name":"openai/gpt-5.3-codex"},{"value":"openai/gpt-5.3-codex-fast","name":"openai/gpt-5.3-codex-fast"},{"value":"openai/gpt-5.2","name":"openai/gpt-5.2"},{"value":"openai/gpt-5.2-fast","name":"openai/gpt-5.2-fast"},{"value":"openai/gpt-5.2-pro","name":"openai/gpt-5.2-pro"},{"value":"openai/gpt-5.1-thinking","name":"openai/gpt-5.1-thinking"},{"value":"openai/gpt-5.1-thinking-fast","name":"openai/gpt-5.1-thinking-fast"},{"value":"openai/gpt-5-pro","name":"openai/gpt-5-pro"},{"value":"openai/gpt-5","name":"openai/gpt-5"},{"value":"openai/gpt-5-fast","name":"openai/gpt-5-fast"},{"value":"openai/gpt-5-nano","name":"openai/gpt-5-nano"},{"value":"openai/o3-pro","name":"openai/o3-pro"},{"value":"openai/o3","name":"openai/o3"},{"value":"openai/o3-fast","name":"openai/o3-fast"},{"value":"openai/o1","name":"openai/o1"},{"value":"deepseek/deepseek-v4-pro-0813","name":"deepseek/deepseek-v4-pro-0813"},{"value":"deepseek/deepseek-v4-pro","name":"deepseek/deepseek-v4-pro"},{"value":"spacexai/grok-4.7","name":"spacexai/grok-4.7"},{"value":"spacexai/grok-4.6","name":"spacexai/grok-4.6"},{"value":"spacexai/grok-4.5","name":"spacexai/grok-4.5"},{"value":"spacexai/grok-4.3","name":"spacexai/grok-4.3"},{"value":"spacexai/grok-4.20-multi-agent","name":"spacexai/grok-4.20-multi-agent"},{"value":"spacexai/grok-4.20-non-reasoning","name":"spacexai/grok-4.20-non-reasoning"},{"value":"spacexai/grok-4.20-reasoning","name":"spacexai/grok-4.20-reasoning"},{"value":"spacexai/grok-4.1-fast-non-reasoning","name":"spacexai/grok-4.1-fast-non-reasoning"},{"value":"spacexai/grok-4.1-fast-reasoning","name":"spacexai/grok-4.1-fast-reasoning"},{"value":"amazon/nova-pro","name":"amazon/nova-pro"},{"value":"anthropic/claude-fable-5.1","name":"anthropic/claude-fable-5.1"},{"value":"anthropic/claude-fable-5","name":"anthropic/claude-fable-5"},{"value":"openai/gpt-6.1-sol","name":"openai/gpt-6.1-sol"},{"value":"openai/gpt-6.1-sol-fast","name":"openai/gpt-6.1-sol-fast"},{"value":"openai/gpt-6-luna","name":"openai/gpt-6-luna"},{"value":"openai/gpt-6-luna-fast","name":"openai/gpt-6-luna-fast"},{"value":"openai/gpt-6-sol","name":"openai/gpt-6-sol"},{"value":"openai/gpt-6-sol-fast","name":"openai/gpt-6-sol-fast"},{"value":"openai/gpt-6-astra","name":"openai/gpt-6-astra"},{"value":"openai/gpt-6-astra-fast","name":"openai/gpt-6-astra-fast"},{"value":"openai/gpt-oss-safeguard-120b","name":"openai/gpt-oss-safeguard-120b"},{"value":"openai/gpt-oss-safeguard-20b","name":"openai/gpt-oss-safeguard-20b"},{"value":"openai/gpt-oss-120b","name":"openai/gpt-oss-120b"},{"value":"openai/gpt-oss-20b","name":"openai/gpt-oss-20b"},{"value":"openai/gpt-4.1","name":"openai/gpt-4.1"},{"value":"openai/gpt-4.1-fast","name":"openai/gpt-4.1-fast"},{"value":"openai/gpt-4.1-nano","name":"openai/gpt-4.1-nano"},{"value":"openai/gpt-4.1-nano-fast","name":"openai/gpt-4.1-nano-fast"},{"value":"openai/gpt-4o","name":"openai/gpt-4o"},{"value":"openai/gpt-4o-fast","name":"openai/gpt-4o-fast"},{"value":"openai/gpt-4-turbo","name":"openai/gpt-4-turbo"},{"value":"openai/gpt-3.5-turbo","name":"openai/gpt-3.5-turbo"},{"value":"google/gemma-4-26b-a4b-it","name":"google/gemma-4-26b-a4b-it"},{"value":"deepseek/deepseek-v3.2","name":"deepseek/deepseek-v3.2"},{"value":"deepseek/deepseek-v3.2-thinking","name":"deepseek/deepseek-v3.2-thinking"},{"value":"deepseek/deepseek-r1","name":"deepseek/deepseek-r1"},{"value":"meta/llama-4-maverick","name":"meta/llama-4-maverick"},{"value":"meta/llama-4-scout","name":"meta/llama-4-scout"},{"value":"meta/llama-3.3-70b","name":"meta/llama-3.3-70b"},{"value":"meta/llama-3.1-70b","name":"meta/llama-3.1-70b"},{"value":"meta/llama-3.1-8b","name":"meta/llama-3.1-8b"},{"value":"alibaba/qwen3.8-2.4t-a95b","name":"alibaba/qwen3.8-2.4t-a95b"},{"value":"alibaba/qwen3.8-max","name":"alibaba/qwen3.8-max"},{"value":"alibaba/qwen3-next-80b-a3b-instruct","name":"alibaba/qwen3-next-80b-a3b-instruct"},{"value":"alibaba/qwen3-next-80b-a3b-thinking","name":"alibaba/qwen3-next-80b-a3b-thinking"},{"value":"alibaba/qwen3-coder-30b-a3b","name":"alibaba/qwen3-coder-30b-a3b"},{"value":"alibaba/qwen3-coder","name":"alibaba/qwen3-coder"},{"value":"alibaba/qwen3-coder-next","name":"alibaba/qwen3-coder-next"},{"value":"alibaba/qwen-3-235b","name":"alibaba/qwen-3-235b"},{"value":"alibaba/qwen-3-32b","name":"alibaba/qwen-3-32b"},{"value":"fireworks/ember-1","name":"fireworks/ember-1"},{"value":"zai/glm-5.3-fast","name":"zai/glm-5.3-fast"},{"value":"zai/glm-5.3","name":"zai/glm-5.3"},{"value":"nvidia/nemotron-3.5-lightning","name":"nvidia/nemotron-3.5-lightning"},{"value":"moonshotai/kimi-k3-fast","name":"moonshotai/kimi-k3-fast"},{"value":"moonshotai/kimi-k3","name":"moonshotai/kimi-k3"},{"value":"zai/glm-5.2-fast","name":"zai/glm-5.2-fast"},{"value":"zai/glm-5.2","name":"zai/glm-5.2"},{"value":"nvidia/nemotron-3-ultra-550b-a55b","name":"nvidia/nemotron-3-ultra-550b-a55b"},{"value":"spacexai/grok-build-0.1","name":"spacexai/grok-build-0.1"},{"value":"nvidia/nemotron-3-super-120b-a12b","name":"nvidia/nemotron-3-super-120b-a12b"},{"value":"zai/glm-5","name":"zai/glm-5"},{"value":"moonshotai/kimi-k2.5","name":"moonshotai/kimi-k2.5"},{"value":"zai/glm-4.7","name":"zai/glm-4.7"},{"value":"nvidia/nemotron-nano-12b-v2-vl","name":"nvidia/nemotron-nano-12b-v2-vl"},{"value":"nvidia/nemotron-nano-9b-v2","name":"nvidia/nemotron-nano-9b-v2"},{"value":"amazon/nova-micro","name":"amazon/nova-micro"},{"value":"deepseek/deepseek-v4.1-flash","name":"deepseek/deepseek-v4.1-flash"},{"value":"deepseek/deepseek-v4-flash","name":"deepseek/deepseek-v4-flash"},{"value":"deepseek/deepseek-v4-flash-0731","name":"deepseek/deepseek-v4-flash-0731"},{"value":"zai/glm-5.3-flash","name":"zai/glm-5.3-flash"},{"value":"zai/glm-4.7-flash","name":"zai/glm-4.7-flash"},{"value":"anthropic/claude-haiku-5.5","name":"anthropic/claude-haiku-5.5"},{"value":"anthropic/claude-haiku-4.5","name":"anthropic/claude-haiku-4.5"},{"value":"anthropic/claude-3-haiku","name":"anthropic/claude-3-haiku"},{"value":"openai/gpt-5.4-mini","name":"openai/gpt-5.4-mini"},{"value":"openai/gpt-5.4-mini-fast","name":"openai/gpt-5.4-mini-fast"},{"value":"openai/gpt-5-mini","name":"openai/gpt-5-mini"},{"value":"openai/gpt-5-mini-fast","name":"openai/gpt-5-mini-fast"},{"value":"openai/gpt-4.1-mini","name":"openai/gpt-4.1-mini"},{"value":"openai/gpt-4.1-mini-fast","name":"openai/gpt-4.1-mini-fast"},{"value":"openai/o4-mini","name":"openai/o4-mini"},{"value":"openai/o4-mini-fast","name":"openai/o4-mini-fast"},{"value":"openai/o3-mini","name":"openai/o3-mini"},{"value":"openai/gpt-4o-mini","name":"openai/gpt-4o-mini"},{"value":"openai/gpt-4o-mini-fast","name":"openai/gpt-4o-mini-fast"},{"value":"google/gemini-3.8-flash","name":"google/gemini-3.8-flash"},{"value":"google/gemini-3.7-flash","name":"google/gemini-3.7-flash"},{"value":"google/gemini-3.5-flash-lite","name":"google/gemini-3.5-flash-lite"},{"value":"google/gemini-3.6-flash","name":"google/gemini-3.6-flash"},{"value":"google/gemini-3.5-flash","name":"google/gemini-3.5-flash"},{"value":"google/gemini-3.1-flash-lite","name":"google/gemini-3.1-flash-lite"},{"value":"google/gemini-3-flash","name":"google/gemini-3-flash"},{"value":"google/gemini-2.5-flash-lite","name":"google/gemini-2.5-flash-lite"},{"value":"google/gemini-2.5-flash","name":"google/gemini-2.5-flash"},{"value":"google/gemini-2.5-pro","name":"google/gemini-2.5-pro"},{"value":"minimax/minimax-m3","name":"minimax/minimax-m3"},{"value":"minimax/minimax-m2.5","name":"minimax/minimax-m2.5"},{"value":"minimax/minimax-m2.1","name":"minimax/minimax-m2.1"},{"value":"amazon/nova-2-lite","name":"amazon/nova-2-lite"},{"value":"amazon/nova-lite","name":"amazon/nova-lite"},{"value":"google/gemini-3.1-pro-preview","name":"google/gemini-3.1-pro-preview"},{"value":"spacexai/grok-4.20-multi-agent-beta","name":"spacexai/grok-4.20-multi-agent-beta"},{"value":"spacexai/grok-4.20-non-reasoning-beta","name":"spacexai/grok-4.20-non-reasoning-beta"},{"value":"spacexai/grok-4.20-reasoning-beta","name":"spacexai/grok-4.20-reasoning-beta"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"code","name":"Code","description":"Write and modify code with full tool access","permissionMode":"auto"},{"value":"ask","name":"Ask","description":"Request permission before making any changes","permissionMode":"ask"}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"xhigh","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"code","name":"Code","description":"Write and modify code with full tool access"},{"id":"ask","name":"Ask","description":"Request permission before making any changes"}]}}}} {"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"effort","value":"medium"}}} {"type":"emit_inbound","label":"notification:session/update:available_commands_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/fx_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/fx_transcript.ndjson index d7c5cd808504d..fe27477574e29 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/fx_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/fx_transcript.ndjson @@ -1,7 +1,7 @@ {"type":"transcript_start","provider":"fx","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"multi_turn","metadata":{"generatedBy":"live-fx-recorder","fxVersion":"0.0.13","normalization":"Session ids are fx-session-NN, the workspace is , HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are . User skill names, emails and token-shaped strings are removed. Timestamps are kept as recorded.","droppedFrames":0}} {"type":"expect_outbound","label":"request:initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"","capabilities":"","clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"session":{"notices":{},"compaction":{}},"elicitation":{"form":{}}},"clientInfo":""}}} {"type":"emit_inbound","label":"response:initialize","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":true,"audio":false,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":true,"acp":true},"sessionCapabilities":{"list":{},"resume":{},"close":{},"systemPrompt":{}},"_meta":{"fx":{"steering":true}}},"agentInfo":{"name":"fx","title":"fx","version":"0.0.13"},"authMethods":[]}}} -{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","_meta":{"fx":{"profileMcpServers":true}},"mcpServers":""}}} {"type":"emit_inbound","label":"response:session/new","frame":{"kind":"response","method":"session/new","result":{"sessionId":"fx-session-01","configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"gateway","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"anthropic/claude-opus-5.5","options":[{"value":"anthropic/claude-sonnet-5.5","name":"anthropic/claude-sonnet-5.5"},{"value":"anthropic/claude-opus-5.5","name":"anthropic/claude-opus-5.5"},{"value":"anthropic/claude-opus-5.5-fast","name":"anthropic/claude-opus-5.5-fast"},{"value":"anthropic/claude-opus-5","name":"anthropic/claude-opus-5"},{"value":"anthropic/claude-opus-5-fast","name":"anthropic/claude-opus-5-fast"},{"value":"anthropic/claude-sonnet-5","name":"anthropic/claude-sonnet-5"},{"value":"anthropic/claude-opus-4.8","name":"anthropic/claude-opus-4.8"},{"value":"anthropic/claude-opus-4.8-fast","name":"anthropic/claude-opus-4.8-fast"},{"value":"anthropic/claude-opus-4.7","name":"anthropic/claude-opus-4.7"},{"value":"anthropic/claude-sonnet-4.6","name":"anthropic/claude-sonnet-4.6"},{"value":"anthropic/claude-opus-4.6","name":"anthropic/claude-opus-4.6"},{"value":"anthropic/claude-opus-4.5","name":"anthropic/claude-opus-4.5"},{"value":"anthropic/claude-sonnet-4.5","name":"anthropic/claude-sonnet-4.5"},{"value":"anthropic/claude-opus-4","name":"anthropic/claude-opus-4"},{"value":"anthropic/claude-sonnet-4","name":"anthropic/claude-sonnet-4"},{"value":"openai/gpt-5.6-luna","name":"openai/gpt-5.6-luna"},{"value":"openai/gpt-5.6-luna-fast","name":"openai/gpt-5.6-luna-fast"},{"value":"openai/gpt-5.6-sol","name":"openai/gpt-5.6-sol"},{"value":"openai/gpt-5.6-sol-fast","name":"openai/gpt-5.6-sol-fast"},{"value":"openai/gpt-5.6-terra","name":"openai/gpt-5.6-terra"},{"value":"openai/gpt-5.6-terra-fast","name":"openai/gpt-5.6-terra-fast"},{"value":"openai/gpt-5.5","name":"openai/gpt-5.5"},{"value":"openai/gpt-5.5-fast","name":"openai/gpt-5.5-fast"},{"value":"openai/gpt-5.5-pro","name":"openai/gpt-5.5-pro"},{"value":"openai/gpt-5.4-nano","name":"openai/gpt-5.4-nano"},{"value":"openai/gpt-5.4","name":"openai/gpt-5.4"},{"value":"openai/gpt-5.4-fast","name":"openai/gpt-5.4-fast"},{"value":"openai/gpt-5.4-pro","name":"openai/gpt-5.4-pro"},{"value":"openai/gpt-5.3-codex","name":"openai/gpt-5.3-codex"},{"value":"openai/gpt-5.3-codex-fast","name":"openai/gpt-5.3-codex-fast"},{"value":"openai/gpt-5.2","name":"openai/gpt-5.2"},{"value":"openai/gpt-5.2-fast","name":"openai/gpt-5.2-fast"},{"value":"openai/gpt-5.2-pro","name":"openai/gpt-5.2-pro"},{"value":"openai/gpt-5.1-thinking","name":"openai/gpt-5.1-thinking"},{"value":"openai/gpt-5.1-thinking-fast","name":"openai/gpt-5.1-thinking-fast"},{"value":"openai/gpt-5-pro","name":"openai/gpt-5-pro"},{"value":"openai/gpt-5","name":"openai/gpt-5"},{"value":"openai/gpt-5-fast","name":"openai/gpt-5-fast"},{"value":"openai/gpt-5-nano","name":"openai/gpt-5-nano"},{"value":"openai/o3-pro","name":"openai/o3-pro"},{"value":"openai/o3","name":"openai/o3"},{"value":"openai/o3-fast","name":"openai/o3-fast"},{"value":"openai/o1","name":"openai/o1"},{"value":"deepseek/deepseek-v4-pro-0813","name":"deepseek/deepseek-v4-pro-0813"},{"value":"deepseek/deepseek-v4-pro","name":"deepseek/deepseek-v4-pro"},{"value":"spacexai/grok-4.7","name":"spacexai/grok-4.7"},{"value":"spacexai/grok-4.6","name":"spacexai/grok-4.6"},{"value":"spacexai/grok-4.5","name":"spacexai/grok-4.5"},{"value":"spacexai/grok-4.3","name":"spacexai/grok-4.3"},{"value":"spacexai/grok-4.20-multi-agent","name":"spacexai/grok-4.20-multi-agent"},{"value":"spacexai/grok-4.20-non-reasoning","name":"spacexai/grok-4.20-non-reasoning"},{"value":"spacexai/grok-4.20-reasoning","name":"spacexai/grok-4.20-reasoning"},{"value":"spacexai/grok-4.1-fast-non-reasoning","name":"spacexai/grok-4.1-fast-non-reasoning"},{"value":"spacexai/grok-4.1-fast-reasoning","name":"spacexai/grok-4.1-fast-reasoning"},{"value":"amazon/nova-pro","name":"amazon/nova-pro"},{"value":"anthropic/claude-fable-5.1","name":"anthropic/claude-fable-5.1"},{"value":"anthropic/claude-fable-5","name":"anthropic/claude-fable-5"},{"value":"openai/gpt-6.1-sol","name":"openai/gpt-6.1-sol"},{"value":"openai/gpt-6.1-sol-fast","name":"openai/gpt-6.1-sol-fast"},{"value":"openai/gpt-6-luna","name":"openai/gpt-6-luna"},{"value":"openai/gpt-6-luna-fast","name":"openai/gpt-6-luna-fast"},{"value":"openai/gpt-6-sol","name":"openai/gpt-6-sol"},{"value":"openai/gpt-6-sol-fast","name":"openai/gpt-6-sol-fast"},{"value":"openai/gpt-6-astra","name":"openai/gpt-6-astra"},{"value":"openai/gpt-6-astra-fast","name":"openai/gpt-6-astra-fast"},{"value":"openai/gpt-oss-safeguard-120b","name":"openai/gpt-oss-safeguard-120b"},{"value":"openai/gpt-oss-safeguard-20b","name":"openai/gpt-oss-safeguard-20b"},{"value":"openai/gpt-oss-120b","name":"openai/gpt-oss-120b"},{"value":"openai/gpt-oss-20b","name":"openai/gpt-oss-20b"},{"value":"openai/gpt-4.1","name":"openai/gpt-4.1"},{"value":"openai/gpt-4.1-fast","name":"openai/gpt-4.1-fast"},{"value":"openai/gpt-4.1-nano","name":"openai/gpt-4.1-nano"},{"value":"openai/gpt-4.1-nano-fast","name":"openai/gpt-4.1-nano-fast"},{"value":"openai/gpt-4o","name":"openai/gpt-4o"},{"value":"openai/gpt-4o-fast","name":"openai/gpt-4o-fast"},{"value":"openai/gpt-4-turbo","name":"openai/gpt-4-turbo"},{"value":"openai/gpt-3.5-turbo","name":"openai/gpt-3.5-turbo"},{"value":"google/gemma-4-26b-a4b-it","name":"google/gemma-4-26b-a4b-it"},{"value":"deepseek/deepseek-v3.2","name":"deepseek/deepseek-v3.2"},{"value":"deepseek/deepseek-v3.2-thinking","name":"deepseek/deepseek-v3.2-thinking"},{"value":"deepseek/deepseek-r1","name":"deepseek/deepseek-r1"},{"value":"meta/llama-4-maverick","name":"meta/llama-4-maverick"},{"value":"meta/llama-4-scout","name":"meta/llama-4-scout"},{"value":"meta/llama-3.3-70b","name":"meta/llama-3.3-70b"},{"value":"meta/llama-3.1-70b","name":"meta/llama-3.1-70b"},{"value":"meta/llama-3.1-8b","name":"meta/llama-3.1-8b"},{"value":"alibaba/qwen3.8-2.4t-a95b","name":"alibaba/qwen3.8-2.4t-a95b"},{"value":"alibaba/qwen3.8-max","name":"alibaba/qwen3.8-max"},{"value":"alibaba/qwen3-next-80b-a3b-instruct","name":"alibaba/qwen3-next-80b-a3b-instruct"},{"value":"alibaba/qwen3-next-80b-a3b-thinking","name":"alibaba/qwen3-next-80b-a3b-thinking"},{"value":"alibaba/qwen3-coder-30b-a3b","name":"alibaba/qwen3-coder-30b-a3b"},{"value":"alibaba/qwen3-coder","name":"alibaba/qwen3-coder"},{"value":"alibaba/qwen3-coder-next","name":"alibaba/qwen3-coder-next"},{"value":"alibaba/qwen-3-235b","name":"alibaba/qwen-3-235b"},{"value":"alibaba/qwen-3-32b","name":"alibaba/qwen-3-32b"},{"value":"fireworks/ember-1","name":"fireworks/ember-1"},{"value":"zai/glm-5.3-fast","name":"zai/glm-5.3-fast"},{"value":"zai/glm-5.3","name":"zai/glm-5.3"},{"value":"nvidia/nemotron-3.5-lightning","name":"nvidia/nemotron-3.5-lightning"},{"value":"moonshotai/kimi-k3-fast","name":"moonshotai/kimi-k3-fast"},{"value":"moonshotai/kimi-k3","name":"moonshotai/kimi-k3"},{"value":"zai/glm-5.2-fast","name":"zai/glm-5.2-fast"},{"value":"zai/glm-5.2","name":"zai/glm-5.2"},{"value":"nvidia/nemotron-3-ultra-550b-a55b","name":"nvidia/nemotron-3-ultra-550b-a55b"},{"value":"spacexai/grok-build-0.1","name":"spacexai/grok-build-0.1"},{"value":"nvidia/nemotron-3-super-120b-a12b","name":"nvidia/nemotron-3-super-120b-a12b"},{"value":"zai/glm-5","name":"zai/glm-5"},{"value":"moonshotai/kimi-k2.5","name":"moonshotai/kimi-k2.5"},{"value":"zai/glm-4.7","name":"zai/glm-4.7"},{"value":"nvidia/nemotron-nano-12b-v2-vl","name":"nvidia/nemotron-nano-12b-v2-vl"},{"value":"nvidia/nemotron-nano-9b-v2","name":"nvidia/nemotron-nano-9b-v2"},{"value":"amazon/nova-micro","name":"amazon/nova-micro"},{"value":"deepseek/deepseek-v4.1-flash","name":"deepseek/deepseek-v4.1-flash"},{"value":"deepseek/deepseek-v4-flash","name":"deepseek/deepseek-v4-flash"},{"value":"deepseek/deepseek-v4-flash-0731","name":"deepseek/deepseek-v4-flash-0731"},{"value":"zai/glm-5.3-flash","name":"zai/glm-5.3-flash"},{"value":"zai/glm-4.7-flash","name":"zai/glm-4.7-flash"},{"value":"anthropic/claude-haiku-5.5","name":"anthropic/claude-haiku-5.5"},{"value":"anthropic/claude-haiku-4.5","name":"anthropic/claude-haiku-4.5"},{"value":"anthropic/claude-3-haiku","name":"anthropic/claude-3-haiku"},{"value":"openai/gpt-5.4-mini","name":"openai/gpt-5.4-mini"},{"value":"openai/gpt-5.4-mini-fast","name":"openai/gpt-5.4-mini-fast"},{"value":"openai/gpt-5-mini","name":"openai/gpt-5-mini"},{"value":"openai/gpt-5-mini-fast","name":"openai/gpt-5-mini-fast"},{"value":"openai/gpt-4.1-mini","name":"openai/gpt-4.1-mini"},{"value":"openai/gpt-4.1-mini-fast","name":"openai/gpt-4.1-mini-fast"},{"value":"openai/o4-mini","name":"openai/o4-mini"},{"value":"openai/o4-mini-fast","name":"openai/o4-mini-fast"},{"value":"openai/o3-mini","name":"openai/o3-mini"},{"value":"openai/gpt-4o-mini","name":"openai/gpt-4o-mini"},{"value":"openai/gpt-4o-mini-fast","name":"openai/gpt-4o-mini-fast"},{"value":"google/gemini-3.8-flash","name":"google/gemini-3.8-flash"},{"value":"google/gemini-3.7-flash","name":"google/gemini-3.7-flash"},{"value":"google/gemini-3.5-flash-lite","name":"google/gemini-3.5-flash-lite"},{"value":"google/gemini-3.6-flash","name":"google/gemini-3.6-flash"},{"value":"google/gemini-3.5-flash","name":"google/gemini-3.5-flash"},{"value":"google/gemini-3.1-flash-lite","name":"google/gemini-3.1-flash-lite"},{"value":"google/gemini-3-flash","name":"google/gemini-3-flash"},{"value":"google/gemini-2.5-flash-lite","name":"google/gemini-2.5-flash-lite"},{"value":"google/gemini-2.5-flash","name":"google/gemini-2.5-flash"},{"value":"google/gemini-2.5-pro","name":"google/gemini-2.5-pro"},{"value":"minimax/minimax-m3","name":"minimax/minimax-m3"},{"value":"minimax/minimax-m2.5","name":"minimax/minimax-m2.5"},{"value":"minimax/minimax-m2.1","name":"minimax/minimax-m2.1"},{"value":"amazon/nova-2-lite","name":"amazon/nova-2-lite"},{"value":"amazon/nova-lite","name":"amazon/nova-lite"},{"value":"google/gemini-3.1-pro-preview","name":"google/gemini-3.1-pro-preview"},{"value":"spacexai/grok-4.20-multi-agent-beta","name":"spacexai/grok-4.20-multi-agent-beta"},{"value":"spacexai/grok-4.20-non-reasoning-beta","name":"spacexai/grok-4.20-non-reasoning-beta"},{"value":"spacexai/grok-4.20-reasoning-beta","name":"spacexai/grok-4.20-reasoning-beta"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"code","name":"Code","description":"Write and modify code with full tool access","permissionMode":"auto"},{"value":"ask","name":"Ask","description":"Request permission before making any changes","permissionMode":"ask"}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"xhigh","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"code","name":"Code","description":"Write and modify code with full tool access"},{"id":"ask","name":"Ask","description":"Request permission before making any changes"}]}}}} {"type":"emit_inbound","label":"notification:session/update:available_commands_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}} {"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"effort","value":"medium"}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/fx_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/fx_transcript.ndjson index 28d92260dcecd..c099f2ad978ff 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/fx_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/fx_transcript.ndjson @@ -1,7 +1,7 @@ {"type":"transcript_start","provider":"fx","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"queued_turn","metadata":{"generatedBy":"live-fx-recorder","fxVersion":"0.0.13","normalization":"Session ids are fx-session-NN, the workspace is , HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are . User skill names, emails and token-shaped strings are removed. Timestamps are kept as recorded.","droppedFrames":0}} {"type":"expect_outbound","label":"request:initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"","capabilities":"","clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"session":{"notices":{},"compaction":{}},"elicitation":{"form":{}}},"clientInfo":""}}} {"type":"emit_inbound","label":"response:initialize","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":true,"audio":false,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":true,"acp":true},"sessionCapabilities":{"list":{},"resume":{},"close":{},"systemPrompt":{}},"_meta":{"fx":{"steering":true}}},"agentInfo":{"name":"fx","title":"fx","version":"0.0.13"},"authMethods":[]}}} -{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","_meta":{"fx":{"profileMcpServers":true}},"mcpServers":""}}} {"type":"emit_inbound","label":"response:session/new","frame":{"kind":"response","method":"session/new","result":{"sessionId":"fx-session-01","configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"gateway","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"anthropic/claude-opus-5.5","options":[{"value":"anthropic/claude-sonnet-5.5","name":"anthropic/claude-sonnet-5.5"},{"value":"anthropic/claude-opus-5.5","name":"anthropic/claude-opus-5.5"},{"value":"anthropic/claude-opus-5.5-fast","name":"anthropic/claude-opus-5.5-fast"},{"value":"anthropic/claude-opus-5","name":"anthropic/claude-opus-5"},{"value":"anthropic/claude-opus-5-fast","name":"anthropic/claude-opus-5-fast"},{"value":"anthropic/claude-sonnet-5","name":"anthropic/claude-sonnet-5"},{"value":"anthropic/claude-opus-4.8","name":"anthropic/claude-opus-4.8"},{"value":"anthropic/claude-opus-4.8-fast","name":"anthropic/claude-opus-4.8-fast"},{"value":"anthropic/claude-opus-4.7","name":"anthropic/claude-opus-4.7"},{"value":"anthropic/claude-sonnet-4.6","name":"anthropic/claude-sonnet-4.6"},{"value":"anthropic/claude-opus-4.6","name":"anthropic/claude-opus-4.6"},{"value":"anthropic/claude-opus-4.5","name":"anthropic/claude-opus-4.5"},{"value":"anthropic/claude-sonnet-4.5","name":"anthropic/claude-sonnet-4.5"},{"value":"anthropic/claude-opus-4","name":"anthropic/claude-opus-4"},{"value":"anthropic/claude-sonnet-4","name":"anthropic/claude-sonnet-4"},{"value":"openai/gpt-5.6-luna","name":"openai/gpt-5.6-luna"},{"value":"openai/gpt-5.6-luna-fast","name":"openai/gpt-5.6-luna-fast"},{"value":"openai/gpt-5.6-sol","name":"openai/gpt-5.6-sol"},{"value":"openai/gpt-5.6-sol-fast","name":"openai/gpt-5.6-sol-fast"},{"value":"openai/gpt-5.6-terra","name":"openai/gpt-5.6-terra"},{"value":"openai/gpt-5.6-terra-fast","name":"openai/gpt-5.6-terra-fast"},{"value":"openai/gpt-5.5","name":"openai/gpt-5.5"},{"value":"openai/gpt-5.5-fast","name":"openai/gpt-5.5-fast"},{"value":"openai/gpt-5.5-pro","name":"openai/gpt-5.5-pro"},{"value":"openai/gpt-5.4-nano","name":"openai/gpt-5.4-nano"},{"value":"openai/gpt-5.4","name":"openai/gpt-5.4"},{"value":"openai/gpt-5.4-fast","name":"openai/gpt-5.4-fast"},{"value":"openai/gpt-5.4-pro","name":"openai/gpt-5.4-pro"},{"value":"openai/gpt-5.3-codex","name":"openai/gpt-5.3-codex"},{"value":"openai/gpt-5.3-codex-fast","name":"openai/gpt-5.3-codex-fast"},{"value":"openai/gpt-5.2","name":"openai/gpt-5.2"},{"value":"openai/gpt-5.2-fast","name":"openai/gpt-5.2-fast"},{"value":"openai/gpt-5.2-pro","name":"openai/gpt-5.2-pro"},{"value":"openai/gpt-5.1-thinking","name":"openai/gpt-5.1-thinking"},{"value":"openai/gpt-5.1-thinking-fast","name":"openai/gpt-5.1-thinking-fast"},{"value":"openai/gpt-5-pro","name":"openai/gpt-5-pro"},{"value":"openai/gpt-5","name":"openai/gpt-5"},{"value":"openai/gpt-5-fast","name":"openai/gpt-5-fast"},{"value":"openai/gpt-5-nano","name":"openai/gpt-5-nano"},{"value":"openai/o3-pro","name":"openai/o3-pro"},{"value":"openai/o3","name":"openai/o3"},{"value":"openai/o3-fast","name":"openai/o3-fast"},{"value":"openai/o1","name":"openai/o1"},{"value":"deepseek/deepseek-v4-pro-0813","name":"deepseek/deepseek-v4-pro-0813"},{"value":"deepseek/deepseek-v4-pro","name":"deepseek/deepseek-v4-pro"},{"value":"spacexai/grok-4.7","name":"spacexai/grok-4.7"},{"value":"spacexai/grok-4.6","name":"spacexai/grok-4.6"},{"value":"spacexai/grok-4.5","name":"spacexai/grok-4.5"},{"value":"spacexai/grok-4.3","name":"spacexai/grok-4.3"},{"value":"spacexai/grok-4.20-multi-agent","name":"spacexai/grok-4.20-multi-agent"},{"value":"spacexai/grok-4.20-non-reasoning","name":"spacexai/grok-4.20-non-reasoning"},{"value":"spacexai/grok-4.20-reasoning","name":"spacexai/grok-4.20-reasoning"},{"value":"spacexai/grok-4.1-fast-non-reasoning","name":"spacexai/grok-4.1-fast-non-reasoning"},{"value":"spacexai/grok-4.1-fast-reasoning","name":"spacexai/grok-4.1-fast-reasoning"},{"value":"amazon/nova-pro","name":"amazon/nova-pro"},{"value":"anthropic/claude-fable-5.1","name":"anthropic/claude-fable-5.1"},{"value":"anthropic/claude-fable-5","name":"anthropic/claude-fable-5"},{"value":"openai/gpt-6.1-sol","name":"openai/gpt-6.1-sol"},{"value":"openai/gpt-6.1-sol-fast","name":"openai/gpt-6.1-sol-fast"},{"value":"openai/gpt-6-luna","name":"openai/gpt-6-luna"},{"value":"openai/gpt-6-luna-fast","name":"openai/gpt-6-luna-fast"},{"value":"openai/gpt-6-sol","name":"openai/gpt-6-sol"},{"value":"openai/gpt-6-sol-fast","name":"openai/gpt-6-sol-fast"},{"value":"openai/gpt-6-astra","name":"openai/gpt-6-astra"},{"value":"openai/gpt-6-astra-fast","name":"openai/gpt-6-astra-fast"},{"value":"openai/gpt-oss-safeguard-120b","name":"openai/gpt-oss-safeguard-120b"},{"value":"openai/gpt-oss-safeguard-20b","name":"openai/gpt-oss-safeguard-20b"},{"value":"openai/gpt-oss-120b","name":"openai/gpt-oss-120b"},{"value":"openai/gpt-oss-20b","name":"openai/gpt-oss-20b"},{"value":"openai/gpt-4.1","name":"openai/gpt-4.1"},{"value":"openai/gpt-4.1-fast","name":"openai/gpt-4.1-fast"},{"value":"openai/gpt-4.1-nano","name":"openai/gpt-4.1-nano"},{"value":"openai/gpt-4.1-nano-fast","name":"openai/gpt-4.1-nano-fast"},{"value":"openai/gpt-4o","name":"openai/gpt-4o"},{"value":"openai/gpt-4o-fast","name":"openai/gpt-4o-fast"},{"value":"openai/gpt-4-turbo","name":"openai/gpt-4-turbo"},{"value":"openai/gpt-3.5-turbo","name":"openai/gpt-3.5-turbo"},{"value":"google/gemma-4-26b-a4b-it","name":"google/gemma-4-26b-a4b-it"},{"value":"deepseek/deepseek-v3.2","name":"deepseek/deepseek-v3.2"},{"value":"deepseek/deepseek-v3.2-thinking","name":"deepseek/deepseek-v3.2-thinking"},{"value":"deepseek/deepseek-r1","name":"deepseek/deepseek-r1"},{"value":"meta/llama-4-maverick","name":"meta/llama-4-maverick"},{"value":"meta/llama-4-scout","name":"meta/llama-4-scout"},{"value":"meta/llama-3.3-70b","name":"meta/llama-3.3-70b"},{"value":"meta/llama-3.1-70b","name":"meta/llama-3.1-70b"},{"value":"meta/llama-3.1-8b","name":"meta/llama-3.1-8b"},{"value":"alibaba/qwen3.8-2.4t-a95b","name":"alibaba/qwen3.8-2.4t-a95b"},{"value":"alibaba/qwen3.8-max","name":"alibaba/qwen3.8-max"},{"value":"alibaba/qwen3-next-80b-a3b-instruct","name":"alibaba/qwen3-next-80b-a3b-instruct"},{"value":"alibaba/qwen3-next-80b-a3b-thinking","name":"alibaba/qwen3-next-80b-a3b-thinking"},{"value":"alibaba/qwen3-coder-30b-a3b","name":"alibaba/qwen3-coder-30b-a3b"},{"value":"alibaba/qwen3-coder","name":"alibaba/qwen3-coder"},{"value":"alibaba/qwen3-coder-next","name":"alibaba/qwen3-coder-next"},{"value":"alibaba/qwen-3-235b","name":"alibaba/qwen-3-235b"},{"value":"alibaba/qwen-3-32b","name":"alibaba/qwen-3-32b"},{"value":"fireworks/ember-1","name":"fireworks/ember-1"},{"value":"zai/glm-5.3-fast","name":"zai/glm-5.3-fast"},{"value":"zai/glm-5.3","name":"zai/glm-5.3"},{"value":"nvidia/nemotron-3.5-lightning","name":"nvidia/nemotron-3.5-lightning"},{"value":"moonshotai/kimi-k3-fast","name":"moonshotai/kimi-k3-fast"},{"value":"moonshotai/kimi-k3","name":"moonshotai/kimi-k3"},{"value":"zai/glm-5.2-fast","name":"zai/glm-5.2-fast"},{"value":"zai/glm-5.2","name":"zai/glm-5.2"},{"value":"nvidia/nemotron-3-ultra-550b-a55b","name":"nvidia/nemotron-3-ultra-550b-a55b"},{"value":"spacexai/grok-build-0.1","name":"spacexai/grok-build-0.1"},{"value":"nvidia/nemotron-3-super-120b-a12b","name":"nvidia/nemotron-3-super-120b-a12b"},{"value":"zai/glm-5","name":"zai/glm-5"},{"value":"moonshotai/kimi-k2.5","name":"moonshotai/kimi-k2.5"},{"value":"zai/glm-4.7","name":"zai/glm-4.7"},{"value":"nvidia/nemotron-nano-12b-v2-vl","name":"nvidia/nemotron-nano-12b-v2-vl"},{"value":"nvidia/nemotron-nano-9b-v2","name":"nvidia/nemotron-nano-9b-v2"},{"value":"amazon/nova-micro","name":"amazon/nova-micro"},{"value":"deepseek/deepseek-v4.1-flash","name":"deepseek/deepseek-v4.1-flash"},{"value":"deepseek/deepseek-v4-flash","name":"deepseek/deepseek-v4-flash"},{"value":"deepseek/deepseek-v4-flash-0731","name":"deepseek/deepseek-v4-flash-0731"},{"value":"zai/glm-5.3-flash","name":"zai/glm-5.3-flash"},{"value":"zai/glm-4.7-flash","name":"zai/glm-4.7-flash"},{"value":"anthropic/claude-haiku-5.5","name":"anthropic/claude-haiku-5.5"},{"value":"anthropic/claude-haiku-4.5","name":"anthropic/claude-haiku-4.5"},{"value":"anthropic/claude-3-haiku","name":"anthropic/claude-3-haiku"},{"value":"openai/gpt-5.4-mini","name":"openai/gpt-5.4-mini"},{"value":"openai/gpt-5.4-mini-fast","name":"openai/gpt-5.4-mini-fast"},{"value":"openai/gpt-5-mini","name":"openai/gpt-5-mini"},{"value":"openai/gpt-5-mini-fast","name":"openai/gpt-5-mini-fast"},{"value":"openai/gpt-4.1-mini","name":"openai/gpt-4.1-mini"},{"value":"openai/gpt-4.1-mini-fast","name":"openai/gpt-4.1-mini-fast"},{"value":"openai/o4-mini","name":"openai/o4-mini"},{"value":"openai/o4-mini-fast","name":"openai/o4-mini-fast"},{"value":"openai/o3-mini","name":"openai/o3-mini"},{"value":"openai/gpt-4o-mini","name":"openai/gpt-4o-mini"},{"value":"openai/gpt-4o-mini-fast","name":"openai/gpt-4o-mini-fast"},{"value":"google/gemini-3.8-flash","name":"google/gemini-3.8-flash"},{"value":"google/gemini-3.7-flash","name":"google/gemini-3.7-flash"},{"value":"google/gemini-3.5-flash-lite","name":"google/gemini-3.5-flash-lite"},{"value":"google/gemini-3.6-flash","name":"google/gemini-3.6-flash"},{"value":"google/gemini-3.5-flash","name":"google/gemini-3.5-flash"},{"value":"google/gemini-3.1-flash-lite","name":"google/gemini-3.1-flash-lite"},{"value":"google/gemini-3-flash","name":"google/gemini-3-flash"},{"value":"google/gemini-2.5-flash-lite","name":"google/gemini-2.5-flash-lite"},{"value":"google/gemini-2.5-flash","name":"google/gemini-2.5-flash"},{"value":"google/gemini-2.5-pro","name":"google/gemini-2.5-pro"},{"value":"minimax/minimax-m3","name":"minimax/minimax-m3"},{"value":"minimax/minimax-m2.5","name":"minimax/minimax-m2.5"},{"value":"minimax/minimax-m2.1","name":"minimax/minimax-m2.1"},{"value":"amazon/nova-2-lite","name":"amazon/nova-2-lite"},{"value":"amazon/nova-lite","name":"amazon/nova-lite"},{"value":"google/gemini-3.1-pro-preview","name":"google/gemini-3.1-pro-preview"},{"value":"spacexai/grok-4.20-multi-agent-beta","name":"spacexai/grok-4.20-multi-agent-beta"},{"value":"spacexai/grok-4.20-non-reasoning-beta","name":"spacexai/grok-4.20-non-reasoning-beta"},{"value":"spacexai/grok-4.20-reasoning-beta","name":"spacexai/grok-4.20-reasoning-beta"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"code","name":"Code","description":"Write and modify code with full tool access","permissionMode":"auto"},{"value":"ask","name":"Ask","description":"Request permission before making any changes","permissionMode":"ask"}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"xhigh","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"code","name":"Code","description":"Write and modify code with full tool access"},{"id":"ask","name":"Ask","description":"Request permission before making any changes"}]}}}} {"type":"emit_inbound","label":"notification:session/update:available_commands_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}} {"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"effort","value":"medium"}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/fx_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/simple/fx_transcript.ndjson index 923aa3d611f4a..c4c00bf558656 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/simple/fx_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/fx_transcript.ndjson @@ -1,7 +1,7 @@ {"type":"transcript_start","provider":"fx","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"simple","metadata":{"generatedBy":"live-fx-recorder","fxVersion":"0.0.13","normalization":"Session ids are fx-session-NN, the workspace is , HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are . User skill names, emails and token-shaped strings are removed. Timestamps are kept as recorded.","droppedFrames":0}} {"type":"expect_outbound","label":"request:initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"","capabilities":"","clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"session":{"notices":{},"compaction":{}},"elicitation":{"form":{}}},"clientInfo":""}}} {"type":"emit_inbound","label":"response:initialize","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":true,"audio":false,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":true,"acp":true},"sessionCapabilities":{"list":{},"resume":{},"close":{},"systemPrompt":{}},"_meta":{"fx":{"steering":true}}},"agentInfo":{"name":"fx","title":"fx","version":"0.0.13"},"authMethods":[]}}} -{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","_meta":{"fx":{"profileMcpServers":true}},"mcpServers":""}}} {"type":"emit_inbound","label":"response:session/new","frame":{"kind":"response","method":"session/new","result":{"sessionId":"fx-session-01","configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"gateway","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"anthropic/claude-opus-5.5","options":[{"value":"anthropic/claude-sonnet-5.5","name":"anthropic/claude-sonnet-5.5"},{"value":"anthropic/claude-opus-5.5","name":"anthropic/claude-opus-5.5"},{"value":"anthropic/claude-opus-5.5-fast","name":"anthropic/claude-opus-5.5-fast"},{"value":"anthropic/claude-opus-5","name":"anthropic/claude-opus-5"},{"value":"anthropic/claude-opus-5-fast","name":"anthropic/claude-opus-5-fast"},{"value":"anthropic/claude-sonnet-5","name":"anthropic/claude-sonnet-5"},{"value":"anthropic/claude-opus-4.8","name":"anthropic/claude-opus-4.8"},{"value":"anthropic/claude-opus-4.8-fast","name":"anthropic/claude-opus-4.8-fast"},{"value":"anthropic/claude-opus-4.7","name":"anthropic/claude-opus-4.7"},{"value":"anthropic/claude-sonnet-4.6","name":"anthropic/claude-sonnet-4.6"},{"value":"anthropic/claude-opus-4.6","name":"anthropic/claude-opus-4.6"},{"value":"anthropic/claude-opus-4.5","name":"anthropic/claude-opus-4.5"},{"value":"anthropic/claude-sonnet-4.5","name":"anthropic/claude-sonnet-4.5"},{"value":"anthropic/claude-opus-4","name":"anthropic/claude-opus-4"},{"value":"anthropic/claude-sonnet-4","name":"anthropic/claude-sonnet-4"},{"value":"openai/gpt-5.6-luna","name":"openai/gpt-5.6-luna"},{"value":"openai/gpt-5.6-luna-fast","name":"openai/gpt-5.6-luna-fast"},{"value":"openai/gpt-5.6-sol","name":"openai/gpt-5.6-sol"},{"value":"openai/gpt-5.6-sol-fast","name":"openai/gpt-5.6-sol-fast"},{"value":"openai/gpt-5.6-terra","name":"openai/gpt-5.6-terra"},{"value":"openai/gpt-5.6-terra-fast","name":"openai/gpt-5.6-terra-fast"},{"value":"openai/gpt-5.5","name":"openai/gpt-5.5"},{"value":"openai/gpt-5.5-fast","name":"openai/gpt-5.5-fast"},{"value":"openai/gpt-5.5-pro","name":"openai/gpt-5.5-pro"},{"value":"openai/gpt-5.4-nano","name":"openai/gpt-5.4-nano"},{"value":"openai/gpt-5.4","name":"openai/gpt-5.4"},{"value":"openai/gpt-5.4-fast","name":"openai/gpt-5.4-fast"},{"value":"openai/gpt-5.4-pro","name":"openai/gpt-5.4-pro"},{"value":"openai/gpt-5.3-codex","name":"openai/gpt-5.3-codex"},{"value":"openai/gpt-5.3-codex-fast","name":"openai/gpt-5.3-codex-fast"},{"value":"openai/gpt-5.2","name":"openai/gpt-5.2"},{"value":"openai/gpt-5.2-fast","name":"openai/gpt-5.2-fast"},{"value":"openai/gpt-5.2-pro","name":"openai/gpt-5.2-pro"},{"value":"openai/gpt-5.1-thinking","name":"openai/gpt-5.1-thinking"},{"value":"openai/gpt-5.1-thinking-fast","name":"openai/gpt-5.1-thinking-fast"},{"value":"openai/gpt-5-pro","name":"openai/gpt-5-pro"},{"value":"openai/gpt-5","name":"openai/gpt-5"},{"value":"openai/gpt-5-fast","name":"openai/gpt-5-fast"},{"value":"openai/gpt-5-nano","name":"openai/gpt-5-nano"},{"value":"openai/o3-pro","name":"openai/o3-pro"},{"value":"openai/o3","name":"openai/o3"},{"value":"openai/o3-fast","name":"openai/o3-fast"},{"value":"openai/o1","name":"openai/o1"},{"value":"deepseek/deepseek-v4-pro-0813","name":"deepseek/deepseek-v4-pro-0813"},{"value":"deepseek/deepseek-v4-pro","name":"deepseek/deepseek-v4-pro"},{"value":"spacexai/grok-4.7","name":"spacexai/grok-4.7"},{"value":"spacexai/grok-4.6","name":"spacexai/grok-4.6"},{"value":"spacexai/grok-4.5","name":"spacexai/grok-4.5"},{"value":"spacexai/grok-4.3","name":"spacexai/grok-4.3"},{"value":"spacexai/grok-4.20-multi-agent","name":"spacexai/grok-4.20-multi-agent"},{"value":"spacexai/grok-4.20-non-reasoning","name":"spacexai/grok-4.20-non-reasoning"},{"value":"spacexai/grok-4.20-reasoning","name":"spacexai/grok-4.20-reasoning"},{"value":"spacexai/grok-4.1-fast-non-reasoning","name":"spacexai/grok-4.1-fast-non-reasoning"},{"value":"spacexai/grok-4.1-fast-reasoning","name":"spacexai/grok-4.1-fast-reasoning"},{"value":"amazon/nova-pro","name":"amazon/nova-pro"},{"value":"anthropic/claude-fable-5.1","name":"anthropic/claude-fable-5.1"},{"value":"anthropic/claude-fable-5","name":"anthropic/claude-fable-5"},{"value":"openai/gpt-6.1-sol","name":"openai/gpt-6.1-sol"},{"value":"openai/gpt-6.1-sol-fast","name":"openai/gpt-6.1-sol-fast"},{"value":"openai/gpt-6-luna","name":"openai/gpt-6-luna"},{"value":"openai/gpt-6-luna-fast","name":"openai/gpt-6-luna-fast"},{"value":"openai/gpt-6-sol","name":"openai/gpt-6-sol"},{"value":"openai/gpt-6-sol-fast","name":"openai/gpt-6-sol-fast"},{"value":"openai/gpt-6-astra","name":"openai/gpt-6-astra"},{"value":"openai/gpt-6-astra-fast","name":"openai/gpt-6-astra-fast"},{"value":"openai/gpt-oss-safeguard-120b","name":"openai/gpt-oss-safeguard-120b"},{"value":"openai/gpt-oss-safeguard-20b","name":"openai/gpt-oss-safeguard-20b"},{"value":"openai/gpt-oss-120b","name":"openai/gpt-oss-120b"},{"value":"openai/gpt-oss-20b","name":"openai/gpt-oss-20b"},{"value":"openai/gpt-4.1","name":"openai/gpt-4.1"},{"value":"openai/gpt-4.1-fast","name":"openai/gpt-4.1-fast"},{"value":"openai/gpt-4.1-nano","name":"openai/gpt-4.1-nano"},{"value":"openai/gpt-4.1-nano-fast","name":"openai/gpt-4.1-nano-fast"},{"value":"openai/gpt-4o","name":"openai/gpt-4o"},{"value":"openai/gpt-4o-fast","name":"openai/gpt-4o-fast"},{"value":"openai/gpt-4-turbo","name":"openai/gpt-4-turbo"},{"value":"openai/gpt-3.5-turbo","name":"openai/gpt-3.5-turbo"},{"value":"google/gemma-4-26b-a4b-it","name":"google/gemma-4-26b-a4b-it"},{"value":"deepseek/deepseek-v3.2","name":"deepseek/deepseek-v3.2"},{"value":"deepseek/deepseek-v3.2-thinking","name":"deepseek/deepseek-v3.2-thinking"},{"value":"deepseek/deepseek-r1","name":"deepseek/deepseek-r1"},{"value":"meta/llama-4-maverick","name":"meta/llama-4-maverick"},{"value":"meta/llama-4-scout","name":"meta/llama-4-scout"},{"value":"meta/llama-3.3-70b","name":"meta/llama-3.3-70b"},{"value":"meta/llama-3.1-70b","name":"meta/llama-3.1-70b"},{"value":"meta/llama-3.1-8b","name":"meta/llama-3.1-8b"},{"value":"alibaba/qwen3.8-2.4t-a95b","name":"alibaba/qwen3.8-2.4t-a95b"},{"value":"alibaba/qwen3.8-max","name":"alibaba/qwen3.8-max"},{"value":"alibaba/qwen3-next-80b-a3b-instruct","name":"alibaba/qwen3-next-80b-a3b-instruct"},{"value":"alibaba/qwen3-next-80b-a3b-thinking","name":"alibaba/qwen3-next-80b-a3b-thinking"},{"value":"alibaba/qwen3-coder-30b-a3b","name":"alibaba/qwen3-coder-30b-a3b"},{"value":"alibaba/qwen3-coder","name":"alibaba/qwen3-coder"},{"value":"alibaba/qwen3-coder-next","name":"alibaba/qwen3-coder-next"},{"value":"alibaba/qwen-3-235b","name":"alibaba/qwen-3-235b"},{"value":"alibaba/qwen-3-32b","name":"alibaba/qwen-3-32b"},{"value":"fireworks/ember-1","name":"fireworks/ember-1"},{"value":"zai/glm-5.3-fast","name":"zai/glm-5.3-fast"},{"value":"zai/glm-5.3","name":"zai/glm-5.3"},{"value":"nvidia/nemotron-3.5-lightning","name":"nvidia/nemotron-3.5-lightning"},{"value":"moonshotai/kimi-k3-fast","name":"moonshotai/kimi-k3-fast"},{"value":"moonshotai/kimi-k3","name":"moonshotai/kimi-k3"},{"value":"zai/glm-5.2-fast","name":"zai/glm-5.2-fast"},{"value":"zai/glm-5.2","name":"zai/glm-5.2"},{"value":"nvidia/nemotron-3-ultra-550b-a55b","name":"nvidia/nemotron-3-ultra-550b-a55b"},{"value":"spacexai/grok-build-0.1","name":"spacexai/grok-build-0.1"},{"value":"nvidia/nemotron-3-super-120b-a12b","name":"nvidia/nemotron-3-super-120b-a12b"},{"value":"zai/glm-5","name":"zai/glm-5"},{"value":"moonshotai/kimi-k2.5","name":"moonshotai/kimi-k2.5"},{"value":"zai/glm-4.7","name":"zai/glm-4.7"},{"value":"nvidia/nemotron-nano-12b-v2-vl","name":"nvidia/nemotron-nano-12b-v2-vl"},{"value":"nvidia/nemotron-nano-9b-v2","name":"nvidia/nemotron-nano-9b-v2"},{"value":"amazon/nova-micro","name":"amazon/nova-micro"},{"value":"deepseek/deepseek-v4.1-flash","name":"deepseek/deepseek-v4.1-flash"},{"value":"deepseek/deepseek-v4-flash","name":"deepseek/deepseek-v4-flash"},{"value":"deepseek/deepseek-v4-flash-0731","name":"deepseek/deepseek-v4-flash-0731"},{"value":"zai/glm-5.3-flash","name":"zai/glm-5.3-flash"},{"value":"zai/glm-4.7-flash","name":"zai/glm-4.7-flash"},{"value":"anthropic/claude-haiku-5.5","name":"anthropic/claude-haiku-5.5"},{"value":"anthropic/claude-haiku-4.5","name":"anthropic/claude-haiku-4.5"},{"value":"anthropic/claude-3-haiku","name":"anthropic/claude-3-haiku"},{"value":"openai/gpt-5.4-mini","name":"openai/gpt-5.4-mini"},{"value":"openai/gpt-5.4-mini-fast","name":"openai/gpt-5.4-mini-fast"},{"value":"openai/gpt-5-mini","name":"openai/gpt-5-mini"},{"value":"openai/gpt-5-mini-fast","name":"openai/gpt-5-mini-fast"},{"value":"openai/gpt-4.1-mini","name":"openai/gpt-4.1-mini"},{"value":"openai/gpt-4.1-mini-fast","name":"openai/gpt-4.1-mini-fast"},{"value":"openai/o4-mini","name":"openai/o4-mini"},{"value":"openai/o4-mini-fast","name":"openai/o4-mini-fast"},{"value":"openai/o3-mini","name":"openai/o3-mini"},{"value":"openai/gpt-4o-mini","name":"openai/gpt-4o-mini"},{"value":"openai/gpt-4o-mini-fast","name":"openai/gpt-4o-mini-fast"},{"value":"google/gemini-3.8-flash","name":"google/gemini-3.8-flash"},{"value":"google/gemini-3.7-flash","name":"google/gemini-3.7-flash"},{"value":"google/gemini-3.5-flash-lite","name":"google/gemini-3.5-flash-lite"},{"value":"google/gemini-3.6-flash","name":"google/gemini-3.6-flash"},{"value":"google/gemini-3.5-flash","name":"google/gemini-3.5-flash"},{"value":"google/gemini-3.1-flash-lite","name":"google/gemini-3.1-flash-lite"},{"value":"google/gemini-3-flash","name":"google/gemini-3-flash"},{"value":"google/gemini-2.5-flash-lite","name":"google/gemini-2.5-flash-lite"},{"value":"google/gemini-2.5-flash","name":"google/gemini-2.5-flash"},{"value":"google/gemini-2.5-pro","name":"google/gemini-2.5-pro"},{"value":"minimax/minimax-m3","name":"minimax/minimax-m3"},{"value":"minimax/minimax-m2.5","name":"minimax/minimax-m2.5"},{"value":"minimax/minimax-m2.1","name":"minimax/minimax-m2.1"},{"value":"amazon/nova-2-lite","name":"amazon/nova-2-lite"},{"value":"amazon/nova-lite","name":"amazon/nova-lite"},{"value":"google/gemini-3.1-pro-preview","name":"google/gemini-3.1-pro-preview"},{"value":"spacexai/grok-4.20-multi-agent-beta","name":"spacexai/grok-4.20-multi-agent-beta"},{"value":"spacexai/grok-4.20-non-reasoning-beta","name":"spacexai/grok-4.20-non-reasoning-beta"},{"value":"spacexai/grok-4.20-reasoning-beta","name":"spacexai/grok-4.20-reasoning-beta"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"code","name":"Code","description":"Write and modify code with full tool access","permissionMode":"auto"},{"value":"ask","name":"Ask","description":"Request permission before making any changes","permissionMode":"ask"}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"xhigh","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"code","name":"Code","description":"Write and modify code with full tool access"},{"id":"ask","name":"Ask","description":"Request permission before making any changes"}]}}}} {"type":"emit_inbound","label":"notification:session/update:available_commands_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}} {"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"effort","value":"medium"}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_denied_write/fx_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_denied_write/fx_transcript.ndjson index 5a643d4df438c..454db28728fd1 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_denied_write/fx_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_denied_write/fx_transcript.ndjson @@ -1,7 +1,7 @@ {"type":"transcript_start","provider":"fx","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"tool_call_denied_write","metadata":{"generatedBy":"live-fx-recorder","fxVersion":"0.0.13","normalization":"Session ids are fx-session-NN, the workspace is , HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are . User skill names, emails and token-shaped strings are removed. Timestamps are kept as recorded.","droppedFrames":0}} {"type":"expect_outbound","label":"request:initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"","capabilities":"","clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"session":{"notices":{},"compaction":{}},"elicitation":{"form":{}}},"clientInfo":""}}} {"type":"emit_inbound","label":"response:initialize","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":true,"audio":false,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":true,"acp":true},"sessionCapabilities":{"list":{},"resume":{},"close":{},"systemPrompt":{}},"_meta":{"fx":{"steering":true}}},"agentInfo":{"name":"fx","title":"fx","version":"0.0.13"},"authMethods":[]}}} -{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","_meta":{"fx":{"profileMcpServers":true}},"mcpServers":""}}} {"type":"emit_inbound","label":"response:session/new","frame":{"kind":"response","method":"session/new","result":{"sessionId":"fx-session-01","configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"gateway","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"anthropic/claude-opus-5.5","options":[{"value":"anthropic/claude-sonnet-5.5","name":"anthropic/claude-sonnet-5.5"},{"value":"anthropic/claude-opus-5.5","name":"anthropic/claude-opus-5.5"},{"value":"anthropic/claude-opus-5.5-fast","name":"anthropic/claude-opus-5.5-fast"},{"value":"anthropic/claude-opus-5","name":"anthropic/claude-opus-5"},{"value":"anthropic/claude-opus-5-fast","name":"anthropic/claude-opus-5-fast"},{"value":"anthropic/claude-sonnet-5","name":"anthropic/claude-sonnet-5"},{"value":"anthropic/claude-opus-4.8","name":"anthropic/claude-opus-4.8"},{"value":"anthropic/claude-opus-4.8-fast","name":"anthropic/claude-opus-4.8-fast"},{"value":"anthropic/claude-opus-4.7","name":"anthropic/claude-opus-4.7"},{"value":"anthropic/claude-sonnet-4.6","name":"anthropic/claude-sonnet-4.6"},{"value":"anthropic/claude-opus-4.6","name":"anthropic/claude-opus-4.6"},{"value":"anthropic/claude-opus-4.5","name":"anthropic/claude-opus-4.5"},{"value":"anthropic/claude-sonnet-4.5","name":"anthropic/claude-sonnet-4.5"},{"value":"anthropic/claude-opus-4","name":"anthropic/claude-opus-4"},{"value":"anthropic/claude-sonnet-4","name":"anthropic/claude-sonnet-4"},{"value":"openai/gpt-5.6-luna","name":"openai/gpt-5.6-luna"},{"value":"openai/gpt-5.6-luna-fast","name":"openai/gpt-5.6-luna-fast"},{"value":"openai/gpt-5.6-sol","name":"openai/gpt-5.6-sol"},{"value":"openai/gpt-5.6-sol-fast","name":"openai/gpt-5.6-sol-fast"},{"value":"openai/gpt-5.6-terra","name":"openai/gpt-5.6-terra"},{"value":"openai/gpt-5.6-terra-fast","name":"openai/gpt-5.6-terra-fast"},{"value":"openai/gpt-5.5","name":"openai/gpt-5.5"},{"value":"openai/gpt-5.5-fast","name":"openai/gpt-5.5-fast"},{"value":"openai/gpt-5.5-pro","name":"openai/gpt-5.5-pro"},{"value":"openai/gpt-5.4-nano","name":"openai/gpt-5.4-nano"},{"value":"openai/gpt-5.4","name":"openai/gpt-5.4"},{"value":"openai/gpt-5.4-fast","name":"openai/gpt-5.4-fast"},{"value":"openai/gpt-5.4-pro","name":"openai/gpt-5.4-pro"},{"value":"openai/gpt-5.3-codex","name":"openai/gpt-5.3-codex"},{"value":"openai/gpt-5.3-codex-fast","name":"openai/gpt-5.3-codex-fast"},{"value":"openai/gpt-5.2","name":"openai/gpt-5.2"},{"value":"openai/gpt-5.2-fast","name":"openai/gpt-5.2-fast"},{"value":"openai/gpt-5.2-pro","name":"openai/gpt-5.2-pro"},{"value":"openai/gpt-5.1-thinking","name":"openai/gpt-5.1-thinking"},{"value":"openai/gpt-5.1-thinking-fast","name":"openai/gpt-5.1-thinking-fast"},{"value":"openai/gpt-5-pro","name":"openai/gpt-5-pro"},{"value":"openai/gpt-5","name":"openai/gpt-5"},{"value":"openai/gpt-5-fast","name":"openai/gpt-5-fast"},{"value":"openai/gpt-5-nano","name":"openai/gpt-5-nano"},{"value":"openai/o3-pro","name":"openai/o3-pro"},{"value":"openai/o3","name":"openai/o3"},{"value":"openai/o3-fast","name":"openai/o3-fast"},{"value":"openai/o1","name":"openai/o1"},{"value":"deepseek/deepseek-v4-pro-0813","name":"deepseek/deepseek-v4-pro-0813"},{"value":"deepseek/deepseek-v4-pro","name":"deepseek/deepseek-v4-pro"},{"value":"spacexai/grok-4.7","name":"spacexai/grok-4.7"},{"value":"spacexai/grok-4.6","name":"spacexai/grok-4.6"},{"value":"spacexai/grok-4.5","name":"spacexai/grok-4.5"},{"value":"spacexai/grok-4.3","name":"spacexai/grok-4.3"},{"value":"spacexai/grok-4.20-multi-agent","name":"spacexai/grok-4.20-multi-agent"},{"value":"spacexai/grok-4.20-non-reasoning","name":"spacexai/grok-4.20-non-reasoning"},{"value":"spacexai/grok-4.20-reasoning","name":"spacexai/grok-4.20-reasoning"},{"value":"spacexai/grok-4.1-fast-non-reasoning","name":"spacexai/grok-4.1-fast-non-reasoning"},{"value":"spacexai/grok-4.1-fast-reasoning","name":"spacexai/grok-4.1-fast-reasoning"},{"value":"amazon/nova-pro","name":"amazon/nova-pro"},{"value":"anthropic/claude-fable-5.1","name":"anthropic/claude-fable-5.1"},{"value":"anthropic/claude-fable-5","name":"anthropic/claude-fable-5"},{"value":"openai/gpt-6.1-sol","name":"openai/gpt-6.1-sol"},{"value":"openai/gpt-6.1-sol-fast","name":"openai/gpt-6.1-sol-fast"},{"value":"openai/gpt-6-luna","name":"openai/gpt-6-luna"},{"value":"openai/gpt-6-luna-fast","name":"openai/gpt-6-luna-fast"},{"value":"openai/gpt-6-sol","name":"openai/gpt-6-sol"},{"value":"openai/gpt-6-sol-fast","name":"openai/gpt-6-sol-fast"},{"value":"openai/gpt-6-astra","name":"openai/gpt-6-astra"},{"value":"openai/gpt-6-astra-fast","name":"openai/gpt-6-astra-fast"},{"value":"openai/gpt-oss-safeguard-120b","name":"openai/gpt-oss-safeguard-120b"},{"value":"openai/gpt-oss-safeguard-20b","name":"openai/gpt-oss-safeguard-20b"},{"value":"openai/gpt-oss-120b","name":"openai/gpt-oss-120b"},{"value":"openai/gpt-oss-20b","name":"openai/gpt-oss-20b"},{"value":"openai/gpt-4.1","name":"openai/gpt-4.1"},{"value":"openai/gpt-4.1-fast","name":"openai/gpt-4.1-fast"},{"value":"openai/gpt-4.1-nano","name":"openai/gpt-4.1-nano"},{"value":"openai/gpt-4.1-nano-fast","name":"openai/gpt-4.1-nano-fast"},{"value":"openai/gpt-4o","name":"openai/gpt-4o"},{"value":"openai/gpt-4o-fast","name":"openai/gpt-4o-fast"},{"value":"openai/gpt-4-turbo","name":"openai/gpt-4-turbo"},{"value":"openai/gpt-3.5-turbo","name":"openai/gpt-3.5-turbo"},{"value":"google/gemma-4-26b-a4b-it","name":"google/gemma-4-26b-a4b-it"},{"value":"deepseek/deepseek-v3.2","name":"deepseek/deepseek-v3.2"},{"value":"deepseek/deepseek-v3.2-thinking","name":"deepseek/deepseek-v3.2-thinking"},{"value":"deepseek/deepseek-r1","name":"deepseek/deepseek-r1"},{"value":"meta/llama-4-maverick","name":"meta/llama-4-maverick"},{"value":"meta/llama-4-scout","name":"meta/llama-4-scout"},{"value":"meta/llama-3.3-70b","name":"meta/llama-3.3-70b"},{"value":"meta/llama-3.1-70b","name":"meta/llama-3.1-70b"},{"value":"meta/llama-3.1-8b","name":"meta/llama-3.1-8b"},{"value":"alibaba/qwen3.8-2.4t-a95b","name":"alibaba/qwen3.8-2.4t-a95b"},{"value":"alibaba/qwen3.8-max","name":"alibaba/qwen3.8-max"},{"value":"alibaba/qwen3-next-80b-a3b-instruct","name":"alibaba/qwen3-next-80b-a3b-instruct"},{"value":"alibaba/qwen3-next-80b-a3b-thinking","name":"alibaba/qwen3-next-80b-a3b-thinking"},{"value":"alibaba/qwen3-coder-30b-a3b","name":"alibaba/qwen3-coder-30b-a3b"},{"value":"alibaba/qwen3-coder","name":"alibaba/qwen3-coder"},{"value":"alibaba/qwen3-coder-next","name":"alibaba/qwen3-coder-next"},{"value":"alibaba/qwen-3-235b","name":"alibaba/qwen-3-235b"},{"value":"alibaba/qwen-3-32b","name":"alibaba/qwen-3-32b"},{"value":"fireworks/ember-1","name":"fireworks/ember-1"},{"value":"zai/glm-5.3-fast","name":"zai/glm-5.3-fast"},{"value":"zai/glm-5.3","name":"zai/glm-5.3"},{"value":"nvidia/nemotron-3.5-lightning","name":"nvidia/nemotron-3.5-lightning"},{"value":"moonshotai/kimi-k3-fast","name":"moonshotai/kimi-k3-fast"},{"value":"moonshotai/kimi-k3","name":"moonshotai/kimi-k3"},{"value":"zai/glm-5.2-fast","name":"zai/glm-5.2-fast"},{"value":"zai/glm-5.2","name":"zai/glm-5.2"},{"value":"nvidia/nemotron-3-ultra-550b-a55b","name":"nvidia/nemotron-3-ultra-550b-a55b"},{"value":"spacexai/grok-build-0.1","name":"spacexai/grok-build-0.1"},{"value":"nvidia/nemotron-3-super-120b-a12b","name":"nvidia/nemotron-3-super-120b-a12b"},{"value":"zai/glm-5","name":"zai/glm-5"},{"value":"moonshotai/kimi-k2.5","name":"moonshotai/kimi-k2.5"},{"value":"zai/glm-4.7","name":"zai/glm-4.7"},{"value":"nvidia/nemotron-nano-12b-v2-vl","name":"nvidia/nemotron-nano-12b-v2-vl"},{"value":"nvidia/nemotron-nano-9b-v2","name":"nvidia/nemotron-nano-9b-v2"},{"value":"amazon/nova-micro","name":"amazon/nova-micro"},{"value":"deepseek/deepseek-v4.1-flash","name":"deepseek/deepseek-v4.1-flash"},{"value":"deepseek/deepseek-v4-flash","name":"deepseek/deepseek-v4-flash"},{"value":"deepseek/deepseek-v4-flash-0731","name":"deepseek/deepseek-v4-flash-0731"},{"value":"zai/glm-5.3-flash","name":"zai/glm-5.3-flash"},{"value":"zai/glm-4.7-flash","name":"zai/glm-4.7-flash"},{"value":"anthropic/claude-haiku-5.5","name":"anthropic/claude-haiku-5.5"},{"value":"anthropic/claude-haiku-4.5","name":"anthropic/claude-haiku-4.5"},{"value":"anthropic/claude-3-haiku","name":"anthropic/claude-3-haiku"},{"value":"openai/gpt-5.4-mini","name":"openai/gpt-5.4-mini"},{"value":"openai/gpt-5.4-mini-fast","name":"openai/gpt-5.4-mini-fast"},{"value":"openai/gpt-5-mini","name":"openai/gpt-5-mini"},{"value":"openai/gpt-5-mini-fast","name":"openai/gpt-5-mini-fast"},{"value":"openai/gpt-4.1-mini","name":"openai/gpt-4.1-mini"},{"value":"openai/gpt-4.1-mini-fast","name":"openai/gpt-4.1-mini-fast"},{"value":"openai/o4-mini","name":"openai/o4-mini"},{"value":"openai/o4-mini-fast","name":"openai/o4-mini-fast"},{"value":"openai/o3-mini","name":"openai/o3-mini"},{"value":"openai/gpt-4o-mini","name":"openai/gpt-4o-mini"},{"value":"openai/gpt-4o-mini-fast","name":"openai/gpt-4o-mini-fast"},{"value":"google/gemini-3.8-flash","name":"google/gemini-3.8-flash"},{"value":"google/gemini-3.7-flash","name":"google/gemini-3.7-flash"},{"value":"google/gemini-3.5-flash-lite","name":"google/gemini-3.5-flash-lite"},{"value":"google/gemini-3.6-flash","name":"google/gemini-3.6-flash"},{"value":"google/gemini-3.5-flash","name":"google/gemini-3.5-flash"},{"value":"google/gemini-3.1-flash-lite","name":"google/gemini-3.1-flash-lite"},{"value":"google/gemini-3-flash","name":"google/gemini-3-flash"},{"value":"google/gemini-2.5-flash-lite","name":"google/gemini-2.5-flash-lite"},{"value":"google/gemini-2.5-flash","name":"google/gemini-2.5-flash"},{"value":"google/gemini-2.5-pro","name":"google/gemini-2.5-pro"},{"value":"minimax/minimax-m3","name":"minimax/minimax-m3"},{"value":"minimax/minimax-m2.5","name":"minimax/minimax-m2.5"},{"value":"minimax/minimax-m2.1","name":"minimax/minimax-m2.1"},{"value":"amazon/nova-2-lite","name":"amazon/nova-2-lite"},{"value":"amazon/nova-lite","name":"amazon/nova-lite"},{"value":"google/gemini-3.1-pro-preview","name":"google/gemini-3.1-pro-preview"},{"value":"spacexai/grok-4.20-multi-agent-beta","name":"spacexai/grok-4.20-multi-agent-beta"},{"value":"spacexai/grok-4.20-non-reasoning-beta","name":"spacexai/grok-4.20-non-reasoning-beta"},{"value":"spacexai/grok-4.20-reasoning-beta","name":"spacexai/grok-4.20-reasoning-beta"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"code","name":"Code","description":"Write and modify code with full tool access","permissionMode":"auto"},{"value":"ask","name":"Ask","description":"Request permission before making any changes","permissionMode":"ask"}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"xhigh","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"code","name":"Code","description":"Write and modify code with full tool access"},{"id":"ask","name":"Ask","description":"Request permission before making any changes"}]}}}} {"type":"emit_inbound","label":"notification:session/update:available_commands_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}} {"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"effort","value":"medium"}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/fx_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/fx_transcript.ndjson index 1f9c4cd5e1cfe..23b12ea6cacfa 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/fx_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/fx_transcript.ndjson @@ -1,7 +1,7 @@ {"type":"transcript_start","provider":"fx","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"tool_call_read_only_on_request","metadata":{"generatedBy":"live-fx-recorder","fxVersion":"0.0.13","normalization":"Session ids are fx-session-NN, the workspace is , HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are . User skill names, emails and token-shaped strings are removed. Timestamps are kept as recorded.","droppedFrames":0}} {"type":"expect_outbound","label":"request:initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"","capabilities":"","clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"session":{"notices":{},"compaction":{}},"elicitation":{"form":{}}},"clientInfo":""}}} {"type":"emit_inbound","label":"response:initialize","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":true,"audio":false,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":true,"acp":true},"sessionCapabilities":{"list":{},"resume":{},"close":{},"systemPrompt":{}},"_meta":{"fx":{"steering":true}}},"agentInfo":{"name":"fx","title":"fx","version":"0.0.13"},"authMethods":[]}}} -{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","_meta":{"fx":{"profileMcpServers":true}},"mcpServers":""}}} {"type":"emit_inbound","label":"response:session/new","frame":{"kind":"response","method":"session/new","result":{"sessionId":"fx-session-01","configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"gateway","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"anthropic/claude-opus-5.5","options":[{"value":"anthropic/claude-sonnet-5.5","name":"anthropic/claude-sonnet-5.5"},{"value":"anthropic/claude-opus-5.5","name":"anthropic/claude-opus-5.5"},{"value":"anthropic/claude-opus-5.5-fast","name":"anthropic/claude-opus-5.5-fast"},{"value":"anthropic/claude-opus-5","name":"anthropic/claude-opus-5"},{"value":"anthropic/claude-opus-5-fast","name":"anthropic/claude-opus-5-fast"},{"value":"anthropic/claude-sonnet-5","name":"anthropic/claude-sonnet-5"},{"value":"anthropic/claude-opus-4.8","name":"anthropic/claude-opus-4.8"},{"value":"anthropic/claude-opus-4.8-fast","name":"anthropic/claude-opus-4.8-fast"},{"value":"anthropic/claude-opus-4.7","name":"anthropic/claude-opus-4.7"},{"value":"anthropic/claude-sonnet-4.6","name":"anthropic/claude-sonnet-4.6"},{"value":"anthropic/claude-opus-4.6","name":"anthropic/claude-opus-4.6"},{"value":"anthropic/claude-opus-4.5","name":"anthropic/claude-opus-4.5"},{"value":"anthropic/claude-sonnet-4.5","name":"anthropic/claude-sonnet-4.5"},{"value":"anthropic/claude-opus-4","name":"anthropic/claude-opus-4"},{"value":"anthropic/claude-sonnet-4","name":"anthropic/claude-sonnet-4"},{"value":"openai/gpt-5.6-luna","name":"openai/gpt-5.6-luna"},{"value":"openai/gpt-5.6-luna-fast","name":"openai/gpt-5.6-luna-fast"},{"value":"openai/gpt-5.6-sol","name":"openai/gpt-5.6-sol"},{"value":"openai/gpt-5.6-sol-fast","name":"openai/gpt-5.6-sol-fast"},{"value":"openai/gpt-5.6-terra","name":"openai/gpt-5.6-terra"},{"value":"openai/gpt-5.6-terra-fast","name":"openai/gpt-5.6-terra-fast"},{"value":"openai/gpt-5.5","name":"openai/gpt-5.5"},{"value":"openai/gpt-5.5-fast","name":"openai/gpt-5.5-fast"},{"value":"openai/gpt-5.5-pro","name":"openai/gpt-5.5-pro"},{"value":"openai/gpt-5.4-nano","name":"openai/gpt-5.4-nano"},{"value":"openai/gpt-5.4","name":"openai/gpt-5.4"},{"value":"openai/gpt-5.4-fast","name":"openai/gpt-5.4-fast"},{"value":"openai/gpt-5.4-pro","name":"openai/gpt-5.4-pro"},{"value":"openai/gpt-5.3-codex","name":"openai/gpt-5.3-codex"},{"value":"openai/gpt-5.3-codex-fast","name":"openai/gpt-5.3-codex-fast"},{"value":"openai/gpt-5.2","name":"openai/gpt-5.2"},{"value":"openai/gpt-5.2-fast","name":"openai/gpt-5.2-fast"},{"value":"openai/gpt-5.2-pro","name":"openai/gpt-5.2-pro"},{"value":"openai/gpt-5.1-thinking","name":"openai/gpt-5.1-thinking"},{"value":"openai/gpt-5.1-thinking-fast","name":"openai/gpt-5.1-thinking-fast"},{"value":"openai/gpt-5-pro","name":"openai/gpt-5-pro"},{"value":"openai/gpt-5","name":"openai/gpt-5"},{"value":"openai/gpt-5-fast","name":"openai/gpt-5-fast"},{"value":"openai/gpt-5-nano","name":"openai/gpt-5-nano"},{"value":"openai/o3-pro","name":"openai/o3-pro"},{"value":"openai/o3","name":"openai/o3"},{"value":"openai/o3-fast","name":"openai/o3-fast"},{"value":"openai/o1","name":"openai/o1"},{"value":"deepseek/deepseek-v4-pro-0813","name":"deepseek/deepseek-v4-pro-0813"},{"value":"deepseek/deepseek-v4-pro","name":"deepseek/deepseek-v4-pro"},{"value":"spacexai/grok-4.7","name":"spacexai/grok-4.7"},{"value":"spacexai/grok-4.6","name":"spacexai/grok-4.6"},{"value":"spacexai/grok-4.5","name":"spacexai/grok-4.5"},{"value":"spacexai/grok-4.3","name":"spacexai/grok-4.3"},{"value":"spacexai/grok-4.20-multi-agent","name":"spacexai/grok-4.20-multi-agent"},{"value":"spacexai/grok-4.20-non-reasoning","name":"spacexai/grok-4.20-non-reasoning"},{"value":"spacexai/grok-4.20-reasoning","name":"spacexai/grok-4.20-reasoning"},{"value":"spacexai/grok-4.1-fast-non-reasoning","name":"spacexai/grok-4.1-fast-non-reasoning"},{"value":"spacexai/grok-4.1-fast-reasoning","name":"spacexai/grok-4.1-fast-reasoning"},{"value":"amazon/nova-pro","name":"amazon/nova-pro"},{"value":"anthropic/claude-fable-5.1","name":"anthropic/claude-fable-5.1"},{"value":"anthropic/claude-fable-5","name":"anthropic/claude-fable-5"},{"value":"openai/gpt-6.1-sol","name":"openai/gpt-6.1-sol"},{"value":"openai/gpt-6.1-sol-fast","name":"openai/gpt-6.1-sol-fast"},{"value":"openai/gpt-6-luna","name":"openai/gpt-6-luna"},{"value":"openai/gpt-6-luna-fast","name":"openai/gpt-6-luna-fast"},{"value":"openai/gpt-6-sol","name":"openai/gpt-6-sol"},{"value":"openai/gpt-6-sol-fast","name":"openai/gpt-6-sol-fast"},{"value":"openai/gpt-6-astra","name":"openai/gpt-6-astra"},{"value":"openai/gpt-6-astra-fast","name":"openai/gpt-6-astra-fast"},{"value":"openai/gpt-oss-safeguard-120b","name":"openai/gpt-oss-safeguard-120b"},{"value":"openai/gpt-oss-safeguard-20b","name":"openai/gpt-oss-safeguard-20b"},{"value":"openai/gpt-oss-120b","name":"openai/gpt-oss-120b"},{"value":"openai/gpt-oss-20b","name":"openai/gpt-oss-20b"},{"value":"openai/gpt-4.1","name":"openai/gpt-4.1"},{"value":"openai/gpt-4.1-fast","name":"openai/gpt-4.1-fast"},{"value":"openai/gpt-4.1-nano","name":"openai/gpt-4.1-nano"},{"value":"openai/gpt-4.1-nano-fast","name":"openai/gpt-4.1-nano-fast"},{"value":"openai/gpt-4o","name":"openai/gpt-4o"},{"value":"openai/gpt-4o-fast","name":"openai/gpt-4o-fast"},{"value":"openai/gpt-4-turbo","name":"openai/gpt-4-turbo"},{"value":"openai/gpt-3.5-turbo","name":"openai/gpt-3.5-turbo"},{"value":"google/gemma-4-26b-a4b-it","name":"google/gemma-4-26b-a4b-it"},{"value":"deepseek/deepseek-v3.2","name":"deepseek/deepseek-v3.2"},{"value":"deepseek/deepseek-v3.2-thinking","name":"deepseek/deepseek-v3.2-thinking"},{"value":"deepseek/deepseek-r1","name":"deepseek/deepseek-r1"},{"value":"meta/llama-4-maverick","name":"meta/llama-4-maverick"},{"value":"meta/llama-4-scout","name":"meta/llama-4-scout"},{"value":"meta/llama-3.3-70b","name":"meta/llama-3.3-70b"},{"value":"meta/llama-3.1-70b","name":"meta/llama-3.1-70b"},{"value":"meta/llama-3.1-8b","name":"meta/llama-3.1-8b"},{"value":"alibaba/qwen3.8-2.4t-a95b","name":"alibaba/qwen3.8-2.4t-a95b"},{"value":"alibaba/qwen3.8-max","name":"alibaba/qwen3.8-max"},{"value":"alibaba/qwen3-next-80b-a3b-instruct","name":"alibaba/qwen3-next-80b-a3b-instruct"},{"value":"alibaba/qwen3-next-80b-a3b-thinking","name":"alibaba/qwen3-next-80b-a3b-thinking"},{"value":"alibaba/qwen3-coder-30b-a3b","name":"alibaba/qwen3-coder-30b-a3b"},{"value":"alibaba/qwen3-coder","name":"alibaba/qwen3-coder"},{"value":"alibaba/qwen3-coder-next","name":"alibaba/qwen3-coder-next"},{"value":"alibaba/qwen-3-235b","name":"alibaba/qwen-3-235b"},{"value":"alibaba/qwen-3-32b","name":"alibaba/qwen-3-32b"},{"value":"fireworks/ember-1","name":"fireworks/ember-1"},{"value":"zai/glm-5.3-fast","name":"zai/glm-5.3-fast"},{"value":"zai/glm-5.3","name":"zai/glm-5.3"},{"value":"nvidia/nemotron-3.5-lightning","name":"nvidia/nemotron-3.5-lightning"},{"value":"moonshotai/kimi-k3-fast","name":"moonshotai/kimi-k3-fast"},{"value":"moonshotai/kimi-k3","name":"moonshotai/kimi-k3"},{"value":"zai/glm-5.2-fast","name":"zai/glm-5.2-fast"},{"value":"zai/glm-5.2","name":"zai/glm-5.2"},{"value":"nvidia/nemotron-3-ultra-550b-a55b","name":"nvidia/nemotron-3-ultra-550b-a55b"},{"value":"spacexai/grok-build-0.1","name":"spacexai/grok-build-0.1"},{"value":"nvidia/nemotron-3-super-120b-a12b","name":"nvidia/nemotron-3-super-120b-a12b"},{"value":"zai/glm-5","name":"zai/glm-5"},{"value":"moonshotai/kimi-k2.5","name":"moonshotai/kimi-k2.5"},{"value":"zai/glm-4.7","name":"zai/glm-4.7"},{"value":"nvidia/nemotron-nano-12b-v2-vl","name":"nvidia/nemotron-nano-12b-v2-vl"},{"value":"nvidia/nemotron-nano-9b-v2","name":"nvidia/nemotron-nano-9b-v2"},{"value":"amazon/nova-micro","name":"amazon/nova-micro"},{"value":"deepseek/deepseek-v4.1-flash","name":"deepseek/deepseek-v4.1-flash"},{"value":"deepseek/deepseek-v4-flash","name":"deepseek/deepseek-v4-flash"},{"value":"deepseek/deepseek-v4-flash-0731","name":"deepseek/deepseek-v4-flash-0731"},{"value":"zai/glm-5.3-flash","name":"zai/glm-5.3-flash"},{"value":"zai/glm-4.7-flash","name":"zai/glm-4.7-flash"},{"value":"anthropic/claude-haiku-5.5","name":"anthropic/claude-haiku-5.5"},{"value":"anthropic/claude-haiku-4.5","name":"anthropic/claude-haiku-4.5"},{"value":"anthropic/claude-3-haiku","name":"anthropic/claude-3-haiku"},{"value":"openai/gpt-5.4-mini","name":"openai/gpt-5.4-mini"},{"value":"openai/gpt-5.4-mini-fast","name":"openai/gpt-5.4-mini-fast"},{"value":"openai/gpt-5-mini","name":"openai/gpt-5-mini"},{"value":"openai/gpt-5-mini-fast","name":"openai/gpt-5-mini-fast"},{"value":"openai/gpt-4.1-mini","name":"openai/gpt-4.1-mini"},{"value":"openai/gpt-4.1-mini-fast","name":"openai/gpt-4.1-mini-fast"},{"value":"openai/o4-mini","name":"openai/o4-mini"},{"value":"openai/o4-mini-fast","name":"openai/o4-mini-fast"},{"value":"openai/o3-mini","name":"openai/o3-mini"},{"value":"openai/gpt-4o-mini","name":"openai/gpt-4o-mini"},{"value":"openai/gpt-4o-mini-fast","name":"openai/gpt-4o-mini-fast"},{"value":"google/gemini-3.8-flash","name":"google/gemini-3.8-flash"},{"value":"google/gemini-3.7-flash","name":"google/gemini-3.7-flash"},{"value":"google/gemini-3.5-flash-lite","name":"google/gemini-3.5-flash-lite"},{"value":"google/gemini-3.6-flash","name":"google/gemini-3.6-flash"},{"value":"google/gemini-3.5-flash","name":"google/gemini-3.5-flash"},{"value":"google/gemini-3.1-flash-lite","name":"google/gemini-3.1-flash-lite"},{"value":"google/gemini-3-flash","name":"google/gemini-3-flash"},{"value":"google/gemini-2.5-flash-lite","name":"google/gemini-2.5-flash-lite"},{"value":"google/gemini-2.5-flash","name":"google/gemini-2.5-flash"},{"value":"google/gemini-2.5-pro","name":"google/gemini-2.5-pro"},{"value":"minimax/minimax-m3","name":"minimax/minimax-m3"},{"value":"minimax/minimax-m2.5","name":"minimax/minimax-m2.5"},{"value":"minimax/minimax-m2.1","name":"minimax/minimax-m2.1"},{"value":"amazon/nova-2-lite","name":"amazon/nova-2-lite"},{"value":"amazon/nova-lite","name":"amazon/nova-lite"},{"value":"google/gemini-3.1-pro-preview","name":"google/gemini-3.1-pro-preview"},{"value":"spacexai/grok-4.20-multi-agent-beta","name":"spacexai/grok-4.20-multi-agent-beta"},{"value":"spacexai/grok-4.20-non-reasoning-beta","name":"spacexai/grok-4.20-non-reasoning-beta"},{"value":"spacexai/grok-4.20-reasoning-beta","name":"spacexai/grok-4.20-reasoning-beta"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"code","name":"Code","description":"Write and modify code with full tool access","permissionMode":"auto"},{"value":"ask","name":"Ask","description":"Request permission before making any changes","permissionMode":"ask"}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"xhigh","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"code","name":"Code","description":"Write and modify code with full tool access"},{"id":"ask","name":"Ask","description":"Request permission before making any changes"}]}}}} {"type":"emit_inbound","label":"notification:session/update:available_commands_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}} {"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"effort","value":"medium"}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/fx_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/fx_transcript.ndjson index 23191a20397de..cd3e07191adb4 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/fx_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/fx_transcript.ndjson @@ -1,7 +1,7 @@ {"type":"transcript_start","provider":"fx","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"turn_interrupt","metadata":{"generatedBy":"live-fx-recorder","fxVersion":"0.0.13","normalization":"Session ids are fx-session-NN, the workspace is , HOME is /home/fx-replay and the recording user is fx-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are . User skill names, emails and token-shaped strings are removed. Timestamps are kept as recorded.","droppedFrames":0}} {"type":"expect_outbound","label":"request:initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"","capabilities":"","clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"session":{"notices":{},"compaction":{}},"elicitation":{"form":{}}},"clientInfo":""}}} {"type":"emit_inbound","label":"response:initialize","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":true,"audio":false,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":true,"acp":true},"sessionCapabilities":{"list":{},"resume":{},"close":{},"systemPrompt":{}},"_meta":{"fx":{"steering":true}}},"agentInfo":{"name":"fx","title":"fx","version":"0.0.13"},"authMethods":[]}}} -{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"expect_outbound","label":"request:session/new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","_meta":{"fx":{"profileMcpServers":true}},"mcpServers":""}}} {"type":"emit_inbound","label":"response:session/new","frame":{"kind":"response","method":"session/new","result":{"sessionId":"fx-session-01","configOptions":[{"id":"provider","name":"Provider","category":"model","type":"select","currentValue":"gateway","options":[{"value":"gateway","name":"Vercel AI Gateway"},{"value":"codex","name":"Codex subscription"},{"value":"grok","name":"Grok subscription"}]},{"id":"model","name":"Model","category":"model","type":"select","currentValue":"anthropic/claude-opus-5.5","options":[{"value":"anthropic/claude-sonnet-5.5","name":"anthropic/claude-sonnet-5.5"},{"value":"anthropic/claude-opus-5.5","name":"anthropic/claude-opus-5.5"},{"value":"anthropic/claude-opus-5.5-fast","name":"anthropic/claude-opus-5.5-fast"},{"value":"anthropic/claude-opus-5","name":"anthropic/claude-opus-5"},{"value":"anthropic/claude-opus-5-fast","name":"anthropic/claude-opus-5-fast"},{"value":"anthropic/claude-sonnet-5","name":"anthropic/claude-sonnet-5"},{"value":"anthropic/claude-opus-4.8","name":"anthropic/claude-opus-4.8"},{"value":"anthropic/claude-opus-4.8-fast","name":"anthropic/claude-opus-4.8-fast"},{"value":"anthropic/claude-opus-4.7","name":"anthropic/claude-opus-4.7"},{"value":"anthropic/claude-sonnet-4.6","name":"anthropic/claude-sonnet-4.6"},{"value":"anthropic/claude-opus-4.6","name":"anthropic/claude-opus-4.6"},{"value":"anthropic/claude-opus-4.5","name":"anthropic/claude-opus-4.5"},{"value":"anthropic/claude-sonnet-4.5","name":"anthropic/claude-sonnet-4.5"},{"value":"anthropic/claude-opus-4","name":"anthropic/claude-opus-4"},{"value":"anthropic/claude-sonnet-4","name":"anthropic/claude-sonnet-4"},{"value":"openai/gpt-5.6-luna","name":"openai/gpt-5.6-luna"},{"value":"openai/gpt-5.6-luna-fast","name":"openai/gpt-5.6-luna-fast"},{"value":"openai/gpt-5.6-sol","name":"openai/gpt-5.6-sol"},{"value":"openai/gpt-5.6-sol-fast","name":"openai/gpt-5.6-sol-fast"},{"value":"openai/gpt-5.6-terra","name":"openai/gpt-5.6-terra"},{"value":"openai/gpt-5.6-terra-fast","name":"openai/gpt-5.6-terra-fast"},{"value":"openai/gpt-5.5","name":"openai/gpt-5.5"},{"value":"openai/gpt-5.5-fast","name":"openai/gpt-5.5-fast"},{"value":"openai/gpt-5.5-pro","name":"openai/gpt-5.5-pro"},{"value":"openai/gpt-5.4-nano","name":"openai/gpt-5.4-nano"},{"value":"openai/gpt-5.4","name":"openai/gpt-5.4"},{"value":"openai/gpt-5.4-fast","name":"openai/gpt-5.4-fast"},{"value":"openai/gpt-5.4-pro","name":"openai/gpt-5.4-pro"},{"value":"openai/gpt-5.3-codex","name":"openai/gpt-5.3-codex"},{"value":"openai/gpt-5.3-codex-fast","name":"openai/gpt-5.3-codex-fast"},{"value":"openai/gpt-5.2","name":"openai/gpt-5.2"},{"value":"openai/gpt-5.2-fast","name":"openai/gpt-5.2-fast"},{"value":"openai/gpt-5.2-pro","name":"openai/gpt-5.2-pro"},{"value":"openai/gpt-5.1-thinking","name":"openai/gpt-5.1-thinking"},{"value":"openai/gpt-5.1-thinking-fast","name":"openai/gpt-5.1-thinking-fast"},{"value":"openai/gpt-5-pro","name":"openai/gpt-5-pro"},{"value":"openai/gpt-5","name":"openai/gpt-5"},{"value":"openai/gpt-5-fast","name":"openai/gpt-5-fast"},{"value":"openai/gpt-5-nano","name":"openai/gpt-5-nano"},{"value":"openai/o3-pro","name":"openai/o3-pro"},{"value":"openai/o3","name":"openai/o3"},{"value":"openai/o3-fast","name":"openai/o3-fast"},{"value":"openai/o1","name":"openai/o1"},{"value":"deepseek/deepseek-v4-pro-0813","name":"deepseek/deepseek-v4-pro-0813"},{"value":"deepseek/deepseek-v4-pro","name":"deepseek/deepseek-v4-pro"},{"value":"spacexai/grok-4.7","name":"spacexai/grok-4.7"},{"value":"spacexai/grok-4.6","name":"spacexai/grok-4.6"},{"value":"spacexai/grok-4.5","name":"spacexai/grok-4.5"},{"value":"spacexai/grok-4.3","name":"spacexai/grok-4.3"},{"value":"spacexai/grok-4.20-multi-agent","name":"spacexai/grok-4.20-multi-agent"},{"value":"spacexai/grok-4.20-non-reasoning","name":"spacexai/grok-4.20-non-reasoning"},{"value":"spacexai/grok-4.20-reasoning","name":"spacexai/grok-4.20-reasoning"},{"value":"spacexai/grok-4.1-fast-non-reasoning","name":"spacexai/grok-4.1-fast-non-reasoning"},{"value":"spacexai/grok-4.1-fast-reasoning","name":"spacexai/grok-4.1-fast-reasoning"},{"value":"amazon/nova-pro","name":"amazon/nova-pro"},{"value":"anthropic/claude-fable-5.1","name":"anthropic/claude-fable-5.1"},{"value":"anthropic/claude-fable-5","name":"anthropic/claude-fable-5"},{"value":"openai/gpt-6.1-sol","name":"openai/gpt-6.1-sol"},{"value":"openai/gpt-6.1-sol-fast","name":"openai/gpt-6.1-sol-fast"},{"value":"openai/gpt-6-luna","name":"openai/gpt-6-luna"},{"value":"openai/gpt-6-luna-fast","name":"openai/gpt-6-luna-fast"},{"value":"openai/gpt-6-sol","name":"openai/gpt-6-sol"},{"value":"openai/gpt-6-sol-fast","name":"openai/gpt-6-sol-fast"},{"value":"openai/gpt-6-astra","name":"openai/gpt-6-astra"},{"value":"openai/gpt-6-astra-fast","name":"openai/gpt-6-astra-fast"},{"value":"openai/gpt-oss-safeguard-120b","name":"openai/gpt-oss-safeguard-120b"},{"value":"openai/gpt-oss-safeguard-20b","name":"openai/gpt-oss-safeguard-20b"},{"value":"openai/gpt-oss-120b","name":"openai/gpt-oss-120b"},{"value":"openai/gpt-oss-20b","name":"openai/gpt-oss-20b"},{"value":"openai/gpt-4.1","name":"openai/gpt-4.1"},{"value":"openai/gpt-4.1-fast","name":"openai/gpt-4.1-fast"},{"value":"openai/gpt-4.1-nano","name":"openai/gpt-4.1-nano"},{"value":"openai/gpt-4.1-nano-fast","name":"openai/gpt-4.1-nano-fast"},{"value":"openai/gpt-4o","name":"openai/gpt-4o"},{"value":"openai/gpt-4o-fast","name":"openai/gpt-4o-fast"},{"value":"openai/gpt-4-turbo","name":"openai/gpt-4-turbo"},{"value":"openai/gpt-3.5-turbo","name":"openai/gpt-3.5-turbo"},{"value":"google/gemma-4-26b-a4b-it","name":"google/gemma-4-26b-a4b-it"},{"value":"deepseek/deepseek-v3.2","name":"deepseek/deepseek-v3.2"},{"value":"deepseek/deepseek-v3.2-thinking","name":"deepseek/deepseek-v3.2-thinking"},{"value":"deepseek/deepseek-r1","name":"deepseek/deepseek-r1"},{"value":"meta/llama-4-maverick","name":"meta/llama-4-maverick"},{"value":"meta/llama-4-scout","name":"meta/llama-4-scout"},{"value":"meta/llama-3.3-70b","name":"meta/llama-3.3-70b"},{"value":"meta/llama-3.1-70b","name":"meta/llama-3.1-70b"},{"value":"meta/llama-3.1-8b","name":"meta/llama-3.1-8b"},{"value":"alibaba/qwen3.8-2.4t-a95b","name":"alibaba/qwen3.8-2.4t-a95b"},{"value":"alibaba/qwen3.8-max","name":"alibaba/qwen3.8-max"},{"value":"alibaba/qwen3-next-80b-a3b-instruct","name":"alibaba/qwen3-next-80b-a3b-instruct"},{"value":"alibaba/qwen3-next-80b-a3b-thinking","name":"alibaba/qwen3-next-80b-a3b-thinking"},{"value":"alibaba/qwen3-coder-30b-a3b","name":"alibaba/qwen3-coder-30b-a3b"},{"value":"alibaba/qwen3-coder","name":"alibaba/qwen3-coder"},{"value":"alibaba/qwen3-coder-next","name":"alibaba/qwen3-coder-next"},{"value":"alibaba/qwen-3-235b","name":"alibaba/qwen-3-235b"},{"value":"alibaba/qwen-3-32b","name":"alibaba/qwen-3-32b"},{"value":"fireworks/ember-1","name":"fireworks/ember-1"},{"value":"zai/glm-5.3-fast","name":"zai/glm-5.3-fast"},{"value":"zai/glm-5.3","name":"zai/glm-5.3"},{"value":"nvidia/nemotron-3.5-lightning","name":"nvidia/nemotron-3.5-lightning"},{"value":"moonshotai/kimi-k3-fast","name":"moonshotai/kimi-k3-fast"},{"value":"moonshotai/kimi-k3","name":"moonshotai/kimi-k3"},{"value":"zai/glm-5.2-fast","name":"zai/glm-5.2-fast"},{"value":"zai/glm-5.2","name":"zai/glm-5.2"},{"value":"nvidia/nemotron-3-ultra-550b-a55b","name":"nvidia/nemotron-3-ultra-550b-a55b"},{"value":"spacexai/grok-build-0.1","name":"spacexai/grok-build-0.1"},{"value":"nvidia/nemotron-3-super-120b-a12b","name":"nvidia/nemotron-3-super-120b-a12b"},{"value":"zai/glm-5","name":"zai/glm-5"},{"value":"moonshotai/kimi-k2.5","name":"moonshotai/kimi-k2.5"},{"value":"zai/glm-4.7","name":"zai/glm-4.7"},{"value":"nvidia/nemotron-nano-12b-v2-vl","name":"nvidia/nemotron-nano-12b-v2-vl"},{"value":"nvidia/nemotron-nano-9b-v2","name":"nvidia/nemotron-nano-9b-v2"},{"value":"amazon/nova-micro","name":"amazon/nova-micro"},{"value":"deepseek/deepseek-v4.1-flash","name":"deepseek/deepseek-v4.1-flash"},{"value":"deepseek/deepseek-v4-flash","name":"deepseek/deepseek-v4-flash"},{"value":"deepseek/deepseek-v4-flash-0731","name":"deepseek/deepseek-v4-flash-0731"},{"value":"zai/glm-5.3-flash","name":"zai/glm-5.3-flash"},{"value":"zai/glm-4.7-flash","name":"zai/glm-4.7-flash"},{"value":"anthropic/claude-haiku-5.5","name":"anthropic/claude-haiku-5.5"},{"value":"anthropic/claude-haiku-4.5","name":"anthropic/claude-haiku-4.5"},{"value":"anthropic/claude-3-haiku","name":"anthropic/claude-3-haiku"},{"value":"openai/gpt-5.4-mini","name":"openai/gpt-5.4-mini"},{"value":"openai/gpt-5.4-mini-fast","name":"openai/gpt-5.4-mini-fast"},{"value":"openai/gpt-5-mini","name":"openai/gpt-5-mini"},{"value":"openai/gpt-5-mini-fast","name":"openai/gpt-5-mini-fast"},{"value":"openai/gpt-4.1-mini","name":"openai/gpt-4.1-mini"},{"value":"openai/gpt-4.1-mini-fast","name":"openai/gpt-4.1-mini-fast"},{"value":"openai/o4-mini","name":"openai/o4-mini"},{"value":"openai/o4-mini-fast","name":"openai/o4-mini-fast"},{"value":"openai/o3-mini","name":"openai/o3-mini"},{"value":"openai/gpt-4o-mini","name":"openai/gpt-4o-mini"},{"value":"openai/gpt-4o-mini-fast","name":"openai/gpt-4o-mini-fast"},{"value":"google/gemini-3.8-flash","name":"google/gemini-3.8-flash"},{"value":"google/gemini-3.7-flash","name":"google/gemini-3.7-flash"},{"value":"google/gemini-3.5-flash-lite","name":"google/gemini-3.5-flash-lite"},{"value":"google/gemini-3.6-flash","name":"google/gemini-3.6-flash"},{"value":"google/gemini-3.5-flash","name":"google/gemini-3.5-flash"},{"value":"google/gemini-3.1-flash-lite","name":"google/gemini-3.1-flash-lite"},{"value":"google/gemini-3-flash","name":"google/gemini-3-flash"},{"value":"google/gemini-2.5-flash-lite","name":"google/gemini-2.5-flash-lite"},{"value":"google/gemini-2.5-flash","name":"google/gemini-2.5-flash"},{"value":"google/gemini-2.5-pro","name":"google/gemini-2.5-pro"},{"value":"minimax/minimax-m3","name":"minimax/minimax-m3"},{"value":"minimax/minimax-m2.5","name":"minimax/minimax-m2.5"},{"value":"minimax/minimax-m2.1","name":"minimax/minimax-m2.1"},{"value":"amazon/nova-2-lite","name":"amazon/nova-2-lite"},{"value":"amazon/nova-lite","name":"amazon/nova-lite"},{"value":"google/gemini-3.1-pro-preview","name":"google/gemini-3.1-pro-preview"},{"value":"spacexai/grok-4.20-multi-agent-beta","name":"spacexai/grok-4.20-multi-agent-beta"},{"value":"spacexai/grok-4.20-non-reasoning-beta","name":"spacexai/grok-4.20-non-reasoning-beta"},{"value":"spacexai/grok-4.20-reasoning-beta","name":"spacexai/grok-4.20-reasoning-beta"}]},{"id":"mode","name":"Session Mode","description":"Controls how the agent requests permission","category":"mode","type":"select","currentValue":"ask","options":[{"value":"code","name":"Code","description":"Write and modify code with full tool access","permissionMode":"auto"},{"value":"ask","name":"Ask","description":"Request permission before making any changes","permissionMode":"ask"}]},{"id":"effort","name":"Reasoning Effort","description":"Controls how much the model thinks before responding","category":"thought_level","type":"select","currentValue":"xhigh","options":[{"value":"auto","name":"default"},{"value":"low","name":"low"},{"value":"medium","name":"medium"},{"value":"high","name":"high"},{"value":"xhigh","name":"xhigh"},{"value":"max","name":"max"}]}],"modes":{"currentModeId":"ask","availableModes":[{"id":"code","name":"Code","description":"Write and modify code with full tool access"},{"id":"ask","name":"Ask","description":"Request permission before making any changes"}]}}}} {"type":"emit_inbound","label":"notification:session/update:available_commands_update","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"fx-session-01","update":{"sessionUpdate":"available_commands_update","availableCommands":[]}}}} {"type":"expect_outbound","label":"request:session/set_config_option","frame":{"kind":"request","method":"session/set_config_option","params":{"sessionId":"fx-session-01","configId":"effort","value":"medium"}}} diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts index baae43ed7f768..5f53bfdf5b9dd 100644 --- a/apps/server/src/peer/PeerForwarding.test.ts +++ b/apps/server/src/peer/PeerForwarding.test.ts @@ -14,10 +14,12 @@ import { } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; 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 Ref from "effect/Ref"; +import * as TestClock from "effect/testing/TestClock"; import { McpSchema, McpServer } from "effect/ai"; import * as ServerConfig from "../config.ts"; @@ -705,3 +707,36 @@ it.effect("refuses what a linked environment cannot take before anything leaves" }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); + +it.effect("refuses a launch there above the link's access, naming the link", () => + Effect.scoped( + Effect.gen(function* () { + const seen = yield* Ref.make(nothingSeen); + const linkSession = yield* Ref.make(""); + const b = yield* serveBox(seen, linkSession); + const a = yield* makeLaptop; + yield* linkTo(a.links, b, "auto"); + yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId); + + // A full-access agent here asks for more than the link allows there. + const launchAboveLink = a.call("thread:laptop-full", "t3_thread_launch", { + environmentId: box.environmentId, + projectId: boxProject, + title: "Run the suite there", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, + message: "Run the suite.", + runtimeMode: "full-access", + }); + const { message } = failureOf(yield* launchAboveLink); + expect(message).toContain('"Box"'); + expect(message).toContain("auto"); + expect(message).toContain("full-access"); + expect(message).not.toContain("parent mode"); + expect((yield* Ref.get(seen)).launches).toEqual([]); + + // Once the link has expired, that is what the agent needs to hear. + yield* TestClock.adjust(Duration.days(31)); + expect(failureOf(yield* launchAboveLink).message).toContain("expired"); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.ts index f6fdb40beede0..080f701c45cb2 100644 --- a/apps/server/src/peer/PeerForwarding.ts +++ b/apps/server/src/peer/PeerForwarding.ts @@ -8,6 +8,8 @@ import { OrchestratorMcpThreadReadResult, OrchestratorMcpThreadWaitInput, OrchestratorMcpThreadWaitResult, + type PeerLinkError, + RuntimeMode, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; @@ -15,9 +17,11 @@ import * as DateTime from "effect/DateTime"; 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 Schema from "effect/Schema"; import type * as Tool from "effect/ai/Tool"; +import { runtimeModeRank } from "../mcp/delegatedTaskModes.ts"; import { assertNotLinked } from "../mcp/linkOrigin.ts"; import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; import { readCaller, unavailable } from "../mcp/threadAccess.ts"; @@ -82,6 +86,11 @@ export const linkedEnvironmentsOff = new OrchestratorMcpFailure({ "Linked environments is off on this machine, so no tool can act on another machine. Leave out environmentId to work here; the user can turn it on in Settings → Labs.", }); +const isRuntimeMode = Schema.is(RuntimeMode); + +const linkStorageFailure = (error: PeerLinkError) => + new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }); + /** The linked environment a call names, or nothing when it names this one. */ export const remoteTarget = (scope: Scope, environmentId: EnvironmentId | undefined) => environmentId === scope.environmentId ? undefined : environmentId; @@ -116,6 +125,28 @@ const make = Effect.gen(function* () { Effect.orDie, ); + /** + * The linked environment refuses a mode above the link's access too, but as + * "broader than parent mode", which misleads when the parent here is broader. + * A read-only link refuses the launch there with its own capability error, + * and an expired one is left to say it expired. + */ + const assertWithinLinkAccess = Effect.fn("PeerForwarding.assertWithinLinkAccess")(function* ( + environmentId: EnvironmentId, + requested: unknown, + ) { + if (!isRuntimeMode(requested)) return; + const link = yield* links.get(environmentId).pipe(Effect.mapError(linkStorageFailure)); + if (Option.isNone(link)) return; + if (DateTime.isLessThanOrEqualTo(link.value.expiresAt, yield* DateTime.now)) return; + const { label, access } = link.value; + if (access === "read-only" || runtimeModeRank(requested) <= runtimeModeRank(access)) return; + return yield* new OrchestratorMcpFailure({ + code: "runtime_mode_escalation_denied", + message: `Linked environment "${label}" was linked with ${access} access, so work there cannot run in ${requested}. Omit runtimeMode to run it at a mode up to ${access}, or link it again with broader access.`, + }); + }); + /** Tool and contract schemas are plain data: they encode and decode without services. */ const forward = Effect.fn("PeerForwarding.forward")(function*
( scope: Scope, @@ -130,6 +161,7 @@ const make = Effect.gen(function* () { params, ).pipe(Effect.mapError(unavailable))) as Record; const { environmentId: _target, ...args } = encoded; + yield* assertWithinLinkAccess(environmentId, args.runtimeMode); // A pending upload lives here, so it cannot go with the call. if (Array.isArray(args.attachments) && args.attachments.length > 0) { return yield* new OrchestratorMcpFailure({ @@ -230,12 +262,7 @@ const make = Effect.gen(function* () { function* (scope) { yield* forwardingCaller(scope); yield* requireEnabled; - const listed = yield* links.list.pipe( - Effect.mapError( - (error) => - new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }), - ), - ); + const listed = yield* links.list.pipe(Effect.mapError(linkStorageFailure)); return { environmentId: scope.environmentId, links: listed.map((link) => ({ diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts index fcb682ab03faf..6923037b6f7c4 100644 --- a/apps/server/src/peer/PeerLinks.test.ts +++ b/apps/server/src/peer/PeerLinks.test.ts @@ -444,6 +444,38 @@ it.effect("lists a peer as reachable at another address while its first one slee ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect("resolves a link at its answering address without waiting out a sleeping first", () => + Effect.scoped( + Effect.gen(function* () { + const b = yield* serveB(box); + const described = yield* HttpClient.get(`${b.url}/.well-known/t3/environment`).pipe( + Effect.flatMap((response) => response.text), + Effect.provide(FetchHttpClient.layer), + ); + const elsewhere = yield* serveRaw(() => + Effect.succeed(HttpServerResponse.text(described, { contentType: "application/json" })), + ); + const a = yield* makeA(laptop); + const pairing = yield* b.auth.issuePairingCredential(); + yield* a.links.link({ + url: b.url, + alternateUrls: [elsewhere], + pairingCode: pairing.credential, + access: "auto", + }); + + yield* Ref.set(b.asleep, true); + const first = yield* a.links.resolve(box.environmentId).pipe(Effect.forkScoped); + yield* Queue.take(b.unanswered); + yield* TestClock.adjust(Duration.seconds(3)); + expect((yield* Fiber.join(first)).url).toBe(elsewhere); + + // The clock no longer moves: a resolve that probes the sleeping address first never returns. + expect((yield* a.links.resolve(box.environmentId)).url).toBe(elsewhere); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("cancelling a descriptor probe aborts its request and leaves later resolves fresh", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 6325085b5ba51..1b53c9d007a84 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -666,38 +666,39 @@ const make = Effect.gen(function* () { }); } // The token goes only to an address that still answers as this peer, - // so one that now answers as another machine never receives it. - let capabilities: ExecutionEnvironmentCapabilities = { repositoryIdentity: false }; - let label = link.label; - const url = yield* Effect.findFirst(link.urls, (candidate) => - answersAs(candidate, environmentId).pipe( - Effect.map((found) => { - if (Option.isNone(found) || found.value.environmentId !== environmentId) return false; - capabilities = found.value.capabilities; - label = found.value.label; - return true; - }), - ), - ); - if (Option.isNone(url)) { + // so one that now answers as another machine never receives it. The + // addresses race, so a silent one never delays one that answers. + const answered = + link.urls.length === 0 + ? Option.none() + : yield* Effect.raceAll( + link.urls.map((url) => + answersAs(url, environmentId).pipe( + Effect.flatMap(Effect.fromOption), + Effect.map((peer) => ({ url, peer })), + ), + ), + ).pipe(Effect.option); + if (Option.isNone(answered)) { return yield* new PeerLinkError({ reason: "unreachable", message: `${link.label} did not answer at ${link.urls.join(", ")}.`, }); } + const { url, peer } = answered.value; // A link made before the peer had to fence linked work, or a peer moved // back to such a version, would carry work past those limits. - if (!linkLimitsHold({ capabilities })) { + if (!linkLimitsHold(peer)) { return yield* new PeerLinkError({ reason: "incompatible", message: `${link.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`, }); } return { - link: yield* withLabel(link, label), - url: url.value, + link: yield* withLabel(link, peer.label), + url, token: new TextDecoder().decode(stored.value), - capabilities, + capabilities: peer.capabilities, }; }, ); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 840cd922b3611..3863624578578 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -106,6 +106,7 @@ import Migration0091 from "./Migrations/091_AuthConnectDeniedRequests.ts"; import Migration0092 from "./Migrations/092_QueuedTurnInputIndexJsonValid.ts"; import Migration0093 from "./Migrations/093_ProviderTurnAttemptIndex.ts"; import Migration0094 from "./Migrations/094_TurnItemMessageOrdinalIndex.ts"; +import Migration0095 from "./Migrations/095_TurnItemInlineWorkOutput.ts"; // s2code fork: fork migration 4 added this column before upstream shipped it as 71. const peerLinkFenceOnce = Effect.gen(function* () { @@ -211,6 +212,7 @@ const migrationEntries = [ [92, "QueuedTurnInputIndexJsonValid", Migration0092], [93, "ProviderTurnAttemptIndex", Migration0093], [94, "TurnItemMessageOrdinalIndex", Migration0094], + [95, "TurnItemInlineWorkOutput", Migration0095], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/094_TurnItemMessageOrdinalIndex.test.ts b/apps/server/src/persistence/Migrations/094_TurnItemMessageOrdinalIndex.test.ts index 1a8ea4ecfed43..5d76b7d1a95b9 100644 --- a/apps/server/src/persistence/Migrations/094_TurnItemMessageOrdinalIndex.test.ts +++ b/apps/server/src/persistence/Migrations/094_TurnItemMessageOrdinalIndex.test.ts @@ -43,7 +43,7 @@ it.effect("migrates over a message whose payload is not JSON, and takes one afte yield* insertTurnItem("ok-1", "thread-a", 2, "user_message", '{"messageId":"m1"}'); assert.deepEqual( - (yield* runMigrations()).map(([id]) => id), + (yield* runMigrations({ toMigrationInclusive: 94 })).map(([id]) => id), [94], ); yield* insertTurnItem("bad-2", "thread-a", 3, "user_message", "{not json"); diff --git a/apps/server/src/persistence/Migrations/095_TurnItemInlineWorkOutput.test.ts b/apps/server/src/persistence/Migrations/095_TurnItemInlineWorkOutput.test.ts new file mode 100644 index 0000000000000..2b07b076bf0cc --- /dev/null +++ b/apps/server/src/persistence/Migrations/095_TurnItemInlineWorkOutput.test.ts @@ -0,0 +1,47 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; + +const layer = it.layer(NodeSqliteClient.layer({ filename: ":memory:" })); + +layer("095_TurnItemInlineWorkOutput", (it) => { + it.effect("flags existing dynamic tools whose output renders inline", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 94 }); + const rows: ReadonlyArray = [ + ["delegate", "dynamic_tool", { toolName: "mcp__t3_code__delegate_task" }, 1], + ["html", "dynamic_tool", { toolName: "x", output: { htmlRender: {} } }, 1], + ["mcp-app", "dynamic_tool", { toolName: "x", output: { t3McpApp: {} } }, 1], + ["image", "dynamic_tool", { toolName: "view_image", viewedImagePath: "/a.png" }, 1], + ["send", "dynamic_tool", { toolName: "mcp__t3-code__send_to_user" }, 1], + ["sent", "dynamic_tool", { toolName: "execute", output: '{"sentMessage":"Hi"}' }, 1], + ["plain", "dynamic_tool", { toolName: "mcp__docs__search", output: "ok" }, 0], + ["command", "command_execution", { output: "htmlRender" }, 0], + ]; + for (const [id, type, payload] of rows) { + yield* sql` + INSERT INTO orchestration_v2_projection_turn_items ( + turn_item_id, thread_id, ordinal, type, status, updated_at, payload_json + ) VALUES ( + ${id}, 'thread-1', 0, ${type}, 'completed', '2026-11-01T00:00:00.000Z', + ${JSON.stringify({ type, ...payload })} + ) + `; + } + + yield* runMigrations({ toMigrationInclusive: 95 }); + const flagged = yield* sql<{ readonly turn_item_id: string; readonly inline: number }>` + SELECT turn_item_id, inline_work_output AS inline + FROM orchestration_v2_projection_turn_items + `; + assert.deepStrictEqual( + new Map(flagged.map((row) => [row.turn_item_id, row.inline])), + new Map(rows.map(([id, , , inline]) => [id, inline])), + ); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/095_TurnItemInlineWorkOutput.ts b/apps/server/src/persistence/Migrations/095_TurnItemInlineWorkOutput.ts new file mode 100644 index 0000000000000..731dbcc7df1cc --- /dev/null +++ b/apps/server/src/persistence/Migrations/095_TurnItemInlineWorkOutput.ts @@ -0,0 +1,23 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Thread windows read this flag for every row; scanning payloads on each read + // dominated thread open. Keep the predicate in step with ProjectionStore. + yield* sql` + ALTER TABLE orchestration_v2_projection_turn_items + ADD COLUMN inline_work_output INTEGER NOT NULL DEFAULT 0 + `; + yield* sql` + UPDATE orchestration_v2_projection_turn_items + SET inline_work_output = 1 + WHERE type = 'dynamic_tool' AND ( + payload_json LIKE '%htmlRender%' OR payload_json LIKE '%t3McpApp%' + OR payload_json LIKE '%"viewedImagePath"%' + OR payload_json LIKE '%"toolName":"%delegate_task"%' + OR payload_json LIKE '%"toolName":"%send_to_user"%' + OR payload_json LIKE '%sentMessage%') + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 953a2229ce26e..4c5ea36726c4a 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -74,6 +74,7 @@ describe("V2 preview upgrade", () => { [92, "QueuedTurnInputIndexJsonValid"], [93, "ProviderTurnAttemptIndex"], [94, "TurnItemMessageOrdinalIndex"], + [95, "TurnItemInlineWorkOutput"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -191,6 +192,7 @@ describe("V2 preview upgrade", () => { [92, "QueuedTurnInputIndexJsonValid"], [93, "ProviderTurnAttemptIndex"], [94, "TurnItemMessageOrdinalIndex"], + [95, "TurnItemInlineWorkOutput"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/preview/PortScanner.test.ts b/apps/server/src/preview/PortScanner.test.ts index 1ed544910b1bc..d9b226e21f4fe 100644 --- a/apps/server/src/preview/PortScanner.test.ts +++ b/apps/server/src/preview/PortScanner.test.ts @@ -22,6 +22,7 @@ import * as TestClock from "effect/testing/TestClock"; import { expect, vi } from "vite-plus/test"; import { FetchHttpClient } from "effect/http"; +import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as PortScanner from "./PortScanner.ts"; @@ -44,12 +45,18 @@ const processProbeFailure: ProcessRunner.ProcessRunner["Service"]["run"] = (inpu const layerNoProc = FileSystem.layerNoop({}); +const layerForeground = Layer.mock(BackgroundPolicy.BackgroundPolicy)({ + shouldRunOpportunisticWork: Effect.succeed(true), +}); + +const layerScanner = PortScanner.layer.pipe(Layer.provide(layerForeground)); + const layerProbeFailure = ( run: ProcessRunner.ProcessRunner["Service"]["run"], fetch: typeof globalThis.fetch = globalThis.fetch, fileSystem: Layer.Layer = layerNoProc, ) => - PortScanner.layer.pipe( + layerScanner.pipe( Layer.provide( Layer.mergeAll( fileSystem, @@ -86,10 +93,12 @@ const layerLsofScanner = (input: { readonly pid: () => number; readonly fetch: typeof globalThis.fetch; readonly stdout?: () => string; + readonly backgroundPolicy?: Layer.Layer; }) => PortScanner.layer.pipe( Layer.provide( Layer.mergeAll( + input.backgroundPolicy ?? layerForeground, layerNoProc, Layer.succeed(ProcessRunner.ProcessRunner, { run: () => @@ -287,6 +296,41 @@ effectIt.effect("stops probing a subscriber's configured paths after its scope c }).pipe(Effect.scoped, Effect.provide(layer)); }); +effectIt.effect("skips scheduled scans while no client is in the foreground", () => { + let lsofRuns = 0; + let foreground = true; + const layer = layerLsofScanner({ + pid: () => 1234, + fetch: (() => Promise.resolve(new Response("not found", { status: 404 }))) as typeof fetch, + stdout: () => { + lsofRuns += 1; + return `p1234\ncnode\nn*:${LSOF_TEST_PORT}\n`; + }, + backgroundPolicy: Layer.mock(BackgroundPolicy.BackgroundPolicy)({ + shouldRunOpportunisticWork: Effect.sync(() => foreground), + }), + }); + + return Effect.gen(function* () { + const scanner = yield* PortScanner.PortDiscovery; + yield* scanner.subscribe( + { configuredUrls: [`http://localhost:${LSOF_TEST_PORT}/`], initialSnapshot: [] }, + () => Effect.void, + ); + yield* scanner.retain; + const afterInitialScan = lsofRuns; + expect(afterInitialScan).toBeGreaterThan(0); + + foreground = false; + yield* TestClock.adjust(Duration.seconds(15)); + expect(lsofRuns).toBe(afterInitialScan); + + foreground = true; + yield* TestClock.adjust(Duration.seconds(3)); + expect(lsofRuns).toBeGreaterThan(afterInitialScan); + }).pipe(Effect.scoped, Effect.provide(layer)); +}); + effectIt.effect("uses the current configured fragment when readiness comes from cache", () => { const requests: string[] = []; const fetchFn = ((input: Parameters[0]) => { @@ -554,7 +598,7 @@ effectIt.effect.each([ let lsofSpawns = 0; let procWalks = 0; const missing = FileSystem.makeNoop({}); - const layer = PortScanner.layer.pipe( + const layer = layerScanner.pipe( Layer.provide( Layer.mergeAll( FileSystem.layerNoop({ @@ -635,7 +679,7 @@ effectIt.effect("ignores a partial Windows netstat snapshot when one query exits requests.push(String(input)); return Promise.resolve(new Response("hello", { headers: { "content-type": "text/html" } })); }) as typeof globalThis.fetch; - const layer = PortScanner.layer.pipe( + const layer = layerScanner.pipe( Layer.provide( Layer.mergeAll( layerNoProc, @@ -744,7 +788,7 @@ effectIt.effect.each(["linux", "darwin", "win32"] as const)( const fileReads: string[] = []; const requests: string[] = []; const missing = FileSystem.makeNoop({}); - const layer = PortScanner.layer.pipe( + const layer = layerScanner.pipe( Layer.provide( Layer.mergeAll( FileSystem.layerNoop({ @@ -811,7 +855,7 @@ effectIt.effect.each(["linux", "darwin"] as const)( "/proc/4242/environ": `PATH=/usr/bin\0${PortScanner.AGENT_THREAD_ENV}=thread-agent\0`, "/proc/5000/environ": "PATH=/usr/bin\0", }; - const layer = PortScanner.layer.pipe( + const layer = layerScanner.pipe( Layer.provide( Layer.mergeAll( FileSystem.layerNoop({ @@ -1051,7 +1095,7 @@ effectIt.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( }).pipe( Effect.scoped, Effect.provide( - PortScanner.layer.pipe( + layerScanner.pipe( Layer.provide(ProcessRunner.layer), Layer.provide(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer)), ), diff --git a/apps/server/src/preview/PortScanner.ts b/apps/server/src/preview/PortScanner.ts index 12421453ade56..d950cd636f4f5 100644 --- a/apps/server/src/preview/PortScanner.ts +++ b/apps/server/src/preview/PortScanner.ts @@ -24,6 +24,7 @@ import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import { FetchHttpClient, HttpClient } from "effect/http"; +import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; import * as WindowsTcpListeners from "../process/windowsTcpListeners.ts"; import * as ProcessRunner from "../processRunner.ts"; @@ -508,6 +509,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() { const hostPlatform = yield* HostProcess.Platform; const listenerDiscovery = (yield* HostProcess.Environment)[PORT_DISCOVERY_ENV] !== "0"; const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope); + const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; const stateRef = yield* Ref.make({ listeners: new Map(), terminalProcesses: new Map(), @@ -973,7 +975,10 @@ export const make = Effect.gen(function* PortDiscoveryMake() { const pollIfRetained = Ref.get(stateRef).pipe( Effect.flatMap((state) => (state.retainCount > 0 ? pollTick() : Effect.void)), ); - yield* Effect.forkScoped(pollIfRetained.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL)))); + const scheduledPoll = backgroundPolicy.shouldRunOpportunisticWork.pipe( + Effect.flatMap((foreground) => (foreground ? pollIfRetained : Effect.void)), + ); + yield* Effect.forkScoped(scheduledPoll.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL)))); const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () { const wasIdle = yield* Ref.modify(stateRef, (state) => [ diff --git a/apps/server/src/preview/ServerBrowserContexts.test.ts b/apps/server/src/preview/ServerBrowserContexts.test.ts index 8a5a280d1f1b8..413b41eb08b4b 100644 --- a/apps/server/src/preview/ServerBrowserContexts.test.ts +++ b/apps/server/src/preview/ServerBrowserContexts.test.ts @@ -1,4 +1,8 @@ +// @effect-diagnostics nodeBuiltinImport:off - Hands a real file on disk to a real desktop browser. import * as NodeEvents from "node:events"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; import { INCOGNITO_BROWSER_PROFILE_ID } from "@t3tools/contracts"; import { chromium, type Browser, type BrowserContext, type BrowserType } from "playwright-core"; @@ -12,6 +16,7 @@ const launches = vi.hoisted(() => ({ mkdir: vi.fn().mockResolvedValue(undefined), rm: vi.fn().mockResolvedValue(undefined), })); +const launchPersistentChromium = chromium.launchPersistentContext.bind(chromium); vi.spyOn(chromium, "launch").mockImplementation(launches.launch); vi.spyOn(chromium, "launchPersistentContext").mockImplementation(launches.persistent); vi.mock("node:fs/promises", () => ({ mkdir: launches.mkdir, rm: launches.rm })); @@ -347,4 +352,45 @@ describe("ServerBrowserContexts", () => { expect(browser.close).toHaveBeenCalledTimes(1); expect(browser.created[0]?.close).toHaveBeenCalled(); }); + + it("uploads a file over 50 MB to a desktop tab, which shares the server's filesystem", async () => { + const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-desktop-upload-")); + const userDataDir = NodePath.join(directory, "profile"); + const pool = new ServerBrowserContexts(options()); + try { + const desktop = await launchPersistentChromium(userDataDir, { + headless: true, + args: ["--remote-debugging-port=0"], + }); + try { + const [port] = NodeFS.readFileSync( + NodePath.join(userDataDir, "DevToolsActivePort"), + "utf8", + ).split("\n"); + const { browser, page } = await pool.connectDesktopPage(`http://127.0.0.1:${port}`); + try { + const file = NodePath.join(directory, "large.bin"); + NodeFS.writeFileSync(file, ""); + NodeFS.truncateSync(file, 51 * 1024 * 1024); + await page.setContent(``); + await page.locator("input").setInputFiles(file); + expect( + await page.$eval("input", (input) => + Array.from( + (input as unknown as { files: ArrayLike<{ name: string; size: number }> }).files, + ({ name, size }) => ({ name, size }), + ), + ), + ).toEqual([{ name: "large.bin", size: 51 * 1024 * 1024 }]); + } finally { + await browser.close(); + } + } finally { + await pool.close(); + await desktop.close(); + } + } finally { + NodeFS.rmSync(directory, { recursive: true, force: true }); + } + }); }); diff --git a/apps/server/src/preview/ServerBrowserContexts.ts b/apps/server/src/preview/ServerBrowserContexts.ts index 03088a173a815..ec7fc926cad46 100644 --- a/apps/server/src/preview/ServerBrowserContexts.ts +++ b/apps/server/src/preview/ServerBrowserContexts.ts @@ -279,7 +279,8 @@ export class ServerBrowserContexts { async connectDesktopPage(endpoint: string) { const { chromium } = loadPlaywright(); - const browser = await chromium.connectOverCDP(endpoint, { timeout: 15_000 }); + // Only a same-machine desktop backend gets the browser channel, so uploads can pass file paths. + const browser = await chromium.connectOverCDP(endpoint, { isLocal: true, timeout: 15_000 }); const page = browser.contexts().flatMap((context) => context.pages())[0]; if (!page) { await browser.close().catch(constVoid); diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index e483f37c0389e..efe0652884709 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -13,6 +13,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { vi } from "vite-plus/test"; import * as ServerConfig from "../config.ts"; import { makeCodexAppServerSpawnCommand } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; @@ -26,6 +27,13 @@ import { type ScopeState, } from "./agentScope.ts"; +const GiB = 1024 ** 3; +const memory = vi.hoisted(() => ({ total: 16 * 1024 ** 3 })); +vi.mock("node:os", async (importOriginal) => ({ + ...(await importOriginal()), + totalmem: () => memory.total, +})); + const running: ScopeState = { loadState: "loaded", activeState: "active", @@ -57,6 +65,7 @@ const withFakeSystemd = ( readonly units: Map; readonly calls: ReadonlyArray>; readonly awaitReset: (unit: string) => Effect.Effect; + readonly failingVerbs: Set; readonly stateDir: string; readonly cgroupRoot: string; readonly cleanupSlices: ReadonlyArray; @@ -89,6 +98,7 @@ const withFakeSystemd = ( resetSignals.set(unit, signal); return signal; }; + const failingVerbs = new Set(); const output = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({ stdout, stderr: "", @@ -107,6 +117,7 @@ const withFakeSystemd = ( return output("", 1); } const [, verb, unit = ""] = args; + if (failingVerbs.has(verb!)) return output("", 1); if (stopFails && verb === "stop") { return { ...output(""), @@ -155,6 +166,7 @@ const withFakeSystemd = ( units, calls, awaitReset: (unit) => Deferred.await(resetSignal(unit)), + failingVerbs, stateDir, cgroupRoot, cleanupSlices: leftoverAgentSlices(stateDir), @@ -451,6 +463,40 @@ describe("AgentScope service", () => { ), ); + it.effect("follows a live memory change at the next launch", () => { + memory.total = 16 * GiB; + return withFakeSystemd(({ scope, calls, failingVerbs }) => + Effect.gen(function* () { + const launch = scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" }); + const memoryLimits = () => + calls + .filter( + ([, verb, , slice]) => verb === "set-property" && slice === "app-s2code-agents.slice", + ) + .map((args) => args.slice(4)); + yield* launch; + yield* launch; + expect(memoryLimits()).toEqual([[`MemoryHigh=${10 * GiB}`, `MemoryMax=${12 * GiB}`]]); + + // A VM balloon or `pct set --memory` grows RAM while the server keeps running. + memory.total = 22 * GiB; + failingVerbs.add("set-property"); + yield* launch; + yield* launch; + failingVerbs.delete("set-property"); + yield* launch; + yield* launch; + const grown = [`MemoryHigh=${16 * GiB}`, `MemoryMax=${18 * GiB}`]; + expect(memoryLimits()).toEqual([ + [`MemoryHigh=${10 * GiB}`, `MemoryMax=${12 * GiB}`], + grown, + grown, + grown, + ]); + }), + ); + }); + it.effect("stops agents a killed server left before startup completes", () => withFakeSystemd( ({ scope, calls, stateDir }) => diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index dda8e2318f8ba..90a8ef4d46b8b 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -15,6 +15,7 @@ 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 Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; import * as ProcessRunner from "../processRunner.ts"; @@ -206,20 +207,44 @@ export const make = Effect.gen(function* () { slice, ...properties, ]); - if (result._tag === "None" || result.value.code !== 0) { - yield* Effect.logWarning("Could not set resource limits on an agents slice", { - slice, - properties, - stderr: result._tag === "Some" ? result.value.stderr.trim() : undefined, - }); - } + if (result._tag === "Some" && result.value.code === 0) return true; + yield* Effect.logWarning("Could not set resource limits on an agents slice", { + slice, + properties, + stderr: result._tag === "Some" ? result.value.stderr.trim() : undefined, + }); + return false; }); - const limits = agentSliceMemoryLimits(NodeOS.totalmem()); - yield* setProperties(AGENT_SLICE, [`MemoryHigh=${limits.high}`, `MemoryMax=${limits.max}`]); + // VMs and containers can resize RAM live, so each launch re-checks the total + // the limits came from. A failed update is retried by the next launch. + let appliedTotal: number | undefined; + const memoryLimitsLock = yield* Semaphore.make(1); + const applyMemoryLimits = memoryLimitsLock.withPermits(1)( + Effect.gen(function* () { + const total = NodeOS.totalmem(); + if (total === appliedTotal) return; + const limits = agentSliceMemoryLimits(total); + const applied = yield* setProperties(AGENT_SLICE, [ + `MemoryHigh=${limits.high}`, + `MemoryMax=${limits.max}`, + ]); + if (!applied) return; + if (appliedTotal !== undefined) { + yield* Effect.logInfo("Agent memory limits follow a memory change", { + slice: AGENT_SLICE, + previousTotal: appliedTotal, + total, + ...limits, + }); + } + appliedTotal = total; + }), + ); + yield* applyMemoryLimits; yield* setProperties(AGENTS_PARENT_SLICE, AGENTS_PARENT_PROPERTIES); yield* Effect.logInfo("Agent scopes are on", { slice: AGENT_SLICE, - ...limits, + ...agentSliceMemoryLimits(NodeOS.totalmem()), oomPolicy: supportsOomPolicy, }); return { @@ -227,6 +252,7 @@ export const make = Effect.gen(function* () { systemctl, runtimeDir, supportsOomPolicy, + applyMemoryLimits, }; }), ); @@ -418,6 +444,7 @@ export const make = Effect.gen(function* () { if (resolved === null) return { command, args }; const scope = yield* systemd; if (scope === undefined) return agentScopeCommand({ command: resolved, args }); + yield* scope.applyMemoryLimits; const unit = `${PRODUCT_ID}-${name}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`; // A continuing shared scope cannot attribute a tool's OOM to one thread. // Clear the launch thread's previous scope instead. diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 89659aa9979e7..18c0946144d4a 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -16,7 +16,6 @@ import { type OrchestrationV2ProviderThread, } from "@t3tools/contracts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; -import * as KeyedLock from "@t3tools/shared/KeyedLock"; import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as Context from "effect/Context"; @@ -188,7 +187,7 @@ const makeImporter = Effect.fn(function* ( candidates: ReadonlyArray, beforeTransaction: Effect.Effect = Effect.void, getAdapter?: ProviderAdapterRegistry.ProviderAdapterRegistryV2Shape["get"], - threadCommands?: KeyedLock.KeyedLock, + threadCommands?: ThreadCommandExecutor.ThreadCommandExecutor["Service"], settings: Layer.Layer< ServerSettings.ServerSettingsService, ServerSettingsError @@ -271,7 +270,7 @@ const makeImporter = Effect.fn(function* ( ), Layer.succeed( ThreadCommandExecutor.ThreadCommandExecutor, - threadCommands ?? (yield* KeyedLock.make()), + threadCommands ?? (yield* ThreadCommandExecutor.make), ), ), ), @@ -816,7 +815,7 @@ const importDuringCommand = Effect.fn(function* ( const projections = yield* ProjectionStore.ProjectionStoreV2; const sink = yield* EventSink.EventSinkV2; const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, name)); - const lock = yield* KeyedLock.make(); + const lock = yield* ThreadCommandExecutor.make; const loaded = yield* Deferred.make(); const importerCommitting = yield* Deferred.make(); const commandWritten = yield* Deferred.make(); diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.ts index 4bdc8386438ca..1db031456f2d7 100644 --- a/apps/server/src/project/ProjectService.ts +++ b/apps/server/src/project/ProjectService.ts @@ -538,7 +538,7 @@ export const make = Effect.gen(function* () { projectThreads, (thread) => threadCommands - .withLock(thread.id, deleteChildThread(input, thread.id)) + .withDeletionLock(threadCommands.withLock(thread.id, deleteChildThread(input, thread.id))) .pipe( Effect.mapError( (cause) => diff --git a/apps/server/src/provider/CodexProvider.test.ts b/apps/server/src/provider/CodexProvider.test.ts index ad15bf0896eb2..a70ea15a73570 100644 --- a/apps/server/src/provider/CodexProvider.test.ts +++ b/apps/server/src/provider/CodexProvider.test.ts @@ -1,12 +1,150 @@ import { assert, it } from "@effect/vitest"; +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 Queue from "effect/Queue"; +import * as Scope from "effect/Scope"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as TestClock from "effect/testing/TestClock"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { applyPreferredCodexDefaultModel, codexCustomEndpoint, codexRoutesSpendNativeQuota, + makeCodexSkillsProbe, mapCodexModelCapabilities, } from "./CodexProvider.ts"; +function makeFakeCodexAppServers() { + const helpers: Array<{ + readonly codexHome: unknown; + readonly crash: Effect.Effect; + readonly requests: Array; + closed: boolean; + }> = []; + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + const output = yield* Queue.unbounded(); + const exited = yield* Deferred.make(); + const crash = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(1)).pipe( + Effect.andThen(Queue.end(output)), + Effect.asVoid, + ); + const helper = { + codexHome: command._tag === "StandardCommand" ? command.options.env?.CODEX_HOME : undefined, + crash, + requests: [] as Array, + closed: false, + }; + helpers.push(helper); + yield* Effect.addFinalizer(() => Effect.sync(() => (helper.closed = true))); + const respond = (id: unknown, result: unknown) => + Queue.offer(output, new TextEncoder().encode(`${JSON.stringify({ id, result })}\n`)); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(900_000_000 + helpers.length), + exitCode: Deferred.await(exited), + isRunning: Effect.map(Deferred.isDone(exited), (done) => !done), + kill: () => crash, + unref: Effect.succeed(Effect.void), + stdin: Sink.forEach((chunk: string | Uint8Array) => + Effect.forEach( + (typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk)) + .split("\n") + .filter(Boolean), + (line) => { + const frame = JSON.parse(line) as { + readonly id?: number; + readonly method: string; + readonly params?: { readonly cwds: ReadonlyArray }; + }; + if (frame.id === undefined) return Effect.void; + if (frame.method === "initialize") { + return respond(frame.id, { + codexHome: "/codex-home", + platformFamily: "unix", + platformOs: "linux", + userAgent: "codex/0.0.0", + }); + } + helper.requests.push(frame.params); + return respond(frame.id, { + data: (frame.params?.cwds ?? []).map((cwd) => ({ + cwd, + errors: [], + skills: [ + { + name: `skill-in-${cwd}`, + path: `${cwd}/SKILL.md`, + enabled: true, + description: "", + scope: "repo", + }, + ], + })), + }); + }, + { discard: true }, + ), + ), + stdout: Stream.fromQueue(output), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); + }), + ); + return { helpers, spawner }; +} + +it.effect("reuses one Codex skills helper per launch until it idles out", () => + Effect.gen(function* () { + const { helpers, spawner } = makeFakeCodexAppServers(); + const providerScope = yield* Scope.make(); + const probe = yield* makeCodexSkillsProbe().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Scope.provide(providerScope), + ); + const read = (cwd: string, homePath = "/home-a") => + probe({ binaryPath: "codex", homePath, cwd, environment: {} }).pipe( + Effect.map((skills) => skills.map((skill) => skill.name)), + ); + + assert.deepStrictEqual(yield* read("/alpha"), ["skill-in-/alpha"]); + assert.deepStrictEqual(yield* read("/beta"), ["skill-in-/beta"]); + assert.strictEqual(helpers.length, 1); + assert.deepStrictEqual(helpers[0]!.requests, [ + { cwds: ["/alpha"], forceReload: true }, + { cwds: ["/beta"], forceReload: true }, + ]); + + // Another home is another launch identity; the previous helper retires at once. + assert.deepStrictEqual(yield* read("/alpha", "/home-b"), ["skill-in-/alpha"]); + assert.strictEqual(helpers.length, 2); + assert.strictEqual(helpers[0]!.closed, true); + assert.strictEqual(helpers[1]!.codexHome, "/home-b"); + + // A helper that exits is replaced within the same read. + yield* helpers[1]!.crash; + assert.deepStrictEqual(yield* read("/beta", "/home-b"), ["skill-in-/beta"]); + assert.strictEqual(helpers.length, 3); + + yield* TestClock.adjust("29 seconds"); + assert.strictEqual(helpers[2]!.closed, false); + yield* TestClock.adjust("1 second"); + assert.strictEqual(helpers[2]!.closed, true); + assert.deepStrictEqual(yield* read("/alpha", "/home-b"), ["skill-in-/alpha"]); + assert.strictEqual(helpers.length, 4); + + yield* Scope.close(providerScope, Exit.void); + assert.strictEqual(helpers[3]!.closed, true); + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), +); + it("maps current Codex model capability fields", () => { const capabilities = mapCodexModelCapabilities({ additionalSpeedTiers: [], diff --git a/apps/server/src/provider/CodexProvider.ts b/apps/server/src/provider/CodexProvider.ts index df105d3ba20fe..7dcf9079f82b3 100644 --- a/apps/server/src/provider/CodexProvider.ts +++ b/apps/server/src/provider/CodexProvider.ts @@ -3,10 +3,12 @@ import { pipe } from "effect/Function"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Equal from "effect/Equal"; 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 RcMap from "effect/RcMap"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as Schedule from "effect/Schedule"; @@ -839,6 +841,52 @@ export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(functi return parseCodexSkillsListResponse(skillsResponse, input.cwd); }); +// Long enough for a burst of workspace switches; short because the helper holds the user's +// binary open, and Windows refuses to overwrite or delete a running executable. +const CODEX_SKILLS_HELPER_IDLE_TTL = "30 seconds"; + +/** Reuses one app-server per launch identity; each read passes its cwd and rescans from disk. */ +export const makeCodexSkillsProbe = Effect.fn("makeCodexSkillsProbe")(function* () { + const helpers = yield* RcMap.make({ + lookup: (launch: { + readonly binaryPath: string; + readonly homePath?: string; + readonly launchArgs?: string; + readonly environment: NodeJS.ProcessEnv; + }) => + withCodexAppServerClient({ ...launch, cwd: process.cwd() }).pipe( + Effect.map(({ client }) => client), + ), + idleTimeToLive: CODEX_SKILLS_HELPER_IDLE_TTL, + }); + return Effect.fn("CodexSkillsProbe.probe")(function* (input: { + readonly binaryPath: string; + readonly homePath?: string; + readonly launchArgs?: string; + readonly cwd: string; + readonly environment?: NodeJS.ProcessEnv; + }) { + const { cwd, ...rest } = input; + const launch = { + ...rest, + environment: providerProbeEnvironment(rest.environment ?? process.env), + }; + // Retire helpers for a previous binary, home, credentials, or launch options. + const stale = Array.from(yield* RcMap.keys(helpers)).filter( + (key) => !Equal.equals(key, launch), + ); + yield* Effect.forEach(stale, (key) => RcMap.invalidate(helpers, key), { discard: true }); + const skillsResponse = yield* RcMap.get(helpers, launch).pipe( + Effect.flatMap((client) => client.request("skills/list", { cwds: [cwd], forceReload: true })), + Effect.scoped, + // RcMap keeps a failed spawn, and a dead helper keeps failing; drop it so the retry respawns. + Effect.onError(() => RcMap.invalidate(helpers, launch)), + Effect.retry({ times: 1 }), + ); + return parseCodexSkillsListResponse(skillsResponse, cwd); + }); +}); + const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => appendCustomCodexModels([], codexSettings.customModels); diff --git a/apps/server/src/provider/Drivers/AntigravityUsage.ts b/apps/server/src/provider/Drivers/AntigravityUsage.ts index 5cb55ed77ac09..2eb9744a3e42a 100644 --- a/apps/server/src/provider/Drivers/AntigravityUsage.ts +++ b/apps/server/src/provider/Drivers/AntigravityUsage.ts @@ -15,7 +15,11 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import { resolveAntigravityInstanceDirectories } from "../antigravityAuthSupport.ts"; -import { makeAntigravityUsageCache, readAntigravityUsage } from "./antigravityUsageReader.ts"; +import { + antigravityRateModel, + makeAntigravityUsageCache, + readAntigravityUsage, +} from "./antigravityUsageReader.ts"; export class AntigravityUsage extends Context.Service< AntigravityUsage, @@ -123,6 +127,7 @@ export const layer = Layer.effect(AntigravityUsage, make); export const antigravityUsageReader: ProviderUsageReader = { kind: "scan", provider: "antigravity", + rateModel: antigravityRateModel, scan: ({ instances, windowStartMs }) => AntigravityUsage.pipe(Effect.flatMap((usage) => usage.scan({ instances, windowStartMs }))), }; diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts index e1319caf69b16..b6dc61470e497 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts @@ -9,6 +9,9 @@ const NPM_DIR = "C:\\Users\\dev\\AppData\\Roaming\\npm"; const NPM_SHIM = `${NPM_DIR}\\claude.cmd`; const NPM_PACKAGE_EXE = `${NPM_DIR}\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe`; const NPM_PACKAGE_CLI = `${NPM_DIR}\\node_modules\\@anthropic-ai\\claude-code\\cli.js`; +const WINGET_DIR = "C:\\Users\\dev\\AppData\\Local\\Microsoft\\WinGet"; +const WINGET_SHIM = `${WINGET_DIR}\\Links\\claude.cmd`; +const WINGET_EXE = `${WINGET_DIR}\\Packages\\Anthropic.ClaudeCode_Microsoft.Winget.Source_8wekyb3d8bbwe\\claude.exe`; function withWindowsResolution(input: { readonly resolvedCommand: string | undefined; @@ -37,6 +40,16 @@ describe("resolveClaudeSdkExecutablePath", () => { }), ); + it.effect("follows the WinGet launcher to the package's native binary", () => + Effect.gen(function* () { + expect( + yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( + withWindowsResolution({ resolvedCommand: WINGET_SHIM, existingFiles: [WINGET_EXE] }), + ), + ).toBe(WINGET_EXE); + }), + ); + it.effect("follows .bat and .ps1 launcher shims the same way", () => Effect.gen(function* () { for (const shim of [`${NPM_DIR}\\claude.bat`, `${NPM_DIR}\\claude.ps1`]) { diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.ts index 5e4cbb4db6efe..5797066446b99 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.ts @@ -13,10 +13,14 @@ const WINDOWS_SHIM_EXTENSIONS: ReadonlySet = new Set([".cmd", ".bat", ". export const isWindowsClaudeLauncherShimPath = (filePath: string): boolean => WINDOWS_SHIM_EXTENSIONS.has(NodePath.win32.extname(filePath).toLowerCase()); -/** New packages provide bin/claude.exe; older packages need a JavaScript runtime for cli.js. */ -const NPM_PACKAGE_ENTRY_CANDIDATES = [ +/** + * npm: new packages provide bin/claude.exe; older ones need a JavaScript runtime for cli.js. + * WinGet: Links\claude.cmd forwards to the package's native executable under ..\Packages. + */ +const PACKAGE_ENTRY_CANDIDATES = [ ["node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe"], ["node_modules", "@anthropic-ai", "claude-code", "cli.js"], + ["..", "Packages", "Anthropic.ClaudeCode_Microsoft.Winget.Source_8wekyb3d8bbwe", "claude.exe"], ] as const; export type ExecutableFileCheck = (filePath: string) => boolean; @@ -53,7 +57,7 @@ export const resolveClaudeSdkExecutablePath = Effect.fn("resolveClaudeSdkExecuta } const shimDirectory = NodePath.win32.dirname(resolved); - for (const entrySegments of NPM_PACKAGE_ENTRY_CANDIDATES) { + for (const entrySegments of PACKAGE_ENTRY_CANDIDATES) { const candidate = NodePath.win32.join(shimDirectory, ...entrySegments); if (isFile(candidate)) { return candidate; diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index f8a753169b54a..03245ba46d6c1 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -29,7 +29,7 @@ import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts"; import { checkCodexProviderStatus, makePendingCodexProvider, - probeCodexSkillsForCwd, + makeCodexSkillsProbe, withCodexAppServerClient, } from "../CodexProvider.ts"; import { resolveCodexLaunchArgs } from "../codexLaunchArgs.ts"; @@ -321,22 +321,21 @@ export const CodexDriver: ProviderDriver< processEnv, snapshot.getSnapshot.pipe(Effect.map((value) => value.models)), ); + const probeSkills = yield* makeCodexSkillsProbe().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); const snapshotForCwd = (cwd: string) => !effectiveConfig.enabled ? snapshot.getSnapshot : Effect.all([ snapshot.getSnapshot, - probeCodexSkillsForCwd({ + probeSkills({ binaryPath: effectiveConfig.binaryPath, homePath: effectiveConfig.homePath, launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv), cwd, environment: processEnv, - }).pipe( - Effect.scoped, - Effect.timeout(resolveProviderProbeTimeoutMs("codex", 20_000, processEnv)), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ), + }).pipe(Effect.timeout(resolveProviderProbeTimeoutMs("codex", 20_000, processEnv))), ]).pipe( Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })), Effect.mapError( diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index 4d473f50c9d67..532233f7facce 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -129,18 +129,19 @@ const MODEL_IDS: Record = { }; // Effort and routing variants share the base model's price. -function withRateModel(record: UsageRecord): UsageRecord { - const base = record.model.replace( - /-(?:extra-low|low|medium|high|tiered|control|thinking|agent)$/, - "", - ); - const rateModel = /^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(record.model) +export const antigravityRateModel = (model: string) => { + const base = model.replace(/-(?:extra-low|low|medium|high|tiered|control|thinking|agent)$/, ""); + return /^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(model) ? "gemini-3.5-flash" - : record.model === "gemini-3.7-flash-safety-le" + : model === "gemini-3.7-flash-safety-le" ? "gemini-3.7-flash" : base === "gemini-3-flash" ? "gemini-3-flash-preview" : base; +}; + +function withRateModel(record: UsageRecord): UsageRecord { + const rateModel = antigravityRateModel(record.model); return rateModel === record.model ? record : { ...record, rateModel }; } diff --git a/apps/server/src/provider/codexLaunchArgs.test.ts b/apps/server/src/provider/codexLaunchArgs.test.ts index 8f4e1b7ca6d6a..e74b29d44818c 100644 --- a/apps/server/src/provider/codexLaunchArgs.test.ts +++ b/apps/server/src/provider/codexLaunchArgs.test.ts @@ -38,6 +38,15 @@ describe("codexExecLaunchArgs", () => { ); }); + it("drops launch args that enable user hooks", () => { + NodeAssert.deepStrictEqual( + codexExecLaunchArgs( + "--enable hooks --enable=hooks --enable codex_hooks --enable=codex_hooks --enable foo --disable hooks", + ), + ["--enable", "foo", "--disable", "hooks"], + ); + }); + it("does not pair value-taking flags with adjacent flags", () => { NodeAssert.deepStrictEqual(codexExecLaunchArgs("--config --strict-config --enable --disable"), [ "--strict-config", diff --git a/apps/server/src/provider/codexLaunchArgs.ts b/apps/server/src/provider/codexLaunchArgs.ts index 31ff37e31deb5..e49314ee83e0d 100644 --- a/apps/server/src/provider/codexLaunchArgs.ts +++ b/apps/server/src/provider/codexLaunchArgs.ts @@ -62,8 +62,17 @@ const filterLaunchArgs = (launchArgs: string | undefined, allowed: LaunchArgFilt return kept; }; -export const codexExecLaunchArgs = (launchArgs?: string) => - filterLaunchArgs(launchArgs, EXEC_FILTER); +const HOOK_FEATURES = new Set(["hooks", "codex_hooks"]); + +// Feature toggles beat config overrides, so a launch arg's hook enable would undo ours. +export const codexExecLaunchArgs = (launchArgs?: string) => { + const args = filterLaunchArgs(launchArgs, EXEC_FILTER); + return args.filter((arg, index) => { + if (arg.startsWith("--enable=")) return !HOOK_FEATURES.has(arg.slice("--enable=".length)); + if (arg === "--enable") return !HOOK_FEATURES.has(args[index + 1] ?? ""); + return !(args[index - 1] === "--enable" && HOOK_FEATURES.has(arg)); + }); +}; export const codexMcpListLaunchArgs = (launchArgs?: string) => filterLaunchArgs(launchArgs, MCP_LIST_FILTER); diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index b031547be6160..5957fdd3cd892 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -14,9 +14,10 @@ const CELL_END = Symbol("cell-end"); type TextPart = string | typeof CELL_START | typeof CELL_END | { fallback: string }; const TRUNCATED = "\n\n[Extracted text truncated at document extraction limits.]"; -// Parts the document never displays: tracked deletions and moves, field codes, phonetic guides, -// paragraph properties such as tab-stop definitions. +// Parts the document never displays: the XHTML head, tracked deletions and moves, field codes, +// phonetic guides, paragraph properties such as tab-stop definitions. const HIDDEN = new Set([ + "head", "script", "style", "binary-data", diff --git a/apps/server/src/provider/testFixtures/grok-text-mock-agent.mjs b/apps/server/src/provider/testFixtures/grok-text-mock-agent.mjs index 357bdb7fe564d..b8cb949a5fb71 100644 --- a/apps/server/src/provider/testFixtures/grok-text-mock-agent.mjs +++ b/apps/server/src/provider/testFixtures/grok-text-mock-agent.mjs @@ -5,12 +5,35 @@ const sessionId = "grok-text-session"; let currentModelId = "grok-mock-default"; const models = ["grok-mock-default", "grok-mock-alt"]; const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`); +const permissionRequestId = 9001; +let pendingPromptId; +const completePrompt = (id) => { + write({ + jsonrpc: "2.0", + method: "session/update", + params: { + sessionId, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: process.env.T3_ACP_PROMPT_RESPONSE_TEXT ?? "" }, + }, + }, + }); + write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); +}; for await (const line of NodeReadline.createInterface({ input: process.stdin })) { const request = JSON.parse(line); if (process.env.T3_ACP_REQUEST_LOG_PATH) { NodeFS.appendFileSync(process.env.T3_ACP_REQUEST_LOG_PATH, `${line}\n`); } + if (request.method === undefined) { + if (request.id === permissionRequestId && pendingPromptId !== undefined) { + completePrompt(pendingPromptId); + pendingPromptId = undefined; + } + continue; + } if (request.id === undefined) continue; let result; switch (request.method) { @@ -43,19 +66,25 @@ for await (const line of NodeReadline.createInterface({ input: process.stdin })) result = {}; break; case "session/prompt": - write({ - jsonrpc: "2.0", - method: "session/update", - params: { - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: process.env.T3_ACP_PROMPT_RESPONSE_TEXT ?? "" }, + if (process.env.T3_ACP_REQUEST_PERMISSION) { + pendingPromptId = request.id; + write({ + jsonrpc: "2.0", + id: permissionRequestId, + method: "session/request_permission", + params: { + sessionId, + toolCall: { toolCallId: "tool-1", kind: "execute", title: "Run `git status`" }, + options: [ + { optionId: "allow-once", name: "Yes", kind: "allow_once" }, + { optionId: "reject-once", name: "No", kind: "reject_once" }, + ], }, - }, - }); - result = { stopReason: "end_turn" }; - break; + }); + continue; + } + completePrompt(request.id); + continue; default: write({ jsonrpc: "2.0", diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 0911f94a6a6aa..4087601b58c0b 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1078,11 +1078,11 @@ describe("question answer paths", () => { "OEBPS/a.xhtml": '

Last chapter

Price 10 8 old

', "OEBPS/b.xhtml": - "

First chapter

Larkspur

Direct div
Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    ", + 'My Novel

    First chapter

    Larkspur

    Direct div
    Direct section
  • Direct item emphasis trailing
  • Account: A
    Balance: 731Currency: USD
    HeadingTotal
    Important value731
    Before
    Inner
    After
    Neighbor
    ', }, expected: [ "## Chapter 1", - "# First chapter", + "\n# First chapter", "Larkspur", "Direct div", "Direct section", @@ -1095,6 +1095,7 @@ describe("question answer paths", () => { "Last chapter", "Price 10 8 old", ], + absent: ["My Novel", "Hidden Author"], }, ]; for (const [caseIndex, item] of cases.entries()) { diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 74106b14cd403..905c96319d52a 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -3249,6 +3249,40 @@ it.effect("reads the fresh diff when detail or summary discovers a changed revis }), ); +it.effect("keeps a withheld file's read out of the page's cached diff", () => + Effect.gen(function* () { + const provider = fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getDiff: (input) => + Effect.succeed({ + patch: input.path === undefined ? "page" : `file ${input.path}`, + truncated: input.path === undefined, + nextCursor: null, + }), + }); + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [provider], + }); + const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 10 }; + assert.strictEqual((yield* service.diff(ref)).patch, "page"); + assert.strictEqual( + (yield* service.diff({ ...ref, path: "sdk.patch" })).patch, + "file sdk.patch", + ); + assert.strictEqual((yield* service.diff(ref)).patch, "page"); + + // A host that would answer with its whole diff must not be cached as one file's. + const wholeDiffOnly = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + { ...provider, capabilities: { ...provider.capabilities, withheldFileDiff: false } }, + ], + }); + const error = yield* Effect.flip(wholeDiffOnly.diff({ ...ref, path: "sdk.patch" })); + assert.strictEqual(error._tag, "PullRequestOperationError"); + }), +); + it.effect("keeps routed reads separate when the GitHub account changes", () => Effect.gen(function* () { for (const operation of ["summary", "detail", "checks", "diff", "filesViewed"] as const) { diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 85a9349b7af82..74da9bacee95d 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -2036,23 +2036,31 @@ export const make = Effect.gen(function* () { const diffUncached: PullRequestService["Service"]["diff"] = (input) => requireProject(input).pipe( Effect.flatMap((project) => - project.api.capabilities.diff - ? project.api - .getDiff({ - cwd: project.project.workspaceRoot, - repository: project.repository, - host: project.host, - number: input.number, - ...(input.cursor === undefined ? {} : { cursor: input.cursor }), - ...(input.commit === undefined ? {} : { commit: input.commit }), - }) - .pipe(Effect.mapError(toPullRequestError("diff"))) - : Effect.fail( + input.path !== undefined && project.api.capabilities.withheldFileDiff !== true + ? Effect.fail( new PullRequestOperationError({ operation: "diff", - detail: "This host cannot provide a diff for a change request.", + detail: "This host cannot read one file of a change request's diff.", }), - ), + ) + : project.api.capabilities.diff + ? project.api + .getDiff({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: input.number, + ...(input.path === undefined ? {} : { path: input.path }), + ...(input.cursor === undefined ? {} : { cursor: input.cursor }), + ...(input.commit === undefined ? {} : { commit: input.commit }), + }) + .pipe(Effect.mapError(toPullRequestError("diff"))) + : Effect.fail( + new PullRequestOperationError({ + operation: "diff", + detail: "This host cannot provide a diff for a change request.", + }), + ), ), ); @@ -3503,16 +3511,26 @@ export const make = Effect.gen(function* () { const diffCache = yield* Cache.makeWith( (key: string) => { - const [reference, cursor, commit] = JSON.parse(key) as [string, string | null, string | null]; + const [reference, cursor, commit, , path] = JSON.parse(key) as [ + string, + string | null, + string | null, + string | null, + string | null, + ]; return diffUncached({ ...refOfCacheKey(reference), + ...(path === null ? {} : { path }), ...(cursor === null ? {} : { cursor }), ...(commit === null ? {} : { commit }), } as PullRequestDiffInput).pipe( observeRead, Effect.tap(({ value, observedAt }) => { // Keep the loader's epoch and read time if a refresh occurs during the provider read. - diffFiles.record(JSON.stringify([reference, cursor, commit]), value, observedAt); + // One withheld file is not the page's file list. + if (path === null) { + diffFiles.record(JSON.stringify([reference, cursor, commit]), value, observedAt); + } return Effect.void; }), ); @@ -3559,6 +3577,7 @@ export const make = Effect.gen(function* () { input.commit === undefined ? (lastGoodSummary.peek(refCacheKey(input))?.updatedAt ?? null) : null, + input.path ?? null, ]); const evictDiffs = Cache.entries(diffCache).pipe( Effect.flatMap((entries) => diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 934cdc6be1cb7..af45b6f7268d8 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -521,7 +521,10 @@ const layerVcs = Layer.empty.pipe( const layerCheckpointStore = CheckpointStore.layer.pipe(Layer.provide(layerVcsDriverRegistry)); -const layerPortScanner = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer)); +const layerPortScanner = PortScanner.layer.pipe( + Layer.provide(ProcessRunner.layer), + Layer.provide(layerBackground), +); const layerTerminal = TerminalManager.layer( ProviderInstanceRegistryHydration.deriveProviderInstanceConfigMap, diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 45d519f70c610..40025a62c9853 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -659,6 +659,15 @@ const cleanupTestLayer = GitVcsDriver.layer.pipe( ), Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); +const annexWorktree = Effect.fnUntraced(function* ( + fixture: Effect.Success>, + worktree: string, +) { + const adminDir = (yield* fixture.command(worktree, ["rev-parse", "--absolute-git-dir"])).stdout; + yield* fixture.fs.remove(`${worktree}/.git`); + yield* fixture.fs.symlink(adminDir.trim(), `${worktree}/.git`); +}); + const runCleanupTest = ( effect: Effect.Effect< A, @@ -2109,7 +2118,7 @@ describe("orphan worktree reports", () => { ), ); - it.live.each(["nested", "direct"] as const)( + it.live.each(["nested", "direct", "annexed"] as const)( "reports a linked orphan's size without removing its files (%s)", (location) => runCleanupTest( @@ -2118,8 +2127,13 @@ describe("orphan worktree reports", () => { fixture.setThreads([]); const orphan = `${fixture.config.worktreesDir}/${location === "nested" ? "repository/" : ""}orphan`; yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "orphan", orphan]); - const sizes = yield* Effect.forEach(yield* fixture.fs.readDirectory(orphan), (name) => - allocatedBytes(fixture.fs, `${orphan}/${name}`), + if (location === "annexed") yield* annexWorktree(fixture, orphan); + const sizes = yield* Effect.forEach( + // Links are not measured, and the annexed `.git` is one. + (yield* fixture.fs.readDirectory(orphan)).filter( + (name) => location !== "annexed" || name !== ".git", + ), + (name) => allocatedBytes(fixture.fs, `${orphan}/${name}`), ); const outside = yield* fixture.fs.makeTempDirectoryScoped(); yield* fixture.fs.writeFileString(`${outside}/external`, "outside data"); @@ -2973,6 +2987,17 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live("removes a worktree whose .git file git-annex replaced with a symlink", () => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* cleanupFixture(); + const { service, worktree, fs } = fixture; + yield* annexWorktree(fixture, worktree); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); + expect(yield* fs.exists(worktree)).toBe(false); + }), + ), + ); it.live("keeps a worktree when the inspection cannot read its directories", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index 6e38b58009039..43ff8254daa6d 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -58,7 +58,7 @@ import * as TerminalManager from "./terminal/Manager.ts"; import { isFilesystemRoot, managedWorktreesDirectories } from "./worktreesDirectory.ts"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; import { isNonRepositoryGitStderr } from "./vcs/GitVcsDriverCore.ts"; -import { removeLinkedWorktree } from "./vcs/worktreeRemoval.ts"; +import { isLinkedWorktree, removeLinkedWorktree } from "./vcs/worktreeRemoval.ts"; import { withWorkspaceLease } from "./workspace/workspaceLease.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; @@ -591,7 +591,7 @@ const make = Effect.gen(function* () { const modified = Option.getOrNull((yield* fs.stat(worktreePath)).mtime); if (modified !== null && modified.getTime() > now - ORPHAN_WORKTREE_GRACE_MS) return; const gitPath = path.join(worktreePath, ".git"); - const linked = (yield* fs.exists(gitPath)) && (yield* fs.stat(gitPath)).type === "File"; + const linked = (yield* fs.exists(gitPath)) && (yield* isLinkedWorktree(worktreePath)); reported.add(key); const remaining = measurementDeadline - (yield* Clock.currentTimeMillis); if (!orphanSizes.has(key) && (firstMeasurement || remaining > 0)) { @@ -636,7 +636,7 @@ const make = Effect.gen(function* () { (worktree) => Effect.gen(function* () { if (pathKey(yield* fs.realPath(worktree)) !== pathKey(worktree)) return false; - return (yield* fs.stat(path.join(worktree, ".git"))).type === "File"; + return yield* isLinkedWorktree(worktree); }).pipe(Effect.orElseSucceed(() => false)), ); }); @@ -647,7 +647,7 @@ const make = Effect.gen(function* () { if (referenced.has(pathKey(projectDirectory))) return; const gitPath = path.join(projectDirectory, ".git"); if (yield* fs.exists(gitPath)) { - if ((yield* fs.stat(gitPath)).type === "File") yield* report(projectDirectory); + if (yield* isLinkedWorktree(projectDirectory)) yield* report(projectDirectory); return; } for (const worktreePath of yield* directories(projectDirectory, root)) { @@ -1084,10 +1084,10 @@ const make = Effect.gen(function* () { return "worktree is a symbolic link"; if (!roots.some((root) => inside(root, realPath))) return "outside the managed worktree folder"; - const gitLink = yield* fs - .stat(path.join(worktreePath, ".git")) - .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined)); - if (gitLink?.type !== "File") return "not a linked worktree"; + const linked = yield* isLinkedWorktree(worktreePath).pipe( + Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)), + ); + if (!linked) return "not a linked worktree"; return null; }); const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>` diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index ad69895e916f8..d3e7e84a1321d 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1940,6 +1940,41 @@ it.layer( }), ); + it.effect("keeps a startup failure in the snapshot every later attachment receives", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + ptyAdapter.spawnFailures.push(new Error("forkpty(3) failed.")); + const startupFailure = { + type: "snapshot", + snapshot: { + status: "error", + error: expect.stringContaining("Failed to spawn PTY process"), + }, + }; + const record = (events: TerminalAttachStreamEvent[]) => (event: TerminalAttachStreamEvent) => + Effect.sync(() => events.push(event)); + + const creating: TerminalAttachStreamEvent[] = []; + (yield* manager.attachStream(openInput(), record(creating)))(); + const resumed: TerminalAttachStreamEvent[] = []; + (yield* manager.attachStream({ ...openInput(), resume: true }, record(resumed)))(); + const observed: TerminalAttachStreamEvent[] = []; + (yield* manager.observeStream( + { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }, + record(observed), + ))(); + expect([creating, resumed, observed]).toMatchObject([ + [startupFailure], + [startupFailure], + [startupFailure], + ]); + + const restarted = yield* manager.open(openInput()); + expect(restarted.status).toBe("running"); + expect(restarted).not.toHaveProperty("error"); + }), + ); + it.effect("retries with fallback shells when preferred shell spawn fails", () => Effect.gen(function* () { const platform = yield* HostProcess.Platform; @@ -1977,29 +2012,56 @@ it.layer( }), ); - it.effect("starts a $SHELL whose path contains a space", () => + it.effect("starts an existing $SHELL whose path contains spaces before a dash", () => Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { join } = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-shell-path-" }); + const bin = join(root, "Jane -Doe Smith", ".local", "bin"); + yield* fs.makeDirectory(bin, { recursive: true }); + yield* fs.writeFileString(join(bin, "fish"), ""); + // Temp dirs are not POSIX-absolute on Windows, so stat maps a fixed POSIX prefix onto them. + const fixtureFs = FileSystem.FileSystem.of({ + ...fs, + stat: (filePath) => + fs.stat( + filePath.startsWith("/shell-fixture/") + ? join(root, filePath.slice("/shell-fixture/".length)) + : filePath, + ), + }); const { manager, ptyAdapter } = yield* createManager(5, { - env: { SHELL: "/Users/Jane Doe/.local/bin/fish" }, - }).pipe(Effect.provide(layerWithHostPlatform("darwin"))); + env: { SHELL: "/shell-fixture/Jane -Doe Smith/.local/bin/fish -l" }, + }).pipe( + Effect.provide(layerWithHostPlatform("darwin")), + Effect.provideService(FileSystem.FileSystem, fixtureFs), + ); yield* manager.open(openInput()); expect(ptyAdapter.spawnInputs.map((input) => input.shell)).toEqual([ - "/Users/Jane Doe/.local/bin/fish", + "/shell-fixture/Jane -Doe Smith/.local/bin/fish", ]); }), ); - it.effect("starts a quoted $SHELL whose path contains a space and a dash", () => + it.effect("keeps missing or quoted $SHELL paths that contain spaces", () => Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(5, { - env: { SHELL: '"/opt/my -shell/fish" -l' }, - }).pipe(Effect.provide(layerWithHostPlatform("darwin"))); + for (const [shell, expected] of [ + ["/Users/Jane Doe/.local/bin/fish", "/Users/Jane Doe/.local/bin/fish"], + ['"/opt/my -shell/fish" -l', "/opt/my -shell/fish"], + ]) { + const { manager, ptyAdapter } = yield* createManager(5, { + env: { SHELL: shell }, + }).pipe(Effect.provide(layerWithHostPlatform("darwin"))); - yield* manager.open(openInput()); + yield* manager.open(openInput()); - expect(ptyAdapter.spawnInputs.map((input) => input.shell)).toEqual(["/opt/my -shell/fish"]); + expect( + ptyAdapter.spawnInputs.map((input) => input.shell), + shell, + ).toEqual([expected]); + } }), ); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index d658083a13a01..d034af98ee1f3 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -316,6 +316,7 @@ interface TerminalSessionState { childCommandLabel: string | null; runtimeEnv: Record | null; stopOnSettle: boolean; + startupError: string | null; } interface TerminalGrid { @@ -411,6 +412,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { sequence: session.eventSequence, cols: session.cols, rows: session.rows, + ...(session.startupError === null ? {} : { error: session.startupError }), }; } @@ -527,10 +529,10 @@ function defaultShellResolver(platform: NodeJS.Platform, env: NodeJS.ProcessEnv) return env.SHELL ?? "bash"; } -function normalizeShellCommand( +const normalizeShellCommand = Effect.fn("terminal.normalizeShellCommand")(function* ( value: string | undefined, platform: NodeJS.Platform, -): string | null { +) { if (!value) return null; const trimmed = value.trim(); if (trimmed.length === 0) return null; @@ -539,12 +541,24 @@ function normalizeShellCommand( return trimmed; } - // A shell path can contain spaces, so only text from the first flag (`bash -l`) is dropped, - // and a quoted path is kept whole even when it contains " -". const quoted = /^(['"])(.*?)\1(?:\s|$)/.exec(trimmed); - const command = quoted ? quoted[2] : trimmed.split(/\s+(?=-)/)[0]?.replace(/^['"]|['"]$/g, ""); - return command || null; -} + if (quoted) return quoted[2] || null; + + if (trimmed.startsWith("/") && /\s/.test(trimmed)) { + const fs = yield* FileSystem.FileSystem; + const ends = [...trimmed.matchAll(/\s+/g)].map((match) => match.index); + // Unquoted paths are ambiguous; prefer the longest existing file over flag syntax. + for (const end of [trimmed.length, ...ends.reverse()]) { + const candidate = trimmed.slice(0, end); + const info = yield* fs + .stat(candidate) + .pipe(Effect.catchTags({ PlatformError: () => Effect.succeed(null) })); + if (info?.type === "File") return candidate; + } + } + + return trimmed.split(/\s+(?=-)/)[0]?.replace(/^['"]|['"]$/g, "") || null; +}); function basenameForPlatform(command: string, platform: NodeJS.Platform): string { const normalized = @@ -620,13 +634,13 @@ function uniqueShellCandidates(candidates: Array): ShellC return ordered; } -function resolveShellCandidates( +const resolveShellCandidates = Effect.fn("terminal.resolveShellCandidates")(function* ( shellResolver: () => string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -): ShellCandidate[] { +) { const requested = shellCandidateFromCommand( - normalizeShellCommand(shellResolver(), platform), + yield* normalizeShellCommand(shellResolver(), platform), platform, ); @@ -644,7 +658,7 @@ function resolveShellCandidates( return uniqueShellCandidates([ requested, - shellCandidateFromCommand(normalizeShellCommand(env.SHELL, platform), platform), + shellCandidateFromCommand(yield* normalizeShellCommand(env.SHELL, platform), platform), shellCandidateFromCommand("/bin/zsh", platform), shellCandidateFromCommand("/bin/bash", platform), shellCandidateFromCommand("/bin/sh", platform), @@ -652,7 +666,7 @@ function resolveShellCandidates( shellCandidateFromCommand("bash", platform), shellCandidateFromCommand("sh", platform), ]); -} +}); function isRetryableShellSpawnError(error: PtyAdapter.PtySpawnError): boolean { const queue: unknown[] = [error]; @@ -2668,6 +2682,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const startingAt = yield* nowIso; yield* modifyManagerState((state) => { session.status = "starting"; + session.startupError = null; session.shell = null; session.cwd = input.cwd; session.worktreePath = input.worktreePath ?? null; @@ -2691,7 +2706,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func increment(terminalSessionsTotal, { lifecycle: eventType }).pipe( Effect.andThen( Effect.gen(function* () { - const shellCandidates = resolveShellCandidates(shellResolver, platform, baseEnv); + const shellCandidates = yield* resolveShellCandidates( + shellResolver, + platform, + baseEnv, + ).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem)); const terminalEnv = createTerminalSpawnEnv( baseEnv, session.runtimeEnv, @@ -2784,6 +2803,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func { const error = startResult.failure; + const message = error.message; if (ptyProcess) { yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId); } @@ -2791,6 +2811,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* modifyManagerState((state) => { cleanupProcessHandles(session); session.status = "error"; + session.startupError = message; session.pid = null; session.process = null; session.hasRunningSubprocess = false; @@ -2808,7 +2829,6 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* evictInactiveSessionsIfNeeded(); - const message = error.message; yield* publishEvent({ type: "error", threadId: session.threadId, @@ -3127,6 +3147,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func childCommandLabel: null, runtimeEnv: normalizedRuntimeEnv(input.env), stopOnSettle: input.stopOnSettle ?? false, + startupError: null, }; const createdSession = session; diff --git a/apps/server/src/terminal/OutputProtocol.test.ts b/apps/server/src/terminal/OutputProtocol.test.ts index 6d851b93d374d..7ae536605e8fa 100644 --- a/apps/server/src/terminal/OutputProtocol.test.ts +++ b/apps/server/src/terminal/OutputProtocol.test.ts @@ -218,6 +218,9 @@ describe("terminal output stream", () => { Effect.forkScoped, ); const write = yield* Deferred.await(receive); + // Each event arrives after the batching window, so it is sent on its own. + const publish = (event: TerminalAttachStreamEvent) => + TestClock.adjust("2 millis").pipe(Effect.andThen(publisher.publish(event))); const takeChunk = Effect.fnUntraced(function* (queue: typeof stalled) { const response = yield* Queue.take(queue); assert.equal(response._tag, "Chunk"); @@ -234,7 +237,7 @@ describe("terminal output stream", () => { // Eight unacknowledged chunks fill only client 0's output window. for (let index = 0; index < 7; index++) { const event = output("before-stall-" + index); - yield* publisher.publish(event); + yield* publish(event); assert.deepEqual(yield* takeChunk(stalled), [event]); assert.deepEqual(yield* takeChunk(healthy), [event]); yield* write(1, { _tag: "Ack", requestId: "2" }); @@ -242,7 +245,7 @@ describe("terminal output stream", () => { assert.equal(publisher.listeners.size, 2); for (let index = 0; index < 100; index++) { const event = output(index + ":" + "界".repeat(1365)); - yield* publisher.publish(event); + yield* publish(event); assert.deepEqual(yield* takeChunk(healthy), [event]); yield* write(1, { _tag: "Ack", requestId: "2" }); if (index === 31) assert.equal(publisher.listeners.size, 2); @@ -257,7 +260,7 @@ describe("terminal output stream", () => { yield* write(0, { _tag: "Ack", requestId: "1" }); } const after = output("unique output after recovery"); - yield* publisher.publish(after); + yield* publish(after); assert.deepEqual(yield* takeChunk(healthy), [after]); assert.deepEqual(yield* takeChunk(stalled), [after]); assert.equal(yield* Queue.size(stalled), 0); @@ -327,7 +330,48 @@ describe("terminal output stream", () => { }), ); - it.effect("caps each delivered batch at the output window in UTF-8 bytes", () => + it.effect("emits idle output immediately and batches a burst until a fixed deadline", () => + Effect.gen(function* () { + const publisher = makePublisher(); + const pull = yield* Stream.toPull(terminalOutputStream(attach(publisher, ""))); + assert.deepEqual(yield* pull, [snapshot("")]); + + yield* TestClock.adjust("10 millis"); + yield* publisher.publish(output("a")); + assert.deepEqual(yield* pull, [output("a")]); + + yield* publisher.publish(output("b")); + const burst = yield* pull.pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust("1 millis"); + assert.isUndefined(burst.pollUnsafe()); + // Arrivals inside the window never push the deadline back. + yield* publisher.publish(output("c")); + yield* publisher.publish(output("d")); + yield* TestClock.adjust("1 millis"); + assert.deepEqual(yield* Fiber.join(burst), [output("b"), output("c"), output("d")]); + }).pipe(Effect.scoped), + ); + + it.effect("flushes pending output early, in order, when a lifecycle event arrives", () => + Effect.gen(function* () { + const publisher = makePublisher(); + const pull = yield* Stream.toPull(terminalOutputStream(attach(publisher, ""))); + assert.deepEqual(yield* pull, [snapshot("")]); + + yield* publisher.publish(output("last words")); + const waiting = yield* pull.pipe(Effect.forkChild({ startImmediately: true })); + assert.isUndefined(waiting.pollUnsafe()); + const closed: TerminalAttachStreamEvent = { + type: "closed", + threadId: "thread-1", + terminalId: "default", + }; + yield* publisher.publish(closed); + assert.deepEqual(yield* Fiber.join(waiting), [output("last words"), closed]); + }).pipe(Effect.scoped), + ); + + it.effect("flushes full batches early and caps each at the output window in UTF-8 bytes", () => Effect.gen(function* () { const publisher = makePublisher(); const pull = yield* Stream.toPull(terminalOutputStream(attach(publisher, ""))); @@ -336,8 +380,9 @@ describe("terminal output stream", () => { const data = "界".repeat(1024); for (let index = 0; index < 1024; index++) yield* publisher.publish(output(data)); + // Twenty 3 KiB events fill a 64 KiB batch, so full batches skip the deadline. let delivered = 0; - while (delivered < 1024) { + while (delivered < 1020) { const batch = yield* pull; assert.isAtMost( batch.reduce( @@ -348,7 +393,11 @@ describe("terminal output stream", () => { ); delivered += batch.length; } - assert.equal(delivered, 1024); + assert.equal(delivered, 1020); + const tail = yield* pull.pipe(Effect.forkChild({ startImmediately: true })); + assert.isUndefined(tail.pollUnsafe()); + yield* TestClock.adjust("2 millis"); + assert.lengthOf(yield* Fiber.join(tail), 4); }), ); diff --git a/apps/server/src/terminal/OutputProtocol.ts b/apps/server/src/terminal/OutputProtocol.ts index 0edb5aff4978d..84f6e40923417 100644 --- a/apps/server/src/terminal/OutputProtocol.ts +++ b/apps/server/src/terminal/OutputProtocol.ts @@ -6,6 +6,8 @@ import { } from "@t3tools/contracts"; import type * as Arr from "effect/Array"; import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Latch from "effect/Latch"; import * as Stream from "effect/Stream"; @@ -137,6 +139,9 @@ export function withOutputWindow( } const MAX_QUEUED_OUTPUT = 8 * 1024 * 1024; +// Output that follows an emission this closely waits and rides along in one batch, +// so a PTY that delivers one line per callback (ConPTY) is not sent one frame per line. +const OUTPUT_WINDOW_NANOS = 2_000_000n; type Listener
    = (event: A) => Effect.Effect; // Acquisition must register cleanup synchronously with installing the listener. @@ -152,11 +157,15 @@ export function terminalOutputStream { return Stream.unwrap( Effect.gen(function* () { + const clock = yield* Clock.Clock; const ready = yield* Latch.make(); let pending: Array = []; let sizes: number[] = []; let head = 0; let queued = 0; + // Pending events other than output; any of them flushes the window early. + let lifecycle = 0; + let deadline = 0n; let overflowed = false; let subscription = 0; let unsubscribe: (() => void) | null = null; @@ -168,7 +177,9 @@ export function terminalOutputStream lifecycle > 0 || queued >= MAX_PENDING_BYTES; yield* Effect.addFinalizer(() => Effect.sync(release)); const listen = (from: Subscribe) => @@ -178,16 +189,19 @@ export function terminalOutputStream Effect.sync(() => { if (id !== subscription) return; + const wasEmpty = head === pending.length; const size = queuedSize(event); pending.push(event); sizes.push(size); queued += size; + if (event.type !== "output") lifecycle += 1; // A single snapshot must fit even when history fills the budget. if (queued - sizes[head]! > maxQueued) { release(); overflowed = true; } - ready.openUnsafe(); + // The current or next pull handles the pending output deadline. + if (wasEmpty || overflowed || urgent()) ready.openUnsafe(); }), (stop) => { // Overflow or cancellation may invalidate acquisition before registration. @@ -204,6 +218,7 @@ export function terminalOutputStream => { @@ -228,9 +243,16 @@ export function terminalOutputStream= deadline || urgent()) { + deadline = now + OUTPUT_WINDOW_NANOS; + return Effect.succeed(takeBatch()); + } + return Effect.raceFirst(ready.await, Effect.sleep(Duration.nanos(deadline - now))).pipe( + Effect.andThen(pull), + ); }, ); diff --git a/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts b/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts index 783417693c722..5a410dbf342f7 100644 --- a/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts +++ b/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts @@ -549,6 +549,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { { name: "hooks.json", value: "{}", available: true }, { name: "hooks.json", value: '{"hooks":{}}', available: true }, { name: "mcp_config.json", value: '{"mcpServers":{}}', available: true }, + { name: "mcp_config.json", value: "", available: true }, ])("checks $name before starting a helper, available=$available", ({ name, value, available }) => Effect.gen(function* () { const fixture = yield* makeFixture(); diff --git a/apps/server/src/textGeneration/AntigravityTextGeneration.ts b/apps/server/src/textGeneration/AntigravityTextGeneration.ts index b7e7cfaeb40e8..b67bad85faf03 100644 --- a/apps/server/src/textGeneration/AntigravityTextGeneration.ts +++ b/apps/server/src/textGeneration/AntigravityTextGeneration.ts @@ -79,14 +79,20 @@ export const isAntigravityTextGenerationAvailable = Effect.fn( if (info.type !== "File" || info.size > 64_000n) { return false; } + // CLI 1.5.8 writes a 0-byte mcp_config.json before any server exists. const empty = yield* fs.readFileString(configurationPath).pipe( - Effect.flatMap(decodeConfiguration), - Effect.flatMap((configuration) => - decodeConfigurationObject( - configuration[name === "hooks.json" ? "hooks" : "mcpServers"] ?? configuration, - ), + Effect.flatMap((text) => + text.trim().length === 0 + ? Effect.succeed(true) + : decodeConfiguration(text).pipe( + Effect.flatMap((configuration) => + decodeConfigurationObject( + configuration[name === "hooks.json" ? "hooks" : "mcpServers"] ?? configuration, + ), + ), + Effect.map((configuration) => Object.keys(configuration).length === 0), + ), ), - Effect.map((configuration) => Object.keys(configuration).length === 0), Effect.orElseSucceed(() => false), ); if (!empty) return false; diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index a7041d5d249e5..d2e165ea3b2b5 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -234,6 +234,35 @@ it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { }), ); + it.effect("passes --settings from the instance launch args to Claude text generation", () => + withFakeClaudeEnv( + { + output: JSON.stringify({ + structured_output: { + title: "Use instance settings", + }, + }), + argsMustContain: `"env":{"ANTHROPIC_VERTEX_PROJECT_ID":"vertex-project-a"}`, + claudeConfig: { + launchArgs: `--settings '{"env":{"ANTHROPIC_VERTEX_PROJECT_ID":"vertex-project-a"}}'`, + }, + }, + (textGeneration) => + Effect.gen(function* () { + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "thread title", + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: SYNTHETIC_CLAUDE_STANDARD_MODEL, + }, + }); + + expect(generated.title).toBe(sanitizeThreadTitle("Use instance settings")); + }), + ), + ); + it.effect("retries without --no-session-persistence when the Claude CLI rejects it", () => withFakeClaudeEnv( { diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts index 756a068926a60..a523a3873a2c5 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts @@ -1,6 +1,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; 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 Stream from "effect/Stream"; @@ -33,6 +34,7 @@ import { hasClaudeManagedMcpConfig, makeClaudeEnvironment, } from "../provider/Drivers/ClaudeHome.ts"; +import { readClaudeLaunchArgSettings } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; const CLAUDE_TIMEOUT_MS = 180_000; /** `--tools` takes bare names; patterns go in the allow list. */ @@ -105,6 +107,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu ) { const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment); const scopedModelCatalog = modelCatalog.pipe( Effect.map((catalog) => scopeClaudeModelCatalog(catalog, claudeSettings.customModels)), @@ -200,7 +203,18 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu : undefined; const fastMode = fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined; + const launchArgSettings = yield* readClaudeLaunchArgSettings({ + settings: claudeSettings, + cwd, + fileSystem, + path, + }).pipe( + Effect.mapError( + (cause) => new TextGenerationError({ operation, detail: cause.message, cause }), + ), + ); const settings = { + ...launchArgSettings, disableAllHooks: true, ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}), ...(fastMode ? { fastMode: true } : {}), diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index e6e43d606e27f..1a1a5c43b0a0d 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -499,6 +499,26 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { ), ); + it.effect("keeps user hooks off over launch args that turn them on", () => + withFakeCodexEnv( + { + output: JSON.stringify({ title: "Hookless title" }), + launchArgs: "--config features.hooks=true --enable hooks", + requireArg: "--config features.codex_hooks=false --config features.hooks=false", + forbidArg: "--enable", + }, + (textGeneration) => + Effect.gen(function* () { + const result = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Describe this change", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + expect(result.title).toBe("Hookless title"); + }), + ), + ); + it.effect("passes exec-safe launch args into codex exec", () => withFakeCodexEnv( { diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index 49c60166111ba..fc741aaaeb262 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -326,6 +326,11 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func model, "--config", `model_reasoning_effort="${reasoningEffort}"`, + // Current Codex gives hooks precedence over the historical codex_hooks alias. + "--config", + "features.codex_hooks=false", + "--config", + "features.hooks=false", ...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []), "--output-schema", schemaPath, diff --git a/apps/server/src/textGeneration/GrokTextGeneration.test.ts b/apps/server/src/textGeneration/GrokTextGeneration.test.ts index 26ab9e79c7103..adb911623f800 100644 --- a/apps/server/src/textGeneration/GrokTextGeneration.test.ts +++ b/apps/server/src/textGeneration/GrokTextGeneration.test.ts @@ -35,7 +35,7 @@ function makeAcpGrokWrapper(dir: string, env: Record): string { env, source: execScriptSource({ scriptPath: mockAgentPath, - expectedArgs: ["agent", "stdio"], + expectedArgs: ["--permission-mode", "default", "agent", "stdio"], }), }); } @@ -58,14 +58,19 @@ function withFakeAcpGrok( }).pipe(Effect.scoped); } -function readJsonRpcRequests( - filePath: string, -): ReadonlyArray<{ readonly method?: string; readonly params?: Record }> { +function readJsonRpcRequests(filePath: string): ReadonlyArray<{ + readonly id?: unknown; + readonly method?: string; + readonly params?: Record; +}> { return NodeFS.readFileSync(filePath, "utf8") .trim() .split("\n") .filter((line) => line.length > 0) - .map((line) => JSON.parse(line) as { method?: string; params?: Record }); + .map( + (line) => + JSON.parse(line) as { id?: unknown; method?: string; params?: Record }, + ); } it.layer(layerGrokTextGenerationTest)("GrokTextGeneration", (it) => { @@ -78,6 +83,7 @@ it.layer(layerGrokTextGenerationTest)("GrokTextGeneration", (it) => { return withFakeAcpGrok( { T3_ACP_REQUEST_LOG_PATH: requestLogPath, + T3_ACP_REQUEST_PERMISSION: "1", T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ subject: "Add Grok provider", body: "Wire up the ACP runtime and headless text generation path.", @@ -110,6 +116,9 @@ it.layer(layerGrokTextGenerationTest)("GrokTextGeneration", (it) => { request.params?.modelId === "grok-mock-alt", ), ).toBe(true); + expect(requests.find((request) => request.id === 9001)).toMatchObject({ + result: { outcome: { outcome: "cancelled" } }, + }); }), ); }); diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 652024e174775..d6e48d526fe73 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -217,6 +217,7 @@ const layerService = (input: { Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Layer.provideMerge(Layer.succeed(HostProcess.Platform, input.platform ?? "linux")), Layer.provideMerge(Layer.succeed(HostProcess.Hostname, input.hostname ?? "usage-test-host")), + Layer.provideMerge(Layer.succeed(HostProcess.HomeDirectory, input.home)), Layer.provideMerge(ServerSettings.layerTest(input.settings)), Layer.provideMerge( Layer.succeed( @@ -1236,6 +1237,76 @@ describe("UsageService", () => { }), ); + it.effect("prices Pi usage mapped onto a Pi model at that model's rate", () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + const dir = NodePath.join(home, "pi", "sessions", "project"); + const message = (id: string, model: string) => ({ + type: "message", + id, + timestamp: "2026-08-01T10:00:00Z", + message: { + role: "assistant", + provider: "anthropic", + model, + usage: { input: 10, output: 5 }, + }, + }); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(dir, { recursive: true }); + await NodeFSP.writeFile( + NodePath.join(dir, "session.jsonl"), + [ + { type: "session", id: "session" }, + message("released", "actual-model"), + message("preview", "actual-model-preview"), + ] + .map((line) => encodeUnknownJsonString(line)) + .join("\n") + "\n", + ); + }); + const summary = yield* Effect.gen(function* () { + const service = yield* UsageService.make; + return yield* service.readSummary(WINDOW); + }).pipe( + Effect.scoped, + Effect.provide( + layerService({ + prefix: "usage-pi-model-alias", + home, + ratesDocument: { + "actual-model": { input_cost_per_token: 1, output_cost_per_token: 4 }, + }, + settings: { + ...settings, + usageModelAliases: { "anthropic/actual-model-preview": "anthropic/actual-model" }, + }, + }), + ), + ); + assert.deepStrictEqual( + summary.buckets + .filter((bucket) => bucket.provider === "pi") + .map(({ model, records, unpricedRecords, costUsd, costSource }) => ({ + model, + records, + unpricedRecords, + costUsd, + costSource, + })), + [ + { + model: "anthropic/actual-model", + records: 2, + unpricedRecords: 0, + costUsd: 60, + costSource: "modelPriced", + }, + ], + ); + }), + ); + it.effect( "reads Muse inference history once, persists appended usage, and reprices unknown models", () => @@ -2603,6 +2674,34 @@ describe("UsageService", () => { }), ); + it.effect("keeps default-home history after the default account moves to a custom home", () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + const defaultHome = NodePath.join(home, "default-claude"); + const defaultProjects = NodePath.join(defaultHome, "projects", "proj"); + yield* Effect.promise(async () => { + await NodeFSP.writeFile(transcript, claudeLine(1, 5)); + await NodeFSP.mkdir(defaultProjects, { recursive: true }); + await NodeFSP.writeFile( + NodePath.join(defaultProjects, "earlier.jsonl"), + claudeLine(2, 7, "claude-fable-5", "earlier-session"), + ); + }); + const summary = yield* UsageService.make.pipe( + Effect.flatMap((service) => service.readSummary(WINDOW)), + Effect.provide( + layerService({ + prefix: "usage-service-default-home-test", + home, + environment: { CLAUDE_CONFIG_DIR: defaultHome }, + settings, + }), + ), + ); + assert.strictEqual(totalOutputTokens(summary), 12); + }), + ); + it.effect( "uses explicit account settings before environment and default homes, then refreshes them", () => diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 5ed7a5e8e75b6..1a0a6d4a2ddc6 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -90,6 +90,12 @@ const scanReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) => driver.usage?.kind === "scan" ? [{ driver, reader: driver.usage }] : [], ); +const providerRateModels = new Map( + BUILT_IN_USAGE_DRIVERS.flatMap(({ usage }) => + usage?.rateModel === undefined ? [] : [[usage.provider, usage.rateModel] as const], + ), +); + const transcriptFormats = new Map( transcriptReaders.map(({ reader }) => [reader.provider, reader.format] as const), ); @@ -360,9 +366,8 @@ export const make = Effect.gen(function* () { > = Object.entries(settings.providerInstances) .filter(([, instance]) => instance.driver === driver.driverKind) .map(([id, instance]) => [ProviderInstanceId.make(id), instance, true] as const); - if (!Object.hasOwn(settings.providerInstances, driver.driverKind)) { - entries.push([ProviderInstanceId.make(driver.driverKind), {}, false]); - } + // History in the driver's default home stays counted after every instance moves elsewhere; readers dedupe shared directories. + entries.push([ProviderInstanceId.make(driver.driverKind), {}, false]); const decodeConfig = Schema.decodeUnknownOption(driver.configSchema); return yield* Effect.forEach( entries, @@ -999,6 +1004,7 @@ export const make = Effect.gen(function* () { rates, priceOverrides, modelAliases, + rateModel: (provider, model) => providerRateModels.get(provider)?.(model), ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }), }); diff --git a/apps/server/src/usage/usageAggregation.test.ts b/apps/server/src/usage/usageAggregation.test.ts index 3819903606be2..58953fbcfafea 100644 --- a/apps/server/src/usage/usageAggregation.test.ts +++ b/apps/server/src/usage/usageAggregation.test.ts @@ -277,6 +277,7 @@ describe("UsageAggregator", () => { untilDay: "2026-08-31", rates, modelAliases: resolveModelAliases({ "example-preview": "claude-fable-5" }), + rateModel: () => "claude-fable", }); aggregator.add(record()); aggregator.add(record({ model: "example-preview", rateModel: "example-preview-high" })); diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts index ce7a78a99d9c1..f4c39753548fd 100644 --- a/apps/server/src/usage/usageAggregation.ts +++ b/apps/server/src/usage/usageAggregation.ts @@ -10,7 +10,7 @@ import type { } from "@t3tools/contracts"; import { EMPTY_TOTALS, type UsageRecord } from "@t3tools/provider-core/server/usage"; -import { cacheSavingsUsd, priceUsage, type RateTable } from "./usagePricing.ts"; +import { cacheSavingsUsd, lookupRate, priceUsage, type RateTable } from "./usagePricing.ts"; // en-CA gives ISO-ordered parts in the requested zone; Date getters are host-local. function makeDayFormatter(timeZone: string): (timestampMs: number) => string { @@ -70,6 +70,7 @@ export interface AggregateOptions { readonly rates: RateTable; readonly priceOverrides?: RateTable; readonly modelAliases?: ReadonlyMap; + readonly rateModel?: (provider: UsageRecord["provider"], model: string) => string | undefined; readonly modelFilter?: UsageModelFilter; readonly resolution?: UsageResolution; readonly sinceTimeMs?: number; @@ -341,12 +342,16 @@ export class UsageAggregator { if (priced.costSource === "providerReported") bucket.providerReportedRecords += 1; } - // Aliases use the target's rate, replacing provider-specific rateModel. + // Aliases use the target's rate. Only an unpriced target goes through the provider's own rate naming. #mapModel(record: UsageRecord): UsageRecord { const model = this.#options.modelAliases?.get(record.model); if (model === undefined) return record; const { rateModel: _rateModel, ...rest } = record; - return { ...rest, model }; + const rateModel = + lookupRate(this.#options.rates, model) === null + ? this.#options.rateModel?.(record.provider, model) + : undefined; + return rateModel === undefined ? { ...rest, model } : { ...rest, model, rateModel }; } // Time-ordered records usually reuse the previous bucket; avoid rebuilding its key. diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 14a3c1ca65a1b..363545bf7352e 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -5287,6 +5287,21 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reports no branch while a clone has not checked out HEAD yet", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* driver.initRepo({ cwd }); + // `git clone` points HEAD here until checkout; status then prints `branch.head (unknown)`. + yield* (yield* FileSystem.FileSystem).writeFileString( + NodePath.join(cwd, ".git", "HEAD"), + "ref: refs/heads/.invalid\n", + ); + + assert.equal((yield* driver.statusDetailsLocal(cwd)).branch, null); + }), + ); + it.effect("records no failed span reading status of a repository without a remote", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -7282,6 +7297,41 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect.skipIf(!symlinksSupported)( + "removes a worktree whose .git file git-annex replaced with a symlink, keeping the symlink when refused", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const pathService = yield* Path.Path; + const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "annexed"); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* driver.createWorktree({ + cwd, + path: worktreePath, + refName: initialBranch, + newRefName: "feature/annexed", + }); + const gitFile = pathService.join(worktreePath, ".git"); + const adminDir = (yield* git(worktreePath, ["rev-parse", "--absolute-git-dir"])).trim(); + NodeFS.rmSync(gitFile); + NodeFS.symlinkSync(adminDir, gitFile); + yield* writeTextFile(worktreePath, "notes.txt", "draft\n"); + + const refused = yield* Effect.result(driver.removeWorktree({ cwd, path: worktreePath })); + + assert.isTrue(Result.isFailure(refused)); + assert.isTrue(NodeFS.lstatSync(gitFile).isSymbolicLink()); + assert.equal(NodeFS.realpathSync(gitFile), NodeFS.realpathSync(adminDir)); + NodeFS.rmSync(pathService.join(worktreePath, "notes.txt")); + + yield* driver.removeWorktree({ cwd, path: worktreePath }); + + assert.isFalse(NodeFS.existsSync(worktreePath)); + assert.isFalse(NodeFS.existsSync(adminDir)); + }), + ); + it.effect("leaves a folder alone that only shares the worktree's short name", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -8358,6 +8408,53 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("keeps other files conflicted through a selected-file commit", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + // git stash pop leaves README.md conflicted with no merge in progress. + yield* writeTextFile(cwd, "README.md", "stashed version\n"); + yield* git(cwd, ["stash"]); + yield* writeTextFile(cwd, "README.md", "committed version\n"); + yield* git(cwd, ["commit", "-am", "Change README"]); + const pop = yield* driver.execute({ + operation: "test.stashPop", + cwd, + args: ["stash", "pop"], + allowNonZeroExit: true, + }); + assert.equal(pop.exitCode, 1); + yield* writeTextFile(cwd, "other.txt", "other\n"); + const head = yield* git(cwd, ["rev-parse", "HEAD"]); + const unmerged = yield* git(cwd, ["ls-files", "--unmerged"]); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const nested = path.join(cwd, "nested"); + yield* fs.makeDirectory(nested); + // A formatting hook stages its edit into the temporary index that --only commits from. + yield* writeTextFile( + cwd, + ".git/hooks/pre-commit", + "#!/bin/sh\necho formatted >> other.txt\ngit add other.txt\n", + ); + yield* fs.chmod(path.join(cwd, ".git/hooks/pre-commit"), 0o755); + + yield* driver.commit(cwd, "Add other", "", { stage: { filePaths: ["other.txt"] } }); + + assert.equal(yield* git(cwd, ["rev-parse", "HEAD~1"]), head); + assert.equal(yield* git(cwd, ["show", "--pretty=", "--name-only", "HEAD"]), "other.txt"); + assert.equal(yield* git(cwd, ["show", "HEAD:other.txt"]), "other\nformatted"); + assert.equal(yield* git(cwd, ["show", ":other.txt"]), "other\nformatted"); + assert.equal(yield* git(cwd, ["ls-files", "--unmerged"]), unmerged); + const all = yield* driver.prepareCommitContext(nested).pipe(Effect.flip); + assert.equal( + all.detail, + "Cannot commit with unresolved merge conflicts in README.md. Resolve them, then commit.", + ); + }), + ); + const commitWithHooks = (hooks: Record) => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 36bb3fe576cd7..da1794188b0b2 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2500,7 +2500,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } if (line.startsWith("# branch.head ")) { const value = line.slice("# branch.head ".length).trim(); - refName = value === "(detached)" ? null : value; + // `(unknown)` is printed while HEAD names no resolvable branch, e.g. mid-`git clone`. + refName = value === "(detached)" || value === "(unknown)" ? null : value; continue; } if (line.startsWith("# branch.upstream ")) { @@ -2679,6 +2680,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const config = env ? ["-c", "core.splitIndex=false", "-c", "splitIndex.sharedIndexExpire=never"] : []; + let preserveUnselectedConflicts = false; if (filePaths && filePaths.length > 0) { if (env) { const head = yield* executeGit( @@ -2755,7 +2757,20 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* detail: `Cannot commit selected files during a ${operation}. Commit all files to finish the ${operation}.`, }); } - yield* runGit("GitVcsDriver.commit.reset", cwd, ["reset", "--quiet"]); + const selectedFiles = new Set(filePaths); + const unmergedPaths = yield* runGitStdoutWithOptions( + "GitVcsDriver.commit.unmergedPaths", + cwd, + ["-c", "diff.relative=false", "diff", "--cached", "--name-only", "--diff-filter=U", "-z"], + { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + ); + // Reset drops every conflict stage, so keep the index while unselected files are conflicted. + preserveUnselectedConflicts = unmergedPaths + .split("\0") + .some((file) => file.length > 0 && !selectedFiles.has(file)); + if (!preserveUnselectedConflicts) { + yield* runGit("GitVcsDriver.commit.reset", cwd, ["reset", "--quiet"]); + } } // Status paths are repository-relative, while cwd can be a subdirectory. const pathspecs = filePaths.map((file) => `:(top,literal)${file}`); @@ -2871,6 +2886,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* env ? { env } : {}, ); } + return preserveUnselectedConflicts && filePaths + ? filePaths.map((file) => `:(top,literal)${file}`) + : undefined; }); const prepareCommitContext: GitVcsDriver.GitVcsDriver["Service"]["prepareCommitContext"] = @@ -3015,14 +3033,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* body, options?: GitVcsDriver.GitCommitOptions, ) { - if (options?.stage !== undefined) { - yield* stageCommitChanges(cwd, options.stage.filePaths); - } + const partialCommitPaths = + options?.stage !== undefined + ? yield* stageCommitChanges(cwd, options.stage.filePaths) + : undefined; const args = ["commit", "-m", subject]; const trimmedBody = body.trim(); if (trimmedBody.length > 0) { args.push("-m", trimmedBody); } + const onlyFromStdin = partialCommitPaths ? yield* supportsPathspecFromFile(cwd) : false; + const onlyPathspecArgs = onlyFromStdin + ? ["--pathspec-from-file=-", "--pathspec-file-nul"] + : ["--", ...(partialCommitPaths ?? [])]; + const onlyPathspecStdin = + partialCommitPaths && onlyFromStdin + ? { stdin: partialCommitPaths.map((pathspec) => `${pathspec}\0`).join("") } + : {}; + if (partialCommitPaths) { + args.push("--only", ...onlyPathspecArgs); + } const progress = options?.progress?.onOutputLine === undefined ? options?.progress @@ -3035,9 +3065,19 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }; yield* executeGit("GitVcsDriver.commit.commit", cwd, args, { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, + ...onlyPathspecStdin, ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), ...(progress ? { progress } : {}), }).pipe(Effect.asVoid); + if (partialCommitPaths) { + // --only runs hooks on a temporary index, so a hook's `git add` never reaches the real one. + yield* runGit( + "GitVcsDriver.commit.syncSelectedIndex", + cwd, + ["reset", "--quiet", "HEAD", ...onlyPathspecArgs], + onlyPathspecStdin, + ); + } const commitSha = yield* runGitStdout("GitVcsDriver.commit.revParseHead", cwd, [ "rev-parse", "HEAD", diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 852c9f9ba0631..08fad4ae56aff 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -78,6 +78,7 @@ function layerTestFor(state: { localInvalidationCalls: number; remoteInvalidationCalls: number; remoteStatusRefreshUpstreamValues?: Array; + localStatusBranchChanges?: Array; refSnapshot?: string | null; remoteStatusError?: GitManagerError; backgroundWorkEnabled?: boolean; @@ -109,9 +110,13 @@ function layerTestFor(state: { ), Layer.provide( Layer.mock(GitWorkflowService.GitWorkflowService)({ - localStatus: () => + localStatus: (_input, options) => Effect.suspend(() => { state.localStatusCalls += 1; + const includeBranchChanges = options?.includeBranchChanges !== false; + state.localStatusBranchChanges?.push(includeBranchChanges); + const { branchChanges: _branchChanges, ...withoutBranchChanges } = + state.currentLocalStatus; if (state.failLocalStatus) { return (state.onLocalStatusFailure ?? Effect.void).pipe( Effect.andThen( @@ -126,7 +131,7 @@ function layerTestFor(state: { ); } return (state.beforeLocalStatus ?? Effect.void).pipe( - Effect.as(state.currentLocalStatus), + Effect.as(includeBranchChanges ? state.currentLocalStatus : withoutBranchChanges), ); }), repositoryRoot: () => Effect.sync(() => (state.currentLocalStatus.isRepo ? "/repo" : null)), @@ -1158,6 +1163,116 @@ describe("VcsStatusBroadcaster", () => { }).pipe(Effect.provide(layerTestFor(state))); }); + it.effect("reads Changes totals only while a subscriber shows them", () => { + const branchChanges = { baseRef: "origin/main", insertions: 3, deletions: 1 }; + const state: Parameters[0] = { + currentLocalStatus: { ...baseLocalStatus, branchChanges }, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + localStatusBranchChanges: [], + }; + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const paletteEvents = yield* Queue.unbounded(); + yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe( + Stream.runForEach((event) => Queue.offer(paletteEvents, event)), + Effect.forkScoped, + ); + const paletteSnapshot = yield* Queue.take(paletteEvents); + assert.strictEqual(paletteSnapshot._tag, "snapshot"); + if (paletteSnapshot._tag === "snapshot") { + assert.isUndefined(paletteSnapshot.local.branchChanges); + } + yield* broadcaster.refreshLocalStatus("/repo"); + assert.deepStrictEqual(state.localStatusBranchChanges, [false, false]); + + const headerScope = yield* Scope.make(); + const headerEvents = yield* Queue.unbounded(); + yield* broadcaster.streamStatus({ cwd: "/repo" }).pipe( + Stream.runForEach((event) => Queue.offer(headerEvents, event)), + Effect.forkIn(headerScope), + ); + const headerSnapshot = yield* Queue.take(headerEvents); + assert.strictEqual(headerSnapshot._tag, "snapshot"); + if (headerSnapshot._tag === "snapshot") { + assert.deepStrictEqual(headerSnapshot.local.branchChanges, branchChanges); + } + const paletteUpdate = yield* Queue.take(paletteEvents); + assert.strictEqual(paletteUpdate._tag, "localUpdated"); + if (paletteUpdate._tag === "localUpdated") { + assert.deepStrictEqual(paletteUpdate.local.branchChanges, branchChanges); + } + // The header's first remote poll also rereads local status. + while ((yield* Queue.take(headerEvents))._tag !== "remoteUpdated") {} + const turnEnd = yield* broadcaster.refreshLocalStatus("/repo"); + assert.deepStrictEqual(turnEnd.branchChanges, branchChanges); + + yield* Scope.close(headerScope, Exit.void); + yield* broadcaster.refreshLocalStatus("/repo"); + assert.deepStrictEqual(state.localStatusBranchChanges, [ + false, + false, + true, + true, + true, + false, + ]); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }); + + it.effect("a light refresh that a header joins mid-read publishes Changes totals", () => { + const branchChanges = { baseRef: "origin/main", insertions: 3, deletions: 1 }; + const state: Parameters[0] = { + currentLocalStatus: { ...baseLocalStatus, branchChanges }, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + localStatusBranchChanges: [], + fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }), + }; + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const subscribeHeader = Effect.fn("subscribeHeader")(function* (scope: Scope.Scope) { + const events = yield* Queue.unbounded(); + yield* broadcaster.streamStatus({ cwd: "/repo" }).pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkIn(scope, { startImmediately: true }), + ); + return events; + }); + const firstHeader = yield* Scope.make(); + const firstEvents = yield* subscribeHeader(firstHeader); + while ((yield* Queue.take(firstEvents))._tag !== "remoteUpdated") {} + yield* Scope.close(firstHeader, Exit.void); + + const readStarted = yield* Deferred.make(); + const finishRead = yield* Deferred.make(); + state.beforeLocalStatus = Deferred.succeed(readStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishRead)), + ); + const turnEnd = yield* broadcaster.refreshLocalStatus("/repo").pipe(Effect.forkScoped); + yield* Deferred.await(readStarted); + // Starting immediately registers the header's demand before it waits behind the read. + const secondEvents = yield* subscribeHeader(yield* Scope.make()); + yield* Deferred.succeed(finishRead, undefined); + const snapshot = yield* Queue.take(secondEvents); + assert.strictEqual(snapshot._tag, "snapshot"); + if (snapshot._tag === "snapshot") { + assert.deepStrictEqual(snapshot.local.branchChanges, branchChanges); + } + + assert.deepStrictEqual((yield* Fiber.join(turnEnd)).branchChanges, branchChanges); + assert.deepStrictEqual(state.localStatusBranchChanges?.slice(-2), [false, true]); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }); + it.effect("an explicit refresh reads local totals after the fetch", () => { return Effect.gen(function* () { const fetchStarted = yield* Deferred.make(); @@ -1233,7 +1348,7 @@ describe("VcsStatusBroadcaster", () => { event._tag === "snapshot" ? Deferred.succeed(subscribed, undefined) : Effect.void, ), Stream.filter((event) => event._tag !== "snapshot"), - Stream.take(3), + Stream.take(4), Stream.runCollect, Effect.forkScoped, ); @@ -1254,7 +1369,8 @@ describe("VcsStatusBroadcaster", () => { assert.deepStrictEqual(moved.branchChanges, totals(0).branchChanges); assert.deepStrictEqual( [...(yield* Fiber.join(events))].map((event) => event._tag), - ["remoteUpdated", "remoteUpdated", "localUpdated"], + // The first refresh adds the totals this palette-style subscription skipped. + ["localUpdated", "remoteUpdated", "remoteUpdated", "localUpdated"], ); state.localStatusCalls = 0; @@ -2097,8 +2213,10 @@ it.effect("serializes branch reads with detailed refresh publication", () => { yield* Fiber.join(older); yield* Fiber.join(newer); state.branchRead = () => Effect.succeed("new"); - const result = yield* b.getStatus({ cwd: "/repo" }); - assert.equal(result.refName, "new"); + const result = yield* b + .streamStatus({ cwd: "/repo", includeRemote: false }) + .pipe(Stream.runHead, Effect.flatMap(Effect.fromOption)); + assert.equal(result._tag === "snapshot" && result.local.refName, "new"); assert.equal(state.localStatusCalls, 1); }).pipe(Effect.provide(layerTestFor(state))); }); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 8e69679d50638..b691b9d2978a2 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -143,8 +143,12 @@ interface CachedRemoteStatus extends CachedValue { readonly branch: string | null; } +interface CachedLocalStatus extends CachedValue { + readonly includesBranchChanges: boolean; +} + interface CachedVcsStatus { - readonly local: CachedValue | null; + readonly local: CachedLocalStatus | null; readonly remote: CachedRemoteStatus | null; } @@ -315,14 +319,51 @@ export const make = Effect.gen(function* () { return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null)); }); + // Only full subscribers and direct reads show Changes totals. Command palette rows subscribe + // without remote status and skip them, which halves the git processes a burst of rows spawns. + const branchChangesDemand = new Map(); + const wantsBranchChanges = (cwd: string) => branchChangesDemand.has(cwd); + const acquireBranchChangesDemand = (cwd: string) => + Effect.acquireRelease( + Effect.sync(() => { + branchChangesDemand.set(cwd, (branchChangesDemand.get(cwd) ?? 0) + 1); + }), + () => + Effect.sync(() => { + const count = (branchChangesDemand.get(cwd) ?? 1) - 1; + if (count > 0) branchChangesDemand.set(cwd, count); + else branchChangesDemand.delete(cwd); + }), + ); + + const readLocalStatus = Effect.fn("VcsStatusBroadcaster.readLocalStatus")(function* ( + cwd: string, + ) { + const includeBranchChanges = wantsBranchChanges(cwd); + const local = yield* workflow.localStatus({ cwd }, { includeBranchChanges }); + // A subscriber that shows totals arrived during the read and must not receive it without them. + if (!includeBranchChanges && wantsBranchChanges(cwd)) { + return { + local: yield* workflow.localStatus({ cwd }, { includeBranchChanges: true }), + includesBranchChanges: true, + }; + } + return { local, includesBranchChanges: includeBranchChanges }; + }); + const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")( function* ( cwd: string, - local: VcsStatusLocalResult, + read: { readonly local: VcsStatusLocalResult; readonly includesBranchChanges: boolean }, observation: number, options?: { publish?: boolean }, ) { - const nextLocal = { fingerprint: fingerprintStatusPart(local), value: local }; + const { local, includesBranchChanges } = read; + const nextLocal = { + fingerprint: fingerprintStatusPart(local), + value: local, + includesBranchChanges, + }; const [localChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => { const previous = cache.get(cwd) ?? { local: null, remote: null }; const remote = previous.remote?.branch === local.refName ? previous.remote : null; @@ -373,16 +414,17 @@ export const make = Effect.gen(function* () { options?: { publish?: boolean }, ) { const observation = ++branchObservation; - const local = yield* workflow.localStatus({ cwd }); - return yield* updateCachedLocalStatus(cwd, local, observation, options); + return yield* updateCachedLocalStatus(cwd, yield* readLocalStatus(cwd), observation, options); }); const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")( function* (cwd: string) { const cached = yield* getCachedStatus(cwd); if (cached?.local) { - const branch = yield* workflow.currentBranch(cwd); - if (branch === cached.local.value.refName) return cached.local.value; + if (cached.local.includesBranchChanges || !wantsBranchChanges(cwd)) { + const branch = yield* workflow.currentBranch(cwd); + if (branch === cached.local.value.refName) return cached.local.value; + } yield* workflow.invalidateLocalStatus(cwd); return yield* loadLocalStatus(cwd, { publish: true }); } @@ -407,6 +449,7 @@ export const make = Effect.gen(function* () { "VcsStatusBroadcaster.getStatus", )(function* (input) { const cwd = yield* withFileSystem(normalizeCwd(input.cwd)); + yield* acquireBranchChangesDemand(cwd); yield* getOrLoadLocalStatus(cwd); const cached = yield* getCachedStatus(cwd); if (cached?.local && cached.remote) { @@ -423,14 +466,18 @@ export const make = Effect.gen(function* () { return mergeGitStatusParts(parts.local, parts.remote); }), ); - }); + }, Effect.scoped); // 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(); const localRefreshResults = new Map< string, - { readonly startedAt: number; readonly local: VcsStatusLocalResult } + { + readonly startedAt: number; + readonly local: VcsStatusLocalResult; + readonly includesBranchChanges: boolean; + } >(); const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")( function* (cwd: string) { @@ -440,13 +487,19 @@ export const make = Effect.gen(function* () { cwd, Effect.gen(function* () { const shared = localRefreshResults.get(cwd); - if (shared !== undefined && shared.startedAt >= requestedAt) return shared.local; + if ( + shared !== undefined && + shared.startedAt >= requestedAt && + (shared.includesBranchChanges || !wantsBranchChanges(cwd)) + ) { + return shared.local; + } const startedAt = localRefreshRequests.get(cwd) ?? requestedAt; yield* workflow.invalidateLocalStatus(cwd); const observation = ++branchObservation; - const local = yield* workflow.localStatus({ cwd }); - localRefreshResults.set(cwd, { startedAt, local }); - return yield* updateCachedLocalStatus(cwd, local, observation, { publish: true }); + const read = yield* readLocalStatus(cwd); + localRefreshResults.set(cwd, { startedAt, ...read }); + return yield* updateCachedLocalStatus(cwd, read, observation, { publish: true }); }), ); }, @@ -623,6 +676,7 @@ export const make = Effect.gen(function* () { "VcsStatusBroadcaster.refreshStatus", )(function* (rawCwd, options) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); + yield* acquireBranchChangesDemand(cwd); const refsBeforeLocalRead = options?.localOnly ? null : yield* workflow.readRefSnapshot(cwd); yield* refreshLocalStatusCore(cwd); if (options?.localOnly) { @@ -631,7 +685,7 @@ export const make = Effect.gen(function* () { return mergeGitStatusParts(parts.local, parts.remote); } return yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead); - }); + }, Effect.scoped); const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn( "VcsStatusBroadcaster.refreshAfterCheckout", @@ -1055,6 +1109,7 @@ export const make = Effect.gen(function* () { else detailedSubscribers.set(cwd, remaining); }), ); + if (input.includeRemote !== false) yield* acquireBranchChangesDemand(cwd); const subscription = yield* PubSub.subscribe(changesPubSub); // Watch before reading so a checkout in between still publishes. yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd)); diff --git a/apps/server/src/vcs/worktreeRemoval.ts b/apps/server/src/vcs/worktreeRemoval.ts index f1140cdcc3a48..b48994873b282 100644 --- a/apps/server/src/vcs/worktreeRemoval.ts +++ b/apps/server/src/vcs/worktreeRemoval.ts @@ -9,6 +9,42 @@ import type * as GitVcsDriver from "./GitVcsDriver.ts"; const INDEX_LIST_MAX_BYTES = 64 * 1024 * 1024; +/** + * git-annex replaces a linked worktree's `.git` file with a symlink to its admin + * directory, so its symlinks into `.git/annex` resolve. Git then refuses to remove it. + */ +const annexedAdminDir = Effect.fn("WorktreeRemoval.annexedAdminDir")( + function* (worktreePath: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const adminDir = path.resolve( + worktreePath, + yield* fileSystem.readLink(path.join(worktreePath, ".git")), + ); + const pointsBackTo = path.dirname( + path.resolve( + adminDir, + (yield* fileSystem.readFileString(path.join(adminDir, "gitdir"))).trim(), + ), + ); + return (yield* fileSystem.realPath(pointsBackTo)) === (yield* fileSystem.realPath(worktreePath)) + ? Option.some(adminDir) + : Option.none(); + }, + Effect.orElseSucceed(() => Option.none()), +); + +export const isLinkedWorktree = Effect.fn("WorktreeRemoval.isLinkedWorktree")(function* ( + worktreePath: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + return ( + (yield* fileSystem.stat(path.join(worktreePath, ".git"))).type === "File" || + Option.isSome(yield* annexedAdminDir(worktreePath)) + ); +}); + /** * Git for Windows before 2.54 follows NTFS junctions; newer Git leaves them behind. * On Windows, mirror Git's removal checks, then delete with Node's `rm`, which @@ -33,6 +69,39 @@ export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorkt // Git refuses to remove a worktree with untracked files unless forced, but // its check honors `status.showUntrackedFiles=no` and would delete them. const statusConfig = ["-c", "status.showUntrackedFiles=normal"]; + // Git's own refusals, worded the way it prints them. + const refuse = (message: string, cause?: unknown) => + new GitCommandError({ + operation: input.operation, + command: "git worktree remove", + cwd: input.cwd, + detail: `fatal: ${message}`, + ...(cause === undefined ? {} : { cause }), + }); + const annexed = yield* annexedAdminDir(worktreePath); + if (Option.isSome(annexed)) { + const adminDir = annexed.value; + const writeGitFile = fileSystem.writeFileString(gitFile, `gitdir: ${adminDir}\n`); + // A kept worktree's annexed files resolve only through the symlink; a gitdir + // file is the fallback when it cannot be recreated. + yield* Effect.addFinalizer(() => + fileSystem.exists(worktreePath).pipe( + Effect.flatMap((kept) => + kept + ? fileSystem.remove(gitFile, { force: true }).pipe( + Effect.andThen(fileSystem.symlink(adminDir, gitFile)), + Effect.catch(() => writeGitFile), + ) + : Effect.void, + ), + Effect.ignore, + ), + ); + yield* fileSystem.remove(gitFile).pipe( + Effect.andThen(writeGitFile), + Effect.mapError((cause) => refuse(`failed to replace '${gitFile}'`, cause)), + ); + } const linked = (yield* HostProcess.isWindows) && (yield* fileSystem.stat(gitFile).pipe( @@ -50,15 +119,6 @@ export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorkt ]); } - // Git's own refusals, worded the way it prints them. - const refuse = (message: string, cause?: unknown) => - new GitCommandError({ - operation: input.operation, - command: "git worktree remove", - cwd: input.cwd, - detail: `fatal: ${message}`, - ...(cause === undefined ? {} : { cause }), - }); const gitOutput = (cwd: string, args: ReadonlyArray, env?: NodeJS.ProcessEnv) => input .execute({ @@ -153,4 +213,4 @@ export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorkt ); // The folder is gone, so Git only drops the worktree's metadata. return yield* input.run(["worktree", "remove", "--force", "--force", "--", worktreePath]); -}); +}, Effect.scoped); diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 1c50b94a7cbcc..92d8bc882c951 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -1014,6 +1014,68 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { expect({ finders, rescans }).toEqual({ finders: 1, rescans: 1 }); }), ); + + it.effect("serves content search once a first scan that outlasted the wait finishes", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-slow-scan-" }); + yield* writeTextFile(cwd, "src/notes.ts", "const needle = 1;\n"); + // Real finders; only the initial wait and the progress it reads report a scan still running. + let scanning = true; + let finders = 0; + let settle = (): Promise => Promise.resolve(); + const createFinder = FileFinder.create.bind(FileFinder); + vi.spyOn(FileFinder, "create").mockImplementation((options) => { + const created = createFinder(options); + if (!created.ok) return created; + const finder = created.value; + finders += 1; + const waitForIndexReady = finder.waitForIndexReady.bind(finder); + settle = () => waitForIndexReady(15_000); + finder.waitForIndexReady = (timeoutMs) => + scanning ? Promise.resolve({ ok: true, value: false }) : waitForIndexReady(timeoutMs); + const getScanProgress = finder.getScanProgressAsync.bind(finder); + finder.getScanProgressAsync = async () => { + const progress = await getScanProgress(); + return scanning && progress.ok + ? { + ok: true, + value: { ...progress.value, isScanning: true, isWarmupComplete: false }, + } + : progress; + }; + return created; + }); + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searchNeedle = workspaceEntries + .searchContents({ + cwd, + query: "needle", + limit: 100, + caseSensitive: true, + wholeWord: false, + useRegex: false, + }) + .pipe( + Effect.map((result): unknown => result.matches.map((match) => match.path)), + Effect.catchTags({ + WorkspaceSearchIndexScanTimedOut: (error) => Effect.succeed(error._tag), + }), + ); + + const whileScanning = yield* Effect.all([searchNeedle, searchNeedle], { + concurrency: "unbounded", + }); + scanning = false; + yield* Effect.promise(() => settle()); + const afterScan = yield* searchNeedle; + + expect({ whileScanning, afterScan, finders }).toEqual({ + whileScanning: ["WorkspaceSearchIndexScanTimedOut", "WorkspaceSearchIndexScanTimedOut"], + afterScan: ["src/notes.ts"], + finders: 1, + }); + }), + ); }); describe("browse", () => { diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.ts index 51b1720126536..ad1d2c2ae0ebe 100644 --- a/apps/server/src/workspace/WorkspaceEntries.ts +++ b/apps/server/src/workspace/WorkspaceEntries.ts @@ -179,7 +179,6 @@ export const make = Effect.gen(function* () { function* ( cause: | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed - | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed, ) { yield* Effect.logWarning("Failed to refresh workspace search index", { @@ -197,7 +196,6 @@ export const make = Effect.gen(function* () { Effect.provide(workspaceSearchIndexes.get(indexKey)), Effect.catchTags({ WorkspaceSearchIndexCreateFailed: recoverRefreshFailure, - WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure, WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure, }), ); diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 8d9798baadfd7..fd92420396e48 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -142,7 +142,10 @@ export class WorkspaceSearchIndex extends Context.Service< ) => Effect.Effect; readonly searchContents: ( input: Omit, - ) => Effect.Effect; + ) => Effect.Effect< + ProjectSearchContentsResult, + WorkspaceSearchIndexScanTimedOut | WorkspaceSearchIndexSearchFailed + >; readonly refresh: () => Effect.Effect; } >()("t3/workspace/WorkspaceSearchIndex") {} @@ -585,13 +588,12 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( cause, }), ).pipe( + // The scan keeps running on this finder; failing here would destroy it and cache the failure. Effect.catchTags({ - WorkspaceSearchIndexScanTimedOut: (error) => - variant === "paths" - ? Effect.sync(() => { - initialScanTimedOut = true; - }) - : Effect.fail(error), + WorkspaceSearchIndexScanTimedOut: () => + Effect.sync(() => { + initialScanTimedOut = true; + }), }), ); @@ -609,7 +611,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* ( query: string, pageSize: number, - operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch", + operation: "directorySearch" | "fileSearch" | "getScanProgress" | "grep" | "mixedSearch", execute: () => Promise>, ): Effect.fn.Return { // fff's searches wait on its picker lock, which its watcher can hold for minutes. @@ -1036,6 +1038,20 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn( "WorkspaceSearchIndex.searchContents", )(function* (input) { + if (initialScanTimedOut) { + const progress = yield* runSearch(input.query, input.limit, "getScanProgress", () => + finder.getScanProgressAsync(), + ); + // Files the first scan has not indexed yet would read as "No results found". + if (!progress.isWarmupComplete) { + return yield* new WorkspaceSearchIndexScanTimedOut({ + cwd, + timeout: WORKSPACE_INDEX_SCAN_TIMEOUT, + }); + } + initialScanTimedOut = false; + } + let { searchQuery, regexMode } = buildContentSearchQuery(input); const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS; // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing. diff --git a/apps/web/src/appearanceFonts.ts b/apps/web/src/appearanceFonts.ts index 19f2d88d3c29d..50a664fea336e 100644 --- a/apps/web/src/appearanceFonts.ts +++ b/apps/web/src/appearanceFonts.ts @@ -276,6 +276,18 @@ function resolveGenericFamilyLabel(generic: string): string | null { return null; } +// Synthetic Apple labels are not necessarily available as named CSS families. +export function displayFontFamily(family: string): string { + const label = family + .trim() + .replace(/^(['"])(.*)\1$/, "$2") + .trim() + .toLowerCase(); + if (label === "sf pro") return appearanceFontStack(family, DEFAULT_SANS_FONT_STACK); + if (label === "sf mono") return DEFAULT_CODE_FONT_STACK; + return cssFontFamilies(family) ?? ""; +} + export function resolveDefaultFamilyLabel(stack: string): string | null { for (const raw of stack.split(",")) { const family = raw.trim().replace(/^(['"])(.*)\1$/, "$2"); diff --git a/apps/web/src/authBootstrap.test.ts b/apps/web/src/authBootstrap.test.ts index 2c2887ac3a496..85192d0edbf49 100644 --- a/apps/web/src/authBootstrap.test.ts +++ b/apps/web/src/authBootstrap.test.ts @@ -8,6 +8,7 @@ import { import { createBrowserHistory } from "@tanstack/react-router"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import { HttpClientError, HttpClientRequest } from "effect/http"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { installEnvironmentHttpTest } from "../test/environmentHttpTest"; @@ -166,6 +167,54 @@ describe("resolveInitialServerAuthGateState", () => { expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]); }); + it("retries the desktop bootstrap while the backend is still unreachable", async () => { + const nextSession = sequence( + unauthenticatedSession(DESKTOP_AUTH), + authenticatedSession(DESKTOP_AUTH), + ); + const testApi = await installAuthApi({ + session: nextSession, + browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])), + }); + // What FetchHttpClient yields when nothing listens on the backend port. + const connectionRefused = new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ + request: HttpClientRequest.get("http://localhost:3773/api/auth/session"), + cause: new TypeError("Failed to fetch"), + }), + }); + let unreachableAttempts = 1; + __setPrimaryHttpRunnerForTests((effect) => { + if (unreachableAttempts > 0) { + unreachableAttempts -= 1; + return Promise.reject(connectionRefused); + } + return testApi.run(effect); + }); + + const testWindow = installTestBrowser("http://localhost/"); + testWindow.desktopBridge = { + getLocalEnvironmentBootstraps: () => [ + { + id: "primary", + label: "Local", + httpBaseUrl: "http://localhost:3773", + wsBaseUrl: "ws://localhost:3773", + bootstrapToken: "desktop-bootstrap-token", + }, + ], + } as unknown as DesktopBridge; + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + vi.useFakeTimers({ toFake: ["setTimeout", "Date"] }); + await Promise.all([ + expect(resolveInitialServerAuthGateState()).resolves.toEqual({ status: "authenticated" }), + vi.advanceTimersByTimeAsync(1_000), + ]); + expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]); + }); + it("takes a pairing token from the location hash and strips it immediately", async () => { const testWindow = installTestBrowser("http://localhost/#token=pairing-token"); const { takePairingTokenFromUrl } = await import("./environments/primary"); diff --git a/apps/web/src/components/AppRouteModal.browser.test.tsx b/apps/web/src/components/AppRouteModal.browser.test.tsx index cb31eeca45ab0..004e07744e22e 100644 --- a/apps/web/src/components/AppRouteModal.browser.test.tsx +++ b/apps/web/src/components/AppRouteModal.browser.test.tsx @@ -24,4 +24,24 @@ describe("AppRouteModal", () => { expect(onCommit).toHaveBeenCalledWith("Keep titles short"); }); + + it("stays open when Esc belongs to a modal outside Base UI", async () => { + await using _screen = await render( + + undefined} /> + , + { router: "/settings/general" }, + ); + const settings = page.getByRole("dialog", { name: "Settings" }); + // Base UI takes initial focus a frame after opening; let it land before Clerk's modal takes focus. + await expect.element(settings).toHaveFocus(); + // Clerk renders its account modal in its own root and dismisses on a document Esc listener. + const foreignModal = document.body.appendChild(document.createElement("input")); + using _foreignModal = { [Symbol.dispose]: () => foreignModal.remove() }; + + foreignModal.focus(); + await userEvent.keyboard("{Escape}"); + + await expect.element(settings).toHaveAttribute("data-open"); + }); }); diff --git a/apps/web/src/components/AppRouteModal.tsx b/apps/web/src/components/AppRouteModal.tsx index bfce6b50d4cac..0c8a8a670d2f6 100644 --- a/apps/web/src/components/AppRouteModal.tsx +++ b/apps/web/src/components/AppRouteModal.tsx @@ -31,8 +31,18 @@ export function AppRouteModal({ label, children }: { label: string; children: Re open={open} // Portaled layers outside this tree (toasts, Clerk, confirm dialogs) are not backdrop presses. disablePointerDismissal - onOpenChange={(nextOpen) => { + onOpenChange={(nextOpen, eventDetails) => { if (nextOpen) return; + // Esc from a layer outside Base UI (Clerk's modals) is that layer's to handle. + const target = eventDetails.event.target; + if ( + eventDetails.reason === "escape-key" && + target !== document.body && + target instanceof Node && + !popupRef.current?.contains(target) + ) { + return eventDetails.cancel(); + } // Closing unmounts a focused field without a blur, so commit-on-blur rows would // drop what was typed. Blur first so they commit. const focused = document.activeElement; diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index 535a075202019..92a6b87f689bf 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -601,7 +601,7 @@ export function BranchToolbarBranchSelector({ : resolveDefaultWorktreeBaseBranch(refs); const projectCloneDone = useProjectClone(activeProjectRef)?.phase === "done"; - const refreshRefsAfterClone = useEffectEvent(() => { + const refreshStaleRefs = useEffectEvent(() => { if (branchCwd === null) return; void refreshLocalStatusForPicker({ environmentId, @@ -610,8 +610,18 @@ export function BranchToolbarBranchSelector({ }); // 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 useEffect(() => { - if (projectCloneDone) refreshRefsAfterClone(); + if (projectCloneDone) refreshStaleRefs(); }, [projectCloneDone]); + // 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 (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 + useEffect(() => { + refreshRefsMissingStatusBranch(statusBranch); + }, [statusBranch]); // The server sets started threads' branches; defaulting here would detach the agent from its worktree. const threadStarted = serverSession !== null; diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index 09caff1422072..a0458f9e80280 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -1,12 +1,19 @@ import { createMemoryHistory } from "@tanstack/react-router"; import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts"; +import { + EnvironmentId, + ORCHESTRATION_V2_WS_METHODS, + RunId, + ThreadId, + WS_METHODS, +} from "@t3tools/contracts"; import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; import { compileResolvedKeybindingsConfig, mergeWithDefaultKeybindings, } from "@t3tools/shared/keybindings"; import type * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; import { expect, it, vi } from "vite-plus/test"; import { cdp, page, userEvent } from "vite-plus/test/browser"; @@ -28,6 +35,7 @@ import { ENVIRONMENT_ID, PROJECT_ID, answerAssetUrls, + answerRpc, assistantItem, dispatchedCommands, emitThreadEvent, @@ -40,6 +48,52 @@ import { } from "../../test/fakeEnvironment"; import { act, fakeTimers, render } from "../../test/render"; +const PNG = Uint8Array.from( + atob( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=", + ), + (char) => char.charCodeAt(0), +); + +/** Accepts every attachment upload without sending its bytes, until disposed. */ +function acceptAttachmentUploads(): Disposable { + const mint = answerRpc(WS_METHODS.attachmentsCreateUploadUrl, () => + Effect.succeed({ attachmentId: "upload-1", relativeUrl: "/upload", expiresAt: 0 }), + ); + // Sending verifies each ready upload still exists on the server. + const verify = answerRpc(WS_METHODS.assetsCreateUrl, () => + Effect.succeed({ relativeUrl: "/upload-1", expiresAt: 0 }), + ); + const status = vi.spyOn(XMLHttpRequest.prototype, "status", "get").mockReturnValue(200); + const send = vi.spyOn(XMLHttpRequest.prototype, "send").mockImplementation(function ( + this: XMLHttpRequest, + ) { + queueMicrotask(() => this.dispatchEvent(new ProgressEvent("load"))); + }); + return { + [Symbol.dispose]: () => { + send.mockRestore(); + status.mockRestore(); + mint[Symbol.dispose](); + verify[Symbol.dispose](); + }, + }; +} + +/** Holds every call to `method` until `release`, then ends it with `end`, until disposed. */ +function holdRpc(method: string, end: Effect.Effect) { + let release = () => {}; + const held = new Promise((resolve) => { + release = resolve; + }); + const calls: Input[] = []; + const answer = answerRpc(method, (input: Input) => { + calls.push(input); + return Effect.promise(() => held).pipe(Effect.andThen(end)); + }); + return { calls, release, [Symbol.dispose]: () => answer[Symbol.dispose]() }; +} + // The socket is the only fake layer; see test/appScenarios.renders.tsx. vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => { const [actual, { fakeDriver }, Layer] = await Promise.all([ @@ -197,6 +251,51 @@ 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 () => { + using _environment = installFakeEnvironment([]); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const draftId = DraftId.make("draft-image-only-interrupted"); + useComposerDraftStore + .getState() + .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); + const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] })); + 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(editor).toBeVisible(); + // The send needs the project, which arrives with the shell snapshot. + 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 })); + await expect.element(page.getByRole("img", { name: "shot.png" })).toBeVisible(); + await userEvent.keyboard("{Enter}"); + await vi.waitFor(() => expect(launch.calls).toHaveLength(1)); + await userEvent.keyboard("next draft"); + await expect.element(editor).toHaveTextContent("next draft"); + launch.release(); + + await expect.element(page.getByText("Message may not have been 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("opens the thread actions menu for an older settled thread the shell leaves out", async () => { const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const }; using _environment = installFakeEnvironment([thread]); diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 6cf3ce762d434..54174262fd70f 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -1,4 +1,3 @@ -import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic"; import { boundAttachmentIds, buildExpiredTerminalContextToastCopy, @@ -1500,25 +1499,3 @@ describe("deriveThreadPendingBackgroundTasks", () => { ).toEqual([{ taskId: "task-1", kind: "background_task" }]); }); }); - -describe("Open in for the host environment", () => { - it("shows both local environments when the primary has a separate WSL home", () => { - const primaryEnvironmentId = EnvironmentId.make("wsl"); - const hostEnvironmentId = EnvironmentId.make("host"); - for (const [activeThreadEnvironmentId, visible] of [ - [primaryEnvironmentId, true], - [hostEnvironmentId, true], - [EnvironmentId.make("other"), false], - ] as const) { - expect( - shouldShowOpenInPicker({ - activeProjectName: "Project", - activeThreadEnvironmentId, - primaryEnvironmentId, - hostEnvironmentId, - remoteOpenMode: "local-exec", - }), - ).toBe(visible); - } - }); -}); diff --git a/apps/web/src/components/ChatView.modelPick.browser.test.tsx b/apps/web/src/components/ChatView.modelPick.browser.test.tsx index 384d83009d38f..c157e7972b14a 100644 --- a/apps/web/src/components/ChatView.modelPick.browser.test.tsx +++ b/apps/web/src/components/ChatView.modelPick.browser.test.tsx @@ -1,8 +1,9 @@ import { createMemoryHistory } from "@tanstack/react-router"; +import { ProviderInstanceId } from "@t3tools/contracts"; import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; import type * as Context from "effect/Context"; import { expect, it, vi } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import { AppRoot } from "~/AppRoot"; // The route loads ChatView lazily, and its first transform (React Compiler over ~4k lines) @@ -36,8 +37,17 @@ vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ // Its own file: the app's shell subscription outlives a test, and it must list this thread. it("a model picked for an existing thread reaches the server before any message is sent", async () => { - const thread = threadWithHistory("thread-model-pick", 1); - using _environment = installFakeEnvironment([thread], { acceptCommands: true }); + const stored = { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + options: [{ id: "reasoningEffort", value: "high" }], + }; + const thread = { ...threadWithHistory("thread-model-pick", 1), modelSelection: stored }; + const aliasThread = { + ...threadWithHistory("thread-model-alias", 1), + modelSelection: { ...stored, model: "gpt-5-codex" }, + }; + using _environment = installFakeEnvironment([thread, aliasThread], { acceptCommands: true }); __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, onboardingCompletedAt: "2026-01-01T00:00:00.000Z", @@ -52,16 +62,29 @@ it("a model picked for an existing thread reaches the server before any message }); await expect.element(page.getByText("Answer 0 for thread-model-pick.")).toBeVisible(); + const modelSets = () => + dispatchedCommands().filter((command) => command.type === "thread.model-selection.set"); + await page.getByRole("button", { name: "GPT-5.4", exact: true }).click(); await page.getByRole("option", { name: /GPT-5\.5/ }).click(); await vi.waitFor(() => - expect( - dispatchedCommands().filter((command) => command.type === "thread.model-selection.set"), - ).toEqual([ + expect(modelSets()).toEqual([ expect.objectContaining({ threadId: thread.id, - modelSelection: expect.objectContaining({ instanceId: "codex", model: "gpt-5.5" }), + modelSelection: { instanceId: "codex", model: "gpt-5.5" }, }), ]), ); + + // A thread stored under an alias keeps its options when its canonical model is picked. + await userEvent.keyboard("{Escape}"); + await router.navigate({ href: `/${ENVIRONMENT_ID}/${aliasThread.id}` }); + await expect.element(page.getByText("Answer 0 for thread-model-alias.")).toBeVisible(); + await page.getByRole("button", { name: "GPT-5.4", exact: true }).click(); + await page.getByRole("option", { name: /GPT-5\.4/ }).click(); + await vi.waitFor(() => + expect(modelSets().at(-1)).toEqual( + expect.objectContaining({ threadId: aliasThread.id, modelSelection: stored }), + ), + ); }); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 3887f7a56d18f..1ee270bd087cb 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -208,7 +208,11 @@ import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar"; import { toastManager } from "./ui/toast"; import { projectScriptIdFromCommand } from "~/projectScripts"; import { newMessageId } from "~/lib/utils"; -import { isInSideChatPane, type SideChatParentPanel } from "~/lib/sideChatPane"; +import { + isInSideChatPane, + resolveThreadOpenRoute, + type SideChatParentPanel, +} from "~/lib/sideChatPane"; import { NO_PROVIDER_MODEL_SELECTION, providerInstanceEntriesFor, @@ -928,7 +932,9 @@ export default function ChatView(props: ChatViewProps) { open: (): void => { void navigate({ to: "/$environmentId/$threadId", - params: buildThreadRouteParams(parentSubagentThreadRef), + params: buildThreadRouteParams( + resolveThreadOpenRoute(parentSubagentThreadRef, parentSubagentThread), + ), }); }, }; @@ -1385,10 +1391,6 @@ export default function ChatView(props: ChatViewProps) { pendingUserInputs, activePendingApproval, activePendingUserInput, - activePendingDraftAnswers, - activePendingQuestionIndex, - activePendingProgress, - activePendingResolvedAnswers, activePendingIsResponding, respondingRequestIds, onRespondToApproval: onRespondToApprovalStable, @@ -2976,7 +2978,7 @@ export default function ChatView(props: ChatViewProps) { readPendingEnvironmentChange, pendingApprovals, respondingRequestIds, - activePendingProgress, + activePendingUserInput, onAdvanceActivePendingUserInput, onRespondToApproval: onRespondToApprovalStable, beginLocalDispatch, @@ -3095,7 +3097,7 @@ export default function ChatView(props: ChatViewProps) { clientSettingsHydrated && !needsLoadBalancing && !activeEnvironmentUnavailable && - !activePendingProgress && + !activePendingUserInput && !feedbackUploading; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- switches the draft to local mode, then resends the waiting message once sending is idle useEffect(() => { @@ -3706,11 +3708,7 @@ export default function ChatView(props: ChatViewProps) { pendingApprovals={pendingApprovals} onHeldRequestIdsChange={onHeldRequestIdsChange} pendingUserInputs={pendingUserInputs} - activePendingProgress={activePendingProgress} - activePendingResolvedAnswers={activePendingResolvedAnswers} activePendingIsResponding={activePendingIsResponding} - activePendingDraftAnswers={activePendingDraftAnswers} - activePendingQuestionIndex={activePendingQuestionIndex} respondingRequestIds={respondingRequestIds} runtimeMode={runtimeMode} defaultRuntimeMode={defaultRuntimeMode} diff --git a/apps/web/src/components/CommandPalette.browser.test.tsx b/apps/web/src/components/CommandPalette.browser.test.tsx index 27341c2972495..eb071d2ffb68a 100644 --- a/apps/web/src/components/CommandPalette.browser.test.tsx +++ b/apps/web/src/components/CommandPalette.browser.test.tsx @@ -84,7 +84,9 @@ describe("CommandPalette open intents", () => { document.dispatchEvent(pointer("pointerup", 50, window.innerHeight - 30)); }); expect(onDrop).toHaveBeenCalledOnce(); - expect((onDrop.mock.calls[0]![0] as CustomEvent).detail).toEqual([{ environmentId, threadId }]); + expect((onDrop.mock.calls[0]![0] as CustomEvent).detail).toEqual([ + { environmentId, threadId, title: "Drag this thread" }, + ]); expect(screen.router?.state.location.pathname).toBe(pathname); }); diff --git a/apps/web/src/components/CommandPalette.drag.ts b/apps/web/src/components/CommandPalette.drag.ts index 3dec40e02b0f1..090bab6efbd02 100644 --- a/apps/web/src/components/CommandPalette.drag.ts +++ b/apps/web/src/components/CommandPalette.drag.ts @@ -22,7 +22,7 @@ export function startPaletteThreadDrag( distance: 6, onAttach: () => {}, onFinish: endThreadContextDrag, - onDrop: (point) => dropThreadContext(point, [thread]), + onDrop: (point) => dropThreadContext(point, [{ ...thread, title }]), }, onStart: () => { flushSync(() => dispatchCommandPalette({ _tag: "SetOpen", open: false })); diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index 604889da5bb68..e10bd823889cc 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -6,6 +6,7 @@ import { ProjectId, RunId, ThreadId, + TurnItemId, type ClientSettings, type ReviewBranchCommitsResult, type ReviewDiffPreviewResult, @@ -31,6 +32,11 @@ const state = vi.hoisted(() => ({ previews: new Map>(), patch: null as unknown as ResultAtom, diffFilesCollapsed: false, + project: { + workspaceRoot: "/project", + repositoryIdentity: null as { rootPath: string } | null, + }, + toolCallItem: null as unknown, config: null as unknown as Atom.Atom, status: null as unknown as ResultAtom, localRefs: null as unknown as ResultAtom, @@ -61,7 +67,7 @@ vi.mock("~/state/vcs", () => ({ })); vi.mock("~/state/entities", () => ({ useQuietThreadShell: () => state.thread, - useProject: () => ({ workspaceRoot: "/project", repositoryIdentity: null }), + useProject: () => state.project, useThreadCheckpointSummaries: () => state.checkpoints, useQuietThreadVisibleTurnItems: () => [], })); @@ -81,7 +87,11 @@ vi.mock("~/hooks/useTheme", () => ({ })); vi.mock("~/state/queries", () => ({ useCheckpointDiff: () => ({ data: state.checkpointDiff, error: null, isPending: false }), - useTurnItemDetail: () => ({ data: null, error: null, isPending: false }), + useTurnItemDetail: () => ({ + data: state.toolCallItem ? { item: state.toolCallItem } : null, + error: null, + isPending: false, + }), useDebouncedValue: (value: A) => value, })); vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => async () => {} })); @@ -131,6 +141,8 @@ function setup(failedBaseRef: string | null) { }; reset(); state.diffFilesCollapsed = false; + state.project = { workspaceRoot: "/project", repositoryIdentity: null }; + state.toolCallItem = null; state.checkpoints = []; state.checkpointDiff = null; const patch = Atom.make>( @@ -368,3 +380,38 @@ it.each([ .element(screen.getByRole("button", { name: `Collapse ${name}`, exact: true })) .toHaveAttribute("aria-expanded", "true"); }); + +it("opens a file from a tool call's diff by the path its agent recorded", async () => { + using context = setup("origin/orphan"); + // A local thread in a project that is the repository's apps/web folder. + state.thread = { ...state.thread!, worktreePath: null }; + state.project = { workspaceRoot: "/repo/apps/web", repositoryIdentity: { rootPath: "/repo" } }; + const status = AsyncResult.getOrThrow(context.registry.get(state.status)); + state.status = Atom.make( + AsyncResult.success({ ...status, workingTree: { ...status.workingTree, rootPath: "/repo" } }), + ); + // Claude's Edit can record a path relative to the workspace, unlike the repository's diffs. + state.toolCallItem = { + type: "file_change", + fileName: "src/a.ts", + diffStr: "--- src/a.ts\n+++ src/a.ts\n@@ -1 +1 @@\n-before\n+after\n", + }; + useDiffPanelStore.getState().selectToolCall(context.threadRef, { + threadId: context.threadRef.threadId, + itemId: TurnItemId.make("edit"), + revision: "1", + }); + await using screen = await render( + +
    + +
    +
    , + ); + await userEvent.click(screen.getByText("src/a.ts", { exact: true })); + await vi.waitFor(() => + expect( + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, context.threadRef), + ).toMatchObject({ activeSurfaceId: "file:src/a.ts" }), + ); +}); diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 4276a3020e6e6..38e3151eb7978 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -280,6 +280,9 @@ export default function DiffPanel({ selectThreadBranchBaseRef(state, routeThreadRef), ); const toolCallSelection = diffSelection.kind === "tool-call" ? diffSelection : null; + // Turn and git diffs name files from the repository root; a tool call's diff names them as + // its provider recorded them, absolute or relative to the workspace. + const diffPathRepositoryRoot = toolCallSelection ? undefined : activeRepositoryRoot; const isGitSelection = diffSelection.kind === "branch" || diffSelection.kind === "unstaged" || @@ -743,7 +746,7 @@ export default function DiffPanel({ threadRef: routeThreadRef, filePath, activeCwd, - repositoryRoot: activeRepositoryRoot, + repositoryRoot: diffPathRepositoryRoot, openInEditor: (targetPath) => { void (async () => { const result = await openInPreferredEditor(targetPath); @@ -1410,7 +1413,7 @@ export default function DiffPanel({ environmentId: activeThread?.environmentId ?? null, filePath, workspaceRoot: activeCwd, - repositoryRoot: activeRepositoryRoot, + repositoryRoot: diffPathRepositoryRoot, }, event, ); diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx index 752ecff286a33..739136162d31f 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx @@ -6,6 +6,7 @@ import { type FilesystemEntryMetadata, type ResolvedKeybindingsConfig, } from "@t3tools/contracts"; +import { Cause } from "effect"; import { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings"; import { Atom, AsyncResult } from "effect/reactivity"; import type { GhosttyTerminalSurfaceOptions } from "~/terminal/ghostty/surface"; @@ -28,17 +29,29 @@ const fixture = vi.hoisted(() => ({ _thread: ScopedThreadRef, _status: "closed" | "starting" | "running", _version: number, + _generation?: number, ) => {}, surfaceOptions: [] as GhosttyTerminalSurfaceOptions[], + reportedSize: null as { cols: number; rows: number } | null, + resizeCommand: {}, + runResize: (_input: unknown): Promise> => + Promise.resolve(AsyncResult.success(undefined)), metadata: new Map< string, Atom.Writable> >(), })); -// Every surface method is a no-op; `then` stays undefined so awaiting the surface resolves to it. +// Every other surface method is a no-op; `then` stays undefined so awaiting the surface resolves to it. const fakeSurface: object = new Proxy( - { input: document.createElement("textarea") }, + { + input: document.createElement("textarea"), + // The real surface re-reports its measured grid. + resendSize: () => { + const size = fixture.reportedSize; + if (size) fixture.surfaceOptions.at(-1)!.onResize(size.cols, size.rows); + }, + }, { get: (target, key) => key === "then" ? undefined : key in target ? Reflect.get(target, key) : () => undefined, @@ -76,11 +89,14 @@ vi.mock("../state/terminalSessions", async () => { fixture.resetSessions = () => { sessions = new Map(); }; - fixture.setSession = (thread, status, version) => { + fixture.setSession = (thread, status, version, generation) => { appAtomRegistry.set(session(thread.environmentId, thread.threadId), { ...EMPTY_TERMINAL_SESSION_STATE, status, version, + ...(generation === undefined + ? {} + : { output: { ...EMPTY_TERMINAL_SESSION_STATE.output, generation } }), }); }; return { @@ -93,12 +109,14 @@ vi.mock("../state/session", () => ({ readEnvironmentScope: () => true, })); vi.mock("../state/use-atom-command", () => ({ - useAtomCommand: () => async (args: { input: { threadId: string; data?: string } }) => { - if (args.input.data !== undefined) { - fixture.writes.push({ threadId: args.input.threadId, data: args.input.data }); - } - return { _tag: "Success" }; - }, + useAtomCommand: + (command: object) => async (args: { input: { threadId: string; data?: string } }) => { + if (command === fixture.resizeCommand) return fixture.runResize(args); + if (args.input.data !== undefined) { + fixture.writes.push({ threadId: args.input.threadId, data: args.input.data }); + } + return { _tag: "Success" }; + }, })); // The commands are replaced above; importing their runtime would connect a client. vi.mock("../state/server", async () => { @@ -106,7 +124,9 @@ vi.mock("../state/server", async () => { const config = Atom.make(null); return { serverEnvironment: { configValueAtom: () => config } }; }); -vi.mock("../state/terminal", () => ({ terminalEnvironment: { write: {}, resize: {} } })); +vi.mock("../state/terminal", () => ({ + terminalEnvironment: { write: {}, resize: fixture.resizeCommand }, +})); vi.mock("../state/preview", () => ({ previewEnvironment: { open: {} } })); vi.mock("../state/projects", async () => { const { Atom, AsyncResult } = await import("effect/reactivity"); @@ -190,6 +210,8 @@ function setup(originalStatus: "starting" | "exited" = "exited") { fixture.pressKey = null; fixture.writes = []; fixture.surfaceOptions = []; + fixture.reportedSize = null; + fixture.runResize = () => Promise.resolve(AsyncResult.success(undefined)); fixture.metadata.clear(); useRightPanelStore.setState(useRightPanelStore.getInitialState()); useTerminalUiStateStore.setState(useTerminalUiStateStore.getInitialState()); @@ -354,3 +376,39 @@ it("only activates terminal paths confirmed to exist on their environment", asyn await hover("~/notes.ts:5:2"); expect(canActivate("~/notes.ts:5:2")).toBe(true); }); + +it("resends a failed resize once in each writable session", async () => { + const { other: threadRef } = setup(); + const resizes: unknown[] = []; + const failure = AsyncResult.failure(Cause.die(new Error("resize rejected"))); + let failFirstResize = () => {}; + fixture.runResize = (input) => { + resizes.push(input); + if (resizes.length > 1) return Promise.resolve(failure); + return new Promise((resolve) => { + failFirstResize = () => resolve(failure); + }); + }; + await using _screen = await render( {}} />); + await act(async () => { + fixture.pendingSurfaces.shift()?.(); + }); + await act(async () => { + fixture.reportedSize = { cols: 57, rows: 41 }; + fixture.surfaceOptions.at(-1)!.onResize(57, 41); + }); + // The first request fails while the attachment reconnects, so its retry is not sent. + await act(async () => { + fixture.setSession(threadRef, "running", 0, 1); + failFirstResize(); + }); + expect(resizes).toHaveLength(1); + await act(async () => { + fixture.setSession(threadRef, "running", 1, 2); + }); + const resize = { + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId, terminalId: "term-1", cols: 57, rows: 41 }, + }; + expect(resizes).toEqual([resize, resize, resize]); +}); diff --git a/apps/web/src/components/ThreadTerminalDrawer.test.ts b/apps/web/src/components/ThreadTerminalDrawer.test.ts index 9f0204cd70c30..a88fa94521085 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.test.ts +++ b/apps/web/src/components/ThreadTerminalDrawer.test.ts @@ -98,4 +98,34 @@ it("reports an attach failure that leaves the output unchanged", () => { expect(terminal.getSelection).not.toHaveBeenCalled(); expect(terminal.getSelectionCellCount).not.toHaveBeenCalled(); expect(terminal.clearSelection).not.toHaveBeenCalled(); + + const snapshot = { + threadId: "thread", + terminalId: "term-1", + cwd: "/repo", + worktreePath: null, + status: "error" as const, + pid: null, + history: "", + exitCode: null, + exitSignal: null, + label: "Terminal", + updatedAt: "2026-11-15T00:00:00.000Z", + error: "Terminal attach failed", + }; + const attached = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), { + type: "snapshot", + snapshot, + }); + const cursor = synchronizeTerminalSession( + terminal, + failed, + attached, + INITIAL_TERMINAL_OUTPUT_CURSOR, + ); + terminal.write.mockClear(); + const reconnected = applyTerminalAttachStreamEvent(attached, { type: "snapshot", snapshot }); + synchronizeTerminalSession(terminal, attached, reconnected, cursor); + expect(terminal.resetAndWrite).toHaveBeenLastCalledWith(""); + expect(terminal.write).toHaveBeenCalledWith("\r\n[terminal] Terminal attach failed\r\n"); }); diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index d81de1ae38509..e5de4ea090b44 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -191,7 +191,7 @@ export function synchronizeTerminalOutput( return update.cursor; } -/** Writes what changed between two session notifications: new output, then a new error. */ +/** Writes what changed between two session notifications: new output, then the error, again after a reset. */ export function synchronizeTerminalSession( terminal: Parameters[0], previous: Pick, @@ -203,7 +203,12 @@ export function synchronizeTerminalSession( ? cursor : synchronizeTerminalOutput(terminal, session, cursor); // An attach failure can change only the error, keeping the last buffer. - if (session.error !== null && session.error !== previous.error) { + if ( + session.error !== null && + (session.error !== previous.error || + nextCursor.generation !== cursor.generation || + nextCursor.resetVersion !== cursor.resetVersion) + ) { writeSystemMessage(terminal, session.error); } return nextCursor; @@ -623,14 +628,22 @@ function TerminalSessionViewport({ input: { threadId, terminalId, data }, }), ); - const resizeTerminal = useEffectEvent((cols: number, rows: number) => { - if (writableSessionGeneration(readTerminalSession(), hasTerminalWriteAccess()) === null) { - return; - } - return runTerminalResize({ + // The surface reports a resent grid like any other, so the next report is the retry. + const resizeRetryGenerationRef = useRef(null); + const resizeTerminal = useEffectEvent(async (cols: number, rows: number) => { + const generation = writableSessionGeneration(readTerminalSession(), hasTerminalWriteAccess()); + const retry = generation !== null && generation === resizeRetryGenerationRef.current; + resizeRetryGenerationRef.current = null; + if (generation === null) return; + const result = await runTerminalResize({ environmentId, input: { threadId, terminalId, cols, rows }, }); + // Resend the current grid, not this one: a newer resize may already be queued behind it. + if (!retry && result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + resizeRetryGenerationRef.current = generation; + terminalRef.current?.resendSize(); + } }); const outputCursorRef = useRef(INITIAL_TERMINAL_OUTPUT_CURSOR); const synchronizedStatusRef = useRef("closed"); diff --git a/apps/web/src/components/chat/BackgroundWorkDetails.tsx b/apps/web/src/components/chat/BackgroundWorkDetails.tsx index 86df01be78f59..892e428359f59 100644 --- a/apps/web/src/components/chat/BackgroundWorkDetails.tsx +++ b/apps/web/src/components/chat/BackgroundWorkDetails.tsx @@ -83,7 +83,7 @@ export function BackgroundWorkDetails(props: { props.onOpenThread(childThreadId); }} > - Open thread + Open subagent ) : null} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index fed015b56db48..17f7a3283674e 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -191,6 +191,7 @@ import { import { rememberCopiedComposerAttachments } from "~/lib/copiedComposerAttachments"; import { hasExplicitComposerModelSelection } from "~/lib/chatThreadActions"; import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag"; +import { droppedThreadContextRecord } from "./threadContextDrop.logic"; import { readThreadShell } from "~/state/entities"; import { useLinkedEnvironments } from "~/state/peerLinks"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; @@ -251,7 +252,7 @@ import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelS import type { UnifiedSettings } from "@t3tools/contracts/settings"; import { isVideoAttachment, type SessionPhase, type Thread } from "../../types"; import { type ComposerPromptHistoryPosition } from "./composerPromptHistory"; -import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input"; +import { usePendingUserInputDraft } from "./usePendingThreadRequests"; import type { PendingApproval, PendingUserInput, TimelineEntry } from "../../session-logic"; import { resolveComposerDispatchMode, @@ -401,23 +402,7 @@ export interface ChatComposerProps { pendingApprovals: PendingApproval[]; onHeldRequestIdsChange: (requestIds: ReadonlySet) => void; pendingUserInputs: PendingUserInput[]; - activePendingProgress: { - questionIndex: number; - isLastQuestion: boolean; - canAdvance: boolean; - customAnswer: string; - activeQuestion: { - id: string; - options: ReadonlyArray; - initialAnswer?: string | undefined; - multiSelect?: boolean | undefined; - allowCustomAnswer?: boolean | undefined; - } | null; - } | null; - activePendingResolvedAnswers: Record | null; activePendingIsResponding: boolean; - activePendingDraftAnswers: Record; - activePendingQuestionIndex: number; respondingRequestIds: RuntimeRequestId[]; runtimeMode: RuntimeMode; @@ -535,11 +520,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) pendingApprovals, onHeldRequestIdsChange, pendingUserInputs: incomingPendingUserInputs, - activePendingProgress: incomingPendingProgress, - activePendingResolvedAnswers, activePendingIsResponding: incomingPendingIsResponding, - activePendingDraftAnswers, - activePendingQuestionIndex, respondingRequestIds, runtimeMode, lockedProvider, @@ -590,6 +571,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) editingQueuedAttachments, onRemoveEditingQueuedAttachment, } = props; + const { + activePendingProgress: incomingPendingProgress, + activePendingResolvedAnswers, + activePendingDraftAnswers, + activePendingQuestionIndex, + } = usePendingUserInputDraft({ + environmentId, + activeThreadId, + activePendingUserInput: incomingPendingUserInputs[0] ?? null, + supportsQuestionAttachments, + }); const primaryEnvironmentId = usePrimaryEnvironmentId(); const composerDraftTargetKey = composerTargetKey(composerDraftTarget); const { @@ -913,13 +905,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? providerInstanceEntries.find((entry) => hasProviderSetup(entry.snapshot))?.instanceId : undefined)) : undefined; + // Called before the derivation below: a hook between it and its uses stops React Compiler + // from caching the mode options, and the footer then re-renders on every keystroke. + const managedPolicy = useManagedPolicy(environmentId); const { modes: compatibleRuntimeModes, mode: compatibleRuntimeMode } = resolveCompatibleRuntimeMode( runtimeMode, selectedProviderEntry?.snapshot.supportedRuntimeModes, ); // Modes above an administrator's ceiling stay listed, disabled with the reason. - const managedPolicy = useManagedPolicy(environmentId); const compatibleRuntimeModeOptions = resolveRuntimeModeOptions( compatibleRuntimeModes, managedPolicy, @@ -2881,8 +2875,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ); return []; } - const shell = readThreadShell(ref); - return shell ? [threadContextRecord(ref, shell.title)] : []; + const record = droppedThreadContextRecord(ref, readThreadShell(ref)); + return record ? [record] : []; }); if (records.length === 0) return; if (questionAttachmentTarget !== null) { @@ -3693,12 +3687,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) /> {speechInput.preview ? ( + // column-reverse pins the scroll to the bottom; the single inner div keeps the text in normal order.
    - {speechInput.preview.committed} - {speechInput.preview.tentative} +
    + {speechInput.preview.committed} + {speechInput.preview.tentative} +
    ) : null} diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 1b5ab41725566..22e02b228a24d 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -21,6 +21,7 @@ import { } from "react"; import { isTrailingDoubleClick } from "../Sidebar.logic"; import { Badge } from "../ui/badge"; +import { MiddleTruncate } from "../ui/middle-truncate"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { toastManager } from "../ui/toast"; import { useThreadActionMenu } from "~/hooks/useThreadActionMenu"; @@ -273,9 +274,12 @@ export const ChatHeader = memo(function ChatHeader({ } > - - {activeProjectName} - + New thread in {activeProjectName} diff --git a/apps/web/src/components/chat/ComposerBanner.tsx b/apps/web/src/components/chat/ComposerBanner.tsx index 1ea9b8002b31f..a523c00378957 100644 --- a/apps/web/src/components/chat/ComposerBanner.tsx +++ b/apps/web/src/components/chat/ComposerBanner.tsx @@ -77,6 +77,8 @@ function Attachment({ className, ...props }: ComponentProps<"div">) { data-slot="composer-banner-attachment" className={cn( "mx-auto -mb-[calc(1rem+1px)] w-[calc(100%-2*var(--chat-composer-drawer-inset))]", + // Only the banner touching the composer gets the dark seam shade; stacked ones would band. + "[&:has(+[data-slot=composer-banner-attachment])]:[--chat-composer-attached-seam:transparent]", "[&+[data-slot=composer-banner-attachment]_[data-composer-banner-surface=attached]]:before:rounded-none [&+[data-slot=composer-banner-attachment]_[data-composer-banner-surface=attached]]:before:border-t-0 [&+[data-slot=composer-banner-attachment]_[data-composer-banner-surface=attached]]:[--composer-banner-corner-top:var(--control-radius)]", className, )} diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx index d4919fe4a2808..9abda3c246362 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx @@ -20,7 +20,7 @@ import { act, fakeTimers, render } from "../../../test/render"; import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { makeThreadProjectionFixture } from "../../test-fixtures"; import { toastManager } from "../ui/toast"; -import { usePendingThreadRequests } from "./usePendingThreadRequests"; +import { usePendingThreadRequests, usePendingUserInputDraft } from "./usePendingThreadRequests"; const threadRef = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") }; @@ -86,7 +86,7 @@ interface ProbeProps { function useProbeRequests({ environmentId, projection, loading = false, draftTarget }: ProbeProps) { const promptRef = useRef(""); const composerRef = useRef(null); - return usePendingThreadRequests({ + const requests = usePendingThreadRequests({ environmentId, activeThreadId: projection.thread.id, serverProjection: loading ? null : projection, @@ -98,9 +98,16 @@ function useProbeRequests({ environmentId, projection, loading = false, draftTar composerRef, setThreadError: () => {}, }); + const draft = usePendingUserInputDraft({ + environmentId, + activeThreadId: projection.thread.id, + activePendingUserInput: requests.activePendingUserInput, + supportsQuestionAttachments: false, + }); + return { ...requests, ...draft }; } -let requests: ReturnType; +let requests: ReturnType; function PendingRequestsProbe(props: ProbeProps) { const state = useProbeRequests(props); diff --git a/apps/web/src/components/chat/ComposerStashMenu.test.ts b/apps/web/src/components/chat/ComposerStashMenu.test.ts new file mode 100644 index 0000000000000..efabfc93c42dd --- /dev/null +++ b/apps/web/src/components/chat/ComposerStashMenu.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { stashEntrySnippet } from "./ComposerStashMenu"; + +const entry = (prompt: string) => ({ + id: "stash-1", + createdAt: "2026-10-01T00:00:00.000Z", + prompt, + attachments: [], + droppedImageNames: [], +}); + +describe("stashEntrySnippet", () => { + it("cuts a long prompt on a whole character", () => { + expect(stashEntrySnippet(entry(`${"a".repeat(89)}😀 and more`))).toBe(`${"a".repeat(89)}…`); + expect(stashEntrySnippet(entry(`${"a".repeat(88)}😀 and more`))).toBe(`${"a".repeat(88)}😀…`); + }); +}); diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index 938c42d32c8c9..15f19f0b3ed3f 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -13,10 +13,14 @@ function missingImageCount(entry: PromptStashEntry): number { return entry.droppedImageNames.length + (entry.unreadableImageNames?.length ?? 0); } -function stashEntrySnippet(entry: PromptStashEntry): string { +export function stashEntrySnippet(entry: PromptStashEntry): string { const trimmed = assistantCitationsToPlainText(entry.prompt).trim().replace(/\s+/g, " "); if (trimmed.length > 0) { - return trimmed.length > SNIPPET_MAX_CHARS ? `${trimmed.slice(0, SNIPPET_MAX_CHARS)}…` : trimmed; + if (trimmed.length <= SNIPPET_MAX_CHARS) return trimmed; + // Never end on a lone high surrogate, the first half of an emoji. + const last = trimmed.charCodeAt(SNIPPET_MAX_CHARS - 1); + const end = last >= 0xd800 && last <= 0xdbff ? SNIPPET_MAX_CHARS - 1 : SNIPPET_MAX_CHARS; + return `${trimmed.slice(0, end)}…`; } const imageCount = entry.attachments.length + entry.droppedImageNames.length; const fileCount = entry.files?.length ?? 0; diff --git a/apps/web/src/components/chat/MarkdownFileLink.logic.test.ts b/apps/web/src/components/chat/MarkdownFileLink.logic.test.ts new file mode 100644 index 0000000000000..9480916ca3e4d --- /dev/null +++ b/apps/web/src/components/chat/MarkdownFileLink.logic.test.ts @@ -0,0 +1,27 @@ +import { expect, it } from "vite-plus/test"; + +import { shouldUseMarkdownFileBrowserPrimaryAction } from "./MarkdownFileLink.logic"; + +it("opens PDFs in the file panel and uses the browser only when no other destination exists", () => { + expect( + shouldUseMarkdownFileBrowserPrimaryAction({ + canOpenInEditor: true, + canOpenInBrowser: true, + canOpenInPanel: true, + }), + ).toBe(false); + expect( + shouldUseMarkdownFileBrowserPrimaryAction({ + canOpenInEditor: false, + canOpenInBrowser: true, + canOpenInPanel: true, + }), + ).toBe(false); + expect( + shouldUseMarkdownFileBrowserPrimaryAction({ + canOpenInEditor: false, + canOpenInBrowser: true, + canOpenInPanel: false, + }), + ).toBe(true); +}); diff --git a/apps/web/src/components/chat/MarkdownFileLink.logic.ts b/apps/web/src/components/chat/MarkdownFileLink.logic.ts index d42ff1f9e8448..b850cbb3e7936 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.logic.ts +++ b/apps/web/src/components/chat/MarkdownFileLink.logic.ts @@ -1,10 +1,7 @@ import type { EnvironmentId } from "@t3tools/contracts"; import { splitFilePathPosition } from "@t3tools/shared/fileLinks"; -import { - shouldOpenMarkdownFileLinkInBrowserByDefault, - type MarkdownFileLinkMeta, -} from "../../markdown-links"; +import type { MarkdownFileLinkMeta } from "../../markdown-links"; import type { RemoteOpenMode } from "../../remoteOpen"; export function canUseMarkdownFileShellActions( @@ -49,14 +46,9 @@ export function markdownFileCopyMenuItems({ } export function shouldUseMarkdownFileBrowserPrimaryAction(input: { - iconPath: string; canOpenInEditor: boolean; canOpenInBrowser: boolean; canOpenInPanel: boolean; }): boolean { - return ( - input.canOpenInBrowser && - (shouldOpenMarkdownFileLinkInBrowserByDefault(input.iconPath) || - (!input.canOpenInEditor && !input.canOpenInPanel)) - ); + return input.canOpenInBrowser && !input.canOpenInEditor && !input.canOpenInPanel; } diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx index 79f75048fe538..5d0238fb1f3af 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.tsx +++ b/apps/web/src/components/chat/MarkdownFileLink.tsx @@ -7,6 +7,7 @@ import { } from "@t3tools/client-runtime/state/runtime"; import type { ContextMenuSource, EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; import { memo, useState, type MouseEvent as ReactMouseEvent } from "react"; +import { FolderIcon } from "lucide-react"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { readLocalApi } from "../../localApi"; @@ -24,7 +25,7 @@ import { shouldUseMarkdownFileBrowserPrimaryAction, } from "./MarkdownFileLink.logic"; import { reportMarkdownActionFailure } from "./markdownActionFailure"; -import { WorkspaceEntryIcon, WorkspaceEntryTooltip } from "./WorkspaceEntryIcon"; +import { WorkspaceEntryTooltip } from "./WorkspaceEntryIcon"; interface MarkdownFileLinkProps { environmentId: EnvironmentId | null; @@ -315,7 +316,6 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ canOpenMedia: onOpenMedia !== undefined, }); const useBrowserPrimaryAction = shouldUseMarkdownFileBrowserPrimaryAction({ - iconPath, canOpenInEditor, canOpenInBrowser, canOpenInPanel, @@ -351,7 +351,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ + ) : undefined } path={iconPath} @@ -375,7 +375,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ + ) : undefined } path={iconPath} @@ -422,25 +422,31 @@ function areMarkdownFileLinkPropsEqual( ); } -function AppBundleIcon(props: { - environmentId: EnvironmentId | null; - path: string; - theme: "light" | "dark"; -}) { +function AppBundleIcon(props: { environmentId: EnvironmentId | null; path: string }) { const asset = useAssetUrlState(props.environmentId, { _tag: "native-app-icon", app: { _tag: "app-path", path: props.path }, }); const [failedUrl, setFailedUrl] = useState(null); - if (asset._tag !== "Success" || asset.url === failedUrl) { - return ; - } + const [loadedUrl, setLoadedUrl] = useState(null); + const url = asset._tag === "Success" && asset.url !== failedUrl ? asset.url : null; + const loaded = url !== null && loadedUrl === url; return ( - setFailedUrl(asset.url)} - /> + ); } diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 6c209d78d6ba3..1cd8066dbcd32 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -32,6 +32,7 @@ import { timelineTurnFoldRunIdsByEntryId, liveAnswerPreview, deriveMessagesTimelineRowsWithState, + isTimelineMinimapTurnVisible, resolveAssistantMessageCopyState, type MessagesTimelineRow, workEntryDisplayLabel, @@ -5146,3 +5147,14 @@ describe("subagent continued by a later turn", () => { ]); }); }); + +describe("isTimelineMinimapTurnVisible", () => { + it("keeps a turn lit while only its reply is on screen", () => { + // Turn rows 10..499, viewport inside the reply. + expect(isTimelineMinimapTurnVisible(10, 500, 200, 210)).toBe(true); + expect(isTimelineMinimapTurnVisible(500, undefined, 600, 610)).toBe(true); + expect(isTimelineMinimapTurnVisible(500, undefined, 200, 210)).toBe(false); + expect(isTimelineMinimapTurnVisible(10, 500, 500, 510)).toBe(false); + expect(isTimelineMinimapTurnVisible(10, 500, null, null)).toBe(false); + }); +}); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 9208e409ba205..5c4f99d76dc44 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -401,13 +401,18 @@ export function resolveTimelineMinimapVisibleRange(state: { return { start, end }; } -export function isTimelineMinimapRowVisible( - rowIndex: number, +/** A turn spans its user message up to the next one, so a long reply keeps its strip lit. */ +export function isTimelineMinimapTurnVisible( + turnStartRowIndex: number, + nextTurnStartRowIndex: number | undefined, visibleStart: number | null | undefined, visibleEnd: number | null | undefined, ): boolean { return ( - visibleStart != null && visibleEnd != null && rowIndex >= visibleStart && rowIndex <= visibleEnd + visibleStart != null && + visibleEnd != null && + turnStartRowIndex <= visibleEnd && + (nextTurnStartRowIndex === undefined || nextTurnStartRowIndex > visibleStart) ); } diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 9fcdaaf669754..b9653da6b315b 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -81,7 +81,7 @@ import { resolveTimelineIsAtEnd, resolveTimelineMinimapHasPersistentGutter, resolveTimelineMinimapCurrentIndex, - isTimelineMinimapRowVisible, + isTimelineMinimapTurnVisible, resolveTimelineMinimapVisibleRange, resolveTimelineMinimapHitStripWidth, TIMELINE_MINIMAP_TARGET_OFFSET, @@ -934,10 +934,11 @@ const ConversationTimeline = memo(function ConversationTimeline({ firstBufferedRow.getBoundingClientRect().top : state.scroll; const visibleRange = resolveTimelineMinimapVisibleRange({ ...state, scroll }); - for (const item of minimapItems) { + for (const [index, item] of minimapItems.entries()) { const strip = minimapStripMap.get(item.id); - const inView = isTimelineMinimapRowVisible( + const inView = isTimelineMinimapTurnVisible( item.rowIndex, + minimapItems[index + 1]?.rowIndex, visibleRange.start, visibleRange.end, ); diff --git a/apps/web/src/components/chat/ThreadActivityBanners.tsx b/apps/web/src/components/chat/ThreadActivityBanners.tsx index ff4ee1ef7078e..308be5a138ec3 100644 --- a/apps/web/src/components/chat/ThreadActivityBanners.tsx +++ b/apps/web/src/components/chat/ThreadActivityBanners.tsx @@ -212,7 +212,6 @@ export function backgroundWorkNowItem(input: { activity: subagent?.progress?.replace(/\s+/gu, " ").trim() || null, startedAtMs: item?.startedAt ? DateTime.toEpochMillis(item.startedAt) : null, updatedAtMs: subagent ? DateTime.toEpochMillis(subagent.updatedAt) : 0, - childThreadId: task.childThreadId ?? subagent?.childThreadId ?? undefined, }; }); const [only] = rows.length === 1 ? rows : []; @@ -220,7 +219,6 @@ export function backgroundWorkNowItem(input: { .filter((row) => row.activity) .toSorted((left, right) => right.updatedAtMs - left.updatedAtMs)[0]; const isCommand = (row: (typeof rows)[number]) => row.task.kind !== "subagent"; - const onlyThreadId = only?.childThreadId; const startedAtMs = only?.startedAtMs ?? null; return { id: `background-work:${input.threadId}`, @@ -265,11 +263,6 @@ export function backgroundWorkNowItem(input: { turnItems={input.turnItems} onOpenThread={onOpenThread} /> - {onlyThreadId === undefined ? null : ( - onOpenThread(onlyThreadId)}> - Open - - )} void input.onStop()}> {input.stopping ? "Stopping..." : "Stop"} diff --git a/apps/web/src/components/chat/ThreadDetailsControl.tsx b/apps/web/src/components/chat/ThreadDetailsControl.tsx index 5a6c09853a514..78f22ea5bec98 100644 --- a/apps/web/src/components/chat/ThreadDetailsControl.tsx +++ b/apps/web/src/components/chat/ThreadDetailsControl.tsx @@ -59,16 +59,14 @@ export function ThreadDetailsControl({ multiline && "h-auto min-h-8 py-1.5 disabled:opacity-100 sm:h-auto", tone === "muted" && "text-muted-foreground hover:text-foreground/80", tone === "primary" && - // The row surface forces a faint hover fill with !important; the solid pill keeps its own. - "bg-primary text-primary-foreground hover:text-primary-foreground hover:!bg-primary/85 data-pressed:!bg-primary/85 dark:hover:!bg-primary/85 dark:data-pressed:!bg-primary/85", + // The row surface forces a faint hover fill with !important; the pill keeps its own. + "bg-black/[0.035] text-foreground/80 hover:text-foreground hover:!bg-black/[0.06] data-pressed:!bg-black/[0.06] dark:bg-white/[0.08] dark:hover:!bg-white/[0.12] dark:data-pressed:!bg-white/[0.12]", tone === "destructive" && "text-destructive hover:text-destructive data-pressed:text-destructive", - // PR row actions share one 20px pill with a 1px inset focus ring that stays clear of the - // label. The solid pill draws it in the canvas color so it shows against the fill. + // Keep the inset focus ring clear of the 20px PR action label. part === "meta" && (tone === "primary" || tone === "destructive") && "h-5 focus-visible:ring-1 focus-visible:ring-offset-0", - part === "meta" && tone === "primary" && "focus-visible:ring-background", part === "meta" && tone === "destructive" && "bg-destructive/10 hover:!bg-destructive/16 data-pressed:!bg-destructive/16 dark:hover:!bg-destructive/16 dark:data-pressed:!bg-destructive/16", diff --git a/apps/web/src/components/chat/ThreadRelationshipIcon.tsx b/apps/web/src/components/chat/ThreadRelationshipIcon.tsx index c007ac03c2c44..e97915914b6c3 100644 --- a/apps/web/src/components/chat/ThreadRelationshipIcon.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipIcon.tsx @@ -1,7 +1,11 @@ import type { ProviderDriverKind, ServerProvider } from "@t3tools/contracts"; import { BotIcon, type LucideIcon } from "lucide-react"; import { cn } from "../../lib/utils"; -import { shouldShowInstanceBadge, type ProviderInstanceEntry } from "../../providerInstances"; +import { + hasInstanceBadge, + shouldShowInstanceBadge, + type ProviderInstanceEntry, +} from "../../providerInstances"; import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; export function threadRelationshipStatusLabel(status: string | null): string { @@ -47,12 +51,15 @@ export function ThreadRelationshipIcon({ driver, provider, providerEntries = [], + anyInstanceBadge = hasInstanceBadge(providerEntries), status, fallbackIcon: FallbackIcon = BotIcon, }: { driver?: ProviderDriverKind | undefined; provider?: ServerProvider | undefined; providerEntries?: ReadonlyArray; + /** For rows that can't take `providerEntries` but sit in the same list as rows that do. */ + anyInstanceBadge?: boolean; status: string | null; fallbackIcon?: LucideIcon; }) { @@ -80,8 +87,8 @@ export function ThreadRelationshipIcon({ )} ( function RemoteSubagentRow(props: { readonly agent: RemoteSubagent; readonly provider: ServerProvider | undefined; + readonly anyInstanceBadge: boolean; }) { const navigate = useNavigate(); const environment = useEnvironment(props.agent.remoteChild.environmentId); @@ -300,6 +302,7 @@ function RemoteSubagentRow(props: { // The task's own driver here is only a "remote" label. driver={props.provider?.driver} provider={props.provider} + anyInstanceBadge={props.anyInstanceBadge} fallbackIcon={BotIcon} status={status} /> @@ -337,6 +340,7 @@ function RemoteSubagentRow(props: { function DelegatedFromRow(props: { readonly delegatedFrom: OrchestrationV2DelegatedFrom; readonly fallbackLabel: string | undefined; + readonly anyInstanceBadge: boolean; }) { const navigate = useNavigate(); const router = useRouter(); @@ -394,7 +398,11 @@ function DelegatedFromRow(props: { /> } > - + {title} @@ -630,10 +638,14 @@ export function ThreadRelationshipsPanel(props: { // Idle children can be omitted from the shell; opening one loads its own detail. const openThread = (threadId: ThreadId) => { - if (openSideChatTab(ref, graph.nodes.get(threadId)?.thread ?? null)) return; + const routeRef = resolveThreadOpenRoute( + scopeThreadRef(props.environmentId, threadId), + graph.nodes.get(threadId)?.thread ?? null, + ); + if (routeRef.threadId === ref.threadId) return; void navigate({ to: "/$environmentId/$threadId", - params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)), + params: buildThreadRouteParams(routeRef), }); }; @@ -1014,6 +1026,7 @@ export function ThreadRelationshipsPanel(props: { )} @@ -1029,6 +1042,7 @@ export function ThreadRelationshipsPanel(props: { provider={providersByEnvironment .get(row.remote.remoteChild.environmentId) ?.find((entry) => entry.instanceId === row.remote.providerInstanceId)} + anyInstanceBadge={hasInstanceBadge(providerEntries)} /> ) : ( renderRelationshipRow(row) diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index 1854bc74181d0..920586f6d1dbb 100644 --- a/apps/web/src/components/chat/V2LifecycleRow.tsx +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -56,6 +56,7 @@ import { applyProviderInstanceSettings, brandProviderInstanceEntries, deriveProviderInstanceEntries, + hasInstanceBadge, shouldShowInstanceBadge, type ProviderInstanceEntry, } from "../../providerInstances"; @@ -210,6 +211,7 @@ function SubagentAvatar({ iconUrl, accentColor, showBadge, + anyInstanceBadge, status, className, }: { @@ -218,6 +220,7 @@ function SubagentAvatar({ iconUrl?: string | undefined; accentColor?: string | undefined; showBadge: boolean; + anyInstanceBadge: boolean; status?: OrchestrationV2TurnItem["status"] | undefined; className?: string; }) { @@ -246,8 +249,8 @@ function SubagentAvatar({ {status ? ( @@ -298,6 +301,9 @@ export function EnvironmentSubagentAvatar({ const entry = all.find((candidate) => candidate.instanceId === providerInstanceId); return entry !== undefined && shouldShowInstanceBadge(entry, all); }); + const anyInstanceBadge = useAtomValue(providersAtom, (providers) => + hasInstanceBadge(entries(providers)), + ); const iconUrl = useAtomValue( providersAtom, (providers) => @@ -311,6 +317,7 @@ export function EnvironmentSubagentAvatar({ iconUrl={iconUrl} accentColor={accentColor} showBadge={showBadge} + anyInstanceBadge={anyInstanceBadge} /> ); } diff --git a/apps/web/src/components/chat/chatViewSend.ts b/apps/web/src/components/chat/chatViewSend.ts index c5c65e7d6e783..58f12549d15f3 100644 --- a/apps/web/src/components/chat/chatViewSend.ts +++ b/apps/web/src/components/chat/chatViewSend.ts @@ -16,7 +16,10 @@ import { type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; import { readLocalApi } from "../../localApi"; -import { awaitAttachmentUploads, getUploadedAttachments } from "../../lib/attachmentUploadQueue"; +import { + getUploadedAttachments, + refreshExpiredAttachmentUploads, +} from "../../lib/attachmentUploadQueue"; import { findRevertCheckpoint } from "../../session-logic"; import { type ChatMessage } from "../../types"; import { randomUUID } from "~/lib/utils"; @@ -25,6 +28,7 @@ import { newThreadId } from "~/lib/utils"; import { type ComposerFileAttachment, type ComposerImageAttachment, + type ComposerThreadTarget, useComposerDraftStore, DraftId, } from "../../composerDraftStore"; @@ -328,12 +332,17 @@ export function prepareTurnAttachments(input: { readonly environmentId: EnvironmentId; readonly attachments: ReadonlyArray; readonly usesAttachmentUploads: boolean; + readonly draftTarget: ComposerThreadTarget; }) { - const { environmentId, usesAttachmentUploads } = input; + const { environmentId, usesAttachmentUploads, draftTarget } = input; return Promise.all( input.attachments.map(async (attachment) => { if (usesAttachmentUploads) { - await awaitAttachmentUploads([attachment.id]); + await refreshExpiredAttachmentUploads({ + environmentId, + images: [attachment], + draftTarget, + }); const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0]; if (!uploaded) { throw new Error(`Attachment '${attachment.name}' failed to upload.`); diff --git a/apps/web/src/components/chat/composerImagePersistence.test.ts b/apps/web/src/components/chat/composerImagePersistence.test.ts index 5d8a210977bfd..0d95a007b67ec 100644 --- a/apps/web/src/components/chat/composerImagePersistence.test.ts +++ b/apps/web/src/components/chat/composerImagePersistence.test.ts @@ -77,6 +77,22 @@ describe("serializeComposerImages", () => { expect(readFileAsDataUrl).not.toHaveBeenCalled(); }); + it("keeps composer order when a later image finishes reading first", async () => { + const large = image("large"); + const small = image("small"); + let finishLargeRead = (_dataUrl: string) => {}; + const largeRead = new Promise((resolve) => { + finishLargeRead = resolve; + }); + vi.mocked(readFileAsDataUrl).mockImplementation(async (file) => + file === large.file ? largeRead : "data:image/png;base64,c21hbGw=", + ); + + const serialized = serializeComposerImages([large, small], []); + finishLargeRead("data:image/png;base64,bGFyZ2U="); + expect((await serialized).map(({ id }) => id)).toEqual(["large", "small"]); + }); + it("omits failed uncached reads while keeping successfully serialized images", async () => { const a = image("a"); const b = image("b"); diff --git a/apps/web/src/components/chat/composerImagePersistence.ts b/apps/web/src/components/chat/composerImagePersistence.ts index ad189b5224c99..4f99ddc1b8b48 100644 --- a/apps/web/src/components/chat/composerImagePersistence.ts +++ b/apps/web/src/components/chat/composerImagePersistence.ts @@ -11,27 +11,23 @@ export async function serializeComposerImages( const existingPersistedById = new Map( persistedAttachments.map((attachment) => [attachment.id, attachment]), ); - const stagedAttachmentById = new Map(); - await Promise.all( + const staged = await Promise.all( images.map(async (image) => { try { const dataUrl = existingPersistedById.get(image.id)?.dataUrl ?? (await readFileAsDataUrl(image.file)); - stagedAttachmentById.set(image.id, { + return { id: image.id, name: image.name, mimeType: image.mimeType, sizeBytes: image.sizeBytes, dataUrl, ...(image.source ? { source: image.source } : {}), - }); + }; } catch { - const existingPersisted = existingPersistedById.get(image.id); - if (existingPersisted) { - stagedAttachmentById.set(image.id, existingPersisted); - } + return existingPersistedById.get(image.id); } }), ); - return Array.from(stagedAttachmentById.values()); + return staged.filter((attachment) => attachment !== undefined); } diff --git a/apps/web/src/components/chat/composerSend.logic.test.ts b/apps/web/src/components/chat/composerSend.logic.test.ts index 13e36ea5659c9..dea00844d6a50 100644 --- a/apps/web/src/components/chat/composerSend.logic.test.ts +++ b/apps/web/src/components/chat/composerSend.logic.test.ts @@ -1,11 +1,13 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { describe, expect, it } from "vite-plus/test"; +import type { ComposerThreadDraftState } from "../../composerDraftStore"; import { formatInlineContextReference } from "../../lib/composerContextReferences"; import { threadContextReference } from "../../lib/composerContextRecords"; import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { approvalRedirectNotice, + composerDraftContentChanged, loadBalancingSendWarning, multipleModelSendBlock, referencedThreadContexts, @@ -16,6 +18,46 @@ const remote = EnvironmentId.make("remote"); const localThread = threadContextRecord(scopeThreadRef(local, ThreadId.make("a")), "Local"); const remoteThread = threadContextRecord(scopeThreadRef(remote, ThreadId.make("b")), "Remote"); +it("detects draft edits during upload preparation without treating upload metadata as an edit", () => { + const draft: ComposerThreadDraftState = { + prompt: "before", + images: [], + files: [ + { + type: "file", + id: "file", + name: "a.pdf", + mimeType: "application/pdf", + sizeBytes: 1, + file: null, + }, + ], + nonPersistedImageIds: [], + persistedAttachments: [], + terminalContexts: [], + previewAnnotations: [], + reviewComments: [], + threadContexts: [], + environmentContexts: [], + replyTo: null, + modelSelectionByProvider: {}, + activeProvider: null, + runtimeMode: null, + interactionMode: null, + }; + expect( + composerDraftContentChanged(draft, { + ...draft, + files: [{ ...draft.files[0]!, uploadedAttachmentId: "upload", uploadEnvironmentId: local }], + }), + ).toBe(false); + expect(composerDraftContentChanged(draft, { ...draft, prompt: "after" })).toBe(true); + expect(composerDraftContentChanged(draft, { ...draft, files: [] })).toBe(true); + expect(composerDraftContentChanged(draft, { ...draft, threadContexts: [localThread] })).toBe( + true, + ); +}); + describe("referencedThreadContexts", () => { it("keeps only the attached threads the prompt still links", () => { const prompt = `see ${formatInlineContextReference(threadContextReference(remoteThread))}`; diff --git a/apps/web/src/components/chat/composerSend.logic.ts b/apps/web/src/components/chat/composerSend.logic.ts index e19512e6c90d4..5b7a5ac3a09c7 100644 --- a/apps/web/src/components/chat/composerSend.logic.ts +++ b/apps/web/src/components/chat/composerSend.logic.ts @@ -1,5 +1,28 @@ import type { EnvironmentId, ThreadContextRecord } from "@t3tools/contracts"; import { collectInlineContextIds } from "../../lib/composerContextReferences"; +import type { ComposerThreadDraftState } from "../../composerDraftStore"; + +/** Compare immutable user content without copying image bytes or upload metadata. */ +export function composerDraftContentChanged( + before: ComposerThreadDraftState | null, + after: ComposerThreadDraftState | null, +): boolean { + if (before === after) return false; + if (!before || !after) return true; + const sameIds = (left: ReadonlyArray<{ id: string }>, right: ReadonlyArray<{ id: string }>) => + left.length === right.length && left.every((item, index) => item.id === right[index]?.id); + return ( + before.prompt !== after.prompt || + !sameIds(before.images, after.images) || + !sameIds(before.files, after.files) || + before.terminalContexts !== after.terminalContexts || + before.previewAnnotations !== after.previewAnnotations || + before.reviewComments !== after.reviewComments || + before.threadContexts !== after.threadContexts || + before.environmentContexts !== after.environmentContexts || + before.replyTo !== after.replyTo + ); +} /** Attached threads the prompt still links to; replacing linked text leaves stale records. */ export function referencedThreadContexts(draft: { diff --git a/apps/web/src/components/chat/threadContextDrag.ts b/apps/web/src/components/chat/threadContextDrag.ts index 66e89060c231b..8c16191657e4c 100644 --- a/apps/web/src/components/chat/threadContextDrag.ts +++ b/apps/web/src/components/chat/threadContextDrag.ts @@ -1,13 +1,15 @@ -import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; +import type { EnvironmentId } from "@t3tools/contracts"; import { type RefObject, useEffect, useEffectEvent, useSyncExternalStore } from "react"; +import type { ThreadContextDropRef } from "./threadContextDrop.logic"; + export const THREAD_CONTEXT_DROP_EVENT = "t3-thread-context-drop"; export function useThreadContextDrop( targetRef: RefObject, environmentId: EnvironmentId, targetKey: string, - onDrop: (refs: ReadonlyArray, isActive: () => boolean) => void, + onDrop: (refs: ReadonlyArray, isActive: () => boolean) => void, ) { const handleDrop = useEffectEvent(onDrop); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes the target element to thread-context drop events and marks old drops inactive @@ -16,7 +18,7 @@ export function useThreadContextDrop( if (!target) return; let active = true; const listener = (event: Event) => - handleDrop((event as CustomEvent>).detail, () => active); + handleDrop((event as CustomEvent>).detail, () => active); target.addEventListener(THREAD_CONTEXT_DROP_EVENT, listener); return () => { active = false; @@ -91,7 +93,7 @@ export function endThreadContextDrag() { export function dropThreadContext( point: { x: number; y: number }, - threads: ReadonlyArray, + threads: ReadonlyArray, ): boolean { const target = findDropTarget(point); if (!target || threads.length === 0) return false; diff --git a/apps/web/src/components/chat/threadContextDrop.logic.test.ts b/apps/web/src/components/chat/threadContextDrop.logic.test.ts new file mode 100644 index 0000000000000..8d37a0e86de67 --- /dev/null +++ b/apps/web/src/components/chat/threadContextDrop.logic.test.ts @@ -0,0 +1,29 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; +import { describe, expect, it } from "vite-plus/test"; +import { droppedThreadContextRecord } from "./threadContextDrop.logic"; + +describe("droppedThreadContextRecord", () => { + it.each([null, { title: "Cached title" }])( + "uses the search result title even when the sidebar shell is %s", + (shell) => { + const ref = { + environmentId: EnvironmentId.make("remote"), + threadId: ThreadId.make("search-result"), + title: "Search result", + }; + expect(droppedThreadContextRecord(ref, shell)).toEqual(threadContextRecord(ref, ref.title)); + }, + ); + + it("uses the sidebar title for a drag without search metadata", () => { + const ref = { + environmentId: EnvironmentId.make("local"), + threadId: ThreadId.make("sidebar-thread"), + }; + expect(droppedThreadContextRecord(ref, { title: "Sidebar thread" })).toEqual( + threadContextRecord(ref, "Sidebar thread"), + ); + expect(droppedThreadContextRecord(ref, null)).toBeNull(); + }); +}); diff --git a/apps/web/src/components/chat/threadContextDrop.logic.ts b/apps/web/src/components/chat/threadContextDrop.logic.ts new file mode 100644 index 0000000000000..ee875c2e5ccaf --- /dev/null +++ b/apps/web/src/components/chat/threadContextDrop.logic.ts @@ -0,0 +1,12 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; + +export type ThreadContextDropRef = ScopedThreadRef & { readonly title?: string }; + +export function droppedThreadContextRecord( + ref: ThreadContextDropRef, + shell: { readonly title: string } | null, +) { + const title = ref.title ?? shell?.title; + return title === undefined ? null : threadContextRecord(ref, title); +} diff --git a/apps/web/src/components/chat/useComposerAttachmentIntake.ts b/apps/web/src/components/chat/useComposerAttachmentIntake.ts index 17be926907bc0..9bd8d1293e617 100644 --- a/apps/web/src/components/chat/useComposerAttachmentIntake.ts +++ b/apps/web/src/components/chat/useComposerAttachmentIntake.ts @@ -18,6 +18,7 @@ import { composerFileNeedsReattach, } from "../../composerDraftStore"; import { type ComposerPromptEditorHandle } from "../ComposerPromptEditorTiptap"; +import type { PendingUserInputProgress } from "../../pendingUserInput"; import type { ComposerAttachmentInsertion } from "../composerAttachmentInsertion"; import { type PendingUserInput } from "../../session-logic"; import { @@ -62,7 +63,7 @@ import { */ export function useComposerAttachmentIntake(input: { readonly activeThreadId: ChatComposerProps["activeThreadId"]; - readonly activePendingProgress: ChatComposerProps["activePendingProgress"]; + readonly activePendingProgress: PendingUserInputProgress | null; readonly activePendingIsResponding: boolean; readonly pendingUserInputs: ReadonlyArray; readonly supportsQuestionAttachments: boolean; diff --git a/apps/web/src/components/chat/useComposerSelection.ts b/apps/web/src/components/chat/useComposerSelection.ts index 6641bf0903ff0..01562f0cf536d 100644 --- a/apps/web/src/components/chat/useComposerSelection.ts +++ b/apps/web/src/components/chat/useComposerSelection.ts @@ -23,7 +23,11 @@ import { resolveNewDraftStartFromOrigin, threadHasStarted, } from "../../lib/chatThreadActions"; -import { type DraftThreadEnvMode, useComposerDraftStore } from "../../composerDraftStore"; +import { + type DraftThreadEnvMode, + isSameModel, + useComposerDraftStore, +} from "../../composerDraftStore"; import { getStartedThreadModelChangeBlockReason, deriveLockedProvider, @@ -188,9 +192,23 @@ export function useComposerSelection(input: ComposerSelectionInput) { } const rememberedOptions = useComposerDraftStore.getState().stickyOptionsByModelByProvider[instanceId]?.[resolvedModel]; - const nextModelSelection: ModelSelection = + const threadSelection = activeThread.modelSelection; + // This pick replaces the stored options, so the thread's own model carries them over. + const pickOptions = rememberedOptions !== undefined && rememberedOptions.length > 0 - ? { instanceId, model: resolvedModel, options: [...rememberedOptions] } + ? rememberedOptions + : threadSelection.instanceId === instanceId && + entry !== undefined && + isSameModel( + { providers: providerStatuses, selectedProvider: entry.driver, settings }, + threadSelection, + { instanceId, model: resolvedModel }, + ) + ? threadSelection.options + : undefined; + const nextModelSelection: ModelSelection = + pickOptions !== undefined && pickOptions.length > 0 + ? { instanceId, model: resolvedModel, options: [...pickOptions] } : { instanceId, model: resolvedModel }; const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({ hasStartedSession: activeRuntime !== null, diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index b479d0022c041..3a045e22f8ee2 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -99,6 +99,7 @@ import { useStableCallback } from "../../hooks/useStableCallback"; import { environmentPresentations } from "../../state/presentation"; import { approvalRedirectNotice, + composerDraftContentChanged, loadBalancingSendWarning, multipleModelSendBlock, referencedThreadContexts, @@ -106,8 +107,8 @@ import { import { useMultipleModelSend } from "./useMultipleModelSend"; import { type ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; import { - awaitAttachmentUploads, getUploadedAttachments, + refreshExpiredAttachmentUploads, readAttachmentUpload, releaseDraftAttachments, retryAttachmentUpload, @@ -220,7 +221,7 @@ interface ComposerSendInput { readonly readPendingEnvironmentChange: DraftEnvironmentRouting["readPendingEnvironmentChange"]; readonly pendingApprovals: PendingThreadRequests["pendingApprovals"]; readonly respondingRequestIds: PendingThreadRequests["respondingRequestIds"]; - readonly activePendingProgress: PendingThreadRequests["activePendingProgress"]; + readonly activePendingUserInput: PendingThreadRequests["activePendingUserInput"]; readonly onAdvanceActivePendingUserInput: PendingThreadRequests["onAdvanceActivePendingUserInput"]; readonly onRespondToApproval: PendingThreadRequests["onRespondToApproval"]; readonly beginLocalDispatch: LocalDispatchState["beginLocalDispatch"]; @@ -316,7 +317,7 @@ export function useComposerSend(input: ComposerSendInput) { readPendingEnvironmentChange, pendingApprovals, respondingRequestIds, - activePendingProgress, + activePendingUserInput, onAdvanceActivePendingUserInput, onRespondToApproval: onRespondToApprovalStable, beginLocalDispatch, @@ -410,7 +411,7 @@ export function useComposerSend(input: ComposerSendInput) { ? parseSideChatCommand(promptAtSend) : null; const answeringQuestion = - Boolean(activePendingProgress) && sendCtx?.answeringPendingUserInput !== false; + Boolean(activePendingUserInput) && sendCtx?.answeringPendingUserInput !== false; const startsSideChat = onSideChat !== undefined && sideChatCommand !== null && sideChatDisabledReason === null; // An answer responds to the open request rather than starting a turn, so the new-message @@ -873,6 +874,14 @@ export function useComposerSend(input: ComposerSendInput) { multipleTargets.push(resolved); } + const draftBeforePreparation = useComposerDraftStore + .getState() + .getComposerDraft(composerDraftTarget); + const draftChangedDuringPreparation = () => { + if (composerRef.current?.hasPendingAttachments() === true) return true; + const draft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); + return composerDraftContentChanged(draftBeforePreparation, draft); + }; sendInFlightRef.current = true; const sendGeneration = ++composerSendGenerationRef.current; const attachmentCapabilitiesBeforeUpload = readLiveAttachmentCapabilities(); @@ -920,6 +929,17 @@ export function useComposerSend(input: ComposerSendInput) { } const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities(); + if (draftChangedDuringPreparation()) { + sendInFlightRef.current = false; + setThreadError( + threadIdForSend, + "Draft changed while preparing this message. Review it and send again.", + ); + setDockedDraftHeroThreadKey((currentThreadKey) => + currentThreadKey === activeThreadKey ? null : currentThreadKey, + ); + return; + } if ( !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || attachmentCapabilitiesBeforeDispatch.fileBlockReason !== null @@ -941,7 +961,22 @@ export function useComposerSend(input: ComposerSendInput) { composerAttachmentsSnapshot.length > 0 && (sendCtx?.shownPendingApprovalIds.length ?? 0) > 0 ) { - await awaitAttachmentUploads(composerAttachmentsSnapshot.map((attachment) => attachment.id)); + await refreshExpiredAttachmentUploads({ + environmentId, + images: composerAttachmentsSnapshot, + draftTarget: composerDraftTarget, + }); + if (draftChangedDuringPreparation()) { + sendInFlightRef.current = false; + setThreadError( + threadIdForSend, + "Draft changed while preparing this message. Review it and send again.", + ); + setDockedDraftHeroThreadKey((currentThreadKey) => + currentThreadKey === activeThreadKey ? null : currentThreadKey, + ); + return; + } const uploadBlockReason = readLiveAttachmentCapabilities().fileBlockReason ?? (getUploadedAttachments({ environmentId, images: composerAttachmentsSnapshot }) === null @@ -1104,6 +1139,7 @@ export function useComposerSend(input: ComposerSendInput) { environmentId, attachments: composerAttachmentsSnapshot, usesAttachmentUploads: turnUsesAttachmentUploads, + draftTarget: composerDraftTarget, }); if (multipleModelSelections !== null) { await sendToMultipleModels({ @@ -1119,6 +1155,7 @@ export function useComposerSend(input: ComposerSendInput) { readFileBlockReason: () => readLiveAttachmentCapabilities().fileBlockReason, buildOutgoingMessageContext, isCurrentSend: () => composerSendGenerationRef.current === sendGeneration, + draftChangedDuringPreparation, }); return; } @@ -1413,26 +1450,34 @@ export function useComposerSend(input: ComposerSendInput) { ) { // A draft typed meanwhile keeps the composer, so the failed text stays reachable here. const failedText = sendSnapshot.draftText; - if (failedText.trim().length > 0) { - toastManager.add( - stackedThreadToast({ - type: "error", - title: isAtomCommandInterrupted(failure) - ? "Message may not have been sent" - : "Message not sent", - description: "Your new draft was kept. Copy the failed message to send it again.", - // The toast holds the only copy of the failed text, so it stays until dismissed. - timeout: 0, - data: { hideCopyButton: true }, - actionProps: { - children: "Copy message", - onClick: () => { - void writeTextToClipboard(failedText, "failed message").catch(() => undefined); - }, - }, - }), - ); - } + const hasText = failedText.trim().length > 0; + // An image-only message has nothing to copy, but its failure still needs a notice. + toastManager.add( + stackedThreadToast({ + type: "error", + title: isAtomCommandInterrupted(failure) + ? "Message may not have been sent" + : "Message not sent", + description: hasText + ? "Your new draft was kept. Copy the failed message to send it again." + : "Your new draft was kept.", + // The toast holds the only trace of the failed message, so it stays until dismissed. + timeout: 0, + data: { hideCopyButton: true }, + ...(hasText + ? { + actionProps: { + children: "Copy message", + onClick: () => { + void writeTextToClipboard(failedText, "failed message").catch( + () => undefined, + ); + }, + }, + } + : {}), + }), + ); } else { const retryComposerImages = restoreComposerDraft(composerDraftTarget, sendSnapshot); if (currentRouteThreadKeyRef.current === routeThreadKey) { diff --git a/apps/web/src/components/chat/useComposerStash.ts b/apps/web/src/components/chat/useComposerStash.ts index f32b61fd9a704..65b635acc1df6 100644 --- a/apps/web/src/components/chat/useComposerStash.ts +++ b/apps/web/src/components/chat/useComposerStash.ts @@ -25,6 +25,7 @@ import { partitionStashAttachments, usePromptStashStore, } from "../../promptStashStore"; +import type { PendingUserInputProgress } from "../../pendingUserInput"; import { type PendingUserInput } from "../../session-logic"; import { type ReviewCommentContext } from "../../reviewCommentContext"; import { collapseExpandedComposerCursor } from "../../composer-logic"; @@ -80,7 +81,7 @@ export function useComposerStash(input: { readonly routeThreadRef: ChatComposerProps["routeThreadRef"]; readonly projectSelectionRequired: boolean; readonly pendingUserInputs: ReadonlyArray; - readonly activePendingProgress: ChatComposerProps["activePendingProgress"]; + readonly activePendingProgress: PendingUserInputProgress | null; readonly prompt: string; readonly composerMenuOpen: boolean; readonly isComposerCollapsedMobile: boolean; diff --git a/apps/web/src/components/chat/useMultipleModelSend.ts b/apps/web/src/components/chat/useMultipleModelSend.ts index ccea2378968f5..ccf3b32621ce2 100644 --- a/apps/web/src/components/chat/useMultipleModelSend.ts +++ b/apps/web/src/components/chat/useMultipleModelSend.ts @@ -97,6 +97,7 @@ export function useMultipleModelSend(input: MultipleModelSendInput) { readFileBlockReason, buildOutgoingMessageContext, isCurrentSend, + draftChangedDuringPreparation, }: { readonly threadId: ThreadId; readonly project: EnvironmentProject; @@ -113,6 +114,7 @@ export function useMultipleModelSend(input: MultipleModelSendInput) { ) => ReturnType; /** False once a newer send from this composer started. */ readonly isCurrentSend: () => boolean; + readonly draftChangedDuringPreparation: () => boolean; }) => { const { attachments: attachmentsSnapshot, messageText } = sendSnapshot; const failedSelections: ModelSelection[] = []; @@ -124,6 +126,8 @@ export function useMultipleModelSend(input: MultipleModelSendInput) { // fails every selection; the draft restore below still runs. const sendResult = await settlePromise(async () => { const attachments = await attachmentsPromise; + if (draftChangedDuringPreparation()) + throw new Error("Draft changed while preparing this message. Review it and send again."); const fileBlockReason = readFileBlockReason(); if (fileBlockReason !== null) throw new Error(fileBlockReason); const context = buildOutgoingMessageContext( diff --git a/apps/web/src/components/chat/usePendingThreadRequests.ts b/apps/web/src/components/chat/usePendingThreadRequests.ts index e357066d1d7d3..8c32b07a29271 100644 --- a/apps/web/src/components/chat/usePendingThreadRequests.ts +++ b/apps/web/src/components/chat/usePendingThreadRequests.ts @@ -19,9 +19,18 @@ import { } from "@t3tools/client-runtime/state/runtime"; import { useRef, useState, type RefObject, type SetStateAction } from "react"; import { useShallow } from "zustand/react/shallow"; -import { type DraftId, useComposerDraftStore } from "../../composerDraftStore"; +import { + type ComposerThreadDraftState, + type DraftId, + useComposerDraftStore, +} from "../../composerDraftStore"; import { useStableCallback } from "../../hooks/useStableCallback"; -import { getUploadedAttachments, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue"; +import { + getUploadedAttachments, + refreshExpiredAttachmentUploads, + useAttachmentUploadStore, +} from "../../lib/attachmentUploadQueue"; +import { composerDraftContentChanged } from "./composerSend.logic"; import { buildPendingUserInputAnswers, setPendingUserInputCustomAnswer, @@ -60,6 +69,171 @@ const NO_PENDING_REQUESTS = { approvals: [], userInputs: [] } as const; const NO_PENDING_APPROVALS: ReturnType = []; const NO_PENDING_USER_INPUTS: ReturnType = []; +interface PendingUserInputDraftScope { + readonly environmentId: EnvironmentId; + readonly activeThreadId: ThreadId | null; + readonly activePendingUserInput: PendingUserInput | null; + readonly supportsQuestionAttachments: boolean; +} + +function pendingUserInputDraftKeys(scope: PendingUserInputDraftScope) { + const { environmentId, activeThreadId, activePendingUserInput } = scope; + return { + requestKey: userInputDraftKey(environmentId, activeThreadId, activePendingUserInput?.requestId), + questionKeys: + activeThreadId && activePendingUserInput + ? activePendingUserInput.questions.map((question) => + questionAttachmentDraftId( + environmentId, + activeThreadId, + activePendingUserInput.requestId, + question.id, + ), + ) + : [], + }; +} + +const selectQuestionComposerDrafts = + (keys: ReadonlyArray) => + (state: { readonly draftsByThreadKey: Record }) => + Object.fromEntries(keys.map((key) => [key, state.draftsByThreadKey[key]])); + +const selectQuestionUploadsBlocked = + ( + keys: ReadonlyArray, + questionComposerDrafts: Record, + environmentId: EnvironmentId, + ) => + (state: ReturnType) => + Object.fromEntries( + keys.map((key) => { + const draft = questionComposerDrafts[key]; + const attachments = draft ? [...draft.images, ...draft.files] : []; + return [ + key, + attachments.some((attachment) => { + const upload = state.uploadsByImageId[attachment.id]; + return upload?.status !== "ready" || upload.environmentId !== environmentId; + }), + ]; + }), + ); + +const selectQuestionPreparations = + (keys: ReadonlyArray) => (state: { readonly counts: Record }) => + Object.fromEntries(keys.map((key) => [key, state.counts[key] ?? 0])); + +function deriveActivePendingDraft( + scope: PendingUserInputDraftScope, + storedPendingAnswerDrafts: Record, + activePendingQuestionIndex: number, + questionComposerDrafts: Record, + questionUploadsBlocked: Record, + questionPreparations: Record, +) { + const { environmentId, activeThreadId, activePendingUserInput, supportsQuestionAttachments } = + scope; + // Suggested answers are shown until the user edits them; only edits are stored. + const activePendingAnswerDrafts: Record = + activePendingUserInput + ? seedUserInputDraftAnswers(activePendingUserInput.questions, storedPendingAnswerDrafts) + : storedPendingAnswerDrafts; + const activePendingDraftAnswers = + !activePendingUserInput || !activeThreadId + ? EMPTY_PENDING_USER_INPUT_ANSWERS + : Object.fromEntries( + activePendingUserInput.questions.map((question) => { + const key = questionAttachmentDraftId( + environmentId, + activeThreadId, + activePendingUserInput.requestId, + question.id, + ); + const draft = questionComposerDrafts[key]; + const attachments = draft ? [...draft.images, ...draft.files] : []; + return [ + question.id, + { + ...activePendingAnswerDrafts[question.id], + attachmentCount: attachments.length, + attachmentsBlocked: + (attachments.length > 0 && !supportsQuestionAttachments) || + (questionPreparations[key] ?? 0) > 0 || + questionUploadsBlocked[key] === true, + }, + ]; + }), + ); + const activePendingProgress = activePendingUserInput + ? derivePendingUserInputProgress( + activePendingUserInput.questions, + activePendingDraftAnswers, + activePendingQuestionIndex, + ) + : null; + const activePendingResolvedAnswers = activePendingUserInput + ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingDraftAnswers) + : null; + return { + activePendingDraftAnswers, + activePendingQuestionIndex, + activePendingProgress, + activePendingResolvedAnswers, + }; +} + +/** + * The open question's answers, position and progress. These change on every keystroke, so + * the composer subscribes to them rather than the chat view. + */ +export function usePendingUserInputDraft(scope: PendingUserInputDraftScope) { + const { requestKey, questionKeys: keys } = pendingUserInputDraftKeys(scope); + const storedPendingAnswerDrafts = usePendingUserInputAnswers( + (state) => state[requestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS, + ); + const activePendingQuestionIndex = usePendingUserInputQuestionIndex( + (state) => state[requestKey] ?? 0, + ); + const questionComposerDrafts = useComposerDraftStore( + useShallow(selectQuestionComposerDrafts(keys)), + ); + const questionUploadsBlocked = useAttachmentUploadStore( + useShallow(selectQuestionUploadsBlocked(keys, questionComposerDrafts, scope.environmentId)), + ); + const questionPreparations = useQuestionAttachmentPreparation( + useShallow(selectQuestionPreparations(keys)), + ); + return deriveActivePendingDraft( + scope, + storedPendingAnswerDrafts, + activePendingQuestionIndex, + questionComposerDrafts, + questionUploadsBlocked, + questionPreparations, + ); +} + +// Request callbacks read drafts when called, so the chat view never subscribes to them. +function readPendingUserInputDraft(scope: PendingUserInputDraftScope) { + const { requestKey, questionKeys: keys } = pendingUserInputDraftKeys(scope); + const questionComposerDrafts = selectQuestionComposerDrafts(keys)( + useComposerDraftStore.getState(), + ); + return deriveActivePendingDraft( + scope, + usePendingUserInputAnswers.getState()[requestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS, + usePendingUserInputQuestionIndex.getState()[requestKey] ?? 0, + questionComposerDrafts, + selectQuestionUploadsBlocked( + keys, + questionComposerDrafts, + scope.environmentId, + )(useAttachmentUploadStore.getState()), + selectQuestionPreparations(keys)(useQuestionAttachmentPreparation.getState()), + ); +} + function makePendingCustomAnswerSetter(input: { readonly activePendingUserInput: PendingUserInput | null; readonly activePendingRequestKey: string; @@ -162,89 +336,12 @@ export function usePendingThreadRequests(input: { activeThreadId, activePendingUserInput?.requestId, ); - const storedPendingAnswerDrafts = usePendingUserInputAnswers( - (state) => state[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS, - ); - // Suggested answers are shown until the user edits them; only edits are stored. - const activePendingAnswerDrafts: Record = - activePendingUserInput - ? seedUserInputDraftAnswers(activePendingUserInput.questions, storedPendingAnswerDrafts) - : storedPendingAnswerDrafts; - const activePendingQuestionIndex = usePendingUserInputQuestionIndex( - (state) => state[activePendingRequestKey] ?? 0, - ); - const pendingQuestionDraftKeys = activeThreadId - ? pendingUserInputs.flatMap((request) => - request.questions.map((question) => - questionAttachmentDraftId(environmentId, activeThreadId, request.requestId, question.id), - ), - ) - : []; - const questionComposerDrafts = useComposerDraftStore( - useShallow((state) => - Object.fromEntries( - pendingQuestionDraftKeys.map((key) => [key, state.draftsByThreadKey[key]]), - ), - ), - ); - const questionUploadsBlocked = useAttachmentUploadStore( - useShallow((state) => - Object.fromEntries( - pendingQuestionDraftKeys.map((key) => { - const draft = questionComposerDrafts[key]; - const attachments = draft ? [...draft.images, ...draft.files] : []; - return [ - key, - attachments.some((attachment) => { - const upload = state.uploadsByImageId[attachment.id]; - return upload?.status !== "ready" || upload.environmentId !== environmentId; - }), - ]; - }), - ), - ), - ); - const questionPreparations = useQuestionAttachmentPreparation( - useShallow((state) => - Object.fromEntries(pendingQuestionDraftKeys.map((key) => [key, state.counts[key] ?? 0])), - ), - ); - const activePendingDraftAnswers = - !activePendingUserInput || !activeThreadId - ? EMPTY_PENDING_USER_INPUT_ANSWERS - : Object.fromEntries( - activePendingUserInput.questions.map((question) => { - const key = questionAttachmentDraftId( - environmentId, - activeThreadId, - activePendingUserInput.requestId, - question.id, - ); - const draft = questionComposerDrafts[key]; - const attachments = draft ? [...draft.images, ...draft.files] : []; - return [ - question.id, - { - ...activePendingAnswerDrafts[question.id], - attachmentCount: attachments.length, - attachmentsBlocked: - (attachments.length > 0 && !supportsQuestionAttachments) || - (questionPreparations[key] ?? 0) > 0 || - questionUploadsBlocked[key] === true, - }, - ]; - }), - ); - const activePendingProgress = activePendingUserInput - ? derivePendingUserInputProgress( - activePendingUserInput.questions, - activePendingDraftAnswers, - activePendingQuestionIndex, - ) - : null; - const activePendingResolvedAnswers = activePendingUserInput - ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingDraftAnswers) - : null; + const draftScope = { + environmentId, + activeThreadId, + activePendingUserInput, + supportsQuestionAttachments, + }; const activePendingIsResponding = activePendingUserInput ? activePendingUserInput.responseCapability === "not_resumable" || respondingUserInputRequestIds.includes(activePendingUserInput.requestId) @@ -298,60 +395,102 @@ export function usePendingThreadRequests(input: { if (!pendingInput || pendingInput.responseCapability === "not_resumable") return; const responseKey = JSON.stringify([environmentId, activeThreadId, requestId]); if (userInputResponsesInFlight.current.has(responseKey)) return; - const attachmentsByQuestionId = new Map(); - const providerAnswers = { ...answers }; - const threadDraft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); - for (const question of pendingInput.questions) { - const target = questionAttachmentDraftId( - environmentId, - activeThreadId, - requestId, - question.id, - ); - if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return; - const draft = useComposerDraftStore.getState().getComposerDraft(target); - providerAnswers[question.id] = projectPendingUserInputAnswer( - answers[question.id], - answerContextRecords(draft, threadDraft), - ); - const attachments = draft ? [...draft.images, ...draft.files] : []; - if (attachments.length === 0) continue; - const uploaded = getUploadedAttachments({ environmentId, images: attachments }); - if (!uploaded) { + userInputResponsesInFlight.current.add(responseKey); + const answerDraftKey = userInputDraftKey(environmentId, activeThreadId, requestId); + const answerDraftBeforePreparation = usePendingUserInputAnswers.getState()[answerDraftKey]; + setRespondingUserInputRequestIds((existing) => + existing.includes(requestId) ? existing : [...existing, requestId], + ); + const prepareAndRespond = async () => { + const attachmentsByQuestionId = new Map(); + const providerAnswers = { ...answers }; + const threadDraft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); + const questionDrafts = pendingInput.questions.map((question) => { + const target = questionAttachmentDraftId( + environmentId, + activeThreadId, + requestId, + question.id, + ); + const draft = useComposerDraftStore.getState().getComposerDraft(target); + return { question, target, draft }; + }); + for (const { question, target, draft } of questionDrafts) { + if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return; + providerAnswers[question.id] = projectPendingUserInputAnswer( + answers[question.id], + answerContextRecords(draft, threadDraft), + ); + const attachments = draft ? [...draft.images, ...draft.files] : []; + if (attachments.length === 0) continue; + await refreshExpiredAttachmentUploads({ + environmentId, + images: attachments, + draftTarget: target, + }); + if ( + composerDraftContentChanged( + draft, + useComposerDraftStore.getState().getComposerDraft(target), + ) + ) { + setThreadError( + activeThreadId, + "Answer changed while preparing attachments. Review it and send again.", + ); + return; + } + const uploaded = getUploadedAttachments({ environmentId, images: attachments }); + if (!uploaded) { + setThreadError( + activeThreadId, + "Wait for attachments to finish uploading, or remove failed uploads.", + ); + return; + } + attachmentsByQuestionId.set(question.id, uploaded as UserInputAttachments[string]); + } + if ( + usePendingUserInputAnswers.getState()[answerDraftKey] !== answerDraftBeforePreparation || + questionDrafts.some( + ({ target, draft }) => + (useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0 || + composerDraftContentChanged( + draft, + useComposerDraftStore.getState().getComposerDraft(target), + ), + ) + ) { setThreadError( activeThreadId, - "Wait for attachments to finish uploading, or remove failed uploads.", + "Answer changed while preparing attachments. Review it and send again.", ); return; } - attachmentsByQuestionId.set(question.id, uploaded as UserInputAttachments[string]); - } - userInputResponsesInFlight.current.add(responseKey); - - setRespondingUserInputRequestIds((existing) => - existing.includes(requestId) ? existing : [...existing, requestId], - ); - const result = await respondToThreadUserInput({ - environmentId, - input: { - threadId: activeThreadId, - requestId, - answers: providerAnswers, - ...(attachmentsByQuestionId.size > 0 - ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) } - : {}), - }, + const result = await respondToThreadUserInput({ + environmentId, + input: { + threadId: activeThreadId, + requestId, + answers: providerAnswers, + ...(attachmentsByQuestionId.size > 0 + ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) } + : {}), + }, + }); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + setThreadError( + activeThreadId, + error instanceof Error ? error.message : "Failed to submit user input.", + ); + } + return result; + }; + return prepareAndRespond().finally(() => { + userInputResponsesInFlight.current.delete(responseKey); + setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId)); }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError( - activeThreadId, - error instanceof Error ? error.message : "Failed to submit user input.", - ); - } - userInputResponsesInFlight.current.delete(responseKey); - setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId)); - return result; }; const onDismissUserInput = async (requestId: RuntimeRequestId) => { @@ -392,7 +531,8 @@ export function usePendingThreadRequests(input: { } // The option replaces the custom answer. Anything typed there is the // user's text, so it goes back to the thread draft instead of vanishing. - const displacedAnswer = activePendingAnswerDrafts[questionId]?.customAnswer; + const displacedAnswer = + readPendingUserInputDraft(draftScope).activePendingDraftAnswers[questionId]?.customAnswer; const currentPrompt = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? ""; const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(currentPrompt, displacedAnswer); @@ -428,10 +568,7 @@ export function usePendingThreadRequests(input: { } } setPendingUserInputAnswersByRequestId((existing) => { - const question = - (activePendingProgress?.activeQuestion?.id === questionId - ? activePendingProgress.activeQuestion - : undefined) ?? activePendingUserInput.questions.find((entry) => entry.id === questionId); + const question = activePendingUserInput.questions.find((entry) => entry.id === questionId); if (!question) { return existing; } @@ -493,13 +630,12 @@ export function usePendingThreadRequests(input: { }); const onAdvanceActivePendingUserInput = () => { - if ( - !activePendingUserInput || - activePendingUserInput.responseCapability === "not_resumable" || - !activePendingProgress - ) { + if (!activePendingUserInput || activePendingUserInput.responseCapability === "not_resumable") { return; } + const { activePendingProgress, activePendingResolvedAnswers } = + readPendingUserInputDraft(draftScope); + if (!activePendingProgress) return; if (activePendingProgress.isLastQuestion) { if (activePendingResolvedAnswers) { void onRespondToUserInput(activePendingUserInput.requestId, activePendingResolvedAnswers); @@ -512,6 +648,7 @@ export function usePendingThreadRequests(input: { const onAdvanceActivePendingUserInputStable = useStableCallback(onAdvanceActivePendingUserInput); const onPreviousActivePendingUserInputQuestion = () => { + const { activePendingProgress } = readPendingUserInputDraft(draftScope); if (!activePendingProgress) { return; } @@ -526,10 +663,6 @@ export function usePendingThreadRequests(input: { pendingUserInputs, activePendingApproval, activePendingUserInput, - activePendingDraftAnswers, - activePendingQuestionIndex, - activePendingProgress, - activePendingResolvedAnswers, activePendingIsResponding, respondingRequestIds, onRespondToApproval: onRespondToApprovalStable, diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index e7f321bec9dc2..d5cb8505a013e 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -38,6 +38,7 @@ import { useStableCallback } from "../../hooks/useStableCallback"; import { awaitAttachmentUploads, getUploadedAttachments, + refreshExpiredAttachmentUploads, releaseDraftAttachments, startAttachmentUpload, } from "../../lib/attachmentUploadQueue"; @@ -60,6 +61,7 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { stackedThreadToast, toastManager } from "../ui/toast"; import type { ChatComposerHandle } from "./ChatComposer"; import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles"; +import { composerDraftContentChanged } from "./composerSend.logic"; import { discardQueuedEditDraft, prepareQueuedEditAttachments, @@ -105,6 +107,7 @@ async function submitQueuedRunEdit(input: { readonly editing: EditingQueuedRun; readonly content: QueuedRunEditContent; readonly editQueuedRun: ReturnType; + readonly draftChanged: () => boolean; }): Promise { const { environmentId, draftTarget, editing, content } = input; const editText = content.prompt.trim(); @@ -124,6 +127,7 @@ async function submitQueuedRunEdit(input: { validateFiles(); for (const file of files) startAttachmentUpload({ environmentId, image: file, draftTarget }); await awaitAttachmentUploads(files.map((file) => file.id)); + await refreshExpiredAttachmentUploads({ environmentId, images: files, draftTarget }); validateFiles(); const uploaded = getUploadedAttachments({ environmentId, images: files }); if (uploaded === null) throw new Error("Retry or remove failed uploads before saving."); @@ -137,6 +141,8 @@ async function submitQueuedRunEdit(input: { readImage: readFileAsDataUrl, uploadFiles, }); + if (input.draftChanged()) + return "Draft changed while preparing this message. Review it and save again."; // The edit draft owns thread and machine mentions, so a chip removed while editing is dropped. const keptRecords = (editing.context?.records ?? []).filter( (record) => @@ -363,15 +369,29 @@ export function useQueuedRunEdit(input: { // The save's result decides the edit's fate, even if the run starts meanwhile. const finishSave = queuedRunEdits.startSave(editKey); if (finishSave === null) return; + const draftBeforeSave = useComposerDraftStore.getState().getComposerDraft(draftTarget); + const draftChanged = () => + appAtomRegistry.get(queuedRunEdits.atom)[editKey] !== editing || + composerDraftContentChanged( + draftBeforeSave, + useComposerDraftStore.getState().getComposerDraft(draftTarget), + ); const error = await submitQueuedRunEdit({ environmentId, draftTarget, editing, content, editQueuedRun: editQueuedRunCommand, + draftChanged, }); - setThreadError(editing.threadId, error); - const current = finishSave(error === null); + const changedAfterSave = error === null && draftChanged(); + setThreadError( + editing.threadId, + changedAfterSave + ? "The earlier edit was saved. Review your newer changes and save again." + : error, + ); + const current = finishSave(error === null && !changedAfterSave); if (!current) { // A failed save can recover into the thread draft; a newer edit can also retain resources. const drafts = Object.values(useComposerDraftStore.getState().draftsByThreadKey); @@ -394,6 +414,7 @@ export function useQueuedRunEdit(input: { return; } if (error !== null) return; + if (changedAfterSave) return; releaseDraftAttachments(newAttachments); promptRef.current = ""; clearEditDraft(editing.runId); diff --git a/apps/web/src/components/chat/useThreadLifecycle.tsx b/apps/web/src/components/chat/useThreadLifecycle.tsx index 66b2a9f6b3fd3..4f27c18b75c7d 100644 --- a/apps/web/src/components/chat/useThreadLifecycle.tsx +++ b/apps/web/src/components/chat/useThreadLifecycle.tsx @@ -76,7 +76,7 @@ import { useAtomValue } from "@effect/atom-react"; import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution"; import { Atom } from "effect/reactivity"; import { environmentThreadDetails } from "../../state/threads"; -import { openSideChatTab } from "../../lib/sideChatPane"; +import { resolveThreadOpenRoute } from "../../lib/sideChatPane"; import type { useLocalDispatchState } from "./useLocalDispatchState"; const RELATED_THREAD_SHELL_WAIT_MS = 1_000; const NO_RUN_STOP_ATOM = Atom.make(null).pipe( @@ -495,10 +495,11 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { toastManager.add({ type: "info", title: "This thread is no longer available" }); return; } - if (activeThreadRef && openSideChatTab(activeThreadRef, shell)) return; + const routeRef = resolveThreadOpenRoute(threadRef, shell); + if (scopedThreadKey(routeRef) === routeThreadKey) return; void navigate({ to: "/$environmentId/$threadId", - params: buildThreadRouteParams(threadRef), + params: buildThreadRouteParams(routeRef), }); }; const onOpenRelatedThreadStable = useStableCallback(onOpenRelatedThread); diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsx index 7e8bc3e1d171a..4dba7607f81c0 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx @@ -168,7 +168,8 @@ function FileDocument(props: { readonly src: string; readonly title: string }) {