From 298cb24140fdddebfbfaedad3a097e86ff3d9d04 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 4 Nov 2026 20:05:44 -0800 Subject: [PATCH 01/18] 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 02/18] 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 03/18] 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 04/18] 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 ? ( - -