Skip to content

Commit 5a90658

Browse files
refactor: Effect.try calls map failures to typed errors (#31217)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent e313a12 commit 5a90658

62 files changed

Lines changed: 949 additions & 453 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/desktop/src/app/DesktopCliCommand.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,10 @@ export const make = Effect.gen(function* () {
140140
const isExecutableFile = Effect.fn("DesktopCliCommand.isExecutableFile")(
141141
function* (target: string) {
142142
if ((yield* fs.stat(target)).type !== "File") return false;
143-
yield* Effect.tryPromise(() => NodeFSP.access(target, NodeFSP.constants.X_OK));
143+
yield* Effect.tryPromise({
144+
try: () => NodeFSP.access(target, NodeFSP.constants.X_OK),
145+
catch: () => fail(`${target} is not executable.`),
146+
});
144147
return true;
145148
},
146149
Effect.orElseSucceed(() => false),

‎apps/desktop/src/electron/ElectronProtocol.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,9 +216,7 @@ const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* (
216216
if (request.method !== "GET" && request.method !== "HEAD") {
217217
return new Response(null, { status: 405 });
218218
}
219-
const pathname = yield* Effect.try(() => decodeURIComponent(url.pathname)).pipe(
220-
Effect.orElseSucceed(() => null),
221-
);
219+
const pathname = Option.getOrNull(Option.liftThrowable(decodeURIComponent)(url.pathname));
222220
if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 });
223221
const root = path.resolve(assetDirectory);
224222
const assetPath = path.resolve(root, `.${pathname}`);

‎apps/desktop/src/ipc/methods/window.ts‎

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,12 @@ export const openExternal = DesktopIpc.makeIpcMethod({
314314

315315
const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024;
316316

317+
// No URL field: media URLs can carry signed query tokens.
318+
class MediaReadError extends Schema.TaggedError<MediaReadError>()("MediaReadError", {
319+
message: Schema.String,
320+
cause: Schema.Defect(),
321+
}) {}
322+
317323
// The renderer can display media it cannot fetch(); reading here keeps Save and Copy working for it.
318324
export const readMedia = DesktopIpc.makeIpcMethod({
319325
channel: IpcChannels.READ_MEDIA_CHANNEL,
@@ -330,25 +336,28 @@ export const readMedia = DesktopIpc.makeIpcMethod({
330336
return null;
331337
}
332338
const session = window.value.webContents.session;
333-
return yield* Effect.tryPromise(async () => {
334-
// Like an <img>, send the session's cookies.
335-
const response = await session.fetch(url, { credentials: "include" });
336-
const mimeType = response.headers.get("content-type") ?? "";
337-
if (!response.ok || !response.body) {
338-
await response.body?.cancel();
339-
return { status: response.status, mimeType, data: new Uint8Array() };
340-
}
341-
// The whole body crosses IPC, so stop before a huge file can exhaust main-process memory.
342-
const chunks: Uint8Array[] = [];
343-
let size = 0;
344-
for await (const chunk of response.body) {
345-
size += chunk.byteLength;
346-
if (size > READ_MEDIA_MAX_BYTES) {
347-
return { status: 413, mimeType, data: new Uint8Array() };
339+
return yield* Effect.tryPromise({
340+
try: async () => {
341+
// Like an <img>, send the session's cookies.
342+
const response = await session.fetch(url, { credentials: "include" });
343+
const mimeType = response.headers.get("content-type") ?? "";
344+
if (!response.ok || !response.body) {
345+
await response.body?.cancel();
346+
return { status: response.status, mimeType, data: new Uint8Array() };
348347
}
349-
chunks.push(chunk);
350-
}
351-
return { status: response.status, mimeType, data: Buffer.concat(chunks) };
348+
// The whole body crosses IPC, so stop before a huge file can exhaust main-process memory.
349+
const chunks: Uint8Array[] = [];
350+
let size = 0;
351+
for await (const chunk of response.body) {
352+
size += chunk.byteLength;
353+
if (size > READ_MEDIA_MAX_BYTES) {
354+
return { status: 413, mimeType, data: new Uint8Array() };
355+
}
356+
chunks.push(chunk);
357+
}
358+
return { status: response.status, mimeType, data: Buffer.concat(chunks) };
359+
},
360+
catch: (cause) => new MediaReadError({ message: "Could not read media.", cause }),
352361
}).pipe(Effect.orElseSucceed(() => null));
353362
}),
354363
});

‎apps/desktop/src/permissions/MacPermissions.ts‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as Context from "effect/Context";
22
import * as Effect from "effect/Effect";
33
import * as Layer from "effect/Layer";
44
import * as Path from "effect/Path";
5+
import * as Schema from "effect/Schema";
56
import * as Electron from "electron";
67
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
78
import { MacPermissionHelper } from "./MacPermissionHelper.ts";
@@ -18,6 +19,15 @@ export class MacPermissions extends Context.Service<
1819
}
1920
>()("@t3tools/desktop/permissions/MacPermissions") {}
2021

22+
class MacPermissionHelperError extends Schema.TaggedError<MacPermissionHelperError>()(
23+
"MacPermissionHelperError",
24+
{ cause: Schema.Defect() },
25+
) {
26+
override get message(): string {
27+
return "Could not show the permission helper.";
28+
}
29+
}
30+
2131
export const layer = Layer.effect(
2232
MacPermissions,
2333
Effect.gen(function* () {
@@ -28,15 +38,17 @@ export const layer = Layer.effect(
2838
return MacPermissions.of({
2939
showHelper: Effect.fn("MacPermissions.showHelper")(function* (permission, owner, isGranted) {
3040
if (environment.platform !== "darwin" || !environment.isPackaged) return;
31-
yield* Effect.tryPromise(() =>
32-
helper.show(
33-
permission,
34-
path.join(environment.dirname, "mac-permission-preload.cjs"),
35-
owner,
36-
environment.resolveResourcePathCandidates("icon.png"),
37-
isGranted,
38-
),
39-
).pipe(
41+
yield* Effect.tryPromise({
42+
try: () =>
43+
helper.show(
44+
permission,
45+
path.join(environment.dirname, "mac-permission-preload.cjs"),
46+
owner,
47+
environment.resolveResourcePathCandidates("icon.png"),
48+
isGranted,
49+
),
50+
catch: (cause) => new MacPermissionHelperError({ cause }),
51+
}).pipe(
4052
Effect.catch((cause) => Effect.logWarning("Could not show permission helper", cause)),
4153
);
4254
}),

‎apps/desktop/src/preview/BrowserImport/BrowserImport.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,15 @@ export const checkBrowserImportPolicy = Effect.fn("BrowserImport.checkPolicy")(f
9292
}
9393
});
9494

95+
class BrowserCookieFlushError extends Schema.TaggedError<BrowserCookieFlushError>()(
96+
"BrowserCookieFlushError",
97+
{ cause: Schema.Defect() },
98+
) {
99+
override get message(): string {
100+
return "Imported cookies could not be flushed to disk.";
101+
}
102+
}
103+
95104
export class BrowserCookieWriteError extends Schema.TaggedError<BrowserCookieWriteError>()(
96105
"BrowserCookieWriteError",
97106
{
@@ -183,7 +192,10 @@ export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* (
183192
}
184193
// Cookie writes settle in memory; flush to disk before reporting a durable import.
185194
if (imported > 0) {
186-
yield* Effect.tryPromise(() => session.cookies.flushStore()).pipe(
195+
yield* Effect.tryPromise({
196+
try: () => session.cookies.flushStore(),
197+
catch: (cause) => new BrowserCookieFlushError({ cause }),
198+
}).pipe(
187199
Effect.tapError((error) =>
188200
Effect.logWarning("Imported cookies could not be flushed to disk", { cause: error.cause }),
189201
),

‎apps/desktop/src/snapShot/DesktopSnapShot.ts‎

Lines changed: 85 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,17 @@ export class DesktopSnapShotError extends Schema.TaggedError<DesktopSnapShotErro
167167

168168
const isDesktopSnapShotError = Schema.is(DesktopSnapShotError);
169169

170+
class SnapShotShortcutError extends Schema.TaggedError<SnapShotShortcutError>()(
171+
"SnapShotShortcutError",
172+
{ cause: Schema.Defect() },
173+
) {
174+
override get message(): string {
175+
return "Could not register the SnapShot shortcut.";
176+
}
177+
}
178+
179+
const shortcutFailure = (cause: unknown) => new SnapShotShortcutError({ cause });
180+
170181
function captureFailure(cause: unknown, captureId?: string): DesktopSnapShotError {
171182
if (isDesktopSnapShotError(cause)) return cause;
172183
const operation = cause instanceof CaptureSetupRequiredError ? "setup-required" : "capture";
@@ -1068,13 +1079,15 @@ export const make = Effect.gen(function* () {
10681079
if (mode === "portal") {
10691080
return { available: false, message: WAYLAND_MODIFIER_PAIR_UNAVAILABLE_MESSAGE };
10701081
}
1071-
const available = yield* Effect.tryPromise(() =>
1072-
startPairShortcutProcess(
1073-
snapShotShortcutModifierPair(shortcut),
1074-
() => undefined,
1075-
() => undefined,
1076-
),
1077-
).pipe(
1082+
const available = yield* Effect.tryPromise({
1083+
try: () =>
1084+
startPairShortcutProcess(
1085+
snapShotShortcutModifierPair(shortcut),
1086+
() => undefined,
1087+
() => undefined,
1088+
),
1089+
catch: shortcutFailure,
1090+
}).pipe(
10781091
Effect.tap((stop) => Effect.sync(stop)),
10791092
Effect.as(true),
10801093
Effect.orElseSucceed(() => false),
@@ -1089,7 +1102,10 @@ export const make = Effect.gen(function* () {
10891102
const systemConflict = snapShotShortcutSystemConflict(shortcut);
10901103
if (systemConflict) return { available: false, message: systemConflict };
10911104
if (mode === "portal") {
1092-
return yield* Effect.try(() => portalShortcutTrigger(shortcut)).pipe(
1105+
return yield* Effect.try({
1106+
try: () => portalShortcutTrigger(shortcut),
1107+
catch: shortcutFailure,
1108+
}).pipe(
10931109
Effect.match({
10941110
onSuccess: () => ({
10951111
available: true,
@@ -1199,13 +1215,16 @@ export const make = Effect.gen(function* () {
11991215
return;
12001216
}
12011217
if (mode === "portal" && niriSocketPath()) {
1202-
const registered = yield* Effect.tryPromise(async () => {
1203-
const { startNiriCaptureShortcut } = await import("./NiriCaptureShortcut.ts");
1204-
return startNiriCaptureShortcut(linuxAppId, onCurrentShortcut, () => {
1205-
void runPromise(
1206-
setShortcutFailure("The Niri capture endpoint disconnected. Restart T3 Code."),
1207-
).catch(() => undefined);
1208-
});
1218+
const registered = yield* Effect.tryPromise({
1219+
try: async () => {
1220+
const { startNiriCaptureShortcut } = await import("./NiriCaptureShortcut.ts");
1221+
return startNiriCaptureShortcut(linuxAppId, onCurrentShortcut, () => {
1222+
void runPromise(
1223+
setShortcutFailure("The Niri capture endpoint disconnected. Restart T3 Code."),
1224+
).catch(() => undefined);
1225+
});
1226+
},
1227+
catch: shortcutFailure,
12091228
}).pipe(
12101229
Effect.tap((stop) =>
12111230
Effect.sync(() => {
@@ -1249,29 +1268,32 @@ export const make = Effect.gen(function* () {
12491268
shortcutMessage: null,
12501269
message: null,
12511270
});
1252-
yield* Effect.tryPromise(async () => {
1253-
const { PortalCaptureShortcut } = await import("./PortalCaptureShortcut.ts");
1254-
return new PortalCaptureShortcut(
1255-
linuxAppId,
1256-
isModifierPairShortcut(shortcut)
1257-
? {
1258-
key: "2",
1259-
ctrlKey: true,
1260-
modKey: false,
1261-
altKey: false,
1262-
shiftKey: true,
1263-
metaKey: false,
1264-
}
1265-
: shortcut,
1266-
onCurrentShortcut,
1267-
() => {
1268-
if (generation !== shortcutGeneration) return;
1269-
shortcutVerified = false;
1270-
void runPromise(emit({ type: "shortcut-changed" })).catch(() => undefined);
1271-
},
1272-
undefined,
1273-
hyprland,
1274-
);
1271+
yield* Effect.tryPromise({
1272+
try: async () => {
1273+
const { PortalCaptureShortcut } = await import("./PortalCaptureShortcut.ts");
1274+
return new PortalCaptureShortcut(
1275+
linuxAppId,
1276+
isModifierPairShortcut(shortcut)
1277+
? {
1278+
key: "2",
1279+
ctrlKey: true,
1280+
modKey: false,
1281+
altKey: false,
1282+
shiftKey: true,
1283+
metaKey: false,
1284+
}
1285+
: shortcut,
1286+
onCurrentShortcut,
1287+
() => {
1288+
if (generation !== shortcutGeneration) return;
1289+
shortcutVerified = false;
1290+
void runPromise(emit({ type: "shortcut-changed" })).catch(() => undefined);
1291+
},
1292+
undefined,
1293+
hyprland,
1294+
);
1295+
},
1296+
catch: shortcutFailure,
12751297
}).pipe(
12761298
Effect.tap((registration) =>
12771299
Effect.sync(() => {
@@ -1293,15 +1315,21 @@ export const make = Effect.gen(function* () {
12931315

12941316
let registered = false;
12951317
if (isModifierPairShortcut(shortcut)) {
1296-
registered = yield* Effect.tryPromise(() =>
1297-
startPairShortcutProcess(snapShotShortcutModifierPair(shortcut), onCurrentShortcut, () => {
1298-
void pipe(
1299-
snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform),
1300-
setShortcutFailure,
1301-
runPromise,
1302-
).catch(() => undefined);
1303-
}),
1304-
).pipe(
1318+
registered = yield* Effect.tryPromise({
1319+
try: () =>
1320+
startPairShortcutProcess(
1321+
snapShotShortcutModifierPair(shortcut),
1322+
onCurrentShortcut,
1323+
() => {
1324+
void pipe(
1325+
snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform),
1326+
setShortcutFailure,
1327+
runPromise,
1328+
).catch(() => undefined);
1329+
},
1330+
),
1331+
catch: shortcutFailure,
1332+
}).pipe(
13051333
Effect.tap((stop) =>
13061334
Effect.sync(() => {
13071335
stopShiftShortcut = stop;
@@ -1489,7 +1517,10 @@ export const make = Effect.gen(function* () {
14891517
if (action === "retry-shortcut") {
14901518
const currentPortal = portalShortcut;
14911519
if (currentPortal?.hasSession && !currentPortal.state.shortcutPending) {
1492-
yield* Effect.tryPromise(() => currentPortal.configure()).pipe(
1520+
yield* Effect.tryPromise({
1521+
try: () => currentPortal.configure(),
1522+
catch: shortcutFailure,
1523+
}).pipe(
14931524
Effect.mapError(
14941525
(error) =>
14951526
new DesktopSnapShotSetupError({
@@ -1583,9 +1614,12 @@ export const make = Effect.gen(function* () {
15831614
state: Ref.get(stateRef).pipe(
15841615
Effect.flatMap((state) =>
15851616
state.mode === "portal"
1586-
? Effect.tryPromise(async () => {
1587-
const { getLinuxCaptureSupport } = await import("./LinuxSnapShot.ts");
1588-
return getLinuxCaptureSupport(linuxAppId);
1617+
? Effect.tryPromise({
1618+
try: async () => {
1619+
const { getLinuxCaptureSupport } = await import("./LinuxSnapShot.ts");
1620+
return getLinuxCaptureSupport(linuxAppId);
1621+
},
1622+
catch: (cause) => new DesktopSnapShotError({ operation: "unsupported", cause }),
15891623
}).pipe(
15901624
Effect.map((support) => ({ ...state, ...support })),
15911625
Effect.catch((error) =>

‎apps/desktop/src/window/DesktopWindow.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import * as Fiber from "effect/Fiber";
55
import * as Layer from "effect/Layer";
66
import * as Option from "effect/Option";
77
import * as Ref from "effect/Ref";
8+
import * as Schema from "effect/Schema";
89
import * as Semaphore from "effect/Semaphore";
910

1011
import * as Electron from "electron";
@@ -39,6 +40,15 @@ import { makeQuitShortcutHandler } from "./QuitHold.ts";
3940
import { copyContextMenuImage } from "./ContextMenuImage.ts";
4041

4142
const TITLEBAR_HEIGHT = 40;
43+
44+
class ContextMenuImageCopyError extends Schema.TaggedError<ContextMenuImageCopyError>()(
45+
"ContextMenuImageCopyError",
46+
{ cause: Schema.Defect() },
47+
) {
48+
override get message(): string {
49+
return "Could not copy the context-menu image.";
50+
}
51+
}
4252
// Match --workspace-topbar-height in apps/web/src/index.css; native macOS buttons stay 14 points at any zoom.
4353
const MACOS_WORKSPACE_TOPBAR_HEIGHT = 52;
4454
const MACOS_WINDOW_BUTTON_RADIUS = 7;
@@ -580,9 +590,10 @@ export const make = Effect.gen(function* () {
580590
label: "Copy Image",
581591
click: () => {
582592
void runPromise(
583-
Effect.tryPromise(() => copyContextMenuImage(contents, params)).pipe(
584-
Effect.catch(() => logWindowWarning("failed to copy context-menu image")),
585-
),
593+
Effect.tryPromise({
594+
try: () => copyContextMenuImage(contents, params),
595+
catch: (cause) => new ContextMenuImageCopyError({ cause }),
596+
}).pipe(Effect.catch(() => logWindowWarning("failed to copy context-menu image"))),
586597
);
587598
},
588599
});

0 commit comments

Comments
 (0)