From 580b526758c59e92e4688c82b4cc95ebbaa10a42 Mon Sep 17 00:00:00 2001 From: prov3ntus <113371782+prov3ntus@users.noreply.github.com> Date: Sat, 14 Nov 2026 04:36:24 +0000 Subject: [PATCH 001/524] fix(server): respect the default Windows file manager (#28205) Co-authored-by: Julius Marminge --- .../src/process/externalLauncher.test.ts | 116 +++++++++++++++++- apps/server/src/process/externalLauncher.ts | 30 +++-- 2 files changed, 134 insertions(+), 12 deletions(-) diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index fbb407233a315..4472577644b3a 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -339,6 +339,111 @@ it.effect("launches an installed editor with platform-safe arguments", () => }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +it.live.skipIf(!windowsHost)("opens Windows folders through the default shell handler", () => + Effect.gen(function* () { + let spawned: ChildProcess.StandardCommand | undefined; + yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + yield* launcher.launchEditor({ + editor: "file-manager", + cwd: "C:/workspace [draft]/author's ‘left’ ‚low‛ $media/’; Write-Output injected; #", + }); + }).pipe( + Effect.provide( + layerTest({ + platform: "win32", + env: { PATH: "C:\\Windows", PATHEXT: ".EXE" }, + onSpawn: (command) => { + spawned = command; + }, + }), + ), + ); + assert.ok(spawned); + assert.equal(spawned.options.detached, false); + const source = Buffer.from(String(spawned.args.at(-1) ?? ""), "base64").toString("utf16le"); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const output = yield* spawner.string( + ChildProcess.make(spawned.command, [ + ...spawned.args.slice(0, -1), + Buffer.from( + `[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); function Invoke-Item { param($LiteralPath) Write-Output $LiteralPath }; ${source}`, + "utf16le", + ).toString("base64"), + ]), + ); + assert.equal( + output.trim(), + "C:\\workspace [draft]\\author's ‘left’ ‚low‛ $media\\’; Write-Output injected; #", + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +for (const [replacement, verb, handler, target, expected] of [ + ["none", "none", "", "C:/repo/file.txt", 'explorer.exe /select,"C:\\repo\\file.txt"'], + ["Directory", "openindopus", "dopusrt.exe", "C:/repo/file.txt", "shell:C:\\repo"], + ["Folder", "openindopus", "dopusrt.exe", "C:/repo/file.txt", "shell:C:\\repo"], + [ + "Folder", + "open", + '"C:\\Windows\\explorer.exe"', + "C:/repo/file.txt", + 'explorer.exe /select,"C:\\repo\\file.txt"', + ], + [ + "Folder", + "open", + "ExplorerDelegate", + "C:/repo/file.txt", + 'explorer.exe /select,"C:\\repo\\file.txt"', + ], + [ + "Drive", + "openindopus", + "dopusrt.exe", + "C:/repo/file.txt", + 'explorer.exe /select,"C:\\repo\\file.txt"', + ], + ["Drive", "openindopus", "dopusrt.exe", "C:/file.txt", "shell:C:\\"], +] as const) { + it.live.skipIf(!windowsHost)( + `reveals ${target} with ${replacement}/${verb} handled by ${handler}`, + () => + Effect.gen(function* () { + let spawned: ChildProcess.StandardCommand | undefined; + yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + yield* launcher.launchEditor({ + editor: "file-manager", + cwd: target, + reveal: true, + }); + }).pipe( + Effect.provide( + layerTest({ + platform: "win32", + env: { PATH: "C:\\Windows", PATHEXT: ".EXE" }, + onSpawn: (command) => { + spawned = command; + }, + }), + ), + ); + assert.ok(spawned); + const source = Buffer.from(String(spawned.args.at(-1) ?? ""), "base64").toString("utf16le"); + const stubs = `function Get-ItemProperty { param($LiteralPath, $ErrorAction) @{ '(default)' = if ($LiteralPath -eq 'Registry::HKEY_CLASSES_ROOT\\${replacement}\\shell') { '${verb}' } elseif ($LiteralPath -eq 'Registry::HKEY_CLASSES_ROOT\\${replacement}\\shell\\${verb}\\command') { '${handler}' } else { 'none' }; DelegateExecute = if ('${handler}' -eq 'ExplorerDelegate') { '{11dbb47c-a525-400b-9e80-a54615a090c0}' } else { '' } } }; function Invoke-Item { param($LiteralPath) Write-Output "shell:$LiteralPath" }; function Start-Process { param($FilePath, $ArgumentList) Write-Output "$FilePath $ArgumentList" }; `; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const output = yield* spawner.string( + ChildProcess.make(spawned.command, [ + ...spawned.args.slice(0, -1), + Buffer.from(stubs + source, "utf16le").toString("base64"), + ]), + ); + assert.equal(output.trim(), expected); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +} + it.effect.skipIf(windowsHost)( "reveals a WSL file in Windows File Explorer through its UNC path", () => @@ -359,7 +464,7 @@ it.effect.skipIf(windowsHost)( const editors = yield* launcher.resolveAvailableEditors(); yield* launcher.launchEditor({ editor: "file-manager", - cwd: "/home/t3/workspace [draft]/author's $media/clip|draft.mp4", + cwd: "/home/t3/workspace [draft]/author's ‘$media/clip|draft.mp4", reveal: true, }); return { kind, editors }; @@ -386,9 +491,14 @@ it.effect.skipIf(windowsHost)( assert.equal(spawned.options.detached, true); const encodedCommand = String(spawned.args[spawned.args.length - 1] ?? ""); const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le"); - assert.equal( + assert.include(decodedCommand, "'Directory', 'Folder'"); + assert.include( + decodedCommand, + "Invoke-Item -LiteralPath '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s ‘‘$media'", + ); + assert.include( decodedCommand, - "$ProgressPreference = 'SilentlyContinue'; $folderVerb = (Get-ItemProperty -LiteralPath 'Registry::HKEY_CLASSES_ROOT\\Directory\\shell' -ErrorAction SilentlyContinue).'(default)'; if ($folderVerb -and $folderVerb -ne 'none') { Invoke-Item -LiteralPath '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s $media' } else { Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s $media\\clip|draft.mp4' + '\"') }", + "'\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s ‘‘$media\\clip|draft.mp4'", ); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index 3b1ed43142ac0..4eecaf2c5cb2c 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -182,7 +182,8 @@ function encodeUtf16LeBase64(input: string): string { } function escapePowerShellStringLiteral(input: string): string { - return `'${input.replaceAll("'", "''")}'`; + // PowerShell also recognises typographic apostrophes as single-quote delimiters. + return `'${input.replace(/['\u2018-\u201b]/g, "$&$&")}'`; } function resolveWindowsRoot(env: NodeJS.ProcessEnv): string { @@ -527,6 +528,18 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( return yield* resolveFileManagerRevealLaunch(target, platform, env, command); } + if (platform === "win32") { + // ShellExecute honours replacement folder handlers that explorer.exe bypasses. + return { + ...powerShellFileManagerLaunch( + target, + `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(normalizeWindowsFileManagerPath(target))}`, + resolvePowerShellPath(env), + ), + detached: WINDOWS_POWERSHELL_DETACHED, + }; + } + return { editor: editorDef.id, target, @@ -534,19 +547,18 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( args: command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined ? [resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME)] - : platform === "win32" - ? // Explorer interprets / as a switch and silently opens a fallback folder. - [normalizeWindowsFileManagerPath(target)] - : [target], + : [target], }; }); -// A replacement manager registers a default Directory shell verb; stock Windows -// uses "none". Explorer needs its /select argument passed verbatim through -// PowerShell because Node's argument quoting changes how Explorer parses it. +// Replacement managers can register under Directory, Drive, or Folder. Explorer +// needs its /select argument passed verbatim through PowerShell because Node's +// argument quoting changes how Explorer parses it. function buildFileManagerRevealPowerShellSource(target: string, parent: string): string { const literal = escapePowerShellStringLiteral(target); - return `$ProgressPreference = 'SilentlyContinue'; $folderVerb = (Get-ItemProperty -LiteralPath 'Registry::HKEY_CLASSES_ROOT\\Directory\\shell' -ErrorAction SilentlyContinue).'(default)'; if ($folderVerb -and $folderVerb -ne 'none') { Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)} } else { Start-Process 'explorer.exe' -ArgumentList ('/select,"' + ${literal} + '"') }`; + const folderClass = /^[a-z]:\\$/i.test(parent) ? "Drive" : "Directory"; + // Explorer's ordinary open/explore handlers may also be explicit defaults. + return String.raw`$ProgressPreference = 'SilentlyContinue'; $folderVerb = '${folderClass}', 'Folder' | ForEach-Object { $key = "Registry::HKEY_CLASSES_ROOT\$_\shell"; $verb = (Get-ItemProperty -LiteralPath $key -ErrorAction SilentlyContinue).'(default)'; if ($verb -and $verb -ne 'none') { $handler = Get-ItemProperty -LiteralPath "$key\$verb\command" -ErrorAction SilentlyContinue; if ($handler.DelegateExecute -ne '{11dbb47c-a525-400b-9e80-a54615a090c0}' -and $handler.'(default)' -notmatch '^\s*"?(?:[^"]*[\\/])?explorer\.exe(?:["\s]|$)') { $verb } } }; if ($folderVerb) { Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)} } else { Start-Process 'explorer.exe' -ArgumentList ('/select,"' + ${literal} + '"') }`; } function powerShellFileManagerLaunch( From 34cf030e5e4cdfc175e1d875a6f21b66c4272d69 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 20:52:26 -0800 Subject: [PATCH 002/524] fix(web): pull requests error names the environment that failed (#27882) --- .../pullRequest/PullRequestsPage.tsx | 11 ++-- apps/web/src/state/pullRequests.test.ts | 55 ++++++++++++++++++- apps/web/src/state/pullRequests.ts | 16 ++++-- 3 files changed, 72 insertions(+), 10 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx index a85b6a080948f..06861fb6ab06a 100644 --- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx @@ -1176,6 +1176,9 @@ export function PullRequestsPage() { {panelToggleControls} ); + const listError = listQuery.error + ? `${environmentLabels.get(listQuery.error.environmentId) || "Environment"}: ${listQuery.error.message}` + : null; const carriedToNothing = shownCount === 0 && typedQuery.length === 0 && @@ -1191,9 +1194,9 @@ export function PullRequestsPage() { /> ) : firstLoad ? ( - ) : listQuery.error && shownCount === 0 ? ( + ) : listError && shownCount === 0 ? ( listQuery.refresh()} /> @@ -1236,9 +1239,9 @@ export function PullRequestsPage() { /> )} - {listQuery.error && shownCount > 0 ? ( + {listError && shownCount > 0 ? (
- {listQuery.error} Showing the last pull requests loaded. + {listError} Showing the last pull requests loaded. diff --git a/apps/web/src/state/pullRequests.test.ts b/apps/web/src/state/pullRequests.test.ts index 13a5de6ee9c54..fafec751a6c0f 100644 --- a/apps/web/src/state/pullRequests.test.ts +++ b/apps/web/src/state/pullRequests.test.ts @@ -9,9 +9,34 @@ import { type PullRequestListResult, type PullRequestSummary, } from "@t3tools/contracts"; -import { describe, expect, it, vi } from "vite-plus/test"; import * as Cause from "effect/Cause"; -import { AsyncResult } from "effect/reactivity"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { describe, expect, it, vi } from "vite-plus/test"; + +const listAnswers = vi.hoisted(() => new Map()); + +vi.mock("@effect/atom-react", async (importOriginal) => { + const { AtomRegistry } = await import("effect/reactivity"); + const registry = AtomRegistry.make(); + return { + ...(await importOriginal()), + useAtomValue: (atom: Atom.Atom) => registry.get(atom), + }; +}); +vi.mock("@t3tools/client-runtime/state/pull-requests", async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + createPullRequestEnvironmentAtoms: ( + ...args: Parameters + ) => ({ + ...actual.createPullRequestEnvironmentAtoms(...args), + list: ({ environmentId }: { readonly environmentId: string }) => + listAnswers.get(environmentId), + }), + }; +}); import { newestPullRequestObservation, @@ -24,6 +49,7 @@ import { restoredPullRequestList, threadPullRequestLinkToSummary, observeFailedPullRequestList, + usePullRequestList, } from "./pullRequests"; it("observes both typed list failures without changing their status or replaying cached timestamps", () => { @@ -490,6 +516,31 @@ describe("pull request list answers across a reload", () => { } }); + it("names the environment whose list failed while the others' rows still show", () => { + listAnswers.set(local, Atom.make(AsyncResult.success(answer([listEntry(1)])))); + listAnswers.set( + remote, + Atom.make( + AsyncResult.failure( + Cause.fail( + new Error("Relay could not reach the environment endpoint (endpoint_request_failed)."), + ), + ), + ), + ); + + const view = usePullRequestList([ + { environmentId: local, input }, + { environmentId: remote, input }, + ]); + + expect(view.data?.entries.map((row) => [row.environmentId, row.number])).toEqual([[local, 1]]); + expect(view.error).toEqual({ + environmentId: remote, + message: "Relay could not reach the environment endpoint (endpoint_request_failed).", + }); + }); + it("removes the composite snapshots it replaced", () => { const storage = makeStorage(); storage.held.set("t3.pullRequests.list:env-local,env-remote", "{}"); diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.ts index 13d71301e2035..bb8961328f1a9 100644 --- a/apps/web/src/state/pullRequests.ts +++ b/apps/web/src/state/pullRequests.ts @@ -525,10 +525,15 @@ export interface EnvironmentQueryTarget { readonly input: Input; } +interface EnvironmentQueryError { + readonly environmentId: EnvironmentId; + readonly message: string; +} + interface MergedEnvironmentQueryView { readonly observations: ReadonlyArray; readonly values: ReadonlyArray; - readonly error: string | null; + readonly error: EnvironmentQueryError | null; readonly isPending: boolean; } @@ -568,14 +573,17 @@ function createMergedEnvironmentQuery( const values: Array = []; const observations: Array = []; const pendingEnvironments = new Set(); - let error: string | null = null; + let error: EnvironmentQueryError | null = null; let isPending = false; for (const target of targets) { const result = get(atomFor(target)); isPending ||= result.waiting; if (result.waiting) pendingEnvironments.add(target.environmentId); if (result._tag === "Failure" && error === null) { - error = formatEnvironmentQueryError(result.cause); + error = { + environmentId: target.environmentId, + message: formatEnvironmentQueryError(result.cause), + }; } const value = AsyncResult.getOrElse(result, () => null); if (value !== null) values.push([target.environmentId, value]); @@ -656,7 +664,7 @@ export function usePullRequestTurnRefresh(environmentId: EnvironmentId): number export interface MergedPullRequestListView { readonly data: MergedPullRequestList | null; - readonly error: string | null; + readonly error: EnvironmentQueryError | null; readonly isPending: boolean; readonly observations: ReadonlyArray; readonly refresh: (targets?: ReadonlyArray>) => void; From eea9d15ee275858a681db6293dd35345bb338728 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 20:55:56 -0800 Subject: [PATCH 003/524] fix(desktop): Windows folders dropped on a WSL backend insert their WSL path (#30037) --- apps/desktop/src/ipc/DesktopIpcHandlers.ts | 2 + apps/desktop/src/ipc/channels.ts | 1 + apps/desktop/src/ipc/methods/window.test.ts | 43 +++++++++++ apps/desktop/src/ipc/methods/window.ts | 44 ++++++++--- apps/desktop/src/preload.ts | 2 + .../src/wsl/DesktopWslEnvironment.test.ts | 49 +++++++++++++ apps/desktop/src/wsl/DesktopWslEnvironment.ts | 5 +- apps/web/src/components/chat/ChatComposer.tsx | 73 ++++++++++++++----- .../src/components/chat/folderDrop.test.ts | 18 ++++- apps/web/src/components/chat/folderDrop.ts | 22 +++--- packages/contracts/src/ipc.ts | 2 + 11 files changed, 219 insertions(+), 42 deletions(-) diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 9f2f68be61520..57d7101cf9ec7 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -50,6 +50,7 @@ import { probeRemoteEditors, revealWindow, pickFolder, + toLocalBackendPath, pickProjectFavicon, pickThemeFiles, setTheme, @@ -145,6 +146,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(setWslOnly); yield* ipc.handle(pickFolder); + yield* ipc.handle(toLocalBackendPath); yield* ipc.handle(pickProjectFavicon); yield* ipc.handle(pickThemeFiles); yield* ipc.handle(setTheme); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 0e422f9bc7356..b7bb5e579572f 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -1,4 +1,5 @@ export const PICK_FOLDER_CHANNEL = "desktop:pick-folder"; +export const TO_LOCAL_BACKEND_PATH_CHANNEL = "desktop:to-local-backend-path"; export const SET_NOTIFICATION_BADGE_CHANNEL = "desktop:set-notification-badge"; export const PICK_PROJECT_FAVICON_CHANNEL = "desktop:pick-project-favicon"; export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files"; diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index 376f85d2baf9d..fbeda6d2f2dcd 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -25,6 +25,7 @@ import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; +import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts"; import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as IpcChannels from "../channels.ts"; @@ -36,6 +37,7 @@ import { probeRemoteEditors, readMedia, syncHtmlFullscreen, + toLocalBackendPath, } from "./window.ts"; const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = { @@ -185,6 +187,47 @@ describe("getLocalEnvironmentBootstraps", () => { }); }); +describe("toLocalBackendPath", () => { + const { runningDistro: _, ...windowsConfig } = readyWslConfig; + it.effect("converts paths through wslpath only for backends running in WSL", () => + Effect.gen(function* () { + const convert = (backendId: string, path = "C:\\Users\\me\\project") => + toLocalBackendPath.handler({ backendId, path }); + assert.strictEqual(yield* convert("primary"), "C:\\Users\\me\\project"); + assert.strictEqual(yield* convert("wsl:default"), "/drives/c/Users/me/project"); + assert.strictEqual(yield* convert("wsl:missing"), null); + assert.strictEqual( + yield* convert("wsl:default", "\\\\wsl.localhost\\ubuntu\\home\\me\\repo"), + "/home/me/repo", + ); + assert.strictEqual(yield* convert("wsl:default", "\\\\wsl$\\Debian\\home\\me\\repo"), null); + assert.strictEqual( + yield* convert("primary", "\\\\wsl$\\Debian\\home\\me\\repo"), + "\\\\wsl$\\Debian\\home\\me\\repo", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + DesktopBackendPool.layerTest([ + { + ...defaultWslInstance, + id: DesktopBackendManager.BackendInstanceId("primary"), + currentConfig: Effect.succeedSome(windowsConfig), + }, + defaultWslInstance, + ]), + DesktopWslEnvironment.layerTest({ + windowsToWslPath: (distro, windowsPath) => + distro === "Ubuntu" && windowsPath === "C:\\Users\\me\\project" + ? Option.some("/drives/c/Users/me/project") + : Option.none(), + }), + ), + ), + ), + ); +}); + describe("installRelayTelemetryEnabled", () => { // The renderer reads this over sync IPC, so the answer must not wait on the filesystem. const relayTelemetryEnabled = ( diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 53a1138d71a99..3a525e8eac420 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -25,6 +25,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts"; +import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts"; import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; @@ -204,6 +205,20 @@ export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({ }), }); +// Ask the distro: its automount root is configurable, so /mnt/ is only the default. +const windowsPathToWsl = Effect.fn("desktop.ipc.window.windowsPathToWsl")(function* ( + distro: string | null, + windowsPath: string, +) { + const linuxUncPath = wslUncPathToLinuxPath(windowsPath); + if (linuxUncPath !== null) return Option.some(linuxUncPath); + const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; + return yield* wslEnvironment.windowsToWslPath( + extractDistroFromUncPath(windowsPath) ?? distro, + windowsPath, + ); +}); + export const pickFolder = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PICK_FOLDER_CHANNEL, payload: Schema.UndefinedOr(PickFolderOptionsSchema), @@ -250,20 +265,29 @@ export const pickFolder = DesktopIpc.makeIpcMethod({ if (!useWsl) { return selectedPath.value; } - - const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value); - if (linuxUncPath !== null) { - return linuxUncPath; - } - - const converted = yield* wslEnvironment.windowsToWslPath( - extractDistroFromUncPath(selectedPath.value) ?? wslDistro, - selectedPath.value, - ); + const converted = yield* windowsPathToWsl(wslDistro, selectedPath.value); return Option.getOrElse(converted, () => selectedPath.value); }), }); +export const toLocalBackendPath = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.TO_LOCAL_BACKEND_PATH_CHANNEL, + payload: Schema.Struct({ backendId: Schema.String, path: Schema.String }), + result: Schema.NullOr(Schema.String), + handler: Effect.fn("desktop.ipc.window.toLocalBackendPath")(function* ({ backendId, path }) { + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const instance = yield* pool.get(DesktopBackendManager.BackendInstanceId(backendId)); + if (Option.isNone(instance)) return null; + const config = yield* instance.value.currentConfig; + if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) return null; + const { runningDistro } = config.value; + if (runningDistro === undefined) return path; + const uncDistro = extractDistroFromUncPath(path); + if (uncDistro !== null && uncDistro.toLowerCase() !== runningDistro.toLowerCase()) return null; + return Option.getOrNull(yield* windowsPathToWsl(runningDistro, path)); + }), +}); + export const pickProjectFavicon = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PICK_PROJECT_FAVICON_CHANNEL, payload: Schema.UndefinedOr(Schema.String), diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 6414743ac3b2f..0dacf5ecaabf2 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -238,6 +238,8 @@ contextBridge.exposeInMainWorld("desktopBridge", { setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro), setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled), pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options), + toLocalBackendPath: (backendId, path) => + ipcRenderer.invoke(IpcChannels.TO_LOCAL_BACKEND_PATH_CHANNEL, { backendId, path }), pickProjectFavicon: (initialPath) => ipcRenderer.invoke(IpcChannels.PICK_PROJECT_FAVICON_CHANNEL, initialPath), pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined), diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index e2fd195b1955c..0787956a72b76 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -4,8 +4,11 @@ import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Redacted from "effect/Redacted"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { afterAll, expect } from "vite-plus/test"; import * as NodeChildProcess from "node:child_process"; @@ -24,6 +27,7 @@ import { buildWslRuntimeProbeScript, parseResolvedPath, parseWslRuntimeRoot, + windowsToWslPathImpl, } from "./DesktopWslEnvironment.ts"; // The install script only fails the way this file cares about when a real shell @@ -552,3 +556,48 @@ describe("makeIsAvailable", () => { }), ); }); + +describe("windowsToWslPathImpl", () => { + it.effect("runs wslpath without a shell so folder names stay one literal argument", () => + Effect.gen(function* () { + const spawned: Array = []; + const stdout = Stream.make(new TextEncoder().encode("/mnt/c/a$b & c;(d)\n")); + const spawner = ChildProcessSpawner.make((command) => { + spawned.push(command); + return Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout, + stderr: Stream.empty, + all: stdout, + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ); + }); + + const converted = yield* windowsToWslPathImpl("Ubuntu", "C:\\a$b & c;(d)").pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + assert.deepStrictEqual(converted, Option.some("/mnt/c/a$b & c;(d)")); + assert.lengthOf(spawned, 1); + const [command] = spawned; + assert(command?._tag === "StandardCommand"); + assert.strictEqual(command.command, "wsl.exe"); + assert.deepStrictEqual(command.args, [ + "-d", + "Ubuntu", + "--exec", + "wslpath", + "-u", + "C:/a$b & c;(d)", + ]); + }), + ); +}); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index fd557c01489a2..4e5e5b423f20e 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -1035,7 +1035,7 @@ const preWarmImpl = ( }), ).pipe(Effect.timeoutOption(PRE_WARM_TIMEOUT), Effect.ignore); -const windowsToWslPathImpl = ( +export const windowsToWslPathImpl = ( distro: string | null, windowsPath: string, ): Effect.Effect, never, ChildProcessSpawner.ChildProcessSpawner> => { @@ -1046,7 +1046,8 @@ const windowsToWslPathImpl = ( const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const command = ChildProcess.make( "wsl.exe", - [...buildDistroArgs(distro), "--", "wslpath", "-u", normalized], + // --exec skips the distro shell, which would expand `$`, `&` or `;` in folder names. + [...buildDistroArgs(distro), "--exec", "wslpath", "-u", normalized], { stdin: "ignore", stdout: "pipe", diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index eb01b8242e2df..00054443d7ca1 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -44,6 +44,7 @@ import { ProviderDriverKind, ProviderInstanceId, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + PRIMARY_LOCAL_ENVIRONMENT_ID, } from "@t3tools/contracts"; import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; @@ -52,7 +53,7 @@ import { formatComposerModelMention } from "@t3tools/client-runtime/composer-mod import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste"; import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; -import { folderDropTarget, resolveDroppedFolderPath } from "./folderDrop"; +import { type FolderDropTarget, folderDropTarget, resolveDroppedFolderPath } from "./folderDrop"; import { splitTransferredFiles } from "./workspaceFileDrop"; import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"; import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits"; @@ -666,6 +667,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) useLayoutEffect(() => { attachmentTargetKeyRef.current = attachmentTargetKey; }); + const composerMountedRef = useRef(true); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tracks unmount so an awaited folder conversion cannot write into ChatView's reused promptRef + useLayoutEffect(() => { + composerMountedRef.current = true; + return () => { + composerMountedRef.current = false; + }; + }, []); const questionPreparations = useQuestionAttachmentPreparation((state) => state.counts); const prompt = composerDraft.prompt; const composerImages = attachmentDraft.images; @@ -2649,23 +2658,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const insertComposerTextAtEndStable = useStableCallback(insertComposerTextAtEnd); - const addComposerFolders = (folders: File[]) => { - const target = folderDropTarget({ - localEnvironmentDisabled: isLocalEnvironmentDisabled(), - environmentId, - primaryEnvironmentId, - connection: readPreparedConnection(environmentId), - isDesktopRenderer: window.desktopBridge !== undefined, - }); - if (target === "remote") { - toastManager.add({ - type: "error", - title: "Folders can only be referenced on a server running on this computer", - }); - return; - } + const insertComposerFolders = async ( + folders: File[], + target: FolderDropTarget, + draftKey: string, + ) => { + const bridge = window.desktopBridge; for (const folder of folders) { - const path = resolveDroppedFolderPath(folder, window.desktopBridge?.getPathForFile); + const droppedPath = resolveDroppedFolderPath(folder, bridge?.getPathForFile); + const path = + droppedPath === null || typeof target === "string" + ? droppedPath + : ((await bridge + ?.toLocalBackendPath(target.wslBackendId, droppedPath) + .catch(() => null)) ?? null); + // ChatView is reused across threads, so a slow conversion must not land in the next draft. + if (!composerMountedRef.current || attachmentTargetKeyRef.current !== draftKey) return; if (path === null) { toastManager.add({ type: "error", @@ -2688,6 +2696,37 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } focusComposer(); }; + + const addComposerFolders = (folders: File[]) => { + const target = folderDropTarget({ + localEnvironmentDisabled: isLocalEnvironmentDisabled(), + environmentId, + primaryEnvironmentId, + connection: readPreparedConnection(environmentId), + isDesktopRenderer: window.desktopBridge !== undefined, + primaryRunsInWsl: + window.desktopBridge + ?.getLocalEnvironmentBootstraps() + .some( + (bootstrap) => + bootstrap.id === PRIMARY_LOCAL_ENVIRONMENT_ID && + typeof bootstrap.runningDistro === "string", + ) === true, + }); + if (target === "remote") { + toastManager.add({ + type: "error", + title: "Folders can only be referenced on a server running on this computer", + }); + return; + } + const draftKey = attachmentTargetKeyRef.current; + // Hold send until every conversion lands, or the folder misses the message. + pendingDraftWork.begin(draftKey); + void insertComposerFolders(folders, target, draftKey).finally(() => + pendingDraftWork.end(draftKey), + ); + }; const addComposerFoldersStable = useStableCallback(addComposerFolders); const onComposerPaste = (event: React.ClipboardEvent) => { diff --git a/apps/web/src/components/chat/folderDrop.test.ts b/apps/web/src/components/chat/folderDrop.test.ts index 6c42bf42cb6dd..7b5485efc008f 100644 --- a/apps/web/src/components/chat/folderDrop.test.ts +++ b/apps/web/src/components/chat/folderDrop.test.ts @@ -19,6 +19,7 @@ const thinClient = { environmentId, primaryEnvironmentId: null, isDesktopRenderer: true, + primaryRunsInWsl: false, }; describe("folderDropTarget", () => { @@ -33,6 +34,17 @@ describe("folderDropTarget", () => { }, "local", ], + [ + "the bundled primary running in WSL", + { + ...thinClient, + localEnvironmentDisabled: false, + primaryEnvironmentId: environmentId, + primaryRunsInWsl: true, + connection: null, + }, + { wslBackendId: "primary" }, + ], [ "a saved loopback server on desktop", { ...thinClient, connection: savedServer("http://127.0.0.1:3773") }, @@ -50,8 +62,8 @@ describe("folderDropTarget", () => { ], [ "a desktop WSL backend", - { ...thinClient, connection: savedServer("http://127.0.0.1:3774", "local:wsl-ubuntu") }, - "remote", + { ...thinClient, connection: savedServer("http://127.0.0.1:3774", "local:wsl:Ubuntu") }, + { wslBackendId: "wsl:Ubuntu" }, ], [ "an SSH forward on loopback", @@ -77,6 +89,6 @@ describe("folderDropTarget", () => { ], ["an unprepared connection", { ...thinClient, connection: null }, "remote"], ] as const)("targets %s", (_name, input, expected) => { - expect(folderDropTarget(input)).toBe(expected); + expect(folderDropTarget(input)).toEqual(expected); }); }); diff --git a/apps/web/src/components/chat/folderDrop.ts b/apps/web/src/components/chat/folderDrop.ts index df4089589aa2d..200cd84cd7955 100644 --- a/apps/web/src/components/chat/folderDrop.ts +++ b/apps/web/src/components/chat/folderDrop.ts @@ -1,31 +1,33 @@ import type { PreparedConnection } from "@t3tools/client-runtime/connection"; -import type { EnvironmentId } from "@t3tools/contracts"; +import { PRIMARY_LOCAL_ENVIRONMENT_ID, type EnvironmentId } from "@t3tools/contracts"; -import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal"; +import { desktopLocalBackendId, isDesktopLocalConnectionTarget } from "~/connection/desktopLocal"; import { isLoopbackHostname } from "~/environments/primary/target"; +export type FolderDropTarget = "local" | "remote" | { readonly wslBackendId: string }; + export function folderDropTarget(input: { localEnvironmentDisabled: boolean; environmentId: EnvironmentId; primaryEnvironmentId: EnvironmentId | null; connection: Pick | null; isDesktopRenderer: boolean; -}): "local" | "remote" { + primaryRunsInWsl: boolean; +}): FolderDropTarget { if ( !input.localEnvironmentDisabled && input.primaryEnvironmentId !== null && input.environmentId === input.primaryEnvironmentId ) { - return "local"; + return input.primaryRunsInWsl ? { wslBackendId: PRIMARY_LOCAL_ENVIRONMENT_ID } : "local"; } - return input.isDesktopRenderer && - input.connection !== null && - isSavedLoopbackConnection(input.connection) - ? "local" - : "remote"; + if (!input.isDesktopRenderer || input.connection === null) return "remote"; + const backendId = desktopLocalBackendId(input.connection.target); + if (backendId?.startsWith("wsl:")) return { wslBackendId: backendId }; + return isSavedLoopbackConnection(input.connection) ? "local" : "remote"; } -// A direct saved connection to loopback shares the desktop's filesystem; WSL backends and SSH forwards do not. +// A direct saved connection to loopback shares the desktop's filesystem; SSH forwards do not. function isSavedLoopbackConnection({ target, httpBaseUrl, diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 83ed8a813ece4..c5f9e46bb2594 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -1127,6 +1127,8 @@ export interface DesktopBridge { setWslDistro: (distro: string | null) => Promise; setWslOnly: (enabled: boolean) => Promise; pickFolder: (options?: PickFolderOptions) => Promise; + /** Maps a Windows path to the one a local backend (`primary` or `wsl:…`) sees; null when it cannot. */ + toLocalBackendPath: (backendId: string, windowsPath: string) => Promise; pickProjectFavicon: (initialPath?: string) => Promise; pickThemeFiles: () => Promise; setTheme: (theme: DesktopTheme) => Promise; From be78ee494019ac6bed347f7d622132eadf2bae12 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 21:04:50 -0800 Subject: [PATCH 004/524] fix(server): stopping an agent's server no longer wakes Codex as if it crashed (#36501) --- .../Adapters/CodexAdapterV2.test.ts | 89 ++++++++++++ .../Adapters/CodexAdapterV2.testkit.ts | 2 + .../Adapters/CodexAdapterV2.ts | 32 +++++ apps/server/src/preview/PortScanner.test.ts | 28 +++- apps/server/src/preview/PortScanner.ts | 128 +++++++++++++++++- .../src/provider/Drivers/CodexDriver.test.ts | 2 + .../provider/ProviderInstanceRegistry.test.ts | 3 +- 7 files changed, 280 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 0fc1b9a2bf82d..97fb058bf092f 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1382,6 +1382,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { const changes = yield* makeChangeSignal; const continuationRequests: Array = []; + const commandStopWatchers: Array = []; const driver = yield* CodexReplay.makeReplayDriver( withConfigReads(transcript), beforeEmitInbound === undefined ? {} : { beforeEmitInbound }, @@ -1445,6 +1446,10 @@ describe("CodexAdapterV2 post-settle continuation", () => { continuationRequests.push(request); }).pipe(Effect.andThen(changes.notify)), }, + watchCommandStops: (watcher) => + Effect.sync(() => { + commandStopWatchers.push(watcher); + }), }); const threadId = ThreadId.make(`thread-${transcript.scenario}`); const runtime = yield* adapter.openSession({ @@ -1504,6 +1509,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { serverConfig, events, continuationRequests, + commandStopWatchers, terminalEvents, subagentUpdates, hasPendingBackgroundWork, @@ -5287,6 +5293,89 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect.each([ + { stop: "onStop", woken: ["CODEX_BG_OTHER_DONE"] }, + { stop: "onStopAbandoned", woken: ["CODEX_BG_OTHER_DONE", "CODEX_BG_WAKE_DONE"] }, + ] as const)("wakes for every command but the one the user stopped ($stop)", ({ stop, woken }) => + Effect.gen(function* () { + // Same command and start as the stopped one, and it finishes first. + const other = (status: "inProgress" | "completed") => ({ + ...backgroundCommandItem(status), + id: "call-codex-bg-other", + processId: "4243", + aggregatedOutput: status === "completed" ? "CODEX_BG_OTHER_DONE\n" : null, + }); + const [started, ...settle] = backgroundExecTranscript.entries.slice(-4, -1); + const inbound = (label: string, method: string, item: Record) => ({ + type: "emit_inbound" as const, + label, + frame: { + method, + params: { item, threadId: BG_NATIVE_THREAD, turnId: BG_NATIVE_TURN }, + }, + }); + const released = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: `codex-bg-user-stop-${stop}`, + entries: [ + ...backgroundExecTranscript.entries.slice(0, -4), + started!, + inbound("item/started/other", "item/started", other("inProgress")), + ...settle, + inbound("item/completed/other", "item/completed", other("completed")), + inbound("item/completed/stopped", "item/completed", backgroundCommandItem("completed")), + ], + }), + undefined, + undefined, + undefined, + (entry) => + entry.label === "item/completed/other" ? Deferred.await(released) : Effect.void, + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-command-user-stop"), + text: BG_PROMPT, + }), + ); + yield* harness.firstTerminal; + const [watcher] = harness.commandStopWatchers; + assert.equal(watcher?.variable, "CODEX_TOOL_CALL_ID"); + yield* watcher!.onStop("not-a-command-of-this-session"); + yield* watcher!.onStop(BG_COMMAND_ITEM); + if (stop === "onStopAbandoned") yield* watcher!.onStopAbandoned(BG_COMMAND_ITEM); + yield* Deferred.succeed(released, undefined); + yield* harness.until( + () => + harness.events.filter( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.status === "completed", + ).length === 2 && harness.continuationRequests.length === woken.length, + ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + assert.deepEqual( + harness.continuationRequests.map((request) => request.detail?.trim().split("\n").at(-1)), + [...woken], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("wakes with well-formed text when the cuts split an emoji", () => Effect.gen(function* () { const harness = yield* makeCodexReplayHarness( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts index 4cf14c195453f..a2ad18b48ed3d 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts @@ -13,6 +13,7 @@ import * as ServerConfig from "../../config.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import { ProviderAdapterDriverCreateError } from "@t3tools/provider-core/server/adapterDriver"; +import * as PortScanner from "../../preview/PortScanner.ts"; import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts"; import { makeReplayServerConfig, @@ -142,6 +143,7 @@ export function layer(input: { NodeServices.layer, NodeCrypto.layer, IdAllocator.layer, + PortScanner.layerTest, ), ), ); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index e26b3dc5860c2..b6673c0b29ec7 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1556,6 +1556,8 @@ function readCodexProtocolPath(value: unknown, ...path: ReadonlyArray): return current; } +/** Codex sets this on every command it starts, to that command's item id. */ +const CODEX_COMMAND_ITEM_ENV = "CODEX_TOOL_CALL_ID"; const CODEX_THREAD_ENV_CONFIG_KEY = `shell_environment_policy.set.${PortScanner.AGENT_THREAD_ENV}`; /** @@ -1766,6 +1768,7 @@ export type CodexAdapterV2DriverEnv = | IdAllocator.IdAllocatorV2 | McpProviderSessions.McpProviderSessions | Path.Path + | PortScanner.PortDiscovery | ServerConfig; export const createCodexAdapterV2 = Effect.fn("CodexAdapterV2.createCodexAdapterV2")(function* ( @@ -1781,6 +1784,7 @@ export const createCodexAdapterV2 = Effect.fn("CodexAdapterV2.createCodexAdapter const fileSystem = yield* FileSystem.FileSystem; const hostEnvironment = yield* HostProcess.Environment; const idAllocator = yield* IdAllocator.IdAllocatorV2; + const portDiscovery = yield* PortScanner.PortDiscovery; const serverConfig = yield* ServerConfig; const homeLayout = yield* resolveCodexHomeLayout(config); @@ -1813,6 +1817,7 @@ export const createCodexAdapterV2 = Effect.fn("CodexAdapterV2.createCodexAdapter idAllocator, serverConfig, continuationRequests, + watchCommandStops: portDiscovery.watchAgentCommandStops, ...hooks, }); }); @@ -1839,6 +1844,8 @@ export interface CodexAdapterV2Options { request: ProviderContinuationRequests.ProviderContinuationRequest, ) => Effect.Effect; }; + /** Omitting this reports a command the user stopped as one that finished by itself. */ + readonly watchCommandStops?: PortScanner.PortDiscovery["Service"]["watchAgentCommandStops"]; } export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( @@ -2095,6 +2102,26 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( new Map>(), ); const interruptingNativeTurns = yield* Ref.make(new Set()); + // Running commands the user is stopping outside a turn interrupt; their exit wakes nobody. + const userStoppedCommandItemIds = yield* Ref.make(new Set()); + if (adapterOptions.watchCommandStops !== undefined) { + yield* adapterOptions.watchCommandStops({ + variable: CODEX_COMMAND_ITEM_ENV, + onStop: Effect.fn("CodexAdapterV2.onCommandStop")(function* (itemId) { + const running = yield* Ref.get(runningCommandItemsByTurn); + if (![...running.values()].some((items) => items.has(itemId))) return; + yield* Ref.update(userStoppedCommandItemIds, (current) => + new Set(current).add(itemId), + ); + }), + onStopAbandoned: (itemId) => + Ref.update(userStoppedCommandItemIds, (current) => { + const updated = new Set(current); + updated.delete(itemId); + return updated; + }), + }); + } const terminalizedNonCompletedNativeTurns = yield* Ref.make(new Set()); // Keep the stream open until descendants settle to avoid stranding child projections. const deferredRootTerminals = yield* Ref.make(new Map()); @@ -5417,6 +5444,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( // Other tools can retain the context after thread closure. if (context.closedCommandItemIds?.has(payload.item.id)) return; const turnDrained = yield* clearRunningCommandItem(payload.turnId, payload.item.id); + const userStopped = yield* Ref.modify(userStoppedCommandItemIds, (current) => { + const updated = new Set(current); + return [updated.delete(payload.item.id), updated] as const; + }); const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item); yield* emitProviderEvent({ type: "node.updated", @@ -5432,6 +5463,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if ( context.subagent === null && continuationRequests !== undefined && + !userStopped && !(yield* Ref.get(interruptingNativeTurns)).has(payload.turnId) ) { const alreadyOffered = yield* Ref.modify( diff --git a/apps/server/src/preview/PortScanner.test.ts b/apps/server/src/preview/PortScanner.test.ts index db13a996255ea..1ed544910b1bc 100644 --- a/apps/server/src/preview/PortScanner.test.ts +++ b/apps/server/src/preview/PortScanner.test.ts @@ -936,6 +936,17 @@ effectIt.effect("stops only a job's own process group", () => for (const pid of [20, 210, 500, 999]) { expect(PortScanner.stoppableProcessGroup(table, pid, serverPid)).toBeNull(); } + // The tool shell is the command; its `npm run dev &` job only inherited the name. + const variables = new Map([ + [200, new Map()], + [300, new Map([["COMMAND", "a"]])], + [400, new Map([["COMMAND", "a"]])], + ]); + expect([...PortScanner.agentCommandsInGroup(variables, table.get(300)!)]).toEqual([ + ["COMMAND", "a"], + ]); + expect(PortScanner.agentCommandsInGroup(variables, table.get(400)!).size).toBe(0); + expect(PortScanner.agentCommandsInGroup(variables, table.get(600)!).size).toBe(0); }), ); @@ -949,6 +960,8 @@ server.listen(0, "127.0.0.1", () => { }); `; +const AGENT_COMMAND_ENV = "T3CODE_TEST_AGENT_COMMAND"; + /** * A real HTML server with an agent's environment, started the way an agent's tool shell starts a * job: under a detached shell with job control, in a group of its own. Release kills only the pids @@ -966,7 +979,12 @@ const agentServer = () => // dash ignores `set -m` without a terminal; bash, like agent tool shells, honors it. const child = NodeChildProcess.spawn( "bash", - ["-c", 'set -m; "$0" -e "$1" & wait', process.execPath, AGENT_SERVER_SCRIPT], + [ + "-c", + `set -m; ${AGENT_COMMAND_ENV}=command-live "$0" -e "$1" & wait`, + process.execPath, + AGENT_SERVER_SCRIPT, + ], { detached: true, env, stdio: ["ignore", "pipe", "ignore"] }, ); const exited = new Promise((resolve) => child.once("exit", () => resolve())); @@ -1004,6 +1022,12 @@ effectIt.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( Effect.sync(release), ); const job = yield* agentServer(); + const stops: Array = []; + yield* scanner.watchAgentCommandStops({ + variable: AGENT_COMMAND_ENV, + onStop: (command) => Effect.sync(() => stops.push([command, isRunning(job.pid)])), + onStopAbandoned: () => Effect.die("the signal reached the job"), + }); expect(yield* scanner.scan()).toEqual( expect.arrayContaining([ @@ -1017,8 +1041,10 @@ effectIt.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( const unlisted = yield* Effect.flip(scanner.stopServer({ pid: process.pid, port: job.port })); expect(unlisted.reason).toBe("not-found"); + expect(stops).toEqual([]); yield* scanner.stopServer({ pid: job.pid, port: job.port }); + expect(stops).toEqual([["command-live", true]]); // The shell waits on its job, so it exits once the job has. yield* Effect.promise(() => job.exited); expect(isRunning(job.pid)).toBe(false); diff --git a/apps/server/src/preview/PortScanner.ts b/apps/server/src/preview/PortScanner.ts index 78f134fc1b813..12421453ade56 100644 --- a/apps/server/src/preview/PortScanner.ts +++ b/apps/server/src/preview/PortScanner.ts @@ -56,6 +56,13 @@ export class PortDiscovery extends Context.Service< * outside Effect. */ readonly trackAgent: () => () => void; + /** + * Tells an agent CLI's adapter which of its commands a user stop is about to signal, so the + * exit is not reported to the agent as the command finishing by itself. + */ + readonly watchAgentCommandStops: ( + watcher: AgentCommandStopWatcher, + ) => Effect.Effect; /** Stops a listed server's process group, never this server, an agent CLI, or a shell. */ readonly stopServer: ( input: PreviewStopLocalServerInput, @@ -69,6 +76,14 @@ export class PortDiscovery extends Context.Service< */ export const AGENT_THREAD_ENV = "T3CODE_THREAD_ID"; +export interface AgentCommandStopWatcher { + /** The variable the CLI sets on each command it starts, naming that command. */ + readonly variable: string; + readonly onStop: (command: string) => Effect.Effect; + /** The signal never reached the command, so it is still running or ended by itself. */ + readonly onStopAbandoned: (command: string) => Effect.Effect; +} + /** `0` turns off listener discovery; configured preview URLs are still probed. */ const PORT_DISCOVERY_ENV = "T3CODE_PORT_DISCOVERY"; @@ -382,6 +397,42 @@ const parsePsEnvironmentThreads = (raw: string): ReadonlyMap/environ` on NUL, or the environment macOS `ps -E` appends on spaces. */ +const parseEnvironmentVariables = ( + raw: string, + separator: "\0" | RegExp, + names: ReadonlyArray, +): ReadonlyMap => { + const variables = new Map(); + for (const entry of raw.split(separator)) { + const name = names.find((candidate) => entry.startsWith(`${candidate}=`)); + if (name !== undefined && !variables.has(name)) { + variables.set(name, entry.slice(name.length + 1)); + } + } + return variables; +}; + +/** + * The agent commands that signaling a group stops, by the variable naming each. A CLI starts a + * command as a group leader and names it in the command's environment, which the CLI itself does + * not carry. A job the command moved to its own group inherits the name from its parent, and + * stopping that job does not end the command. + */ +export const agentCommandsInGroup = ( + variables: ReadonlyMap>, + leader: ProcessTableRow, +): ReadonlyMap => { + const commands = new Map(); + const parent = variables.get(leader.ppid); + // An unreadable parent cannot rule out an inherited name. + if (parent === undefined) return commands; + for (const [name, command] of variables.get(leader.pid) ?? []) { + if (command !== "" && parent.get(name) !== command) commands.set(name, command); + } + return commands; +}; + const parseProcessTable = (raw: string): ReadonlyMap => { const rows = new Map(); for (const line of raw.split("\n")) { @@ -476,6 +527,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() { // environment, so a pid is read once while it listens. Cleared while no client retains the // scanner, since unscanned pids can be reused. const agentThreadsRef = yield* Ref.make>(new Map()); + const agentCommandStopWatchers = new Set(); let runningAgents = 0; // An agent that exited, or a cache cleared with a marked listener, owes one listener read: the // servers it left may still run. So does startup, for agents that ran before a restart. @@ -1016,6 +1068,62 @@ export const make = Effect.gen(function* PortDiscoveryMake() { }; }; + const watchAgentCommandStops: PortDiscovery["Service"]["watchAgentCommandStops"] = (watcher) => + Effect.acquireRelease( + Effect.sync(() => { + agentCommandStopWatchers.add(watcher); + }), + () => Effect.sync(() => agentCommandStopWatchers.delete(watcher)), + ); + + /** Each process's launch values for `names`; a process that cannot be read is left out. */ + const readEnvironmentVariables = Effect.fn("PortDiscovery.readEnvironmentVariables")(function* ( + pids: ReadonlyArray, + names: ReadonlyArray, + ) { + if (hostPlatform === "linux") { + const read = yield* Effect.forEach(pids, (pid) => + fileSystem.readFileString(`/proc/${pid}/environ`).pipe( + Effect.map((raw) => [pid, parseEnvironmentVariables(raw, "\0", names)] as const), + Effect.option, + ), + ); + return new Map(read.flatMap(Option.toArray)); + } + const result = yield* processRunner + .run({ + command: "ps", + args: ["-E", "-ww", "-o", "pid=,command=", "-p", pids.join(",")], + timeout: Duration.millis(PS_TIMEOUT_MS), + maxOutputBytes: PS_MAX_OUTPUT_BYTES, + }) + .pipe(Effect.option); + const variables = new Map>(); + for (const line of Option.isSome(result) ? result.value.stdout.split("\n") : []) { + const match = /^\s*(\d+)\s(.*)$/.exec(line); + if (match) { + variables.set(Number(match[1]), parseEnvironmentVariables(match[2]!, /\s+/, names)); + } + } + return variables; + }); + + const agentCommandStops = Effect.fn("PortDiscovery.agentCommandStops")(function* ( + leader: ProcessTableRow | undefined, + ) { + const watchers = [...agentCommandStopWatchers]; + if (leader === undefined || watchers.length === 0) return []; + const names = [...new Set(watchers.map((watcher) => watcher.variable))]; + const commands = agentCommandsInGroup( + yield* readEnvironmentVariables([leader.pid, leader.ppid], names), + leader, + ); + return watchers.flatMap((watcher) => { + const command = commands.get(watcher.variable); + return command === undefined ? [] : [{ watcher, command }]; + }); + }); + // Fails when `ps` does, so an empty table never reads as every process having exited. const readProcessTable = Effect.suspend(() => processRunner.run({ @@ -1076,7 +1184,19 @@ export const make = Effect.gen(function* PortDiscoveryMake() { : Effect.fail(new PreviewStopLocalServerError({ reason: "signal-failed", cause })); } }); - if (!(yield* signalGroup("SIGTERM"))) return; + // Told before the signal, since the CLI can report the exit before a later step runs. + const commandStops = yield* agentCommandStops(table.get(group)); + yield* Effect.forEach(commandStops, ({ watcher, command }) => watcher.onStop(command), { + discard: true, + }); + const abandonCommandStops = Effect.forEach( + commandStops, + ({ watcher, command }) => watcher.onStopAbandoned(command), + { discard: true }, + ); + if (!(yield* signalGroup("SIGTERM").pipe(Effect.tapError(() => abandonCommandStops)))) { + return yield* abandonCommandStops; + } // While one of the group's original members is still in it, the group has not been reused, // so SIGKILL goes only to the job that ignored SIGTERM. const members = [...table.values()].filter((row) => row.pgid === group).map((row) => row.pid); @@ -1103,6 +1223,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() { registerTerminalProcesses, unregisterTerminal, trackAgent, + watchAgentCommandStops, stopServer, }); }).pipe(Effect.withSpan("PortDiscovery.make")); @@ -1110,4 +1231,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() { export const layer = Layer.effect(PortDiscovery, make); /** A scanner that tracks nothing, for tests that build provider runners without a host. */ -export const layerTest = Layer.mock(PortDiscovery)({ trackAgent: () => () => undefined }); +export const layerTest = Layer.mock(PortDiscovery)({ + trackAgent: () => () => undefined, + watchAgentCommandStops: () => Effect.void, +}); diff --git a/apps/server/src/provider/Drivers/CodexDriver.test.ts b/apps/server/src/provider/Drivers/CodexDriver.test.ts index 6ce377a74a1e4..01d44f3d3d1e8 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.test.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.test.ts @@ -42,6 +42,7 @@ import { CodexDriver } from "./CodexDriver.ts"; import * as CodexAdapterV2 from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as PortScanner from "../../preview/PortScanner.ts"; import * as ProviderCredentialStore from "../ProviderCredentialStore.ts"; import * as ProviderHostLive from "../ProviderHostLive.ts"; @@ -51,6 +52,7 @@ const layerDeps = ServerConfig.layerTest(process.cwd(), { Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Layer.provideMerge(IdAllocator.layer), Layer.provideMerge(McpProviderSessions.layer), + Layer.provideMerge(PortScanner.layerTest), Layer.provideMerge( Layer.mock(CodexAdapterV2.CodexAppServerClientFactory)({ open: () => Effect.die("Maintenance resolution must not open a Codex session"), diff --git a/apps/server/src/provider/ProviderInstanceRegistry.test.ts b/apps/server/src/provider/ProviderInstanceRegistry.test.ts index 707275afc97d2..ce6416332bae0 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.test.ts @@ -212,7 +212,8 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { ); const layerBase = ProviderHostLive.layer.pipe(Layer.provideMerge(layerBaseDeps)); const layerTest = ProviderOrchestrationAdapterInfrastructure.layer.pipe( - Layer.provide(Layer.merge(PortScanner.layerTest, SqlitePersistence.layerMemory)), + Layer.provide(SqlitePersistence.layerMemory), + Layer.provideMerge(PortScanner.layerTest), Layer.provideMerge(layerBase), ); From d9619adc0922028dd32d0d0c8aed09d8a531993a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 21:05:54 -0800 Subject: [PATCH 005/524] fix(web): stop offering T3 Connect routes for the desktop's own WSL backend (#27479) --- ...oudEnvironmentConnectList.browser.test.tsx | 110 ++++++++++++++++++ .../cloud/CloudEnvironmentConnectList.tsx | 11 +- 2 files changed, 120 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/components/cloud/CloudEnvironmentConnectList.browser.test.tsx diff --git a/apps/web/src/components/cloud/CloudEnvironmentConnectList.browser.test.tsx b/apps/web/src/components/cloud/CloudEnvironmentConnectList.browser.test.tsx new file mode 100644 index 0000000000000..7c2df55289561 --- /dev/null +++ b/apps/web/src/components/cloud/CloudEnvironmentConnectList.browser.test.tsx @@ -0,0 +1,110 @@ +import { BearerConnectionTarget } from "@t3tools/client-runtime/connection"; +import type { Discovery } from "@t3tools/client-runtime/relay"; +import { EnvironmentId } from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { render } from "../../../test/render"; + +const testState = vi.hoisted(() => ({ + discovered: [] as Array, +})); + +vi.mock(import("~/state/environments"), async (original) => ({ + ...(await original()), + useRelayEnvironmentDiscovery: (() => ({ + environments: new Map( + testState.discovered.map((environment) => [ + environment.environment.environmentId, + environment, + ]), + ), + refreshing: false, + offline: false, + error: Option.none(), + })) as never, +})); +vi.mock(import("~/state/use-atom-command"), async (original) => ({ + ...(await original()), + useAtomCommand: (() => () => Promise.resolve({ _tag: "Success" })) as never, +})); + +import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList"; + +function discovered( + environmentId: EnvironmentId, + label: string, +): Discovery.RelayDiscoveredEnvironment { + return { + environment: { + environmentId, + label, + endpoint: { + httpBaseUrl: `https://${environmentId}.relay.test`, + wsBaseUrl: `wss://${environmentId}.relay.test`, + providerKind: "t3_relay", + }, + linkedAt: "2026-10-01T00:00:00.000Z", + }, + availability: "online", + status: Option.none(), + error: Option.none(), + }; +} + +function saved(environmentId: EnvironmentId, label: string, connectionId: string) { + return { + environmentId, + entry: { target: new BearerConnectionTarget({ environmentId, label, connectionId }) }, + connection: { phase: "connected", error: null, traceId: null }, + relayManaged: false, + serverConfig: null, + } as const; +} + +const primaryEnvironmentId = EnvironmentId.make("primary"); +const wslEnvironmentId = EnvironmentId.make("wsl-ubuntu"); +const laptopEnvironmentId = EnvironmentId.make("laptop"); + +function setup(discoveredEnvironments: Array) { + testState.discovered = discoveredEnvironments; +} + +describe("CloudEnvironmentConnectRows", () => { + it("does not offer a T3 Connect route for the desktop's own WSL backend", async () => { + setup([ + discovered(primaryEnvironmentId, "This PC"), + discovered(wslEnvironmentId, "Ubuntu (WSL)"), + discovered(laptopEnvironmentId, "Laptop"), + ]); + await using screen = await render( + , + ); + + await expect.element(screen.getByText("Laptop")).toBeInTheDocument(); + await expect.element(screen.getByText("Ubuntu (WSL)")).not.toBeInTheDocument(); + await expect.element(screen.getByRole("button", { name: "Add route" })).toBeInTheDocument(); + }); + + it("shows the empty state when the desktop's own WSL backend is the only saved environment", async () => { + setup([ + discovered(primaryEnvironmentId, "This PC"), + discovered(wslEnvironmentId, "Ubuntu (WSL)"), + ]); + await using screen = await render( + No environments

} + />, + ); + + await expect.element(screen.getByText("No environments")).toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx b/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx index c411fb81be5cb..8c3df53380749 100644 --- a/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx +++ b/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx @@ -1,5 +1,6 @@ import { findErrorTraceId } from "@t3tools/client-runtime/errors"; import { + type ConnectionTarget, type EnvironmentConnectionPresentation, RelayConnectionRegistration, RelayConnectionTarget, @@ -24,6 +25,7 @@ import * as Option from "effect/Option"; import { type ReactNode, useEffect, useEffectEvent, useState } from "react"; import { environmentCatalog } from "~/connection/catalog"; +import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal"; import { cn } from "~/lib/utils"; import { relayEnvironmentDiscovery } from "~/state/relay"; import { useRelayEnvironmentDiscovery } from "~/state/environments"; @@ -49,6 +51,7 @@ function discoveredCompatibilityError( export interface SavedCloudEnvironmentConnection { readonly environmentId: EnvironmentId; + readonly entry: { readonly target: ConnectionTarget }; readonly connection: EnvironmentConnectionPresentation; readonly relayManaged: boolean; readonly serverConfig?: Pick | null; @@ -122,6 +125,11 @@ export function CloudEnvironmentConnectRows({ .filter((environment) => !environment.relayManaged) .map((environment) => environment.environmentId), ); + const desktopLocalIds = new Set( + savedEnvironments + .filter((environment) => isDesktopLocalConnectionTarget(environment.entry.target)) + .map((environment) => environment.environmentId), + ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- fetches relay discovery when its inputs change, unless hidden polling covers it, and reports readiness useEffect(() => { @@ -189,6 +197,7 @@ export function CloudEnvironmentConnectRows({ // Omit machines saved over other routes; onboarding selection must not add a T3 Connect route. const isVisibleEnvironment = (environmentId: EnvironmentId) => environmentId !== primaryEnvironmentId && + !desktopLocalIds.has(environmentId) && (showSavedEnvironments || !savedById.has(environmentId)) && !(selection && savedWithoutRelay.has(environmentId)); const visibleEnvironments = [...environmentsState.environments.values()].filter( @@ -269,7 +278,7 @@ export function CloudEnvironmentConnectRows({ }; }, [shouldRefreshWhileEmpty]); - const standalone = showSavedEnvironments || savedEnvironments.length === 0; + const standalone = showSavedEnvironments || savedEnvironments.length === desktopLocalIds.size; if ( !refreshWhileEmpty && From a4723422e7dbb48089db78023fc450d8588a54de Mon Sep 17 00:00:00 2001 From: nibarAhmed <61316519+nibarAhmed@users.noreply.github.com> Date: Sat, 14 Nov 2026 06:07:28 +0100 Subject: [PATCH 006/524] fix(web): screen readers no longer say "Message" twice entering the composer (#26692) Co-authored-by: nibarAhmed Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- apps/web/src/components/ChatView.tsx | 7 +++++-- apps/web/src/lib/workspaceFocus.ts | 5 ++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 9242d934169f1..abc4cbdbf27a8 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -744,7 +744,6 @@ export default function ChatView(props: ChatViewProps) { ] = useState>({}); const legendListRef = useRef(null); const conversationArea = workspaceAreaProps("conversation", 1, "Conversation"); - const composerArea = workspaceAreaProps("composer", 2, "Message input"); const [composerOverlayElement, setComposerOverlayElement] = useState(null); const [composerTimelineInset, setComposerTimelineInset] = useState(0); const composerTimelineInsetRef = useRef(0); @@ -3528,7 +3527,11 @@ export default function ChatView(props: ChatViewProps) {
{ setComposerOverlayElement(overlay); attachFollowComposerOverlay(overlay); diff --git a/apps/web/src/lib/workspaceFocus.ts b/apps/web/src/lib/workspaceFocus.ts index 05dd8281dca05..37b3644d4ca06 100644 --- a/apps/web/src/lib/workspaceFocus.ts +++ b/apps/web/src/lib/workspaceFocus.ts @@ -9,12 +9,11 @@ const FOCUSABLE_SELECTOR = 'button:not(:disabled), a[href], input:not(:disabled), textarea:not(:disabled), select:not(:disabled), [contenteditable="true"], [tabindex]'; /** Props that make an element one stop in the F6 cycle; `order` sets its place in the cycle. */ -export function workspaceAreaProps(name: string, order: number, label: string) { +export function workspaceAreaProps(name: string, order: number, label?: string) { return { "data-workspace-area": name, "data-workspace-order": order, - "aria-label": label, - role: "region", + ...(label ? { "aria-label": label, role: "region" } : {}), tabIndex: -1, } as const; } From a35fd811749c2b65d917652cbdb90b28d65b2e0c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 21:28:59 -0800 Subject: [PATCH 007/524] fix(server): settlement sweep reads quiet open pull requests every 5 minutes (#34953) --- .../PullRequestSyncReactor.ts | 4 +- .../ThreadSettlementService.test.ts | 148 +++++++++++++++++- .../ThreadSettlementService.ts | 40 ++++- 3 files changed, 185 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts index b654364d3a7fb..d21b607f1bf58 100644 --- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts @@ -42,8 +42,8 @@ const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000; // Every server polls every open linked pull request, and most of them sit untouched for days. // One nobody has updated for QUIET_AFTER_MS is read on the quiet cadence instead of each sweep; // requested refreshes, watches and a host CLI's merge command still read it at once. -const QUIET_AFTER_MS = 30 * 60 * 1_000; -const QUIET_SYNC_INTERVAL_MS = 5 * 60 * 1_000; +export const QUIET_AFTER_MS = 30 * 60 * 1_000; +export const QUIET_SYNC_INTERVAL_MS = 5 * 60 * 1_000; // A pull request closed this long ago is rarely reopened, so the sweep stops reading it, as it // does merged ones. A reader that sees it open, or a requested refresh, still reads it at once. const CLOSED_FINAL_AFTER_MS = 24 * 60 * 60 * 1_000; diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index 4895066ce31c6..e5e5f97416d23 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -602,6 +602,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: const settingsReadCount = yield* Ref.make(0); const settingsChanges = yield* PubSub.unbounded(); const mergedPullRequests = yield* PubSub.unbounded(); + const pullRequestRefreshes = yield* PubSub.unbounded(); const commands = yield* Ref.make>([]); const branchCalls = yield* Ref.make< ReadonlyArray<{ readonly cwd: string; readonly branch: string }> @@ -737,6 +738,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe( Effect.map((subscription) => Stream.fromSubscription(subscription)), ), + subscribeRefreshes: Stream.fromPubSub(pullRequestRefreshes), }), Layer.succeed(ServerSettings.ServerSettingsService, serverSettings), Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)), @@ -775,6 +777,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: observedEvents, publishEvent: (event: OrchestrationV2DomainEvent) => PubSub.publish(domainEvents, event), updateSettings, + publishRefresh: PubSub.publish(pullRequestRefreshes, 1), publishMerge: PubSub.publish(mergedPullRequests, { projectId: PROJECT_ID, repository: "owner/repository", @@ -1623,20 +1626,40 @@ describe("ThreadSettlementServiceV2 worker", () => { }), ); - it.effect("settles an unlinked branch thread its agent merged from a shell, past the cache", () => + it.effect.each([ + { kind: "an unlinked", linked: false }, + { kind: "a quiet linked", linked: true }, + ])("settles $kind branch thread its agent merged from a shell, past the cache", ({ linked }) => Effect.gen(function* () { yield* TestClock.setTime(Date.parse(NOW)); - const settled = yield* Deferred.make(); const thread = makeThread("shell-merged", { branch: "saved-feature", latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + ...(linked + ? { + branchPullRequest: { + projectId: PROJECT_ID, + repository: "owner/repository", + number: 42, + url: "https://example.test/owner/repository/pull/42", + }, + } + : {}), }); const fixture = yield* makeHarness({ snapshot: makeSnapshot([thread]), // The host already merged it; only a fresh read sees that past the cached open lookup. branchPullRequest: (_input, lookupOptions) => Effect.succeed(makeBranchPullRequest(lookupOptions?.refresh ? "merged" : "open")), - onDispatch: () => Deferred.succeed(settled, undefined), + pullRequestSummary: (input, readOptions) => + Effect.succeed({ + ...makePullRequestSummary({ + ...input, + state: readOptions?.bypassCache ? "merged" : "open", + updatedAt: DateTime.formatIso(DateTime.makeUnsafe(Date.parse(NOW) - 2 * DAY_MS)), + }), + ...(readOptions?.bypassCache ? { mergedAt: NOW } : {}), + }), }); const at = DateTime.makeUnsafe(NOW); const runId = RunId.make("run:shell-merged"); @@ -1681,7 +1704,8 @@ describe("ThreadSettlementServiceV2 worker", () => { input: "gh pr merge 42 --squash", }, }); - yield* Deferred.await(settled); + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; assert.deepStrictEqual( (yield* Ref.get(fixture.commands)).map((command) => command.threadId), [thread.id], @@ -1728,6 +1752,122 @@ describe("ThreadSettlementServiceV2 worker", () => { }), ); + it.effect("reads a quiet open branch pull request every 5 minutes", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([ + makeThread("active-branch", { + branch: "feature", + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + branchPullRequest: { + projectId: PROJECT_ID, + repository: "owner/repository", + number: 42, + url: "https://example.test/owner/repository/pull/42", + }, + }), + ]), + pullRequestSummary: (input) => + Effect.succeed( + makePullRequestSummary({ + ...input, + state: "open", + updatedAt: DateTime.formatIso(DateTime.makeUnsafe(Date.parse(NOW) - 2 * DAY_MS)), + }), + ), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1); + + for (let minute = 0; minute < 4; minute++) { + yield* TestClock.adjust("1 minute"); + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + } + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1); + + yield* TestClock.adjust("1 minute"); + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2); + + // An app merge the host completes later sends only a refresh; reads stay on the minute + // cadence while the pull request still reads open. + yield* fixture.publishRefresh; + for (const expected of [3, 4]) { + yield* TestClock.adjust("1 minute"); + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, expected); + } + }).pipe(Effect.provide(fixture.layer)); + }), + ); + + it.effect.each([ + { when: "after", mergeDuringRead: false }, + { when: "during", mergeDuringRead: true }, + ])( + "a merge $when a quiet pull request's read, while its thread is not a candidate, rereads it next sweep", + ({ mergeDuringRead }) => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const thread = makeThread("busy-branch", { + branch: "feature", + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + branchPullRequest: { + projectId: PROJECT_ID, + repository: "owner/repository", + number: 42, + url: "https://example.test/owner/repository/pull/42", + }, + }); + const readStarted = yield* Deferred.make(); + const releaseRead = yield* Deferred.make(); + if (!mergeDuringRead) yield* Deferred.succeed(releaseRead, undefined); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([thread]), + pullRequestSummary: (input) => + Deferred.succeed(readStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseRead)), + Effect.as( + makePullRequestSummary({ + ...input, + state: "open", + updatedAt: DateTime.formatIso(DateTime.makeUnsafe(Date.parse(NOW) - 2 * DAY_MS)), + }), + ), + ), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* reactor.start(); + yield* Deferred.succeed(fixture.activation, undefined); + yield* Queue.take(fixture.snapshotReads); + yield* Deferred.await(readStarted); + if (!mergeDuringRead) yield* reactor.drain; + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1); + + yield* Ref.set(fixture.snapshots, makeSnapshot([])); + yield* fixture.publishMerge; + yield* Queue.take(fixture.snapshotReads); + yield* Deferred.succeed(releaseRead, undefined); + yield* reactor.drain; + + yield* Ref.set(fixture.snapshots, makeSnapshot([thread])); + yield* TestClock.adjust("1 minute"); + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + it.effect("rereads a branch without a pull request less often the longer its thread idles", () => Effect.gen(function* () { yield* TestClock.setTime(Date.parse(NOW)); diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index f493951983ec8..512648e6657d2 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -38,6 +38,7 @@ import { sourceControlDefinitions } from "../sourceControl/sourceControlDefiniti import { makeNoPullRequestRechecks } from "./noPullRequestRechecks.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; +import { QUIET_AFTER_MS, QUIET_SYNC_INTERVAL_MS } from "./PullRequestSyncReactor.ts"; export interface SettlementPullRequest { readonly state: "open" | "closed" | "merged"; @@ -320,6 +321,22 @@ export const make = Effect.gen(function* () { // A shell merge or close sends no event, and the branch lookup caches an open pull request for // a minute, so these threads' next lookup reads the host fresh. const shellClosedThreads = new Set(); + // Each summary read can be a host CLI process (one `az` per read on Azure DevOps), so a quiet + // open pull request is read on the sync reactor's quiet cadence rather than every sweep. + const quietOpenReadAt = new Map(); + const quietReadKey = (reference: { + readonly projectId: string; + readonly repository: string; + readonly number: number; + }) => `${reference.projectId}\0${reference.repository.toLowerCase()}\0${reference.number}`; + // A host can finish a merge minutes after the app's merge action and its refresh, and Azure's + // updatedAt never moves while open, so pull requests stay on the fast cadence for a while after. + // Sweeps that started before the pause fail the same check, so their reads record nothing. + let quietPausedAtMs = Number.NEGATIVE_INFINITY; + const pauseQuietReads = Effect.fn("ThreadSettlementServiceV2.pauseQuietReads")(function* () { + quietPausedAtMs = DateTime.toEpochMillis(yield* DateTime.now); + quietOpenReadAt.clear(); + }); const terminals = yield* TerminalManager.TerminalManager; const projectScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; // Repeated thread.settled retains settledAt; run the action only once per settlement. @@ -330,6 +347,8 @@ export const make = Effect.gen(function* () { mergedPullRequest: PullRequestService.PullRequestMergeEvent | null, threadId?: ThreadId, ) { + // A thread that is not a candidate now (still running) must not keep a merged PR's quiet entry. + if (mergedPullRequest !== null) yield* pauseQuietReads(); const settings = yield* settingsService.getSettings; const automaticSettlementEnabled = autoSettlementConfigured(settings); const threads = yield* projections.getSettlementCandidates(threadId); @@ -337,6 +356,9 @@ export const make = Effect.gen(function* () { const projectShells = yield* projectStore.listShells(); const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const projects = new Map(projectShells.map((project) => [project.id, project])); + for (const [key, readAtMs] of quietOpenReadAt) { + if (nowMs - readAtMs >= QUIET_SYNC_INTERVAL_MS) quietOpenReadAt.delete(key); + } // Merge events resweep all candidates because unlinked threads settle through branch lookup. const candidates = threads.filter( (thread) => @@ -509,6 +531,13 @@ export const make = Effect.gen(function* () { if (!matchesMerge && !projects.has(reference.projectId)) { return yield* Effect.die(new Error("linked pull request project not found")); } + const readKey = quietReadKey(reference); + const shellClosed = + group.filter((member) => shellClosedThreads.delete(member.id)).length > 0; + if (shellClosed) quietOpenReadAt.delete(readKey); + else if (!matchesMerge && quietOpenReadAt.has(readKey)) { + return { state: "open", closedAt: null, mergedAt: null } satisfies SettlementPullRequest; + } const summary = matchesMerge ? ({ state: "merged", @@ -521,8 +550,16 @@ export const make = Effect.gen(function* () { repository: reference.repository, number: reference.number, }, - { recoverTransientFailure: false }, + { recoverTransientFailure: false, bypassCache: shellClosed }, ); + if ( + "updatedAt" in summary && + summary.state === "open" && + nowMs - quietPausedAtMs >= QUIET_SYNC_INTERVAL_MS && + nowMs - Date.parse(summary.updatedAt) >= QUIET_AFTER_MS + ) { + quietOpenReadAt.set(readKey, nowMs); + } const terminal = { state: summary.state, closedAt: summary.closedAt ?? null, @@ -786,6 +823,7 @@ export const make = Effect.gen(function* () { }), ); yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event))); + yield* forkParked(Stream.runForEach(pullRequests.subscribeRefreshes, pauseQuietReads)); yield* forkParked( Stream.runForEach(events, processEvent).pipe( Effect.catchCause((cause) => From 31d9b3bcd60cd113ad8df50c9819f59c8b769ce9 Mon Sep 17 00:00:00 2001 From: "Timo S." <18382402+sti0@users.noreply.github.com> Date: Sat, 14 Nov 2026 07:11:26 +0100 Subject: [PATCH 008/524] fix(web): edited HTML previews outside the workspace no longer turn white (#34569) Co-authored-by: Julius Marminge --- .../AttachmentFilePreview.browser.test.tsx | 36 +++++++++++++++++++ .../src/components/files/FilePreviewPanel.tsx | 19 ++++++---- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 72683a255e3c8..9d7c2ad1298e1 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -1494,6 +1494,42 @@ it("keeps a workspace PDF open across URL renewals and reloads it when the file URL.revokeObjectURL(edited); } }); + +it("loads an edited HTML file outside the workspace from a renewed URL", async () => { + const { WorkspaceBrowserPreview } = await import("./FilePreviewPanel"); + const preview = (mutation: string) => ( + + ); + assetUrlState.mockReturnValue({ _tag: "Success", url: "data:text/html,original", expiresAt: 0 }); + await using screen = await render(preview("first")); + const opened = screen.container.querySelector("iframe"); + expect(opened?.getAttribute("src")).toMatch(/^data:text\/html,original/); + + assetUrlState.mockReturnValue({ + _tag: "Success", + url: "data:text/html,original", + expiresAt: 0, + waiting: true, + }); + await screen.rerender(preview("second")); + expect(assetUrlState).toHaveBeenLastCalledWith(expect.anything(), expect.anything(), "second"); + expect(screen.container.querySelector("iframe")).toBe(opened); + + assetUrlState.mockReturnValue({ _tag: "Success", url: "data:text/html,edited", expiresAt: 0 }); + await screen.rerender(preview("second")); + expect(screen.container.querySelector("iframe")?.getAttribute("src")).toMatch( + /^data:text\/html,edited/, + ); +}); + function planningPdf( titles = ["Quarterly outlook", "Delivery milestones", "Budget and risks"], firstHeight = 140, diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 9d842f0d85d4c..cd498b88bd580 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -249,13 +249,20 @@ export function WorkspaceBrowserPreview(props: { workspaceRoot: props.workspaceRoot, absolutePath: props.absolutePath, }); - const assetUrl = useAssetUrlState( - props.environmentId, - resource, - pdf ? props.workspaceMutationId : undefined, - ); + // Each workspace mutation re-mints the URL: a file outside the workspace is signed by its + // inode, which an atomic replace changes. + const assetUrl = useAssetUrlState(props.environmentId, resource, props.workspaceMutationId); + // The HTML frame keeps its first URL per key, so the key moves only once the re-minted URL arrives. + const [settledMutationId, setSettledMutationId] = useState(props.workspaceMutationId); + if ( + assetUrl._tag === "Success" && + !assetUrl.waiting && + settledMutationId !== props.workspaceMutationId + ) { + setSettledMutationId(props.workspaceMutationId); + } const fileRevision = pdf && assetUrl._tag === "Success" ? assetUrl.fileRevision : undefined; - const revision = fileRevision ?? props.workspaceMutationId; + const revision = fileRevision ?? (pdf ? props.workspaceMutationId : settledMutationId); const revisionSuffix = revision === null ? "" From ddc36529ad76f9c4ef24ae3f6eda6a83ed7bb22e Mon Sep 17 00:00:00 2001 From: Shai List <47258818+shailist@users.noreply.github.com> Date: Sat, 14 Nov 2026 08:17:53 +0200 Subject: [PATCH 009/524] fix(forgejo): the fj sign-in hint points subpath servers to tea (#36290) Co-authored-by: Julius Marminge --- docs/user/source-control.md | 2 +- packages/source-control-forgejo/src/server/ForgejoCli.ts | 4 ++-- .../src/server/ForgejoSourceControlProvider.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 2ebd53ced8565..41879e69a24cf 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -55,7 +55,7 @@ T3 Code prefers a matching `fj` login and falls back to `tea` when `fj` is unava or has no login for that server. Once an account is selected, failed actions stay on that account. Settings shows the detected CLI. Forgejo and Gitea share one integration entry. Servers hosted under a URL subpath, such as `https://example.com/forgejo`, use `tea` because -fj 0.6 does not preserve the subpath when checking its account. +fj does not preserve the subpath when checking its account. When cloning or publishing, use a full repository URL to select a specific server. You can use `owner/repo` when only one fj server is configured, or with your default `tea` diff --git a/packages/source-control-forgejo/src/server/ForgejoCli.ts b/packages/source-control-forgejo/src/server/ForgejoCli.ts index b4c57f22aec51..5fa49386c37e0 100644 --- a/packages/source-control-forgejo/src/server/ForgejoCli.ts +++ b/packages/source-control-forgejo/src/server/ForgejoCli.ts @@ -305,7 +305,7 @@ export const make = Effect.gen(function* () { const remote = remoteUrl ? parseForgejoRemote(remoteUrl) : null; return Object.keys(keys.hosts).flatMap((host) => { const url = parseForgejoRemote(`https://${host}`); - // fj 0.6 drops URL mounts during whoami and OAuth renewal; tea supports them. + // fj drops URL mounts during whoami and OAuth renewal; tea supports them. if (!url || url.path) return []; // fj omits the scheme in storage. Only an explicit matching HTTP remote opts into HTTP. const scheme = @@ -634,7 +634,7 @@ export const make = Effect.gen(function* () { cwd: input.cwd, reason: "authentication", detail: - "No matching Forgejo login. Use `fj auth login`, `fj auth add-token`, or `tea login add` for this server; choose a default when multiple tea accounts match.", + "No matching Forgejo login. Use `fj auth login`, `fj auth add-token`, or `tea login add` for this server. For a server under a URL subpath, use `tea login add`. Choose a default when multiple tea accounts match.", }); if (hostOnly) return { command, login: login.name, repository: "", baseUrl: login.url.replace(/\/+$/, "") }; diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts index c12ac502be24d..8a1b8d49b876f 100644 --- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts +++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts @@ -129,7 +129,7 @@ export const makeDiscovery = Effect.gen(function* () { : providerAuth({ status: "unauthenticated", detail: - "Authenticate this server with `fj --host auth add-token`.", + "Authenticate this server with `fj --host auth add-token`. For a server under a URL subpath, such as `https://example.com/forgejo`, use `tea login add` instead.", }), }, }); From 62ba72fa15441050469740a51a19b45a8b1085c0 Mon Sep 17 00:00:00 2001 From: Artem <42048389+artbom@users.noreply.github.com> Date: Sat, 14 Nov 2026 07:19:14 +0100 Subject: [PATCH 010/524] fix(web): onboarding rechecks an agent when its install command finishes (#36477) Co-authored-by: Julius Marminge --- .../WelcomePage.import.browser.test.tsx | 75 ++++++++++++++++++- .../src/components/onboarding/WelcomePage.tsx | 25 +++++++ 2 files changed, 98 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/onboarding/WelcomePage.import.browser.test.tsx b/apps/web/src/components/onboarding/WelcomePage.import.browser.test.tsx index 409bbf481570c..5615fa3081842 100644 --- a/apps/web/src/components/onboarding/WelcomePage.import.browser.test.tsx +++ b/apps/web/src/components/onboarding/WelcomePage.import.browser.test.tsx @@ -4,6 +4,7 @@ import { AuthOrchestrationReadScope, AuthRelayReadScope, AuthRelayWriteScope, + AuthTerminalOperateScope, EnvironmentId, ProjectId, ProviderDriverKind, @@ -47,6 +48,10 @@ const state = vi.hoisted(() => ({ refreshLinkState: vi.fn(), scanError: null as string | null, scanPending: false, + runningTerminalIds: null as unknown, + openTerminal: vi.fn(), + writeTerminal: vi.fn(), + closeTerminal: vi.fn(), })); vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => { @@ -148,10 +153,41 @@ vi.mock(import("../../onboarding/useProjectScans"), async (original) => { }, }; }); +vi.mock(import("../../state/terminal"), async (original) => { + const actual = await original(); + return { + ...actual, + terminalEnvironment: { + ...actual.terminalEnvironment, + open: "openTerminal", + write: "writeTerminal", + close: "closeTerminal", + } as never, + }; +}); +vi.mock(import("../../state/terminalSessions"), async (original) => { + const { useAtomValue } = await import("@effect/atom-react"); + return { + ...(await original()), + useThreadRunningTerminalIds: (() => + useAtomValue(state.runningTerminalIds as Atom.Atom>)) as never, + }; +}); +vi.mock(import("../ThreadTerminalDrawer"), async (original) => ({ + ...(await original()), + TerminalViewport: () =>
, +})); vi.mock(import("../../state/use-atom-command"), async (original) => ({ ...(await original()), - useAtomCommand: ((command: "createProject" | "importThreads" | "refreshProviders") => - state[command]) as never, + useAtomCommand: (( + command: + | "createProject" + | "importThreads" + | "refreshProviders" + | "openTerminal" + | "writeTerminal" + | "closeTerminal", + ) => state[command]) as never, })); import { welcomeImportSelectionKey } from "../../onboarding/welcomeState"; @@ -327,6 +363,10 @@ function setup() { state.refreshLinkState.mockReset(); state.scanError = null; state.scanPending = false; + state.runningTerminalIds = Atom.make>([]).pipe(Atom.keepAlive); + for (const command of [state.openTerminal, state.writeTerminal, state.closeTerminal]) { + command.mockReset().mockResolvedValue(AsyncResult.success(undefined)); + } localStorage.removeItem(welcomeImportSelectionKey(primaryId)); return now; } @@ -625,6 +665,37 @@ it("offers Update for a signed-in agent whose version is broken, and keeps Start expect(button("Import 2 projects and start").disabled).toBe(true); }); +it("checks an agent again once its install command finishes in the setup terminal", async () => { + using _now = setup(); + appAtomRegistry.set( + sessionAtom(primaryId), + AsyncResult.success(session([AuthOrchestrationOperateScope, AuthTerminalOperateScope])), + ); + appAtomRegistry.set(state.config as Atom.Writable, { + cwd: "/Users/dev", + environment: { platform: { os: "darwin" } }, + keybindings: [], + settings: { providerInstances: {}, projectSettingsOverrides: {} }, + }); + appAtomRegistry.set(state.providers as Atom.Writable>, [ + { ...readyClaude, installed: false, status: "error", auth: { status: "unknown" } }, + ]); + await using _screen = await mountWelcome(); + await vi.waitFor(() => button("Install")); + await click("Install"); + await vi.waitFor(() => expect(state.writeTerminal).toHaveBeenCalledOnce()); + const { terminalId } = state.openTerminal.mock.calls[0]![0].input; + const runningTerminalIds = state.runningTerminalIds as Atom.Writable>; + const recheck = { environmentId: primaryId, input: { instanceId: readyClaude.instanceId } }; + + await act(async () => appAtomRegistry.set(runningTerminalIds, [terminalId])); + expect(state.refreshProviders).not.toHaveBeenCalledWith(recheck); + // The shell stays open at its prompt after the install, so only the command exits. + await act(async () => appAtomRegistry.set(runningTerminalIds, [])); + expect(state.refreshProviders).toHaveBeenCalledWith(recheck); + expect(state.closeTerminal).not.toHaveBeenCalled(); +}); + it("keeps an import opt-out on the page when storage cannot save it", async () => { using _now = setup(); await using _screen = await mountWelcome(); diff --git a/apps/web/src/components/onboarding/WelcomePage.tsx b/apps/web/src/components/onboarding/WelcomePage.tsx index 4696cb9f1cc91..be114c58554af 100644 --- a/apps/web/src/components/onboarding/WelcomePage.tsx +++ b/apps/web/src/components/onboarding/WelcomePage.tsx @@ -94,6 +94,7 @@ import { useEnvironmentsWithScope, } from "../../state/session"; import { terminalEnvironment } from "../../state/terminal"; +import { useThreadRunningTerminalIds } from "../../state/terminalSessions"; import { useAtomCommand } from "../../state/use-atom-command"; import { getProviderSummary } from "../settings/providerStatus"; import { AddProviderInstanceDialog } from "../settings/AddProviderInstanceDialog"; @@ -696,6 +697,12 @@ function AgentsSection({ + void refreshProviders({ + environmentId, + input: { instanceId: terminalSession.providerInstanceId }, + }) + } onClose={() => { setTerminalSession(null); void refreshProviders({ environmentId, input: {} }); @@ -1201,9 +1208,11 @@ function AgentRow({ function AgentInstallTerminal({ session, + onCommandFinished, onClose, }: { readonly session: AgentTerminalSession; + readonly onCommandFinished: () => void; readonly onClose: () => void; }) { const { command, cwd, driver, environmentId, keybindings, providerInstanceId } = session; @@ -1226,6 +1235,22 @@ function AgentInstallTerminal({ "preparing" | "ready" | "openFailed" | "writeFailed" >("preparing"); const terminalReady = setupState === "ready" || setupState === "writeFailed"; + const commandRunning = useThreadRunningTerminalIds({ + environmentId, + threadId: AGENT_ONBOARDING_THREAD_ID, + }).includes(terminalId); + const commandStartedRef = useRef(false); + const handleCommandFinished = useEffectEvent(onCommandFinished); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the shell stays open after an install or sign-in, so its command exiting is the only signal to check the agent again + useEffect(() => { + if (commandRunning) { + commandStartedRef.current = true; + } else if (commandStartedRef.current) { + commandStartedRef.current = false; + handleCommandFinished(); + } + }, [commandRunning]); // StrictMode can finish a cancelled open after replacement setup; it must not close or pre-type into that // session. From bd9ff7eb2a3bff5a12ea442af9d1d7af900ff2f2 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:51:01 +0530 Subject: [PATCH 011/524] fix(client-runtime): recover thread list updates after stream defects (#33244) Co-authored-by: Julius Marminge --- .../src/state/shell-sync.test.ts | 68 +++++++++++++++++++ packages/client-runtime/src/state/shell.ts | 21 +++++- 2 files changed, 87 insertions(+), 2 deletions(-) diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.ts index 96a5b59c5d743..04c165ee72fed 100644 --- a/packages/client-runtime/src/state/shell-sync.test.ts +++ b/packages/client-runtime/src/state/shell-sync.test.ts @@ -8,6 +8,7 @@ import { type ThreadPullRequestLink, } from "@t3tools/contracts"; import { describe, expect, 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"; @@ -1580,6 +1581,73 @@ describe("environment shell cold start", () => { }), ); + it.effect("keeps syncing row status after a shell stream defect", () => + Effect.gen(function* () { + const h = yield* makeColdStart(RECENT_ORIGIN); + const rowUpdate = (sequence: number, status: "completed" | "running") => ({ + kind: "thread.updated" as const, + sequence, + location: "active" as const, + thread: { ...v2ThreadShell, status }, + }); + const liveRow = (sequence: number, status: "completed" | "running") => + SubscriptionRef.changes(h.shellState).pipe( + Stream.filter( + (state) => + state.status === "live" && + Option.exists( + state.snapshot, + (snapshot) => + snapshot.snapshotSequence === sequence && + snapshot.threads.some( + (thread) => thread.id === v2ThreadShell.id && thread.status === status, + ), + ), + ), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + + const first = yield* Queue.take(h.subscriptions); + yield* Queue.offerAll(first.events, [ + rowUpdate(CACHED_SEQUENCE + 1, "completed"), + { kind: "synchronized" }, + ]); + yield* liveRow(CACHED_SEQUENCE + 1, "completed"); + + const failWithDefect = (events: typeof first.events) => + Queue.failCause(events, Cause.die(new Error("shell invariant failed"))).pipe( + Effect.andThen( + SubscriptionRef.changes(h.shellState).pipe( + Stream.filter((state) => + Option.exists( + state.error, + (error) => error === "Could not synchronize environment data.", + ), + ), + Stream.runHead, + ), + ), + ); + + yield* failWithDefect(first.events); + yield* h.reconnect; + const resumed = yield* Queue.take(h.subscriptions); + expect(resumed.input).toMatchObject({ afterSequence: CACHED_SEQUENCE + 1 }); + yield* Queue.offerAll(resumed.events, [ + rowUpdate(CACHED_SEQUENCE + 2, "running"), + { kind: "synchronized" }, + ]); + expect((yield* liveRow(CACHED_SEQUENCE + 2, "running")).error).toEqual(Option.none()); + + // Without a reconnect or wakeup, the stream resubscribes once the backoff passes. + yield* failWithDefect(resumed.events); + yield* TestClock.adjust("250 millis"); + const retried = yield* Queue.take(h.subscriptions); + expect(retried.input).toMatchObject({ afterSequence: CACHED_SEQUENCE + 2 }); + }), + ); + it.effect("reloads over HTTP when the server answers a resume with snapshot-required", () => Effect.gen(function* () { const h = yield* makeColdStart(RECENT_ORIGIN); diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.ts index 86584c4a03faa..cf5462d3f3e2f 100644 --- a/packages/client-runtime/src/state/shell.ts +++ b/packages/client-runtime/src/state/shell.ts @@ -30,7 +30,7 @@ import * as ConnectionWakeups from "../connection/wakeups.ts"; import { safeErrorLogAttributes } from "../errors/safeLog.ts"; import * as Persistence from "../platform/persistence.ts"; import { runCachePersistence } from "./cachePersistence.ts"; -import { subscribeDynamicWithSession } from "../rpc/client.ts"; +import { subscribeDynamicWithSession, subscriptionRetryDelay } from "../rpc/client.ts"; import type { RpcSession } from "../rpc/session.ts"; import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts"; import type { DeferredShellSnapshot } from "./shellPullRequests.ts"; @@ -203,6 +203,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") // Only a server snapshot renews it; `snapshot-required` drops it. const origin = yield* Ref.make(cachedOrigin); const reloadRequests = yield* Queue.unbounded(); + let defectRetries = 0; const latestLive = yield* Ref.make>(Option.none()); const persistence = yield* Queue.sliding(1); @@ -702,11 +703,27 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") }; }), { + // A defect parks the stream, so resubscribe after a backoff rather than wait for a wakeup. + onDefect: (cause) => + setStreamError(Cause.squash(cause)).pipe( + Effect.andThen(Effect.sleep(subscriptionRetryDelay("250 millis", defectRetries++))), + Effect.andThen(Queue.offer(reloadRequests, undefined)), + ), onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)), retryExpectedFailureAfter: "250 millis", resubscribe: resubscriptions, }, - ).pipe(Stream.runForEachArray((entries) => applyItems(entries))), + ).pipe( + Stream.runForEachArray((entries) => + applyItems(entries).pipe( + Effect.andThen( + Effect.sync(() => { + defectRetries = 0; + }), + ), + ), + ), + ), ); yield* SubscriptionRef.changes(supervisor.state).pipe( Stream.runForEach((connectionState) => { From 2dd6cddbc3fc20a4c8a330dc7361750cccfe35e3 Mon Sep 17 00:00:00 2001 From: JS-coder-K <350883774+JS-coder-K@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:23:04 +0900 Subject: [PATCH 012/524] fix(shared): @ mentions complete display names in any script (#36504) Co-authored-by: Julius Marminge --- packages/shared/src/pullRequestComposerTrigger.test.ts | 3 +++ packages/shared/src/pullRequestComposerTrigger.ts | 5 +++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/pullRequestComposerTrigger.test.ts b/packages/shared/src/pullRequestComposerTrigger.test.ts index c17beab3a1275..de7633280de0d 100644 --- a/packages/shared/src/pullRequestComposerTrigger.test.ts +++ b/packages/shared/src/pullRequestComposerTrigger.test.ts @@ -16,6 +16,9 @@ describe("detectPullRequestComposerTrigger", () => { ["cc @ju", 3, "@", "ju"], ["line one\n@first.last", 9, "@", "first.last"], ["@jane-doe more", 0, "@", "jane-doe"], + ["cc @김철", 3, "@", "김철"], + ["@ㄱ", 0, "@", "ㄱ"], + ["@प्रिया", 0, "@", "प्रिया"], ["fixes #", 6, "#", ""], ["see #12", 4, "#", "12"], ["after !5", 6, "!", "5"], diff --git a/packages/shared/src/pullRequestComposerTrigger.ts b/packages/shared/src/pullRequestComposerTrigger.ts index 6a14f0fcc8260..8d21dbff45070 100644 --- a/packages/shared/src/pullRequestComposerTrigger.ts +++ b/packages/shared/src/pullRequestComposerTrigger.ts @@ -17,8 +17,9 @@ export type PullRequestComposerTrigger = { | { readonly kind: "reference"; readonly sigil: PullRequestReferenceSigil } ); -// Mentions cover GitHub logins (letters, digits, hyphens) and GitLab usernames (also `_` and `.`). -const TOKEN = /^(?:@([A-Za-z0-9_][A-Za-z0-9_.-]*)?|([#!])([\p{L}\p{N}_-]*))$/u; +// Logins are ASCII, but the query also matches display names, which can be in any script. +// Combining marks (\p{M}) attach to the letter before them, so they cannot start a name. +const TOKEN = /^(?:@([\p{L}\p{N}_][\p{L}\p{M}\p{N}_.-]*)?|([#!])([\p{L}\p{N}_-]*))$/u; /** What a pull request's host can complete; absent fields complete nothing. */ export type PullRequestCompletionSupport = Pick< From 56fd98be528babf8a8101004c5b10d8ac86411db Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 14 Nov 2026 07:32:39 +0100 Subject: [PATCH 013/524] perf(web): batch first-send composer updates (#36166) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../chat/draftHeroTransition.test.ts | 124 ++++++++++++++++++ .../components/chat/draftHeroTransition.ts | 74 +++++++---- .../src/components/chat/useComposerSend.ts | 18 +-- 3 files changed, 174 insertions(+), 42 deletions(-) create mode 100644 apps/web/src/components/chat/draftHeroTransition.test.ts diff --git a/apps/web/src/components/chat/draftHeroTransition.test.ts b/apps/web/src/components/chat/draftHeroTransition.test.ts new file mode 100644 index 0000000000000..56f8fcc8af4df --- /dev/null +++ b/apps/web/src/components/chat/draftHeroTransition.test.ts @@ -0,0 +1,124 @@ +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +import { runMobileComposerTransition } from "./draftHeroTransition"; + +type StartViewTransition = (update: () => void | Promise) => { + finished: Promise; +}; + +function stubEnvironment(input: { + mobile: boolean; + reducedMotion?: boolean; + startViewTransition?: StartViewTransition; +}) { + const styles = new Map(); + const root = { + style: { + setProperty: (name: string, value: string) => styles.set(name, value), + removeProperty: (name: string) => styles.delete(name), + getPropertyValue: (name: string) => styles.get(name) ?? "", + }, + dataset: {} as Record, + }; + vi.stubGlobal("window", { + matchMedia: (query: string) => ({ + matches: query.includes("max-width") ? input.mobile : (input.reducedMotion ?? false), + }), + }); + vi.stubGlobal("document", { + documentElement: root, + ...(input.startViewTransition ? { startViewTransition: input.startViewTransition } : {}), + }); + return root; +} + +/** A view transition that runs its update after the old snapshot, like the browser does. */ +function deferredViewTransition(): StartViewTransition { + return (update) => ({ + finished: Promise.resolve().then(update), + }); +} + +describe("runMobileComposerTransition", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it.each([ + { name: "desktop viewport", mobile: false, active: true }, + { name: "reduced motion", mobile: true, reducedMotion: true, active: true }, + { name: "panel motion off", mobile: true, active: false }, + { name: "no view transition support", mobile: true, active: true, unsupported: true }, + ])("applies the update before returning on $name", ({ unsupported, active, ...env }) => { + const startViewTransition = vi.fn(deferredViewTransition()); + stubEnvironment({ ...env, ...(unsupported ? {} : { startViewTransition }) }); + const update = vi.fn(); + + const docking = runMobileComposerTransition(update, { active, durationMs: 200 }); + + expect(docking).toBeUndefined(); + expect(update).toHaveBeenCalledTimes(1); + expect(startViewTransition).not.toHaveBeenCalled(); + }); + + it("applies the update once inside a mobile view transition and resolves after it", async () => { + let finish!: () => void; + const finished = new Promise((resolve) => { + finish = resolve; + }); + const startViewTransition = vi.fn((update: () => void) => { + void Promise.resolve().then(update); + return { finished }; + }); + const root = stubEnvironment({ mobile: true, startViewTransition }); + const update = vi.fn(); + + const docking = runMobileComposerTransition(update, { active: true, durationMs: 200 }); + + expect(update).not.toHaveBeenCalled(); + expect(root.dataset.mobileComposerRouteTransition).toBe("true"); + expect(root.style.getPropertyValue("--mobile-composer-transition-duration")).toBe("200ms"); + await docking; + expect(update).toHaveBeenCalledTimes(1); + expect(root.dataset.mobileComposerRouteTransition).toBe("true"); + finish(); + await finished; + expect(root.dataset.mobileComposerRouteTransition).toBeUndefined(); + expect(root.style.getPropertyValue("--mobile-composer-transition-duration")).toBe(""); + expect(update).toHaveBeenCalledTimes(1); + }); + + it.each([ + { + name: "the transition cannot start", + startViewTransition: (): ReturnType => { + throw new Error("InvalidStateError"); + }, + update: vi.fn(), + }, + { + name: "the update throws", + startViewTransition: deferredViewTransition(), + update: vi.fn(() => { + throw new Error("render failed"); + }), + }, + { + name: "an inline update throws", + mobile: false, + startViewTransition: deferredViewTransition(), + update: vi.fn(() => { + throw new Error("render failed"); + }), + }, + ])( + "still releases the caller once when $name", + async ({ mobile = true, startViewTransition, update }) => { + stubEnvironment({ mobile, startViewTransition }); + + await runMobileComposerTransition(update, { active: true, durationMs: 200 }); + + expect(update).toHaveBeenCalledTimes(1); + }, + ); +}); diff --git a/apps/web/src/components/chat/draftHeroTransition.ts b/apps/web/src/components/chat/draftHeroTransition.ts index 7a53a22b2042b..3fb27e4da0d8b 100644 --- a/apps/web/src/components/chat/draftHeroTransition.ts +++ b/apps/web/src/components/chat/draftHeroTransition.ts @@ -1,3 +1,5 @@ +import { flushSync } from "react-dom"; + export const DRAFT_HERO_TRANSITION_ANIMATION_ID = "t3-draft-hero-transition"; export const DRAFT_HERO_TRANSITION_EASING = "cubic-bezier(0.4, 0, 0.2, 1)"; export const MOBILE_COMPOSER_VIEW_TRANSITION_NAME = "t3-mobile-composer"; @@ -35,12 +37,14 @@ export async function waitForDraftHeroTransition(): Promise { ]); } -export async function runMobileComposerTransition( - update: () => void | Promise, +// Only a mobile view transition flushes `update` (its new snapshot must show it) and returns a +// promise; otherwise it runs inline so its state batches with the caller's. Errors never block. +export function runMobileComposerTransition( + update: () => void, options: { active: boolean; durationMs: number }, -): Promise { +): Promise | undefined { if (typeof document === "undefined" || typeof window === "undefined") { - await update(); + runInlineUpdate(update); return; } @@ -48,46 +52,58 @@ export async function runMobileComposerTransition( const mobileViewport = window.matchMedia?.("(max-width: 639px)").matches ?? false; const prefersReducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false; - if ( - !options.active || - !mobileViewport || - prefersReducedMotion || - !transitionDocument.startViewTransition - ) { - await update(); + const startViewTransition = transitionDocument.startViewTransition?.bind(transitionDocument); + if (!options.active || !mobileViewport || prefersReducedMotion || !startViewTransition) { + runInlineUpdate(update); return; } - let updateStarted = false; - const runUpdate = async () => { - if (updateStarted) return; - updateStarted = true; - await update(); - }; + return new Promise((resolveUpdated) => { + let updateStarted = false; + const runUpdate = () => { + if (updateStarted) return; + updateStarted = true; + try { + flushSync(update); + } finally { + resolveUpdated(); + } + }; + void runViewTransition(startViewTransition, runUpdate, options.durationMs); + }); +} + +function runInlineUpdate(update: () => void) { + try { + update(); + } catch {} +} + +async function runViewTransition( + startViewTransition: (update: () => void) => ComposerViewTransition, + runUpdate: () => void, + durationMs: number, +) { + const root = document.documentElement; let transitionFinished: Promise | null = null; - transitionDocument.documentElement.style.setProperty( - MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY, - `${String(options.durationMs)}ms`, - ); - transitionDocument.documentElement.dataset.mobileComposerRouteTransition = "true"; + root.style.setProperty(MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY, `${String(durationMs)}ms`); + root.dataset.mobileComposerRouteTransition = "true"; try { - const transition = transitionDocument.startViewTransition(runUpdate); + const transition = startViewTransition(runUpdate); transitionFinished = transition.finished.catch(() => undefined); activeMobileComposerTransition = transitionFinished; try { await transition.finished; } catch { - await runUpdate(); + runInlineUpdate(runUpdate); } } catch { - await runUpdate(); + runInlineUpdate(runUpdate); } finally { if (activeMobileComposerTransition === transitionFinished) { activeMobileComposerTransition = null; } - delete transitionDocument.documentElement.dataset.mobileComposerRouteTransition; - transitionDocument.documentElement.style.removeProperty( - MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY, - ); + delete root.dataset.mobileComposerRouteTransition; + root.style.removeProperty(MOBILE_COMPOSER_TRANSITION_DURATION_PROPERTY); } } diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 7257dee5ced9e..1afe53a944707 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -45,7 +45,6 @@ import { } from "@t3tools/client-runtime/environment"; import { createModelSelection } from "@t3tools/shared/model"; import { type SetStateAction, useLayoutEffect, useRef } from "react"; -import { flushSync } from "react-dom"; import { useNavigate } from "@tanstack/react-router"; import { isAtomCommandInterrupted, @@ -905,25 +904,18 @@ export function useComposerSend(input: ComposerSendInput) { shouldDockDraftHeroForSubmission({ isDraftHeroState, activeThreadKey, submissionIntent }) && activeThreadKey ) { - let resolveDockStarted: (() => void) | undefined; - const dockStarted = new Promise((resolve) => { - resolveDockStarted = resolve; - }); - const dockTransition = runMobileComposerTransition( + const docking = runMobileComposerTransition( () => { - flushSync(() => { - captureDraftHeroComposerRect(); - setDockedDraftHeroThreadKey(activeThreadKey); - }); - resolveDockStarted?.(); + captureDraftHeroComposerRect(); + setDockedDraftHeroThreadKey(activeThreadKey); }, { active: panelAnimationsActive, durationMs: panelAnimationDurationMs, }, ); - void dockTransition.catch(() => resolveDockStarted?.()); - await dockStarted; + // Awaiting only a real transition keeps an inline dock in the same render as the send. + if (docking) await docking; } const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities(); From 9803d1adb5352a59aa78624e6465fd4ae9968c93 Mon Sep 17 00:00:00 2001 From: Aviddaram <130821636+darjss@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:40:26 +0800 Subject: [PATCH 014/524] fix(web): paint the selected environment theme from the first frame on launch (#36042) Co-authored-by: Julius Marminge --- apps/web/index.html | 16 +++++--- .../web/src/hooks/useEnvironmentTheme.test.ts | 30 ++++++++++++-- apps/web/src/hooks/useEnvironmentTheme.ts | 9 +++- apps/web/src/state/server.ts | 15 ++++++- apps/web/src/themeBoot.test.ts | 26 ++++++++++++ apps/web/src/themePalette.ts | 41 +++++++++++++++---- .../client-runtime/src/rpc/session.test.ts | 4 +- .../src/state/serverConfigProjection.ts | 3 +- 8 files changed, 120 insertions(+), 24 deletions(-) diff --git a/apps/web/index.html b/apps/web/index.html index 1a8bc02e19c9d..051e3090a5d48 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -15,6 +15,7 @@ const LIGHT_BACKGROUND = "#ffffff"; const DARK_BACKGROUND = "#000000"; const CUSTOM_THEMES_STORAGE_KEY = "t3code:themes:v1"; + const ENVIRONMENT_THEMES_STORAGE_KEY = "t3code:environment-themes:v1"; const THEME_FOLLOW_SYSTEM_STORAGE_KEY = "t3code:theme-follow-system"; const THEME_APPEARANCE_MODE_STORAGE_KEY = "t3code:theme-appearance-mode"; const THEME_HALVES_STORAGE_KEY = "t3code:theme-halves:v1"; @@ -197,12 +198,9 @@ (appearance === value.appearance || isRecord(colors)), ); }; - const findCustomTheme = (themeId) => { - if (RESERVED_THEME_IDS.includes(themeId)) return null; + const findStoredTheme = (storageKey, themeId) => { try { - const parsed = JSON.parse( - window.localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY) ?? "null", - ); + const parsed = JSON.parse(window.localStorage.getItem(storageKey) ?? "null"); if (!Array.isArray(parsed)) return null; return ( parsed.find((value) => isStoredCustomTheme(value) && value.id === themeId) ?? null @@ -211,6 +209,14 @@ return null; } }; + // Same precedence as getThemeDefinition: saved custom themes, then published ones. + const findCustomTheme = (themeId) => { + if (RESERVED_THEME_IDS.includes(themeId)) return null; + return ( + findStoredTheme(CUSTOM_THEMES_STORAGE_KEY, themeId) ?? + findStoredTheme(ENVIRONMENT_THEMES_STORAGE_KEY, themeId) + ); + }; try { const storedTheme = window.localStorage.getItem("t3code:theme"); diff --git a/apps/web/src/hooks/useEnvironmentTheme.test.ts b/apps/web/src/hooks/useEnvironmentTheme.test.ts index 855d1a3d5463a..4a6725f4a7e95 100644 --- a/apps/web/src/hooks/useEnvironmentTheme.test.ts +++ b/apps/web/src/hooks/useEnvironmentTheme.test.ts @@ -2,13 +2,11 @@ import type { EnvironmentTheme } from "@t3tools/contracts"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; const publishedThemes = vi.hoisted(() => ({ - atom: null as unknown as import("effect/reactivity").Atom.Writable< - ReadonlyArray - >, + atom: null as unknown as import("effect/reactivity").Atom.Writable | null>, })); vi.mock(import("../state/server"), async () => { const { Atom } = await import("effect/reactivity"); - publishedThemes.atom = Atom.make>([]); + publishedThemes.atom = Atom.make | null>([]); return { themeServerEnvironmentThemesAtom: publishedThemes.atom } as never; }); const refreshTheme = vi.hoisted(() => vi.fn()); @@ -21,6 +19,7 @@ import { invalidateCustomThemes, publishedThemeDefinitions, } from "../themePalette"; +import { startEnvironmentThemeRepaint } from "./useEnvironmentTheme"; const NIGHTFALL_THEME = { id: "nightfall", @@ -122,6 +121,29 @@ describe("environment themes", () => { expect(getThemeDefinition("nightfall")?.label).toBe("Nightfall"); }); + it("keeps the last published palette while the server has not answered", () => { + const store = new Map(); + vi.stubGlobal("window", { + localStorage: { + getItem: (key: string) => store.get(key) ?? null, + setItem: (key: string, value: string) => store.set(key, value), + }, + }); + const stop = startEnvironmentThemeRepaint(); + try { + appAtomRegistry.set(publishedThemes.atom, [NIGHTFALL_THEME]); + appAtomRegistry.set(publishedThemes.atom, null); + expect(getThemeDefinition("nightfall")?.label).toBe("Nightfall"); + + appAtomRegistry.set(publishedThemes.atom, []); + appAtomRegistry.set(publishedThemes.atom, null); + expect(getThemeDefinition("nightfall")).toBeNull(); + } finally { + stop(); + vi.unstubAllGlobals(); + } + }); + it("repaints when the environment publishes themes nothing has read yet", async () => { vi.resetModules(); const { appAtomRegistry: registry } = await import("../rpc/atomRegistry"); diff --git a/apps/web/src/hooks/useEnvironmentTheme.ts b/apps/web/src/hooks/useEnvironmentTheme.ts index ac13e38fa1541..6bafcb1830928 100644 --- a/apps/web/src/hooks/useEnvironmentTheme.ts +++ b/apps/web/src/hooks/useEnvironmentTheme.ts @@ -1,7 +1,11 @@ import { useAtomValue } from "@effect/atom-react"; import { subscribeAtomChanges } from "../rpc/atomRegistry"; -import { environmentThemeDefinitionsAtom, type ThemeDefinition } from "../themePalette"; +import { + environmentThemeDefinitionsAtom, + storePublishedEnvironmentThemes, + type ThemeDefinition, +} from "../themePalette"; import { refreshTheme } from "./useTheme"; export function useEnvironmentThemeDefinitions(): ReadonlyArray { @@ -13,7 +17,8 @@ export function useEnvironmentThemeDefinitions(): ReadonlyArray * only land if the active theme is re-applied. */ export function startEnvironmentThemeRepaint(): () => void { - return subscribeAtomChanges(environmentThemeDefinitionsAtom, () => { + return subscribeAtomChanges(environmentThemeDefinitionsAtom, (definitions) => { + storePublishedEnvironmentThemes(definitions); refreshTheme({ preservePreview: true }); }); } diff --git a/apps/web/src/state/server.ts b/apps/web/src/state/server.ts index b759f456e3208..6e2a71baf53e4 100644 --- a/apps/web/src/state/server.ts +++ b/apps/web/src/state/server.ts @@ -171,9 +171,20 @@ const themeServerConfigAtom = Atom.make((get): ServerConfig | null => { return environmentId === null ? null : get(serverEnvironment.configValueAtom(environmentId)); }).pipe(Atom.withLabel("web-theme-server-config")); +/** + * Null until the theme environment says what it publishes. Cached configs and + * snapshots never carry themes, so a capable server has none until its theme + * event lands. + */ export const themeServerEnvironmentThemesAtom = Atom.make( - (get): ReadonlyArray => - get(themeServerConfigAtom)?.environmentThemes ?? EMPTY_ENVIRONMENT_THEMES, + (get): ReadonlyArray | null => { + const config = get(themeServerConfigAtom); + if (config === null) return null; + if (config.environmentThemes !== undefined) return config.environmentThemes; + return config.environment.capabilities.environmentThemes === true + ? null + : EMPTY_ENVIRONMENT_THEMES; + }, ).pipe(Atom.withLabel("web-theme-server-environment-themes")); export const themeServerSettingsAtom = Atom.make( diff --git a/apps/web/src/themeBoot.test.ts b/apps/web/src/themeBoot.test.ts index 8341978986bbe..891096cbdaf69 100644 --- a/apps/web/src/themeBoot.test.ts +++ b/apps/web/src/themeBoot.test.ts @@ -3,10 +3,12 @@ import { describe, expect, it, vi } from "vite-plus/test"; import indexHtml from "../index.html?raw"; import { CUSTOM_THEMES_STORAGE_KEY, + ENVIRONMENT_THEMES_STORAGE_KEY, getDefaultThemeColors, getThemeColorsForMode, invalidateCustomThemes, isKnownThemePreference, + publishedThemeDefinitions, resolveThemeAppearance, T3_CHAT_THEME, EMBER_THEME, @@ -283,6 +285,30 @@ describe("index.html boot script", () => { expect(boot.metaContent).toBe(colors.chrome); }); + it("paints a published theme from its stored copy before the server connects", () => { + const [published] = publishedThemeDefinitions([ + { + id: "nightfall", + name: "Nightfall", + appearance: "dark", + canvas: "#1a1b26", + accent: "#7aa2f7", + }, + ]); + if (!published) throw new Error("expected the published theme"); + const boot = runBootScript({ + storage: { + [THEME_STORAGE_KEY]: "nightfall", + [ENVIRONMENT_THEMES_STORAGE_KEY]: JSON.stringify([published]), + }, + prefersDark: true, + }); + + expect(boot.themeId).toBe("nightfall"); + expect(boot.bootVariables["--boot-background"]).toBe(published.colors.canvas); + expect(boot.backgroundColor).toBe(published.colors.chrome); + }); + it("keeps every built-in boot splash in sync with the real palettes", () => { for (const theme of [T3_CHAT_THEME, GROVE_THEME, OCEAN_THEME, EMBER_THEME, IRIS_THEME]) { expect(theme.appearance).toBe("light"); diff --git a/apps/web/src/themePalette.ts b/apps/web/src/themePalette.ts index b5191ebc0bfee..a6bea8fb86a23 100644 --- a/apps/web/src/themePalette.ts +++ b/apps/web/src/themePalette.ts @@ -46,6 +46,7 @@ export const CUSTOM_THEMES_STORAGE_KEY = "t3code:themes:v1"; export const THEME_FOLLOW_SYSTEM_STORAGE_KEY = "t3code:theme-follow-system"; export const THEME_APPEARANCE_MODE_STORAGE_KEY = "t3code:theme-appearance-mode"; export const THEME_HALVES_STORAGE_KEY = "t3code:theme-halves:v1"; +export const ENVIRONMENT_THEMES_STORAGE_KEY = "t3code:environment-themes:v1"; const LEGACY_T3_CHAT_DARK_THEME_ID = "t3-chat-dark"; @@ -322,20 +323,44 @@ export function publishedThemeDefinitions( // Every reconnect snapshot delivers a fresh but usually identical array; keeping the // previous one skips regenerating palettes and repainting the document for it. -const publishedThemesAtom = Atom.make((get): ReadonlyArray => { +const publishedThemesAtom = Atom.make((get): ReadonlyArray | null => { const next = get(themeServerEnvironmentThemesAtom); - const previous = Option.getOrNull(get.self>()); + const previous = Option.getOrNull(get.self | null>()); return previous !== null && Equal.equals(previous, next) ? previous : next; }).pipe(Atom.withLabel("web-published-environment-themes")); +function readStoredEnvironmentThemes(): ReadonlyArray { + try { + const parsed: unknown = JSON.parse( + window.localStorage.getItem(ENVIRONMENT_THEMES_STORAGE_KEY) ?? "null", + ); + return Array.isArray(parsed) ? parseStoredThemes(parsed) : []; + } catch { + return []; + } +} + /** - * The environment's palettes are not saved: they are republished by the server - * on every change and would go stale the moment the machine's theme moved on. - * Kept alive because theme lookups read it outside React on every repaint. + * Falls back to the last published set while the server connects, so boot and the + * first render paint the selected palette. Kept alive because theme lookups read it + * outside React on every repaint. */ -export const environmentThemeDefinitionsAtom = Atom.make((get) => - publishedThemeDefinitions(get(publishedThemesAtom)), -).pipe(Atom.keepAlive, Atom.withLabel("web-environment-theme-definitions")); +export const environmentThemeDefinitionsAtom = Atom.make((get) => { + const published = get(publishedThemesAtom); + const definitions = + published === null ? readStoredEnvironmentThemes() : publishedThemeDefinitions(published); + const previous = Option.getOrNull(get.self>()); + return previous !== null && Equal.equals(previous, definitions) ? previous : definitions; +}).pipe(Atom.keepAlive, Atom.withLabel("web-environment-theme-definitions")); + +export function storePublishedEnvironmentThemes(definitions: ReadonlyArray) { + if (appAtomRegistry.get(publishedThemesAtom) === null) return; + try { + window.localStorage.setItem(ENVIRONMENT_THEMES_STORAGE_KEY, JSON.stringify(definitions)); + } catch { + // Without the stored copy the next launch paints stock colors until connect. + } +} function getEnvironmentThemes(): ReadonlyArray { return appAtomRegistry.get(environmentThemeDefinitionsAtom); diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index b6e0908a1f1a9..5882638af0c0c 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -664,7 +664,7 @@ describe("RpcSessionFactory", () => { for (const event of replay) { projection = applyServerConfigProjection(projection, event); } - expect(Option.getOrThrow(projection).config.environmentThemes).toBeUndefined(); + expect(Option.getOrThrow(projection).config.environmentThemes).toEqual([]); }), ); @@ -791,7 +791,7 @@ describe("RpcSessionFactory", () => { for (const event of recovered.slice(1)) { projection = applyServerConfigProjection(projection, event); } - expect(Option.getOrThrow(projection).config.environmentThemes).toBeUndefined(); + expect(Option.getOrThrow(projection).config.environmentThemes).toEqual([]); expect(Option.getOrThrow(projection).config.usageLimitSources).toBeUndefined(); }), ); diff --git a/packages/client-runtime/src/state/serverConfigProjection.ts b/packages/client-runtime/src/state/serverConfigProjection.ts index f8b24fadb08de..5c04a704c2a5b 100644 --- a/packages/client-runtime/src/state/serverConfigProjection.ts +++ b/packages/client-runtime/src/state/serverConfigProjection.ts @@ -166,7 +166,8 @@ export function applyServerConfigProjection( return Option.map(current, (projection) => ({ config: { ...projection.config, - environmentThemes: event.payload.themes.length > 0 ? event.payload.themes : undefined, + // Kept when empty: undefined means the theme event has not arrived yet. + environmentThemes: event.payload.themes, }, latestEvent: event, source: "live", From 2c61677d59bf28730779a578a7b543528f0ca683 Mon Sep 17 00:00:00 2001 From: Roger V <12006627+rgrvlsk@users.noreply.github.com> Date: Sat, 14 Nov 2026 07:44:26 +0100 Subject: [PATCH 015/524] fix(web): overlays close on a click over the desktop header (#36250) Co-authored-by: Roger Co-authored-by: Julius Marminge --- apps/web/src/components/ui/command.tsx | 2 +- apps/web/src/components/ui/dialog.tsx | 5 +++-- apps/web/src/components/ui/sheet.tsx | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/ui/command.tsx b/apps/web/src/components/ui/command.tsx index 1f888a5beff72..13ca99530a5fa 100644 --- a/apps/web/src/components/ui/command.tsx +++ b/apps/web/src/components/ui/command.tsx @@ -45,7 +45,7 @@ function CommandDialogViewport({ className, ...props }: CommandDialogPrimitive.V return ( {popup} diff --git a/apps/web/src/components/ui/sheet.tsx b/apps/web/src/components/ui/sheet.tsx index 3a867ab3965e3..8a06c7d74ee7d 100644 --- a/apps/web/src/components/ui/sheet.tsx +++ b/apps/web/src/components/ui/sheet.tsx @@ -40,7 +40,7 @@ function SheetViewport({ return ( Date: Sat, 14 Nov 2026 00:54:13 -0600 Subject: [PATCH 016/524] fix(server): give MCP clients an absolute attachment upload URL (#35907) Co-authored-by: Julius Marminge --- apps/server/src/mcp/McpHttpServer.test.ts | 105 +++++++++++++++++- apps/server/src/mcp/McpHttpServer.ts | 3 +- apps/server/src/mcp/McpInvocationContext.ts | 5 + .../src/mcp/toolkits/attachment/handlers.ts | 5 +- .../src/mcp/toolkits/attachment/tools.ts | 7 +- 5 files changed, 120 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 395d9dfe04fe5..bd32b3b81c82b 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -27,11 +27,13 @@ import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as Tracer from "effect/Tracer"; import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai"; -import { HttpBody, HttpClient, HttpClientRequest, HttpRouter } from "effect/http"; +import { HttpBody, HttpClient, HttpClientRequest, HttpRouter, HttpServer } from "effect/http"; +import * as NetAddress from "effect/net/NetAddress"; import * as ProjectService from "../project/ProjectService.ts"; import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; +import * as AssetSigner from "../assets/AssetSigner.ts"; import * as DocumentText from "../provider/DocumentText.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; @@ -1385,6 +1387,107 @@ it.effect("accepts case-insensitive MCP bearer schemes and diagnoses rejected cr ); }); +it.effect("gives outside clients an upload URL on the origin their request reached", () => + Effect.scoped( + Effect.gen(function* () { + const token = "outsideClientToken"; + const scope: McpInvocationContext.McpInvocationScope = { + environmentId, + requestNamespace: `client:${token}`, + thread: undefined, + client: { sessionId: token, label: "Hosted agent", access: "full-access" }, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + const serverLayer = McpHttpServer.layerMcpTransport( + McpHttpServer.layerAttachmentToolkit, + ).pipe( + Layer.provide(ServerSettings.layerTest()), + Layer.provide(McpToolAccessTestkit.liveThreadsLayer), + Layer.provide( + Layer.mock(McpSessionRegistry.McpSessionRegistry)({ + resolve: () => Effect.undefined, + }), + ), + // Signs in the way an OAuth client such as a hosted ChatGPT app does. + Layer.provide( + Layer.succeed(McpHttpServer.McpClientAuthenticator)({ + authenticate: (request) => + Effect.succeed( + request.headers.authorization === `Bearer ${token}` ? scope : undefined, + ), + }), + ), + Layer.provide( + AssetSigner.layer.pipe( + Layer.provideMerge(ServerSecretStore.layer), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-upload-" })), + Layer.provideMerge(DocumentText.layer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ); + yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe( + Layer.build, + ); + const httpClient = yield* HttpClient.HttpClient; + const prepareUpload = (proxyHeaders: Record) => + Effect.gen(function* () { + const headers = { + accept: "application/json, text/event-stream", + authorization: `Bearer ${token}`, + ...proxyHeaders, + }; + const initialize = yield* httpClient.post("/mcp", { + headers, + 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", + ), + }); + const response = yield* httpClient.post("/mcp", { + headers: { + ...headers, + "mcp-session-id": initialize.headers["mcp-session-id"]!, + "mcp-protocol-version": "2025-06-18", + }, + body: HttpBody.text( + JSON.stringify({ + jsonrpc: "2.0", + id: 2, + method: "tools/call", + params: { + name: "t3_attachment_prepare_upload", + arguments: { + upload: { + type: "image", + name: "shot.png", + mimeType: "image/png", + sizeBytes: 6, + }, + }, + }, + }), + "application/json", + ), + }); + const body = (yield* response.json) as { + result: { structuredContent: { uploadUrl: string } }; + }; + return body.result.structuredContent; + }); + + const direct = yield* prepareUpload({}); + const { address } = yield* HttpServer.HttpServer; + if (!NetAddress.isInetAddress(address)) throw new Error("Expected a TCP test server"); + expect(new URL(direct.uploadUrl).origin).toBe(`http://127.0.0.1:${address.port}`); + + const proxied = yield* prepareUpload({ "x-forwarded-proto": "https" }); + expect(new URL(proxied.uploadUrl).protocol).toBe("https:"); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("hides tools for links and refuses another environment while the beta is off", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 062c51ac6d7c2..20f1ccf94aab7 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -274,7 +274,8 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { const limited = McpInvocationContext.withRuntimeModeCeiling(asked, runtimeModeCeiling); const linkedEnvironments = yield* linksEnabled; if (limited.client?.linked === true && !linkedEnvironments) return linkedEnvironmentsOff; - return { ...limited, linkedEnvironments }; + const origin = Option.getOrUndefined(Option.map(requestUrl(request), (url) => url.origin)); + return { ...limited, linkedEnvironments, origin }; }); // Untraced: a span here would wrap the tool call; the HTTP server span already covers it. return Effect.fnUntraced(function* (httpEffect) { diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index eb102be177782..37323863e8b72 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -141,6 +141,11 @@ export interface McpInvocationScope { readonly client: McpClientCaller | undefined; /** False while the Linked environments beta is off here; `/mcp` reads it per request. */ readonly linkedEnvironments?: boolean; + /** + * The origin this `/mcp` request reached, e.g. a T3 Connect tunnel. Hosted clients cannot + * see the URL they were configured with, so links they must fetch carry it. Unset in-process. + */ + readonly origin?: string | undefined; } /** diff --git a/apps/server/src/mcp/toolkits/attachment/handlers.ts b/apps/server/src/mcp/toolkits/attachment/handlers.ts index 8d72943f337ae..032ab3a1d0ed6 100644 --- a/apps/server/src/mcp/toolkits/attachment/handlers.ts +++ b/apps/server/src/mcp/toolkits/attachment/handlers.ts @@ -62,7 +62,10 @@ export const layer = McpToolAccess.toLayer( if (now - entry.issuedAt > UPLOAD_OWNER_TTL_MS) uploadOwners.delete(id); } uploadOwners.set(result.attachmentId, { owner: yield* uploadOwner, issuedAt: now }); - return result; + const { origin } = yield* McpInvocationContext.McpInvocationContext; + return origin === undefined + ? result + : { ...result, uploadUrl: `${origin}${result.relativeUrl}` }; }), { linkedCallers: "allowed" }, ), diff --git a/apps/server/src/mcp/toolkits/attachment/tools.ts b/apps/server/src/mcp/toolkits/attachment/tools.ts index f9965850ec8c8..59cecace84386 100644 --- a/apps/server/src/mcp/toolkits/attachment/tools.ts +++ b/apps/server/src/mcp/toolkits/attachment/tools.ts @@ -34,9 +34,12 @@ const shared = { const AttachmentUploadTool = Tool.make("t3_attachment_prepare_upload", { ...shared, description: - "Get an upload URL. POST the file's exact bytes to `relativeUrl` on this MCP server's HTTP origin, then send via `t3_thread_send_attachments` with the returned `attachmentId`.", + "Get an upload URL. POST the file's exact bytes to `uploadUrl` (else this server's `relativeUrl`), then send via `t3_thread_send_attachments` with the returned `attachmentId`.", parameters: Schema.Struct({ upload: AttachmentCreateUploadUrlInput }), - success: AttachmentCreateUploadUrlResult, + success: Schema.Struct({ + ...AttachmentCreateUploadUrlResult.fields, + uploadUrl: Schema.optionalKey(Schema.String), + }), }).annotate(Tool.Destructive, true); const AttachmentDiscardTool = Tool.make("t3_attachment_discard", { ...shared, From 4a53d80239dfcea6a5701a080c70fc3f2aa0da31 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 22:58:45 -0800 Subject: [PATCH 017/524] fix(server): database folders on btrfs are No_COW so SQLite stops fragmenting (#36518) --- apps/server/src/config.ts | 8 ++++++- apps/server/src/noCopyOnWrite.ts | 36 ++++++++++++++++++++++++++++++ apps/server/src/serviceLauncher.ts | 2 ++ 3 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/noCopyOnWrite.ts diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 1acad23117c8d..c707c912d672d 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -10,6 +10,7 @@ import * as Schema from "effect/Schema"; import type { OtlpEndpointSource } from "@t3tools/contracts"; import { sweepStalePendingAttachments } from "./attachmentStore.ts"; +import { markNoCopyOnWrite } from "./noCopyOnWrite.ts"; import { DEFAULT_SIGNAL_EXPORT, nodeProcessRuntimeAttributes, @@ -179,9 +180,14 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + yield* fs.makeDirectory(derivedPaths.stateDir, { recursive: true }); + // Only before the database exists: a No_COW WAL beside an existing copy-on-write database + // could not be reflinked into one backup folder with it. When unsure, leave the folder as is. + if (!(yield* fs.exists(derivedPaths.dbPath).pipe(Effect.orElseSucceed(() => true)))) { + yield* Effect.promise(() => markNoCopyOnWrite(derivedPaths.stateDir)); + } yield* Effect.all( [ - fs.makeDirectory(derivedPaths.stateDir, { recursive: true }), fs.makeDirectory(derivedPaths.logsDir, { recursive: true }), fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }), fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }), diff --git a/apps/server/src/noCopyOnWrite.ts b/apps/server/src/noCopyOnWrite.ts new file mode 100644 index 0000000000000..03d52a0a6d924 --- /dev/null +++ b/apps/server/src/noCopyOnWrite.ts @@ -0,0 +1,36 @@ +// @effect-diagnostics nodeBuiltinImport:off +// The service launcher shares this and runs without an Effect runtime. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFSP from "node:fs/promises"; + +const BTRFS_SUPER_MAGIC = 0x9123683e; + +async function onBtrfs(target: string): Promise { + // oxlint-disable-next-line t3code/no-global-process-runtime -- Shared with the standalone launcher. + if (process.platform !== "linux") return false; + const stats = await NodeFSP.statfs(target).catch(() => undefined); + return stats?.type === BTRFS_SUPER_MAGIC; +} + +const run = (command: string, args: ReadonlyArray) => + new Promise((resolve) => { + NodeChildProcess.execFile(command, args, (error, stdout) => + resolve(error === null ? stdout : undefined), + ); + }); + +/** + * SQLite rewrites pages in place, which fragments copy-on-write files on btrfs. Files created + * in a No_COW directory inherit the flag, as systemd-journald does for its journals. Node has no + * ioctl, so this runs chattr. Btrfs refuses reflinks between No_COW and copy-on-write files. + */ +export async function markNoCopyOnWrite(directory: string): Promise { + if (await onBtrfs(directory)) await run("chattr", ["+C", directory]); +} + +export async function isNoCopyOnWrite(file: string): Promise { + if (!(await onBtrfs(file))) return false; + // lsattr skips symlinks; its first field is the flag string, e.g. "---------------C------". + const output = await run("lsattr", ["-d", await NodeFSP.realpath(file).catch(() => file)]); + return output?.trimStart().split(/\s/, 1)[0]?.includes("C") ?? false; +} diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 1a6c07cf43659..d57a3abaccc99 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -8,6 +8,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import * as NodeUtil from "node:util"; import { acquireServiceSelectionLock } from "./cloud/serviceSelectionLock.ts"; +import { isNoCopyOnWrite, markNoCopyOnWrite } from "./noCopyOnWrite.ts"; import type { PendingServiceUpdate, @@ -438,6 +439,7 @@ export async function databaseBackupBlocker( const { readFreeBytes, canClone } = { ...filesystemBackupSpaceProbe, ...probe }; const backupRoot = NodePath.join(baseDir, "runtime", "db-backup"); await NodeFSP.mkdir(backupRoot, { recursive: true, mode: 0o700 }); + if (await isNoCopyOnWrite(dbPath)) await markNoCopyOnWrite(backupRoot); await removeAbandonedBackupCopies(backupRoot); const [files, free] = await Promise.all([statDatabaseFiles(dbPath), readFreeBytes(backupRoot)]); const size = files.reduce((total, file) => total + file.size, 0); From 7847ec93866bd8e00689e1ff0087f4ce0a67a07d Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Sat, 14 Nov 2026 18:01:22 +1100 Subject: [PATCH 018/524] fix(web): preserve queued project settings changes (#35741) Co-authored-by: SAPHID Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../settings/scopedSettings.test.ts | 125 +++++++++++++++ .../src/components/settings/scopedSettings.ts | 149 +++++++++++++++--- .../components/settings/useScopedSettings.ts | 29 +++- 3 files changed, 277 insertions(+), 26 deletions(-) diff --git a/apps/web/src/components/settings/scopedSettings.test.ts b/apps/web/src/components/settings/scopedSettings.test.ts index fb76500ecdedb..7bed12efc93d6 100644 --- a/apps/web/src/components/settings/scopedSettings.test.ts +++ b/apps/web/src/components/settings/scopedSettings.test.ts @@ -5,6 +5,7 @@ import { ProjectId, ProviderInstanceId, type ServerSettings, + type ServerSettingsPatch, } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; @@ -13,6 +14,7 @@ import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings"; import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping"; import { + createScopedSettingsWriter, persistScopedSettingsPatch, planProjectOverridesClear, planScopedSettingsClear, @@ -565,6 +567,129 @@ describe("scoped settings writes", () => { ]); expect(persistServer).toHaveBeenCalledTimes(4); }); + + describe("rapid project saves on one environment", () => { + const saving = (initial: ServerSettings) => { + let stored = initial; + const persistServer = vi.fn(async ({ input }: { input: { patch: ServerSettingsPatch } }) => { + stored = applyServerSettingsPatch(stored, input.patch); + return { _tag: "Success" as const, value: stored }; + }); + return { persistServer, stored: () => stored }; + }; + + // regression: #18426 rapid project saves rebuilt overrides from a copy that trailed them + it("keeps every edit and reset while the client's copy trails its saves", async () => { + let copy: ServerSettings = { + ...DEFAULT_SERVER_SETTINGS, + projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } }, + }; + const host = saving(copy); + // No config push arrives, so the client's copy stays as it was before the first save. + const write = createScopedSettingsWriter(() => copy); + const save = (plan: Parameters[1]) => + write([environment("Server", { settings: copy })], plan, host.persistServer, vi.fn()); + await Promise.all([ + save((current) => planScopedSettingsPatch(checkout, current, { defaultAutoPull: true })), + save((current) => planScopedSettingsClear(checkout, current, ["enableAgentBrowserAccess"])), + save((current) => + planScopedSettingsPatch(checkout, current, { removeAgentCreditsOnMerge: true }), + ), + ]); + expect(host.stored().projectSettingsOverrides[projectId]).toEqual({ + defaultAutoPull: true, + removeAgentCreditsOnMerge: true, + }); + // The first save's push arrives late, after the newer saves have finished. + copy = (await host.persistServer.mock.results[0]!.value).value; + await save((current) => + planScopedSettingsPatch(checkout, current, { defaultThreadEnvMode: "worktree" }), + ); + expect(host.stored().projectSettingsOverrides[projectId]).toEqual({ + defaultAutoPull: true, + removeAgentCreditsOnMerge: true, + defaultThreadEnvMode: "worktree", + }); + }); + + it.each(["remote", "previous save"] as const)( + "keeps the current base when a %s push arrives during a save", + async (push) => { + let copy: ServerSettings = DEFAULT_SERVER_SETTINGS; + const host = saving(copy); + const write = createScopedSettingsWriter(() => copy); + const edit = (patch: ServerSettingsPatch) => + write( + [environment("Server", { settings: copy })], + (current) => planScopedSettingsPatch(checkout, current, patch), + host.persistServer, + vi.fn(), + ); + await edit({ defaultAutoPull: true }); + const previous = host.stored(); + const persist = host.persistServer.getMockImplementation()!; + host.persistServer.mockImplementationOnce(async (request) => { + const response = await persist(request); + if (push === "remote") { + await persist({ + input: { + patch: { + projectSettingsOverrides: { + [projectId]: { enableAgentBrowserAccess: false }, + }, + }, + }, + }); + copy = host.stored(); + } else { + copy = { ...previous }; + } + return response; + }); + await edit({ removeAgentCreditsOnMerge: true }); + await edit({ defaultThreadEnvMode: "worktree" }); + expect(host.stored().projectSettingsOverrides[projectId]).toEqual( + push === "remote" + ? { enableAgentBrowserAccess: false, defaultThreadEnvMode: "worktree" } + : { + defaultAutoPull: true, + removeAgentCreditsOnMerge: true, + defaultThreadEnvMode: "worktree", + }, + ); + }, + ); + + it("plans from a copy that changed after the last save, and saves again after a failure", async () => { + let copy: ServerSettings = DEFAULT_SERVER_SETTINGS; + const host = saving(copy); + const write = createScopedSettingsWriter(() => copy); + const edit = (patch: ServerSettingsPatch) => + write( + [environment("Server", { settings: copy })], + (current) => planScopedSettingsPatch(checkout, current, patch), + host.persistServer, + vi.fn(), + ); + host.persistServer.mockRejectedValueOnce(new Error("Disconnected")); + expect((await edit({ defaultAutoPull: true })).failedEnvironments).toMatchObject([ + { message: "Disconnected" }, + ]); + expect((await edit({ defaultAutoPull: true })).savedEnvironmentCount).toBe(1); + // Another client replaces the override, and its push reaches this client. + await host.persistServer({ + input: { + patch: { projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } } }, + }, + }); + copy = host.stored(); + await edit({ removeAgentCreditsOnMerge: true }); + expect(host.stored().projectSettingsOverrides[projectId]).toEqual({ + enableAgentBrowserAccess: false, + removeAgentCreditsOnMerge: true, + }); + }); + }); }); describe("scoped settings mixed values", () => { diff --git a/apps/web/src/components/settings/scopedSettings.ts b/apps/web/src/components/settings/scopedSettings.ts index 89affccbdd4d0..44ac4c0ac4bc4 100644 --- a/apps/web/src/components/settings/scopedSettings.ts +++ b/apps/web/src/components/settings/scopedSettings.ts @@ -451,36 +451,147 @@ function droppedSettingKeys(write: ScopedServerWrite, saved: ServerSettings | un ); } +type ScopedSettingsPlan = ReturnType; + +type ScopedSettingsPersistServer = (input: { + environmentId: EnvironmentId; + input: { patch: ServerSettingsPatch }; +}) => Promise<{ + readonly _tag: "Success" | "Failure"; + readonly cause?: Cause.Cause; + readonly value?: ServerSettings; +}>; + export async function persistScopedSettingsPatch( - plan: ReturnType, - persistServer: (input: { - environmentId: EnvironmentId; - input: { patch: ServerSettingsPatch }; - }) => Promise<{ - readonly _tag: "Success" | "Failure"; - readonly cause?: Cause.Cause; - readonly value?: ServerSettings; + plan: ScopedSettingsPlan, + persistServer: ScopedSettingsPersistServer, + persistClient: (patch: ClientSettingsPatch) => void, +) { + return persistScopedSettingsPlan( + plan, + async (write) => ({ + write, + result: await persistServer({ + environmentId: write.environmentId, + input: { patch: write.patch }, + }), + }), + persistClient, + ); +} + +const OWN_ECHO_LIMIT = 8; + +/** + * Project overrides are whole entries built from this client's copy of the settings, and that + * copy hears about a save only when the server pushes it back. So saves to one environment run + * one at a time, each planned as it starts from the newest settings this client holds: the + * previous save's response, unless an independently changed copy has arrived. + */ +export function createScopedSettingsWriter( + readSettings: (environmentId: EnvironmentId) => ServerSettings | null, +) { + const queues = new Map>(); + const responses = new Map< + EnvironmentId, + { + readonly settings: ServerSettings; + readonly copy: ServerSettings; + readonly saved: readonly ServerSettings[]; + } + >(); + return ( + environments: readonly ScopedSettingsEnvironment[], + plan: (environments: readonly ScopedSettingsEnvironment[]) => ScopedSettingsPlan, + persistServer: ScopedSettingsPersistServer, + persistClient: (patch: ClientSettingsPatch) => void, + ) => + persistScopedSettingsPlan( + plan(environments), + (planned) => { + const { environmentId } = planned; + const save = (queues.get(environmentId) ?? Promise.resolve()).then(async () => { + const copy = readSettings(environmentId); + const response = responses.get(environmentId); + // A copy equal to one of our earlier responses is a delayed echo, older than the latest. + const isOwnEcho = (settings: ServerSettings) => + response?.saved.some((saved) => Equal.equals(saved, settings)) === true; + const continues = + copy !== null && response !== undefined && (response.copy === copy || isOwnEcho(copy)); + const settings = continues ? response.settings : copy; + const replanned = + settings === null ? null : plan(withSettings(environments, environmentId, settings)); + const write = + replanned?.serverWrites.find((next) => next.environmentId === environmentId) ?? planned; + const result = await persistServer({ environmentId, input: { patch: write.patch } }); + const savedCopy = readSettings(environmentId); + if (result._tag === "Success" && result.value !== undefined && savedCopy !== null) { + // A changed copy may be a newer remote push or the delayed echo of our previous save. + if ( + savedCopy === copy || + Equal.equals(savedCopy, settings) || + Equal.equals(savedCopy, result.value) || + isOwnEcho(savedCopy) + ) { + responses.set(environmentId, { + settings: result.value, + copy: savedCopy, + saved: [...(continues ? response.saved : []), result.value].slice(-OWN_ECHO_LIMIT), + }); + } else { + responses.delete(environmentId); + } + } + return { write, result }; + }); + queues.set( + environmentId, + save.catch(() => undefined), + ); + return save; + }, + persistClient, + ); +} + +function withSettings( + environments: readonly ScopedSettingsEnvironment[], + environmentId: EnvironmentId, + settings: ServerSettings, +) { + return environments.map((environment) => + environment.environmentId === environmentId && environment.serverConfig + ? { ...environment, serverConfig: { ...environment.serverConfig, settings } } + : environment, + ); +} + +async function persistScopedSettingsPlan( + plan: ScopedSettingsPlan, + persistWrite: (write: ScopedServerWrite) => Promise<{ + readonly write: ScopedServerWrite; + readonly result: Awaited>; }>, persistClient: (patch: ClientSettingsPatch) => void, ) { if (plan.hasClientWrite) persistClient(plan.clientPatch); - const results = await Promise.allSettled( - plan.serverWrites.map(({ environmentId, patch }) => - persistServer({ environmentId, input: { patch } }), - ), + const results = await Promise.allSettled(plan.serverWrites.map(persistWrite)); + // A queued write is replanned before it is sent, so judge the write that was sent. + const writes = results.map((result, index) => + result.status === "fulfilled" ? result.value.write : plan.serverWrites[index]!, ); const saved = (index: number) => { const result = results[index]; return ( result?.status === "fulfilled" && - result.value._tag === "Success" && - droppedSettingKeys(plan.serverWrites[index]!, result.value.value).length === 0 + result.value.result._tag === "Success" && + droppedSettingKeys(writes[index]!, result.value.result.value).length === 0 ); }; - const failedEnvironments = plan.serverWrites.flatMap((environment, index) => { + const failedEnvironments = writes.flatMap((environment, index) => { if (saved(index)) return []; const result = results[index]; - if (result?.status === "fulfilled" && result.value._tag === "Success") { + if (result?.status === "fulfilled" && result.value.result._tag === "Success") { return [ { ...environment, @@ -491,8 +602,8 @@ export async function persistScopedSettingsPatch( const error: unknown = result?.status === "rejected" ? result.reason - : result?.status === "fulfilled" && result.value.cause - ? Cause.squash(result.value.cause) + : result?.status === "fulfilled" && result.value.result.cause + ? Cause.squash(result.value.result.cause) : undefined; return [ { @@ -504,7 +615,7 @@ export async function persistScopedSettingsPatch( }, ]; }); - const savedEnvironments = plan.serverWrites.filter((_, index) => saved(index)); + const savedEnvironments = writes.filter((_, index) => saved(index)); return { failedEnvironments, savedEnvironments, diff --git a/apps/web/src/components/settings/useScopedSettings.ts b/apps/web/src/components/settings/useScopedSettings.ts index e95bc6647e593..10ba059ceef81 100644 --- a/apps/web/src/components/settings/useScopedSettings.ts +++ b/apps/web/src/components/settings/useScopedSettings.ts @@ -15,12 +15,13 @@ import { } from "@t3tools/contracts"; import { persistClientSettingsPatch, useMergedSettings } from "../../hooks/useSettings"; +import { readEnvironment } from "../../state/environments"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; import { toastManager } from "../ui/toast"; import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext"; import { - persistScopedSettingsPatch, + createScopedSettingsWriter, planProjectOverridesClear, planScopedSettingsClear, planScopedSettingsPatch, @@ -30,6 +31,10 @@ import { type ScopedSettingsPatch, } from "./scopedSettings"; +const writeScopedSettings = createScopedSettingsWriter( + (environmentId) => readEnvironment(environmentId)?.serverConfig?.settings ?? null, +); + export function useScopedSettings( selector?: (settings: UnifiedSettings) => T, ): T { @@ -49,7 +54,12 @@ export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[]) function useRunScopedPlan() { const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false }); - return (plan: ReturnType, onFailed?: () => void) => { + return ( + environments: Parameters[0], + planner: Parameters[1], + onFailed?: () => void, + ) => { + const plan = planner(environments); if (plan.unavailableReason) { toastManager.add({ type: "warning", @@ -59,8 +69,9 @@ function useRunScopedPlan() { onFailed?.(); return; } - void persistScopedSettingsPatch( - plan, + void writeScopedSettings( + environments, + planner, async (request) => { const missing = requiredScopesForServerSettingsPatch(request.input.patch).find( (scope) => !readEnvironmentScope(request.environmentId, scope), @@ -102,7 +113,11 @@ export function useUpdateScopedSettings() { const run = useRunScopedPlan(); /** `onFailed` runs when any target rejects or drops the patch, so a draft can fall back. */ return (patch: ScopedSettingsPatch, options?: { readonly onFailed?: () => void }) => - run(planScopedSettingsPatch(scope, environments, patch, { deviceOnly }), options?.onFailed); + run( + environments, + (current) => planScopedSettingsPatch(scope, current, patch, { deviceOnly }), + options?.onFailed, + ); } export function useClearScopedSettings() { @@ -110,7 +125,7 @@ export function useClearScopedSettings() { const run = useRunScopedPlan(); return (keys: readonly ProjectScopedServerSettingKey[]) => { if (context === null) return; - run(planScopedSettingsClear(context.scope, context.environments, keys)); + run(context.environments, (current) => planScopedSettingsClear(context.scope, current, keys)); }; } @@ -122,7 +137,7 @@ export function useClearProjectOverrides() { keys: readonly ProjectScopedServerSettingKey[], ) => { if (context === null) return; - run(planProjectOverridesClear(context.environments, entries, keys)); + run(context.environments, (current) => planProjectOverridesClear(current, entries, keys)); }; } From 8656cdb3a93883e06fd2786f1cb921571a04da11 Mon Sep 17 00:00:00 2001 From: Koi Date: Sat, 14 Nov 2026 02:01:36 -0500 Subject: [PATCH 019/524] fix(web): reply labels no longer cut an emoji in half (#35701) Co-authored-by: Julius Marminge --- .../src/lib/composerContextRecords.test.ts | 22 +++++++++++++++++++ apps/web/src/lib/composerContextRecords.ts | 10 ++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/apps/web/src/lib/composerContextRecords.test.ts b/apps/web/src/lib/composerContextRecords.test.ts index 4f119f1b45573..dff3f83a59554 100644 --- a/apps/web/src/lib/composerContextRecords.test.ts +++ b/apps/web/src/lib/composerContextRecords.test.ts @@ -4,6 +4,7 @@ import { MessageId, OrchestrationMessageContext, ThreadId, + TurnItemId, type PreviewAnnotationPayload, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; @@ -24,6 +25,7 @@ import { previewAnnotationFromRecord, pullRequestContextKindLabel, resolveUserMessageContext, + responseContextRecord, reviewCommentContextLabel, selectedMessageContextFragment, reviewCommentContextRecord, @@ -227,6 +229,26 @@ describe("composerContextRecords", () => { expect(record.label).toBe(`${"a".repeat(46)}…`); }); + it("shortens a long reply label without splitting an emoji", () => { + const text = `${"a".repeat(63)}😀 trailing`; + const record = responseContextRecord({ + citation: { + version: 1, + environmentId: EnvironmentId.make("environment-1"), + threadId: ThreadId.make("thread-1"), + messageId: MessageId.make("message-1"), + text, + start: 0, + end: text.length, + prefix: "", + suffix: "", + }, + itemId: TurnItemId.make("item-1"), + subagents: [], + }); + expect(record.label).toBe("a".repeat(63)); + }); + it("restores multiple edits on one target without parsing display strings", () => { const styleChanges = [ ...annotation.styleChanges, diff --git a/apps/web/src/lib/composerContextRecords.ts b/apps/web/src/lib/composerContextRecords.ts index ac4256da894cf..a7ae316b5c865 100644 --- a/apps/web/src/lib/composerContextRecords.ts +++ b/apps/web/src/lib/composerContextRecords.ts @@ -48,6 +48,7 @@ import { import type { ReviewCommentContext } from "~/reviewCommentContext"; const PREVIEW_LABEL_MAX_CHARS = 48; +const RESPONSE_LABEL_MAX_CHARS = 64; // Truncate selections to wire bounds before persistence to avoid send-time encoding failures. const TRUNCATION_MARKER = "\n… truncated …"; @@ -178,6 +179,13 @@ export function responseContextReference(record: ResponseContextRecord): Compose return { kind: "response", contextId: record.contextId, label: record.label }; } +function responseContextLabel(text: string): string { + const last = text.charCodeAt(RESPONSE_LABEL_MAX_CHARS - 1); + const end = + last >= 0xd800 && last <= 0xdbff ? RESPONSE_LABEL_MAX_CHARS - 1 : RESPONSE_LABEL_MAX_CHARS; + return sanitizeComposerContextLabel(text.slice(0, end), "response"); +} + /** One record per response, so replying to it again reuses the same reference. */ export function responseContextRecord( input: Pick & { @@ -192,7 +200,7 @@ export function responseContextRecord( version: 1, kind: "response", contextId: toKindScopedComposerContextId("response", input.citation.messageId), - label: sanitizeComposerContextLabel(input.citation.text.slice(0, 64), "response"), + label: responseContextLabel(input.citation.text), citation: input.citation, itemId: input.itemId, ...(input.subagents.length > 0 From 388424db26888211304931461e947de1b6091c8d Mon Sep 17 00:00:00 2001 From: Simone Date: Sat, 14 Nov 2026 08:04:25 +0100 Subject: [PATCH 020/524] fix(shared): capture shell values after profiles replace PATH (#35617) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- packages/shared/src/shell.test.ts | 19 +++++++++++++++---- packages/shared/src/shell.ts | 25 ++++++++++++++++++++++--- 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index d1e881a821878..c1b109ec8b625 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -119,16 +119,26 @@ describe("readEnvironmentFromLoginShell", () => { ); it.runIf(NodeFS.existsSync("/bin/bash"))( - "ignores probe markers a bash DEBUG trap echoes into the terminal title", + "captures values when the profile replaces PATH and a DEBUG trap echoes commands", () => { const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-bash-env-")); try { - const shellPath = `${NodePath.join(home, "bin")}:/usr/bin:/bin`; + const tools = NodePath.join(home, "tools 'quoted $dir"); + NodeFS.mkdirSync(tools); + const printenv = NodeChildProcess.execFileSync("/bin/bash", ["-c", "type -P printenv"], { + encoding: "utf8", + env: { PATH: process.env.PATH }, + }).trim(); + NodeFS.copyFileSync(printenv, NodePath.join(tools, "printenv")); + vi.stubEnv("PATH", tools); + const shellPath = NodePath.join(home, "bin"); const bashEnv = NodePath.join(home, "env.bash"); NodeFS.writeFileSync( bashEnv, [ - `export PATH=${JSON.stringify(shellPath)}`, + `export PATH='${shellPath.replaceAll("'", "'\\''")}'`, + // Simulate a non-FHS host while retaining the real executable in its private prefix. + "function /usr/bin/printenv { return 127; }", `trap 'echo -ne "\\033]0;\${BASH_COMMAND}\\007"' DEBUG`, ].join("\n"), ); @@ -141,11 +151,12 @@ describe("readEnvironmentFromLoginShell", () => { (file, [, command = ""], options) => NodeChildProcess.execFileSync(file, ["-c", command], { ...options, - env: { HOME: home, PATH: "/usr/bin:/bin", TERM: "dumb", BASH_ENV: bashEnv }, + env: { HOME: home, PATH: tools, TERM: "dumb", BASH_ENV: bashEnv }, }), ), ).toEqual({ PATH: shellPath }); } finally { + vi.unstubAllEnvs(); NodeFS.rmSync(home, { recursive: true, force: true }); } }, diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index e15ebe8129460..12babdb715d2b 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -209,6 +209,12 @@ function envCaptureEnd(name: string): string { } const DEBUG_TRAP_SHELLS = new Set(["bash", "zsh", "sh", "ksh", "ksh93"]); +const POSIX_CAPTURE_SYNTAX = { assignment: "__T3CODE_PRINTENV=$(", orElse: " || " }; +const PRINTENV_CAPTURE_SYNTAX = new Map( + [...DEBUG_TRAP_SHELLS, "dash", "ash"].map((shell) => [shell, POSIX_CAPTURE_SYNTAX] as const), +).set("fish", { assignment: "set -l __T3CODE_PRINTENV (", orElse: "; or " }); +// Network PATH entries must be probed inside the shell's deadline, away from the desktop thread. +const PRINTENV_LOOKUP_COMMAND = `/bin/sh -c 'command -v printenv || { [ -n "$1" ] && PATH="$1" command -v printenv; } || printf %s /usr/bin/printenv' t3`; export function buildEnvironmentCaptureCommand( shell: string, @@ -216,6 +222,16 @@ export function buildEnvironmentCaptureCommand( ): string { const executableName = NodePath.basename(shell).toLowerCase(); const isNushell = executableName.startsWith("nu"); + const syntax = PRINTENV_CAPTURE_SYNTAX.get(executableName); + const supportsFallback = syntax !== undefined; + const inheritedPath = resolvePathEnvironmentVariable(process.env) + .split(POSIX_PATH_DELIMITER) + .filter(Boolean) + .map((entry) => NodePath.posix.resolve(entry)) + .join(POSIX_PATH_DELIMITER); + const lookupPrintenv = `${PRINTENV_LOOKUP_COMMAND} '${inheritedPath.replaceAll("'", "'\\''")}'`; + const { assignment, orElse } = syntax ?? POSIX_CAPTURE_SYNTAX; + const resolvePrintenv = `${assignment}${lookupPrintenv}); `; const capture = names .map((name) => { @@ -246,7 +262,9 @@ export function buildEnvironmentCaptureCommand( return [ `printf '%s\\n' '${envCaptureStart(name)}'`, - `printenv ${name} || true`, + supportsFallback + ? `printenv ${name}${orElse}"$__T3CODE_PRINTENV" ${name}${orElse}true` + : `printenv ${name} || true`, `printf '%s\\n' '${envCaptureEnd(name)}'`, ].join("; "); }) @@ -254,9 +272,10 @@ export function buildEnvironmentCaptureCommand( // A DEBUG trap that echoes each command (e.g. into the terminal title) would print the markers. // OpenBSD ksh (also its /bin/sh) exits on `trap - DEBUG`, so try it in a subshell first. + const command = supportsFallback ? resolvePrintenv + capture : capture; return DEBUG_TRAP_SHELLS.has(executableName) - ? `(trap - DEBUG) 2>/dev/null && trap - DEBUG; ${capture}` - : capture; + ? `(trap - DEBUG) 2>/dev/null && trap - DEBUG; ${command}` + : command; } function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray): string { From e1f5b682813fa5c15366513ce1868d6c5b50b655 Mon Sep 17 00:00:00 2001 From: Fuksss Date: Sat, 14 Nov 2026 08:05:56 +0100 Subject: [PATCH 021/524] fix(server): MCP tools say why the orchestrator refused (#36083) Co-authored-by: Julius Marminge --- .../src/mcp/OrchestratorMcpService.test.ts | 265 +++++++++++++++++- apps/server/src/mcp/OrchestratorMcpService.ts | 14 +- 2 files changed, 271 insertions(+), 8 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index a017590b1f30a..3643be87ea126 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -54,6 +54,7 @@ import { type DispatchModeRefusal, } from "../orchestration-v2/DispatchModeLimit.ts"; import { + OrchestratorDispatchError, OrchestratorProjectionError, OrchestratorThreadAboveModeLimitError, } from "../orchestration-v2/Orchestrator.ts"; @@ -707,7 +708,15 @@ describe("OrchestratorMcpService", () => { cancelDelegatedTask: ({ command, stopDescendants }) => stopDescendants(() => Effect.die("No remote descendants in this test")).pipe( Effect.andThen(Ref.update(dispatched, (commands) => [...commands, command])), - Effect.andThen(Effect.fail(new Error("simulated stop failure") as never)), + Effect.andThen( + Effect.fail( + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: new Error("simulated stop failure"), + }) as never, + ), + ), ), }), ServerSettings.layerTest(), @@ -739,6 +748,10 @@ describe("OrchestratorMcpService", () => { .cancelTask(scope, { taskId, clientRequestId: "cancel-failed-task" }) .pipe(Effect.flip); assert.equal(error.code, "task_not_cancellable"); + assert.equal( + error.message, + `Unable to stop delegated task ${taskId}: simulated stop failure`, + ); assert.deepEqual( (yield* Ref.get(dispatched)).map((command) => (command as { type: string }).type), ["thread.stop"], @@ -841,6 +854,98 @@ describe("OrchestratorMcpService", () => { }), ); + it.effect( + "reports the dispatch cause instead of the generic wrapper when disposing a finished task's completion delivery fails", + () => + Effect.gen(function* () { + const parentThreadId = ThreadId.make("thread:mcp-cancel-dispose-cause-parent"); + const childThreadId = ThreadId.make("thread:mcp-cancel-dispose-cause-child"); + const taskId = NodeId.make("node:mcp-cancel-dispose-cause-task"); + const parentProjection = { + thread: { id: parentThreadId }, + runs: [], + contextTransfers: [], + subagents: [ + { + id: taskId, + threadId: parentThreadId, + origin: "app_owned", + childThreadId, + driver: "codex", + model: "gpt-5.6-terra", + status: "completed", + result: "Done.", + completionDelivery: { state: "pending" }, + }, + ], + } as unknown as OrchestrationV2ThreadProjection; + const childProjection = { + thread: { id: childThreadId, title: "Child" }, + runs: [], + contextTransfers: [], + messages: [], + subagents: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], + } as unknown as OrchestrationV2ThreadProjection; + const layerDependencies = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: (threadId) => + Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection), + getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), + listAppOwnedChildThreadIds: () => Effect.succeed([]), + stopDelegatedTasks: () => Effect.void, + cancelDelegatedTask: () => Effect.void, + dispatch: (command) => + command.type === "delegated_task.completion-delivery.dispose" + ? Effect.fail( + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: new Error("refused by the orchestrator"), + }) as never, + ) + : Effect.succeed({} as never), + }), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + }), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + const scope: McpInvocationScope = { + environmentId: EnvironmentId.make("environment:mcp-cancel-dispose-cause"), + requestNamespace: "provider-session:mcp-cancel-dispose-cause", + thread: { + threadId: parentThreadId, + providerSessionId: "provider-session:mcp-cancel-dispose-cause", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + const error = yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + return yield* service + .cancelTask(scope, { taskId, clientRequestId: "cancel-dispose-dispatch-cause" }) + .pipe(Effect.flip); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); + assert.equal(error.code, "orchestration_error"); + assert.equal( + error.message, + `Unable to dispose delegated task ${taskId} completion delivery: refused by the orchestrator`, + ); + }), + ); + it.effect("refuses to cancel a task whose child now runs above the parent's modes", () => Effect.gen(function* () { const parentThreadId = ThreadId.make("thread:mcp-cancel-dispose-failed-parent"); @@ -1976,6 +2081,119 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + it.effect("reports the dispatch cause instead of the generic wrapper when delegating fails", () => + Effect.gen(function* () { + const layerDependencies = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + hasReceipt: () => Effect.succeed(false), + getThreadRecords: () => Effect.succeed(parentProjection([])), + dispatch: (command) => + Effect.fail( + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: new Error("refused by the orchestrator"), + }) as never, + ), + }), + ServerSettings.layerTest(), + providerRegistryLayer([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + adapterRegistryLayer([codexInstanceId]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + const error = yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + return yield* service + .delegateTask(scope, { + task: "Summarize the diff.", + mode: "async", + clientRequestId: "delegate-dispatch-cause", + }) + .pipe(Effect.flip); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); + assert.equal(error.code, "orchestration_error"); + assert.equal(error.message, "Unable to create delegated task: refused by the orchestrator"); + }), + ); + + it.effect.each([ + { failingType: "thread.create", prefix: "Unable to create thread 1: " }, + { failingType: "message.dispatch", prefix: "Unable to start thread 1: " }, + { + failingType: "thread.created.record", + prefix: "Unable to record thread 1 in the parent timeline: ", + }, + ] as const)( + "reports the dispatch cause instead of the generic wrapper when create_threads' $failingType dispatch fails", + ({ failingType, prefix }) => + Effect.gen(function* () { + const childThreadId = ThreadId.make("thread:mcp-providers-create-child"); + const childShell = { + thread: { + id: childThreadId, + title: "Child", + modelSelection: { instanceId: codexInstanceId, model: "gpt-5.4" }, + }, + runs: [], + } as unknown as OrchestrationV2ThreadProjection; + const layerDependencies = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + hasReceipt: () => Effect.succeed(false), + assertProviderInstanceEnabled: () => Effect.void, + getThreadRecords: (threadId) => + Effect.succeed(threadId === parentThreadId ? parentProjection([]) : childShell), + dispatch: (command) => + command.type === failingType + ? Effect.fail( + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: new Error("refused by the orchestrator"), + }) as never, + ) + : Effect.succeed({} as never), + }), + ServerSettings.layerTest(), + providerRegistryLayer([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + adapterRegistryLayer([codexInstanceId]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + const error = yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + return yield* service + .createThreads(scope, { + threads: [{ prompt: "Summarize the diff." }], + clientRequestId: `create-threads-dispatch-cause-${failingType}`, + }) + .pipe(Effect.flip); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); + assert.equal(error.code, "orchestration_error"); + assert.equal(error.message, `${prefix}refused by the orchestrator`); + }), + ); + it.effect("driver-only delegation skips an instance the project turned off", () => Effect.gen(function* () { const altInstanceId = ProviderInstanceId.make("codex-alt"); @@ -3719,6 +3937,51 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + it.effect( + "reports the dispatch cause instead of the generic wrapper when interrupting fails", + () => + Effect.gen(function* () { + const layerDependencies = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => Effect.succeed(parentProjection([])), + interruptThread: (input) => + Effect.fail( + new OrchestratorDispatchError({ + commandId: input.commandId, + commandType: "thread.interrupt", + cause: new Error("refused by the orchestrator"), + }) as never, + ), + }), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + }), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + const error = yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + return yield* service + .interruptThread(scope, { + threadId: parentThreadId, + clientRequestId: "interrupt-dispatch-cause", + }) + .pipe(Effect.flip); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); + assert.equal(error.code, "orchestration_error"); + assert.equal( + error.message, + `Unable to interrupt thread ${parentThreadId}: refused by the orchestrator`, + ); + }), + ); + describe("resolveRuntimeMode", () => { const muse = { modelSelection: { instanceId: ProviderInstanceId.make("muse"), model: "muse-model" }, diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index fc741bcac6ab5..a333b3f8fd27a 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2661,7 +2661,7 @@ const make = Effect.gen(function* () { ? threadManagementFailure(error) : failure( "orchestration_error", - `Unable to create delegated task: ${errorMessage(error)}`, + `Unable to create delegated task: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`, ), ), ); @@ -2769,7 +2769,7 @@ const make = Effect.gen(function* () { Effect.mapError((error) => failure( "orchestration_error", - `Unable to dispose delegated task ${input.taskId} completion delivery: ${errorMessage(error)}`, + `Unable to dispose delegated task ${input.taskId} completion delivery: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`, ), ), ); @@ -2800,7 +2800,7 @@ const make = Effect.gen(function* () { Effect.mapError((error) => failure( "task_not_cancellable", - `Unable to stop delegated task ${input.taskId}: ${errorMessage(error)}`, + `Unable to stop delegated task ${input.taskId}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`, ), ), ); @@ -3004,7 +3004,7 @@ const make = Effect.gen(function* () { Effect.mapError((error) => failure( "orchestration_error", - `Unable to create thread ${index + 1}: ${errorMessage(error)}`, + `Unable to create thread ${index + 1}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`, ), ), ); @@ -3042,7 +3042,7 @@ const make = Effect.gen(function* () { ? threadManagementFailure(error) : failure( "orchestration_error", - `Unable to start thread ${index + 1}: ${errorMessage(error)}`, + `Unable to start thread ${index + 1}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`, ), ), ); @@ -3068,7 +3068,7 @@ const make = Effect.gen(function* () { Effect.mapError((error) => failure( "orchestration_error", - `Unable to record thread ${index + 1} in the parent timeline: ${errorMessage(error)}`, + `Unable to record thread ${index + 1} in the parent timeline: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`, ), ), ); @@ -3469,7 +3469,7 @@ const make = Effect.gen(function* () { ? threadManagementFailure(error) : failure( "orchestration_error", - `Unable to interrupt thread ${input.threadId}: ${errorMessage(error)}`, + `Unable to interrupt thread ${input.threadId}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`, ), ), ); From 5ef603df343c29c5c6fd1b8a8db0e705d2be9941 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sat, 14 Nov 2026 01:07:23 -0600 Subject: [PATCH 022/524] fix(web): remove routine success notifications (#36527) --- .../src/features/files/ZipArchiveView.tsx | 2 -- .../SettingsNotificationsRouteScreen.tsx | 4 +-- apps/web/src/components/BranchToolbar.tsx | 10 +----- .../BranchToolbarBranchSelector.tsx | 28 +++++---------- .../DiffFilePathCopyButton.browser.test.tsx | 2 +- .../src/components/DiffFilePathCopyButton.tsx | 7 +--- .../components/KeybindingsUpdateToast.test.ts | 3 +- .../src/components/KeybindingsUpdateToast.tsx | 10 +----- apps/web/src/components/Sidebar.tsx | 21 ----------- .../src/components/chat/MarkdownFileLink.tsx | 35 +++++++------------ .../chat/MessageCopyButton.browser.test.tsx | 2 +- .../src/components/chat/MessageCopyButton.tsx | 2 -- .../components/chat/useRightPanelActions.ts | 27 +++++--------- .../src/components/files/FileBrowserPanel.tsx | 5 --- .../web/src/components/media/MediaActions.tsx | 9 +---- .../components/promptLinks/copyPromptLink.ts | 3 +- .../pullRequest/PullRequestDetailPanel.tsx | 1 - .../pullRequest/PullRequestsPage.tsx | 24 ++++--------- .../AboutVersionTitle.browser.test.tsx | 4 +-- .../components/settings/AboutVersionTitle.tsx | 6 ---- .../settings/AcpSessionManagementSection.tsx | 4 --- .../settings/AuthorizedClientsSettings.tsx | 17 --------- .../settings/ConnectionDiagnosisDetails.tsx | 1 - .../settings/SavedEnvironmentRows.tsx | 7 ---- .../components/settings/ThemeEditorHost.tsx | 21 ----------- .../src/components/ui/anchoredCopyToast.ts | 14 -------- apps/web/src/hooks/useThreadActionMenu.ts | 9 ----- apps/web/src/lib/copyThreadReference.ts | 8 +---- 28 files changed, 50 insertions(+), 236 deletions(-) diff --git a/apps/mobile/src/features/files/ZipArchiveView.tsx b/apps/mobile/src/features/files/ZipArchiveView.tsx index 9f5dbbec0725f..6187a051e1c4d 100644 --- a/apps/mobile/src/features/files/ZipArchiveView.tsx +++ b/apps/mobile/src/features/files/ZipArchiveView.tsx @@ -667,8 +667,6 @@ function ZipEntryView(props: { () => { if (controller.signal.aborted) return; setBusy(null); - if (kind === "attach") - Dialog.alert("Added to chat", `${entry.name} is attached to your message.`); }, (cause: unknown) => { if (controller.signal.aborted) return; diff --git a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx index acd24efb8dc19..db19b556625fa 100644 --- a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx @@ -202,9 +202,7 @@ function ConfiguredSettingsNotificationsRouteScreen() { } if (result.value.type === "granted") { setNotificationStatus("enabled"); - if (agentAwarenessNotificationsReady()) { - Dialog.alert("Notifications enabled", "Agent notifications are enabled for this device."); - } else { + if (!agentAwarenessNotificationsReady()) { Dialog.alert( "Couldn't finish enabling notifications", "Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.", diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 93249bcf0c9f2..eae9e43459f42 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -117,15 +117,7 @@ function showWorkspaceContextMenu(event: ReactMouseEvent, workspacePath: string) if (action !== "copy-path") return; const clipboardPath = formatFilePathForClipboard(workspacePath); void writeTextToClipboard(clipboardPath, "workspace path").then( - (didCopy) => { - if (didCopy) { - toastManager.add({ - type: "success", - title: "Path copied", - description: clipboardPath, - }); - } - }, + undefined, (error: unknown) => { toastManager.add( stackedThreadToast({ diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index e685e623f2bc1..ad139c40c0c57 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -364,25 +364,15 @@ export function BranchToolbarBranchSelector({ : null; const copyBranchName = (branchName: string) => { - void writeTextToClipboard(branchName, "branch name").then( - (didCopy) => { - if (!didCopy) return; - toastManager.add({ - type: "success", - title: "Branch name copied", - description: branchName, - }); - }, - (error: unknown) => { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to copy branch name", - description: toBranchActionErrorMessage(error), - }), - ); - }, - ); + void writeTextToClipboard(branchName, "branch name").then(undefined, (error: unknown) => { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to copy branch name", + description: toBranchActionErrorMessage(error), + }), + ); + }); }; const handleBranchContextMenu = (event: ReactMouseEvent, branchName: string | null) => { diff --git a/apps/web/src/components/DiffFilePathCopyButton.browser.test.tsx b/apps/web/src/components/DiffFilePathCopyButton.browser.test.tsx index a2bec09ca960d..1a0b4238f5f6e 100644 --- a/apps/web/src/components/DiffFilePathCopyButton.browser.test.tsx +++ b/apps/web/src/components/DiffFilePathCopyButton.browser.test.tsx @@ -24,7 +24,7 @@ it("explains a denied clipboard write and lets the same path be copied again", a await page.getByRole("button", { name: "Dismiss notification" }).click(); await copy.click(); - await expect.element(page.getByText("Copied!", { exact: true })).toBeVisible(); + await expect.element(page.getByText("Copied!", { exact: true })).not.toBeInTheDocument(); expect(write).toHaveBeenCalledTimes(2); expect(write).toHaveBeenLastCalledWith("apps/web/src/index.ts"); }); diff --git a/apps/web/src/components/DiffFilePathCopyButton.tsx b/apps/web/src/components/DiffFilePathCopyButton.tsx index 5e78949336cff..59aa256294d85 100644 --- a/apps/web/src/components/DiffFilePathCopyButton.tsx +++ b/apps/web/src/components/DiffFilePathCopyButton.tsx @@ -1,18 +1,13 @@ import { CheckIcon, CopyIcon } from "lucide-react"; import { useRef } from "react"; import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; -import { - ANCHORED_COPY_TOAST_TIMEOUT_MS, - showAnchoredCopyErrorToast, - showAnchoredCopySuccessToast, -} from "./ui/anchoredCopyToast"; +import { ANCHORED_COPY_TOAST_TIMEOUT_MS, showAnchoredCopyErrorToast } from "./ui/anchoredCopyToast"; import { Button } from "./ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; export function DiffFilePathCopyButton({ filePath }: { filePath: string }) { const ref = useRef(null); const { copyToClipboard, isCopied } = useCopyToClipboard({ - onCopy: () => showAnchoredCopySuccessToast(ref), onError: (error) => showAnchoredCopyErrorToast(ref, error), timeout: ANCHORED_COPY_TOAST_TIMEOUT_MS, }); diff --git a/apps/web/src/components/KeybindingsUpdateToast.test.ts b/apps/web/src/components/KeybindingsUpdateToast.test.ts index 01cb26c3f7ebc..0f2bae3fea877 100644 --- a/apps/web/src/components/KeybindingsUpdateToast.test.ts +++ b/apps/web/src/components/KeybindingsUpdateToast.test.ts @@ -44,7 +44,7 @@ function keybindingsUpdated(issues: ReadonlyArray): ServerConfigStreamE } describe("startKeybindingsUpdateToasts", () => { - it("toasts reloads the server reports after start", () => { + it("only toasts invalid reloads the server reports after start", () => { const stop = startKeybindingsUpdateToasts(); try { appAtomRegistry.set(mocks.state, { latestEvent: keybindingsUpdated([]) }); @@ -55,7 +55,6 @@ describe("startKeybindingsUpdateToasts", () => { }); expect(mocks.addToast.mock.calls.map(([toast]) => toast.title)).toEqual([ - "Keybindings updated", "Invalid keybindings configuration", ]); } finally { diff --git a/apps/web/src/components/KeybindingsUpdateToast.tsx b/apps/web/src/components/KeybindingsUpdateToast.tsx index 63702210b7e14..7ae58759732c6 100644 --- a/apps/web/src/components/KeybindingsUpdateToast.tsx +++ b/apps/web/src/components/KeybindingsUpdateToast.tsx @@ -5,21 +5,13 @@ import { KeybindingsConfigWarning } from "./KeybindingsConfigWarning"; import { createKeybindingsUpdateToastController } from "./KeybindingsUpdateToast.logic"; import { stackedThreadToast, toastManager } from "./ui/toast"; -/** Toasts each keybindings reload the primary server reports. */ export function startKeybindingsUpdateToasts(): () => void { const controller = createKeybindingsUpdateToastController({}); return subscribeAtomChanges(primaryServerConfigEventAtom, (event) => { const decision = controller.handle(event); if (!decision) return; - if (decision._tag === "Success") { - toastManager.add({ - type: "success", - title: "Keybindings updated", - description: "Keybindings configuration reloaded successfully.", - }); - return; - } + if (decision._tag === "Success") return; const serverConfig = appAtomRegistry.get(primaryServerConfigAtom); toastManager.add( diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index a94b9e9497c6b..ec9cde4684b9c 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -942,13 +942,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve reportFailure: false, }); const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({ - onCopy: ({ path }) => { - toastManager.add({ - type: "success", - title: "Path copied", - description: path, - }); - }, onError: (error) => { toastManager.add( stackedThreadToast({ @@ -961,13 +954,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }); const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({ target: "branch name", - onCopy: ({ branch }) => { - toastManager.add({ - type: "success", - title: "Branch copied", - description: branch, - }); - }, onError: (error) => { toastManager.add( stackedThreadToast({ @@ -979,13 +965,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }, }); const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({ - onCopy: ({ threadId }) => { - toastManager.add({ - type: "success", - title: "Thread ID copied", - description: threadId, - }); - }, onError: (error) => { toastManager.add( stackedThreadToast({ diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx index 0fa8eaf4f30f6..2e553acdb8d2d 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.tsx +++ b/apps/web/src/components/chat/MarkdownFileLink.tsx @@ -220,28 +220,19 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ }), ]) : value.then((text) => navigator.clipboard.writeText(text)); - void Promise.all([write, value]).then( - ([, text]) => { - toastManager.add({ - type: "success", - title: `${title} copied`, - description: text, - }); - }, - (error) => { - reportMarkdownActionFailure( - { operation: "copy-file-path", target: targetPath, copyTarget: title }, - error, - ); - toastManager.add( - stackedThreadToast({ - type: "error", - title: `Failed to copy ${title.toLowerCase()}`, - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - }, - ); + void Promise.all([write, value]).catch((error) => { + reportMarkdownActionFailure( + { operation: "copy-file-path", target: targetPath, copyTarget: title }, + error, + ); + toastManager.add( + stackedThreadToast({ + type: "error", + title: `Failed to copy ${title.toLowerCase()}`, + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + }); }; const showFileContextMenu = async (position: { x: number; y: number }) => { diff --git a/apps/web/src/components/chat/MessageCopyButton.browser.test.tsx b/apps/web/src/components/chat/MessageCopyButton.browser.test.tsx index fdae9c7afcacf..7290599de7cd5 100644 --- a/apps/web/src/components/chat/MessageCopyButton.browser.test.tsx +++ b/apps/web/src/components/chat/MessageCopyButton.browser.test.tsx @@ -25,6 +25,6 @@ it("explains a denied clipboard write and lets the same message be copied again" await page.getByRole("button", { name: "Dismiss notification" }).click(); await copy.click(); - await expect.element(page.getByText("Copied!", { exact: true })).toBeVisible(); + await expect.element(page.getByText("Copied!", { exact: true })).not.toBeInTheDocument(); await expect.element(copy).toBeDisabled(); }); diff --git a/apps/web/src/components/chat/MessageCopyButton.tsx b/apps/web/src/components/chat/MessageCopyButton.tsx index cf1af485ce160..91f5cba71084e 100644 --- a/apps/web/src/components/chat/MessageCopyButton.tsx +++ b/apps/web/src/components/chat/MessageCopyButton.tsx @@ -5,7 +5,6 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; import { ANCHORED_COPY_TOAST_TIMEOUT_MS, showAnchoredCopyErrorToast, - showAnchoredCopySuccessToast, } from "../ui/anchoredCopyToast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -28,7 +27,6 @@ export const MessageCopyButton = memo(function MessageCopyButton({ }) { const ref = useRef(null); const { copyToClipboard, isCopied } = useCopyToClipboard({ - onCopy: () => showAnchoredCopySuccessToast(ref), onError: (error: Error) => showAnchoredCopyErrorToast(ref, error), timeout: ANCHORED_COPY_TOAST_TIMEOUT_MS, ...(extraFlavors ? { extraFlavors } : {}), diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.ts index 33fbb938a3c12..0a7e2297ddfa1 100644 --- a/apps/web/src/components/chat/useRightPanelActions.ts +++ b/apps/web/src/components/chat/useRightPanelActions.ts @@ -262,24 +262,15 @@ export function useRightPanelActions(input: RightPanelActionsInput) { relativePath, resolvePathLinkTarget(relativePath, gitCwd ?? activeProjectCwd ?? ""), ); - void navigator.clipboard.writeText(clipboardPath).then( - () => { - toastManager.add({ - type: "success", - title: "Path copied", - description: clipboardPath, - }); - }, - (error) => { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to copy path", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - }, - ); + void navigator.clipboard.writeText(clipboardPath).then(undefined, (error) => { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to copy path", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + }); }; const copyRightPanelFilePathStable = useStableCallback(copyRightPanelFilePath); const addPullRequestSurface = () => { diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 8729e74d27e0c..4e79632dc72a8 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -228,11 +228,6 @@ export default function FileBrowserPanel({ if (clicked === "copy-mention") { try { await writeTextToClipboard(mention); - toastManager.add({ - type: "success", - title: "Mention copied", - description: relativePath, - }); } catch (error) { toastManager.add({ type: "error", diff --git a/apps/web/src/components/media/MediaActions.tsx b/apps/web/src/components/media/MediaActions.tsx index 72c003f717a69..da383a9ba7af5 100644 --- a/apps/web/src/components/media/MediaActions.tsx +++ b/apps/web/src/components/media/MediaActions.tsx @@ -173,10 +173,6 @@ export function MediaActions({ const clipboardText = reference?.kind === "file" ? formatFilePathForClipboard(text, reference.path) : text; await writeTextToClipboard(clipboardText, reference?.kind === "file" ? "file path" : "URL"); - toastManager.add({ - type: "success", - title: action === "copy-url" ? "URL copied" : "Path copied", - }); } else if (action === "open-file") { assertCanReadMedia(); source.onOpenFile?.(); @@ -186,10 +182,7 @@ export function MediaActions({ title: action === "save" ? `Preparing ${noun} download…` : "Copying image…", }); await (action === "save" ? save() : copyImage()); - toastManager.update(progressToast, { - type: "success", - title: action === "save" ? "Download started" : "Image copied", - }); + toastManager.close(progressToast); } }); if (AsyncResult.isFailure(result)) { diff --git a/apps/web/src/components/promptLinks/copyPromptLink.ts b/apps/web/src/components/promptLinks/copyPromptLink.ts index 6f2a6762fa4a6..1ba1612d3c486 100644 --- a/apps/web/src/components/promptLinks/copyPromptLink.ts +++ b/apps/web/src/components/promptLinks/copyPromptLink.ts @@ -69,8 +69,7 @@ export function composerPromptLink(input: { export async function copyPromptLink(link: string): Promise { try { - if (!(await writeTextToClipboard(link))) return; - toastManager.add({ type: "success", title: "Prompt link copied" }); + await writeTextToClipboard(link); } catch (error) { toastManager.add( stackedThreadToast({ diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 130741ae1f928..6e4a2bb6fb6a0 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -535,7 +535,6 @@ export function PullRequestDetailPanel({ const keybindings = useAtomValue(primaryServerKeybindingsAtom); const { copyToClipboard: copyReference } = useCopyToClipboard({ target: `${terminology.singular} reference`, - onCopy: (label) => toastManager.add({ type: "success", title: `${label} copied` }), onError: (error, label) => toastManager.add({ type: "error", diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx index 06861fb6ab06a..4fb9969218c22 100644 --- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx @@ -1443,23 +1443,13 @@ export function PullRequestsPage() { const { shortLabel, singular } = ( sourceControlClients.findByChangeRequestUrl(url) ?? sourceControlClients.get(undefined) ).changeRequest; - void writeTextToClipboard(url, `${singular} link`).then( - (didCopy) => { - if (didCopy) - toastManager.add({ - type: "success", - title: `${shortLabel} link copied`, - description: url, - }); - }, - (error) => { - toastManager.add({ - type: "error", - title: `Failed to copy ${shortLabel} link`, - description: error instanceof Error ? error.message : "An error occurred.", - }); - }, - ); + void writeTextToClipboard(url, `${singular} link`).then(undefined, (error) => { + toastManager.add({ + type: "error", + title: `Failed to copy ${shortLabel} link`, + description: error instanceof Error ? error.message : "An error occurred.", + }); + }); }); const closeActiveSurfaceFromShortcut = useEffectEvent((event: KeyboardEvent) => { if (activePullRequestSurface === null) return; diff --git a/apps/web/src/components/settings/AboutVersionTitle.browser.test.tsx b/apps/web/src/components/settings/AboutVersionTitle.browser.test.tsx index 387c673c89769..777068574762e 100644 --- a/apps/web/src/components/settings/AboutVersionTitle.browser.test.tsx +++ b/apps/web/src/components/settings/AboutVersionTitle.browser.test.tsx @@ -6,7 +6,7 @@ import { APP_VERSION } from "../../branding"; import { AnchoredToastProvider } from "../ui/toast"; import { AboutVersionTitle } from "./AboutVersionTitle"; -it("shows copy confirmation when the version is clicked without waiting for a hover tooltip", async () => { +it("copies the version without a notification", async () => { await using screen = await render( @@ -17,5 +17,5 @@ it("shows copy confirmation when the version is clicked without waiting for a ho await screen.getByRole("button", { name: `Copy version ${APP_VERSION}` }).click(); expect(write).toHaveBeenCalledWith(APP_VERSION); - await expect.element(page.getByText(/^Copied!?$/)).toBeVisible(); + await expect.element(page.getByText(/^Copied!?$/)).not.toBeInTheDocument(); }); diff --git a/apps/web/src/components/settings/AboutVersionTitle.tsx b/apps/web/src/components/settings/AboutVersionTitle.tsx index 62b94bc85bda0..3bd6391ae34d7 100644 --- a/apps/web/src/components/settings/AboutVersionTitle.tsx +++ b/apps/web/src/components/settings/AboutVersionTitle.tsx @@ -1,17 +1,12 @@ -import { useRef } from "react"; - import { APP_VERSION } from "../../branding"; import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; -import { showAnchoredCopySuccessToast } from "../ui/anchoredCopyToast"; import { InlineButton } from "../ui/button"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; export function AboutVersionTitle() { - const copyButtonRef = useRef(null); const { copyToClipboard } = useCopyToClipboard({ target: "version", - onCopy: () => showAnchoredCopySuccessToast(copyButtonRef), onError: (error) => { toastManager.add( stackedThreadToast({ @@ -31,7 +26,6 @@ export function AboutVersionTitle() { copyToClipboard(APP_VERSION, undefined)} diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.tsx index c7085f5b4b44a..d2f46c09d5ffb 100644 --- a/apps/web/src/components/settings/AcpSessionManagementSection.tsx +++ b/apps/web/src/components/settings/AcpSessionManagementSection.tsx @@ -265,7 +265,6 @@ function InstanceSessionManagement( setSessions((current) => current.filter((candidate) => candidate.sessionId !== session.sessionId), ); - toastManager.add({ type: "success", title: "ACP session deleted" }); return; } reportFailure("Could not delete ACP session", result); @@ -338,7 +337,6 @@ function InstanceSessionManagement( if (generation !== projectGeneration.current) return; setSavingProviderId(null); if (result._tag === "Success") { - toastManager.add({ type: "success", title: "ACP provider configured" }); await loadProviders(provider.providerId); return; } @@ -367,7 +365,6 @@ function InstanceSessionManagement( if (generation !== projectGeneration.current) return; setSavingProviderId(null); if (result._tag === "Success") { - toastManager.add({ type: "success", title: "ACP provider disabled" }); await loadProviders(provider.providerId); return; } @@ -385,7 +382,6 @@ function InstanceSessionManagement( if (result._tag === "Success") { setSessions([]); setNextCursor(null); - toastManager.add({ type: "success", title: "Logged out of ACP agent" }); return; } reportFailure("Could not log out of ACP agent", result); diff --git a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx index f58bf7b1d1ce9..577bdd40f8c45 100644 --- a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx +++ b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx @@ -216,23 +216,6 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ value: string; kind: "code" | "hosted-link" | "link"; }>({ - onCopy: ({ kind }) => { - toastManager.add({ - type: "success", - title: - kind === "hosted-link" - ? "Hosted app link copied" - : kind === "link" - ? "Pairing URL copied" - : "Pairing code copied", - description: - kind === "hosted-link" - ? "Open it in the browser on the device you want to connect." - : kind === "link" - ? "Open it in the client you want to pair to this environment." - : "Paste it into another client to finish pairing.", - }); - }, onError: (error, { value, kind }) => { // Captured per attempt so concurrent copies cannot make the dialog // reveal a different value than the one that failed. diff --git a/apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx b/apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx index d896efe455216..df88b12e64841 100644 --- a/apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx +++ b/apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx @@ -129,7 +129,6 @@ export function ConnectionDiagnosisPanel({ }) { const { copyToClipboard } = useCopyToClipboard({ target: "connection diagnostics", - onCopy: () => toastManager.add({ type: "success", title: "Diagnostics copied" }), onError: (error) => toastManager.add( stackedThreadToast({ diff --git a/apps/web/src/components/settings/SavedEnvironmentRows.tsx b/apps/web/src/components/settings/SavedEnvironmentRows.tsx index 805d914f1a74a..540514e98fa82 100644 --- a/apps/web/src/components/settings/SavedEnvironmentRows.tsx +++ b/apps/web/src/components/settings/SavedEnvironmentRows.tsx @@ -131,13 +131,6 @@ export function SavedBackendListRow({ const errorTraceId = environment.connection.traceId; const { copyToClipboard: copyTraceIdToClipboard } = useCopyToClipboard<{ traceId: string }>({ target: "trace ID", - onCopy: ({ traceId }) => { - toastManager.add({ - type: "success", - title: "Trace ID copied", - description: traceId, - }); - }, onError: (error) => { toastManager.add( stackedThreadToast({ diff --git a/apps/web/src/components/settings/ThemeEditorHost.tsx b/apps/web/src/components/settings/ThemeEditorHost.tsx index 66c8123bf4288..6731c8c827463 100644 --- a/apps/web/src/components/settings/ThemeEditorHost.tsx +++ b/apps/web/src/components/settings/ThemeEditorHost.tsx @@ -44,13 +44,6 @@ export function ThemeEditorHost() { ); return false; } - toastManager.add( - stackedThreadToast({ - type: "success", - title: `${savedTheme.label} updated`, - description: `Its ${mergedAppearance} palette was added.`, - }), - ); return true; } if (!created) { @@ -60,13 +53,6 @@ export function ThemeEditorHost() { themeHalves?.light === savedTheme.id || themeHalves?.dark === savedTheme.id; if (wasActive) refreshTheme(); - toastManager.add( - stackedThreadToast({ - type: "success", - title: `${savedTheme.label} saved`, - description: wasActive ? "Your changes are now active." : "Your changes are saved.", - }), - ); return true; } @@ -80,13 +66,6 @@ export function ThemeEditorHost() { ); return false; } - toastManager.add( - stackedThreadToast({ - type: "success", - title: `${savedTheme.label} created`, - description: "It’s now active.", - }), - ); return true; }; diff --git a/apps/web/src/components/ui/anchoredCopyToast.ts b/apps/web/src/components/ui/anchoredCopyToast.ts index a22d3104f9ef6..ba861e737b494 100644 --- a/apps/web/src/components/ui/anchoredCopyToast.ts +++ b/apps/web/src/components/ui/anchoredCopyToast.ts @@ -3,20 +3,6 @@ import { anchoredToastManager } from "./toast"; export const ANCHORED_COPY_TOAST_TIMEOUT_MS = 1000; -export function showAnchoredCopySuccessToast(ref: RefObject) { - if (!ref.current) return; - anchoredToastManager.add({ - data: { - tooltipStyle: true, - }, - positionerProps: { - anchor: ref.current, - }, - timeout: ANCHORED_COPY_TOAST_TIMEOUT_MS, - title: "Copied!", - }); -} - export function showAnchoredCopyErrorToast(ref: RefObject, error: Error) { if (!ref.current) return; anchoredToastManager.add({ diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index bf22bd066b9a4..f96baf908b3d9 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -97,22 +97,13 @@ export function useThreadActionMenu(input: { const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive); const timestampFormat = useClientSettings((s) => s.timestampFormat); const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({ - onCopy: ({ path }) => { - toastManager.add({ type: "success", title: "Path copied", description: path }); - }, onError: (error) => failureToast("Failed to copy path", error), }); const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({ target: "branch name", - onCopy: ({ branch }) => { - toastManager.add({ type: "success", title: "Branch copied", description: branch }); - }, onError: (error) => failureToast("Failed to copy branch", error), }); const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({ - onCopy: ({ threadId }) => { - toastManager.add({ type: "success", title: "Thread ID copied", description: threadId }); - }, onError: (error) => failureToast("Failed to copy thread ID", error), }); diff --git a/apps/web/src/lib/copyThreadReference.ts b/apps/web/src/lib/copyThreadReference.ts index bbfa3b73a2c9c..aab0292be2380 100644 --- a/apps/web/src/lib/copyThreadReference.ts +++ b/apps/web/src/lib/copyThreadReference.ts @@ -10,17 +10,11 @@ import { writeTextToClipboard } from "../hooks/useCopyToClipboard"; export async function copyThreadReference(target: ThreadReferenceCopyTarget): Promise { const fragment = target.fragment ? encodeComposerContextFragment(target.fragment) : null; try { - const didCopy = await writeTextToClipboard( + await writeTextToClipboard( target.value, target.clipboardTarget, fragment ? { [COMPOSER_CONTEXT_CLIPBOARD_MIME]: fragment } : undefined, ); - if (!didCopy) return; - toastManager.add({ - type: "success", - title: target.successTitle, - description: target.description, - }); } catch (error) { console.error(error); toastManager.add( From 9d6da455e205de3c63ebf7dc7951bce5f2a2204a Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sat, 14 Nov 2026 01:08:09 -0600 Subject: [PATCH 023/524] fix(server): idle delegated tasks when recovery holds follow-ups (#36529) --- .../DelegatedCompletionDelivery.test.ts | 93 +++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 5 +- 2 files changed, 97 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 22827388bffa0..e26487fdf2667 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -48,6 +48,7 @@ import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as EventSink from "./EventSink.ts"; import * as Orchestrator from "./Orchestrator.ts"; +import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts"; import { continueRestartedRun } from "./RestartContinuation.ts"; import * as RuntimeLayer from "./runtimeLayer.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; @@ -4856,6 +4857,98 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { }), ); + it.effect("holding a follow-up during runtime recovery makes its parent task idle", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:held-followup-parent"); + const projectId = ProjectId.make("project:held-followup"); + const runId = RunId.make("run:held-followup-parent"); + const rootNodeId = NodeId.make("node:held-followup-parent"); + yield* seedParentWithTerminalTask({ + threadId, + projectId, + runId, + rootNodeId, + taskId: NodeId.make("node:held-followup-seed"), + deliveryState: "delivered", + now, + }); + const child = yield* seedRestartCancelledChild({ + parentThreadId: threadId, + projectId, + parentRunId: runId, + rootNodeId, + name: "held-followup-child", + completionWake: "always", + continuationPending: false, + now, + }); + yield* orchestrator.recoverDelegatedTasks; + const parent = yield* orchestrator.getThreadProjection(threadId); + const original = parent.subagents.find((task) => task.id === child.taskId)!; + const taskId = NodeId.make("node:held-followup"); + const held = runEvent({ + threadId: child.childThreadId, + runId: RunId.make("run:held-followup"), + ordinal: 2, + status: "queued", + now, + }); + yield* sink.write({ + commandId: reconcileCommandId("held-followup"), + events: [ + { + ...held, + payload: { + ...held.payload, + delegatedTaskId: taskId, + startedAt: null, + completedAt: null, + queueHeld: false, + }, + }, + { + id: EventId.make("event:held-followup-task"), + type: "subagent.updated", + threadId, + runId, + nodeId: taskId, + occurredAt: now, + payload: { + ...original, + id: taskId, + status: "pending", + result: null, + completedAt: null, + completionDelivery: { state: "pending", observedByRunId: null }, + }, + }, + ], + }); + + const afterSequence = yield* sink.latestSequence(); + yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup"); + yield* sink.stream({ afterSequence, eventType: "subagent.updated" }).pipe( + Stream.filter( + (stored) => + stored.event.type === "subagent.updated" && + stored.event.payload.id === taskId && + stored.event.payload.status === "idle", + ), + Stream.take(1), + Stream.runDrain, + ); + + const recovered = yield* orchestrator.getThreadProjection(threadId); + assert.equal(recovered.subagents.find((task) => task.id === taskId)?.status, "idle"); + const queued = (yield* orchestrator.getThreadProjection(child.childThreadId)).runs.at(-1)!; + assert.equal(queued.status, "queued"); + assert.isTrue(queued.queueHeld); + }), + ); + it.effect("settles a child whose provider failure holds its queued wakes", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index c732e0ca67ccf..0140b7b4dc071 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -15515,7 +15515,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio Stream.filter( (stored) => stored.event.type === "run.updated" && - !String(stored.commandId).startsWith("command:runtime-reconcile:") && + (!String(stored.commandId).startsWith("command:runtime-reconcile:") || + (stored.event.payload.delegatedTaskId !== undefined && + stored.event.payload.status === "queued" && + stored.event.payload.queueHeld === true)) && ((stored.event.payload.delegatedTaskId !== undefined && (stored.event.payload.status === "queued" || stored.event.payload.status === "starting")) || From 058eea9246ffbf79fdc26f9988cd48c50f81d0ea Mon Sep 17 00:00:00 2001 From: Simon Maggini Date: Sat, 14 Nov 2026 08:11:20 +0100 Subject: [PATCH 024/524] fix(pr): hide unsupported GitCafe review reactions (#36171) Co-authored-by: Julius Marminge --- .../pull-requests/PullRequestReactions.tsx | 4 +- .../usePullRequestPermissions.ts | 3 ++ .../pullRequest/PullRequestSummaryTab.tsx | 3 +- .../pullRequest/PullRequestTimelineTab.tsx | 16 +++++--- .../src/pullRequestReactions.test.ts | 40 ++++++++++++++++++- .../src/pullRequestReactions.ts | 17 +++++++- 6 files changed, 71 insertions(+), 12 deletions(-) diff --git a/apps/mobile/src/features/pull-requests/PullRequestReactions.tsx b/apps/mobile/src/features/pull-requests/PullRequestReactions.tsx index 394fc630a0046..722a435d2f118 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestReactions.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestReactions.tsx @@ -145,7 +145,7 @@ export function PullRequestCommentFooter(props: { >; readonly permissions: Pick< ReturnType, - "canEditComment" | "canReact" + "canEditComment" | "canReactComment" >; readonly onChanged: () => void; readonly onEdit?: () => void; @@ -155,7 +155,7 @@ export function PullRequestCommentFooter(props: { const reactions = comment.reactions ?? []; const editableKind = comment.kind === "review" ? null : comment.kind; const canEdit = editableKind !== null && props.permissions.canEditComment(comment); - const { canReact } = props.permissions; + const canReact = props.permissions.canReactComment(comment); if (reactions.length === 0 && !canReact && !canEdit) return null; return ( diff --git a/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts b/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts index 28a2bbb04cc97..38ba2b74deb24 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestPermissions.ts @@ -4,6 +4,7 @@ import { canEditPullRequestComment, canEditPullRequestMaintainerEdits, } from "@t3tools/client-runtime/pull-request-editing"; +import { canReactPullRequestComment } from "@t3tools/client-runtime/pull-request-reactions"; import type { PullRequestComment, PullRequestDetail } from "@t3tools/contracts"; import { usePullRequestConnected } from "./usePullRequestConnected"; import { composerPullRequests } from "../../state/pull-requests"; @@ -54,6 +55,8 @@ export function usePullRequestPermissions(params: PullRequestParams, pr: PullReq connected && canUpdate && pr !== null && canEditPullRequestMaintainerEdits(pr), canEditComment: (comment: Pick) => connected && canUpdateComment && pr !== null && canEditPullRequestComment(pr, comment), + canReactComment: (comment: Pick) => + connected && canSetReaction && pr !== null && canReactPullRequestComment(pr, comment), canReact: connected && canSetReaction && pr?.capabilities.reactions === true, canComment: connected && canComment && pr?.capabilities.comment === true && pr.viewerPermissions.comment, diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx index 3da06db5cd8b3..15e0769a700da 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx @@ -97,6 +97,7 @@ import { pullRequestCompletionScope, } from "./PullRequestMarkdownTextarea"; import { PullRequestReactionBar } from "./PullRequestReactions"; +import { canReactPullRequestComment } from "@t3tools/client-runtime/pull-request-reactions"; import { PullRequestResolveThreadButton } from "./PullRequestResolveThreadButton"; import { PullRequestConversationGhost } from "./PullRequestGhosts"; import { sectionCollapseAnchorScrollTop } from "./pullRequestSummaryScroll.logic"; @@ -695,7 +696,7 @@ export function PullRequestSummaryTab({ boolean; /** Absent where there is no composer beside the panel to add a remark to. */ readonly onAddToChat?: ((comment: PullRequestComment) => void) | undefined; readonly environmentId: EnvironmentId; @@ -245,6 +246,7 @@ function ConversationCard({ /** A reply goes with its conversation, from the card that heads it. */ reply?: boolean; }) { + const canReact = reactions.canReact(event); const [editing, setEditing] = useState(false); const [saving, setSaving] = useState(false); const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, { @@ -304,11 +306,11 @@ function ConversationCard({ {event.body && event.comment && !reply ? ( ) : null} - {reactions.canReact || event.reactions.length > 0 ? ( + {canReact || event.reactions.length > 0 ? ( void; reactions: ReactionSurface; }) { + const canReact = reactions.canReact(event); return (
) : null} - {reactions.canReact || event.reactions.length > 0 ? ( + {canReact || event.reactions.length > 0 ? ( + event.comment !== undefined && canReactPullRequestComment(detail, event.comment), onAddToChat: onAddToChat && ((comment) => onAddToChat({ kind: "comment", comment })), environmentId, threadRef, diff --git a/packages/client-runtime/src/pullRequestReactions.test.ts b/packages/client-runtime/src/pullRequestReactions.test.ts index a88d0bbf7ac7a..9beefb3abef77 100644 --- a/packages/client-runtime/src/pullRequestReactions.test.ts +++ b/packages/client-runtime/src/pullRequestReactions.test.ts @@ -1,7 +1,15 @@ -import type { PullRequestReaction, PullRequestReactionContent } from "@t3tools/contracts"; +import { + SourceControlProviderKind, + type PullRequestDetail, + type PullRequestReaction, + type PullRequestReactionContent, +} from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { applyPendingPullRequestReactions } from "./pullRequestReactions.ts"; +import { + applyPendingPullRequestReactions, + canReactPullRequestComment, +} from "./pullRequestReactions.ts"; function reaction(overrides: Partial = {}): PullRequestReaction { return { @@ -13,6 +21,34 @@ function reaction(overrides: Partial = {}): PullRequestReac }; } +describe("comment reaction permissions", () => { + it("excludes only GitCafe review summaries from comment reactions", () => { + const detail = { + provider: SourceControlProviderKind.make("gitcafe"), + capabilities: { + diff: true, + comment: true, + actions: [], + mergeMethods: [], + search: true, + reactions: true, + review: { inlineComment: true, reply: true, resolve: true, verdicts: [] }, + reviewers: { request: true, listCandidates: true }, + }, + } satisfies Pick; + + expect(canReactPullRequestComment(detail, { kind: "issue-comment" })).toBe(true); + expect(canReactPullRequestComment(detail, { kind: "review-comment" })).toBe(true); + expect( + canReactPullRequestComment( + { ...detail, provider: SourceControlProviderKind.make("github") }, + { kind: "review" }, + ), + ).toBe(true); + expect(canReactPullRequestComment(detail, { kind: "review" })).toBe(false); + }); +}); + describe("pending reactions", () => { const pending = ( entries: ReadonlyArray, diff --git a/packages/client-runtime/src/pullRequestReactions.ts b/packages/client-runtime/src/pullRequestReactions.ts index f20e94603267a..ce96903506bc1 100644 --- a/packages/client-runtime/src/pullRequestReactions.ts +++ b/packages/client-runtime/src/pullRequestReactions.ts @@ -1,4 +1,19 @@ -import type { PullRequestReaction, PullRequestReactionContent } from "@t3tools/contracts"; +import type { + PullRequestComment, + PullRequestDetail, + PullRequestReaction, + PullRequestReactionContent, +} from "@t3tools/contracts"; + +export function canReactPullRequestComment( + detail: Pick, + comment: Pick, +): boolean { + return ( + detail.capabilities.reactions === true && + !(detail.provider === "gitcafe" && comment.kind === "review") + ); +} export const PULL_REQUEST_REACTION_ORDER: ReadonlyArray = [ "thumbs-up", From 0516493a914c193f548b6201463ba6d5f5ad9f70 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sat, 14 Nov 2026 01:12:01 -0600 Subject: [PATCH 025/524] fix(web): align status text and tighten pull request menu spacing (#36528) --- apps/web/src/components/GitActionsControl.tsx | 48 ++++++++++++------- .../components/chat/ComposerBannerStack.tsx | 2 +- .../components/chat/ThreadDetailsControl.tsx | 4 ++ .../components/chat/ThreadDetailsPrRow.tsx | 6 +-- 4 files changed, 37 insertions(+), 23 deletions(-) diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index a019b729d3190..7ae210230a612 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -21,7 +21,7 @@ import type { } from "@t3tools/contracts"; import { useNavigate } from "@tanstack/react-router"; import * as Option from "effect/Option"; -import { useEffect, useEffectEvent, useRef, useState } from "react"; +import { useEffect, useEffectEvent, useId, useRef, useState } from "react"; import { useDeadlinePassed } from "../hooks/useDeadline"; import { useNowSecond } from "../hooks/useNowSecond"; import { flushSync } from "react-dom"; @@ -354,26 +354,46 @@ function RunningGitActionElapsedTime({ return null; } - return

{elapsed}

; + return ( +

+ {elapsed} +

+ ); } -function GitActionProgressButtonContent({ progress }: { progress: GitActionProgressPresentation }) { +function GitActionProgressButtonContent({ + progress, + id, +}: { + progress: GitActionProgressPresentation; + id: string; +}) { const hasOutput = progress.output !== null; return (