From 34701646e39077be00302a7fd66a12a96e2fcf37 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 4 Nov 2026 19:22:56 -0800 Subject: [PATCH 001/397] revert(web): working threads stay in the Working shelf when their environment disconnects (#31269) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/Sidebar.logic.test.ts | 34 ------------------- apps/web/src/components/Sidebar.logic.ts | 24 ------------- apps/web/src/components/Sidebar.tsx | 26 ++------------ apps/web/src/state/environments.ts | 4 --- 4 files changed, 2 insertions(+), 86 deletions(-) diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 574ae3b402126..9e7489a0ffca1 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -11,8 +11,6 @@ import { getFallbackThreadIdAfterDelete, hasUnseenCompletion, resolveSidebarRowThreadId, - belongsInSidebarWorkingShelf, - isSidebarEnvironmentDisconnected, orderItemsByPreferredIds, pinOrderKeyBetween, resolveSidebarSweepKeys, @@ -1010,38 +1008,6 @@ describe("Working shelf (beta)", () => { ).toBe(false); }); - it.each([ - ["connected", true, false], - ["connected", false, true], - ["connecting", false, false], - ["reconnecting", false, true], - ["offline", false, true], - ["error", false, true], - ["unsupported", false, true], - ["available", false, true], - ] as const)( - "lists threads outside the shelf on a %s environment: %s", - (phase, shellIsLive, disconnected) => { - expect(isSidebarEnvironmentDisconnected(phase, shellIsLive)).toBe(disconnected); - }, - ); - - it("lists a running thread outside the shelf while its environment is disconnected", () => { - const thread = { ...idle, runtime, environmentId: localEnvironmentId }; - const shelve = (disconnected: ReadonlyArray, enabled = true) => - belongsInSidebarWorkingShelf(thread, { - enabled, - disconnectedEnvironmentIds: new Set(disconnected), - isWorking: isSidebarThreadWorking, - }); - - expect(shelve([])).toBe(true); - expect(shelve([localEnvironmentId])).toBe(false); - expect(shelve([])).toBe(true); - expect(shelve([EnvironmentId.make("environment-other")])).toBe(true); - expect(shelve([], false)).toBe(false); - }); - describe("sortInboxThreadsByReturn", () => { const thread = ( id: string, diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 5af89dd0224b8..e2c6a60fc33d5 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -16,7 +16,6 @@ import { type ThreadSearchShell, } from "@t3tools/client-runtime/state/thread-search"; import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch"; -import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; import { isListedThreadLineage, type ContextMenuItem, @@ -185,29 +184,6 @@ export function resolveSidebarThreadSection(input: { return "active"; } -// Keep cached placement on the first connection attempt, matching mobile's threadRouteIsHydrating. -export function isSidebarEnvironmentDisconnected( - phase: EnvironmentConnectionPhase, - shellIsLive: boolean, -): boolean { - return phase !== "connecting" && (phase !== "connected" || !shellIsLive); -} - -export function belongsInSidebarWorkingShelf( - thread: T, - input: { - readonly enabled: boolean; - readonly disconnectedEnvironmentIds: ReadonlySet; - readonly isWorking: (thread: T) => boolean; - }, -): boolean { - return ( - input.enabled && - !input.disconnectedEnvironmentIds.has(thread.environmentId) && - input.isWorking(thread) - ); -} - const SIDEBAR_MARKER_PREFIX = "sidebar-marker-"; export type SidebarListMarker = diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 18aa27709e4c0..a10183a32d8f0 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1,4 +1,3 @@ -import { liveShellEnvironmentIdsAtom } from "../state/shell"; import { attachSidebarTree } from "../lib/sidebarTree"; import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts"; import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; @@ -140,7 +139,6 @@ import { useNowMinute } from "../hooks/useNowMinute"; import { useEnvironmentIdentities, useConnectedEnvironmentIds, - useEnvironmentConnectionSummaries, useEnvironmentMachines, usePrimaryEnvironmentId, } from "../state/environments"; @@ -187,8 +185,6 @@ import { deleteSelectedThreadEntries, filterSidebarProjectScopeItems, firstValidTimestampMs, - belongsInSidebarWorkingShelf, - isSidebarEnvironmentDisconnected, isSidebarNestedLinkClick, isTrailingDoubleClick, orderItemsByPreferredIds, @@ -356,7 +352,6 @@ interface SidebarThreadPartitionInput { readonly workingShelfEnabled: boolean; /** Boring mode: folders list active threads by the user's latest message. */ readonly sortActiveBySend: boolean; - readonly disconnectedEnvironmentIds: ReadonlySet; // Snooze wakes, the queued-turn grace and the Working shelf's exit grace depend // on the clock, so the minute tick, the precise snooze-wake tick and the inbox // tracker's expiry version are inputs: a new key repartitions. @@ -442,18 +437,6 @@ function useSidebarThreads(input: { // Folders already separate the work, so boring mode has no Working shelf. const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled) && folderGroups === null; - const environmentConnections = useEnvironmentConnectionSummaries(); - const liveShellEnvironmentIds = useAtomValue(liveShellEnvironmentIdsAtom); - const disconnectedEnvironmentIds = new Set( - environmentConnections - .filter((environment) => - isSidebarEnvironmentDisconnected( - environment.connectionState, - liveShellEnvironmentIds.has(environment.environmentId), - ), - ) - .map((environment) => environment.environmentId), - ); const inboxReturnsVersion = useSyncExternalStore( inboxReturns.subscribe, inboxReturns.getSnapshot, @@ -498,7 +481,6 @@ function useSidebarThreads(input: { optimisticDrop, workingShelfEnabled, sortActiveBySend: folderGroups !== null, - disconnectedEnvironmentIds, clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`, }); @@ -634,7 +616,6 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { optimisticDrop, workingShelfEnabled, sortActiveBySend, - disconnectedEnvironmentIds, } = input; const preciseNow = new Date().toISOString(); const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys, delegatedUnderParent); @@ -643,11 +624,8 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { const active: EnvironmentThreadShell[] = []; const working: EnvironmentThreadShell[] = []; const inbox = (thread: EnvironmentThreadShell, manuallyMoved = false) => - belongsInSidebarWorkingShelf(thread, { - enabled: workingShelfEnabled, - disconnectedEnvironmentIds, - isWorking: manuallyMoved ? isThreadWorking : inboxObservation.isWorking, - }) + workingShelfEnabled && + (manuallyMoved ? isThreadWorking(thread) : inboxObservation.isWorking(thread)) ? working : active; const snoozed: EnvironmentThreadShell[] = []; diff --git a/apps/web/src/state/environments.ts b/apps/web/src/state/environments.ts index a35af5e094a00..0b2cab287d223 100644 --- a/apps/web/src/state/environments.ts +++ b/apps/web/src/state/environments.ts @@ -114,7 +114,3 @@ export function useEnvironmentMachines() { export function useConnectedEnvironmentIds() { return useAtomValue(environmentSummaries.connectedEnvironmentIdsAtom); } - -export function useEnvironmentConnectionSummaries() { - return useAtomValue(environmentSummaries.environmentsAtom); -} From e313a122452835da330feef41d0b74a4d2eddbeb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 4 Nov 2026 19:31:10 -0800 Subject: [PATCH 002/397] refactor: Effect code reads env through HostProcess.Environment (#31218) Co-authored-by: Claude Opus 5.5 --- apps/desktop/src/app/DesktopApp.ts | 11 +- .../desktop/src/app/DesktopCliCommand.test.ts | 36 ++-- apps/desktop/src/app/DesktopCliCommand.ts | 15 +- apps/desktop/src/app/DesktopConfig.ts | 2 +- .../src/app/DesktopPreReadyPlatform.test.ts | 19 +- .../src/app/DesktopPreReadyPlatform.ts | 22 ++- .../DesktopBackendConfiguration.test.ts | 175 +++++++----------- .../backend/DesktopBackendConfiguration.ts | 8 +- apps/desktop/src/snapShot/DesktopSnapShot.ts | 5 +- apps/desktop/src/wsl/DesktopWslEnvironment.ts | 4 +- .../transferBudgetV2.integration.test.ts | 9 +- apps/server/scripts/acp-mock-agent.ts | 8 +- .../record-codex-app-server-replay-fixture.ts | 18 +- .../scripts/record-fx-acp-replay-fixture.ts | 26 ++- .../scripts/record-grok-acp-replay-fixture.ts | 15 +- .../scripts/record-kiro-acp-replay-fixture.ts | 18 +- apps/server/src/cli/app.test.ts | 21 ++- apps/server/src/cli/uninstall.test.ts | 6 +- .../src/cloud/ManagedEndpointRuntime.test.ts | 38 ++-- .../src/cloud/ManagedEndpointRuntime.ts | 9 +- .../src/device/AgentDeviceTarget.test.ts | 3 +- apps/server/src/git/GitManager.ts | 7 +- .../ClaudeAgentSdkQueryRunner.test.ts | 4 +- .../src/project/ManagedProjectFolders.test.ts | 34 ++-- .../provider/ClaudeCapabilitiesProbe.test.ts | 3 +- .../src/provider/CodexManagedRuntime.test.ts | 5 +- .../provider/acp/AcpJsonRpcConnection.test.ts | 22 ++- apps/server/src/serviceLauncher.test.ts | 3 +- .../ClaudeTextGeneration.test.ts | 150 +++------------ apps/server/src/vcs/GitVcsDriver.test.ts | 15 +- apps/server/src/vcs/GitVcsDriver.ts | 5 +- apps/server/src/vcs/GitVcsDriverCore.test.ts | 79 +++----- apps/server/src/vcs/GitVcsDriverCore.ts | 2 +- evals/mcp-tool-use/run.ts | 3 +- .../effect-acp/test/fixtures/acp-mock-peer.ts | 6 +- .../scripts/generate.ts | 7 +- .../test/examples/codex-app-server-probe.ts | 4 +- .../src/server/AcpRegistrySupport.test.ts | 12 +- .../src/server/ForgejoCli.ts | 15 +- scripts/build-npm-launcher.test.ts | 8 +- tsconfig.effect.json | 1 + 41 files changed, 404 insertions(+), 449 deletions(-) diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 8bdd1957cbfb7..151c227e47ff4 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -1,4 +1,5 @@ import * as Cause from "effect/Cause"; +import * as Config from "effect/Config"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -42,6 +43,11 @@ const DEFAULT_DESKTOP_BACKEND_PORT = 3773; const MAX_TCP_PORT = 65_535; const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const; +const LinuxDesktopSessionConfig = Config.all({ + current: Config.String("XDG_CURRENT_DESKTOP").pipe(Config.option), + session: Config.String("XDG_SESSION_DESKTOP").pipe(Config.option), +}); + const makeDesktopRunId = SecureRandom.SecureRandom.pipe( Effect.flatMap((random) => random.uuidV4()), Effect.map((value) => value.replaceAll("-", "").slice(0, 12)), @@ -307,12 +313,13 @@ const startup = Effect.gen(function* () { yield* desktopSettings.load; if (linuxElectronOptions !== null) { + const xdgDesktop = yield* LinuxDesktopSessionConfig; yield* logStartupInfo("linux password store configured", { passwordStore: hasCommandLinePasswordStore ? "command-line" : (linuxElectronOptions.passwordStore ?? "electron-default"), - xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null, - xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null, + xdgCurrentDesktop: Option.getOrNull(xdgDesktop.current), + xdgSessionDesktop: Option.getOrNull(xdgDesktop.session), }); } diff --git a/apps/desktop/src/app/DesktopCliCommand.test.ts b/apps/desktop/src/app/DesktopCliCommand.test.ts index 8566613dd6069..ebb32bda43ced 100644 --- a/apps/desktop/src/app/DesktopCliCommand.test.ts +++ b/apps/desktop/src/app/DesktopCliCommand.test.ts @@ -1,5 +1,5 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; -import { afterEach, beforeEach, expect, it } from "@effect/vitest"; +import { expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -29,7 +29,13 @@ const environmentFor = ( } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]); const commandIn = ( - input: { home: string; baseDir?: string; platform?: NodeJS.Platform; isPackaged?: boolean }, + input: { + home: string; + baseDir?: string; + platform?: NodeJS.Platform; + isPackaged?: boolean; + env?: NodeJS.ProcessEnv; + }, spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"], ) => Effect.gen(function* () { @@ -42,6 +48,7 @@ const commandIn = ( DesktopEnvironment.DesktopEnvironment, environmentFor(path, { ...input, baseDir }), ), + Effect.provideService(HostProcess.Environment, input.env ?? { PATH: "" }), ); return yield* spawner ? make.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)) @@ -84,14 +91,6 @@ const fakePowerShell = (initial: string) => { return { registry, spawner }; }; -const machinePath = process.env.PATH; -beforeEach(() => { - process.env.PATH = ""; -}); -afterEach(() => { - process.env.PATH = machinePath; -}); - it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { it.effect("links the launcher onto PATH and removes only that link", () => Effect.gen(function* () { @@ -124,7 +123,8 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const home = yield* fs.makeTempDirectoryScoped(); - const command = yield* commandIn({ home }); + const env: NodeJS.ProcessEnv = { PATH: "" }; + const command = yield* commandIn({ home, env }); const theirs = path.join(home, ".local", "bin", "t3"); yield* fs.makeDirectory(path.dirname(theirs), { recursive: true }); yield* fs.writeFileString(theirs, "npm's t3\n"); @@ -139,7 +139,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { const launcher = path.join(home, ".t3", "bin", "t3"); yield* fs.writeFileString(launcher, "npm's t3\n"); - process.env.PATH = path.dirname(launcher); + env.PATH = path.dirname(launcher); expect(yield* command.state).toMatchObject({ onPath: false, shadowedBy: launcher }); expect((yield* Effect.flip(command.install)).message).toContain("Could not set up"); yield* command.uninstall; @@ -173,9 +173,9 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { const shadow = path.join(home, "shadow"); yield* fs.makeDirectory(shadow); yield* fs.writeFileString(path.join(shadow, "t3"), "#!/bin/sh\n", { mode: 0o755 }); - process.env.PATH = [shadow, path.join(home, ".local", "bin")].join(":"); + const env = { PATH: [shadow, path.join(home, ".local", "bin")].join(":") }; - const command = yield* commandIn({ home }); + const command = yield* commandIn({ home, env }); const theirs = path.join(shadow, "t3"); expect((yield* command.state).shadowedBy).toBe(theirs); const error = yield* Effect.flip(command.install); @@ -209,9 +209,9 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { yield* fs.chmod(path.join(plain, "t3"), process.getuid?.() === 0 ? 0o600 : 0o601); yield* fs.makeDirectory(shadow); yield* fs.writeFileString(path.join(shadow, "t3"), "#!/bin/sh\n", { mode: 0o755 }); - process.env.PATH = [folder, plain, shadow, path.join(home, ".local", "bin")].join(":"); + const env = { PATH: [folder, plain, shadow, path.join(home, ".local", "bin")].join(":") }; - const command = yield* commandIn({ home }); + const command = yield* commandIn({ home, env }); expect((yield* command.state).shadowedBy).toBe(path.join(shadow, "t3")); const error = yield* Effect.flip(command.install); @@ -231,9 +231,9 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { const path = yield* Path.Path; const home = yield* fs.makeTempDirectoryScoped(); const launcher = path.join(home, ".t3", "bin", "t3"); - process.env.PATH = [path.dirname(launcher), path.join(home, ".local", "bin")].join(":"); + const env = { PATH: [path.dirname(launcher), path.join(home, ".local", "bin")].join(":") }; - const command = yield* commandIn({ home }); + const command = yield* commandIn({ home, env }); const installed = yield* command.install; expect(yield* fs.exists(launcher)).toBe(true); diff --git a/apps/desktop/src/app/DesktopCliCommand.ts b/apps/desktop/src/app/DesktopCliCommand.ts index f53895a60a570..5dfb579cf2cc5 100644 --- a/apps/desktop/src/app/DesktopCliCommand.ts +++ b/apps/desktop/src/app/DesktopCliCommand.ts @@ -2,6 +2,7 @@ import * as NodeFSP from "node:fs/promises"; import type { DesktopCliCommandState } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -61,11 +62,13 @@ export class DesktopCliCommand extends Context.Service< } >()("@t3tools/desktop/app/DesktopCliCommand") {} -/** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fs = yield* FileSystem.FileSystem; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + // Read the live env: shell discovery patches PATH after startup, and Windows variable + // names are case-insensitive only on process.env, not on Config's copy of it. + const env = yield* HostProcess.Environment; const path = environment.path; const windows = environment.platform === "win32"; const launcher = DesktopCliShim.launcherPath(environment); @@ -105,15 +108,15 @@ export const make = Effect.gen(function* () { Effect.orElseSucceed(() => false), ); - const powershell = (env: Record) => + const powershell = (overrides: Record) => Effect.scoped( Effect.gen(function* () { - const root = process.env.SystemRoot ?? process.env.WINDIR; + const root = env.SystemRoot ?? env.WINDIR; const handle = yield* spawner.spawn( ChildProcess.make( root ? `${root}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe` : "powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", WINDOWS_USER_PATH_SCRIPT], - { stdin: "ignore", stderr: "ignore", env, extendEnv: true }, + { stdin: "ignore", stderr: "ignore", env: overrides, extendEnv: true }, ), ); const [stdout, exitCode] = yield* Effect.all( @@ -144,7 +147,7 @@ export const make = Effect.gen(function* () { ); const firstOnPath = Effect.gen(function* () { - for (const directory of pathEntries(process.env.PATH, ":")) { + for (const directory of pathEntries(env.PATH, ":")) { const candidate = path.join(directory, "t3"); if (yield* isExecutableFile(candidate)) return Option.some(candidate); } @@ -239,7 +242,7 @@ export const make = Effect.gen(function* () { `Another t3 at ${shadowedBy.value} runs first in a new terminal. Remove it, or run the launcher directly at ${launcher}.`, ); } - const onPath = pathEntries(process.env.PATH, ":"); + const onPath = pathEntries(env.PATH, ":"); const candidates = unixCandidates(environment.homeDirectory, environment.platform); for (const directory of [ ...candidates.filter((candidate) => onPath.includes(candidate)), diff --git a/apps/desktop/src/app/DesktopConfig.ts b/apps/desktop/src/app/DesktopConfig.ts index 11f975a6b86af..ef2909045bb4f 100644 --- a/apps/desktop/src/app/DesktopConfig.ts +++ b/apps/desktop/src/app/DesktopConfig.ts @@ -8,7 +8,7 @@ const trimNonEmptyOption = (value: string): Option.Option => { return trimmed.length > 0 ? Option.some(trimmed) : Option.none(); }; -const trimmedString = (name: string) => +export const trimmedString = (name: string) => Config.String(name).pipe(Config.option, Config.map(Option.flatMap(trimNonEmptyOption))); const optionalBoolean = (name: string) => diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts index f2b176ee3761f..22bfc969c4088 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts @@ -57,6 +57,7 @@ vi.mock("node:child_process", () => ({ execFileSync: execFileSyncMock, })); +import * as DesktopConfig from "./DesktopConfig.ts"; import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts"; describe("DesktopPreReadyPlatform", () => { @@ -124,8 +125,6 @@ describe("DesktopPreReadyPlatform", () => { { previousEntry: 'Exec="/Applications/deleted-previous.AppImage" %U', label: "stale" }, ])("prepares a $label Linux desktop entry before startup yields", ({ previousEntry }) => { vi.stubEnv("VITE_DEV_SERVER_URL", ""); - vi.stubEnv("XDG_DATA_HOME", "/xdg"); - vi.stubEnv("APPIMAGE", "/Applications/current.AppImage"); getSwitchValueMock.mockReturnValue(""); let desktopName = "t3code.desktop"; let desktopEntry = previousEntry; @@ -150,6 +149,12 @@ describe("DesktopPreReadyPlatform", () => { yield* Layer.build( DesktopPreReadyPlatform.layer.pipe( Layer.provide(Layer.succeed(HostProcess.Platform, "linux")), + Layer.provide( + DesktopConfig.layerTest({ + XDG_DATA_HOME: "/xdg", + APPIMAGE: "/Applications/current.AppImage", + }), + ), ), ); const identity = yield* Effect.promise(() => portalIdentity); @@ -168,9 +173,6 @@ describe("DesktopPreReadyPlatform", () => { it.effect("points the early portal entry at a configured distribution launcher", () => { vi.stubEnv("VITE_DEV_SERVER_URL", ""); - vi.stubEnv("XDG_DATA_HOME", "/xdg"); - vi.stubEnv("APPIMAGE", "/Applications/current.AppImage"); - vi.stubEnv("T3CODE_DESKTOP_LAUNCHER_PATH", " /opt/T3 Code/t3code "); getSwitchValueMock.mockReturnValue(""); return Effect.scoped( @@ -178,6 +180,13 @@ describe("DesktopPreReadyPlatform", () => { yield* Layer.build( DesktopPreReadyPlatform.layer.pipe( Layer.provide(Layer.succeed(HostProcess.Platform, "linux")), + Layer.provide( + DesktopConfig.layerTest({ + XDG_DATA_HOME: "/xdg", + APPIMAGE: "/Applications/current.AppImage", + T3CODE_DESKTOP_LAUNCHER_PATH: " /opt/T3 Code/t3code ", + }), + ), ), ); const entry = writeFileSyncMock.mock.calls.find( diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.ts index d77544f54b69a..ff8c97b8f8260 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.ts @@ -2,14 +2,17 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; +import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Electron from "electron"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts"; +import { trimmedString } from "./DesktopConfig.ts"; import { resolveDesktopAppBranding } from "./DesktopEnvironment.ts"; import { renderUrlHandlerDesktopEntry } from "./DesktopLinuxUrlHandler.ts"; import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; @@ -49,10 +52,17 @@ export class DesktopPreReadyElectronOptions extends Context.Service< } >()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {} +const LinuxDesktopEntryConfig = Config.all({ + xdgDataHome: trimmedString("XDG_DATA_HOME"), + launcherPath: trimmedString("T3CODE_DESKTOP_LAUNCHER_PATH"), + appImagePath: trimmedString("APPIMAGE"), +}); + /** @public */ export const make = Effect.gen(function* () { const platform = yield* HostProcess.Platform; const homeDirectory = yield* HostProcess.HomeDirectory; + const linuxDesktopEntryConfig = yield* LinuxDesktopEntryConfig; return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => { const linuxPasswordStoreCommandLine = platform === "linux" @@ -77,8 +87,9 @@ export const make = Effect.gen(function* () { // have removed the executable referenced by the previous launch's entry. try { const applicationsDir = NodePath.posix.join( - process.env.XDG_DATA_HOME?.trim() || + Option.getOrElse(linuxDesktopEntryConfig.xdgDataHome, () => NodePath.posix.join(homeDirectory, ".local", "share"), + ), "applications", ); NodeFS.mkdirSync(applicationsDir, { recursive: true }); @@ -110,9 +121,12 @@ export const make = Effect.gen(function* () { appVersion: Electron.app.getVersion(), }).displayName, execTarget: - process.env.T3CODE_DESKTOP_LAUNCHER_PATH?.trim() || - process.env.APPIMAGE?.trim() || - process.execPath, + Option.getOrUndefined( + Option.orElse( + linuxDesktopEntryConfig.launcherPath, + () => linuxDesktopEntryConfig.appImagePath, + ), + ) ?? process.execPath, scheme: ElectronProtocol.getDesktopScheme(linux.isDevelopment), ...(iconPath === undefined ? {} : { iconPath }), }), diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index b0c042c05f5ca..e71d838188706 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -2,6 +2,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -93,14 +94,6 @@ function layerEnvironment( ); } -const restoreEnv = (name: string, value: string | undefined) => { - if (value === undefined) { - delete process.env[name]; - } else { - process.env[name] = value; - } -}; - const withHarness = ( effect: Effect.Effect< A, @@ -692,49 +685,38 @@ describe("DesktopBackendConfiguration", () => { prefix: "t3-desktop-backend-config-test-", }); - const previousWslEnv = process.env.WSLENV; - const previousDisabled = process.env.OTEL_SDK_DISABLED; - const previousTelemetry = process.env.T3CODE_TELEMETRY_ENABLED; - const previousResourceAttributes = process.env.OTEL_RESOURCE_ATTRIBUTES; - try { - delete process.env.WSLENV; - process.env.OTEL_SDK_DISABLED = "true"; - process.env.T3CODE_TELEMETRY_ENABLED = "false"; - process.env.OTEL_RESOURCE_ATTRIBUTES = "deployment.environment.name=staging"; - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolveWsl({ port: 5050, distro: null }); - - assert.equal(config.env.OTEL_SDK_DISABLED, "true"); - assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_SDK_DISABLED"); - assert.equal(config.env.T3CODE_TELEMETRY_ENABLED, "false"); - assert.include((config.env.WSLENV ?? "").split(":"), "T3CODE_TELEMETRY_ENABLED"); - assert.equal(config.env.OTEL_RESOURCE_ATTRIBUTES, "deployment.environment.name=staging"); - assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_RESOURCE_ATTRIBUTES"); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge( - DesktopWslEnvironment.layerTest({ - isAvailable: true, - windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"), - getDistroIp: () => Option.some("172.27.0.99"), - }), - ), - Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), + yield* Effect.gen(function* () { + const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; + const config = yield* configuration.resolveWsl({ port: 5050, distro: null }); + + assert.equal(config.env.OTEL_SDK_DISABLED, "true"); + assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_SDK_DISABLED"); + assert.equal(config.env.T3CODE_TELEMETRY_ENABLED, "false"); + assert.include((config.env.WSLENV ?? "").split(":"), "T3CODE_TELEMETRY_ENABLED"); + assert.equal(config.env.OTEL_RESOURCE_ATTRIBUTES, "deployment.environment.name=staging"); + assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_RESOURCE_ATTRIBUTES"); + }).pipe( + Effect.provide( + layerBackendConfiguration().pipe( + Layer.provideMerge(layerServerExposure), + Layer.provideMerge(DesktopAppSettings.layerTest()), + Layer.provideMerge(DesktopWslServerTree.layerTest()), + Layer.provideMerge( + DesktopWslEnvironment.layerTest({ + isAvailable: true, + windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"), + getDistroIp: () => Option.some("172.27.0.99"), + }), ), + Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), ), - ); - } finally { - restoreEnv("WSLENV", previousWslEnv); - restoreEnv("OTEL_SDK_DISABLED", previousDisabled); - restoreEnv("T3CODE_TELEMETRY_ENABLED", previousTelemetry); - restoreEnv("OTEL_RESOURCE_ATTRIBUTES", previousResourceAttributes); - } + ), + Effect.provideService(HostProcess.Environment, { + OTEL_SDK_DISABLED: "true", + T3CODE_TELEMETRY_ENABLED: "false", + OTEL_RESOURCE_ATTRIBUTES: "deployment.environment.name=staging", + }), + ); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); @@ -745,63 +727,48 @@ describe("DesktopBackendConfiguration", () => { prefix: "t3-desktop-backend-config-test-", }); - const previousWslEnv = process.env.WSLENV; - const previousOpenAiKey = process.env.OPENAI_API_KEY; - const previousAnthropicKey = process.env.ANTHROPIC_API_KEY; - const previousOtlpHeaders = process.env.T3CODE_OTLP_HEADERS; - const previousOtlpProtocol = process.env.T3CODE_OTLP_PROTOCOL; - const ambientOtel = Object.entries(process.env).filter(([name]) => name.startsWith("OTEL_")); - try { - for (const [name] of ambientOtel) delete process.env[name]; - process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u"; - process.env.OPENAI_API_KEY = "openai-key"; - process.env.ANTHROPIC_API_KEY = "anthropic-key"; - process.env.T3CODE_OTLP_HEADERS = 'authorization="Bearer%20my-token"'; - process.env.T3CODE_OTLP_PROTOCOL = "http/protobuf"; - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolveWsl({ port: 5050, distro: null }); - - assert.equal(config.executablePath, "wsl.exe"); - assert.equal(config.bootstrap.port, 5050); - assert.equal(config.bootstrap.host, "0.0.0.0"); - assert.equal(config.bootstrap.tailscaleServeEnabled, false); - assert.notProperty(config.bootstrap, "desktopTelemetryFd"); - assert.notProperty(config.bootstrap, "resourceMonitorPath"); - assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/"); - assert.equal(config.env.OPENAI_API_KEY, "openai-key"); - assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key"); - assert.equal(config.env.T3CODE_OTLP_PROTOCOL, "http/protobuf"); - assert.equal( - config.env.WSLENV, - "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL", - ); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge( - DesktopWslEnvironment.layerTest({ - isAvailable: true, - windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"), - getDistroIp: () => Option.some("172.27.0.99"), - }), - ), - Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), + yield* Effect.gen(function* () { + const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; + const config = yield* configuration.resolveWsl({ port: 5050, distro: null }); + + assert.equal(config.executablePath, "wsl.exe"); + assert.equal(config.bootstrap.port, 5050); + assert.equal(config.bootstrap.host, "0.0.0.0"); + assert.equal(config.bootstrap.tailscaleServeEnabled, false); + assert.notProperty(config.bootstrap, "desktopTelemetryFd"); + assert.notProperty(config.bootstrap, "resourceMonitorPath"); + assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/"); + assert.equal(config.env.OPENAI_API_KEY, "openai-key"); + assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key"); + assert.equal(config.env.T3CODE_OTLP_PROTOCOL, "http/protobuf"); + assert.equal( + config.env.WSLENV, + "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL", + ); + }).pipe( + Effect.provide( + layerBackendConfiguration().pipe( + Layer.provideMerge(layerServerExposure), + Layer.provideMerge(DesktopAppSettings.layerTest()), + Layer.provideMerge(DesktopWslServerTree.layerTest()), + Layer.provideMerge( + DesktopWslEnvironment.layerTest({ + isAvailable: true, + windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"), + getDistroIp: () => Option.some("172.27.0.99"), + }), ), + Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), ), - ); - } finally { - restoreEnv("WSLENV", previousWslEnv); - restoreEnv("OPENAI_API_KEY", previousOpenAiKey); - restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey); - restoreEnv("T3CODE_OTLP_HEADERS", previousOtlpHeaders); - restoreEnv("T3CODE_OTLP_PROTOCOL", previousOtlpProtocol); - for (const [name, value] of ambientOtel) restoreEnv(name, value); - } + ), + Effect.provideService(HostProcess.Environment, { + WSLENV: "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u", + OPENAI_API_KEY: "openai-key", + ANTHROPIC_API_KEY: "anthropic-key", + T3CODE_OTLP_HEADERS: 'authorization="Bearer%20my-token"', + T3CODE_OTLP_PROTOCOL: "http/protobuf", + }), + ); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 1789c31eb4074..abadf58f3f02f 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -2,6 +2,7 @@ import * as NodeOS from "node:os"; import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -562,6 +563,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl const environment = yield* DesktopEnvironment.DesktopEnvironment; const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; const fileSystem = yield* FileSystem.FileSystem; + const env = yield* HostProcess.Environment; // wslhost loopback forwarding is unreliable on some Windows hosts; advertise the WSL IP instead. const wslBindHost = "0.0.0.0"; @@ -633,7 +635,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl const forwardedEnv: Record = {}; const forwardedEnvNames: string[] = []; for (const name of WSL_FORWARDED_ENV_NAMES) { - const value = process.env[name]; + const value = env[name]; if (value !== undefined && value.length > 0) { forwardedEnv[name] = value; forwardedEnvNames.push(name); @@ -641,7 +643,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl } const parentEnvWithoutT3Home: Record = {}; - for (const [key, value] of Object.entries(process.env)) { + for (const [key, value] of Object.entries(env)) { if (key === "T3CODE_HOME") continue; parentEnvWithoutT3Home[key] = value; } @@ -658,7 +660,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl ...forwardedEnv, ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}), }, - // env already excludes T3CODE_HOME; merging process.env would restore it. + // env already excludes T3CODE_HOME; merging the host env would restore it. extendEnv: false, bootstrap, bootstrapDelivery: "stdin" as const, diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.ts index a3d4db0bb4dc2..95b39d944e490 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts @@ -768,6 +768,8 @@ export const make = Effect.gen(function* () { const captureDirectory = path.join(environment.stateDir, "snap-shots"); const linuxAppId = environment.linuxDesktopEntryName.replace(/\.desktop$/, ""); const home = yield* HostProcess.HomeDirectory; + // Shell discovery can replace XDG_CURRENT_DESKTOP after startup, so read the live env per state. + const hostEnv = yield* HostProcess.Environment; let shortcutVerified = false; const gnomeSetupPaths = { bundle: environment.isPackaged @@ -1621,7 +1623,8 @@ export const make = Effect.gen(function* () { Effect.gen(function* () { const linuxDesktop = state.mode === "portal" - ? process.env.XDG_CURRENT_DESKTOP?.toLowerCase() + ? (hostEnv.XDG_CURRENT_DESKTOP ?? "") + .toLowerCase() .split(":") .find( (name) => diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index f65fc11f59a75..57d6c61f7c43a 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -9,6 +9,7 @@ import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel"; import { satisfiesSemverRange } from "@t3tools/shared/semver"; @@ -1141,7 +1142,8 @@ export const layer = Layer.effect( const environment = yield* DesktopEnvironment.DesktopEnvironment; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fileSystem = yield* FileSystem.FileSystem; - const windir = process.env.WINDIR ?? "C:\\Windows"; + // Not Config: Windows variable names are case-insensitive only on the live process.env. + const windir = (yield* HostProcess.Environment).WINDIR ?? "C:\\Windows"; const provideSpawner = ( effect: Effect.Effect, diff --git a/apps/server/integration/transferBudgetV2.integration.test.ts b/apps/server/integration/transferBudgetV2.integration.test.ts index 68a622c541fe9..3f1d50b510c68 100644 --- a/apps/server/integration/transferBudgetV2.integration.test.ts +++ b/apps/server/integration/transferBudgetV2.integration.test.ts @@ -27,6 +27,7 @@ import { type OrchestrationV2ShellStreamItem, } from "@t3tools/contracts"; import * as Context from "effect/Context"; +import * as Config from "effect/Config"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -453,9 +454,13 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => } const fs = yield* FileSystem.FileSystem; const report = formatTransferBudgetReport(runs); + const outputPaths = yield* Config.all({ + report: Config.String("T3CODE_TRANSFER_BUDGET_REPORT_PATH").pipe(Config.withDefault("")), + result: Config.String("T3CODE_TRANSFER_BUDGET_RESULT_PATH").pipe(Config.withDefault("")), + }); for (const [path, contents] of [ - [process.env.T3CODE_TRANSFER_BUDGET_REPORT_PATH, report], - [process.env.T3CODE_TRANSFER_BUDGET_RESULT_PATH, formatTransferBudgetResult(runs)], + [outputPaths.report, report], + [outputPaths.result, formatTransferBudgetResult(runs)], ]) if (path && contents) yield* fs.writeFileString(path, contents); yield* Effect.log(report); diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index a8ca338c87750..feb4aa405ae64 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -43,6 +43,9 @@ const omitInitializeModelState = process.env.T3_ACP_OMIT_INITIALIZE_MODEL_STATE const completeFirstPromptOnCancel = process.env.T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL === "1"; const floodStderr = process.env.T3_ACP_FLOOD_STDERR === "1"; const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1"; +const agentVersion = process.env.T3_ACP_AGENT_VERSION ?? "0.0.0"; +const geminiApiKey = process.env.GEMINI_API_KEY; +const idleError = process.env.T3_ACP_IDLE_ERROR; const emitTrackedToolCallKindThenHang = process.env.T3_ACP_EMIT_TRACKED_TOOL_CALL_KIND_THEN_HANG; const clientFsProbePath = process.env.T3_ACP_CLIENT_FS_PROBE_PATH; const clientFsProbeLogPath = process.env.T3_ACP_CLIENT_FS_PROBE_LOG_PATH; @@ -512,7 +515,7 @@ const program = Effect.gen(function* () { parameterizedModelPicker = request.capabilities?._meta?.parameterizedModelPicker === true; return { protocolVersion: 2, - info: { name: "t3-acp-mock-agent", version: process.env.T3_ACP_AGENT_VERSION ?? "0.0.0" }, + info: { name: "t3-acp-mock-agent", version: agentVersion }, ...(omitInitializeModelState ? {} : { _meta: { modelState: modelState() } }), capabilities: { session: { @@ -550,7 +553,7 @@ const program = Effect.gen(function* () { if (antigravityProfile) { if ( request.methodId !== "oauth-personal" && - !(request.methodId === "gemini-api-key" && process.env.GEMINI_API_KEY) + !(request.methodId === "gemini-api-key" && geminiApiKey) ) { return yield* AcpError.AcpRequestError.invalidParams( `Mock Antigravity rejected auth method ${request.methodId}.`, @@ -811,7 +814,6 @@ const program = Effect.gen(function* () { const requestedSessionId = String(request.sessionId ?? sessionId); beginAcpMockPrompt(cancelledSessions, requestedSessionId); promptCount += 1; - const idleError = process.env.T3_ACP_IDLE_ERROR; if (idleError === "grok-background" && promptCount === 1) { // The structured completion lands before the prompt settles, so it is buffered. const taskId = "call-idle-error-background"; diff --git a/apps/server/scripts/record-codex-app-server-replay-fixture.ts b/apps/server/scripts/record-codex-app-server-replay-fixture.ts index aa2c17af06c34..202e72de32a43 100644 --- a/apps/server/scripts/record-codex-app-server-replay-fixture.ts +++ b/apps/server/scripts/record-codex-app-server-replay-fixture.ts @@ -13,6 +13,8 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; +import * as Config from "effect/Config"; +import * as Option from "effect/Option"; import * as Effect from "effect/Effect"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; @@ -1486,12 +1488,24 @@ const runScenario = Effect.fn("record-codex-app-server-replay-fixture.runScenari yield* recorder.flush(); }); +const RecorderEnv = Config.all({ + T3_CODEX_REPLAY_OUT_DIR: Config.String("T3_CODEX_REPLAY_OUT_DIR").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + T3_CODEX_REPLAY_OUT: Config.String("T3_CODEX_REPLAY_OUT").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), +}); + const program = Effect.gen(function* () { + const recorderEnv = yield* RecorderEnv; const path = yield* Path.Path; const requestedScenarios = parseScenarios(); const allScenarios = scenarios(); - const outDir = readArgValue("--out-dir") ?? process.env.T3_CODEX_REPLAY_OUT_DIR; - const singleOutPath = readArgValue("--out") ?? process.env.T3_CODEX_REPLAY_OUT; + const outDir = readArgValue("--out-dir") ?? recorderEnv.T3_CODEX_REPLAY_OUT_DIR; + const singleOutPath = readArgValue("--out") ?? recorderEnv.T3_CODEX_REPLAY_OUT; const selected = allScenarios.filter((scenario) => requestedScenarios.includes(scenario.name)); if (selected.length === 0) { diff --git a/apps/server/scripts/record-fx-acp-replay-fixture.ts b/apps/server/scripts/record-fx-acp-replay-fixture.ts index 46af7ce49ee25..ad24e8140ce96 100644 --- a/apps/server/scripts/record-fx-acp-replay-fixture.ts +++ b/apps/server/scripts/record-fx-acp-replay-fixture.ts @@ -13,6 +13,8 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; import * as Clock from "effect/Clock"; import * as Console from "effect/Console"; +import * as Config from "effect/Config"; +import * as Option from "effect/Option"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -322,7 +324,19 @@ function normalizeEntries(input: { const DEFAULT_FX_SETTINGS = Schema.decodeSync(FxSettings)({}); +const RecorderEnv = Config.all({ + T3_FX_BIN: Config.String("T3_FX_BIN").pipe(Config.option, Config.map(Option.getOrUndefined)), + HOME: Config.String("HOME").pipe(Config.option, Config.map(Option.getOrUndefined)), + USER: Config.String("USER").pipe(Config.option, Config.map(Option.getOrUndefined)), + AI_GATEWAY_API_KEY: Config.String("AI_GATEWAY_API_KEY").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + TMPDIR: Config.String("TMPDIR").pipe(Config.option, Config.map(Option.getOrUndefined)), +}); + const recordScenario = Effect.fn("recordFxScenario")(function* (fixtureName: string) { + const recorderEnv = yield* RecorderEnv; const fixture = ORCHESTRATOR_REPLAY_FIXTURES.find((candidate) => candidate.name === fixtureName); const variant = fixture?.providers.find((provider) => provider.driver === FX_DRIVER_KIND); if (fixture === undefined || variant === undefined) { @@ -359,7 +373,7 @@ const recordScenario = Effect.fn("recordFxScenario")(function* (fixtureName: str }; const tee = makeWireTee(); - const settings = { ...DEFAULT_FX_SETTINGS, binaryPath: process.env.T3_FX_BIN ?? "fx" }; + const settings = { ...DEFAULT_FX_SETTINGS, binaryPath: recorderEnv.T3_FX_BIN ?? "fx" }; const layerRegistry = ProviderAdapterRegistry.layerFromAdaptersEffect( Effect.gen(function* () { const environment = yield* HostProcess.Environment; @@ -455,7 +469,7 @@ const recordScenario = Effect.fn("recordFxScenario")(function* (fixtureName: str isRecord(initialize.frame.result.agentInfo) ? initialize.frame.result.agentInfo : {}; - const home = process.env.HOME ?? ""; + const home = recorderEnv.HOME ?? ""; const transcript = { provider: FX_DRIVER_KIND, protocol: ACP_PROTOCOL, @@ -473,11 +487,11 @@ const recordScenario = Effect.fn("recordFxScenario")(function* (fixtureName: str entries, workspace: realWorkspace, home, - user: process.env.USER ?? "", + user: recorderEnv.USER ?? "", skillNames: yield* readUserSkillNames(home), - ...(process.env.AI_GATEWAY_API_KEY === undefined + ...(recorderEnv.AI_GATEWAY_API_KEY === undefined ? {} - : { gatewayApiKey: process.env.AI_GATEWAY_API_KEY }), + : { gatewayApiKey: recorderEnv.AI_GATEWAY_API_KEY }), runtimeInstructions: buildRuntimeInstructions({ harness: "fx", model: variant.modelSelection.model, @@ -494,7 +508,7 @@ const recordScenario = Effect.fn("recordFxScenario")(function* (fixtureName: str ); if (liveFailure._tag === "Some") { const dumpPath = path.join( - process.env.TMPDIR ?? "/tmp", + recorderEnv.TMPDIR ?? "/tmp", `fx-replay-${fixtureName}-failed.json`, ); yield* fs.writeFileString(dumpPath, encodeJson(transcript)); diff --git a/apps/server/scripts/record-grok-acp-replay-fixture.ts b/apps/server/scripts/record-grok-acp-replay-fixture.ts index d9ce096a16504..d9c5facfa71fc 100644 --- a/apps/server/scripts/record-grok-acp-replay-fixture.ts +++ b/apps/server/scripts/record-grok-acp-replay-fixture.ts @@ -6,6 +6,8 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; import * as Clock from "effect/Clock"; import * as Console from "effect/Console"; +import * as Config from "effect/Config"; +import * as Option from "effect/Option"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -370,7 +372,14 @@ function normalizeEntries(input: { const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({}); +const RecorderEnv = Config.all({ + T3_GROK_BIN: Config.String("T3_GROK_BIN").pipe(Config.option, Config.map(Option.getOrUndefined)), + HOME: Config.String("HOME").pipe(Config.option, Config.map(Option.getOrUndefined)), + USER: Config.String("USER").pipe(Config.option, Config.map(Option.getOrUndefined)), +}); + const recordScenario = Effect.fn("recordGrokScenario")(function* (fixtureName: string) { + const recorderEnv = yield* RecorderEnv; const fixture = ORCHESTRATOR_REPLAY_FIXTURES.find((candidate) => candidate.name === fixtureName); const variant = fixture?.providers.find((provider) => provider.driver === GROK_PROVIDER); if (fixture === undefined || variant === undefined) { @@ -404,7 +413,7 @@ const recordScenario = Effect.fn("recordGrokScenario")(function* (fixtureName: s }; const tee = makeWireTee(); - const settings = { ...DEFAULT_GROK_SETTINGS, binaryPath: process.env.T3_GROK_BIN ?? "grok" }; + const settings = { ...DEFAULT_GROK_SETTINGS, binaryPath: recorderEnv.T3_GROK_BIN ?? "grok" }; const layerRegistry = ProviderAdapterRegistry.layerFromAdaptersEffect( Effect.gen(function* () { const environment = yield* HostProcess.Environment; @@ -522,8 +531,8 @@ const recordScenario = Effect.fn("recordGrokScenario")(function* (fixtureName: s ...normalizeEntries({ entries, workspace: realWorkspace, - home: process.env.HOME ?? "", - user: process.env.USER ?? "", + home: recorderEnv.HOME ?? "", + user: recorderEnv.USER ?? "", runtimeInstructions: buildRuntimeInstructions({ harness: "Grok", model: variant.modelSelection.model, diff --git a/apps/server/scripts/record-kiro-acp-replay-fixture.ts b/apps/server/scripts/record-kiro-acp-replay-fixture.ts index 41262fc8dadd1..28299b5ad7295 100644 --- a/apps/server/scripts/record-kiro-acp-replay-fixture.ts +++ b/apps/server/scripts/record-kiro-acp-replay-fixture.ts @@ -12,6 +12,8 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; import * as Clock from "effect/Clock"; import * as Console from "effect/Console"; +import * as Config from "effect/Config"; +import * as Option from "effect/Option"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -407,7 +409,17 @@ const KIRO_RECORDING_SETTINGS = Schema.decodeSync(KiroSettings)({ binaryPath: process.env.T3_KIRO_BIN ?? "kiro-cli", }); +const RecorderEnv = Config.all({ + T3_KIRO_VERSION: Config.String("T3_KIRO_VERSION").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + HOME: Config.String("HOME").pipe(Config.option, Config.map(Option.getOrUndefined)), + USER: Config.String("USER").pipe(Config.option, Config.map(Option.getOrUndefined)), +}); + const recordScenario = Effect.fn("recordKiroScenario")(function* (fixtureName: string) { + const recorderEnv = yield* RecorderEnv; const fixture = ORCHESTRATOR_REPLAY_FIXTURES.find((candidate) => candidate.name === fixtureName); const variant = fixture?.providers.find((provider) => provider.driver === KIRO_PROVIDER); if (fixture === undefined || variant === undefined) { @@ -544,7 +556,7 @@ const recordScenario = Effect.fn("recordKiroScenario")(function* (fixtureName: s scenario: fixtureName, metadata: { generatedBy: "live-kiro-recorder", - kiroVersion: process.env.T3_KIRO_VERSION ?? "unknown", + kiroVersion: recorderEnv.T3_KIRO_VERSION ?? "unknown", normalization: "Session ids are fixed sess_ UUIDs and other UUIDs (message and request ids) are numbered in first-seen order, the workspace is , HOME is /home/kiro-replay and the recording user is kiro-replay. T3-owned prompt text, MCP servers and initialize params other than clientCapabilities and _meta are . Kiro's log directory, user-scoped commands and agents, and the _kiro/* broadcasts T3 ignores (governance, steering documents, powers, tools, hooks, MCP status, session roster, memory sync) are removed. Timestamps are kept as recorded.", droppedFrames, @@ -553,8 +565,8 @@ const recordScenario = Effect.fn("recordKiroScenario")(function* (fixtureName: s ...normalizeEntries({ entries, workspace: realWorkspace, - home: process.env.HOME ?? "", - user: process.env.USER ?? "", + home: recorderEnv.HOME ?? "", + user: recorderEnv.USER ?? "", runtimeInstructions: buildRuntimeInstructions({ harness: "Kiro", model: variant.modelSelection.model, diff --git a/apps/server/src/cli/app.test.ts b/apps/server/src/cli/app.test.ts index 2dba3b0eb061a..eecdd7fbe5018 100644 --- a/apps/server/src/cli/app.test.ts +++ b/apps/server/src/cli/app.test.ts @@ -41,6 +41,16 @@ const liveProcess = Effect.acquireRelease( const encodeRuntimeState = Schema.encodeEffect(Schema.fromJsonString(PersistedServerRuntimeState)); +// Node reads this variable itself, so the test must set the real process environment. +const setProcessEnv = (name: string, value: string) => { + const previous = process.env[name]; + process.env[name] = value; + return () => { + if (previous === undefined) delete process.env[name]; + else process.env[name] = previous; + }; +}; + const runCli = (args: ReadonlyArray, env: Record = {}) => Command.runWith(makeCli(), { version: "0.0.0" })(args).pipe( Effect.provide( @@ -229,16 +239,9 @@ describe("t3 app", () => { "t3-app-unsafe-", (root) => Effect.gen(function* () { - const previousTmpdir = process.env.TMPDIR; yield* Effect.acquireRelease( - Effect.sync(() => { - process.env.TMPDIR = root; - }), - () => - Effect.sync(() => { - if (previousTmpdir === undefined) delete process.env.TMPDIR; - else process.env.TMPDIR = previousTmpdir; - }), + Effect.sync(() => setProcessEnv("TMPDIR", root)), + (restore) => Effect.sync(restore), ); const baseDir = NodePath.join(root, ".t3"); const userId = yield* HostProcess.UserId; diff --git a/apps/server/src/cli/uninstall.test.ts b/apps/server/src/cli/uninstall.test.ts index d2ad673408d40..bf9fb85f89747 100644 --- a/apps/server/src/cli/uninstall.test.ts +++ b/apps/server/src/cli/uninstall.test.ts @@ -1,5 +1,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; +import * as Config from "effect/Config"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -47,7 +48,10 @@ it.live.runIf(HostProcess.Platform.defaultValue() === "win32")( yield* fs.makeDirectory(path.join(runtimeDir, "versions", "1.0.0"), { recursive: true }); yield* fs.writeFileString(path.join(runtimeDir, "versions", "1.0.0", "t3.exe"), ""); - const child = spawnWindowsRemoval(process.env.ComSpec ?? "cmd.exe", runtimeDir); + const child = spawnWindowsRemoval( + yield* Config.String("ComSpec").pipe(Config.withDefault("cmd.exe")), + runtimeDir, + ); yield* Effect.callback((resume) => { child.once("error", (error) => resume(Effect.fail(error))); child.once("exit", (code) => diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts b/apps/server/src/cloud/ManagedEndpointRuntime.test.ts index 5cad290678f5f..d1f95140fa0a6 100644 --- a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts +++ b/apps/server/src/cloud/ManagedEndpointRuntime.test.ts @@ -1,6 +1,8 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as ConfigProvider from "effect/ConfigProvider"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; @@ -80,6 +82,7 @@ const buildCloudManagedEndpointRuntime = ( relayClientLayer = layerRelayClientAvailable, httpClient = unusedHttpClient, secretStoreLayer = emptySecretStoreLayer, + env: Record = {}, ) => Effect.gen(function* () { const context = yield* Layer.build( @@ -90,7 +93,10 @@ const buildCloudManagedEndpointRuntime = ( return yield* Effect.service(ManagedEndpointRuntime.CloudManagedEndpointRuntime).pipe( Effect.provide(context), ); - }); + }).pipe( + Effect.provideService(HostProcess.Environment, env), + Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))), + ); function makeHandle(input: { readonly pid: number; @@ -345,19 +351,6 @@ describe("CloudManagedEndpointRuntime", () => { isRunning?: Effect.Effect; } = {}, ) { - yield* Effect.acquireRelease( - Effect.sync(() => { - const previous = process.env.TUNNEL_TRANSPORT_PROTOCOL; - if (options.transport === undefined) delete process.env.TUNNEL_TRANSPORT_PROTOCOL; - else process.env.TUNNEL_TRANSPORT_PROTOCOL = options.transport; - return previous; - }), - (previous) => - Effect.sync(() => { - if (previous === undefined) delete process.env.TUNNEL_TRANSPORT_PROTOCOL; - else process.env.TUNNEL_TRANSPORT_PROTOCOL = previous; - }), - ); const spawned: Array = []; const killed: Array = []; const outputs: Array> = []; @@ -410,7 +403,9 @@ describe("CloudManagedEndpointRuntime", () => { index, lines + "2026-10-16T20:30:00Z INF Registered tunnel connection connIndex=0\n", ).pipe(Effect.andThen(Stream.runHead(runtime.tunnelConnected))); - return { spawner, spawned, killed, exits, started, emit, observe }; + const env: Record = + options.transport === undefined ? {} : { TUNNEL_TRANSPORT_PROTOCOL: options.transport }; + return { spawner, env, spawned, killed, exits, started, emit, observe }; }); it.effect("restarts only the inspected connector and supervises its replacement", () => @@ -438,7 +433,13 @@ describe("CloudManagedEndpointRuntime", () => { it.effect("preserves an explicit transport choice despite repeated QUIC stalls", () => Effect.gen(function* () { const fixture = yield* makeTransportSpawner({ transport: "quic" }); - const runtime = yield* buildCloudManagedEndpointRuntime(fixture.spawner); + const runtime = yield* buildCloudManagedEndpointRuntime( + fixture.spawner, + layerRelayClientAvailable, + unusedHttpClient, + emptySecretStoreLayer, + fixture.env, + ); yield* runtime.applyConfig(tunnelConfig); yield* fixture.observe(runtime, 0, quicDialWarning.repeat(30)); yield* fixture.observe(runtime, 0, quicDatagramWarning.repeat(30)); @@ -464,12 +465,13 @@ describe("CloudManagedEndpointRuntime", () => { context.pipe(Context.get(ServerSecretStore.ServerSecretStore)), ); const fixture = yield* makeTransportSpawner(); - const start = (spawner = fixture.spawner) => + const start = (spawner = fixture.spawner, env = fixture.env) => buildCloudManagedEndpointRuntime( spawner, layerRelayClientAvailable, unusedHttpClient, secretStoreLayer, + env, ); yield* Effect.gen(function* () { const runtime = yield* start(); @@ -486,7 +488,7 @@ describe("CloudManagedEndpointRuntime", () => { for (const transport of [undefined, "quic", "http2", "auto", undefined]) { yield* Effect.gen(function* () { const next = yield* makeTransportSpawner(transport ? { transport } : {}); - const restarted = yield* start(next.spawner); + const restarted = yield* start(next.spawner, next.env); yield* restarted.applyConfig(tunnelConfig); if (transport === undefined) { expect(next.spawned[0]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]); diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.ts b/apps/server/src/cloud/ManagedEndpointRuntime.ts index def1a8d112c2c..d52f27a2ee806 100644 --- a/apps/server/src/cloud/ManagedEndpointRuntime.ts +++ b/apps/server/src/cloud/ManagedEndpointRuntime.ts @@ -1,7 +1,9 @@ import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay"; import { RotatingFileSink } from "@t3tools/shared/logging"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as RelayClient from "@t3tools/shared/relayClient"; import * as Clock from "effect/Clock"; +import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; @@ -225,7 +227,10 @@ export const make = Effect.gen(function* () { const retryLoopRunningRef = yield* Ref.make(false); const notReadyChecksBeforeRestartRef = yield* Ref.make(CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART); // An explicit cloudflared transport in the environment is the user's choice. - const transportChosenByUser = process.env.TUNNEL_TRANSPORT_PROTOCOL !== undefined; + const env = yield* HostProcess.Environment; + const transportChosenByUser = Option.isSome( + yield* Config.String("TUNNEL_TRANSPORT_PROTOCOL").pipe(Config.option), + ); const previousFallback = transportChosenByUser ? Option.none() : yield* secrets.get(HTTP2_FALLBACK_STATE).pipe( @@ -730,7 +735,7 @@ export const make = Effect.gen(function* () { { detached: false, env: { - ...process.env, + ...env, TUNNEL_TOKEN: config.connectorToken, }, shell: false, diff --git a/apps/server/src/device/AgentDeviceTarget.test.ts b/apps/server/src/device/AgentDeviceTarget.test.ts index d8c99eb3321f2..bf180c9004dfd 100644 --- a/apps/server/src/device/AgentDeviceTarget.test.ts +++ b/apps/server/src/device/AgentDeviceTarget.test.ts @@ -77,10 +77,11 @@ exec '${process.execPath.replaceAll("'", "'\"'\"'")}' "$@" "a!b!c", "", ]; + const hostPath = (yield* HostProcess.Environment).PATH ?? ""; yield* Effect.promise(() => expect( exec(path.join(shim, "agent-device"), args, { - env: { PATH: process.env.PATH ?? "", HOME: temp }, + env: { PATH: hostPath, HOME: temp }, }), ).rejects.toMatchObject({ code: 23, stdout: `${JSON.stringify(args)}\n`, stderr: "" }), ); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 7ec4b4effbdaa..e8c2acbce4886 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -1,6 +1,7 @@ import * as Arr from "effect/Array"; import * as Cache from "effect/Cache"; import * as Clock from "effect/Clock"; +import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as ByteSize from "effect/ByteSize"; @@ -1098,7 +1099,11 @@ export const make = Effect.gen(function* () { ), ), ); - const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp"; + const tempDir = yield* Config.String("TMPDIR").pipe( + Config.orElse(() => Config.String("TEMP")), + Config.orElse(() => Config.String("TMP")), + Config.withDefault("/tmp"), + ); const canonicalizeExistingPath = (value: string) => fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value)); const normalizeStatusCacheKey = canonicalizeExistingPath; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 0c36d4a5869b6..1ea0a62e168ce 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -84,7 +84,7 @@ it.effect("forks a session stored under the instance's own CLAUDE_CONFIG_DIR", ( prefix: "t3-claude-fork-config-", }); const projectDir = yield* writeClaudeSession(configDir); - const hostConfigDir = process.env.CLAUDE_CONFIG_DIR; + const hostConfigDir = (yield* HostProcess.Environment).CLAUDE_CONFIG_DIR; const inProcessFork = vi.spyOn(ClaudeSdk, "forkSession"); yield* Effect.addFinalizer(() => Effect.sync(() => inProcessFork.mockRestore())); @@ -110,7 +110,7 @@ it.effect("forks a session stored under the instance's own CLAUDE_CONFIG_DIR", ( ?.match(/"uuid"\s*:\s*"([^"]+)"/)?.[1]; assert.isString(inheritedHead); assert.equal(forked.headMessageId, inheritedHead); - assert.equal(process.env.CLAUDE_CONFIG_DIR, hostConfigDir); + assert.equal((yield* HostProcess.Environment).CLAUDE_CONFIG_DIR, hostConfigDir); assert.equal(inProcessFork.mock.calls.length, 0); }).pipe(Effect.provide(forkRunnerLayer)), ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), diff --git a/apps/server/src/project/ManagedProjectFolders.test.ts b/apps/server/src/project/ManagedProjectFolders.test.ts index 7990537355ed2..bf6f43a3fdb30 100644 --- a/apps/server/src/project/ManagedProjectFolders.test.ts +++ b/apps/server/src/project/ManagedProjectFolders.test.ts @@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { CommandId, ProjectId, ThreadId, VcsProcessSpawnError } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -306,25 +307,15 @@ const withGitEnv = ( Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const emptyConfig = yield* fileSystem.makeTempFileScoped({ prefix: "t3-gitconfig-" }); - return yield* Effect.acquireUseRelease( - Effect.sync(() => { - const saved = GIT_IDENTITY_KEYS.map((key) => [key, process.env[key]] as const); - for (const key of GIT_IDENTITY_KEYS) delete process.env[key]; - Object.assign(process.env, { - GIT_CONFIG_GLOBAL: emptyConfig, - GIT_CONFIG_NOSYSTEM: "1", - ...env, - }); - return saved; + const hostEnv: NodeJS.ProcessEnv = { ...(yield* HostProcess.Environment) }; + for (const key of GIT_IDENTITY_KEYS) delete hostEnv[key]; + return yield* effect.pipe( + Effect.provideService(HostProcess.Environment, { + ...hostEnv, + GIT_CONFIG_GLOBAL: emptyConfig, + GIT_CONFIG_NOSYSTEM: "1", + ...env, }), - () => effect, - (saved) => - Effect.sync(() => { - for (const [key, value] of saved) { - if (value === undefined) delete process.env[key]; - else process.env[key] = value; - } - }), ); }); @@ -354,7 +345,7 @@ it.effect("starts a named project as a committed repository, and suffixes a take yield* fileSystem.writeFileString(attributes, "* text=auto eol=crlf\n"); yield* git(baseDir, ["config", "--file", crlfConfig, "core.safecrlf", "true"]); yield* git(baseDir, ["config", "--file", crlfConfig, "core.attributesFile", attributes]); - process.env.GIT_CONFIG_GLOBAL = crlfConfig; + (yield* HostProcess.Environment).GIT_CONFIG_GLOBAL = crlfConfig; const first = yield* folders.createNamedProject({ name: "Pinball Stats" }); const second = yield* folders.createNamedProject({ name: "pinball stats" }); @@ -427,7 +418,10 @@ it.effect("keeps a named project and reports why when Git cannot commit", () => path.join(baseDir, "no-identity.gitconfig"), "[user]\n\tuseConfigOnly = true\n", ); - process.env.GIT_CONFIG_GLOBAL = path.join(baseDir, "no-identity.gitconfig"); + (yield* HostProcess.Environment).GIT_CONFIG_GLOBAL = path.join( + baseDir, + "no-identity.gitconfig", + ); const result = yield* folders.createNamedProject({ name: "No Identity" }); diff --git a/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts b/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts index d71421debc727..bf3c9318877bb 100644 --- a/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts +++ b/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts @@ -4,6 +4,7 @@ import { ClaudeSettings, type ServerProvider } from "@t3tools/contracts"; import { vi } from "vite-plus/test"; import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk"; import { assert, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Schema from "effect/Schema"; @@ -76,7 +77,7 @@ it.effect("keeps the probe subprocess alive while gateway model discovery can fi ); const capabilities = yield* probeClaudeCapabilities( yield* decodeClaudeSettings({ binaryPath: "claude" }), - { PATH: process.env.PATH, CLAUDE_CONFIG_DIR: configDir }, + { PATH: (yield* HostProcess.Environment).PATH, CLAUDE_CONFIG_DIR: configDir }, ); assert.deepEqual( capabilities.models?.map((model) => model.value), diff --git a/apps/server/src/provider/CodexManagedRuntime.test.ts b/apps/server/src/provider/CodexManagedRuntime.test.ts index 754716ac53106..2c697f8fa8531 100644 --- a/apps/server/src/provider/CodexManagedRuntime.test.ts +++ b/apps/server/src/provider/CodexManagedRuntime.test.ts @@ -95,6 +95,7 @@ it.live.each( email: null, }); yield* store.set(new TextEncoder().encode(json)); + const hostEnv = yield* HostProcess.Environment; const ambient = { CODEX_HOME: "/user/.codex", ACCESS_TOKEN: "ambient-bearer", @@ -102,8 +103,8 @@ it.live.each( OPENAI_API_KEY: "dummy-global-key", OPENAI_BASE_URL: "https://user-proxy.test", T3CODE_CODEX_LAUNCH_ARGS: "--config model_provider=global-proxy", - PATH: process.env.PATH, - SystemRoot: process.env.SystemRoot, + PATH: hostEnv.PATH, + SystemRoot: hostEnv.SystemRoot, }; const runtime = yield* makeCodexManagedRuntime({ instanceId, diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index 8957c12747a89..f06c4f47570dd 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -34,6 +34,16 @@ const mockRuntimeOptions = { authMethodId: "test", } satisfies AcpSessionRuntime.AcpSessionRuntimeOptions; +// The spawner extends the real process environment, so the test must set it there. +const setProcessEnv = (name: string, value: string) => { + const previous = process.env[name]; + process.env[name] = value; + return () => { + if (previous === undefined) delete process.env[name]; + else process.env[name] = previous; + }; +}; + describe("AcpSessionRuntime", () => { it.effect.each(["session/new", "session/resume"] as const)( "buffers root metadata while %s startup is still pending", @@ -422,16 +432,8 @@ describe("AcpSessionRuntime", () => { it.effect("does not restore ambient variables to a sanitized child environment", () => Effect.gen(function* () { yield* Effect.acquireRelease( - Effect.sync(() => { - const previous = process.env.T3_ACP_RUNTIME_AMBIENT; - process.env.T3_ACP_RUNTIME_AMBIENT = "sentinel"; - return previous; - }), - (previous) => - Effect.sync(() => { - if (previous === undefined) delete process.env.T3_ACP_RUNTIME_AMBIENT; - else process.env.T3_ACP_RUNTIME_AMBIENT = previous; - }), + Effect.sync(() => setProcessEnv("T3_ACP_RUNTIME_AMBIENT", "sentinel")), + (restore) => Effect.sync(restore), ); const runtime = yield* AcpSessionRuntime.make({ ...mockRuntimeOptions, diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index 1da6c2e195140..274b86573ed3c 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -6,6 +6,7 @@ import * as NodeFS from "node:fs"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { SERVER_EXIT_CODE_STATE_DIR_OWNED } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -379,7 +380,7 @@ if (context.update?.status === "pending") { { token: "initial", update: "pending" }, { token: "initial", update: "rolled-back" }, ]); - assert.equal(process.env.T3CODE_TEST_SERVICE_TOKEN, "inherited"); + assert.equal((yield* HostProcess.Environment).T3CODE_TEST_SERVICE_TOKEN, "inherited"); assert.equal(yield* fs.readFileString(envPath), "T3CODE_TEST_SERVICE_TOKEN=changed\n"); }), ); diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index 197d412d93405..78b8724e1f93c 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -75,136 +75,34 @@ function withFakeClaudeEnv( const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" }); const binDir = yield* makeFakeClaudeBinary(tempDir, input.lifecyclePort); const pathDelimiter = (yield* HostProcess.isWindows) ? ";" : ":"; - const previousPath = process.env.PATH; - const previousRejectsNoSessionPersistence = - process.env.T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE; - const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT; - const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE; - const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR; - const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN; - const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN; - const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; - const previousConfigDirMustBe = process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE; - const previousCwdMustNotBe = process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE; - - yield* Effect.acquireRelease( - Effect.sync(() => { - process.env.PATH = `${binDir}${pathDelimiter}${previousPath ?? ""}`; - process.env.T3_FAKE_CLAUDE_OUTPUT = input.output; - - if (input.rejectsNoSessionPersistence) { - process.env.T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE = "1"; - } else { - delete process.env.T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE; - } - - if (input.exitCode !== undefined) { - process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode); - } else { - delete process.env.T3_FAKE_CLAUDE_EXIT_CODE; - } - - if (input.stderr !== undefined) { - process.env.T3_FAKE_CLAUDE_STDERR = input.stderr; - } else { - delete process.env.T3_FAKE_CLAUDE_STDERR; - } - - if (input.argsMustContain !== undefined) { - process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain; - } else { - delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN; - } - - if (input.argsMustNotContain !== undefined) { - process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain; - } else { - delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN; - } - - if (input.stdinMustContain !== undefined) { - process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain; - } else { - delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; - } - - if (input.cwdMustNotBe !== undefined) { - process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE = input.cwdMustNotBe; - } else { - delete process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE; - } - - if (input.configDirMustBe !== undefined) { - process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = input.configDirMustBe; - } else { - delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE; - } - }), - () => - Effect.sync(() => { - process.env.PATH = previousPath; - - if (previousRejectsNoSessionPersistence === undefined) { - delete process.env.T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE; - } else { - process.env.T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE = - previousRejectsNoSessionPersistence; - } - - if (previousOutput === undefined) { - delete process.env.T3_FAKE_CLAUDE_OUTPUT; - } else { - process.env.T3_FAKE_CLAUDE_OUTPUT = previousOutput; - } - - if (previousExitCode === undefined) { - delete process.env.T3_FAKE_CLAUDE_EXIT_CODE; - } else { - process.env.T3_FAKE_CLAUDE_EXIT_CODE = previousExitCode; - } - - if (previousStderr === undefined) { - delete process.env.T3_FAKE_CLAUDE_STDERR; - } else { - process.env.T3_FAKE_CLAUDE_STDERR = previousStderr; - } - - if (previousArgsMustContain === undefined) { - delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN; - } else { - process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previousArgsMustContain; - } - - if (previousArgsMustNotContain === undefined) { - delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN; - } else { - process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previousArgsMustNotContain; - } - - if (previousStdinMustContain === undefined) { - delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN; - } else { - process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain; - } - - if (previousCwdMustNotBe === undefined) { - delete process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE; - } else { - process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE = previousCwdMustNotBe; - } - - if (previousConfigDirMustBe === undefined) { - delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE; - } else { - process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = previousConfigDirMustBe; - } - }), - ); + const hostEnv = yield* HostProcess.Environment; + const fakeClaudeEnv: Record = { + T3_FAKE_CLAUDE_OUTPUT: input.output, + T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE: input.rejectsNoSessionPersistence + ? "1" + : undefined, + T3_FAKE_CLAUDE_EXIT_CODE: input.exitCode === undefined ? undefined : String(input.exitCode), + T3_FAKE_CLAUDE_STDERR: input.stderr, + T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN: input.argsMustContain, + T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN: input.argsMustNotContain, + T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN: input.stdinMustContain, + T3_FAKE_CLAUDE_CWD_MUST_NOT_BE: input.cwdMustNotBe, + T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE: input.configDirMustBe, + }; + const environment: NodeJS.ProcessEnv = { + ...Object.fromEntries( + Object.entries(hostEnv).filter(([name]) => !name.startsWith("T3_FAKE_CLAUDE_")), + ), + ...Object.fromEntries( + Object.entries(fakeClaudeEnv).filter(([, value]) => value !== undefined), + ), + PATH: `${binDir}${pathDelimiter}${hostEnv.PATH ?? ""}`, + }; const config = decodeClaudeSettings(input.claudeConfig ?? {}); const textGeneration = yield* makeClaudeTextGeneration( config, - undefined, + environment, Effect.succeed(SYNTHETIC_CLAUDE_MODEL_CATALOG), ); return yield* effectFn(textGeneration); diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index fed1c484d0d16..b79f93c192d4e 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -277,18 +277,11 @@ it.effect("checkpoint recovery discovers nested HEAD independently of inherited const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); yield* git(["init", "empty"]); const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index")); - yield* Effect.acquireUseRelease( - Effect.sync(() => { - const previous = process.env.GIT_DIR; - process.env.GIT_DIR = path.join(cwd, ".git"); - return previous; + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }).pipe( + Effect.provideService(HostProcess.Environment, { + ...(yield* HostProcess.Environment), + GIT_DIR: path.join(cwd, ".git"), }), - () => driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }), - (previous) => - Effect.sync(() => { - if (previous === undefined) delete process.env.GIT_DIR; - else process.env.GIT_DIR = previous; - }), ); assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n"); assert.strictEqual((yield* git(["ls-tree", "-r", checkpointRef, "--", "empty"])).stdout, ""); diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 48f1f56b9b06e..a2cd548bcc0b9 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -913,8 +913,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const { gitCommonDir, indexPath, headExists } = yield* resolveCaptureRepository(input.cwd); const indexId = yield* random.uuidV4(); const tempIndexPath = path.join(gitCommonDir, `t3-checkpoint-index-${indexId}`); + const hostEnv = yield* HostProcess.Environment; const commitEnv: NodeJS.ProcessEnv = { - ...process.env, + ...hostEnv, GIT_INDEX_FILE: tempIndexPath, GIT_AUTHOR_NAME: "T3 Code", GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", @@ -1207,7 +1208,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ); if (candidates.length > CHECKPOINT_RECOVERY_MAX_CANDIDATES) return yield* error; const nestedRepoEnv: NodeJS.ProcessEnv = { - ...process.env, + ...hostEnv, GIT_DIR: undefined, GIT_WORK_TREE: undefined, GIT_COMMON_DIR: undefined, diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d00301e96e7d8..532a6db2b9e9f 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -266,6 +266,14 @@ const git = ( return result.stdout.trim(); }); +// Git blocks file submodule transports (CVE-2022-39253) despite repo config; local fixtures need env permission. +const withGitFileProtocol = (effect: Effect.Effect) => + Effect.flatMap(HostProcess.Environment, (env) => + effect.pipe( + Effect.provideService(HostProcess.Environment, { ...env, GIT_ALLOW_PROTOCOL: "file" }), + ), + ); + const initRepoWithCommit = ( cwd: string, ): Effect.Effect< @@ -4040,30 +4048,12 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const sshWrapperPath = yield* pathService.fromFileUrl( new URL("./testing/GitVcsDriverCore.fixture.sh", import.meta.url), ); - const envKeys = [ - "GCM_INTERACTIVE", - "GIT_ASKPASS", - "GIT_SSH", - "GIT_TERMINAL_PROMPT", - "SSH_ASKPASS", - "SSH_ASKPASS_REQUIRE", - "T3_TEST_SSH_ASKPASS_LOG", - ] as const; - const previousEnv = new Map(envKeys.map((key) => [key, process.env[key]])); yield* git(cwd, ["remote", "add", "origin", "ssh://example.invalid/repo.git"]); yield* git(cwd, ["update-ref", `refs/remotes/origin/${initialBranch}`, "HEAD"]); yield* git(cwd, ["branch", "--set-upstream-to", `origin/${initialBranch}`]); yield* Effect.gen(function* () { - process.env.GIT_SSH = sshWrapperPath; - process.env.GCM_INTERACTIVE = "always"; - process.env.GIT_ASKPASS = "git-askpass"; - process.env.GIT_TERMINAL_PROMPT = "1"; - process.env.SSH_ASKPASS = "ssh-askpass"; - process.env.SSH_ASKPASS_REQUIRE = "force"; - process.env.T3_TEST_SSH_ASKPASS_LOG = sshLogPath; - yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd); assert.deepEqual((yield* fileSystem.readFileString(sshLogPath)).trim().split(/\r?\n/), [ @@ -4074,18 +4064,16 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { "SSH_ASKPASS_REQUIRE=never", ]); }).pipe( - Effect.ensuring( - Effect.sync(() => { - for (const key of envKeys) { - const previous = previousEnv.get(key); - if (previous === undefined) { - delete process.env[key]; - } else { - process.env[key] = previous; - } - } - }), - ), + Effect.provideService(HostProcess.Environment, { + ...(yield* HostProcess.Environment), + GIT_SSH: sshWrapperPath, + GCM_INTERACTIVE: "always", + GIT_ASKPASS: "git-askpass", + GIT_TERMINAL_PROMPT: "1", + SSH_ASKPASS: "ssh-askpass", + SSH_ASKPASS_REQUIRE: "force", + T3_TEST_SSH_ASKPASS_LOG: sshLogPath, + }), ); }), ); @@ -4488,7 +4476,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const driver = yield* GitVcsDriver.GitVcsDriver; - const serverLocale = process.env.LC_ALL ?? "unset"; + const serverLocale = (yield* HostProcess.Environment).LC_ALL ?? "unset"; const seenLocale = path.join(yield* makeTmpDir("git-hook-locale-"), "lc-all"); yield* writeTextFile( cwd, @@ -4767,19 +4755,6 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const fileSystem = yield* FileSystem.FileSystem; const pathService = yield* Path.Path; - // Git blocks file submodule transports (CVE-2022-39253) despite repo config; local fixtures need env permission. - const previousAllowedProtocol = process.env.GIT_ALLOW_PROTOCOL; - process.env.GIT_ALLOW_PROTOCOL = "file"; - yield* Effect.addFinalizer(() => - Effect.sync(() => { - if (previousAllowedProtocol === undefined) { - delete process.env.GIT_ALLOW_PROTOCOL; - } else { - process.env.GIT_ALLOW_PROTOCOL = previousAllowedProtocol; - } - }), - ); - const submoduleRepo = yield* makeTmpDir("git-submodule-"); yield* initRepoWithCommit(submoduleRepo); yield* writeTextFile(submoduleRepo, ".gitattributes", "* text eol=lf\n"); @@ -4865,7 +4840,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { "", ); if (progress) assert.isNotEmpty(yield* Ref.get(lines)); - }), + }).pipe(withGitFileProtocol), ); it.effect("still creates the worktree when submodule checkout fails", () => @@ -4994,18 +4969,6 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const fileSystem = yield* FileSystem.FileSystem; const pathService = yield* Path.Path; - const previousAllowedProtocol = process.env.GIT_ALLOW_PROTOCOL; - process.env.GIT_ALLOW_PROTOCOL = "file"; - yield* Effect.addFinalizer(() => - Effect.sync(() => { - if (previousAllowedProtocol === undefined) { - delete process.env.GIT_ALLOW_PROTOCOL; - } else { - process.env.GIT_ALLOW_PROTOCOL = previousAllowedProtocol; - } - }), - ); - const nestedRepo = yield* makeTmpDir("git-nested-"); yield* initRepoWithCommit(nestedRepo); yield* writeTextFile(nestedRepo, "NESTED.md", "# nested\n"); @@ -5076,7 +5039,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { inner: false, nested: false, }); - }), + }).pipe(withGitFileProtocol), ); it.effect("still creates the worktree when the base-ref config stays locked", () => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 25a757104db32..351daa0e697ff 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -977,7 +977,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), ); const baseEnv = { - ...process.env, + ...(yield* HostProcess.Environment), // Concurrent status polls must not take index.lock to save refreshed indexes. GIT_OPTIONAL_LOCKS: "0", ...input.env, diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index 7ab7cd24a986c..dbddce4c1c2fe 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -22,6 +22,7 @@ import { } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; +import * as Config from "effect/Config"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -2403,7 +2404,7 @@ const main = Effect.gen(function* () { } return; } - const apiKey = process.env.ANTHROPIC_API_KEY ?? ""; + const apiKey = yield* Config.String("ANTHROPIC_API_KEY").pipe(Config.withDefault("")); const out = flags.out; if ((!apiKey && !codex) || out === undefined) { const message = diff --git a/packages/effect-acp/test/fixtures/acp-mock-peer.ts b/packages/effect-acp/test/fixtures/acp-mock-peer.ts index a75d6f5df1bc0..7509cd88457e1 100644 --- a/packages/effect-acp/test/fixtures/acp-mock-peer.ts +++ b/packages/effect-acp/test/fixtures/acp-mock-peer.ts @@ -23,6 +23,8 @@ const sessionId = "mock-session-1"; const v2Management = process.env.ACP_MOCK_V2_MANAGEMENT === "1"; const unknownVariants = process.env.ACP_MOCK_UNKNOWN_VARIANTS === "1"; const mcpOverAcp = process.env.ACP_MOCK_MCP_OVER_ACP === "1"; +const v2Diff = process.env.ACP_MOCK_V2_DIFF === "1"; +const badTypedRequest = process.env.ACP_MOCK_BAD_TYPED_REQUEST === "1"; const program = Effect.gen(function* () { const agent = yield* AcpAgent.AcpAgent; @@ -178,7 +180,7 @@ const program = Effect.gen(function* () { }, }); - if (process.env.ACP_MOCK_V2_DIFF === "1") { + if (v2Diff) { yield* agent.client.sessionUpdate({ sessionId, update: { @@ -211,7 +213,7 @@ const program = Effect.gen(function* () { }); yield* agent.client.extRequest("x/typed_request", { - message: process.env.ACP_MOCK_BAD_TYPED_REQUEST === "1" ? 123 : "hello from typed request", + message: badTypedRequest ? 123 : "hello from typed request", }); yield* agent.client.extNotification("x/typed_notification", { diff --git a/packages/effect-codex-app-server/scripts/generate.ts b/packages/effect-codex-app-server/scripts/generate.ts index 86c0dc7e662da..343738c800c83 100644 --- a/packages/effect-codex-app-server/scripts/generate.ts +++ b/packages/effect-codex-app-server/scripts/generate.ts @@ -203,12 +203,13 @@ const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () { yield* fs.makeDirectory(generatedDir, { recursive: true }); }); +const githubToken = process.env.GITHUB_TOKEN; + const fetchText = Effect.fn("fetchText")(function* (url: string) { - const token = process.env.GITHUB_TOKEN; return yield* HttpClientRequest.get(url).pipe( HttpClientRequest.setHeader("user-agent", USER_AGENT), - token && url.startsWith("https://api.github.com/") - ? HttpClientRequest.bearerToken(token) + githubToken && url.startsWith("https://api.github.com/") + ? HttpClientRequest.bearerToken(githubToken) : (request) => request, HttpClient.execute, Effect.flatMap(HttpClientResponse.filterStatusOk), diff --git a/packages/effect-codex-app-server/test/examples/codex-app-server-probe.ts b/packages/effect-codex-app-server/test/examples/codex-app-server-probe.ts index fed0e61440792..898c8cc094598 100644 --- a/packages/effect-codex-app-server/test/examples/codex-app-server-probe.ts +++ b/packages/effect-codex-app-server/test/examples/codex-app-server-probe.ts @@ -7,10 +7,12 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import * as CodexClient from "../../src/client.ts"; +const codexBin = process.env.CODEX_BIN ?? "codex"; + const program = Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const handle = yield* spawner.spawn( - ChildProcess.make(process.env.CODEX_BIN ?? "codex", ["app-server"], { + ChildProcess.make(codexBin, ["app-server"], { cwd: process.cwd(), shell: false, }), diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 904fbdfcb5c22..02a32ac40250d 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -91,10 +91,12 @@ const makeFakeNpmToolchain = Effect.fn("AcpRegistrySupport.test.makeFakeNpmToolc npmPath, ); yield* fileSystem.chmod(npmPath, 0o755); + // The fake toolchain runs on the real host, not the simulated provider environment. + const hostEnv = HostProcess.Environment.defaultValue(); return { environment: { - ...process.env, - PATH: `${toolchainBin}:${process.env.PATH ?? ""}`, + ...hostEnv, + PATH: `${toolchainBin}:${hostEnv.PATH ?? ""}`, FAKE_NPM_LOG: logPath, FAKE_NPM_PREFIX: path.join(rootDirectory, "external-npm-global"), FAKE_NPM_MANIFEST: encodeUnknownJson({ @@ -127,10 +129,12 @@ const makeFakeUvToolchain = Effect.fn("AcpRegistrySupport.test.makeFakeUvToolcha uvPath, ); yield* fileSystem.chmod(uvPath, 0o755); + // The fake toolchain runs on the real host, not the simulated provider environment. + const hostEnv = HostProcess.Environment.defaultValue(); return { environment: { - ...process.env, - PATH: `${toolchainBin}:${process.env.PATH ?? ""}`, + ...hostEnv, + PATH: `${toolchainBin}:${hostEnv.PATH ?? ""}`, FAKE_UV_LOG: logPath, FAKE_UV_BIN: path.join(rootDirectory, "external-uv-bin"), FAKE_UV_EXECUTABLE: executablePath, diff --git a/packages/source-control-forgejo/src/server/ForgejoCli.ts b/packages/source-control-forgejo/src/server/ForgejoCli.ts index a2cd718b9d497..4ae39f3ae9626 100644 --- a/packages/source-control-forgejo/src/server/ForgejoCli.ts +++ b/packages/source-control-forgejo/src/server/ForgejoCli.ts @@ -1,6 +1,8 @@ +import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Result from "effect/Result"; import * as Clock from "effect/Clock"; @@ -209,7 +211,14 @@ export function matchForgejoLogin( : undefined; } +const ForgejoKeysConfig = Config.all({ + dataHome: Config.String("XDG_DATA_HOME").pipe(Config.option), + appData: Config.String("APPDATA").pipe(Config.option), +}); + export const make = Effect.gen(function* () { + // Optional strings cannot fail to decode. + const { dataHome, appData } = yield* Effect.suspend(() => ForgejoKeysConfig).pipe(Effect.orDie); const { process } = yield* SourceControlHost.SourceControlHost; const fileSystem = yield* FileSystem.FileSystem; const httpClient = yield* HttpClient.HttpClient; @@ -249,10 +258,8 @@ export const make = Effect.gen(function* () { for (const path of forgejoKeysPaths({ platform: yield* HostProcess.Platform, home: yield* HostProcess.HomeDirectory, - ...(globalThis.process.env.XDG_DATA_HOME - ? { dataHome: globalThis.process.env.XDG_DATA_HOME } - : {}), - ...(globalThis.process.env.APPDATA ? { appData: globalThis.process.env.APPDATA } : {}), + ...(Option.isSome(dataHome) ? { dataHome: dataHome.value } : {}), + ...(Option.isSome(appData) ? { appData: appData.value } : {}), })) { const exists = yield* fileSystem.exists(path).pipe( Effect.mapError( diff --git a/scripts/build-npm-launcher.test.ts b/scripts/build-npm-launcher.test.ts index fd241e7543bae..bb6a5c73bf5a5 100644 --- a/scripts/build-npm-launcher.test.ts +++ b/scripts/build-npm-launcher.test.ts @@ -68,7 +68,7 @@ exit 7 yield* fs.chmod(path.join(root, "release", stem, "t3"), 0o755); const tar = yield* run("tar", ["-czf", archiveName, stem], { cwd: path.join(root, "release"), - env: { PATH: process.env.PATH }, + env: { PATH: (yield* HostProcess.Environment).PATH }, }); assert.equal(tar.exitCode, 0, tar.stderr); const archive = yield* fs.readFile(path.join(root, "release", archiveName)); @@ -131,7 +131,7 @@ it.layer(NodeServices.layer)("build-npm-launcher", (it) => { yield* fs.makeDirectory(installed); const unpack = yield* run("tar", ["-xzf", output.tarball, "-C", installed], { cwd: root, - env: { PATH: process.env.PATH }, + env: { PATH: (yield* HostProcess.Environment).PATH }, }); assert.equal(unpack.exitCode, 0, unpack.stderr); const packageDir = path.join(installed, "package"); @@ -139,7 +139,7 @@ it.layer(NodeServices.layer)("build-npm-launcher", (it) => { const release = yield* serveFakeRelease(root); const home = path.join(root, "home"); const env = { - PATH: process.env.PATH, + PATH: (yield* HostProcess.Environment).PATH, T3CODE_HOME: home, T3CODE_TEST_CALLS: path.join(root, "calls"), T3CODE_RELEASE_BASE_URL: release.baseUrl, @@ -374,7 +374,7 @@ syncBuiltinESMExports(); `, ); const env = { - PATH: process.env.PATH, + PATH: (yield* HostProcess.Environment).PATH, T3CODE_HOME: home, T3CODE_RELEASE_BASE_URL: release.baseUrl, T3CODE_TEST_READY: path.join(root, "probe-ready"), diff --git a/tsconfig.effect.json b/tsconfig.effect.json index 685d7ebbb2a99..29240a31e71e8 100644 --- a/tsconfig.effect.json +++ b/tsconfig.effect.json @@ -96,6 +96,7 @@ "timeoutCatchTagToTimeoutOrElse": "error", "unnecessaryPipe": "error", "unnecessaryTypeofType": "error", + "processEnvInEffect": "error", "schemaNumber": "off" }, "overrides": [ From 5a906583fed3fa41dc806f2a19bd9d095537ed3e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 4 Nov 2026 19:47:19 -0800 Subject: [PATCH 003/397] refactor: Effect.try calls map failures to typed errors (#31217) Co-authored-by: Claude Opus 5.5 --- apps/desktop/src/app/DesktopCliCommand.ts | 5 +- apps/desktop/src/electron/ElectronProtocol.ts | 4 +- apps/desktop/src/ipc/methods/window.ts | 45 +++--- .../desktop/src/permissions/MacPermissions.ts | 30 ++-- .../preview/BrowserImport/BrowserImport.ts | 14 +- apps/desktop/src/snapShot/DesktopSnapShot.ts | 136 +++++++++++------- apps/desktop/src/window/DesktopWindow.ts | 17 ++- .../agent-awareness/remoteRegistration.ts | 9 +- .../SettingsDiagnosticsRouteScreen.tsx | 14 +- .../pull-requests/usePullRequestDiff.test.tsx | 10 +- apps/mobile/src/lib/composerImagePreview.ts | 15 +- .../src/native/ProjectChipIconImages.tsx | 20 ++- .../scripts/record-fx-acp-replay-fixture.ts | 12 +- .../scripts/record-grok-acp-replay-fixture.ts | 10 +- apps/server/src/auth/McpOAuth.ts | 2 +- apps/server/src/auth/http.test.ts | 2 +- .../src/cloud/ManagedEndpointRuntime.ts | 18 ++- apps/server/src/compileCache.ts | 21 ++- apps/server/src/device/localSshDeviceHost.ts | 6 +- apps/server/src/mcp/AcpMcpStdioBridge.ts | 19 ++- .../src/observability/EventLoopMonitor.ts | 26 +++- apps/server/src/observability/HeapSnapshot.ts | 17 ++- .../Adapters/ClaudeAdapterV2.ts | 42 +++--- apps/server/src/orchestration-v2/http.ts | 6 +- .../persistence/initializeV2Database.test.ts | 4 +- .../src/persistence/initializeV2Database.ts | 25 ++-- apps/server/src/preview/ServerBrowser.ts | 14 +- .../server/src/project/AgentSessionScanner.ts | 45 ++++-- .../src/provider/AntigravityInstallation.ts | 7 +- apps/server/src/provider/ClaudeProvider.ts | 55 ++++--- .../src/provider/CodexChatGptAuth.test.ts | 9 +- .../Drivers/antigravityUsageReader.ts | 5 +- .../provider/acp/AntigravityTurnOutcome.ts | 81 +++++++---- .../src/provider/antigravityAuthSupport.ts | 21 ++- apps/server/src/storageCleanup.ts | 16 ++- apps/server/src/terminal/NodePtyAdapter.ts | 36 +++-- apps/server/src/usage/UsageService.test.ts | 22 +-- apps/server/src/vcs/GitVcsDriverCore.ts | 5 +- apps/server/src/vcs/removeEmptyDirectory.ts | 15 +- .../src/components/device/deviceHubAtoms.ts | 15 +- apps/web/src/connection/platform.ts | 16 ++- evals/mcp-tool-use/run.ts | 63 +++++--- infra/relay/scripts/android-push-watch.ts | 14 +- infra/task-cache/src/developerAuth.ts | 3 +- .../src/server/AcpSessionRuntime.ts | 12 +- .../src/server/CursorAgentSdk.ts | 31 ++-- .../src/server/credentialStore.test.ts | 22 +-- .../src/server/textGeneration.ts | 87 ++++++----- .../provider-muse/src/server/MuseUsageHome.ts | 8 +- packages/provider-muse/src/server/adapter.ts | 19 ++- .../provider-muse/src/server/modelCatalog.ts | 12 +- packages/provider-muse/src/server/sdk.ts | 31 +++- .../src/server/textGeneration.ts | 29 ++-- .../provider-muse/src/server/usage.test.ts | 18 +-- .../src/server/usageLimits.ts | 60 ++++---- packages/shared/src/HostProcess.ts | 18 ++- packages/shared/src/nodeSqliteClient.ts | 6 +- packages/shared/src/relayClient.ts | 15 +- packages/shared/src/shell.test.ts | 8 +- scripts/build-cli-archive.ts | 14 +- scripts/build-desktop-artifact.ts | 40 ++++-- tsconfig.effect.json | 1 + 62 files changed, 949 insertions(+), 453 deletions(-) diff --git a/apps/desktop/src/app/DesktopCliCommand.ts b/apps/desktop/src/app/DesktopCliCommand.ts index 5dfb579cf2cc5..de48328850794 100644 --- a/apps/desktop/src/app/DesktopCliCommand.ts +++ b/apps/desktop/src/app/DesktopCliCommand.ts @@ -140,7 +140,10 @@ export const make = Effect.gen(function* () { const isExecutableFile = Effect.fn("DesktopCliCommand.isExecutableFile")( function* (target: string) { if ((yield* fs.stat(target)).type !== "File") return false; - yield* Effect.tryPromise(() => NodeFSP.access(target, NodeFSP.constants.X_OK)); + yield* Effect.tryPromise({ + try: () => NodeFSP.access(target, NodeFSP.constants.X_OK), + catch: () => fail(`${target} is not executable.`), + }); return true; }, Effect.orElseSucceed(() => false), diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts index 27af3f2cfd8ae..7563898f43efc 100644 --- a/apps/desktop/src/electron/ElectronProtocol.ts +++ b/apps/desktop/src/electron/ElectronProtocol.ts @@ -216,9 +216,7 @@ const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* ( if (request.method !== "GET" && request.method !== "HEAD") { return new Response(null, { status: 405 }); } - const pathname = yield* Effect.try(() => decodeURIComponent(url.pathname)).pipe( - Effect.orElseSucceed(() => null), - ); + const pathname = Option.getOrNull(Option.liftThrowable(decodeURIComponent)(url.pathname)); if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 }); const root = path.resolve(assetDirectory); const assetPath = path.resolve(root, `.${pathname}`); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 63b8db03dad03..2833abca43859 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -314,6 +314,12 @@ export const openExternal = DesktopIpc.makeIpcMethod({ const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024; +// No URL field: media URLs can carry signed query tokens. +class MediaReadError extends Schema.TaggedError()("MediaReadError", { + message: Schema.String, + cause: Schema.Defect(), +}) {} + // The renderer can display media it cannot fetch(); reading here keeps Save and Copy working for it. export const readMedia = DesktopIpc.makeIpcMethod({ channel: IpcChannels.READ_MEDIA_CHANNEL, @@ -330,25 +336,28 @@ export const readMedia = DesktopIpc.makeIpcMethod({ return null; } const session = window.value.webContents.session; - return yield* Effect.tryPromise(async () => { - // Like an , send the session's cookies. - const response = await session.fetch(url, { credentials: "include" }); - const mimeType = response.headers.get("content-type") ?? ""; - if (!response.ok || !response.body) { - await response.body?.cancel(); - return { status: response.status, mimeType, data: new Uint8Array() }; - } - // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory. - const chunks: Uint8Array[] = []; - let size = 0; - for await (const chunk of response.body) { - size += chunk.byteLength; - if (size > READ_MEDIA_MAX_BYTES) { - return { status: 413, mimeType, data: new Uint8Array() }; + return yield* Effect.tryPromise({ + try: async () => { + // Like an , send the session's cookies. + const response = await session.fetch(url, { credentials: "include" }); + const mimeType = response.headers.get("content-type") ?? ""; + if (!response.ok || !response.body) { + await response.body?.cancel(); + return { status: response.status, mimeType, data: new Uint8Array() }; } - chunks.push(chunk); - } - return { status: response.status, mimeType, data: Buffer.concat(chunks) }; + // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory. + const chunks: Uint8Array[] = []; + let size = 0; + for await (const chunk of response.body) { + size += chunk.byteLength; + if (size > READ_MEDIA_MAX_BYTES) { + return { status: 413, mimeType, data: new Uint8Array() }; + } + chunks.push(chunk); + } + return { status: response.status, mimeType, data: Buffer.concat(chunks) }; + }, + catch: (cause) => new MediaReadError({ message: "Could not read media.", cause }), }).pipe(Effect.orElseSucceed(() => null)); }), }); diff --git a/apps/desktop/src/permissions/MacPermissions.ts b/apps/desktop/src/permissions/MacPermissions.ts index 0a7bb3a2c4475..2052f378743c6 100644 --- a/apps/desktop/src/permissions/MacPermissions.ts +++ b/apps/desktop/src/permissions/MacPermissions.ts @@ -2,6 +2,7 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; import * as Electron from "electron"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import { MacPermissionHelper } from "./MacPermissionHelper.ts"; @@ -18,6 +19,15 @@ export class MacPermissions extends Context.Service< } >()("@t3tools/desktop/permissions/MacPermissions") {} +class MacPermissionHelperError extends Schema.TaggedError()( + "MacPermissionHelperError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not show the permission helper."; + } +} + export const layer = Layer.effect( MacPermissions, Effect.gen(function* () { @@ -28,15 +38,17 @@ export const layer = Layer.effect( return MacPermissions.of({ showHelper: Effect.fn("MacPermissions.showHelper")(function* (permission, owner, isGranted) { if (environment.platform !== "darwin" || !environment.isPackaged) return; - yield* Effect.tryPromise(() => - helper.show( - permission, - path.join(environment.dirname, "mac-permission-preload.cjs"), - owner, - environment.resolveResourcePathCandidates("icon.png"), - isGranted, - ), - ).pipe( + yield* Effect.tryPromise({ + try: () => + helper.show( + permission, + path.join(environment.dirname, "mac-permission-preload.cjs"), + owner, + environment.resolveResourcePathCandidates("icon.png"), + isGranted, + ), + catch: (cause) => new MacPermissionHelperError({ cause }), + }).pipe( Effect.catch((cause) => Effect.logWarning("Could not show permission helper", cause)), ); }), diff --git a/apps/desktop/src/preview/BrowserImport/BrowserImport.ts b/apps/desktop/src/preview/BrowserImport/BrowserImport.ts index 0a762d92416aa..e5f8665d11358 100644 --- a/apps/desktop/src/preview/BrowserImport/BrowserImport.ts +++ b/apps/desktop/src/preview/BrowserImport/BrowserImport.ts @@ -92,6 +92,15 @@ export const checkBrowserImportPolicy = Effect.fn("BrowserImport.checkPolicy")(f } }); +class BrowserCookieFlushError extends Schema.TaggedError()( + "BrowserCookieFlushError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Imported cookies could not be flushed to disk."; + } +} + export class BrowserCookieWriteError extends Schema.TaggedError()( "BrowserCookieWriteError", { @@ -183,7 +192,10 @@ export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* ( } // Cookie writes settle in memory; flush to disk before reporting a durable import. if (imported > 0) { - yield* Effect.tryPromise(() => session.cookies.flushStore()).pipe( + yield* Effect.tryPromise({ + try: () => session.cookies.flushStore(), + catch: (cause) => new BrowserCookieFlushError({ cause }), + }).pipe( Effect.tapError((error) => Effect.logWarning("Imported cookies could not be flushed to disk", { cause: error.cause }), ), diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.ts index 95b39d944e490..ae0c2f04121ea 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts @@ -167,6 +167,17 @@ export class DesktopSnapShotError extends Schema.TaggedError()( + "SnapShotShortcutError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not register the SnapShot shortcut."; + } +} + +const shortcutFailure = (cause: unknown) => new SnapShotShortcutError({ cause }); + function captureFailure(cause: unknown, captureId?: string): DesktopSnapShotError { if (isDesktopSnapShotError(cause)) return cause; const operation = cause instanceof CaptureSetupRequiredError ? "setup-required" : "capture"; @@ -1068,13 +1079,15 @@ export const make = Effect.gen(function* () { if (mode === "portal") { return { available: false, message: WAYLAND_MODIFIER_PAIR_UNAVAILABLE_MESSAGE }; } - const available = yield* Effect.tryPromise(() => - startPairShortcutProcess( - snapShotShortcutModifierPair(shortcut), - () => undefined, - () => undefined, - ), - ).pipe( + const available = yield* Effect.tryPromise({ + try: () => + startPairShortcutProcess( + snapShotShortcutModifierPair(shortcut), + () => undefined, + () => undefined, + ), + catch: shortcutFailure, + }).pipe( Effect.tap((stop) => Effect.sync(stop)), Effect.as(true), Effect.orElseSucceed(() => false), @@ -1089,7 +1102,10 @@ export const make = Effect.gen(function* () { const systemConflict = snapShotShortcutSystemConflict(shortcut); if (systemConflict) return { available: false, message: systemConflict }; if (mode === "portal") { - return yield* Effect.try(() => portalShortcutTrigger(shortcut)).pipe( + return yield* Effect.try({ + try: () => portalShortcutTrigger(shortcut), + catch: shortcutFailure, + }).pipe( Effect.match({ onSuccess: () => ({ available: true, @@ -1199,13 +1215,16 @@ export const make = Effect.gen(function* () { return; } if (mode === "portal" && niriSocketPath()) { - const registered = yield* Effect.tryPromise(async () => { - const { startNiriCaptureShortcut } = await import("./NiriCaptureShortcut.ts"); - return startNiriCaptureShortcut(linuxAppId, onCurrentShortcut, () => { - void runPromise( - setShortcutFailure("The Niri capture endpoint disconnected. Restart T3 Code."), - ).catch(() => undefined); - }); + const registered = yield* Effect.tryPromise({ + try: async () => { + const { startNiriCaptureShortcut } = await import("./NiriCaptureShortcut.ts"); + return startNiriCaptureShortcut(linuxAppId, onCurrentShortcut, () => { + void runPromise( + setShortcutFailure("The Niri capture endpoint disconnected. Restart T3 Code."), + ).catch(() => undefined); + }); + }, + catch: shortcutFailure, }).pipe( Effect.tap((stop) => Effect.sync(() => { @@ -1249,29 +1268,32 @@ export const make = Effect.gen(function* () { shortcutMessage: null, message: null, }); - yield* Effect.tryPromise(async () => { - const { PortalCaptureShortcut } = await import("./PortalCaptureShortcut.ts"); - return new PortalCaptureShortcut( - linuxAppId, - isModifierPairShortcut(shortcut) - ? { - key: "2", - ctrlKey: true, - modKey: false, - altKey: false, - shiftKey: true, - metaKey: false, - } - : shortcut, - onCurrentShortcut, - () => { - if (generation !== shortcutGeneration) return; - shortcutVerified = false; - void runPromise(emit({ type: "shortcut-changed" })).catch(() => undefined); - }, - undefined, - hyprland, - ); + yield* Effect.tryPromise({ + try: async () => { + const { PortalCaptureShortcut } = await import("./PortalCaptureShortcut.ts"); + return new PortalCaptureShortcut( + linuxAppId, + isModifierPairShortcut(shortcut) + ? { + key: "2", + ctrlKey: true, + modKey: false, + altKey: false, + shiftKey: true, + metaKey: false, + } + : shortcut, + onCurrentShortcut, + () => { + if (generation !== shortcutGeneration) return; + shortcutVerified = false; + void runPromise(emit({ type: "shortcut-changed" })).catch(() => undefined); + }, + undefined, + hyprland, + ); + }, + catch: shortcutFailure, }).pipe( Effect.tap((registration) => Effect.sync(() => { @@ -1293,15 +1315,21 @@ export const make = Effect.gen(function* () { let registered = false; if (isModifierPairShortcut(shortcut)) { - registered = yield* Effect.tryPromise(() => - startPairShortcutProcess(snapShotShortcutModifierPair(shortcut), onCurrentShortcut, () => { - void pipe( - snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform), - setShortcutFailure, - runPromise, - ).catch(() => undefined); - }), - ).pipe( + registered = yield* Effect.tryPromise({ + try: () => + startPairShortcutProcess( + snapShotShortcutModifierPair(shortcut), + onCurrentShortcut, + () => { + void pipe( + snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform), + setShortcutFailure, + runPromise, + ).catch(() => undefined); + }, + ), + catch: shortcutFailure, + }).pipe( Effect.tap((stop) => Effect.sync(() => { stopShiftShortcut = stop; @@ -1489,7 +1517,10 @@ export const make = Effect.gen(function* () { if (action === "retry-shortcut") { const currentPortal = portalShortcut; if (currentPortal?.hasSession && !currentPortal.state.shortcutPending) { - yield* Effect.tryPromise(() => currentPortal.configure()).pipe( + yield* Effect.tryPromise({ + try: () => currentPortal.configure(), + catch: shortcutFailure, + }).pipe( Effect.mapError( (error) => new DesktopSnapShotSetupError({ @@ -1583,9 +1614,12 @@ export const make = Effect.gen(function* () { state: Ref.get(stateRef).pipe( Effect.flatMap((state) => state.mode === "portal" - ? Effect.tryPromise(async () => { - const { getLinuxCaptureSupport } = await import("./LinuxSnapShot.ts"); - return getLinuxCaptureSupport(linuxAppId); + ? Effect.tryPromise({ + try: async () => { + const { getLinuxCaptureSupport } = await import("./LinuxSnapShot.ts"); + return getLinuxCaptureSupport(linuxAppId); + }, + catch: (cause) => new DesktopSnapShotError({ operation: "unsupported", cause }), }).pipe( Effect.map((support) => ({ ...state, ...support })), Effect.catch((error) => diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 5e02f4cfd8bbe..b2f643e55fb97 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -5,6 +5,7 @@ import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Electron from "electron"; @@ -39,6 +40,15 @@ import { makeQuitShortcutHandler } from "./QuitHold.ts"; import { copyContextMenuImage } from "./ContextMenuImage.ts"; const TITLEBAR_HEIGHT = 40; + +class ContextMenuImageCopyError extends Schema.TaggedError()( + "ContextMenuImageCopyError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not copy the context-menu image."; + } +} // Match --workspace-topbar-height in apps/web/src/index.css; native macOS buttons stay 14 points at any zoom. const MACOS_WORKSPACE_TOPBAR_HEIGHT = 52; const MACOS_WINDOW_BUTTON_RADIUS = 7; @@ -580,9 +590,10 @@ export const make = Effect.gen(function* () { label: "Copy Image", click: () => { void runPromise( - Effect.tryPromise(() => copyContextMenuImage(contents, params)).pipe( - Effect.catch(() => logWindowWarning("failed to copy context-menu image")), - ), + Effect.tryPromise({ + try: () => copyContextMenuImage(contents, params), + catch: (cause) => new ContextMenuImageCopyError({ cause }), + }).pipe(Effect.catch(() => logWindowWarning("failed to copy context-menu image"))), ); }, }); diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts index 6151c8935cc2b..437a00be9eaf1 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts @@ -62,6 +62,7 @@ const AgentAwarenessOperation = Schema.Literals([ "list-active-live-activities", "load-live-activity-prime-preferences", "prime-live-activity", + "load-registration-record", ]); export class AgentAwarenessOperationError extends Schema.TaggedError()( @@ -345,9 +346,11 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith } const identity = relayTokenProviderIdentity ?? ""; - const persisted = yield* Effect.tryPromise(() => loadAgentAwarenessRegistrationRecord()).pipe( - Effect.orElseSucceed(() => null), - ); + const persisted = yield* Effect.tryPromise({ + try: () => loadAgentAwarenessRegistrationRecord(), + catch: (cause) => + new AgentAwarenessOperationError({ operation: "load-registration-record", cause }), + }).pipe(Effect.orElseSucceed(() => null)); if (expectedGeneration !== deviceRegistrationGeneration) { // Signed out while the record loaded — do not resurrect the cleared // record or report the previous account's registration as current. diff --git a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx index b3efc031af645..528a18541eb46 100644 --- a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx +++ b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx @@ -6,6 +6,7 @@ import * as Updates from "expo-updates"; import { useAtomSet, useAtomValue } from "@effect/atom-react"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as Schema from "effect/Schema"; import { AsyncResult, Atom } from "effect/reactivity"; import { useState } from "react"; import { View } from "react-native"; @@ -34,9 +35,20 @@ type CrashLogState = | { readonly status: "unavailable" } | { readonly status: "ready"; readonly records: ReadonlyArray }; +class CrashLogReadError extends Schema.TaggedError()("CrashLogReadError", { + cause: Schema.Defect(), +}) { + override get message(): string { + return "Could not read the expo-updates log."; + } +} + // Not kept alive: each visit to the screen re-reads the log. const crashLogAtom = Atom.make( - Effect.tryPromise(() => Updates.readLogEntriesAsync(LOG_WINDOW_MS)).pipe( + Effect.tryPromise({ + try: () => Updates.readLogEntriesAsync(LOG_WINDOW_MS), + catch: (cause) => new CrashLogReadError({ cause }), + }).pipe( Effect.map((entries): CrashLogState => ({ status: "ready", records: parseStartupCrashRecords(entries), diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx b/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx index 3000efb9633bf..3fc878b5cf902 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx +++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx @@ -1,6 +1,6 @@ import { RegistryContext } from "@effect/atom-react"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; -import type { PullRequestDiffResult } from "@t3tools/contracts"; +import { PullRequestOperationError, type PullRequestDiffResult } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { Atom, AtomRegistry } from "effect/reactivity"; import { act, useLayoutEffect, useState } from "react"; @@ -32,12 +32,14 @@ function setup() { }[] = []; const queries = Atom.family((cursor: string | null) => Atom.make( - Effect.tryPromise( - () => + Effect.tryPromise({ + try: () => new Promise((resolve, reject) => { requests.push({ cursor, resolve, reject }); }), - ), + catch: (cause) => + new PullRequestOperationError({ operation: "diff", detail: "Connection lost", cause }), + }), ).pipe(Atom.keepAlive), ); mocks.diff.mockImplementation((target: { input: { cursor?: string } }) => diff --git a/apps/mobile/src/lib/composerImagePreview.ts b/apps/mobile/src/lib/composerImagePreview.ts index bcd649b3d106d..6c27d3889bf62 100644 --- a/apps/mobile/src/lib/composerImagePreview.ts +++ b/apps/mobile/src/lib/composerImagePreview.ts @@ -1,6 +1,7 @@ import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; import * as Hash from "effect/Hash"; +import * as Schema from "effect/Schema"; import { Atom } from "effect/reactivity"; import type { DraftComposerImageAttachment } from "./composerImages"; @@ -31,6 +32,15 @@ async function materializeDataUrlPreview(id: string, dataUrl: string): Promise()( + "ImagePreviewCacheError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not cache an image preview."; + } +} + /** * Keyed by attachment id only: the cached file is named by id, and an upload * reference landing on the same draft must not restart materialization and @@ -48,7 +58,10 @@ export class MaterializedPreviewKey implements Equal.Equal { export const materializedPreviewAtom = Atom.family(({ attachment }: MaterializedPreviewKey) => Atom.make( - Effect.tryPromise(() => materializeDataUrlPreview(attachment.id, attachment.previewUri)).pipe( + Effect.tryPromise({ + try: () => materializeDataUrlPreview(attachment.id, attachment.previewUri), + catch: (cause) => new ImagePreviewCacheError({ cause }), + }).pipe( Effect.catch((error) => Effect.logWarning("[composer-attachments] could not cache an image preview", error).pipe( Effect.as(null), diff --git a/apps/mobile/src/native/ProjectChipIconImages.tsx b/apps/mobile/src/native/ProjectChipIconImages.tsx index 25038801bf2ff..56b355ef6ab82 100644 --- a/apps/mobile/src/native/ProjectChipIconImages.tsx +++ b/apps/mobile/src/native/ProjectChipIconImages.tsx @@ -1,5 +1,6 @@ import type { ProjectIconColor } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; import { Atom } from "effect/reactivity"; import { useRef, useSyncExternalStore } from "react"; import { Platform, View } from "react-native"; @@ -68,11 +69,22 @@ function subscribe(listener: () => void) { return () => listeners.delete(listener); } +class ProjectGlyphRasterizeError extends Schema.TaggedError()( + "ProjectGlyphRasterizeError", + { key: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `Could not rasterize the project glyph ${this.key}.`; + } +} + export const projectGlyphImageAtom = Atom.family((key: string) => - Atom.make(Effect.tryPromise(() => rasterize(key))).pipe( - Atom.keepAlive, - Atom.withLabel(`mobile-project-glyph-image:${key}`), - ), + Atom.make( + Effect.tryPromise({ + try: () => rasterize(key), + catch: (cause) => new ProjectGlyphRasterizeError({ key, cause }), + }), + ).pipe(Atom.keepAlive, Atom.withLabel(`mobile-project-glyph-image:${key}`)), ); export function ProjectChipIconRasterizer() { diff --git a/apps/server/scripts/record-fx-acp-replay-fixture.ts b/apps/server/scripts/record-fx-acp-replay-fixture.ts index ad24e8140ce96..17b1a8f1b7d06 100644 --- a/apps/server/scripts/record-fx-acp-replay-fixture.ts +++ b/apps/server/scripts/record-fx-acp-replay-fixture.ts @@ -34,6 +34,7 @@ import { ORCHESTRATOR_REPLAY_FIXTURES } from "../src/orchestration-v2/testkit/fi import { materializeFixtureInput } from "../src/orchestration-v2/testkit/fixtures/shared.ts"; import { runOrchestratorV2Scenario } from "../src/orchestration-v2/testkit/OrchestratorScenario.ts"; import * as ProviderReplayHarness from "../src/orchestration-v2/testkit/ProviderReplayHarness.ts"; +import * as Result from "effect/Result"; const wallClock = Clock.Clock.defaultValue(); const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); @@ -502,11 +503,8 @@ const recordScenario = Effect.fn("recordFxScenario")(function* (fixtureName: str }; const outputPath = readArgValues("--out")[0] ?? (yield* path.fromFileUrl(variant.transcriptFile)); - const liveFailure = yield* Effect.try(() => variant.assertOutput(result, transcript)).pipe( - Effect.flip, - Effect.option, - ); - if (liveFailure._tag === "Some") { + const liveFailure = Result.try(() => variant.assertOutput(result, transcript)); + if (Result.isFailure(liveFailure)) { const dumpPath = path.join( recorderEnv.TMPDIR ?? "/tmp", `fx-replay-${fixtureName}-failed.json`, @@ -514,9 +512,9 @@ const recordScenario = Effect.fn("recordFxScenario")(function* (fixtureName: str yield* fs.writeFileString(dumpPath, encodeJson(transcript)); yield* Console.log( `Live orchestration failed ${fixtureName} assertions; left ${outputPath} unchanged. Dump: ${dumpPath}`, - liveFailure.value, + liveFailure.failure, ); - return yield* Effect.die(liveFailure.value); + return yield* Effect.die(liveFailure.failure); } const { entries: transcriptEntries, ...header } = transcript; diff --git a/apps/server/scripts/record-grok-acp-replay-fixture.ts b/apps/server/scripts/record-grok-acp-replay-fixture.ts index d9c5facfa71fc..4d017e68dd7bb 100644 --- a/apps/server/scripts/record-grok-acp-replay-fixture.ts +++ b/apps/server/scripts/record-grok-acp-replay-fixture.ts @@ -35,6 +35,7 @@ import * as ProviderReplayHarness from "../src/orchestration-v2/testkit/Provider import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; import { makeGrokAcpRuntime } from "@t3tools/provider-grok/testing"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; +import * as Result from "effect/Result"; const wallClock = Clock.Clock.defaultValue(); const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); @@ -554,12 +555,9 @@ const recordScenario = Effect.fn("recordGrokScenario")(function* (fixtureName: s ); yield* Console.log(`Wrote ${transcriptEntries.length} Grok ACP replay entries to ${outputPath}`); - const liveFailure = yield* Effect.try(() => variant.assertOutput(result, transcript)).pipe( - Effect.flip, - Effect.option, - ); - if (liveFailure._tag === "Some") { - yield* Console.log(`Live orchestration failed ${fixtureName} assertions:`, liveFailure.value); + const liveFailure = Result.try(() => variant.assertOutput(result, transcript)); + if (Result.isFailure(liveFailure)) { + yield* Console.log(`Live orchestration failed ${fixtureName} assertions:`, liveFailure.failure); } }); diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index bc89ab9fd2906..0be7c1ebb2624 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -283,7 +283,7 @@ const make = Effect.gen(function* () { if (!body || !signature || extra !== undefined) return undefined; const verified = yield* signer.verify(`mcp-client-id.${body}`, signature); if (!verified) return undefined; - const json = yield* Effect.try(() => base64UrlDecodeUtf8(body)).pipe(Effect.option); + const json = Option.liftThrowable(base64UrlDecodeUtf8)(body); if (Option.isNone(json)) return undefined; return Option.getOrUndefined( decodeClientIdPayload(json.value).pipe( diff --git a/apps/server/src/auth/http.test.ts b/apps/server/src/auth/http.test.ts index 86bd322f3c4dc..45bf8b3baa2e4 100644 --- a/apps/server/src/auth/http.test.ts +++ b/apps/server/src/auth/http.test.ts @@ -94,7 +94,7 @@ it.effect("sets the selected browser session cookies through the HTTP route", () ] as const, ), ([environmentA, environmentB]) => - Effect.tryPromise(async () => { + Effect.promise(async () => { const devResponse = await environmentA.handler( postJson("/api/auth/browser-session", { credential: DEV_TOKEN }), requestContext, diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.ts b/apps/server/src/cloud/ManagedEndpointRuntime.ts index d52f27a2ee806..66ef48f547730 100644 --- a/apps/server/src/cloud/ManagedEndpointRuntime.ts +++ b/apps/server/src/cloud/ManagedEndpointRuntime.ts @@ -1,5 +1,5 @@ import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay"; -import { RotatingFileSink } from "@t3tools/shared/logging"; +import { RotatingFileSink, RotatingFileSinkError } from "@t3tools/shared/logging"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as RelayClient from "@t3tools/shared/relayClient"; import * as Clock from "effect/Clock"; @@ -100,6 +100,8 @@ interface ActiveConnector { } // An instantly failing relay client otherwise respawns ~100 times/sec and exhausts V8 via tracing. +const isRotatingFileSinkError = Schema.is(RotatingFileSinkError); + const RELAY_RESTART_STABLE_UPTIME_MS = 30_000; const RELAY_RESTART_BACKOFF_BASE_MS = 1_000; const RELAY_RESTART_BACKOFF_MAX_MS = 60_000; @@ -252,15 +254,23 @@ export const make = Effect.gen(function* () { // Synchronous appends avoid a flush timer for this low-volume log. const fallbackLoggers = yield* Effect.service(Logger.CurrentLoggers); let writeFailureReported = false; - const relayClientLog = yield* Effect.try( - () => + const relayClientLog = yield* Effect.try({ + try: () => new RotatingFileSink({ filePath: relayClientLogPath, maxBytes: 1024 * 1024, maxFiles: 2, throwOnError: true, }), - ).pipe( + catch: (cause) => + isRotatingFileSinkError(cause) + ? cause + : new RotatingFileSinkError({ + operation: "initialize", + filePath: relayClientLogPath, + cause, + }), + }).pipe( Effect.map((sink) => Logger.make((options) => { try { diff --git a/apps/server/src/compileCache.ts b/apps/server/src/compileCache.ts index b01db74cbe34d..ea58a1cd3f503 100644 --- a/apps/server/src/compileCache.ts +++ b/apps/server/src/compileCache.ts @@ -1,9 +1,22 @@ import * as NodeModule from "node:module"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; -// Windows force-kills on quit; persist the cache after startup. -export const flushCompileCache = Effect.try(() => { - if (!Reflect.get(globalThis, Symbol.for("t3code.preparedServerCache"))) { - NodeModule.flushCompileCache(); +class CompileCacheFlushError extends Schema.TaggedError()( + "CompileCacheFlushError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not flush the module compile cache."; } +} + +// Windows force-kills on quit; persist the cache after startup. +export const flushCompileCache = Effect.try({ + try: () => { + if (!Reflect.get(globalThis, Symbol.for("t3code.preparedServerCache"))) { + NodeModule.flushCompileCache(); + } + }, + catch: (cause) => new CompileCacheFlushError({ cause }), }).pipe(Effect.ignore); diff --git a/apps/server/src/device/localSshDeviceHost.ts b/apps/server/src/device/localSshDeviceHost.ts index a2fee8c88812c..434aa7541b5d8 100644 --- a/apps/server/src/device/localSshDeviceHost.ts +++ b/apps/server/src/device/localSshDeviceHost.ts @@ -5,6 +5,7 @@ import * as NodeOS from "node:os"; import * as Context from "effect/Context"; import { runSshCommand } from "@t3tools/ssh/command"; import * as Effect from "effect/Effect"; +import { HostnameLookupError } from "@t3tools/shared/HostProcess"; export const LocalDeviceHostAddresses = Context.Reference>( "LocalDeviceHostAddresses", @@ -45,7 +46,10 @@ export const isLocalSshDeviceHost = Effect.fn("isLocalSshDeviceHost")(function* if (!hostname) return false; const addresses = NodeNet.isIP(hostname) ? [hostname] - : yield* Effect.tryPromise(() => NodeDnsPromises.lookup(hostname, { all: true })).pipe( + : yield* Effect.tryPromise({ + try: () => NodeDnsPromises.lookup(hostname, { all: true }), + catch: (cause) => new HostnameLookupError({ hostname, cause }), + }).pipe( Effect.map((entries) => entries.map((entry) => entry.address)), Effect.timeout("2 seconds"), Effect.orElseSucceed(() => [] as string[]), diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.ts index 6a63a0ba58fff..d84873082c68c 100644 --- a/apps/server/src/mcp/AcpMcpStdioBridge.ts +++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts @@ -4,7 +4,8 @@ import * as NodeReadline from "node:readline"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; -import * as Result from "effect/Result"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; import * as Fiber from "effect/Fiber"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -21,6 +22,8 @@ const bridgeError = (cause: unknown): AcpMcpBridgeError => ? cause : new AcpMcpBridgeError(cause instanceof Error ? cause.message : String(cause), { cause }); +const decodeJsonLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); + interface JsonRpcEnvelope { readonly id?: unknown; readonly method?: unknown; @@ -132,9 +135,11 @@ export const mcpToolSession = ( const terminate = Effect.suspend(() => sessionId === null ? Effect.void - : Effect.tryPromise(() => - fetchImplementation(options.endpoint, { method: "DELETE", headers: headers() }), - ).pipe(Effect.flatMap(discardResponseBody), Effect.ignore), + : Effect.tryPromise({ + try: () => + fetchImplementation(options.endpoint, { method: "DELETE", headers: headers() }), + catch: bridgeError, + }).pipe(Effect.flatMap(discardResponseBody), Effect.ignore), ); // Registered before the handshake so a session the server opened is ended @@ -274,11 +279,11 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect. line: string, ): Effect.fn.Return { if (line.trim().length === 0) return; - const parsed = yield* Effect.try((): unknown => JSON.parse(line)).pipe(Effect.result); - if (Result.isFailure(parsed)) { + const parsed = decodeJsonLine(line); + if (Option.isNone(parsed)) { return yield* respondWithError(null, "Parse error", -32700); } - const envelope = asEnvelope(parsed.success); + const envelope = asEnvelope(parsed.value); if (envelope === null) return; const isResponse = envelope.id !== undefined && ("result" in envelope || "error" in envelope); const isSessionHandshake = diff --git a/apps/server/src/observability/EventLoopMonitor.ts b/apps/server/src/observability/EventLoopMonitor.ts index d66d3695ca8b9..02922cdd3ae67 100644 --- a/apps/server/src/observability/EventLoopMonitor.ts +++ b/apps/server/src/observability/EventLoopMonitor.ts @@ -3,7 +3,7 @@ import * as NodeOS from "node:os"; import * as NodePerfHooks from "node:perf_hooks"; import type { ServerEventLoopStall } from "@t3tools/contracts"; -import { RotatingFileSink } from "@t3tools/shared/logging"; +import { RotatingFileSink, RotatingFileSinkError } from "@t3tools/shared/logging"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -150,15 +150,21 @@ const layerWith = ( const latestNoticeableStall = yield* Ref.make< { readonly stall: ServerEventLoopStall; readonly detectedAtMs: number } | undefined >(undefined); - const stallSink = yield* Effect.try( - () => + const stallSink = yield* Effect.try({ + try: () => new RotatingFileSink({ filePath: stallLog.filePath, maxBytes: stallLog.maxBytes, maxFiles: 1, throwOnError: true, }), - ).pipe( + catch: (cause) => + new RotatingFileSinkError({ + operation: "initialize", + filePath: stallLog.filePath, + cause, + }), + }).pipe( Effect.catch(() => Effect.logWarning("event loop stall log unavailable", { filePath: stallLog.filePath, @@ -201,7 +207,17 @@ const layerWith = ( ); if (stallSink !== undefined) { yield* encodeStallLine({ time: detectedAt, ...attributes }).pipe( - Effect.flatMap((line) => Effect.try(() => stallSink.write(`${line}\n`))), + Effect.flatMap((line) => + Effect.try({ + try: () => stallSink.write(`${line}\n`), + catch: (cause) => + new RotatingFileSinkError({ + operation: "write", + filePath: stallLog.filePath, + cause, + }), + }), + ), Effect.catch(() => Effect.logWarning("event loop stall log write failed", { filePath: stallLog.filePath, diff --git a/apps/server/src/observability/HeapSnapshot.ts b/apps/server/src/observability/HeapSnapshot.ts index e452f4f5ce341..6619797d053c5 100644 --- a/apps/server/src/observability/HeapSnapshot.ts +++ b/apps/server/src/observability/HeapSnapshot.ts @@ -7,18 +7,29 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; import * as ServerConfig from "../config.ts"; +class HeapSnapshotWriteError extends Schema.TaggedError()( + "HeapSnapshotWriteError", + { path: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `Could not write a heap snapshot to ${this.path}.`; + } +} + const writeHeapSnapshot = Effect.fn("server.heapSnapshot", { root: true })( function* (logsDir: string) { const fs = yield* FileSystem.FileSystem; const timestamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-"); const path = NodePath.join(logsDir, `server-${process.pid}-${timestamp}.heapsnapshot`); yield* Effect.annotateCurrentSpan({ path }); - yield* Effect.try(() => NodeV8.writeHeapSnapshot(path)).pipe( - Effect.tapError(() => fs.remove(path, { force: true }).pipe(Effect.ignore)), - ); + yield* Effect.try({ + try: () => NodeV8.writeHeapSnapshot(path), + catch: (cause) => new HeapSnapshotWriteError({ path, cause }), + }).pipe(Effect.tapError(() => fs.remove(path, { force: true }).pipe(Effect.ignore))); yield* Effect.logInfo("Wrote heap snapshot.", { path }); }, Effect.catch((cause) => Effect.logWarning("Failed to write heap snapshot.", { cause })), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index a3dea196ed34e..3c6295494ec83 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -1285,9 +1285,10 @@ export const layerQueryRunner: Layer.Layer< Effect.gen(function* () { if (mcpServers !== undefined) { // Errors and mcp_status can echo headers; log only server names. - const failed = yield* Effect.tryPromise(() => - queryRuntime.setMcpServers(mcpServers), - ).pipe( + const failed = yield* Effect.tryPromise({ + try: () => queryRuntime.setMcpServers(mcpServers), + catch: (cause) => queryRunnerError(cause, "setMcpServers"), + }).pipe( Effect.map((result) => Object.keys(result.errors)), Effect.orElseSucceed(() => Object.keys(mcpServers)), Effect.timeoutOrElse({ @@ -1583,7 +1584,10 @@ export const layerQueryRunner: Layer.Layer< ForkSessionResult & { readonly headMessageId?: string }, unknown > = usesHostConfig - ? Effect.tryPromise(() => forkClaudeSession(input.sessionId, input.options)) + ? Effect.tryPromise({ + try: () => forkClaudeSession(input.sessionId, input.options), + catch: (cause) => queryRunnerError(cause, "forkSession"), + }) : forkClaudeSessionInWorker(input).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(Path.Path, path), @@ -4886,13 +4890,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const home = customHome ? yield* readBypassSettings(path.join(homePath, "settings.json")) : {}; - const resolved = yield* Effect.tryPromise(() => - resolveClaudeSettings({ - ...(cwd === null ? {} : { cwd }), - settingSources: customHome ? ["project", "local"] : ["user", "project", "local"], - serverManagedSettings: claudeSdkBypassSettings(remote), - }), - ); + const resolved = yield* Effect.tryPromise({ + try: () => + resolveClaudeSettings({ + ...(cwd === null ? {} : { cwd }), + settingSources: customHome ? ["project", "local"] : ["user", "project", "local"], + serverManagedSettings: claudeSdkBypassSettings(remote), + }), + catch: (cause) => queryRunnerError(cause, "resolveSettings"), + }); const launchArgSettings = yield* readClaudeLaunchArgSettings({ settings: adapterOptions.settings, cwd, @@ -4916,12 +4922,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( adapterOptions.environment.CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL, ); if (Option.isSome(fromEnvironment)) return fromEnvironment.value; - const resolved = yield* Effect.tryPromise(() => - resolveClaudeSettings({ - ...(cwd === null ? {} : { cwd }), - settingSources: customHome ? ["project", "local"] : ["user", "project", "local"], - }), - ).pipe(Effect.orElseSucceed(() => undefined)); + const resolved = yield* Effect.tryPromise({ + try: () => + resolveClaudeSettings({ + ...(cwd === null ? {} : { cwd }), + settingSources: customHome ? ["project", "local"] : ["user", "project", "local"], + }), + catch: (cause) => queryRunnerError(cause, "resolveSettings"), + }).pipe(Effect.orElseSucceed(() => undefined)); const home = customHome ? yield* fileSystem.readFileString(path.join(homePath, "settings.json")).pipe( Effect.flatMap(decodeClaudeSubagentCacheSettings), diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts index c2c67eb04d9dc..5415998619c03 100644 --- a/apps/server/src/orchestration-v2/http.ts +++ b/apps/server/src/orchestration-v2/http.ts @@ -246,11 +246,9 @@ export const layer = HttpApiBuilder.group( Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); yield* requireEnvironmentScope(AuthOrchestrationReadScope); - const decoded = yield* Effect.try(() => - decodeThreadHistoryCursor(args.query.cursor), - ).pipe(Effect.result); + const decoded = Result.try(() => decodeThreadHistoryCursor(args.query.cursor)); if (Result.isFailure(decoded)) { - const cause = decoded.failure.cause; + const cause = decoded.failure; if (cause instanceof InvalidThreadHistoryCursorError) return yield* failEnvironmentInvalidRequest("invalid_history_cursor"); return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause); diff --git a/apps/server/src/persistence/initializeV2Database.test.ts b/apps/server/src/persistence/initializeV2Database.test.ts index ec8ded1cab5ac..f8c68f49ceb9a 100644 --- a/apps/server/src/persistence/initializeV2Database.test.ts +++ b/apps/server/src/persistence/initializeV2Database.test.ts @@ -11,6 +11,7 @@ import { ThreadId } from "@t3tools/contracts"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Predicate from "effect/Predicate"; import * as SqlClient from "effect/sql/SqlClient"; import * as ServerConfig from "../config.ts"; @@ -124,7 +125,8 @@ it.effect("includes committed WAL data and does not publish a failed snapshot", const destinationPath = NodePath.join(directory, "statev2.sqlite"); return Effect.gen(function* () { NodeFS.writeFileSync(sourcePath, "invalid SQLite"); - assert.isTrue((yield* Effect.result(initializeV2Database(destinationPath)))._tag === "Failure"); + const failure = yield* Effect.flip(initializeV2Database(destinationPath)); + assert.isFalse(Predicate.isTagged(failure.cause, "V2DatabaseImportError")); assert.isFalse(NodeFS.existsSync(destinationPath)); NodeFS.unlinkSync(sourcePath); const source = new NodeSqlite.DatabaseSync(sourcePath); diff --git a/apps/server/src/persistence/initializeV2Database.ts b/apps/server/src/persistence/initializeV2Database.ts index 4f6d8d969c3ec..492567c7980da 100644 --- a/apps/server/src/persistence/initializeV2Database.ts +++ b/apps/server/src/persistence/initializeV2Database.ts @@ -14,6 +14,8 @@ export class V2DatabaseImportError extends Schema.TaggedError { if (!Number.isInteger(pid) || pid <= 0) return false; try { @@ -58,13 +60,16 @@ export const initializeV2Database = Effect.fn("initializeV2Database")(function* prefix: `.v2-import-${process.pid}-`, }); const snapshotPath = path.join(temporaryDirectory, "snapshot.sqlite"); - yield* Effect.tryPromise(async () => { - const database = new NodeSqlite.DatabaseSync(sourcePath, { readOnly: true }); - try { - await NodeSqlite.backup(database, snapshotPath); - } finally { - database.close(); - } + yield* Effect.tryPromise({ + try: async () => { + const database = new NodeSqlite.DatabaseSync(sourcePath, { readOnly: true }); + try { + await NodeSqlite.backup(database, snapshotPath); + } finally { + database.close(); + } + }, + catch: (cause) => new V2DatabaseImportError({ sourcePath, destinationPath, cause }), }); // Publish only a complete snapshot, without replacing an existing V2 database. yield* fs.link(snapshotPath, destinationPath).pipe( @@ -75,6 +80,10 @@ export const initializeV2Database = Effect.fn("initializeV2Database")(function* ); }).pipe( Effect.scoped, - Effect.mapError((cause) => new V2DatabaseImportError({ sourcePath, destinationPath, cause })), + Effect.mapError((cause) => + isV2DatabaseImportError(cause) + ? cause + : new V2DatabaseImportError({ sourcePath, destinationPath, cause }), + ), ); }); diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 2afeae055437d..913f6dc639459 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -147,6 +147,15 @@ const isHostSetupError = Schema.is( ]), ); +class ServerBrowserDownloadsCleanupError extends Schema.TaggedError()( + "ServerBrowserDownloadsCleanupError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "The server preview could not clear earlier downloads."; + } +} + export class ServerBrowserLaunchError extends Schema.TaggedError()( "ServerBrowserLaunchError", { cause: Schema.Defect() }, @@ -1034,7 +1043,10 @@ const make = Effect.gen(function* () { const downloadsRoot = NodePath.join(config.stateDir, "server-browser", "downloads"); // Saved downloads are indexed in memory, so an earlier run's files can never be opened again. - yield* Effect.tryPromise(() => NodeFSP.rm(downloadsRoot, { recursive: true, force: true })).pipe( + yield* Effect.tryPromise({ + try: () => NodeFSP.rm(downloadsRoot, { recursive: true, force: true }), + catch: (cause) => new ServerBrowserDownloadsCleanupError({ cause }), + }).pipe( Effect.catch((cause) => Effect.logWarning("server preview could not clear earlier downloads", { cause }), ), diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 3ed97f8a7d8f4..511728cf2121c 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -46,6 +46,15 @@ import { } from "./AgentSessionJson.ts"; const TRANSCRIPT_PREFIX_BYTES = 32 * 1024; + +class TranscriptParseError extends Schema.TaggedError()( + "TranscriptParseError", + { filePath: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `Could not parse the transcript at ${this.filePath}.`; + } +} const METADATA_READ_BYTES = 8 * 1024; const MAX_TRANSCRIPT_SCAN_BYTES = 1024 * 1024; const MAX_CODEX_SESSION_INDEX_BYTES = 1024 * 1024; @@ -1071,23 +1080,33 @@ export const make = Effect.gen(function* () { } bytesRead += next.value.byteLength; - const withinBudget = yield* Effect.try(() => { - let start = 0; - while (start < next.value.byteLength) { - const newline = next.value.indexOf(10, start); - const end = newline === -1 ? next.value.byteLength : newline; - recordStarted = true; - reader.write(decoder.decode(next.value.subarray(start, end), { stream: true })); - if (newline === -1) break; - if (!finishRecord()) return false; - start = newline + 1; - } - return true; + const withinBudget = yield* Effect.try({ + try: () => { + let start = 0; + while (start < next.value.byteLength) { + const newline = next.value.indexOf(10, start); + const end = newline === -1 ? next.value.byteLength : newline; + recordStarted = true; + reader.write(decoder.decode(next.value.subarray(start, end), { stream: true })); + if (newline === -1) break; + if (!finishRecord()) return false; + start = newline + 1; + } + return true; + }, + catch: (cause) => new TranscriptParseError({ filePath, cause }), }); if (!withinBudget) return null; } - if (recordStarted && !(yield* Effect.try(finishRecord))) return null; + if ( + recordStarted && + !(yield* Effect.try({ + try: finishRecord, + catch: (cause) => new TranscriptParseError({ filePath, cause }), + })) + ) + return null; return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat)) ? { records, cwd, claudeFields } : null; diff --git a/apps/server/src/provider/AntigravityInstallation.ts b/apps/server/src/provider/AntigravityInstallation.ts index b70e5d6860000..707cb0b44699e 100644 --- a/apps/server/src/provider/AntigravityInstallation.ts +++ b/apps/server/src/provider/AntigravityInstallation.ts @@ -497,9 +497,10 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma return; } - const available = yield* Effect.tryPromise(() => - NodeFSP.statfs(versionsDirectory, { bigint: true }), - ).pipe(Effect.option); + const available = yield* Effect.tryPromise({ + try: () => NodeFSP.statfs(versionsDirectory, { bigint: true }), + catch: (cause) => installationError("download", "Could not check free disk space.", cause), + }).pipe(Effect.option); const required = asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN; if ( diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index 97512d3d621f0..ded4badd6fcda 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -13,6 +13,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { createModelCapabilities } from "@t3tools/shared/model"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; @@ -335,6 +336,15 @@ function claudeGatewayDiscoveryGraceMs(environment: Readonly 0 ? configured : 3_000; } +class ClaudeCapabilitiesProbeSdkError extends Schema.TaggedError()( + "ClaudeCapabilitiesProbeSdkError", + { operation: Schema.Literals(["initialize", "usage"]), cause: Schema.Defect() }, +) { + override get message(): string { + return `Claude capability probe ${this.operation} failed.`; + } +} + /** A never-yielding prompt allows local initialization IPC without sending an Anthropic request. */ const probeClaudeCapabilities = ( claudeSettings: ClaudeSettings, @@ -360,22 +370,25 @@ const probeClaudeCapabilities = ( ...(yield* readClaudeSettingsEnv(claudeSettings, cwd, claudeEnvironment)), }) : 0; - return yield* Effect.tryPromise(async () => { - const q = claudeQuery({ - // oxlint-disable-next-line require-yield -- never yields, so no prompt reaches the API - prompt: (async function* (): AsyncGenerator { - await waitForAbortSignal(abort.signal); - })(), - options: buildClaudeCapabilitiesProbeQueryOptions({ - executablePath, - abortController: abort, - environment: claudeEnvironment, - cwd, - managedMcpConfig, - }), - }); - const init = await q.initializationResult(); - return { q, init, graceMs }; + return yield* Effect.tryPromise({ + try: async () => { + const q = claudeQuery({ + // oxlint-disable-next-line require-yield -- never yields, so no prompt reaches the API + prompt: (async function* (): AsyncGenerator { + await waitForAbortSignal(abort.signal); + })(), + options: buildClaudeCapabilitiesProbeQueryOptions({ + executablePath, + abortController: abort, + environment: claudeEnvironment, + cwd, + managedMcpConfig, + }), + }); + const init = await q.initializationResult(); + return { q, init, graceMs }; + }, + catch: (cause) => new ClaudeCapabilitiesProbeSdkError({ operation: "initialize", cause }), }); }).pipe( Effect.timeout(CAPABILITIES_PROBE_TIMEOUT_MS), @@ -386,9 +399,13 @@ const probeClaudeCapabilities = ( // `behaviors`: with a few GB of transcripts it outlasts the deadline. const usageCheckedAt = DateTime.formatIso(yield* DateTime.now); const usageResult = includeUsage - ? yield* Effect.tryPromise(() => - q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true }), - ).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result) + ? yield* Effect.tryPromise({ + try: () => + q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ + skipBehaviors: true, + }), + catch: (cause) => new ClaudeCapabilitiesProbeSdkError({ operation: "usage", cause }), + }).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result) : undefined; const usage = usageResult && Result.isSuccess(usageResult) diff --git a/apps/server/src/provider/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.ts index 1c23f395935da..44a2f799e3df1 100644 --- a/apps/server/src/provider/CodexChatGptAuth.test.ts +++ b/apps/server/src/provider/CodexChatGptAuth.test.ts @@ -1640,8 +1640,13 @@ it.effect( const callback = new URL( new URL(state.authorizationUrl!).searchParams.get("redirect_uri")!, ); - const request = yield* Effect.tryPromise(() => fetch(callback)).pipe(Effect.result); - assert.strictEqual(request._tag, "Failure"); + const rejected = yield* Effect.promise(() => + fetch(callback).then( + () => false, + () => true, + ), + ); + assert.isTrue(rejected); assert.isTrue(Option.isNone(yield* h.auth.read)); }), ), diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index d3035d5ae9b5f..d6cb74aa19e42 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -414,7 +414,10 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function* if (visited.has(canonical)) return null; visited.add(canonical); const fingerprintOf = (file: string) => - Effect.tryPromise(() => NodeFSP.stat(file)).pipe( + Effect.tryPromise({ + try: () => NodeFSP.stat(file), + catch: (cause) => new AntigravityDatabaseDecodeError({ path: file, cause }), + }).pipe( Effect.map((stat) => ({ stat, part: `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` })), ); const { stat, part } = yield* fingerprintOf(path); diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts index 00de1e836296e..41e25f2e417e1 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts @@ -8,6 +8,7 @@ import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; import type * as EffectAcpSchema from "effect-acp/compat"; import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; @@ -41,19 +42,33 @@ interface LastStep { readonly payload: Uint8Array | null; } +class AntigravitySessionLogError extends Schema.TaggedError()( + "AntigravitySessionLogError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not read the Antigravity session log."; + } +} + +const sessionLogError = (cause: unknown) => new AntigravitySessionLogError({ cause }); + const readSteps = (file: string, read: (database: NodeSqlite.DatabaseSync) => A) => - Effect.try(() => { - const database = new NodeSqlite.DatabaseSync(file, { readOnly: true }); - try { - database.exec("PRAGMA busy_timeout = 100"); - const hasSteps = - database - .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'") - .get() !== undefined; - return hasSteps ? read(database) : undefined; - } finally { - database.close(); - } + Effect.try({ + try: () => { + const database = new NodeSqlite.DatabaseSync(file, { readOnly: true }); + try { + database.exec("PRAGMA busy_timeout = 100"); + const hasSteps = + database + .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'") + .get() !== undefined; + return hasSteps ? read(database) : undefined; + } finally { + database.close(); + } + }, + catch: sessionLogError, }); const lastStepIndex = (database: NodeSqlite.DatabaseSync) => { @@ -142,22 +157,25 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w DateTime.now.pipe(Effect.map((now) => turnFailure(result.stopReason, undefined, now))); if (!NATIVE_SESSION_ID.test(sessionId)) return typedOnly; const segments = [...conversationSegments, `${sessionId}.db`]; - const before = yield* Effect.tryPromise(async () => { - const root = await antigravityProfileRoot(profileDirectory); - if (root === undefined) return undefined; - if ((await antigravityManagedPath(root, conversationSegments, "directory")) === undefined) { - return undefined; - } - const database = await antigravityManagedPath(root, segments, "file"); - // A path that exists but fails the proof is a link or other foreign entry. - if (database === undefined) { - const present = await NodeFSP.lstat(NodePath.join(root, ...segments)).then( - () => true, - () => false, - ); - return present ? undefined : { root, identity: undefined, startIndex: -1 }; - } - return { root, identity: database.info, startIndex: undefined }; + const before = yield* Effect.tryPromise({ + try: async () => { + const root = await antigravityProfileRoot(profileDirectory); + if (root === undefined) return undefined; + if ((await antigravityManagedPath(root, conversationSegments, "directory")) === undefined) { + return undefined; + } + const database = await antigravityManagedPath(root, segments, "file"); + // A path that exists but fails the proof is a link or other foreign entry. + if (database === undefined) { + const present = await NodeFSP.lstat(NodePath.join(root, ...segments)).then( + () => true, + () => false, + ); + return present ? undefined : { root, identity: undefined, startIndex: -1 }; + } + return { root, identity: database.info, startIndex: undefined }; + }, + catch: sessionLogError, }).pipe(Effect.orElseSucceed(() => undefined)); if (before === undefined) { yield* Effect.logWarning("The Antigravity session log is not this session's own file."); @@ -177,9 +195,10 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w result: EffectAcpSchema.PromptResponse, ) { // The same file as before the prompt, or one this prompt created, still unlinked. - const after = yield* Effect.tryPromise(() => - antigravityManagedPath(before.root, segments, "file"), - ).pipe(Effect.orElseSucceed(() => undefined)); + const after = yield* Effect.tryPromise({ + try: () => antigravityManagedPath(before.root, segments, "file"), + catch: sessionLogError, + }).pipe(Effect.orElseSucceed(() => undefined)); const sameFile = after !== undefined && (before.identity === undefined || diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts index 2b2ae029e5b0e..32de13ef129e8 100644 --- a/apps/server/src/provider/antigravityAuthSupport.ts +++ b/apps/server/src/provider/antigravityAuthSupport.ts @@ -230,6 +230,15 @@ function antigravityEnvironment( }; } +class AntigravitySkillLinkError extends Schema.TaggedError()( + "AntigravitySkillLinkError", + { link: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `Could not link Antigravity user skills at ${this.link}.`; + } +} + /** Private GEMINI_HOME isolates credentials/hooks/MCP; link global skills from the real ~/.gemini. */ const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(function* (input: { readonly profileDirectory: string; @@ -260,7 +269,10 @@ const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(functio // An empty folder is the harness's placeholder from a launch without the link. // rmdir refuses a non-empty folder, so content added meanwhile is never deleted. Effect.catch((error) => - Effect.tryPromise(() => NodeFSP.rmdir(link)).pipe( + Effect.tryPromise({ + try: () => NodeFSP.rmdir(link), + catch: (cause) => new AntigravitySkillLinkError({ link, cause }), + }).pipe( Effect.as(undefined), Effect.mapError(() => error), ), @@ -271,9 +283,10 @@ const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(functio yield* fs.remove(link); } yield* fs.makeDirectory(path.dirname(link), { recursive: true }); - yield* Effect.tryPromise(() => - NodeFSP.symlink(target, link, input.platform === "win32" ? "junction" : "dir"), - ); + yield* Effect.tryPromise({ + try: () => NodeFSP.symlink(target, link, input.platform === "win32" ? "junction" : "dir"), + catch: (cause) => new AntigravitySkillLinkError({ link, cause }), + }); }).pipe( Effect.catch((error) => Effect.logWarning("Antigravity user skills are not linked into the profile.", { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index 9714d9175afdf..6ce9fce4a50c1 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -67,6 +67,15 @@ const decodePnpmModulesManifest = Schema.decodeUnknownEffect( }), ); +class PnpmModulesManifestParseError extends Schema.TaggedError()( + "PnpmModulesManifestParseError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not parse the pnpm modules manifest."; + } +} + const DAY_MS = 86_400_000; // Give settle scripts time to open terminals that protect the worktree. const SETTLE_SCRIPT_GRACE_MS = 60_000; @@ -341,7 +350,12 @@ const make = Effect.gen(function* () { function* (root: string) { const nodeModules = path.join(root, "node_modules"); const text = yield* fs.readFileString(path.join(nodeModules, ".modules.yaml")); - const manifest = yield* decodePnpmModulesManifest(yield* Effect.try(() => parseYaml(text))); + const manifest = yield* decodePnpmModulesManifest( + yield* Effect.try({ + try: () => parseYaml(text), + catch: (cause) => new PnpmModulesManifestParseError({ cause }), + }), + ); // An agent can write this manifest, and statting a network path makes // Windows sign in to its host with the user's NTLM credentials. if (isNetworkPath(manifest.storeDir) || isNetworkPath(manifest.virtualStoreDir ?? "")) { diff --git a/apps/server/src/terminal/NodePtyAdapter.ts b/apps/server/src/terminal/NodePtyAdapter.ts index 4b83ddf6697e6..cc7ae638f7df2 100644 --- a/apps/server/src/terminal/NodePtyAdapter.ts +++ b/apps/server/src/terminal/NodePtyAdapter.ts @@ -24,6 +24,15 @@ export class NodePtyModuleLoadError extends Schema.TaggedError()("NodePtyCancelError", { + terminalPid: Schema.Number, + cause: Schema.Defect(), +}) { + override get message(): string { + return `Failed to cancel Windows terminal startup for ${this.terminalPid}.`; + } +} + type NodePtyModuleLoader = () => Promise; // node-pty's native addon stays external; single-executables need require to resolve disk modules and spawn helpers. @@ -134,18 +143,21 @@ const waitForWindowsPid = ( // The private agent cancels pending connections before a child exists; public kill waits for first output. const killStartingWindowsPty = (process: import("node-pty").IPty) => - Effect.try(() => { - if ( - "_agent" in process && - typeof process._agent === "object" && - process._agent !== null && - "kill" in process._agent && - typeof process._agent.kill === "function" - ) { - process._agent.kill(); - } else { - process.kill(); - } + Effect.try({ + try: () => { + if ( + "_agent" in process && + typeof process._agent === "object" && + process._agent !== null && + "kill" in process._agent && + typeof process._agent.kill === "function" + ) { + process._agent.kill(); + } else { + process.kill(); + } + }, + catch: (cause) => new NodePtyCancelError({ terminalPid: process.pid, cause }), }).pipe( Effect.catch((error) => Effect.logWarning("failed to cancel Windows terminal startup", { diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 9cf97cd4c7c4d..c33b6da64a728 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -56,14 +56,20 @@ import { MuseUsageHome } from "@t3tools/provider-muse/server"; import { makeScanCacheWriter, SCAN_CACHE_FILE_NAME } from "./usageScanCache.ts"; vi.mock("node:fs/promises", { spy: true }); -vi.mock("../../../../packages/provider-muse/src/server/sdk.ts", async (importOriginal) => ({ - ...(await importOriginal()), - createMuseSdkHostEffect: vi.fn(() => - Effect.try(() => { - throw new Error("Muse is not installed in this test"); - }), - ), -})); +vi.mock("../../../../packages/provider-muse/src/server/sdk.ts", async (importOriginal) => { + const original = await importOriginal(); + return { + ...original, + createMuseSdkHostEffect: vi.fn(() => + Effect.fail( + new original.MuseSdkError({ + operation: "start", + cause: new Error("Muse is not installed in this test"), + }), + ), + ), + }; +}); const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 351daa0e697ff..94404b488b136 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1,5 +1,4 @@ import * as Cache from "effect/Cache"; -import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Data from "effect/Data"; import * as Digest from "effect/crypto/Digest"; @@ -42,7 +41,7 @@ import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings"; import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts"; import * as GitVcsDriver from "./GitVcsDriver.ts"; -import { removeEmptyDirectory } from "./removeEmptyDirectory.ts"; +import { removeEmptyDirectory, type RemoveEmptyDirectoryError } from "./removeEmptyDirectory.ts"; import { explicitBareRepositoryEnv, gitConfigEnv } from "./VcsProcess.ts"; import { removeLinkedWorktree } from "./worktreeRemoval.ts"; import { resolveWorktreesDirectory } from "../worktreesDirectory.ts"; @@ -4732,7 +4731,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // Recursive filesystem traversal can visit many entries; removeWorktree owns the operation span. const removeLeftoverLinks = Effect.fnUntraced(function* ( target: string, - ): Effect.fn.Return { + ): Effect.fn.Return { if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) { yield* fileSystem.remove(target); return true; diff --git a/apps/server/src/vcs/removeEmptyDirectory.ts b/apps/server/src/vcs/removeEmptyDirectory.ts index 2ce80dfe588a2..f7c8348af8db6 100644 --- a/apps/server/src/vcs/removeEmptyDirectory.ts +++ b/apps/server/src/vcs/removeEmptyDirectory.ts @@ -2,6 +2,16 @@ import * as NodeFSP from "node:fs/promises"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +export class RemoveEmptyDirectoryError extends Schema.TaggedError()( + "RemoveEmptyDirectoryError", + { path: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `Could not remove the directory ${this.path}.`; + } +} /** * Removes `path` only while it is an empty directory. Succeeds with false when @@ -9,7 +19,10 @@ import * as Effect from "effect/Effect"; * Other failures, such as a permission error, stay errors. */ export const removeEmptyDirectory = (path: string) => - Effect.tryPromise(() => NodeFSP.rmdir(path)).pipe( + Effect.tryPromise({ + try: () => NodeFSP.rmdir(path), + catch: (cause) => new RemoveEmptyDirectoryError({ path, cause }), + }).pipe( Effect.as(true), Effect.catchIf( (error) => (error.cause as NodeJS.ErrnoException | undefined)?.code === "ENOTEMPTY", diff --git a/apps/web/src/components/device/deviceHubAtoms.ts b/apps/web/src/components/device/deviceHubAtoms.ts index 5a83f26824d52..e9e6c1c66b980 100644 --- a/apps/web/src/components/device/deviceHubAtoms.ts +++ b/apps/web/src/components/device/deviceHubAtoms.ts @@ -1,6 +1,7 @@ import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess"; import * as Effect from "effect/Effect"; import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { AsyncResult, Atom } from "effect/reactivity"; @@ -40,11 +41,23 @@ export const deviceEventLogAtom = Atom.family((target: DeviceHubTarget) => }).pipe(Atom.withLabel(`device-event-log:${target.deviceId}`)), ); +class DeviceAxTreeFetchError extends Schema.TaggedError()( + "DeviceAxTreeFetchError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not read the device accessibility tree."; + } +} + // A failed poll keeps the last frames on screen; the next poll replaces them. export const deviceAxElementsAtom = Atom.family((target: DeviceHubTarget) => Atom.make( Stream.fromEffectSchedule( - Effect.tryPromise((signal) => fetchDeviceAxTree(target, signal)).pipe( + Effect.tryPromise({ + try: (signal) => fetchDeviceAxTree(target, signal), + catch: (cause) => new DeviceAxTreeFetchError({ cause }), + }).pipe( Effect.map((tree): ReadonlyArray | null => tree.elements), Effect.orElseSucceed(() => null), ), diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts index e60ed172e9260..dcd50342f1c91 100644 --- a/apps/web/src/connection/platform.ts +++ b/apps/web/src/connection/platform.ts @@ -313,13 +313,15 @@ const ANALYTICS_DEVICE_ID_KEY = "t3code:analytics-device-id"; // Lives as long as this browser profile's site data. Storage can be blocked, which only drops the id. const analyticsDevice = { - id: Effect.try(() => { - const existing = window.localStorage.getItem(ANALYTICS_DEVICE_ID_KEY); - if (existing) return existing; - const created = randomUUID(); - window.localStorage.setItem(ANALYTICS_DEVICE_ID_KEY, created); - return created; - }).pipe(Effect.option), + id: Effect.sync( + Option.liftThrowable(() => { + const existing = window.localStorage.getItem(ANALYTICS_DEVICE_ID_KEY); + if (existing) return existing; + const created = randomUUID(); + window.localStorage.setItem(ANALYTICS_DEVICE_ID_KEY, created); + return created; + }), + ), }; const layerCapabilities = Layer.effectContext( diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index dbddce4c1c2fe..5b0cf7d1e1ee0 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -112,6 +112,15 @@ const isPricedModel = (model: ShellModel): model is PricedModel => model in PRIC const T3_PREFIX = "mcp__t3-code__"; const RUNTIME_MARKER = ""; const TOOL_LOADED = "Tool loaded."; + +class EvalToolCallError extends Schema.TaggedError()("EvalToolCallError", { + tool: Schema.String, + cause: Schema.Defect(), +}) { + override get message(): string { + return `The ${this.tool} tool call failed.`; + } +} const DEFERRED_LIST = /(The following deferred tools are now available via ToolSearch\.[^\n]*\n)((?:[^\n]+\n)*)/; const MODEL_LINE = /You are powered by the model named .+?\. The exact model ID is [\w.-]+\./; @@ -2063,24 +2072,27 @@ const runSample = Effect.fn("evaluateMcpToolUse.runSample")(function* ( runPromise, ); }; - return yield* Effect.tryPromise(async () => { - const output = - use.name === "exec" - ? await executeCodex( - valueText(use.input), - codexCatalog(base), - answer, - sample.codeStore, - ) - : await answer(use.name, use.input, false); - const item = { - type: use.name === "exec" ? "custom_tool_call_output" : "function_call_output", - call_id: use.id, - output: valueText(output), - }; - input.push(item); - transcript.push(item); - return toolResult(use.id, output); + return yield* Effect.tryPromise({ + try: async () => { + const output = + use.name === "exec" + ? await executeCodex( + valueText(use.input), + codexCatalog(base), + answer, + sample.codeStore, + ) + : await answer(use.name, use.input, false); + const item = { + type: use.name === "exec" ? "custom_tool_call_output" : "function_call_output", + call_id: use.id, + output: valueText(output), + }; + input.push(item); + transcript.push(item); + return toolResult(use.id, output); + }, + catch: (cause) => new EvalToolCallError({ tool: use.name, cause }), }); }), ); @@ -2429,11 +2441,16 @@ const main = Effect.gen(function* () { // Only a case that passed every baseline sample can stop a run; flaky ones are just reported. const passedBefore = (id: string) => baseline.get(id) === 1; // Before the paid runs, so a missing git cannot lose their results. - const commit = yield* Effect.try(() => - NodeChildProcess.execFileSync("git", ["describe", "--always", "--dirty"], { - encoding: "utf8", - }).trim(), - ).pipe(Effect.orElseSucceed(() => "unknown")); + const commit = yield* Effect.sync(() => + Option.getOrElse( + Option.liftThrowable(() => + NodeChildProcess.execFileSync("git", ["describe", "--always", "--dirty"], { + encoding: "utf8", + }).trim(), + )(), + () => "unknown", + ), + ); const inFlight = yield* Semaphore.make(flags.concurrency); const runOne = (testCase: McpToolUseCase) => { const { id, kind, pattern } = testCase; diff --git a/infra/relay/scripts/android-push-watch.ts b/infra/relay/scripts/android-push-watch.ts index 5f052f58e4c17..e62ac73d746f4 100644 --- a/infra/relay/scripts/android-push-watch.ts +++ b/infra/relay/scripts/android-push-watch.ts @@ -42,7 +42,19 @@ const Connection = Schema.Struct({ wsUrl: Schema.NonEmptyString, bearerToken: Schema.NonEmptyString, }); -const readFile = (path: string) => Effect.tryPromise(() => NodeFSP.readFile(path, "utf8")); +class WatchReadFileError extends Schema.TaggedError()("WatchReadFileError", { + path: Schema.String, + cause: Schema.Defect(), +}) { + override get message() { + return `Could not read ${this.path}`; + } +} +const readFile = (path: string) => + Effect.tryPromise({ + try: () => NodeFSP.readFile(path, "utf8"), + catch: (cause) => new WatchReadFileError({ path, cause }), + }); const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); class WatchUnregisteredDeviceError extends Schema.TaggedError()( "WatchUnregisteredDeviceError", diff --git a/infra/task-cache/src/developerAuth.ts b/infra/task-cache/src/developerAuth.ts index f358a8961e2f8..c7e4b35c6a241 100644 --- a/infra/task-cache/src/developerAuth.ts +++ b/infra/task-cache/src/developerAuth.ts @@ -1,4 +1,5 @@ import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; const Keys = Schema.fromJsonString(Schema.Record(Schema.String, Schema.String)); @@ -13,7 +14,7 @@ export const developerIdentity = Effect.fn("TaskCache.developerIdentity")(functi if (!authorization?.toLowerCase().startsWith("basic ")) return undefined; if (!encodedKeys || authorization.length > 1024) return null; - const decoded = yield* Effect.try(() => atob(authorization.slice(6))).pipe(Effect.option); + const decoded = Option.liftThrowable(atob)(authorization.slice(6)); if (decoded._tag === "None") return null; const keys = yield* decodeKeys(encodedKeys).pipe(Effect.option); if (keys._tag === "None") return null; diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index 0ef446ef3453a..ecbe61e342746 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -484,18 +484,18 @@ export function terminateLinuxCgroupLease( let lastRemovalFailure: { readonly cause: unknown } | null = null; for (let attempt = 0; attempt < 200; attempt += 1) { if (!lease.exists()) return; - const killed = yield* Effect.try(() => lease.kill()).pipe(Effect.result); + const killed = Result.try(() => lease.kill()); if (Result.isFailure(killed)) { - const cause = killed.failure.cause; + const cause = killed.failure; const code = (cause as NodeJS.ErrnoException | undefined)?.code; if (code !== "ENOENT") return yield* failure("kill", cause); if (!lease.exists()) return; yield* Effect.sleep("10 millis"); continue; } - const populated = yield* Effect.try(() => lease.populated()).pipe(Effect.result); + const populated = Result.try(() => lease.populated()); if (Result.isFailure(populated)) { - const cause = populated.failure.cause; + const cause = populated.failure; const code = (cause as NodeJS.ErrnoException | undefined)?.code; if (code === "ENOENT" && !lease.exists()) return; if (code === "ENOENT") { @@ -509,9 +509,9 @@ export function terminateLinuxCgroupLease( yield* Effect.sleep("10 millis"); continue; } - const removed = yield* Effect.try(() => lease.remove()).pipe(Effect.result); + const removed = Result.try(() => lease.remove()); if (Result.isFailure(removed)) { - const cause = removed.failure.cause; + const cause = removed.failure; const code = (cause as NodeJS.ErrnoException | undefined)?.code; if (code === "ENOENT" && !lease.exists()) return; if (code !== "EBUSY" && code !== "ENOTEMPTY" && code !== "ENOENT") { diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts index f48d7baf1b24a..92fb764b432d5 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts @@ -357,20 +357,23 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu if (yield* Ref.getAndSet(sandboxSupportPrimeStarted, true)) { return yield* Deferred.await(sandboxSupportPrimed); } - yield* Effect.tryPromise(async () => { - const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined; - const platform = await sdk - .load() - .createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd }); - const release = await platform.prewarmLocalWorkspace({ - ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }), - local: { - ...(cwd === undefined ? {} : { cwd }), - settingSources: [], - sandboxOptions: { enabled: true }, - }, - }); - await release(); + yield* Effect.tryPromise({ + try: async () => { + const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined; + const platform = await sdk + .load() + .createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd }); + const release = await platform.prewarmLocalWorkspace({ + ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }), + local: { + ...(cwd === undefined ? {} : { cwd }), + settingSources: [], + sandboxOptions: { enabled: true }, + }, + }); + await release(); + }, + catch: (cause) => runnerError(cause, "prewarmLocalWorkspace"), }).pipe(Effect.ignore, Effect.ensuring(Deferred.succeed(sandboxSupportPrimed, undefined))); }, ); diff --git a/packages/provider-cursor/src/server/credentialStore.test.ts b/packages/provider-cursor/src/server/credentialStore.test.ts index 1ced56c62b808..d9ee986acc517 100644 --- a/packages/provider-cursor/src/server/credentialStore.test.ts +++ b/packages/provider-cursor/src/server/credentialStore.test.ts @@ -56,7 +56,7 @@ it.effect.each([ yield* (yield* host.credentials("cursor", instanceId)).set(new TextEncoder().encode(stored)); } const migrated = yield* makeCursorCredentialStore(instanceId, legacyFile); - assert.strictEqual((yield* Effect.tryPromise(() => migrated.store.load()))?.apiKey, expected); + assert.strictEqual((yield* Effect.promise(() => migrated.store.load()))?.apiKey, expected); assert.isFalse(yield* fileSystem.exists(legacyFile)); }).pipe(Effect.scoped, Effect.provide(layerHost)), ); @@ -77,21 +77,21 @@ it.effect( apiKeyExpiresAtMs: 1000, email: "test@example.com", }; - yield* Effect.tryPromise(() => personal.store.save(credentials)); - yield* Effect.tryPromise(() => + yield* Effect.promise(() => personal.store.save(credentials)); + yield* Effect.promise(() => work.store.save({ ...credentials, apiKey: "test-only-work-key" }), ); const restored = yield* makeStore("personal"); - assert.deepEqual(yield* Effect.tryPromise(() => restored.store.load()), credentials); + assert.deepEqual(yield* Effect.promise(() => restored.store.load()), credentials); yield* (yield* host.credentials("cursor", "personal")).set( new TextEncoder().encode("damaged credential"), ); - assert.isUndefined(yield* Effect.tryPromise(() => restored.store.load())); - yield* Effect.tryPromise(() => restored.store.save(credentials)); - yield* Effect.tryPromise(() => restored.store.clear()); - assert.isUndefined(yield* Effect.tryPromise(() => personal.store.load())); + assert.isUndefined(yield* Effect.promise(() => restored.store.load())); + yield* Effect.promise(() => restored.store.save(credentials)); + yield* Effect.promise(() => restored.store.clear()); + assert.isUndefined(yield* Effect.promise(() => personal.store.load())); assert.strictEqual( - (yield* Effect.tryPromise(() => work.store.load()))?.apiKey, + (yield* Effect.promise(() => work.store.load()))?.apiKey, "test-only-work-key", ); }).pipe(Effect.provide(layerHost)), @@ -131,10 +131,10 @@ it.effect.each([ const credentials = { ...requiredFields }; // Match the SDK's runtime values without relying on its stricter declarations. Object.assign(credentials, optionalFields); - yield* Effect.tryPromise(() => store.save(credentials)); + yield* Effect.promise(() => store.save(credentials)); const restored = yield* makeCursorCredentialStore(instanceId); - assert.deepEqual(yield* Effect.tryPromise(() => restored.store.load()), { + assert.deepEqual(yield* Effect.promise(() => restored.store.load()), { ...requiredFields, ...expectedFields, }); diff --git a/packages/provider-cursor/src/server/textGeneration.ts b/packages/provider-cursor/src/server/textGeneration.ts index fa8228d0ba012..278839558ee92 100644 --- a/packages/provider-cursor/src/server/textGeneration.ts +++ b/packages/provider-cursor/src/server/textGeneration.ts @@ -86,7 +86,12 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu const { operation, prompt, modelSelection } = input; const apiKey = yield* resolveCursorApiKey(operation); - const { Agent } = yield* Effect.try(sdk.load); + const sdkFailure = (detail: string) => (cause: unknown) => + new TextGenerationError({ operation, detail, cause }); + const { Agent } = yield* Effect.try({ + try: sdk.load, + catch: sdkFailure("Cursor SDK could not be loaded."), + }); // sandbox.json expands writable paths independently of settingSources; the public API cannot override it. if (yield* fs.exists(`${yield* HostProcess.HomeDirectory}/.cursor/sandbox.json`)) { return yield* new TextGenerationError({ @@ -99,10 +104,15 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu // Only store disposal releases SDK SQLite handles; keep state outside the empty workspace. const stateRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-state-" }); const store = yield* Effect.acquireRelease( - Effect.tryPromise(() => - sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot }), - ), - (store) => Effect.tryPromise(() => store.dispose()).pipe(Effect.ignore({ log: true })), + Effect.tryPromise({ + try: () => sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot }), + catch: sdkFailure("Cursor SDK agent store could not be opened."), + }), + (store) => + Effect.tryPromise({ + try: () => store.dispose(), + catch: sdkFailure("Cursor SDK agent store could not be disposed."), + }).pipe(Effect.ignore({ log: true })), ); const agentOptions = { apiKey, @@ -118,22 +128,24 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu }, } satisfies AgentOptions; const createCursorAgent = (sandboxEnabled: boolean) => - Effect.tryPromise((signal) => - Agent.create( - sandboxEnabled - ? agentOptions - : { - ...agentOptions, - local: { - ...agentOptions.local, - sandboxOptions: { enabled: false }, + Effect.tryPromise({ + try: (signal) => + Agent.create( + sandboxEnabled + ? agentOptions + : { + ...agentOptions, + local: { + ...agentOptions.local, + sandboxOptions: { enabled: false }, + }, }, - }, - ).then((agent) => { - if (signal.aborted) agent.close(); - return agent; - }), - ); + ).then((agent) => { + if (signal.aborted) agent.close(); + return agent; + }), + catch: sdkFailure("Cursor SDK agent could not be created."), + }); const request = Effect.gen(function* () { // Empty cwd and setting sources isolate the run from user projects even if sandboxing fails. @@ -142,27 +154,32 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu Effect.catchIf(cursorSandboxUnsupported, () => createCursorAgent(false)), ), (agent) => - Effect.tryPromise(() => agent[Symbol.asyncDispose]()).pipe( - Effect.timeout("5 seconds"), - Effect.ignore({ log: true }), - ), + Effect.tryPromise({ + try: () => agent[Symbol.asyncDispose](), + catch: sdkFailure("Cursor SDK agent could not be disposed."), + }).pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })), { interruptible: true }, ); - const run = yield* Effect.tryPromise((signal) => - agent.send(prompt).then((run) => { - if (signal.aborted) void run.cancel().catch(() => undefined); - return run; - }), - ); + const run = yield* Effect.tryPromise({ + try: (signal) => + agent.send(prompt).then((run) => { + if (signal.aborted) void run.cancel().catch(() => undefined); + return run; + }), + catch: sdkFailure("Cursor SDK request could not be sent."), + }); yield* Effect.addFinalizer(() => run.status === "running" - ? Effect.tryPromise(() => run.cancel()).pipe( - Effect.timeout("5 seconds"), - Effect.ignore({ log: true }), - ) + ? Effect.tryPromise({ + try: () => run.cancel(), + catch: sdkFailure("Cursor SDK run could not be cancelled."), + }).pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })) : Effect.void, ); - return yield* Effect.tryPromise(() => run.wait()); + return yield* Effect.tryPromise({ + try: () => run.wait(), + catch: sdkFailure("Cursor SDK run failed."), + }); }).pipe(Effect.scoped); const promptResult = yield* request.pipe( Effect.timeoutOption(CURSOR_TIMEOUT_MS), diff --git a/packages/provider-muse/src/server/MuseUsageHome.ts b/packages/provider-muse/src/server/MuseUsageHome.ts index de2689d042ef7..a0c5c16261c0e 100644 --- a/packages/provider-muse/src/server/MuseUsageHome.ts +++ b/packages/provider-muse/src/server/MuseUsageHome.ts @@ -5,7 +5,7 @@ import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; -import { createMuseSdkHostEffect } from "./sdk.ts"; +import { createMuseSdkHostEffect, MuseSdkError } from "./sdk.ts"; export class MuseUsageHome extends Context.Service< MuseUsageHome, @@ -26,7 +26,11 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const host = yield* Effect.acquireRelease( createMuseSdkHostEffect({ ...input, readOnly: true, startupTimeoutMs: 5_000 }), - (host) => Effect.tryPromise(() => host.close()).pipe(Effect.ignore), + (host) => + Effect.tryPromise({ + try: () => host.close(), + catch: (cause) => new MuseSdkError({ operation: "close", cause }), + }).pipe(Effect.ignore), { interruptible: true }, ); return host.initializeResult.museHome; diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 354e457b2ca81..b29f8d51947bf 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -64,6 +64,7 @@ import { import { isMuseUsageLimitFailure, museUsageLimitResetAt } from "./usageLimits.ts"; import { createMuseSdkHostEffect, + MuseSdkError, museApprovalMode, museCanonicalPath, musePermissionProfile, @@ -1069,7 +1070,10 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( } yield* settleObservedChildren("failed"); if (turn) yield* Queue.fail(events, protocolError(detail, cause)); - yield* Effect.tryPromise(() => failed.close()).pipe(Effect.ignore, Effect.forkIn(scope)); + yield* Effect.tryPromise({ + try: () => failed.close(), + catch: (cause) => new MuseSdkError({ operation: "close", cause }), + }).pipe(Effect.ignore, Effect.forkIn(scope)); }); const owns = (turn: ActiveTurn, turnId: string) => turnId === turn.nativeId || turn.joined.has(turnId); @@ -1724,7 +1728,10 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( closed = true; hostEpoch++; } - const close = Effect.tryPromise(() => created.close()); + const close = Effect.tryPromise({ + try: () => created.close(), + catch: (cause) => new MuseSdkError({ operation: "close", cause }), + }); // SDK shutdown sends SIGKILL after 10s + 2s, but inherited pipes can // keep its close promise pending. Let the scope reap those holders. yield* ( @@ -2258,10 +2265,10 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( Effect.gen(function* () { if (active !== turn) return; hostEpoch++; - yield* Effect.tryPromise(() => host.close()).pipe( - Effect.mapError((cause) => protocolError("Cannot stop Muse compaction", cause)), - Effect.onError(failHost), - ); + yield* Effect.tryPromise({ + try: () => host.close(), + catch: (cause) => protocolError("Cannot stop Muse compaction", cause), + }).pipe(Effect.onError(failHost)); broken = true; yield* finish(turn, "interrupted", undefined, "broken"); yield* settleObservedChildren("interrupted"); diff --git a/packages/provider-muse/src/server/modelCatalog.ts b/packages/provider-muse/src/server/modelCatalog.ts index d10a076f27c10..b8a62297ddf59 100644 --- a/packages/provider-muse/src/server/modelCatalog.ts +++ b/packages/provider-muse/src/server/modelCatalog.ts @@ -4,7 +4,12 @@ import { MuseSettings } from "../settings.ts"; import { createModelCapabilities, getProviderOptionDescriptors } from "@t3tools/shared/model"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -import { createMuseSdkHost, createMuseSdkHostEffect, type MuseSdkHost } from "./sdk.ts"; +import { + createMuseSdkHost, + createMuseSdkHostEffect, + MuseSdkError, + type MuseSdkHost, +} from "./sdk.ts"; type MuseReasoningEffort = NonNullable["reasoningEffort"]>; @@ -113,7 +118,10 @@ export const discoverMuseModels = Effect.fn("discoverMuseModels")(function* ( (host: MuseSdkHost) => Effect.promise(() => host.close()), { interruptible: true }, ); - const result = yield* Effect.tryPromise(() => host.connection.request("model/list", {})); + const result = yield* Effect.tryPromise({ + try: () => host.connection.request("model/list", {}), + catch: (cause) => new MuseSdkError({ operation: "model/list", cause }), + }); const catalog = yield* decodeModelList(result); if (catalog.providerId !== "meta") { return yield* new MuseCatalogError({ detail: "Muse returned a catalog for another provider." }); diff --git a/packages/provider-muse/src/server/sdk.ts b/packages/provider-muse/src/server/sdk.ts index 17e9a017d81e2..0269a64d9c967 100644 --- a/packages/provider-muse/src/server/sdk.ts +++ b/packages/provider-muse/src/server/sdk.ts @@ -13,6 +13,16 @@ import type { RuntimeMode } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +export class MuseSdkError extends Schema.TaggedError()("MuseSdkError", { + operation: Schema.String, + cause: Schema.Defect(), +}) { + override get message(): string { + return `Muse SDK ${this.operation} failed.`; + } +} export interface MuseSdkHost { readonly connection: Pick< @@ -72,15 +82,19 @@ export function museVerbatimPath(path: string): string { // Native realpath corrects filesystem case as well as resolving symlinks. export const museCanonicalPath = Effect.fn("museCanonicalPath")(function* (path: string) { - return yield* Effect.tryPromise(() => NodeFSP.realpath(path)).pipe( - Effect.orElseSucceed(() => path), - ); + return yield* Effect.tryPromise({ + try: () => NodeFSP.realpath(path), + catch: (cause) => new MuseSdkError({ operation: "realpath", cause }), + }).pipe(Effect.orElseSucceed(() => path)); }); // Windows turn roots need verbatim form; launch cmd.exe with the plain canonical path. export const museWorkspaceRoot = Effect.fn("museWorkspaceRoot")(function* (path: string) { if ((yield* HostProcess.Platform) !== "win32") return yield* museCanonicalPath(path); - const canonical = yield* Effect.tryPromise(() => NodeFSP.realpath(path)).pipe( + const canonical = yield* Effect.tryPromise({ + try: () => NodeFSP.realpath(path), + catch: (cause) => new MuseSdkError({ operation: "realpath", cause }), + }).pipe( // A verbatim path takes `/` literally, so an unresolved root needs Windows separators. Effect.orElseSucceed(() => path.replaceAll("/", "\\")), ); @@ -214,9 +228,12 @@ export const createMuseSdkHostEffect = Effect.fn("createMuseSdkHostEffect")(func ) { const launch = options.launch ?? (yield* museLaunch(options.binaryPath, options.environment)); let startup: Promise | undefined; - return yield* Effect.tryPromise((signal) => { - startup = createHost({ ...options, launch, signal }); - return startup; + return yield* Effect.tryPromise({ + try: (signal) => { + startup = createHost({ ...options, launch, signal }); + return startup; + }, + catch: (cause) => new MuseSdkError({ operation: "start", cause }), }).pipe( Effect.onInterrupt(() => Effect.promise(async () => { diff --git a/packages/provider-muse/src/server/textGeneration.ts b/packages/provider-muse/src/server/textGeneration.ts index f122d1df756e6..5c1bceadeea7d 100644 --- a/packages/provider-muse/src/server/textGeneration.ts +++ b/packages/provider-muse/src/server/textGeneration.ts @@ -14,7 +14,12 @@ import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import { createMuseSdkHost, createMuseSdkHostEffect, type MuseSdkHost } from "./sdk.ts"; +import { + createMuseSdkHost, + createMuseSdkHostEffect, + MuseSdkError, + type MuseSdkHost, +} from "./sdk.ts"; import { museModelCapabilities, resolveMuseReasoningEffort } from "./modelCatalog.ts"; import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration"; import { investigationUnsupported } from "@t3tools/provider-core/server/textGenerationOperations"; @@ -250,16 +255,18 @@ export const makeMuseTextGeneration = Effect.fn("makeMuseTextGeneration")(functi (host: MuseSdkHost) => Effect.promise(() => host.close()), { interruptible: true }, ); - return yield* Effect.tryPromise((signal) => - generateMuseText( - host, - cwd, - `${input.prompt}\n\nReturn only a JSON object matching this schema, with no markdown fences. Do not use tools or ask questions.\n${jsonSchema}`, - modelId, - reasoningEffort, - signal, - ), - ); + return yield* Effect.tryPromise({ + try: (signal) => + generateMuseText( + host, + cwd, + `${input.prompt}\n\nReturn only a JSON object matching this schema, with no markdown fences. Do not use tools or ask questions.\n${jsonSchema}`, + modelId, + reasoningEffort, + signal, + ), + catch: (cause) => new MuseSdkError({ operation: "generate text", cause }), + }); }).pipe( Effect.scoped, Effect.mapError( diff --git a/packages/provider-muse/src/server/usage.test.ts b/packages/provider-muse/src/server/usage.test.ts index 266b6097b8ef1..4ca72c5682488 100644 --- a/packages/provider-muse/src/server/usage.test.ts +++ b/packages/provider-muse/src/server/usage.test.ts @@ -236,11 +236,13 @@ describe("Muse history discovery", () => { it.effect("does not guess a directory when initialization fails", () => Effect.gen(function* () { - using _create = vi.spyOn(MuseSdk, "createMuseSdkHostEffect").mockReturnValue( - Effect.try(() => { - throw new Error("not installed"); - }), - ); + using _create = vi + .spyOn(MuseSdk, "createMuseSdkHostEffect") + .mockReturnValue( + Effect.fail( + new MuseSdk.MuseSdkError({ operation: "start", cause: new Error("not installed") }), + ), + ); if (museUsageReader.kind !== "transcripts") throw new Error("Expected a transcript reader"); const directories = yield* museUsageReader.directories({ instanceId: ProviderInstanceId.make("muse"), @@ -381,9 +383,9 @@ describe("Muse history discovery", () => { using create = vi .spyOn(MuseSdk, "createMuseSdkHostEffect") .mockReturnValueOnce( - Effect.try(() => { - throw new Error("not installed"); - }), + Effect.fail( + new MuseSdk.MuseSdkError({ operation: "start", cause: new Error("not installed") }), + ), ) .mockReturnValue( Effect.succeed({ diff --git a/packages/provider-opencode/src/server/usageLimits.ts b/packages/provider-opencode/src/server/usageLimits.ts index 0f97ea36cfefa..03488e515a79f 100644 --- a/packages/provider-opencode/src/server/usageLimits.ts +++ b/packages/provider-opencode/src/server/usageLimits.ts @@ -43,32 +43,44 @@ const UsageResponse = Schema.Struct({ // Select before decoding so an OAuth or self-hosted connection cannot fall // through to another stored account. NULL-active rows predate the selection flag. +class OpenCodeCredentialReadError extends Schema.TaggedError()( + "OpenCodeCredentialReadError", + { databasePath: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `Could not read OpenCode credentials from ${this.databasePath}.`; + } +} + const readStoredApiKey = (databasePath: string, integrationId: "opencode" | "opencode-go") => - Effect.try(() => { - const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true }); - try { - database.exec("PRAGMA busy_timeout = 100"); - const row = database - .prepare( - `SELECT value FROM credential - WHERE integration_id = ? AND active IS NOT 0 - ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`, - ) - .get(integrationId); - const stored = - typeof row?.value === "string" - ? Option.getOrUndefined(decodeStoredKey(row.value)) - : undefined; - const server = stored?.metadata?.server; - if (typeof server === "string") { - const url = new URL(server); - if (`${url.origin}${url.pathname.replace(/\/+$/, "")}` !== "https://opencode.ai/console") - return undefined; + Effect.try({ + try: () => { + const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true }); + try { + database.exec("PRAGMA busy_timeout = 100"); + const row = database + .prepare( + `SELECT value FROM credential + WHERE integration_id = ? AND active IS NOT 0 + ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`, + ) + .get(integrationId); + const stored = + typeof row?.value === "string" + ? Option.getOrUndefined(decodeStoredKey(row.value)) + : undefined; + const server = stored?.metadata?.server; + if (typeof server === "string") { + const url = new URL(server); + if (`${url.origin}${url.pathname.replace(/\/+$/, "")}` !== "https://opencode.ai/console") + return undefined; + } + return stored?.key.trim(); + } finally { + database.close(); } - return stored?.key.trim(); - } finally { - database.close(); - } + }, + catch: (cause) => new OpenCodeCredentialReadError({ databasePath, cause }), }).pipe(Effect.orElseSucceed(() => undefined)); /** External OpenCode servers own their credentials; never read the host's account for them. */ diff --git a/packages/shared/src/HostProcess.ts b/packages/shared/src/HostProcess.ts index f24365cd5c81f..50f0a3ef85950 100644 --- a/packages/shared/src/HostProcess.ts +++ b/packages/shared/src/HostProcess.ts @@ -1,5 +1,6 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; import * as NodeDns from "node:dns"; import * as NodeOS from "node:os"; import * as NodeSea from "node:sea"; @@ -73,6 +74,15 @@ export const IsExecutable = Context.Reference("@t3tools/shared/HostProc defaultValue: () => NodeSea.isSea(), }); +export class HostnameLookupError extends Schema.TaggedError()( + "HostnameLookupError", + { hostname: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `Could not resolve ${this.hostname}.`; + } +} + /** Includes hostname-resolved addresses absent from interfaces, such as Debian's 127.0.1.1 used by Firefox locks. */ export const Addresses = Context.Reference>>( "@t3tools/shared/HostProcess/Addresses", @@ -82,9 +92,11 @@ export const Addresses = Context.Reference>>( const interfaces = Object.values(NodeOS.networkInterfaces()) .flat() .flatMap((entry) => (entry ? [entry.address] : [])); - const resolved = yield* Effect.tryPromise(() => - NodeDns.promises.lookup(NodeOS.hostname(), { all: true }), - ).pipe( + const hostname = NodeOS.hostname(); + const resolved = yield* Effect.tryPromise({ + try: () => NodeDns.promises.lookup(hostname, { all: true }), + catch: (cause) => new HostnameLookupError({ hostname, cause }), + }).pipe( Effect.map((entries) => entries.map((entry) => entry.address)), Effect.orElseSucceed(() => [] as ReadonlyArray), ); diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index 0b9adc6ab96ef..481b7af0377e0 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -637,7 +637,7 @@ const startCheckpointWorker = Effect.fnUntraced(function* ( } const frames = writer.prepare("PRAGMA wal_checkpoint(NOOP)"); const sizeLimit = writer.prepare("PRAGMA journal_size_limit"); - const started = yield* Effect.try( + const started = Result.try( () => new NodeWorkerThreads.Worker(checkpointWorkerSource, { eval: true, @@ -648,9 +648,9 @@ const startCheckpointWorker = Effect.fnUntraced(function* ( idleMs: CHECKPOINT_IDLE_MS, }, }), - ).pipe(Effect.result); + ); if (Result.isFailure(started)) { - yield* warn(String(started.failure.cause)); + yield* warn(String(started.failure)); return undefined; } const worker = started.success; diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.ts index ea461340681b3..7bce72d00d438 100644 --- a/packages/shared/src/relayClient.ts +++ b/packages/shared/src/relayClient.ts @@ -21,6 +21,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import type * as PlatformError from "effect/PlatformError"; import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; @@ -56,6 +57,15 @@ export type RelayClientStatus = export type AvailableRelayClient = Extract; +class RelayClientLockRemoveError extends Schema.TaggedError()( + "RelayClientLockRemoveError", + { lockPath: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `Could not remove the relay client lock ${this.lockPath}.`; + } +} + export class RelayClientInstallError extends Data.TaggedError("RelayClientInstallError")<{ readonly reason: | "download_failed" @@ -486,7 +496,10 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function }); const removeEmptyLock = (lockPath: string) => - Effect.tryPromise(() => NodeFSP.rmdir(lockPath)).pipe(Effect.ignore); + Effect.tryPromise({ + try: () => NodeFSP.rmdir(lockPath), + catch: (cause) => new RelayClientLockRemoveError({ lockPath, cause }), + }).pipe(Effect.ignore); const releaseOwnedLock = Effect.fn("cloudflared.releaseOwnedLock")(function* ( lockPath: string, diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index e3af0855ebfac..5f268ffa507ea 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -341,7 +341,7 @@ describe("readEnvironmentFromWindowsShell", () => { expect( yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) => - Effect.try(() => execFile(...args)).pipe(Effect.option), + Effect.sync(() => Option.liftThrowable(execFile)(...args)), ), ).toEqual({ PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm", @@ -369,7 +369,7 @@ describe("readEnvironmentFromWindowsShell", () => { expect( yield* readEnvironmentFromWindowsShell(["FNM_DIR"], {}, (...args) => - Effect.try(() => execFile(...args)).pipe(Effect.option), + Effect.sync(() => Option.liftThrowable(execFile)(...args)), ), ).toEqual({ FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm", @@ -389,7 +389,7 @@ describe("readEnvironmentFromWindowsShell", () => { expect( yield* readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, (...args) => - Effect.try(() => execFile(...args)).pipe(Effect.option), + Effect.sync(() => Option.liftThrowable(execFile)(...args)), ), ).toEqual({ PATH: "C:\\Tools", @@ -420,7 +420,7 @@ describe("readEnvironmentFromWindowsShell", () => { expect( yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) => - Effect.try(() => execFile(...args)).pipe(Effect.option), + Effect.sync(() => Option.liftThrowable(execFile)(...args)), ), ).toEqual({ PATH: "C:\\Tools", diff --git a/scripts/build-cli-archive.ts b/scripts/build-cli-archive.ts index 3c74b6714ddeb..1244b9491fb73 100644 --- a/scripts/build-cli-archive.ts +++ b/scripts/build-cli-archive.ts @@ -62,6 +62,15 @@ const RepoRoot = Effect.service(Path.Path).pipe( Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))), ); +export class CliArchiveLinuxArm64PageError extends Schema.TaggedError()( + "CliArchiveLinuxArm64PageError", + { executablePath: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `${this.executablePath} is not page-compatible with Linux arm64.`; + } +} + export class CliArchiveCommandFailedError extends Schema.TaggedError()( "CliArchiveCommandFailedError", { command: Schema.String, exitCode: Schema.Int }, @@ -537,7 +546,10 @@ const buildCliArchive = Effect.fn("buildCliArchive")(function* (input: { // TEMPORARY one-time Node fix. Remove when fixed: https://github.com/nodejs/node/issues/67048 if (input.platform === "linux" && input.arch === "arm64") { const bytes = yield* fs.readFile(executablePath); - yield* Effect.try(() => assertLinuxArm64PageCompatibility(bytes)); + yield* Effect.try({ + try: () => assertLinuxArm64PageCompatibility(bytes), + catch: (cause) => new CliArchiveLinuxArm64PageError({ executablePath, cause }), + }); } if (input.platform === "mac") { yield* signMacArchiveContents({ repoRoot, contentDir, executablePath }); diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 6756f6fea855d..9bc12cde9854c 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -685,6 +685,15 @@ export class DesktopBuildDistDirectoryMissingError extends Schema.TaggedError()( + "DesktopBuildArtifactCopyError", + { from: Schema.String, to: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `Failed to copy build artifact ${this.from} to ${this.to}.`; + } +} + export class DesktopBuildNoArtifactsProducedError extends Schema.TaggedError()( "DesktopBuildNoArtifactsProducedError", { @@ -2095,7 +2104,7 @@ const NativeMarkerManifest = Schema.Struct({ dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)), optionalDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)), }); -const decodeNativeMarkerManifest = Schema.decodeUnknownSync( +const decodeNativeMarkerManifest = Schema.decodeUnknownOption( Schema.fromJsonString(NativeMarkerManifest), ); @@ -2135,13 +2144,12 @@ const hasNativeLoaderMarkers = Effect.fn("hasNativeLoaderMarkers")(function* (pa if (!(yield* exists(manifestPath))) return false; const source = yield* fs.readFileString(manifestPath).pipe(Effect.orElseSucceed(() => "")); if (source === "") return false; - const manifest = yield* Effect.try(() => decodeNativeMarkerManifest(source)).pipe( - Effect.orElseSucceed(() => null), - ); - if (manifest === null) return false; - return Object.keys({ ...manifest.dependencies, ...manifest.optionalDependencies }).some( - (dependency) => dependency.startsWith("node-gyp-build"), - ); + const manifest = decodeNativeMarkerManifest(source); + if (Option.isNone(manifest)) return false; + return Object.keys({ + ...manifest.value.dependencies, + ...manifest.value.optionalDependencies, + }).some((dependency) => dependency.startsWith("node-gyp-build")); }); export const copyDirectoryPreservingSymlinks = Effect.fn("copyDirectoryPreservingSymlinks")( @@ -4107,13 +4115,15 @@ export const copyDesktopBuildArtifacts = Effect.fn("copyDesktopBuildArtifacts")( // overwrite a directory with a file or a file with a directory, and only merges into // an existing directory, so a stale entry of either type must go first. yield* fs.remove(to, { recursive: true, force: true }); - yield* Effect.tryPromise(() => - NodeFSP.cp(from, to, { - recursive: true, - force: true, - verbatimSymlinks: true, - }), - ); + yield* Effect.tryPromise({ + try: () => + NodeFSP.cp(from, to, { + recursive: true, + force: true, + verbatimSymlinks: true, + }), + catch: (cause) => new DesktopBuildArtifactCopyError({ from, to, cause }), + }); copiedArtifacts.push(to); } diff --git a/tsconfig.effect.json b/tsconfig.effect.json index 29240a31e71e8..dab2c98e7712e 100644 --- a/tsconfig.effect.json +++ b/tsconfig.effect.json @@ -96,6 +96,7 @@ "timeoutCatchTagToTimeoutOrElse": "error", "unnecessaryPipe": "error", "unnecessaryTypeofType": "error", + "effectTryWithoutCatch": "error", "processEnvInEffect": "error", "schemaNumber": "off" }, From 20e92ffe022fe7813c854eeb68195ffa8e04850f Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:24:54 +0530 Subject: [PATCH 004/397] fix(web): sidebar project filter rows line up and stay still on hover (#29639) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../web/src/components/ProjectComboboxRow.tsx | 18 +++++ .../components/ProjectEnvironmentBadge.tsx | 2 +- apps/web/src/components/Sidebar.tsx | 77 +++++++++++-------- 3 files changed, 66 insertions(+), 31 deletions(-) create mode 100644 apps/web/src/components/ProjectComboboxRow.tsx diff --git a/apps/web/src/components/ProjectComboboxRow.tsx b/apps/web/src/components/ProjectComboboxRow.tsx new file mode 100644 index 0000000000000..0ecc4ece2d0c2 --- /dev/null +++ b/apps/web/src/components/ProjectComboboxRow.tsx @@ -0,0 +1,18 @@ +import type { ReactNode } from "react"; + +/** Settings shows only on the highlighted row; the pin keeps the far-right column. */ +export function ProjectRowActions(props: { + readonly settings?: ReactNode; + readonly pin?: ReactNode; +}) { + return ( + + {props.settings ? ( + + {props.settings} + + ) : null} + {props.pin ?? } + + ); +} diff --git a/apps/web/src/components/ProjectEnvironmentBadge.tsx b/apps/web/src/components/ProjectEnvironmentBadge.tsx index e9257d0de9408..e1ece5dfd53b4 100644 --- a/apps/web/src/components/ProjectEnvironmentBadge.tsx +++ b/apps/web/src/components/ProjectEnvironmentBadge.tsx @@ -28,7 +28,7 @@ export function ProjectEnvironmentBadge(props: { } > diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index a10183a32d8f0..a82da0bf5f4de 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -170,6 +170,7 @@ import type { SidebarThreadSummary } from "../types"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { cn } from "~/lib/utils"; import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge"; +import { ProjectRowActions } from "./ProjectComboboxRow"; import { buildDraftActionMenuItems, buildThreadActionMenuItems, @@ -3020,13 +3021,18 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } > {scopedProjectGroups.length > 1 ? ( - - {scopedProjectGroups.slice(0, 2).map((project) => ( - + {scopedProjectGroups.slice(0, 2).map((project, index) => ( + + className={ + index === 0 + ? "flex" + : "-ml-1 flex rounded-[25%] bg-sidebar ring-2 ring-sidebar" + } + > + + ))} ) : scopedProjectGroups[0] ? ( @@ -3117,15 +3123,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve )} - {item.label} - {project && canPinProject(project) ? ( - toggleProjectGroupPin(project)} - /> - ) : null} + {item.label} {project && showProjectEnvironments ? ( ) : null} {project ? ( - - ) : null} + toggleProjectGroupPin(project)} + /> + ) : null + } + settings={ + + } + /> + ) : ( + // Keeps "All projects" as tall as the project rows. + + )} ); }} From 298cb24140fdddebfbfaedad3a097e86ff3d9d04 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 4 Nov 2026 20:05:44 -0800 Subject: [PATCH 005/397] refactor: errors are Schema.TaggedError, not Data.TaggedError or native Error (#31216) Co-authored-by: Claude Opus 5.5 --- .../desktop/src/ipc/methods/sshEnvironment.ts | 33 +-- .../src/snapShot/DesktopSnapShot.test.ts | 4 +- apps/desktop/src/snapShot/DesktopSnapShot.ts | 4 +- apps/desktop/src/snapShot/HyprlandSnapShot.ts | 4 +- apps/desktop/src/snapShot/KdeSnapShot.ts | 2 +- .../src/snapShot/linuxCaptureSession.ts | 10 +- apps/desktop/src/ssh/DesktopSshEnvironment.ts | 5 +- .../src/components/FilePreviewModal.tsx | 33 +-- apps/mobile/src/features/cloud/dpop.ts | 9 +- .../src/features/cloud/linkEnvironment.ts | 14 +- .../src/features/files/ZipArchiveView.tsx | 40 ++-- .../features/files/sourceHighlightingState.ts | 8 +- .../src/features/threads/McpAppWebView.tsx | 28 +-- .../features/threads/ThreadMarkdownImage.tsx | 6 +- .../src/native/voiceTranscription.android.ts | 11 +- .../src/native/voiceTranscription.ios.ts | 25 ++- apps/server/src/device/DeviceService.ts | 4 +- apps/server/src/device/SshDeviceHost.ts | 4 +- apps/server/src/http.ts | 8 +- apps/server/src/mcp/AcpMcpStdioBridge.ts | 32 +-- apps/server/src/orchestration-v2/http.ts | 4 +- .../orchestration-v2/threadHistoryPaging.ts | 12 +- apps/server/src/preview/ServerBrowser.ts | 203 ++++++++++-------- apps/server/src/preview/ServerBrowserPage.ts | 156 ++++++++------ apps/server/src/preview/SessionControl.ts | 56 +++-- .../src/project/AgentSessionJson.test.ts | 2 +- apps/server/src/project/AgentSessionJson.ts | 10 +- .../server/src/project/AgentSessionScanner.ts | 6 +- .../server/src/provider/documentTextWorker.ts | 1 + .../src/provider/providerMaintenanceRunner.ts | 12 +- .../scheduledTasks/ScheduledTaskService.ts | 8 +- .../web/src/browser/browserViewportActions.ts | 14 +- apps/web/src/browser/openFileInPreview.ts | 20 +- apps/web/src/browser/useOpenLink.ts | 4 +- apps/web/src/cloud/dpop.ts | 15 +- apps/web/src/cloud/linkEnvironment.ts | 16 +- apps/web/src/cloud/useCloudLinkController.ts | 4 +- apps/web/src/components/ChatMarkdown.tsx | 6 +- apps/web/src/components/chat/McpAppFrame.tsx | 28 +-- .../components/chat/useRightPanelActions.ts | 4 +- .../device/DeviceAndroidFoldControls.tsx | 5 +- .../src/components/device/DeviceWorkspace.tsx | 5 +- apps/web/src/components/device/deviceFold.ts | 21 +- .../src/components/device/deviceHubAtoms.ts | 4 +- .../components/files/office/Spreadsheet.tsx | 5 +- .../src/components/files/office/worker-rpc.ts | 28 ++- .../components/guest/guestTurnItemSource.ts | 7 +- .../src/components/preview/PreviewView.tsx | 4 +- .../components/preview/openPreviewSession.ts | 4 +- .../settings/IntegrationsSettings.tsx | 18 +- .../settings/OpenSourceLicenses.tsx | 9 +- .../resourceTelemetryState.browser.test.tsx | 6 +- infra/relay/src/http/Api.test.ts | 3 +- .../src/errors.ts | 1 + oxlint-plugin-t3code/test/utils.ts | 31 +-- .../src/authorization/remote.ts | 5 +- .../src/connection/errors.test.ts | 5 +- .../client-runtime/src/device/screenshot.ts | 15 +- .../client-runtime/src/mcpApps/host.test.ts | 4 +- packages/client-runtime/src/mcpApps/host.ts | 12 +- .../src/platform/threadCacheEncoding.ts | 6 +- .../client-runtime/src/relay/dpopProof.ts | 10 +- .../src/relay/managedRelayState.ts | 12 +- packages/client-runtime/src/rpc/http.ts | 71 +++--- .../src/state/environmentHttpAuth.ts | 5 +- .../src/state/peerPairingCode.ts | 13 +- .../src/state/pullRequests.test.ts | 4 +- .../client-runtime/src/state/pullRequests.ts | 6 +- packages/client-runtime/src/state/session.ts | 5 +- .../src/voice-input/controller.test.ts | 8 +- .../src/voice-input/controller.ts | 9 +- .../src/voice-input/transcription.ts | 38 ++-- .../src/server/mcpOverAcpBridge.ts | 56 ++--- .../src/server/CursorSdk.test.ts | 1 + .../provider-cursor/src/server/sdk.test.ts | 1 + packages/provider-grok/src/server/adapter.ts | 9 +- .../src/server/xaiAcpExtension.ts | 9 +- .../src/server/OpenCodeRuntime.ts | 21 +- .../provider-opencode/src/server/status.ts | 14 +- packages/shared/src/Net.ts | 10 +- packages/shared/src/managedPolicyFile.ts | 20 +- packages/shared/src/relayClient.ts | 45 ++-- .../src/server/GitHubSourceControlProvider.ts | 9 +- packages/ssh/src/errors.ts | 109 ++++++---- packages/ssh/src/tunnel.test.ts | 9 +- scripts/mobile-e2e/device.ts | 17 +- tsconfig.effect.json | 2 + 87 files changed, 903 insertions(+), 673 deletions(-) diff --git a/apps/desktop/src/ipc/methods/sshEnvironment.ts b/apps/desktop/src/ipc/methods/sshEnvironment.ts index 15e04f71282b1..b368b5581d06d 100644 --- a/apps/desktop/src/ipc/methods/sshEnvironment.ts +++ b/apps/desktop/src/ipc/methods/sshEnvironment.ts @@ -26,7 +26,6 @@ import { } from "@t3tools/contracts"; import { SshHttpBridgeError } from "@t3tools/ssh/errors"; import { resolveLoopbackSshHttpBaseUrl } from "@t3tools/ssh/tunnel"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -35,10 +34,12 @@ import * as DesktopIpc from "../DesktopIpc.ts"; import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts"; import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts"; -type DesktopSshEnvironmentRequestOperation = - | "fetch-environment-descriptor" - | "bootstrap-bearer-session" - | "fetch-session-state"; +const DesktopSshEnvironmentRequestOperation = Schema.Literals([ + "fetch-environment-descriptor", + "bootstrap-bearer-session", + "fetch-session-state", +]); +type DesktopSshEnvironmentRequestOperation = typeof DesktopSshEnvironmentRequestOperation.Type; type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError; @@ -47,12 +48,13 @@ const isEnvironmentInternalError = Schema.is(EnvironmentInternalError); const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError); const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError); const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError); +const isRemoteEnvironmentAuthUndeclaredStatusError = Schema.is( + RemoteEnvironmentAuthUndeclaredStatusError, +); +const isSshHttpBridgeError = Schema.is(SshHttpBridgeError); function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null { - if ( - cause instanceof RemoteEnvironmentAuthUndeclaredStatusError || - cause instanceof SshHttpBridgeError - ) { + if (isRemoteEnvironmentAuthUndeclaredStatusError(cause) || isSshHttpBridgeError(cause)) { return cause.status ?? null; } if (isEnvironmentRequestInvalidError(cause)) { @@ -73,13 +75,14 @@ function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | n return null; } -export class DesktopSshEnvironmentRequestError extends Data.TaggedError( +export class DesktopSshEnvironmentRequestError extends Schema.TaggedError()( "DesktopSshEnvironmentRequestError", -)<{ - readonly operation: DesktopSshEnvironmentRequestOperation; - readonly cause: DesktopSshEnvironmentRequestCause; - readonly sshHttpStatus: number | null; -}> { + { + operation: DesktopSshEnvironmentRequestOperation, + cause: Schema.Defect(), + sshHttpStatus: Schema.NullOr(Schema.Number), + }, +) { // The web client matches "[ssh_http:500]" to explain version-skewed SSH pairing. override get message() { const prefix = this.sshHttpStatus === null ? "" : `[ssh_http:${this.sshHttpStatus}] `; diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts index 721f130ef5e56..59d658e1eedaf 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts @@ -1872,7 +1872,9 @@ it.effect("capture fails closed while snapshots are disabled", () => { it.effect("points capture setup failures at SnapShot settings", () => { vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - linuxCaptureMock.mockRejectedValueOnce(new CaptureSetupRequiredError("Install the helper.")); + linuxCaptureMock.mockRejectedValueOnce( + new CaptureSetupRequiredError({ state: "Install the helper." }), + ); return Effect.scoped( Effect.gen(function* () { const service = yield* DesktopSnapShot.make; diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.ts index ae0c2f04121ea..53799e1577939 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts @@ -94,6 +94,8 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import { readImageDimensions } from "@t3tools/shared/imageDimensions"; +const isCaptureSetupRequiredError = Schema.is(CaptureSetupRequiredError); + const MAX_CAPTURE_WIDTH = 2_560; const MAX_CAPTURE_HEIGHT = 1_600; const SHORTCUT_COOLDOWN_NS = 200_000_000n; @@ -180,7 +182,7 @@ const shortcutFailure = (cause: unknown) => new SnapShotShortcutError({ cause }) function captureFailure(cause: unknown, captureId?: string): DesktopSnapShotError { if (isDesktopSnapShotError(cause)) return cause; - const operation = cause instanceof CaptureSetupRequiredError ? "setup-required" : "capture"; + const operation = isCaptureSetupRequiredError(cause) ? "setup-required" : "capture"; return new DesktopSnapShotError({ operation, captureId, cause }); } diff --git a/apps/desktop/src/snapShot/HyprlandSnapShot.ts b/apps/desktop/src/snapShot/HyprlandSnapShot.ts index a0b8b4181cd2a..c40f397809d26 100644 --- a/apps/desktop/src/snapShot/HyprlandSnapShot.ts +++ b/apps/desktop/src/snapShot/HyprlandSnapShot.ts @@ -171,11 +171,11 @@ export async function captureHyprlandWindow( let state = await setup.state(); if (state.status === "update-required") { await setup.perform("install-hyprland-helper").catch((cause: unknown) => { - throw new CaptureSetupRequiredError(state.message, { cause }); + throw new CaptureSetupRequiredError({ state: state.message, cause }); }); state = await setup.state(); } - if (state.status !== "ready") throw new CaptureSetupRequiredError(state.message); + if (state.status !== "ready") throw new CaptureSetupRequiredError({ state: state.message }); const executable = hyprlandCaptureExecutable(paths); const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-hyprland-capture-")); const cleanup = () => NodeFSP.rm(directory, { recursive: true, force: true }); diff --git a/apps/desktop/src/snapShot/KdeSnapShot.ts b/apps/desktop/src/snapShot/KdeSnapShot.ts index 2e5723f51aae0..f141bd485d027 100644 --- a/apps/desktop/src/snapShot/KdeSnapShot.ts +++ b/apps/desktop/src/snapShot/KdeSnapShot.ts @@ -215,7 +215,7 @@ export async function captureKdeWindow( options?: { readonly flash: boolean; readonly animate: boolean }, ): Promise { const state = await new KdeCaptureSetup(paths).state(); - if (state.status !== "ready") throw new CaptureSetupRequiredError(state.message); + if (state.status !== "ready") throw new CaptureSetupRequiredError({ state: state.message }); const { executable } = kdeCapturePaths(paths); const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-kde-capture-")); let retained = false; diff --git a/apps/desktop/src/snapShot/linuxCaptureSession.ts b/apps/desktop/src/snapShot/linuxCaptureSession.ts index 11bf3984223df..e1f7c3601efc0 100644 --- a/apps/desktop/src/snapShot/linuxCaptureSession.ts +++ b/apps/desktop/src/snapShot/linuxCaptureSession.ts @@ -2,15 +2,19 @@ import * as NodeFSP from "node:fs/promises"; import * as NodeURL from "node:url"; import type { SnapShotKeyChord } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; import { nativeImage } from "electron"; // Keep dbus-next out of desktop detection and PNG reads in the main process. export const HYPRLAND_CAPTURE_ACTION = "capture-window"; -export class CaptureSetupRequiredError extends Error { - constructor(state: string, options?: ErrorOptions) { - super(`${state} Open Settings → SnapShots to continue setup.`, options); +export class CaptureSetupRequiredError extends Schema.TaggedError()( + "CaptureSetupRequiredError", + { state: Schema.String, cause: Schema.optional(Schema.Defect()) }, +) { + override get message(): string { + return `${this.state} Open Settings → SnapShots to continue setup.`; } } export const NIRI_CAPTURE_PATH = "/com/t3tools/SnapShot"; diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.ts index 3a3e84e03a9b7..7b480b36fbd12 100644 --- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts @@ -23,6 +23,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; import * as HttpClient from "effect/http/HttpClient"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -74,11 +75,13 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) { return discoverSshHosts(input ?? {}); } +const isSshPasswordPromptError = Schema.is(SshPasswordPromptError); + export function isDesktopSshPasswordPromptCancellation( error: unknown, ): error is SshPasswordPromptError { return ( - error instanceof SshPasswordPromptError && + isSshPasswordPromptError(error) && DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause) ); } diff --git a/apps/mobile/src/components/FilePreviewModal.tsx b/apps/mobile/src/components/FilePreviewModal.tsx index 0d6ddaa2f26d3..9093507581c7a 100644 --- a/apps/mobile/src/components/FilePreviewModal.tsx +++ b/apps/mobile/src/components/FilePreviewModal.tsx @@ -1,3 +1,4 @@ +import * as Schema from "effect/Schema"; import * as Dialog from "./ui/Dialog"; import { useContext, useEffect, useEffectEvent, useState } from "react"; import { Platform } from "react-native"; @@ -21,15 +22,17 @@ export type { ResolvedFilePreviewSource, } from "./FilePreviewModal.types"; -class PreviewResolutionError extends Error { - constructor( - override readonly cause: unknown, - readonly fallbackMessage: string, - ) { - super(fallbackMessage, { cause }); +class PreviewResolutionError extends Schema.TaggedError()( + "PreviewResolutionError", + { cause: Schema.Defect(), fallbackMessage: Schema.String }, +) { + override get message(): string { + return this.fallbackMessage; } } +const isPreviewResolutionError = Schema.is(PreviewResolutionError); + interface ResolvedPreviewUri { readonly uri: string; readonly dispose?: () => void; @@ -42,7 +45,10 @@ async function resolvePreviewUri( if ("uri" in item) return { uri: item.uri }; if ("attachment" in item) { return loadLocalAttachmentPreview(item.attachment, signal).catch((error: unknown) => { - throw new PreviewResolutionError(error, "Attach the file again and retry."); + throw new PreviewResolutionError({ + cause: error, + fallbackMessage: "Attach the file again and retry.", + }); }); } // Refresh expired URLs before handing them to Quick Look or ACTION_VIEW, which retain them. @@ -52,10 +58,11 @@ async function resolvePreviewUri( return value; }) .catch((error: unknown) => { - throw new PreviewResolutionError( - error, - "Reconnect to this environment and try again. The file may have been moved or deleted.", - ); + throw new PreviewResolutionError({ + cause: error, + fallbackMessage: + "Reconnect to this environment and try again. The file may have been moved or deleted.", + }); }); return { uri: url + (item.srcFragment ?? "") }; } @@ -99,9 +106,9 @@ function ResolvedFilePreview(props: { if (progressiveGallery && index !== selectedIndex) return settle(index, null); controller.abort(); onResolutionError( - error instanceof PreviewResolutionError + isPreviewResolutionError(error) ? error - : new PreviewResolutionError(error, "Try again."), + : new PreviewResolutionError({ cause: error, fallbackMessage: "Try again." }), ); }, ); diff --git a/apps/mobile/src/features/cloud/dpop.ts b/apps/mobile/src/features/cloud/dpop.ts index b3eaf006f3d34..b427861b1e36a 100644 --- a/apps/mobile/src/features/cloud/dpop.ts +++ b/apps/mobile/src/features/cloud/dpop.ts @@ -1,6 +1,5 @@ import * as Digest from "effect/crypto/Digest"; import * as SecureRandom from "effect/crypto/SecureRandom"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; import * as Hex from "effect/encoding/Hex"; @@ -13,10 +12,10 @@ import { DpopProof } from "@t3tools/client-runtime/relay"; import { DpopPublicJwk } from "@t3tools/shared/dpopCommon"; import * as Layer from "effect/Layer"; -export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} +export class CloudDpopError extends Schema.TaggedError()("CloudDpopError", { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) {} function cloudDpopError(message: string) { return (cause: unknown) => new CloudDpopError({ message, cause }); diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.ts index 3aef69252932f..f072f5c96d83d 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.ts @@ -1,4 +1,3 @@ -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { HttpClient } from "effect/http"; @@ -26,11 +25,14 @@ function readRelayUrl(): string | null { return resolveCloudPublicConfig().relay.url; } -export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{ - readonly message: string; - readonly cause?: unknown; - readonly traceId?: string; -}> {} +export class CloudEnvironmentLinkError extends Schema.TaggedError()( + "CloudEnvironmentLinkError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + traceId: Schema.optional(Schema.String), + }, +) {} const isEnvironmentCloudApiError = Schema.is( Schema.Union([ diff --git a/apps/mobile/src/features/files/ZipArchiveView.tsx b/apps/mobile/src/features/files/ZipArchiveView.tsx index d36506a70e63f..66290e9d6c381 100644 --- a/apps/mobile/src/features/files/ZipArchiveView.tsx +++ b/apps/mobile/src/features/files/ZipArchiveView.tsx @@ -12,6 +12,7 @@ import { hostPreviewMimeTypeFromExtension, } from "@t3tools/shared/filePreview"; import { LegendList } from "@legendapp/list/react-native"; +import * as Schema from "effect/Schema"; import { fetch } from "expo/fetch"; import { File } from "expo-file-system"; import { useNavigation, usePreventRemove } from "@react-navigation/native"; @@ -68,11 +69,12 @@ interface ZipArchive { readonly fileCount: number; } -interface ZipFailure { - readonly title: string; - readonly detail: string; - readonly retry: boolean; -} +const ZipFailure = Schema.Struct({ + title: Schema.String, + detail: Schema.String, + retry: Schema.Boolean, +}); +type ZipFailure = typeof ZipFailure.Type; const SAVE_ZIP_HINT = "Save the ZIP to open it in another app."; const TOO_LARGE: ZipFailure = { @@ -91,12 +93,16 @@ const NETWORK: ZipFailure = { retry: true, }; -class ZipFailureError extends Error { - constructor(readonly failure: ZipFailure) { - super(failure.title); +class ZipFailureError extends Schema.TaggedError()("ZipFailureError", { + failure: ZipFailure, +}) { + override get message(): string { + return this.failure.title; } } +const isZipFailureError = Schema.is(ZipFailureError); + function errorMessage(cause: unknown, fallback: string) { return cause instanceof Error ? cause.message : fallback; } @@ -113,7 +119,7 @@ async function readArchiveBody( const { value, done } = await reader.read(); if (done) break; size += value.byteLength; - if (size > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE); + if (size > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE }); chunks.push(value); onProgress(size); } @@ -135,9 +141,11 @@ async function openArchive(bytes: ArrayBuffer): Promise { files = await boundedZip(bytes); } catch (cause) { throw new ZipFailureError({ - title: "Couldn't browse this ZIP", - detail: `${errorMessage(cause, "It may be incomplete or damaged.")} ${SAVE_ZIP_HINT}`, - retry: false, + failure: { + title: "Couldn't browse this ZIP", + detail: `${errorMessage(cause, "It may be incomplete or damaged.")} ${SAVE_ZIP_HINT}`, + retry: false, + }, }); } const entries = [...files].map(([path, file]): ZipEntry => { @@ -187,15 +195,15 @@ function useZipArchive(input: { // oxlint-disable-next-line react/set-state-in-effect -- A new archive load resets its progress. setState({ status: "loading", receivedBytes: 0, timeLeft: null }); void (async () => { - if (sizeBytes > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE); + if (sizeBytes > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE }); if (isLocal) { const file = new File(uri); - if ((file.size ?? 0) > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE); + if ((file.size ?? 0) > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE }); return openArchive(await file.arrayBuffer()); } const url = (await refresh()) ?? uri; const response = await fetch(url, { signal: abort.signal }); - if (!response.ok || !response.body) throw new ZipFailureError(NETWORK); + if (!response.ok || !response.body) throw new ZipFailureError({ failure: NETWORK }); const bytes = await readArchiveBody(response.body, (receivedBytes) => setState({ status: "loading", @@ -217,7 +225,7 @@ function useZipArchive(input: { if (!abort.signal.aborted) setState({ status: "failed", - failure: cause instanceof ZipFailureError ? cause.failure : NETWORK, + failure: isZipFailureError(cause) ? cause.failure : NETWORK, }); }); return () => abort.abort(); diff --git a/apps/mobile/src/features/files/sourceHighlightingState.ts b/apps/mobile/src/features/files/sourceHighlightingState.ts index 2a2db842ec4be..5dcc5eff50511 100644 --- a/apps/mobile/src/features/files/sourceHighlightingState.ts +++ b/apps/mobile/src/features/files/sourceHighlightingState.ts @@ -1,5 +1,6 @@ import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; import { Atom } from "effect/reactivity"; import { resolveHighlightLanguage } from "../../lib/highlightLanguage"; @@ -15,9 +16,10 @@ export interface SourceHighlightInput { class SourceHighlightCacheKey extends Data.Class {} -class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{ - readonly cause: unknown; -}> {} +class SourceHighlightError extends Schema.TaggedError()( + "SourceHighlightError", + { cause: Schema.Defect() }, +) {} // Highlighting is synchronous, so a cold atom resolves on its first read. The // family keeps results for files the user moves between. diff --git a/apps/mobile/src/features/threads/McpAppWebView.tsx b/apps/mobile/src/features/threads/McpAppWebView.tsx index 473177f706849..39c69ca0bebd6 100644 --- a/apps/mobile/src/features/threads/McpAppWebView.tsx +++ b/apps/mobile/src/features/threads/McpAppWebView.tsx @@ -69,9 +69,10 @@ const commandFailure = (result: { readonly cause: Parameters[0]["cause"]; }) => { const error = squashAtomCommandFailure(result); - return new McpAppHostRefusal( - error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.", - ); + return new McpAppHostRefusal({ + message: + error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.", + }); }; const confirm = (title: string, message: string, action: string) => @@ -320,7 +321,8 @@ export function ThreadMcpApp(props: { const { environmentId, input } = scope(); const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } }); if (info._tag !== "Success") throw commandFailure(info); - if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool."); + if (!info.value.callable) + throw new McpAppHostRefusal({ message: "This app cannot call that tool." }); if ( !info.value.readOnly && !(await confirm( @@ -329,7 +331,7 @@ export function ThreadMcpApp(props: { "Allow", )) ) { - throw new McpAppHostRefusal("Declined by the user."); + throw new McpAppHostRefusal({ message: "Declined by the user." }); } const result = await latest.current.callTool({ environmentId, @@ -350,15 +352,15 @@ export function ThreadMcpApp(props: { openLink: async (url) => { // WebViews cannot prove user activation; confirm links to prevent timer-driven navigation out of T3. if (!(await confirm(`Open a link from ${app.server}?`, url, "Open"))) { - throw new McpAppHostRefusal("Declined by the user."); + throw new McpAppHostRefusal({ message: "Declined by the user." }); } if (!(await tryOpenExternalUrl(url, "mcp-app"))) { - throw new McpAppHostRefusal("The link could not be opened."); + throw new McpAppHostRefusal({ message: "The link could not be opened." }); } }, sendMessage: async (text) => { if (!(await confirm(`Send this message from ${app.server}?`, text, "Send"))) { - throw new McpAppHostRefusal("Declined by the user."); + throw new McpAppHostRefusal({ message: "Declined by the user." }); } await enqueueThreadOutboxMessage({ environmentId: latest.current.props.environmentId, @@ -422,7 +424,7 @@ export function ThreadMcpApp(props: { downloadFile: async (files) => { const names = files.map((file) => file.name).join(", "); if (!(await confirm(`Save a file from ${app.server}?`, names, "Save"))) { - throw new McpAppHostRefusal("Declined by the user."); + throw new McpAppHostRefusal({ message: "Declined by the user." }); } for (const file of files) { let bytes: Uint8Array | undefined; @@ -441,16 +443,18 @@ export function ThreadMcpApp(props: { const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType; if (typeof declared === "string") mimeType = declared; } - if (bytes === undefined) throw new McpAppHostRefusal(`${file.name} has no contents.`); + if (bytes === undefined) + throw new McpAppHostRefusal({ message: `${file.name} has no contents.` }); if (bytes.byteLength > MAX_DOWNLOAD_BYTES) { - throw new McpAppHostRefusal(`${file.name} is too large to save.`); + throw new McpAppHostRefusal({ message: `${file.name} is too large to save.` }); } const shared = await shareGeneratedAttachment({ bytes, attachment: { name: file.name, mimeType }, signal: new AbortController().signal, }); - if (!shared) throw new McpAppHostRefusal("Sharing is not available on this device."); + if (!shared) + throw new McpAppHostRefusal({ message: "Sharing is not available on this device." }); } }, onRequestTeardown: () => { diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx index 04005284750b7..d510bc536e285 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx @@ -1,8 +1,8 @@ import { useAtomValue } from "@effect/atom-react"; import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets"; import type { AssetResource, EnvironmentId } from "@t3tools/contracts"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; import { AsyncResult, Atom } from "effect/reactivity"; import { Image } from "expo-image"; import { createContext, useContext, useId, useState } from "react"; @@ -33,7 +33,9 @@ export const MarkdownImageAvailableWidthContext = createContext(0); type ImageSize = { readonly width: number; readonly height: number }; -class SvgLoadError extends Data.TaggedError("SvgLoadError")<{ readonly cause: unknown }> {} +class SvgLoadError extends Schema.TaggedError()("SvgLoadError", { + cause: Schema.Defect(), +}) {} async function readSvgXml(uri: string, signal: AbortSignal): Promise { if (uri.startsWith("data:image/svg+xml")) { diff --git a/apps/mobile/src/native/voiceTranscription.android.ts b/apps/mobile/src/native/voiceTranscription.android.ts index 13e233d0cccfa..3749b6d2a9726 100644 --- a/apps/mobile/src/native/voiceTranscription.android.ts +++ b/apps/mobile/src/native/voiceTranscription.android.ts @@ -73,14 +73,15 @@ async function runOperation( throwIfVoiceTranscriptionAborted(signal); const code = typeof error === "object" && error !== null && "code" in error ? error.code : undefined; - throw new VoiceTranscriptionError( - code === "unavailable" || code === "unsupported-locale" ? code : fallbackCode, - (typeof code === "string" ? nativeErrorMessages[code] : undefined) ?? + throw new VoiceTranscriptionError({ + code: code === "unavailable" || code === "unsupported-locale" ? code : fallbackCode, + message: + (typeof code === "string" ? nativeErrorMessages[code] : undefined) ?? (fallbackCode === "preparation-failed" ? "Voice transcription could not prepare this language. Check Google speech services and try again." : "Voice transcription failed."), - { cause: error }, - ); + cause: error, + }); } finally { signal.removeEventListener("abort", abort); await cancellation; diff --git a/apps/mobile/src/native/voiceTranscription.ios.ts b/apps/mobile/src/native/voiceTranscription.ios.ts index 9f9556645101d..5fc6c9a0b8a2b 100644 --- a/apps/mobile/src/native/voiceTranscription.ios.ts +++ b/apps/mobile/src/native/voiceTranscription.ios.ts @@ -1,3 +1,4 @@ +import * as Schema from "effect/Schema"; import AppleTranscription from "@react-native-ai/apple/src/NativeAppleTranscription"; import { File } from "expo-file-system"; @@ -9,6 +10,8 @@ import { type VoiceTranscriptionOptions, } from "@t3tools/client-runtime/voice-input"; +const isVoiceTranscriptionError = Schema.is(VoiceTranscriptionError); + function getDeviceLocale(): string { return Intl.DateTimeFormat().resolvedOptions().locale; } @@ -18,11 +21,11 @@ function wrapError( message: string, cause: unknown, ): VoiceTranscriptionError { - if (cause instanceof VoiceTranscriptionError) { + if (isVoiceTranscriptionError(cause)) { return cause; } - return new VoiceTranscriptionError(code, message, { cause }); + return new VoiceTranscriptionError({ code, message, cause }); } function getNativeErrorCode(error: unknown): string | undefined { @@ -45,10 +48,10 @@ async function prepareVoiceTranscription( ): Promise { throwIfVoiceTranscriptionAborted(signal); if (!AppleTranscription.isAvailable(locale)) { - throw new VoiceTranscriptionError( - "unavailable", - "Voice transcription requires a supported device with iOS 26 or later.", - ); + throw new VoiceTranscriptionError({ + code: "unavailable", + message: "Voice transcription requires a supported device with iOS 26 or later.", + }); } try { @@ -61,11 +64,11 @@ async function prepareVoiceTranscription( } catch (error) { throwIfVoiceTranscriptionAborted(signal); if (getNativeErrorCode(error) === "AppleTranscriptionUnsupportedLocale") { - throw new VoiceTranscriptionError( - "unsupported-locale", - "Voice transcription does not support this device language.", - { cause: error }, - ); + throw new VoiceTranscriptionError({ + code: "unsupported-locale", + message: "Voice transcription does not support this device language.", + cause: error, + }); } throw wrapError( diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.ts index 663eaeaf726a0..c860f652c4fe4 100644 --- a/apps/server/src/device/DeviceService.ts +++ b/apps/server/src/device/DeviceService.ts @@ -81,11 +81,13 @@ import * as LocalDeviceHost from "./LocalDeviceHost.ts"; export const DEVICE_HUB_ROUTE_PREFIX = "/api/device-hub"; +const isSshCommandError = Schema.is(SshCommandError); + const sshProbeFailureMessage = (error: DeviceHost.DeviceHostError): string => { const windows = SshDeviceHost.isSshWindowsHostError(error.cause) ? error.cause : null; const cause = windows ? windows.cause : error.cause; if ( - !(cause instanceof SshCommandError) || + !isSshCommandError(cause) || cause.exitCode === null || cause.exitCode < 1 || (cause.exitCode > 254 && cause.exitCode !== 9009) diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.ts index 8d17d4d3f3a2d..2dd9b21f290bb 100644 --- a/apps/server/src/device/SshDeviceHost.ts +++ b/apps/server/src/device/SshDeviceHost.ts @@ -90,6 +90,8 @@ const bootstrap = ( ), ); +const isSshCommandError = Schema.is(SshCommandError); + // cmd expands only %OS% and PowerShell only $env:OS; POSIX shells expand neither to Windows_NT. const explainWindowsHost = Effect.fn("SshDeviceHost.explainWindowsHost")(function* ( config: SshDeviceHostConfig, @@ -98,7 +100,7 @@ const explainWindowsHost = Effect.fn("SshDeviceHost.explainWindowsHost")(functio const cause = error.cause; // Windows ssh.exe preserves full remote exit statuses such as 9009. if ( - !(cause instanceof SshCommandError) || + !isSshCommandError(cause) || cause.exitCode === null || cause.exitCode < 1 || (cause.exitCode > 254 && cause.exitCode !== 9009) diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index d1f7ab740e241..1427035404722 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -8,7 +8,6 @@ import { isDevProxiedPath } from "@t3tools/shared/devProxy"; import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp"; import { decodeOtlpTraceRecords } from "@t3tools/shared/observability"; import * as ByteSize from "effect/ByteSize"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -327,9 +326,10 @@ export const layerServerEnvironmentHttpApi = HttpApiBuilder.group( }), ); -class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{ - readonly cause: unknown; -}> {} +class DecodeOtlpTraceRecordsError extends Schema.TaggedError()( + "DecodeOtlpTraceRecordsError", + { cause: Schema.Defect() }, +) {} // Tracing once-per-second renderer exports would create more spans than it forwards. export const layerOtlpTracesProxyRoute = HttpRouter.add( diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.ts index d84873082c68c..4f12497be5d12 100644 --- a/apps/server/src/mcp/AcpMcpStdioBridge.ts +++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts @@ -5,22 +5,28 @@ import * as NodeReadline from "node:readline"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; import * as Fiber from "effect/Fiber"; +import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpResponsePayloads"; /** ACP mandates stdio MCP support; HTTP/SSE support varies. */ -export class AcpMcpBridgeError extends Error { - readonly _tag = "AcpMcpBridgeError"; -} +export class AcpMcpBridgeError extends Schema.TaggedError()( + "AcpMcpBridgeError", + { message: Schema.String, cause: Schema.optional(Schema.Defect()) }, +) {} + +const isAcpMcpBridgeError = Schema.is(AcpMcpBridgeError); const bridgeError = (cause: unknown): AcpMcpBridgeError => - cause instanceof AcpMcpBridgeError + isAcpMcpBridgeError(cause) ? cause - : new AcpMcpBridgeError(cause instanceof Error ? cause.message : String(cause), { cause }); + : new AcpMcpBridgeError({ + message: cause instanceof Error ? cause.message : String(cause), + cause, + }); const decodeJsonLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); @@ -104,9 +110,9 @@ export const mcpToolSession = ( sessionId = response.headers.get("mcp-session-id") ?? sessionId; if (!response.ok) { yield* discardResponseBody(response); - return yield* Effect.fail( - new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`), - ); + return yield* new AcpMcpBridgeError({ + message: `T3 Code MCP endpoint responded with HTTP ${response.status}.`, + }); } const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError)); for (const payload of payloads) { @@ -123,11 +129,9 @@ export const mcpToolSession = ( const responses = yield* send({ jsonrpc: "2.0", id, method, params }); const envelope = asEnvelope(responses.find((entry) => asEnvelope(entry)?.id === id)); if (envelope === null || envelope.error !== undefined) { - return yield* Effect.fail( - new AcpMcpBridgeError( - `T3 Code MCP ${method} failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`, - ), - ); + return yield* new AcpMcpBridgeError({ + message: `T3 Code MCP ${method} failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`, + }); } return envelope; }); diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts index 5415998619c03..3bba05f7db63a 100644 --- a/apps/server/src/orchestration-v2/http.ts +++ b/apps/server/src/orchestration-v2/http.ts @@ -35,6 +35,8 @@ import { loadSubscriberShellSnapshot } from "./ShellStream.ts"; import { boundedSnapshotResponseFields } from "./ThreadStream.ts"; import { projectThreadProjectionForWire } from "./WireProjection.ts"; +const isInvalidThreadHistoryCursorError = Schema.is(InvalidThreadHistoryCursorError); + const isThreadTranscriptTooLargeError = Schema.is( ThreadManagementService.ThreadTranscriptTooLargeError, ); @@ -249,7 +251,7 @@ export const layer = HttpApiBuilder.group( const decoded = Result.try(() => decodeThreadHistoryCursor(args.query.cursor)); if (Result.isFailure(decoded)) { const cause = decoded.failure; - if (cause instanceof InvalidThreadHistoryCursorError) + if (isInvalidThreadHistoryCursorError(cause)) return yield* failEnvironmentInvalidRequest("invalid_history_cursor"); return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause); } diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.ts index d226d21e3248c..abfaf0ade693b 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts @@ -5,6 +5,7 @@ import type { ThreadId, TurnItemId, } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; /** * Every window stops at the byte budget. A window that holds a user turn also @@ -84,11 +85,12 @@ export type BoundedProjectionResult = { readonly latestLocalTurnOrdinal: number | null; }; -export class InvalidThreadHistoryCursorError extends Error { - readonly _tag = "InvalidThreadHistoryCursorError"; - constructor(message = "Invalid thread history cursor.") { - super(message); - this.name = "InvalidThreadHistoryCursorError"; +export class InvalidThreadHistoryCursorError extends Schema.TaggedError()( + "InvalidThreadHistoryCursorError", + {}, +) { + override get message(): string { + return "Invalid thread history cursor."; } } diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 913f6dc639459..6b92e33ce960f 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -1223,22 +1223,23 @@ const make = Effect.gen(function* () { const uploadFiles = async (tab: ServerTab, input: PreviewAutomationUploadInput) => { const relative = input.paths.find((path) => !NodePath.isAbsolute(path)); if (relative !== undefined) - throw new ServerBrowserPage.ServerBrowserOperationError( - "PreviewAutomationExecutionError", - `Upload paths must be absolute: ${relative}`, - ); + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: "PreviewAutomationExecutionError", + message: `Upload paths must be absolute: ${relative}`, + }); if (await ServerBrowserPage.setInputFiles(tab.page, input)) return undefined; const open = tab.fileChooser; if (!open) - throw new ServerBrowserPage.ServerBrowserOperationError( - "PreviewAutomationExecutionError", - "No file picker is open. Click the page's upload control first, or pass the file input's locator.", - ); + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: "PreviewAutomationExecutionError", + message: + "No file picker is open. Click the page's upload control first, or pass the file input's locator.", + }); if (input.paths.length > 1 && !open.chooser.isMultiple()) - throw new ServerBrowserPage.ServerBrowserOperationError( - "PreviewAutomationExecutionError", - "This file picker accepts one file.", - ); + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: "PreviewAutomationExecutionError", + message: "This file picker accepts one file.", + }); if (input.paths.length > 0) await open.chooser.setFiles([...input.paths], { timeout: input.timeoutMs ?? NAVIGATION_TIMEOUT_MS, @@ -1418,10 +1419,10 @@ const make = Effect.gen(function* () { const assertTabCapacity = (agentSessionId: string) => { if (atTabLimit(agentSessionId)) - throw new BrowserControlInterrupted( - `Too many server browser tabs are open (${AGENT_TAB_LIMIT} per agent session, ${SERVER_TAB_LIMIT} per server). Close one with t3_preview_close or reuse one from preview_status tabs.`, - "tabLimit", - ); + throw new BrowserControlInterrupted({ + message: `Too many server browser tabs are open (${AGENT_TAB_LIMIT} per agent session, ${SERVER_TAB_LIMIT} per server). Close one with t3_preview_close or reuse one from preview_status tabs.`, + reason: "tabLimit", + }); }; // The desktop draws its tabs in its own webview, so they never get a streamed viewer. @@ -1591,12 +1592,12 @@ const make = Effect.gen(function* () { findBrowserProfile(profiles, requested) ?? profiles.find((profile) => profile.name.toLowerCase() === wanted); if (match) return match.id; - throw new ServerBrowserPage.ServerBrowserOperationError( - "PreviewAutomationUnknownProfileError", - `No browser profile is named "${requested}". Use one of: ${profiles + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: "PreviewAutomationUnknownProfileError", + message: `No browser profile is named "${requested}". Use one of: ${profiles .map((profile) => `${profile.name} (id ${profile.id})`) .join(", ")}.`, - ); + }); }; const statusWithTitle = async ( @@ -1692,16 +1693,16 @@ const make = Effect.gen(function* () { await navigation.catch((cause: unknown) => { const message = cause instanceof Error ? cause.message : String(cause); if (message.includes("Download is starting")) { - throw new ServerBrowserPage.ServerBrowserOperationError( - "PreviewAutomationExecutionError", - `${url} is a file this browser cannot show, so it was downloaded instead. preview_status lists it under downloads.`, - ); + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: "PreviewAutomationExecutionError", + message: `${url} is a file this browser cannot show, so it was downloaded instead. preview_status lists it under downloads.`, + }); } if (/ERR_[A-Z_]+/.test(message)) { - throw new ServerBrowserPage.ServerBrowserOperationError( - "PreviewAutomationExecutionError", - `Navigation to ${url} failed: ${ServerBrowserPage.parseNetError(message).description}`, - ); + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: "PreviewAutomationExecutionError", + message: `Navigation to ${url} failed: ${ServerBrowserPage.parseNetError(message).description}`, + }); } throw ServerBrowserPage.toOperationError(cause, timeout); }); @@ -1804,10 +1805,10 @@ const make = Effect.gen(function* () { withCaptureLock(tab, async () => { const recording = tab.recording; if (!recording) { - throw new ServerBrowserPage.ServerBrowserOperationError( - "PreviewAutomationRecordingNotActiveError", - "No recording is active for this tab.", - ); + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: "PreviewAutomationRecordingNotActiveError", + message: "No recording is active for this tab.", + }); } let mimeType: string | null; const chunks: Array = []; @@ -1821,10 +1822,10 @@ const make = Effect.gen(function* () { mimeType = stopped.mimeType; // Checked before the transfer so an oversized video never lands in this process. if (stopped.bytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) { - throw new ServerBrowserPage.ServerBrowserOperationError( - "PreviewAutomationRecordingTooLargeError", - "The recording is larger than the attachment limit.", - ); + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: "PreviewAutomationRecordingTooLargeError", + message: "The recording is larger than the attachment limit.", + }); } for (let index = 0; index < stopped.count; index += 1) { const chunk = await recording.encoder.evaluate( @@ -1839,10 +1840,10 @@ const make = Effect.gen(function* () { } const data = Buffer.concat(chunks); if (!mimeType || data.byteLength === 0) { - throw new ServerBrowserPage.ServerBrowserOperationError( - "PreviewAutomationExecutionError", - "The recording captured no frames.", - ); + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: "PreviewAutomationExecutionError", + message: "The recording captured no frames.", + }); } const extension = mimeType.startsWith("video/mp4") ? "mp4" : "webm"; @@ -1921,15 +1922,18 @@ const make = Effect.gen(function* () { const requireTab = async (request: PreviewAutomationRequest) => { if (!request.agentSessionId) - throw new BrowserControlInterrupted("The agent session is missing. Reconnect the provider."); + throw new BrowserControlInterrupted({ + message: "The agent session is missing. Reconnect the provider.", + }); const owned = [...tabs.values()].filter( (tab) => tab.threadId === request.threadId && tab.control.agentId === request.agentSessionId, ); if (!request.tabIdExplicit && owned.length > 1) - throw new BrowserControlInterrupted( - "Multiple tabs belong to this agent session. Pass a tabId from preview_open or preview_status tabs.", - "tabRequired", - ); + throw new BrowserControlInterrupted({ + message: + "Multiple tabs belong to this agent session. Pass a tabId from preview_open or preview_status tabs.", + reason: "tabRequired", + }); const tab = request.tabId === undefined ? latestThreadTab(request.threadId, request.agentSessionId) @@ -1937,16 +1941,17 @@ const make = Effect.gen(function* () { findTab(request.threadId, request.tabId).pipe(Effect.orElseSucceed(constVoid)), ); if (!tab) { - throw new ServerBrowserPage.ServerBrowserOperationError( - "PreviewAutomationTabNotFoundError", - "No server preview tab is open for this thread. Call preview_open first.", - ); + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: "PreviewAutomationTabNotFoundError", + message: "No server preview tab is open for this thread. Call preview_open first.", + }); } if (!READ_OPERATIONS.has(request.operation) && !tab.control.agentMayAct(request.agentSessionId)) - throw new BrowserControlInterrupted( - "This tab belongs to another agent session. You can read it, but open your own tab to act.", - "agentMismatch", - ); + throw new BrowserControlInterrupted({ + message: + "This tab belongs to another agent session. You can read it, but open your own tab to act.", + reason: "agentMismatch", + }); return tab; }; @@ -1976,9 +1981,9 @@ const make = Effect.gen(function* () { ); case "open": { if (!request.agentSessionId) - throw new BrowserControlInterrupted( - "The agent session is missing. Reconnect the provider.", - ); + throw new BrowserControlInterrupted({ + message: "The agent session is missing. Reconnect the provider.", + }); const open = input as PreviewAutomationOpenInput; const url = open.url === undefined ? undefined : normalizePreviewUrl(open.url); const reuse = open.reuseExistingTab ?? true; @@ -1990,10 +1995,10 @@ const make = Effect.gen(function* () { tab.threadId === request.threadId && tab.control.agentId === request.agentSessionId, ).length > 1 ) - throw new BrowserControlInterrupted( - "Multiple tabs are open. Pass tabId or reuseExistingTab=false.", - "tabRequired", - ); + throw new BrowserControlInterrupted({ + message: "Multiple tabs are open. Pass tabId or reuseExistingTab=false.", + reason: "tabRequired", + }); const found = reuse && request.tabId !== undefined @@ -2012,12 +2017,12 @@ const make = Effect.gen(function* () { const desktop = sessions.some( (session) => session.tabId === request.tabId && session.runtime !== "server", ); - throw new ServerBrowserPage.ServerBrowserOperationError( - desktop ? "PreviewAutomationExecutionError" : "PreviewAutomationTabNotFoundError", - desktop + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: desktop ? "PreviewAutomationExecutionError" : "PreviewAutomationTabNotFoundError", + message: desktop ? "This tab belongs to the desktop runtime. This environment's server browser cannot control desktop tabs. Omit tabId to open a server tab instead." : "The requested server preview tab does not exist.", - ); + }); } // Reusing another session's tab requires explicit tabId; reading it grants no implicit takeover. const existing = @@ -2043,18 +2048,20 @@ const make = Effect.gen(function* () { ), )); if (existing?.dialog) - throw new BrowserControlInterrupted( - "A browser dialog is pending. Read preview_status and use preview_dialog first.", - "dialogPending", - ); + throw new BrowserControlInterrupted({ + message: + "A browser dialog is pending. Read preview_status and use preview_dialog first.", + reason: "dialogPending", + }); return tab.control.agent( request.agentSessionId, async () => { if (tab.dialog) - throw new BrowserControlInterrupted( - "A browser dialog is pending. Read preview_status and use preview_dialog first.", - "dialogPending", - ); + throw new BrowserControlInterrupted({ + message: + "A browser dialog is pending. Read preview_status and use preview_dialog first.", + reason: "dialogPending", + }); if (existing) { if (url) await navigate(tab, url, "load", navigationTimeout); } else { @@ -2098,10 +2105,11 @@ const make = Effect.gen(function* () { candidate.control.agentId === request.agentSessionId, ).length > 1 ) - throw new BrowserControlInterrupted( - "Multiple tabs belong to this agent session. Pass a tabId from preview_open or preview_status tabs.", - "tabRequired", - ); + throw new BrowserControlInterrupted({ + message: + "Multiple tabs belong to this agent session. Pass a tabId from preview_open or preview_status tabs.", + reason: "tabRequired", + }); const recordings = [...tabs.values()].filter( (candidate) => candidate.threadId === request.threadId && @@ -2114,10 +2122,10 @@ const make = Effect.gen(function* () { recordings.find((candidate) => candidate.tabId === targetTabId) ?? (!request.tabIdExplicit && recordings.length === 1 ? recordings[0] : undefined); if (!tab) { - throw new ServerBrowserPage.ServerBrowserOperationError( - "PreviewAutomationRecordingNotActiveError", - "No recording is active for this thread.", - ); + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: "PreviewAutomationRecordingNotActiveError", + message: "No recording is active for this thread.", + }); } // A stop cannot act twice (a retry finds no recording); // dropping a late one would leave capture running. @@ -2128,12 +2136,15 @@ const make = Effect.gen(function* () { // Closing must unblock an action waiting on a dialog, without queueing behind it. if (request.operation === "close") { if (tab.control.agentId !== request.agentSessionId) - throw new BrowserControlInterrupted( - "Only the agent session that opened this tab can close it.", - "agentMismatch", - ); + throw new BrowserControlInterrupted({ + message: "Only the agent session that opened this tab can close it.", + reason: "agentMismatch", + }); if (tab.control.controller !== null) - throw new BrowserControlInterrupted("A human controls this tab.", "humanControl"); + throw new BrowserControlInterrupted({ + message: "A human controls this tab.", + reason: "humanControl", + }); void tab.control.close().catch(constVoid); await runPromise(manager.close({ threadId: tab.threadId, tabId: tab.tabId })); dropTab(tab, false); @@ -2142,7 +2153,10 @@ const make = Effect.gen(function* () { // Resolve dialogs outside the queue, with ownership checked, to unblock waiting clicks. if (request.operation === "dialog") { if (tab.control.controller !== null) - throw new BrowserControlInterrupted("A human controls this tab.", "humanControl"); + throw new BrowserControlInterrupted({ + message: "A human controls this tab.", + reason: "humanControl", + }); await resolveDialog(tab, input as PreviewAutomationDialogInput); return statusWithTitle(tab, request.agentSessionId); } @@ -2155,10 +2169,10 @@ const make = Effect.gen(function* () { ) { return tab.control.observe(async () => { if (tab.dialog) - throw new BrowserControlInterrupted( - "A browser dialog is pending. Read preview_status.", - "dialogPending", - ); + throw new BrowserControlInterrupted({ + message: "A browser dialog is pending. Read preview_status.", + reason: "dialogPending", + }); return executeTabOperation(tab, request); }); } @@ -2166,10 +2180,11 @@ const make = Effect.gen(function* () { agentSessionId, async () => { if (tab.dialog) - throw new BrowserControlInterrupted( - "A browser dialog is pending. Read preview_status and use preview_dialog first.", - "dialogPending", - ); + throw new BrowserControlInterrupted({ + message: + "A browser dialog is pending. Read preview_status and use preview_dialog first.", + reason: "dialogPending", + }); const generation = tab.control.generation; tab.agentOperating = !READ_OPERATIONS.has(request.operation); updateFileChooserInterception(tab); diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index f128bf445e603..622482cd1b86f 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -19,56 +19,69 @@ import { type PreviewAutomationWaitForInput, } from "@t3tools/contracts"; import { constVoid } from "effect/Function"; +import * as Schema from "effect/Schema"; import type { CDPSession, ConsoleMessage, Frame, Locator, Page } from "playwright-core"; import * as NodeCrypto from "node:crypto"; import { BrowserControlInterrupted } from "./SessionControl.ts"; +const isBrowserControlInterrupted = Schema.is(BrowserControlInterrupted); + const MAX_EVALUATION_BYTES = 64_000; const MAX_VISIBLE_TEXT_LENGTH = 20_000; const MAX_SCREENSHOT_WIDTH = 1280; const WAIT_POLL_MS = 100; export const DIAGNOSTIC_BUFFER_LIMIT = 200; -export class ServerBrowserOperationError extends Error { - readonly tag: string; - readonly detail: unknown; +export class ServerBrowserOperationError extends Schema.TaggedError()( + "ServerBrowserOperationError", + { + tag: Schema.String, + message: Schema.String, + detail: Schema.optional(Schema.Unknown), + cause: Schema.optional(Schema.Defect()), + }, +) {} - constructor(tag: string, message: string, detail?: unknown, options?: ErrorOptions) { - super(message, options); - this.tag = tag; - this.detail = detail; - } -} +const isServerBrowserOperationError = Schema.is(ServerBrowserOperationError); export const toOperationError = ( cause: unknown, timeoutMs?: number, ): ServerBrowserOperationError => { - if (cause instanceof BrowserControlInterrupted) - return new ServerBrowserOperationError( - "PreviewAutomationControlInterruptedError", - cause.message, - cause.reason, - ); - if (cause instanceof ServerBrowserOperationError) return cause; + if (isBrowserControlInterrupted(cause)) + return new ServerBrowserOperationError({ + tag: "PreviewAutomationControlInterruptedError", + message: cause.message, + detail: cause.reason, + }); + if (isServerBrowserOperationError(cause)) return cause; const message = cause instanceof Error ? cause.message : String(cause); const firstLine = message.split("\n")[0] ?? message; if (cause instanceof Error && cause.name === "TimeoutError") { - return new ServerBrowserOperationError( - "PreviewAutomationTimeoutError", - firstLine, - timeoutMs === undefined ? undefined : { timeoutMs }, - ); + return new ServerBrowserOperationError({ + tag: "PreviewAutomationTimeoutError", + message: firstLine, + detail: timeoutMs === undefined ? undefined : { timeoutMs }, + }); } if ( /while parsing selector|Unknown engine|Unexpected token|strict mode violation/i.test(message) ) { - return new ServerBrowserOperationError("PreviewAutomationInvalidSelectorError", firstLine); + return new ServerBrowserOperationError({ + tag: "PreviewAutomationInvalidSelectorError", + message: firstLine, + }); } if (/not an |not editable|not an editable/i.test(message)) { - return new ServerBrowserOperationError("PreviewAutomationTargetNotEditableError", firstLine); + return new ServerBrowserOperationError({ + tag: "PreviewAutomationTargetNotEditableError", + message: firstLine, + }); } - return new ServerBrowserOperationError("PreviewAutomationExecutionError", firstLine); + return new ServerBrowserOperationError({ + tag: "PreviewAutomationExecutionError", + message: firstLine, + }); }; const DEFAULT_TIMEOUT_MS = 15_000; @@ -115,11 +128,12 @@ const targetLocator = ( const ref = /^\s*aria-ref\s*=\s*(\S+)\s*$/.exec(selector)?.[1]; const nativeRef = ref === undefined ? undefined : pageRefs.get(page)?.refs.get(ref); if (nativeRef === undefined) { - throw new ServerBrowserOperationError( - "PreviewAutomationInvalidSelectorError", - "This element ref is stale or belongs to another tab. Take a fresh snapshot and use its locator.", - { staleRef: true }, - ); + throw new ServerBrowserOperationError({ + tag: "PreviewAutomationInvalidSelectorError", + message: + "This element ref is stale or belongs to another tab. Take a fresh snapshot and use its locator.", + detail: { staleRef: true }, + }); } return page.locator(`aria-ref=${nativeRef}`); } @@ -229,16 +243,17 @@ const DOTTED_SCRIPT = `(() => { })()`; const pageChanged = () => - new ServerBrowserOperationError( - "PreviewAutomationExecutionError", - "The page changed while capturing its snapshot. Take another snapshot.", - ); + new ServerBrowserOperationError({ + tag: "PreviewAutomationExecutionError", + message: "The page changed while capturing its snapshot. Take another snapshot.", + }); const tooBusy = () => - new ServerBrowserOperationError( - "PreviewAutomationTimeoutError", - "The page was too busy to capture a snapshot in time. Wait for it to settle and take another snapshot.", - ); + new ServerBrowserOperationError({ + tag: "PreviewAutomationTimeoutError", + message: + "The page was too busy to capture a snapshot in time. Wait for it to settle and take another snapshot.", + }); const VALUE_TOO_LONG = "A password field holds a value too long to hide, so no snapshot was taken."; @@ -381,7 +396,10 @@ const dottedPattern = (values: ReadonlyArray) => { pattern.test(""); pattern.test("\u2022"); } catch { - throw new ServerBrowserOperationError("PreviewAutomationExecutionError", VALUE_TOO_LONG); + throw new ServerBrowserOperationError({ + tag: "PreviewAutomationExecutionError", + message: VALUE_TOO_LONG, + }); } return pattern; }; @@ -673,12 +691,12 @@ const namedTargetTimeout = async ( : matches === 0 ? `The click may have happened and removed its target or navigated; check the page before retrying. No element matches ${target} after the timeout; take a fresh snapshot and use its locator.` : `The click may have happened; check the page before retrying. ${target} still matches an element after the timeout.`; - return new ServerBrowserOperationError( - "PreviewAutomationTimeoutError", - reason, - { reason }, - { cause }, - ); + return new ServerBrowserOperationError({ + tag: "PreviewAutomationTimeoutError", + message: reason, + detail: { reason }, + cause, + }); }; const clickTarget = async ( @@ -756,10 +774,10 @@ export const type = async (page: Page, input: PreviewAutomationTypeInput) => { { timeout }, )); if (focused !== true) { - throw new ServerBrowserOperationError( - "PreviewAutomationTargetNotEditableError", - "The target is not an enabled text field, so no text was typed.", - ); + throw new ServerBrowserOperationError({ + tag: "PreviewAutomationTargetNotEditableError", + message: "The target is not an enabled text field, so no text was typed.", + }); } if (input.clear) { await page.keyboard.press("ControlOrMeta+A"); @@ -811,10 +829,10 @@ export const select = async ( )?.value ?? entry, ); if (values === null) - throw new ServerBrowserOperationError( - "PreviewAutomationTargetNotEditableError", - "This element is not a . Click a custom dropdown, then click its option.", + }); return { selected: await locator.selectOption(values, { timeout }) }; }; @@ -872,10 +890,10 @@ export const evaluate = async ( // Stops a busy script; an awaited promise is abandoned and settles unread. void cdp.send("Runtime.terminateExecution").catch(constVoid); reject( - new ServerBrowserOperationError( - "PreviewAutomationTimeoutError", - `Evaluation did not finish within ${timeoutMs}ms and was stopped.`, - ), + new ServerBrowserOperationError({ + tag: "PreviewAutomationTimeoutError", + message: `Evaluation did not finish within ${timeoutMs}ms and was stopped.`, + }), ); }, timeoutMs); }); @@ -887,20 +905,20 @@ export const evaluate = async ( void evaluation.catch(constVoid); const result = await Promise.race([evaluation, expired]).finally(() => clearTimeout(timer)); if (result.exceptionDetails) { - throw new ServerBrowserOperationError( - "PreviewAutomationExecutionError", - result.exceptionDetails.exception?.description ?? result.exceptionDetails.text, - ); + throw new ServerBrowserOperationError({ + tag: "PreviewAutomationExecutionError", + message: result.exceptionDetails.exception?.description ?? result.exceptionDetails.text, + }); } const value = "value" in result.result ? result.result.value : (result.result.description ?? null); const actualBytes = Buffer.byteLength(JSON.stringify(value ?? null), "utf8"); if (actualBytes > MAX_EVALUATION_BYTES) { - throw new ServerBrowserOperationError( - "PreviewAutomationResultTooLargeError", - `Evaluation result is ${actualBytes} bytes; the limit is ${MAX_EVALUATION_BYTES}.`, - { maximumBytes: MAX_EVALUATION_BYTES }, - ); + throw new ServerBrowserOperationError({ + tag: "PreviewAutomationResultTooLargeError", + message: `Evaluation result is ${actualBytes} bytes; the limit is ${MAX_EVALUATION_BYTES}.`, + detail: { maximumBytes: MAX_EVALUATION_BYTES }, + }); } return value; }; @@ -926,10 +944,10 @@ export const waitFor = async (page: Page, input: PreviewAutomationWaitForInput) const results = await Promise.all(checks.map((check) => check())); if (results.every(Boolean)) return; if (Date.now() >= deadline) { - throw new ServerBrowserOperationError( - "PreviewAutomationTimeoutError", - `Waited ${timeoutMs}ms without every condition holding.`, - ); + throw new ServerBrowserOperationError({ + tag: "PreviewAutomationTimeoutError", + message: `Waited ${timeoutMs}ms without every condition holding.`, + }); } await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS)); } diff --git a/apps/server/src/preview/SessionControl.ts b/apps/server/src/preview/SessionControl.ts index 57644e3be7135..f19f566ed30bb 100644 --- a/apps/server/src/preview/SessionControl.ts +++ b/apps/server/src/preview/SessionControl.ts @@ -1,15 +1,20 @@ -import type { PreviewAutomationControlReason } from "@t3tools/contracts"; - -export class BrowserControlInterrupted extends Error { - readonly reason: PreviewAutomationControlReason; - constructor( - message = "Browser control changed. Refresh the snapshot before trying again.", - reason: PreviewAutomationControlReason = "interrupted", - ) { - super(message); - this.reason = reason; - } -} +import { PreviewAutomationControlReason } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +export class BrowserControlInterrupted extends Schema.TaggedError()( + "BrowserControlInterrupted", + { + message: Schema.String.pipe( + Schema.withConstructorDefault( + Effect.succeed("Browser control changed. Refresh the snapshot before trying again."), + ), + ), + reason: PreviewAutomationControlReason.pipe( + Schema.withConstructorDefault(Effect.succeed("interrupted" as const)), + ), + }, +) {} const settle = (work: Promise) => work.then( @@ -69,7 +74,11 @@ export class SessionControl { } private assertOpen() { - if (this.closed) throw new BrowserControlInterrupted("This browser tab is closed.", "closed"); + if (this.closed) + throw new BrowserControlInterrupted({ + message: "This browser tab is closed.", + reason: "closed", + }); } private changeOwner(owner: string | null) { @@ -81,7 +90,8 @@ export class SessionControl { private async action(allowed: () => boolean, run: () => Promise, deadlineMs?: number) { this.assertOpen(); - if (!allowed()) throw new BrowserControlInterrupted("You do not control this browser tab."); + if (!allowed()) + throw new BrowserControlInterrupted({ message: "You do not control this browser tab." }); const epoch = this.epoch; return this.enqueue(async () => { this.assertOpen(); @@ -103,11 +113,17 @@ export class SessionControl { agent(agentId: string, run: () => Promise, deadlineMs?: number) { if (!this.agentMayAct(agentId)) return Promise.reject( - new BrowserControlInterrupted("This tab belongs to another agent.", "agentMismatch"), + new BrowserControlInterrupted({ + message: "This tab belongs to another agent.", + reason: "agentMismatch", + }), ); if (this.owner !== null) return Promise.reject( - new BrowserControlInterrupted("A human controls this tab.", "humanControl"), + new BrowserControlInterrupted({ + message: "A human controls this tab.", + reason: "humanControl", + }), ); return this.action(() => this.agentMayAct(agentId) && this.owner === null, run, deadlineMs); } @@ -164,7 +180,7 @@ export class SessionControl { async take(viewerId: string) { this.assertOpen(); if (this.owner !== null && this.owner !== viewerId) { - throw new BrowserControlInterrupted("Another viewer controls this browser tab."); + throw new BrowserControlInterrupted({ message: "Another viewer controls this browser tab." }); } if (this.owner !== viewerId) this.changeOwner(viewerId); return this.human(viewerId, async () => {}); @@ -173,9 +189,9 @@ export class SessionControl { async release(viewerId: string, afterDrain: () => Promise = async () => {}) { this.assertOpen(); if (this.owner !== viewerId) { - throw new BrowserControlInterrupted( - "Only the controlling viewer can release this browser tab.", - ); + throw new BrowserControlInterrupted({ + message: "Only the controlling viewer can release this browser tab.", + }); } this.changeOwner(null); await this.enqueue(async () => { diff --git a/apps/server/src/project/AgentSessionJson.test.ts b/apps/server/src/project/AgentSessionJson.test.ts index 515aa50b1b976..ea6f31f13c8af 100644 --- a/apps/server/src/project/AgentSessionJson.test.ts +++ b/apps/server/src/project/AgentSessionJson.test.ts @@ -48,7 +48,7 @@ describe("transcript JSON projection", () => { it("retains the import allocation and depth limits", () => { const limited = createTranscriptJsonReader( () => { - throw new TranscriptJsonLimitError("budget"); + throw new TranscriptJsonLimitError({ message: "budget" }); }, () => true, ); diff --git a/apps/server/src/project/AgentSessionJson.ts b/apps/server/src/project/AgentSessionJson.ts index 84b318f0642cc..c9dc6baa5f5e6 100644 --- a/apps/server/src/project/AgentSessionJson.ts +++ b/apps/server/src/project/AgentSessionJson.ts @@ -1,3 +1,4 @@ +import * as Schema from "effect/Schema"; import * as SchemaAST from "effect/SchemaAST"; import { none, type Many } from "stream-chain/defs.js"; import { Assembler } from "stream-json/core/assembler.js"; @@ -40,7 +41,10 @@ export function createTranscriptJsonSelector(schema: { readonly ast: SchemaAST.A return (path: JsonPath) => includes(ast, path, 0); } -export class TranscriptJsonLimitError extends Error {} +export class TranscriptJsonLimitError extends Schema.TaggedError()( + "TranscriptJsonLimitError", + { message: Schema.String }, +) {} export function createTranscriptJsonReader( reserve: (bytes: number) => void, @@ -150,7 +154,9 @@ export function createTranscriptJsonReader( for (const token of tokens.values) { if (token.name === "startObject" || token.name === "startArray") { if (++depth > (options?.maxDepth ?? 128)) - throw new TranscriptJsonLimitError("Transcript JSON nesting exceeds the depth limit"); + throw new TranscriptJsonLimitError({ + message: "Transcript JSON nesting exceeds the depth limit", + }); } else if (token.name === "endObject" || token.name === "endArray") { if (--depth === 0) complete = true; } diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 511728cf2121c..026bc6abb4d0e 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -1026,9 +1026,9 @@ export const make = Effect.gen(function* () { const reserve = (bytes: number) => { recordBytes += bytes; if (historyBytes + recordBytes > MAX_IMPORT_HISTORY_BYTES) { - throw new TranscriptJsonLimitError( - "Transcript selected history exceeds the 32 MiB memory budget", - ); + throw new TranscriptJsonLimitError({ + message: "Transcript selected history exceeds the 32 MiB memory budget", + }); } }; let reader = createTranscriptJsonReader(reserve, selectTranscriptPath); diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 4abadfbdb173b..3f9ed4f1ed228 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -29,6 +29,7 @@ const HIDDEN = new Set([ "pPr", ]); +// @effect-diagnostics-next-line extendsNativeError:off - this worker loads no Effect runtime; Truncation is a local throw sentinel. class Truncation extends Error {} interface XmlNode { diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index ee7709e710eda..d3fe7fdf86739 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -10,7 +10,6 @@ import { import { resolveSpawnCommand } from "@t3tools/shared/shell"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; -import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -79,10 +78,13 @@ export class ProviderMaintenanceRunner extends Context.Service< ProviderMaintenanceRunnerShape >()("t3/provider/providerMaintenanceRunner") {} -class ProviderMaintenanceCommandError extends Data.TaggedError("ProviderMaintenanceCommandError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} +class ProviderMaintenanceCommandError extends Schema.TaggedError()( + "ProviderMaintenanceCommandError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} interface VerifiedProviderRefresh { readonly providers: ReadonlyArray; diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 6d5e4484860fc..546d68c8ebe9b 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -31,7 +31,6 @@ import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; import * as Mac from "effect/crypto/Mac"; import * as SecureRandom from "effect/crypto/SecureRandom"; -import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; @@ -122,9 +121,10 @@ export class ScheduledTaskWebhookOrigin extends Context.Reference {} +class WebhookDeliverySkipped extends Schema.TaggedError()( + "WebhookDeliverySkipped", + { reason: Schema.String }, +) {} interface RateWindow { readonly accepted: ReadonlyArray<{ readonly at: number }>; diff --git a/apps/web/src/browser/browserViewportActions.ts b/apps/web/src/browser/browserViewportActions.ts index c88605be577ce..18ea91427c8a3 100644 --- a/apps/web/src/browser/browserViewportActions.ts +++ b/apps/web/src/browser/browserViewportActions.ts @@ -1,5 +1,6 @@ import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { PreviewViewportSetting, ScopedThreadRef } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; import { toastManager } from "~/components/ui/toast"; import { updatePreviewServerSnapshot } from "~/previewStateStore"; @@ -15,11 +16,12 @@ export interface BrowserViewportTarget { const BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS = 15_000; -class BrowserViewportCommitTimeoutError extends Error { - override readonly name = "BrowserViewportCommitTimeoutError"; - - constructor(readonly tabId: string) { - super(`Timed out committing the browser viewport for tab ${tabId}`); +class BrowserViewportCommitTimeoutError extends Schema.TaggedError()( + "BrowserViewportCommitTimeoutError", + { tabId: Schema.String }, +) { + override get message(): string { + return `Timed out committing the browser viewport for tab ${this.tabId}`; } } @@ -53,7 +55,7 @@ const runHandlerWithTimeout = (tabId: string, operation: Promise): Promise let timeoutId: ReturnType | undefined; const timeout = new Promise((_resolve, reject) => { timeoutId = setTimeout( - () => reject(new BrowserViewportCommitTimeoutError(tabId)), + () => reject(new BrowserViewportCommitTimeoutError({ tabId })), BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS, ); }); diff --git a/apps/web/src/browser/openFileInPreview.ts b/apps/web/src/browser/openFileInPreview.ts index 9c4a6c803ff5b..a997ee2b552e4 100644 --- a/apps/web/src/browser/openFileInPreview.ts +++ b/apps/web/src/browser/openFileInPreview.ts @@ -12,7 +12,7 @@ import { mapAtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; import * as Cause from "effect/Cause"; -import * as Data from "effect/Data"; +import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; import { resolveAssetUrl } from "~/assets/assetUrls"; @@ -35,20 +35,22 @@ import { resolveBrowserDefaults } from "./browserDefaults"; export const isBrowserPreviewFile = (path: string): boolean => /\.(?:html?|pdf)$/i.test(path.split(/[?#]/, 1)[0] ?? ""); -export class BrowserPreviewUnavailableError extends Data.TaggedError( +export class BrowserPreviewUnavailableError extends Schema.TaggedError()( "BrowserPreviewUnavailableError", -)<{ - readonly message: string; -}> {} + { message: Schema.String }, +) {} -export class BrowserSettingsReadError extends Data.TaggedError("BrowserSettingsReadError")<{ - readonly cause: unknown; -}> { +export class BrowserSettingsReadError extends Schema.TaggedError()( + "BrowserSettingsReadError", + { cause: Schema.Defect() }, +) { override get message(): string { return "Saved browser settings could not be loaded."; } } +export const isBrowserSettingsReadError = Schema.is(BrowserSettingsReadError); + export type OpenPreviewMutation = (input: { readonly environmentId: EnvironmentId; readonly input: PreviewOpenInput; @@ -66,7 +68,7 @@ export async function openUrlInPreview(input: { const defaults = await resolveBrowserDefaults().catch( (cause: unknown) => new BrowserSettingsReadError({ cause }), ); - if (defaults instanceof BrowserSettingsReadError) { + if (isBrowserSettingsReadError(defaults)) { return AsyncResult.failure(Cause.fail(defaults)); } const runtime = previewRuntimeFor(threadRef.environmentId); diff --git a/apps/web/src/browser/useOpenLink.ts b/apps/web/src/browser/useOpenLink.ts index 6a60fcbfed54f..73d880632e939 100644 --- a/apps/web/src/browser/useOpenLink.ts +++ b/apps/web/src/browser/useOpenLink.ts @@ -13,7 +13,7 @@ import { resolveBrowserLinkTargetPreference, resolveLinkTarget, } from "./browserLinkTarget"; -import { BrowserSettingsReadError, openUrlInPreview } from "./openFileInPreview"; +import { isBrowserSettingsReadError, openUrlInPreview } from "./openFileInPreview"; const NO_MODIFIER = { metaKey: false, ctrlKey: false } as const; @@ -46,7 +46,7 @@ export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): ( return; } const failure = squashAtomCommandFailure(result); - if (failure instanceof BrowserSettingsReadError) throw failure; + if (isBrowserSettingsReadError(failure)) throw failure; console.error(result.cause); } const api = readLocalApi(); diff --git a/apps/web/src/cloud/dpop.ts b/apps/web/src/cloud/dpop.ts index 442f00aaacfba..41a3dffb42b4d 100644 --- a/apps/web/src/cloud/dpop.ts +++ b/apps/web/src/cloud/dpop.ts @@ -3,7 +3,6 @@ import { computeDpopJwkThumbprint, DpopPublicJwk } from "@t3tools/shared/dpop"; import * as Digest from "effect/crypto/Digest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Signature from "effect/crypto/Signature"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -14,10 +13,12 @@ export interface BrowserDpopKey { readonly thumbprint: string; } -export class BrowserDpopError extends Data.TaggedError("BrowserDpopError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} +export class BrowserDpopError extends Schema.TaggedError()("BrowserDpopError", { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) {} + +const isBrowserDpopError = Schema.is(BrowserDpopError); const DPOP_DATABASE_NAME = "t3code:cloud-auth"; const DPOP_DATABASE_VERSION = 1; @@ -113,9 +114,7 @@ const generateBrowserDpopKey = Effect.gen(function* () { }).pipe( Effect.flatMap((jwk) => decodeDpopPublicJwk(jwk)), Effect.mapError((cause) => - cause instanceof BrowserDpopError - ? cause - : dpopError("Generated DPoP public key is invalid.", cause), + isBrowserDpopError(cause) ? cause : dpopError("Generated DPoP public key is invalid.", cause), ), ); const privateKey = yield* Effect.tryPromise({ diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.ts index 70fd2de055f68..8673e06d20c94 100644 --- a/apps/web/src/cloud/linkEnvironment.ts +++ b/apps/web/src/cloud/linkEnvironment.ts @@ -1,4 +1,3 @@ -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -36,11 +35,16 @@ function relayUrl(): string | null { return resolveCloudPublicConfig().relayUrl; } -export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{ - readonly message: string; - readonly cause?: unknown; - readonly traceId?: string; -}> {} +export class CloudEnvironmentLinkError extends Schema.TaggedError()( + "CloudEnvironmentLinkError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + traceId: Schema.optional(Schema.String), + }, +) {} + +export const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError); const relayClientRpcError = (message: string) => (cause: unknown) => new CloudEnvironmentLinkError({ diff --git a/apps/web/src/cloud/useCloudLinkController.ts b/apps/web/src/cloud/useCloudLinkController.ts index 9936bf888d929..0e94b0e7e7bbe 100644 --- a/apps/web/src/cloud/useCloudLinkController.ts +++ b/apps/web/src/cloud/useCloudLinkController.ts @@ -21,7 +21,7 @@ import { toastManager } from "../components/ui/toast"; import { relayEnvironmentDiscovery } from "../state/relay"; import { readEnvironmentScope } from "../state/session"; import { useAtomCommand } from "../state/use-atom-command"; -import { CloudEnvironmentLinkError } from "./linkEnvironment"; +import { isCloudEnvironmentLinkError } from "./linkEnvironment"; import { refreshManagedTunnelUsage } from "./managedRelayState"; import { linkEnvironment as linkEnvironmentAtom, @@ -54,7 +54,7 @@ const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequ /** The account's tunnel cap when the relay refused a new tunnel for being at it. */ function tunnelLimitFromLinkFailure(cause: unknown): number | null { - if (!(cause instanceof CloudEnvironmentLinkError)) return null; + if (!isCloudEnvironmentLinkError(cause)) return null; const relayCause = cause.cause; if (!isManagedRelayRequestFailedError(relayCause)) return null; return relayCause.relayError?._tag === "RelayEnvironmentLinkLimitExceededError" diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 3ab3148bf39f1..2f2cfea67fd20 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -185,7 +185,7 @@ import { openFileInPreview, openUrlInPreview, BrowserPreviewUnavailableError, - BrowserSettingsReadError, + isBrowserSettingsReadError, } from "../browser/openFileInPreview"; import { resolveLinkTarget } from "../browser/browserLinkTarget"; import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview"; @@ -712,7 +712,7 @@ function useChatMarkdownState({ if (result._tag === "Success") recordVisitForThread(threadRef, url); else if (!isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); - if (error instanceof BrowserSettingsReadError) { + if (isBrowserSettingsReadError(error)) { toastManager.add( stackedThreadToast({ type: "error", @@ -1204,7 +1204,7 @@ const CHAT_MARKDOWN_COMPONENTS = { { operation: "open-link-in-preview", target: href }, result.cause, ); - if (squashAtomCommandFailure(result) instanceof BrowserSettingsReadError) return; + if (isBrowserSettingsReadError(squashAtomCommandFailure(result))) return; void readLocalApi()?.shell.openExternal(href); }); }} diff --git a/apps/web/src/components/chat/McpAppFrame.tsx b/apps/web/src/components/chat/McpAppFrame.tsx index d65758f08d45d..fc697333d6108 100644 --- a/apps/web/src/components/chat/McpAppFrame.tsx +++ b/apps/web/src/components/chat/McpAppFrame.tsx @@ -40,9 +40,10 @@ const commandFailure = (result: { readonly cause: Parameters[0]["cause"]; }) => { const error = squashAtomCommandFailure(result); - return new McpAppHostRefusal( - error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.", - ); + return new McpAppHostRefusal({ + message: + error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.", + }); }; const fullscreenSupported = @@ -253,7 +254,7 @@ export function McpAppFrame(props: { flushSync(() => setDisplayMode("inline")); const approved = await requestConfirmDialog(message); if (approved === undefined) { - throw new McpAppHostRefusal("T3 could not ask for approval here."); + throw new McpAppHostRefusal({ message: "T3 could not ask for approval here." }); } return approved; }; @@ -272,12 +273,13 @@ export function McpAppFrame(props: { const { environmentId, input } = scope(); const info = await readLive().toolInfo({ environmentId, input: { ...input, name } }); if (info._tag !== "Success") throw commandFailure(info); - if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool."); + if (!info.value.callable) + throw new McpAppHostRefusal({ message: "This app cannot call that tool." }); if (!info.value.readOnly) { const approved = await ask( `Allow ${app.server} to run ${info.value.title ?? name}?\n${JSON.stringify(args, null, 2)}`, ); - if (approved !== true) throw new McpAppHostRefusal("Declined by the user."); + if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." }); } const result = await readLive().callTool({ environmentId, @@ -297,15 +299,16 @@ export function McpAppFrame(props: { }, openLink: async (url) => { if (document.activeElement !== frameRef.current || !navigator.userActivation?.isActive) { - throw new McpAppHostRefusal("Links open only from a click in the app."); + throw new McpAppHostRefusal({ message: "Links open only from a click in the app." }); } window.open(url, "_blank", "noopener,noreferrer"); }, sendMessage: async (text) => { const send = readLive().props.onSendMessage; - if (send === undefined) throw new McpAppHostRefusal("Messages are not available here."); + if (send === undefined) + throw new McpAppHostRefusal({ message: "Messages are not available here." }); const approved = await ask(`Send this message from ${app.server}?\n${text}`); - if (approved !== true) throw new McpAppHostRefusal("Declined by the user."); + if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." }); await send(text); }, updateModelContext: async (context) => { @@ -340,7 +343,7 @@ export function McpAppFrame(props: { downloadFile: async (files) => { const names = files.map((file) => file.name).join(", "); const approved = await ask(`Save ${names} from ${app.server}?`); - if (approved !== true) throw new McpAppHostRefusal("Declined by the user."); + if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." }); for (const file of files) { let bytes: Uint8Array | undefined; let mimeType = file.mimeType ?? "application/octet-stream"; @@ -358,9 +361,10 @@ export function McpAppFrame(props: { const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType; if (typeof declared === "string") mimeType = declared; } - if (bytes === undefined) throw new McpAppHostRefusal(`${file.name} has no contents.`); + if (bytes === undefined) + throw new McpAppHostRefusal({ message: `${file.name} has no contents.` }); if (bytes.byteLength > MAX_DOWNLOAD_BYTES) { - throw new McpAppHostRefusal(`${file.name} is too large to save.`); + throw new McpAppHostRefusal({ message: `${file.name} is too large to save.` }); } saveBlob(new Blob([bytes.slice()], { type: mimeType }), file.name); } diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.ts index 0f8e8e3ce303f..25ec5c22c2e1a 100644 --- a/apps/web/src/components/chat/useRightPanelActions.ts +++ b/apps/web/src/components/chat/useRightPanelActions.ts @@ -22,7 +22,7 @@ import { } from "../../rightPanelStore"; import { requestWorkspaceContentFocus, requestWorkspaceFocus } from "../../lib/workspaceFocus"; import { setActivePreviewTab } from "../../previewStateStore"; -import { BrowserSettingsReadError } from "../../browser/openFileInPreview"; +import { isBrowserSettingsReadError } from "../../browser/openFileInPreview"; import { addBrowserSurface } from "../preview/addBrowserSurface"; import { focusActivePanelTerminal, focusTerminal } from "../../lib/terminalFocus"; import { subscribePreviewAction } from "../preview/previewActionBus"; @@ -119,7 +119,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) { }).then((result) => { if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; const error = squashAtomCommandFailure(result); - if (error instanceof BrowserSettingsReadError) { + if (isBrowserSettingsReadError(error)) { toastManager.add( stackedThreadToast({ type: "error", diff --git a/apps/web/src/components/device/DeviceAndroidFoldControls.tsx b/apps/web/src/components/device/DeviceAndroidFoldControls.tsx index b680a20f1dfb7..a6d47cba8902e 100644 --- a/apps/web/src/components/device/DeviceAndroidFoldControls.tsx +++ b/apps/web/src/components/device/DeviceAndroidFoldControls.tsx @@ -1,3 +1,4 @@ +import * as Schema from "effect/Schema"; import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess"; import { useAtomMount, useAtomSet, useAtomValue } from "@effect/atom-react"; import { useRef, useState } from "react"; @@ -7,6 +8,8 @@ import { AndroidFoldError, setAndroidFold, type AndroidFoldPosture } from "./dev import { androidFoldReadAtom, androidFoldViewAtom, foldAngle, NOOP_ATOM } from "./deviceHubAtoms"; import { DeviceDuoGlyph } from "./DeviceDuoGlyph"; +const isAndroidFoldError = Schema.is(AndroidFoldError); + export function DeviceAndroidFoldControls(props: { readonly access: DeviceHubAccess; readonly deviceKey: string; @@ -47,7 +50,7 @@ export function DeviceAndroidFoldControls(props: { void send(props.access) .catch(async (cause: unknown) => { // Hub tickets expire after a few minutes, while the panel stays open much longer. - if (!(cause instanceof AndroidFoldError && cause.status === 401)) throw cause; + if (!(isAndroidFoldError(cause) && cause.status === 401)) throw cause; const renewed = await props.renewAccess(); if (!renewed || controller.signal.aborted) throw cause; return send(renewed); diff --git a/apps/web/src/components/device/DeviceWorkspace.tsx b/apps/web/src/components/device/DeviceWorkspace.tsx index 08ce51c1c548c..21f51520ba3a3 100644 --- a/apps/web/src/components/device/DeviceWorkspace.tsx +++ b/apps/web/src/components/device/DeviceWorkspace.tsx @@ -1,3 +1,4 @@ +import * as Schema from "effect/Schema"; import type { DeviceHostSummary, DeviceSummary, EnvironmentId } from "@t3tools/contracts"; import { useRef, useState } from "react"; import { @@ -10,6 +11,8 @@ import { DeviceStreamView } from "./DeviceStreamView"; import { DeviceToolsPanel } from "./DeviceToolsPanel"; import { useDeviceControls } from "./useDeviceControls"; +const isDeviceScreenshotError = Schema.is(DeviceScreenshotError); + const DOWNLOAD_URL_LIFETIME_MS = 60_000; export function DeviceWorkspace(props: { @@ -59,7 +62,7 @@ export function DeviceWorkspace(props: { window.setTimeout(() => URL.revokeObjectURL(url), DOWNLOAD_URL_LIFETIME_MS); }) .catch((cause: unknown) => { - if (cause instanceof DeviceScreenshotError && cause.status === 401) + if (isDeviceScreenshotError(cause) && cause.status === 401) refreshDeviceHubAccess(props.environmentId); setScreenshotError( cause instanceof Error ? cause.message : "Screenshot capture failed. Try again.", diff --git a/apps/web/src/components/device/deviceFold.ts b/apps/web/src/components/device/deviceFold.ts index 779e89a1252ed..1ad9e09c8568e 100644 --- a/apps/web/src/components/device/deviceFold.ts +++ b/apps/web/src/components/device/deviceFold.ts @@ -1,5 +1,6 @@ import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess"; import { withDeviceHubQuery } from "@t3tools/client-runtime/state/deviceHubAccess"; +import * as Schema from "effect/Schema"; export type AndroidFoldPosture = "closed" | "opened"; @@ -9,14 +10,10 @@ export interface AndroidFoldState { readonly hingeAngle: number | null; } -export class AndroidFoldError extends Error { - readonly status: number; - - constructor(message: string, status: number) { - super(message); - this.status = status; - } -} +export class AndroidFoldError extends Schema.TaggedError()("AndroidFoldError", { + message: Schema.String, + status: Schema.Number, +}) {} const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); @@ -63,10 +60,10 @@ const foldRequest = async ( if (!response.ok) { const payload: unknown = await response.json().catch(() => null); const error = isRecord(payload) ? payload.error : null; - throw new AndroidFoldError( - typeof error === "string" ? error : `Fold command failed (${response.status}).`, - response.status, - ); + throw new AndroidFoldError({ + message: typeof error === "string" ? error : `Fold command failed (${response.status}).`, + status: response.status, + }); } return parseFold(await response.json()); }; diff --git a/apps/web/src/components/device/deviceHubAtoms.ts b/apps/web/src/components/device/deviceHubAtoms.ts index e9e6c1c66b980..345405ba3a689 100644 --- a/apps/web/src/components/device/deviceHubAtoms.ts +++ b/apps/web/src/components/device/deviceHubAtoms.ts @@ -17,6 +17,8 @@ import { } from "./deviceHubApi"; import { AndroidFoldError, readAndroidFold, type AndroidFoldState } from "./deviceFold"; +const isAndroidFoldError = Schema.is(AndroidFoldError); + const AX_POLL_INTERVAL_MS = 2_000; const FOLD_RETRY_MS = 3_000; @@ -102,7 +104,7 @@ export const androidFoldReadAtom = Atom.family( Atom.make((get) => Effect.tryPromise({ try: (signal) => readAndroidFold(input.access, input.deviceId, signal), - catch: (cause) => ({ expired: cause instanceof AndroidFoldError && cause.status === 401 }), + catch: (cause) => ({ expired: isAndroidFoldError(cause) && cause.status === 401 }), }).pipe( Effect.retry({ while: (failure) => !failure.expired, diff --git a/apps/web/src/components/files/office/Spreadsheet.tsx b/apps/web/src/components/files/office/Spreadsheet.tsx index 6faa42d924c08..7bea259b9f07b 100644 --- a/apps/web/src/components/files/office/Spreadsheet.tsx +++ b/apps/web/src/components/files/office/Spreadsheet.tsx @@ -1,3 +1,4 @@ +import * as Schema from "effect/Schema"; import { observeResize } from "~/lib/observeResize"; import { useEffect, useRef, useState } from "react"; import { @@ -33,6 +34,8 @@ import { } from "./sheet-paint"; import { externalUrl } from "./links"; +const isSupersededError = Schema.is(SupersededError); + type Client = ReturnType>; type Opened = { engine: Client; @@ -264,7 +267,7 @@ function SpreadsheetGrid(props: { schedule(); }) .catch((cause: unknown) => { - if (!(cause instanceof SupersededError) && !controller.signal.aborted) + if (!isSupersededError(cause) && !controller.signal.aborted) setNotice("These cells could not be drawn."); }); } diff --git a/apps/web/src/components/files/office/worker-rpc.ts b/apps/web/src/components/files/office/worker-rpc.ts index c5471cea87c82..2be77ea89388f 100644 --- a/apps/web/src/components/files/office/worker-rpc.ts +++ b/apps/web/src/components/files/office/worker-rpc.ts @@ -3,6 +3,8 @@ // two ends of that worker's protocol: typed calls by method name, a key that lets a newer call replace a queued one // (as the markdown worker's queue does), transferable payloads, and a worker that fails every pending call when it dies. +import * as Schema from "effect/Schema"; + /** What one method takes and returns. */ export type Method = { readonly input: Input; readonly output: Output }; @@ -43,10 +45,14 @@ export class Transfer { } /** A call that a newer call with the same key replaced before it ran. */ -export class SupersededError extends Error {} +export class SupersededError extends Schema.TaggedError()("SupersededError", { + message: Schema.String, +}) {} /** A call made after the worker failed or was closed, or pending when that happened. */ -class WorkerClosedError extends Error {} +class WorkerClosedError extends Schema.TaggedError()("WorkerClosedError", { + message: Schema.String, +}) {} type CallOptions = { /** A newer call with the same key replaces this one while it waits to run. */ @@ -93,10 +99,10 @@ export function createWorkerClient(worker: Worker) { }); worker.addEventListener("error", (event) => - fail(new WorkerClosedError(event.message || "The Office engine stopped")), + fail(new WorkerClosedError({ message: event.message || "The Office engine stopped" })), ); worker.addEventListener("messageerror", () => - fail(new WorkerClosedError("The Office engine sent an unreadable reply")), + fail(new WorkerClosedError({ message: "The Office engine sent an unreadable reply" })), ); return { @@ -108,7 +114,7 @@ export function createWorkerClient(worker: Worker) { if (state.failure) return Promise.reject(state.failure); if (options.signal?.aborted) - return Promise.reject(new WorkerClosedError("The call was aborted")); + return Promise.reject(new WorkerClosedError({ message: "The call was aborted" })); const id = ++state.next; @@ -116,16 +122,16 @@ export function createWorkerClient(worker: Worker) { const timeout = setTimeout( () => fail( - new WorkerClosedError( - "This document took too long to preview. Open it in another app.", - ), + new WorkerClosedError({ + message: "This document took too long to preview. Open it in another app.", + }), ), 30_000, ); const abort = () => { clearTimeout(timeout); pending.delete(id); - reject(new WorkerClosedError("The call was aborted")); + reject(new WorkerClosedError({ message: "The call was aborted" })); worker.postMessage({ cancel: id } satisfies Cancel, []); }; @@ -138,7 +144,7 @@ export function createWorkerClient(worker: Worker) { if (!response.ok) return reject( response.superseded - ? new SupersededError(response.message) + ? new SupersededError({ message: response.message }) : new Error(response.message), ); @@ -158,7 +164,7 @@ export function createWorkerClient(worker: Worker) { }, /** Stops the worker, which frees its engine's memory, and fails every pending call. */ close() { - fail(new WorkerClosedError("The Office engine was closed")); + fail(new WorkerClosedError({ message: "The Office engine was closed" })); }, }; } diff --git a/apps/web/src/components/guest/guestTurnItemSource.ts b/apps/web/src/components/guest/guestTurnItemSource.ts index 5ce858251d8c9..72a5802e812be 100644 --- a/apps/web/src/components/guest/guestTurnItemSource.ts +++ b/apps/web/src/components/guest/guestTurnItemSource.ts @@ -10,7 +10,6 @@ import { OrchestrationV2GetTurnItemResult, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; @@ -21,9 +20,9 @@ import { Atom } from "effect/reactivity"; import type { TurnItemSource } from "../chat/timelineRowContext"; /** What an expanded guest row says when it cannot read the item. */ -class GuestItemReadError extends Data.TaggedError("GuestItemReadError")<{ - readonly message: string; -}> {} +class GuestItemReadError extends Schema.TaggedError()("GuestItemReadError", { + message: Schema.String, +}) {} const decodeDetail = Schema.decodeUnknownSync(Schema.toCodecJson(OrchestrationV2GetTurnItemResult)); const decodeFrame = Schema.decodeUnknownOption( diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx index 865448e1f6dc9..28779191d77bd 100644 --- a/apps/web/src/components/preview/PreviewView.tsx +++ b/apps/web/src/components/preview/PreviewView.tsx @@ -71,7 +71,7 @@ import { BrowserDeviceToolbar } from "~/browser/BrowserDeviceToolbar"; import { BROWSER_DEVICE_TOOLBAR_HEIGHT } from "~/browser/browserViewportLayout"; import { useBrowserLayoutZoomFactor } from "~/browser/useBrowserLayoutZoomFactor"; import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId"; -import { BrowserSettingsReadError } from "~/browser/openFileInPreview"; +import { isBrowserSettingsReadError } from "~/browser/openFileInPreview"; import { PreviewFileNotShown, PreviewUnreachable } from "./PreviewUnreachable"; import { revealInFileExplorerLabel } from "./fileExplorerLabel"; import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic"; @@ -243,7 +243,7 @@ export function PreviewView({ const result = await openPreviewSession({ openPreview: open, threadRef, url: resolvedUrl }); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); - if (error instanceof BrowserSettingsReadError) { + if (isBrowserSettingsReadError(error)) { toastManager.add({ type: "error", title: "Unable to open browser", diff --git a/apps/web/src/components/preview/openPreviewSession.ts b/apps/web/src/components/preview/openPreviewSession.ts index 4827d0045355b..99dc6c3e572c4 100644 --- a/apps/web/src/components/preview/openPreviewSession.ts +++ b/apps/web/src/components/preview/openPreviewSession.ts @@ -11,7 +11,7 @@ import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { resolveBrowserDefaults } from "~/browser/browserDefaults"; -import { BrowserSettingsReadError } from "~/browser/openFileInPreview"; +import { BrowserSettingsReadError, isBrowserSettingsReadError } from "~/browser/openFileInPreview"; import { previewRuntimeFor } from "~/browser/previewRuntime"; import { applyPreviewServerSnapshot, rememberPreviewUrl } from "~/previewStateStore"; @@ -34,7 +34,7 @@ export async function openPreviewSession( const defaults = await resolveBrowserDefaults().catch( (cause: unknown) => new BrowserSettingsReadError({ cause }), ); - if (defaults instanceof BrowserSettingsReadError) { + if (isBrowserSettingsReadError(defaults)) { return AsyncResult.failure(Cause.fail(defaults)); } const runtime = input.runtime ?? previewRuntimeFor(input.threadRef.environmentId); diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsx index b64e35db95181..4d2032f9471d2 100644 --- a/apps/web/src/components/settings/IntegrationsSettings.tsx +++ b/apps/web/src/components/settings/IntegrationsSettings.tsx @@ -40,6 +40,7 @@ import { usePrimaryManagedPolicy } from "~/state/managedPolicy"; import { isValidSearchUrlTemplate } from "@t3tools/shared/preview"; import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport"; import { MoreVertical, Plus as PlusIcon } from "lucide-react"; +import * as Schema from "effect/Schema"; import { useRef, useState } from "react"; import { ScreenRotationIcon } from "~/browser/ScreenRotationIcon"; @@ -174,13 +175,17 @@ const zoomLabel = (zoomFactor: number) => `${Math.round(zoomFactor * 100)}%`; /** IPC carries reason tokens inside messages; treat unknown tokens as read failures without exposing raw * text. */ -class ProfileLimitReachedError extends Error { - constructor() { - super("Browser profile limit reached."); - this.name = "ProfileLimitReachedError"; +class ProfileLimitReachedError extends Schema.TaggedError()( + "ProfileLimitReachedError", + {}, +) { + override get message(): string { + return "Browser profile limit reached."; } } +const isProfileLimitReachedError = Schema.is(ProfileLimitReachedError); + export const importFailureReason = (cause: unknown): BrowserImportFailureReason => { const message = String((cause as { message?: unknown } | undefined)?.message ?? ""); return ( @@ -257,8 +262,9 @@ async function importBrowserCookiesIntoTarget( await clearBrowserProfileData(bridge, [environmentId], input.target.profileId).catch( () => undefined, ); - const reason = - cause instanceof ProfileLimitReachedError ? "profileLimitReached" : "profileNotSaved"; + const reason = isProfileLimitReachedError(cause) + ? "profileLimitReached" + : "profileNotSaved"; throw new Error(`Importing cookies from ${source.id} failed: ${reason}.`, { cause }); } } else { diff --git a/apps/web/src/components/settings/OpenSourceLicenses.tsx b/apps/web/src/components/settings/OpenSourceLicenses.tsx index df311db516c5a..087227384230b 100644 --- a/apps/web/src/components/settings/OpenSourceLicenses.tsx +++ b/apps/web/src/components/settings/OpenSourceLicenses.tsx @@ -1,7 +1,7 @@ import { ChevronRightIcon, ExternalLinkIcon, SearchIcon } from "lucide-react"; import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; import * as Cause from "effect/Cause"; -import * as Data from "effect/Data"; +import * as Schema from "effect/Schema"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import { FetchHttpClient, HttpClient } from "effect/http"; @@ -22,9 +22,10 @@ import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group" import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { SettingsPageContainer, SettingsSection } from "./settingsLayout"; -class LicenseManifestLoadError extends Data.TaggedError("LicenseManifestLoadError")<{ - readonly message: string; -}> {} +class LicenseManifestLoadError extends Schema.TaggedError()( + "LicenseManifestLoadError", + { message: Schema.String }, +) {} // Not keepAlive: a failed load must not stick for the session, so each visit to the page loads // the manifest again (a static asset the HTTP cache serves). diff --git a/apps/web/src/lib/resourceTelemetryState.browser.test.tsx b/apps/web/src/lib/resourceTelemetryState.browser.test.tsx index 1ad71e6e765cd..981beeafdfd38 100644 --- a/apps/web/src/lib/resourceTelemetryState.browser.test.tsx +++ b/apps/web/src/lib/resourceTelemetryState.browser.test.tsx @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; -import * as Data from "effect/Data"; +import * as Schema from "effect/Schema"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; @@ -64,7 +64,9 @@ vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => monitor.retr import { ResourceTelemetryDiagnostics } from "../components/settings/ResourceTelemetryDiagnostics"; -class MonitorError extends Data.TaggedError("MonitorError")<{ readonly message: string }> {} +class MonitorError extends Schema.TaggedError()("MonitorError", { + message: Schema.String, +}) {} const environmentId = EnvironmentId.make("remote"); const startError = "The resource monitor is not available."; diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.ts index 0ed73648e78c1..3abb8b28f4d6a 100644 --- a/infra/relay/src/http/Api.test.ts +++ b/infra/relay/src/http/Api.test.ts @@ -15,7 +15,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; import { vi } from "vite-plus/test"; import * as Context from "effect/Context"; -import * as Data from "effect/Data"; import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -1471,7 +1470,7 @@ describe("relay routing fallback", () => { describe("relay CORS", () => { const origin = "https://app.t3.codes"; - class HandlerFailed extends Data.TaggedError("HandlerFailed") {} + class HandlerFailed extends Schema.TaggedError()("HandlerFailed", {}) {} it.effect("adds CORS headers to handler failures and defects", () => Effect.gen(function* () { diff --git a/infra/task-cache/vendor/vite-plus-remote-cache-cloudflare/src/errors.ts b/infra/task-cache/vendor/vite-plus-remote-cache-cloudflare/src/errors.ts index 9b54ffce50c80..19eb7c2b848d6 100644 --- a/infra/task-cache/vendor/vite-plus-remote-cache-cloudflare/src/errors.ts +++ b/infra/task-cache/vendor/vite-plus-remote-cache-cloudflare/src/errors.ts @@ -1,3 +1,4 @@ +// @effect-diagnostics-next-line extendsNativeError:off - vendored upstream code without Effect; kept as published. export class HttpError extends Error { constructor( public status: number, diff --git a/oxlint-plugin-t3code/test/utils.ts b/oxlint-plugin-t3code/test/utils.ts index 8982a5513552c..7146048afabd5 100644 --- a/oxlint-plugin-t3code/test/utils.ts +++ b/oxlint-plugin-t3code/test/utils.ts @@ -1,11 +1,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; -import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; @@ -19,18 +17,21 @@ const oxlintPackageJsonPath = NodeModule.createRequire( NodeModule.createRequire(import.meta.url).resolve("vite-plus/package.json"), ).resolve("oxlint/package.json"); -class OxlintFixtureFailure extends Data.TaggedError("OxlintFixtureFailure")<{ - readonly exitCode: number; - readonly stdout: string; - readonly stderr: string; -}> { - static readonly is = (u: unknown): u is OxlintFixtureFailure => - Predicate.isTagged(u, "OxlintFixtureFailure"); -} - -class OxlintFixtureExpectedFailure extends Data.TaggedError("OxlintFixtureExpectedFailure")<{ - readonly ruleName: string; -}> { +class OxlintFixtureFailure extends Schema.TaggedError()( + "OxlintFixtureFailure", + { + exitCode: Schema.Number, + stdout: Schema.String, + stderr: Schema.String, + }, +) {} + +const isOxlintFixtureFailure = Schema.is(OxlintFixtureFailure); + +class OxlintFixtureExpectedFailure extends Schema.TaggedError()( + "OxlintFixtureExpectedFailure", + { ruleName: Schema.String }, +) { override get message() { return `Expected oxlint to report a failure for rule ${this.ruleName}, but it passed.`; } @@ -140,7 +141,7 @@ export const createOxlintRuleHarness = ( run(source).pipe( Effect.matchEffect({ onFailure: (error) => - OxlintFixtureFailure.is(error) + isOxlintFixtureFailure(error) ? Effect.succeed( `oxlint fixture failed with exit code ${error.exitCode}\n${error.stdout}\n${error.stderr}`, ) diff --git a/packages/client-runtime/src/authorization/remote.ts b/packages/client-runtime/src/authorization/remote.ts index 135c443df3f49..814bff4983445 100644 --- a/packages/client-runtime/src/authorization/remote.ts +++ b/packages/client-runtime/src/authorization/remote.ts @@ -13,6 +13,7 @@ import { hashTelemetryId } from "@t3tools/shared/telemetryId"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; import { environmentEndpointUrl } from "../environment/endpoint.ts"; import * as ClientCapabilities from "../platform/capabilities.ts"; import { @@ -26,6 +27,7 @@ export { RemoteEnvironmentAuthUndeclaredStatusError } from "../rpc/http.ts"; export type RemoteEnvironmentAuthError = RemoteEnvironmentRequestError; const DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 10_000; +const isUndeclaredStatusError = Schema.is(RemoteEnvironmentAuthUndeclaredStatusError); const clientMetadataTokenExchangeFields = ( clientMetadata: AuthClientPresentationMetadata | undefined, @@ -205,8 +207,7 @@ const issueWebSocketTicketWithFallback = ( ? issue(use) : issue(use).pipe( Effect.catchIf( - (error) => - error instanceof RemoteEnvironmentAuthUndeclaredStatusError && error.status === 404, + (error) => isUndeclaredStatusError(error) && error.status === 404, () => issue(undefined), ), ); diff --git a/packages/client-runtime/src/connection/errors.test.ts b/packages/client-runtime/src/connection/errors.test.ts index d270ed2c52473..55619af5a413e 100644 --- a/packages/client-runtime/src/connection/errors.test.ts +++ b/packages/client-runtime/src/connection/errors.test.ts @@ -93,7 +93,10 @@ describe("mapRemoteDpopEnvironmentError", () => { message: "Failed to fetch remote environment endpoint.", cause: new TypeError("Failed to fetch"), }), - new RemoteEnvironmentAuthTimeoutError("https://environment.example.test", 10_000), + new RemoteEnvironmentAuthTimeoutError({ + requestUrl: "https://environment.example.test", + timeoutMs: 10_000, + }), ])("suggests another network when the relay endpoint cannot be reached: $_tag", (error) => { const mapped = mapRemoteDpopEnvironmentError(error); expect(mapped).toMatchObject({ diff --git a/packages/client-runtime/src/device/screenshot.ts b/packages/client-runtime/src/device/screenshot.ts index 922295c698407..c3d09e854f5b0 100644 --- a/packages/client-runtime/src/device/screenshot.ts +++ b/packages/client-runtime/src/device/screenshot.ts @@ -1,13 +1,14 @@ // @effect-diagnostics globalFetch:off - This browser transport runs without an Effect runtime, like the live stream. +import * as Schema from "effect/Schema"; import { withDeviceHubQuery } from "./hubAccess.ts"; import type { DeviceStreamTarget } from "./stream.ts"; -export class DeviceScreenshotError extends Error { - readonly status: number; - - constructor(status: number) { - super(`Screenshot capture failed (${status}). Try again.`); - this.status = status; +export class DeviceScreenshotError extends Schema.TaggedError()( + "DeviceScreenshotError", + { status: Schema.Number }, +) { + override get message(): string { + return `Screenshot capture failed (${this.status}). Try again.`; } } @@ -22,7 +23,7 @@ export async function captureDeviceScreenshot(target: DeviceStreamTarget, signal credentials: target.access.credentials ? "include" : "omit", signal: AbortSignal.any([signal, AbortSignal.timeout(20_000)]), }); - if (!response.ok) throw new DeviceScreenshotError(response.status); + if (!response.ok) throw new DeviceScreenshotError({ status: response.status }); const image = await response.blob(); if (!image.size) throw new Error("The device returned an empty screenshot. Try again."); return image; diff --git a/packages/client-runtime/src/mcpApps/host.test.ts b/packages/client-runtime/src/mcpApps/host.test.ts index 8588770715814..898588737c31f 100644 --- a/packages/client-runtime/src/mcpApps/host.test.ts +++ b/packages/client-runtime/src/mcpApps/host.test.ts @@ -206,7 +206,7 @@ describe("makeMcpAppHost", () => { const { host, sent } = setup({ callTool: async (input) => { if (input.name === "delete_everything") - throw new McpAppHostRefusal("Declined by the user."); + throw new McpAppHostRefusal({ message: "Declined by the user." }); return { content: [], structuredContent: { ok: true } }; }, }); @@ -311,7 +311,7 @@ describe("makeMcpAppHost", () => { updateModelContext: async (update) => void contexts.push(update), downloadFile: async (files) => { downloads.push(files); - if (files.length > 1) throw new McpAppHostRefusal("Declined by the user."); + if (files.length > 1) throw new McpAppHostRefusal({ message: "Declined by the user." }); }, }); initialize(host); diff --git a/packages/client-runtime/src/mcpApps/host.ts b/packages/client-runtime/src/mcpApps/host.ts index 5eee10af4338a..847771fb09dbd 100644 --- a/packages/client-runtime/src/mcpApps/host.ts +++ b/packages/client-runtime/src/mcpApps/host.ts @@ -3,6 +3,7 @@ import { MCP_APP_PROTOCOL_VERSION, type McpAppReference } from "@t3tools/shared/ import * as Base64 from "effect/encoding/Base64"; import * as Predicate from "effect/Predicate"; import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; const MAX_MESSAGE_BYTES = 256 * 1024; const MAX_PENDING_REQUESTS = 16; @@ -71,7 +72,12 @@ export interface McpAppCallToolResult { readonly _meta?: unknown; } -export class McpAppHostRefusal extends Error {} +export class McpAppHostRefusal extends Schema.TaggedError()( + "McpAppHostRefusal", + { message: Schema.String }, +) {} + +const isMcpAppHostRefusal = Schema.is(McpAppHostRefusal); export interface McpAppHostOptions { readonly app: McpAppReference; @@ -141,7 +147,7 @@ function normalizeMcpAppToolResult(result: McpAppCallToolResult): McpAppCallTool } const errorMessage = (error: unknown) => - error instanceof McpAppHostRefusal + isMcpAppHostRefusal(error) ? error.message : error instanceof Error && error.message.trim() !== "" ? error.message @@ -342,7 +348,7 @@ export function makeMcpAppHost(options: McpAppHostOptions): McpAppHost { options.downloadFile(files).then( () => ({}), (error: unknown) => - error instanceof McpAppHostRefusal ? { isError: true } : Promise.reject(error), + isMcpAppHostRefusal(error) ? { isError: true } : Promise.reject(error), ), ); return; diff --git a/packages/client-runtime/src/platform/threadCacheEncoding.ts b/packages/client-runtime/src/platform/threadCacheEncoding.ts index b7c233942de43..f993ff3ec2038 100644 --- a/packages/client-runtime/src/platform/threadCacheEncoding.ts +++ b/packages/client-runtime/src/platform/threadCacheEncoding.ts @@ -2,7 +2,6 @@ import { omitLocalVisibleTurnItems, restoreLocalVisibleTurnItems, } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -23,7 +22,10 @@ const StoredCompactThreadSnapshot = StoredOrchestrationThreadSnapshot.mapFields( })), })); -class InvalidThreadCache extends Data.TaggedError("InvalidThreadCache") {} +class InvalidThreadCache extends Schema.TaggedError()( + "InvalidThreadCache", + {}, +) {} const encodeCompact = Schema.encodeEffect(Schema.fromJsonString(StoredCompactThreadSnapshot)); const decodeCompatible = Schema.decodeUnknownEffect( diff --git a/packages/client-runtime/src/relay/dpopProof.ts b/packages/client-runtime/src/relay/dpopProof.ts index 7d9822921cd68..fcab782788291 100644 --- a/packages/client-runtime/src/relay/dpopProof.ts +++ b/packages/client-runtime/src/relay/dpopProof.ts @@ -5,7 +5,7 @@ import * as Cache from "effect/Cache"; import * as Clock from "effect/Clock"; import * as Digest from "effect/crypto/Digest"; import * as SecureRandom from "effect/crypto/SecureRandom"; -import * as Data from "effect/Data"; +import * as Schema from "effect/Schema"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; @@ -18,10 +18,10 @@ import { ManagedRelayDpopSigner, } from "./managedRelay.ts"; -export class DpopProofError extends Data.TaggedError("DpopProofError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} +export class DpopProofError extends Schema.TaggedError()("DpopProofError", { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) {} /** A P-256 proof key. `sign` returns the raw `r‖s` ES256 signature over the JWS signing input. */ export interface DpopProofKey { diff --git a/packages/client-runtime/src/relay/managedRelayState.ts b/packages/client-runtime/src/relay/managedRelayState.ts index 983ccc87ffad9..5a4b9a62a547a 100644 --- a/packages/client-runtime/src/relay/managedRelayState.ts +++ b/packages/client-runtime/src/relay/managedRelayState.ts @@ -2,7 +2,6 @@ import type { EnvironmentId } from "@t3tools/contracts"; import { decodeRelayJwt } from "@t3tools/shared/relayJwt"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; @@ -50,10 +49,13 @@ export interface ManagedRelayQueryEvent { readonly traceId?: string | null; } -export class ManagedRelaySessionError extends Data.TaggedError("ManagedRelaySessionError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} +export class ManagedRelaySessionError extends Schema.TaggedError()( + "ManagedRelaySessionError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} export const managedRelaySessionAtom = Atom.make(null).pipe( Atom.keepAlive, diff --git a/packages/client-runtime/src/rpc/http.ts b/packages/client-runtime/src/rpc/http.ts index 59aee1f45ff28..5f32a6c3c087d 100644 --- a/packages/client-runtime/src/rpc/http.ts +++ b/packages/client-runtime/src/rpc/http.ts @@ -9,7 +9,6 @@ import { type EnvironmentScopeRequiredError, } from "@t3tools/contracts"; import * as HttpObservability from "@t3tools/shared/httpObservability"; -import * as Data from "effect/Data"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -20,52 +19,48 @@ import * as HttpApiClient from "effect/http-api/HttpApiClient"; const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError); -export class RemoteEnvironmentAuthFetchError extends Data.TaggedError( +export class RemoteEnvironmentAuthFetchError extends Schema.TaggedError()( "RemoteEnvironmentAuthFetchError", -)<{ - readonly message: string; - readonly cause: unknown; -}> {} + { + message: Schema.String, + cause: Schema.Defect(), + }, +) {} -class RemoteEnvironmentAuthInvalidJsonError extends Data.TaggedError( +class RemoteEnvironmentAuthInvalidJsonError extends Schema.TaggedError()( "RemoteEnvironmentAuthInvalidJsonError", -)<{ - readonly message: string; - readonly cause: unknown; -}> {} + { + message: Schema.String, + cause: Schema.Defect(), + }, +) {} -export class RemoteEnvironmentAuthUndeclaredStatusError extends Data.TaggedError( +export class RemoteEnvironmentAuthUndeclaredStatusError extends Schema.TaggedError()( "RemoteEnvironmentAuthUndeclaredStatusError", -)<{ - readonly message: string; - readonly status: number; - readonly requestUrl: string; -}> { - constructor(requestUrl: string, status: number) { - super({ - message: `Remote environment endpoint ${requestUrl} returned undeclared status ${status}.`, - requestUrl, - status, - }); + { + status: Schema.Number, + requestUrl: Schema.String, + }, +) { + override get message(): string { + return `Remote environment endpoint ${this.requestUrl} returned undeclared status ${this.status}.`; } } -export class RemoteEnvironmentAuthTimeoutError extends Data.TaggedError( +export class RemoteEnvironmentAuthTimeoutError extends Schema.TaggedError()( "RemoteEnvironmentAuthTimeoutError", -)<{ - readonly message: string; - readonly requestUrl: string; - readonly timeoutMs: number; -}> { - constructor(requestUrl: string, timeoutMs: number) { - super({ - message: `Remote environment endpoint ${requestUrl} timed out after ${timeoutMs}ms.`, - requestUrl, - timeoutMs, - }); + { + requestUrl: Schema.String, + timeoutMs: Schema.Number, + }, +) { + override get message(): string { + return `Remote environment endpoint ${this.requestUrl} timed out after ${this.timeoutMs}ms.`; } } +const isRemoteEnvironmentAuthTimeoutError = Schema.is(RemoteEnvironmentAuthTimeoutError); + export type RemoteEnvironmentRequestError = | EnvironmentRequestInvalidError | EnvironmentAuthInvalidError @@ -122,7 +117,7 @@ const failRemoteRequest = ( requestUrl: string, cause: unknown, ): Effect.Effect => { - if (cause instanceof RemoteEnvironmentAuthTimeoutError) { + if (isRemoteEnvironmentAuthTimeoutError(cause)) { return Effect.fail(cause); } if (isEnvironmentHttpCommonError(cause)) { @@ -140,7 +135,7 @@ const failRemoteRequest = ( const response = cause.response; if (response.status < 200 || response.status >= 300) { return Effect.fail( - new RemoteEnvironmentAuthUndeclaredStatusError(requestUrl, response.status), + new RemoteEnvironmentAuthUndeclaredStatusError({ requestUrl, status: response.status }), ); } return Effect.fail( @@ -167,7 +162,7 @@ export const executeEnvironmentHttpRequest = ( Effect.timeoutOption(Duration.millis(timeoutMs)), Effect.flatMap( Option.match({ - onNone: () => Effect.fail(new RemoteEnvironmentAuthTimeoutError(requestUrl, timeoutMs)), + onNone: () => Effect.fail(new RemoteEnvironmentAuthTimeoutError({ requestUrl, timeoutMs })), onSome: Effect.succeed, }), ), diff --git a/packages/client-runtime/src/state/environmentHttpAuth.ts b/packages/client-runtime/src/state/environmentHttpAuth.ts index 57ec7409540be..f858c895aa35b 100644 --- a/packages/client-runtime/src/state/environmentHttpAuth.ts +++ b/packages/client-runtime/src/state/environmentHttpAuth.ts @@ -247,7 +247,10 @@ const executeEnvironmentRequest = Effect.fnUntraced(function* < duration: input.timeoutMs, orElse: () => Effect.fail( - new RemoteEnvironmentAuthTimeoutError(requestUrlFor(httpBaseUrl), input.timeoutMs), + new RemoteEnvironmentAuthTimeoutError({ + requestUrl: requestUrlFor(httpBaseUrl), + timeoutMs: input.timeoutMs, + }), ), }), ); diff --git a/packages/client-runtime/src/state/peerPairingCode.ts b/packages/client-runtime/src/state/peerPairingCode.ts index 814eeb88d5446..3ae9a076ada11 100644 --- a/packages/client-runtime/src/state/peerPairingCode.ts +++ b/packages/client-runtime/src/state/peerPairingCode.ts @@ -4,7 +4,7 @@ * It carries exactly what an agent sign-in with the chosen access needs. */ import { type AuthMcpClientAccess, mcpClientScopes } from "@t3tools/contracts"; -import * as Data from "effect/Data"; +import * as Schema from "effect/Schema"; import * as Effect from "effect/Effect"; import type * as HttpClient from "effect/http/HttpClient"; import * as Option from "effect/Option"; @@ -23,10 +23,13 @@ const MINT_TIMEOUT_MS = 8_000; const PEER_PAIRING_CODE_LABEL = "T3 Code link"; /** Minting failed; the user can still paste a code from the other environment. */ -export class PeerPairingCodeError extends Data.TaggedError("PeerPairingCodeError")<{ - readonly reason: "not_allowed" | "unavailable"; - readonly cause: unknown; -}> { +export class PeerPairingCodeError extends Schema.TaggedError()( + "PeerPairingCodeError", + { + reason: Schema.Literals(["not_allowed", "unavailable"]), + cause: Schema.Defect(), + }, +) { override get message(): string { return this.reason === "not_allowed" ? "Your session there cannot create pairing codes. Paste a code from there instead." diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.ts index b182beef9007b..6efc11818cef2 100644 --- a/packages/client-runtime/src/state/pullRequests.test.ts +++ b/packages/client-runtime/src/state/pullRequests.test.ts @@ -11,7 +11,7 @@ import { type AuthSessionState, } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; -import * as Data from "effect/Data"; +import * as Schema from "effect/Schema"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; import * as Effect from "effect/Effect"; @@ -53,7 +53,7 @@ const trustedRouting = { forget: () => Effect.void, }; -class MutationRefused extends Data.TaggedError("MutationRefused") {} +class MutationRefused extends Schema.TaggedError()("MutationRefused", {}) {} for (const scenario of [ "prefers the local environment with the same github account", diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts index e6566f2b7d503..64ae5ae3df56e 100644 --- a/packages/client-runtime/src/state/pullRequests.ts +++ b/packages/client-runtime/src/state/pullRequests.ts @@ -24,7 +24,6 @@ import { type PullRequestSummary, type VcsStatusResult, } from "@t3tools/contracts"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { persistPullRequestStats } from "./pullRequestStatsPersistence.ts"; @@ -53,9 +52,10 @@ export { export * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts"; /** @public Required to name the error in consumers' inferred pull request results. */ -export class EnvironmentHttpConnectionNotReadyError extends Data.TaggedError( +export class EnvironmentHttpConnectionNotReadyError extends Schema.TaggedError()( "EnvironmentHttpConnectionNotReadyError", -)<{ readonly message: string }> {} + { message: Schema.String }, +) {} const LINKED_PULL_REQUEST_IDLE_TTL_MS = 5_000; diff --git a/packages/client-runtime/src/state/session.ts b/packages/client-runtime/src/state/session.ts index 90afa29f9d05d..9312ae048e6e0 100644 --- a/packages/client-runtime/src/state/session.ts +++ b/packages/client-runtime/src/state/session.ts @@ -1,6 +1,6 @@ import { pipe } from "effect/Function"; import type { AuthSessionState, EnvironmentId, ServerConfig } from "@t3tools/contracts"; -import * as Data from "effect/Data"; +import * as Schema from "effect/Schema"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; @@ -20,8 +20,9 @@ import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAut import { followStreamInEnvironment } from "./environmentStreams.ts"; /** @public Required to name the error in consumers' inferred session results. */ -export class SessionHttpClientUnavailable extends Data.TaggedError( +export class SessionHttpClientUnavailable extends Schema.TaggedError()( "SessionHttpClientUnavailable", + {}, ) {} function initialConfigOption( diff --git a/packages/client-runtime/src/voice-input/controller.test.ts b/packages/client-runtime/src/voice-input/controller.test.ts index 4b7f9a9c3d40d..52069d1bd67b9 100644 --- a/packages/client-runtime/src/voice-input/controller.test.ts +++ b/packages/client-runtime/src/voice-input/controller.test.ts @@ -120,10 +120,10 @@ describe("VoiceInputController", () => { expect(unsupported.controller.currentState.error).toContain("not available"); expect(unsupported.recorder.record).not.toHaveBeenCalled(); - const reason = new VoiceTranscriptionError( - "unavailable", - "This device requires iOS 26 or later.", - ); + const reason = new VoiceTranscriptionError({ + code: "unavailable", + message: "This device requires iOS 26 or later.", + }); const unavailable = createHarness({ getTranscriber: () => ({ prepare: async () => { diff --git a/packages/client-runtime/src/voice-input/controller.ts b/packages/client-runtime/src/voice-input/controller.ts index 41576db90cf8e..5b057c61fab23 100644 --- a/packages/client-runtime/src/voice-input/controller.ts +++ b/packages/client-runtime/src/voice-input/controller.ts @@ -1,3 +1,4 @@ +import * as Schema from "effect/Schema"; import { replaceTextRange } from "@t3tools/shared/composerTrigger"; import { @@ -6,6 +7,8 @@ import { type VoiceTranscriber, } from "./transcription.ts"; +const isVoiceTranscriptionError = Schema.is(VoiceTranscriptionError); + export const VOICE_RECORDING_LIMIT_SECONDS = 5 * 60; export type VoiceInputPhase = "idle" | "preparing" | "recording" | "transcribing" | "error"; @@ -171,7 +174,7 @@ function preparationErrorMessage(error: unknown): string { if (errorCode(error) === "unsupported-locale") { return "Voice transcription is not available for this language."; } - return error instanceof VoiceTranscriptionError + return isVoiceTranscriptionError(error) ? error.message : "Could not prepare voice transcription."; } @@ -180,9 +183,7 @@ function transcriptionErrorMessage(error: unknown): string { if (error instanceof Error && error.message === "voice-operation-busy") { return "Voice transcription is still finishing. Try again shortly."; } - return error instanceof VoiceTranscriptionError - ? error.message - : "Could not transcribe this recording."; + return isVoiceTranscriptionError(error) ? error.message : "Could not transcribe this recording."; } const IDLE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null }; diff --git a/packages/client-runtime/src/voice-input/transcription.ts b/packages/client-runtime/src/voice-input/transcription.ts index 9e927f7caa5b6..4a8b1ab4e28e9 100644 --- a/packages/client-runtime/src/voice-input/transcription.ts +++ b/packages/client-runtime/src/voice-input/transcription.ts @@ -1,3 +1,5 @@ +import * as Schema from "effect/Schema"; + /** Cancellation is cooperative: settle only after the underlying work has stopped. */ export type VoiceTranscriptionOptions = { readonly signal: AbortSignal; @@ -12,25 +14,29 @@ export type VoiceTranscriber = { readonly prepare: (options: VoiceTranscriptionOptions) => Promise; }; -export type VoiceTranscriptionErrorCode = - | "unavailable" - | "unsupported-locale" - | "preparation-failed" - | "transcription-failed" - | "cancelled"; - -export class VoiceTranscriptionError extends Error { - readonly code: VoiceTranscriptionErrorCode; +const VoiceTranscriptionErrorCode = Schema.Literals([ + "unavailable", + "unsupported-locale", + "preparation-failed", + "transcription-failed", + "cancelled", +]); +export type VoiceTranscriptionErrorCode = typeof VoiceTranscriptionErrorCode.Type; - constructor(code: VoiceTranscriptionErrorCode, message: string, options?: ErrorOptions) { - super(message, options); - this.name = "VoiceTranscriptionError"; - this.code = code; - } -} +export class VoiceTranscriptionError extends Schema.TaggedError()( + "VoiceTranscriptionError", + { + code: VoiceTranscriptionErrorCode, + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} export function throwIfVoiceTranscriptionAborted(signal: AbortSignal): void { if (signal.aborted) { - throw new VoiceTranscriptionError("cancelled", "Voice transcription was cancelled."); + throw new VoiceTranscriptionError({ + code: "cancelled", + message: "Voice transcription was cancelled.", + }); } } diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.ts index 662ef38912c5f..95c3d09e08e72 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.ts @@ -1,5 +1,6 @@ // @effect-diagnostics globalJsonInEffect:off import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import type * as AcpSchema from "effect-acp/compat"; @@ -23,15 +24,20 @@ interface Connection { nextRequestId: number; } -export class AcpMcpOverAcpError extends Error { - readonly _tag = "AcpMcpOverAcpError"; - override readonly name = "AcpMcpOverAcpError"; -} +export class AcpMcpOverAcpError extends Schema.TaggedError()( + "AcpMcpOverAcpError", + { message: Schema.String, cause: Schema.optional(Schema.Defect()) }, +) {} + +const isAcpMcpOverAcpError = Schema.is(AcpMcpOverAcpError); const bridgeError = (cause: unknown): AcpMcpOverAcpError => - cause instanceof AcpMcpOverAcpError + isAcpMcpOverAcpError(cause) ? cause - : new AcpMcpOverAcpError(cause instanceof Error ? cause.message : String(cause), { cause }); + : new AcpMcpOverAcpError({ + message: cause instanceof Error ? cause.message : String(cause), + cause, + }); const asEnvelope = (value: unknown): JsonRpcEnvelope | null => typeof value === "object" && value !== null && !Array.isArray(value) @@ -88,7 +94,11 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun Effect.suspend(() => { const connection = connections.get(connectionId); return connection === undefined - ? Effect.fail(new AcpMcpOverAcpError(`Unknown MCP-over-ACP connection "${connectionId}".`)) + ? Effect.fail( + new AcpMcpOverAcpError({ + message: `Unknown MCP-over-ACP connection "${connectionId}".`, + }), + ) : Effect.succeed(connection); }); @@ -107,7 +117,7 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun Effect.gen(function* () { const body = JSON.stringify(message); if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES) { - return yield* Effect.fail(new AcpMcpOverAcpError("MCP-over-ACP message exceeds 8 MiB.")); + return yield* new AcpMcpOverAcpError({ message: "MCP-over-ACP message exceeds 8 MiB." }); } const response = yield* Effect.tryPromise({ try: (signal) => @@ -134,9 +144,9 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun yield* Effect.promise( () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(), ); - return yield* Effect.fail( - new AcpMcpOverAcpError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`), - ); + return yield* new AcpMcpOverAcpError({ + message: `T3 Code MCP endpoint responded with HTTP ${response.status}.`, + }); } const payloads = [...(yield* Stream.runCollect(responsePayloads(response, bridgeError)))]; for (const payload of payloads) { @@ -169,11 +179,9 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun catch: bridgeError, }); if (!response.ok && response.status !== 404) { - return yield* Effect.fail( - new AcpMcpOverAcpError( - `T3 Code MCP endpoint rejected disconnect with HTTP ${response.status}.`, - ), - ); + return yield* new AcpMcpOverAcpError({ + message: `T3 Code MCP endpoint rejected disconnect with HTTP ${response.status}.`, + }); } yield* Effect.promise( () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(), @@ -185,12 +193,12 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun return { connect: Effect.fn("mcpOverAcpBridge.connect")(function* (request) { if (request.serverId !== "t3-code") { - return yield* Effect.fail( - new AcpMcpOverAcpError(`Unknown ACP MCP server "${request.serverId}".`), - ); + return yield* new AcpMcpOverAcpError({ + message: `Unknown ACP MCP server "${request.serverId}".`, + }); } if (connections.size >= MAX_CONNECTIONS) { - return yield* Effect.fail(new AcpMcpOverAcpError("Too many MCP-over-ACP connections.")); + return yield* new AcpMcpOverAcpError({ message: "Too many MCP-over-ACP connections." }); } const connectionId = yield* options.allocateConnectionId; connections.set(connectionId, { @@ -213,12 +221,12 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun const response = payloads.find((payload) => asEnvelope(payload)?.id === id); const envelope = asEnvelope(response); if (envelope === null) { - return yield* Effect.fail( - new AcpMcpOverAcpError("MCP server did not return a matching response."), - ); + return yield* new AcpMcpOverAcpError({ + message: "MCP server did not return a matching response.", + }); } if (envelope.error !== undefined) { - return yield* Effect.fail(new AcpMcpOverAcpError(errorMessage(envelope.error))); + return yield* new AcpMcpOverAcpError({ message: errorMessage(envelope.error) }); } return (envelope.result ?? null) as AcpSchema.MessageMcpResponse; }), diff --git a/packages/provider-cursor/src/server/CursorSdk.test.ts b/packages/provider-cursor/src/server/CursorSdk.test.ts index bf5229c9642fd..60daa04365cce 100644 --- a/packages/provider-cursor/src/server/CursorSdk.test.ts +++ b/packages/provider-cursor/src/server/CursorSdk.test.ts @@ -6,6 +6,7 @@ import { vi } from "vite-plus/test"; import * as CursorSdk from "./CursorSdk.ts"; // Shaped like the SDK's minified class: the constructor is not named after the error. +// @effect-diagnostics-next-line extendsNativeError:off - mimics the Cursor SDK's own native Error class. class o extends Error { override name = "WriteIterableClosedError"; } diff --git a/packages/provider-cursor/src/server/sdk.test.ts b/packages/provider-cursor/src/server/sdk.test.ts index bd6de78dc3872..350598df7da95 100644 --- a/packages/provider-cursor/src/server/sdk.test.ts +++ b/packages/provider-cursor/src/server/sdk.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; const fixture = vi.hoisted(() => { + // @effect-diagnostics-next-line extendsNativeError:off - stands in for the Cursor SDK's native Error classes. class SdkError extends Error {} const sdk = { CursorSdkError: SdkError, diff --git a/packages/provider-grok/src/server/adapter.ts b/packages/provider-grok/src/server/adapter.ts index 35a8794619dff..9ed1368f16984 100644 --- a/packages/provider-grok/src/server/adapter.ts +++ b/packages/provider-grok/src/server/adapter.ts @@ -79,6 +79,8 @@ import { type AcpAdapterV2RuntimeInput, } from "@t3tools/provider-acp/server/adapter"; +const isXAiPromptFailureText = Schema.is(XAiPromptFailureText); + export const GROK_PROVIDER = ProviderDriverKind.make("grok"); const GROK_DRIVER_KIND = GROK_PROVIDER; export const GROK_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(GROK_DRIVER_KIND); @@ -306,10 +308,9 @@ export function makeGrokAcpAdapterFlavor( cause, ...(isAcpRequestError(cause) ? { - message: - cause.cause instanceof XAiPromptFailureText - ? cause.cause.message - : cause.errorMessage, + message: isXAiPromptFailureText(cause.cause) + ? cause.cause.message + : cause.errorMessage, code: String(cause.code), class: cause.code === xAiRateLimitedErrorCode ? "usage_limit" : "provider_error", } diff --git a/packages/provider-grok/src/server/xaiAcpExtension.ts b/packages/provider-grok/src/server/xaiAcpExtension.ts index d323c7d241392..fe356d0ec0483 100644 --- a/packages/provider-grok/src/server/xaiAcpExtension.ts +++ b/packages/provider-grok/src/server/xaiAcpExtension.ts @@ -1285,14 +1285,19 @@ function xAiPromptFailure( code: -32603, errorMessage: "Grok ended the turn with an error.", operation: "receive-response", - ...(agentResult === undefined ? {} : { cause: new XAiPromptFailureText(agentResult) }), + ...(agentResult === undefined + ? {} + : { cause: new XAiPromptFailureText({ message: agentResult }) }), }); } return null; } /** Keep unbounded provider text out of structured attributes; read only at presentation. */ -export class XAiPromptFailureText extends Error {} +export class XAiPromptFailureText extends Schema.TaggedError()( + "XAiPromptFailureText", + { message: Schema.String }, +) {} const registerXAiPromptCompletionFallback = ( pendingRef: Ref.Ref>, diff --git a/packages/provider-opencode/src/server/OpenCodeRuntime.ts b/packages/provider-opencode/src/server/OpenCodeRuntime.ts index f18ab07bbe19f..fffda5ff823b2 100644 --- a/packages/provider-opencode/src/server/OpenCodeRuntime.ts +++ b/packages/provider-opencode/src/server/OpenCodeRuntime.ts @@ -13,7 +13,6 @@ import { } from "@opencode-ai/sdk/v2"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; -import * as Data from "effect/Data"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -102,14 +101,18 @@ export interface OpenCodeServerConnection { } const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError"; -export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{ - readonly operation: string; - readonly cause?: unknown; - readonly detail: string; - readonly reason?: OpenCodeStartupFailureReason; -}> {} - -export type OpenCodeStartupFailureReason = "databaseLocked"; +const OpenCodeStartupFailureReason = Schema.Literal("databaseLocked"); +export type OpenCodeStartupFailureReason = typeof OpenCodeStartupFailureReason.Type; + +export class OpenCodeRuntimeError extends Schema.TaggedError()( + OPENCODE_RUNTIME_ERROR_TAG, + { + operation: Schema.String, + cause: Schema.optional(Schema.Defect()), + detail: Schema.String, + reason: Schema.optional(OpenCodeStartupFailureReason), + }, +) {} // Classify stderr database locks at exit so callers need not parse diagnostics. function classifyStartupExit(stderr: string): OpenCodeStartupFailureReason | undefined { diff --git a/packages/provider-opencode/src/server/status.ts b/packages/provider-opencode/src/server/status.ts index c113bd5551e84..b14333445ce01 100644 --- a/packages/provider-opencode/src/server/status.ts +++ b/packages/provider-opencode/src/server/status.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import type { OpenCodeSettings } from "../settings.ts"; import * as Cause from "effect/Cause"; -import * as Data from "effect/Data"; +import * as Schema from "effect/Schema"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Schedule from "effect/Schedule"; @@ -30,10 +30,12 @@ const OPENCODE_PRESENTATION = { showInteractionModeToggle: false, } as const; -class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{ - readonly cause?: unknown; - readonly detail: string; -}> {} +class OpenCodeProbeError extends Schema.TaggedError()("OpenCodeProbeError", { + cause: Schema.optional(Schema.Defect()), + detail: Schema.String, +}) {} + +const isOpenCodeProbeError = Schema.is(OpenCodeProbeError); function normalizeProbeMessage(message: string): string | undefined { const trimmed = message.trim(); @@ -50,7 +52,7 @@ function normalizeProbeMessage(message: string): string | undefined { } function normalizedErrorMessage(cause: unknown): string | undefined { - if (cause instanceof OpenCodeProbeError) { + if (isOpenCodeProbeError(cause)) { return normalizeProbeMessage(cause.detail); } diff --git a/packages/shared/src/Net.ts b/packages/shared/src/Net.ts index 9210b3d139224..40ef669db4e64 100644 --- a/packages/shared/src/Net.ts +++ b/packages/shared/src/Net.ts @@ -1,15 +1,15 @@ import * as NodeNet from "node:net"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Context from "effect/Context"; import * as Predicate from "effect/Predicate"; +import * as Schema from "effect/Schema"; -export class NetError extends Data.TaggedError("NetError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} +export class NetError extends Schema.TaggedError()("NetError", { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) {} const isErrnoExceptionWithCode = ( cause: unknown, diff --git a/packages/shared/src/managedPolicyFile.ts b/packages/shared/src/managedPolicyFile.ts index e6faf3b711239..2f775abb8a02a 100644 --- a/packages/shared/src/managedPolicyFile.ts +++ b/packages/shared/src/managedPolicyFile.ts @@ -186,14 +186,16 @@ const ERROR_NO_MORE_ITEMS = 259; // Value and key names are at most 16,383 characters. const MAX_NAME_CHARS = 16_384; -class Win32Failure extends Error { - readonly code: number; - constructor(code: number) { - super(`Windows error ${code}`); - this.code = code; +class Win32Failure extends Schema.TaggedError()("Win32Failure", { + code: Schema.Number, +}) { + override get message(): string { + return `Windows error ${this.code}`; } } +const isWin32Failure = Schema.is(Win32Failure); + /** * Each app passes how it loads ffi-rs: a server single-executable resolves packages on disk only * through `require`, and the desktop's CommonJS bundle loads them with `import()`. @@ -263,7 +265,7 @@ export const layerWindowsRegistry = (loadFfi: () => Promise Promise Promise Promise readKey(api, subkey), catch: (cause) => new WindowsRegistryError( - cause instanceof Win32Failure ? { code: cause.code, cause } : { cause }, + isWin32Failure(cause) ? { code: cause.code, cause } : { cause }, ), }); }), diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.ts index 7bce72d00d438..ae48676e6e171 100644 --- a/packages/shared/src/relayClient.ts +++ b/packages/shared/src/relayClient.ts @@ -66,24 +66,33 @@ class RelayClientLockRemoveError extends Schema.TaggedError {} +export class RelayClientInstallError extends Schema.TaggedError()( + "RelayClientInstallError", + { + reason: Schema.Literals([ + "download_failed", + "invalid_checksum", + "install_locked", + "managed_by_policy", + "override_missing", + "unsupported_platform", + "validation_failed", + "write_failed", + ]), + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} -class CloudflaredCommandError extends Data.TaggedError("CloudflaredCommandError")<{ - readonly command: string; - readonly exitCode: number; -}> {} +const isRelayClientInstallError = Schema.is(RelayClientInstallError); + +class CloudflaredCommandError extends Schema.TaggedError()( + "CloudflaredCommandError", + { + command: Schema.String, + exitCode: Schema.Number, + }, +) {} export interface CloudflaredReleaseAsset { readonly url: string; @@ -668,7 +677,7 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function }).pipe( Effect.scoped, Effect.catchIf( - (cause) => !(cause instanceof RelayClientInstallError), + (cause) => !isRelayClientInstallError(cause), (cause) => Effect.fail( new RelayClientInstallError({ diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts index 8583797a9688b..0048560977cdc 100644 --- a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts +++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts @@ -1,5 +1,4 @@ import { settingsSecretLiteral, SourceControlProviderKind } from "@t3tools/contracts"; -import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -318,10 +317,10 @@ export const makeDiscovery = Effect.gen(function* () { } satisfies SourceControlManagedCliDiscoverySpec; }); -class GitHubFailure extends Data.TaggedError("GitHubFailure")<{ - readonly detail: string; - readonly cause: unknown; -}> {} +class GitHubFailure extends Schema.TaggedError()("GitHubFailure", { + detail: Schema.String, + cause: Schema.Defect(), +}) {} const failure = (detail: string, cause?: unknown) => new GitHubFailure({ detail, cause }); diff --git a/packages/ssh/src/errors.ts b/packages/ssh/src/errors.ts index f1ba40b560c96..4199e2a2445f1 100644 --- a/packages/ssh/src/errors.ts +++ b/packages/ssh/src/errors.ts @@ -1,47 +1,62 @@ -import * as Data from "effect/Data"; - -export class SshHostDiscoveryError extends Data.TaggedError("SshHostDiscoveryError")<{ - readonly message: string; - readonly cause: unknown; -}> {} - -export class SshInvalidTargetError extends Data.TaggedError("SshInvalidTargetError")<{ - readonly message: string; -}> {} - -export class SshCommandError extends Data.TaggedError("SshCommandError")<{ - readonly message: string; - readonly command: readonly string[]; - readonly exitCode: number | null; - readonly stderr: string; - readonly stdout?: string; - readonly cause?: unknown; -}> {} - -export class SshLaunchError extends Data.TaggedError("SshLaunchError")<{ - readonly message: string; - readonly stdout: string; - readonly cause?: unknown; -}> {} - -export class SshPairingError extends Data.TaggedError("SshPairingError")<{ - readonly message: string; - readonly stdout: string; - readonly cause?: unknown; -}> {} - -export class SshHttpBridgeError extends Data.TaggedError("SshHttpBridgeError")<{ - readonly message: string; - readonly status?: number; - readonly cause?: unknown; -}> {} - -export class SshReadinessError extends Data.TaggedError("SshReadinessError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} - -export class SshPasswordPromptError extends Data.TaggedError("SshPasswordPromptError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} +import * as Schema from "effect/Schema"; + +export class SshHostDiscoveryError extends Schema.TaggedError()( + "SshHostDiscoveryError", + { + message: Schema.String, + cause: Schema.Defect(), + }, +) {} + +export class SshInvalidTargetError extends Schema.TaggedError()( + "SshInvalidTargetError", + { + message: Schema.String, + }, +) {} + +export class SshCommandError extends Schema.TaggedError()("SshCommandError", { + message: Schema.String, + command: Schema.Array(Schema.String), + exitCode: Schema.NullOr(Schema.Number), + stderr: Schema.String, + stdout: Schema.optional(Schema.String), + cause: Schema.optional(Schema.Defect()), +}) {} + +export class SshLaunchError extends Schema.TaggedError()("SshLaunchError", { + message: Schema.String, + stdout: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) {} + +export class SshPairingError extends Schema.TaggedError()("SshPairingError", { + message: Schema.String, + stdout: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) {} + +export class SshHttpBridgeError extends Schema.TaggedError()( + "SshHttpBridgeError", + { + message: Schema.String, + status: Schema.optional(Schema.Number), + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export class SshReadinessError extends Schema.TaggedError()( + "SshReadinessError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export class SshPasswordPromptError extends Schema.TaggedError()( + "SshPasswordPromptError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index b0ff65cba3af3..663f30fb40c48 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -8,6 +8,7 @@ import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as PlatformError from "effect/PlatformError"; +import * as Schema from "effect/Schema"; import * as Result from "effect/Result"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; @@ -19,6 +20,8 @@ import * as SshAuth from "./auth.ts"; import { SshCommandError, SshPasswordPromptError } from "./errors.ts"; import * as SshTunnel from "./tunnel.ts"; +const isSshCommandError = Schema.is(SshCommandError); + const makeSuccessfulProcess = (stdout: string) => { const stdoutStream = Stream.make(new TextEncoder().encode(stdout)); return ChildProcessSpawner.makeHandle({ @@ -202,7 +205,7 @@ describe("ssh tunnel scripts", () => { assert.isTrue(Result.isFailure(result)); if (Result.isFailure(result)) { assert.instanceOf(result.failure, SshCommandError); - if (result.failure instanceof SshCommandError) { + if (isSshCommandError(result.failure)) { assert.equal(result.failure.exitCode, 1); assert.equal(result.failure.stderr.length, 16_384); assert.isTrue(result.failure.stderr.endsWith(diagnostic)); @@ -260,7 +263,7 @@ describe("ssh tunnel scripts", () => { assert.isTrue(Result.isFailure(result)); if (Result.isFailure(result)) { assert.instanceOf(result.failure, SshCommandError); - if (result.failure instanceof SshCommandError) { + if (isSshCommandError(result.failure)) { assert.equal(result.failure.exitCode, 255); assert.equal(result.failure.stderr, diagnostic); } @@ -337,7 +340,7 @@ describe("ssh tunnel scripts", () => { if (Result.isFailure(result)) { if (expectedPromptAttempts.length === 0) { assert.instanceOf(result.failure, SshCommandError); - if (result.failure instanceof SshCommandError) { + if (isSshCommandError(result.failure)) { assert.equal(result.failure.stderr, stderr); } } else { diff --git a/scripts/mobile-e2e/device.ts b/scripts/mobile-e2e/device.ts index 7aac025443c21..f27092d35dcf7 100644 --- a/scripts/mobile-e2e/device.ts +++ b/scripts/mobile-e2e/device.ts @@ -3,6 +3,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodePath from "node:path"; import * as NodeProcess from "node:process"; +import * as Schema from "effect/Schema"; import type { Snapshot } from "./checks.ts"; import type { Pose } from "./poses.ts"; @@ -61,7 +62,11 @@ export interface Pool { readonly env: NodeJS.ProcessEnv; } -class AgentDeviceError extends Error {} +class AgentDeviceError extends Schema.TaggedError()("AgentDeviceError", { + message: Schema.String, +}) {} + +const isAgentDeviceError = Schema.is(AgentDeviceError); // A shared pool's workers drop off the gateway and stall under load for seconds at a time. const TRANSIENT = @@ -112,7 +117,7 @@ export class Device { try { return await this.agentOnce(args, options); } catch (error) { - if (attempt >= 5 || !(error instanceof AgentDeviceError) || !TRANSIENT.test(error.message)) + if (attempt >= 5 || !isAgentDeviceError(error) || !TRANSIENT.test(error.message)) throw error; await delay(5_000 * attempt); } @@ -137,10 +142,14 @@ export class Device { try { parsed = JSON.parse(stdout); } catch { - throw new AgentDeviceError(`agent-device ${args[0]}: ${(stderr || stdout).slice(-400)}`); + throw new AgentDeviceError({ + message: `agent-device ${args[0]}: ${(stderr || stdout).slice(-400)}`, + }); } if (!parsed.success) - throw new AgentDeviceError(`agent-device ${args.join(" ")}: ${parsed.error?.message}`); + throw new AgentDeviceError({ + message: `agent-device ${args.join(" ")}: ${parsed.error?.message}`, + }); return parsed.data ?? {}; } diff --git a/tsconfig.effect.json b/tsconfig.effect.json index dab2c98e7712e..144cd46b5c97a 100644 --- a/tsconfig.effect.json +++ b/tsconfig.effect.json @@ -98,6 +98,8 @@ "unnecessaryTypeofType": "error", "effectTryWithoutCatch": "error", "processEnvInEffect": "error", + "preferSchemaTaggedError": "error", + "extendsNativeError": "error", "schemaNumber": "off" }, "overrides": [ From 67eebaca23f8f7bc46e8817434087fc9c5acf8e3 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:52:36 +0530 Subject: [PATCH 006/397] fix(server): a stopped run no longer shrinks thread history to one row (#31266) Co-authored-by: Claude Opus 5.5 --- .../threadHistoryPaging.test.ts | 69 ++++++++++--------- .../orchestration-v2/threadHistoryPaging.ts | 4 +- 2 files changed, 40 insertions(+), 33 deletions(-) diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts index eba4ceec7f6c8..111cf0541358a 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts @@ -904,39 +904,46 @@ describe("threadHistoryPaging", () => { expect(bounded.projection.visibleTurnItems).toEqual(actionable.visibleTurnItems); }); - it("keeps agent-only turns visible when checkpoint file lists fill the byte budget", () => { - const items = Array.from({ length: 3 }, (_, turn) => { - const first = makeRow(turn * 5); - const prompt = { - ...first, - item: { - ...first.item, - type: "user_message" as const, - createdBy: "agent" as const, - creationSource: "provider" as const, - inputIntent: "turn_start" as const, - messageId: MessageId.make(`agent-prompt-${turn}`), - text: `Step ${turn}`, - attachments: [], - }, - } as OrchestrationV2ProjectedTurnItem; - return [prompt, ...Array.from({ length: 4 }, (_, index) => makeRow(turn * 5 + index + 1))]; - }).flat(); - const files = Array.from( - { length: 15_000 }, - (_, index) => - `work/ws-${index % 40}/.jj/repo/store/extra/${index.toString(16).padStart(40, "0")}`, - ); - const projection = { - ...makeProjection(items), - checkpoints: [{ id: "checkpoint-1", files }], - } as unknown as ReturnType; + it.each([false, true])( + "keeps agent-only turns visible when checkpoint file lists fill the byte budget (stored interrupt request: %s)", + (withInterruptRequest) => { + const items = Array.from({ length: 3 }, (_, turn) => { + const first = makeRow(turn * 5); + const prompt = { + ...first, + item: { + ...first.item, + type: "user_message" as const, + createdBy: "agent" as const, + creationSource: "provider" as const, + inputIntent: "turn_start" as const, + messageId: MessageId.make(`agent-prompt-${turn}`), + text: `Step ${turn}`, + attachments: [], + }, + } as OrchestrationV2ProjectedTurnItem; + return [prompt, ...Array.from({ length: 4 }, (_, index) => makeRow(turn * 5 + index + 1))]; + }).flat(); + const files = Array.from( + { length: 15_000 }, + (_, index) => + `work/ws-${index % 40}/.jj/repo/store/extra/${index.toString(16).padStart(40, "0")}`, + ); + const base = makeProjection(items); + const projection = { + ...base, + turnItems: withInterruptRequest + ? [interruptItem("old-interrupt-req", "run_interrupt_request", 0), ...base.turnItems] + : base.turnItems, + checkpoints: [{ id: "checkpoint-1", files }], + } as unknown as ReturnType; - const bounded = buildBoundedThreadProjection({ projection, snapshotSequence: 1 }); + const bounded = buildBoundedThreadProjection({ projection, snapshotSequence: 1 }); - expect(bounded.projection.visibleTurnItems).toHaveLength(items.length); - expect(bounded.hasMoreHistory).toBe(false); - }); + expect(bounded.projection.visibleTurnItems).toHaveLength(items.length); + expect(bounded.hasMoreHistory).toBe(false); + }, + ); it("keeps paged historical plan detail in the turn item and only status in its artifact", () => { const detail = "Implement the historical plan exactly.\n".repeat(1_000); diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.ts index abfaf0ade693b..8bc794ce36c4d 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts @@ -675,9 +675,9 @@ export function buildBoundedThreadProjection(input: { turnItems: [], visibleTurnItems: [], }); - // Keep the control-only window minimum, but required dependency cards claim their reserve first. + // Control state cannot be paged, so the window keeps half the budget; dependency cards take their reserve from that half. const windowBudget = Math.max( - dependencyReserve === 0 ? policy.maxEncodedBytes / 2 : 0, + Math.max(policy.maxEncodedBytes / 2 - dependencyReserve, 0), policy.maxEncodedBytes - dependencyReserve - controlBytes - 1_024, ); const windowPolicy: ThreadHistoryPagePolicy = { ...policy, maxEncodedBytes: windowBudget }; From 01a8db0aad27fa18010c552340e1b36168707ae8 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Thu, 5 Nov 2026 02:35:42 -0600 Subject: [PATCH 007/397] fix(server): refresh divergence after a merged branch ref changes (#31342) --- .../src/vcs/VcsStatusBroadcaster.test.ts | 19 +++++++++++-------- apps/server/src/vcs/VcsStatusBroadcaster.ts | 10 +--------- 2 files changed, 12 insertions(+), 17 deletions(-) diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index be3a286ffc32b..45b130f9a2b4b 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -382,13 +382,14 @@ describe("VcsStatusBroadcaster", () => { ); it.effect("refreshes a loaded cwd without reusing a previous branch's PR", () => { - const state = { + const state: Parameters[0] = { currentLocalStatus: baseLocalStatus, - currentRemoteStatus: baseRemoteStatus, + currentRemoteStatus: { ...baseRemoteStatus, aheadCount: 3, behindCount: 5 }, localStatusCalls: 0, remoteStatusCalls: 0, localInvalidationCalls: 0, remoteInvalidationCalls: 0, + remoteStatusRefreshUpstreamValues: [], }; return Effect.gen(function* () { @@ -400,9 +401,14 @@ describe("VcsStatusBroadcaster", () => { yield* broadcaster.getStatus({ cwd: "/repo" }); assert.equal(state.remoteStatusCalls, 1); - state.currentRemoteStatus = remoteStatusWithPr; + state.backgroundWorkEnabled = false; + state.currentRemoteStatus = { ...remoteStatusWithPr, aheadCount: 7 }; const refreshed = yield* broadcaster.refreshPullRequestStatus("/repo"); - assert.deepStrictEqual(refreshed, remoteStatusWithPr); + assert.deepStrictEqual(refreshed, state.currentRemoteStatus); + const merged = yield* broadcaster.getStatus({ cwd: "/repo" }); + assert.equal(merged.aheadCount, 7); + assert.equal(merged.behindCount, 0); + assert.equal(state.remoteStatusRefreshUpstreamValues?.at(-1), false); assert.equal(state.remoteStatusCalls, 2); assert.equal(state.remoteInvalidationCalls, 2); @@ -944,7 +950,7 @@ describe("VcsStatusBroadcaster", () => { }, ); - it.effect("recovers a discarded branch lookup on the next permitted turn-end refresh", () => { + it.effect("recovers a discarded branch lookup on the next turn-end refresh", () => { const state: Parameters[0] = { currentLocalStatus: baseLocalStatus, currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 3, behindCount: 5 }, @@ -983,9 +989,6 @@ describe("VcsStatusBroadcaster", () => { pr: { ...remoteStatusWithPr.pr!, number: 2979, headRef: "feature/next-status" }, }; state.backgroundWorkEnabled = false; - yield* broadcaster.refreshPullRequestStatus("/repo"); - assert.equal(state.remoteStatusCalls, 1); - state.backgroundWorkEnabled = true; const recovered = yield* broadcaster.refreshPullRequestStatus("/repo"); assert.deepStrictEqual(recovered, state.currentRemoteStatus); const cached = yield* broadcaster.getStatus({ cwd: "/repo" }); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 327e0bcb1bb41..7fee5379e4a3b 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -540,15 +540,7 @@ export const make = Effect.gen(function* () { Effect.gen(function* () { const cached = yield* getCachedStatus(cwd); if (!cached?.local || cached.remote?.value === null) return null; - const poller = (yield* SynchronizedRef.get(pollersRef)).get(cwd); - const demandCwds = poller ? [...(yield* Ref.get(poller.demandCwds)).keys()] : [rawCwd]; - const shouldRefresh = (yield* Effect.forEach( - demandCwds, - (demandCwd) => - backgroundPolicy.shouldRunScopeWork({ type: "vcs-status", cwd: demandCwd }), - { concurrency: "unbounded" }, - )).some(Boolean); - if (!shouldRefresh) return null; + // Turn completion must update divergence even when background polling is paused. const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream: false, refreshMissingPullRequest: true, From 8a14762c9093ea11e1e58d65cfe788f458a0d6b5 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Thu, 5 Nov 2026 14:16:54 +0530 Subject: [PATCH 008/397] fix(mobile): one aligned notice for ChatGPT sharing limits (#31277) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../threads/ChatGptUsageLimitNotice.tsx | 69 --------- .../features/threads/ThreadDetailScreen.tsx | 5 - .../threads/UsageLimitRecoveryCard.test.tsx | 96 ++++++++++++- .../threads/UsageLimitRecoveryCard.tsx | 133 ++++++++++++++---- 4 files changed, 200 insertions(+), 103 deletions(-) delete mode 100644 apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsx diff --git a/apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsx b/apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsx deleted file mode 100644 index faebfa5ddf927..0000000000000 --- a/apps/mobile/src/features/threads/ChatGptUsageLimitNotice.tsx +++ /dev/null @@ -1,69 +0,0 @@ -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; -import { - CHATGPT_USAGE_LIMIT_CODE, - CHATGPT_USAGE_URL, - CHATGPT_WORKSPACE_ADMIN_REQUEST, - CHATGPT_WORKSPACE_USAGE_LIMIT_CODE, -} from "@t3tools/shared/usageLimits"; -import * as Clipboard from "expo-clipboard"; -import { useState } from "react"; -import { Linking, View } from "react-native"; -import { ProviderIcon } from "../../components/ProviderIcon"; -import { AppText as Text } from "../../components/ui/AppText"; -import { Button } from "../../components/ui/Button"; - -export function ChatGptUsageLimitNotice({ thread }: { thread: EnvironmentThreadShell }) { - const [status, setStatus] = useState<"copied" | "copy-failed" | "open-failed" | null>(null); - const code = thread.runtime?.lastErrorCode; - const workspaceLimit = code === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE; - if (thread.runtime?.status !== "failed" || (!workspaceLimit && code !== CHATGPT_USAGE_LIMIT_CODE)) - return null; - return ( - - - - ChatGPT usage limit reached - - - {workspaceLimit - ? status === "copied" - ? "Request copied. Send it to your workspace admin." - : "You've reached your workspace's limit for using your ChatGPT plan in other apps. Copy a request to ask your workspace admin for increased usage limits." - : "Review your usage settings in ChatGPT."} - - {workspaceLimit ? ( - + ), View: ({ children }: { children: ReactNode }) =>
{children}
, })); +vi.mock("expo-clipboard", () => ({ setStringAsync: vi.fn() })); +vi.mock("../../components/ProviderIcon", () => ({ ProviderIcon: () => null })); vi.mock("../../components/ui/AppText", () => ({ AppText: ({ children }: { children: ReactNode }) => {children}, })); @@ -27,18 +40,97 @@ import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard"; const DAY_MS = 24 * 60 * 60 * 1000; -function failedThread(resetAt: string): EnvironmentThreadShell { +function failedThread( + resetAt: string | null, + lastErrorCode?: string, + lastErrorClass = "usage_limit", +): EnvironmentThreadShell { return { id: "thread-1", updatedAt: new Date(0).toISOString(), snoozedUntil: null, latestRun: { runId: "run-1", completedAt: new Date(0).toISOString() }, limitRecovery: null, - runtime: { status: "failed", lastErrorClass: "usage_limit", usageLimitResetAt: resetAt }, + runtime: { status: "failed", lastErrorClass, lastErrorCode, usageLimitResetAt: resetAt }, } as unknown as EnvironmentThreadShell; } describe("UsageLimitRecoveryCard", () => { + // Older servers report ChatGPT sharing limits as provider errors and may store a reset. + it.each([ + [CHATGPT_USAGE_LIMIT_CODE, "usage_limit", null, ["Manage usage"]], + [CHATGPT_WORKSPACE_USAGE_LIMIT_CODE, "usage_limit", null, ["Copy request for admin"]], + [CHATGPT_USAGE_LIMIT_CODE, "provider_error", null, ["Manage usage"]], + [ + CHATGPT_USAGE_LIMIT_CODE, + "usage_limit", + new Date(DAY_MS).toISOString(), + ["Manage usage", "Resume at reset", "Snooze until reset"], + ], + ])("shows one ChatGPT notice for %s (%s, reset %s)", (code, errorClass, resetAt, actions) => { + const container = document.createElement("div"); + const root = createRoot(container); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + act(() => + root.render( + , + ), + ); + expect(container.textContent).toContain("ChatGPT usage limit reached"); + expect(container.textContent).not.toContain("did not report a reset time"); + expect([...container.querySelectorAll("button")].map((button) => button.textContent)).toEqual( + actions, + ); + }); + + it("drops a failed copy's error once a retry copies the request", async () => { + vi.mocked(Clipboard.setStringAsync) + .mockRejectedValueOnce(new Error("denied")) + .mockResolvedValueOnce(true); + const container = document.createElement("div"); + const root = createRoot(container); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + act(() => + root.render( + , + ), + ); + const copy = () => container.querySelector("button")!.click(); + await act(async () => copy()); + expect(container.textContent).toContain("Could not copy the request"); + await act(async () => copy()); + expect(container.textContent).toContain("Request copied"); + expect(container.textContent).not.toContain("Could not copy the request"); + }); + + it("ignores a second copy while the first is still in flight", async () => { + const first = Promise.withResolvers(); + vi.mocked(Clipboard.setStringAsync).mockReset().mockReturnValueOnce(first.promise); + const container = document.createElement("div"); + const root = createRoot(container); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + act(() => + root.render( + , + ), + ); + const copy = () => container.querySelector("button")!.click(); + act(() => copy()); + act(() => copy()); + expect(Clipboard.setStringAsync).toHaveBeenCalledTimes(1); + await act(async () => first.resolve(true)); + expect(container.textContent).toContain("Request copied"); + }); + it("disables Snooze once a reset more than 24.8 days away passes", () => { using _timers = { [Symbol.dispose]: () => vi.useRealTimers() }; vi.useFakeTimers({ now: 0 }); diff --git a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx index 791dc2ab5d847..27fece0272be6 100644 --- a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx +++ b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx @@ -3,9 +3,17 @@ import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime" import { AsyncResult } from "effect/reactivity"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import type { EnvironmentId } from "@t3tools/contracts"; +import { + CHATGPT_USAGE_LIMIT_CODE, + CHATGPT_USAGE_URL, + CHATGPT_WORKSPACE_ADMIN_REQUEST, + CHATGPT_WORKSPACE_USAGE_LIMIT_CODE, +} from "@t3tools/shared/usageLimits"; import * as DateTime from "effect/DateTime"; +import * as Clipboard from "expo-clipboard"; import { useState } from "react"; -import { View } from "react-native"; +import { Linking, Pressable, View } from "react-native"; +import { ProviderIcon } from "../../components/ProviderIcon"; import { AppText as Text } from "../../components/ui/AppText"; import { useDeadlinePassed } from "../../lib/clock"; import { threadEnvironment } from "../../state/threads"; @@ -30,12 +38,22 @@ export function UsageLimitRecoveryCard({ const recovery = thread.limitRecovery; const scheduled = recovery?.runId === runId && recovery?.resetAt === resetAt && recovery?.autoResume; + const [copied, setCopied] = useState(false); + const [actionPending, setActionPending] = useState(false); + const code = thread.runtime?.lastErrorCode; + // OpenAI's partner guidelines specify the ChatGPT notice and its action. + const workspaceLimit = code === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE; + const chatGptLimit = workspaceLimit || code === CHATGPT_USAGE_LIMIT_CODE; if ( thread.runtime?.status !== "failed" || - thread.runtime.lastErrorClass !== "usage_limit" || + // Older servers report ChatGPT sharing limits as provider errors. + (thread.runtime.lastErrorClass !== "usage_limit" && !chatGptLimit) || !runId ) return null; + const resetText = resetAt + ? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.` + : null; const snoozed = recovery?.snooze === true && recovery.runId === runId && @@ -68,34 +86,95 @@ export function UsageLimitRecoveryCard({ setError(cause instanceof Error ? cause.message : "Could not change limit recovery."); } } + const action = workspaceLimit + ? { + label: "Copy request for admin", + role: "button" as const, + run: () => { + setError(null); + setCopied(false); + setActionPending(true); + void Clipboard.setStringAsync(CHATGPT_WORKSPACE_ADMIN_REQUEST) + .then( + () => setCopied(true), + () => setError("Could not copy the request. Try again."), + ) + .finally(() => setActionPending(false)); + }, + } + : { + label: "Manage usage", + role: "link" as const, + run: () => { + setError(null); + setActionPending(true); + void Linking.openURL(CHATGPT_USAGE_URL) + .catch(() => setError("Could not open ChatGPT. Go to chatgpt.com → Settings → Usage.")) + .finally(() => setActionPending(false)); + }, + }; return ( - - - {resetAt - ? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.` - : "The provider did not report a reset time. Retry manually when your limit is available."} - - {canSchedule ? ( - -
+ + ); +} + /** Permissions change rarely, so the footer names the mode and nests the choice in a menu. */ function PermissionsMenu(props: { runtimeMode: RuntimeMode; @@ -647,6 +681,7 @@ export function ComposerPickerFooter(props: { return (
{props.traits ? : null} + {props.traits ? : null} ; -// Ultracode changes the workflow, not only intensity, so it keeps its name like Ultrathink. +// Older servers offer Ultracode as a level. It changes the workflow, so it keeps its name. // Max is named too, so the full scale stops short of it. const NAMED_LEVELS = new Set(["ultracode", "max"]); const OFF_LEVELS = new Set(["off", "none"]); diff --git a/apps/web/src/components/chat/SubagentTooltipContent.tsx b/apps/web/src/components/chat/SubagentTooltipContent.tsx index a965e89efd728..5b5f8b3477420 100644 --- a/apps/web/src/components/chat/SubagentTooltipContent.tsx +++ b/apps/web/src/components/chat/SubagentTooltipContent.tsx @@ -50,16 +50,16 @@ export function SubagentTooltipContent(props: { result?: string | null | undefined; progress?: string | null | undefined; }) { - const { modelLabel, workspace: metadata } = resolveSubagentMetadata(props); - const preview = subagentDetailPreview(props); - const model = props.model?.trim(); - const modelSlug = props.provider - ? resolveSelectableModel(props.provider.driver, model, props.provider.models) - : model; - const providerModel = props.provider?.models.find((candidate) => candidate.slug === modelSlug); const childSelection = props.modelSelection ?? (props.origin === "app_owned" ? props.childThread?.modelSelection : undefined); + const { + modelLabel, + modelSlug, + workspace: metadata, + } = resolveSubagentMetadata({ ...props, modelSelection: childSelection }); + const preview = subagentDetailPreview(props); + const providerModel = props.provider?.models.find((candidate) => candidate.slug === modelSlug); const childModel = props.provider ? (resolveSelectableModel( props.provider.driver, @@ -69,7 +69,7 @@ export function SubagentTooltipContent(props: { : childSelection?.model.trim(); const provider = props.provider; const matchingSelection = - childModel === (modelSlug ?? model) && childSelection?.instanceId === props.providerInstanceId + childModel === modelSlug && childSelection?.instanceId === props.providerInstanceId ? childSelection : undefined; const effort = REASONING_EFFORT_OPTION_IDS.map((id) => diff --git a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx index 9d31ec35761e9..4cfb23350e912 100644 --- a/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx +++ b/apps/web/src/components/chat/ThreadLineageWorkflowRow.tsx @@ -1,6 +1,7 @@ -import type { - SubagentWorkflowGroup, - RuntimeSubagent, +import { + workflowMemberModelSelection, + type SubagentWorkflowGroup, + type RuntimeSubagent, } from "@t3tools/client-runtime/state/subagentRuntime"; import type { ProviderDriverKind, ProviderInstanceId, ServerProvider } from "@t3tools/contracts"; import { ChevronDownIcon, SquareIcon } from "lucide-react"; @@ -101,6 +102,7 @@ function WorkflowMemberRow({ model={member.model} providerInstanceId={providerInstanceId} origin="provider_native" + modelSelection={workflowMemberModelSelection(member, providerInstanceId)} provider={provider} providers={providers} driver={driver} diff --git a/apps/web/src/components/chat/WorkflowOpeningBlock.tsx b/apps/web/src/components/chat/WorkflowOpeningBlock.tsx index 3ab51f077e060..c6be9690e9940 100644 --- a/apps/web/src/components/chat/WorkflowOpeningBlock.tsx +++ b/apps/web/src/components/chat/WorkflowOpeningBlock.tsx @@ -1,6 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; import { isTerminalSubagentStatus, + workflowMemberModelSelection, workflowOpeningHeadline, type RuntimeSubagent, type WorkflowOpening, @@ -183,6 +184,7 @@ function WorkflowMemberRow(props: { model={member.model} providerInstanceId={props.providerInstanceId} origin="provider_native" + modelSelection={workflowMemberModelSelection(member, props.providerInstanceId)} provider={props.providers.find( (provider) => provider.instanceId === props.providerInstanceId, )} diff --git a/packages/client-runtime/src/modelTraits.ts b/packages/client-runtime/src/modelTraits.ts index b05f9226defb3..9a3dc06a15173 100644 --- a/packages/client-runtime/src/modelTraits.ts +++ b/packages/client-runtime/src/modelTraits.ts @@ -120,10 +120,12 @@ export function buildTraitsTriggerDisplay(input: { label: string; /** "Fast" or "Ultrafast" when a speed option is on. */ speedLabel: string | null; + ultracode: boolean; } { let fastModeFallbackLabel: string | null = null; let speedLabel: string | null = null; let reasoningLabelIndex = -1; + let ultracodeLabelIndex = -1; const labels: Array = []; for (const descriptor of input.descriptors) { if (descriptor.id === "fastMode" && descriptor.type === "boolean") { @@ -131,6 +133,13 @@ export function buildTraitsTriggerDisplay(input: { fastModeFallbackLabel = speedLabel ?? "Normal"; continue; } + if (descriptor.id === "ultracode" && descriptor.type === "boolean") { + if (descriptor.currentValue === true) { + ultracodeLabelIndex = labels.length; + labels.push(descriptor.label); + } + continue; + } if ( input.provider === "codex" && descriptor.id === "serviceTier" && @@ -173,8 +182,9 @@ export function buildTraitsTriggerDisplay(input: { } } + const ultracode = ultracodeLabelIndex >= 0; if (labels.length === 0 && fastModeFallbackLabel !== null) { - return { label: fastModeFallbackLabel, speedLabel }; + return { label: fastModeFallbackLabel, speedLabel, ultracode }; } if (speedLabel) { if (reasoningLabelIndex >= 0) { @@ -183,5 +193,5 @@ export function buildTraitsTriggerDisplay(input: { labels.push(speedLabel); } } - return { label: labels.join(" · "), speedLabel }; + return { label: labels.join(" · "), speedLabel, ultracode }; } diff --git a/packages/client-runtime/src/state/subagentDisplay.ts b/packages/client-runtime/src/state/subagentDisplay.ts index 124c45e264f79..c0763fa4c2f41 100644 --- a/packages/client-runtime/src/state/subagentDisplay.ts +++ b/packages/client-runtime/src/state/subagentDisplay.ts @@ -1,4 +1,5 @@ import type { + ModelSelection, OrchestrationV2TurnItemStatus, OrchestrationV2ThreadShell, OrchestrationProjectShell, @@ -50,6 +51,7 @@ export function formatSubagentDisplayTitle(title: string): string { export function resolveSubagentMetadata(input: { readonly model: string | null; + readonly modelSelection?: Pick | undefined; readonly provider?: Pick | null | undefined; readonly parentThread?: | Pick @@ -65,7 +67,7 @@ export function resolveSubagentMetadata(input: { | null | undefined; }) { - const model = input.model?.trim(); + const model = input.model?.trim() || input.modelSelection?.model.trim(); const slug = input.provider ? resolveSelectableModel(input.provider.driver, model, input.provider.models) : model; @@ -108,7 +110,7 @@ export function resolveSubagentMetadata(input: { ] : []), ]; - return { modelLabel, workspace }; + return { modelLabel, modelSlug: slug ?? model ?? null, workspace }; } export function subagentDetailPreview(input: { diff --git a/packages/client-runtime/src/state/subagentRuntime.test.ts b/packages/client-runtime/src/state/subagentRuntime.test.ts index c40c9fe42d81e..93d15b016d755 100644 --- a/packages/client-runtime/src/state/subagentRuntime.test.ts +++ b/packages/client-runtime/src/state/subagentRuntime.test.ts @@ -13,7 +13,10 @@ import { isWorkflowScriptMessage, projectedSubagentsToRuntime, resolveWorkflowOpening, + workflowMemberModelSelection, } from "./subagentRuntime.ts"; +import { resolveSubagentMetadata } from "./subagentDisplay.ts"; +import { formatSubagentEffort } from "./threadExecution.ts"; const at = (iso: string) => DateTime.makeUnsafe(iso); @@ -82,6 +85,42 @@ describe("projectedSubagentsToRuntime workflow expansion", () => { expect(settled?.speed).toBe("standard"); expect(settled?.progress).toBe("Reply with exactly: A1"); expect(settled?.usage).toEqual({ totalTokens: 71_141, toolUses: 3, durationMs: 1500 }); + const instanceId = ProviderInstanceId.make("claudeAgent"); + expect(workflowMemberModelSelection(settled!, instanceId)).toEqual({ + instanceId, + model: "claude-opus-5[1m]", + options: [ + { id: "effort", value: "xhigh" }, + { id: "fastMode", value: false }, + ], + }); + expect(workflowMemberModelSelection({ model: null, effort: "xhigh" }, instanceId)).toBe( + undefined, + ); + const provider = { + driver: ProviderDriverKind.make("claudeAgent"), + models: [ + { slug: "claude-opus-5", name: "Claude Opus 5", isCustom: false, capabilities: null }, + ], + }; + const modelSelection = workflowMemberModelSelection(settled!, instanceId); + const { modelSlug } = resolveSubagentMetadata({ + model: settled!.model, + modelSelection, + provider, + }); + expect(formatSubagentEffort({ modelSlug, modelSelection, provider })).toBe("xhigh"); + }); + + it("names a workflow by the model it runs on when the provider reports none", () => { + const [workflow] = projectedSubagentsToRuntime([subagent({ model: null })]); + expect( + resolveSubagentMetadata({ + model: workflow!.model, + modelSelection: { model: "claude-opus-5-5" }, + }).modelLabel, + ).toBe("Claude Opus 5.5"); + expect(resolveSubagentMetadata({ model: workflow!.model }).modelLabel).toBe("Not reported"); }); it.each(["completed", "cancelled", "failed"] as const)( diff --git a/packages/client-runtime/src/state/subagentRuntime.ts b/packages/client-runtime/src/state/subagentRuntime.ts index e3807362fbdf6..fac58a029ce62 100644 --- a/packages/client-runtime/src/state/subagentRuntime.ts +++ b/packages/client-runtime/src/state/subagentRuntime.ts @@ -1,6 +1,7 @@ import { groupBy } from "effect/Array"; import * as DateTime from "effect/DateTime"; import type { + ModelSelection, OrchestrationV2AppThread, OrchestrationV2Subagent, OrchestrationV2SubagentWorkflow, @@ -175,6 +176,21 @@ function workflowMembersToRuntime( }); } +export function workflowMemberModelSelection( + member: Pick, + instanceId: ModelSelection["instanceId"], +): ModelSelection | undefined { + if (!member.model) return undefined; + return { + instanceId, + model: member.model, + options: [ + ...(member.effort ? [{ id: "effort", value: member.effort }] : []), + ...(member.speed ? [{ id: "fastMode", value: member.speed === "fast" }] : []), + ], + }; +} + export function projectedSubagentsToRuntime( subagents: ReadonlyArray<{ readonly id: string; diff --git a/packages/client-runtime/src/state/threadExecution.test.ts b/packages/client-runtime/src/state/threadExecution.test.ts index ed60963ce7ef2..fd03b06b32017 100644 --- a/packages/client-runtime/src/state/threadExecution.test.ts +++ b/packages/client-runtime/src/state/threadExecution.test.ts @@ -14,6 +14,7 @@ import { type OrchestrationV2RunStatus, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import { createModelCapabilities, createModelSelection } from "@t3tools/shared/model"; import { usageLimitBlockedRun } from "@t3tools/shared/orchestrationV2ThreadError"; import { describe, expect, it } from "vite-plus/test"; @@ -26,6 +27,7 @@ import { deriveRunlessWorkStartedAt, deriveThreadActivityRun, deriveThreadRuntime, + formatModelSelectionEffort, isBackgroundWorkStopPending, presentPendingBackgroundWork, presentProviderGoal, @@ -473,6 +475,39 @@ describe("provider-reported model selection", () => { }); }); +describe("formatModelSelectionEffort", () => { + it("labels an old Ultracode effort by the effort it runs at", () => { + const models = [ + { + slug: "claude-opus-5-5", + name: "Claude Opus 5.5", + isCustom: false, + capabilities: createModelCapabilities({ + optionDescriptors: [ + { + id: "effort", + label: "Reasoning", + type: "select", + options: [ + { id: "high", label: "High", isDefault: true }, + { id: "xhigh", label: "Extra High" }, + ], + }, + { id: "ultracode", label: "Ultracode", type: "boolean" }, + ], + }), + }, + ]; + const selection = createModelSelection( + ProviderInstanceId.make("claudeAgent"), + "claude-opus-5-5", + [{ id: "effort", value: "ultracode" }], + ); + + expect(formatModelSelectionEffort(selection, models)).toBe("Extra High"); + }); +}); + describe("isBackgroundWorkStopPending", () => { const tasks = [{ taskId: "dev-server" }]; const sent = { threadKey: "env:thread", taskIds: ["dev-server"], retryAt: null }; diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index b6151c7c875be..f4335256e98fb 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -13,6 +13,7 @@ import { type OrchestrationV2NotificationSource, type OrchestrationV2PendingBackgroundTask, type OrchestrationV2ProviderGoal, + type ServerProvider, type ServerProviderModel, type OrchestrationV2ExecutionNode, type OrchestrationV2ThreadProjection, @@ -24,7 +25,13 @@ import { backgroundWorkHoldsCompletion, derivePendingBackgroundWork, } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; -import { getProviderOptionCurrentLabel, getProviderOptionStatedValue } from "@t3tools/shared/model"; +import { + getModelSelectionStringOptionValue, + getProviderOptionCurrentLabel, + getProviderOptionStatedValue, + resolveSelectableModel, + withLegacyUltracodeEffort, +} from "@t3tools/shared/model"; import { formatDuration } from "@t3tools/shared/orchestrationTiming"; import * as DateTime from "effect/DateTime"; @@ -164,16 +171,18 @@ export function formatModelSelectionEffort( ): string | null { const caps = models.find((model) => model.slug === selection.model)?.capabilities; if (!caps) return null; + const options = withLegacyUltracodeEffort(caps.optionDescriptors, selection.options); + const current = options ? { ...selection, options } : selection; for (const id of REASONING_EFFORT_OPTION_IDS) { const descriptor = caps.optionDescriptors?.find((candidate) => candidate.id === id); if (descriptor?.type !== "select") continue; - const value = getProviderOptionStatedValue(id, selection, reportedSelection); + const value = getProviderOptionStatedValue(id, current, reportedSelection); if (value === undefined && id !== "variant") continue; if (typeof value === "boolean") continue; // Bypass picker normalization so an obsolete choice cannot become a catalog default. const label = getProviderOptionCurrentLabel( { ...descriptor, currentValue: value }, - selection, + current, reportedSelection, ); if (label) return label; @@ -181,6 +190,28 @@ export function formatModelSelectionEffort( return null; } +/** A reported model the picker catalog does not know, such as `claude-opus-5[1m]`, keeps its raw effort. */ +export function formatSubagentEffort(input: { + readonly modelSlug: string | null; + readonly modelSelection: ModelSelection | undefined; + readonly provider: Pick | undefined; +}): string | null { + const { modelSlug, modelSelection: selection, provider } = input; + if (!provider || !selection || !modelSlug) return null; + const selectionSlug = + resolveSelectableModel(provider.driver, selection.model, provider.models) ?? + selection.model.trim(); + if (selectionSlug !== modelSlug) return null; + if (provider.models.some((model) => model.slug === modelSlug)) { + return formatModelSelectionEffort({ ...selection, model: modelSlug }, provider.models); + } + return ( + REASONING_EFFORT_OPTION_IDS.map((id) => getModelSelectionStringOptionValue(selection, id)).find( + Boolean, + ) ?? null + ); +} + const SUBAGENT_STATUS_LABELS: Record = { idle: "Idle", pending: "Working", diff --git a/packages/shared/src/model.test.ts b/packages/shared/src/model.test.ts index 396d4d9c86c26..af6af0254a94d 100644 --- a/packages/shared/src/model.test.ts +++ b/packages/shared/src/model.test.ts @@ -50,6 +50,32 @@ describe("descriptor helpers", () => { ).toEqual([{ id: "fastMode", value: true }]); }); + it("dispatches an old Ultracode effort as Extra High with the Ultracode toggle", () => { + const legacy = [{ id: "effort", value: "ultracode" }]; + const descriptors = getProviderOptionDescriptors({ + caps: createModelCapabilities({ + optionDescriptors: [ + { + id: "effort", + label: "Reasoning", + type: "select", + options: [ + { id: "high", label: "High", isDefault: true }, + { id: "xhigh", label: "Extra High" }, + ], + }, + { id: "ultracode", label: "Ultracode", type: "boolean" }, + ], + }), + selections: legacy, + }); + + expect(buildExplicitProviderOptionSelectionsFromDescriptors(descriptors, legacy)).toEqual([ + { id: "effort", value: "xhigh" }, + { id: "ultracode", value: true }, + ]); + }); + it("compares complete model selections independent of option ordering", () => { const left = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ { id: "reasoningEffort", value: "high" }, diff --git a/packages/shared/src/model.ts b/packages/shared/src/model.ts index 51cc1430321d8..0fdb2bc71ec4f 100644 --- a/packages/shared/src/model.ts +++ b/packages/shared/src/model.ts @@ -196,12 +196,40 @@ function withDescriptorCurrentValue( }; } +// Ultracode was a Claude effort level before it became its own toggle; that level ran at xhigh. +export function withLegacyUltracodeEffort< + Selections extends ReadonlyArray | null | undefined, +>( + descriptors: ReadonlyArray | null | undefined, + selections: Selections, +): Selections | Array { + if ( + getRawSelectionValueById(selections, "effort") !== "ultracode" || + !descriptors?.some( + (descriptor) => descriptor.id === "ultracode" && descriptor.type === "boolean", + ) + ) { + return selections; + } + return [ + ...(selections ?? []).map((selection) => + selection.id === "effort" && selection.value === "ultracode" + ? { id: "effort", value: "xhigh" } + : selection, + ), + ...(getRawSelectionValueById(selections, "ultracode") === undefined + ? [{ id: "ultracode", value: true }] + : []), + ]; +} + export function getProviderOptionDescriptors(input: { caps: ModelCapabilities; selections?: ReadonlyArray | null | undefined; }): ReadonlyArray { - const { caps, selections } = input; + const { caps } = input; const baseDescriptors = (caps.optionDescriptors ?? []).map(cloneDescriptor); + const selections = withLegacyUltracodeEffort(baseDescriptors, input.selections); return baseDescriptors.map((descriptor) => withDescriptorCurrentValue( @@ -312,7 +340,9 @@ export function buildExplicitProviderOptionSelectionsFromDescriptors( if (!selections || selections.length === 0) { return undefined; } - const explicitIds = new Set(selections.map((selection) => selection.id)); + const explicitIds = new Set( + withLegacyUltracodeEffort(descriptors, selections).map(({ id }) => id), + ); const normalized = buildProviderOptionSelectionsFromDescriptors(descriptors)?.filter( (selection) => explicitIds.has(selection.id), ); From 0ea3c0243fb5b3c07bb8c2bad01c1d3d0f5fde35 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Thu, 5 Nov 2026 23:53:37 +0300 Subject: [PATCH 046/397] perf(pr): pull requests paint from data already held, on web, desktop and mobile (#27798) Co-authored-by: Claude Opus 5.5 Co-authored-by: Julius Marminge Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> --- .../layout/AdaptiveWorkspaceLayout.tsx | 2 + .../PullRequestOverviewLoading.tsx | 11 +- .../pull-requests/PullRequestRouteScreen.tsx | 16 ++- .../pull-requests/PullRequestStackCard.tsx | 5 +- .../pull-requests/usePullRequestDiff.ts | 9 +- .../workspace/workspace-tab-navigation.ts | 10 +- apps/mobile/src/native/useOpenPullRequest.ts | 6 +- .../src/state/thread-pr-presentation.ts | 59 +++++++- apps/mobile/src/state/use-thread-pr.test.ts | 51 ++++++- apps/mobile/src/state/use-thread-pr.ts | 18 +++ .../pullRequest/PullRequestService.test.ts | 67 +++++++++ .../src/pullRequest/PullRequestService.ts | 19 ++- .../PullRequestLinkPreview.browser.test.tsx | 92 ++++++++++++ .../pullRequest/PullRequestLinkPreview.tsx | 51 ++++--- .../pullRequest/PullRequestListGroups.tsx | 36 ++++- .../components/pullRequest/PullRequestRow.tsx | 11 ++ .../pullRequest/PullRequestsPage.tsx | 16 ++- .../pullRequest/usePullRequestDetail.ts | 16 +++ ...PullRequestIntentPrefetch.browser.test.tsx | 86 +++++++++++ .../usePullRequestIntentPrefetch.ts | 51 +++++++ .../src/connection/storage.browser.test.ts | 72 ++++++++++ apps/web/src/connection/storage.ts | 135 +++++++++++++++++- .../src/state/pullRequestStatsPersistence.ts | 6 +- .../client-runtime/src/state/pullRequests.ts | 3 +- .../client-runtime/src/state/runtime.test.ts | 32 ++++- packages/client-runtime/src/state/runtime.ts | 6 +- .../src/server/GitHubPullRequestApi.test.ts | 85 ++++++++++- .../src/server/GitHubPullRequestApi.ts | 83 +++++++---- 28 files changed, 958 insertions(+), 96 deletions(-) create mode 100644 apps/web/src/components/pullRequest/PullRequestLinkPreview.browser.test.tsx create mode 100644 apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.browser.test.tsx create mode 100644 apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.ts create mode 100644 apps/web/src/connection/storage.browser.test.ts diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx index 354d6413549fe..02c18801445a1 100644 --- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx +++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx @@ -58,6 +58,7 @@ import type { ThreadListFilters } from "../../persistence/mobile-preferences"; import { appAtomRegistry } from "../../state/atom-registry"; import { useProjects } from "../../state/entities"; import { environmentThreadShells } from "../../state/threads"; +import { withKnownPullRequestSummary } from "../../state/use-thread-pr"; import { mobilePreferencesAtom } from "../../state/preferences"; import { DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS, @@ -589,6 +590,7 @@ function AdaptiveWorkspaceLayoutContent( columns: workspaceTabColumns(Platform.OS, tab, options?.columns ?? layout.usesSplitView), check: workspaceSelectionCheck, overlays, + seedPullRequest: withKnownPullRequestSummary, }, ); if (layout.variant === "medium") { diff --git a/apps/mobile/src/features/pull-requests/PullRequestOverviewLoading.tsx b/apps/mobile/src/features/pull-requests/PullRequestOverviewLoading.tsx index 647aa26e46373..2494dd93ea0fb 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestOverviewLoading.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestOverviewLoading.tsx @@ -1,6 +1,6 @@ import { Chip } from "../../components/ui/Chip"; import { PullRequestSectionHeading } from "./PullRequestSectionHeading"; -import type { PullRequestListEntry } from "@t3tools/contracts"; +import type { PullRequestListEntry, PullRequestSummary } from "@t3tools/contracts"; import { View } from "react-native"; import { PullRequestCardGroup, PullRequestCardRow } from "./PullRequestControls"; import { PullRequestStackCard } from "./PullRequestStackCard"; @@ -14,11 +14,14 @@ export function PullRequestOverviewLoading({ params, stack, }: { - readonly summary: PullRequestListEntry; + readonly summary: PullRequestListEntry | PullRequestSummary; readonly params: PullRequestParams; readonly stack: PullRequestStackState; }) { - const review = pullRequestListReviewStatus(summary); + const review = pullRequestListReviewStatus({ + reviewDecision: summary.reviewDecision ?? undefined, + viewerReviewRequested: "viewerReviewRequested" in summary && summary.viewerReviewRequested, + }); const conflicting = summary.mergeability === "conflicting"; const clean = summary.mergeability === "mergeable"; return ( @@ -89,7 +92,7 @@ export function PullRequestOverviewLoading({ - {summary.labels.length ? ( + {"labels" in summary && summary.labels.length ? ( {summary.labels.map((label) => ( diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx index 522a5eaf9a745..306864ecd237e 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx @@ -47,7 +47,11 @@ import { useFocusEffect, useNavigation, type StaticScreenProps } from "@react-na import type { NativeStackNavigationProp } from "@react-navigation/native-stack"; import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react"; import { pullRequestReviewKey } from "./pullRequestReviewDrafts"; -import { type PullRequestDetail, type PullRequestListEntry } from "@t3tools/contracts"; +import { + type PullRequestDetail, + type PullRequestListEntry, + type PullRequestSummary, +} from "@t3tools/contracts"; import { PullRequestOverviewLoading } from "./PullRequestOverviewLoading"; import { copyPullRequestLink, sharePullRequestLink } from "./pullRequestLink"; import { pullRequestStatus } from "./pullRequestStatus"; @@ -180,11 +184,11 @@ function usePullRequestActivityRows(params: PullRequestParams, filter: ActivityF } function PullRequestIdentity(props: { - readonly pr: PullRequestDetail | PullRequestListEntry; + readonly pr: PullRequestDetail | PullRequestListEntry | PullRequestSummary; readonly params: PullRequestParams; }) { const { pr } = props; - const status = pullRequestStatus(pr); + const status = pullRequestStatus({ state: pr.state, isDraft: pr.isDraft === true }); return ( @@ -196,8 +200,8 @@ function PullRequestIdentity(props: { {status.label} )} - - {"changedFiles" in pr ? ( + + {"changedFiles" in pr && pr.changedFiles !== undefined ? ( {pr.changedFiles} {pr.changedFiles === 1 ? "file" : "files"} @@ -209,7 +213,7 @@ function PullRequestIdentity(props: { {pr.title} - + {pr.author?.login ?? "Unknown author"} diff --git a/apps/mobile/src/features/pull-requests/PullRequestStackCard.tsx b/apps/mobile/src/features/pull-requests/PullRequestStackCard.tsx index cbb751c74c4c7..bdf4399f1e6cb 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestStackCard.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestStackCard.tsx @@ -9,6 +9,7 @@ import { pullRequestStatus } from "./pullRequestStatus"; import type { PullRequestParams } from "./usePullRequestDiff"; import type { PullRequestStackState } from "./usePullRequestStack"; import { PullRequestGlyph } from "./pullRequestGlyphs"; +import { withKnownPullRequestSummary } from "../../state/use-thread-pr"; export function PullRequestStackCard(props: { readonly params: PullRequestParams; @@ -67,7 +68,9 @@ export function PullRequestStackCard(props: { selected ? undefined : () => { - const params = pullRequestLayerParams(props.params, layer.number); + const params = withKnownPullRequestSummary( + pullRequestLayerParams(props.params, layer.number), + ); if (Platform.OS === "android") selectDetail({ name: "PullRequest", params }); else navigation.dispatch(StackActions.push("PullRequest", params)); diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts index 92e36f4486944..6f5180d8ab6bc 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts @@ -1,5 +1,10 @@ import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients"; -import { EnvironmentId, ProjectId, type PullRequestListEntry } from "@t3tools/contracts"; +import { + EnvironmentId, + ProjectId, + type PullRequestListEntry, + type PullRequestSummary, +} from "@t3tools/contracts"; import { useAtomRefresh } from "@effect/atom-react"; import { useLayoutEffect, useMemo, useState } from "react"; @@ -18,7 +23,7 @@ export type PullRequestParams = { readonly repository: string; readonly number: number; readonly host?: string; - readonly initialSummary?: PullRequestListEntry; + readonly initialSummary?: PullRequestListEntry | PullRequestSummary; }; export type PullRequestDiffParams = PullRequestParams & { readonly commit?: string }; diff --git a/apps/mobile/src/features/workspace/workspace-tab-navigation.ts b/apps/mobile/src/features/workspace/workspace-tab-navigation.ts index 3674c52972e03..bee1efc005fdc 100644 --- a/apps/mobile/src/features/workspace/workspace-tab-navigation.ts +++ b/apps/mobile/src/features/workspace/workspace-tab-navigation.ts @@ -150,6 +150,7 @@ function detailRoute( tab: "threads" | "pullRequests", selections: WorkspaceSelections, check: WorkspaceSelectionCheck, + seedPullRequest?: (identity: Omit) => object, ): RouteLike | undefined { if (tab === "threads") { const draft = selections.threadsDraft; @@ -184,7 +185,11 @@ function detailRoute( (route) => route.name === "PullRequest" && samePullRequest(pullRequestSelection(route.params), pullRequest), - ) ?? { key: pullRequest.key, name: "PullRequest", params: identityOf(pullRequest) } + ) ?? { + key: pullRequest.key, + name: "PullRequest", + params: seedPullRequest?.(identityOf(pullRequest)) ?? identityOf(pullRequest), + } ); } @@ -204,6 +209,7 @@ export function workspaceTabNavigationState< readonly columns: boolean; readonly check: WorkspaceSelectionCheck; readonly overlays?: readonly RouteLike[]; + readonly seedPullRequest?: (identity: Omit) => object; }, ) { const overlays = options.overlays ?? []; @@ -221,7 +227,7 @@ export function workspaceTabNavigationState< const home = state.routes.find((route) => route.name === "Home") ?? { name: "Home" }; const detail = options.columns && tab !== "usage" - ? detailRoute(state, tab, selections, options.check) + ? detailRoute(state, tab, selections, options.check, options.seedPullRequest) : undefined; const routes = [...[home, ...(detail ? [detail] : [])].map(keyed), ...overlays]; return { ...state, index: routes.length - 1, routes }; diff --git a/apps/mobile/src/native/useOpenPullRequest.ts b/apps/mobile/src/native/useOpenPullRequest.ts index 755f0b965ee09..fa7d437155b5e 100644 --- a/apps/mobile/src/native/useOpenPullRequest.ts +++ b/apps/mobile/src/native/useOpenPullRequest.ts @@ -7,6 +7,7 @@ import { useProjects, useThreadShell } from "../state/entities"; import { tryOpenExternalUrl } from "../lib/openExternalUrl"; import { appAtomRegistry } from "../state/atom-registry"; import { environmentServerConfigsAtom } from "../state/server"; +import { withKnownPullRequestSummary } from "../state/use-thread-pr"; type PullRequestContext = { readonly environmentId: string; readonly projectId: string }; @@ -19,10 +20,11 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean return async (url: string, context: PullRequestContext | null) => { // Read at press time so a config push does not hand every link a new handler. const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom); - const params = nativePullRequestDestination(url, context, projects, (environmentId) => + const destination = nativePullRequestDestination(url, context, projects, (environmentId) => serverConfigs.has(environmentId), ); - if (!params) return tryOpenExternalUrl(url, "pull-request"); + if (!destination) return tryOpenExternalUrl(url, "pull-request"); + const params = withKnownPullRequestSummary(destination); // Android shows one page at a time; iOS opens it over the current page, so Back returns. if (Platform.OS === "android") selectDetail({ name: "PullRequest", params }); else if (replace) navigation.dispatch(StackActions.replace("PullRequest", params)); diff --git a/apps/mobile/src/state/thread-pr-presentation.ts b/apps/mobile/src/state/thread-pr-presentation.ts index 2c151676f5c6c..a44f410b54ca3 100644 --- a/apps/mobile/src/state/thread-pr-presentation.ts +++ b/apps/mobile/src/state/thread-pr-presentation.ts @@ -1,13 +1,20 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; -import type { ThreadPullRequestLink, VcsStatusResult } from "@t3tools/contracts"; +import type { + PullRequestSummary, + ThreadPullRequestKey, + ThreadPullRequestLink, + VcsStatusResult, +} from "@t3tools/contracts"; import { sourceControlClients, type ChangeRequestTerminology, } from "@t3tools/client-runtime/source-control-clients"; import { + legacyThreadPullRequestKey, resolveThreadCurrentPullRequestLink, resolveThreadPullRequestBadge, + threadPullRequestKeyOf, } from "@t3tools/client-runtime/thread-pull-requests"; export type ThreadPr = NonNullable; @@ -142,3 +149,53 @@ export function rememberBounded( } return next; } + +/** The newest summary held for `pullRequest`, matched strictly by host, repository and number. */ +export function knownPullRequestSummary( + pullRequest: ThreadPullRequestKey, + threads: Iterable>, + summaries: Iterable, +): PullRequestSummary | undefined { + const key = threadPullRequestKeyOf(pullRequest); + let newest: + | { readonly summary: PullRequestSummary; readonly updatedAt: number; readonly readAt: number } + | undefined; + // Checks and reviews change without moving `updatedAt`, so equal versions prefer the later read. + const consider = (summary: PullRequestSummary, readAt = Number.NEGATIVE_INFINITY) => { + const updatedAt = Date.parse(summary.updatedAt); + if ( + newest === undefined || + updatedAt > newest.updatedAt || + (updatedAt === newest.updatedAt && readAt > newest.readAt) + ) { + newest = { summary, updatedAt, readAt }; + } + }; + for (const summary of summaries) { + if (threadPullRequestKeyOf(legacyThreadPullRequestKey(summary)) === key) { + consider(summary, summary.observedAt); + } + } + for (const thread of threads) { + for (const link of thread.pullRequests) { + const snapshot = link.snapshot; + if (snapshot?.updatedAt == null || threadPullRequestKeyOf(link) !== key) continue; + consider( + { + ...snapshot, + updatedAt: snapshot.updatedAt, + provider: ( + sourceControlClients.findByChangeRequestUrl(link.url) ?? + sourceControlClients.get(undefined) + ).kind, + projectId: thread.projectId, + repository: link.repository, + number: link.number, + url: link.url, + }, + Date.parse(snapshot.syncedAt), + ); + } + } + return newest?.summary; +} diff --git a/apps/mobile/src/state/use-thread-pr.test.ts b/apps/mobile/src/state/use-thread-pr.test.ts index 309953ddbdc3b..4edbb903dbebf 100644 --- a/apps/mobile/src/state/use-thread-pr.test.ts +++ b/apps/mobile/src/state/use-thread-pr.test.ts @@ -1,7 +1,13 @@ -import { ProjectId, type ThreadPullRequestLink } from "@t3tools/contracts"; +import { + ProjectId, + type PullRequestSummary, + SourceControlProviderKind, + type ThreadPullRequestLink, +} from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { + knownPullRequestSummary, presentThreadLinkedPullRequests, rememberBounded, resolveThreadPrSource, @@ -113,6 +119,49 @@ describe("resolveThreadPrSource compatibility", () => { }); }); +describe("knownPullRequestSummary", () => { + it("seeds from the newest summary of the same pull request, never another's", () => { + const projectId = ProjectId.make("project"); + const link = linkedPr(7); + const threads = [ + { + projectId, + pullRequests: [ + { ...link, snapshot: { ...link.snapshot!, updatedAt: "2026-09-08T00:00:00.000Z" } }, + ], + }, + ]; + const listed: PullRequestSummary = { + provider: SourceControlProviderKind.make("github"), + projectId, + repository: "t3tools/t3code", + number: 7, + title: "Listed title", + url: "https://github.com/t3tools/t3code/pull/7", + state: "open", + headBranch: "change-7", + baseBranch: "main", + updatedAt: "2026-09-09T00:00:00.000Z", + }; + const lookup = (host: string, number: number, summaries = [listed]) => + knownPullRequestSummary({ host, repository: "t3tools/t3code", number }, threads, summaries); + + expect(lookup("github.com", 7, [])?.title).toBe("Change 7"); + expect(lookup("github.com", 7)?.title).toBe("Listed title"); + expect(lookup("github.com", 8)).toBeUndefined(); + expect(lookup("gitlab.com", 7)).toBeUndefined(); + + const sameVersion = { ...listed, updatedAt: "2026-09-08T00:00:00.000Z" }; + const syncedAt = Date.parse(link.snapshot!.syncedAt); + expect(lookup("github.com", 7, [{ ...sameVersion, observedAt: syncedAt - 1 }])?.title).toBe( + "Change 7", + ); + expect(lookup("github.com", 7, [{ ...sameVersion, observedAt: syncedAt + 1 }])?.title).toBe( + "Listed title", + ); + }); +}); + describe("rememberBounded", () => { it("moves a re-answered entry to the newest slot and evicts the oldest past the limit", () => { let snapshots: ReadonlyMap = new Map(); diff --git a/apps/mobile/src/state/use-thread-pr.ts b/apps/mobile/src/state/use-thread-pr.ts index af14ce3827b4e..6c67e9f18f6b5 100644 --- a/apps/mobile/src/state/use-thread-pr.ts +++ b/apps/mobile/src/state/use-thread-pr.ts @@ -10,10 +10,13 @@ import { Atom } from "effect/reactivity"; import { use, useMemo } from "react"; import { connectionAtomRuntime } from "../connection/runtime"; +import { appAtomRegistry } from "./atom-registry"; import { serverEnvironment } from "./server"; +import { environmentThreadShells } from "./threads"; import { useEnvironmentQuery } from "./query"; import { ThreadPrDemandContext } from "./thread-pr-demand"; import { + knownPullRequestSummary, rememberBounded, resolveThreadPrSource, presentThreadPr, @@ -59,6 +62,21 @@ const pullRequestSummaryAtom = createLinkedPullRequestSummaryAtomFamily( export { type ThreadPr, type ThreadPrPresentation } from "./thread-pr-presentation"; +/** Seeds a pull request page with a summary already in memory, never another pull request's. */ +export function withKnownPullRequestSummary< + Params extends { readonly host?: string; readonly repository: string; readonly number: number }, +>(params: Params) { + const initialSummary = + params.host === undefined + ? undefined + : knownPullRequestSummary( + { host: params.host, repository: params.repository, number: params.number }, + appAtomRegistry.get(environmentThreadShells.threadShellsAtom), + appAtomRegistry.get(pullRequestSnapshotsAtom).values(), + ); + return initialSummary === undefined ? params : { ...params, initialSummary }; +} + export function useThreadPr(thread: EnvironmentThreadShell): ThreadPrPresentation | null { const demand = use(ThreadPrDemandContext); const supportsLinks = useAtomValue( diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 93aa60cd2c97c..50581506ea1e3 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -202,6 +202,73 @@ it.effect("does not wait for an in-flight detail read to display a preview", () }), ); +it.effect("shows a listed pull request's preview without asking the host again", () => + Effect.gen(function* () { + let previewReads = 0; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + listChangeRequests: () => + Effect.succeed({ + items: [changeRequest(1, "2026-07-02T00:00:00Z")], + truncated: false, + continues: false, + }), + getChangeRequestPreview: () => + Effect.sync(() => { + previewReads++; + return { ...changeRequest(1, "2026-07-02T00:00:00Z"), title: "Renamed" }; + }), + }), + ], + }); + const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + yield* service.list({ state: "open" }); + assert.strictEqual((yield* service.preview(ref)).title, "Change request 1"); + assert.strictEqual(previewReads, 0); + yield* service.refreshAfterTurn(ref.projectId); + assert.strictEqual((yield* service.preview(ref)).title, "Renamed"); + assert.strictEqual(previewReads, 1); + yield* service.list({ state: "open", limit: 1 }); + assert.strictEqual((yield* service.preview(ref)).title, "Renamed"); + }), +); + +it.effect("a list read under a pinned account leaves the shared preview to the host", () => + Effect.gen(function* () { + let previewReads = 0; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getRoutingIdentity: () => Effect.succeed({ accountId: "101", viewer: "octocat" }), + withVerifiedCredential: (_, use) => + use({ accountId: "101", viewer: "octocat", credentialFingerprint: "pinned" }), + listChangeRequests: () => + Effect.succeed({ + items: [{ ...changeRequest(1, "2026-07-02T00:00:00Z"), title: "Pinned view" }], + truncated: false, + continues: false, + }), + getChangeRequestPreview: () => + Effect.sync(() => { + previewReads++; + return changeRequest(1, "2026-07-02T00:00:00Z"); + }), + }), + ], + }); + const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + yield* service.withRoutingCredential( + { ...ref, host: "github.com", expectedAccountId: "101" }, + service.list({ state: "open" }), + ); + assert.strictEqual((yield* service.preview(ref)).title, "Change request 1"); + assert.strictEqual(previewReads, 1); + }), +); + function unusable(provider: SourceControlProviderKind, reason: "missing-tool" | "unauthenticated") { return new PullRequestProviderError({ provider, diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index e77434c1697b3..304ce2d3fa52b 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -1262,6 +1262,7 @@ export const make = Effect.gen(function* () { "PullRequestService.listUncached", )(function* (input) { const involvement = input.involvement ?? "all"; + const epochAtStart = epochCounter; const continuation = yield* decodeCursors(input.cursors); const { supported: projects, unimplemented, viewerRoots } = yield* listWorkspaceProjects(input); const projectCounts = new Map(); @@ -1549,13 +1550,25 @@ export const make = Effect.gen(function* () { for (const batch of batches) { if (batch.nextCursor !== null) nextCursors[batch.key] = batch.nextCursor; } + const entries = batches + .flatMap((batch) => batch.entries) + .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)); + // Hover cards on listed rows read from here. A pinned account or a mid-read refresh is another + // scope; half the cache stays free for previews read directly. + if ((yield* routingCredential) === null && epochCounter === epochAtStart) { + const seeds = entries + .slice(0, DETAIL_CACHE_CAPACITY / 2) + .map((entry) => [refCacheKey(entry), previewFields(entry)] as const) + .toReversed(); + for (const [key, value] of seeds) { + if (!(yield* Cache.has(previewCache, key))) yield* Cache.set(previewCache, key, value); + } + } return { viewers: viewers as PullRequestListResult["viewers"], providers, - entries: batches - .flatMap((batch) => batch.entries) - .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)), + entries, errors: [...unreadable, ...batches.flatMap((batch) => batch.errors)], truncated: batches.some((batch) => batch.truncated), nextCursors, diff --git a/apps/web/src/components/pullRequest/PullRequestLinkPreview.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestLinkPreview.browser.test.tsx new file mode 100644 index 0000000000000..29f0211eaef83 --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestLinkPreview.browser.test.tsx @@ -0,0 +1,92 @@ +import { EnvironmentId, ProjectId, type PullRequestSummary } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +const known = vi.hoisted( + () => + ({ + provider: "github", + projectId: "project", + repository: "owner/repo", + number: 1, + title: "Known title", + url: "https://github.com/owner/repo/pull/1", + state: "open", + headBranch: "feature", + baseBranch: "main", + updatedAt: "2026-09-01T00:00:00Z", + }) as PullRequestSummary, +); +const state = vi.hoisted(() => ({ restoredPreview: null as unknown })); +vi.mock(import("~/state/query"), async (original) => ({ + ...(await original()), + // The host has not answered the preview read yet. + useEnvironmentQuery: ((atom: unknown) => ({ + data: state.restoredPreview, + dataUpdatedAt: 0, + error: null, + failure: null, + isPending: atom !== null, + isSuccess: false, + refresh: () => undefined, + })) as never, +})); +vi.mock(import("~/state/pullRequests"), async (original) => ({ + ...(await original()), + useSharedPullRequestSummary: (() => known) as never, +})); + +import { render } from "../../../test/render"; +import { PullRequestLinkPreview } from "./PullRequestLinkPreview"; + +function renderPreview() { + return render( + #1} + originalUrl={known.url} + target={{ + environmentId: EnvironmentId.make("environment"), + input: { projectId: ProjectId.make("project"), repository: "owner/repo", number: 1 }, + }} + />, + ); +} + +it("keeps a refreshing preview's state and title over an older known summary", async () => { + state.restoredPreview = { + projectId: "project", + repository: "owner/repo", + number: 1, + title: "Renamed title", + url: known.url, + author: { login: "octocat" }, + state: "closed", + isDraft: false, + createdAt: "2026-08-01T00:00:00Z", + }; + await using screen = await renderPreview(); + + await userEvent.hover(screen.getByRole("link")); + + await expect.element(page.getByText("Renamed title")).toBeVisible(); + await expect.element(page.getByText("Closed", { exact: true })).toBeVisible(); + expect(page.getByText("Known title").query()).toBeNull(); +}); + +it("shows the known summary while the preview loads", async () => { + state.restoredPreview = null; + await using screen = await render( + #1} + originalUrl={known.url} + target={{ + environmentId: EnvironmentId.make("environment"), + input: { projectId: ProjectId.make("project"), repository: "owner/repo", number: 1 }, + }} + />, + ); + + await userEvent.hover(screen.getByRole("link")); + + await expect.element(page.getByText("Known title")).toBeVisible(); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestLinkPreview.tsx b/apps/web/src/components/pullRequest/PullRequestLinkPreview.tsx index f5ed4ea6553bf..8e3ee75602342 100644 --- a/apps/web/src/components/pullRequest/PullRequestLinkPreview.tsx +++ b/apps/web/src/components/pullRequest/PullRequestLinkPreview.tsx @@ -12,7 +12,7 @@ import { } from "react"; import { RelativeTime } from "~/components/RelativeTime"; -import { pullRequestEnvironment } from "~/state/pullRequests"; +import { pullRequestEnvironment, useSharedPullRequestSummary } from "~/state/pullRequests"; import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; import { useEnvironmentQuery } from "~/state/query"; @@ -57,6 +57,10 @@ export function PullRequestLinkPreview({ }) : null, ); + const summary = useSharedPullRequestSummary( + open ? target.environmentId : null, + open ? target.input : null, + ); const readPreview = useAtomQueryRunner(pullRequestEnvironment.preview, { reportFailure: false, reportDefect: false, @@ -85,18 +89,19 @@ export function PullRequestLinkPreview({ }) : link; const preview = previewQuery.data; - const showCard = preview !== null || (previewQuery.error !== null && fallback !== undefined); + const card = preview ?? summary; + const showCard = card !== null || (previewQuery.error !== null && fallback !== undefined); const showUrlTooltip = open && previewQuery.error !== null && !showCard; const state = - preview === null + card === null ? null - : resolvePullRequestState({ state: preview.state, isDraft: preview.isDraft }); + : resolvePullRequestState({ state: card.state, isDraft: card.isDraft ?? false }); const authorLabel = - preview?.author === null + card?.author === null ? "ghost" - : preview?.author.name && preview.author.name !== preview.author.login - ? `${preview.author.name} (@${preview.author.login})` - : (preview?.author.login ?? null); + : card?.author?.name && card.author.name !== card.author.login + ? `${card.author.name} (@${card.author.login})` + : (card?.author?.login ?? null); return ( @@ -116,13 +121,13 @@ export function PullRequestLinkPreview({ {showCard ? (
- {preview === null ? ( + {card === null ? ( fallback ) : (
- {preview.repository} - #{preview.number} + {card.repository} + #{card.number} · {state === null ? null : ( @@ -132,16 +137,22 @@ export function PullRequestLinkPreview({ )}

- {preview.title} + {card.title}

-
- - {authorLabel} - · - - opened - -
+ {card.author === undefined ? null : ( +
+ + {authorLabel} + {preview === null ? null : ( + <> + · + + opened + + + )} +
+ )}
)}
diff --git a/apps/web/src/components/pullRequest/PullRequestListGroups.tsx b/apps/web/src/components/pullRequest/PullRequestListGroups.tsx index 7e8c4e3a26f10..4eb994f7c6627 100644 --- a/apps/web/src/components/pullRequest/PullRequestListGroups.tsx +++ b/apps/web/src/components/pullRequest/PullRequestListGroups.tsx @@ -1,6 +1,6 @@ import type { EnvironmentId, PullRequestAction } from "@t3tools/contracts"; import { EyeIcon, LayersIcon, PenLineIcon, UsersIcon, type LucideIcon } from "lucide-react"; -import type { RefCallback } from "react"; +import { useDeferredValue, type RefCallback } from "react"; import { cn } from "~/lib/utils"; import { Separator } from "../ui/separator"; @@ -23,18 +23,32 @@ const GROUP_ICONS: Record = { }; const MATCHED_ELSEWHERE_SCORE = 10; +const FIRST_PAINT_ROWS = 24; + +function firstPaintGroups }>( + groups: ReadonlyArray, +): ReadonlyArray { + let left = FIRST_PAINT_ROWS; + return groups.flatMap((group) => { + const entries = group.entries.slice(0, left); + left -= entries.length; + return entries.length === 0 ? [] : [{ ...group, entries }]; + }); +} function PullRequestGroupHeader({ group, + count, }: { - group: { key: string; label: string; entries: ReadonlyArray }; + group: { key: string; label: string }; + count: number; }) { const Icon = GROUP_ICONS[group.key] ?? LayersIcon; return (

{group.label}

- {group.entries.length} + {count}
); @@ -48,6 +62,7 @@ export function PullRequestListGroups({ showProvider, statsRef, onSelect, + onIntent, hostActionsOf, onActed, closingKeys, @@ -67,18 +82,28 @@ export function PullRequestListGroups({ showProvider: boolean; statsRef: RefCallback; onSelect: (entry: PullRequestRowTarget) => void; + onIntent: (entry: PullRequestRowTarget | null) => void; hostActionsOf: (entry: EnvironmentPullRequestEntry) => ReadonlySet; onActed: (result: PullRequestSpeedActionResult) => void; closingKeys: ReadonlySet; sweepingKeys: ReadonlySet; onCloseSweepStart: (entry: EnvironmentPullRequestEntry, event: PointerEvent) => void; }) { + // Every row mounts tooltips and actions; painting a first screenful before the rest keeps + // opening the page from blocking on the whole list. + const shownGroups = useDeferredValue(groups, firstPaintGroups(groups)); + const counts = new Map(groups.map((group) => [group.key, group.entries.length])); return (
0 && "**:pointer-events-none")}> - {groups.map((group) => ( + {shownGroups.map((group) => (
- {group.label ? : null} + {group.label ? ( + + ) : null} {group.entries.map((entry) => { const entryKey = pullRequestEntryKey(entry); const environmentLabel = environmentLabels?.get(entry.environmentId); @@ -102,6 +127,7 @@ export function PullRequestListGroups({ selected.number === entry.number } onSelect={onSelect} + onIntent={onIntent} hostActions={hostActionsOf(entry)} onActed={onActed} closing={closingKeys.has(entryKey)} diff --git a/apps/web/src/components/pullRequest/PullRequestRow.tsx b/apps/web/src/components/pullRequest/PullRequestRow.tsx index 3b4d1f84c01d9..71fbf1100d554 100644 --- a/apps/web/src/components/pullRequest/PullRequestRow.tsx +++ b/apps/web/src/components/pullRequest/PullRequestRow.tsx @@ -78,6 +78,7 @@ function PullRequestRowImpl({ statsKey, statsRef, onSelect, + onIntent, hostActions, onActed, closing = false, @@ -94,6 +95,8 @@ function PullRequestRowImpl({ statsKey?: string; statsRef?: RefCallback; onSelect: (entry: PullRequestRowTarget) => void; + /** The row the pointer or focus rests on, or null when it leaves. */ + onIntent?: (entry: PullRequestRowTarget | null) => void; hostActions: ReadonlySet; onActed: (result: PullRequestSpeedActionResult) => void; closing?: boolean; @@ -115,6 +118,14 @@ function PullRequestRowImpl({ type="button" aria-current={selected ? "true" : undefined} onClick={() => onSelect(entry)} + onPointerEnter={() => onIntent?.(entry)} + onPointerLeave={(event) => { + if (event.currentTarget !== document.activeElement) onIntent?.(null); + }} + onFocus={() => onIntent?.(entry)} + onBlur={(event) => { + if (!event.currentTarget.matches(":hover")) onIntent?.(null); + }} className={cn( PULL_REQUEST_ROW_CLASS, PAGE_ROW_CLASS, diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx index 1b3d1bc74c186..0fc32bce3257a 100644 --- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx @@ -64,6 +64,8 @@ import { PullRequestCompactFilterMenu } from "./PullRequestCompactFilterMenu"; import { INVOLVEMENT_TABS, SORT_OPTIONS, STATE_TABS } from "./pullRequestListOptions"; import { PullRequestsColumn } from "./PullRequestsColumn"; import { PullRequestListGroups } from "./PullRequestListGroups"; +import { pullRequestPanelReference } from "./usePullRequestDetail"; +import { usePullRequestIntentPrefetch } from "./usePullRequestIntentPrefetch"; import { usePullRequestDisplayGroups, usePullRequestQueryFilters, @@ -1080,6 +1082,9 @@ export function PullRequestsPage() { ), ); + const prefetchEntry = usePullRequestIntentPrefetch((entry) => + listedPullRequestsBySurface.has(pullRequestListEntryId(entry)), + ); const selectEntry = (entry: PullRequestRowTarget) => { if (rightPanelRef === null) return; useRightPanelStore.getState().openPullRequest(rightPanelRef, entry); @@ -1184,6 +1189,7 @@ export function PullRequestsPage() { showProvider={showProvider} statsRef={registerStatsRow} onSelect={selectEntry} + onIntent={prefetchEntry} hostActionsOf={hostActionsOf} onActed={onSpeedAction} closingKeys={closingKeys} @@ -1528,14 +1534,10 @@ export function PullRequestsPage() { selectedEnvironmentId: panelEnvironmentId, }); }} - reference={{ + reference={pullRequestPanelReference({ + ...renderedPullRequestSurface, projectId: renderedPullRequestSurface.projectId as ProjectId, - repository: renderedPullRequestSurface.repository, - number: renderedPullRequestSurface.number, - ...(renderedPullRequestSurface.host - ? { host: renderedPullRequestSurface.host } - : {}), - }} + })} listEntry={ listedPullRequestsBySurface.get( pullRequestListEntryId(renderedPullRequestSurface), diff --git a/apps/web/src/components/pullRequest/usePullRequestDetail.ts b/apps/web/src/components/pullRequest/usePullRequestDetail.ts index 7451ee38c5fee..7d6ab0c7a6154 100644 --- a/apps/web/src/components/pullRequest/usePullRequestDetail.ts +++ b/apps/web/src/components/pullRequest/usePullRequestDetail.ts @@ -4,6 +4,7 @@ import { type EnvironmentId, type PullRequestListEntry, type PullRequestRef, + type ProjectId, } from "@t3tools/contracts"; import { useState } from "react"; @@ -22,6 +23,21 @@ import { resolveDisplayedPullRequestDetail, } from "./pullRequestDetail.logic"; +// Query atoms key on JSON order, so the panel and the row prefetch must build the ref here. +export function pullRequestPanelReference(target: { + readonly projectId: ProjectId; + readonly repository: string; + readonly number: number; + readonly host?: string | undefined; +}): PullRequestRef { + return { + projectId: target.projectId, + repository: target.repository, + number: target.number, + ...(target.host ? { host: target.host } : {}), + }; +} + export function pullRequestRefKey(reference: PullRequestRef) { return `${reference.projectId}:${reference.host ?? ""}:${reference.repository}#${reference.number}`; } diff --git a/apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.browser.test.tsx b/apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.browser.test.tsx new file mode 100644 index 0000000000000..366fb4cfe76e4 --- /dev/null +++ b/apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.browser.test.tsx @@ -0,0 +1,86 @@ +import { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +const state = vi.hoisted(() => ({ reads: [] as Array })); +vi.mock(import("~/state/pullRequests"), async (original) => { + const actual = await original(); + return { + ...actual, + pullRequestEnvironment: { + ...actual.pullRequestEnvironment, + detail: ((target: unknown) => target) as never, + }, + }; +}); +vi.mock(import("~/state/query"), async (original) => ({ + ...(await original()), + useEnvironmentQuery: ((target: unknown) => { + if (target !== null || state.reads.length > 0) state.reads.push(target); + return {}; + }) as never, +})); + +import { act, fakeTimers, render } from "../../../test/render"; +import { usePullRequestIntentPrefetch } from "./usePullRequestIntentPrefetch"; + +const environmentId = EnvironmentId.make("environment"); +const row = { + environmentId, + projectId: ProjectId.make("project"), + host: "GitHub.com", + repository: "owner/repo", + number: 7, +}; + +function Rows() { + const prefetch = usePullRequestIntentPrefetch(() => true); + return ( + <> + + + + ); +} + +it("reads the panel's detail once intent rests on a row for 150 ms", async () => { + state.reads = []; + await using screen = await render(, { + // A bare hook probe; nothing here navigates. + router: false, + }); + using _timers = fakeTimers({ now: 0 }); + const rest = screen.getByRole("button", { name: "rest" }).element() as HTMLElement; + const leave = screen.getByRole("button", { name: "leave" }).element() as HTMLElement; + + await act(() => { + rest.click(); + leave.click(); + }); + await act(() => vi.advanceTimersByTime(1_000)); + expect(state.reads).toEqual([]); + + await act(() => rest.click()); + await act(() => vi.advanceTimersByTime(149)); + expect(state.reads).toEqual([]); + await act(() => vi.advanceTimersByTime(1)); + // Query atoms key on JSON order: this is the order the PRs page panel reads. + expect(JSON.stringify(state.reads.at(-1))).toBe( + JSON.stringify({ + environmentId, + input: { + projectId: row.projectId, + repository: "owner/repo", + number: 7, + host: "github.com", + allowStale: false, + }, + }), + ); + + await act(() => leave.click()); + expect(state.reads.at(-1)).toBeNull(); +}); diff --git a/apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.ts b/apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.ts new file mode 100644 index 0000000000000..a078ce2c94ff7 --- /dev/null +++ b/apps/web/src/components/pullRequest/usePullRequestIntentPrefetch.ts @@ -0,0 +1,51 @@ +import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { useRef, useState } from "react"; + +import { useStableCallback } from "~/hooks/useStableCallback"; +import { pullRequestEnvironment } from "~/state/pullRequests"; +import { useEnvironmentQuery } from "~/state/query"; + +import { pullRequestPanelReference } from "./usePullRequestDetail"; + +const INTENT_DELAY_MS = 150; + +interface PullRequestIntentTarget { + readonly environmentId: EnvironmentId; + readonly projectId: ProjectId; + readonly host: string; + readonly repository: string; + readonly number: number; +} + +/** + * Reads the detail a row's panel will ask for once the pointer or focus rests on it, so the + * click paints from it. Passing over rows asks the host nothing, and leaving a row stops reading it. + */ +export function usePullRequestIntentPrefetch( + isListed: (target: PullRequestIntentTarget) => boolean, +) { + const [target, setTarget] = useState(null); + const timer = useRef | undefined>(undefined); + // A removed row fires no leave event. + const listed = target !== null && isListed(target); + if (target !== null && !listed) setTarget(null); + useEnvironmentQuery( + target === null || !listed + ? null + : pullRequestEnvironment.detail({ + environmentId: target.environmentId, + input: { + ...pullRequestPanelReference({ ...target, host: target.host.toLowerCase() }), + allowStale: false, + }, + }), + ); + return useStableCallback((next: PullRequestIntentTarget | null) => { + clearTimeout(timer.current); + if (next === null) { + setTarget(null); + return; + } + timer.current = setTimeout(() => setTarget(next), INTENT_DELAY_MS); + }); +} diff --git a/apps/web/src/connection/storage.browser.test.ts b/apps/web/src/connection/storage.browser.test.ts new file mode 100644 index 0000000000000..2b36f9827c84f --- /dev/null +++ b/apps/web/src/connection/storage.browser.test.ts @@ -0,0 +1,72 @@ +import { Persistence } from "@t3tools/client-runtime/platform"; +import { EnvironmentQueryStore } from "@t3tools/client-runtime/state/query-persistence"; +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import { TestClock } from "effect/testing"; + +import * as ConnectionStorage from "./storage"; + +describe("IndexedDB query cache", () => { + it.effect("round trips per environment and clears with the environment", () => + Effect.gen(function* () { + const store = (yield* EnvironmentQueryStore)!; + const first = EnvironmentId.make("query-first"); + yield* store.save(first, "pr", "cached"); + expect(yield* store.load(first, "pr")).toEqual(Option.some("cached")); + expect(yield* store.load(EnvironmentId.make("query-second"), "pr")).toEqual(Option.none()); + yield* (yield* Persistence.EnvironmentCacheStore).clear(first); + expect(yield* store.load(first, "pr")).toEqual(Option.none()); + }).pipe(Effect.provide(ConnectionStorage.layer)), + ); + + it.effect("two tabs' bursts of saves end within 256 rows and 32 MiB", () => + Effect.gen(function* () { + const openTab = Layer.build(Layer.fresh(ConnectionStorage.layer)).pipe( + Effect.map((context) => Context.get(context, EnvironmentQueryStore)!), + ); + const tabs = [yield* openTab, yield* openTab]; + const environmentId = EnvironmentId.make("query-bounded"); + const saveAll = (keys: ReadonlyArray, payload: (key: string) => string) => + Effect.forEach(keys, (key, index) => + tabs[index % 2]!.save(environmentId, key, payload(key)).pipe( + Effect.andThen(TestClock.adjust("1 millis")), + ), + ); + const loadAll = (keys: ReadonlyArray) => + Effect.forEach(keys, (key) => tabs[0]!.load(environmentId, key)).pipe( + Effect.map((loaded) => loaded.filter(Option.isSome).map((stored) => stored.value)), + ); + + const rows = Array.from({ length: 300 }, (_, index) => `row-${index}`); + yield* saveAll(rows, (key) => key); + const keptRows = yield* loadAll(rows); + expect(keptRows.length).toBeLessThanOrEqual(256); + expect(keptRows).not.toContain("row-0"); + expect(keptRows).toContain("row-299"); + + const answer = "x".repeat(4 * 1024 * 1024); + const large = Array.from({ length: 9 }, (_, index) => `large-${index}`); + yield* saveAll(large, () => answer); + const keptBytes = (yield* loadAll([...rows, ...large])).reduce( + (total, payload) => total + payload.length, + 0, + ); + expect(keptBytes).toBeLessThanOrEqual(32 * 1024 * 1024); + expect(yield* tabs[1]!.load(environmentId, "large-8")).toEqual(Option.some(answer)); + }).pipe(Effect.scoped), + ); + + it.effect("drops the older copy when an answer grows too large to keep", () => + Effect.gen(function* () { + const store = (yield* EnvironmentQueryStore)!; + const environmentId = EnvironmentId.make("query-oversize"); + yield* store.save(environmentId, "diff", "small"); + yield* store.save(environmentId, "diff", "x".repeat(4 * 1024 * 1024 + 1)); + expect(yield* store.load(environmentId, "diff")).toEqual(Option.none()); + }).pipe(Effect.provide(ConnectionStorage.layer)), + ); +}); diff --git a/apps/web/src/connection/storage.ts b/apps/web/src/connection/storage.ts index 7d9db4afdc494..78b01fc6d4695 100644 --- a/apps/web/src/connection/storage.ts +++ b/apps/web/src/connection/storage.ts @@ -28,7 +28,9 @@ import { pullRequestRoutingConnectionKey, pullRequestRoutingPermissionFor, } from "@t3tools/client-runtime/connection"; +import { EnvironmentQueryStore } from "@t3tools/client-runtime/state/query-persistence"; import { EnvironmentId, ServerConfig, ThreadId, VcsListRefsResult } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -41,12 +43,23 @@ import * as Stream from "effect/Stream"; import { projectFaviconCache } from "../assets/projectFaviconCache"; const DATABASE_NAME = "t3code:connection-runtime"; -const DATABASE_VERSION = 4; +const DATABASE_VERSION = 5; const CATALOG_STORE_NAME = "catalog"; const SHELL_STORE_NAME = "shell"; const THREAD_STORE_NAME = "thread"; const SERVER_CONFIG_STORE_NAME = "server-config"; const VCS_REFS_STORE_NAME = "vcs-refs"; +const QUERY_STORE_NAME = "query"; +const QUERY_UPDATED_INDEX_NAME = "environment-updated"; +const QUERY_MAX_ROWS = 256; +const QUERY_MAX_BYTES = 32 * 1024 * 1024; +const QUERY_MAX_PAYLOAD_BYTES = 4 * 1024 * 1024; +const QUERY_MAX_AGE_MS = 30 * 24 * 60 * 60_000; +// A stats answer saves one row per listed PR, so the bounds index is walked once per batch of +// saves. Each walk trims a batch below the caps, so the caps hold between walks. The batch count +// lives in the database, so tabs sharing it share one count. +const QUERY_PRUNE_BATCH_ROWS = 32; +const QUERY_PRUNE_BATCH_BYTES = 1024 * 1024; const CATALOG_KEY = "document"; const StoredShellSnapshot = StoredOrchestrationShellSnapshot; const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot); @@ -65,6 +78,10 @@ const StoredVcsRefs = Schema.Struct({ refs: VcsListRefsResult, }); const StoredVcsRefsJson = Schema.fromJsonString(StoredVcsRefs); +const isStoredQuery = Schema.is( + Schema.Struct({ environmentId: Schema.String, payload: Schema.String, updatedAt: Schema.Number }), +); +const isQueryBatch = Schema.is(Schema.Struct({ rows: Schema.Number, bytes: Schema.Number })); const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument); const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson); const encodeConnectionCatalogDocument = Schema.encodeEffect(ConnectionCatalogDocumentJson); @@ -137,6 +154,11 @@ const openDatabase = Effect.fn("web.connectionStorage.openDatabase")(function* ( if (!request.result.objectStoreNames.contains(VCS_REFS_STORE_NAME)) { request.result.createObjectStore(VCS_REFS_STORE_NAME); } + if (!request.result.objectStoreNames.contains(QUERY_STORE_NAME)) { + request.result + .createObjectStore(QUERY_STORE_NAME) + .createIndex(QUERY_UPDATED_INDEX_NAME, ["environmentId", "updatedAt", "bytes"]); + } }); request.addEventListener("error", () => { resume(Effect.fail(catalogError("open", request.error ?? "Unknown IndexedDB error"))); @@ -326,6 +348,75 @@ function removeDatabaseValuesInRangeOnConnection( }).pipe(Effect.withSpan("web.connectionStorage.removeDatabaseValuesInRange")); } +// Mirrors mobile's pull-request cache bounds, per environment. +function saveQueryOnConnection( + database: IDBDatabase, + environmentId: EnvironmentId, + key: string, + payload: string, + updatedAt: number, +) { + return Effect.callback((resume) => { + try { + const bytes = new TextEncoder().encode(payload).length; + const transaction = database.transaction(QUERY_STORE_NAME, "readwrite"); + transaction.addEventListener("abort", () => { + resume( + Effect.fail(catalogError("write", transaction.error ?? "Unknown IndexedDB write error")), + ); + }); + transaction.addEventListener("complete", () => { + resume(Effect.void); + }); + const store = transaction.objectStore(QUERY_STORE_NAME); + // An answer too large to keep must not leave its older copy to paint on the next start. + if (bytes > QUERY_MAX_PAYLOAD_BYTES) { + store.delete(queryCacheKey(environmentId, key)); + return; + } + store.put({ environmentId, payload, updatedAt, bytes }, queryCacheKey(environmentId, key)); + const batchKey = queryBatchKey(environmentId); + const batchRequest = store.get(batchKey); + batchRequest.addEventListener("success", () => { + const batch: unknown = batchRequest.result; + const rows = (isQueryBatch(batch) ? batch.rows : 0) + 1; + const written = (isQueryBatch(batch) ? batch.bytes : 0) + bytes; + if ( + isQueryBatch(batch) && + rows < QUERY_PRUNE_BATCH_ROWS && + written < QUERY_PRUNE_BATCH_BYTES + ) { + store.put({ rows, bytes: written }, batchKey); + return; + } + store.put({ rows: 0, bytes: 0 }, batchKey); + const request = store + .index(QUERY_UPDATED_INDEX_NAME) + .openKeyCursor(IDBKeyRange.bound([environmentId], [environmentId, []]), "prev"); + let kept = 0; + let totalBytes = 0; + request.addEventListener("success", () => { + const cursor = request.result; + if (cursor === null) return; + const [, rowUpdatedAt, rowBytes] = cursor.key as [string, number, number]; + kept += 1; + totalBytes += rowBytes; + if ( + kept > QUERY_MAX_ROWS - QUERY_PRUNE_BATCH_ROWS || + totalBytes > QUERY_MAX_BYTES - QUERY_PRUNE_BATCH_BYTES || + rowUpdatedAt < updatedAt - QUERY_MAX_AGE_MS + ) { + store.delete(cursor.primaryKey); + } + cursor.continue(); + }); + }); + } catch (cause) { + resume(Effect.fail(catalogError("write", cause))); + } + }).pipe(Effect.withSpan("web.connectionStorage.saveQuery")); +} + function readDatabaseValue(database: DatabaseHandle, storeName: string, key: IDBValidKey) { return withDatabase(database, (opened) => readDatabaseValueOnConnection(opened, storeName, key)); } @@ -361,6 +452,14 @@ function threadCacheKey(environmentId: EnvironmentId, threadId: ThreadId) { return `${environmentId}:${threadId}`; } +function queryCacheKey(environmentId: EnvironmentId, key: string) { + return `${environmentId}:v1:${key}`; +} + +function queryBatchKey(environmentId: EnvironmentId) { + return `${environmentId}:batch`; +} + function vcsRefsCacheKey(environmentId: EnvironmentId, cwd: string) { return `${environmentId}:${cwd}`; } @@ -955,12 +1054,45 @@ export const layer = Layer.effectContext( VCS_REFS_STORE_NAME, IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`), ), + removeDatabaseValuesInRange( + database, + QUERY_STORE_NAME, + IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`), + ), ], { concurrency: "unbounded", discard: true }, ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause))); }), }); + const queryStore: NonNullable = { + load: Effect.fn("EnvironmentQueryStore.load")( + function* (environmentId, key) { + const stored = yield* readDatabaseValue( + database, + QUERY_STORE_NAME, + queryCacheKey(environmentId, key), + ); + const now = yield* Clock.currentTimeMillis; + return isStoredQuery(stored) && + stored.environmentId === environmentId && + stored.updatedAt >= now - QUERY_MAX_AGE_MS + ? Option.some(stored.payload) + : Option.none(); + }, + Effect.catch(() => Effect.succeedNone), + ), + save: (environmentId, key, payload) => + Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => + withDatabase(database, (opened) => + saveQueryOnConnection(opened, environmentId, key, payload, now), + ), + ), + Effect.catch(() => Effect.logWarning("Offline query database save failed")), + ), + }; + return Context.make(Persistence.ConnectionTargetStore, targetStore).pipe( Context.add(PullRequestRoutingPermissions, pullRequestRoutingPermissions), Context.add(Persistence.ConnectionRegistrationStore, registrationStore), @@ -968,6 +1100,7 @@ export const layer = Layer.effectContext( Context.add(CredentialStore.ConnectionCredentialStore, credentialStore), Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore), Context.add(Persistence.EnvironmentCacheStore, cacheStore), + Context.add(EnvironmentQueryStore, queryStore), ); }), ); diff --git a/packages/client-runtime/src/state/pullRequestStatsPersistence.ts b/packages/client-runtime/src/state/pullRequestStatsPersistence.ts index 2d97ce23d1c7d..75cba63031a2f 100644 --- a/packages/client-runtime/src/state/pullRequestStatsPersistence.ts +++ b/packages/client-runtime/src/state/pullRequestStatsPersistence.ts @@ -19,8 +19,10 @@ export function persistPullRequestStats(): QueryPersistence - row.load(environmentId, statKey(ref)), + const rows = yield* Effect.forEach( + input.refs, + (ref) => row.load(environmentId, statKey(ref)), + { concurrency: "unbounded" }, ); const stats = rows.flatMap((value) => (Option.isSome(value) ? [value.value] : [])); return stats.length ? Option.some({ stats }) : Option.none(); diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts index 64ae5ae3df56e..b92f00c8a3695 100644 --- a/packages/client-runtime/src/state/pullRequests.ts +++ b/packages/client-runtime/src/state/pullRequests.ts @@ -21,7 +21,7 @@ import { type PullRequestRef, type PullRequestMergeMethod, PullRequestOperationError, - type PullRequestSummary, + PullRequestSummary, type VcsStatusResult, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; @@ -147,6 +147,7 @@ export function createLinkedPullRequestSummaryAtomFamily( const routedRequest = createPullRequestRouter(); return createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:pull-requests:linked-summary", + persistence: persistQuery(PullRequestSummary), tag: WS_METHODS.pullRequestsSummary, execute: (input) => routedRequest(WS_METHODS.pullRequestsSummary, input), staleTimeMs: 60_000, diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts index 381623f23207a..f79f00cdaa80e 100644 --- a/packages/client-runtime/src/state/runtime.test.ts +++ b/packages/client-runtime/src/state/runtime.test.ts @@ -1370,19 +1370,20 @@ describe("persisted environment queries", () => { Effect.scoped( Effect.gen(function* () { let saved = Option.none(); + const saves = yield* Queue.unbounded(); const persistence: QueryPersistence = { load: () => Effect.sync(() => saved), save: (_environmentId, _key, value) => Effect.sync(() => { saved = Option.some(value); - }), + }).pipe(Effect.andThen(Queue.offer(saves, value))), }; const first = yield* makeEnvironmentQueryHarness(Effect.succeed("first"), { persistence, }); const firstRegistry = yield* mountEnvironmentQuery(first.atom); expect(yield* readEnvironmentQuery(firstRegistry, first.atom)).toBe("first"); - expect(saved).toEqual(Option.some("first")); + expect(yield* Queue.take(saves)).toBe("first"); const restarted = yield* makeEnvironmentQueryHarness(Effect.succeed("updated"), { persistence, @@ -1393,11 +1394,36 @@ describe("persisted environment queries", () => { yield* SubscriptionRef.set(restarted.supervisorState, queryConnectionState()); yield* Effect.yieldNow; expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("updated"); - expect(saved).toEqual(Option.some("updated")); + expect(yield* Queue.take(saves)).toBe("updated"); }), ), ); + it.effect("answers readers while its save is pending, and ends the save with the query", () => + Effect.scoped( + Effect.gen(function* () { + const saveEnded = Latch.makeUnsafe(); + const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("fresh"), { + persistence: { + load: () => Effect.succeedNone, + // The registry's scheduler stops on dispose, so signal synchronously. + save: () => + Effect.never.pipe( + Effect.onInterrupt(() => Effect.sync(() => saveEnded.openUnsafe())), + ), + }, + }); + yield* Effect.scoped( + Effect.gen(function* () { + const registry = yield* mountEnvironmentQuery(harness.atom); + expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh"); + }), + ); + yield* saveEnded.await; + }), + ), + ); + it.effect("hands each server answer to onAnswer before readers see it", () => Effect.scoped( Effect.gen(function* () { diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index 58c37070fd8d6..78e0cec6437a3 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -781,8 +781,12 @@ export function createEnvironmentQueryAtomFamily( return cached.value; } if (Option.isNone(previous) && Option.isSome(cached)) yield* emit(cached.value); + // Readers must not wait on the disk: web saves one IndexedDB row per listed PR's stats. + // The save ends with the query, so a removed environment's cache stays cleared. return yield* answer().pipe( - Effect.tap((value) => persistence.save(target.environmentId, cacheKey, value)), + Effect.tap((value) => + persistence.save(target.environmentId, cacheKey, value).pipe(Effect.forkScoped), + ), ); }); }) diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index 5a5c46f28d99a..b676a91f0cab4 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -820,6 +820,74 @@ layer("GitHubPullRequestApi.layer", (it) => { }), ); + it.effect("reads commit stats alongside later activity pages", () => + Effect.gen(function* () { + const laterPageStarted = yield* Deferred.make(); + const statsStarted = yield* Deferred.make(); + const activityPage = (head: boolean) => ({ + data: { + repository: { + pullRequest: { + ...(head + ? { + author: null, + commits: { + nodes: [ + { + commit: { + id: "node-regular", + oid: "regular", + messageHeadline: "regular", + committedDate: "2026-07-05T00:00:00Z", + parents: { totalCount: 1 }, + authors: { nodes: [] }, + }, + }, + ], + }, + } + : {}), + comments: { + nodes: [], + pageInfo: head ? { hasNextPage: true, endCursor: "c1" } : lastPage, + }, + reviews: { nodes: [], pageInfo: lastPage }, + }, + }, + }, + }); + mockedExecute.mockImplementation((call) => { + if (matches(call, "PullRequestCommitStats")) { + return Deferred.succeed(statsStarted, undefined).pipe( + Effect.andThen(Deferred.await(laterPageStarted)), + Effect.as( + output( + encodeJson({ + data: { + nodes: [{ __typename: "Commit", oid: "regular", additions: 3, deletions: 1 }], + }, + }), + ), + ), + ); + } + const head = call.kind === "graphql" && call.variables?.["head"] === true; + return head + ? Effect.succeed(output(encodeJson(activityPage(true)))) + : Deferred.succeed(laterPageStarted, undefined).pipe( + Effect.andThen(Deferred.await(statsStarted)), + Effect.as(output(encodeJson(activityPage(false)))), + ); + }); + const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; + + const activity = yield* cli.getPullRequestActivity(pullRequestInput); + + expect(activity.commits[0]).toMatchObject({ additions: 3, deletions: 1 }); + expect(mockedExecute).toHaveBeenCalledTimes(3); + }), + ); + it.effect("loads the complete hover card with one GraphQL request", () => Effect.gen(function* () { mockedExecute.mockReturnValueOnce( @@ -3299,7 +3367,10 @@ layer("GitHubPullRequestApi.layer", (it) => { Effect.succeed(output(reviewThreadsPage([thread("T3", "c3")], null))), ); const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; - const read = cli.listReviewThreadComments(pullRequestInput); + const read = cli.listReviewThreadComments({ + ...pullRequestInput, + repository: `acme/refused-threads-${later}`, + }); const conversation = yield* read; expect( variablesOf("ReviewThreads").map((v) => [v["after"], v["requestedReviewers"]]), @@ -3327,7 +3398,7 @@ layer("GitHubPullRequestApi.layer", (it) => { yield* read; expect(variablesOf("ReviewThreads").at(-1)).toMatchObject({ after: null, - requestedReviewers: 50, + requestedReviewers: 0, }); }), ); @@ -3460,7 +3531,10 @@ layer("GitHubPullRequestApi.layer", (it) => { ), ); const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; - const read = cli.getPullRequestDetail(pullRequestInput); + const read = cli.getPullRequestDetail({ + ...pullRequestInput, + repository: `acme/refused-checks-${refused}`, + }); const detail = yield* read; expect(detail.reviewRequestLogins).toEqual([]); expect(detail.reviewRequestTeams).toEqual([]); @@ -3480,7 +3554,8 @@ layer("GitHubPullRequestApi.layer", (it) => { if (refused) { mockedExecute.mockReturnValueOnce(Effect.succeed(output(encodeJson(coreResponse())))); yield* read; - expect(variablesOf("PullRequestCore").at(-1)).toMatchObject({ requestedReviewers: 100 }); + expect(variablesOf("PullRequestCore").at(-1)).toMatchObject({ requestedReviewers: 0 }); + expect(mockedExecute).toHaveBeenCalledTimes(4); } }), ); @@ -3514,7 +3589,7 @@ layer("GitHubPullRequestApi.layer", (it) => { const error = yield* Effect.flip( cli.getPullRequestDetail({ cwd: "/w", - repository: "acme/web", + repository: `acme/head-changed-${refused}`, host: "github.com", number: 7, }), diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index 2defbb6684919..cb96b97d8556c 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -1422,6 +1422,31 @@ export const make = Effect.gen(function* () { }; }); + // GitHub refuses a requested-reviewer list holding a team the viewer cannot see. Remember the + // refusal so later reads of that pull request skip straight to the read without reviewers. + const refusedReviewers = yield* Cache.make({ + capacity: 512, + timeToLive: "10 minutes", + lookup: (_key: string) => Effect.void, + }); + const readRequestedReviewers = Effect.fn("GitHubPullRequestApi.readRequestedReviewers")( + function* ( + input: { readonly host: string; readonly repository: string; readonly number: number }, + wanted: number, + read: (requestedReviewers: number) => Effect.Effect, + ) { + const host = normalizeHost(input.host); + const { fingerprint } = yield* api.credential(host); + const key = `${fingerprint}\0${host}\0${input.repository.toLowerCase()}\0${input.number}`; + if (yield* Cache.has(refusedReviewers, key)) return yield* read(0); + return yield* read(wanted).pipe( + Effect.catchIf(isRefusedRequestedReviewersOnly, () => + Cache.set(refusedReviewers, key, undefined).pipe(Effect.andThen(read(0))), + ), + ); + }, + ); + const getPullRequestDetail: GitHubPullRequestApi["Service"]["getPullRequestDetail"] = (input) => { const { owner, name } = parseRepositorySelector(input.repository); const operation = "getPullRequestDetail"; @@ -1436,8 +1461,7 @@ export const make = Effect.gen(function* () { }); return SourceControlRateLimit.Interactive.pipe( Effect.flatMap((allowReserve) => - read(100).pipe( - Effect.catchIf(isRefusedRequestedReviewersOnly, () => read(0)), + readRequestedReviewers(input, 100, read).pipe( graphql({ ...input, operation, allowReserve }), Effect.map(toPullRequestCore), Effect.flatMap(found({ ...input, operation })), @@ -2031,7 +2055,9 @@ export const make = Effect.gen(function* () { let withComments = true; let withReviews = true; const target = { ...input, operation: "getPullRequestActivity" }; - for (let page = 0; page < REVIEW_THREAD_PAGES && (withComments || withReviews); page++) { + const readPage = Effect.fn("GitHubPullRequestApi.readActivityPage")(function* ( + page: number, + ) { const read: GitHubPullRequestActivityPage = yield* client .PullRequestActivity({ owner, @@ -2058,16 +2084,28 @@ export const make = Effect.gen(function* () { reviewsAfter = read.nextReviewsCursor; withComments = withComments && commentsAfter !== null; withReviews = withReviews && reviewsAfter !== null; - } + }); + yield* readPage(0); + const laterPages = Effect.gen(function* () { + for (let page = 1; page < REVIEW_THREAD_PAGES; page++) { + if (!withComments && !withReviews) return; + yield* readPage(page); + } + }); const emptyStats = toPullRequestCommitStats({ nodes: [] }); - const commitStats = - nonMergeCommitIds.length === 0 - ? emptyStats - : yield* client.PullRequestCommitStats({ ids: nonMergeCommitIds }).pipe( - graphql(target), - Effect.map(toPullRequestCommitStats), - Effect.orElseSucceed(() => emptyStats), - ); + const [, commitStats] = yield* Effect.all( + [ + laterPages, + nonMergeCommitIds.length === 0 + ? Effect.succeed(emptyStats) + : client.PullRequestCommitStats({ ids: nonMergeCommitIds }).pipe( + graphql(target), + Effect.map(toPullRequestCommitStats), + Effect.orElseSucceed(() => emptyStats), + ), + ], + { concurrency: 2 }, + ); return { author, comments: remarks.toSorted((left, right) => @@ -2157,25 +2195,12 @@ export const make = Effect.gen(function* () { function* (input) { const { owner, name } = parseRepositorySelector(input.repository); const target = { ...input, operation: "listReviewThreadComments" }; - let requestedReviewers = 50; const threadPage = ( after: string | null, - ): Effect.Effect => { - const read = () => - client.ReviewThreads({ owner, name, number: input.number, after, requestedReviewers }); - return read().pipe( - Effect.catchIf( - (error) => requestedReviewers > 0 && isRefusedRequestedReviewersOnly(error), - () => { - requestedReviewers = 0; - return read(); - }, - ), - graphql(target), - Effect.map(toReviewThreadPage), - Effect.flatMap(found(target)), - ); - }; + ): Effect.Effect => + readRequestedReviewers(input, 50, (requestedReviewers) => + client.ReviewThreads({ owner, name, number: input.number, after, requestedReviewers }), + ).pipe(graphql(target), Effect.map(toReviewThreadPage), Effect.flatMap(found(target))); const entries: GitHubReviewThreadEntry[] = []; const avatarsByLogin = new Map(); const botLogins = new Set(); From e71e4d2a020c221312f1f4d175e382f8915a1324 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Fri, 6 Nov 2026 02:42:37 +0530 Subject: [PATCH 047/397] fix(mobile): approval card buttons line up (#31415) Co-authored-by: Claude Opus 5.5 --- .../features/threads/PendingApprovalCard.tsx | 3 +- .../features/threads/ThreadDetailScreen.tsx | 29 +++++++++++++++---- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/apps/mobile/src/features/threads/PendingApprovalCard.tsx b/apps/mobile/src/features/threads/PendingApprovalCard.tsx index b5a9d4ed27eb2..f9ec44d5d4ee5 100644 --- a/apps/mobile/src/features/threads/PendingApprovalCard.tsx +++ b/apps/mobile/src/features/threads/PendingApprovalCard.tsx @@ -80,7 +80,7 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) { {warning ? ( {warning} ) : null} - + {options.map((option) => (