Skip to content
TypeScript

refactor: Effect.try calls map failures to typed errors (#31217)

Julius Marminge5a906583fed3
diff --git a/apps/desktop/src/app/DesktopCliCommand.ts b/apps/desktop/src/app/DesktopCliCommand.ts
index 5dfb579cf2c..de483288507 100644
--- a/apps/desktop/src/app/DesktopCliCommand.ts
+++ b/apps/desktop/src/app/DesktopCliCommand.ts
@@ -140,7 +140,10 @@ export const make = Effect.gen(function* () {
const isExecutableFile = Effect.fn("DesktopCliCommand.isExecutableFile")(
function* (target: string) {
if ((yield* fs.stat(target)).type !== "File") return false;
- yield* Effect.tryPromise(() => NodeFSP.access(target, NodeFSP.constants.X_OK));
+ yield* Effect.tryPromise({
+ try: () => NodeFSP.access(target, NodeFSP.constants.X_OK),
+ catch: () => fail(`${target} is not executable.`),
+ });
return true;
},
Effect.orElseSucceed(() => false),
diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts
index 27af3f2cfd8..7563898f43e 100644
--- a/apps/desktop/src/electron/ElectronProtocol.ts
+++ b/apps/desktop/src/electron/ElectronProtocol.ts
@@ -216,9 +216,7 @@ const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* (
if (request.method !== "GET" && request.method !== "HEAD") {
return new Response(null, { status: 405 });
}
- const pathname = yield* Effect.try(() => decodeURIComponent(url.pathname)).pipe(
- Effect.orElseSucceed(() => null),
- );
+ const pathname = Option.getOrNull(Option.liftThrowable(decodeURIComponent)(url.pathname));
if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 });
const root = path.resolve(assetDirectory);
const assetPath = path.resolve(root, `.${pathname}`);
diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts
index 63b8db03dad..2833abca438 100644
--- a/apps/desktop/src/ipc/methods/window.ts
+++ b/apps/desktop/src/ipc/methods/window.ts
@@ -314,6 +314,12 @@ export const openExternal = DesktopIpc.makeIpcMethod({
const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024;
+// No URL field: media URLs can carry signed query tokens.
+class MediaReadError extends Schema.TaggedError<MediaReadError>()("MediaReadError", {
+ message: Schema.String,
+ cause: Schema.Defect(),
+}) {}
+
// The renderer can display media it cannot fetch(); reading here keeps Save and Copy working for it.
export const readMedia = DesktopIpc.makeIpcMethod({
channel: IpcChannels.READ_MEDIA_CHANNEL,
@@ -330,25 +336,28 @@ export const readMedia = DesktopIpc.makeIpcMethod({
return null;
}
const session = window.value.webContents.session;
- return yield* Effect.tryPromise(async () => {
- // Like an <img>, send the session's cookies.
- const response = await session.fetch(url, { credentials: "include" });
- const mimeType = response.headers.get("content-type") ?? "";
- if (!response.ok || !response.body) {
- await response.body?.cancel();
- return { status: response.status, mimeType, data: new Uint8Array() };
- }
- // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory.
- const chunks: Uint8Array[] = [];
- let size = 0;
- for await (const chunk of response.body) {
- size += chunk.byteLength;
- if (size > READ_MEDIA_MAX_BYTES) {
- return { status: 413, mimeType, data: new Uint8Array() };
+ return yield* Effect.tryPromise({
+ try: async () => {
+ // Like an <img>, send the session's cookies.
+ const response = await session.fetch(url, { credentials: "include" });
+ const mimeType = response.headers.get("content-type") ?? "";
+ if (!response.ok || !response.body) {
+ await response.body?.cancel();
+ return { status: response.status, mimeType, data: new Uint8Array() };
}
- chunks.push(chunk);
- }
- return { status: response.status, mimeType, data: Buffer.concat(chunks) };
+ // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory.
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ for await (const chunk of response.body) {
+ size += chunk.byteLength;
+ if (size > READ_MEDIA_MAX_BYTES) {
+ return { status: 413, mimeType, data: new Uint8Array() };
+ }
+ chunks.push(chunk);
+ }
+ return { status: response.status, mimeType, data: Buffer.concat(chunks) };
+ },
+ catch: (cause) => new MediaReadError({ message: "Could not read media.", cause }),
}).pipe(Effect.orElseSucceed(() => null));
}),
});
diff --git a/apps/desktop/src/permissions/MacPermissions.ts b/apps/desktop/src/permissions/MacPermissions.ts
index 0a7bb3a2c44..2052f378743 100644
--- a/apps/desktop/src/permissions/MacPermissions.ts
+++ b/apps/desktop/src/permissions/MacPermissions.ts
@@ -2,6 +2,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
+import * as Schema from "effect/Schema";
import * as Electron from "electron";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { MacPermissionHelper } from "./MacPermissionHelper.ts";
@@ -18,6 +19,15 @@ export class MacPermissions extends Context.Service<
}
>()("@t3tools/desktop/permissions/MacPermissions") {}
+class MacPermissionHelperError extends Schema.TaggedError<MacPermissionHelperError>()(
+ "MacPermissionHelperError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Could not show the permission helper.";
+ }
+}
+
export const layer = Layer.effect(
MacPermissions,
Effect.gen(function* () {
@@ -28,15 +38,17 @@ export const layer = Layer.effect(
return MacPermissions.of({
showHelper: Effect.fn("MacPermissions.showHelper")(function* (permission, owner, isGranted) {
if (environment.platform !== "darwin" || !environment.isPackaged) return;
- yield* Effect.tryPromise(() =>
- helper.show(
- permission,
- path.join(environment.dirname, "mac-permission-preload.cjs"),
- owner,
- environment.resolveResourcePathCandidates("icon.png"),
- isGranted,
- ),
- ).pipe(
+ yield* Effect.tryPromise({
+ try: () =>
+ helper.show(
+ permission,
+ path.join(environment.dirname, "mac-permission-preload.cjs"),
+ owner,
+ environment.resolveResourcePathCandidates("icon.png"),
+ isGranted,
+ ),
+ catch: (cause) => new MacPermissionHelperError({ cause }),
+ }).pipe(
Effect.catch((cause) => Effect.logWarning("Could not show permission helper", cause)),
);
}),
diff --git a/apps/desktop/src/preview/BrowserImport/BrowserImport.ts b/apps/desktop/src/preview/BrowserImport/BrowserImport.ts
index 0a762d92416..e5f8665d113 100644
--- a/apps/desktop/src/preview/BrowserImport/BrowserImport.ts
+++ b/apps/desktop/src/preview/BrowserImport/BrowserImport.ts
@@ -92,6 +92,15 @@ export const checkBrowserImportPolicy = Effect.fn("BrowserImport.checkPolicy")(f
}
});
+class BrowserCookieFlushError extends Schema.TaggedError<BrowserCookieFlushError>()(
+ "BrowserCookieFlushError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Imported cookies could not be flushed to disk.";
+ }
+}
+
export class BrowserCookieWriteError extends Schema.TaggedError<BrowserCookieWriteError>()(
"BrowserCookieWriteError",
{
@@ -183,7 +192,10 @@ export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* (
}
// Cookie writes settle in memory; flush to disk before reporting a durable import.
if (imported > 0) {
- yield* Effect.tryPromise(() => session.cookies.flushStore()).pipe(
+ yield* Effect.tryPromise({
+ try: () => session.cookies.flushStore(),
+ catch: (cause) => new BrowserCookieFlushError({ cause }),
+ }).pipe(
Effect.tapError((error) =>
Effect.logWarning("Imported cookies could not be flushed to disk", { cause: error.cause }),
),
diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.ts
index 95b39d944e4..ae0c2f04121 100644
--- a/apps/desktop/src/snapShot/DesktopSnapShot.ts
+++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts
@@ -167,6 +167,17 @@ export class DesktopSnapShotError extends Schema.TaggedError<DesktopSnapShotErro
const isDesktopSnapShotError = Schema.is(DesktopSnapShotError);
+class SnapShotShortcutError extends Schema.TaggedError<SnapShotShortcutError>()(
+ "SnapShotShortcutError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Could not register the SnapShot shortcut.";
+ }
+}
+
+const shortcutFailure = (cause: unknown) => new SnapShotShortcutError({ cause });
+
function captureFailure(cause: unknown, captureId?: string): DesktopSnapShotError {
if (isDesktopSnapShotError(cause)) return cause;
const operation = cause instanceof CaptureSetupRequiredError ? "setup-required" : "capture";
@@ -1068,13 +1079,15 @@ export const make = Effect.gen(function* () {
if (mode === "portal") {
return { available: false, message: WAYLAND_MODIFIER_PAIR_UNAVAILABLE_MESSAGE };
}
- const available = yield* Effect.tryPromise(() =>
- startPairShortcutProcess(
- snapShotShortcutModifierPair(shortcut),
- () => undefined,
- () => undefined,
- ),
- ).pipe(
+ const available = yield* Effect.tryPromise({
+ try: () =>
+ startPairShortcutProcess(
+ snapShotShortcutModifierPair(shortcut),
+ () => undefined,
+ () => undefined,
+ ),
+ catch: shortcutFailure,
+ }).pipe(
Effect.tap((stop) => Effect.sync(stop)),
Effect.as(true),
Effect.orElseSucceed(() => false),
@@ -1089,7 +1102,10 @@ export const make = Effect.gen(function* () {
const systemConflict = snapShotShortcutSystemConflict(shortcut);
if (systemConflict) return { available: false, message: systemConflict };
if (mode === "portal") {
- return yield* Effect.try(() => portalShortcutTrigger(shortcut)).pipe(
+ return yield* Effect.try({
+ try: () => portalShortcutTrigger(shortcut),
+ catch: shortcutFailure,
+ }).pipe(
Effect.match({
onSuccess: () => ({
available: true,
@@ -1199,13 +1215,16 @@ export const make = Effect.gen(function* () {
return;
}
if (mode === "portal" && niriSocketPath()) {
- const registered = yield* Effect.tryPromise(async () => {
- const { startNiriCaptureShortcut } = await import("./NiriCaptureShortcut.ts");
- return startNiriCaptureShortcut(linuxAppId, onCurrentShortcut, () => {
- void runPromise(
- setShortcutFailure("The Niri capture endpoint disconnected. Restart T3 Code."),
- ).catch(() => undefined);
- });
+ const registered = yield* Effect.tryPromise({
+ try: async () => {
+ const { startNiriCaptureShortcut } = await import("./NiriCaptureShortcut.ts");
+ return startNiriCaptureShortcut(linuxAppId, onCurrentShortcut, () => {
+ void runPromise(
+ setShortcutFailure("The Niri capture endpoint disconnected. Restart T3 Code."),
+ ).catch(() => undefined);
+ });
+ },
+ catch: shortcutFailure,
}).pipe(
Effect.tap((stop) =>
Effect.sync(() => {
@@ -1249,29 +1268,32 @@ export const make = Effect.gen(function* () {
shortcutMessage: null,
message: null,
});
- yield* Effect.tryPromise(async () => {
- const { PortalCaptureShortcut } = await import("./PortalCaptureShortcut.ts");
- return new PortalCaptureShortcut(
- linuxAppId,
- isModifierPairShortcut(shortcut)
- ? {
- key: "2",
- ctrlKey: true,
- modKey: false,
- altKey: false,
- shiftKey: true,
- metaKey: false,
- }
- : shortcut,
- onCurrentShortcut,
- () => {
- if (generation !== shortcutGeneration) return;
- shortcutVerified = false;
- void runPromise(emit({ type: "shortcut-changed" })).catch(() => undefined);
- },
- undefined,
- hyprland,
- );
+ yield* Effect.tryPromise({
+ try: async () => {
+ const { PortalCaptureShortcut } = await import("./PortalCaptureShortcut.ts");
+ return new PortalCaptureShortcut(
+ linuxAppId,
+ isModifierPairShortcut(shortcut)
+ ? {
+ key: "2",
+ ctrlKey: true,
+ modKey: false,
+ altKey: false,
+ shiftKey: true,
+ metaKey: false,
+ }
+ : shortcut,
+ onCurrentShortcut,
+ () => {
+ if (generation !== shortcutGeneration) return;
+ shortcutVerified = false;
+ void runPromise(emit({ type: "shortcut-changed" })).catch(() => undefined);
+ },
+ undefined,
+ hyprland,
+ );
+ },
+ catch: shortcutFailure,
}).pipe(
Effect.tap((registration) =>
Effect.sync(() => {
@@ -1293,15 +1315,21 @@ export const make = Effect.gen(function* () {
let registered = false;
if (isModifierPairShortcut(shortcut)) {
- registered = yield* Effect.tryPromise(() =>
- startPairShortcutProcess(snapShotShortcutModifierPair(shortcut), onCurrentShortcut, () => {
- void pipe(
- snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform),
- setShortcutFailure,
- runPromise,
- ).catch(() => undefined);
- }),
- ).pipe(
+ registered = yield* Effect.tryPromise({
+ try: () =>
+ startPairShortcutProcess(
+ snapShotShortcutModifierPair(shortcut),
+ onCurrentShortcut,
+ () => {
+ void pipe(
+ snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform),
+ setShortcutFailure,
+ runPromise,
+ ).catch(() => undefined);
+ },
+ ),
+ catch: shortcutFailure,
+ }).pipe(
Effect.tap((stop) =>
Effect.sync(() => {
stopShiftShortcut = stop;
@@ -1489,7 +1517,10 @@ export const make = Effect.gen(function* () {
if (action === "retry-shortcut") {
const currentPortal = portalShortcut;
if (currentPortal?.hasSession && !currentPortal.state.shortcutPending) {
- yield* Effect.tryPromise(() => currentPortal.configure()).pipe(
+ yield* Effect.tryPromise({
+ try: () => currentPortal.configure(),
+ catch: shortcutFailure,
+ }).pipe(
Effect.mapError(
(error) =>
new DesktopSnapShotSetupError({
@@ -1583,9 +1614,12 @@ export const make = Effect.gen(function* () {
state: Ref.get(stateRef).pipe(
Effect.flatMap((state) =>
state.mode === "portal"
- ? Effect.tryPromise(async () => {
- const { getLinuxCaptureSupport } = await import("./LinuxSnapShot.ts");
- return getLinuxCaptureSupport(linuxAppId);
+ ? Effect.tryPromise({
+ try: async () => {
+ const { getLinuxCaptureSupport } = await import("./LinuxSnapShot.ts");
+ return getLinuxCaptureSupport(linuxAppId);
+ },
+ catch: (cause) => new DesktopSnapShotError({ operation: "unsupported", cause }),
}).pipe(
Effect.map((support) => ({ ...state, ...support })),
Effect.catch((error) =>
diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts
index 5e02f4cfd8b..b2f643e55fb 100644
--- a/apps/desktop/src/window/DesktopWindow.ts
+++ b/apps/desktop/src/window/DesktopWindow.ts
@@ -5,6 +5,7 @@ import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
+import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Electron from "electron";
@@ -39,6 +40,15 @@ import { makeQuitShortcutHandler } from "./QuitHold.ts";
import { copyContextMenuImage } from "./ContextMenuImage.ts";
const TITLEBAR_HEIGHT = 40;
+
+class ContextMenuImageCopyError extends Schema.TaggedError<ContextMenuImageCopyError>()(
+ "ContextMenuImageCopyError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Could not copy the context-menu image.";
+ }
+}
// Match --workspace-topbar-height in apps/web/src/index.css; native macOS buttons stay 14 points at any zoom.
const MACOS_WORKSPACE_TOPBAR_HEIGHT = 52;
const MACOS_WINDOW_BUTTON_RADIUS = 7;
@@ -580,9 +590,10 @@ export const make = Effect.gen(function* () {
label: "Copy Image",
click: () => {
void runPromise(
- Effect.tryPromise(() => copyContextMenuImage(contents, params)).pipe(
- Effect.catch(() => logWindowWarning("failed to copy context-menu image")),
- ),
+ Effect.tryPromise({
+ try: () => copyContextMenuImage(contents, params),
+ catch: (cause) => new ContextMenuImageCopyError({ cause }),
+ }).pipe(Effect.catch(() => logWindowWarning("failed to copy context-menu image"))),
);
},
});
diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts
index 6151c8935cc..437a00be9ea 100644
--- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts
+++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts
@@ -62,6 +62,7 @@ const AgentAwarenessOperation = Schema.Literals([
"list-active-live-activities",
"load-live-activity-prime-preferences",
"prime-live-activity",
+ "load-registration-record",
]);
export class AgentAwarenessOperationError extends Schema.TaggedError<AgentAwarenessOperationError>()(
@@ -345,9 +346,11 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith
}
const identity = relayTokenProviderIdentity ?? "";
- const persisted = yield* Effect.tryPromise(() => loadAgentAwarenessRegistrationRecord()).pipe(
- Effect.orElseSucceed(() => null),
- );
+ const persisted = yield* Effect.tryPromise({
+ try: () => loadAgentAwarenessRegistrationRecord(),
+ catch: (cause) =>
+ new AgentAwarenessOperationError({ operation: "load-registration-record", cause }),
+ }).pipe(Effect.orElseSucceed(() => null));
if (expectedGeneration !== deviceRegistrationGeneration) {
// Signed out while the record loaded — do not resurrect the cleared
// record or report the previous account's registration as current.
diff --git a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
index b3efc031af6..528a18541eb 100644
--- a/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
+++ b/apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
@@ -6,6 +6,7 @@ import * as Updates from "expo-updates";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
+import * as Schema from "effect/Schema";
import { AsyncResult, Atom } from "effect/reactivity";
import { useState } from "react";
import { View } from "react-native";
@@ -34,9 +35,20 @@ type CrashLogState =
| { readonly status: "unavailable" }
| { readonly status: "ready"; readonly records: ReadonlyArray<StartupCrashRecord> };
+class CrashLogReadError extends Schema.TaggedError<CrashLogReadError>()("CrashLogReadError", {
+ cause: Schema.Defect(),
+}) {
+ override get message(): string {
+ return "Could not read the expo-updates log.";
+ }
+}
+
// Not kept alive: each visit to the screen re-reads the log.
const crashLogAtom = Atom.make(
- Effect.tryPromise(() => Updates.readLogEntriesAsync(LOG_WINDOW_MS)).pipe(
+ Effect.tryPromise({
+ try: () => Updates.readLogEntriesAsync(LOG_WINDOW_MS),
+ catch: (cause) => new CrashLogReadError({ cause }),
+ }).pipe(
Effect.map((entries): CrashLogState => ({
status: "ready",
records: parseStartupCrashRecords(entries),
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx b/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx
index 3000efb9633..3fc878b5cf9 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx
+++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx
@@ -1,6 +1,6 @@
import { RegistryContext } from "@effect/atom-react";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
-import type { PullRequestDiffResult } from "@t3tools/contracts";
+import { PullRequestOperationError, type PullRequestDiffResult } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { Atom, AtomRegistry } from "effect/reactivity";
import { act, useLayoutEffect, useState } from "react";
@@ -32,12 +32,14 @@ function setup() {
}[] = [];
const queries = Atom.family((cursor: string | null) =>
Atom.make(
- Effect.tryPromise(
- () =>
+ Effect.tryPromise({
+ try: () =>
new Promise<PullRequestDiffResult>((resolve, reject) => {
requests.push({ cursor, resolve, reject });
}),
- ),
+ catch: (cause) =>
+ new PullRequestOperationError({ operation: "diff", detail: "Connection lost", cause }),
+ }),
).pipe(Atom.keepAlive),
);
mocks.diff.mockImplementation((target: { input: { cursor?: string } }) =>
diff --git a/apps/mobile/src/lib/composerImagePreview.ts b/apps/mobile/src/lib/composerImagePreview.ts
index bcd649b3d10..6c27d3889bf 100644
--- a/apps/mobile/src/lib/composerImagePreview.ts
+++ b/apps/mobile/src/lib/composerImagePreview.ts
@@ -1,6 +1,7 @@
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as Hash from "effect/Hash";
+import * as Schema from "effect/Schema";
import { Atom } from "effect/reactivity";
import type { DraftComposerImageAttachment } from "./composerImages";
@@ -31,6 +32,15 @@ async function materializeDataUrlPreview(id: string, dataUrl: string): Promise<s
return file.uri;
}
+class ImagePreviewCacheError extends Schema.TaggedError<ImagePreviewCacheError>()(
+ "ImagePreviewCacheError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Could not cache an image preview.";
+ }
+}
+
/**
* Keyed by attachment id only: the cached file is named by id, and an upload
* reference landing on the same draft must not restart materialization and
@@ -48,7 +58,10 @@ export class MaterializedPreviewKey implements Equal.Equal {
export const materializedPreviewAtom = Atom.family(({ attachment }: MaterializedPreviewKey) =>
Atom.make(
- Effect.tryPromise(() => materializeDataUrlPreview(attachment.id, attachment.previewUri)).pipe(
+ Effect.tryPromise({
+ try: () => materializeDataUrlPreview(attachment.id, attachment.previewUri),
+ catch: (cause) => new ImagePreviewCacheError({ cause }),
+ }).pipe(
Effect.catch((error) =>
Effect.logWarning("[composer-attachments] could not cache an image preview", error).pipe(
Effect.as(null),
diff --git a/apps/mobile/src/native/ProjectChipIconImages.tsx b/apps/mobile/src/native/ProjectChipIconImages.tsx
index 25038801bf2..56b355ef6ab 100644
--- a/apps/mobile/src/native/ProjectChipIconImages.tsx
+++ b/apps/mobile/src/native/ProjectChipIconImages.tsx
@@ -1,5 +1,6 @@
import type { ProjectIconColor } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
import { Atom } from "effect/reactivity";
import { useRef, useSyncExternalStore } from "react";
import { Platform, View } from "react-native";
@@ -68,11 +69,22 @@ function subscribe(listener: () => void) {
return () => listeners.delete(listener);
}
+class ProjectGlyphRasterizeError extends Schema.TaggedError<ProjectGlyphRasterizeError>()(
+ "ProjectGlyphRasterizeError",
+ { key: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `Could not rasterize the project glyph ${this.key}.`;
+ }
+}
+
export const projectGlyphImageAtom = Atom.family((key: string) =>
- Atom.make(Effect.tryPromise(() => rasterize(key))).pipe(
- Atom.keepAlive,
- Atom.withLabel(`mobile-project-glyph-image:${key}`),
- ),
+ Atom.make(
+ Effect.tryPromise({
+ try: () => rasterize(key),
+ catch: (cause) => new ProjectGlyphRasterizeError({ key, cause }),
+ }),
+ ).pipe(Atom.keepAlive, Atom.withLabel(`mobile-project-glyph-image:${key}`)),
);
export function ProjectChipIconRasterizer() {
diff --git a/apps/server/scripts/record-fx-acp-replay-fixture.ts b/apps/server/scripts/record-fx-acp-replay-fixture.ts
index ad24e8140ce..17b1a8f1b7d 100644
--- a/apps/server/scripts/record-fx-acp-replay-fixture.ts
+++ b/apps/server/scripts/record-fx-acp-replay-fixture.ts
@@ -34,6 +34,7 @@ import { ORCHESTRATOR_REPLAY_FIXTURES } from "../src/orchestration-v2/testkit/fi
import { materializeFixtureInput } from "../src/orchestration-v2/testkit/fixtures/shared.ts";
import { runOrchestratorV2Scenario } from "../src/orchestration-v2/testkit/OrchestratorScenario.ts";
import * as ProviderReplayHarness from "../src/orchestration-v2/testkit/ProviderReplayHarness.ts";
+import * as Result from "effect/Result";
const wallClock = Clock.Clock.defaultValue();
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
@@ -502,11 +503,8 @@ const recordScenario = Effect.fn("recordFxScenario")(function* (fixtureName: str
};
const outputPath = readArgValues("--out")[0] ?? (yield* path.fromFileUrl(variant.transcriptFile));
- const liveFailure = yield* Effect.try(() => variant.assertOutput(result, transcript)).pipe(
- Effect.flip,
- Effect.option,
- );
- if (liveFailure._tag === "Some") {
+ const liveFailure = Result.try(() => variant.assertOutput(result, transcript));
+ if (Result.isFailure(liveFailure)) {
const dumpPath = path.join(
recorderEnv.TMPDIR ?? "/tmp",
`fx-replay-${fixtureName}-failed.json`,
@@ -514,9 +512,9 @@ const recordScenario = Effect.fn("recordFxScenario")(function* (fixtureName: str
yield* fs.writeFileString(dumpPath, encodeJson(transcript));
yield* Console.log(
`Live orchestration failed ${fixtureName} assertions; left ${outputPath} unchanged. Dump: ${dumpPath}`,
- liveFailure.value,
+ liveFailure.failure,
);
- return yield* Effect.die(liveFailure.value);
+ return yield* Effect.die(liveFailure.failure);
}
const { entries: transcriptEntries, ...header } = transcript;
diff --git a/apps/server/scripts/record-grok-acp-replay-fixture.ts b/apps/server/scripts/record-grok-acp-replay-fixture.ts
index d9c5facfa71..4d017e68dd7 100644
--- a/apps/server/scripts/record-grok-acp-replay-fixture.ts
+++ b/apps/server/scripts/record-grok-acp-replay-fixture.ts
@@ -35,6 +35,7 @@ import * as ProviderReplayHarness from "../src/orchestration-v2/testkit/Provider
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
import { makeGrokAcpRuntime } from "@t3tools/provider-grok/testing";
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
+import * as Result from "effect/Result";
const wallClock = Clock.Clock.defaultValue();
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
@@ -554,12 +555,9 @@ const recordScenario = Effect.fn("recordGrokScenario")(function* (fixtureName: s
);
yield* Console.log(`Wrote ${transcriptEntries.length} Grok ACP replay entries to ${outputPath}`);
- const liveFailure = yield* Effect.try(() => variant.assertOutput(result, transcript)).pipe(
- Effect.flip,
- Effect.option,
- );
- if (liveFailure._tag === "Some") {
- yield* Console.log(`Live orchestration failed ${fixtureName} assertions:`, liveFailure.value);
+ const liveFailure = Result.try(() => variant.assertOutput(result, transcript));
+ if (Result.isFailure(liveFailure)) {
+ yield* Console.log(`Live orchestration failed ${fixtureName} assertions:`, liveFailure.failure);
}
});
diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts
index bc89ab9fd29..0be7c1ebb26 100644
--- a/apps/server/src/auth/McpOAuth.ts
+++ b/apps/server/src/auth/McpOAuth.ts
@@ -283,7 +283,7 @@ const make = Effect.gen(function* () {
if (!body || !signature || extra !== undefined) return undefined;
const verified = yield* signer.verify(`mcp-client-id.${body}`, signature);
if (!verified) return undefined;
- const json = yield* Effect.try(() => base64UrlDecodeUtf8(body)).pipe(Effect.option);
+ const json = Option.liftThrowable(base64UrlDecodeUtf8)(body);
if (Option.isNone(json)) return undefined;
return Option.getOrUndefined(
decodeClientIdPayload(json.value).pipe(
diff --git a/apps/server/src/auth/http.test.ts b/apps/server/src/auth/http.test.ts
index 86bd322f3c4..45bf8b3baa2 100644
--- a/apps/server/src/auth/http.test.ts
+++ b/apps/server/src/auth/http.test.ts
@@ -94,7 +94,7 @@ it.effect("sets the selected browser session cookies through the HTTP route", ()
] as const,
),
([environmentA, environmentB]) =>
- Effect.tryPromise(async () => {
+ Effect.promise(async () => {
const devResponse = await environmentA.handler(
postJson("/api/auth/browser-session", { credential: DEV_TOKEN }),
requestContext,
diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.ts b/apps/server/src/cloud/ManagedEndpointRuntime.ts
index d52f27a2ee8..66ef48f5477 100644
--- a/apps/server/src/cloud/ManagedEndpointRuntime.ts
+++ b/apps/server/src/cloud/ManagedEndpointRuntime.ts
@@ -1,5 +1,5 @@
import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
-import { RotatingFileSink } from "@t3tools/shared/logging";
+import { RotatingFileSink, RotatingFileSinkError } from "@t3tools/shared/logging";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as RelayClient from "@t3tools/shared/relayClient";
import * as Clock from "effect/Clock";
@@ -100,6 +100,8 @@ interface ActiveConnector {
}
// An instantly failing relay client otherwise respawns ~100 times/sec and exhausts V8 via tracing.
+const isRotatingFileSinkError = Schema.is(RotatingFileSinkError);
+
const RELAY_RESTART_STABLE_UPTIME_MS = 30_000;
const RELAY_RESTART_BACKOFF_BASE_MS = 1_000;
const RELAY_RESTART_BACKOFF_MAX_MS = 60_000;
@@ -252,15 +254,23 @@ export const make = Effect.gen(function* () {
// Synchronous appends avoid a flush timer for this low-volume log.
const fallbackLoggers = yield* Effect.service(Logger.CurrentLoggers);
let writeFailureReported = false;
- const relayClientLog = yield* Effect.try(
- () =>
+ const relayClientLog = yield* Effect.try({
+ try: () =>
new RotatingFileSink({
filePath: relayClientLogPath,
maxBytes: 1024 * 1024,
maxFiles: 2,
throwOnError: true,
}),
- ).pipe(
+ catch: (cause) =>
+ isRotatingFileSinkError(cause)
+ ? cause
+ : new RotatingFileSinkError({
+ operation: "initialize",
+ filePath: relayClientLogPath,
+ cause,
+ }),
+ }).pipe(
Effect.map((sink) =>
Logger.make((options) => {
try {
diff --git a/apps/server/src/compileCache.ts b/apps/server/src/compileCache.ts
index b01db74cbe3..ea58a1cd3f5 100644
--- a/apps/server/src/compileCache.ts
+++ b/apps/server/src/compileCache.ts
@@ -1,9 +1,22 @@
import * as NodeModule from "node:module";
import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
-// Windows force-kills on quit; persist the cache after startup.
-export const flushCompileCache = Effect.try(() => {
- if (!Reflect.get(globalThis, Symbol.for("t3code.preparedServerCache"))) {
- NodeModule.flushCompileCache();
+class CompileCacheFlushError extends Schema.TaggedError<CompileCacheFlushError>()(
+ "CompileCacheFlushError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Could not flush the module compile cache.";
}
+}
+
+// Windows force-kills on quit; persist the cache after startup.
+export const flushCompileCache = Effect.try({
+ try: () => {
+ if (!Reflect.get(globalThis, Symbol.for("t3code.preparedServerCache"))) {
+ NodeModule.flushCompileCache();
+ }
+ },
+ catch: (cause) => new CompileCacheFlushError({ cause }),
}).pipe(Effect.ignore);
diff --git a/apps/server/src/device/localSshDeviceHost.ts b/apps/server/src/device/localSshDeviceHost.ts
index a2fee8c8881..434aa7541b5 100644
--- a/apps/server/src/device/localSshDeviceHost.ts
+++ b/apps/server/src/device/localSshDeviceHost.ts
@@ -5,6 +5,7 @@ import * as NodeOS from "node:os";
import * as Context from "effect/Context";
import { runSshCommand } from "@t3tools/ssh/command";
import * as Effect from "effect/Effect";
+import { HostnameLookupError } from "@t3tools/shared/HostProcess";
export const LocalDeviceHostAddresses = Context.Reference<ReadonlySet<string>>(
"LocalDeviceHostAddresses",
@@ -45,7 +46,10 @@ export const isLocalSshDeviceHost = Effect.fn("isLocalSshDeviceHost")(function*
if (!hostname) return false;
const addresses = NodeNet.isIP(hostname)
? [hostname]
- : yield* Effect.tryPromise(() => NodeDnsPromises.lookup(hostname, { all: true })).pipe(
+ : yield* Effect.tryPromise({
+ try: () => NodeDnsPromises.lookup(hostname, { all: true }),
+ catch: (cause) => new HostnameLookupError({ hostname, cause }),
+ }).pipe(
Effect.map((entries) => entries.map((entry) => entry.address)),
Effect.timeout("2 seconds"),
Effect.orElseSucceed(() => [] as string[]),
diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.ts
index 6a63a0ba58f..d84873082c6 100644
--- a/apps/server/src/mcp/AcpMcpStdioBridge.ts
+++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts
@@ -4,7 +4,8 @@ import * as NodeReadline from "node:readline";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
-import * as Result from "effect/Result";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
import * as Fiber from "effect/Fiber";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
@@ -21,6 +22,8 @@ const bridgeError = (cause: unknown): AcpMcpBridgeError =>
? cause
: new AcpMcpBridgeError(cause instanceof Error ? cause.message : String(cause), { cause });
+const decodeJsonLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
+
interface JsonRpcEnvelope {
readonly id?: unknown;
readonly method?: unknown;
@@ -132,9 +135,11 @@ export const mcpToolSession = (
const terminate = Effect.suspend(() =>
sessionId === null
? Effect.void
- : Effect.tryPromise(() =>
- fetchImplementation(options.endpoint, { method: "DELETE", headers: headers() }),
- ).pipe(Effect.flatMap(discardResponseBody), Effect.ignore),
+ : Effect.tryPromise({
+ try: () =>
+ fetchImplementation(options.endpoint, { method: "DELETE", headers: headers() }),
+ catch: bridgeError,
+ }).pipe(Effect.flatMap(discardResponseBody), Effect.ignore),
);
// Registered before the handshake so a session the server opened is ended
@@ -274,11 +279,11 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.
line: string,
): Effect.fn.Return<void> {
if (line.trim().length === 0) return;
- const parsed = yield* Effect.try((): unknown => JSON.parse(line)).pipe(Effect.result);
- if (Result.isFailure(parsed)) {
+ const parsed = decodeJsonLine(line);
+ if (Option.isNone(parsed)) {
return yield* respondWithError(null, "Parse error", -32700);
}
- const envelope = asEnvelope(parsed.success);
+ const envelope = asEnvelope(parsed.value);
if (envelope === null) return;
const isResponse = envelope.id !== undefined && ("result" in envelope || "error" in envelope);
const isSessionHandshake =
diff --git a/apps/server/src/observability/EventLoopMonitor.ts b/apps/server/src/observability/EventLoopMonitor.ts
index d66d3695ca8..02922cdd3ae 100644
--- a/apps/server/src/observability/EventLoopMonitor.ts
+++ b/apps/server/src/observability/EventLoopMonitor.ts
@@ -3,7 +3,7 @@ import * as NodeOS from "node:os";
import * as NodePerfHooks from "node:perf_hooks";
import type { ServerEventLoopStall } from "@t3tools/contracts";
-import { RotatingFileSink } from "@t3tools/shared/logging";
+import { RotatingFileSink, RotatingFileSinkError } from "@t3tools/shared/logging";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -150,15 +150,21 @@ const layerWith = (
const latestNoticeableStall = yield* Ref.make<
{ readonly stall: ServerEventLoopStall; readonly detectedAtMs: number } | undefined
>(undefined);
- const stallSink = yield* Effect.try(
- () =>
+ const stallSink = yield* Effect.try({
+ try: () =>
new RotatingFileSink({
filePath: stallLog.filePath,
maxBytes: stallLog.maxBytes,
maxFiles: 1,
throwOnError: true,
}),
- ).pipe(
+ catch: (cause) =>
+ new RotatingFileSinkError({
+ operation: "initialize",
+ filePath: stallLog.filePath,
+ cause,
+ }),
+ }).pipe(
Effect.catch(() =>
Effect.logWarning("event loop stall log unavailable", {
filePath: stallLog.filePath,
@@ -201,7 +207,17 @@ const layerWith = (
);
if (stallSink !== undefined) {
yield* encodeStallLine({ time: detectedAt, ...attributes }).pipe(
- Effect.flatMap((line) => Effect.try(() => stallSink.write(`${line}\n`))),
+ Effect.flatMap((line) =>
+ Effect.try({
+ try: () => stallSink.write(`${line}\n`),
+ catch: (cause) =>
+ new RotatingFileSinkError({
+ operation: "write",
+ filePath: stallLog.filePath,
+ cause,
+ }),
+ }),
+ ),
Effect.catch(() =>
Effect.logWarning("event loop stall log write failed", {
filePath: stallLog.filePath,
diff --git a/apps/server/src/observability/HeapSnapshot.ts b/apps/server/src/observability/HeapSnapshot.ts
index e452f4f5ce3..6619797d053 100644
--- a/apps/server/src/observability/HeapSnapshot.ts
+++ b/apps/server/src/observability/HeapSnapshot.ts
@@ -7,18 +7,29 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
+import * as Schema from "effect/Schema";
import * as ServerConfig from "../config.ts";
+class HeapSnapshotWriteError extends Schema.TaggedError<HeapSnapshotWriteError>()(
+ "HeapSnapshotWriteError",
+ { path: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `Could not write a heap snapshot to ${this.path}.`;
+ }
+}
+
const writeHeapSnapshot = Effect.fn("server.heapSnapshot", { root: true })(
function* (logsDir: string) {
const fs = yield* FileSystem.FileSystem;
const timestamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-");
const path = NodePath.join(logsDir, `server-${process.pid}-${timestamp}.heapsnapshot`);
yield* Effect.annotateCurrentSpan({ path });
- yield* Effect.try(() => NodeV8.writeHeapSnapshot(path)).pipe(
- Effect.tapError(() => fs.remove(path, { force: true }).pipe(Effect.ignore)),
- );
+ yield* Effect.try({
+ try: () => NodeV8.writeHeapSnapshot(path),
+ catch: (cause) => new HeapSnapshotWriteError({ path, cause }),
+ }).pipe(Effect.tapError(() => fs.remove(path, { force: true }).pipe(Effect.ignore)));
yield* Effect.logInfo("Wrote heap snapshot.", { path });
},
Effect.catch((cause) => Effect.logWarning("Failed to write heap snapshot.", { cause })),
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index a3dea196ed3..3c6295494ec 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -1285,9 +1285,10 @@ export const layerQueryRunner: Layer.Layer<
Effect.gen(function* () {
if (mcpServers !== undefined) {
// Errors and mcp_status can echo headers; log only server names.
- const failed = yield* Effect.tryPromise(() =>
- queryRuntime.setMcpServers(mcpServers),
- ).pipe(
+ const failed = yield* Effect.tryPromise({
+ try: () => queryRuntime.setMcpServers(mcpServers),
+ catch: (cause) => queryRunnerError(cause, "setMcpServers"),
+ }).pipe(
Effect.map((result) => Object.keys(result.errors)),
Effect.orElseSucceed(() => Object.keys(mcpServers)),
Effect.timeoutOrElse({
@@ -1583,7 +1584,10 @@ export const layerQueryRunner: Layer.Layer<
ForkSessionResult & { readonly headMessageId?: string },
unknown
> = usesHostConfig
- ? Effect.tryPromise(() => forkClaudeSession(input.sessionId, input.options))
+ ? Effect.tryPromise({
+ try: () => forkClaudeSession(input.sessionId, input.options),
+ catch: (cause) => queryRunnerError(cause, "forkSession"),
+ })
: forkClaudeSessionInWorker(input).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(Path.Path, path),
@@ -4886,13 +4890,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
const home = customHome
? yield* readBypassSettings(path.join(homePath, "settings.json"))
: {};
- const resolved = yield* Effect.tryPromise(() =>
- resolveClaudeSettings({
- ...(cwd === null ? {} : { cwd }),
- settingSources: customHome ? ["project", "local"] : ["user", "project", "local"],
- serverManagedSettings: claudeSdkBypassSettings(remote),
- }),
- );
+ const resolved = yield* Effect.tryPromise({
+ try: () =>
+ resolveClaudeSettings({
+ ...(cwd === null ? {} : { cwd }),
+ settingSources: customHome ? ["project", "local"] : ["user", "project", "local"],
+ serverManagedSettings: claudeSdkBypassSettings(remote),
+ }),
+ catch: (cause) => queryRunnerError(cause, "resolveSettings"),
+ });
const launchArgSettings = yield* readClaudeLaunchArgSettings({
settings: adapterOptions.settings,
cwd,
@@ -4916,12 +4922,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
adapterOptions.environment.CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL,
);
if (Option.isSome(fromEnvironment)) return fromEnvironment.value;
- const resolved = yield* Effect.tryPromise(() =>
- resolveClaudeSettings({
- ...(cwd === null ? {} : { cwd }),
- settingSources: customHome ? ["project", "local"] : ["user", "project", "local"],
- }),
- ).pipe(Effect.orElseSucceed(() => undefined));
+ const resolved = yield* Effect.tryPromise({
+ try: () =>
+ resolveClaudeSettings({
+ ...(cwd === null ? {} : { cwd }),
+ settingSources: customHome ? ["project", "local"] : ["user", "project", "local"],
+ }),
+ catch: (cause) => queryRunnerError(cause, "resolveSettings"),
+ }).pipe(Effect.orElseSucceed(() => undefined));
const home = customHome
? yield* fileSystem.readFileString(path.join(homePath, "settings.json")).pipe(
Effect.flatMap(decodeClaudeSubagentCacheSettings),
diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts
index c2c67eb04d9..5415998619c 100644
--- a/apps/server/src/orchestration-v2/http.ts
+++ b/apps/server/src/orchestration-v2/http.ts
@@ -246,11 +246,9 @@ export const layer = HttpApiBuilder.group(
Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
- const decoded = yield* Effect.try(() =>
- decodeThreadHistoryCursor(args.query.cursor),
- ).pipe(Effect.result);
+ const decoded = Result.try(() => decodeThreadHistoryCursor(args.query.cursor));
if (Result.isFailure(decoded)) {
- const cause = decoded.failure.cause;
+ const cause = decoded.failure;
if (cause instanceof InvalidThreadHistoryCursorError)
return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);
diff --git a/apps/server/src/persistence/initializeV2Database.test.ts b/apps/server/src/persistence/initializeV2Database.test.ts
index ec8ded1cab5..f8c68f49ceb 100644
--- a/apps/server/src/persistence/initializeV2Database.test.ts
+++ b/apps/server/src/persistence/initializeV2Database.test.ts
@@ -11,6 +11,7 @@ import { ThreadId } from "@t3tools/contracts";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
+import * as Predicate from "effect/Predicate";
import * as SqlClient from "effect/sql/SqlClient";
import * as ServerConfig from "../config.ts";
@@ -124,7 +125,8 @@ it.effect("includes committed WAL data and does not publish a failed snapshot",
const destinationPath = NodePath.join(directory, "statev2.sqlite");
return Effect.gen(function* () {
NodeFS.writeFileSync(sourcePath, "invalid SQLite");
- assert.isTrue((yield* Effect.result(initializeV2Database(destinationPath)))._tag === "Failure");
+ const failure = yield* Effect.flip(initializeV2Database(destinationPath));
+ assert.isFalse(Predicate.isTagged(failure.cause, "V2DatabaseImportError"));
assert.isFalse(NodeFS.existsSync(destinationPath));
NodeFS.unlinkSync(sourcePath);
const source = new NodeSqlite.DatabaseSync(sourcePath);
diff --git a/apps/server/src/persistence/initializeV2Database.ts b/apps/server/src/persistence/initializeV2Database.ts
index 4f6d8d969c3..492567c7980 100644
--- a/apps/server/src/persistence/initializeV2Database.ts
+++ b/apps/server/src/persistence/initializeV2Database.ts
@@ -14,6 +14,8 @@ export class V2DatabaseImportError extends Schema.TaggedError<V2DatabaseImportEr
}
}
+const isV2DatabaseImportError = Schema.is(V2DatabaseImportError);
+
const isProcessAlive = (pid: number): boolean => {
if (!Number.isInteger(pid) || pid <= 0) return false;
try {
@@ -58,13 +60,16 @@ export const initializeV2Database = Effect.fn("initializeV2Database")(function*
prefix: `.v2-import-${process.pid}-`,
});
const snapshotPath = path.join(temporaryDirectory, "snapshot.sqlite");
- yield* Effect.tryPromise(async () => {
- const database = new NodeSqlite.DatabaseSync(sourcePath, { readOnly: true });
- try {
- await NodeSqlite.backup(database, snapshotPath);
- } finally {
- database.close();
- }
+ yield* Effect.tryPromise({
+ try: async () => {
+ const database = new NodeSqlite.DatabaseSync(sourcePath, { readOnly: true });
+ try {
+ await NodeSqlite.backup(database, snapshotPath);
+ } finally {
+ database.close();
+ }
+ },
+ catch: (cause) => new V2DatabaseImportError({ sourcePath, destinationPath, cause }),
});
// Publish only a complete snapshot, without replacing an existing V2 database.
yield* fs.link(snapshotPath, destinationPath).pipe(
@@ -75,6 +80,10 @@ export const initializeV2Database = Effect.fn("initializeV2Database")(function*
);
}).pipe(
Effect.scoped,
- Effect.mapError((cause) => new V2DatabaseImportError({ sourcePath, destinationPath, cause })),
+ Effect.mapError((cause) =>
+ isV2DatabaseImportError(cause)
+ ? cause
+ : new V2DatabaseImportError({ sourcePath, destinationPath, cause }),
+ ),
);
});
diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts
index 2afeae05543..913f6dc6394 100644
--- a/apps/server/src/preview/ServerBrowser.ts
+++ b/apps/server/src/preview/ServerBrowser.ts
@@ -147,6 +147,15 @@ const isHostSetupError = Schema.is(
]),
);
+class ServerBrowserDownloadsCleanupError extends Schema.TaggedError<ServerBrowserDownloadsCleanupError>()(
+ "ServerBrowserDownloadsCleanupError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "The server preview could not clear earlier downloads.";
+ }
+}
+
export class ServerBrowserLaunchError extends Schema.TaggedError<ServerBrowserLaunchError>()(
"ServerBrowserLaunchError",
{ cause: Schema.Defect() },
@@ -1034,7 +1043,10 @@ const make = Effect.gen(function* () {
const downloadsRoot = NodePath.join(config.stateDir, "server-browser", "downloads");
// Saved downloads are indexed in memory, so an earlier run's files can never be opened again.
- yield* Effect.tryPromise(() => NodeFSP.rm(downloadsRoot, { recursive: true, force: true })).pipe(
+ yield* Effect.tryPromise({
+ try: () => NodeFSP.rm(downloadsRoot, { recursive: true, force: true }),
+ catch: (cause) => new ServerBrowserDownloadsCleanupError({ cause }),
+ }).pipe(
Effect.catch((cause) =>
Effect.logWarning("server preview could not clear earlier downloads", { cause }),
),
diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts
index 3ed97f8a7d8..511728cf212 100644
--- a/apps/server/src/project/AgentSessionScanner.ts
+++ b/apps/server/src/project/AgentSessionScanner.ts
@@ -46,6 +46,15 @@ import {
} from "./AgentSessionJson.ts";
const TRANSCRIPT_PREFIX_BYTES = 32 * 1024;
+
+class TranscriptParseError extends Schema.TaggedError<TranscriptParseError>()(
+ "TranscriptParseError",
+ { filePath: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `Could not parse the transcript at ${this.filePath}.`;
+ }
+}
const METADATA_READ_BYTES = 8 * 1024;
const MAX_TRANSCRIPT_SCAN_BYTES = 1024 * 1024;
const MAX_CODEX_SESSION_INDEX_BYTES = 1024 * 1024;
@@ -1071,23 +1080,33 @@ export const make = Effect.gen(function* () {
}
bytesRead += next.value.byteLength;
- const withinBudget = yield* Effect.try(() => {
- let start = 0;
- while (start < next.value.byteLength) {
- const newline = next.value.indexOf(10, start);
- const end = newline === -1 ? next.value.byteLength : newline;
- recordStarted = true;
- reader.write(decoder.decode(next.value.subarray(start, end), { stream: true }));
- if (newline === -1) break;
- if (!finishRecord()) return false;
- start = newline + 1;
- }
- return true;
+ const withinBudget = yield* Effect.try({
+ try: () => {
+ let start = 0;
+ while (start < next.value.byteLength) {
+ const newline = next.value.indexOf(10, start);
+ const end = newline === -1 ? next.value.byteLength : newline;
+ recordStarted = true;
+ reader.write(decoder.decode(next.value.subarray(start, end), { stream: true }));
+ if (newline === -1) break;
+ if (!finishRecord()) return false;
+ start = newline + 1;
+ }
+ return true;
+ },
+ catch: (cause) => new TranscriptParseError({ filePath, cause }),
});
if (!withinBudget) return null;
}
- if (recordStarted && !(yield* Effect.try(finishRecord))) return null;
+ if (
+ recordStarted &&
+ !(yield* Effect.try({
+ try: finishRecord,
+ catch: (cause) => new TranscriptParseError({ filePath, cause }),
+ }))
+ )
+ return null;
return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))
? { records, cwd, claudeFields }
: null;
diff --git a/apps/server/src/provider/AntigravityInstallation.ts b/apps/server/src/provider/AntigravityInstallation.ts
index b70e5d68600..707cb0b4469 100644
--- a/apps/server/src/provider/AntigravityInstallation.ts
+++ b/apps/server/src/provider/AntigravityInstallation.ts
@@ -497,9 +497,10 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma
return;
}
- const available = yield* Effect.tryPromise(() =>
- NodeFSP.statfs(versionsDirectory, { bigint: true }),
- ).pipe(Effect.option);
+ const available = yield* Effect.tryPromise({
+ try: () => NodeFSP.statfs(versionsDirectory, { bigint: true }),
+ catch: (cause) => installationError("download", "Could not check free disk space.", cause),
+ }).pipe(Effect.option);
const required =
asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN;
if (
diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts
index 97512d3d621..ded4badd6fc 100644
--- a/apps/server/src/provider/ClaudeProvider.ts
+++ b/apps/server/src/provider/ClaudeProvider.ts
@@ -13,6 +13,7 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
+import * as Schema from "effect/Schema";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { createModelCapabilities } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
@@ -335,6 +336,15 @@ function claudeGatewayDiscoveryGraceMs(environment: Readonly<Record<string, unkn
return Number.isFinite(configured) && configured > 0 ? configured : 3_000;
}
+class ClaudeCapabilitiesProbeSdkError extends Schema.TaggedError<ClaudeCapabilitiesProbeSdkError>()(
+ "ClaudeCapabilitiesProbeSdkError",
+ { operation: Schema.Literals(["initialize", "usage"]), cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `Claude capability probe ${this.operation} failed.`;
+ }
+}
+
/** A never-yielding prompt allows local initialization IPC without sending an Anthropic request. */
const probeClaudeCapabilities = (
claudeSettings: ClaudeSettings,
@@ -360,22 +370,25 @@ const probeClaudeCapabilities = (
...(yield* readClaudeSettingsEnv(claudeSettings, cwd, claudeEnvironment)),
})
: 0;
- return yield* Effect.tryPromise(async () => {
- const q = claudeQuery({
- // oxlint-disable-next-line require-yield -- never yields, so no prompt reaches the API
- prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
- await waitForAbortSignal(abort.signal);
- })(),
- options: buildClaudeCapabilitiesProbeQueryOptions({
- executablePath,
- abortController: abort,
- environment: claudeEnvironment,
- cwd,
- managedMcpConfig,
- }),
- });
- const init = await q.initializationResult();
- return { q, init, graceMs };
+ return yield* Effect.tryPromise({
+ try: async () => {
+ const q = claudeQuery({
+ // oxlint-disable-next-line require-yield -- never yields, so no prompt reaches the API
+ prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
+ await waitForAbortSignal(abort.signal);
+ })(),
+ options: buildClaudeCapabilitiesProbeQueryOptions({
+ executablePath,
+ abortController: abort,
+ environment: claudeEnvironment,
+ cwd,
+ managedMcpConfig,
+ }),
+ });
+ const init = await q.initializationResult();
+ return { q, init, graceMs };
+ },
+ catch: (cause) => new ClaudeCapabilitiesProbeSdkError({ operation: "initialize", cause }),
});
}).pipe(
Effect.timeout(CAPABILITIES_PROBE_TIMEOUT_MS),
@@ -386,9 +399,13 @@ const probeClaudeCapabilities = (
// `behaviors`: with a few GB of transcripts it outlasts the deadline.
const usageCheckedAt = DateTime.formatIso(yield* DateTime.now);
const usageResult = includeUsage
- ? yield* Effect.tryPromise(() =>
- q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true }),
- ).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result)
+ ? yield* Effect.tryPromise({
+ try: () =>
+ q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({
+ skipBehaviors: true,
+ }),
+ catch: (cause) => new ClaudeCapabilitiesProbeSdkError({ operation: "usage", cause }),
+ }).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result)
: undefined;
const usage =
usageResult && Result.isSuccess(usageResult)
diff --git a/apps/server/src/provider/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.ts
index 1c23f395935..44a2f799e3d 100644
--- a/apps/server/src/provider/CodexChatGptAuth.test.ts
+++ b/apps/server/src/provider/CodexChatGptAuth.test.ts
@@ -1640,8 +1640,13 @@ it.effect(
const callback = new URL(
new URL(state.authorizationUrl!).searchParams.get("redirect_uri")!,
);
- const request = yield* Effect.tryPromise(() => fetch(callback)).pipe(Effect.result);
- assert.strictEqual(request._tag, "Failure");
+ const rejected = yield* Effect.promise(() =>
+ fetch(callback).then(
+ () => false,
+ () => true,
+ ),
+ );
+ assert.isTrue(rejected);
assert.isTrue(Option.isNone(yield* h.auth.read));
}),
),
diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts
index d3035d5ae9b..d6cb74aa19e 100644
--- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts
+++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts
@@ -414,7 +414,10 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function*
if (visited.has(canonical)) return null;
visited.add(canonical);
const fingerprintOf = (file: string) =>
- Effect.tryPromise(() => NodeFSP.stat(file)).pipe(
+ Effect.tryPromise({
+ try: () => NodeFSP.stat(file),
+ catch: (cause) => new AntigravityDatabaseDecodeError({ path: file, cause }),
+ }).pipe(
Effect.map((stat) => ({ stat, part: `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` })),
);
const { stat, part } = yield* fingerprintOf(path);
diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts
index 00de1e83629..41e25f2e417 100644
--- a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts
+++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts
@@ -8,6 +8,7 @@ import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
import type * as EffectAcpSchema from "effect-acp/compat";
import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts";
@@ -41,19 +42,33 @@ interface LastStep {
readonly payload: Uint8Array | null;
}
+class AntigravitySessionLogError extends Schema.TaggedError<AntigravitySessionLogError>()(
+ "AntigravitySessionLogError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Could not read the Antigravity session log.";
+ }
+}
+
+const sessionLogError = (cause: unknown) => new AntigravitySessionLogError({ cause });
+
const readSteps = <A>(file: string, read: (database: NodeSqlite.DatabaseSync) => A) =>
- Effect.try(() => {
- const database = new NodeSqlite.DatabaseSync(file, { readOnly: true });
- try {
- database.exec("PRAGMA busy_timeout = 100");
- const hasSteps =
- database
- .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'")
- .get() !== undefined;
- return hasSteps ? read(database) : undefined;
- } finally {
- database.close();
- }
+ Effect.try({
+ try: () => {
+ const database = new NodeSqlite.DatabaseSync(file, { readOnly: true });
+ try {
+ database.exec("PRAGMA busy_timeout = 100");
+ const hasSteps =
+ database
+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'")
+ .get() !== undefined;
+ return hasSteps ? read(database) : undefined;
+ } finally {
+ database.close();
+ }
+ },
+ catch: sessionLogError,
});
const lastStepIndex = (database: NodeSqlite.DatabaseSync) => {
@@ -142,22 +157,25 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w
DateTime.now.pipe(Effect.map((now) => turnFailure(result.stopReason, undefined, now)));
if (!NATIVE_SESSION_ID.test(sessionId)) return typedOnly;
const segments = [...conversationSegments, `${sessionId}.db`];
- const before = yield* Effect.tryPromise(async () => {
- const root = await antigravityProfileRoot(profileDirectory);
- if (root === undefined) return undefined;
- if ((await antigravityManagedPath(root, conversationSegments, "directory")) === undefined) {
- return undefined;
- }
- const database = await antigravityManagedPath(root, segments, "file");
- // A path that exists but fails the proof is a link or other foreign entry.
- if (database === undefined) {
- const present = await NodeFSP.lstat(NodePath.join(root, ...segments)).then(
- () => true,
- () => false,
- );
- return present ? undefined : { root, identity: undefined, startIndex: -1 };
- }
- return { root, identity: database.info, startIndex: undefined };
+ const before = yield* Effect.tryPromise({
+ try: async () => {
+ const root = await antigravityProfileRoot(profileDirectory);
+ if (root === undefined) return undefined;
+ if ((await antigravityManagedPath(root, conversationSegments, "directory")) === undefined) {
+ return undefined;
+ }
+ const database = await antigravityManagedPath(root, segments, "file");
+ // A path that exists but fails the proof is a link or other foreign entry.
+ if (database === undefined) {
+ const present = await NodeFSP.lstat(NodePath.join(root, ...segments)).then(
+ () => true,
+ () => false,
+ );
+ return present ? undefined : { root, identity: undefined, startIndex: -1 };
+ }
+ return { root, identity: database.info, startIndex: undefined };
+ },
+ catch: sessionLogError,
}).pipe(Effect.orElseSucceed(() => undefined));
if (before === undefined) {
yield* Effect.logWarning("The Antigravity session log is not this session's own file.");
@@ -177,9 +195,10 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w
result: EffectAcpSchema.PromptResponse,
) {
// The same file as before the prompt, or one this prompt created, still unlinked.
- const after = yield* Effect.tryPromise(() =>
- antigravityManagedPath(before.root, segments, "file"),
- ).pipe(Effect.orElseSucceed(() => undefined));
+ const after = yield* Effect.tryPromise({
+ try: () => antigravityManagedPath(before.root, segments, "file"),
+ catch: sessionLogError,
+ }).pipe(Effect.orElseSucceed(() => undefined));
const sameFile =
after !== undefined &&
(before.identity === undefined ||
diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts
index 2b2ae029e5b..32de13ef129 100644
--- a/apps/server/src/provider/antigravityAuthSupport.ts
+++ b/apps/server/src/provider/antigravityAuthSupport.ts
@@ -230,6 +230,15 @@ function antigravityEnvironment(
};
}
+class AntigravitySkillLinkError extends Schema.TaggedError<AntigravitySkillLinkError>()(
+ "AntigravitySkillLinkError",
+ { link: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `Could not link Antigravity user skills at ${this.link}.`;
+ }
+}
+
/** Private GEMINI_HOME isolates credentials/hooks/MCP; link global skills from the real ~/.gemini. */
const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(function* (input: {
readonly profileDirectory: string;
@@ -260,7 +269,10 @@ const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(functio
// An empty folder is the harness's placeholder from a launch without the link.
// rmdir refuses a non-empty folder, so content added meanwhile is never deleted.
Effect.catch((error) =>
- Effect.tryPromise(() => NodeFSP.rmdir(link)).pipe(
+ Effect.tryPromise({
+ try: () => NodeFSP.rmdir(link),
+ catch: (cause) => new AntigravitySkillLinkError({ link, cause }),
+ }).pipe(
Effect.as(undefined),
Effect.mapError(() => error),
),
@@ -271,9 +283,10 @@ const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(functio
yield* fs.remove(link);
}
yield* fs.makeDirectory(path.dirname(link), { recursive: true });
- yield* Effect.tryPromise(() =>
- NodeFSP.symlink(target, link, input.platform === "win32" ? "junction" : "dir"),
- );
+ yield* Effect.tryPromise({
+ try: () => NodeFSP.symlink(target, link, input.platform === "win32" ? "junction" : "dir"),
+ catch: (cause) => new AntigravitySkillLinkError({ link, cause }),
+ });
}).pipe(
Effect.catch((error) =>
Effect.logWarning("Antigravity user skills are not linked into the profile.", {
diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts
index 9714d9175af..6ce9fce4a50 100644
--- a/apps/server/src/storageCleanup.ts
+++ b/apps/server/src/storageCleanup.ts
@@ -67,6 +67,15 @@ const decodePnpmModulesManifest = Schema.decodeUnknownEffect(
}),
);
+class PnpmModulesManifestParseError extends Schema.TaggedError<PnpmModulesManifestParseError>()(
+ "PnpmModulesManifestParseError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Could not parse the pnpm modules manifest.";
+ }
+}
+
const DAY_MS = 86_400_000;
// Give settle scripts time to open terminals that protect the worktree.
const SETTLE_SCRIPT_GRACE_MS = 60_000;
@@ -341,7 +350,12 @@ const make = Effect.gen(function* () {
function* (root: string) {
const nodeModules = path.join(root, "node_modules");
const text = yield* fs.readFileString(path.join(nodeModules, ".modules.yaml"));
- const manifest = yield* decodePnpmModulesManifest(yield* Effect.try(() => parseYaml(text)));
+ const manifest = yield* decodePnpmModulesManifest(
+ yield* Effect.try({
+ try: () => parseYaml(text),
+ catch: (cause) => new PnpmModulesManifestParseError({ cause }),
+ }),
+ );
// An agent can write this manifest, and statting a network path makes
// Windows sign in to its host with the user's NTLM credentials.
if (isNetworkPath(manifest.storeDir) || isNetworkPath(manifest.virtualStoreDir ?? "")) {
diff --git a/apps/server/src/terminal/NodePtyAdapter.ts b/apps/server/src/terminal/NodePtyAdapter.ts
index 4b83ddf6697..cc7ae638f7d 100644
--- a/apps/server/src/terminal/NodePtyAdapter.ts
+++ b/apps/server/src/terminal/NodePtyAdapter.ts
@@ -24,6 +24,15 @@ export class NodePtyModuleLoadError extends Schema.TaggedError<NodePtyModuleLoad
}
}
+class NodePtyCancelError extends Schema.TaggedError<NodePtyCancelError>()("NodePtyCancelError", {
+ terminalPid: Schema.Number,
+ cause: Schema.Defect(),
+}) {
+ override get message(): string {
+ return `Failed to cancel Windows terminal startup for ${this.terminalPid}.`;
+ }
+}
+
type NodePtyModuleLoader = () => Promise<typeof import("node-pty")>;
// node-pty's native addon stays external; single-executables need require to resolve disk modules and spawn helpers.
@@ -134,18 +143,21 @@ const waitForWindowsPid = (
// The private agent cancels pending connections before a child exists; public kill waits for first output.
const killStartingWindowsPty = (process: import("node-pty").IPty) =>
- Effect.try(() => {
- if (
- "_agent" in process &&
- typeof process._agent === "object" &&
- process._agent !== null &&
- "kill" in process._agent &&
- typeof process._agent.kill === "function"
- ) {
- process._agent.kill();
- } else {
- process.kill();
- }
+ Effect.try({
+ try: () => {
+ if (
+ "_agent" in process &&
+ typeof process._agent === "object" &&
+ process._agent !== null &&
+ "kill" in process._agent &&
+ typeof process._agent.kill === "function"
+ ) {
+ process._agent.kill();
+ } else {
+ process.kill();
+ }
+ },
+ catch: (cause) => new NodePtyCancelError({ terminalPid: process.pid, cause }),
}).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to cancel Windows terminal startup", {
diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts
index 9cf97cd4c7c..c33b6da64a7 100644
--- a/apps/server/src/usage/UsageService.test.ts
+++ b/apps/server/src/usage/UsageService.test.ts
@@ -56,14 +56,20 @@ import { MuseUsageHome } from "@t3tools/provider-muse/server";
import { makeScanCacheWriter, SCAN_CACHE_FILE_NAME } from "./usageScanCache.ts";
vi.mock("node:fs/promises", { spy: true });
-vi.mock("../../../../packages/provider-muse/src/server/sdk.ts", async (importOriginal) => ({
- ...(await importOriginal<typeof MuseSdk>()),
- createMuseSdkHostEffect: vi.fn(() =>
- Effect.try(() => {
- throw new Error("Muse is not installed in this test");
- }),
- ),
-}));
+vi.mock("../../../../packages/provider-muse/src/server/sdk.ts", async (importOriginal) => {
+ const original = await importOriginal<typeof MuseSdk>();
+ return {
+ ...original,
+ createMuseSdkHostEffect: vi.fn(() =>
+ Effect.fail(
+ new original.MuseSdkError({
+ operation: "start",
+ cause: new Error("Muse is not installed in this test"),
+ }),
+ ),
+ ),
+ };
+});
const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts
index 351daa0e697..94404b488b1 100644
--- a/apps/server/src/vcs/GitVcsDriverCore.ts
+++ b/apps/server/src/vcs/GitVcsDriverCore.ts
@@ -1,5 +1,4 @@
import * as Cache from "effect/Cache";
-import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Data from "effect/Data";
import * as Digest from "effect/crypto/Digest";
@@ -42,7 +41,7 @@ import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings";
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
-import { removeEmptyDirectory } from "./removeEmptyDirectory.ts";
+import { removeEmptyDirectory, type RemoveEmptyDirectoryError } from "./removeEmptyDirectory.ts";
import { explicitBareRepositoryEnv, gitConfigEnv } from "./VcsProcess.ts";
import { removeLinkedWorktree } from "./worktreeRemoval.ts";
import { resolveWorktreesDirectory } from "../worktreesDirectory.ts";
@@ -4732,7 +4731,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
// Recursive filesystem traversal can visit many entries; removeWorktree owns the operation span.
const removeLeftoverLinks = Effect.fnUntraced(function* (
target: string,
- ): Effect.fn.Return<boolean, PlatformError.PlatformError | Cause.UnknownError> {
+ ): Effect.fn.Return<boolean, PlatformError.PlatformError | RemoveEmptyDirectoryError> {
if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) {
yield* fileSystem.remove(target);
return true;
diff --git a/apps/server/src/vcs/removeEmptyDirectory.ts b/apps/server/src/vcs/removeEmptyDirectory.ts
index 2ce80dfe588..f7c8348af8d 100644
--- a/apps/server/src/vcs/removeEmptyDirectory.ts
+++ b/apps/server/src/vcs/removeEmptyDirectory.ts
@@ -2,6 +2,16 @@
import * as NodeFSP from "node:fs/promises";
import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+
+export class RemoveEmptyDirectoryError extends Schema.TaggedError<RemoveEmptyDirectoryError>()(
+ "RemoveEmptyDirectoryError",
+ { path: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `Could not remove the directory ${this.path}.`;
+ }
+}
/**
* Removes `path` only while it is an empty directory. Succeeds with false when
@@ -9,7 +19,10 @@ import * as Effect from "effect/Effect";
* Other failures, such as a permission error, stay errors.
*/
export const removeEmptyDirectory = (path: string) =>
- Effect.tryPromise(() => NodeFSP.rmdir(path)).pipe(
+ Effect.tryPromise({
+ try: () => NodeFSP.rmdir(path),
+ catch: (cause) => new RemoveEmptyDirectoryError({ path, cause }),
+ }).pipe(
Effect.as(true),
Effect.catchIf(
(error) => (error.cause as NodeJS.ErrnoException | undefined)?.code === "ENOTEMPTY",
diff --git a/apps/web/src/components/device/deviceHubAtoms.ts b/apps/web/src/components/device/deviceHubAtoms.ts
index 5a83f26824d..e9e6c1c66b9 100644
--- a/apps/web/src/components/device/deviceHubAtoms.ts
+++ b/apps/web/src/components/device/deviceHubAtoms.ts
@@ -1,6 +1,7 @@
import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
+import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { AsyncResult, Atom } from "effect/reactivity";
@@ -40,11 +41,23 @@ export const deviceEventLogAtom = Atom.family((target: DeviceHubTarget) =>
}).pipe(Atom.withLabel(`device-event-log:${target.deviceId}`)),
);
+class DeviceAxTreeFetchError extends Schema.TaggedError<DeviceAxTreeFetchError>()(
+ "DeviceAxTreeFetchError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Could not read the device accessibility tree.";
+ }
+}
+
// A failed poll keeps the last frames on screen; the next poll replaces them.
export const deviceAxElementsAtom = Atom.family((target: DeviceHubTarget) =>
Atom.make(
Stream.fromEffectSchedule(
- Effect.tryPromise((signal) => fetchDeviceAxTree(target, signal)).pipe(
+ Effect.tryPromise({
+ try: (signal) => fetchDeviceAxTree(target, signal),
+ catch: (cause) => new DeviceAxTreeFetchError({ cause }),
+ }).pipe(
Effect.map((tree): ReadonlyArray<DeviceAxElement> | null => tree.elements),
Effect.orElseSucceed(() => null),
),
diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts
index e60ed172e92..dcd50342f1c 100644
--- a/apps/web/src/connection/platform.ts
+++ b/apps/web/src/connection/platform.ts
@@ -313,13 +313,15 @@ const ANALYTICS_DEVICE_ID_KEY = "t3code:analytics-device-id";
// Lives as long as this browser profile's site data. Storage can be blocked, which only drops the id.
const analyticsDevice = {
- id: Effect.try(() => {
- const existing = window.localStorage.getItem(ANALYTICS_DEVICE_ID_KEY);
- if (existing) return existing;
- const created = randomUUID();
- window.localStorage.setItem(ANALYTICS_DEVICE_ID_KEY, created);
- return created;
- }).pipe(Effect.option),
+ id: Effect.sync(
+ Option.liftThrowable(() => {
+ const existing = window.localStorage.getItem(ANALYTICS_DEVICE_ID_KEY);
+ if (existing) return existing;
+ const created = randomUUID();
+ window.localStorage.setItem(ANALYTICS_DEVICE_ID_KEY, created);
+ return created;
+ }),
+ ),
};
const layerCapabilities = Layer.effectContext(
diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts
index dbddce4c1c2..5b0cf7d1e1e 100644
--- a/evals/mcp-tool-use/run.ts
+++ b/evals/mcp-tool-use/run.ts
@@ -112,6 +112,15 @@ const isPricedModel = (model: ShellModel): model is PricedModel => model in PRIC
const T3_PREFIX = "mcp__t3-code__";
const RUNTIME_MARKER = "<runtime_info>";
const TOOL_LOADED = "Tool loaded.";
+
+class EvalToolCallError extends Schema.TaggedError<EvalToolCallError>()("EvalToolCallError", {
+ tool: Schema.String,
+ cause: Schema.Defect(),
+}) {
+ override get message(): string {
+ return `The ${this.tool} tool call failed.`;
+ }
+}
const DEFERRED_LIST =
/(The following deferred tools are now available via ToolSearch\.[^\n]*\n)((?:[^\n]+\n)*)/;
const MODEL_LINE = /You are powered by the model named .+?\. The exact model ID is [\w.-]+\./;
@@ -2063,24 +2072,27 @@ const runSample = Effect.fn("evaluateMcpToolUse.runSample")(function* (
runPromise,
);
};
- return yield* Effect.tryPromise(async () => {
- const output =
- use.name === "exec"
- ? await executeCodex(
- valueText(use.input),
- codexCatalog(base),
- answer,
- sample.codeStore,
- )
- : await answer(use.name, use.input, false);
- const item = {
- type: use.name === "exec" ? "custom_tool_call_output" : "function_call_output",
- call_id: use.id,
- output: valueText(output),
- };
- input.push(item);
- transcript.push(item);
- return toolResult(use.id, output);
+ return yield* Effect.tryPromise({
+ try: async () => {
+ const output =
+ use.name === "exec"
+ ? await executeCodex(
+ valueText(use.input),
+ codexCatalog(base),
+ answer,
+ sample.codeStore,
+ )
+ : await answer(use.name, use.input, false);
+ const item = {
+ type: use.name === "exec" ? "custom_tool_call_output" : "function_call_output",
+ call_id: use.id,
+ output: valueText(output),
+ };
+ input.push(item);
+ transcript.push(item);
+ return toolResult(use.id, output);
+ },
+ catch: (cause) => new EvalToolCallError({ tool: use.name, cause }),
});
}),
);
@@ -2429,11 +2441,16 @@ const main = Effect.gen(function* () {
// Only a case that passed every baseline sample can stop a run; flaky ones are just reported.
const passedBefore = (id: string) => baseline.get(id) === 1;
// Before the paid runs, so a missing git cannot lose their results.
- const commit = yield* Effect.try(() =>
- NodeChildProcess.execFileSync("git", ["describe", "--always", "--dirty"], {
- encoding: "utf8",
- }).trim(),
- ).pipe(Effect.orElseSucceed(() => "unknown"));
+ const commit = yield* Effect.sync(() =>
+ Option.getOrElse(
+ Option.liftThrowable(() =>
+ NodeChildProcess.execFileSync("git", ["describe", "--always", "--dirty"], {
+ encoding: "utf8",
+ }).trim(),
+ )(),
+ () => "unknown",
+ ),
+ );
const inFlight = yield* Semaphore.make(flags.concurrency);
const runOne = (testCase: McpToolUseCase) => {
const { id, kind, pattern } = testCase;
diff --git a/infra/relay/scripts/android-push-watch.ts b/infra/relay/scripts/android-push-watch.ts
index 5f052f58e4c..e62ac73d746 100644
--- a/infra/relay/scripts/android-push-watch.ts
+++ b/infra/relay/scripts/android-push-watch.ts
@@ -42,7 +42,19 @@ const Connection = Schema.Struct({
wsUrl: Schema.NonEmptyString,
bearerToken: Schema.NonEmptyString,
});
-const readFile = (path: string) => Effect.tryPromise(() => NodeFSP.readFile(path, "utf8"));
+class WatchReadFileError extends Schema.TaggedError<WatchReadFileError>()("WatchReadFileError", {
+ path: Schema.String,
+ cause: Schema.Defect(),
+}) {
+ override get message() {
+ return `Could not read ${this.path}`;
+ }
+}
+const readFile = (path: string) =>
+ Effect.tryPromise({
+ try: () => NodeFSP.readFile(path, "utf8"),
+ catch: (cause) => new WatchReadFileError({ path, cause }),
+ });
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
class WatchUnregisteredDeviceError extends Schema.TaggedError<WatchUnregisteredDeviceError>()(
"WatchUnregisteredDeviceError",
diff --git a/infra/task-cache/src/developerAuth.ts b/infra/task-cache/src/developerAuth.ts
index f358a8961e2..c7e4b35c6a2 100644
--- a/infra/task-cache/src/developerAuth.ts
+++ b/infra/task-cache/src/developerAuth.ts
@@ -1,4 +1,5 @@
import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
const Keys = Schema.fromJsonString(Schema.Record(Schema.String, Schema.String));
@@ -13,7 +14,7 @@ export const developerIdentity = Effect.fn("TaskCache.developerIdentity")(functi
if (!authorization?.toLowerCase().startsWith("basic ")) return undefined;
if (!encodedKeys || authorization.length > 1024) return null;
- const decoded = yield* Effect.try(() => atob(authorization.slice(6))).pipe(Effect.option);
+ const decoded = Option.liftThrowable(atob)(authorization.slice(6));
if (decoded._tag === "None") return null;
const keys = yield* decodeKeys(encodedKeys).pipe(Effect.option);
if (keys._tag === "None") return null;
diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts
index 0ef446ef345..ecbe61e3427 100644
--- a/packages/provider-acp/src/server/AcpSessionRuntime.ts
+++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts
@@ -484,18 +484,18 @@ export function terminateLinuxCgroupLease(
let lastRemovalFailure: { readonly cause: unknown } | null = null;
for (let attempt = 0; attempt < 200; attempt += 1) {
if (!lease.exists()) return;
- const killed = yield* Effect.try(() => lease.kill()).pipe(Effect.result);
+ const killed = Result.try(() => lease.kill());
if (Result.isFailure(killed)) {
- const cause = killed.failure.cause;
+ const cause = killed.failure;
const code = (cause as NodeJS.ErrnoException | undefined)?.code;
if (code !== "ENOENT") return yield* failure("kill", cause);
if (!lease.exists()) return;
yield* Effect.sleep("10 millis");
continue;
}
- const populated = yield* Effect.try(() => lease.populated()).pipe(Effect.result);
+ const populated = Result.try(() => lease.populated());
if (Result.isFailure(populated)) {
- const cause = populated.failure.cause;
+ const cause = populated.failure;
const code = (cause as NodeJS.ErrnoException | undefined)?.code;
if (code === "ENOENT" && !lease.exists()) return;
if (code === "ENOENT") {
@@ -509,9 +509,9 @@ export function terminateLinuxCgroupLease(
yield* Effect.sleep("10 millis");
continue;
}
- const removed = yield* Effect.try(() => lease.remove()).pipe(Effect.result);
+ const removed = Result.try(() => lease.remove());
if (Result.isFailure(removed)) {
- const cause = removed.failure.cause;
+ const cause = removed.failure;
const code = (cause as NodeJS.ErrnoException | undefined)?.code;
if (code === "ENOENT" && !lease.exists()) return;
if (code !== "EBUSY" && code !== "ENOTEMPTY" && code !== "ENOENT") {
diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts
index f48d7baf1b2..92fb764b432 100644
--- a/packages/provider-cursor/src/server/CursorAgentSdk.ts
+++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts
@@ -357,20 +357,23 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
if (yield* Ref.getAndSet(sandboxSupportPrimeStarted, true)) {
return yield* Deferred.await(sandboxSupportPrimed);
}
- yield* Effect.tryPromise(async () => {
- const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
- const platform = await sdk
- .load()
- .createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
- const release = await platform.prewarmLocalWorkspace({
- ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
- local: {
- ...(cwd === undefined ? {} : { cwd }),
- settingSources: [],
- sandboxOptions: { enabled: true },
- },
- });
- await release();
+ yield* Effect.tryPromise({
+ try: async () => {
+ const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
+ const platform = await sdk
+ .load()
+ .createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
+ const release = await platform.prewarmLocalWorkspace({
+ ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
+ local: {
+ ...(cwd === undefined ? {} : { cwd }),
+ settingSources: [],
+ sandboxOptions: { enabled: true },
+ },
+ });
+ await release();
+ },
+ catch: (cause) => runnerError(cause, "prewarmLocalWorkspace"),
}).pipe(Effect.ignore, Effect.ensuring(Deferred.succeed(sandboxSupportPrimed, undefined)));
},
);
diff --git a/packages/provider-cursor/src/server/credentialStore.test.ts b/packages/provider-cursor/src/server/credentialStore.test.ts
index 1ced56c62b8..d9ee986acc5 100644
--- a/packages/provider-cursor/src/server/credentialStore.test.ts
+++ b/packages/provider-cursor/src/server/credentialStore.test.ts
@@ -56,7 +56,7 @@ it.effect.each([
yield* (yield* host.credentials("cursor", instanceId)).set(new TextEncoder().encode(stored));
}
const migrated = yield* makeCursorCredentialStore(instanceId, legacyFile);
- assert.strictEqual((yield* Effect.tryPromise(() => migrated.store.load()))?.apiKey, expected);
+ assert.strictEqual((yield* Effect.promise(() => migrated.store.load()))?.apiKey, expected);
assert.isFalse(yield* fileSystem.exists(legacyFile));
}).pipe(Effect.scoped, Effect.provide(layerHost)),
);
@@ -77,21 +77,21 @@ it.effect(
apiKeyExpiresAtMs: 1000,
};
- yield* Effect.tryPromise(() => personal.store.save(credentials));
- yield* Effect.tryPromise(() =>
+ yield* Effect.promise(() => personal.store.save(credentials));
+ yield* Effect.promise(() =>
work.store.save({ ...credentials, apiKey: "test-only-work-key" }),
);
const restored = yield* makeStore("personal");
- assert.deepEqual(yield* Effect.tryPromise(() => restored.store.load()), credentials);
+ assert.deepEqual(yield* Effect.promise(() => restored.store.load()), credentials);
yield* (yield* host.credentials("cursor", "personal")).set(
new TextEncoder().encode("damaged credential"),
);
- assert.isUndefined(yield* Effect.tryPromise(() => restored.store.load()));
- yield* Effect.tryPromise(() => restored.store.save(credentials));
- yield* Effect.tryPromise(() => restored.store.clear());
- assert.isUndefined(yield* Effect.tryPromise(() => personal.store.load()));
+ assert.isUndefined(yield* Effect.promise(() => restored.store.load()));
+ yield* Effect.promise(() => restored.store.save(credentials));
+ yield* Effect.promise(() => restored.store.clear());
+ assert.isUndefined(yield* Effect.promise(() => personal.store.load()));
assert.strictEqual(
- (yield* Effect.tryPromise(() => work.store.load()))?.apiKey,
+ (yield* Effect.promise(() => work.store.load()))?.apiKey,
"test-only-work-key",
);
}).pipe(Effect.provide(layerHost)),
@@ -131,10 +131,10 @@ it.effect.each([
const credentials = { ...requiredFields };
// Match the SDK's runtime values without relying on its stricter declarations.
Object.assign(credentials, optionalFields);
- yield* Effect.tryPromise(() => store.save(credentials));
+ yield* Effect.promise(() => store.save(credentials));
const restored = yield* makeCursorCredentialStore(instanceId);
- assert.deepEqual(yield* Effect.tryPromise(() => restored.store.load()), {
+ assert.deepEqual(yield* Effect.promise(() => restored.store.load()), {
...requiredFields,
...expectedFields,
});
diff --git a/packages/provider-cursor/src/server/textGeneration.ts b/packages/provider-cursor/src/server/textGeneration.ts
index fa8228d0ba0..278839558ee 100644
--- a/packages/provider-cursor/src/server/textGeneration.ts
+++ b/packages/provider-cursor/src/server/textGeneration.ts
@@ -86,7 +86,12 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
const { operation, prompt, modelSelection } = input;
const apiKey = yield* resolveCursorApiKey(operation);
- const { Agent } = yield* Effect.try(sdk.load);
+ const sdkFailure = (detail: string) => (cause: unknown) =>
+ new TextGenerationError({ operation, detail, cause });
+ const { Agent } = yield* Effect.try({
+ try: sdk.load,
+ catch: sdkFailure("Cursor SDK could not be loaded."),
+ });
// sandbox.json expands writable paths independently of settingSources; the public API cannot override it.
if (yield* fs.exists(`${yield* HostProcess.HomeDirectory}/.cursor/sandbox.json`)) {
return yield* new TextGenerationError({
@@ -99,10 +104,15 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
// Only store disposal releases SDK SQLite handles; keep state outside the empty workspace.
const stateRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-state-" });
const store = yield* Effect.acquireRelease(
- Effect.tryPromise(() =>
- sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot }),
- ),
- (store) => Effect.tryPromise(() => store.dispose()).pipe(Effect.ignore({ log: true })),
+ Effect.tryPromise({
+ try: () => sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot }),
+ catch: sdkFailure("Cursor SDK agent store could not be opened."),
+ }),
+ (store) =>
+ Effect.tryPromise({
+ try: () => store.dispose(),
+ catch: sdkFailure("Cursor SDK agent store could not be disposed."),
+ }).pipe(Effect.ignore({ log: true })),
);
const agentOptions = {
apiKey,
@@ -118,22 +128,24 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
},
} satisfies AgentOptions;
const createCursorAgent = (sandboxEnabled: boolean) =>
- Effect.tryPromise((signal) =>
- Agent.create(
- sandboxEnabled
- ? agentOptions
- : {
- ...agentOptions,
- local: {
- ...agentOptions.local,
- sandboxOptions: { enabled: false },
+ Effect.tryPromise({
+ try: (signal) =>
+ Agent.create(
+ sandboxEnabled
+ ? agentOptions
+ : {
+ ...agentOptions,
+ local: {
+ ...agentOptions.local,
+ sandboxOptions: { enabled: false },
+ },
},
- },
- ).then((agent) => {
- if (signal.aborted) agent.close();
- return agent;
- }),
- );
+ ).then((agent) => {
+ if (signal.aborted) agent.close();
+ return agent;
+ }),
+ catch: sdkFailure("Cursor SDK agent could not be created."),
+ });
const request = Effect.gen(function* () {
// Empty cwd and setting sources isolate the run from user projects even if sandboxing fails.
@@ -142,27 +154,32 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
Effect.catchIf(cursorSandboxUnsupported, () => createCursorAgent(false)),
),
(agent) =>
- Effect.tryPromise(() => agent[Symbol.asyncDispose]()).pipe(
- Effect.timeout("5 seconds"),
- Effect.ignore({ log: true }),
- ),
+ Effect.tryPromise({
+ try: () => agent[Symbol.asyncDispose](),
+ catch: sdkFailure("Cursor SDK agent could not be disposed."),
+ }).pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })),
{ interruptible: true },
);
- const run = yield* Effect.tryPromise((signal) =>
- agent.send(prompt).then((run) => {
- if (signal.aborted) void run.cancel().catch(() => undefined);
- return run;
- }),
- );
+ const run = yield* Effect.tryPromise({
+ try: (signal) =>
+ agent.send(prompt).then((run) => {
+ if (signal.aborted) void run.cancel().catch(() => undefined);
+ return run;
+ }),
+ catch: sdkFailure("Cursor SDK request could not be sent."),
+ });
yield* Effect.addFinalizer(() =>
run.status === "running"
- ? Effect.tryPromise(() => run.cancel()).pipe(
- Effect.timeout("5 seconds"),
- Effect.ignore({ log: true }),
- )
+ ? Effect.tryPromise({
+ try: () => run.cancel(),
+ catch: sdkFailure("Cursor SDK run could not be cancelled."),
+ }).pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true }))
: Effect.void,
);
- return yield* Effect.tryPromise(() => run.wait());
+ return yield* Effect.tryPromise({
+ try: () => run.wait(),
+ catch: sdkFailure("Cursor SDK run failed."),
+ });
}).pipe(Effect.scoped);
const promptResult = yield* request.pipe(
Effect.timeoutOption(CURSOR_TIMEOUT_MS),
diff --git a/packages/provider-muse/src/server/MuseUsageHome.ts b/packages/provider-muse/src/server/MuseUsageHome.ts
index de2689d042e..a0c5c16261c 100644
--- a/packages/provider-muse/src/server/MuseUsageHome.ts
+++ b/packages/provider-muse/src/server/MuseUsageHome.ts
@@ -5,7 +5,7 @@ import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
-import { createMuseSdkHostEffect } from "./sdk.ts";
+import { createMuseSdkHostEffect, MuseSdkError } from "./sdk.ts";
export class MuseUsageHome extends Context.Service<
MuseUsageHome,
@@ -26,7 +26,11 @@ const make = Effect.gen(function* () {
Effect.gen(function* () {
const host = yield* Effect.acquireRelease(
createMuseSdkHostEffect({ ...input, readOnly: true, startupTimeoutMs: 5_000 }),
- (host) => Effect.tryPromise(() => host.close()).pipe(Effect.ignore),
+ (host) =>
+ Effect.tryPromise({
+ try: () => host.close(),
+ catch: (cause) => new MuseSdkError({ operation: "close", cause }),
+ }).pipe(Effect.ignore),
{ interruptible: true },
);
return host.initializeResult.museHome;
diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts
index 354e457b2ca..b29f8d51947 100644
--- a/packages/provider-muse/src/server/adapter.ts
+++ b/packages/provider-muse/src/server/adapter.ts
@@ -64,6 +64,7 @@ import {
import { isMuseUsageLimitFailure, museUsageLimitResetAt } from "./usageLimits.ts";
import {
createMuseSdkHostEffect,
+ MuseSdkError,
museApprovalMode,
museCanonicalPath,
musePermissionProfile,
@@ -1069,7 +1070,10 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
}
yield* settleObservedChildren("failed");
if (turn) yield* Queue.fail(events, protocolError(detail, cause));
- yield* Effect.tryPromise(() => failed.close()).pipe(Effect.ignore, Effect.forkIn(scope));
+ yield* Effect.tryPromise({
+ try: () => failed.close(),
+ catch: (cause) => new MuseSdkError({ operation: "close", cause }),
+ }).pipe(Effect.ignore, Effect.forkIn(scope));
});
const owns = (turn: ActiveTurn, turnId: string) =>
turnId === turn.nativeId || turn.joined.has(turnId);
@@ -1724,7 +1728,10 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
closed = true;
hostEpoch++;
}
- const close = Effect.tryPromise(() => created.close());
+ const close = Effect.tryPromise({
+ try: () => created.close(),
+ catch: (cause) => new MuseSdkError({ operation: "close", cause }),
+ });
// SDK shutdown sends SIGKILL after 10s + 2s, but inherited pipes can
// keep its close promise pending. Let the scope reap those holders.
yield* (
@@ -2258,10 +2265,10 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
Effect.gen(function* () {
if (active !== turn) return;
hostEpoch++;
- yield* Effect.tryPromise(() => host.close()).pipe(
- Effect.mapError((cause) => protocolError("Cannot stop Muse compaction", cause)),
- Effect.onError(failHost),
- );
+ yield* Effect.tryPromise({
+ try: () => host.close(),
+ catch: (cause) => protocolError("Cannot stop Muse compaction", cause),
+ }).pipe(Effect.onError(failHost));
broken = true;
yield* finish(turn, "interrupted", undefined, "broken");
yield* settleObservedChildren("interrupted");
diff --git a/packages/provider-muse/src/server/modelCatalog.ts b/packages/provider-muse/src/server/modelCatalog.ts
index d10a076f27c..b8a62297ddf 100644
--- a/packages/provider-muse/src/server/modelCatalog.ts
+++ b/packages/provider-muse/src/server/modelCatalog.ts
@@ -4,7 +4,12 @@ import { MuseSettings } from "../settings.ts";
import { createModelCapabilities, getProviderOptionDescriptors } from "@t3tools/shared/model";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
-import { createMuseSdkHost, createMuseSdkHostEffect, type MuseSdkHost } from "./sdk.ts";
+import {
+ createMuseSdkHost,
+ createMuseSdkHostEffect,
+ MuseSdkError,
+ type MuseSdkHost,
+} from "./sdk.ts";
type MuseReasoningEffort = NonNullable<SendUserTurnOptions<never>["reasoningEffort"]>;
@@ -113,7 +118,10 @@ export const discoverMuseModels = Effect.fn("discoverMuseModels")(function* (
(host: MuseSdkHost) => Effect.promise(() => host.close()),
{ interruptible: true },
);
- const result = yield* Effect.tryPromise(() => host.connection.request("model/list", {}));
+ const result = yield* Effect.tryPromise({
+ try: () => host.connection.request("model/list", {}),
+ catch: (cause) => new MuseSdkError({ operation: "model/list", cause }),
+ });
const catalog = yield* decodeModelList(result);
if (catalog.providerId !== "meta") {
return yield* new MuseCatalogError({ detail: "Muse returned a catalog for another provider." });
diff --git a/packages/provider-muse/src/server/sdk.ts b/packages/provider-muse/src/server/sdk.ts
index 17e9a017d81..0269a64d9c9 100644
--- a/packages/provider-muse/src/server/sdk.ts
+++ b/packages/provider-muse/src/server/sdk.ts
@@ -13,6 +13,16 @@ import type { RuntimeMode } from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+
+export class MuseSdkError extends Schema.TaggedError<MuseSdkError>()("MuseSdkError", {
+ operation: Schema.String,
+ cause: Schema.Defect(),
+}) {
+ override get message(): string {
+ return `Muse SDK ${this.operation} failed.`;
+ }
+}
export interface MuseSdkHost {
readonly connection: Pick<
@@ -72,15 +82,19 @@ export function museVerbatimPath(path: string): string {
// Native realpath corrects filesystem case as well as resolving symlinks.
export const museCanonicalPath = Effect.fn("museCanonicalPath")(function* (path: string) {
- return yield* Effect.tryPromise(() => NodeFSP.realpath(path)).pipe(
- Effect.orElseSucceed(() => path),
- );
+ return yield* Effect.tryPromise({
+ try: () => NodeFSP.realpath(path),
+ catch: (cause) => new MuseSdkError({ operation: "realpath", cause }),
+ }).pipe(Effect.orElseSucceed(() => path));
});
// Windows turn roots need verbatim form; launch cmd.exe with the plain canonical path.
export const museWorkspaceRoot = Effect.fn("museWorkspaceRoot")(function* (path: string) {
if ((yield* HostProcess.Platform) !== "win32") return yield* museCanonicalPath(path);
- const canonical = yield* Effect.tryPromise(() => NodeFSP.realpath(path)).pipe(
+ const canonical = yield* Effect.tryPromise({
+ try: () => NodeFSP.realpath(path),
+ catch: (cause) => new MuseSdkError({ operation: "realpath", cause }),
+ }).pipe(
// A verbatim path takes `/` literally, so an unresolved root needs Windows separators.
Effect.orElseSucceed(() => path.replaceAll("/", "\\")),
);
@@ -214,9 +228,12 @@ export const createMuseSdkHostEffect = Effect.fn("createMuseSdkHostEffect")(func
) {
const launch = options.launch ?? (yield* museLaunch(options.binaryPath, options.environment));
let startup: Promise<MuseSdkHost> | undefined;
- return yield* Effect.tryPromise((signal) => {
- startup = createHost({ ...options, launch, signal });
- return startup;
+ return yield* Effect.tryPromise({
+ try: (signal) => {
+ startup = createHost({ ...options, launch, signal });
+ return startup;
+ },
+ catch: (cause) => new MuseSdkError({ operation: "start", cause }),
}).pipe(
Effect.onInterrupt(() =>
Effect.promise(async () => {
diff --git a/packages/provider-muse/src/server/textGeneration.ts b/packages/provider-muse/src/server/textGeneration.ts
index f122d1df756..5c1bceadeea 100644
--- a/packages/provider-muse/src/server/textGeneration.ts
+++ b/packages/provider-muse/src/server/textGeneration.ts
@@ -14,7 +14,12 @@ import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
-import { createMuseSdkHost, createMuseSdkHostEffect, type MuseSdkHost } from "./sdk.ts";
+import {
+ createMuseSdkHost,
+ createMuseSdkHostEffect,
+ MuseSdkError,
+ type MuseSdkHost,
+} from "./sdk.ts";
import { museModelCapabilities, resolveMuseReasoningEffort } from "./modelCatalog.ts";
import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration";
import { investigationUnsupported } from "@t3tools/provider-core/server/textGenerationOperations";
@@ -250,16 +255,18 @@ export const makeMuseTextGeneration = Effect.fn("makeMuseTextGeneration")(functi
(host: MuseSdkHost) => Effect.promise(() => host.close()),
{ interruptible: true },
);
- return yield* Effect.tryPromise((signal) =>
- generateMuseText(
- host,
- cwd,
- `${input.prompt}\n\nReturn only a JSON object matching this schema, with no markdown fences. Do not use tools or ask questions.\n${jsonSchema}`,
- modelId,
- reasoningEffort,
- signal,
- ),
- );
+ return yield* Effect.tryPromise({
+ try: (signal) =>
+ generateMuseText(
+ host,
+ cwd,
+ `${input.prompt}\n\nReturn only a JSON object matching this schema, with no markdown fences. Do not use tools or ask questions.\n${jsonSchema}`,
+ modelId,
+ reasoningEffort,
+ signal,
+ ),
+ catch: (cause) => new MuseSdkError({ operation: "generate text", cause }),
+ });
}).pipe(
Effect.scoped,
Effect.mapError(
diff --git a/packages/provider-muse/src/server/usage.test.ts b/packages/provider-muse/src/server/usage.test.ts
index 266b6097b8e..4ca72c56824 100644
--- a/packages/provider-muse/src/server/usage.test.ts
+++ b/packages/provider-muse/src/server/usage.test.ts
@@ -236,11 +236,13 @@ describe("Muse history discovery", () => {
it.effect("does not guess a directory when initialization fails", () =>
Effect.gen(function* () {
- using _create = vi.spyOn(MuseSdk, "createMuseSdkHostEffect").mockReturnValue(
- Effect.try(() => {
- throw new Error("not installed");
- }),
- );
+ using _create = vi
+ .spyOn(MuseSdk, "createMuseSdkHostEffect")
+ .mockReturnValue(
+ Effect.fail(
+ new MuseSdk.MuseSdkError({ operation: "start", cause: new Error("not installed") }),
+ ),
+ );
if (museUsageReader.kind !== "transcripts") throw new Error("Expected a transcript reader");
const directories = yield* museUsageReader.directories({
instanceId: ProviderInstanceId.make("muse"),
@@ -381,9 +383,9 @@ describe("Muse history discovery", () => {
using create = vi
.spyOn(MuseSdk, "createMuseSdkHostEffect")
.mockReturnValueOnce(
- Effect.try(() => {
- throw new Error("not installed");
- }),
+ Effect.fail(
+ new MuseSdk.MuseSdkError({ operation: "start", cause: new Error("not installed") }),
+ ),
)
.mockReturnValue(
Effect.succeed({
diff --git a/packages/provider-opencode/src/server/usageLimits.ts b/packages/provider-opencode/src/server/usageLimits.ts
index 0f97ea36cfe..03488e515a7 100644
--- a/packages/provider-opencode/src/server/usageLimits.ts
+++ b/packages/provider-opencode/src/server/usageLimits.ts
@@ -43,32 +43,44 @@ const UsageResponse = Schema.Struct({
// Select before decoding so an OAuth or self-hosted connection cannot fall
// through to another stored account. NULL-active rows predate the selection flag.
+class OpenCodeCredentialReadError extends Schema.TaggedError<OpenCodeCredentialReadError>()(
+ "OpenCodeCredentialReadError",
+ { databasePath: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `Could not read OpenCode credentials from ${this.databasePath}.`;
+ }
+}
+
const readStoredApiKey = (databasePath: string, integrationId: "opencode" | "opencode-go") =>
- Effect.try(() => {
- const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
- try {
- database.exec("PRAGMA busy_timeout = 100");
- const row = database
- .prepare(
- `SELECT value FROM credential
- WHERE integration_id = ? AND active IS NOT 0
- ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`,
- )
- .get(integrationId);
- const stored =
- typeof row?.value === "string"
- ? Option.getOrUndefined(decodeStoredKey(row.value))
- : undefined;
- const server = stored?.metadata?.server;
- if (typeof server === "string") {
- const url = new URL(server);
- if (`${url.origin}${url.pathname.replace(/\/+$/, "")}` !== "https://opencode.ai/console")
- return undefined;
+ Effect.try({
+ try: () => {
+ const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
+ try {
+ database.exec("PRAGMA busy_timeout = 100");
+ const row = database
+ .prepare(
+ `SELECT value FROM credential
+ WHERE integration_id = ? AND active IS NOT 0
+ ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`,
+ )
+ .get(integrationId);
+ const stored =
+ typeof row?.value === "string"
+ ? Option.getOrUndefined(decodeStoredKey(row.value))
+ : undefined;
+ const server = stored?.metadata?.server;
+ if (typeof server === "string") {
+ const url = new URL(server);
+ if (`${url.origin}${url.pathname.replace(/\/+$/, "")}` !== "https://opencode.ai/console")
+ return undefined;
+ }
+ return stored?.key.trim();
+ } finally {
+ database.close();
}
- return stored?.key.trim();
- } finally {
- database.close();
- }
+ },
+ catch: (cause) => new OpenCodeCredentialReadError({ databasePath, cause }),
}).pipe(Effect.orElseSucceed(() => undefined));
/** External OpenCode servers own their credentials; never read the host's account for them. */
diff --git a/packages/shared/src/HostProcess.ts b/packages/shared/src/HostProcess.ts
index f24365cd5c8..50f0a3ef859 100644
--- a/packages/shared/src/HostProcess.ts
+++ b/packages/shared/src/HostProcess.ts
@@ -1,5 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
import * as NodeDns from "node:dns";
import * as NodeOS from "node:os";
import * as NodeSea from "node:sea";
@@ -73,6 +74,15 @@ export const IsExecutable = Context.Reference<boolean>("@t3tools/shared/HostProc
defaultValue: () => NodeSea.isSea(),
});
+export class HostnameLookupError extends Schema.TaggedError<HostnameLookupError>()(
+ "HostnameLookupError",
+ { hostname: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `Could not resolve ${this.hostname}.`;
+ }
+}
+
/** Includes hostname-resolved addresses absent from interfaces, such as Debian's 127.0.1.1 used by Firefox locks. */
export const Addresses = Context.Reference<Effect.Effect<ReadonlySet<string>>>(
"@t3tools/shared/HostProcess/Addresses",
@@ -82,9 +92,11 @@ export const Addresses = Context.Reference<Effect.Effect<ReadonlySet<string>>>(
const interfaces = Object.values(NodeOS.networkInterfaces())
.flat()
.flatMap((entry) => (entry ? [entry.address] : []));
- const resolved = yield* Effect.tryPromise(() =>
- NodeDns.promises.lookup(NodeOS.hostname(), { all: true }),
- ).pipe(
+ const hostname = NodeOS.hostname();
+ const resolved = yield* Effect.tryPromise({
+ try: () => NodeDns.promises.lookup(hostname, { all: true }),
+ catch: (cause) => new HostnameLookupError({ hostname, cause }),
+ }).pipe(
Effect.map((entries) => entries.map((entry) => entry.address)),
Effect.orElseSucceed(() => [] as ReadonlyArray<string>),
);
diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts
index 0b9adc6ab96..481b7af0377 100644
--- a/packages/shared/src/nodeSqliteClient.ts
+++ b/packages/shared/src/nodeSqliteClient.ts
@@ -637,7 +637,7 @@ const startCheckpointWorker = Effect.fnUntraced(function* (
}
const frames = writer.prepare("PRAGMA wal_checkpoint(NOOP)");
const sizeLimit = writer.prepare("PRAGMA journal_size_limit");
- const started = yield* Effect.try(
+ const started = Result.try(
() =>
new NodeWorkerThreads.Worker(checkpointWorkerSource, {
eval: true,
@@ -648,9 +648,9 @@ const startCheckpointWorker = Effect.fnUntraced(function* (
idleMs: CHECKPOINT_IDLE_MS,
},
}),
- ).pipe(Effect.result);
+ );
if (Result.isFailure(started)) {
- yield* warn(String(started.failure.cause));
+ yield* warn(String(started.failure));
return undefined;
}
const worker = started.success;
diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.ts
index ea461340681..7bce72d00d4 100644
--- a/packages/shared/src/relayClient.ts
+++ b/packages/shared/src/relayClient.ts
@@ -21,6 +21,7 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import type * as PlatformError from "effect/PlatformError";
import * as Schedule from "effect/Schedule";
+import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
@@ -56,6 +57,15 @@ export type RelayClientStatus =
export type AvailableRelayClient = Extract<RelayClientStatus, { readonly status: "available" }>;
+class RelayClientLockRemoveError extends Schema.TaggedError<RelayClientLockRemoveError>()(
+ "RelayClientLockRemoveError",
+ { lockPath: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `Could not remove the relay client lock ${this.lockPath}.`;
+ }
+}
+
export class RelayClientInstallError extends Data.TaggedError("RelayClientInstallError")<{
readonly reason:
| "download_failed"
@@ -486,7 +496,10 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
});
const removeEmptyLock = (lockPath: string) =>
- Effect.tryPromise(() => NodeFSP.rmdir(lockPath)).pipe(Effect.ignore);
+ Effect.tryPromise({
+ try: () => NodeFSP.rmdir(lockPath),
+ catch: (cause) => new RelayClientLockRemoveError({ lockPath, cause }),
+ }).pipe(Effect.ignore);
const releaseOwnedLock = Effect.fn("cloudflared.releaseOwnedLock")(function* (
lockPath: string,
diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts
index e3af0855ebf..5f268ffa507 100644
--- a/packages/shared/src/shell.test.ts
+++ b/packages/shared/src/shell.test.ts
@@ -341,7 +341,7 @@ describe("readEnvironmentFromWindowsShell", () => {
expect(
yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
- Effect.try(() => execFile(...args)).pipe(Effect.option),
+ Effect.sync(() => Option.liftThrowable(execFile)(...args)),
),
).toEqual({
PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
@@ -369,7 +369,7 @@ describe("readEnvironmentFromWindowsShell", () => {
expect(
yield* readEnvironmentFromWindowsShell(["FNM_DIR"], {}, (...args) =>
- Effect.try(() => execFile(...args)).pipe(Effect.option),
+ Effect.sync(() => Option.liftThrowable(execFile)(...args)),
),
).toEqual({
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
@@ -389,7 +389,7 @@ describe("readEnvironmentFromWindowsShell", () => {
expect(
yield* readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, (...args) =>
- Effect.try(() => execFile(...args)).pipe(Effect.option),
+ Effect.sync(() => Option.liftThrowable(execFile)(...args)),
),
).toEqual({
PATH: "C:\\Tools",
@@ -420,7 +420,7 @@ describe("readEnvironmentFromWindowsShell", () => {
expect(
yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
- Effect.try(() => execFile(...args)).pipe(Effect.option),
+ Effect.sync(() => Option.liftThrowable(execFile)(...args)),
),
).toEqual({
PATH: "C:\\Tools",
diff --git a/scripts/build-cli-archive.ts b/scripts/build-cli-archive.ts
index 3c74b6714dd..1244b9491fb 100644
--- a/scripts/build-cli-archive.ts
+++ b/scripts/build-cli-archive.ts
@@ -62,6 +62,15 @@ const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
);
+export class CliArchiveLinuxArm64PageError extends Schema.TaggedError<CliArchiveLinuxArm64PageError>()(
+ "CliArchiveLinuxArm64PageError",
+ { executablePath: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `${this.executablePath} is not page-compatible with Linux arm64.`;
+ }
+}
+
export class CliArchiveCommandFailedError extends Schema.TaggedError<CliArchiveCommandFailedError>()(
"CliArchiveCommandFailedError",
{ command: Schema.String, exitCode: Schema.Int },
@@ -537,7 +546,10 @@ const buildCliArchive = Effect.fn("buildCliArchive")(function* (input: {
// TEMPORARY one-time Node fix. Remove when fixed: https://github.com/nodejs/node/issues/67048
if (input.platform === "linux" && input.arch === "arm64") {
const bytes = yield* fs.readFile(executablePath);
- yield* Effect.try(() => assertLinuxArm64PageCompatibility(bytes));
+ yield* Effect.try({
+ try: () => assertLinuxArm64PageCompatibility(bytes),
+ catch: (cause) => new CliArchiveLinuxArm64PageError({ executablePath, cause }),
+ });
}
if (input.platform === "mac") {
yield* signMacArchiveContents({ repoRoot, contentDir, executablePath });
diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts
index 6756f6fea85..9bc12cde985 100644
--- a/scripts/build-desktop-artifact.ts
+++ b/scripts/build-desktop-artifact.ts
@@ -685,6 +685,15 @@ export class DesktopBuildDistDirectoryMissingError extends Schema.TaggedError<De
}
}
+export class DesktopBuildArtifactCopyError extends Schema.TaggedError<DesktopBuildArtifactCopyError>()(
+ "DesktopBuildArtifactCopyError",
+ { from: Schema.String, to: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `Failed to copy build artifact ${this.from} to ${this.to}.`;
+ }
+}
+
export class DesktopBuildNoArtifactsProducedError extends Schema.TaggedError<DesktopBuildNoArtifactsProducedError>()(
"DesktopBuildNoArtifactsProducedError",
{
@@ -2095,7 +2104,7 @@ const NativeMarkerManifest = Schema.Struct({
dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
optionalDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
});
-const decodeNativeMarkerManifest = Schema.decodeUnknownSync(
+const decodeNativeMarkerManifest = Schema.decodeUnknownOption(
Schema.fromJsonString(NativeMarkerManifest),
);
@@ -2135,13 +2144,12 @@ const hasNativeLoaderMarkers = Effect.fn("hasNativeLoaderMarkers")(function* (pa
if (!(yield* exists(manifestPath))) return false;
const source = yield* fs.readFileString(manifestPath).pipe(Effect.orElseSucceed(() => ""));
if (source === "") return false;
- const manifest = yield* Effect.try(() => decodeNativeMarkerManifest(source)).pipe(
- Effect.orElseSucceed(() => null),
- );
- if (manifest === null) return false;
- return Object.keys({ ...manifest.dependencies, ...manifest.optionalDependencies }).some(
- (dependency) => dependency.startsWith("node-gyp-build"),
- );
+ const manifest = decodeNativeMarkerManifest(source);
+ if (Option.isNone(manifest)) return false;
+ return Object.keys({
+ ...manifest.value.dependencies,
+ ...manifest.value.optionalDependencies,
+ }).some((dependency) => dependency.startsWith("node-gyp-build"));
});
export const copyDirectoryPreservingSymlinks = Effect.fn("copyDirectoryPreservingSymlinks")(
@@ -4107,13 +4115,15 @@ export const copyDesktopBuildArtifacts = Effect.fn("copyDesktopBuildArtifacts")(
// overwrite a directory with a file or a file with a directory, and only merges into
// an existing directory, so a stale entry of either type must go first.
yield* fs.remove(to, { recursive: true, force: true });
- yield* Effect.tryPromise(() =>
- NodeFSP.cp(from, to, {
- recursive: true,
- force: true,
- verbatimSymlinks: true,
- }),
- );
+ yield* Effect.tryPromise({
+ try: () =>
+ NodeFSP.cp(from, to, {
+ recursive: true,
+ force: true,
+ verbatimSymlinks: true,
+ }),
+ catch: (cause) => new DesktopBuildArtifactCopyError({ from, to, cause }),
+ });
copiedArtifacts.push(to);
}
diff --git a/tsconfig.effect.json b/tsconfig.effect.json
index 29240a31e71..dab2c98e771 100644
--- a/tsconfig.effect.json
+++ b/tsconfig.effect.json
@@ -96,6 +96,7 @@
"timeoutCatchTagToTimeoutOrElse": "error",
"unnecessaryPipe": "error",
"unnecessaryTypeofType": "error",
+ "effectTryWithoutCatch": "error",
"processEnvInEffect": "error",
"schemaNumber": "off"
},